代码将返回x1和y1值,但似乎没有通过touchesEnded函数运行。我的目标是从用户触摸的角落开始创建一个矩形,并结束用户抬起手指的位置。
//touch initialized
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
let x1 = location.x
let y1 = location.y
print(x1,y1)
}
func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?){
for touch in touches{
let location2 = touch.location(in: self)
let x2 = location2.x
let y2 = location2.y
let originX = min(x1,x2)
let originY = min(y1,y2)
let cornerX = max(x1,x2)
let cornerY = max(y1,y2)
let boxWidth = cornerX - originX
let boxHeight = cornerY - originY
let box = SKSpriteNode()
box.size = CGSize(width: boxWidth, height: boxHeight)
box.color = SKColor.black
box.position = CGPoint(x:originX, y: originY)
addChild(box)
print(x1,y1,x2,y2)
}
}
答案 0 :(得分:2)
您的代码中的问题是它缺少一个大括号来关闭touchesBegan
,因此不允许覆盖touchesEnded
,因为它在技术上位于您的touchesBegan
而不是场景中本身。
试试这个:
var x1: CGFloat = 0.0
var y1: CGFloat = 0.0
//...
//touch initialized
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
x1 = location.x
y1 = location.y
print(x1,y1)
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?){
for touch in touches{
let location2 = touch.location(in: self)
let x2 = location2.x
let y2 = location2.y
let originX = min(x1,x2)
let originY = min(y1,y2)
let cornerX = max(x1,x2)
let cornerY = max(y1,y2)
let boxWidth = cornerX - originX
let boxHeight = cornerY - originY
let box = SKSpriteNode()
box.size = CGSize(width: boxWidth, height: boxHeight)
box.color = SKColor.black
box.position = CGPoint(x:originX, y: originY)
addChild(box)
print(x1,y1,x2,y2)
}
}
当然,我不会分别保存每个x和y坐标,而是会存储两个CGPoints