- Home /
How to make rigidbody movement without changing or clamping the Velocity?
I try to make a physic based rigidbody fps controller, but most fps controller changing the velocity like this:
rb.velocity = new Vector3(move.x, rb.velocity.y, move.z);
If you change the velocity directly like this, the controller won't react to something like boost pads or any other changes to the velocity. Is there any other way to move the controller without changing or clamping the actually Velocity?
Answer by afraism · Feb 03, 2021 at 06:50 PM
try this:
void Update()
{
// Move the object forward along its z axis 1 unit/second.
transform.Translate(Vector3.forward * Time.deltaTime);
// Move the object upward in world space 1 unit/second.
transform.Translate(Vector3.up * Time.deltaTime, Space.World);
}
Answer by hamerilay · Feb 03, 2021 at 11:00 PM
The answer is to add velocity instead of setting the velocity, to do this in the FixedUpdate put:
if (Mathf.Abs(rb.velocity.x) < maxSpeed)
{
rb.velocity += new Vector3(move.x * speed, 0, 0);
}
if (Mathf.Abs(rb.velocity.z) < maxSpeed)
{
rb.velocity += new Vector3(0, 0, move.z * speed);
}
use "Mathf.Abs()" to turn any number to a positive number.
Add these variables:
public float speed;
public float maxSpeed;
public Rigidbody rb;
Vector3 move;
In the Update function put this:
move = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
This code will check if the velocity is under the max speed and if it is true we add some velocity, if you want to boost the player just add or set the velocity. Here is an example to give a boost in the direction the player is going:
if (Input.GetKeyDown(KeyCode.Space))
{
rb.velocity += rb.velocity * 1.5f;
}
Final code:
public float speed;
public float maxSpeed;
public Rigidbody rb;
Vector3 move;
private void Update()
{
move = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
if (Input.GetKeyDown(KeyCode.Space))
{
rb.velocity += rb.velocity * 1.5f;
}
}
private void FixedUpdate()
{
if (Mathf.Abs(rb.velocity.x) < maxSpeed)
{
rb.velocity += new Vector3(move.x * speed, 0, 0);
}
if (Mathf.Abs(rb.velocity.z) < maxSpeed)
{
rb.velocity += new Vector3(0, 0, move.z * speed);
}
}
I used speed: 0.5, maxSpeed: 5 and set the rb to the rigidbody on the player.
I hope this helped you!
Answer by AbandonedCrypt · Feb 03, 2021 at 07:07 PM
Unity has a nice physics implementation to apply forces to a rigidbody: Rigidbody.AddForce
You can choose between multiple types of applying force such as constant force or impulse. You can monitor the velocity and adjust the force you apply accordingly. That way you can still have external elements apply force (think boost pads) properly.
Edit: To not make your character fall over and act all weird, you can freeze rotation on all axis in the rigidbody constrains
Previous repliers answer is basically just transform manipulation and not physics based movement controlling.