- Home /
Question by
lullaharsh · Dec 27, 2016 at 12:44 PM ·
cameratargetthird-person
Changing Free Look Camera Target At Runtime
Question says it all! Actually I spawn a character with UNET and I need to set him as a target on the camera after I spawn him. Thanks!
Comment
Answer by dustypantz · May 02, 2017 at 08:56 AM
public Transform Target { get { return m_Target; }}
No setter for Target property. Use "SetTarget(Transform newTransform)"
example: LocalCamera.GetComponent().SetTarget(transform);
Answer by tashfiq103 · Dec 18, 2019 at 09:17 AM
I hope the following code will solve the problem :)
using UnityEngine;
[RequireComponent(typeof(Camera))]
public class CameraLook : MonoBehaviour
{
#region Public Variable
//Setting : A default camera target, so it can look at something when the game is start
public Transform defaultCameraTarget;
[Space(5.0f)]
//Value : How fast your camera will follow the target
[Range(0f,1f)]
public float cameraAngulerVelocity = 0.05f;
#endregion
#region Private Variables
private Transform m_TransformReference;
//Reference : We are actually using another transform reference so that we can change the camera target in runtime.
private Transform m_CurrentCameraTarget;
//Note : What should be the rotational value to look at to the following target.
private Quaternion m_LookDirection;
//Note : Modified Rotational value based on your angulerVelocity
private Quaternion m_ModifiedRotation;
#endregion
private void Start()
{
m_TransformReference = transform;
m_CurrentCameraTarget = defaultCameraTarget;
}
private void LateUpdate()
{
//If : The current camera target is destroyed, it will switch back to the default one.
if (m_CurrentCameraTarget == null)
m_CurrentCameraTarget = defaultCameraTarget;
m_LookDirection = Quaternion.LookRotation(m_CurrentCameraTarget.position - m_TransformReference.position);
m_ModifiedRotation = Quaternion.Slerp(
m_TransformReference.rotation,
m_LookDirection,
cameraAngulerVelocity
);
m_TransformReference.rotation = m_ModifiedRotation;
}
/// <summary>
/// Call the function by passing the transform reference if you want to change the camera angle through runtime
/// </summary>
/// <param name="t_CameraTarget"></param>
public void ChangeCameraTarget(Transform t_CameraTarget) {
m_CurrentCameraTarget = t_CameraTarget;
}
}
Your answer
Follow this Question
Related Questions
Third Person Flight Camera HELP!! 1 Answer
Third Person Camera Help? 0 Answers
Camera and Target JS to CS converting 2 Answers
How can I mimic this game's camera in Unity? 1 Answer
Set Camera Target Error .. 0 Answers