unity3d - How to make an enemy stop when he enter the required distance to shoot -
the problem have when enemy enters range shoot stops , never follows player again if player gets out of shooting range. detect if player entered shooting range have made sphere collider enemy.
using unityengine; using system.collections; public class enemywithriflemovement : monobehaviour { private gameobject player; private navmeshagent nav; private bool playerinrange = false; private rigidbody rb; void awake() { rb = getcomponent<rigidbody>(); player = gameobject.findgameobjectwithtag("player").gameobject; nav = getcomponent<navmeshagent>(); } void update() { if(playerinrange) { nav.setdestination(transform.position); } else if(playerinrange == false) nav.setdestination(player.transform.position); } void ontriggerenter(collider other) { if(other.gameobject.comparetag("player")) { playerinrange = true; } } void ontriggetexit(collider other) { if(other.gameobject.comparetag("player")) { playerinrange = false; } } }
your code looks fine, except there 1 typo. replace ontriggetexit
ontriggerexit
, , should work!
also, in opinion easier distance between enemy , player doing playerinrange = (vector3.distance(transform.position, player) <= range
.
Comments
Post a Comment