I have almost 10 gameobject and they would collision one by one.how can the camera target on A when A collision,and target on B when B collision,CDE…etc.
You can use the 2 scripts below to achieve what you want. You must attach the “Player” script to each GameObject that you want the camera to look at when it collides. You must attach the “CameraBehavior” script on the main camera, or another camera appropriately tagged.
Bear in mind that a single collision between two GameObjects, will result in both the two GameObjects asking the camera to look at them. However, they will be so close that even if the camera looks at each one in succession the effect will not be really noticeable. Nevertheless, you can improve the scripts, so that if a GameObject collides with another which has already called the camera’s CameraLookAt method, it will not itself call that method. Or something similar, depending on what you want.
using UnityEngine;
public class CameraBehavior : MonoBehaviour {
//// Use this for initialization
//void Start () {
//}
//// Update is called once per frame
//void Update () {
//}
public void CameraLookAt(Transform target)
{
transform.LookAt(target);
}
}
using UnityEngine;
public class Player : MonoBehaviour
{
private CameraBehavior cameraBehavior;
// Use this for initialization
void Start ()
{
//Get a reference the CameraBehavior component (skript) of the "Main Camera" GameObject (tagged "Main Camera" by default)
//If another camera is to be used, it must be tagged appropriately,
//and it's tag used below insteaed of "Main Camera"
cameraBehavior = GameObject.FindGameObjectWithTag("Main Camera").GetComponent<CameraBehavior>();
}
//// Update is called once per frame
//void Update () {
//}
void OnCollisionEnter(Collision collision)
{
//Pass the Transform of the current GameObject to the CameraLookAt method
cameraBehavior.CameraLookAt(transform);
}
}
Alternative script for smooth camera rotation:
using UnityEngine;
public class CameraBehavior : MonoBehaviour
{
public float RotationSpeed = 2f;
private Transform target; //set this every time there is a new target
private bool hasNewTarget;
private Vector3 relativePos;
private Quaternion targetRotation;
//// Use this for initialization
//void Start () {
//}
// Update is called once per frame
void Update()
{
if (hasNewTarget)
{
relativePos = target.position - transform.position;
targetRotation = Quaternion.LookRotation(relativePos);
}
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, RotationSpeed * Time.deltaTime);
}
public void CameraLookAt(Transform newTarget)
{
target = newTarget;
hasNewTarget = true;
}
}