Search Unity

How to Increase speed of the ball over time?

Discussion in 'Scripting' started by CR-Safari, Jan 18, 2019.

  1. CR-Safari

    CR-Safari

    Joined:
    Jan 17, 2019
    Posts:
    1
    I'm trying to make a Brick Breaker game and I want to speed up the ball's movement over time. Now I've wrote the code for it, but it doesn't effect the ball's movement. 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?


    Ball's Script:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class Ball : MonoBehaviour {

    private Rigidbody2D rb;
    public float ballSpeed = 400;
    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 movement over time
    if(ballMoving == true)
    {
    ballSpeed += 20f;

    if (ballSpeed >= maxBallSpeed)
    {
    ballSpeed = maxBallSpeed;
    }

    }
    }
     
  2. MattM_Unity

    MattM_Unity

    Unity Technologies

    Joined:
    Aug 18, 2017
    Posts:
    45
    Hello CR-Safari!

    Please use code tags when you paste code, makes it much more readable: https://forum.unity.com/threads/using-code-tags-properly.143875/ :)

    Now regarding your problem, at no point you're setting your ballMoving boolean back to false, so the following code is executed only once:

    Code (CSharp):
    1. if (Input.GetButtonDown("Jump") & ballMoving == false)
    2. {
    3.     ballMoving = true;
    4.     rb.AddForce(Vector2.up * ballSpeed);
    5. }
    That would explain why you see the value increasing in the Inspector but not see the ball moving faster. :)
     
    Last edited: Jan 18, 2019