How to make the player object lock on to another object?

I’ve been inspired by Breath of the Wild to make my game have a similar “lock on” feature. I understand that I need to try and make the player object face the object I’m locked on to, but I have no idea how to write the code for it.

I also want to disable the rotation I already have in the code when I’m locked on, since it will probably mess up the lock on rotation.

Here’s my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player1Controller : MonoBehaviour {

	public float moveSpeed;

	void Start ()
	{
		moveSpeed = 10f;
	}

	void Update ()
	{
		float moveHorizontal = Input.GetAxisRaw ("Horizontal");
		float moveVertical = Input.GetAxisRaw ("Vertical");

		Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
		transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(movement), 0.15F);

		transform.Translate (movement * moveSpeed * Time.deltaTime, Space.World);
	}
}

My player object is a simple rectangle. I’ve frozen the X and Z rotations in the rigidbody component.

Also I have another little question that I’m guessing has a quick fix. When I move my player object around, it faces the direction I want it to move, but the direction snaps back to 0 when it stops moving. How do I fix this?

Thanks for your time.

@m4koren

This might work for you.

There’s a transform.LookAt(Vector3) method, which will basically make the object look at a specific point in space, which could be the enemy’s location.

I’d implement it like this in your Update function:

if (lockedOn) // However you are going to control and check this
{
    // This will make the forward (z-axis) of your object point at the enemy
    transform.LookAt(enemy.transform.position);
}
else
{
    // Whatever code you use to control your object's rotation otherwise
}

And I think probably the problem with your code above is that your rotation is dependent on the movement vector, so when you stop moving, your movement vector is Vector3(0.0f, 0.0f, 0.0f) and your object will Slerp its way over to there. You can probably put a bit of logic around the transform.rotation line, to only apply when you are actually moving.