PlayerControls.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class PlayerControls : MonoBehaviour
  5. {
  6. [Header("Physics")]
  7. public Vector3 colliderOffset;
  8. public Vector3 colliderSize;
  9. public Vector2 castDirection;
  10. public float castDistance;
  11. public Vector3 gravity;
  12. public Vector3 velocity;
  13. public float maxVelocity = 100;
  14. [Header("Monitor")]
  15. public bool stuckBottom;
  16. public bool stuckRight;
  17. public bool stuckLeft;
  18. public bool stuckUp;
  19. void Start()
  20. {
  21. }
  22. void FixedUpdate()
  23. {
  24. Simulate();
  25. }
  26. void Simulate(){
  27. RaycastHit2D[] overlappingColliders= Physics2D.BoxCastAll(transform.position + colliderOffset, colliderSize,0,castDirection,castDistance);
  28. stuckBottom = stuckLeft = stuckRight = stuckUp = false; // <-- Reset all stuck states.
  29. if(overlappingColliders.Length > 0){
  30. for(int i =0; i < overlappingColliders.Length; i++){
  31. RaycastHit2D hit = overlappingColliders[i];
  32. Debug.Log(hit.collider.name);
  33. Vector2 offset = (Vector2)(transform.position+colliderOffset) - hit.point;
  34. float xBoundary = (colliderSize.x /2f) * 0.9f;
  35. float yBoundary = (colliderSize.y /2f) * 0.1f;
  36. if(offset.x >= xBoundary){
  37. stuckLeft=true;
  38. }else if(offset.x <= -xBoundary) {
  39. stuckRight=true;
  40. }
  41. if(offset.y >= yBoundary){
  42. stuckBottom=true;
  43. }else if(offset.y <= -yBoundary){
  44. stuckUp=true;
  45. }
  46. }
  47. }else{
  48. //No contacts... freefalling
  49. velocity+=gravity;
  50. }
  51. //Apply stucks
  52. velocity = new Vector3(
  53. Mathf.Clamp(velocity.x, (stuckLeft) ? 0: -maxVelocity, (stuckRight) ? 0: maxVelocity),
  54. Mathf.Clamp(velocity.y, (stuckBottom) ? 0: -maxVelocity, (stuckUp)?0: maxVelocity)
  55. );
  56. transform.Translate(velocity); // <-- Apply the calculated velocity
  57. }
  58. private void OnDrawGizmos() {
  59. Gizmos.color = Color.green;
  60. Gizmos.DrawWireCube(transform.position + colliderOffset, colliderSize);
  61. }
  62. }