我有一个 SKSpriteNode,它由加速度计控制左右移动,如下所示:
var destX = myNode.position.x
override func update(currentTime: CFTimeInterval) {
if let data = motionManager.accelerometerData {
let currentX = self.myNode.position.x
if data.acceleration.x < 0 {
self.destX = currentX + CGFloat(data.acceleration.x * 2000)
} else if data.acceleration.x > 0 {
self.destX = currentX + CGFloat(data.acceleration.x * 2000)
}
else if data.acceleration.x == 0 {
self.destX = currentX
}
}
}
然后,同样在更新方法中,我创建一个 SKAction
将 SpriteNode 移动到 destX
:
if alive {
let action = SKAction.moveToX(destX, duration: 1)
self.myNode.runAction(action)
}
左右移动效果很好。不过,我现在需要做的是使节点无法离开屏幕。我尝试在屏幕边缘放置一个物理体:
self.physicsBody = SKPhysicsBody(edgeLoopFromRect: CGRectMake(0, 0, self.size.width, self.size.height))
self.physicsBody?.categoryBitMask = PhysicsCategory.ScreenEdge
myNode.physicsBody?.collisionBitMask = PhysicsCategory.ScreenEdge
我的物理体本身运行良好,但 Sprite 节点和屏幕边缘之间的碰撞不起作用的原因是该节点正在运行一个 Action ,而 Action 有点“覆盖”物理。有什么方法可以使节点停止在屏幕边缘,同时仍然保持加速度计数据的加速度?我知道目前,destX
是一个非常高或非常低的数字,但那是为了使 Sprite 节点快速从一侧移动到另一侧。
基本上,我需要一种方法来 a) 即使在节点上运行 SKAction
时也允许发生冲突,或者 b) 使 moveToX
操作在以下情况下停止: Sprite 节点离开屏幕,并在节点返回屏幕后重新启动。
谢谢!
最佳答案
也许这可以帮助:
(对 Objective C 感到抱歉,我不是一个快速程序员,但仍然会尝试解释如何用自己的语言来做到这一点)
-(BOOL)isNode:(*SKnode)theNode outOfScene:(*SKScene)theScene
{
BOOL isIt = NO;
if (theNode.position.x > theScene.frame.size.width + (theNode.frame.size.width / 2)){isIt = YES;}
if (theNode.position.x < -(theNode.frame.size.width / 2)){isIt = YES;}
if (theNode.position.y > theScene.frame.size.height + (theNode.frame.size.height / 2)){isIt = YES;}
if (theNode.position.y < -(theNode.frame.size.height / 2)){isIt = YES;}
return isIt;
}
这是它的工作原理
-(BOOL)isNode:(*SKnode)theNode outOfScene:(*SKScene)theScene
新函数,
输入变量为:theNode
一个节点,和 theScene
场景以查看其是否在范围内。
BOOL isIt = NO;
创建一个新的 bool 变量,它的默认值为 NO
if (theNode.position.x > theScene.frame.size.width){isIt = YES;}
if (theNode.position.x < 0){isIt = YES;}
if (theNode.position.y > theScene.frame.size.height){isIt = YES;}
if (theNode.position.y < 0){isIt = YES;}
检查是否theNode
不在 theScene
内的可见边界。
如果超出theScene
,则将isIt 设置为Yes。的界限。
这假设 theNode
的方向是 (0,0) - 如果您不知道这意味着什么,那么您可能应该忽略它。
return isIt
返回isIt
发送给发送者(“调用”该函数的人)
事情就是这样。
注意:此代码未经测试,如有错误请留言。
编辑:如果 theNode
不是 theScene
的子项您可能需要转换 theNode
的位置的坐标空间到 theScene
的坐标空间.
关于swift - 使 SKSpriteNode 运行 Action 与屏幕边缘碰撞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34252876/