Programming a smooth change of thrust from current velocity vector to a target vector

后端 未结 7 1689
北海茫月
北海茫月 2021-02-04 16:47

TL;dr: \"I am not sure how to calculate a smooth transition of thrust between one vector and another.\"

I am programming a simple game where an enemy chases after the pl

7条回答
  •  梦毁少年i
    2021-02-04 17:43

    You may get the effect you want by ensuring a smooth change in velocity, rather than thrust. That way, if the enemy overshoots the player, it can immediately reverse its acceleration, which will slow it down and eventually reverse its direction of travel.

    You can accomplish this by changing the velocity during each iteration, by a small amount that's based on the distance from the enemy to the player:

    while (game_in_progress)
    {
        // Distance from enemy to player.  The larger the
        // distance, the greater the acceleration will be.
        delta.x = player.x - enemy.x
        delta.y = player.y - enemy.y
    
        // Accelerate by changing velocity based on distance,
        // where 'scale' is sufficiently small. (Limit v to
        // some maximum if you choose; likely to be unnecessary.)
        v.x += delta.x * scale
        v.y += delta.y * scale
    
        // Update the enemy's position.
        enemy.x += v.x
        enemy.y += v.y
    }
    

    By calculating the x and y values independently, you can save yourself the headache of dealing with vectors, angles, and simultaneous equiations.

    Similarly, by recognizing that acceleration (thrust) is simply a change in velocity, which in turn is a change in position, you can create a discrete-time simulation using only simple algebra instead of calculus.

    Have fun!

提交回复
热议问题