Collision Detection edits the Spawn Location of a Picture Box - vb.net

I am making a two dimensional game where the user is able to shoot enemies and gain points. So far I have added borders to the level as well as the collision detection between the Player and said borders. When the player presses "w" the user shoots a bullet. Without me setting the boundaries, the bullet appears at the centre of the players sprite. With the boundaries set, the bullets appear to increase height from the player when spawned; when the player moves to the left of the screen. Vice Versa when the player moves to the right.
The first Class:
Public Class Bullet
Inherits PictureBox 'this class is a variation of a picture box
Public Sub New() 'every time bullet is accessed it will access this sub as well
With Me 'refers back to anything in the class
.Height = 5
.Width = 2
.Location = PlayScreen.PlayerShip.Location 'sets the bullets start point to the ship
.BackColor = Color.White
.SetBounds(x:=PlayScreen.PlayerShip.Left, y:=PlayScreen.PlayerShip.Left, height:=5, width:=2)
End With
End Sub
Public Sub ShootUp()
Me.Top -= 10 'Males the bullet move upwards
End Sub
End Class
The Rest of my Code:
Public Class PlayScreen
Public Shared PlayerShip As New PictureBox 'defines the ship as a picture box
Dim WallNorth As New PictureBox
Dim WallSouth As New PictureBox
Dim WallEast As New PictureBox 'these will be given collision detection to check if the player is trying to exit the boundires of the level
Dim WallWest As New PictureBox
Dim Bullets(-1) As Bullet 'makes the array have nothing in it
Dim BulletCounter As Integer 'used to make new bullets
Dim MoveRight As Boolean = False
Dim MoveLeft As Boolean = False 'Making movement based upon boolean factors allows for more user friendly controls
Dim MoveUp As Boolean = False
Dim MoveDown As Boolean = False
Dim PUHealth As New PictureBox
Dim Health As Integer
Dim Score As Integer
Private Sub PlayScreen_Load(sender As Object, e As EventArgs) Handles MyBase.Load
MovementTimer.Start()
PUHealthTimer.Start()
Health = 3
HealthLbl.Text = "Health: " & Health
Score = 0
ScoreLbl.Text = "Score: " & Score
Me.Controls.Add(PUHealth)
PUHealth.Width = 25
PUHealth.Height = 25
PUHealth.BorderStyle = BorderStyle.FixedSingle
PUHealth.BackColor = Color.Yellow
PUHealth.Top = Me.Height / 2 - 100
PUHealth.Left = Me.Width / 2 - 100
PUHealth.SetBounds(x:=Me.Height / 2 - 100, y:=Me.Width / 2 - 100, height:=25, width:=25)
Me.Controls.Add(PlayerShip) 'imports the picture box onto the PlayScreen
PlayerShip.Width = 40
PlayerShip.Height = 40 'Dimensions of the player ship
PlayerShip.BorderStyle = BorderStyle.FixedSingle 'adds a border to the picturebox
PlayerShip.BackColor = Color.White 'adds colour to the ship background
PlayerShip.SetBounds(x:=Me.Left, y:=Me.Top, height:=40, width:=40)
Me.Controls.Add(WallNorth)
WallNorth.Width = 750
WallNorth.Height = 5
WallNorth.BorderStyle = BorderStyle.FixedSingle 'this is defining the wall at the top of the screen, setting its positions as well as its bounds
WallNorth.BackColor = Color.Green
WallNorth.Top = 1
WallNorth.Left = 1
WallNorth.SetBounds(x:=1, y:=1, height:=5, width:=750)
Me.Controls.Add(WallEast)
WallEast.Width = 5
WallEast.Height = 750
WallEast.BorderStyle = BorderStyle.FixedSingle 'This defines the wall at the right of the screen, setting its position as well as its bounds
WallEast.BackColor = Color.Green
WallEast.Top = 1
WallEast.Left = 545
WallEast.SetBounds(x:=545, y:=1, width:=5, height:=750)
Me.Controls.Add(WallSouth)
WallSouth.Width = 750
WallSouth.Height = 5
WallSouth.BorderStyle = BorderStyle.FixedSingle
WallSouth.BackColor = Color.Green
WallSouth.Top = 574
WallSouth.Left = 1
WallSouth.SetBounds(x:=1, y:=573, width:=750, height:=5)
Me.Controls.Add(WallWest)
WallWest.Width = 5
WallWest.Height = 750
WallWest.BorderStyle = BorderStyle.FixedSingle
WallWest.BackColor = Color.Green
WallWest.Top = 1
WallWest.Left = 1
End Sub
Private Sub PlayScreen_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
Select Case e.KeyValue
Case Keys.Right
MoveRight = True
Case Keys.Left
MoveLeft = True 'This edits the boolean value of the varibales when the correct key is pressed
Case Keys.Up
MoveUp = True
Case Keys.Down
MoveDown = True
Case Keys.W
ReDim Preserve Bullets(BulletCounter) 'allows the array to expand more efficiently
Dim Bullet1 As New Bullet 'creates new bullet
Controls.Add(Bullet1) 'adds bullet to the screen
Bullets(BulletCounter) = Bullet1 'the new space created in the array is saved as the new bullet made
BulletCounter += 1
ShootUpTimer.Start() 'starts the shoot timer
End Select
While WallNorth.Bounds.IntersectsWith(PlayerShip.Bounds)
PlayerShip.Top += 5
End While
While WallEast.Bounds.IntersectsWith(PlayerShip.Bounds) 'I have to check if the player has collided with the wall when the key is down
PlayerShip.Left -= 5
End While
While WallSouth.Bounds.IntersectsWith(PlayerShip.Bounds)
PlayerShip.Top -= 5
End While
While WallWest.Bounds.IntersectsWith(PlayerShip.Bounds)
PlayerShip.Left += 5
End While
If PUHealth.Bounds.IntersectsWith(PlayerShip.Bounds) Then 'checks if the player has collided with the the power up
If PUHealth.Visible() Then 'This stops a bug where the player could go to the spot where the power up use to be and collect health
Health += 1 'increaeses the players health by one
HealthLbl.Text = "Health: " & Health 'displays the new player health
PUHealth.Hide() 'hides the power up
End If
End If
End Sub
Private Sub PlayScreen_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyUp
Select Case e.KeyValue
Case Keys.Right
MoveRight = False
Case Keys.Left
MoveLeft = False 'This edits the boolean value when the key has been lifted
Case Keys.Up
MoveUp = False
Case Keys.Down
MoveDown = False
End Select
While WallNorth.Bounds.IntersectsWith(PlayerShip.Bounds)
PlayerShip.Top += 5
End While
While WallEast.Bounds.IntersectsWith(PlayerShip.Bounds) 'i have to check if the player collides with a wall while the key is down
PlayerShip.Left -= 5
End While
While WallSouth.Bounds.IntersectsWith(PlayerShip.Bounds)
PlayerShip.Top -= 5
End While
If PUHealth.Bounds.IntersectsWith(PlayerShip.Bounds) Then
If PUHealth.Visible() Then
Health += 1
HealthLbl.Text = "Health: " & Health
PUHealth.Hide()
End If
End If
End Sub
Private Sub MovementTimer_Tick(sender As Object, e As EventArgs) Handles MovementTimer.Tick
If MoveRight = True Then
PlayerShip.Left += 5
End If
If MoveLeft = True Then
PlayerShip.Left -= 5
End If
If MoveUp = True Then
PlayerShip.Top -= 5 ' I use a timer to tick every 10 milliseconds ato check the states of each key, this statement controlls the execution of the direction
End If
If MoveDown = True Then
PlayerShip.Top += 5
End If
While WallNorth.Bounds.IntersectsWith(PlayerShip.Bounds)
PlayerShip.Top += 5
End While
While WallEast.Bounds.IntersectsWith(PlayerShip.Bounds) 'i check if the player is collided with the wall whilst the timer ticks because the player could not collide with the wall every 20 milliseconds
PlayerShip.Left -= 5
End While
While WallSouth.Bounds.IntersectsWith(PlayerShip.Bounds)
PlayerShip.Top -= 5
End While
While WallWest.Bounds.IntersectsWith(PlayerShip.Bounds)
PlayerShip.Left += 5
End While
If PUHealth.Bounds.IntersectsWith(PlayerShip.Bounds) Then
If PUHealth.Visible() Then
Health += 1
HealthLbl.Text = "Health: " & Health
PUHealth.Hide()
End If
End If
End Sub
Private Sub PUHealthTimer_Tick(sender As Object, e As EventArgs) Handles PUHealthTimer.Tick
If PUHealth.Visible() Then 'checks if the health power up i visible
Else 'if not the coordinates are randomised and then displayerd
PUHealth.Top = ((500 * Rnd()) + 10)
PUHealth.Left = ((500 * Rnd()) + 10)
PUHealth.Show()
End If
End Sub
Private Sub ShootTimerUp_Tick(sender As Object, e As EventArgs) Handles ShootUpTimer.Tick
For x = 0 To Bullets.Length - 1 'to check every position within the array apart from the newest
Bullets(x).ShootUp()
Next
End Sub
End Class
What do i need to change to get the bullets to shoot from the middle, of the top, of the ship.

