Random generator in class

Android

Active member
Joined
Mar 6, 2007
Messages
35
Programming Experience
1-3
I'm writing a simple game and have a class for the ball. The constructor of this class sets the amount for the ball to increment each frame to make it move for both the x and y axis This is done with random numbers.

With one ball this all works fine but then if I call the class again for a second ball although everything still works the random numbers that are generated in this instance of the class are always exactly the same as the numbers that are generated for the first instance of this class. This means that both balls are always in the same place so you can only see one of them.

Is there anyway that I can make it so that the numbers generated by different instances of the class are different in every instance?

Thanks
 
What code are you using for random? Are you using Random class? If not, use this.
 
Yes I'm using the random class

VB.NET:
         Dim objRnd As New Random()
        intBallXInc = objRnd.Next(-4, 5)
        intBallYInc = objRnd.Next(-4, 5)
 
Getting different numbers from that every time here.
 
I just made a new project to test this and i still have the same problem. heres all of the code

Class
VB.NET:
Public Class Class1
    Public r1 As Integer
    Public r2 As Integer

    Public Sub New()
        Dim objrand As New Random
        r1 = objrand.Next(-4, 5)
        r2 = objrand.Next(-4, 5)
    End Sub
End Class

Form
VB.NET:
Public Class Form1
    Public cls As Class1
    Public cls2 As Class1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        cls = New Class1()
        cls2 = New Class1()
        MsgBox(cls.r1)
        MsgBox(cls.r2)


        MsgBox(cls2.r1)
        MsgBox(cls2.r2)
    End Sub
End Class

The first to msgboxes have different values but then the next two are the same as the first two.
 
Since what you do there happens instantly, and the Random class is by default time-based, the equal results you get here is predictably true and well described in documentation. You can solve this dilemma quite easily by sleeping the thread 1ms between each Next call:
VB.NET:
Public Sub New()
    Dim objrand As New Random
    r1 = objrand.Next(-4, 5)
    Threading.Thread.Sleep(1)
    r2 = objrand.Next(-4, 5)
End Sub
 
Back
Top