Enemy-Player Collision
Our enemy versus player collision detection starts with us getting our player’s unscaled x position. We’ll store that value in d.
CheckEnemyPlayerCollision::
; Get our player's unscaled x position in d
ld a, [wPlayerPositionX]
ld d, a
ld a, [wPlayerPositionX+1]
ld e, a
srl e
rr d
srl e
rr d
srl e
rr d
srl e
rr d
With our player’s x position in d, we’ll compare it against a previously saved enemy x position variable. If they are more than 16 pixels apart, we’ll jump to the “NoCollisionWithPlayer” label.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Check the x distances. Jump to 'NoCollisionWithPlayer' on failure
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ld a, [wCurrentEnemyX]
ld [wObject1Value], a
ld a, d
ld [wObject2Value], a
; Save if the minimum distance
ld a, 16
ld [wSize], a
call CheckObjectPositionDifference
ld a, [wResult]
and a
jp z, NoCollisionWithPlayer
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
After checking the x axis, if the code gets this far there was an overlap. We’ll do the same for the y axis next.
We’ll get the player’s unscaled y position. We’ll store that value in d for consistency.
; Get our player's unscaled y position in d
ld a, [wPlayerPositionY+0]
ld d, a
ld a, [wPlayerPositionY+1]
ld e, a
srl e
rr d
srl e
rr d
srl e
rr d
srl e
rr d
Just like before, we’ll compare our player’s unscaled y position (stored in d) against a previously saved enemy y position variable. If they are more than 16 pixels apart, we’ll jump to the “NoCollisionWithPlayer” label.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Check the y distances. Jump to 'NoCollisionWithPlayer' on failure
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ld a, [wCurrentEnemyY]
ld [wObject1Value], a
ld a, d
ld [wObject2Value], a
; Save if the minimum distance
ld a, 16
ld [wSize], a
call CheckObjectPositionDifference
ld a, [wResult]
and a
jp z, NoCollisionWithPlayer
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
The “NoCollisionWithPlayer”, just set’s the “wResult” to 0 for failure. If overlap occurs on both axis, we’ll isntead set 1 for success.
ld a, 1
ld [wResult], a
ret
NoCollisionWithPlayer::
xor a
ld [wResult], a
ret
That’s the enemy-player collision logic. Callers of the function can simply check the “wResult” variable to determine if there was collision.