I have a Swift file called ChainsawMaker.swift which I want to use to create chainsaws throughout my game. When I call instances of this and add it to my game, the chainsaws and it's physics body get added to the game perfectly - except for an error that pops up in the console: "Physics Body: Could not create physics body". Here is the code for ChainsawMaker.swift:
import SpriteKit
class ChainsawMaker: SKSpriteNode {
func longChainsawCreator2 () -> SKSpriteNode {
//LONG CHAINSAW
let longChainsawWidth = size.width/3
let longChainsawHeight = size.height*0.20
let chainsaw = SKSpriteNode ()
chainsaw.zPosition = 13
chainsaw.anchorPoint = CGPoint(x: 0.5, y: 0.5)
chainsaw.size = CGSize(width: longChainsawWidth, height: longChainsawHeight)
let textures = [SKTexture(imageNamed: "chainsaw1"), SKTexture(imageNamed: "chainsaw2")]
let animation = SKAction.animateWithTextures(textures, timePerFrame: 0.1)
let runSawAnimation = SKAction.repeatActionForever(animation)
chainsaw.runAction(runSawAnimation)
var offsetX = chainsaw.frame.size.width/2;
var offsetY = chainsaw.frame.size.height/2 + chainsaw.size.height/13;
var path = CGPathCreateMutable();
CGPathMoveToPoint(path, nil, chainsaw.frame.size.width/2 - offsetX, chainsaw.frame.size.height - offsetY);
CGPathAddLineToPoint(path, nil, 0 + chainsaw.frame.size.width/12 - offsetX, chainsaw.frame.size.height - offsetY);
CGPathAddLineToPoint(path, nil, 0 - offsetX, chainsaw.frame.size.height - chainsaw.size.height/2 - offsetY);
CGPathAddLineToPoint(path, nil, 0 + chainsaw.size.width/28 - offsetX, chainsaw.frame.size.height - chainsaw.size.height/2 - chainsaw.size.height/6 - offsetY);
CGPathAddLineToPoint(path, nil, 0 + chainsaw.frame.size.width/12 - offsetX, 0 + chainsaw.size.height/8 - offsetY);
CGPathAddLineToPoint(path, nil, chainsaw.size.width - chainsaw.frame.size.width/12 - offsetX, 0 + chainsaw.size.height/8 - offsetY);
CGPathAddLineToPoint(path, nil, chainsaw.size.width - offsetX, chainsaw.frame.size.height - chainsaw.size.height/2 - offsetY);
CGPathAddLineToPoint(path, nil, chainsaw.size.width - chainsaw.frame.size.width/16 - offsetX, chainsaw.size.height - offsetY);
CGPathCloseSubpath(path);
chainsaw.physicsBody = SKPhysicsBody(polygonFromPath: path)
chainsaw.physicsBody?.dynamic = true
chainsaw.physicsBody?.categoryBitMask = chainsawCategory
chainsaw.physicsBody?.contactTestBitMask = boCategory
chainsaw.physicsBody?.collisionBitMask = noneCategory
return chainsaw
}
}
And then this is how I create an instance of a chainsaw in my GamePlayScene.swift:
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var longChainsaw = ChainsawMaker()
override func didMoveToView(view: SKView) {
longChainsaw.longChainsawCreator2()
longChainsaw.position = CGPoint(x: chainsawHolder.size.width/2, y: chainsawHolder.size.height/2 - boHeight/2)