One solution to Homework 8 is as follows. This includes a testbed in Main( ):
// A sprite which moves toward or away from a
point based on distance
Class GravitySprite
// The sprite object
Private Define sprite As Sprite
// How fast it moves: positive = toward, negative = away
Private Define attraction As Decimal
// Set up the sprite
Method Initialize(fileName As String, animTimeline As Integer[], xPos As Decimal, yPos As Decimal, power As Decimal)
sprite.Load(fileName)
sprite.AnimationTimeline = animTimeline
sprite.CenterAt(xPos, yPos)
sprite.Show()
attraction = power
End Method
// Calculates the distance between (xPos, yPos) and the center of sprite
Private Function DistanceFrom(xPos As Decimal, yPos As Decimal) As Decimal
Define xCenter As Decimal = sprite.X + sprite.Width / 2.0
Define yCenter As Decimal = sprite.Y + sprite.Height / 2.0
Return Math.Sqrt((xPos-xCenter) * (xPos-xCenter) + (yPos-yCenter) * (yPos-yCenter))
End Function
// Moves sprite toward/away from attraction point at (xPos, yPos)
Method MoveSprite(xPos As Decimal, yPos As Decimal)
Define point As Drawing.Point
point.X = xPos
point.Y = yPos
sprite.MoveToward(point, (attraction / (DistanceFrom(xPos,yPos) + 1)))
End Method
End Class
// Testbed for GravitySprite class
Method Main()
Define ufo As GravitySprite
Define anim As Integer[] = { 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100 }
ufo.Initialize("UFO.gif", anim, 50, 100, 150)
Define circle As Circle
Define point As Drawing.Point
point.X = 400
point.Y = 300
circle.Center = point
circle.Radius = 10
circle.Filled = True
circle.Draw()
// Game loop
While (Not IsKeyDown("ESC"))
ufo.MoveSprite(point.X, point.Y)
Delay(50)
RefreshScreen()
End While
End Method