Unity做2D小游戏5------多个动画互相转换
现在我们要实现多个动画的相互转换,这里有jump,run,idle和fall四个状态,分别创建动画资源,具体步骤在Unity做2D小游戏4------让角色动起来-CSDN博客有写,最后如下图所示。
在Animator中把上个练习的布尔类型删除,添加int类型state,因为布尔类型只能针对两个状态。
然后把状态摆好,右键状态”Make Transition”,添加桥梁,两两之间都有两条桥梁。
每条桥梁取消勾选Has Exit Time,Transition Duration改为0,这样动画衔接会更流畅,不会有延迟。
修改右下方的Conditions,只保留一个状态state,参数看下图设置,数字看文字。
指向Static静止状态-------0
指向Running奔跑状态----1
指向Jump跳跃状态--------2
指向Fall下落状态----------3
在角色脚本里面修改添加如下代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Playermovement : MonoBehaviour
{
private Rigidbody2D rb;
private BoxCollider2D coll;
private SpriteRenderer sprite;
private Animator anim;
[SerializeField] private LayerMask jumpableGround;
private float dirX = 0f;
[SerializeField] private float moveSpeed = 7f;
[SerializeField] private float jumpForce = 7f;
private enum MovementState { idle,running,jumping,falling }
// Start is called before the first frame update 第一次运行
private void Start()
{
rb=GetComponent<Rigidbody2D>();
coll = GetComponent<BoxCollider2D>();
sprite = GetComponent<SpriteRenderer>();
anim = GetComponent<Animator>();
}
// Update is called once per frame 反复运行
private void Update()
{
//水平方向速度
dirX = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(dirX * moveSpeed,rb.velocity.y);
if (Input.GetButtonDown("Jump") && IsGrounded())
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
}
UpdateAnimationState();
}
private void UpdateAnimationState()
{
MovementState state;
if (dirX > 0f)
{
state = MovementState.running;
sprite.flipX = false;
}
else if (dirX < 0f)
{
state = MovementState.running;
sprite.flipX = true;//反方向走,人物会翻转
}
else
{
state = MovementState.idle;
}
if (rb.velocity.y > .1f)
{
state = MovementState.jumping;
}
else if (rb.velocity.y < -.1f)
{
state = MovementState.falling;
}
anim.SetInteger("state", (int)state);
}
private bool IsGrounded()
{
return Physics2D.BoxCast(coll.bounds.center, coll.bounds.size, 0f ,Vector2.down, .1f ,jumpableGround);
}
}
在Layers里添加一个Ground层
然后点击左侧Tilemap文件,将右侧的Layer图层改为Ground.
点击Player文件,右侧脚本设置下的Jumpable Ground默认nothing改为Ground
现在,打开游戏就可以看到四个状态的动画转换了。
tips:这个时候,你是否发现角色在贴着墙壁的时候也可以走动,不会往下掉落。
如果你不喜欢这个设置,可以在Tilemap中添加一个组件Platform Effector 2D,并将Use one way勾选上,然后将Composite Collider 2D下的Used by Effector勾选上。