Heyfara
Heyfara

Reputation: 521

Player controlled node ignoring collisions

I have a SKShapeNode controlled by the player. I want to keep this node inside a parent node. So I created edges and I use SKPhysicsBody and collision bit mask to prevent my node from moving outside its parent.

When I try to move the node by updating its position each frame, it just ignores the edges. Here is the function used :

func move(direction: MoveDirection, withTimeInterval timeInterval: TimeInterval) {

    var x, y: CGFloat

    switch direction {
    case .North:
        x = 0
        y = movementSpeed * CGFloat(timeInterval)

    case .South:
        x = 0
        y = -movementSpeed * CGFloat(timeInterval)

    case .East:
        x = movementSpeed * CGFloat(timeInterval)
        y = 0

    case .West:
        x = -movementSpeed * CGFloat(timeInterval)
        y = 0
    }

    let sprite = spriteComponent.sprite
    sprite.position = CGPoint(x: sprite.position.x + x, y: sprite.position.y + y)

}

The moving works great but the node can go everywhere and just doesn't care about the edges (I turned skView.showPhysics on so I can see them).

But, if I replace the line :

sprite.position = CGPoint(x: sprite.position.x + x, y: sprite.position.y + y)

by :

sprite.physicsBody?.applyForce(CGVector(dx: x, dy: y))

collisions work just fine.

It feels like we have to move objects using physics if we want them to collide. But I didn't see anything about this restriction in Apple's doc. So is this behavior expected? Or did I miss something?

Bonus point :

In the TaskBot game provided by Apple, the player's position is (or seems) changed by setting node.position (the code is a bit...complicated, so not really sure). If someone can give me a hint?

Thank you!

Upvotes: 1

Views: 51

Answers (1)

Steve Ives
Steve Ives

Reputation: 8134

If you move an SKSpriteNode manually, there will be no collisions because you are overriding the physics engine by saying "Put this node there no matter what".

If you want the physics engine to reliably generate collisions, then you'll need to use only the physics engine to move your objects via forces or impulses.

If you manually move a node into a position where it generates a collision, the the physics engine will attempt to move it away, but if you carry on trying to move the node, results will be unpredictable.

Upvotes: 1

Related Questions