Get raycast to ignore rotational axis

In my sidescroller game the character’s Z rotation is based on a raycast pointing from -transform.up allowing him to rotate along convex/concave surfaces (and walk up walls and along ceilings). I’m creating my own gravity that always pulls the character towards any surface that’s below him (locally) and the character rotation is always based on the normal of the surface the raycast is hitting.

This works great, however, one of the key mechanics for my game will be to allow the player to flip up/down from ceiling/floor or flip left/right from right wall/left wall.

When I rotate the X axis to make the character flip to another surface the raycast will angle diagonally off the terrain causing some wild spinning and rotations.

My question boils down to this:

Is it possible to have the raycast not rotate with the player’s X rotation? Just the Z?

Hope I explained this well. I new to Unity. Loving it so far!

Thanks!

Since you’re probaly using -transform.up on the character, the raycast will always be facing downwards according to the character…
My first thought would be to make the character a child object of a new empty object and give the new object the raycast instead.
That way the character can flip etc without affecting the raycast, but the raycast position will still follow the character (if you move the new object instead of the character).
Another idea would be to disable the ray while the character is flipping, as to avoid the strange spinning :wink:

After grabbing -transform.up, you could zero out a particular axis before building your raycast.

For example:

var dir = -transform.up;
dir.z = 0f;
var ray = new Ray(transform.position, dir);