75 lines
2.2 KiB
C#
75 lines
2.2 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
public class PlayerControls : MonoBehaviour
|
|
{
|
|
[Header("Physics")]
|
|
public Vector3 colliderOffset;
|
|
public Vector3 colliderSize;
|
|
public Vector2 castDirection;
|
|
public float castDistance;
|
|
public Vector3 gravity;
|
|
public Vector3 velocity;
|
|
public float maxVelocity = 100;
|
|
|
|
[Header("Monitor")]
|
|
public bool stuckBottom;
|
|
public bool stuckRight;
|
|
public bool stuckLeft;
|
|
public bool stuckUp;
|
|
|
|
void Start()
|
|
{
|
|
|
|
}
|
|
|
|
void FixedUpdate()
|
|
{
|
|
Simulate();
|
|
}
|
|
|
|
void Simulate(){
|
|
RaycastHit2D[] overlappingColliders= Physics2D.BoxCastAll(transform.position + colliderOffset, colliderSize,0,castDirection,castDistance);
|
|
stuckBottom = stuckLeft = stuckRight = stuckUp = false; // <-- Reset all stuck states.
|
|
|
|
if(overlappingColliders.Length > 0){
|
|
for(int i =0; i < overlappingColliders.Length; i++){
|
|
RaycastHit2D hit = overlappingColliders[i];
|
|
Debug.Log(hit.collider.name);
|
|
Vector2 offset = (Vector2)(transform.position+colliderOffset) - hit.point;
|
|
float xBoundary = (colliderSize.x /2f) * 0.9f;
|
|
float yBoundary = (colliderSize.y /2f) * 0.1f;
|
|
|
|
if(offset.x >= xBoundary){
|
|
stuckLeft=true;
|
|
}else if(offset.x <= -xBoundary) {
|
|
stuckRight=true;
|
|
}
|
|
|
|
if(offset.y >= yBoundary){
|
|
stuckBottom=true;
|
|
}else if(offset.y <= -yBoundary){
|
|
stuckUp=true;
|
|
}
|
|
}
|
|
}else{
|
|
//No contacts... freefalling
|
|
velocity+=gravity;
|
|
}
|
|
|
|
//Apply stucks
|
|
velocity = new Vector3(
|
|
Mathf.Clamp(velocity.x, (stuckLeft) ? 0: -maxVelocity, (stuckRight) ? 0: maxVelocity),
|
|
Mathf.Clamp(velocity.y, (stuckBottom) ? 0: -maxVelocity, (stuckUp)?0: maxVelocity)
|
|
);
|
|
|
|
transform.Translate(velocity); // <-- Apply the calculated velocity
|
|
}
|
|
|
|
private void OnDrawGizmos() {
|
|
Gizmos.color = Color.green;
|
|
Gizmos.DrawWireCube(transform.position + colliderOffset, colliderSize);
|
|
}
|
|
}
|