[SOLVED] How to determine velocity x and velocity y from an angle and speed?


(Quang Tran) #1

Sorry if this sounds like a really dumb question, but I can not recall the math I need to calculate the X-velocity and Y-velocity of an object from an angle and a top speed.

In my game, the character has a gun with an angle, and it shoots bullets that travel at 5 pixels a frame. I want to give the bullets the X-velocity and Y-velocity they should move every frame based on the gun’s angle and the bullet speed, but I’m getting really weird results (bullets are not going in the direction the gun is pointing).


(Bora Kasap) #2

run this when bullet created

angle = FP.angle(x,y, target.x, target.y)

run this everyframe in bullet

x += Math.cos(angle*FP.RAD*speed)
y += Math.sin(angle*FP.RAD*speed)

hope that gonna help


(JP Mortiboys) #3

Not quite; you want this:

x += Math.cos(angle*FP.RAD)*speed
y += Math.sin(angle*FP.RAD)*speed

But for performance you’d be better off doing this:

// On creation/init:
angle = FP.angle(x, y, target.x, target.y);
dx = Math.cos(angle * FP.RAD) * speed;
dy = Math.sin(angle * FP.RAD) * speed;

// in every frame:
x += dx;
y += dy;

It’s also possible to remove the requirement for angles completely:

// On creation:
dx = target.x - x;
dy = target.y - y;
var coef:Number = speed / Math.sqrt(dx*dx+dy*dy);
dx *= coef; dy *= coef;

// Every frame:
x += dx;
y += dy;

(of course if you want bullets to fan out or something then you’re better off with the angle approach)


(Quang Tran) #4

I plugged it in and it works! Thanks for the quick aid!