Maci
Maci

Reputation: 123

Add Velocity to SKPhysicsBody while moving it's SKSpriteNode

Right now I am moving a SKSpriteNode by changing it's position during func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?).

My problem with that is that while I am moving the SpriteNode, it's SKPhysicsBody's velocity is not changed. Therefore when that SpriteNode does collide with another SKSpriteNode that second SpriteNode will only get pushed around and not really bounce off like you would expect it.

Is there anyway to fix that? I was already thinking about manually applying velocity to that second SpriteNode on func didBegin(_ contact: SKPhysicsContact) but I would not really be happy with that kind of solution.

Thanks!

Upvotes: 1

Views: 401

Answers (1)

peacetype
peacetype

Reputation: 2068

Generally speaking, in SpriteKit you should avoid mixing physics-based movement with direct movement. By physics-based movement, I mean moving a node's physics body by applying a force/impulse or setting its velocity property directly. By direct movement, I mean things like settings its position property directly (which it sounds like you are doing) or using an SKAction like moveTo:duration:.

So if you are already using physics to move a node, you should continue using physics to move it rather than altering its movement directly. Or if you are moving a node using direct movement only, and then you want to find out things about its speed (such as velocity in your case), you will have to write your own calculations to figure out how far the object moves between frames. This is because the object's movement is not being performed by the physics engine.

Of course, you don't have to follow this practice. But you might run into issues like the one you have encountered.

One additional point is that if you want to detect if two nodes contact each other---but not collide with each other---then it's okay to use direct movement on physics bodies. But in your case it sounds like you are dealing with colliding bodies, so I'd recommend sticking with one approach or the other to keep things neat.

Upvotes: 2

Related Questions