我正在尝试检测玩家对象何时与我游戏中的其他对象发生碰撞。这是我目前的代码:
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”。
我不知道我采取的碰撞检测方法是否正确,但任何帮助都会很棒!谢谢:))
答案 0 :(得分:0)
对于非常基本的精灵,是的,它的权利。你可以想象一个对角线图像" /"即使实际物体没有重叠,如果它的左上角与某物重叠,也会触发碰撞。
Apple有一个讨论碰撞的好页面:https://developer.apple.com/library/ios/documentation/GraphicsAnimation/Conceptual/CodeExplainedAdventure/HandlingCollisions/HandlingCollisions.html
此外,许多YouTube视频谈论如何让这类事情发挥作用。例如:https://www.youtube.com/watch?v=dX0KvKtc3_w
你需要让碰撞检测代码运行(可能在计时器或其他东西上),然后,或许,传入你想要检查的对象或使这些对象成为类的成员(IBOutlet)或类似的策略获得访问权限。
答案 1 :(得分:0)
您必须使用SKPhysicsbody:
struct PhysicsCategory {
static let None : UInt32 = 0
static let Player : UInt32 = 0b1
static let Object : UInt32 = 0b10
}
player.physicsBody = SKPhysicsBody(rectangleOfSize: player.size) // 1
player.physicsBody?.dynamic = true // 2
player.physicsBody?.categoryBitMask = PhysicsCategory.Player// 3
player.physicsBody?.contactTestBitMask = PhysicsCategory.Object//4
player.physicsBody?.collisionBitMask = PhysicsCategory.None // 5
SKPhysicsBody
并将其设置为播放器对象的大小categoryBitMask
。这就像你的SKNode的标识符。所以其他SKNodes可以在你身上注册并说:“嘿,我想知道我是否触摸那个人”。有关更多信息和精彩的入门教程,请使用raywenderlichs tutorial.