一,使用velocity方法移动角色;
二,使用localScale,使x等于负数实现图片反转;
三,m_rg.velocity = 数值*方向;
1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4 5public class PlayerController : MonoBehaviour { 6 7 private Rigidbody2D m_rg; 8 9 public float MoveSpeed; 10 11 12 void Start () { 13 14 m_rg = gameObject.GetComponent<Rigidbody2D>(); 15 16 } 17 18 // Update is called once per frame 19 void Update () { 20 //------------------Input.GetAxisRaw没有小数值,只有整数,不会产生缓动------------------ 21 //角色水平移动 22 //按住D键,判断如果大于0,则向右开始移动 23 if (Input.GetAxisRaw("Horizontal") > 0) 24 { 25 m_rg.velocity = new Vector2(MoveSpeed, m_rg.velocity.y); 26 27 //设置自身缩放的值 28 transform.localScale = new Vector2(1f,1f); 29 } 30 //角色水平移动 31 //按住A键,判断如果小于0,则向左开始移动 32 else if (Input.GetAxisRaw("Horizontal") < 0) 33 { 34 m_rg.velocity = new Vector2(-MoveSpeed, m_rg.velocity.y); 35 36 //如果new Vector2(-1f, 1f) x值为负数,则图片进行反转显示 37 transform.localScale = new Vector2(-1f, 1f); 38 } 39 else 40 //角色水平移动 41 //松开按键,判断如果等于0,则停止移动 42 { 43 m_rg.velocity = new Vector2(0, m_rg.velocity.y); 44 } 45 46 } 47}