Search code examples
unity-game-engine2d

How to make unity game object face perpendicularly to collider


Im trying to make it so my 2D player walk up walls/slopes and jump in the opposite direction of them. I use a raycast for jumping and a raycast to detect if the object is in contact with some kind of slope or wall.Player on slope

so the raycast is shot from the player (orange sphere) from the negative of its transform.up. I want it so that when the sphere makes contact with a wall or slope, its transform.up becomes perpendicular to it, so the raycast for jumping would shoot out in the same direction as the red line of the obstacle.


Solution

  • Assuming that your player also has a colider:
    You can use Unity's OnColliderEnter2D method to get the slope game object. With that, you can get the up vector from the transform and turn your player to match it. This would cause the player to always stay perfect 90° to every surface they are on, as long as the surface is one object. You would still have a problem in your screenshot if they jump on the "flat" part of that spike but I don't know how to fix that. Hope it helps.