gpt4 book ai didi

swift - 为什么我的 touchesEnded 函数没有初始化?

转载 作者:搜寻专家 更新时间:2023-11-01 07:16:37 25 4
gpt4 key购买 nike

代码将返回 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)
}
}

最佳答案

您的代码中的问题是它缺少关闭 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

关于swift - 为什么我的 touchesEnded 函数没有初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41862022/

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