I have implemented PlayerMovement code for my 2D tilebased RPG but when I press the direction keys the player sprite moves much further than just one tile. What am I missing to limit the movement?
starty = 0
startx = 0
PlayerX = 1
PlayerY = 5
mapsize = 32
` Main loop
do
cls 0
draw_map() `Draw Map on Screen\
playermovement() `Move the character.
sync
loop
`WAIT KEY
end
function draw_map() `*********************** Draw the game map ***************************
`Draw the map
for i = starty-1 to starty+21 `Slightly bigger than 21*21, in case of smooth scrolling later.
if i > -1 AND i < mapsize `If the tile would be bigger than the world, don't draw anything.
for j = startx-1 to startx+21
if j > -1 AND j < mapsize `Again - don't draw a tile if it's outside the world.
xposition = 5+(i*32) `Position of the tile in question. 5,5 is the top left hand corner of the HUD.
yposition = 5+(j*32)
paste sprite Map(i,j).tile,xposition,yposition
endif
next
endif
next
paste sprite 105,(PlayerX*32),(PlayerY*32) `Draw the Player Character!
endfunction
function playermovement() `****************** Controls the keys that move the character ********************
move = 0
Scroll$ = ""
if leftkey() = 1 `**** LEFT ****
moveX = PlayerX - 1
moveY = PlayerY
if Map(moveX,moveY).collides = 1 `We have collided with something solid.
CheckDoorCollision(MoveX,MoveY)
else `Otherwise, check against objects/critters.
move = 1
Scroll$ = "Left"
endif
endif
if rightkey() = 1 `**** RIGHT ****
moveX = PlayerX + 1
moveY = PlayerY
if Map(moveX,moveY).collides = 1 `We have collided with something solid.
CheckDoorCollision(MoveX,MoveY)
else `Otherwise, check against objects/critters.
move = 1
Scroll$ = "Right"
endif
endif
if upkey() = 1 `**** UP ****
moveX = PlayerX
moveY = PlayerY - 1
if Map(moveX,moveY).collides = 1 `We have collided with something solid.
CheckDoorCollision(MoveX,MoveY)
else `Otherwise, check against objects/critters.
move = 1
Scroll$ = "Up"
endif
endif
if downkey() = 1 `**** DOWN ****
moveX = PlayerX
moveY = PlayerY + 1
if Map(moveX,moveY).collides = 1 `We have collided with something solid.
CheckDoorCollision(MoveX,MoveY)
else `Otherwise, check against objects/critters.
move = 1
Scroll$ = "Down"
endif
endif
if move = 1
`do_turn
PlayerX = moveX
PlayerY = moveY
mapScroll(Scroll$)
endif
endfunction
function mapScroll(direction$)
Select direction$
case "Left"
if PlayerX - startX < 5
startX = PlayerX - 10
if startX < 0 then startX = 0
endif
endcase
case "Right"
if PlayerX - startX > 16
startX = PlayerX + 10
if startX > (mapsize - 10) then startX = (mapsize - 10)
endif
endcase
case "Up"
if PlayerY - startY < 5
startY = PlayerY - 10
if startY < 0 then startY = 0
endif
endcase
case "Down"
if PlayerY - startY > 16
startY = PlayerY + 10
if startY > (mapsize - 10) then startY = (mapsize - 10)
endif
endcase
endSelect
endfunction