一,在角色下添加一個空物體
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); } }