使力 Vector3 适应方向 Vector3

Adapt force Vector3 to directional Vector3

我有一个 Vector3 表示玩家对球的输入力

Vector3(moveHorizontally, 0.0f, moveVertically);

我有另一个 Vector3 指示平面的归一化方向

Vector3(-1.0f, 0.0f, 0.0f);

如何使用 AddForce() 让球跟随物体的方向?在这种情况下,如果我没记错的话,我认为球应该往左而不是往前。

编辑:我不需要在某个方向上向前移动球。每次球触发一个平面时,平面所面对的方向就成为球的方向。这是一个球在非线性轨道上滚动的游戏。

不会使用AddForce,因为我猜你想在碰撞时立即改变方向。

我觉得你的意思是这样的

private rigidBody;

private void Awake()
{
    rigidBody = GetComponent<RigidBody>();
}

private void OnCollisionEnter(Collision col)
{
    // Or however you want to check with what you are colliding
    if(col.gameObject.tag != "Plane") return;

    var hitPlane = col.gameObject;
    var invertedPlaneNormal = hitPlane.transform.forward.normalized * -1;

    var currentSpeed = rigidBody.velocity.magnitude;

    // Keep same velocity but change direction immediately
    rigidBody.velocity = invertedPlaneNormal * currentSpeed;
}

你也可以像这样添加阻尼

[Range(0,1)]
public float dampFactor;

//...

rigidBody.velocity = invertedPlaneNormal * currentSpeed * (1 - dampFactor);

我没有具体的代码,但是假设小球附有刚体,路径和小球都有碰撞器,你可以使用Unity碰撞事件来确定小球的未来方向.

假设球附有一个脚本,当它碰撞时会触发一个 onCollisionEnter 事件,然后从那里你可以得到它所碰撞的平面的脚本组件并在右侧施加力方向作为对碰撞的响应。

注意onCollisionEnter只在对象进入碰撞时发生。