Part9:Wall Slide State(P36)
1:效果和操作
效果:碰到墙体减速下滑
操作:给墙体添加材质,使其摩擦系数改小,防止人物卡在墙体上,定义WallSlide参数和PlayerWallSlide动画
实现:当人物处于airstate时,若人物与墙体IsWallDetected为true,则转化为slide状态
2:代码改变
//新增PlayerWallSlideState
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerWallSlideState : PlayerState//墙体下滑状态
{
public PlayerWallSlideState(Player _player, PlayerStateMachine _stateMachine, string _animBoolName) : base(_player, _stateMachine, _animBoolName)
{
}
public override void Enter()
{
base.Enter();
}
public override void Exit()
{
base.Exit();
}
public override void Update()
{
base.Update();
if(xInput!= 0&&player.facingDir!=xInput)//输入方向和人物朝向不一致则无法slide
{
stateMachine.ChangeState(player.idleState);
}
if(player.IsGroundDetected())//接触地面则取消slide转为idle
{
stateMachine.ChangeState(player.idleState);
}
if (yInput < 0)//若按下往下则按照正常落体速度
rb.velocity = new Vector2(0,rb.velocity.y);
else//若往上或者0则减速营造在墙体划下效果
rb.velocity = new Vector2(0, rb.velocity.y * .7f);
}
}
//Player新增代码
public PlayerWallSlideState wallSlide { get; private set; }
private void Awake()
{
wallSlide = new PlayerWallSlideState(this, stateMachine, "WallSlide");
}
public bool IsWallDetected()//墙体检测
{
return Physics2D.Raycast(wallCheck.position, Vector2.right*facingDir, wallCheckDistance, whatIsGround);
}
//注:PlayerState新增yInput=Input.GetAxisRaw("Vectical");
//PlayerAirState代码改变
public override void Update()
{
base.Update();
if(xInput != 0)
{
player.SetVelocity(player.moveSpeed* 0.8f * xInput, rb.velocity.y);
}
if(player.IsWallDetected())//在空中碰墙时切换为滑墙状态
{
stateMachine.ChangeState(player.wallSlide);
}
}
3:效果图(图片编号60-62)