I'm trying to find a good solution for a bullet to hit the enemy. The game is 2D tower defense, the tower is supposed to shoot a bullet and hit the enemy guaranteed.
I tried this solution - http://blog.wolfire.com/2009/07/linear-algebra-for-game-developers-part-1/
The link mentioned to subtract the bullet's origin and the enemy as well (vector subtraction). I tried that but a bullet just follows around the enemy.
float diffX = enemy.position.x - position.x;
float diffY = enemy.position.y - position.y;
velocity.x = diffX;
velocity.y = diffY;
position.add(velocity.x * deltaTime, velocity.y * deltaTime);
I'm familiar with vectors but not sure what steps (vector math operations) to be done to get this solution working.
Answer
Your reasoning was perfect: use a vector to move from my position to my target. This is the purpose of a vector; you simply forgot the speed!
Velocity is a vector: a speed and a direction. However, if you forget to normalize the difference vector and multiply it the bullet speed (a scalar), you are basically saying that if you are close to the target (the difference vector is small) the bullet slows down; while if you are far away the bullet speed is larger.
This is the underlying problem: you need to calculate both the direction and the magnitude of the vector.
No comments:
Post a Comment