In the Public Class I declared the X and Y location both as the x location

Related

2D Collision detection in Visual Basic

This is my first time writing a small winform game. When researching into collision detection i know that i need to set my bounds first.
Me.Controls.Add(PlayerShip) 'imports the picture box onto the PlayScreen
PlayerShip.Width = 40
PlayerShip.Height = 40 'Dimensions of the player ship
PlayerShip.BorderStyle = BorderStyle.FixedSingle 'adds a border to the picturebox
PlayerShip.BackColor = Color.White 'adds colour to the ship background
PlayerShip.SetBounds(x:=40, y:=40, height:=40, width:=40)
And then the other picture box
Me.Controls.Add(WallNorth)
WallNorth.Width = 750
WallNorth.Height = 5
WallNorth.BorderStyle = BorderStyle.FixedSingle
WallNorth.BackColor = Color.Green
WallNorth.Top = 1
WallNorth.Left = 1
WallNorth.SetBounds(x:=1, y:=1, height:=5, width:=750)
Private Sub PlayScreen_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
Select Case e.KeyValue
Case Keys.Right
MoveRight = True
Case Keys.Left
MoveLeft = True 'This edits the boolean value of the varibales when the correct key is pressed
Case Keys.Up
MoveUp = True
Case Keys.Down
MoveDown = True
End Select
End Sub
Private Sub PlayScreen_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyUp
Select Case e.KeyValue
Case Keys.Right
MoveRight = False
Case Keys.Left
MoveLeft = False 'This edits the boolean value when the key has been lifted
Case Keys.Up
MoveUp = False
Case Keys.Down
MoveDown = False
End Select
End Sub
Private Sub MovementTimer_Tick(sender As Object, e As EventArgs) Handles MovementTimer.Tick
If MoveRight = True Then
PlayerShip.Left += 5
End If
If MoveLeft = True Then
PlayerShip.Left -= 5
End If
If MoveUp = True Then
PlayerShip.Top -= 5 ' I use a timer to tick every 10 milliseconds ato check the states of each key, this statement controlls the execution of the direction
End If
If MoveDown = True Then
PlayerShip.Top += 5
End If
End Sub
End Class
However when i try to write an if statement to check if they will collide or not i do not get a '.bounds' option. I have seen '.bounds' being needed after the name of the picture box. Instead i have been met with '.setbounds' even though i have set them before.
Is something wrong with my version of visual studio, or am I missing something?

