- Home /
How to make my enemy stop moving once dead?
I tried several ways, but it seems no matter what I try it doesn't work. He either sits still before he dies or the game object goes crazy and flys off screen.
using UnityEngine;
using System.Collections;
using SpriteFactory;
public class EnemyAi : MonoBehaviour {
public Transform target;
public int moveSpeed;
public int rotationSpeed;
public int maxDistance = 8;
private Sprite sprite;
public AudioClip swords;
public int life = 100;
public int points = 15;
private Transform myTransform;
IEnumerator Death() {
yield return new WaitForSeconds(0.8f);
Destroy(gameObject);
PointCounter.points += points;
}
void Awake() {
myTransform = transform;
sprite = (Sprite)GetComponent(typeof(Sprite));
}
void Start () {
GameObject go = GameObject.FindGameObjectWithTag("Player");
target = go.transform;
maxDistance = 8;
}
void FixedUpdate () {
if(Vector3.Distance(target.position, myTransform.position) > maxDistance) {
myTransform.position -= myTransform.right * moveSpeed * Time.deltaTime;{
sprite.Play ("EnemyWalk");
if (life <=0) {
sprite.Stop ();
}
}
}
}
//Health and damage rate when enemy is hit
void OnTriggerEnterSprite(SpriteCollider.CollisionData data) {
sprite.Play("hurt");
if(sprite.IsAnimationPlaying ("hurt")){
audio.Play();{
life += -100;
if (life <= 0) {
sprite.Play ("death");
StartCoroutine(Death());
}
}
}
}
}
To clarify, do you want the enemy to remain in the same position for 0.8 seconds after being killed, then to disappear?
Assu$$anonymous$$g that's the case, and taking a look at the code I will say this... If you don't want something to move after it has zero life, then don't move it after it has zero life. Try changing the if clause in FixedUpdate() to:
if(life > 0 && Vector3.Distance(target.position, myTransform.position) > maxDistance) {
What do I put after it? Should I set a new speed and max distance for it? The sprite.Stop(); part is to stop the walking animation and for it to switch to the death animation.
Did you try it as is? Obviously you would remove the "if (life
You play the death animation in OnTriggerEnterSprite. A 'stop' animation in addition to a 'death' animation seems redundant, do you really need both? If you need to play 'stop' then 'death' then chain the animations one after the other.
Answer by spiralfire11 · Nov 09, 2013 at 10:31 PM
Maybe using OnCollision would work since that's what I use; Unfortunetaly, that would mean if you would get touched by the enemy, you would die.
I want the Enemy itself to stop moving once I kill it. After I defeat it, it will move towards me if I move away for the amount of time the Coroutine lasts.
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Simple enemy kill count 1 Answer
Audio Issue, Plays with PlayOneShot but not Play 0 Answers
Enemy Spawn Script Spawning Infinite Enemies [Help] 2 Answers
Distribute terrain in zones 3 Answers