gpt4 book ai didi

ios - 在 SKLabelNode 中识别触摸的问题

转载 作者:行者123 更新时间:2023-11-28 13:17:03 25 4
gpt4 key购买 nike

我已经使用 Swift 编程大约四个月了,现在使用 Sprite Kit 为 IOS 构建一些简单的 Arcade 游戏。直到最近,我在识别特定节点中的触摸方面都没有遇到任何问题。在我的一个项目的主屏幕中,我添加了另一个 SKLabelNode 用于应用程序的最新添加,遵循与其他项目相同的实现布局,但这个不起作用。当点击标签时,它应该运行一个函数但甚至没有那么远,我想出了使用断点。这是所有相关代码,请看一下,我已经看了四个多小时,这让我发疯。

import SpriteKit

let twistedLabelName = "twisted"

class StartScene: SKScene {

var play1P = SKLabelNode(fontNamed: "HelveticaNeue-Thin")
var play2P = SKLabelNode(fontNamed: "HelveticaNeue-Thin")
var playTwisted = SKLabelNode(fontNamed: "HelveticaNeue-Thin")

override func didMoveToView(view: SKView) {
initializeValues()
self.userInteractionEnabled = true
}

func initializeValues () {
backgroundColor = UIColor.whiteColor()


play1P.name = "1p"
play1P.text = "Play 1P"
play1P.fontColor = SKColor.blackColor()
play1P.fontSize = 40
play1P.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetHeight(self.frame) * 0.8)
play1P.zPosition = 100

self.addChild(play1P)


play2P.name = "2p"
play2P.text = "Play 2P"
play2P.fontColor = SKColor.blackColor()
play2P.fontSize = 40
play2P.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetHeight(self.frame) * 0.6)
play2P.zPosition = 100

self.addChild(play2P)

playTwisted.text = "Twisted"
playTwisted.fontColor = SKColor.blackColor()
playTwisted.name = twistedLabelName
playTwisted.fontSize = 40
playTwisted.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetHeight(self.frame) * 0.4)

self.addChild(playTwisted)
}

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
for touch in touches {
let location = touch.locationInNode(self)
if let theName = self.nodeAtPoint(location).name {
if theName == "1p" {
// Some function
}
else if theName == "2p" {
// Some function
}
else if theName == twistedLabelName {
// This is the one that doesn't work
// Some function
}
}
}
}
}

最佳答案

请注意,您可以扩展任何 SKNode(包括 SKLabelNode)并在子类中处理触摸。首先设置 isUserInteractionEnabled = true。例如

import SpriteKit

class MyLabelNode: SKLabelNode {
override init() {
super.init()
isUserInteractionEnabled = true
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
isUserInteractionEnabled = true
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
print( #file + #function )
}
}

关于ios - 在 SKLabelNode 中识别触摸的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28604885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com