I want to add a rectangle with a corner where the user first touches, and with its other corner where the user lifts off. I would also like the rectangle to show while the user is dragging their finger.
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches{
let position1 = touch.location(in: self)
var x1 = position1.x
var y1 = position1.y
func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches{
let position2 = touch.location(in: self)
var x2 = position2.x
var y2 = position2.y
var originX = min(x1,x2)
var originY = min(y1,y2)
var cornerX = max(x1,x2)
var cornerY = max(y1,y2)
var rect_width = cornerX - originX
var rect_height = cornerY - originY
var rect_con = CGRect(x: originX, y:originY, width: rect_width, height: rect_height)
var box = SKShapeNode(rect: rect_con)
}
}
First up, if you're only after a rectangle, you're better off doing this with just a SKSpriteNode, and scaling it, with this:
https://developer.apple.com/reference/spritekit/skspritenode/1645445-scale
Secondly, for future reference, SKShapeNode is a half (or less) complete conversion of CAShapeLayer into a VERY primitive drawing tool. It's not good at dynamic drawing, at all.
Set the anchor point of the SKSpriteNode rectangle at the touch point, and scale to the x and y of the touchesMoved. You might have to do a bit of conversion for negative values, since this is operating from an origin in cartesian coordinates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With