I'm building the retro arcade game 'Asteroids' and have been having some trouble with the collision detection of a 'shot' hitting an asteroid and splitting it into pieces.
Using the following code, I get an error in the If statement at the start of the second subroutine: Operator '=' is not defined for types 'System.Windows.Forms.PictureBox' and '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
As I'm using a for...each statement, how can I transmit which PictureBox is currently being run through "For each PictureBox in Asteroids", to the subroutine 'AsteroidDestroyer' and have it receive, then use it in the if statement?
Example (Pseudo-code):
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
And if you can see any way to improve, to avoid this problem, there's no reason I have it as I currently do, so feel free to suggest!
In lay terms, you are trying to compare two variables which contain references, and in this case, to the same object (or potentially the same object). Whereas the number one can "equal" the number one, or a variable containing the number one can "be equal to" another variable containing the number one, in contrast an object can not equal itself. Equality is a characteristic of the properties, or values of an object.
In the case of comparing references to an object vb.net provides the Is Operator. Where you might be accustomed to comparing values or properties with the equal sign,
to perform a comparison of object references you would instead use ‘Is‘.
Both
=andIsreturn a Boolean indicating a success or failure (equality/true, or inequality/false), but where the equal sign compares a value,Iscompares a reference without regard to the reference's properties.In your specific case, this translates to,