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.

speed = 5.0; // pixels per tick
xVelocity = speed * cos(radian);
yVelocity = speed * sin(radian);
  • \$\begingroup\$ 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? \$\endgroup\$ – Robinson Nov 9 '11 at 19:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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