0

所以我已经完成了 Unity 的 Roll a ball 教程,这是一个小游戏,它使用了一个球体,其中应用了一个刚体,并带有一些基本的运动脚本

我现在想要的是更进一步,并引入一个更高级的移动脚本,它也可以使用鼠标输入。

我想要实现的是根据局部轴添加力,所以如果我将鼠标向左移动,球会转动并且在那个方向上添加力。让我展示一下我想出的代码(添加到应用刚体的简单球体中):

using UnityEngine;
using System.Collections;

public class playerController : MonoBehaviour {

    public float turnSpeed = 2.0f;
    public float moveSpeed = 250.0f;

    void FixedUpdate() {

        float h = turnSpeed * Input.GetAxis("Mouse X");
        transform.Rotate(0, h, 0);

        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");
        Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
        rigidbody.AddForce(movement * moveSpeed * Time.deltaTime);

    }

}

好的,所以发生的事情是当我移动鼠标时球正在转动,如果我使用箭头键,球正在滚动,但是经过反复试验后我无法弄清楚的是让球移动它转向的方向。

您将如何处理这种特殊情况?任何帮助都是非常感谢的家伙。

4

2 回答 2

0

我设法解决了这个问题并分享给其他人看。

我引用了相机 GameObject 并在键上使用了 camera.transform。猜猜它真的很基本,但仍然如此。

public GameObject Camera;
public float moveSpeed = 0.0f;

if (Input.GetKey ("right") || Input.GetKey ("d")) {
    rigidbody.AddForce( Camera.transform.right * moveSpeed * Time.deltaTime);
}

if (Input.GetKey ("left") || Input.GetKey ("a")) {
    rigidbody.AddForce( -Camera.transform.right * moveSpeed * Time.deltaTime);
}

if (Input.GetKey ("up") || Input.GetKey ("w")) {
    rigidbody.AddForce( Camera.transform.forward * moveSpeed * Time.deltaTime);
}

if (Input.GetKey ("down") || Input.GetKey ("s")) {
    rigidbody.AddForce( -Camera.transform.forward * moveSpeed * Time.deltaTime);
}
于 2013-11-14T14:52:37.083 回答
0

像这样的东西应该可以解决问题::

if (Input.GetKey ("up") || Input.GetKey ("w")) {
    rigidbody.AddForce( Camera.transform.forward * moveSpeed * Time.deltaTime);
    rigidbody.AddRelativeTorque(vector3.right * speed)
    //Note that rotation happens around the axis, so when moving (forward orback you will rotate on the vector3.right/left) and when moving( Right/left you will use the vector3.forward/back)
}
于 2013-11-14T17:13:31.343 回答