Getting an enemy to move towards you ?

Can anyone offer a relatively simple script to make an enemy move towards a FPS player.

thanks

found this on the forum, I tested with 2 cubes on a plane and it works but I couldn’t figure out how to slow down the movement of the cube to the enemy cube … it’s instantaneous when in range (obviously from the code)
I added the ‘else’ statement that displays the distance for debugging purposes

var enemy : Transform; 

function Update() 

{ 
    if ( Vector3.Distance( enemy.position, transform.position ) < 500 ) 
	
	
	{ 
        print("player is close"); 
      transform.position = enemy.transform.position; 
      transform.rotation = enemy.transform.rotation ;
       
    } 
	else
       {
	print("not close yet");
	print(Vector3.Distance( enemy.position, transform.position ));
       }
}

Got this working but it happens in 1 second, how do I slow it down ???

var enemy : Transform; 
var start: Transform;
var end: Transform;

function Update() 

{ 
   

if (  Vector3.Distance( enemy.position, (Vector3.Lerp(start.position, end.position,Time.time) )) < 100  ) 
	
	
	{ 
       print("player is close"); 
       transform.position = enemy.transform.position; 
       transform.rotation = enemy.transform.rotation ;
       
	  transform.position = Vector3.Lerp(start.position, end.position, Time.deltaTime  );
	   
    } 
	else
	{
	print("not close yet");
	print(Vector3.Distance( enemy.position, transform.position ));
	}
}

[/code]

var enemy : Transform; 
var speed: float;

function Update() 
{ 
if (  Vector3.Distance( enemy.position, transform.position) < 100  ) 
	{ 
       print("player is close"); 
      
	  transform.position = (enemy.position - transform.position ).normalized * speed * Time.deltaTime;
    } 
	else
	{
	print("not close yet");
	print(Vector3.Distance( enemy.position, transform.position ));
	}
}

Thanks Bren, I’ll try it later.

EDIT:

It didn’t seem to work, the player cube just disappears

I guess you’ve checked out the Lerpz tutorial?

It’s a while since I did it but there are handy enemy scripts there that may provide some useful info.

Speed will be in m/s, so it should be a relatively small number, depending on your scale. Start with 1 and see how that goes.

Try this one, by putting it on an enemy object.

Make sure the player is tagged Player.

It ain’t pretty, but it’s tested and works for me.

var player : GameObject; 
var speed : float = 1; 

function Start () 
{ 
     player = GameObject.FindGameObjectWithTag("Player"); 

     if (!player) 
          Debug.Log ("ERROR could not find Player!"); 
} 

function Update() 
{ 
     if (!player) 
          return; 

     var distance = Vector3.Distance( player.transform.position, transform.position);

     if ( distance < 100  ) 
     { 
          Debug.Log ("player is close"); 
          
          var delta = player.transform.position - transform.position;
          delta.Normalize();
          
          var moveSpeed = speed * Time.deltaTime;
      
          transform.position = transform.position + (delta * moveSpeed);
    } 
    else 
    { 
          Debug.Log("not close yet " + distance); 
    } 
}

okey just give the emeny this script and take the first person player to target

var speed = 3.0;
var rotationSpeed = 5.0;
var shootRange = 15.0;
var attackRange = 30.0;
var shootAngle = 4.0;
var dontComeCloserRange = 5.0;
var delayShootTime = 0.35;
var pickNextWaypointDistance = 2.0;
var target : Transform;

private var lastShot = -10.0;

// Make sure there is always a character controller
@script RequireComponent (CharacterController)

function Start () {
	// Auto setup player as target through tags
	if (target == null  GameObject.FindWithTag("Player"))
		target = GameObject.FindWithTag("Player").transform;

	Patrol();
}

