Unity3D控制人物跳跃

96
Godtoy
2017.03.29 10:37* 字数 5
Paste_Image.png

脚本如下:

using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour
{

    public float m_JumpSpeed = 400f;
    private bool m_jumping = false;
    private Rigidbody2D m_Rigidbody2D;
    private Animator m_Anim;
    //是否在地面上
    private bool grounded = true;


    private void Awake()
    {
        m_Anim = GetComponent<Animator>();
        m_Rigidbody2D = GetComponent<Rigidbody2D>();
    }

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetButtonDown("Jump"))
        {
            Jump();
        }
    }

    private void Jump()
    {
        if (this.grounded)
        {
            m_Rigidbody2D.AddForce(new Vector2(0f, m_JumpSpeed));
            grounded = false;
        }
    }
    //这个时候在地面上
    private void OnCollisionEnter2D(Collision2D collision)
    {
        grounded = true;
    }
}

Unity3D