- Home /
How can I make my enemy stay on the ground and collide with other objects?
In my script the enemy chases the player until it is close enough to attack, but they enemy doesn't stay on the ground and flies through walls. How can I make it obey gravity? here's my code:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class EnemyChase : MonoBehaviour {
public Transform Player;
public int MoveSpeed = 4;
public int MinDist = 5;
public int MaxDist = 10;
public Slider healthBarSlider;
bool attack;
void Update() {
//squares up
transform.LookAt(Player);
//chases player
if (Vector3.Distance (transform.position, Player.position) <= MaxDist) {
transform.position += transform.forward * MoveSpeed * Time.deltaTime;
//stops doing damage
attack = false;
Debug.Log ("get over here and fight like a man!");
//stops and attacks when close enough to player
if(Vector3.Distance(transform.position,Player.position) <= MinDist) {
Debug.Log ("PEWEWPEWEPWEWPEPWP");
//starts doing damage
attack = true;
}
}
//applies damage to player
if (attack) {
healthBarSlider.value -= 0.005f;
} else if (healthBarSlider.value == 0) {
//die
} else {
healthBarSlider.value += 0.0f;
}
}
}
Answer by alemimi · Jan 03, 2015 at 02:49 PM
Did you add Collider components to every wall, ground and enemy? And in order for the enemy to "stop" when colliding with something, i think it needs to have a "Rigidbody" component attached to it, try and see if that works.
should i check if its grounded, and if not add force or somethin?
For checking colliding enemy or not use tag or gameobject name for apply force or changes velocity !!! Rigidbody needed.
Answer by Jabeebus · Apr 08, 2016 at 06:38 AM
One way to make it stay is to add a Rigidbody to it and enable gravity