A bit of context first, I’m making a game where the main camera is fixed at a position and it will look at different game objects depending on the input of the player. In this scene I have 3 game objects and the player would input either A and D to transition the camera perspective to the object on the left or right.
I managed to create a smooth transition based on a answer from the unity forums (https://forum.unity.com/threads/transform-lookat-smooth-transition-instead-of-instant-snapping.522119/) and I was able to achieve the smooth transition I wanted. However I face a problem now: the function to do the rotation keeps getting called in the update function.
Heres the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraBehaviour : MonoBehaviour
{
// Start is called before the first frame update
Vector3 targetDirection;
private Transform targetObject = null;
private float speed;
private float distance;
void Start()
{
speed = 5f;
targetObject = null;
distance = 0;
}
// Update is called once per frame
void Update()
{
if(targetObject != null)
{
SmoothTransition();
Debug.Log("SmoothTransition() is being called");
checkIfDone();
}
}
public void TransitionTo(Transform targetObject)
{
this.targetObject = targetObject;
distance = Vector3.Distance(targetObject.position, transform.position);
}
private void SmoothTransition()
{
Vector3 targetDir = targetObject.position - transform.position;
targetDir.y = 0;
float step = speed * Time.deltaTime;
Vector3 newDirection = Vector3.RotateTowards(transform.forward, targetDir, step, 0.0f);
transform.rotation = Quaternion.LookRotation(newDirection);
}
private void checkIfDone()
{
RaycastHit hit;
Debug.DrawRay(transform.position, transform.forward, Color.red);
if (Physics.Raycast(transform.position, transform.forward, out hit, distance))
{
Debug.Log(transform.gameObject.name + "is hit");
if (hit.transform.Equals(targetObject))
{
targetObject = null;
Debug.Log("TargetObject has been nullified");
}
}
}
}
The function keeps getting called because of the condition in the update function. My reason for putting that condition is to make sure the function won’t be called all the time and would optimize the game. In order to make the condition false, there would be a function that would use raycasting to check if the camera is already looking at the targetObject. If it is already looking at the targetObject, then targetObject would be null.
However it seems that the targetObject is not nulled out when i tested the code. My question is how do I correctly make sure that that the camera is looking at the targetObject?