很多遊戲都會用到拋物線運動,像大砲射擊、生氣鳥等,在這裡我們要運用國中學的物裡公式來實作程式碼。
很多遊戲都會用到拋物線運動,像大砲射擊、生氣鳥等,在這裡我們要運用國中學的物裡公式來實作程式碼。
Vx = Vx
Vy = Vy + a*t
X = X + Vx*t
Y = Y + Vy*t + 1/2*a*t*^2
在Game1類別宣告相關變數
Public Class Game1
Inherits Microsoft.Xna.Framework.Game
Private WithEvents graphics As GraphicsDeviceManager
Private WithEvents spriteBatch As SpriteBatch
Dim ball As Texture2D
Dim position As Vector2 = New Vector2(0, 450) '位置
Dim velocity As Vector2 = New Vector2(7, -30) '速度 (pixel/frame)
Dim acceleration As Integer = 1 '加速度 (pixel/frame^2)
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
ball = Content.Load(Of Texture2D)("ball")
End Sub
我們在Update()裡實作物裡公式:
Vx = Vx
Vy = Vy + a*t
X = X + Vx*t
Y = Y + Vy*t + 1/2*a*t*^2
這裡時間 t = 1 frame
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
velocity.Y += acceleration
position.X += velocity.X
position.Y = position.Y + velocity.Y + CInt(0.5 * acceleration)
MyBase.Update(gameTime)
End Sub
在Draw()繪製小球
Protected Overrides Sub Draw(ByVal gameTime As GameTime)
GraphicsDevice.Clear(Color.CornflowerBlue)
' TODO: Add your drawing code here
spriteBatch.Begin()
spriteBatch.Draw(ball, position, Color.White)
spriteBatch.End()
MyBase.Draw(gameTime)
End Sub
程式執行結果如下,接下來是碰撞偵測喔! (範例下載)