Reputation: 79
The code will return the x1 and y1 values, but does not seem to be running through the touchesEnded function. My goal is to create a rectangle starting at a corner where the user touches and ending where the user lifts their finger.
//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)
}
}
Upvotes: 1
Views: 80
Reputation: 1664
The problem in your code is that it's missing a curly bracket to close touchesBegan
, so touchesEnded
is not allowed to be overridden because it's technically in your touchesBegan
rather than in the scene itself.
Try this:
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)
}
}
Of course, instead of saving each x and y coordinates separately, I would jut store two CGPoints
Upvotes: 2