How to prevent my character from walking through walls

whoabeast

New member
Joined
Mar 10, 2021
Messages
4
Programming Experience
Beginner
I am making a Unity game and I am using Visual Studio to code. I am using a Character Controller to move the character, so how do I prevent the character from walking through walls?
 
Collision detection. See if your character is colliding against a wall and bounce them back if they do. Of course, this assumes that your character is not moving so fast that at t0 it is on one side of the wall, and at t1, it is completely on there other side. For those cases you will need to start using vectors and check for ray-plane intersections.
 
I am making a Unity game and I am using Visual Studio to code. I am using a Character Controller to move the character, so how do I prevent the character from walking through walls?
So just add a ridgidBody to my character and box colliders to the walls?
 
Yeah pretty much

Hi,
I'll tell how I do in my videogames of Super Mario Bros and others (I use C# and SFML.Net, not Unity). You (I suppose) have an image for your level and you should also have something that's called hardness map, that is an array which contains an attribute (from an enum) for each point (pixel) of your level. The attribute can be air, solid, water, etc..
Suppose your level is 2400x600 pixels (3 screens of 800x600) and you have the image. You need to set all the points' attributes. You don't need to do it one by one, you should write methods like setting a complete rectangle from the level to a specific attribute, or a triangle.

C#:
public enum Place { Solid, Air, Water }
//
private byte[,] levelPoints = new byte[2400, 600];
SetRect(0, 0, 2400, 500, (byte)Place.Air);
SetRect(0, 500, 2400, 600, (byte)Place.Solid);
//
private void SetRect(int x1, int y1, int x2, int y2, byte attribute)
{
    for (int x = x1; x < x2; x++)
        for (int y = y1; y < y2; y++)
            levelPoints[x, y] = attribute;
}

For avoiding the possible issue described by Skydiver, you might, instead of writting something like:

if (player.Wall() == false)
player.X += 20;

write something like:

for (int a = 0; a < 20; a++)
if (player.Wall() == false)
player.X++;
else // if reaches the wall
break; // it stops the check

The Wall() method would be something like:

C#:
public bool Wall()
{
    if (levelPoints[player.X + player.Width, player.Y] == (byte)Place.Solid
       || levelPoints[player.X + player.Width, player.Y + player.Height / 2] == (byte)Place.Solid
       || levelPoints[player.X + player.Width, player.Y + player.Height] == (byte)Place.Solid)
        return true;
    return false;
}

I hope this helps you.
Regards
Pablo
 
Back
Top Bottom