Post by u9 on Sept 1, 2007 11:23:32 GMT -5
Here's an example of how one can do 8-directional controls in games, i.e. where the player avatar can move in 8 different direction. It uses a little trigonometry to calculate where the player should move and what frame to use (if using different images for the different directions).
graphics.initialize 800, 600
graphics.settitle "Use arrows to move player"
font = graphics.createfont( "system", 10 )
key.initialize
playerX = 400
playerY = 300
speed = 4
Do While Not key.pressed( vk_escape ) Or key.pressed( vk_windowx )
If key.pressed( vk_right ) Then
x = 1
ElseIf key.pressed( vk_left ) Then
x = -1
Else
x = 0
End If
If key.pressed( vk_up ) Then
y = 1
ElseIf key.pressed( vk_down ) Then
y = -1
Else
y = 0
End If
' If no key pressed then use "" as No-direction
If x <> 0 Or y <> 0 Then
angle = GetDirection( x, y )
dir = angle / (2*pi) ' dividing by 2pi gives dir the range of [0,1[
dir = round( dir * 8 ) ' Quantize dir to one of 8 possible directions, 0 facing right
Else
dir = ""
End If
' With the direction calculated, we can move the player in that direction
If dir > "" Then
playerX = playerX + cos(angle) * speed
playerY = playerY - sin(angle) * speed
End If
graphics.clear
graphics.settext "Frame index to use: " & dir, 10, 10, font, &hFFFFFFFF
graphics.settext "O", playerX, playerY, font, &hFFFFFFFF
graphics.display
graphics.setfps 60
Loop
Public Function GetDirection(ByVal xVelocity, ByVal yVelocity)
Dim Direction
If xVelocity < 0 Then
Direction = Pi + Atn(yVelocity / xVelocity)
ElseIf xVelocity > 0 Then
Direction = Atn(yVelocity / xVelocity)
If Direction < 0 Then
Direction = Direction + 2*Pi
End If
ElseIf yVelocity <= 0 Then
Direction = 3*Pi/2
Else
Direction = Pi/2
End If
GetDirection = Direction
End Function