function Patrol () {
	var curWayPoint = AutoWayPoint.FindClosest(transform.position);
	while (true) {
		var waypointPosition = curWayPoint.transform.position;
		// Are we close to a waypoint? -> pick the next one!
		if (Vector3.Distance(waypointPosition, transform.position) < pickNextWaypointDistance)
			curWayPoint = PickNextWaypoint (curWayPoint);

		// Attack the player and wait until
		// - player is killed
		// - player is out of sight		
		if (CanSeeTarget ())
			yield StartCoroutine("AttackPlayer");
		
		// Move towards our target
		MoveTowards(waypointPosition);
		
		yield;
	}
}


function CanSeeTarget () : boolean {
	if (Vector3.Distance(transform.position, target.position) > attackRange)
		return false;
		
	var hit : RaycastHit;
	if (Physics.Linecast (transform.position, target.position, hit))
		return hit.transform == target;

	return false;
}

function Shoot () {
	// Start shoot animation
	animation.CrossFade("shoot", 0.3);

	// Wait until half the animation has played
	yield WaitForSeconds(delayShootTime);
	
	// Fire gun
	BroadcastMessage("Fire");
	
	// Wait for the rest of the animation to finish
	yield WaitForSeconds(animation["shoot"].length - delayShootTime);
}

function AttackPlayer () {
	var lastVisiblePlayerPosition = target.position;
	while (true) {
		if (CanSeeTarget ()) {
			// Target is dead - stop hunting
			if (target == null)
				return;

			// Target is too far away - give up	
			var distance = Vector3.Distance(transform.position, target.position);
			if (distance > shootRange * 3)
				return;
			
			lastVisiblePlayerPosition = target.position;
			if (distance > dontComeCloserRange)
				MoveTowards (lastVisiblePlayerPosition);
			else
				RotateTowards(lastVisiblePlayerPosition);

			var forward = transform.TransformDirection(Vector3.forward);
			var targetDirection = lastVisiblePlayerPosition - transform.position;
			targetDirection.y = 0;

			var angle = Vector3.Angle(targetDirection, forward);

			// Start shooting if close and play is in sight
			if (distance < shootRange  angle < shootAngle)
				yield StartCoroutine("Shoot");
		} else {
			yield StartCoroutine("SearchPlayer", lastVisiblePlayerPosition);
			// Player not visible anymore - stop attacking
			if (!CanSeeTarget ())
				return;
		}

		yield;
	}
}

function SearchPlayer (position : Vector3) {
	// Run towards the player but after 3 seconds timeout and go back to Patroling
	var timeout = 3.0;
	while (timeout > 0.0) {
		MoveTowards(position);

		// We found the player
		if (CanSeeTarget ())
			return;

		timeout -= Time.deltaTime;
		yield;
	}
}

function RotateTowards (position : Vector3) {
	SendMessage("SetSpeed", 0.0);
	
	var direction = position - transform.position;
	direction.y = 0;
	if (direction.magnitude < 0.1)
		return;
	
	// Rotate towards the target
	transform.rotation = Quaternion.Slerp (transform.rotation, Quaternion.LookRotation(direction), rotationSpeed * Time.deltaTime);
	transform.eulerAngles = Vector3(0, transform.eulerAngles.y, 0);
}

function MoveTowards (position : Vector3) {
	var direction = position - transform.position;
	direction.y = 0;
	if (direction.magnitude < 0.5) {
		SendMessage("SetSpeed", 0.0);
		return;
	}
	
	// Rotate towards the target
	transform.rotation = Quaternion.Slerp (transform.rotation, Quaternion.LookRotation(direction), rotationSpeed * Time.deltaTime);
	transform.eulerAngles = Vector3(0, transform.eulerAngles.y, 0);

	// Modify speed so we slow down when we are not facing the target
	var forward = transform.TransformDirection(Vector3.forward);
	var speedModifier = Vector3.Dot(forward, direction.normalized);
	speedModifier = Mathf.Clamp01(speedModifier);

	// Move the character
	direction = forward * speed * speedModifier;
	GetComponent (CharacterController).SimpleMove(direction);
	
	SendMessage("SetSpeed", speed * speedModifier, SendMessageOptions.DontRequireReceiver);
}

