【问题标题】:local movement on rigidbody sphere with the mouse and keyboard使用鼠标和键盘在刚体球体上进行局部移动
【发布时间】:2013-11-14 12:29:29
【问题描述】:

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

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

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

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);

    }

}

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

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

【问题讨论】:

    标签: c# unity3d input geometry


    【解决方案1】:

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

    我引用了相机 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);
    }
    

    【讨论】:

      【解决方案2】:

      这样的事情应该可以解决问题::

      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)
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-09
        • 2023-03-28
        • 1970-01-01
        • 2015-09-23
        • 2019-04-04
        • 1970-01-01
        • 1970-01-01
        • 2014-02-27
        相关资源
        最近更新 更多