# Fire bullet to predefined angle

## Recommended Posts

Hi Guys,

So I'm flying a space ship using the accelerometer and gyro.js, with gyro.js I calculate the angle the ship is flying in.

Now I want to fire a laser when I touch my mobile device's screen. The laser should fire in the direction the ship is flying in, no matter where the user touches the screen.

I've searched for a couple of hours, but still didn't find a way to make this work.

Any ideas?

`function fire(angle) {	if(game.time.now > bulletTime) {		bullet = bullets.getFirstExists(false);		if(bullet) {			bullet.reset(player.x, player.y + 8);			bullet.rotation = this.game.physics.arcade.moveToObject(bullet, game.input.activePointer, 500);			bulletTime = game.time.now + 200;		}	}}`

This is what I have got so far, and this works. But it doesn't fire in the direction the ship is flying in.

ps. I've calculated the angle with the following code:

`var anglePlayer = Math.atan2(o.y * 20, o.x * 20);anglePlayer *= 180/Math.PI;anglePlayer = 180 - anglePlayer;player.angle = anglePlayer;`

##### Share on other sites

If you want the lazer to travel in the same direction as your ship, regardless where the user presses, then you want to set the velocity from the angle of the ship using either velocityFromAngle or velocityFromRotation and a speed that is known to be faster than the ship is moving.

##### Share on other sites

So should I do something like this?

`function fire(angle) {	if(game.time.now > bulletTime) {		bullet = bullets.getFirstExists(false);		if(bullet) {			bullet.reset(player.x, player.y + 8);			bullet.velocityFromAngle = angle;			bulletTime = game.time.now + 200;		}	}}`

##### Share on other sites

Oh wow, didn't see that in the documentation.

I've got one problem though, the angle I'm calculating goes up to 360 degrees, so it's never negative.

Any suggestions on how I can re-calculate that angle to -90,90 and 0?

##### Share on other sites

Whenever I run that function like this:

`anglePlayer = wrapAngle(anglePlayer, false);`

I get the error saying that wrapAngle is undefined

Edit: fixed it by using game.math.wrapAngle

##### Share on other sites

So now that I have got a angle (which is between 180 and -180, and not -90 and 90 as the velocityFromAngle functions says), how should I move the bullet in that direction?

I'm using this:

`bullet.velocity = game.physics.arcade.velocityFromAngle(angle, 500);`

But it doesn't work at all, the bullet just stays at the position the ship was at the moment of firing.

Edit: Oh, by the way, the 'game' so far can be found here: http://kevinsleegers.nl/dev/space_battalion/

##### Share on other sites

I've been working on this separately, but figured it may help. You can get the code + all the assets from the Phaser Examples github repository:

