- Home /
2D Limit player speed
Hello I am working on a endless runner.I am using InvokeRepeating for adding speed to my player but I have problem with it.I want to limit my max player speed to 20f. How can I do this?
Answer by Lightning_A · Apr 25, 2020 at 04:14 AM
Assuming you want limit the speed on the x axis
public float maxVelocity = 20f;
//put this inside your invoke repeating
if(rb.velocity.x > maxVelocity)
{
rb.velocity = new Vector2(maxVelocity, rb.velocity.y);
}
Answer by K00KIE · Apr 23, 2020 at 06:18 PM
Hi bud.
If you are using rigidbody to move use:
Rigidbody2D = rb;
public float maxVelocity = 20f
void FixedUpdate()
{
if(rb.velocity > maxVelocity)
{
rb.velocity = maxVelocity
}
}
Hope that solves your problem.
If you are using any other way of moving, feel free to let me know. i'll help you.
it gives a error that says cannot implicitly convert type 'float' to 'UnityEngine.Vector2'
Rigidbody = rb;
public float maxVelocity = 20.0f
void FixedUpdate()
{
if (rb.velocity >= maxVelocity)
{
rb.velocity = maxVelocity;
}
}
Answer by Shen-Kit · Apr 24, 2020 at 12:50 PM
If the player is moving up the screen use:
maxVelocity = 20f;
if (rb.velocity.magnitude > maxVelocity) {
rb.velocity = Vector2.up * maxVelocity;
}
If they're moving left to right use:
maxVelocity = 20f;
if (rb.velocity.magnitude > maxVelocity) {
rb.velocity = Vector2.right * maxVelocity;
}
To increase performance, you can replace the (rb.velocity.magnitude > maxVelocity)
with (rb.velocity.sqrMagnitude > Mathf.Pow(maxVelocity, 2))
If this works please mark the question answered. If it doesn't please ask any questions I'm happy to help :)
it gives a error that says Invalid token '=' in class, struct, or interface member declaration.If I change maxVelocity to int or float still doesnt work. I think it happens cuz I am using velocity and float in the same code.Is there any way to limit float without velocity?
sry for bad English :)
Sorry I made a mistake when typing that. In the if statement it should say: if (rb.velocity.magnitude > maxVelocity)
A cheaper option is to use if (rb.velocity.sqr$$anonymous$$agnitude > $$anonymous$$athf.Pow(maxVelocity, 2))
As I am not in the unity editor right now, I'm not certain of the capitalisation and things like that, but if you use the autocorrect to find the right function either of those should work.
EDIT: I have updated my original answer now so you can just refer to that
Your answer
Follow this Question
Related Questions
How to limit the force from player input without limiting speed 2 Answers
how to instantiate UI image in unity2D 1 Answer
Pathfinding with specific end-direction and turning speed limit 0 Answers
InvokeRepeating() not working. 1 Answer
Cap rigid body move speed, without capping rotation speed 1 Answer