我試圖檢測玩家對象何時與我遊戲中的其他物體發生碰撞。這是我當前的代碼:兩個精靈之間的碰撞檢測不起作用
import SpriteKit
class GameScene: SKScene {
let player = SKSpriteNode(imageNamed: 「Box」)
override func didMoveToView(view: SKView) {
backgroundColor = SKColor.whiteColor()
player.position = CGPoint(x: size.width/2, y: size.height/2)
addChild(player)
runAction(SKAction.repeatActionForever(
SKAction.sequence([
SKAction.runBlock(addObject),
SKAction.waitForDuration(1)
])
))
runAction(SKAction.repeatActionForever(
SKAction.sequence([
SKAction.runBlock(addSecondObject),
SKAction.waitForDuration(1)
])
))
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
player.position = location
}
}
func EndGame() {
println("GAME OVER")
}
func Collision() {
if (CGRectIntersectsRect(player.frame, object.frame)) {
[EndGame];
}
if (CGRectIntersectsRect(player.frame, object1.frame)) {
[EndGame];
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
func addObject() {
let object = SKSpriteNode(imageNamed: "object1」)
object.name = "object1」
object.position = CGPoint(x: size.width/4, y: size.height/4)
self.addChild(object)
}
func addSecondObject() {
let object = SKSpriteNode(imageNamed: "object2」)
object.name = "object2」
object.position = CGPoint(x: size.width/2, y: size.height/2)
self.addChild(object)
}
}
所以你可以看到我的碰撞代碼是這樣的:
func Collision() {
if (CGRectIntersectsRect(player.frame, object.frame)) {
[EndGame];
}
if (CGRectIntersectsRect(player.frame, object1.frame)) {
[EndGame];
}
}
的問題是,由於對象和對象1個變量是私有的FUNC( addObject)和func(addSecondObject),我不能在上面的代碼中調用它們。當他們碰撞時,目前我只想讓EndGame()運行,在控制檯中輸出「Game Over」。
我不知道我採取的碰撞檢測方法是否正確,但任何幫助都會很棒!謝謝:)
謝謝你,在那裏我會寫,如果節點碰撞,運行[殘局]? – bandoy123 2015-02-05 21:25:52
此外,對象是否必須全局聲明? – bandoy123 2015-02-05 21:27:26
我已經添加了一個指向教程的鏈接:http://www.raywenderlich.com/84434/sprite-kit-swift-tutorial-beginners。嘗試一下。這就是我開始用精靈套件編寫遊戲的過程,它非常棒。 – Christian 2015-02-05 21:32:23