How do I set my picturebox (bullets in my case) on their own axis seperate from my character's movement in VB?

I'm very, VERY, new to coding and started a class in Visual Studio and the language Visual Basic in a .NET windows form app. So on that note, please cut me some slack.
I am trying to make a little game where you can move your character and shoot a monster or two in only 4 directions (left, right, up, left). Well, the problem is that my bullets move when I try to move my character with the WASD keys. This is most likely because I have set my WASD keys to both movements for the movement of the character, and the direction in which the bullets (PictureBox) shoots. I've tried making boolean switches, but me being new to coding seems to have caused some trouble figuring it out. I'll drop what I have so far:
Public Class Form1
Dim Health As Integer = 7
Dim UUp As Boolean = True
Dim UDown As Boolean = True
Dim ULeft As Boolean = True
Dim URight As Boolean = True
Dim EUp As Boolean = True
Dim EDown As Boolean = True
Dim ELeft As Boolean = True
Dim ERight As Boolean = True
Dim Bullets(-1) As Bullet
Dim intCount As Integer
Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles MyBase.KeyDown
'movement of character player controls
If (e.KeyCode = Keys.W And UUp = True) Then
pbIssac.Top -= 5
ElseIf (e.KeyCode = Keys.A And ULeft = True) Then
pbIssac.Left -= 5
ElseIf (e.KeyCode = Keys.D And URight = True) Then
pbIssac.Left += 5
ElseIf (e.KeyCode = Keys.S And UDown = True) Then
pbIssac.Top += 5
ElseIf (e.KeyCode = Keys.Escape) Then
End
End If
'creation of bullet? code from internet!
Select Case e.KeyCode
Case Keys.Space
ReDim Preserve Bullets(intCount)
Dim bullet1 As New Bullets
Controls.Add(bullet1)
Bullets(intCount) = bullet1
intCount += 1
tmrShoot.Enabled = True
End Select
'direction character is facing determines direction of bullet
If (e.KeyCode = Keys.A) Then
My.Settings.Keypressed = 1
My.Settings.Save()
ElseIf (e.KeyCode = Keys.D) Then
My.Settings.Keypressed = 2
My.Settings.Save()
ElseIf (e.KeyCode = Keys.W) Then
My.Settings.Keypressed = 3
My.Settings.Save()
ElseIf (e.KeyCode = Keys.S) Then
My.Settings.Keypressed = 4
My.Settings.Save()
End If
Bullet Class (From the internet!)
Public Class Bullet
Inherits PictureBox
Public Sub New()
With Me
.Size = New Size(10, 30)
.Location = Form1.pbIssac.Location
.BackgroundImageLayout = ImageLayout.Stretch
.BackgroundImage = My.Resources.green
End With
End Sub
Public Sub Shoot()
If (My.Settings.Keypressed = 1) Then
Me.Left -= 3
My.Settings.Save()
ElseIf (My.Settings.Keypressed = 2) Then
Me.Left += 3
My.Settings.Save()
ElseIf (My.Settings.Keypressed = 3) Then
Me.Top -= 3
My.Settings.Save()
ElseIf (My.Settings.Keypressed = 4) Then
Me.Top += 4
My.Settings.Save()
End If
End Sub
End Class
This is the sort of thing that I would do in that situation:
Public Class Form1
Private characterPosition As Point
'Set a default direction for the character.
Private characterDirection As Direction = Direction.Up
Private ReadOnly bullets As New List(Of Bullet)
Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
Select Case e.KeyCode
Case Keys.W
characterDirection = Direction.Up
'Move character up.
Case Keys.S
characterDirection = Direction.Down
'Move character down.
Case Keys.A
characterDirection = Direction.Left
'Move character left.
Case Keys.D
characterDirection = Direction.Right
'Move character right.
Case Keys.Space
bullets.Add(New Bullet(characterPosition, characterDirection))
End Select
End Sub
End Class
Public Enum Direction
Up
Down
Left
Right
End Enum
Public Class Bullet
Private direction As Direction
Public Sub New(location As Point, direction As Direction)
'...
Me.direction = direction
End Sub
Public Sub Move()
Select Case direction
Case Direction.Up
'Move bullet up.
Case Direction.Down
'Move bullet down.
Case Direction.Left
'Move bullet left.
Case Direction.Right
'Move bullet right.
End Select
End Sub
End Class
Note that each bullet remembers its own direction so you just tell it to move and it moves.

