- Home /
Problem with objects colliding and IsSleeping (C#)
So I have a problem with one of my exploding enemies. The enemy first moves to a position that is set through an array, when it reaches the position the enemy will stay still and I use an if statement and ask "if the enemy == is sleeping". If it is a timer will start to countdown, when it reaches 0 the enemy explodes!
Now the problem is that there are other enemies that collide with the enemy when it is stationary, this makes the timer stutter since enemy is not "sleeping", since moves a little bit every time an object touches it!
What is the best way to solve this problem? I still want collision on the enemy even when it is stationary, but how could I make it so that the enemy is still stationary even though an object collides with it?
Here's the code:
using UnityEngine;
using System.Collections;
public class EnemyExplodeScript : MonoBehaviour {
//private Transform target;
public Transform[] moveToPoints;
//public GameObject explodingEnemy;
public Transform explodingEnemyTransform;
int movePoint = 0;
public float speed;
public float explodeTimer = 3.0f;
public Rigidbody2D enemyMove;
void Start ()
{
//Find the which points the enemy should follow in the array
moveToPoints[0] = GameObject.Find("MoveRightUp").transform;
moveToPoints[1] = GameObject.Find("MoveLeftDown").transform;
moveToPoints[2] = GameObject.Find("MoveRightDown").transform;
moveToPoints[3] = GameObject.Find("MoveRightUp").transform;
moveToPoints[4] = GameObject.Find("MoveMiddle").transform;
//Set where the enemy should go with the array
movePoint = Random.Range(0, moveToPoints.Length);
}
void Update ()
{
// Speed and time
float step = speed * Time.deltaTime;
//Get the enemy moving
transform.Translate (Vector3.MoveTowards (transform.position, moveToPoints[movePoint].position, step) - transform.position);
//**Check if the enemy is stationary**
if(enemyMove.IsSleeping())
{
//Start timer
explodeTimer -= Time.deltaTime;
}
//After 3 seconds destroy object
if(explodeTimer <= 0.0f)
{
//ExplosionSpawnEnemy();
Destroy(gameObject);
}
}
Answer by Ankush186 · Apr 25, 2016 at 12:11 PM
Add a new Layer Enemy assign that layer to each enemy. then in Edit>Project Settings > Physics > Layer Collision Matrix turn off the Collision of Enemy with Enemy
But won't that just ignore the collision? I still want the collision to work with other objects, but so that the enemy doesn't move when it is stationary
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Why is my Rigidbody2D not moving? (C#) 1 Answer
Objects not colliding twice 0 Answers
Issue with adding force and lerping position? Possible unity bug? 0 Answers
Multiple Cars not working 1 Answer