VelocityTweak FIXED

Vector2 tweakVelocityOfBoth = new Vector2(Random.Range(0.1f, randomFactor), Random.Range(0.1f, randomFactor));
Vector2 tweakVelocityOfX = new Vector2(Random.Range(0.1f, randomFactor), 0);
Vector2 tweakVelocityOfY= new Vector2(0, Random.Range(0.1f, randomFactor));

    myRigidBody2d.velocity = myRigidBody2d.velocity.normalized * ballSpeed;
    if (hasStarted && myRigidBody2d.velocity.x >= 0 && myRigidBody2d.velocity.y >= 0)
    {

        myRigidBody2d.velocity += tweakVelocityOfBoth;

        //Debug.Log(myRigidBody2d.velocity);
    }
    else if (hasStarted && myRigidBody2d.velocity.x <= 0 && myRigidBody2d.velocity.y <= 0)
    {
        myRigidBody2d.velocity -= tweakVelocityOfBoth;
    }else if(hasStarted && myRigidBody2d.velocity.x >= 0 && myRigidBody2d.velocity.y <= 0)
    {
        myRigidBody2d.velocity += tweakVelocityOfX;
        myRigidBody2d.velocity -= tweakVelocityOfY;
    }
    else if (hasStarted && myRigidBody2d.velocity.x <= 0 && myRigidBody2d.velocity.y >= 0)
    {
        myRigidBody2d.velocity += tweakVelocityOfY;
        myRigidBody2d.velocity -= tweakVelocityOfX;
    }

It applies tweakVelocity in all direction
Ball never gets stuck!

1 Like

I am going to try this, because I ran into an issue on my level 2 where the ball and paddle are stuck on the right side and never move. This is because the ball goes straight up and down on the right and the angle of the paddle there keeps it there, even with a slight adjustment to the side. I have randomFactor set to 0.5 at the moment.

I do have a question and a suggestions for you:

What is ballSpeed set to? That is not something in the class examples.

Also, I would suggest a small change to improve your code. Every if in here has ‘hasStarted’ at the start. It is better to have a single if that checks the hasStarted flag and have all the rest inside the braces for that if. That way you are only checking it the one time instead of four times.

1 Like

How about:

        Vector2 velocityTweak = new Vector2(
             Random.Range(-randomFactor, randomFactor),    // x
             Random.Range(-randomFactor, randomFactor));   // y
        myRigidbody2D.velocity += velocityTweak;

that way you are adding both plus and minus tweaks.

1 Like

It should work, test it out

Privacy & Terms