[英]Swift Sprite-Kit: How do I increase my game's score when screen is touched?
在我的游戲中,每次觸摸會將背景向下移動50個像素,我希望將某個動畫期間的每次觸摸轉換為50分。在我的代碼中,我有兩個背景節點,使我的背景在每次觸摸時向下滾動而沒有間隙在后台。 運行綠燈動畫時更新分數時出現問題,而在紅燈動畫期間觸摸屏幕時使游戲結束。 我已經創建了分數標簽。 先感謝您。
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */
if bg.position.y + bg.size.height/2 < 50
{
let diff = bg.position.y + bg.size.height/2 - 50
bg.position.y = self.frame.height + bg.size.height/2 + diff
}
else
{
bg.position.y -= 50
}
if bg2.position.y + bg2.size.height/2 < 50
{
let diff = bg2.position.y + bg2.size.height/2 - 50
bg2.position.y = self.frame.height + bg2.size.height/2 + diff
}
else
{
bg2.position.y -= 50
}
}
您可以為greenLightIsShowing和redLightIsShowing設置布爾值,並根據顯示的時間將它們設置為true和false。 然后在bool為真時處理觸摸。
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
if greenLightIsShowing == true {
if nodeAtPoint(location) == self.view {
score = score + 50
scoreLable.text = "\(score)"
}
}else if redLightIsShowing == true {
if nodeAtPoint(location) == self.view {
//end the game
}
}
嘗試這個
class GameScene: SKScene {
var currentLight : SKSpriteNode!
var greenTexture : SKTexture!
var redTexture : SKTexture!
var isGreenLightON : Bool = true
var score : Int = 0
override func didMoveToView(view: SKView) {
/* Setup your scene here */
greenTexture = SKTexture(imageNamed: "green light.png")
redTexture = SKTexture(imageNamed: "red light.png")
currentLight = SKSpriteNode(texture: greenTexture)
currentLight.position = CGPointMake(CGRectGetMidX(self.frame), 650)
let changeToGreenLight : SKAction = SKAction.runBlock({ () -> Void in
self.currentLight.texture = self.greenTexture
self.isGreenLightON = true
})
let changeToRedLight : SKAction = SKAction.runBlock({ () -> Void in
self.currentLight.texture = self.redTexture
self.isGreenLightON = false
})
let changingLights = SKAction.sequence([changeToGreenLight,SKAction.waitForDuration(1, withRange: 4),changeToRedLight,SKAction.waitForDuration(1, withRange: 4)])
currentLight.runAction(SKAction.repeatActionForever(changingLights))
self.addChild(currentLight)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
if isGreenLightON
{
score += 50
}
else
{
score -= 10
}
println(score)
scoreLabel.text = "\(score)"
}
override func update(currentTime: CFTimeInterval) {
// Your Code
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.