Reputation: 315
So first off, what I'm trying to do but clearly failing to is prevent a sprite "the player" from moving off the edge of the map "400x400px img".
The controls on the game are buttons for moving right, left, up and down. I have it so when the buttons are pressed it runs a function that checks if the player's destination is off the map's area.
****Note That the Map is a 5x5 grid map, each square of the grid is 80x80 inside map image****
Here's the function that checks if the player's destination is off the map:
func checkBordersDownPlayer() {
if player.position.y - 80 == map.position.y - 80 {
print("Node cannot move. Map borders are stopping the Node from moving past it's boundaries.")
}
else {
player.runAction(moveDown)
print("Player was able to move!")
}
}
Now what troubles me is that the player automatically ignores the print() functions and the if function but still runs the SKAction to move it.
Upvotes: 0
Views: 247
Reputation: 1027
What I could asses from your post is that perhaps you are not clear about the position concept of sprite node.
Unlike UIKit
in which position
of a frame is at the top left corner of the Rectangle
, in Spritekit
a node's position is at its center by default unless you will play with its anchor point
.
Again taking your situation into consideration, you should use the tools provided by Spritekit for efficiently handling such tasks, You should use Physics body around the map image and make your player another physics body assigning them different physics categories.
In your case you don't need to assign any contact test bit mask or collision bit mask untill you are not interested in getting informed when the player touches the boundary set by you. You can refer to this tutorial for more https://www.raywenderlich.com/123393/how-to-create-a-breakout-game-with-sprite-kit-and-swift
Hope this helps.
Upvotes: 1
Reputation: 3812
Without knowing more of how you calculate movement the best I can do is guess this is your problem.
player.position.y - 80 == map.position.y - 80
Instead you probably want something like this...
player.position.y - 80 <= map.position.y - 80
Hopefully that helps
edit
One step further would be to reset the players position too...
func checkBordersDownPlayer() {
if player.position.y - 80 <= map.position.y - 80 {
player.position.y = map.position.y - 80
print("Node cannot move. Map borders are stopping the Node from moving past it's boundaries.")
}
else {
player.runAction(moveDown)
print("Player was able to move!")
}
}
Upvotes: 0