Reputation: 742
I am practicing with SpriteKit with simple player movement when the user tilts the device. However I want the player to no be able to go off the screen, but when I try to change the y position to the frame.MaxY(or minY) it just keeps going. The code below is what I call inside the update function.
if let accelerometerData = motionManager.accelerometerData {
player.position.y += CGFloat(accelerometerData.acceleration.x * 50)
if(player.position.y < frame.minY) {
player.position.y = frame.minY
} else if(player.position.y > frame.maxY) {
player.position.y = frame.maxY
}
}
Upvotes: 1
Views: 74
Reputation: 8507
Take the size of the player into account like so (pseudocode)
if let accelerometerData = motionManager.accelerometerData {
player.position.y += CGFloat(accelerometerData.acceleration.x * 50)
if (player.position.y < frame.minY) {
player.position.y = frame.minY // <- maybe need some adjustment here too
} else if(player.position.y > frame.maxY - player.size.height) {
player.position.y = frame.maxY - player.size.height
}
}
Upvotes: 2