Follow an object script?

Hello. I am trying to make the enemies in my game follow the player. This is my script, but it is not working, what can be done to fix it? Thanks

function Update(){
transform.Translate(GameObject.FindWithTag("Player").transform.position; * 40);
more ▼

asked Jan 14, 2011 at 04:14 AM

Tyler 2 gravatar image

Tyler 2
1.1k 637 467 475

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

  1. You don't want to be searching by tag on a per-update basis if you can avoid it. Instead, grab a reference to the player game object or transform in Start() or Awake() and just use that.

  2. Your code has a syntax error in it, so it's not going to compile anyway. (As such, I'm not sure how you've determined whether it's working or not :)

  3. Translating by the player's position is unlikely to do anything meaningful.

There are several ways you can get one object to follow another. Here's one (untested):

Vector3 direction = player.position - transform.position;
transform.position += direction  speed  Time.deltaTime;

Note that this assumes the positions of the two objects will never be the same or nearly the same.

more ▼

answered Jan 14, 2011 at 04:40 AM

Jesse Anders gravatar image

Jesse Anders
7.7k 12 28 64

Thanks you for your help. I get an error telling me to put a semi-colon in between "Vector3" and "direction". When I do that, I get an error telling me that "statements must only be executed for their side-effects.".

Jan 14, 2011 at 06:46 AM Tyler 2

his code is in C# while urs is in JS. I suppose u just nid to declare var direction : Vector3 instead of Vector 3 direction. maybe that is the problem

Jan 14, 2011 at 07:27 AM Robindoo

Yes, I think the declaration of/assignment to the variable 'direction' will be the only thing you'd need to change in order for the code to work as UnityScript. (I think.)

Jan 14, 2011 at 04:47 PM Jesse Anders

would it be something like this (basic questions...I know)? var player : Transform; var direction : Vector3 = (player.position - transform.position);

Jan 14, 2011 at 10:58 PM Tyler 2

That's a little hard to follow. Maybe you could add the question as an edit to your post (or, since it seems this might end up requiring some discussion to get right, maybe just post a new thread to the forums).

Jan 14, 2011 at 11:27 PM Jesse Anders
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here



Answers and Comments



asked: Jan 14, 2011 at 04:14 AM

Seen: 3116 times

Last Updated: Jan 14, 2011 at 04:14 AM