Unity 2D角色移動方式(二)
阿新 • • 發佈:2018-12-14
一,使用velocity方法移動角色;
二,使用localScale,使x等於負數實現圖片反轉;
三,m_rg.velocity = 數值*方向;
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { private Rigidbody2D m_rg; public float MoveSpeed; void Start () { m_rg= gameObject.GetComponent<Rigidbody2D>(); } // Update is called once per frame void Update () { //------------------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); } } }