我怎样才能在我的摄像头看的方向上统一滚动一个球?

How can I roll a Ball in unity in the direction my cam is looking?

我有一个可以向各个方向旋转的球体。 使用 WASD 可以将其移动 forward/backwards 并移到一边。

但现在我希望它朝我看的方向移动。 我开始编写代码,因为在 X 轴上移动鼠标,它可以向侧面旋转。这很好用,但是当使用 Forward 键时,它显然仍然在世界 "W" 方向上移动,所以 Z-Positive。 我尝试使用

rigid.AddRelativeForce(transform.forward*inputY, ForceMode.Impulse);

它应该在 "forward" 方向上移动球,这工作正常但是因为它是一个球并且它沿着它自己的轴旋转,当球滚动时前进方向一直在变化。

所以这是我的问题:我怎样才能在我用凸轮观察的方向上给一个旋转的球体一个力。

编辑: 显然可以采用相机的前向矢量,但我仍然遇到相机开始围绕球旋转的问题。

我首先尝试添加一个额外的对象,它只在 y 轴上旋转,并且相机跟随这个对象,但那不是那么干净。所以我想出了虚拟旋转,您可以在下面的固定答案中看到它。

也许你可以使用相机方向。

Camera.main.transform.forward 

代替球的transform.forward

我已经找到解决办法了。这是一个小解决方法。我从我的 mousX 移动中获得虚拟旋转并将其添加到球和相机中。对于 Ball,我用 Space.world 添加它,用四元数添加到相机。

我试着给你一个简短的例子:

//DummyRotation which I add to the object I wanna move
public class DummyRotation : MonoBehaviour {
    public Quaternion rotX = Quaternion.identity;
    public float rotSpeedX;
    void Update() {
        float mouseX = Mathf.Clamp(Input.GetAxis("Mouse X")*rotSpeedX, -15, 15);
        rotX *= Quaternion.AngleAxis(mouseX, Vector3.up);
    }
}
//Movement Script
public partial class SphereMovement : MonoBehaviour {
    private Rigidbody rigid;
    public float speed = 3.0f;

    void Start() {
        rigid = GetComponent<Rigidbody>();
    }
    void Update() {
        dummyRotation = GetComponent<DummyRotation>().rotX;
        checkKeys(); //just checks which keys are pressed
        if (forward) {
            rigid.AddForce(dummyRotation * new Vector3(0, 0, speed));
        } else if (backward) {
            rigid.AddForce(dummyRotation * new Vector3(0, 0, -speed * 0.9f));
        }
    }
}

//The Camera Script
[ExecuteInEditMode]
public class CameraFollowTarget : MonoBehaviour {

    public Transform camTarget;
    public View view; //this is a custom class which contains pitch chaw roll and offset
    private void Update() {
        View view = views.ElementAt(currentView);

        Vector3 pitchYawRoll = view.rotation;
        Vector3 offsetPosition = view.offsetPosition;
        Quaternion dummyRot = camTarget.GetComponent<DummyRotation>().rotX;
        Vector3 newPos = camTarget.position + dummyRot * offsetPosition;

        transform.position = Lerp(transform.position, newPos, 1);
    }
}