精灵没有正确接触

Sprites not contacting properly

有一个球和一个球拍,球应该在球拍上并接触球拍,但球从未接触球拍并且在到达球拍之前停止了,谁能帮我解决一下?

import SpriteKit

class GameScene: SKScene ,SKPhysicsContactDelegate {

    let ballCategory:UInt32 = 0x1 << 0
    let bottomCategory:UInt32 = 0x1 << 1
    let paddleCategory:UInt32 = 0x1 << 2

    override init(size: CGSize){
        super.init(size: size)

        physicsWorld.contactDelegate = self


        let ball = SKSpriteNode(imageNamed: "ball")
        ball.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
        addChild(ball)

        ball.physicsBody = SKPhysicsBody(circleOfRadius: self.frame.size.width / 2)
        ball.physicsBody?.dynamic = true
        ball.physicsBody?.allowsRotation = false
        ball.physicsBody?.friction = 0
       // ball.physicsBody?.applyImpulse(CGVectorMake(2,-2))
        ball.physicsBody?.categoryBitMask = ballCategory
        ball.physicsBody?.contactTestBitMask = paddleCategory
        ball.physicsBody?.collisionBitMask = paddleCategory
        ball.physicsBody?.affectedByGravity = true

        let paddle = SKSpriteNode(imageNamed: "paddle")
        paddle.position = CGPointMake(CGRectGetMidX(self.frame), paddle.frame.size.height * 2)
        addChild(paddle)

        paddle.physicsBody = SKPhysicsBody(rectangleOfSize: paddle.frame.size)
        paddle.physicsBody?.affectedByGravity = false
        paddle.physicsBody?.dynamic = false
        paddle.physicsBody?.categoryBitMask = paddleCategory

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    }

    func didBeginContact(contact: SKPhysicsContact) {
            print("touched")

    }

    override func update(currentTime: CFTimeInterval) {
        /* Called before each frame is rendered */
    }
}

您遇到此问题是因为这一行:

 ball.physicsBody = SKPhysicsBody(circleOfRadius: self.frame.size.width / 2)

self这里是风景

你需要这个:

 ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.frame.size.width / 2)

像这样在 GameViewController 中打开物理视觉表示:

skView.showsPhysics =  true

你会看到发生了什么。

确定节点接触位置的最佳方法是打开物理。

打开GameViewController.swift并输入以下代码:

skView.showsPhysics =  true