Moving along a two-dimensional vector (tower defense) in C ++

I am writing a simple tower defense, and I am stuck a little where my tower should shoot at the enemy.

With this code:

void Bullet::move(int x, int y, int speed) { Punkt delta = {(x + speed) - this->x, (y + speed) - this->y}; if (abs(delta.x) > 1 && abs(delta.y) > 1) { this->x += delta.x / this->speed; this->y += delta.y / this->speed; } else { this->dead = true; } } 

Where the arguments of the method are the target position and speed. It must move the bullet along the vector until it reaches the goal, but the vector changes because the target moves. At the moment, the bullet is ending (black is the tower, blue is the bullet, and red is the enemy)

error

And I know, the problem is that my bullet is aimed at something that has already moved, so my question is: how to improve this code so that it works correctly? I don’t know how to wrap my head around vectors and ballistics, so it’s in advance to make it simple.

+4
source share
3 answers

A reasonable solution to this problem that I saw earlier is as follows:

  • Do your best to predict where there will be a good point of collision for the bullet and the enemy. A naive approach would be to make your prediction just your opponent’s current position.
  • Fire a bullet in a predictable position
  • When the bullet falls into a predictable position, make the bullet disappear, play the damage animation and lower the enemy’s health - regardless of whether the bullet really hits

Thus, if you are smart enough in your math, it will look good. But otherwise the game will work fine.

This approach is also more stable if enemies can change speed (for example, they slow down in a special area or tower with an area effect) after you shoot them.

+3
source

If you shoot at a moving target, you need to target where it will be when it is required for the bullet to reach it, then you have two well-known positions so that you know the vector.

+2
source

Ok, I looked a bit on the gamedev forums, and I got a solution (which I even managed to figure out). It's all about proper calculation (conversion to float was necessary, as everyone said). Here is the code for the lazy:

 float dx = x - this->x; float dy = y - this->y; float dx2, dy2; float distance; float vx, vy; distance = sqrt(dx * dx + dy * dy); dx2 = dx / distance; dy2 = dy / distance; vx = dx2 * this->speed; vy = dy2 * this->speed; if (distance > 10) // 10 is hitbox size { this->x += vx; // still float, its converted to int when applying to surface this->y += vy; } else { this->dead = true; } 
0
source

All Articles