swift – Sprite Kit physicsBody.resting行为

前端之家收集整理的这篇文章主要介绍了swift – Sprite Kit physicsBody.resting行为前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用Swift和Sprite Kit在XCode Beta 6上开发游戏.
为了检测所有节点是否正在休眠,我检查他们的physicsBody.resting属性.
在更新方法中,我打印出结果.
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次并休息(休息),之后继续移动.

谁能解释这种行为?这是一个错误还是我错过了什么?提前致谢.

如果你检查物理体的速度,你会发现它确实在移动,但速度是不可察觉的.这就是为什么没有设置休息属性.检查SKPhysicsBody是否静止的更可靠的方法是测试其线性和角速度是否几乎为零.这是一个如何做到这一点的例子:
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")
        }
    }
}
原文链接:https://www.f2er.com/swift/320149.html

猜你在找的Swift相关文章