簡體   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