Saving an object on the screen. Swift spritekit

I am new to quick sprite pack. In the application, I try to make me a submarine moving across the ocean. Each time the user clicks on the screen, gravity begins to pull the sub in the opposite direction. My problem is that I cannot find a way to keep the unit from exiting the screen. I tried to solve this problem by making a physical panel around the screen, but the sub-channel is still coming out of the screen. I also tried the following code in the updateCurrentTime foundation.

override func update(currentTime: CFTimeInterval) {
    /* Called before each frame is rendered */
self.physicsWorld.gravity = CGVectorMake(0,gravity)

    if (sub.position.y >= self.size.height - sub.size.height / 2){
       sub.position.y = self.size.height - self.sub.size.height / 2
    }
    if (sub.position.y <= sub.size.height / 2) {
        sub.position.y = self.sub.size.height / 2

    }



}

But that also doesn’t.

Any help would be greatly appreciated !!!!! thanks in advance! PS I can’t believe that it’s very difficult to keep things on the screen! frustrating!

+4
source share
2 answers

SKConstraint - . sub :

let width2 =  sub.size.width/2
let height2 =  sub.size.height/2
let xRange = SKRange(lowerLimit:0+width2,upperLimit:size.width-width2)
let yRange = SKRange(lowerLimit:0+height2,upperLimit:size.height-height2)
sub.constraints = [SKConstraint.positionX(xRange,Y:yRange)]
+1

:

if sub.frame.maxY >= view!.frame.height {
    sub.position.y = view!.frame.height - sub.size.height / 2
    sub.physicsBody!.affectedByGravity = false
}
if sub.frame.minY <= 0 {
    sub.position.y = sub.size.height / 2
    sub.physicsBody!.affectedByGravity = false
}

, , :

sub.physicsBody!.affectedByGravity = true

, , :

// This moves the object to the top of the screen
let action = SKAction.moveToY(view!.frame.height - character.size.height / 2, duration: 5.0) // Or however much time you want to the action to run.
action.timingMode = .EaseInEaseOut // Or something else
character.runAction(action)
 // Change view!.frame.height - character.size.height / 2 to just character.size.height / 2 to move to the bottom.
-1

All Articles