角色动画
1.新建动画目录
- 新建Animations文件夹,用来保存动画
- 在Animations文件夹下,新建Player文件夹,保存Player的动画
2.创建时间轴动画窗口
3.新建站立动画Player_Idle
创建
制作帧动画
4.跑动动画Player_Run
帧动画
5.跳跃动画Player_Jump
6.过度动画
站立和跑动切换
新建float型参数moveSpeed
Idle---->Run
Run---->Idle
站立和跳跃切换
新建bool型参数isGrounded
Idle---->Jump
Jump---->Idle
跑动切换跳跃
Run---->Jump
7.角色翻转
向左移动时,角色面向左边
private SpriteRenderer theSR; //用于实现角色向左移动时翻转
获取组件
theSR = GetComponent<SpriteRenderer>();
根据x速度,判断设置翻转
//翻转
if (theRB.velocity.x < 0)
{
theSR.flipX = true;
}
else if (theRB.velocity.x > 0)
{
theSR.flipX = false;
}
8.PlayerController.cs代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float moveSpeed; //移动速度
public Rigidbody2D theRB; //刚体
public float jumpForce; //跳跃力量
private bool isGrounded; //是否在地面
public Transform groundCheckPoint; //地面检测点
public LayerMask whatIsGround; //地面层级
//连跳
private bool canDoubleJump; //是否能连跳
//动画
private Animator anim; //动画主体
private SpriteRenderer theSR; //用于实现角色向左移动时翻转
// Start is called before the first frame update
void Start()
{
//获取组件形式
anim = GetComponent<Animator>();
theSR = GetComponent<SpriteRenderer>();
}
// Update is called once per frame
void Update()
{
//设置速度 /*GetAxisRaw*/
theRB.velocity = new Vector2(moveSpeed * Input.GetAxis("Horizontal"), theRB.velocity.y);
//检测是否在地面 参数:圆形中心,圆形半径,筛选器(用于检查仅在指定层上的对象)
isGrounded = Physics2D.OverlapCircle(groundCheckPoint.position, .2f, whatIsGround);
if (isGrounded)
{
//在地面时,可以连跳为true
canDoubleJump = true;
}
//跳跃
if (Input.GetButtonDown("Jump"))
{
if(isGrounded) //判断是否在地面
{
theRB.velocity = new Vector2(theRB.velocity.x, jumpForce);
}
else
{
if(canDoubleJump)
{
//不在地面,连跳
theRB.velocity = new Vector2(theRB.velocity.x, jumpForce);
canDoubleJump = false;
}
}
}
//翻转
if (theRB.velocity.x < 0)
{
theSR.flipX = true;
}
else if (theRB.velocity.x > 0)
{
theSR.flipX = false;
}
//设置动画中设置的moveSpeed,isGrounded的值
anim.SetFloat("moveSpeed", Mathf.Abs(theRB.velocity.x));
anim.SetBool("isGrounded", isGrounded);
}
}