Hi Matty, how's it all going.
I am sure someone will post an example. But what I can do is illustrate it.
According to your previous post, you have your character moving up, left, right and down. Thanks to Max P's help, you have your map sprites moving.
But what would happen if we disabled movement during a collision? The character would stop, thus collide.
Therefore, if the character is colliding with something, we need to stop it. How do we stop it? We use an if statement; so that if a collision exists, don't move. Infact, we also want the character to move back to the position where it did not collide, bouncing off an obstacle like in the real world.
So far you have the following:
if upkey()=1
rotate sprite Hero, 0
// Increase the y position virtual camera
dec camy, 1
rotate sprite Hero, 0
Heromove = 1
endif
if downkey()=1
rotate sprite Hero, 180
// Decrease the y position virtual camera
inc camy, 1
rotate sprite Hero, 0
Heromove = 2
endif
if leftkey()=1
rotate sprite Hero, 270
// Increase the x position virtual camera
dec camX, 1
rotate sprite Hero, 0
Heromove = 3
endif
if rightkey()=1
rotate sprite Hero, 90
// Decrease the x position virtual camera
inc camX, 1
rotate sprite Hero, 0
Heromove = 4
endif
(By the way, why do you need to rotate the sprite hero if you are already adjusting camX and camY without the [move sprite] command?)
Continuing:
We need to change
if downkey()=1
inc camY
endif
to
if downkey()=1
inc CamY ` Move down
if HeroIsColliding()
dec CamY ` Move back to where we were
endif
endif
And so on.
Now we are checking if there hero is colliding AFTER the move. If there is a collision, move back; like bouncing off a wall.
Finally, we need to create our HeroIsColliding() to return 1 (true) when there is a collision.
This part is up to you. You can use the [sprite collision] command, you could use a line collision or pixel collision function or you could check to see if the character is inside an area using
function SpriteWithin( id, top, left, right, bottom )
if sprite x(id) > left
if sprite y(id) > top
if sprite x(id) < right
if sprite y(id) < bottom then exitfunction 1
endif
endif
endif
endfunction 0
The CPU only needs to compare each co-ordinate if the previous one is true. Just call SpriteWithin( SpriteId, 0, 0, 200, 200) for example, and it will return true if a certain sprite is in the top left of the screen.
You can use the following to check collisions with your map sprites:
function CollisionCheck( id )
local collisionFound = 0
for i=0 to MapSpriteCount
collisionFound = sprite collision( mapSprite(i), id )
if collisionFound then exitfunction 1
next i
endfunction result
Note that sprite collision( Hero, 0 ) would return any sprite colliding with it; without the need of using for loops; which is also a true (non-zero) result. You just need to determine which sprites can collide and which sprites do not.