我无法找到一种方法来为我的游戏添加分数系统。有人可以帮助我以可视化的GUI方式做到这一点吗?非常感谢。我试过用int变量做这个,但它不会工作。如果你再次提供帮助,非常感谢你
import SpriteKit
let BallCategoryName = "ball"
let PaddleCategoryName = "paddle"
let BlockCategoryName = "block"
let BlockNodeCategoryName = "blockNode"
let BallCategory : UInt32 = 0x1 << 0 // 00000000000000000000000000000001
let BottomCategory : UInt32 = 0x1 << 1 // 00000000000000000000000000000010
let BlockCategory : UInt32 = 0x1 << 2 // 00000000000000000000000000000100
let PaddleCategory : UInt32 = 0x1 << 3 // 00000000000000000000000000001000
class GameScene: SKScene, SKPhysicsContactDelegate {
var isFingerOnPaddle = false
override func didMoveToView(view: SKView) {
super.didMoveToView(view)
let bottomRect = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, 1)
let bottom = SKNode()
bottom.physicsBody = SKPhysicsBody(edgeLoopFromRect: bottomRect)
addChild(bottom)
// 1. Create a physics body that borders the screen
let borderBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
// 2. Set the friction of that physicsBody to 0
borderBody.friction = 0
// 3. Set physicsBody of scene to borderBody
self.physicsBody = borderBody
physicsWorld.gravity = CGVectorMake(0, 0)
let ball = childNodeWithName(BallCategoryName) as! SKSpriteNode
ball.physicsBody!.applyImpulse(CGVectorMake(10, -10))
ball.physicsBody!.allowsRotation = false
ball.physicsBody!.friction = 0
ball.physicsBody!.restitution = 1
ball.physicsBody!.linearDamping = 0
ball.physicsBody!.angularDamping = 0
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
var touch = touches.first as! UITouch
var touchLocation = touch.locationInNode(self)
if let body = physicsWorld.bodyAtPoint(touchLocation) {
if body.node!.name == PaddleCategoryName {
println("Began touch on paddle")
isFingerOnPaddle = true
}
}
}
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
// 1. Check whether user touched the paddle
if isFingerOnPaddle {
// 2. Get touch location
var touch = touches.first as! UITouch
var touchLocation = touch.locationInNode(self)
var previousLocation = touch.previousLocationInNode(self)
// 3. Get node for paddle
var paddle = childNodeWithName(PaddleCategoryName) as! SKSpriteNode
// 4. Calculate new position along x for paddle
var paddleX = paddle.position.x + (touchLocation.x - previousLocation.x)
// 5. Limit x so that paddle won't leave screen to left or right
paddleX = max(paddleX, paddle.size.width/2)
paddleX = min(paddleX, size.width - paddle.size.width/2)
// 6. Update paddle position
paddle.position = CGPointMake(paddleX, paddle.position.y)
}
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
isFingerOnPaddle = false
}
}
答案 0 :(得分:2)
要在游戏中添加分数系统,首先需要跟踪分数,这可能是一个Int变量。
至于在GUI上以可视方式显示它,您可以使用SKLabelNode来表示屏幕上的文本,并根据用户的当前分数进行更新,该分数将由您使用的Int变量表示。
至于持久化数据,请查看NSCoding,NSUserDefaults以存储该分数,以便下次用户运行应用程序时可以再次使用它。