Hi everyone, I am making a 2d Infinite Runner, and I am having a struggle to figure out how to play an animation AND stop moving on enemy collision. Here is my script:
using System;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace UnityStandardAssets._2D
{
public class Restarter : MonoBehaviour
{
void OnCollisionEnter2D(Collision2D coll)
{
if (coll.gameObject.tag == "Enemy") {
GetComponent<Animation>().Play("RedGiantDEATHTOALL");
}
}
}
}
Thank you for your help!!
The animation seems alright. But to have the movement stop, I’d have a bool and a coroutine, the Bool will allow the player to move, while the coroutine holds the bool to until the animation plays. Something like this:
bool CanMove = true;
bool MoveWait=false;
void OnCollissionEnter2D(Collision col1){
if(col1.gameObject.tag=="Enemy"){
GetComponent<Animation>().Play("RedGiantDEATHTOALL");
CanMove=false;
if(!MoveWait)
StartCoRoutine(WaitToMove());
}
IEnumerator MoveToWait(){
MoveWait=true;
return yield new WaitForSecconds(1.5f); //Change to Animation Duration
MoveWait=false;
CanMove=true;
}
Of course, you’ll have to return the MoveDirections to zero, or just check if CanMove is true while checking for keypress.