BallUserControl.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System;
  2. using UnityEngine;
  3. using UnityStandardAssets.CrossPlatformInput;
  4. namespace UnityStandardAssets.Vehicles.Ball
  5. {
  6. public class BallUserControl : MonoBehaviour
  7. {
  8. private Ball ball; // Reference to the ball controller.
  9. private Vector3 move;
  10. // the world-relative desired move direction, calculated from the camForward and user input.
  11. private Transform cam; // A reference to the main camera in the scenes transform
  12. private Vector3 camForward; // The current forward direction of the camera
  13. private bool jump; // whether the jump button is currently pressed
  14. private void Awake()
  15. {
  16. // Set up the reference.
  17. ball = GetComponent<Ball>();
  18. // get the transform of the main camera
  19. if (Camera.main != null)
  20. {
  21. cam = Camera.main.transform;
  22. }
  23. else
  24. {
  25. Debug.LogWarning(
  26. "Warning: no main camera found. Ball needs a Camera tagged \"MainCamera\", for camera-relative controls.");
  27. // we use world-relative controls in this case, which may not be what the user wants, but hey, we warned them!
  28. }
  29. }
  30. private void Update()
  31. {
  32. // Get the axis and jump input.
  33. float h = CrossPlatformInputManager.GetAxis("Horizontal");
  34. float v = CrossPlatformInputManager.GetAxis("Vertical");
  35. jump = CrossPlatformInputManager.GetButton("Jump");
  36. // calculate move direction
  37. if (cam != null)
  38. {
  39. // calculate camera relative direction to move:
  40. camForward = Vector3.Scale(cam.forward, new Vector3(1, 0, 1)).normalized;
  41. move = (v*camForward + h*cam.right).normalized;
  42. }
  43. else
  44. {
  45. // we use world-relative directions in the case of no main camera
  46. move = (v*Vector3.forward + h*Vector3.right).normalized;
  47. }
  48. }
  49. private void FixedUpdate()
  50. {
  51. // Call the Move function of the ball controller
  52. ball.Move(move, jump);
  53. jump = false;
  54. }
  55. }
  56. }