我从Youtube Unity教程视频中复制了这段代码,但我无法弄清楚它有什么问题。
当我团结一致地玩游戏时,我试着用鼠标向上看,它试图阻止我这样做。
using UnityEngine;
using System.Collections;
public class FirstPersonController : MonoBehaviour {
public float movementSpeed = 5.0f;
float verticalRotation = 0;
public float upDownRange = 60.0f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//Rotation
float rotLeftRight = Input.GetAxis("Mouse X");
transform.Rotate(0, rotLeftRight, 0);
verticalRotation = Input.GetAxis("Mouse Y");
verticalRotation = Mathf.Clamp(verticalRotation, -upDownRange, upDownRange);
Camera.main.transform.localRotation = Quaternion.Euler(verticalRotation, 0, 0);
//Movement
float forwardSpeed = Input.GetAxis ("Vertical") * movementSpeed;
float sideSpeed = Input.GetAxis("Horizontal") * movementSpeed;
Vector3 speed = new Vector3 (sideSpeed, 0, forwardSpeed);
speed = transform.rotation * speed;
CharacterController cc = GetComponent<CharacterController>();
cc.SimpleMove (speed);
}
}
答案 0 :(得分:1)
我认为问题在于您在verticalRotation中指定Mouse Y值而不是递增它。
尝试类似:
float yAxis = Input.GetAxis("Mouse Y");
verticalRotation = Mathf.Clamp(verticalRotation + yAxis, -upDownRange, upDownRange);`
也许你应该有一个rotationSpeed,就像你有movingSpeed一样。
答案 1 :(得分:1)
如果此脚本在相机上,则:
在这里,尝试用更简单的方式替换您的更新。
void Update()
{
//Rotation
float rotLeftRight = Input.GetAxis("Mouse X");
//transform.Rotate(0, rotLeftRight, 0);
verticalRotation = Input.GetAxis("Mouse Y");
verticalRotation = Mathf.Clamp(verticalRotation, -upDownRange, upDownRange);
//Only add the rotation when both values are set so you don't overwrite the first one.
transform.Rotate(-verticalRotation, rotLeftRight, 0);
//Movement
float forwardSpeed = Input.GetAxis("Vertical") * movementSpeed;
float sideSpeed = Input.GetAxis("Horizontal") * movementSpeed;
Vector3 speed = new Vector3(sideSpeed, 0, forwardSpeed);
speed = transform.rotation * speed;
CharacterController cc = GetComponent<CharacterController>();
cc.SimpleMove(speed);
}
我相信你的主要问题是你在设置X时将Y设置为0然后稍微设置Y后将X设置为0,因为这是在更新中,它看起来很紧张并且结束了两者均为0。