swift - 我的节点没有冲突,我的代码中是否遗漏了某些内容?

标签 swift sprite-kit collision

我遵循了许多不同的碰撞教程,并创建了自己的游戏,我想在其中声明硬币和玩家之间的碰撞。但是,在实现碰撞代码后,我的两个节点没有响应碰撞...有人可以帮助我吗?

import SpriteKit
import GameplayKit

// Collision categories

enum ColliderType: UInt32 {
case playerCase = 1
case coinCase = 2
case borderCase = 3
}

class GameScene: SKScene, SKPhysicsContactDelegate {

let player  = SKSpriteNode(imageNamed:"block")
let buttonDirLeft = SKSpriteNode(imageNamed: "left")
let buttonDirRight = SKSpriteNode(imageNamed: "right")
let coins = SKSpriteNode(imageNamed: "coins")
let background = SKSpriteNode(imageNamed: "background")
var pressedButtons = [SKSpriteNode]()

override func didMove(to view: SKView) {

self.physicsWorld.contactDelegate = self

//score label
let points = SKLabelNode(text: "0")
points.position = CGPoint(x: 530, y: 260)
points.zPosition = 6
points.fontColor = UIColor.black
points.fontSize = 50
addChild(points)


//Set Background
background.zPosition = 1
background.position = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2)
background.size.width = 580
background.size.height = 320

addChild(background)

// Player
player.position = CGPoint(x: 250, y: 40)
player.zPosition = 2
player.texture?.filteringMode = .nearest
// player!.collisionBitMask = 0 //
player.physicsBody = SKPhysicsBody(circleOfRadius: player.size.height / 2.0)
player.physicsBody?.isDynamic = false
player.physicsBody?.allowsRotation = false
player.physicsBody?.affectedByGravity = false
player.physicsBody!.categoryBitMask = ColliderType.playerCase.rawValue
player.physicsBody!.contactTestBitMask = ColliderType.coinCase.rawValue
player.physicsBody!.collisionBitMask = ColliderType.coinCase.rawValue

self.addChild(player)

// button left
buttonDirLeft.position = CGPoint(x: 30, y: 35)
buttonDirLeft.zPosition = 4
buttonDirLeft.size.width = 270
buttonDirLeft.size.height = 320
buttonDirLeft.alpha = 0.0
self.addChild(buttonDirLeft)

// button right
buttonDirRight.position = CGPoint(x: 530, y: 35)
buttonDirRight.zPosition = 4
buttonDirRight.size.width = 270
buttonDirRight.size.height = 320
buttonDirRight.alpha = 0.0
self.addChild(buttonDirRight)


// setting border around game
let borderBody = SKPhysicsBody(edgeLoopFrom: self.frame)
borderBody.friction = 0
self.physicsBody = borderBody

//ENEMY SETTINGS START

//repeat coing spawning
run(SKAction.repeatForever(
    SKAction.sequence([
        SKAction.run(spawnCoins),
        SKAction.wait(forDuration: 1.0)])))


}
//coin settings
func random() -> CGFloat {
    return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}

func random(min: CGFloat, max: CGFloat) -> CGFloat {
    return random() * (max - min) + min
}

//spawn coins
func spawnCoins() {
    // 2
    let coins = SKSpriteNode(imageNamed: "coins")
    coins.zPosition = 2
    coins.size.width = 40
    coins.size.height = 40

    let action = SKAction.moveTo(y: -350, duration: TimeInterval(random(min:   1, max: 5)))

    let remove = SKAction.run({coins.removeFromParent(); print("coins removed  from scene")})

    let sequence = SKAction.sequence([action,remove])

    coins.physicsBody = SKPhysicsBody(rectangleOf: coins.size )
    coins.physicsBody?.isDynamic = false
    coins.physicsBody!.affectedByGravity = false
    coins.physicsBody!.categoryBitMask = ColliderType.coinCase.rawValue
    coins.physicsBody!.contactTestBitMask = ColliderType.playerCase.rawValue
    coins.physicsBody!.collisionBitMask = ColliderType.playerCase.rawValue

    coins.run(sequence)


    coins.size.width = 20
    coins.size.height = 20
    coins.name = "coins"
//    coins.physicsBody!.collisionBitMask = 0
    coins.position = CGPoint(x: frame.size.width * random(min: 0, max: 1), y: frame.size.height + coins.size.height/2)
    addChild(coins)

}


