Ball Breaker - Keep the ball in a range of speeds

Hi All,

I am sharing one of my snippets of code - there is a challenge from Rick and I went about having a go. We want our ball to keep within a range of speeds but it can be difficult to do with vectors. At first, I tried using Pythagoras theorem but there is a much easier way - you can use the command yourVelocity.magnitude. Also I used a do loop to make sure the magnitude is within a range of speeds so it’ll do the command at least once so there will be some variation of velocity even if it’s velocity is in range. Just be careful because it’s easy to get infinite loops - make sure your ball is shot with a speed within your range.

    using UnityEngine;

    Vector2 randomVelocity;
    bool hasStarted = false;
    float speedNew;    

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (hasStarted == true)
        {
            do
            {
                CalcRandomVector();
                FindMag();
            } while (speedNew < 10.0f || speedNew > 30.0f);
            ballRigid.velocity += randomVelocity;
        }
    }
    private void CalcRandomVector()
    {
        float xRand = Random.Range(-1.5f, 1.5f);
        float yRand = Random.Range(-1.5f, 1.5f);
        randomVelocity = new Vector2(xRand, yRand);
    }

    private void FindMag()
    {
        Vector2 velocityNew = randomVelocity + ballRigid.velocity;
        speedNew = velocityNew.magnitude;
    }
1 Like

Awesome stuff man! :clap: :clap: :clap:

1 Like

Privacy & Terms