- Home /
Unity automatically rotate camera on slopes up/down
I have a Player in first person walking around on terrain and I'd like to restrict the camera controls to the y axis (left/right) and automate the camera rotation of the x axis. So looking up/down should require no player input, depending on wether you walk up a slope or down.
I'm not quite sure what to look for. You could probably do it with a Raycast, but I suppose there's an easier way?
You've provided too few details for a complete answer. How you might organize this will depend on factors like how you allowing your character to move. Raycasting is likely necessary to get the normal to align the character with the slop. The critical like of code that I think will allow you to do what you want is:
transform.rotation = Quaternion.FromToRotation(transform.up, hit.normal) * transform.rotation;
This will assure that the up vector of your transform is aligned, but it will allow you to rotate the block along it's local 'Y' axis.
Yes, I should have wrote that I use a Character Controller for movement. Well I can detect going uphill with a Raycast, but how would I look down again after you reach the top? Set one raycast on the upper part of the screen to detect when to move the camera up and one on the lower part of the screen to detect when to move it down?
I'm not sure of your goal here, but a Raycast() will detect the normal to the mesh under the character. Just so I'm sure we are talking about the same thing, here is an image:
Each ray would be the normal at that point on the surface. Whether your camera would be tilted up, or down, would depend on your rotation with respect to that normal. At the top of the hill, the camera would be level because the normal points straight up (and my suggested code aligns the 'y' axis of the object with the normal).
For your game mechanic, you may have a specific restrictions, or behaviors. But you'd have to spell them out in order for anyone here to offer you a specific solution.