- Home /
How to have an object stop incrementing speed after a certain value?,
So I'm playing around with making a simple Pong game (with tutorials), and am trying to have it so the ball doesn't move any faster after a certain point (it gets a bit faster each time it hits a paddle). Because if it moves too fast it just goes right through the paddles. I had wanted to add a couple extra features to make it my own even though I'm still new with coding.
Any help is greatly appreciated!
public class Ball : MonoBehaviour
{
public float speed = 200.0f;
private Rigidbody2D _rigidbody;
private void Awake()
{
_rigidbody = GetComponent<Rigidbody2D>();
}
private void Start ()
{
resetPosition();
AddStartingForce();
}
public void resetPosition()
{
_rigidbody.position = Vector2.zero;
_rigidbody.velocity = Vector2.zero;
}
public void AddStartingForce()
{
float x = Random.value < 0.5f ? -1.0f : 1.0f;
float y = Random.value < 0.5f ? Random.Range(-1.0f, -0.5f) : Random.Range(0.5f, 1.0f);
Vector2 direction = new Vector2(x, y);
_rigidbody.AddForce(direction * this.speed);
}
public void AddForce(Vector2 force)
{
_rigidbody.AddForce(force);
}
}
Answer by swanne · Nov 02, 2021 at 03:57 PM
Apologies, I have done some testing and found my mistake.
On the ball use this
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Ball : MonoBehaviour
{
public float moveSpeed = 1f;
public float maxSpeed = 4;
Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
Move();
}
void Move()
{
rb.AddForce(Vector3.right * moveSpeed);
}
private void Update()
{
Debug.Log(rb.velocity.magnitude);
if(rb.velocity.magnitude > maxSpeed)
{
rb.velocity = rb.velocity.normalized * maxSpeed;
}
}
}
Then on each of the paddles use this:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Paddle : MonoBehaviour
{
Rigidbody rb;
public float force = 50f;
void OnCollisionEnter(Collision col)
{
if (col.gameObject.tag == "Ball") // Do not forget assign tag to the field
{
rb = col.gameObject.GetComponent<Rigidbody>();
rb.AddForce(-transform.right * force);
}
}
}
On the left paddle, enter a negative value and it'll make the ball travel right. eg. -300
I'm unfortunately getting an error though..
And this is what I added:
public class Ball : MonoBehaviour
{
public float maxSpeed = 250.0f;
private void FixedUpdate()
{
if (_rigidbody.velocity > maxSpeed)
{
_rigidbody.velocity = maxSpeed;
}
}
}
Thank you very much for all your help! It has been very useful :)
Your answer

Follow this Question
Related Questions
Finding the speed of MoveTowards 1 Answer
increase speed every spawn wave 0 Answers
Putting a brakes on my spaceship 0 Answers
Hi, knife hit, how do you control the speed of the wheel and the speed of the knife? 1 Answer
Making Top-Down spaceship movement, getting current speed, acceleration, without rigidbody! 1 Answer