将精灵附加到 SKPhysicsBody
Posted
技术标签:
【中文标题】将精灵附加到 SKPhysicsBody【英文标题】:getting the sprite attached to a SKPhysicsBody 【发布时间】:2017-10-21 20:50:52 【问题描述】:我正在为一个精灵设置动画,当它接触另一个精灵时,会调用物理接触函数。比,在这个函数中,我试图让精灵与另一个接触。它的 body 是 bodyA 但它是一个 SKPhysicsBody,它不能转换为一个 SKSpriteNode。你有什么想法? 该函数在接触时被正确调用,我只是尝试获取身体接触的精灵。最后的想法是让动作附加到我正在寻找的精灵上,但我想当你拥有精灵时它很容易。
let shootCategory: UInt32 = 0x1 << 0
let enemyCategory: UInt32 = 0x1 << 1
// Declaration of the SKPhysicsBody of the sprite wich will touch the other one
sprite.physicsBody = SKPhysicsBody(circleOfRadius: (20))
sprite.physicsBody?.usesPreciseCollisionDetection = true
sprite.physicsBody?.categoryBitMask = shootCategory
sprite.physicsBody?.collisionBitMask = shootCategory | enemyCategory
sprite.physicsBody?.contactTestBitMask = shootCategory | enemyCategory
sprite.physicsBody?.affectedByGravity = false
// Declaration of the SKPhysicsBody of the sprite wich will be touched
sprite.run(SKAction.group([moveAction, fadeInAction]))
sprite.physicsBody = SKPhysicsBody(circleOfRadius: (20))
sprite.physicsBody?.usesPreciseCollisionDetection = true
sprite.physicsBody?.categoryBitMask = enemyCategory
sprite.physicsBody?.collisionBitMask = shootCategory | enemyCategory
sprite.physicsBody?.contactTestBitMask = shootCategory | enemyCategory
sprite.physicsBody?.affectedByGravity = false
func didBegin(_ contact: SKPhysicsContact)
if (contact.bodyA.categoryBitMask == enemyCategory) && (contact.bodyB.categoryBitMask == shootCategory)
// I tried this to get the sprite wich the bodyB is attached to but it doesn't even build
let sprite: SKSpriteNode = sprite.contact.bodyB
contact.bodyA.removeAction(forKey: "moveToAction")
【问题讨论】:
Apple 文档的存在是有原因的,我建议使用它们developer.apple.com/documentation/spritekit/skphysicsbody/… 【参考方案1】:我终于发现解决方案真的很简单:
let Node = contact.bodyB.node as! SKSpriteNode
【讨论】:
以上是关于将精灵附加到 SKPhysicsBody的主要内容,如果未能解决你的问题,请参考以下文章
使用固定的 SKPhysicsJoint 将作为孩子的平台检测命中框附加到玩家精灵会更改玩家的碰撞和检测位掩码