- Home /
How to Increase speed of the ball over time?
I'm trying to make a Brick Breaker game and I want to speed up the ball's speed over time. Now I've wrote the code for it, but it doesn't effect the ball's speed. In the inspector ball's speed increases, but not in the game. What am I doing wrong? Why the code doesn't effect the ball in the game?
private Rigidbody2D rb;
public float ballSpeed = 400f;
public bool ballMoving;
public Transform ballPos;
public float maxBallSpeed = 1000f;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(ballMoving == false)
{
transform.position = ballPos.position;
}
if (Input.GetButtonDown("Jump") & ballMoving == false)
{
ballMoving = true;
rb.AddForce(Vector2.up * ballSpeed);
}
// Increase ball's speed over time
if(ballMoving == true)
{
ballSpeed += 20f;
if (ballSpeed >= maxBallSpeed)
{
ballSpeed = maxBallSpeed;
}
}
}
Answer by CR-Safari · Jan 19, 2019 at 08:23 AM
Problem Solved guys! I wrote this code and it now increases the ball's speed over time. Thank you for your help and answers!
// Adds speed to the ball over time
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.name == "Paddle" && ballMoving == true)
{
rb.AddForce(rb.velocity * forceAmount, ForceMode2D.Force);
}
}
Answer by DawidNorasDev · Jan 18, 2019 at 02:20 PM
With your setup here, your ballSpeed will get to max speed in 30 Frames, which would be half a second or less depending on VSync. Are you sure it's not it? try decreasing it. Also, ballSpeed is only a variabie here. You only apply it when you press Jump. You can set rb.velocity to normalized value * ballSpeed. But it's not the greatest way.
ballSpeed is actually 400f when I start the game. And it stays 400f in the game but in the inspector it increases. I've tried to decrease it but same result. Does it have to do something with the Rigidbody?
Answer by FPSworrior · Jan 18, 2019 at 08:26 PM
Maybe you should try moving the addforce function inside of part that checks if the ball should be moving, example move it from line 28 to maybe 35. Otherwise it might only update when you press "Jump". If you also times the increase rate by Time.deltaTime you could control the rate of increase much easier. Also on line 25 you should be using && and not a single & because youre checking a condition. Hope this helps.
I tried moving AddForce from line 28 to 35 but then ball moves so fast and makes crazy moves like bouncing so much that it goes through the blocks and out of the scene :D.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Unity C# lean script not working properly 1 Answer
Unloading Broken Assembly | How to solve this !? 2 Answers
EventTrigger PointerEnter 1 Answer