我正在制作一款复古街机游戏《Asteroids》,并且在"射击"击中小行星并将其分裂成碎片的碰撞检测方面遇到了一些麻烦。
使用下面的代码,我在第二个子程序开始的If语句中得到一个错误:操作符"="没有定义类型"System.Windows.Forms. forms"。"PictureBox"one_answers"System.Windows.Forms.PictureBox"。
Private Sub CollisionDetection_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CollisionDetection.Tick
Dim Asteroids() = {picLrgAsteroid100, picLrgAsteroid200, picLrgAsteroid300, picLrgAsteroid400, picLrgAsteroid500}
'Stores all asteroids, used for testing collision for all asteroids
For Each PictureBox In Asteroids
'For all asteroids
If PictureBox.Bounds.IntersectsWith(picBullet1.Bounds) Then
Me.Controls.Remove(picBullet1)
AsteroidDestroyer(PictureBox)
ElseIf PictureBox.Bounds.IntersectsWith(picBullet2.Bounds) Then
Me.Controls.Remove(picBullet2)
ElseIf PictureBox.Bounds.IntersectsWith(picBullet3.Bounds) Then
Me.Controls.Remove(picBullet3)
End If
'If it intersects with a bullet
'Remove the bullet, and transmit to break apart the asteroid
Next
End Sub
Public Sub AsteroidDestroyer(ByVal Asteroid As System.Windows.Forms.PictureBox)
If Asteroid = picLrgAsteroid100 Then
*
*
*
End if
当我使用for…每个语句,我如何通过"For each PictureBox in Asteroids"将当前正在运行的PictureBox传输到子例程"AsteroidDestroyer"并让它接收,然后在if语句中使用它?
例子(伪代码):
sub CollisionDetection
If PictureBox (picLrgAsteroid100) intersects with picBullet1 then
Remove picBullet1
Transmit to AsteroidDestroyer(picLrgAsteroid100)
End if
End Sub
Sub AsteroidDestroyer(ByVal Asteroid as PictureBox)
If Asteroid = picLrgAsteroid100 then
End If
End Sub
如果你能看到任何改进的方法,以避免这个问题,我没有理由像我现在这样做,所以请随时提出建议!
通俗地说,您正在尝试比较包含引用的两个变量,在这种情况下,是对相同对象(或可能是相同对象)的引用。数字1可以"等于"数字1,或者一个包含数字1的变量可以"等于"另一个包含数字1的变量,相反,一个对象不能等于它自己。相等是一个对象的属性或值的特征。
在比较对象引用的情况下,vb.net提供了Is操作符。当您可能习惯于用等号比较值或属性时,
If var1 = var2 Then
要执行对象引用的比较,您可以使用' Is '。
If objRef1 Is objRef2 Then
=
和Is
都返回一个布尔值,表示成功或失败(等于/真,或不等于/假),但是等号比较的是一个值,Is
比较的是一个引用,而不考虑引用的属性。
在您的特定情况下,这转换为
If Asteroid Is picLrgasteroid100 Then