我是Swift sprite套件的新手。在应用程序中,我试图让我有一艘潜艇在海洋中移动。每次用户点击屏幕时,重力开始沿相反方向拉动子。我的问题是我无法找到一种方法来防止sub离开屏幕。我试图通过在屏幕周围制作一个物理体来解决它,但是子仍然离开了屏幕。我还在updateCurrentTime基金中尝试了以下代码。
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
}
}
但这也没有做任何事情。
任何帮助将不胜感激!!!!!提前致谢! 附:我无法相信屏幕上的内容很难! 令人沮丧!
答案 0 :(得分:1)
尝试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 :(得分:-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.