i know that it's not that hard to move an object, but mine is different, i tried various ways none of them worked..
What i want to achieve?
So i went straight to the touchesBegan
and wrote the following:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
ball?.removeAllActions()
for touch in touches {
let moveBY = SKAction.moveTo(x: touch.location(in: view).x, duration: 1.0)
self.ball?.run(moveBY)
}
}
i tried four different ways, i couldn't get over it, also for your reference, here's a photo of my ball's info:
In order to move a node in a direction you want, you first have to know three things
anchorPoint
of the node you want to move anchorPoint
of the parent node of the node you want to move position
of node you want to move The anchorPoint
property of the nodes store its values in normalised way from (0, 0) to (1, 1). Defaults to (0.5, 0.5) for SPSpriteNode
The position
property of a node store its position as (x, y) coordinates in a ortogonal coordinate system in which the point (0, 0) is positioned where the anchor point of the PARENT is.
So your scene's anchorPoint
is (0.5, 0.5) meaning if you place a direct child in it at coordinates (0, 0), the child will be positioned so that its anchorPoint
is located at (0, 0) which will always match its parent's anchorPoint
.
When you are using those overloads touchesBegan, touchesMoved, etc... inside SKScene
or SKNodes
as a general, if you want to get the position of touch represented in the coordinate system in which all direct children of scene(sknode) are situated, you should do something like
class GameScene: SKScene {
override func didMove(to view: SKView) {
super.didMove(to: view)
let rect = SKSpriteNode(color: .green, size: CGSize(width: 100, height: 100))
addChild(rect)
rect.name = "rect"
// don't pay attention to these two i need them because i dont have .sks file
size = CGSize(width: 1334, height: 750)
anchorPoint = CGPoint(x: 0.5, y: 0.5)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let moveAction = SKAction.move(to: touch.location(in: self), duration: 1)
childNode(withName: "rect")?.run(moveAction)
}
}
hope it was helpful, other problems that you may have is that your ball is not direct child of scene, and you get its coordinates wrong
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.