我似乎无法让 2 个精灵相互联系,因为当应用程序运行时,其中一个精灵没有联系,只是通过了它。我不确定有什么问题。有人可以帮助我。
import SpriteKit
import GameplayKit
enum BodyType:UInt32{
case caveMan = 1
case Zombie = 2
}
class GameScene: SKScene, SKPhysicsContactDelegate {
var caveMan:SKSpriteNode = SKSpriteNode ()
let swipeRightRec = UISwipeGestureRecognizer ()
var Zombie:SKSpriteNode = SKSpriteNode ()
override func didMove(to view: SKView) {
self.physicsWorld.contactDelegate = self
swipeRightRec.addTarget(self, action: #selector (GameScene.swipedRight ))
swipeRightRec.direction = .right
self.view!.addGestureRecognizer(swipeRightRec)
if let somePlayer:SKSpriteNode = self.childNode(withName: "caveMan") as? SKSpriteNode {
caveMan = somePlayer
caveMan.physicsBody?.affectedByGravity = true
caveMan.physicsBody?.isDynamic = false
caveMan.physicsBody?.categoryBitMask = BodyType.caveMan.rawValue
caveMan.physicsBody?.collisionBitMask = BodyType.Zombie.rawValue
caveMan.physicsBody?.contactTestBitMask = BodyType.Zombie.rawValue
}
if let somePlayer:SKSpriteNode = self.childNode(withName: "Zombie") as? SKSpriteNode {
Zombie = somePlayer
Zombie.physicsBody?.affectedByGravity = false
Zombie.physicsBody?.isDynamic = false
Zombie.physicsBody?.categoryBitMask = BodyType.Zombie.rawValue
Zombie.physicsBody?.collisionBitMask = BodyType.caveMan.rawValue
Zombie.physicsBody?.contactTestBitMask = BodyType.caveMan.rawValue
}
}
@objc func swipedRight() {
print("went right")
moveDown()
}
func moveDown() {
let walkAnimation:SKAction = SKAction(named: "Running")!
let walk:SKAction = SKAction.moveBy(x: 90, y: 0, duration: 1)
let group:SKAction = SKAction.group([walkAnimation, walk])
caveMan.run(group)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches {
self.touchDown(atPoint: t.location(in: self))
break
}
}
func didBegin(_ contact: SKPhysicsContact) {
if (contact.bodyA.categoryBitMask == BodyType.caveMan.rawValue && contact.bodyB.categoryBitMask == BodyType.Zombie.rawValue) {
print ("touched a Zombie")
} else if (contact.bodyB.categoryBitMask == BodyType.caveMan.rawValue && contact.bodyA.categoryBitMask == BodyType.Zombie.rawValue) {
print ("touched a Zombie")
}
}
}