Unity 2D 控制器

问题描述 投票:0回答:1

我在检测地面时遇到问题(跳跃似乎在空气中循环) - 跳跃长度是随机的,声音似乎循环。因此我猜地面探测并没有真正起作用。我的代码是:

using UnityEngine;
using UnityEngine.EventSystems;

public class PlayerCtrl : MonoBehaviour
{
    bool facingRight = true;
    public AudioSource jumpSoundEffect;
    private bool grounded;

    void FixedUpdate ()
    {
        grounded = Physics2D.IsTouchingLayers(GetComponent<Collider2D>(), LayerMask.GetMask("Ground"));
    }

    void Update()
    {
        Movement();
    }

    void Movement()
    {
        if (Input.GetKey(KeyCode.RightArrow))
        {
            transform.Translate(Vector2.right * 4f * Time.deltaTime);
            if (facingRight == false)
                Flip();

            facingRight = true;
        }
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            transform.Translate(Vector2.left * 4f * Time.deltaTime);
            if (facingRight == true)
                Flip();

            facingRight = false;
        }
        if (Input.GetKey(KeyCode.Space) && grounded)
        {
            transform.Translate(Vector3.up * 50f * Time.deltaTime);
            jumpSoundEffect.Play ();
        }
    }

    void Flip()
    {
        Vector3 theScale = transform.localScale;
        theScale.x *= -1;
        transform.localScale = theScale;
    }
}
c# unity-game-engine
1个回答
0
投票

我的猜测是,当您按空格键时,“接地”布尔值不会改变。如果你跳起来,这个布尔值一定是假的,所以它会回到地面。

© www.soinside.com 2019 - 2024. All rights reserved.