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

Setting up Go-lang-plugin on IntelliJ IDE (Windows)

While there are many guides about setting up go-lang-plugin on Linux and Mac Os X wasn’t able to find one for Windows and it took me a while to figure it out. Bypassing the very basic steps, you should have Go SDK (Download) and IntelliJ... Continue →