Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Add the imposeMovementLimits() helper method to the PlayerManager class:
Private Sub imposeMovementLimits() Dim location as Vector2 = playerSprite.Location If location.X < playerAreaLimit.X Then location.X = playerAreaLimit.X End If If location.X > (playerAreaLimit.Right - playerSprite.Source.Width) Then location.X = (playerAreaLimit.Right - playerSprite.Source.Width) End If If location.Y < playerAreaLimit.Y location.Y = playerAreaLimit.Y End If If location.Y > (playerAreaLimit.Bottom - playerSprite.Source.Height) Then location.Y = (playerAreaLimit.Bottom - playerSprite.Source.Height) End If playerSprite.Location = location End Sub
Add the Update() method to the PlayerManager class:
Public Sub Update(gameTime As GameTime) PlayerShotManager.Update(gameTime) If Not Destroyed Then playerSprite.Velocity = Vector2.Zero shotTimer += CSng(gameTime.ElapsedGameTime.TotalSeconds) HandleKeyboardInput(Keyboard.GetState()) HandleGamepadInput(GamePad.GetState(PlayerIndex.One)) playerSprite.Velocity.Normalize() playerSprite.Velocity *= playerSpeed playerSprite.Update(gameTime) imposeMovementLimits() End If End Sub
Add a declaration to the Game1 class for the PlayerManager:
Private _playerManager As PlayerManager
In the LoadContent() method of the Game1 class, set up the PlayerManager, after the AsteroidManager is initialized:
_playerManager = New PlayerManager( spriteSheet, New Rectangle(0, 150, 50, 50), 3, New Rectangle( 0, 0, Me.Window.ClientBounds.Width, Me.Window.ClientBounds.Height))
In the Update() method of the Game1 class, add an update line for the PlayerManager, right after the AsteroidManager is updated:
_playerManager.Update(gameTime)
Execute the game and fly your star fighter around in the asteroid field. Fire off a few shots with your cannon!
The imposeMovementLimits() method begins by making a copy of the playerSprite's Location property. Since Location is a property and not a public member, we cannot modify the components of the vector (X and Y) individually. Creating a temporary copy allows us to independently modify these values, and then save the whole vector back to the property.