Hello guys. I am trying to rotate my camera around the main character until the nearest enemy is centered in the view. My main problem is trying to accomplish this while maintining the same offset to the player at all times. I’m trying to replicate the focus mode from zelda, for honor etc etc.
Here is the code that controls my camera. You can find the code that handles the focus mode in the last function named targetMode()
using UnityEngine;
// * -CameraController-
// Handles all camera movement, performed by the main camera.
// *
public class CameraController : MonoBehaviour
{
public GameObject target; // GameObject that we wish to follow
public float angularSpeed;
public Vector3 initialOffset;
public Vector3 currentOffset;
private bool targetmode = false;
private void Start()
{
if (target == null)
{
Debug.LogError("Assign a target for the camera in Unity's inspector");
}
currentOffset = initialOffset;
}
private void LateUpdate()
{
transform.position = target.transform.position + currentOffset; // set the current camera position
float movement = Input.GetAxis("RightJoystickX") * angularSpeed * Time.deltaTime; // get the movement of the left joystick.
if (!Mathf.Approximately(movement, 0f) && !targetmode)
{
transform.RotateAround(target.transform.position, Vector3.up, movement); // rotate around the target (player) while the left joystick is being held
currentOffset = transform.position - target.transform.position; // keep the same offset at all times
}
float leftTrigger = Input.GetAxis("LeftTrigger");
if (leftTrigger > 0.70f) // if the left trigger is (fully) pressed go into focus mode and focus on the nearest enemy
{
// target mode
targetmode = true;
targetMode();
}else
{
targetmode = false;
}
}
private void targetMode()
{
// target the nearest enemy, if the user presses the target trigger again, go out of target mode
// if the user uses the right analog stick find the nearest target in that direction and target it
GameObject targetfound = null;
foreach (Character character in GameController.control.Characters) // each current character (players or enemies) is stored in this global array
{
if (targetfound != null)
{
// find the nearest enemy by finding the distance from each object
if (Vector3.Distance(character.Gobject.transform.position, target.transform.position) < Vector3.Distance(targetfound.transform.position, target.transform.position) && targetfound.gameObject != target)
{
targetfound = character.Gobject;
}
}
else if(character.Gobject != target)
{
targetfound = character.Gobject;
}
}
// the nearest target has been found. Focus on it.
transform.RotateAround(target.transform.position, Vector3.up, Vector3.Distance(target.transform.position, targetfound.transform.position));
currentOffset = transform.position - target.transform.position;
}
}