Reputation: 9
I'm trying to make a game where you tilt your phone and try to keep the ball inside the boundary. I can't seem to figure out how to make the ball not go through the boundary. I have the tilt to move the ball working, but it just goes through all my boundaries and I can't seem to figure out how to make the ball stop when it comes in contact with a boundary. Here is my code:
override func didMove(to view: SKView) {
let border = SKPhysicsBody(edgeLoopFrom: self.frame)
self.physicsBody = border
boundary = (self.childNode(withName: "boundry") as! SKSpriteNode) //the boundary is spelled wrong
airplane = SKSpriteNode(imageNamed: "ball image")
airplane.physicsBody = SKPhysicsBody(circleOfRadius: 10)
airplane.position = CGPoint(x: -211.163, y: 367.3)
airplane.size = CGSize(width: 50, height: 50)
airplane.physicsBody?.isDynamic = true
airplane.physicsBody?.affectedByGravity = false
airplane.physicsBody?.allowsRotation = true
airplane.physicsBody?.pinned = false
self.addChild(airplane)
if motionManager.isAccelerometerAvailable {
// 2
motionManager.accelerometerUpdateInterval = 0.01
motionManager.startAccelerometerUpdates(to: .main) {
(data, error) in
guard let data = data, error == nil else {
return
}
// 3
let currentX = self.airplane.position.x
self.destX = currentX + CGFloat(data.acceleration.x * 500)
let currentY = self.airplane.position.y
self.destY = currentY + CGFloat(data.acceleration.y * 500)
}
}
}
override func update(_ currentTime: TimeInterval) {
let action = SKAction.moveTo(x: destX, duration: 1)
let action2 = SKAction.moveTo(y: destY, duration: 1)
airplane.run(action)
airplane.run(action2)
}
Upvotes: 0
Views: 42
Reputation: 11537
Another thing is that you may need to add a distance constraint to airplane so that it cannot escape from the border if speed is too high.
Upvotes: 0
Reputation: 16347
In SpriteKit things don't collide unless you give them a set of matching collisionBitMask
. ie border.collisionBitMask
& airplane.collisionBitMask
need to have at least one non zero bit in common. Try setting both to 1 to begin with.
Upvotes: 1