Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I have a player sprite that has a x and y coordinate and also a radian. The radian determines which way the sprite faces in a top-down game interface. In this case, the radian points from the player sprite to the mouse cursor, so the player is always facing the mouse.

I'm calculating it like this:

this.radian = Math.atan2(inputs.mousey - this.ypos, inputs.mousex - this.xpos);

Now I want the player to be able to fire bullets. The bullet sprite is 5x5 pixels, and I want it to fire directly away from the player in the players direction (so it's basically firing in the direction of the mouse cursor). The bullets the player fires are held in an array called (conveniently) bullets. It's a 2-dimensional array that looks like this:

var bullets = [
    [xpos, ypos, radian], // first bullet
    [xpos, ypos, radian], // second bullet
    [xpos, ypos, radian]  // third bullet
]

The bullet is to travel 5 pixels on each game tick, in the direction determined by the radian. But I'm having trouble working out the math for this. I already have the bullet being drawn to the canvas, and I can make it move, but have no idea how to make it follow the direction the radian is pointing.

Could anyone lend a hand, perhaps a code sample? Thanks.

share|improve this question

1 Answer 1

up vote 3 down vote accepted
speed = 5.0; // pixels per tick
xVelocity = speed * cos(radian);
yVelocity = speed * sin(radian);
share|improve this answer
    
After doing this: this.bullets[i][0] = 5 * Math.cos(this.bullets[i][3]); this.bullets[i][1] = 5 * Math.sin(this.bullets[i][3]); the bullets don't even appear, although they are being updated and drawn. I guess they're outside of the viewport? –  Robinson Nov 9 '11 at 19:45
    
Nevermind I was being dumb. It works, thanks :) –  Robinson Nov 9 '11 at 19:51

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.