Reply To: Camera Issue from Game World Chapter
Home › Forums › Books › Mastering Unity 2D Game Development › Camera Issue from Game World Chapter › Reply To: Camera Issue from Game World Chapter
May 18, 2016 at 4:44 am
#9641
Guest
Sorry…the formatting is horrid…lets try the code again…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 |
using UnityEngine; using System.Collections;   public class FollowCamera : MonoBehaviour {   // Distance in the x & y axes the player can move before the camera follows public float xMargin = 1.5f; public float yMargin = 1.5f;   // How smoothly the camera catches up with the target public float xSmooth = 1.5f; public float ySmooth = 1.5f;   // The min & max x & y coordinates the camera can travel public Vector2 minXandY; public Vector2 maxXandY;   // Reference to the player's transform public Transform player;   void Awake() { // Setting up the reference player = GameObject.Find("Player").transform;   if (player == null) { Debug.LogError ("Player object not found"); } }   bool CheckXMargin() { // Returns true if the distance between the camera and the player in the x axis // is greater than the x margin return Mathf.Abs(transform.position.x - player.position.x) > xMargin; } bool CheckYMargin() { // Returns true if the distance between the camera and the player in the x axis // is greater than the x margin return Mathf.Abs(transform.position.y - player.position.y) > yMargin; }   void FixedUpdate() { // By default, target x and y coordinates of the camera float targetX = transform.position.x; float targetY = transform.position.y;   // If the player has moved beyond the x margin... if (CheckXMargin ()) { // The target x coord. should be a Lerp between the camera's x and player's x targetX = Mathf.Lerp(transform.position.x, player.position.x, xSmooth * Time.fixedDeltaTime); } // If the player has moved beyond the y margin... if (CheckYMargin ()) { // The target y coord. should be a Lerp between the camera's y and player's y targetY = Mathf.Lerp(transform.position.y, player.position.y, ySmooth * Time.fixedDeltaTime); } // The target x & y coords should not b larger than max or small than min targetX = Mathf.Clamp(targetX, minXandY.x, maxXandY.x); targetY = Mathf.Clamp(targetY, minXandY.y, maxXandY.y);   // After all that error checking crap...set the camera's position with the same z component transform.position = new Vector3(targetX, targetY, transform.position.z); }   } |
-
This reply was modified 4 years, 7 months ago by
Simon (darkside) Jackson.