【问题标题】:Multiple physics bodies in SpriteKitSpriteKit 中的多个物理实体
【发布时间】:2015-08-04 00:53:47
【问题描述】:

我有一个 40x40 的矩形节点,我想检测底部何时接触平台。

我试过了

let feet = SKPhysicsBody(rectangleOfSize: CGSize(width: hero.frame.size.width, height: 1), center: CGPoint(x: 0, y: -(hero.frame.size.height/2 - 0.5)))

然后设置categoryBitMaskcollisionBitMaskcontactTestBitMask并将其添加到英雄中

hero.physicsBody = SKPhysicsBody(bodies: [feet])

但在 didBeginContact 中,println() 不打印。

我需要一个用于矩形底部和一个顶部的主体,因为如果英雄从下方撞到平台,碰撞会将他推倒。

更新

这是我设置位掩码的方法

let heroFeetCategory: UInt32 = 1 << 0
let edgeCategory: UInt32 = 1 << 1
let groundCategory: UInt32 = 1 << 2

let feet = SKPhysicsBody(rectangleOfSize: CGSize(width: hero.frame.size.width, height: 10), center: CGPoint(x: 0, y: -(hero.frame.size.height/2 - 5)))
feet.collisionBitMask = edgeCategory | groundCategory
feet.contactTestBitMask = groundCategory

feet.categoryBitMask = heroFeetCategory


hero.physicsBody = SKPhysicsBody(bodies: [feet])
hero.physicsBody?.usesPreciseCollisionDetection = true
hero.physicsBody?.velocity = CGVectorMake(0, 0)

hero.physicsBody?.restitution = 0.0
hero.physicsBody?.friction = 0.0
hero.physicsBody?.angularDamping = 0.0
hero.physicsBody?.linearDamping = 1.0

hero.physicsBody?.allowsRotation = false
hero.physicsBody?.mass = 0.0641777738928795

world.addChild(hero)

地面

let ground = SKSpriteNode(color: UIColor.whiteColor(), size: CGSizeMake(38, 38))
ground.name = "groundName"
ground.position = CGPoint(x: 0, y: -(self.frame.size.height/2 - ground.frame.size.height/2))

ground.physicsBody = SKPhysicsBody(rectangleOfSize: ground.size)
ground.physicsBody?.collisionBitMask = edgeCategory | heroFeetCategory
ground.physicsBody?.contactTestBitMask = heroFeetCategory
ground.physicsBody?.categoryBitMask = groundCategory
world.addChild(ground)

以及我如何检测他们是否触摸

func didBeginContact(contact: SKPhysicsContact) {

    var notTheHero: SKPhysicsBody!;

    if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask) {
        notTheHero = contact.bodyB;
    } else {
        notTheHero = contact.bodyA;
    }

    println(notTheHero.node) // print "heroName"
    if (notTheHero.categoryBitMask == groundCategory) {
        println("touch began?"); // is never called
    }
}

【问题讨论】:

  • 向我们展示你用来为英雄和平台设置位掩码的代码
  • 我为脚设置了位掩码,因为我只想知道英雄何时在平台上方。
  • 好的,然后是脚和平台的位掩码代码。

标签: sprite-kit skphysicsbody


【解决方案1】:

碰撞很好,但是当您通过物理体使用notTheHero.node 打印节点的名称时,您只能访问SKNode,而不是其名称的NSString 属性。相反,尝试类似println(notTheHero.node.name);

【讨论】:

  • 打印节点时,里面是名称。那为什么我需要 println(notTheHero.node.name) 呢?
  • 您正在访问节点上的 name 属性,这就是原因。
  • 这对碰撞有什么帮助?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多