Unity2d - Fix the 2D basic character asset to avoid getting stuck on walls [C#]

The ability of the basic 2D character Robot from Sample Asset collection to get stuck onto walls, can be really annoying.

One option would be to increase the friction of the objects, it interacts with but that is not an optimal solution since it can create more problems in the future.

Was trying to fix the problem and this is how I got it to work properly. Added a boolean variable which will turn true if there is a collision other than the ground and will go false when the collision cease to exist. Then will allow the character to move only when the variable is false or touches the ground. This solution is alright but generates some extra problems which are based on the design of the 2D character and its collision areas, such as it can get stuck on edges while jumping.

In order to fix that, I check the direction the character faces at the moment and push it slightly, to get it unstuck. Moreover I apply a vertical force to it, so it will recover to the ground with no more collisions.

Below is the code I used in C#:


bool collidingWall;

void OnCollisionEnter2D(){
    if (!grounded) {
        collidingWall = true;       
    }
}

void OnCollisionStay2D(){
    if (!grounded) {
        collidingWall = true;       
    }
}

void OnCollisionExit2D(){
    collidingWall = false;      
}

if(!collidingWall || grounded){
    rigidbody2D.velocity = new Vector2(move * maxSpeed, rigidbody2D.velocity.y);
}else{
    if(facingRight){
        rigidbody2D.velocity = new Vector2(0.5f, rigidbody2D.velocity.y);
    }else{
        rigidbody2D.velocity = new Vector2(-0.5f, rigidbody2D.velocity.y);
    }
    rigidbody2D.AddForce (new Vector2(0f, -5f));
}

It is far from the optimal solution but did the job for the kind of projects I am working on.

 
31
Kudos
 
31
Kudos

Now read this

Persistent IPtables on Raspberry Pi (Raspbian)

This article is not about building proper iptable rules but on how to make iptable configurations to load on every reboot. I have been trying to find a consistent and easy solution to implement iptables on Raspberry Pi (Raspbian-wheezy),... Continue →