用Rigidbody2D来实现(用Unity中刚体属性来改变rigidbody2D中velocity速度来实现移动)
1.申明属性,创建速度和x的移动
Rigidbody2D rb = new Rigidbody2D();
public float PlayerSpeed = 5f;
private float moveX;
2.在start()中导入Rigidbody2D组件
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
3.读入键盘,并实现任务移动+任务移动翻转
(有GetAxisRaw和GetAxis两个版本)
A.GetAxisRaw版本是[-1,0,1],而且按一次移动一次
private void Move()
{
moveX = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(moveX * PlayerSpeed, rb.velocity.y);
//翻转
if(moveX != 0)
{
transform.localScale = new Vector3(moveX, 1, 1);
}
}
B.GetAxis版本是[-1~1],相对于GetAxisRaw来说更加丝滑,它不能用GetAxisRaw的方法翻转
定义一个面朝右
private bool facingRight = true;//面朝右
在move中做一个判断,当面朝右,而输入小于0或者面朝左,输入大于0两种情况进行翻转
private void Move()
{
moveX = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(moveX * PlayerSpeed, rb.velocity.y);
if(facingRight == false && moveX > 0)
{
Flip();
}
else if(facingRight == true && moveX < 0)
{
Flip();
}
}
再写一个翻转函数
private void Flip()
{
facingRight = !facingRight;
Vector3 PlayerScale = transform.localScale;
PlayerScale.x *= -1;
transform.localScale = PlayerScale;
}