- Home /
Rigidbody Keep Vertical Without Applying Rotational Constraints
Hi,
I have a situation where i need a rigidbody character to remain perpendicular to the surface beneath the player, this is not always guaranteed to be in the Y direction for instance if the character was walking up a "vertical" wall. To move the rigidbody i am manually setting the velocity, this causes the rigidbody to topple over which is not what I want.
My question to you is, how can I make my character remain perpendicular to the surface beneath it using C# code? My character uses a ray cast down to detect whether he is grounded and I can use the normal from that to get the target rotation.
Thanks
Answer by Magso · Jan 07, 2018 at 08:06 PM
If you mean making the player stick on whatever's beneath it, I have this js code.
var hit : RaycastHit;
function Update (){
if(Physics.Raycast (transform.localPosition, transform.TransformDirection (Vector3.down), hit)) {
transform.localPosition = hit.point;
transform.rotation = Quaternion.LookRotation (transform.TransformDirection (Vector3.forward), hit.normal);
}
}
I think it's same for C# except for the variable and "function" would be "void".
Hi,
I have tried your example and it doesn't appear to do anything, the character still just rolls over. I'll have a play with it a bit longer to see if there is a way it can be used.
Thanks
Answer by sparkzbarca · Jan 07, 2018 at 08:22 PM
Vector3.cross(a,b)
If you give it up which is the hit. Normal as a and right which is transform. Right it will give you the third parralel which is forward.
This will ensure left and right remain the same locally and all that changes is what's considered up so you can stick objects together.
Post if you need more help or more detailed code example
Hi,
Thanks for your quick response, have you got an example of this? I can get it to work if the second parameter for thie Vector3.cross is the constant Vector3.up but if i use transform.up it spins really quickly.
In additional it also appears to lock the local Y rotation of the character which i need so that he can pivot and look around.
Thanks
Your answer
![](https://koobas.hobune.stream/wayback/20220612150021im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Collision on character controller (fps player) 2 Answers
Multiple Cars not working 1 Answer
Cancel out a Addforce && Addtorque? 1 Answer
Question about topdown-movement and mouse-facing-foward-check 0 Answers