问题描述
我是Swift sprite套件的新手。在应用程序中,我试图让我有一艘潜艇在海洋中移动。每次用户点击屏幕时,重力开始沿相反方向拉动子。我的问题是我无法找到一种方法来防止sub离开屏幕。我试图通过在屏幕周围制作一个物理体来解决它,但是子仍然离开了屏幕。我还在updateCurrentTime基金中尝试了以下代码。
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.
任何帮助都将非常感谢!!!!!提前致谢!
P.S.我无法相信屏幕上的东西很难!
令人沮丧!
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!
推荐答案
尝试 SKConstraint
- 它没有'需要物理实体。代码看起来像这样,并将 sub
精灵限制在场景中:
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)]
这篇关于将对象保留在屏幕内。 Swift SpriteKit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!