一、创建精灵并添加刚体和碰撞体
?二、创建PlayerController脚本并编写
?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
//速度
public int speed;
//刚体
Rigidbody2D player;
//位置
Vector2 moveX;
void Start()
{
player = this.GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
Ider();
Run();
}
//等待
private void Ider()
{
moveX.x = Input.GetAxisRaw("Horizontal");
}
//跑步
private void Run()
{
if (moveX.x != 0)
{
//人物根据移动方向旋转
transform.localScale = new Vector3(moveX.x, 1, 1);
//MovePosition()方法:自身位置+moveX * Time.fixedDeltaTime * speed
player.MovePosition(player.position + moveX * Time.fixedDeltaTime * speed);
}
}
}
?三、把脚本挂在player上,运行脚本,控制player左右移动
|