Player.cs 2.2 KB

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