Random ball direction on click

Somebody can help me with this small game I’m making.
I want when I click on the ball it will go a random direction, up, right, left, under.
Right now I have this code just to test the onclick method

public class BallClickScript : MonoBehaviour {

    void OnMouseDown()
    {
        {
            Destroy (gameObject);
        }
    }
}

I tried something with transform but I don’t realy know how to exactly write it down, because I’m a beginner.

Do you want to apply a force so it kinda bounces away? or simply move it in a random direction

I realy want a smooth bouncing away when I click on the ball, I already have a gravity force on a ball so it will go down.

Anyone can still help me with my problem??

To pick up a random direction use Random.onUnitSphere. Then you can use that direction to apply a force to the ball with Rigidbody.AddForce. Pay attention to ForceMode, that parameter will depend on how you want to apply the force (either a sudden kick or a continuous force over time).

Oke so understand what you explained I have tested but now I just have a force that hits the ball and random direction
But I have now idea where to put the rigidbody.addforce code, here is my code.

public class BallClickScript : MonoBehaviour {

    public float thrust;
    public Rigidbody rb;


    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    void FixedUpdate()
    {
        rb.AddForce(0,0, thrust, ForceMode.Impulse);
    }

    void OnMouseDown()
    {
        {
            //Destroy (gameObject);
            //transform.position = new Vector3(3,4,0);

            // Zorgt ervoor dat er een random kracht op de bal komt.
            GetComponent<Rigidbody>().velocity = Random.onUnitSphere * 10;


        }
    }
}

Don’t do anything in FixedUpdate, that would be applying the force 30x per second.
Where you’re setting the velocity right now, you’d do AddForce instead, with Random.onUnitSphere * thrust.

This what I got, I’m getting a error
MissingReferenceException: The object of type ‘Object’ has been destroyed but you are still trying to access it.

public class BallClickScript : MonoBehaviour {

    public float thrust;

    void Start()
    {
        thrust = 5f;
    }

    void OnMouseDown()
    {
        {
            //Destroy (gameObject);
            //transform.position = new Vector3(3,4,0);

            // Zorgt ervoor dat er een random kracht op de bal komt.
            GetComponent<Rigidbody>().AddForce = Random.onUnitSphere * thrust;

        }
    }
}

AddForce is a method, not a variable.
GetComponent().AddForce(Random.onUnitSphere * thrust, ForceMode.Impulse);

var rigidbody = GetComponent<Rigidbody>();
if(rigidbody == null) return;
rigidbody.AddForce(Random.onUnitSphere * thrust);
1 Like

Oke I fixed that but where can I write that I only want to add to force to right or left because I’m making a 2d ball game where you need to keep the ball in the air, now the ball also use the Z as and I don’t want that.
And the force I’m using doesn’t push the ball up in the air how do I fix that?

In order constraint it in the X-Y plane, just put zero in the Z-component of the randomDirection vector:

Vector3 GetRandomDirection2D()
{
    var dir = Random.onUnitSphere;
    dir.z = 0.0f;
    return dir.normalized;
}

You have to apply a force that overcomes the force due to gravity, which is Fg = mass*g, where g is 9.81 by default in Unity.

Getting a error saying unexpected symbol {

void OnMouseDown()
    {
        {
            //Destroy (gameObject);
            //transform.position = new Vector3(3,4,0);

            // Zorgt ervoor dat er een random kracht op de bal komt.
            GetComponent<Rigidbody>().AddForce(Random.onUnitSphere * thrust, ForceMode.Impulse);

            Vector3 = GetRandomDirection2D()
            {                                                        <<<<<<<<<<< ERROR
                var dir = Random.onUnitSphere;
                dir.z = 0.0f;
                return dir.normalized;
            }
        }
    }

That’s a syntax error, what you wrote does not make sens. GetRandomDirection2D is a function:

using UnityEngine;

public class BallClickScript : MonoBehaviour
{
    public float thrust = 20.0f;

    Vector3 GetRandomDirection2D() // This is a function...
    {
        var dir = Random.onUnitSphere;
        dir.z = 0.0f;
        return dir.normalized;
    }

    void OnMouseDown()
    {
        var impulse = GetRandomDirection2D() * thrust; // ... that is used here.
        GetComponent<Rigidbody>().AddForce(impulse, ForceMode.Impulse);
    }

}

Thank you I’m a whole step closer to my game.
I just have some small things I wanna know.

  • Because my ball is 3d he bounce to the right and left and sometimes he rotates and then he falls of the stage, how can I fix that?

  • Here and there I click on the ball, but the speed is kind of random and it looks like I also need to wait before I click again is there a way I can precise this?

On the Rigidbody, you can freeze position and/or rotation component-wise.

What do you mean by “kind of random”, what do you want as movement?
For waiting, you could add a timer in the Update function that would start when the ball is kicked and allow kicking the ball again only when this timer is elapsed.

I got want I want I think what I did wrong was adding x and y dir, in the code, I removed that and I played around with the drag function and mass of the sphere to make the clicking and falling a little stable so you have enough time to click the ball again before it hits the ground.

One thing I wanna say is that when I click on the ball he goes also down realy fast, wich makes it hard to keep the ball in the air like you can see in this game.

Here is a link of the game I tried to remake: Voetbal Spelletjes - Gratis Online Spelen |

Thank you for your help.

You can change the gravity setting in Edit > Project Settings > Physics.

In this game the direction of the force applied to kick the ball is not random! The ball move randomly because, well, the players movements are random… that’s what makes this game fun.

So the force direction depends on where you click on the ball. You can use Rigidbody.AddForceAtPosition to indicate where the ball is kicked. For that you would need to compute the mouse position (Input.mousePosition) from screenspace to worldspace. You can do that by either use Physics.Raycast and Camera.ScreenToRayPoint or directly compute the mouse position using Camera.ScreenToWorldPoint.