twinStick/twinStickCrawler/Assets/Scripts/Creatures/Animate.cs

86 lines
2.6 KiB
C#
Raw Normal View History

using System;
using System.Collections;
using System.Collections.Generic;
2024-12-19 11:36:55 +00:00
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.SceneManagement;
public class AnimationObject
{
public readonly String name;
public readonly float value;
public readonly Coroutine coroutine;
public AnimationObject(String name, float value, Coroutine coroutine)
{
this.name = name;
this.value = value;
this.coroutine = coroutine;
}
}
2024-12-19 11:36:55 +00:00
public class Animate : MonoBehaviour
{
2024-12-20 14:21:20 +00:00
private Animator _animator;
public void initialize(Animator animator)
{
_animator = animator;
}
List<AnimationObject> animations = new List<AnimationObject>();
2024-12-19 11:36:55 +00:00
2024-12-20 14:21:20 +00:00
public void AnimateState(string animVar, float animVal, float animationSpeed)
{
float t = Mathf.Clamp01(animationSpeed*Time.deltaTime);
2024-12-20 14:21:20 +00:00
float newVal = Mathf.Lerp(_animator.GetFloat(animVar), animVal, t);
_animator.SetFloat(animVar, newVal);
//animator.Play("Attack");
2024-12-20 14:21:20 +00:00
//print(animator.GetCurrentAnimatorStateInfo(1).IsName("Idle"));
}
public void TriggerAnimation(string triggerName)
{
_animator.SetTrigger(triggerName);
}
2024-12-19 11:36:55 +00:00
/*public void AnimateState(Animator animator, string animVar, float animVal, float animationSpeed)
{
AnimationObject animationObject = animations.Find(item => item.name == animVar);
if (animationObject != null && !Mathf.Approximately(animationObject.value, animVal))
{
StopAnimation(animationObject);
}
StartAnimation(animator, animVar, animVal, animationSpeed);
}*/
void StartAnimation(Animator animator, string animVar, float animVal, float animationSpeed)
2024-12-19 11:36:55 +00:00
{
Coroutine coroutine = StartCoroutine(AnimateCoroutine(animator, animVar, animVal, animationSpeed));
animations.Add(new AnimationObject(animVar, animVal, coroutine));
}
void StopAnimation(AnimationObject animationObject)
{
if (animationObject.coroutine != null)
{
StopCoroutine(animationObject.coroutine);
}
animations.Remove(animationObject);
2024-12-19 11:36:55 +00:00
}
IEnumerator AnimateCoroutine(Animator animator, string animVar, float animVal, float animationSpeed)
2024-12-19 11:36:55 +00:00
{
float t = 0f;
float beginningVal = animator.GetFloat(animVar);
2024-12-19 11:36:55 +00:00
while (!Mathf.Approximately(animator.GetFloat(animVar), animVal))
{
animator.SetFloat(animVar, Mathf.Lerp(beginningVal, animVal, t));
t+= Mathf.Clamp(animationSpeed * Time.deltaTime, -1f, 1f);
yield return null;
}
2024-12-19 11:36:55 +00:00
}
}