Ball keeps locking even with the bool

The ball keeps locking to the paddle when I launch it, I put in the bool exactly like Rick but somehow it’s just not working for me D:

{
    [SerializeField] Paddle paddle1;

    //state
    Vector2 paddleToBallVector;
    bool hasStarted = false;


    // Start is called before the first frame update
    void Start()
    {
        paddleToBallVector = transform.position - paddle1.transform.position;

    }

    // Update is called once per frame
    void Update()
    {
        if (!hasStarted)
        {
            LockBallToPaddle();
            LaunchOnClick();
        }
        

    }

    private void LaunchOnClick()
    {
        if (Input.GetMouseButtonDown(0))
        {
            hasStarted = true;
            GetComponent<Rigidbody2D>().velocity = new Vector2(2f, 15f);
        }
    }

    private void LockBallToPaddle()
    {
        Vector2 paddlePos = new Vector2(paddle1.transform.position.x, paddle1.transform.position.y);
        transform.position = paddlePos + paddleToBallVector;
    }
}

Hi,

Have you already tried to add Debug.Logs to your code to see what is going on during runtime?

Pretty new to both unity and C#. Where would I add the debug.logs string?

LockBallToPaddle gets called in the if-block in the Update method if hasStarted is false. In your code, hasStarted gets set to true in the if-block of the LaunchOnClick method. For this reason, it makes sense to add the Debug.Log to the if-block in LaunchOnClick to see if that code block gets executed. If it doesn’t, hasStarted will not get set to true and LockBallToPaddle will continue to get called each frame.

Ok so it gets set to true.
The ball will launch but snap back and bounce off the paddle again continuously.

Ok. i figured it out. I thought it was the code but for some reason the ball gravity scale was set WAY up. Haha thanks for the help though. i

Good job on solving the problem! :slight_smile:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms