- Home /
Play Animation and Stop Moving on Enemy Collision
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!!
float $$anonymous$$oveSpeed = 5f;
void OnCollisionEnter2D(Collision2D coll)
{
if (coll.gameObject.tag == "Enemy") {
$$anonymous$$oveSpeed = 0f;
GetComponent<Animation>().Play("RedGiantDEATHTOALL");
}
}
Answer by SolAZDev · Apr 18, 2016 at 07:14 AM
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.
you missed to ad }
after StartCoRoutine(WaitTo$$anonymous$$ove());
Sorry, I didn't write it on a Text Editor so I was prone to having an error or two. Try making the IEnumarator public, and ins$$anonymous$$d of return yield new, it's yield return new.
You are missing a } closing bracket for the Collission Checking.
read the error it tells you the problem : add using System.Collections;
to the top of the script & StartCoRoutine ($$anonymous$$oveToWait());
not WaitTo$$anonymous$$ove
For some reason more errors pop up when I fix the errors that show:
thees tow errors means you have miss typed some thing you can google any thing about unity to open unity documentation to cheek what you missed . & stop posting images just copy/pest your code with the error log . lastly for now here is the errors :
StartCoroutine
not uper R case for routine & WaitForSeconds
not double c for Seconds . see the doc : StartCoroutine
Thank you, and I will take your advice and put it in action.
Your answer
Follow this Question
Related Questions
Walking Animation 1 Answer
Play a video on clicking on an object 1 Answer
Automatically playing animations 1 Answer
Animation problem in script 0 Answers
Playing Animation When Two Keys Are Held Down To Play Run Animations 0 Answers