i need help with a random number generator

so i want to make an affect where the player is moved in one direction and then the other
but the random.value does not give me a high enough number to do anything even visible to the player

i want to able to get a random value in the tens range constantly to put in a add force

heres the code i have now

using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using UnityEngine;

public class wind : MonoBehaviour
{
    public Rigidbody rb;
   
    // Update is called once per frame
    void FixedUpdate()
    {
        rb.AddForce(Random.value,0,0);
        rb.AddForce(-Random.value,0,0);
       
    }
}

Random.value returns a number between 0 and 1, so just multiply it by 100 or something. If you multiply by 100 you’ll get a number between 0 and 100.

2 Likes

Also note that FixedUpdate is called several times per frame. So you give your Rigidbody always a new direction. This will only cause jitter. If you want to have visible random movement create a random direction and store it in a class variable. Then move a certain (random) amount of time towards it. When time is over create a new direction.

Also note that with your setup the Rigidbody is only moved along the global x axis (not local). Do you have a 2d setup?

And you are the second one to have the cryptography namespace in a script (by accident, I suppose). There really seems to be something off with Unity. Maybe it’s Coronas fault ;).

1 Like

I believe you meant ‘per second’ there. FixedUpdate is called at a fixed time interval, which depending on the framerate and timestep can be multiple times per frame but is usually once per multiple frames. Everything else you said is of course correct.

Maybe I should have been more precise and say “potentially” several times per frame. Especially when certain frames take longer than average FixedUpdate is called multiple times in one frame to “catch up”. Thats at least how I understood it. I just wanted to point out to OP that this may also be a cause of “unexpected behavior” and that just increasing the value may still not work as he wants.
So to be on the same level I think we can agree that FixedUpdate can run from zero to a large number of times per frame. And that it should thus not be utilized for the purpose here.

For reference an interesting article by Jackson Dunstan about How FixedUpdate Works.

1 Like

Also Random.Range(low, high); // can be floats or ints

That is a fantastic article exi! Appreciate it…

1 Like