PlayerMovement.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using UnityEngine;
  2. public class PlayerMovement : MonoBehaviour
  3. {
  4. public static PlayerMovement instance;
  5. public float speed = 0;
  6. Vector3 movement;
  7. Animator anim;
  8. Rigidbody playerRigidbody;
  9. int floorMask;
  10. float camRayLength = 100f;
  11. public Vector3 GetMousePoint { get; set; }
  12. void Awake()
  13. {
  14. floorMask = LayerMask.GetMask("Floor");
  15. anim = GetComponent<Animator>();
  16. playerRigidbody = GetComponent<Rigidbody>();
  17. instance = this;
  18. }
  19. void FixedUpdate()
  20. {
  21. float h = Input.GetAxis("Horizontal");
  22. float v = Input.GetAxis("Vertical");
  23. Move(h, v);
  24. Turning();
  25. Animating(h, v);
  26. }
  27. void Move(float h,float v)
  28. {
  29. movement.Set(h, 0, v);
  30. movement = movement.normalized * speed * Time.deltaTime;
  31. playerRigidbody.MovePosition(transform.position + movement);
  32. }
  33. void Turning()
  34. {
  35. Ray camRay = Camera.main.ScreenPointToRay(Input.mousePosition);
  36. RaycastHit floorHit;
  37. if(Physics.Raycast(camRay,out floorHit, camRayLength, floorMask))
  38. {
  39. Vector3 playerToMouse = floorHit.point - transform.position;
  40. GetMousePoint = playerToMouse;
  41. playerToMouse.y = 0f;
  42. Quaternion newRotation = Quaternion.LookRotation(playerToMouse);
  43. playerRigidbody.MoveRotation(newRotation);
  44. }
  45. Debug.DrawRay(Camera.main.transform.position, floorHit.point, Color.red);
  46. Debug.DrawLine(Camera.main.transform.position, floorHit.point, Color.red);
  47. }
  48. void Animating(float h,float v)
  49. {
  50. bool walking = h != 0f || v != 0f;
  51. anim.SetBool("IsWalking", walking);
  52. }
  53. }