Friday, January 25, 2013

Velocity Based Camera Leading

I've been working on this game in my free time with a few friends. An early build of it can be found on my 'Projects' page. I'm the Lead (well the only) Programmer on the team and one of the things we wanted was a dynamic camera that smoothly followed the player instead of just snapping to his position. So I got the camera to follow the player after a slight delay which looked nice except in certain situations (see image below).

After that I thought of different ways to add more functionality to the camera to better show the player's surroundings. The best way that I thought of was to have the camera boost it's position in a certain direction based on the direction that the player was traveling.



Check out the code

  1. //Script by Devin Curry
  2. //www.Devination.com
  3. using UnityEngine;
  4. using System.Collections;
  5.  
  6. public class CameraFollow : MonoBehaviour
  7. {
  8. private Transform player = null;
  9. public float cameraLag = 0.3f;
  10. //needed for Vector3 SmoothDamp
  11. private Vector3 velocity = Vector3.zero;
  12. //buckets for holding camera and player postions
  13. private float cameraZ = 0.0f;
  14. private Vector3 newCameraPos;
  15. private Vector3 playerv3;
  16. //used for boosting the camera based on player's velocity
  17. public float boostY = 1.0f; //stored value for camera lead distance
  18. private float boostedY = 0.0f; //fluctuates, uses boostY as multiplier with player's velocity
  19. void Start()
  20. {
  21. //finds the player's transform component
  22. player = GameObject.FindGameObjectWithTag("Player").transform;
  23.  
  24. cameraZ = this.transform.position.z; //caches initial camera z position
  25. }
  26. void Update ()
  27. {
  28. playerv3 = player.transform.position; //finds player's current position
  29. //checks the player's current velocity
  30. Debug.Log(player.rigidbody.velocity);
  31. //sets a dead zone to not affect the camera
  32. if(player.rigidbody.velocity.y <= -1.5)
  33. {
  34. //takes the y component of the players velocity and uses it to boost the camera in the direction we want
  35. boostedY = player.rigidbody.velocity.normalized.y * boostY;
  36. }
  37. else if(player.rigidbody.velocity.y > -1.5)
  38. {
  39. //if the player is not moving, camera will boost itself up by the default amount
  40. boostedY = boostY;
  41. }
  42. //appends camera's Z position to player's X and Y positions
  43. newCameraPos = new Vector3 (playerv3.x, (playerv3.y) + boostedY, cameraZ);
  44. //assigns new position to camera with a slight camera lag
  45. this.transform.position = Vector3.SmoothDamp(this.transform.position, newCameraPos, ref velocity, cameraLag);
  46. }
  47. }