- Home /
Question by
Tea_Doogun · Oct 16, 2015 at 09:07 PM ·
c#rigidbody2dvelocity
Put a limit on velocity on the X axis
It seems that some stuff has changed recently-ish with how some code works with 2D physics, or i'm just being dumb, IDK.
I'm writing a simple C# AI for an enemy bot for a 2D platformer.
Bot has a rigidbody2D & Box Collider 2D
I'm using AddRelativeForce to move it
I want to place a limit on the rigidbody's velocity on the X axis
The code i have so far affects the enemy velocity overall, which is problematic as i'm now wanting it to jump.
Below is a BASIC outline of the code i'm using. It works fine, just need to know how to limit 2D velocity on the X axis only.
Thank you, Tom :)
public float speed = 10.0f;
public float maxVel = 10.0f;
public float jumpForce = 700.0f;
void Start ()
{
rb2D = GetComponent<Rigidbody2D>();
}
void FixedUpdate ()
{
if(rb2D.velocity.magnitude > maxVel)
{
rb2D.velocity = rb2D.velocity.normalized * maxVel;
}
// When it's time to move
rb2D.AddRelativeForce (transform.right * speed);
// When it's time to jump
rb2D.AddForce(new Vector2(0, jumpForce));
Comment
Best Answer
Answer by dkjunior · Oct 16, 2015 at 10:39 PM
Tom, try this:
if(rb2D.velocity.x > maxVel)
{
rb2D.velocity = new Vector2(maxVel, rb2D.velocity.y);
}