PlayerController.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. public LayerMask groundLayer;
  9. void Start() {
  10. rb = GetComponent<Rigidbody2D>();
  11. }
  12. public string keyLeft = "a", keyRight = "d", keyJump = "w", keyDown = "s";
  13. public float movementSpeed = 10f, jumpForce = 20f, horizontalF = 0.9f, horizontalA = 0.3f, jumpThreshold = 0.1f, jumpDetectHeight = 0.8f;
  14. public float jumpBufferTime = 0.2f, jumpWolfTime = 0.2f; private float jumpBuffer = 0f, jumpWolf = 0f;
  15. void FixedUpdate() {
  16. // 获取当前情况
  17. float speedX = rb.velocity.x, speedY = rb.velocity.y;
  18. bool isGround = Physics2D.OverlapCircle(transform.position - new Vector3(0, jumpDetectHeight, 0), jumpThreshold, groundLayer);
  19. bool isDown = Input.GetKey(keyDown) && isGround;
  20. int moveHorizontal = isDown ? 0 : // 没有下蹲
  21. (Input.GetKey(keyLeft) == Input.GetKey(keyRight) ? 0 : // 没有同时按住左右
  22. (Input.GetKey(keyLeft) ? -1 : 1)); // 获取方向
  23. // 判断跳跃
  24. jumpBuffer -= Time.fixedDeltaTime;
  25. if (Input.GetKeyDown(keyJump)) jumpBuffer = jumpBufferTime;
  26. jumpWolf -= Time.fixedDeltaTime;
  27. if (isGround) jumpWolf = jumpWolfTime;
  28. if (!isDown && jumpBuffer > 0 && jumpWolf > 0) { // 在地面、没有蹲下
  29. speedY = jumpForce;
  30. jumpBuffer = 0;
  31. }
  32. // 横向移动
  33. if (moveHorizontal != 0) {
  34. speedX = speedX * (1 - horizontalA) + movementSpeed * horizontalA * moveHorizontal;
  35. }
  36. speedX *= horizontalF;
  37. // 设置
  38. rb.velocity = new Vector2(speedX, speedY);
  39. }
  40. }