- Home /
How to Clamp A RigidBody to the Ground/ Moving a RigidBody Along the Ground
Hello! this is my very first Question here!/sorry for my english.
Currently I am writing a RigidBody Character Controller, and I'm having some trouble.
if I move the RB on a flat surface everything is fine, but as soon as there is a slope (like 20°),
it starts to go forward, then its in the air and falls to the ground, then it detects the Ground and falls again, it moves like on stairs, but its a steady slope.
Now I want that the RB moves along the Ground, but stays upright. I already have a version of that working, but the Capsules Y Axis just alligns with the Normal.
I'm adding the Code snippet that allows me to do that. ( its not just Capsule.up = Ground.normal)
void FixedUpdate ()
{
// ControllerInput
float DirH = Input.GetAxis("LSX");
float DirV = Input.GetAxis("LSY");
DetectGround(); //SphereCast Down, Mathf.Infinity, measures distance.
if (onGround == true)
{
if (DirH != 0 || DirV != 0)
{
flippedCharCamera = (CharCamera.forward * -1); //CharCamera is the Main Camera
CharDirection = DirV * flippedCharCamera + DirH * CharCamera.right; // Calculation of the Movement
expectedPlayerPosition = CharRb.transform.position + CharDirection * charSpeed * Time.deltaTime; // Expected Player Position, CharRb is the RigidBody Character Controller
Physics.Raycast(Player.position, CharDirection - (Player.up + new Vector3(0, 2f, 0)), out AddGroundInfo, Mathf.Infinity, CharMask); //CharMask ignores the Layer the Controller is in
Vector3 MagentaDirection = (groundSphereInfo.point - AddGroundInfo.point) * -1; //groundSphereInfo is the RaycastHIt of the SphereCast in DetectGround();
CharDirection = Vector3.Project(CharDirection, MagentaDirection);
CharRb.MovePosition(CharRb.transform.position + CharDirection * charSpeed * Time.deltaTime); //charSpeed is a float 12f;
}
}
}
I am stuck at this... please send help!
Is this a 2D or 3D? If its 2D, why not look at http://unity3d.com/learn/tutorials/modules/beginner/2d/2d-controllers If its 3D, why not use a character controller?
it is 3D, and I already decided on a Rigid Body, because it has to simulate physics. I am going to do some unusual stuff with the Controller, and I can't do that with the CHaracter Controller.