Pablo
Pablo

Reputation: 1332

Check for contact before sprite enters another sprite

I am checking when a sprite touches another sprite, it will stop moving. So I am pretty much creating a barrier for the main player:

enter image description here

When the contact delegate is triggered, I set the player's velocity to 0, and it works perfectly to stop movement when it reaches the barrier. However, if the player hits the barrier, it slightly goes inside the node:

enter image description here

Therefore, if it goes left or right, it will "contact" again with the other two barriers on the side. It should be able to move left and right freely, even if it is touching a barrier. However, due to the main player going "inside" the barrier, it is triggering unwanted contacts. I figured the solution would be to check for contacts before the player goes inside the other sprite nodes, how can I check for that?

EDIT

I figured out the best way to create a barrier is to simply allow collisions to happen and make the barrier block have a great mass. What is the greatest CGFloat I can assign to a SKSpriteNode?

EDIT

They are still getting stuck in corners, even after setting the mass to a huge amount.

EDIT

I really like the suggestion of using SKConstraints, I tried doing this:

    var constraints = [SKConstraint]()

    constraints.append(SKConstraint.distance(SKRange(lowerLimit: 10),
                                                 to: ent[0]))
    constraints.append(SKConstraint.distance(SKRange(lowerLimit: 10),
                                             to: ent[1]))
    constraints.append(SKConstraint.distance(SKRange(lowerLimit: 10),
                                             to: ent[2]))


    mainPlayer.constraints = constraints

However, the mainPlayer goes right through the blocks. The blocks are not static, but since they do not collide, it goes right through them. What I am doing wrong?

Upvotes: 2

Views: 209

Answers (1)

Fluidity
Fluidity

Reputation: 3995

I suggest adding an SKConstraint to the player (or to the boxes), so that after simulating physics your character will always be at least 1 pixel away from the boxes (so as to not trigger another velocity = 0).

Since constraints are handled AFTER physics in spritekit, this should work fairly well:

enter image description here

Something like this should work:

 let boxes: [SKNode] = [leftBox, middleBox, rightBox]
 var constraints = [SKConstraint]()
 for box in boxes {
      constraints.append(SKConstraint.distance(SKRange(lowerLimit: 5),
                                               to: box)
 }

player.constraints = constraints

SKConstraint documentation

note: you may need adjust the distance of the lowerLimit in the constraint to get the desired effect, or add more .distance constraints to your main player.. say, one for each corner of each box.

Upvotes: 0

Related Questions