Player.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class Player : MonoBehaviour
  5. {
  6. public float startSpeed = 5f;
  7. public float lookSmoothingSeconds = 0.05f;
  8. public float cameraSmoothingSeconds = 1;
  9. public float bulletUpBias = 0.1f;
  10. public float bulletForce = 10f;
  11. public float powerLevel;
  12. public Transform gunTransform;
  13. public Rigidbody bulletPrefab;
  14. public Light muzzleLight;
  15. private Vector3 inputDirection;
  16. private float speed;
  17. private Vector3 lookDirection;
  18. private float deadZone = 0.1f;
  19. private Vector3 lookVelocity;
  20. private Vector3 cameraOffset;
  21. private Vector3 cameraVelocity;
  22. private bool shooting = false;
  23. private float lightIntensity;
  24. // Use this for initialization
  25. void Start ()
  26. {
  27. speed = startSpeed;
  28. cameraOffset = Camera.main.transform.position - transform.position;
  29. lightIntensity = muzzleLight.intensity;
  30. }
  31. // Update is called once per frame
  32. void Update ()
  33. {
  34. // TODO lerp movement direction
  35. GetInput();
  36. if (lookDirection.magnitude > deadZone)
  37. transform.forward = Vector3.SmoothDamp(transform.forward, lookDirection, ref lookVelocity, lookSmoothingSeconds);
  38. transform.position += inputDirection * speed * Time.deltaTime;
  39. Camera.main.transform.position = Vector3.SmoothDamp(Camera.main.transform.localPosition, TargetCameraPosition(), ref cameraVelocity, cameraSmoothingSeconds);
  40. if (shooting)
  41. {
  42. if (Time.frameCount % 2 == 0)
  43. {
  44. muzzleLight.intensity = 0;
  45. }
  46. else
  47. {
  48. muzzleLight.intensity = Random.Range(.5f,2f) * lightIntensity;
  49. }
  50. Shoot();
  51. }
  52. else
  53. {
  54. muzzleLight.intensity = 0;
  55. }
  56. }
  57. private void Shoot()
  58. {
  59. var rb = Instantiate<Rigidbody>(bulletPrefab);
  60. rb.transform.position = gunTransform.position;
  61. rb.transform.forward = gunTransform.forward;
  62. rb.AddForce(bulletForce * (transform.forward + Vector3.up * bulletUpBias), ForceMode.VelocityChange);
  63. Destroy(rb.gameObject, 2f);
  64. }
  65. private Vector3 TargetCameraPosition()
  66. {
  67. return transform.position + cameraOffset;
  68. }
  69. void GetInput()
  70. {
  71. shooting = Input.GetButton("Fire1");
  72. lookDirection = new Vector3(
  73. Input.GetAxis("LookX"),
  74. 0,
  75. -Input.GetAxis("LookY")
  76. ).normalized;
  77. inputDirection = new Vector3(
  78. Input.GetAxis("Horizontal"),
  79. 0,
  80. Input.GetAxis("Vertical")
  81. ).normalized;
  82. }
  83. }