Need ball to move at random angle but not random speed

My ball needs to begin the scene moving at a random angle, but not a random speed. Only way I’ve found online to move it at a random angle is with rb.velocity = RandomVector. This successfully moves it at a random angle but also changes the speed of the ball, which I don’t want. How can I do this?

Related: I am using Rigidbody force to control the speed of the ball. Should I do this? Or should I have force and speed as separate, so that I can increase speed but leave force the same?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Ball : MonoBehaviour
{
    float radius;
    public Rigidbody2D rb;
    public float ballForce;
    private Vector2 RandomVector(float min, float max)
    {
        var x = Random.Range(min, max);
        var y = Random.Range(min, max);
        return new Vector2(x, y);
    }

    // Start is called before the first frame update
    void Start()
    {
        radius = transform.localScale.x / 2;
        var rb = GetComponent<Rigidbody2D>();
        rb.velocity = RandomVector(-5f, 5f);
        ballForce = 100f;
        rb.AddForce(new Vector2(ballForce, ballForce));
    }

You can generate a vector from a random angle (in radians) using Mathf’s trig functions, and then multiply that by your desired speed:

float angle = Random.Range(0f, 2f * Mathf.PI);
Vector2 randomDir = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle));
return randomDir * speed;
1 Like

You can also use Random.insideUnitCircle and normalize the result:

rb.velocity = Random.insideUnitCircle.normalized;

Where do I put those lines? I assume the first two are variables and go at the top but I’ve never used return, I don’t know what that is.

But the code you posted has that? And this goes into the same place. You do need to change your parameters from min/max to one “speed” and change line 22 to match.

Oh that’s funny I copied that line of code from somewhere so that just goes to show you that I have no idea what I’m doing.

Also, I entered all three lines of code that you suggested and every one of them produced an error in my console.

It sounds like you should seek out a beginner C# tutorial to teach you the ropes. Showing you how to do something won’t get you very far if you don’t know how to use that information.

1 Like

Can’t help fix the problem if you don’t say what the errors are or if you don’t post your new code after pasting in the lines.