`var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render });function preload() {    game.load.image('space', 'assets/skies/deep-space.jpg');    game.load.image('bullet', 'assets/games/asteroids/bullets.png');    game.load.image('ship', 'assets/games/asteroids/ship.png');}var sprite;var cursors;var bullet;var bullets;var bulletTime = 0;function create() {    //  This will run in Canvas mode, so let's gain a little speed and display    game.renderer.clearBeforeRender = false;    game.renderer.roundPixels = true;    //  We need arcade physics    game.physics.startSystem(Phaser.Physics.ARCADE);    //  A spacey background    game.add.tileSprite(0, 0, game.width, game.height, 'space');    //  Our ships bullets    bullets = game.add.group();    bullets.enableBody = true;    bullets.physicsBodyType = Phaser.Physics.ARCADE;    //  All 40 of them    bullets.createMultiple(40, 'bullet');    bullets.setAll('anchor.x', 0.5);    bullets.setAll('anchor.y', 0.5);    //  Our player ship    sprite = game.add.sprite(300, 300, 'ship');    sprite.anchor.set(0.5);    //  and its physics settings    game.physics.enable(sprite, Phaser.Physics.ARCADE);    sprite.body.drag.set(100);    sprite.body.maxVelocity.set(200);    //  Game input    cursors = game.input.keyboard.createCursorKeys();    game.input.keyboard.addKeyCapture([ Phaser.Keyboard.SPACEBAR ]);}function update() {    if (cursors.up.isDown)    {        game.physics.arcade.accelerationFromRotation(sprite.rotation, 200, sprite.body.acceleration);    }    else    {        sprite.body.acceleration.set(0);    }    if (cursors.left.isDown)    {        sprite.body.angularVelocity = -300;    }    else if (cursors.right.isDown)    {        sprite.body.angularVelocity = 300;    }    else    {        sprite.body.angularVelocity = 0;    }    if (game.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR))    {        fireBullet();    }    screenWrap(sprite);    bullets.forEachExists(screenWrap, this);}function fireBullet () {    if (game.time.now > bulletTime)    {        bullet = bullets.getFirstExists(false);        if (bullet)        {            bullet.reset(sprite.body.x + 16, sprite.body.y + 16);            bullet.lifespan = 2000;            bullet.rotation = sprite.rotation;            game.physics.arcade.velocityFromRotation(sprite.rotation, 400, bullet.body.velocity);            bulletTime = game.time.now + 50;        }    }}function screenWrap (sprite) {    if (sprite.x < 0)    {        sprite.x = game.width;    }    else if (sprite.x > game.width)    {        sprite.x = 0;    }    if (sprite.y < 0)    {        sprite.y = game.height;    }    else if (sprite.y > game.height)    {        sprite.y = 0;    }}function render() {}`
##### Share on other sites

Oh wow, thanks alot man.

Just this line did the trick:

`game.physics.arcade.velocityFromRotation(sprite.rotation, 400, bullet.body.velocity);`
##### Share on other sites

• 1 year later...

Hey, is there any way you can provide a simple example of a ship being able to fire correctly using P2 Physics? I'm stuck.

I've been working on this separately, but figured it may help. You can get the code + all the assets from the Phaser Examples github repository:

`var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render });function preload() {    game.load.image('space', 'assets/skies/deep-space.jpg');    game.load.image('bullet', 'assets/games/asteroids/bullets.png');    game.load.image('ship', 'assets/games/asteroids/ship.png');}var sprite;var cursors;var bullet;var bullets;var bulletTime = 0;function create() {    //  This will run in Canvas mode, so let's gain a little speed and display    game.renderer.clearBeforeRender = false;    game.renderer.roundPixels = true;    //  We need arcade physics    game.physics.startSystem(Phaser.Physics.ARCADE);    //  A spacey background    game.add.tileSprite(0, 0, game.width, game.height, 'space');    //  Our ships bullets    bullets = game.add.group();    bullets.enableBody = true;    bullets.physicsBodyType = Phaser.Physics.ARCADE;    //  All 40 of them    bullets.createMultiple(40, 'bullet');    bullets.setAll('anchor.x', 0.5);    bullets.setAll('anchor.y', 0.5);    //  Our player ship    sprite = game.add.sprite(300, 300, 'ship');    sprite.anchor.set(0.5);    //  and its physics settings    game.physics.enable(sprite, Phaser.Physics.ARCADE);    sprite.body.drag.set(100);    sprite.body.maxVelocity.set(200);    //  Game input    cursors = game.input.keyboard.createCursorKeys();    game.input.keyboard.addKeyCapture([ Phaser.Keyboard.SPACEBAR ]);}function update() {    if (cursors.up.isDown)    {        game.physics.arcade.accelerationFromRotation(sprite.rotation, 200, sprite.body.acceleration);    }    else    {        sprite.body.acceleration.set(0);    }    if (cursors.left.isDown)    {        sprite.body.angularVelocity = -300;    }    else if (cursors.right.isDown)    {        sprite.body.angularVelocity = 300;    }    else    {        sprite.body.angularVelocity = 0;    }    if (game.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR))    {        fireBullet();    }    screenWrap(sprite);    bullets.forEachExists(screenWrap, this);}function fireBullet () {    if (game.time.now > bulletTime)    {        bullet = bullets.getFirstExists(false);        if (bullet)        {            bullet.reset(sprite.body.x + 16, sprite.body.y + 16);            bullet.lifespan = 2000;            bullet.rotation = sprite.rotation;            game.physics.arcade.velocityFromRotation(sprite.rotation, 400, bullet.body.velocity);            bulletTime = game.time.now + 50;        }    }}function screenWrap (sprite) {    if (sprite.x < 0)    {        sprite.x = game.width;    }    else if (sprite.x > game.width)    {        sprite.x = 0;    }    if (sprite.y < 0)    {        sprite.y = game.height;    }    else if (sprite.y > game.height)    {        sprite.y = 0;    }}function render() {}`
##### Share on other sites

