- Home /
Moving enemy toward player.
Yeah, another from me, sorry. So I have a Wolf enemy patrolling around now and it will loop through the waypoints I have set for it, however I need it to be able to move toward either "bait" or the player when it see's on or the other. At the moment the wolf will bug out like crazy, where am I going wrong?
var sightDistance : float;
var waypoint : Transform[];
private var currentWaypoint : int = 0;
var player : Transform;
var bait : Transform;
var state : String ;
var speed : float;
var loop : boolean;
private var character : CharacterController;
function Awake()
{
character = GetComponent(CharacterController);
state = "natural";
}
function Update ()
{
var dir = transform.TransformDirection(Vector3.forward);
var hit : RaycastHit;
var path : Vector3 = waypoint[currentWaypoint].position;
var moveDirection : Vector3 = path - transform.position;
if (Physics.Raycast(transform.position, dir, hit, sightDistance))
{
// If we see Bait.
if (hit.collider.gameObject.tag == "Bait")
{
state = "baited";
}
// If we see the Player.
else if (hit.collider.gameObject.tag == "Player")
{
state = "hostile";
}
else if (hit.collider.gameObject.tag == "Cover")
{
//print ("I see Cover");
}
else
{
state = "natural";
}
}
if (state == "hostile")
{
path = player.position;
character.Move(moveDirection.normalized * speed * Time.deltaTime);
}
if (state == "natural")
{
if (currentWaypoint < waypoint.length)
{
if(moveDirection.magnitude < 1)
{
transform.position = path;
currentWaypoint = (currentWaypoint + 1) % waypoint.Length;
}
else
{
transform.LookAt(path);
character.Move(moveDirection.normalized * speed * Time.deltaTime);
}
}
else
{
if(loop)
{
currentWaypoint = 0;
}
}
}
}
Try replacing this:
if (state == "hostile")
{
path = player.position;
character.$$anonymous$$ove(moveDirection.normalized * speed * Time.deltaTime);
}
with this:
if (state == "hostile")
{
transform.LookAt(player.position);
transform.position += transform.forward * speed * Time.deltaTime;
}
$$anonymous$$oves toward the player now, however it kind of moves to me and walks straight past me to continue on the patrol.
Also, the wolf seems to instantly teleport to me and fly up into the air.
Your answer
Follow this Question
Related Questions
How can I move the character like 2D games? 1 Answer
Move the enemy object opposite to player and keep its distance relative to the player? 1 Answer
Tweaking character movement 1 Answer
EnemyHover Script Error? 0 Answers
is there any better way to move the character than rigidbody.addRelativeForce? 1 Answer