Simple Question

Started by
1 comment, last by NickyP101 19 years, 1 month ago
Ok here is the question: In my 2D top down view, multiplayer network shooter, bullets travell from the player position to the position that clicked. This movement is formulated by finding the gradient on the line, then adding 1 to the x and adding m (gradient) to the y val. This works fyn. But the bullets travvel extrordinarely slow, because im only adding one to the x val everytime the bullet is updated (Every Frame). How can i make my bullet travell faster without making its destination inaccurate, and also making the collision detection inacurate?? So is there away without adding 10 to the x value and multiplying the gradient by 10?
Advertisement
You can do this by finding vector between the player and the target, normalize it and scale the result by the intended velocity.

struct vector { float x, y;};vector bulletAim(vector player, vector target, float speed) { float scale; vector result; // find traveling vector for the bullet to reach its target result.x = target.x - player.x; result.y = target.y - player.y; if(!result.x && !result.y) {  return result; } // use the pythagoran theorem to find its length scale = sqrt(tmp.x * tmp.x + tmp.y * tmp.y); if(!scale) {  return result; } // divide the traveling vector by its length to get one of length 1 // and scale it by the desired velocity scale = speed / scale; result.x *= scale; result.y *= scale; return tmp;}


Another approach is to find the angle between the vectors with some help from atan2 and use cos/sin to synthesise a vector.
vector bulletAim(vector player, vector target, float speed) { float angle; vector result; // find traveling vector for the bullet to reach its target result.x = target.x - player.x; result.y = target.y - player.y; // find its angle angle = atan2(result.y, result.x); // create new vector with the same direction but length 1 result.x = cos(angle); result.y = sin(angle); // scale it to match the desired speed result.x *= speed; result.y *= speed;}


[Edited by - doynax on March 15, 2005 5:53:51 AM]
Thanks Champ :)

This topic is closed to new replies.

Advertisement