无法将PhysicsBody添加到SKSpriteNode(游戏崩溃)

时间:2015-03-06 21:54:17

标签: xcode swift sprite-kit skspritenode

我一直在玩XCode / Swift的一些功能并构建一个简单的游戏。我在将一个physicsBody添加到SKSpriteNode时遇到了困难。 我创造了一个子弹'班级和坦克' class(其数组为10' Bullets'作为其属性之一)。

正在使用纹理正确分配sprite属性。然而,物理学的身体又回来了。

class Tank {
var position = CGPoint()
var speed = CGPoint(x: 0, y: 0)
var sprite = SKSpriteNode()
var viewSize = CGPoint()    // width, height
var bullets: [Bullet] = []
var bulletNumber = 0
let TOTAL_BULLETS = 10

// ***Tank class constructor
init(playerNum: Int, filename: NSString, tankName: NSString) {
    var spaceshipTexture = SKTexture(imageNamed: "Spaceship")
    self.sprite = SKSpriteNode(texture: spaceshipTexture, size: spaceshipTexture.size())
    self.sprite.physicsBody? = SKPhysicsBody(texture: spaceshipTexture, size: spaceshipTexture.size())
    println(self.sprite.physicsBody)

}

// ****Bullet class 
class Bullet {
var position = CGPoint(x: -50, y: -50)
var speed = CGPoint(x: 0, y: 0)
var sprite = SKSpriteNode()
var viewSize = CGPoint()    // width, height
var isBeingFired = false

init () {
    //self.sprite = SKSpriteNode(imageNamed: "Bullet")
    var spaceshipTexture = SKTexture(imageNamed: "Spaceship")
    self.sprite = SKSpriteNode(texture: spaceshipTexture, size: spaceshipTexture.size())
    self.sprite.xScale = 0.04
    self.sprite.yScale = 0.04
    self.sprite.physicsBody? = SKPhysicsBody(texture: spaceshipTexture, size: spaceshipTexture.size())
    self.sprite.physicsBody?.affectedByGravity = false
    println(self.sprite.physicsBody)
}


// *** GameScene
class GameScene: SKScene {
var tank1 = Tank(playerNum: 1, filename: "Spaceship", tankName: "Tank1")
let myLabel = SKLabelNode(fontNamed:"Chalkduster")

override func didMoveToView(view: SKView) {

    self.addChild(tank1.sprite)

    for i in 0 ..< tank1.TOTAL_BULLETS {
        self.addChild(tank1.bullets[i].sprite)
    }

为简单起见,我对Tank和Bullet(只是不同的大小)使用相同的图像来创建SKSpriteNode。

我不确定这是否会有所帮助,但我在游戏中添加了坦克及其所有10颗子弹的实例。

1 个答案:

答案 0 :(得分:0)

您的问题是,您没有向SKTexture添加SKSpriteNode图片。如果您想访问SKTexture,则需要将其添加到节点中:

var spaceshipTexture = SKTexture(imageNamed: "Spaceship")

var sprite = SKSpriteNode(texture: spaceshipTexture, size: spaceshipTexture.size())

然后,您将能够访问精灵的纹理以创建SKPhysicsBody