这个案例实现的动作并不复杂,主要包含一个 跳跃动作、攻击动作、还有一个包含三个动画状态的动画混合树。然后设置三个参数来控制切换。
状态机结构如下:
完整代码
cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GirlAnimacON : MonoBehaviour
{
AudioSource OneAudioSour;
public AudioClip RunVoiceClip;
public AudioClip JumpVoiceClip;
public AudioClip AttackVoiceClip;
// 这个脚本实现控制角色动画播放以及声音播放
Animator GirlsAnimator;
float SpeedGirlsMove;
bool TunMove=false;
int TunMo = 0;
void Start()
{
OneAudioSour = this.GetComponent<AudioSource>();
GirlsAnimator = this.GetComponent<Animator>();
//游戏初始化
GirlsAnimator.SetBool("MoveBlend", false);
GirlsAnimator.SetBool("Jump", false);
GirlsAnimator.SetBool("Attack", false);
TunMove = false;
SpeedGirlsMove = 0f;
}
void Update()
{
ControllAnima();
}
/// <summary>
/// 控制Player动画
/// </summary>
void ControllAnima()
{
if (Input.GetKey(KeyCode.W))
{
TunMove = false;//开关
TunMo = 0;//开关
// 开始移动动画的播放
GirlsAnimator.SetBool("MoveBlend", true);
SpeedGirlsMove += 0.1f;
SpeedGirlsMove = Mathf.Clamp(SpeedGirlsMove, 0f, 20f);//限制最大最小数值
}
//else if (!Input.GetKey(KeyCode.W))
//{
// SpeedGirlsMove -= 0.1f;
// SpeedGirlsMove = Mathf.Clamp(SpeedGirlsMove, 0f, 20f);//限制最大最小数值
//}
//--------------------------------
if (Input.GetKeyUp(KeyCode.W))
{//只执行一次
TunMove = true;
TunMo = 1;
}
if (TunMove)
{
SpeedGirlsMove -= 0.1f;
SpeedGirlsMove = Mathf.Clamp(SpeedGirlsMove, 0f, 20f);//限制最大最小数值
}
GirlsAnimator.SetFloat("MoveSpeed", SpeedGirlsMove);
//------------------------------------------------控制其他动画-----------------------
if (GirlsAnimator.GetCurrentAnimatorStateInfo(0).IsName("MoveBlend"))
{
GirlsAnimator.SetBool("MoveBlend", false);
}
//------------------------------------------------控制其他动画-----------------------
if (Input.GetKeyDown(KeyCode.Space))
{
// 开始跳跃动画的播放
GirlsAnimator.SetBool("Jump", true);
OneAudioSour.clip = AttackVoiceClip;//修改默认声音片段到组件中
OneAudioSour.Play();//播放声音
}
if (GirlsAnimator.GetCurrentAnimatorStateInfo(0).IsName("JUMP"))
{
GirlsAnimator.SetBool("Jump", false);
}
//------------------------------------------------控制gongji动画-----------------------
if (Input.GetMouseButtonDown(0))
{
// 开始攻击动画的播放
GirlsAnimator.SetBool("Attack", true);
OneAudioSour.clip = AttackVoiceClip;
OneAudioSour.Play();
//OneAudioSour.PlayOneShot(AttackVoiceClip);
}
if (GirlsAnimator.GetCurrentAnimatorStateInfo(0).IsName("Attack"))
{
GirlsAnimator.SetBool("Attack", false);
}
//------------------------------------------------控制其他动画-----------------------
}
public void PlayRunVoice1()
{
Debug.Log("跑步动画播到15帧了!开始播放跑步声音");
OneAudioSour.clip = RunVoiceClip;
OneAudioSour.Play();
}
public void PlayRunVoice2()
{
OneAudioSour.clip = RunVoiceClip;
OneAudioSour.Play();
Debug.Log("跑步动画播到30帧了!开始播放跑步声音");
}
}