- Home /
How to implement lock on with a camera that is not a child of the player object?
I'm trying to implement a lock-on system, so that when the player gets close to an enemy, the camera will focus on the enemy, while still keeping the player within view. Kind of like the Dark Souls lock on. Here is my script unaltered. Some of my attempts have been trying to use RotateAround or trying to use the vector between the player and the enemy as the position to use transform.LookAt() on. The object I'm trying to put focus on is the "enemy" GameObject.
using UnityEngine;
using System.Collections;
public class ThirdPersonCamera : MonoBehaviour
{
public Transform lookAt;
public Transform startPos;
enum cameraType {Inverse=-1, noInverse = 1};
private const float Y_ANGLE_MIN = 15.0f;
private const float Y_ANGLE_MAX = 50.0f;
private float distance = 10.0f;
private float distanceAbove = 5.0f;
private float currentX = 0.0f;
private float currentY = 0.0f;
private float sensivityX = 4.0f;
private float sensivityY = 1.0f;
private float afkTimer = 0.0f;
private float afkMaxTime = 10.0f;
private int isInverse = (int)cameraType.noInverse;
public GameObject enemy;
private void Start()
{
}
private void Update()
{
currentX += Input.GetAxis ("Mouse X") * sensivityX;
currentY += Input.GetAxis ("Mouse Y") * isInverse * sensivityY;
currentY = Mathf.Clamp (currentY, Y_ANGLE_MIN, Y_ANGLE_MAX);
}
private void LateUpdate()
{
if (Input.GetAxis("Mouse X") == 0 && Input.GetAxis("Mouse Y") == 0)
{
if (afkTimer >= afkMaxTime)
transform.position = Vector3.MoveTowards(transform.position, startPos.position, 0.1f);
else
afkTimer += Time.deltaTime;
}
else
{
afkTimer = 0;
}
if (afkTimer < afkMaxTime)
{
Quaternion rotation = Quaternion.Euler(currentY, currentX, 0);
Vector3 dir = new Vector3(0, 0, -distance);
transform.position = Vector3.Slerp(transform.position, lookAt.position + rotation * dir, 0.08f);
}
transform.LookAt(lookAt.position + new Vector3(0, distanceAbove, 0));
}
}
Answer by DidaFM · Apr 19, 2019 at 05:21 PM
Did you manage to make this work? I have the same question and would like to find the answer.
I toyed with it a bit but never really got to an answer. However, I have a friend who I think knows how to do this. I'm going to ask him and get back to you.