In Article 16, we had animated a sprite.
Now lets enhance the demo with a 2d camera following our character creating a simple scrolling effect.
Note : a next article will cover parallax scrolling.
We will simply had a camera class.
Lets declare our camera,
then instantiate it in loadcontent passing the width and height,
cam = New camera(graphics.GraphicsDevice.Viewport.Width, graphics.GraphicsDevice.Viewport.Height)
update it,
cam.setfocalpoint(New Vector2(dest_box.X, dest_box.Y), New Vector2(graphics.PreferredBackBufferWidth * 1.5 + 32, graphics.PreferredBackBufferHeight * 1.5 + 32))
cam.update()
and finally use it in our draw method thru a parameter in the spritebatch.begin method
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, Nothing, Nothing, Nothing, Nothing, cam.viewmatrix)
The camera class is itself extremely simple (note that we will manage zoom and rotation also later)
Imports Microsoft.Xna.Framework
Public Class camera
Public position As Vector2
Public viewmatrix As Matrix
Dim _screenx As Integer
Dim _screeny As Integer
Public Sub New(SizeX As Integer, sizeY As Integer)
_screenx = SizeX
_screeny = sizeY
End Sub
Public Sub setfocalpoint(focalposition As Vector2)
position = New Vector2(focalposition.X - _screenx / 2, focalposition.Y - _screeny / 2)
If position.X < 0 Then position.X = 0
If position.Y < 0 Then position.Y = 0
End Sub
Public Sub setfocalpoint(ByVal focalposition As Vector2, ByVal lock As Vector2)
If focalposition.X > lock.X Then focalposition.X = lock.X
If focalposition.Y > lock.Y Then focalposition.Y = lock.Y
position = New Vector2(focalposition.X - _screenx / 2, focalposition.Y - _screeny / 2)
If position.X < 0 Then position.X = 0
If position.Y < 0 Then position.Y = 0
End Sub
Public Sub update()
viewmatrix = Matrix.CreateTranslation(New Vector3(-position, 0))
End Sub
End Class
The video illustrating this.
The source code.
xna_demo_23.2