Let's say we add the same node around 1000 times like shown in the code below. Is there any way to have access of every single platform?
For e.g., if there is a collision between the PlatformCategory
and the PlayerCategory
, the Platform that had the collision should change its color to green and run a SKAction
.
Edit: Thanks to Whirlwind, I can get the platform that collides with the player change to green, while all other stay red. Now I need to set the collision properly, which means I only want the Player
to collide with Platform
when it is above it.
For e.g., the Player jumps from the 1. platform to the 2. platform. While jumping, it should not collide with the 2nd platform, only after it passed it.
class GameScene: SKScene, SKPhysicsContactDelegate {
let PlayerCategory : UInt32 = 0x1 << 1
let PlatformCategory : UInt32 = 0x1 << 2
var Platform: SKSpriteNode!
var Player: SKSpriteNode!
override func didMoveToView(view: SKView) {
/* Setup your scene here */
self.physicsWorld.contactDelegate = self
self.physicsBody?.velocity = CGVectorMake(0, 0)
.....
SpawnPlayer()
generatePlatforms()
}
func SpawnPlatforms(position: CGPoint)->SKSpriteNode{
Platform = SKSpriteNode(color: SKColor.redColor(), size: CGSize(width: self.frame.size.width, height: 25))
Platform.position = position
Platform.zPosition = 1
Platform.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: self.frame.size.width, height: 25))
Platform.physicsBody?.dynamic = false
Platform.physicsBody?.restitution = 0.0
Platform.physicsBody?.allowsRotation = false
Platform.physicsBody?.usesPreciseCollisionDetection = true
Platform.physicsBody?.categoryBitMask = PlatformCategory
Platform.physicsBody?.contactTestBitMask = PlayerCategory
Platform.physicsBody?.collisionBitMask = PlayerCategory
return Platform
}
func generatePlatforms(){
for i in 1...1000{
let position = CGPoint(x: self.frame.size.width / 2, y: 140 * CGFloat(i))
let platform = SpawnPlatforms(position)
self.addChild(platform)
}
}
func didBeginContact(contact: SKPhysicsContact) {
let contactMask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask
let platform = contact.bodyB.node as! SKSpriteNode
switch(contactMask) {
case PlayerCategory | PlatformCategory:
//either the contactMask was the bro type or the ground type
print("Contact Made0")
if(Player.position.y >= platform.position.y && Player.position.y <= platform.position.y + Player.size.height){
Player.physicsBody?.collisionBitMask = PlatformCategory
platform.color = SKColor.greenColor()
}
default:
return
}
}
func didEndContact(contact: SKPhysicsContact) {
let contactMask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask
switch(contactMask) {
case PlayerCategory | PlatformCategory:
//either the contactMask was the bro type or the ground type
print("Contact Made0")
default:
return
}
}