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

后端 未结 7 1686
北海茫月
北海茫月 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条回答
  •  别那么骄傲
    2021-02-04 17:45

    You need to think in proper physics terms. You have a velocity, and you want to add an acceleration. That's all there is to it - the acceleration is a gradual change in velocity that will draw the enemy towards to player, allow it to overshoot, slow down (or turn) and then head back towards the player.

    Acceleration is measured as d(velocity)/time. You want to accelerate towards the player at any point in time, so every interval (second, hundredth of a second or whatever you choose) you need to add the vector between enemy and player, multiplied by some constant, to your velocity.

    Velocity = Velocity + c * (Player-Enemy vector)
    

    Constant c will depend on how fast you want to accelerate towards the player, and how often you are updating your velocity.

    If you want to 'cap' the maximum speed of the enemy so that it doesn't continue to increase the magnitude of its velocity indefinitely, you can also do so.

    Velocity = Velocity * (Maximum magniture / |Velocity|)
    

    EDIT: to clarify further, adding a Velocity simply means adding the component vectors. So

    Vx = Vx + c * Ax
    Vy = Vy + c * Ay
    

    where V is velocity and A is acceleration. Magnitude is measured as sqrt(Vx^2 + Vy^2), ie the hypotenuse of a right triangle. So if you want maximum speed of the enemy to be m,

    Vx = Vx * ( m / sqrt(Vx^2 + Vy^2)
    Vy = Vy * ( m / sqrt(Vx^2 + Vy^2)
    

提交回复
热议问题