Unity 3D Game Engine – JS – Camera – Swap Multi Cameras – On Click
1. Create in the Hierarchy
– CameraTarget1 (Empty object)
– CameraTarget2 (Empty object)
– Main Camera> attach ‘CameraControl.js’
CameraControl.js:
#pragma strict
// ########################################################################################
// This complete script can be attached to a camera to change his Position and his Target
// You will move the camera by clicking GUI.Button CAMERA 1 and GUI.Button CAMERA 2
// ########################################################################################
// The relative speed at which the camera will catch up
// Small value = more steps to reach the new position
public var smooth : float = 1.5f;
// Camera positions START ##################################################################
public var newPosCam1 : Vector3; // Camera Position 1
public var newPosCam2 : Vector3; // Camera Position 2
// Camera positions END ####################################################################
// Camera targets START ####################################################################
// The target variable shows up as a property in the inspector.
// Drag another object onto it to make the camera look at it.
var target1 : Transform;
var target2 : Transform;
// Camera targets END ######################################################################
function Start () {
}
function Update() {
}
// NOTICE: function OnGUI is outside others functions
// Move the Camera START ###################################################################
function OnGUI () {
// Button color and opacity setup START ################################################
// 0.0f rende il bottone completamente trasparente, il tocco funziona ugualmente
GUI.color = new Color(1,1,1,0.5f);
// Button color and opacity setup END ##################################################
// Insert 8 pixels of space between the 2 buttons.
GUILayout.Space (8);
if (GUI.Button (Rect (600,10,200,200), "CAMERA 1")) {
transform.position = Vector3.Lerp(transform.position, newPosCam1, smooth * Time.deltaTime);
transform.LookAt(target2);
}
if (GUI.Button (Rect (600,250,200,200), "CAMERA 2")) {
transform.position = Vector3.Lerp(transform.position, newPosCam2, smooth * Time.deltaTime);
transform.LookAt(target1);
}
}
// Move the Camera END #####################################################################
Main Camera> CameraControl.js:
– var Smoot: Small value = more steps to reach the new position
– New Pos Cam 1: first position of camera
– New Pos Cam 2: second position of camera
– Target 1: target of first position -> DRAG AND DROP from Hierarchy to Inspector CameraTarget1 (Empty object)
– Target 2: target of second position -> DRAG AND DROP from Hierarchy to Inspector CameraTarget2 (Empty object)