動畫是由隨著時間改變的圖片所組成,由於XNA不支援gif圖片格式,所以我們要用簡單的程式技巧將2D圖片顯示成動畫。
動畫是由隨著時間改變的圖片所組成,由於XNA不支援gif圖片格式,所以我們要用簡單的程式技巧將2D圖片顯示成動畫。
我們要先準備一張走路動畫的分解圖片
將這Map.png、WizardSheet.png兩張圖片加入專案
Game1類別宣告的變數
Public Class Game1
Inherits Microsoft.Xna.Framework.Game
Private WithEvents graphics As GraphicsDeviceManager
Private WithEvents spriteBatch As SpriteBatch
Dim map As Texture2D '地圖
Dim mapPosition As Vector2 = New Vector2(0, 0) '地圖位置
Dim wizard As Texture2D '巫師
Dim wizardPosition As Vector2 = New Vector2(100, 100) '巫師位置
Dim frameSize As Point = New Point(128, 192) '每張小圖的大小 (寬x高)
Dim frameSheet As Point = New Point(5, 0) '小圖片個數 (欄x列) 陣列從0開始
Dim currentFrame As Point = New Point(0, 0) '當前小圖片位置 (i,j)
Dim timeFrame As Integer = 0 '調整動畫速度:累積時間用
Dim timePerFrame As Integer = 100 '調整動畫速度:每隔100毫秒換下一張動畫圖片
End Class
LoadContent()載入圖片資源,包含地圖跟巫師
Protected Overrides Sub LoadContent()
' Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = New SpriteBatch(GraphicsDevice)
' TODO: use Me.Content to load your game content here
map = Content.Load(Of Texture2D)("Map")
wizard = Content.Load(Of Texture2D)("WizardSheet")
End Sub
動畫的程式重點就在Update(),動畫的圖片輪播就寫在這
Protected Overrides Sub Update(ByVal gameTime As GameTime)
' Allows the game to exit
If GamePad.GetState(PlayerIndex.One).Buttons.Back = ButtonState.Pressed Then
Me.Exit()
End If
' TODO: Add your update logic here
timeFrame += gameTime.ElapsedGameTime.Milliseconds '累加時間 (毫秒)
If timeFrame > timePerFrame Then '大於100毫秒輪播圖片,可自行調整時間
timeFrame = 0
currentFrame.X += 1
If currentFrame.X >= frameSheet.X Then
currentFrame.X = 0
End If
End If
MyBase.Update(gameTime)
End Sub
最後將圖片繪製出來
Protected Overrides Sub Draw(ByVal gameTime As GameTime)
GraphicsDevice.Clear(Color.CornflowerBlue)
' TODO: Add your drawing code here
spriteBatch.Begin()
spriteBatch.Draw(map, mapPosition, Color.White)
spriteBatch.Draw(wizard, wizardPosition, New Rectangle(currentFrame.X * frameSize.X,currentFrame.Y * frameSize.Y, frameSize.X, frameSize.Y), Color.White)
spriteBatch.End()
MyBase.Draw(gameTime)
End Sub
這邊要特別說明的是,這裡我們用的SpriteBate.Draw()的另一個多載,第三個參數是Rectangle(x,y,w,h),也就是下圖紅框的矩形,坐標跟長寬。
程式執行結果如下,接下來是2D運動喔! (程式下載)