Block Breaker ball following the paddle

The ball launches when I click the mouse. However, it stays with the paddle—if I move right, the ball moves right and if I move left, the ball moves left. I’m using Unity 2017.1.2f1 Here is my ball script:

using UnityEngine;
using System.Collections;

public class Ball : MonoBehaviour
{
    public Paddle paddle;
    private bool hasStarted = false;
    private Vector3 paddleToBallVector;

    // Use this for initialization
    void Start()
    {
        paddleToBallVector = this.transform.position - paddle.transform.position;

    }

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

            if (Input.GetMouseButtonDown(0))
            {
                print("Mouse clicked, launch ball");
                
                hasStarted = true;
                gameObject.GetComponent<Rigidbody2D>().velocity = new Vector2 (2f, 12f);
            }
        }

    }
}

try taking out this line

this.transform.position = paddle.transform.position + paddleToBallVector;

this is whats causing your ball to synchronize together with the Paddles transform

Thank you for replying. However, I tried that and it didn’t solve the problem. I’m going to just start from the beginning again.

1 Like

Hey oyabaka - any luck finding the solution?
I have exactly the same problem you do using Unity 2017 and have had no luck solving this.

1 Like

Would one or both of you like to share your project files and I will happily take a look. The forum will support a maximum file size of 10mb, so if your zipped project files are larger than that, please use something like DropBox or Google Drive and provide the URL in a reply so that I can download your project.

From the posted code above, the only noticeable difference is that the paddle is, presumably, being referenced by dragging it via the Inspector into the exposed public field, rather than being found using code in the Start method.

Hi Rob,
Sorry for the late reply and thank you for offering to look at my file. I’ve uploaded it—it was only 8 MB (I think I zipped it correctly).
Block Breaker.zip (8.2 MB)

Hi oyabaka,
You accidentally attached a Paddle script to your Ball game object, hence the ball follows the mouse just like the paddle does.

1 Like

That was fast! Thank you, Sebastian! You’re a lifesaver! Now I can move forward in the course.

2 Likes

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

Privacy & Terms