首页 > 解决方案 > 当代码另有说明时,是否基于碰撞移除 Sprite 对象?

问题描述

let playerBulletCategory: UInt32 = 0x1 << 2
let meteorCategory: UInt32 = 0x1 << 4

玩家子弹法

func fireBullet(){
    
    let bullet = SKSpriteNode(imageNamed: "playerBullet")
    bullet.name = "playerBullet"
    bullet.size = CGSize(width: 80, height: 80)
    bullet.position = player.position
    bullet.zPosition = 6
    player.physicsBody?.velocity.dx = 0
    player.physicsBody?.velocity.dy = 0
    bullet.physicsBody = SKPhysicsBody(rectangleOf: bullet.size)
    bullet.physicsBody!.affectedByGravity = false
    bullet.physicsBody?.isDynamic = false
    bullet.physicsBody!.categoryBitMask = playerBulletCategory
    bullet.physicsBody!.collisionBitMask = meteorCategory
    bullet.physicsBody!.contactTestBitMask = meteorCategory
    self.addChild(bullet)
    
    let moveBullet = SKAction.moveTo(x: self.size.width + bullet.size.width, duration: 1)
    let deleteBullet = SKAction.removeFromParent()
    let bulletSequence = SKAction.sequence([moveBullet,deleteBullet])
    bullet.run(bulletSequence)

}

流星法

    let Meteor = SKSpriteNode(imageNamed: "Meteor")
    Meteor.setScale(1)
    Meteor.position = startPoint
    Meteor.zPosition = 5
    Meteor.name = "Meteor"
    Meteor.physicsBody = SKPhysicsBody(circleOfRadius: Meteor.size.width / 2)
    Meteor.physicsBody!.affectedByGravity = false
    Meteor.physicsBody!.isDynamic = true
    Meteor.physicsBody!.categoryBitMask = meteorCategory
    Meteor.physicsBody!.collisionBitMask = 0
    Meteor.physicsBody!.contactTestBitMask = playerBulletCategory
    
    self.addChild(Meteor)

检测到接触时已开始的方法

func didBegin(_ contact: SKPhysicsContact) {
    
    let Collision:UInt32 = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask
    
    if Collision == meteorCategory | playerBulletCategory {
        
        playerBulletCollide(bullet: contact.bodyB.node!)
       
           if(contact.bodyA.node != nil){
           spawnExplosion(spawnPosition: contact.bodyA.node!.position)
           print("contact is done")
       
        }
        
        meteorHealthFunction()
        
        if(meteorHealth == 0){
            
            meteorCollide(Meteor: contact.bodyA.node!)
            print("contact is works")
        }
        
    }

当子弹与流星接触时,应将流星移除,但仅当子弹与流星接触 3 次,但在 1 次接触后流星被移除,即使移除联系代码后,流星仍会被移除。

先感谢您。

标签: swiftxcodecollision-detection

解决方案


推荐阅读