Player.cs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class Player : MonoBehaviour
  5. {
  6. [SerializeField] private float moveSpeed = 7f;
  7. private bool isWalking;
  8. private void Update()
  9. {
  10. Vector2 inputVector = new Vector2(0, 0);
  11. // getkey会一直返回true,而getkeydown只会在按下的一帧返回true
  12. if (Input.GetKey(KeyCode.W))
  13. {
  14. inputVector.y += 1;
  15. }
  16. if (Input.GetKey(KeyCode.S))
  17. {
  18. inputVector.y -= 1;
  19. }
  20. if (Input.GetKey(KeyCode.A))
  21. {
  22. inputVector.x -= 1;
  23. }
  24. if (Input.GetKey(KeyCode.D))
  25. {
  26. inputVector.x += 1;
  27. }
  28. inputVector = inputVector.normalized;
  29. Vector3 moveDir = new Vector3(inputVector.x, 0f, inputVector.y);
  30. transform.position += moveDir * Time.deltaTime * moveSpeed;
  31. isWalking = (inputVector != Vector2.zero);
  32. float rotateSpeed = 10f;
  33. transform.forward = Vector3.Slerp(transform.forward, moveDir, Time.deltaTime * rotateSpeed);
  34. }
  35. public bool IsWalking()
  36. {
  37. return isWalking;
  38. }
  39. }