使物体朝某个方向加速

Accelerate object towards a certain direction

我想自己做一个游戏,遇到了困难。

我有这个对象,我需要它加速到矢量 3 点。

我尝试使用Vector3.MoveTowards命令,但物体以恒定速度移动并停在目的地。

我需要做的是让物体从0速度加速到矢量3点,并且不在该点停止,而是在经过该点后继续沿同一方向前进。

有人知道怎么做吗?

谢谢!

UpdateFixedUpdate 方法中调用的方法中执行这些步骤。如果您使用刚体,建议使用 FixedUpdate

首先,您需要找到从您的位置到该点的方向,如果不使用刚体,则在您的脚本中定义一个 velocity 实例变量。如果您 使用 Rigidbody,请改用 rigidbody.velocitytarget 是您要加速到达的 Vector3 位置。

// Use rigidbody.velocity instead of velocity if using a Rigidbody
private Vector3 velocity; // Only if you are NOT using a RigidBody

Vector3 direction = (target - transform.position).normalized;

然后你需要检查我们是否已经超过了目标。此检查确保速度保持不变

// If our velocity and the direction point in different directions 
// we have already passed the target, return
if(Vector3.Dot(velocity, direction) < 0)
    return;

完成此操作后,我们需要加速我们的TransformRigidbody

// If you do NOT use rigidbodies
// Perform Euler integration
velocity += (accelMagnitude * direction) * Time.deltaTime;
transform.position += velocity * Time.deltaTime;

// If you DO use rigidbodies
// Simply add a force to the rigidbody
// We scale the acceleration by the mass to cancel it out
rigidbody.AddForce(rigidbody.mass * (accelMagnitude * direction));

我建议您使用 Rigidbody,因为这样做更有意义。