Ball Launching continue when I click mouse

Please help…
whenever I’m clicking mouse button ball bounce… please help me what to do

here is my ball code:

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

public class Ball : MonoBehaviour {

	private Paddle paddle;
	private bool hasStarted = false;
	private Vector3 paddleToBallVector;



	// Use this for initialization
	void Start () {
		paddle = GameObject.FindObjectOfType<Paddle>();
		paddleToBallVector = this.transform.position - paddle.transform.position;

	}
	
	// Update is called once per frame
	void Update ()
	{
		{
			if (!hasStarted)
				//Lock the ball relative to the paddle.
				this.transform.position = paddle.transform.position + paddleToBallVector;

				//Wait for a mouse press to launch.
				if (Input.GetMouseButtonDown (1)) {
				print ("Mouse Clicked, launch ball");
				hasStarted = true;
				GetComponent<Rigidbody2D>().velocity = transform.up *10.5f  ;
			}

		}
	}





	void OnCollissionEnter2D (Collision2D collision)
	{
		Vector3 tweak = new Vector3 (Random.Range (0f, 0.2f), Random.Range (0f, 0.2f), 0f);
		print (tweak);
	 
		if (hasStarted) {

		}

	}
}
``

Hi Pankaj, welcome to the community :slight_smile:

You have a set of braces in the wrong place within your Update method, they are outside of the first if statement, when in fact, they need to be inside that if statement. Currently, only the first if statement cares whether hasStarted is false, the rest of the code will always run because it is not contained within the same code block.

Solution;

// Update is called once per frame
void Update ()
{
	if (!hasStarted)
	{
		//Lock the ball relative to the paddle.
		this.transform.position = paddle.transform.position + paddleToBallVector;

		//Wait for a mouse press to launch.
		if (Input.GetMouseButtonDown (1)) {
			print ("Mouse Clicked, launch ball");
			hasStarted = true;
			GetComponent<Rigidbody2D>().velocity = transform.up *10.5f  ;
		}
	}
}

You find it easier to identify where your braces/backets open and close if you use a block style approach rather than a trailing approach, examples;

Trailing

void Update() {
   if(someCondition) {
       // ....
   }
}

Block

void Update()
{
    if(someCondition)
    {
        // ....
    }
}

Also, when you copy/paste your code into the forum, please use the code formatting characters both before and after your code, it makes it a lot easier to read for those who offer to help you (see below)

Hope this helps :slight_smile:


See also;

1 Like

It works… Thank You Sir,
I Will keep it mind to copy/paste my codes properly :slight_smile:

1 Like

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

Great! You are more than welcome Pankaj, and no worries, it just helps others help you :slight_smile:

Privacy & Terms