In my game scene I have a ball, a magnet and a platform called leveUnit as seen below
import SpriteKit
import GameplayKit
class GameScene: SKScene {
var ball = SKShapeNode()
var magnet = SKShapeNode()
let worldNode:SKNode = SKNode()
var levelUnit = SKSpriteNode()
override func didMove(to view: SKView) {
ball = SKShapeNode(circleOfRadius: 30)
ball.fillColor = .yellow
ball.position = CGPoint(x: 0, y: 200)
magnet = SKShapeNode(circleOfRadius: 30)
magnet.fillColor = .blue
magnet.position = CGPoint(x: 0, y: 0)
levelUnit = SKSpriteNode(imageNamed: "Wall")
levelUnit.position = CGPoint(x: 0, y: 250)
worldNode.addChild(levelUnit)
self.anchorPoint = CGPoint(x: 0.5, y: 0.5)
addChild(worldNode)
worldNode.addChild(magnet)
//addChild(ball)
levelUnit.addChild(ball)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch: UITouch = touches.first!
let location: CGPoint = touch.location(in: self)
let node: SKNode = self.atPoint(location)
if node == self {
magnet.position = location
}
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
let playerLocation:CGPoint = self.convert(magnet.position, from: worldNode)
let location = playerLocation
let nodeSpeed:CGFloat = 20.5
let node = ball
//Aim
let dx = location.x - (node.position.x)
let dy = location.y - (node.position.y)
let angle = atan2(dy, dx)
node.zRotation = angle
//Seek
let vx = cos(angle) * nodeSpeed
let vy = sin(angle) * nodeSpeed
node.position.x += vx
node.position.y += vy
}
}
My problem here is when I add the ball to the levelUnit instead of just to the view itself it doesn't seem to follow the magnet to its exact position it just seems to hover slightly above its position while when I have it added to the view itself it goes to the magnets exact location. I am using the solution from this question here to make the ball go to the magnet's location.
what am I doing wrong? and what is causing this to happen?