繁体   English   中英

Unity 3D 移动脚本出现问题

[英]Trouble with a Unity 3D movement script

场景的图像。 我正在使用在线教程,然后在代码无法正常工作时遇到问题。

我的主要问题是 isGrounded 变量。 使用时,它不允许我的精灵跳跃,当它的工作是通过仅允许您在接触地面时跳跃来防止双跳时,一切都与发动机内组件有关,我认为主要问题是该行:

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层与groundMask相同。

编辑:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM