javamathinterpolationequationaim

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:

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?


Solution

  • 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