Ball is not launching

I have followed the instrctions but still not getting the ball to launch. am I missing something?

Code below

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

public class Ball : MonoBehaviour
{
//config parameters
[SerializeField] Paddle paddle1;
[SerializeField] float xPush = 2f;
[SerializeField] float yPush = 15f;

//state
Vector2 paddleToBallVector;

//started
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()
{
    LockBallToPaddle();
    LaunchOnMouseClick();

    if (!hasStarted)
    {

        LockBallToPaddle();
        LaunchOnMouseClick();
    }
    
}

private void LaunchOnMouseClick()
{
    if (Input.GetMouseButtonDown(0))
    {
        hasStarted = true;
        GetComponent<Rigidbody2D>().velocity = new Vector2(xPush, yPush);
    }

}

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

Hi Sahar_Mirhadi, I think what’s going on here is every frame LockBallToPaddle is called so of coarse even if the ball gets launched it will immediately get snapped to the paddle again.

Removing LockBallToPaddle and LaunchOnMouseClick on the outside of the if statement should solve the problem.

Hope that helps

1 Like

Thank you so much. I stared at this code for ages and it was staring right back at me.

1 Like

Believe me when I say, we have all been there. If in doubt throw some Debug.Log 's in there. I use them a lot to see if a method is getting called or not, or if it’s getting called when it’s not supposed to.

1 Like

It happens to the best of us, when you doing something as complex as programming it’s so easy to over look things. I even had a T-shirt made up just as a joke on how often this occurs.

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

Privacy & Terms