我正在尝试通过添加一个可以检测到掉落节点的位置来扩展我在Drag and drop example上学习的拖放示例。
从我尝试检测到掉落的节点开始,我了解到放下一个节点并期望它精确命中预定位置非常困难。
如何定义一个位置或像一个更大的矩形来检测放置的节点?
//: A SpriteKit based Playground
import PlaygroundSupport
import SpriteKit
class GameScene: SKScene {
private var currentNode: SKNode?
override func didMove(to view: SKView) {
let node = SKSpriteNode(
color: .red,
size: CGSize(width: 50, height: 50)
)
node.name = "draggable"
self.addChild(node)
let blueNode = SKSpriteNode(
color: .blue,
size: CGSize(width: 50, height: 50)
)
blueNode.name = "draggable"
self.addChild(blueNode)
let greenNode = SKSpriteNode(
color: .green,
size: CGSize(width: 50, height: 50)
)
greenNode.name = "droppable"
greenNode.position = CGPoint(x: 100, y: 100)
self.addChild(greenNode)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let location = touch.location(in: self)
let touchedNodes = self.nodes(at: location)
for node in touchedNodes.reversed() {
if node.name == "draggable" {
self.currentNode = node
}
}
}
}
@objc static override var supportsSecureCoding: Bool {
// SKNode conforms to NSSecureCoding, so any subclass going
// through the decoding process must support secure coding
get {
return true
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first, let node = self.currentNode {
let touchLocation = touch.location(in: self)
node.position = touchLocation
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
print(self.currentNode!.position);
if self.currentNode!.position == CGPoint(x:100,y:100) {
let yellowNode = SKSpriteNode(
color: .yellow,
size: CGSize(width: 50, height: 50)
)
yellowNode.name = "droppable"
yellowNode.position = CGPoint(x: 200, y: 200)
self.addChild(yellowNode)
}
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
self.currentNode = nil
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
}
}
// Load the SKScene from 'GameScene.sks'
let sceneView = SKView(frame: CGRect(x:0 , y:0, width: 640, height: 480))
if let scene = GameScene(fileNamed: "GameScene") {
// Set the scale mode to scale to fit the window
scene.scaleMode = .aspectFill
// Present the scene
sceneView.presentScene(scene)
}
PlaygroundSupport.PlaygroundPage.current.liveView = sceneView
答案 0 :(得分:1)
我假设您正在touchesEnded(...)
函数中寻求建议。
您是对的:就像在
中一样,检查位置是否正确if self.currentNode!.position == CGPoint(x:100,y:100) {}
不会带你走得太远。手动点击屏幕上的特定点非常困难。
例如,您可以使用CGRect
指定目标区域,然后检查触摸的位置是否在矩形内。
let targetRect = CGRect(x: 0, y: 0, width: 200, height: 200)
guard let node = self.currentNode else {return} // Just to avoid forced unwrapping
if targetRect.contains(node.position) {
// Do stuff
}