- Home /
Player passing through wall when pushed 2d C#
I have a game where you move around multiple box players {all attached with the same script} at the same time using the arrow keys {0 gravity scale}. You solve puzzles by getting them in different positions by displacing them with walls, etc. The problem I'm running into is that if one player square pushes the other into a wall, the box in front gets pushed through the wall completely, regardless of how thin or thick the wall may be. The script I have for movement looks something like this:
private float moveSpeed = 0.1f;
void Update () {
if(Input.GetKey("up") || Input.GetKey("right") || Input.GetKey("down") || Input.GetKey("left")){
transform.Translate(moveSpeed, 0f, 0f);
}
if(Input.GetKey("up")){
transform.eulerAngles = new Vector3(0, 0, 90);
}else
if(Input.GetKey("right")){
transform.eulerAngles = new Vector3(0, 0, 0);
}else
if(Input.GetKey("down")){
transform.eulerAngles = new Vector3(0, 0, -90);
}else
if(Input.GetKey("left")){
transform.eulerAngles = new Vector3(0, 0, 180);
}
}
// I am aware the player can only move in four directions, this is intentional
To try & remedy this situation, I added a part to the script that detected which side there was collision on & move the box in the opposite direction of it. That looks like this:
private float topAngle;
private float sideAngle;
void Start() {
Vector2 size = GetComponent<BoxCollider2D>().size;
size = Vector2.Scale (size, (Vector2)transform.localScale);
topAngle = Mathf.Atan (size.x / size.y) * Mathf.Rad2Deg;
sideAngle = 90.0f - topAngle;
Debug.Log (topAngle + ", " + sideAngle);
}
void OnCollisionStay2D(Collision2D coll) {
// Debug.Log("hit something");
Vector2 v = coll.contacts[0].point - (Vector2)transform.position;
if (Mathf.Abs(Vector2.Angle(v, Vector3.up)) <= topAngle){
// Debug.Log("Collision on top");
transform.Translate(0f, -moveSpeed, 0f);
}
else if(Mathf.Abs(Vector2.Angle(v, Vector3.right)) <= sideAngle){
// Debug.Log("Collision side1");
transform.Translate(-moveSpeed, 0f, 0f);
}
else if(Mathf.Abs(Vector2.Angle(v, Vector3.left)) <= sideAngle){
// Debug.Log("Collision side2");
transform.Translate(moveSpeed, 0f, 0f);
}
else{
// Debug.Log("Collision on bottom");
transform.Translate(0f, moveSpeed, 0f);
}
}
Once I did this, the problem happens less often but still consistently enough that it's unplayable. Anyone know what I can do? As always, all help is appreciated <3