简体   繁体   中英

SKSpriteNode Collision Removal In Removing Wrong One With Xcode Swift SpriteKit

I am making a game where when the character lands on the cloud, the cloud fades out. I put in code to determine when it is hit, there are multiple clouds registered under the same SKSpriteNode, but when it lands on the cloud, the wrong cloud is fading away, it is the most recently added SKSpriteNode that is being removed, not the one it is colliding with.

Is there any way to do it so it only removes the one that the character has collided with, not the earliest one that spawns? Here is the code:

func didBeginContact(contact: SKPhysicsContact)
{



    let contactMask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask

    switch(contactMask)
    {





    case BodyType.PersonCategory.rawValue | BodyType.CloudCategory.rawValue:

        let CheckDelay = delay(0.02)
            {

                    self.Cloud.runAction(self.FadeAway)

        }

    default:
        return





Person.physicsBody?.usesPreciseCollisionDetection = true
Person.size = CGSizeMake(self.frame.size.width / 25, self.frame.size.height / 16.25)
Person.physicsBody = SKPhysicsBody(rectangleOfSize: Person.size)
Person.physicsBody?.restitution = 0
Person.physicsBody?.friction = 0
Person.physicsBody?.allowsRotation = false
Person.physicsBody?.affectedByGravity = true
Person.physicsBody?.dynamic = true
Person.physicsBody?.linearDamping = 0
Person.zPosition = 5
Person.physicsBody?.categoryBitMask = BodyType.PersonCategory.rawValue
Person.physicsBody?.contactTestBitMask = BodyType.CloudCategory.rawValue
Person.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame) * 1.7)
self.addChild(Person)


Cloud = SKSpriteNode(texture: NormalCloudTexture)
Cloud.zPosition = 7
Cloud.physicsBody?.usesPreciseCollisionDetection = true
Cloud.physicsBody?.affectedByGravity = false
Cloud.physicsBody?.allowsRotation = false
Cloud.size = CGSizeMake(self.frame.size.width / 8.05, self.frame.size.height / 40)
Cloud.physicsBody = SKPhysicsBody(rectangleOfSize: Cloud.size)
Cloud.physicsBody?.friction = 0
Cloud.physicsBody?.restitution = 0
Cloud.physicsBody?.dynamic = false
Cloud.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame) / 7.60)
addChild(Cloud)

You need to remove the cloud represented by the physicsBody actually making the contact. so bodyA is either the player, or the cloud, and then bodyB is either the player or the cloud. Then get the actual SKSpriteNode from the physics body. It can be referenced via the node property on the SKPhysics body. So either bodyA.node, or bodyB.node.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM