多态和动画
建立player-idle动画,取玩家最后两个图片
选中playcontroller控制器
将玩家动画拖进去
右键player-idle,选择set as layer Default state
右键点击Any State ,点击Make Transition
结果
动画参数
动画参数是动画控制器定义的变量,点击Parameters,再选择Int
重命名为Animator
点击Any到player-walk-east动画状态的白色的线,再在Inspector面板设置属性如下,Has Exit Time 如果不取消,动画会播放到Exite Time文本指定的百分比位置,才会播放下一个动画。
点击Conditions下的加号
设置如下
修改MovementController脚本
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using UnityEngine;
public class MovementController : MonoBehaviour
{
// Start is called before the first frame update
public float movementSpeed = 3.0f;
Vector2 movement = new Vector2();
//用来存储Animator的引用
Animator animator;
string animationState = "AnimationState";
Rigidbody2D rb2D;
enum CharStates
{
walkEast=1,
walkWest=3,
walkSouth=2,
walkNorth=4,
idleSouth=5
}
void Start()
{
//获取GameObject中Animator组件的引用
animator = GetComponent<Animator>();
rb2D = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
UpdateState();
}
//unity引擎以固定时间调用
private void FixedUpdate()
{
MoveCharacter();
}
//玩家移到代码
private void MoveCharacter()
{
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = Input.GetAxisRaw("Vertical");
movement.Normalize();
rb2D.velocity = movement * movementSpeed;
}
//更新动画状态机
private void UpdateState()
{
if (movement.x > 0)
{
//告诉animator 将状态进行转换,第一个是unity编辑器创建的动画参数AnimationState,另外一个是AnimationState的实际值
animator.SetInteger(animationState, (int)CharStates.walkEast);
}
else if (movement.x < 0)
{
animator.SetInteger(animationState, (int)CharStates.walkWest);
}
else if (movement.y > 0)
{
animator.SetInteger(animationState, (int)CharStates.walkNorth);
}
else if (movement.y < 0)
{
animator.SetInteger(animationState, (int)CharStates.walkSouth);
}
else {
animator.SetInteger(animationState, (int)CharStates.idleSouth);
}
}
}
修改每个白色转换箭头,Conditions的值按照枚举的来设置
将每个player-walk动画速度设置为0.6
点击播放,即可通过W,A,D,S移到玩家