VB.NET select area screen how to Ignore the lock center in mouse for games to move the mouse where i want

Hi i have make small program when you hold Shift+Control and after you drag the mouse draw nice Rectangle when release the keys finish
this working very well in windows and some game also when it's full screen :) !
2 Problem i try to solve it
1) some game take the mouse and lock in center the problem it's you cant move the mouse where you like always it's in center
i try in time to use
Me.Cursor = New Cursor(Cursor.Current.Handle)
Cursor.Position = New Point(Control.MousePosition.X, Control.MousePosition.Y)
2) some game ignore the keys control+shift i try to put something like
control+shift+A for example but this don't work
GetKeyPress(Keys.ShiftKey) AndAlso GetKeyPress(Keys.ControlKey) AndAlso GetKeyPress(Keys.A)
the only i see to work its the HotKey but i want get stage when Up Down and i don't know how
<Runtime.InteropServices.DllImport("User32.dll")>
Public Shared Function RegisterHotKey(ByVal hwnd As IntPtr,
ByVal id As Integer, ByVal fsModifiers As Integer,
ByVal vk As Integer) As Integer
End Function
here full code copy paste and run it , to make your test
Dim timerUpdate As New Timer
Private Const KEY_DOWN As Integer = &H8000
Private Declare Function GetKeyPress Lib "user32" Alias "GetAsyncKeyState" (ByVal key As Integer) As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'form Setting transparent and hide
Me.TransparencyKey = Color.Black
Me.BackColor = Color.Black
Me.FormBorderStyle = FormBorderStyle.None
Me.Opacity = 0.0
Me.TopMost = True
'Timer
timerUpdate.Interval = 1
timerUpdate.Enabled = True
AddHandler timerUpdate.Tick, AddressOf timerUpdate_Tick
End Sub
Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)
'paint rectangle to border red
Dim size = 2
Dim RedPen As New Pen(Color.Red, size)
Dim rect As New Rectangle(size, size, Me.ClientSize.Width - size * 2, Me.ClientSize.Height - size * 2)
e.Graphics.DrawRectangle(RedPen, rect)
End Sub
Private Sub Form1_Resize(sender As Object, e As EventArgs) Handles MyBase.Resize
'Refresh for drawing update
Me.Refresh()
End Sub
Private Sub timerUpdate_Tick(sender As Object, e As EventArgs)
Dim key_shift As Integer = GetKeyPress(Keys.ShiftKey) AndAlso GetKeyPress(Keys.ControlKey)
Static key_shift_down As Boolean = False
Static mousePosKeep As New Point()
Static mousePosLast As New Point()
If GetKeyPress(Keys.ShiftKey) AndAlso GetKeyPress(Keys.ControlKey) = KEY_DOWN Then
If (Not key_shift_down) Then
'keep mouse position
mousePosKeep.X = Control.MousePosition.X
mousePosKeep.Y = Control.MousePosition.Y
'Move Form to mouse
Me.Left = mousePosKeep.X
Me.Top = mousePosKeep.Y
'Set Key Shift To True
key_shift_down = True
'Make Form Vissible
Me.Opacity = 1.0
'this help the form to show in game when it's full screen
'If call again make top the form And you can see it !!! :)
Me.TopMost = True
Console.WriteLine("key Shift+Controls Press Down")
End If
'Draw rectangle on mouse move
'Move Size Form Left , Width
If (Control.MousePosition.X - mousePosKeep.X) > -1 Then
Me.Left = mousePosKeep.X
Me.Width = (Control.MousePosition.X - mousePosKeep.X)
Else
Me.Left = Control.MousePosition.X
Me.Width = (mousePosKeep.X - Control.MousePosition.X)
End If
'Move Size Form Top , Height
If (Control.MousePosition.Y - mousePosKeep.Y) > -1 Then
Me.Top = mousePosKeep.Y
Me.Height = Control.MousePosition.Y - mousePosKeep.Y
Else
Me.Top = Control.MousePosition.Y
Me.Height = mousePosKeep.Y - Control.MousePosition.Y
End If
Console.WriteLine("Key Shift+Controls is Down")
Else
If key_shift_down = True Then
'hide form finish when shift up
Me.Opacity = 0.0
'nake shift to false
key_shift_down = False
'Do your stuff when finish
'
'
Console.WriteLine("Key Shift+Controls Press Up")
End If
'Draw Small Point To see where is the mouse when mouse is move
If (mousePosLast.X <> Control.MousePosition.X And mousePosLast.Y <> Control.MousePosition.Y) Then
mousePosLast.X = Control.MousePosition.X
mousePosLast.Y = Control.MousePosition.Y
Me.Width = 5
Me.Height = 5
Me.Opacity = 1.0
Me.TopMost = True
Me.Left = Control.MousePosition.X
Me.Top = Control.MousePosition.Y
Me.Cursor = Cursors.Cross
Console.WriteLine("Key Shift+Controls Up")
Else
Me.Opacity = 0.0
End If
End If
End Sub
thank you

