- Home /
Is there a way to lock velocity?
Im making a 2d pong like game with powerups. one of the powerups doubles the velocity of the ball. Ive been having problems with the physics engine as when I hit the ball with the side of my paddle the ball speeds up alot. Is there any way to lock the velocity to a certain number unless the powerup is activated?`public Rigidbody2D rb; public float ballForce; public Rigidbody2D powerUpRB; private bool timerStart = false; private float timeLeft = 1f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyUp(KeyCode.Space))
{
rb.velocity = new Vector2(ballForce, ballForce);
}
}
void OnCollisionEnter2D(Collision2D coll)
{
if (coll.gameObject.name != "doubleBallSpeed") return;
rb.velocity = new Vector2(ballForce * 2, ballForce * 2);
StartCoroutine("DelayTime");
Destroy(coll.gameObject);
}
IEnumerator DelayTime()
{
yield return new WaitForSeconds(5f);
rb.velocity = new Vector2(ballForce / -2, ballForce / 2);
}
}
You need execute Physic actions in FixedUpdate calling in Update will slow your code.
Answer by ZeroSumGames · Nov 21, 2016 at 11:53 PM
Yes, there is. What you need to do is measure the Magnitude of the velocity. If it exceed the max speed, then you normalize the vector and multiply it by the max speed.
Vector2 vel = new Vector2();
float mag = vel.magnitude;
if (mag >= MaxSpeed)
{
vel = vel.normalized * MaxSpeed;
}
Answer by MattG54321 · Nov 22, 2016 at 08:35 AM
I recommend you try Mathf.Clamp(float value, float min, float max). It returns max if value is greater than max.
Example:
float xVel = Mathf.clamp(ballForce * 2, minVel, maxVel);
float yVel = Mathf.clamp(ballForce * 2, minVel, maxVel);
rb.velocity = new Vector2(xVel, yVel);
Answer by romatallinn · Nov 21, 2016 at 10:47 PM
I am not sure what you mean by "lock the velocity to a certain number". If you want the velocity would not exceed some limits, you can use Mathf.Clamp. Or if you want to keep the speed the same all the time, then you just use Update function and assign there constant velocity.
by lock I mean that the velocity would stay the same no matter what except when the powerup comes into effect. Is this what $$anonymous$$athf.Clamp would do?
@Silent_Eagle no. Then you just keep assigning velocity some constant value in update.
void Update()
{
rb.velocity = new Vector2(ballForce, ballForce);
}
will this fix whenever i slam the ball between the boundary and the paddle the ball speeds up. And as I want to eventually make this a mobile game with the players finger controlling the paddle I feel things could get out of hand.
Your answer
Follow this Question
Related Questions
Help with 2D physics script 1 Answer
How to rotate a GameObject with another GameObject while simulating gravity? 2 Answers
Trying to get a ball to bounce realistically in 2D. 2 Answers
Bullet not moving from script 3 Answers
Reduce Physics2D Lag 0 Answers