I’m having a bit of trouble with this code for my animation. What I am trying to do is get my character to teleport. I have an animation that starts the teleportation and one that ends the teleportation that activates on a trigger. I’ve figured out how to get these to play but I haven’t been able to move the distance at the right time. It takes about 2 seconds for my character to completely disappear. Right now when I press the key they move instantly but I want them to wait 2 seconds after the key is pressed to move. I was wondering if there was a couple of lines of code that would tell the animation to play after the 2 seconds have passed. Here is the code I have:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TeleportCharacterAnim : MonoBehaviour
{
public Animator animator;
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.LeftShift))
{
animator.SetTrigger("TP");
float distance = 2;
transform.position = new Vector2(transform.position.x + distance, transform.position.y);
}
}
}
“Teleport_T100_TP_Start” is the 2 second long animation I want to play before the movement. “Teleport-Code” is a few frames of my character completely invisible. “Teleport_T100_TP_End” is my character coming out of the animations and returning to their Idle.
Additionally My character only moves in one direction when you press the button. Is there any way to get them to teleport in he direction they are facing?
Problem 1: getting it to happen at the right time:
Solution 1a: You can cheese this by simply starting a coroutine with a hard-wired delay equivalent to the animation time, THEN do line 16 above, rather than doing it instantaneously.
Solution 1b: you could implement animation events and do the movement in there. More moving parts but then if you make the animation longer/shorter, it magically works, as long as you move the animation event
Problem 2: teleporting based on facing direction.
Solution 2: based on the whatever you are using to know facing direction, decide the destination position!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TeleportCharacterAnim : MonoBehaviour
{
public Animator animator;
void Start ()
{
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.LeftShift))
{
animator.SetTrigger("TP");
}
if (animator.GetCurrentAnimatorStateInfo(0).IsName("Teleport-Code"))
{
animator.ResetTrigger("TP");
float distance = 1;
transform.position = new Vector2(transform.position.x + distance, transform.position.y);
}
}
}