Home > Software engineering >  Synchronize anim time with object rotation C# Unity
Synchronize anim time with object rotation C# Unity

Time:10-24

how can I set animation time considering the object rotation. Gameobject have limited rotation on Z axis from 0 to 32,8. And animation have 0,25 sec.

So I have to do something like this: when gameobject is on 0% Z = 0; animation time = 0 too. When gameobject is on 50% Z = 16,4; animation time = 0,125 so 50% too.

This is what I have, but it does not work:

 if(this.gameObject.transform.rotation.z <= 0)
    {
        animator.SetTrigger("Start");
        animator.speed = 1;
        animator.SetFloat("Time", 0);
    }
    else if(this.gameObject.transform.rotation.z > 0 && this.gameObject.transform.rotation.z <= 8.2f)
    {
        animator.SetFloat("Time", 0.0625f);
    }
    else if (this.gameObject.transform.rotation.z > 8.2f && this.gameObject.transform.rotation.z <= 16.4f)
    {
        animator.SetFloat("Time", 0.125f);
    }
    else if (this.gameObject.transform.rotation.z > 16.4f && this.gameObject.transform.rotation.z <= 24.6f)
    {
        animator.SetFloat("Time", 0.1875f);
    }
    else if (this.gameObject.transform.rotation.z > 24.6f && this.gameObject.transform.rotation.z <= 32.8f)
    {
       animator.SetFloat("Time", 0.25f);
    }

Any idea how to solve it?

CodePudding user response:

First of all you would not want to go through transform.rotation.z!

transform.rotation retuns a Quaternion (also see Wikipedia Quaternion) which has not three but four components x, y, z and w and they all move in ranges -1 to 1!

Also using the eulerAngles is not really reliable.

So I would

So it could look like e.g.

const float maxAngle = 38.5f;
const float maxTime = 0.25f;

var angle = Vector3.Angle(Vector3.up, transform.up);
// [optional] make sure angle is valid
angle = Mathf.Clamp(angle, 0, maxAngle);

var time = angle / maxAngle * (maxTime);
animator.SetFloat("Time", time);

CodePudding user response:

Yea thanks dude :D I did it like you with small changes and it works:

 public Animator anim;
private void Start()
{
    anim.speed = 0;   
}
private void Update()
{
    float angleZ = Mathf.Round(transform.eulerAngles.z * 100)/100;
    float maxAngle = 32.8f;
    float percentage = angleZ / maxAngle;
    anim.Play("Packa1", 0, percentage);
}
  • Related