Sprite Kit Physics身体休息行为 [英] Sprite Kit physicsBody.resting behavior
问题描述
我正在使用Swift和Sprite Kit在XCode Beta 6上开发游戏. 为了检测是否所有节点都在休眠,我检查了它们的physicsBody.resting属性. 在更新方法中,我打印出结果.
I am using Swift and Sprite Kit to develop a game on XCode Beta 6. In order to detect if all nodes are sleeping, i check their physicsBody.resting property. In update method i print out the result.
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")
}
}
}
令我惊讶的是,结果是:
To my surprise, the results are:
移动 休息的 移动 (n次相同) 移动 休息
moving resting moving (n times the same) moving resting
那英雄为什么要动弹,尽管我什么也没做.节点移动N次并休息一下(休息),然后继续移动.
So why the hero is moving, although i didn't do anything. The node moves N times and takes a break(resting), after that goes on moving.
有人可以解释这种行为吗?那是一个错误还是我错过了什么?预先感谢.
Can anyone explain that behaviour? Is that a bug or do i miss something? Thanks in advance.
推荐答案
如果您检查物理物体的速度,您会发现它确实在运动,但其运动速度是无法察觉的.这就是为什么未设置静止属性的原因.检查SKPhysicsBody是否静止的一种更可靠的方法是测试其线速度和角速度是否接近零.这是如何执行此操作的示例:
If you examine the velocity of a physics body, you'll see that it is indeed moving but at a rate that is not perceivable. That's why the resting property is not set. A more reliable way to check if a SKPhysicsBody is at rest is to test if its linear and angular speeds are nearly zero. Here's an example of how to do that:
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")
}
}
}
这篇关于Sprite Kit Physics身体休息行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!