1
votes

I'm making a simple game. Hero should jump over the enemies and if they collide - enemy should eat the hero. I have 4 types of enemies randomly spawning in front of a hero. I use the first sprite of every enemy-array as a main, the rest are for animation. But when they collide - nothing happens, it's still the first sprite. That's how I'm doing it:

let mouseAtlas = SKTextureAtlas(named: "mouse") 
mouseArray.append(mouseAtlas.textureNamed("mouse_0"));
mouseArray.append(mouseAtlas.textureNamed("mouse_1"));
mouseArray.append(mouseAtlas.textureNamed("mouse_2"));
mouseArray.append(mouseAtlas.textureNamed("mouse_3"));

Mouse is an enemy, cookie is a hero.

mouse = SKSpriteNode(texture: mouseArray[0]);
self.mouse.position = CGPointMake(CGRectGetMaxX(self.frame) + self.cookie.size.width, self.cookieSpot + self.cookie.size.height + self.cookie.size.height / 2)
self.mouse.size = CGSizeMake(self.cookie.size.width + self.cookie.size.width / 2, self.cookie.size.height + cookie.size.height / 2)    

self.addChild(cookie)
self.addChild(mouse)

Then I'm applying physic bodies to them:

self.cookie.physicsBody = SKPhysicsBody(circleOfRadius: CGFloat(self.cookie.size.width / 2))
self.cookie.physicsBody?.affectedByGravity = false
self.cookie.physicsBody?.categoryBitMask = ColliderType.Cookie.rawValue
self.cookie.physicsBody?.collisionBitMask = ColliderType.Pet.rawValue
self.cookie.physicsBody?.contactTestBitMask = ColliderType.Pet.rawValue

self.mouse.physicsBody = SKPhysicsBody(rectangleOfSize: self.mouse.size)
self.mouse.physicsBody?.dynamic = false
self.mouse.physicsBody?.categoryBitMask = ColliderType.Pet.rawValue
self.mouse.physicsBody?.contactTestBitMask = ColliderType.Cookie.rawValue
self.mouse.physicsBody?.collisionBitMask = ColliderType.Cookie.rawValue    

And then I'm trying to make an animation when contact begins:

func didBeginContact(contact: SKPhysicsContact) {
    eatenByMouse(); eatenByHamster(); eatenByRabbit(); eatenByCat()
}

func eatenByMouse() {
    self.groundSpeed = 0
    self.cookie.hidden = true
 let animateAction = SKAction.animateWithTextures(self.mouseArray, timePerFrame: 0.1)
}

Like I said, there are 4 types of enemies but they are practically the same. What am I doing wrong with that? An I also interested, could I make physics body of enemies only on one side? I mean how can one make my hero eaten only if it touched enemies mouth for example? And if it touches the tail it would proceed rolling and jumping? Many thanks!

1

1 Answers

0
votes

You have to run the SKAction after creating it.

func eatenByMouse() {
    self.groundSpeed = 0
    self.cookie.hidden = true
    let animateAction = SKAction.animateWithTextures(self.mouseArray, timePerFrame: 0.1)
    self.mouse.runAction(animateAction) // added line.
}

You can use SKPhysicsContact.contactPoint to detect point of collision.