Steve Steve - 10 months ago 29
Swift Question

Changing collisionBitMask according to y value ascending or descending

Swift - SpriteKit

I am making my first game and I have my

var Player = SKSpriteNode()

and also
var platform = SKNode()

I want to detect when the player is increasing in y direction so i can turn off
. Therefore making it possible to jump up through platforms when jumping and when he is falling he will land on the platforms.

So I can have something like:

if player.position.y = increasing {
Player.physicsBody?.collisionBitMask = nil
Player.physicsBody?.collisionBitMask = PhysicsCategory.Platform

I have looked around and cannot find what I am after, unless I'm looking for the wrong thing.

Many thanks.

Edit: Solved check EmilioPelaez answer, just showing how I i slightly changed it here.

var lastY: CGFloat?
outside the functions with all my other variables.

override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
// Checking y direction
if Player.position.y > lastY {
// Player increasing in y direction
Player.physicsBody?.collisionBitMask = PhysicsCategory.Ground
} else {
// Player decreasing in y direction
Player.physicsBody?.collisionBitMask = PhysicsCategory.Ground | PhysicsCategory.Platform

lastY = Player.position.y


Basically, what you want to do is to compare the current value to the value in the previous frame.

The easiest way to do this is to make a variable where you can store the previous value, and use that to do the comparison. Once you have done the comparison you store the current value in that variable to be used next frame.

Something like this:

var lastY: CGFloat?

// in your function
if let lastY = lastY {
  if player.y > lastY {
    // player.y is increasing
  } else {
    // player.y is decreasing
lastY = player.y