2d game : fire at a moving target by predicting intersection of projectile and unit

后端 未结 11 774
庸人自扰
庸人自扰 2020-11-28 22:26

Okay, this all takes place in a nice and simple 2D world... :)

Suppose I have a static object A at position Apos, and a linearly moving object B at Bpos with bVeloci

11条回答
  •  爱一瞬间的悲伤
    2020-11-28 22:59

    I've seen many ways to solve this problem mathematically, but this was a component relevant to a project my class was required to do in high school, and not everyone in this programming class had a background with calculus, or even vectors for that matter, so I created a way to solve this problem with more of a programming approach. The point of intersection will be accurate, although it may hit 1 frame later than in the mathematical computations.

    Consider:

    S = shooterPos, E = enemyPos, T = targetPos, Sr = shooter range, D = enemyDir
    V = distance from E to T, P = projectile speed, Es = enemy speed
    

    In the standard implementation of this problem [S,E,P,Es,D] are all givens and you are solving either to find T or the angle at which to shoot so that you hit T at the proper timing.

    The main aspect of this method of solving the problem is to consider the range of the shooter as a circle encompassing all possible points that can be shot at any given time. The radius of this circle is equal to:

    Sr = P*time
    

    Where time is calculated as an iteration of a loop.

    Thus to find the distance an enemy travels given the time iteration we create the vector:

    V = D*Es*time
    

    Now, to actually solve the problem we want to find a point at which the distance from the target (T) to our shooter (S) is less than the range of our shooter (Sr). Here is somewhat of a pseudocode implementation of this equation.

    iteration = 0;
    while(TargetPoint.hasNotPassedShooter)
    {
        TargetPoint = EnemyPos + (EnemyMovementVector)
        if(distanceFrom(TargetPoint,ShooterPos) < (ShooterRange))
            return TargetPoint;
        iteration++
    }
    

提交回复
热议问题