Am working on a relatively simple kids game in spritekit, like a virtual dollhouse. In this game their are paper characters, but also some interactive objects like a bouncy ball. Currently, I am able to give the ball velocity when moving my finger, and the ball keeps up with my moving finger. However, when I keep my finger (holding the ball) still in one location on the screen, the ball becomes erratic and starts to jump all over the room or drop out of my finger. I solved this for the characters by setting isDynamic to false while they are held and updating their position to my finger, but this can't be done for the ball because it stops the velocity from working. I've included both the moveChar and moveBall functions so you can see the difference, as well as touchesMoved where they are called. Thanks!
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
// print("Ball velocity is: ", ball.physicsBody?.velocity as Any)
if let touch = touches.first {
let location = touch.location(in: self)
let startLocation = touch.previousLocation(in: self)
if let sprite = currentSpriteHeld {
if sprite == ball {
moveBall(sprite: sprite, to: location)
} else {
moveChar(sprite: sprite, to: location)
}
} else {
let impulse = CGFloat(2.0)
let dx = (impulse * (startLocation.x - location.x))
let dy = (impulse * (startLocation.y - location.y))
let cameraPos = desiredPosition;
let newCameraPos = CGPoint(x: cameraPos.x+dx, y: cameraPos.y + dy);
// cameraNode.position = newCameraPos
desiredPosition = newCameraPos
}
}
}
func moveBall(sprite: SKSpriteNode, to location: CGPoint) {
ball.physicsBody?.velocity = CGVector(dx: 0.0, dy: 0.0)
let distance = CGDistance(from: sprite.position, to: location);
print("CGDistance is: ", distance)
if distance > 10.0 {
let dx = location.x-sprite.position.x;
let dy = location.y-sprite.position.y;
let drag:CGFloat = 0.01
var vel = CGVector(dx: dx/drag, dy: dy/drag)
vel = velocityCheck(vel: vel);
sprite.physicsBody!.velocity = vel
} else {
ball.position = location;
}
}
func moveChar(sprite: SKSpriteNode, to location: CGPoint) {
if (sprite == dad) {
dad.texture = dadPickup
}
sprite.physicsBody?.isDynamic = false;
sprite.zPosition = 2;
sprite.position = location
touchPoint = location;
}
Solved: I fixed this by moving moveBall to touches ended. Now I can hold onto the ball the same way I hold on to the sprite, and apply velocity (which was causing the shaking) only when I let go.