Advertisement
MysteryGM

Unity_SwitchCameraBetweenTargets

May 5th, 2020
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.25 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class CameraMultiTarget : MonoBehaviour
  6. {
  7.     public GameObject TargetA;
  8.     public GameObject TargetB;
  9.  
  10.     GameObject ActiveTarget;
  11.     Vector3 StartOffset = Vector3.zero;
  12.  
  13.     void Start()
  14.     {
  15.         //Make Target A the first target
  16.         ActiveTarget = TargetA;
  17.         //When we start we grab the distance to the target as a vector
  18.         StartOffset = this.transform.position - ActiveTarget.transform.position;
  19.     }
  20.  
  21.     void Update()
  22.     {
  23.         //When we press a button it changes the target
  24.         if (Input.GetButtonUp("Fire2")))
  25.         {
  26.             //If target is A switch to B and return out of code, just switch to A if already B
  27.             if (ActiveTarget == TargetA)
  28.             {
  29.                 ActiveTarget = TargetB;
  30.                 return;
  31.             }
  32.             ActiveTarget = TargetA;
  33.         }
  34.  
  35.     }
  36.  
  37.     private void FixedUpdate()
  38.     {
  39.         //We make the camera follow the object during the physics step
  40.         this.transform.position = ActiveTarget.transform.position + StartOffset;
  41.         //Then we make the camera look at the target
  42.         this.transform.LookAt(ActiveTarget.transform);
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement