我是 Unity 新手,以下代码应该是玩家移动脚本。一切都按预期进行,直到时不时地,通常当连续按下多个输入时,玩家就会飞起来。 这是代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed;
public float yRotation;
float jumpHeight = 5;
public Rigidbody rigidbody;
public CameraController cameraController;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
yRotation = cameraController.yRotation;
float yRotationRad = yRotation * Mathf.Deg2Rad;
Debug.Log(rigidbody.velocity);
Vector3 velocity = Vector3.zero;
if (Input.GetKey(KeyCode.W))
{
velocity += new Vector3(Mathf.Sin(yRotationRad) * speed, rigidbody.velocity.y, Mathf.Cos(yRotationRad) * speed);
}
if (Input.GetKey(KeyCode.A))
{
velocity += new Vector3(Mathf.Sin(yRotationRad-Mathf.PI/2) * speed, rigidbody.velocity.y, Mathf.Cos(yRotationRad - Mathf.PI / 2) * speed);
}
if (Input.GetKey(KeyCode.D))
{
velocity += new Vector3(Mathf.Sin(yRotationRad + Mathf.PI / 2) * speed, rigidbody.velocity.y, Mathf.Cos(yRotationRad + Mathf.PI / 2) * speed);
}
if (Input.GetKey(KeyCode.S))
{
velocity += new Vector3(Mathf.Sin(yRotationRad + Mathf.PI) * speed, rigidbody.velocity.y, Mathf.Cos(yRotationRad + Mathf.PI) * speed);
}
if(velocity!= Vector3.zero)
rigidbody.velocity = velocity;
if (Input.GetKey(KeyCode.Space) && rigidbody.velocity.y == 0) {
rigidbody.velocity = new Vector3(rigidbody.velocity.x,jumpHeight,rigidbody.velocity.z);
}
}
}
我预计玩家会使用 wasd 和空间进行移动,直到玩家飞行为止。如果代码中还有任何其他问题,也请随时指出。
您正在使用刚体并希望在保持某些输入时增加速度。
您的问题是您忘记将速度乘以 Time.deltaTime,这表示自上次更新以来经过的时间。如果您不使用它,您将根据帧速率产生随机行为。
if (Input.GetKey(KeyCode.W))
{
velocity += new Vector3(Mathf.Sin(yRotationRad) * speed, rigidbody.velocity.y, Mathf.Cos(yRotationRad) * speed * Time.deltaTime);
}
此外,建议仅将 Update() 用于逻辑,如果您想玩物理,请尝试在 FixUpdate() 中进行。 有关更多信息,请参阅此https://docs.unity3d.com/ScriptReference/MonoBehaviour.FixedUpdate.html 如果将代码从 Update() 移至 FixUpdate(),请将
Time.deltaTime
替换为 Time.fixedDeltaTime