简体   繁体   中英

How can I prevent two types of SpriteKit nodes from colliding with each other?

I'm writing a small game using Apple Sprite Kit.

I'm having trouble with the collisions. Sometimes I dont want two skSpriteNodes with physicsBodys to interact.

as an example I have the HERO , ENEMYS and SHOTS and I want the SHOTS only to interact with the ENEMYS.

But when 2 shots collide together then they change their position.!

the code for the shot is

   shot.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:shot.size];
   shot.physicsBody.dynamic = YES;
   shot.physicsBody.allowsRotation = FALSE;
   shot.physicsBody.categoryBitMask = playerShotCategory;
   shot.physicsBody.contactTestBitMask = enemyCategory;

and the code for the enemy is

   activeGameObject.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:activeGameObject.size];
    activeGameObject.physicsBody.dynamic = YES;
    activeGameObject.physicsBody.categoryBitMask = enemyCategory;
    activeGameObject.physicsBody.contactTestBitMask = playerCategory | playerShotCategory;
    activeGameObject.physicsBody.allowsRotation = FALSE;

If you only want shots to interact with enemies, you'll need to add this code:

shot.physicsBody.collisionBitMask = enemyCategory;
activeGameObject.physicsBody.collisionBitMask = playerShotCategory|playerCategory;

See the documentation for collisionBitMask for more information. You may need to tinker with the collisionBitMask if you have other categories that you want involved in the collisions.

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