我有一个名为ChainsawMaker.swift的Swift文件,我希望在整个游戏中使用它来创建链锯。当我调用它的实例并将其添加到我的游戏中时,链锯和它的物理主体完美地添加到游戏中 - 除了控制台中弹出的错误:“物理主体:无法创建物理主体”。以下是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
}
}
这就是我在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)