c# - 使物体朝某个方向加速

标签 c# unity3d scripting acceleration

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

我有这个对象,我需要它加速到矢量 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,因为这样做更有意义。

关于c# - 使物体朝某个方向加速,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38277778/

相关文章:

c# - 从抽象类型对象数组访问特定子类的对象

c# - 当尝试从 swi-prolog 获取列表时,SwiPlCs 抛出 'Precondition Failed'

c# - 子触发器也运行父触发器吗?

c# - 从unity c#调用java方法

linux - 条件循环中的多个读取命令是否会在 shell 脚本中产生问题

c# - 使用 asp.net c# 将事件类添加到当前超链接

c# - 用linq减去两个表

c# - 在 Unity/C# 中,.Net 的 async/await 是否真的启动了另一个线程?

javascript - 从photoshop Javascript中的指定文件夹中获取文件名

bash - 如何从 'time' 命令中获取实时值?