How can I use collision detection with spawned arrays

Since I have been trying to make a space invaders style game I have been having trouble with collision detection with spawned objects in arrays (and having a bit of trouble with the bullets, they keep stopping and having another generate). I am new at coding and would like some help with these issues, or at least some links to some forums that had the same thread question.
here is my code:
Public Class Form1
'global variables
Dim intAmountOfEnemys As Short = 9
Dim intRowsOfEnemys As Integer = 0 '**
Dim intAmountOfBullets As Integer = 0
Dim picEnemysWave1(intAmountOfEnemys) As PictureBox
Dim lblBullets As New Label
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Welcome_Screen.Hide()
Call EnemyWaves(picEnemysWave1)
End Sub
Sub PlayerMovement(ByVal sender As Object, ByVal e As KeyEventArgs) Handles MyBase.KeyDown
If e.KeyCode = Keys.A Then
If picShip.Right <= 0 Then
picShip.Left = 1567
Else
picShip.Left -= 10
End If
ElseIf e.KeyCode = Keys.D Then
If picShip.Left >= 1567 Then
picShip.Left = -15
Else
picShip.Left += 10
End If
ElseIf e.KeyCode = Keys.Space Then
Do
BulletGeneration(lblBullets)
Loop Until Keys.Space
lblBullets.Left = (picShip.Left + 7)
End If
End Sub
#Region "Enemy waves, Movement, and Properties"
Sub EnemyWaves(ByRef picEnemysWave1() As PictureBox)
'Enemy Generator
Const srtENEMYSPACING_Y As Short = 155
For intCounterForEnemys As Integer = 0 To intAmountOfEnemys
Dim intEnemySpacing As Integer = srtENEMYSPACING_Y * intCounterForEnemys
picEnemysWave1(intCounterForEnemys) = New PictureBox
picEnemysWave1(intCounterForEnemys).Location = New Point(42 + intEnemySpacing, 1)
picEnemysWave1(intCounterForEnemys).Image = My.Resources.enemy
picEnemysWave1(intCounterForEnemys).Width = 124
picEnemysWave1(intCounterForEnemys).Height = 84
picEnemysWave1(intCounterForEnemys).Show()
Me.Controls.Add(picEnemysWave1(intCounterForEnemys))
Next intCounterForEnemys
End Sub``
Private Sub TmrAlien1_Tick(sender As Object, e As EventArgs) Handles TmrAlien1.Tick
For intRandom As Integer = 0 To 9
picEnemysWave1(intRandom).Top += 3
Dim intRandomNum As Integer = Rnd()
If intRandomNum > 0.66 Then
picEnemysWave1(intRandom).Left += 2 'goes left randomly
ElseIf intRandomNum < 0.33 Then
picEnemysWave1(intRandom).Left -= 2 'goes right randomly
End If
If picEnemysWave1(intRandom).Top <= 0 Then
TmrAlien1.Start()
End If
If picEnemysWave1(intRandom).Top >= 952 Then
TmrAlien1.Stop()
End If
Next intRandom
End Sub
#End Region
#Region "Bullet Generation, Movement, and Properties"
Sub BulletGeneration(ByRef lblBullets As Object)
'Generation of Bullets
For intBulletCounter As Integer = 0 To intAmountOfBullets
lblBullets = New Label
lblBullets.location = New Point(760, 785)
lblBullets.image = My.Resources.blast2
lblBullets.width = 32
lblBullets.height = 64
lblBullets.show()
Me.Controls.Add(lblBullets)
Next intBulletCounter
End Sub
Private Sub tmrBullets_Tick(sender As Object, e As EventArgs) Handles tmrBullets.Tick
lblBullets.Top -= 20
End Sub
#End Region
#Region "Collision Detection"
Sub BulletCollision(ByRef lblBullets As Label, ByRef intAmontOfEnemys As Integer)
For Each picEnemy As PictureBox In picEnemysWave1
If lblBullets.Bounds.IntersectsWith(picEnemy.Bounds) Then
picEnemy.Location = New Point(3900, 8700)
Exit For
End If
Next
'what Im trying
End Sub
#End Region

