Swift 精灵套件physicsBody.静息行为
我正在使用Swift和Sprite工具包在XCode Beta 6上开发一个游戏。 为了检测是否所有节点都在睡眠,我检查了它们的physicsBody.resting属性。 在更新方法中,我打印出结果Swift 精灵套件physicsBody.静息行为,swift,sprite-kit,game-physics,Swift,Sprite Kit,Game Physics,我正在使用Swift和Sprite工具包在XCode Beta 6上开发一个游戏。 为了检测是否所有节点都在睡眠,我检查了它们的physicsBody.resting属性。 在更新方法中,我打印出结果 import SpriteKit class GameScene: SKScene, SKPhysicsContactDelegate { var hero:SKSpriteNode! override func didMoveToView(view: SKView) {
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var hero:SKSpriteNode!
override func didMoveToView(view: SKView) {
self.physicsWorld.gravity = CGVectorMake(0, 0)
self.physicsWorld.contactDelegate = self
self.physicsBody = SKPhysicsBody(edgeLoopFromRect:self.frame)
hero = SKSpriteNode(imageNamed: "Spaceship")
hero.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame))
hero.zPosition = 10.0
hero.physicsBody = SKPhysicsBody(circleOfRadius: hero.size.width/2)
hero.physicsBody.allowsRotation = false
hero.physicsBody.linearDamping = 0.5
self.addChild(hero)
}
override func update(currentTime: CFTimeInterval) {
if hero.physicsBody.resting {
println("resting")
} else {
println("moving")
}
}
}
令我惊讶的是,结果是:
移动
休息
移动
(n倍相同)
移动
休息
那么为什么英雄在移动,尽管我什么也没做。节点移动N次并休息(休息),然后继续移动
有人能解释这种行为吗?那是虫子还是我错过了什么?提前感谢。如果你检查一个物理物体的速度,你会发现它确实在移动,但速度是无法感知的。这就是为什么没有设置rest属性。检查物体是否处于静止状态的更可靠方法是测试其线性速度和角速度是否接近零。下面是一个如何做到这一点的示例:
func speed(velocity:CGVector) -> Float {
let dx = Float(velocity.dx);
let dy = Float(velocity.dy);
return sqrtf(dx*dx+dy*dy)
}
func angularSpeed(velocity:CGFloat) -> Float {
return abs(Float(velocity))
}
// This is a more reliable test for a physicsBody at "rest"
func nearlyAtRest(node:SKNode) -> Bool {
return (self.speed(node.physicsBody.velocity)<self.verySmallValue
&& self.angularSpeed(node.physicsBody.angularVelocity) < self.verySmallValue)
}
override func update(_ currentTime: TimeInterval) {
/* Enumerate over child nodes with names starting with "circle" */
enumerateChildNodesWithName("circle*") {
node, stop in
if (node.physicsBody.resting) {
println("\(node.name) is resting")
}
if (self.nearlyAtRest(node)) {
println("\(node.name) is nearly resting")
}
}
}
func速度(速度:CGVector)->浮点{
设dx=浮动(速度.dx);
设dy=浮动(速度.dy);
返回sqrtf(dx*dx+dy*dy)
}
函数角速度(速度:CGFloat)->Float{
返回abs(浮动(速度))
}
//这是对处于“休息”状态的身体更可靠的测试
func nearlyAtRest(节点:SKNode)->Bool{
返回(self.speed(node.physicsBody.velocity)谢谢你的重播。你的方法看起来很棒。我正在开发一个基于回合的游戏,它需要联网。这种方法也可靠吗?因为我必须确保每个玩家的设备上都显示相同的球的位置。是的,它可以在网络上玩游戏。我相信sqrtf(dxdx+dy+dy)应该是sqrtf(dxdx+dy*dy)只是一个小注释-调用sqrtf
是不必要的,因为您可以将结果与verysmall值的平方进行比较(可以预先计算)。伙计们:在这种情况下,什么是合理的verysmall值?因为我对速度和角速度的检查显示为0.0