override func update(_ currentTime: TimeInterval) {
    // Called before each frame is rendered
    /* Called before each frame is rendered */
    if pressedButtons.index(of: buttonDirLeft) != nil {
        player.position.x -= 3.0
    }
    if pressedButtons.index(of: buttonDirRight) != nil {
        player.position.x += 3.0
    }

    // Update entities       

}
//MOVEMENT FUNCTIONS START HERE
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch: AnyObject in touches {
        let location = touch.location(in: self)
        let previousLocation = touch.previousLocation(in: self)

        for button in [buttonDirLeft, buttonDirRight] {
            // I check if they are already registered in the list
            if button.contains(location) && pressedButtons.index(of: button) == nil {
                pressedButtons.append(button)
            }
        }
    }
}


override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch: AnyObject in touches {
        let location = touch.location(in: self)
        let previousLocation = touch.previousLocation(in: self)

        for button in [buttonDirLeft, buttonDirRight] {
            // if I get off the button where my finger was before
            if button.contains(previousLocation)
                && !button.contains(location) {
                // I remove it from the list
                let index = pressedButtons.index(of: button)
                if index != nil {
                    pressedButtons.remove(at: index!)
                }
            }

                // if I get on the button where I wasn't previously
            else if !button.contains(previousLocation)
                && button.contains(location)
                && pressedButtons.index(of: button) == nil {
                // I add it to the list
                pressedButtons.append(button)

            }}}}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch: AnyObject in touches {
        let location = touch.location(in: self)
        let previousLocation = touch.previousLocation(in: self)

        for button in [buttonDirLeft, buttonDirRight] {
            if button.contains(location) {
                let index = pressedButtons.index(of: button)
                if index != nil {
                    pressedButtons.remove(at: index!)
                }
            }
            else if (button.contains(previousLocation)) {
                let index = pressedButtons.index(of: button)
                if index != nil {
                    pressedButtons.remove(at: index!)
                }
            }
        }
    }
}


override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch: AnyObject in touches {
        let location = touch.location(in: self)
        let previousLocation = touch.previousLocation(in: self)

    for button in [buttonDirLeft, buttonDirRight] {
        if button.contains(location) {
            let index = pressedButtons.index(of: button)
            if index != nil {
                pressedButtons.remove(at: index!)
            }
        }
        else if (button.contains(previousLocation)) {
            let index = pressedButtons.index(of: button)
            if index != nil {
                pressedButtons.remove(at: index!)
            }
        }
    }
}
}

func didBeginContact(contact: SKPhysicsContact){
print("colliding!")
}

最佳答案

只有当至少一个物体处于动态状态时才会发生接触。因此,要么将你的玩家或硬币设置为动态,如果其他所有设置都正确(如果类别设置正确并且 didBeginContact 方法实现正确),你的 body 现在将发生碰撞/接触。如果您只对联系人感兴趣,请将冲突位掩码设置为 0。

关于swift - 我的节点没有冲突,我的代码中是否遗漏了某些内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40829396/

相关文章:

swift - 如何以编程方式呈现 WKWebView 的 WebKit 检查器?

Sprite 之间的 C++ SDL 碰撞

ios - SpriteKit 中的平滑 Sprite 运动

python - 碰撞检测问题 - PyGame

javascript - Javascript 中的碰撞处理——粒子卡住

swift - Swift 4 打印输出中的神秘 ""(Xcode 9Beta)

swift - Xcode6-Beta Swift Playground 停止解释任何项目中的命令

ios - 是否可以在 UITextview 链接选择上设置清除颜色?

swift - SpriteKit categoryBitMask 无法识别

swift - 如何在 Swift 中将节点添加到不同类的 View 中