团结:从特定位置向球添加冲量

时间:2019-01-06 18:03:59

标签: c# unity3d game-engine game-physics unityscript

我正在制作3D台球游戏,但我一直坚持这个问题。
我找不到所需的功能来向球添加脉冲以使球旋转。
换句话说,如何在要添加脉冲的位置设置AIM点?

enter image description here

如果我使用AddForce或AddTorque,似乎它是从球的中心计算得出的。
但是如何指定目标点(左英语,右英语等)?
以及如何在提示杆击中球后将球向摄像机方向路由?

1 个答案:

答案 0 :(得分:0)

乍看之下,我认为您应该检查Rigidbody.AddForceAtPosition。您还应该以某种方式在世界坐标中计算目标点。

我在Unity上还比较陌生,但我想到的主要思想是先将提示矢量沿y轴旋转一个小角度,然后通过投射物理射线来计算每个区域的命中点,最后使用刚体施加脉冲.AddForceAtPosition。我试图编写示例代码:

public class SphereController : MonoBehaviour {

private Vector3 cueStartPoint;

void Start () {

    cueStartPoint = new Vector3(0, 0.5f, -13f);

}

void Update () {

    //direction from cue to center
    var direction = transform.position - cueStartPoint;

    //rotate cue to aim right english
    var angleForRightEnglish = 5f;
    var directionForRight = Quaternion.AngleAxis(angleForRightEnglish, Vector3.up) * direction;
    Debug.DrawRay(cueStartPoint, directionForRight, Color.red, 10f);

    //rotate cue to aim right english
    var angleForLeftEnglish = -5f;
    var directionForLeft = Quaternion.AngleAxis(angleForLeftEnglish, Vector3.up) * direction;
    Debug.DrawRay(cueStartPoint, directionForLeft, Color.blue, 10f);

    //try a sample hit from right
    if (Input.GetKeyDown(KeyCode.RightArrow)) {
        var forceMagnitude = 1f;
        var hitForce = forceMagnitude * directionForRight.normalized;

        //calculate right hit point on sphere surface
        RaycastHit hitInfo;
        if (Physics.Raycast(cueStartPoint, directionForRight, out hitInfo)) {
            var rightHitPoint = hitInfo.point;
            gameObject.GetComponent<Rigidbody>().AddForceAtPosition(hitForce, rightHitPoint, ForceMode.Impulse);
        }

    }

    //try a sample hit from left
    if (Input.GetKeyDown(KeyCode.LeftArrow)) {
        var forceMagnitude = 1f;
        var hitForce = forceMagnitude * directionForLeft.normalized;

        //calculate left hit point on sphere surface
        RaycastHit hitInfo;
        if (Physics.Raycast(cueStartPoint, directionForLeft, out hitInfo)) {
            var leftHitPoint = hitInfo.point;
            gameObject.GetComponent<Rigidbody>().AddForceAtPosition(hitForce, leftHitPoint, ForceMode.Impulse);
        }

    }

}

}

该脚本当然应该作为组件添加到球中,希望对您有所帮助。