On Mar 23, 4:30 pm, "CMulvey" <devn
...@stuff.com> wrote:
> This might sound like a very elementary question, i've been working on a
> small personal project making a top down shooting game where the player
> controls a character(sprite) using the mouse, the player's character should
> be able to shoot from its current location, in a straight line in at the
> cursor.
Let (bx,by) be the coordinates of the bullet. Then you have a bullet
velocity which is (bdx,bdy). This assumes that each frame represents
a constant timeslice. So, each frame, you have:
bx=bx+bdx
by=by+bdy
Simple enough; presumably you already have something like this
implemented. The remaining question is, what should bdx and bdy
be initialized as? Okay, let's assume (bx,by) is initialized at the
player's position, and (mx,my) is the mouse position. Let's SPEED
be the desired bullet speed in pixels. Then you can calculate
(bdx,bdy) using this algorithm:
bdx = mx-bx
bdy = my-by
distance = sqrt(bdx*bdx+bdy*bdy)
if distance = 0
bdx = 0
bdy = -SPEED
else
bdx = bdx*SPEED/distance
bdy = bdy*SPEED/distance
endif
To a first approximation, the bullet velocity is in the correct
direction if we simply subtract the current position from the
destination position. However, the speed will be wrong.
So we calculate the distance using the Pythagorean
formula, and scale (bdx,bdy) to a new length of SPEED.
We have to check for distance=0 so we don't divide by
zero when the mouse is exactly on top of the player. In
that case, we apply an arbitrary direction (in this case,
straight up).
Isaac Kuo