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

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][1] I'm following. Any simplified script is appreciated [1]: https://www.youtube.com/watch?time_continue=2637&v=JL3i_QLSDxk

–

Thanks. I have the same problem as @Zefugi but replacing CurrentLayout-default.dwlt with yours didn't help it unfortunately. I also tried deleting Library folder. Unity rebuilts it but the problem persists.

–

Replacing the file worked for me. So how do I avoid getting the same error again later on?

–

1 Answer

1

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.

If replacing CurrentLayout-default.dwlt didn't work try using the unity LTS version.

–