Stuck on using if else to prevent ball from getting stuck in brick breaker. very new to unity & C# :(,How would I reference an object to add onto its velocity in 2D?

What I am trying to do is make a ball in a brick breaker game stop sticking on the vertical and horizontal axis. I want to execute this by adding to the balls velocity whenever it is between a speed of -1 and 1 by using adding a random range of velocity between -0.5 and 0.5.

How would I actually reference the ball and execute this in an if else statement?

I’ve tried several ways, but I’m too new to c# and unity to grasp the proper syntax or formula still.

I’m thinking from researching that I need to reference the rigidbody of the ball. I have the idea of what I want to accomplish in my head, but I’m not sure how to write it out. Would it be something like this? I’m not sure if I used too many if statement or used them incorrectly, but I’m hoping this is close to the solution.

     private void OnCollisionEnter2D(Collision2D collision)
        {
    
    If (Theball >= 1f ) {
    transform.Translate(vector2.right * Time.deltaTime);
    }
    If (Theball <= -1f) {
    transform.Translate(vector2.left * Time.deltaTime);
    }
    TheBall = get component<Rigidbody2D.velocity.x>() 
    }
    
    If (Theball >= 1f ) {
    transform.Translate(vector2.up * Time.deltaTime);
    }
    If (Theball <= -1f) {
    transform.Translate(vector2.down * Time.deltaTime);
    }
    TheBall = get component<Rigidbody2D.velocity.y>() 
    }
}

HI @danmct1995, yes you need some help. I suggest you go through several getting started tutorials, and you can find a lot in YouTube and hone the Web. Start search with: Unity How to Reference a GameObject.

If your ball object is the the object the above script collides with, you can get it from the collider.gameObject.

 theBall = collision.gameObject;

do a google search on: Unity Collision object

(a word about coding style, do not begin variables identifier with a capital letter - only use a starting capital letter with class identifiers and function identifiers. Eg. use theBall not TheBall.)

If theBall is a GameObject, it cannot have a value of -1 or 1. You can test against the velocity of the ball’s Rigidbody component, or it’s transform.position, or many other properties theBall as a GameObject has.

You want to get the Rigidbody component of theBall? Google Unity how to get object components.

the general form is

  gameObject.GetComponent<ComponentIdentifier>();

note how all function identifiers begin with a capital letter! like OnCollionEnter, and GetComponent, and Translate

Keep pluging - you’ll get there, and go through a lot of examples and tutorials!