1

我想将两个物理实体添加到另一个实体,但是当 showPhysics 打开时,它看起来像这样。

在此处输入图像描述

这是我使用的代码

// Set anchor point
self.anchorPoint = CGPointMake(0.5, 0.5)

// setup physics
self.physicsWorld.gravity = CGVectorMake( 0.0, -5.0)
self.physicsWorld.contactDelegate = self

// set physics body
let borderBody: SKPhysicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
borderBody.friction = 0.0
self.physicsBody = borderBody;
self.physicsBody?.categoryBitMask = BodyType.edge.rawValue

// setup background color
let skyColor = SKColor(red: 81.0/255.0, green: 192.0/255.0, blue: 201.0/255.0, alpha: 1.0)
self.backgroundColor = skyColor

let hero = SKSpriteNode(color: UIColor.whiteColor(), size: CGSizeMake(38, 38))
hero.physicsBody = SKPhysicsBody(rectangleOfSize: hero.size)
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

// Adding the head
let head = SKSpriteNode(color: UIColor.blackColor(), size: CGSize(width: hero.frame.size.width, height: 10))
head.position = CGPoint(x: 0, y: hero.frame.size.height/2 - head.frame.size.height/2)
head.physicsBody = SKPhysicsBody(rectangleOfSize: head.size)
hero.addChild(head)


// Adding the feet
let feet = SKSpriteNode(color: UIColor.orangeColor(), size: CGSize(width: hero.frame.size.width, height: 10))
feet.position = CGPoint(x: 0, y: -(hero.frame.size.height/2 - feet.frame.size.height/2))
feet.physicsBody = SKPhysicsBody(rectangleOfSize: feet.size)

feet.physicsBody?.categoryBitMask = heroFeetCategory
feet.physicsBody?.collisionBitMask = edgeCategory | groundCategory
feet.physicsBody?.contactTestBitMask = groundCategory

hero.addChild(feet)

world.addChild(hero)

// join head
let join = SKPhysicsJointFixed.jointWithBodyA(hero.physicsBody, bodyB:head.physicsBody, anchor:hero.position)
self.physicsWorld.addJoint(join)

// join feet
let joinFeet = SKPhysicsJointFixed.jointWithBodyA(hero.physicsBody, bodyB:feet.physicsBody, anchor:hero.position)
self.physicsWorld.addJoint(joinFeet)

我也尝试

let convertedPosition = self.convertPoint(hero.position, fromNode: hero.parent!)

不知道以后会不会出现问题,但是为什么英雄节点可以和其他节点正常连接呢?

4

1 回答 1

0

您可以解决问题的一件事是只获取 SKPhysicsJointPin 的锚点位置并添加self.size.width/2到 X 和self.size.height/2Y。基本上您所做的是假设 self.anchorPoint 仍然等于 (0 ,0),即使它不是。出于某种原因,SKPhysicsJoints 总是假设场景的锚点位于左下角。快乐编码!

于 2015-08-21T17:05:29.260 回答