- Home /
How to make a RigidBody not go into ground when tilted foward?
We have a game object (RigidBody) that levitates when moving forward. We also make it tilt slightly forward when moving. The issue is that whenever the object is moving with the tilt, it has a tendency of moving into the ground. Here is the code that we currently have:
private void MovingForward()
{
Vector3 movement = transform.forward * m_MovementInputValue * m_Speed * Time.deltaTime;
rb.position += movement;
rb.MovePosition(position: rb.position);
}
private void LeanForward()
{
float lean;
m_leaning = true;
if (m_leanForwardAngle < 20f)
{
lean = 1 * 50f * Time.deltaTime;
m_leanForwardAngle += lean;
transform.Rotate(Vector3.right * lean, Space.Self);
}
}
private void Levitate(int currentState)
{
Vector3 levitate = Vector3.zero;
float levitate_f = 3f;
if (currentState == 0)
{
if (m_levitatePressure < m_maxLevitateHeight)
{
levitate = transform.up * m_LevitateSpeed * Time.deltaTime;
m_levitatePressure += m_LevitateSpeed * Time.deltaTime;
rb.useGravity = false;
rb.MovePosition(rb.position + levitate);
}
else
{
m_levitatePressure = m_maxLevitateHeight;
}
}
else
{
rb.useGravity = true;
m_levitatePressure = 0f;
}
}
Based on our defined states, our character levitates and tilts slightly when moving forward. You can clearly see what the code is for each action ("Move Forward", "Tilt Forward" and "Levitate"). Let us assume our character is moving to the right and that the ground is a staight line. If we levitate and move forward, our character is moving to the right and levitating properly. However, as soon as we add the tilting, our character's angle with respect to the ground changes and it starts moving into the ground instead. See the attached picture.
Eventually we would want this to work with a non-level ground: that is, going up a hill, etc.
Thanks!
Answer by xxmariofer · Jan 24, 2019 at 12:15 AM
Hello, just remove the y value from the transform forward from
Vector3 movement = transform.forward * m_MovementInputValue * m_Speed * Time.deltaTime;
to
Vector3 aux = new Vector3(transform.forward.x, 0, transform.forward.z);
aux.Normalize();
Vector3 movement = aux * m_MovementInputValue * m_Speed * Time.deltaTime;
Thanks! I'll try it and let you know if it works for us.
Answer by Sktew · Jan 24, 2019 at 08:04 AM
Change:
Vector3 movement = transform.forward * m_MovementInputValue * m_Speed * Time.deltaTime;
To:
Vector3 movement = Vector3.forward * m_MovementInputValue * m_Speed * Time.deltaTime;
no, that will make the player go only in one direction even if its rotated.
Your answer
Follow this Question
Related Questions
How not to make a RigidBody not go into ground when tilted foward? 1 Answer
Prevent Rigidbody From Rotating 3 Answers
CONTROL RIGIDBODY MOVEMENT 2 Answers
Rotating my character only while moving in a 2D plane 3 Answers
How may I observe expected physical interactions while using Rigidbody.MoveRotation()? 1 Answer