Riding moving Platforms?

Managed to get it working, thanks to your advice, @samme!

I calculated the platform’s velocity in the tween’s onUpdate, like this:

    this.tweens.timeline({
              targets: platform,
              ease,
              yoyo,
              loop: -1,
              tweens,
              onUpdate: () => {
                platform.vx = platform.body.position.x - platform.previousX;
                platform.vy = platform.body.position.y - platform.previousY;
                platform.previousX = platform.body.position.x; 
                platform.previousY = platform.body.position.y; 
              }
            }); 

Then set up the collision callback to tell the player sprite that the platform collision was occurring and to pass it a reference to the platform:

const collisionMovingPlatform = (sprite, platform) => {
      if (platform.body.touching.up && sprite.body.touching.down) {
        sprite.isOnPlatform = true;
        sprite.currentPlatform = platform;      
      }
    };
    //Only allow collisions from top
    const isCollisionFromTop = (sprite, platform) => {
      return platform.body.y > sprite.body.y;
    };

    this.physics.add.collider(
      sprite,
      movingPlatforms,
      collisionMovingPlatform,
      isCollisionFromTop,
      scene
    );

Then in the player’s update method, applied the platform’s velocity to the player’s position.

if (this.isOnPlatform && this.currentPlatform) {
      this.body.position.x += this.currentPlatform.vx;
      this.body.position.y += this.currentPlatform.vy;

      this.isOnPlatform = false;
      this.currentPlatform = null;
    }

Works like a charm!

ezgif-4-fa06f4e080e5

6 Likes