• 9 months later...

hello, i have a problem. I am creating a game where you fly a spaceship in a map created with tile. the problem is my fire function just crashes the game (cant move the ship no more).

here is my code for my game.js (i also have boot preolad and main files).

var TopDownGame = TopDownGame || {};
var bulletProperties = {
speed: 400,
interval: 250,
lifeSpan: 2000,
maxCount: 30,
};
var playerProperties = {
velocity: 300,
};

var bulletInterval = 0;

TopDownGame.Game = function(){};

TopDownGame.Game.prototype = {
create: function() {

this.backgroundlayer = this.map.createLayer('background');
this.blockedLayer = this.map.createLayer('blocks');
this.map.setCollisionBetween(1, 2000, true, 'blocks');
this.backgroundlayer.resizeWorld();

this.bulletGroup.enableBody = true;
this.bulletGroup.createMultiple(bulletProperties.maxCount, 'bullet');
this.bulletGroup.setAll('anchor.x', 0.5);
this.bulletGroup.setAll('anchor.y', 0.5);
this.bulletGroup.setAll('lifespan', bulletProperties.lifeSpan);

this.player.anchor.set(0.5);
this.player.maxAngular = 500;
this.player.angularDrag = 50;

this.game.camera.follow(this.player);

this.cursors = this.game.input.keyboard.createCursorKeys();

},

update: function() {

this.player.body.velocity.x = 0;
this.player.body.velocity.y = 0;
this.player.body.angularVelocity = 0;

if (this.cursors.left.isDown) {
this.player.body.angularVelocity = -300;
}
else if(this.cursors.right.isDown) {

this.player.body.angularVelocity = 300;
}
if (this.cursors.up.isDown) {
}
if (this.key_fire.isDown) {
this.fire();

}

},
fire: function () {
//if (!this.shipSprite.alive){
//return;
//}

if (this.game.time.now > bulletInterval) {
//this.sndFire.play();
var bullet = this.bulletGroup.getFirstExists(false);

if (bullet) {
var length = this.player.width * 0.5;
var x = this.player.x + (Math.cos(this.player.rotation) * length);
var y = this.player.y + (Math.sin(this.player.rotation) * length);
bullet.reset(x, y);
bullet.lifespan = bulletProperties.lifeSpan;
bullet.rotation = this.player.rotation;
bulletInterval = game.time.now + bulletProperties.interval;
}
}
},
};

i just can figure out why it doesnt work. if you need something else just tell me. Desperation nears.

##### Share on other sites

What's the error message in the console of the browser? If you're running this in Chrome, you can go to the menu at the upper-right, go to "More Tools", then go to Developer Tools at the bottom. There might be an error printed there that will provide more information.

##### Share on other sites

Thank you. I forgot the this. before game. You sir are a lifesavior.

##### Share on other sites

• 2 months later...

Arcade physics is nice, but how would one execute the same function in p2.js?

`game.physics.arcade.velocityFromRotation(sprite.rotation, 400, bullet.body.velocity);`