Keeping an object within the screen. Swift SpriteKit

给你一囗甜甜゛ 提交于 2019-12-06 05:04:36

问题


I am new to swift a Sprite kit. In the app I am trying to make I have a submarine moving through the ocean. Every time the user clicks the screen the gravity starts pulling the sub in the opposite direction. My problem is that i can't find a way to keep the sub from leaving the screen. I have tried to solve it by making a physicsBody around the screen, but the sub still leaves the screen. I have also tried the following code in the updateCurrentTime fund.

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 this doesn't do anything either.

Any help would be greatly appreciated!!!!! thanks in advance! P.S. I can't believe that it is that hard to keep things on the screen!!! frustrating!


回答1:


Try SKConstraint - it doesn't require a physicsBody. The code would look something like this, and would constrain the sub sprite to the scene:

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)]



回答2:


Try this in the update:

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
}

And then inside of the event where you want to reverse gravity don't forget to do this:

sub.physicsBody!.affectedByGravity = true

Alternatively, instead of using gravity you could use this which is a better option in my opinion:

// 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.


来源:https://stackoverflow.com/questions/30105898/keeping-an-object-within-the-screen-swift-spritekit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!