我的游戏不是这样,而是这样:
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var sprite = SKSpriteNode()
override func didMoveToView(view: SKView)
{
self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
self.physicsBody?.categoryBitMask = 1
self.physicsBody?.contactTestBitMask = 1
self.physicsWorld.gravity = CGVectorMake(0, -10)
self.physicsWorld.contactDelegate = self
}
func didBeginContact(contact: SKPhysicsContact) {
print("contact")
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
{
let spriteTexture = SKTexture(imageNamed: "Spaceship")
sprite = SKSpriteNode(texture: spriteTexture)
sprite.position = CGPoint(x: CGRectGetMidX(self.frame) , y: CGRectGetMidY(self.frame))
sprite.size = CGSizeMake(80, 80)
sprite.physicsBody = SKPhysicsBody(texture: spriteTexture, size: CGSizeMake(80, 80))
sprite.physicsBody?.categoryBitMask = 1
sprite.physicsBody?.collisionBitMask = 1
sprite.physicsBody?.contactTestBitMask = 1
sprite.physicsBody?.linearDamping = 0;
self.addChild(sprite)
}
}
如果粘贴此代码并运行,则会看到很多“联系”字符串。我只需要1位联络人:
所以我想当一次接触只有一次碰撞
我编辑了问题,有人可以帮忙吗?
最佳答案
1.基于SpriteKit从Xcode模板创建“基础游戏”
2.将下面的代码粘贴到GameScene
类
class GameScene: SKScene, SKPhysicsContactDelegate {
var sprite = SKSpriteNode()
override func didMoveToView(view: SKView)
{
self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
self.physicsBody?.categoryBitMask = 1
self.physicsBody?.collisionBitMask = 1
self.physicsWorld.gravity = CGVectorMake(0, -10)
self.physicsWorld.contactDelegate = self
self.physicsBody?.restitution = 0.0
}
func didEndContact(contact: SKPhysicsContact) {
print("End contact")
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
{
let spriteTexture = SKTexture(imageNamed: "Spaceship")
sprite = SKSpriteNode(texture: spriteTexture)
sprite.physicsBody = SKPhysicsBody(texture: spriteTexture, size: CGSizeMake(80, 80))
sprite.size = CGSizeMake(80, 80)
sprite.position = CGPoint(x: CGRectGetMidX(self.frame) , y: CGRectGetMidY(self.frame))
sprite.physicsBody?.categoryBitMask = 1
sprite.physicsBody?.collisionBitMask = 1
sprite.physicsBody?.contactTestBitMask = 1
sprite.physicsBody?.fieldBitMask = 1
sprite.physicsBody?.restitution = 0
self.addChild(sprite)
}
}
重要说明尝试使用
didEndContact
委托方法而不是didBeginContact
。在这种情况下,您只能获得一次调用,而didBeginContact
会调用多次。