If my character's raycast collides with an object in front of it (such as a wall), how can I temporarily disable any movement going forward?

Hi everyone,

I’m making a 3D platforming game in Unity and I need help in trying to figure out how to disable my character from moving forward when its raycast collides into an object in front of it. The “W” key or the ‘UP’ arrow key moves my character forward (either the WASD control setup OR the UP, DOWN, LEFT, RIGHT arrow control setup can be used to control the character). The reason why I want to disable those two keys is because I want to prevent any attempt at my character moving forward if the raycast in front of the character has a collision with any object, such as a wall.

However, I should also point out that I don’t want to disable my characters movement completely because I still want my character to be able to move backwards even when the raycast detects a collision (The “S” letter key or the ‘DOWN’ arrow key will move the character backwards). How can I accomplish this? I tried doing this with a Boolean but I had no luck. I provided a screenshot image of my code showing what I have so far, but if for any reason you aren’t able to see the screenshot, I also copied and pasted a slightly shorter version of that same code below. Please help if you can. Thanks :slight_smile:

    bool enable = Input.GetKeyDown(KeyCode.W);
    //added this bool in hopes of helping me disable the movement key

    if (hit_info.collider != null)
    {
     print("Raycast collided!");
     enable = false;
     // My 'enable' bool method did not work
     // However, I know something is suppose to go here, but not sure what
    
    }
   
    else
    {
        print("Raycast is no longer colliding");
        enable = true;
        // enable method did not work at all
    }

Have you considered using rigid bodies, and allowing unity physics to handle this? The advantage to doing this is seen when collision are not perpendicular: What if the wall i front of your player is at 45 degrees? In this case, should the character move along the edge of the wall when pressing forward?

Like Gurth, I would also suggest letting Unity's built in physics do the heavy lifting here. Simply set the physics in the Edit > Project Settings > Physics menu, and let Unity handle the rest. (Make sure to set up the GameObjects on the proper layers as needed.)

1 Answer

1

It would probably be a lot easier to use colliders instead of scripting everything.

71380-screenshot-2.png

Let unity do all the heavy lifting for you