繁体   English   中英

Unity2D无法跳转

[英]Unable to jump in Unity2D

按向上箭头键时无法跳跃。 当我移除 isGrounded 的条件以能够跳跃时,那么我的角色就可以在空中跳跃。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    [SerializeField] private float speed;
    private Rigidbody2D body;
    bool isGrounded;

    private void Awake()
    {
        body = GetComponent<Rigidbody2D>();
    }

    private void Update()
    {
        float HorizontalInput = Input.GetAxis("Horizontal");
        body.velocity = new Vector3(Input.GetAxis("Horizontal") * speed, body.velocity.y);

        if (HorizontalInput < -0.01f)
            transform.localScale = Vector3.one;
        else if (HorizontalInput > 0.01f)
            transform.localScale = new Vector3(-1, 1, 1);
        
        if (Input.GetKey(KeyCode.UpArrow))
            isGrounded = false;

        if (Input.GetKey(KeyCode.UpArrow) && isGrounded)
            body.velocity = new Vector2(body.velocity.x, speed);
    }

    private void OnCollisionEnter2D()
    {
        isGrounded = true;
    }
}

我尝试使用 OnCollisionEnter2D 将 isGrounded 设置为 true,但我认为它不起作用。

问题出在这个逻辑上:

        if (Input.GetKey(KeyCode.UpArrow))
            isGrounded = false;

        // isGrounded will always be false here if up-arrow key is pressed.
        if (Input.GetKey(KeyCode.UpArrow) && isGrounded)
            body.velocity = new Vector2(body.velocity.x, speed);

你在找什么:

        if (Input.GetKey(KeyCode.UpArrow) && isGrounded) {
            body.velocity = new Vector2(body.velocity.x, speed);
            isGrounded = false;
        }

使用大括号表示语句下的多行代码。

此外, 使用 FixedUpdate 进行与物理相关的操作,例如 Rigidbodies

暂无
暂无

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

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