在SpriteKit中将物理物体添加到Sprite中会部分改变其位置 [英] Adding physics body to Sprite in SpriteKit alters its position fractionally
问题描述
我有一个Swift/SpriteKit游戏,其中一堆精灵都有物理物体来检测与玩家的碰撞-否则它们不应该移动.
I have a Swift / SpriteKit game in which a whole bunch of sprites have physics bodies to detect collision with the player - but otherwise they are not supposed to move.
我的问题是,一旦我添加了一个物理物体,精灵就会出现部分移动.更具体地说,其位置变化很小(例如0.0003).最初,这么小的变化并不重要,但它会一直这样变化,直到精灵实际在屏幕上移动并弄乱游戏为止.
My issue is that as soon as I add a physics body, the sprite appears to move fractionally. More specifically its position changes by a small fraction (like 0.0003). Initially such a small change does not matter, but it keeps changing like this until the sprite actually moves onscreen and messes up the game.
为了缩小范围,我创建了一个仅包含一个精灵的简单项目,并且我注意到,只要将物理物体附着到我的精灵上,其位置就会发生部分偏移.
To narrow it down I created a simple project with just one sprite and I notice that as soon as I attach a physics body to my sprite its position shifts fractionally.
我已经尝试过的事情:
- 检查以确保重力已关闭
- 将物理物体的静止属性设置为真
- 将物理物体的重力属性影响设置为false
在OS X上使用Xcode进行Im编码
Im coding using Xcode on OS X
但是没有运气.
下面是一个代码片段,在测试项目中对此进行了显示:
Here's a code fragment which shows this in the test project:
import SpriteKit
class TestScene: SKScene, SKPhysicsContactDelegate {
let sprite1 = SKSpriteNode(color: SKColor.redColor(), size: CGSizeMake(50, 50))
override func didMoveToView(view: SKView) {
physicsWorld.gravity = CGVectorMake(0.0, 0.0)
physicsWorld.contactDelegate = self
sprite1.position = CGPointMake(200, 200)
sprite1.physicsBody = SKPhysicsBody(rectangleOfSize: sprite1.size)
sprite1.physicsBody?.affectedByGravity = false
sprite1.physicsBody?.resting = true
self.addChild(sprite1)
sprite1.position = CGPointMake(200, 200)
}
override func update(currentTime: NSTimeInterval) {
print(sprite1.position)
// position is not 200,200 as expected
// it becomes 199.999938964844, 199.999938964844 after a few updates
// In my real project the position will keep drifting like this until it moves on screen
}
}
推荐答案
我认为它的dynamic属性默认情况下设置为yes.将其设置为false,精灵将不再移动
I think its the dynamic property which is set to yes by default. Set it to false and the sprite should not move anymore
sprite1.physicsBody?.dynamic = false
我刚刚在一个项目中对此进行了测试,它仍然显示为199.9 ....但它似乎并没有增加或减少
I just tested this in a project and it still says 199.9.... but it doesnt seem to increase or decrease
这篇关于在SpriteKit中将物理物体添加到Sprite中会部分改变其位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!