Unity 3D运动脚本出现问题



场景的图像。我在网上使用了一个教程,当代码无法正常工作时,我遇到了问题。

我的主要问题是isGrounded变量。当使用时,它不允许我的精灵跳跃,当它的工作是通过只允许你在接触地面时跳跃来防止doube跳跃时,所有的东西都连接到引擎内的组件,我认为主要的问题是这条线:

isGrounded=Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

代码的其余部分如下。感谢阅读。

public class PlayerMovement : MonoBehaviour
{
public CharacterController controller;
public float speed = 10f;
Vector3 velocity;
public float gravity = -20f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
public float jumpHeight = 3f;
public float speedManager = 1.5f;
bool isGrounded;
// Start is called before the first frame update
void Start()
{

}
// Update is called once per frame
void Update()
{

isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if( isGrounded && velocity.y < 0)
{
velocity.y = -10f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");

Vector3 move = transform.right * (x / speedManager) + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);


velocity.y += gravity * Time.deltaTime;
if (Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -10f * gravity);
}
controller.Move(velocity * Time.deltaTime);

}
}

检查组件中是否设置了public LayerMask groundMask;,并且地面游戏对象的图层是否与groundMask相同。

编辑:

您可以将这段代码添加到您的类中,以检查地面检查是否在正确的位置执行:

private void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawSphere(groundCheck.position, groundDistance);
}

最新更新