gpt4 book ai didi

swift - 背景图像节点干扰触摸命令

转载 作者:行者123 更新时间:2023-11-28 09:17:06 24 4
gpt4 key购买 nike

我正在创建一个游戏场景,它包含两个节点,其中一个是背景节点。但是调用touchesbegan命令时,注册的节点是后台节点,不是我要求移动的节点。

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

for touch: AnyObject in touches{
let touchLocation = touch.locationInNode(self)
let touchedNode = nodeAtPoint(touchLocation)
touchedNode.position = touchLocation
}

}

最佳答案

这是一个如何允许用户拖放节点的示例:

let background = SKSpriteNode(color:SKColor.blueColor(),size:CGSizeMake(200, 200))
let player = SKSpriteNode(color: SKColor.whiteColor(), size: CGSizeMake(32, 32))
var selectedNode:SKNode?

override func didMoveToView(view: SKView) {
let point = CGPointMake (CGRectGetWidth(view.frame)/2,CGRectGetHeight(view.frame)/2)
background.position = point
background.zPosition = 0
self.addChild(background)

// Give the node a name so we can identify it in the touch handler
player.name = "player"
// Ensure that the player rendered over the background
player.zPosition = 1
player.position = point
self.addChild(player)
}

选择用户触摸的节点

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
for touch: AnyObject in touches{
let touchLocation = touch.locationInNode(self)
let touchedNode = nodeAtPoint(touchLocation)
// Only allow the user to select "player" nodes
if (touchedNode.name == "player") {
selectedNode = touchedNode;
}
}
}

随着触摸位置的变化更新选中节点的位置

override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
for touch: AnyObject in touches{
let touchLocation = touch.locationInNode(self)
if (selectedNode != nil) {
selectedNode!.position = touchLocation
}
}
}

触摸结束时取消选中节点

override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
selectedNode = nil;
}

关于swift - 背景图像节点干扰触摸命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27075708/

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