- Home /
How do I Un-Clamp a Rigidbody2D's Magnitude
I limited my Player Character's Maximum Speed. But then I had an Issue, where my Character jumps inconsistently. Now, I also managed to fix that issue.
if (rb.velocity.magnitude > maxSpeed)
{
if (jumpingScript.jumpRequest && !jumpingScript.grounded)
{
//Un-Clamping the Magnitude would be useful in this If-Section
//I'd also like to put a Wait 0.5 Seconds Command here. I understand that I need a Coroutine for this, so I'd move the Commands of this If-Section inside a Coroutine just to be able to do this
rb.velocity = Vector2.ClampMagnitude(rb.velocity, maxFallingSpeed);
}else if (jumpingScript.grounded)
{
rb.velocity = Vector2.ClampMagnitude(rb.velocity, maxSpeed);
}
}
But now, I have a new issue, again. This time, the issue is, that the Player Character's speed isn't limited in the air anymore. The speed is still limited on the ground, but nothing stops the player from going game-breakingly fast when in the air.
If only I could Un-Clamp the Rigidbody2D's magnitude for a split second before clamping it again. Then, I'd be able to fix the issue with the gamebreaking player speeds in the air without re-introducing the problem of inconsistent jump heights.
Answer by Bunny83 · Jul 01, 2019 at 09:02 PM
You should split your velocity into the horizontal (planar) part and the vertical part. Then you can just clamp the horizontal part and just keep the vertical as it is. That allows infinite speed along the y axis but only a certain speed in the x-z plane.
Vector2 vel = rb.velocity;
vel.x = Mathf.Clamp(vel.x, -maxSpeed, maxSpeed),;
rb.velocity = vel;
You don't need that "magnitude" check at all. It's actually pointless and even more expensive than the actual clamping ^^. You can (or should) execute those lines every FixedUpdate.
Note if you also want to restrict the y velocity you can just duplicate the Mathf.Clamp line and replace vel.x with vel.y and your desired max speed.
thank you very much! I put it all inside the FixedUpdate()
method. I replaced this entire part and it works really well: if (rb.velocity.magnitude > maxSpeed) { if (jumpingScript.jumpRequest && !jumpingScript.grounded) { rb.velocity = Vector2.Clamp$$anonymous$$agnitude(rb.velocity, maxFallingSpeed); }else if (jumpingScript.grounded) { rb.velocity = Vector2.Clamp$$anonymous$$agnitude(rb.velocity, maxSpeed); } }
Your answer
Follow this Question
Related Questions
Jump Normal to Collider Surface 1 Answer
How to cut the leg / arm of a character 1 Answer
how to make the player not rotate when i press left or right button ? 1 Answer
Player cannot jump 0 Answers
Can't make my character to jump ?? 0 Answers