Player.cs 2.6 KB

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