Unity 2D角色跳跃

一,在角色下添加一个空物体

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

public class PlayerController : MonoBehaviour {

    private Rigidbody2D m_rg;

    public float MoveSpeed;
    public float JumpSpeed;

    //在角色下添加一个空物体
    //设置一个跳跃监测点
    public Transform CheckPoint;
    //设置一个跳跃监测半径
    public float CheckRadius;
    //设置一个跳跃监测层---角色与地面的检测
    public LayerMask WhatIsGround;

    //角色默认是否着地--true
    public bool isGround;

    private Animator Anim;


    void Start () {

        m_rg = gameObject.GetComponent<Rigidbody2D>();
        Anim = gameObject.GetComponent<Animator>();
    }
    
    // Update is called once per frame
    void Update () {
        //
        isGround = Physics2D.OverlapCircle(CheckPoint.position, CheckRadius, WhatIsGround);


        //------------------Input.GetAxisRaw没有小数值,只有整数,不会产生缓动------------------
        //角色水平移动
        //按住D键,判断如果大于0,则向右开始移动
        if (Input.GetAxisRaw("Horizontal") > 0)
        {
            m_rg.velocity = new Vector2(MoveSpeed, m_rg.velocity.y);

            //设置自身缩放的值
            transform.localScale = new Vector2(1f,1f);
        }
        //角色水平移动
        //按住A键,判断如果小于0,则向左开始移动
        else if (Input.GetAxisRaw("Horizontal") < 0)
        {
            m_rg.velocity = new Vector2(-MoveSpeed, m_rg.velocity.y);

            //如果new Vector2(-1f, 1f)  x值为负数,则图片进行反转显示
            transform.localScale = new Vector2(-1f, 1f);
        }
        else
        //角色水平移动
        //松开按键,判断如果等于0,则停止移动
        {
            m_rg.velocity = new Vector2(0, m_rg.velocity.y);
        }

        //角色按下空格键实现跳跃
        //禁止二连跳
        //要先判断角色是否在地面上,在地面上可以跳,不在地面上则不能跳
        if (Input.GetButtonDown("Jump")&& isGround)
        {

            m_rg.velocity = new Vector2(m_rg.velocity.x,JumpSpeed);
        }


        Anim.SetFloat("Speed", m_rg.velocity.x);
        Anim.SetBool("Grouned", isGround);
    }
}

猜你喜欢

转载自www.cnblogs.com/yueqingli/p/10120607.html