Unity 2D控制器

时间:2015-09-17 00:52:58

标签: unity3d unityscript

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

using UnityEngine;
using UnityEngine.EventSystems;

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

    void Start()
    { }
    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;
    }

1 个答案:

答案 0 :(得分:0)

我的猜测是当你按空格键时,bool“接地”没有改变。如果你跳,这个布尔必须是假的,所以它会回到地面。