I have a SpriteKit scene with an SKFieldNode.linearGravityField(withVector:)
and an SKSpriteNode
that has a physicsBody
. The user moves the sprite with their finger.
I'm moving the sprite by explicitly setting its velocity
in update(_:)
, which causes a problem: the field doesn't affect the sprite when the user's finger is touching the screen because my code overrides it. When the user's finger is not touching the screen, the field works as desired.
Here's how I'm setting the sprite's velocity
:
override func update(_ currentTime: TimeInterval) {
//NOTE: intensityX and intensityY are based on how far the user has dragged their finger, and are set in touchMoved().
if intensityX != 0.0 {
mainCharacter?.physicsBody?.velocity.dx = intensityX
}
if intensityY != 0.0 {
mainCharacter?.physicsBody?.velocity.dy = intensityY
}
}
And here's how I'm creating the field:
let field = SKFieldNode.linearGravityField(withVector: vector_float3(-9.0,0,0))
field.region = SKRegion(size: CGSize(width: screenWidth, height: screenHeight*0.1))
field.position = CGPoint(x: screenWidth, y: screenHeight*0.2)
addChild(field)
Question: How might I go about making it so the field affects the sprite even when the sprite is being moved by the user?
Thanks!
The answer to this problem is to apply some force to the sprite's physicsBody
instead of explicitly setting its velocity. Explicitly setting its velocity overrides the physics of the field, which is no good.
In update(_:)
, I'm now using applyForce(_:)
.
mainCharacter?.physicsBody?.applyForce(CGVector(dx: someForceX, dy: 0.0))
This allows the user to move the sprite while still experiencing the effects of the field.