function PickNextWaypoint (currentWaypoint : AutoWayPoint) {
	// We want to find the waypoint where the character has to turn the least

	// The direction in which we are walking
	var forward = transform.TransformDirection(Vector3.forward);

	// The closer two vectors, the larger the dot product will be.
	var best = currentWaypoint;
	var bestDot = -10.0;
	for (var cur : AutoWayPoint in currentWaypoint.connected) {
		var direction = Vector3.Normalize(cur.transform.position - transform.position);
		var dot = Vector3.Dot(direction, forward);
		if (dot > bestDot  cur != currentWaypoint) {
			bestDot = dot;
			best = cur;
		}
	}
	
	return best;
}

i snap it from FPS tutorial

Thanks Bren, got it going !

It turns out that I had a massive scale, I actually had to use 50 with your code.

How do you set your scale ??? What reference do you use when starting a new scene ?

Mr Shaw, you’re script uses waypoints. I havn’t looked at them yet but thanks anyway.

I tried to add the below script to my enemy object and get this error

Assets/Standard Assets/Scripts/enemy.js(171,19): BCE0018: The name ‘AutoWayPoint’ does not denote a valid type.

not sure what that is…
the enemy toon has character controller on it as well as its animations.
is this a .js or .cs file as well…

thanks

to trinitysj:

in the fps tutorial, the enemy robot things have waypoints that they automatically move to whenever the player is not around. in order to use their a.i. you also have to import the “auto way point” script. just attach it to an empty game object to create a way point, and the robot will work.

thank you bren! this works and really helps with my game! one thing to keep in mind, my cube doesent rotateto face the player! help?

your script works great bren, Wat i need is I have to rotate the enemy to look at my Player.

var Player : Transform;

function Update()
{
transform.LookAt(Player);

}

nice!

hi Bren , this code is related to distance how can we change it to visibilty.
i want enemies start following when they see “player” and stop moving when sight is gone till hitting a wall.
also i expect enemies to move only X or only Z axis.

You need a function like this:

function IsVisible(object : Transform){
	var hits : RaycastHit[];
	var ray : Ray = new Ray (transform.position, transform.position-object.position);
	
	hits = Physics.RaycastAll (ray, Vector3.Distance(transform.position, object.position));
	
	for (var i = 0;i < hits.Length; i++) {
		var hit : RaycastHit = hits[i];
		var obj : Transform = hit.collider.transform;
		// is the object anything but this or the one we are searching for
		if (obj != transform   obj != object) return false;
		// is the object the one we are searching for?
		if (obj == object) return true;
	}
	// this should never happen...
	return true;
}

(Bren, it’s 2013 now… you posted this in 2009)

Thank you.
Your script is exactly what I’ve been looking for…

(1) find the delta between Object and Player
(2) normalize that delta
(3) add normalized delta to Objects’ new transform.

You are a godsend - thank you again.

Sincerely,
kropcke

(hope you get this)

Scratch that, it’s now 2014! Also, my first post. Better late than never.

I came across this thread whilst looking into a simple way of implementing it and this is the gold. In fact, this is pretty much how I’d thought it would be implemented which is encouraging, because this is my first full project using Unity. Anyway, enough of the babbling; I use C# so I have converted it to C# (Not much to change at all) and added the LookAt player feature simply for convenience :slight_smile:

	private GameObject player;
	public float speed = 1.0f;

	// Use this for initialization
	void Start () {
	
		player = GameObject.FindGameObjectWithTag ("Player");

		if (!player) {
			Debug.Log ("ERROR could not find Player!"); 
		}
	}
	
	// Update is called once per frame
	void Update () {

		if (!player) {
			return;
		}

		var distance = Vector3.Distance( player.transform.position, transform.position);

		if ( distance < 100  ) 	
		{ 	
			Debug.Log ("player is close"); 
			var delta = player.transform.position - transform.position;
			delta.Normalize();
			var moveSpeed = speed * Time.deltaTime;
			transform.position = transform.position + (delta * moveSpeed);
			transform.LookAt(player.transform);
		} 

		else 	
		{ 
			Debug.Log("not close yet " + distance); 
		}