Aiming Calculation at Tower-Defense
I'm building a little tower-defense game with some friends in Java. Now I'm assigned with the logic for towers and at the moment I'm trying to figure out how a tower has to turn to aim and hit a target monster. Because a monster moves on while the tower is turning and shooting, it needs to aim for a future position. I've implemented a function, which gives me the position of a monster at any time t and also a function, which gives me the smaller angle needed to turn to a monster, but now I'm confused because there are three unknown variables:
- t1 or angle: the time or angle, the tower needs to turn (the speed at which a tower can turn is given)
- t2 or shoot distance: the time a bullet needs to travel to hit the target (speed also given, 开发者_JS百科constant).
- t3 or travel distance: the distance the monster travels in the same time.
So I'm searching for a solution for:
min(t1+t2) = min(t3)
where the target monster is still in range of the tower. I already thought of calculating with the maximal needed turn and maximal possible range and then stepwise decrementing, but I'm curious if there is a "perfect" non-heuristic solution?
For every coordinate we can calculate the time tB that we need to have a bullet at that location. That's the turn time plus the time a bullet needs (t1 + t2).
The earliest time we can hit the monster is the first location on the monsters (predicted) path, where monster and bullet have their fatal meeting.
I'd start from the monsters location, calculate times and locations for the beast and calculate if a bullet will arrive earlier or later.
You could eliminate one of the variables if you just turn and check on every degree or tick if you can kill the monster if you fire now. You'll just have two vectors (aiming, monster move direction) with one intersection point and simply have to test, if monster and bullet meet there at the same time (distance to intersections point, speed).
ADDED INFO:
I assume that a given monster has distance D to the tower, moves on the shortest path to the tower, and the tower starts turning towards the monster. This is the situation at t=0
.
FIXED TYPOS:
If your tower turns with an angular speed omega
, that is, the angle phi
at time t
is
phi = omega * t
So if you know that your tower has to turn an angle phi
, the bullet will be shot at
t = phi/omega
From this on the distance which the bullet speed v
has traveled is
s(t) = v * (t-phi/omega)
If your monster moves with a speed vm
, the monster will be
at distance d
d(t) = D - vm * t
The bullet hits the monster if
s(t) = d(t)
This equation is easy to solve: just substitute d(t)
and s(t)
and rearange the terms for getting t
:
t = (D + v * phi/omega) / (phi/omega + vm)
And the bullet will have traveled s(t)
at this moment. If this value is negative, the monster was too fast and reached the tower before the bullet was fired
精彩评论