【Unity】控制人物左右移动和跑步的实现

作者 : admin 本文共1762个字,预计阅读时间需要5分钟 发布时间: 2024-06-11 共1人阅读

通过判断shift按下和左右键按下进行移动角色,设置跑步和走路速度。

//字面意思的状态
enum playerGroundStateEnum
{
stand = 0,
walk = 1,
run = 2
}
public class PlayerController : MonoBehaviour
{
public float playerSpeed = 5f;
//走路移动速度
public float walkSpeed = 5f;
//跑步移动速度
public float runningSpeed = 8f;
private bool _isFacingRight=true;
private bool isFacingRight
{
get
{
return _isFacingRight;
}
set
{
//如果当前方向与新赋值的方向不一致则转向
if (_isFacingRight != value)
{
transform.localScale *= new Vector2(-1, 1);
}
_isFacingRight = value;
}
}
private Rigidbody2D body;
private Vector2 inputControll;
private bool isWalking;
private bool isShitfDonw;
public int playerGroundState
{
get
{
return anim.GetInteger(AnimationString.GroundState);
}
set
{
anim.SetInteger(AnimationString.GroundState, value);
}
}
Animator anim;
// Start is called before the first frame update
void Start()
{
}
private void Awake()
{
body = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
}
private void FixedUpdate()
{
body.velocity = new Vector2(inputControll.x * playerSpeed, body.velocity.y);
if (isWalking)
{
if (isShitfDonw)
{
setPlayerRuning();
}
else
{
setPlayerWalk();
}
}
else
{
setPlayerStand();
}
}
private void setPlayerWalk()
{
playerSpeed = walkSpeed;
playerGroundState = (int)playerGroundStateEnum.walk;
}
private void setPlayerStand()
{
playerSpeed = walkSpeed;
playerGroundState = (int)playerGroundStateEnum.stand;
}
private void setPlayerRuning()
{
playerSpeed = runningSpeed;
playerGroundState = (int)playerGroundStateEnum.run;
}
//给角色绑定的移动事件
public void onMove(InputAction.CallbackContext context)
{
inputControll = context.ReadValue<Vector2>();
isWalking = inputControll != Vector2.zero;
if (inputControll.x > 0 && !isFacingRight)
{
isFacingRight = true;
}
else if (inputControll.x < 0 && isFacingRight)
{
isFacingRight = false;
}
}
//给角色绑定的左Left事件
public void onRun(InputAction.CallbackContext context)
{
if (context.started)
{
isShitfDonw = true;
}
else if (context.canceled)
{
isShitfDonw = false;
}
}
}
本站无任何商业行为
个人在线分享 » 【Unity】控制人物左右移动和跑步的实现
E-->