- Home /
Make an enemy follows and point towards player
I got this code, but it doesn't work properly.
using UnityEngine;
using System.Collections;
[AddComponentMenu("Playground/Movement/Follow Target")]
public class FollowTarget : Physics2DObject
{
// This is the target the object is going to move towards
public Transform target;
// Speed used to move towards the target
public float speed = 1f;
// The direction that will face the target
public Enums.Directions useSide = Enums.Directions.Up;
// FixedUpdate is called once per frame
void FixedUpdate ()
{
//Move towards the target
rigidbody2D.MovePosition(Vector2.Lerp(transform.position, target.position, Time.fixedDeltaTime * speed));
//look towards the target
Utils.SetAxisTowards(useSide, transform, target.position - transform.position);
}
}
Any help will be apreciated
I am guessing you got this code from somewhere, as some of the stuff implemented in it is more advanced (enums, inheritance, menucomponents). The presence of those means it is hard to say what your problem is since we do not have the whole picture. Do you have Enums.Directions somewhere? Do you have Physics2DObject class to inherit from? Is Utils.SetAxisTowards defined somewhere? This looks like code that works fine in the context it was created. $$anonymous$$y guess is you are trying to use one script you found out of context. I can't be certain without more information though, sorry. There are plenty of more simplified "move enemy to target" type scripts available. I would use something else.
It isn't out of context since it's part of a game I've found on Internet. There's the code and sprites and you just need to put all togheter.
Some parts os the code give problems, and this in the unique I can't solve on my own.
For instance, there's the tutorial I'm following.
Any simplified script is appreciated
Answer by Happeloy · May 10, 2018 at 07:48 PM
We need more information here. In what way isn't it working?
The Utils.SetAxisTowards() method is not part of UnityEngine namespace, so we can't know what it does. Same thing goes for the Enums.Direction, even though that one is pretty self explanatory.
Anyways, getting one game object to look at another is pretty straight forward, just use
transform.LookAt(otherTransform);
This will make the forward axis of the current gameobject point towards the other gameobject.
Your answer
Follow this Question
Related Questions
make object move in the same direction it faceing 1 Answer
Rotate within range 1 Answer
How to make a object move right automatically in 2d. 2 Answers
Looking at target in 2D 1 Answer