简体   繁体   中英

Random Picturebox Location - VB.NET

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM