对球体施加力会将其发送到不可预测的方向

时间:2016-11-17 19:54:56

标签: c# unity3d raycasting

我试图在鼠标点击方向上移动(射击)一个球体。但是当我点击时,球体会以不可预测的方向移动。

我添加力以移动球体的代码:

if (Input.GetMouseButtonDown(0)){

    RaycastHit hit;

    /**
    * We r using raycasting to detect mouse click on plane
    * */
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

    if (Physics.Raycast(ray, out hit)){
        newPosition = hit.point;
        this.GetComponent<Rigidbody>().AddForce( (newPosition).normalized * 25, ForceMode.Impulse  );
    }
}

1 个答案:

答案 0 :(得分:2)

您为Rigidbody.AddForce()提供了错误的参数。您为第一个参数提供的矢量不应该是您希望力指向的位置 - 它应该是力的方向,乘以幅度。 / p>

在这种情况下,您可以通过从目标位置减去对象的当前位置来计算力的方向:

Vector3 forceDir = newPosition - transform.position;
this.GetComponent<Rigidbody>().AddForce( forceDir.normalized * 25, ForceMode.Impulse  );

希望这有帮助!如果您有任何问题,请告诉我。