Reputation: 111
I am making a reaction game that involves the user clicking a picturebox which randomizes its location.
The tricky part is to randomize the picturebox's location so that it appears within the bounds of a panel which i have created. The reason for this is that i have other controls on the form. Not sure if a panel would be the best way of going about this but i am not sure where to start.
The picturebox's size is (70,55) and the panel's size is (640,400) in location (40,69) if it makes any difference.
I have the following code so far:
Dim rnd1 As Integer = panel1.Width * Rnd()
Dim rnd2 As Integer = panel1.Height * Rnd()
pb1.Top = rnd2
pb1.left = rnd1
while it works it randomizes the picturebox right on the edges of the panel so that some randomizations result in the picturebox not being visible at all. What code would i have to use so that the picturebox is completely visible and does not cross the bounds of the panel?
Thanks
Upvotes: 1
Views: 2940
Reputation: 27322
You are not taking into account the height or width of the PictureBox object.
if you set the left property of the picturebox to be the width of the panel then it will be out of view.
You need to do something like this:
Dim rnd1 As Integer = (panel1.Width - pb1.Width) * Rnd()
Dim rnd2 As Integer = (panel1.Height - pb1.Height) * Rnd()
pb1.Top = rnd2
pb1.left = rnd1
Note: If you use Rnd
you need to call Randmonize()
first otherwise your random numbers will be the same sequence each time you run your application: Using Randomize() before Rnd() in VB.NET
I would suggest using the Random
class instead of Rnd
as this does not require you to initialise a seed before you start using it.
Upvotes: 4
Reputation: 3072
Use Random class to generate your random number. The argument is the max number you want to generate. For your top location, you generate a number between 0 and the panel's height minus picture box's height. For your left location, a number between 0 and the panel's width minus picture box's width.
Put this in the form declaration.
Dim random As New Random
Put this in your event (I use a timer event).
Dim newTop As Integer = random.Next(panel1.Height - pb1.Height)
Dim newLeft As Integer = random.Next(panel1.Width - pb1.Width)
pb1.Top = newTop
pb1.Left = newLeft
Upvotes: 3