Alright. So. When I'm trying to do is restart the game if the ball touches a "danger" (Just a Sprite node thats a rectangle). How do I do that? I have no idea where to start with it. I have them both with physics bodies.
I want the ball to reset to the starting position that I defined in startGame()
ballPlayer.physicsBody?.isDynamic = true
Thats where I give ballPlayer (The ball) a dynamic physics body. I don't know what else I should put there.
The rectangle is defined using the gameScene.sks storyboard.
import SpriteKit
import GameplayKit
class GameScene: SKScene {
var ballPlayer = SKSpriteNode()
override func didMove(to view: SKView) {
ballPlayer = self.childNode(withName: "ballPlayer") as! SKSpriteNode
ballPlayer.physicsBody?.isDynamic = true
let border = SKPhysicsBody(edgeLoopFrom: self.frame)
border.friction = 0
border.restitution = 1
self.physicsBody = border
startGame()
addSwipeGestureReconizers()
}
func addSwipeGestureReconizers() {
let gestureDirections: [UISwipeGestureRecognizer.Direction] = [.right, .left, .up, .down]
for gestureDirection in gestureDirections {
let gestureReconzier = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe))
gestureReconzier.direction = gestureDirection
self.view?.addGestureRecognizer(gestureReconzier)
}
}
func startGame() {
ballPlayer.position = CGPoint(x: 0, y: 550)
}
@objc func handleSwipe(gesture: UIGestureRecognizer) {
if let gesture = gesture as? UISwipeGestureRecognizer {
switch gesture.direction {
case .up:
ballPlayer.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 0))
ballPlayer.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 110))
print("Swiped up")
case .down:
ballPlayer.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 0))
ballPlayer.physicsBody?.applyImpulse(CGVector(dx: 0, dy: -110))
print("Swiped down")
case .right:
ballPlayer.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 0))
ballPlayer.physicsBody?.applyImpulse(CGVector(dx: 110, dy: 0))
print("Swiped right")
case .left:
ballPlayer.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 0))
ballPlayer.physicsBody?.applyImpulse(CGVector(dx: -110, dy: 0))
print("Swiped left")
default:
print("No such gesture")
}
}
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
}
}
Comments
Post a Comment