PlayerController.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using Cinemachine;
  2. using DG.Tweening;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using UnityEngine;
  6. public class PlayerController : MonoBehaviour {
  7. private Rigidbody2D rb;
  8. private SpriteRenderer sprite;
  9. private BoxCollider2D coll;
  10. public LayerMask groundLayer;
  11. public Sprite spriteNormal, spriteDown;
  12. void Start() {
  13. rb = GetComponent<Rigidbody2D>();
  14. sprite = GetComponent<SpriteRenderer>();
  15. coll = GetComponent<BoxCollider2D>();
  16. }
  17. public string keyLeft = "a", keyRight = "d", keyJump = "w", keyDown = "s";
  18. public float movementSpeed = 10f, jumpForce = 20f, horizontalF = 0.9f, horizontalA = 0.3f, jumpThreshold = 0.1f, downA = 0.3f;
  19. public float jumpBufferTime = 0.2f, jumpWolfTime = 0.2f; private float jumpBuffer = 0f, jumpWolf = 0f, jumping = 0f;
  20. void Update() {
  21. // 获取当前情况
  22. float speedX = rb.velocity.x, speedY = rb.velocity.y;
  23. bool isDown = Input.GetKey(keyDown);
  24. bool isGround = Physics2D.OverlapCircle(transform.position, jumpThreshold, groundLayer);
  25. int moveHorizontal = isDown ? 0 : // 没有下蹲
  26. (Input.GetKey(keyLeft) == Input.GetKey(keyRight) ? 0 : // 没有同时按住左右
  27. (Input.GetKey(keyLeft) ? -1 : 1)); // 获取方向
  28. // 判断跳跃
  29. jumpBuffer -= Time.deltaTime; jumpWolf -= Time.deltaTime; jumping -= Time.deltaTime;
  30. if (Input.GetKey(keyJump)) jumpBuffer = jumpBufferTime;
  31. if (isGround) jumpWolf = jumpWolfTime;
  32. if (!isDown && jumpBuffer > 0 && jumpWolf > 0 && jumping < 0) { // 在地面、没有蹲下
  33. speedY = jumpForce;
  34. jumpBuffer = 0;
  35. jumping = 0.5f;
  36. } else if (isDown) {
  37. speedY -= downA;
  38. if (speedY > 0) speedY = 0;
  39. }
  40. // 横向移动
  41. if (moveHorizontal != 0) {
  42. speedX = speedX * (1 - horizontalA) + movementSpeed * horizontalA * moveHorizontal;
  43. }
  44. speedX *= horizontalF;
  45. // 蹲下
  46. if (isDown) {
  47. sprite.sprite = spriteDown;
  48. coll.size = new Vector2(coll.size.x, 0.5f);
  49. coll.offset = new Vector2(0, 0.35f);
  50. } else {
  51. sprite.sprite = spriteNormal;
  52. coll.size = new Vector2(coll.size.x, 1.2f);
  53. coll.offset = new Vector2(0, 0.7f);
  54. }
  55. // 设置
  56. rb.velocity = new Vector2(speedX, speedY);
  57. }
  58. }