Collision detection in vb.net

I am trying to recreate Copter in visual basic, so far I have the player, roof and helicopter but I can't seem to get the game to end when the player touches the floor or roof. Sorry for posting so much, this is my first time on here and I didn't know what to paste. Any help is appreciated :D
Public Class Form1
Dim pb_field As PictureBox
Private Sub create_field()
pb_field = New PictureBox
With pb_field
.Top = 20
.Left = 20
.Width = 500
.Height = 300
.BackColor = Color.Black
End With
Me.Controls.Add(pb_field)
pb_field.BringToFront()
End Sub
Dim pb_player As PictureBox
Private Sub create_player()
pb_player = New PictureBox
With pb_player
.Width = 20
.Height = 20
.BackColor = Color.Red
.Top = pb_field.Top + pb_field.Bottom / 2
.Left = pb_field.Left + 20
End With
Me.Controls.Add(pb_player)
pb_player.BringToFront()
End Sub
#Region "Roof Stuff"
Dim roof(10000) As PictureBox
Dim num_of_roof As Integer = -1
Dim r As New Random
Private Sub create_roof()
num_of_roof += 1
roof(num_of_roof) = New PictureBox
With roof(num_of_roof)
.Top = pb_field.Top
.Left = pb_field.Right
.Height = r.Next(20, 40)
.Width = 20
.BackColor = Color.RoyalBlue
End With
Me.Controls.Add(roof(num_of_roof))
roof(num_of_roof).BringToFront()
End Sub
#End Region
#Region "floor Stuff"
Dim floor(10000) As PictureBox
Dim num_of_floor As Integer = -1
Private Sub create_floor()
num_of_floor += 1
floor(num_of_floor) = New PictureBox
With floor(num_of_floor)
.Left = pb_field.Right
.Height = r.Next(20, 40)
.Width = 20
.Top = pb_field.Bottom - floor(num_of_floor).Height
.BackColor = Color.YellowGreen
End With
Me.Controls.Add(floor(num_of_floor))
floor(num_of_floor).BringToFront()
End Sub
#End Region
Private Sub Form1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Me.KeyPress
Me.Text = e.KeyChar
If e.KeyChar = "w" Then
pb_player.Top -= 10
End If
**Dim collision As Boolean
For Each PictureBox In Me.Controls
If pb_player.Bounds.IntersectsWith(roof(num_of_roof).Bounds) Then
collision = True
Exit For
Else : collision = False
End If
If collision = True Then
MessageBox.Show("Unlucky,better luck next time!")
End If**
Next
End Sub
Private Sub form1_load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
create_field()
create_roof()
create_player()
tm_background.Start()
tm_gravity.Start()
End Sub
Private Sub tm_background_Tick(sender As Object, e As EventArgs) Handles tm_background.Tick
For i = 0 To num_of_roof
roof(i).Left -= 20
If roof(i).Left < pb_field.Left Then
Me.Controls.Remove(roof(i))
End If
Next
create_roof()
For i = 0 To num_of_floor
floor(i).Left -= 20
If floor(i).Left < pb_field.Left Then
Me.Controls.Remove(floor(i))
End If
Next
create_floor()
End Sub
Private Sub tm_gravity_Tick(sender As Object, e As EventArgs) Handles tm_gravity.Tick
pb_player.Top += 5
End Sub
This is the code I was attempting to use after looking online at possible solutions
Private Sub Form1_KeyPress(sender As Object, e As KeyPressEventArgs) HandlesMe.KeyPress
Me.Text = e.KeyChar
If e.KeyChar = "w" Then
pb_player.Top -= 10
End If
Dim collision As Boolean
For Each PictureBox In Me.Controls
If pb_player.Bounds.IntersectsWith(roof(num_of_roof).Bounds) Then
collision = True
Exit For
Else : collision = False
End If
If collision = True Then
MessageBox.Show("Unlucky,better luck next time!")
End If
Next
End Sub
Your problem is where you exit the for loop before displaying the message:
For Each PictureBox In Me.Controls
If pb_player.Bounds.IntersectsWith(roof(num_of_roof).Bounds) Then
collision = True
Exit For ' Note that exiting skips your check after the End If below
Else : collision = False
End If
' Whenever this is true you have already exited your 'for' loop
If collision = True Then
MessageBox.Show("Unlucky,better luck next time!")
End If
Next
Instead you need something like this where you evaluate the condition after the loop:
For Each PictureBox In Me.Controls
If pb_player.Bounds.IntersectsWith(roof(num_of_roof).Bounds) Then
collision = True
Exit For
Else : collision = False
End If
Next
If collision = True Then
MessageBox.Show("Unlucky,better luck next time!")
End If
First you need to set tag's in the floor and ceiling regions
With floor(num_of_floor)
.Tag = "boundaries"
Then you can refer to each picturebox in your controls
For Each box As PictureBox In Me.Controls
If box.Tag <> "boundaries" Then Continue For
If pb_player.Bounds.IntersectsWith(box.Bounds) Then
collision = True
Exit For
Else : collision = False
End If
Next
However, you are still going to have a problem that when it hits the floor it will not pass as a collision, because all this code is going on in the key press,
If a user lets the coptor fall, it will only lose the next time they click on the keyboard