在Unity游戏开发中,大多游戏的人物移动都是瞬间到达一个速度,如何想使人物像显示一样进行移动,就需要让人物的速度动态改变,目前有很多种方法,我接下分享一种运用加速度来使人物的速度动态改变。
private PlayerControls playercontrol;//新输入系统
private Vector2 movement;
private Rigidbody rb;
private Animator anim;
public int movespeed = 5;//移动最大速度
private float acceleration;//移动加速度
private float x;//人物移动的x轴坐标
private float y;//人物移动的y轴坐标
private Vector3 vector;
private void Start()
{
rb=GetComponentInChildren<Rigidbody>();
anim=GetComponentInChildren<Animator>();
acceleration=movespeed*Time.deltaTime;//计算加速度
}
public void OnEnable()//关联新输入系统
{
if (playercontrol == null)
{
playercontrol = new PlayerControls();
playercontrol.PlayerMovement.MovementActive.performed += outputActive => movement = outputActive.ReadValue<Vector2>();
//movementinput = inputAction.PlayerMovement.MovementActive.ReadValue<Vector2>();
}
playercontrol.Enable();
}
private void FixedUpdate()
{
animcontrol();
}
//movement.x>0代表着键盘按下A,movement.x>0代表键盘按下D。
public void animcontrol()
{
if ((movement.x > 0 && x <= movespeed )|| (movement.x == 0 && x < 0)) x += acceleration;
else if((movement.x < 0 && x>=movespeed*-1)||(movement.x==0&&x>0))x -= acceleration;
if (movement.x == 0 && (x>0&&x < 0.1||x>-0.1&&x<0)) x = 0;
//如果没有按下A和D键,那么x轴方向上没有加速度,当速度足够小时x变为0
if ((movement.y > 0 && y <=movespeed) || (movement.y == 0 && y < 0)) y += acceleration;
else if ((movement.y < 0 && y >= movespeed*-1) || (movement.y == 0 && y > 0)) y -= acceleration;
if (movement.y == 0 && (y>0&&y < 0.1 || y >= -0.1&&y<0)) y = 0;
vector = playertransform.right * x;
vector += playertransform.forward * y;
vector.y += rb.velocity.y;
rb.velocity = vector;
anim.SetFloat("veritical", x);
anim.SetFloat("horizontal", y);
float playerCamera = Camera.main.transform.rotation.eulerAngles.y;
playertransform.rotation = Quaternion.Slerp(playertransform.rotation, Quaternion.Euler(0, playerCamera, 0), turnSpeed);
}