Jump to content

Missile follow player. How to get player position inside Missile object?


NistorCristian
 Share

Recommended Posts

I'm trying to make a Missile that will follow the player. My problem is that I don't know how to get the player position inside Missile object. I will paste my code below and write a comment where the problem is:

window.onload = function() {	var GameState = function(game) {	};	//  Here is a custom game object	Player = function (game, x, y) {	    Phaser.Sprite.call(this, game, x, y, 'player');	};	Player.prototype = Object.create(Phaser.Sprite.prototype);	Player.prototype.constructor = Player;	/**	 * Automatically called by World.update	 */	Player.prototype.update = function() {	    // this.angle += this.rotateSpeed;	};	// Load images and sounds	GameState.prototype.preload = function() {	    this.game.load.image('ground', '/phaser/img/background2.png');	    this.game.load.spritesheet('player', '/phaser/img/dude.png', 32, 48);	    this.game.load.image('bullet', '/phaser/img/bullet.png');	    this.game.load.image('gun', '/phaser/img/gun.png');	    this.game.load.image('rocket', '/assets/gfx/rocket.png');	    this.game.load.image('platform', 'assets/platform.png');	};	// Setup the example	GameState.prototype.create = function() {		var player = new Player(game, 200, 300);	    game.add.existing(player);	    // Set stage background to something sky colored	    this.game.stage.backgroundColor = 0x4488cc;	    // Define movement constants	    this.MAX_SPEED = 350; // pixels/second	    this.ACCELERATION = 2600; // pixels/second/second	    this.DRAG = 200; // pixels/second	    this.GRAVITY = 1500; // pixels/second/second	    this.JUMP_SPEED = -400; // pixels/second (negative y is up)	    this.SHOT_DELAY = 100; // milliseconds (10 bullets/second)	    this.BULLET_SPEED = 500; // pixels/second	    this.NUMBER_OF_BULLETS = 10;        this.platforms = this.add.physicsGroup();        for (var i = 0; i <= 10; i++) {        	this.platforms.create(this.game.rnd.integerInRange(450, 600), this.game.rnd.integerInRange(300, 300), 'platform');        };        this.platforms.setAll('body.allowGravity', false);        this.platforms.setAll('body.immovable', true);	    // Create a player sprite	    this.player = player;	    // Enable physics on the player	    this.game.physics.enable(this.player, Phaser.Physics.ARCADE);	    // Make player collide with world boundaries so he doesn't leave the stage	    this.player.body.collideWorldBounds = true;	    // Set player minimum and maximum movement speed	    this.player.body.maxVelocity.setTo(this.MAX_SPEED, this.MAX_SPEED * 10); // x, y	    // Add drag to the player that slows them down when they are not accelerating	    this.player.body.drag.setTo(this.DRAG, 0); // x, y	    this.player.body.setSize(20, 32, 5, 16);	    this.player.animations.add('left', [0, 1, 2, 3], 10, true);	    this.player.animations.add('turn', [4], 20, true);	    this.player.animations.add('right', [5, 6, 7, 8], 10, true);	    this.player.animations.add('jumpright', [6], 10, true);	    this.player.animations.add('jumpleft', [1], 10, true);	    // Create a missile and add it to the game in the bottom center of the stage	    this.game.add.existing(	        new Missile(this.game, this.game.width/2, this.game.height - 16)	    );	    // Since we're jumping we need gravity	    game.physics.arcade.gravity.y = this.GRAVITY;	    // Flag to track if the jump button is pressed	    this.jumping = false;	    // Create some ground for the player to walk on	    this.ground = this.game.add.group();	    for(var x = 0; x < this.game.width; x += 32) {	        // Add the ground blocks, enable physics on each, make them immovable	        var groundBlock = this.game.add.sprite(x, this.game.height - 32, 'ground');	        this.game.physics.enable(groundBlock, Phaser.Physics.ARCADE);	        groundBlock.body.immovable = true;	        groundBlock.body.allowGravity = false;	        this.ground.add(groundBlock);	    }	    // Create an object representing our gun	    this.gun = this.game.add.sprite(this.player.x, this.player.y, 'gun');	    // Set the pivot point to the center of the gun	    this.gun.anchor.setTo(0.5, 0.5);	    // Create an object pool of bullets	    this.bulletPool = this.game.add.group();	    for(var i = 0; i < this.NUMBER_OF_BULLETS; i++) {	        // Create each bullet and add it to the group.	        var bullet = this.game.add.sprite(0, 0, 'bullet');	        this.bulletPool.add(bullet);	        // Set its pivot point to the center of the bullet	        bullet.anchor.setTo(0.5, 0.5);	        // Enable physics on the bullet	        this.game.physics.enable(bullet, Phaser.Physics.ARCADE);	        // Set its initial state to "dead".	        bullet.kill();	    }	    // Simulate a pointer click/tap input at the center of the stage	    // when the example begins running.	    this.game.input.activePointer.x = this.game.width/2;	    this.game.input.activePointer.y = this.game.height/2;	    // Capture certain keys to prevent their default actions in the browser.	    // This is only necessary because this is an HTML5 game. Games on other	    // platforms may not need code like this.	    this.game.input.keyboard.addKeyCapture([	        Phaser.Keyboard.LEFT,	        Phaser.Keyboard.RIGHT,	        Phaser.Keyboard.UP,	        Phaser.Keyboard.DOWN	    ]);	};	// Missile constructor	var Missile = function(game, x, y) {	    Phaser.Sprite.call(this, game, x, y, 'rocket');	    // Set the pivot point for this sprite to the center	    this.anchor.setTo(0.5, 0.5);	    // Enable physics on the missile	    game.physics.enable(this, Phaser.Physics.ARCADE);	    // Define constants that affect motion	    this.SPEED = 250; // missile speed pixels/second	    this.TURN_RATE = 5; // turn rate in degrees/frame	};	// Missiles are a type of Phaser.Sprite	Missile.prototype = Object.create(Phaser.Sprite.prototype);	Missile.prototype.constructor = Missile;	Missile.prototype.update = function() {	    // Calculate the angle from the missile to the mouse cursor game.input.x	    // and game.input.y are the mouse position; substitute with whatever	    // target coordinates you need.	    var targetAngle = this.game.math.angleBetween(	        this.x, this.y,	        this.player.position.x, this.player.position.y // ----- >>>> HOW TO CALL PLAYER ???	    );	    // Gradually (this.TURN_RATE) aim the missile towards the target angle	    if (this.rotation !== targetAngle) {	        // Calculate difference between the current angle and targetAngle	        var delta = targetAngle - this.rotation;	        // Keep it in range from -180 to 180 to make the most efficient turns.	        if (delta > Math.PI) delta -= Math.PI * 2;	        if (delta < -Math.PI) delta += Math.PI * 2;	        if (delta > 0) {	            // Turn clockwise	            this.angle += this.TURN_RATE;	        } else {	            // Turn counter-clockwise	            this.angle -= this.TURN_RATE;	        }	        // Just set angle to target angle if they are close	        if (Math.abs(delta) < this.game.math.degToRad(this.TURN_RATE)) {	            this.rotation = targetAngle;	        }	    }	    // Calculate velocity vector based on this.rotation and this.SPEED	    this.body.velocity.x = Math.cos(this.rotation) * this.SPEED;	    this.body.velocity.y = Math.sin(this.rotation) * this.SPEED;	};	var facing = 'right';	// The update() method is called every frame	GameState.prototype.update = function() {        this.physics.arcade.collide(this.player, this.platforms, this.setFriction, null, this);        this.physics.arcade.collide(this.bulletPool, this.platforms, this.setFrictionBullet, null, this);	    // Collide the player with the ground	    this.game.physics.arcade.collide(this.player, this.ground);	    if (this.leftInputIsActive()) {			if (facing != 'left'){	            this.player.animations.play('left');	            facing = 'left';	        }	            if (this.upInputIsActive()) {            	this.player.animations.play('jumpleft');            };	        // If the LEFT key is down, set the player velocity to move left	        this.player.body.acceleration.x = -this.ACCELERATION;	    } else if (this.rightInputIsActive()) {			if (facing != 'right'){	            this.player.animations.play('right');	            facing = 'right';	        }	            if (this.upInputIsActive()) {            	this.player.animations.play('jumpright');            };	        // If the RIGHT key is down, set the player velocity to move right	        this.player.body.acceleration.x = this.ACCELERATION;	    } else if(this.upInputIsActive()){			if (facing == 'idle-left'){	            this.player.animations.play('jumpleft');	        }else if(facing == 'idle-right'){	        	this.player.animations.play('jumpright');	        }	    }else {			if (facing != 'idle'){	            this.player.animations.stop();	            if (facing == 'left'){	                this.player.frame = 0;	                facing = 'idle-left';	            }else if(facing == 'right'){	                this.player.frame = 5;	                if (facing != 'idle-left') {	                	facing = 'idle-right';	                };	            }else if(facing == 'idle-left'){	            	this.player.frame = 0;	            }else if(facing == 'idle-right'){	            	this.player.frame = 5;	            }	        }	        this.player.body.acceleration.x = 0;	    }	    console.log(this.player.body.velocity.x);	    // Set a variable that is true when the player is touching the ground	    var onTheGround = this.player.body.touching.down;	    // If the player is touching the ground, let him have 2 jumps	    if (onTheGround) {	        this.jumps = 2;	        this.player.body.drag.x = 500;	        this.jumping = false;	    }	    // Jump! Keep y velocity constant while the jump button is held for up to 150 ms	    if (this.jumps > 0 && this.upInputIsActive(150)) {	    	this.player.body.drag.x = 200;	        this.player.body.velocity.y = this.JUMP_SPEED;	        this.jumping = true;	    }	    // Reduce the number of available jumps if the jump input is released	    if (this.jumping && this.upInputReleased()) {	        this.jumps--;	        this.jumping = false;	    }	    // Aim the gun at the pointer.	    // All this function does is calculate the angle using	    // Math.atan2(yPointer-yGun, xPointer-xGun)	    this.gun.rotation = this.game.physics.arcade.angleToPointer(this.gun);	    this.gun.position.x = this.player.position.x + 20;	    this.gun.position.y = this.player.position.y + 40;	    // Shoot a bullet	    if (this.game.input.activePointer.isDown) {	    	if (this.gun.angle > -90 && this.gun.angle < 90 && this.game.input.activePointer.x > this.player.body.x && (facing == 'right' || facing == 'idle-right')) {	        	this.shootBullet();	    	}else if((this.gun.angle < -90 || this.gun.angle > 90) && this.game.input.activePointer.x < this.player.body.x && (facing == 'left' || facing == 'idle-left')){	    		this.shootBullet();	    	};	    }	};	GameState.prototype.shootBullet = function() {	    // Enforce a short delay between shots by recording	    // the time that each bullet is shot and testing if	    // the amount of time since the last shot is more than	    // the required delay.	    if (this.lastBulletShotAt === undefined) this.lastBulletShotAt = 0;	    if (this.game.time.now - this.lastBulletShotAt < this.SHOT_DELAY) return;	    this.lastBulletShotAt = this.game.time.now;	    // Get a dead bullet from the pool	    var bullet = this.bulletPool.getFirstDead();	    // If there aren't any bullets available then don't shoot	    if (bullet === null || bullet === undefined) return;	    // Revive the bullet	    // This makes the bullet "alive"	    bullet.revive();	    // Bullets should kill themselves when they leave the world.	    // Phaser takes care of this for me by setting this flag	    // but you can do it yourself by killing the bullet if	    // its x,y coordinates are outside of the world.	    bullet.checkWorldBounds = true;	    bullet.outOfBoundsKill = true;	    // Set the bullet position to the gun position.	    bullet.reset(this.gun.x, this.gun.y);	    bullet.rotation = this.gun.rotation;	    // Shoot it in the right direction	    bullet.body.velocity.x = Math.cos(bullet.rotation) * this.BULLET_SPEED;	    bullet.body.velocity.y = Math.sin(bullet.rotation) * this.BULLET_SPEED;	    bullet.body.allowGravity = false;	};	// This function should return true when the player activates the "go left" control	// In this case, either holding the right arrow or tapping or clicking on the left	// side of the screen.	GameState.prototype.leftInputIsActive = function() {	    var isActive = false;	    isActive = this.input.keyboard.isDown(Phaser.Keyboard.LEFT);	    return isActive;	};	// This function should return true when the player activates the "go right" control	// In this case, either holding the right arrow or tapping or clicking on the right	// side of the screen.	GameState.prototype.rightInputIsActive = function() {	    var isActive = false;	    isActive = this.input.keyboard.isDown(Phaser.Keyboard.RIGHT);	    return isActive;	};	// This function should return true when the player activates the "jump" control	// In this case, either holding the up arrow or tapping or clicking on the center	// part of the screen.	GameState.prototype.upInputIsActive = function(duration) {	    var isActive = false;	    isActive = this.input.keyboard.downDuration(Phaser.Keyboard.UP, duration);	    return isActive;	};	// This function returns true when the player releases the "jump" control	GameState.prototype.upInputReleased = function() {	    var released = false;	    released = this.input.keyboard.upDuration(Phaser.Keyboard.UP);	    return released;	};	GameState.prototype.setFriction = function(player, platform) {	    player.body.x -= platform.body.x - platform.body.prev.x;	};	GameState.prototype.setFrictionBullet = function(bullet, platform) {	    bullet.kill();	};	var game = new Phaser.Game(848, 450, Phaser.CANVAS, 'game');	game.state.add('game', GameState, true);};
Link to comment
Share on other sites

The "player" the missile is following should be passed as a parameter when the missile is created. You should call it the "target" or something like that.

So, create a missile like so: new Missile(player). In the constructor, do this.target = player. Then to get the player's position just get the x, y position by doing this.target.x and this.target.y..

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...