1

我正在开发我的第一个 swift iOS sprite kit 项目,但我遇到了一个我无法找到解决方案的问题。我的目标是让球落在一个移动的平台上,并且球和平台在接触时都停止。

我遇到的问题是,当代码识别出它们正在接触并使它们停止时,平台和球之间始终存在间隙。见附图:

图片在这里

球:

//Ball Node
func createPlayer() -> SKNode {
    let playerNode = SKNode()
    playerNode.position = CGPoint(x: self.size.width / 2, y: self.size.height * 0.25)

    let sprite = SKSpriteNode(imageNamed: "ball")
    sprite.setScale(scaleFactor)

    playerNode.addChild(sprite)   
    playerNode.physicsBody = SKPhysicsBody(circleOfRadius: sprite.size.width / 2)
    playerNode.physicsBody?.dynamic = false
    playerNode.physicsBody?.allowsRotation = false
    playerNode.physicsBody?.restitution = 0.0
    playerNode.physicsBody?.friction = 0.0
    playerNode.physicsBody?.angularDamping = 0.0
    playerNode.physicsBody?.linearDamping = 0.0
    playerNode.physicsBody?.usesPreciseCollisionDetection = true
    playerNode.physicsBody?.categoryBitMask = CollisionCategoryBitmask.Player
    playerNode.physicsBody?.collisionBitMask = 0
    playerNode.physicsBody?.contactTestBitMask = CollisionCategoryBitmask.Platform | CollisionCategoryBitmask.Vortex

    return playerNode

平台:

//Platform
sprite = SKSpriteNode(imageNamed: "platform")
let node = PlatformNode()
let thePosition = CGPoint(x: position.x * scaleFactor - (sprite.size.width / 1.999), y: position.y + (self.size.height * 0.50))
 sprite.setScale(scaleFactor)
 node.addChild(sprite)
node.physicsBody?.usesPreciseCollisionDetection = true
node.physicsBody = SKPhysicsBody(rectangleOfSize: sprite.size)
node.physicsBody?.dynamic = false
node.physicsBody?.categoryBitMask = CollisionCategoryBitmask.Platform
node.physicsBody?.collisionBitMask = 0
return node

开始联系:

func didBeginContact(contact: SKPhysicsContact) {
    var updateHUD = true
    maxPlayerY = Int(player.position.y)
    let whichNode = (contact.bodyA.node != player) ? contact.bodyA.node : contact.bodyB.node
    //If the ball is falling
    if player.physicsBody?.velocity.dy < 0 {
        let other = whichNode as! GameObjectNode

        //If the player hits the Platform
        if player.physicsBody?.velocity.dy < 0 && whichNode?.name == "NODE_PLATFORM" {

            let joint = SKPhysicsJointFixed.jointWithBodyA(player.physicsBody, bodyB:whichNode!.physicsBody, anchor:CGPoint(x: player.position.x, y: ballBottom))
            let moveScreen = SKAction.moveToY(-(player.position.y - 200), duration: 0.5)
            let moveVortex = SKAction.moveToY((player.position.y - scaleFactor*300), duration: 0.5)

                physicsWorld.addJoint(joint
                player.physicsBody?.velocity = CGVector(dx: player.physicsBody!.velocity.dx, dy: 0)
                player.physicsBody?.affectedByGravity = false
                } 
            } 
    }
4

1 回答 1

0

我怀疑您可以通过等到物理模拟完成(对于当前帧)之后再连接对象来解决此问题。一种方法是在球与平台接触时设置一个标志,didBeginContact然后用一个关节连接两个身体didSimulatePhysics

于 2015-07-15T16:47:08.117 回答