PlayerMovePhysics.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using System;
  2. using UnityEngine;
  3. using UnityEngine.Events;
  4. public class PlayerMovePhysics : MonoBehaviour
  5. {
  6. public float speed = 5;
  7. public bool worldDirection = true;
  8. public bool rotatePlayer = true;
  9. public Action spaceAction;
  10. public Action enterAction;
  11. Rigidbody rb;
  12. void Start()
  13. {
  14. rb = GetComponent<Rigidbody> ();
  15. }
  16. private void OnEnable()
  17. {
  18. transform.position += new Vector3(10, 0, 0);
  19. }
  20. void FixedUpdate()
  21. {
  22. Vector3 input = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
  23. //input = Vector3.forward;
  24. if (input.magnitude > 0)
  25. {
  26. Vector3 fwd = worldDirection
  27. ? Vector3.forward : transform.position - Camera.main.transform.position;
  28. fwd.y = 0;
  29. fwd = fwd.normalized;
  30. if (fwd.magnitude > 0.001f)
  31. {
  32. Quaternion inputFrame = Quaternion.LookRotation(fwd, Vector3.up);
  33. input = inputFrame * input;
  34. if (input.magnitude > 0.001f)
  35. {
  36. rb.AddForce(speed * input);
  37. if (rotatePlayer)
  38. transform.rotation = Quaternion.LookRotation(input.normalized, Vector3.up);
  39. }
  40. }
  41. }
  42. if (Input.GetKeyDown(KeyCode.Space) && spaceAction != null)
  43. spaceAction();
  44. if (Input.GetKeyDown(KeyCode.Return) && enterAction != null)
  45. enterAction();
  46. }
  47. }