I cannot figure out how to move an image from one picturebox to another inside a grid of pictureboxes (all of the pictureboxes are created in an 2 dimensional array, for x and y ) with WASD/arrow keys. Is there a way I can assign each picturebox with co ordinates where I can manipulate it to change in the image in the pictureboxes to give the illusion of movement?
For example: program starts with picturebox (3,3) to have the player image set and a variable called "CurrentPicBox = picturebox(Xpos,Ypos)" ; User presses W/Up arrow; this makes the picturebox (that has the player image set) to clear the image and makes "CurrentPicBox = picturebox(Xpos, Ypos + 1). Which then makes the picturebox(3,4) have the image set.
Would this work or is this logic incorrect?
Your logic should work just fine! Although I think it would be easier to manage if you'd use (0, 0) as the top-left corner and (4, 4) as the bottom-right one.
Moving the player would then be:
Up: (Xpos, Ypos - 1)
Down: (Xpos, Ypos + 1)
Left: (Xpos - 1, Ypos)
Right: (Xpos + 1, Ypos)
Here's an example class for creating and using a game grid:
Public NotInheritable Class GameBoard
'The size of each picture box.
Public Shared ReadOnly GameTileSize As New Size(16, 16)
'The 2D array holding our grid.
Private Grid As PictureBox(,)
Private PosX As Integer = 0
Private PosY As Integer = 0
Public Sub MovePlayer(ByVal Direction As MovementDirection)
Select Case Direction
Case MovementDirection.Left
If PosX - 1 < 0 Then Return 'Error checking. Cannot move outside grid.
Grid(PosX - 1, PosY).Image = Grid(PosX, PosY).Image 'Move image to the left.
Grid(PosX, PosY).Image = Nothing 'Clear the current picture box.
PosX -= 1
Case MovementDirection.Right
If PosX + 1 >= Grid.GetLength(0) Then Return
Grid(PosX + 1, PosY).Image = Grid(PosX, PosY).Image
Grid(PosX, PosY).Image = Nothing
PosX += 1
Case MovementDirection.Up
If PosY - 1 < 0 Then Return
Grid(PosX, PosY - 1).Image = Grid(PosX, PosY).Image
Grid(PosX, PosY).Image = Nothing
PosY -= 1
Case MovementDirection.Down
If PosY + 1 >= Grid.GetLength(1) Then Return
Grid(PosX, PosY + 1).Image = Grid(PosX, PosY).Image
Grid(PosX, PosY).Image = Nothing
PosY += 1
End Select
End Sub
Public Sub New(ByVal Container As Container, ByVal PlayerSprite As Image, ByVal TilesX As Integer, ByVal TilesY As Integer) As PictureBox(,)
'Initialize our array.
Grid = New PictureBox(TilesX - 1, TilesY - 1) {}
'Iterate every "coordinate" and add a game tile to it.
For x = 0 To TilesX - 1
For y = 0 To TilesY - 1
'Create a tile of the appropriate size and place it at a location that is a multiple of its size.
Dim Tile As New PictureBox() With {
.Size = GameBoard.GameTileSize,
.Location = New Point(x * GameBoard.GameTileSize.X, y * GameBoard.GameTileSize.Y),
.BorderStyle = BorderStyle.FixedSingle 'Add a border to the tile.
}
'Add the tile to our array.
Grid(x, y) = Tile
'Add the tile to the specified container.
Container.Controls.Add(Tile)
Next
Next
'Place the player at the initial coordinates.
Grid(PosX, PosY).Image = PlayerSprite
End Sub
Public Enum MovementDirection As Integer
Left = 0
Right
Up
Down
End Enum
End Class
Then you can use it like so:
'The variable holding our game board.
Dim Board As GameBoard
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Create the grid inside the form (Me), 4 tiles tall and wide.
Board = New GameBoard(Me, My.Resources.Player, 4, 4)
End Sub
Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
'Handle movement.
Select Case e.KeyCode
Case Keys.Left, Keys.A : Board.MovePlayer(MovementDirection.Left)
Case Keys.Right, Keys.D : Board.MovePlayer(MovementDirection.Right)
Case Keys.Up, Keys.W : Board.MovePlayer(MovementDirection.Up)
Case Keys.Down, Keys.S : Board.MovePlayer(MovementDirection.Down)
End Select
End Sub
Replace My.Resources.Player with your actual player sprite.
Related
I have some images of document and book covers and those are displayed using pictureboxes in a Table layout panel.
Image excerpt from winform app
I am following this code
(From: https://social.msdn.microsoft.com/Forums/vstudio/en-US/da545e8e-e059-4681-9893-6d5dbdf6eba6/drop-shadow-around-the-image-in-picturebox?forum=vbgeneral)
to make picturebox work as a button when clicked and open the desired book or document.
Public Enum ShadowPosition As Integer
TopLeft = 0
TopRight = 1
BottomLeft = 2
BottomRight = 3
End Enum
Private Sub AddImageWithShadow(ByVal img As System.Drawing.Image, ByVal area As ShadowPosition, ByVal thickness As Integer, ByVal clr As Color, ByVal PicBox As PictureBox)
Using bm As New Bitmap(img.Width + thickness, img.Height + thickness)
Using gr As Graphics = Graphics.FromImage(bm)
Dim ix, iy As Integer
Dim rect As New Rectangle(thickness, thickness, img.Width, img.Height)
If area = ShadowPosition.TopLeft Or area = ShadowPosition.TopRight Then
iy = thickness
rect.Y = 0
End If
If area = ShadowPosition.TopLeft Or area = ShadowPosition.BottomLeft Then
ix = thickness
rect.X = 0
End If
gr.FillRectangle(New SolidBrush(clr), rect)
gr.DrawImage(img, ix, iy)
End Using
If PicBox.Image IsNot Nothing Then PicBox.Image.Dispose()
PicBox.Image = New Bitmap(bm)
End Using
End Sub
I tried to change the position of image:
Picturebox1.Location = New Point(10, 10)
Is there a way someone could guess to redarw picturebox at some offset without its drop shadow and back to initial state.
I'm designing a hexagon grid and I need to be able to name each hexagon, so I can refer to them later. Below is my class, it generates the hexagon grid, and I've labeled the code throughout so you can understand what's happening.
I've been searching for a while now reading a lot about Graphics, but I can't get a working design with the answers I've seen offered. Perhaps, I'm going about this wrong by using Graphics, but my plan is to be able to click on each hexagon and do something with it.
Note: If you see a way to improve my code let me know. It's appreciated!
' Generate Hexagon Grid
Private Sub Form1_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint
' Hexagon Grid Parameters
Dim HexagonRadius As Integer = 20 ' Fix "Position Hexagon Grid Columns" Before Changing Hexagon Radius
Dim GridSize As Integer = 10
' Generate Hexagon Grid
Dim HexagonX As Integer = HexagonRadius
Dim HexagonY As Integer = HexagonRadius
For i As Integer = 1 To GridSize
For j As Integer = 1 To GridSize
' Hexagon Vertex Coordinates
Dim point1 As New Point((HexagonX - HexagonRadius), (HexagonY))
Dim point2 As New Point((HexagonX - (HexagonRadius / 2)), (HexagonY + ((HexagonRadius / 2) * Math.Sqrt(3))))
Dim point3 As New Point((HexagonX + (HexagonRadius / 2)), (HexagonY + ((HexagonRadius / 2) * Math.Sqrt(3))))
Dim point4 As New Point((HexagonX + HexagonRadius), (HexagonY))
Dim point5 As New Point((HexagonX + (HexagonRadius / 2)), (HexagonY - ((HexagonRadius / 2) * Math.Sqrt(3))))
Dim point6 As New Point((HexagonX - (HexagonRadius / 2)), (HexagonY - ((HexagonRadius / 2) * Math.Sqrt(3))))
Dim hexagonPoints As Point() = {point1, point2, point3, point4, point5, point6}
' Create Hexagon
e.Graphics.FillPolygon(Brushes.Green, hexagonPoints)
' Hexagon Outline
e.Graphics.DrawLine(Pens.Black, point1, point2)
e.Graphics.DrawLine(Pens.Black, point2, point3)
e.Graphics.DrawLine(Pens.Black, point3, point4)
e.Graphics.DrawLine(Pens.Black, point4, point5)
e.Graphics.DrawLine(Pens.Black, point5, point6)
e.Graphics.DrawLine(Pens.Black, point6, point1)
' Position Hexagon Grid Columns
HexagonY += 34 ' Specific to Hexagon Radius: 20
Next
If i Mod 2 > 0 Then
HexagonY = 36.75 ' Specific to Hexagon Radius: 20
Else
HexagonY = 20 ' Specific to Hexagon Radius: 20
End If
HexagonX += 30 ' Specific to Hexagon Radius: 20
Next
End Sub
You'll need to create some Hexagon class with it's coordinates and (maybe name, if really needed). And save them to some suitable collection (2-dimensional array maybe?)
This should happen somewhere outside your Paint event and might be recalculated on grid SizeChanged event.
Inside your Paint event you'll just iterate throught existing collection and render according to pre-computed coordinates.
OnClick event will loop throught the same collection to find specific Hexagon for updating (changing background color for example) and forcing form to repaint to take effect.
For large rendering you should consider rendering to bitmap first and drawing that final bitmap to e.Graphics for faster work. Your bitmap could be cached as well to speed up even more.
EDIT: Code sample added
Turn Option Strict On in your project properties to avoid many problems in your code that you're not aware of.
Public Class frmTest
Private Const HexagonRadius As Integer = 20
Private Const GridSize As Integer = 10
Private fHexagons As New List(Of Hexagon)
Private fCache As Bitmap
Private fGraphics As Graphics
Private Sub ResetHexagons() 'Call when some parameter changes (Radius/GridSize)
fHexagons.Clear()
Invalidate()
End Sub
Private Function EnsureHexagons() As List(Of Hexagon)
Dim X, Y As Single, xi, yi As Integer
If fHexagons.Count = 0 Then
X = HexagonRadius : Y = HexagonRadius
For xi = 1 To GridSize
For yi = 1 To GridSize
fHexagons.Add(New Hexagon(HexagonRadius, X, Y))
Y += 34
Next
'Do your math to get theese values from HexagonRadius value
If xi Mod 2 > 0 Then
Y = 36.75
Else
Y = 20
End If
X += 30
Next
fCache?.Dispose()
fGraphics?.Dispose()
fCache = New Bitmap(GridSize * HexagonRadius * 2, GridSize * HexagonRadius * 2)
fGraphics = Graphics.FromImage(fCache)
For Each H As Hexagon In fHexagons
H.Render(fGraphics)
Next
End If
Return fHexagons
End Function
Private Sub frmTest_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint
EnsureHexagons()
e.Graphics.DrawImageUnscaled(fCache, Point.Empty)
End Sub
Private Sub frmTest_MouseClick(sender As Object, e As MouseEventArgs) Handles Me.MouseClick
Dim H As Hexagon = EnsureHexagons.FirstOrDefault(Function(X) X.Contains(e.Location))
If H IsNot Nothing Then
H.Checked = Not H.Checked
H.Render(fGraphics) 'Update cache without repainting all
Invalidate()
End If
End Sub
End Class
Public Class Hexagon
Public ReadOnly Radius, X, Y As Single
Public ReadOnly Points() As PointF
Public Property Checked As Boolean
Public Sub New(Radius As Single, X As Single, Y As Single)
Me.Radius = Radius : Me.X = X : Me.Y = Y
Points = {New PointF((X - Radius), (Y)),
New PointF((X - (Radius / 2)), CSng(Y + ((Radius / 2) * Math.Sqrt(3)))),
New PointF((X + (Radius / 2)), CSng(Y + ((Radius / 2) * Math.Sqrt(3)))),
New PointF((X + Radius), (Y)),
New PointF((X + (Radius / 2)), CSng(Y - ((Radius / 2) * Math.Sqrt(3)))),
New PointF((X - (Radius / 2)), CSng(Y - ((Radius / 2) * Math.Sqrt(3.0!))))}
End Sub
Public Sub Render(G As Graphics)
' Create Hexagon
G.FillPolygon(If(Checked, Brushes.Blue, Brushes.Green), Points)
' Hexagon Outline
For i As Integer = 0 To Points.Length - 1
G.DrawLine(Pens.Black, Points(i), Points((i + 1) Mod Points.Length))
Next
End Sub
Public Function Contains(P As Point) As Boolean
'Do your math here, this is just simplified estimation
Return X - Radius <= P.X AndAlso P.X <= X + Radius AndAlso Y - Radius <= P.Y AndAlso P.Y <= Y + Radius
End Function
End Class
I'm trying to implement a small tool that draws sin and cos functions. The program is supposed to draw from the center of the form, so that the history will extend to the right. Imagine the following gif but with the right end of the line moving up and down, and the path to the left "showing the trace"
What I would like to do is, every time a timer elapses, draw a point (via Graphics.FillRectangle) in the center of a PictureBox. In the next timer fire move the graphics one pixel to the left, and draw the next pixel. This is what I have so far:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
bmp = New Drawing.Bitmap(PictureBox1.Size.Width, PictureBox1.Size.Height)
g1 = Graphics.FromImage(bmp)
MathTimer = New Timers.Timer(30)
AddHandler MathTimer.Elapsed, AddressOf OnTimedEvent
MathTimer.Enabled = True
MathTimer.Start()
End Sub
Private Sub OnTimedEvent(source As Object, e As System.Timers.ElapsedEventArgs)
g1.FillRectangle(Brushes.Red, PictureBox1.Size.Width \ 2, PictureBox1.Size.Height \ 2, 1, 1)
g1.TranslateTransform(-1, 0)
PictureBox1.Image = bmp
End Sub
However, this doesn't achieve the desired effect, since the canvas of the graphics object g1 is moved to the left with this. Eventually it's not drawing anymore. (No wonder, since with this I'm drawing "with the left end of the line")
Anybody have a better idea that achieves the desired effect?
For i As Integer = 0 To pointsToDraw.Count - 2
Dim p As Point = pointsToDraw(i)
Dim xPos As Integer = (pctrBxSinCosDraw.Width / 2) + p.X - currentTick
e.Graphics.FillRectangle(Brushes.Black, xPos, CInt(p.Y + pctrBxSinCosDraw.Height / 2), 1, 1)
If xPos <= 0 Then
pointsToDraw.RemoveAt(i)
End If
Next
Where currentTick is set by a Timer, which on Tick, calculates the x/y values:
Dim yVal As Double
If useSinCalc Then
yVal = Math.Sin(DegreeToRadian(currentTick)) * (180 / Math.PI)
Else
yVal = Math.Cos(DegreeToRadian(currentTick)) * (180 / Math.PI)
End If
pointsToDraw.Add(New Point(currentTick, yVal))
currentTick += 1
pctrBxSinCosDraw.Invalidate()
And DegreeToRadian simply does (as it states):
Private Function DegreeToRadian(ByVal angle As Double)
DegreeToRadian = Math.PI * angle / 180.0
End Function
And pointsToDraw is List(Of Point)
A sample project can be found on my download page.
I am writing a snake game in visual studio in visual basic.
The playing field is a 2D Array of PictureBoxes. My Snake is a 1D array as type Point. The snake array is called 'Snake'.
When the form loads, Snake(0) is set as New Point(1, 1). I have created a sub routine that moves the snake depending on the arrow key the user presses. This is under a timer. Snake(0) (The snake head) is set to equal Snake(0) + direction (direction is a variable altered by the arrow key that the user presses, eg. when up is pressed direction is set to x: 0 and y: -1)
When snake(0) hits a piece of food, the amount of elements in the snake array is set to the length of the array. EG(If snake(0) = foodPosition Then ReDim Preserve snake(snake.Length) End If)
I have created a loop, also under the timer, to make the body of the snake follow the head (eg. snake(2) = snake(1) and snake(1) = snake(0) but can't get it to work)
Code:
Public Class frmPlayfield
'Food Creating and Grow Snake Variables
Dim randF As New Random
Dim foodPointX As Integer = randF.Next(0, 32)
Dim foodPointY As Integer = randF.Next(0, 32)
'Play Field Variables
Dim playMaxWidth As Integer = 32
Dim playMaxHeight As Integer = 32
Dim boxSize As Integer = 16 'Size of PictureBox
Dim boxArray(,) As PictureBox 'PictureBox Array
'Snake Stuff Variable
Dim snake(1) As Point 'Snake array
Dim direction As New Point(1, 0) 'Direction for snake movement
Private Sub frmPlayfield_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ReDim boxArray(playMaxWidth, playMaxHeight)
For x As Integer = 0 To playMaxWidth
For y As Integer = 0 To playMaxHeight
boxArray(x, y) = New PictureBox
boxArray(x, y).Width = boxSize
boxArray(x, y).Height = boxSize
boxArray(x, y).Top = y * boxSize
boxArray(x, y).Left = x * boxSize
boxArray(x, y).Visible = True
boxArray(x, y).BackColor = Color.White
boxArray(x, y).BorderStyle = BorderStyle.FixedSingle
Me.Controls.Add(boxArray(x, y))
Next
Next
Me.ClientSize = New Size((playMaxWidth + 1) * boxSize, (playMaxHeight + 1) * boxSize)
snake(0) = New Point(1, 1) 'Creates snake head
boxArray(foodPointX, foodPointY).BackColor = Color.Red
End Sub
Private Function createBox(x As Integer, y As Integer, bSize As Integer) As PictureBox
Dim tempBox As New PictureBox
tempBox.Width = bSize
tempBox.Height = bSize
tempBox.Top = y * bSize
tempBox.Left = x * bSize
tempBox.Visible = True
tempBox.BackColor = Color.White
tempBox.BorderStyle = BorderStyle.FixedSingle
Me.Controls.Add(tempBox)
Return tempBox
End Function
Private Sub Food()
If snake(0).X = foodPointX And snake(0).Y = foodPointY Then
ReDim Preserve snake(snake.Length) 'Increases the amount of elements in the snake array.
For j As Integer = 0 To 0
foodPointX = randF.Next(0, 32)
foodPointY = randF.Next(0, 32)
boxArray(foodPointX, foodPointY).BackColor = Color.Red
Next
End If
For h As Integer = snake.Length - 1 To snake.GetUpperBound(0)
snake(h) = snake(snake.Length - 2)
Next
End Sub
Private Sub CheckBoundsAndMovement()
For i As Integer = 0 To snake.GetUpperBound(0)
boxArray(snake(i).X, snake(i).Y).BackColor = Color.White 'Loop to change the whole snake black
Next
snake(1) = snake(0)
snake(0) = snake(0) + direction
If snake(0).X > playMaxWidth Then
snake(0).X -= (playMaxWidth + 1)
End If
If snake(0).X < 0 Then
snake(0).X += (playMaxWidth + 1)
End If 'Four If statements to check if the snake has gone outside the play area.
If snake(0).Y > playMaxWidth Then
snake(0).Y -= (playMaxWidth + 1)
End If
If snake(0).Y < 0 Then
snake(0).Y += (playMaxWidth + 1)
End If
For k As Integer = 0 To snake.GetUpperBound(0)
boxArray(snake(k).X, snake(k).Y).BackColor = Color.Black 'Loop to make the whole snake black
Next
End Sub
Private Sub timGameTick_Tick(sender As Object, e As EventArgs) Handles timGameTick.Tick
Food()
CheckBoundsAndMovement()
End Sub
Private Sub frmPlayfield_KeyDown(sender As Object, e As KeyEventArgs) Handles MyBase.KeyDown 'Subroutine for direction
Select Case (e.KeyCode)
Case Keys.Up
direction = New Point(0, -1)
Case Keys.Down
direction = New Point(0, 1)
Case Keys.Left
direction = New Point(-1, 0)
Case Keys.Right
direction = New Point(1, 0)
End Select
End Sub
End Class
This works fine after I eat the first piece of food. The snake of length 2 is increased to length 3. But when I eat another piece of food the end of the snake is left behind at the spot where the food was eaten.
Ok - It looks like I found the problems -
First off - you defined the snake array as Dim snake (1) As Point this created the array with two elements instead of 1
Next, in your Food sub, the loop to roll the pixels back along the snake should be done every time the snake moves, not just when food is eaten. So I moved it into the CheckBoundsAndMovement sub to replace line 4 of that sub which only copied the location of the head to the next point back rather than the whole snake. But of course trying to execute the loop when the length of the snake was only one pixel would result in an out of range exception on the array, so added an If statement to only execute the loop if the length of snake is more than 1.
Also the direction of the loop in your code was in increasing order. To do it properly it should be in decreasing order. This way, the loop overwrites the point representing the end of the tail with the next point forward and so on. Finally, the new location for the head is entered into snake(0)
So - here it is -
Public Class frmPlayfield
'Food Creating and Grow Snake Variables
Dim randF As New Random
Dim foodPointX As Integer = randF.Next(0, 32)
Dim foodPointY As Integer = randF.Next(0, 32)
'Play Field Variables
Dim playMaxWidth As Integer = 32
Dim playMaxHeight As Integer = 32
Dim boxSize As Integer = 16 'Size of PictureBox
Dim boxArray(,) As PictureBox 'PictureBox Array
'Snake Stuff Variable
Dim snake(0) As Point 'Snake array
Dim direction As New Point(1, 0) 'Direction for snake movement
Private Sub frmPlayfield_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ReDim boxArray(playMaxWidth, playMaxHeight)
For x As Integer = 0 To playMaxWidth
For y As Integer = 0 To playMaxHeight
boxArray(x, y) = New PictureBox
boxArray(x, y).Width = boxSize
boxArray(x, y).Height = boxSize
boxArray(x, y).Top = y * boxSize
boxArray(x, y).Left = x * boxSize
boxArray(x, y).Visible = True
boxArray(x, y).BackColor = Color.White
boxArray(x, y).BorderStyle = BorderStyle.FixedSingle
Me.Controls.Add(boxArray(x, y))
Next
Next
Me.ClientSize = New Size((playMaxWidth + 1) * boxSize, (playMaxHeight + 1) * boxSize)
snake(0) = New Point(1, 1) 'Creates snake head
boxArray(foodPointX, foodPointY).BackColor = Color.Red
End Sub
Private Function createBox(x As Integer, y As Integer, bSize As Integer) As PictureBox
Dim tempBox As New PictureBox
tempBox.Width = bSize
tempBox.Height = bSize
tempBox.Top = y * bSize
tempBox.Left = x * bSize
tempBox.Visible = True
tempBox.BackColor = Color.White
tempBox.BorderStyle = BorderStyle.FixedSingle
Me.Controls.Add(tempBox)
Return tempBox
End Function
Private Sub Food()
If snake(0).X = foodPointX And snake(0).Y = foodPointY Then
ReDim Preserve snake(snake.Length)
foodPointX = randF.Next(0, 32)
foodPointY = randF.Next(0, 32)
boxArray(foodPointX, foodPointY).BackColor = Color.Red
End If
End Sub
Private Sub CheckBoundsAndMovement()
For i As Integer = 0 To snake.GetUpperBound(0)
boxArray(snake(i).X, snake(i).Y).BackColor = Color.White 'Loop to change the whole snake white
boxArray(snake(i).X, snake(i).Y).Update()
Next
If snake.Length > 1 Then
For i As Integer = snake.GetUpperBound(0) To 1 Step -1
snake(i) = snake(i - 1)
Next
End If
snake(0) = snake(0) + direction
If snake(0).X > playMaxWidth Then
snake(0).X -= (playMaxWidth + 1)
End If
If snake(0).X < 0 Then
snake(0).X += (playMaxWidth + 1)
End If 'Four If statements to check if the snake has gone outside the play area.
If snake(0).Y > playMaxWidth Then
snake(0).Y -= (playMaxWidth + 1)
End If
If snake(0).Y < 0 Then
snake(0).Y += (playMaxWidth + 1)
End If
For k As Integer = 0 To snake.GetUpperBound(0)
boxArray(snake(k).X, snake(k).Y).BackColor = Color.Black 'Loop to make the whole snake black
Next
End Sub
Private Sub timGameTick_Tick(sender As Object, e As EventArgs) Handles timGameTick.Tick
Food()
CheckBoundsAndMovement()
End Sub
Private Sub frmPlayfield_KeyDown(sender As Object, e As KeyEventArgs) Handles MyBase.KeyDown 'Subroutine for direction
Select Case (e.KeyCode)
Case Keys.Up
direction = New Point(0, -1)
Case Keys.Down
direction = New Point(0, 1)
Case Keys.Left
direction = New Point(-1, 0)
Case Keys.Right
direction = New Point(1, 0)
End Select
End Sub
End Class
In my simulation, the planet's colour is randomly chosen when it is created. The trail left behind is supposed to be the same colour as its planet. This works fine if there is just one planet, but when a new planet is added the trail for every planet is the same colour as that of the new planet. Here are some screenshots to demonstrate what I mean:https://imgur.com/a/EVh5o
I each planet to have a trail the same colour as itself, if that makes sense. Here are the relevant parts of my code:
Public Sub Form1_Paint(sender As Object, e As PaintEventArgs) Handles picSpace.Paint
For Each sun In sunsList
e.Graphics.FillEllipse(Brushes.Yellow, CInt(sun.positionX - 10), CInt(sun.positionY - 30), 20, 20)
Next
For Each planet In planetsList
Dim planetFill As Brush = New SolidBrush(planet.colour)
Dim trailColour As Pen = New Pen(planet.colour)
e.Graphics.FillEllipse(planetFill, planet.displayX - 5, planet.displayY - 5, 10, 10)
For count As Integer = 0 To counter
e.Graphics.DrawEllipse(trailColour, trail(0, count), trail(1, count), 1, 1)
Next
Next
End Sub
Sub Position()
planet.displayX = Math.Round(planet.positionX)
planet.displayY = Math.Round(planet.positionY)
trail(0, counter) = planet.displayX
trail(1, counter) = planet.displayY
counter += 1
ReDim Preserve trail(1, counter)
End Sub
Private Sub space_Click(sender As Object, e As EventArgs) Handles picSpace.Click
If hsbSimulationSpeed.Value > 0 Then
Timer1.Enabled = True
End If
If chkAddPlanets.Checked = True Then
planet = New Body
numberOfPlanets += 1
planet.colour = GetRandomColour()
planet.positionX = MousePosition.X
planet.positionY = MousePosition.Y - 25
planet.velocityX = txtVelocityX.Text * 1000
planet.velocityY = txtVelocityY.Text * 1000
planetsList.Add(planet)
ElseIf chkAddSuns.Checked = True Then
sun = New Body
numberOfSuns += 1
sun.positionX = MousePosition.X
sun.positionY = MousePosition.Y
sun.mass = hsbSunMass.Value * 5 * (10 ^ 29)
sunsList.Add(sun)
End If
End Sub
Function GetRandomColour() As Color
Dim rand As New Random
Return Color.FromArgb(rand.Next(0, 256), rand.Next(0, 256), rand.Next(0,
256))
End Function
Is there an easy way to fix this, or will I need to completely change the way trails are generated?
The problem is that you only have 1 trail() list, which is used for all planets. So in your painting loop, although the planet loop selects a different pen for each planet, they are all drawing in the same coordinates. The last planet will overwrite the first ones. Presumably trail() contains the coordinates from all planets - ie all trails listed together.
You need to have one trail list per planet, as part of the planet object to make it work.