'How to make a sprite moving at the same speed of tileSprite in Phaser3

I am new in Phaser. I want to make a background which represent the ground moving and there should be a bunch of rocks above it which I made them as a sprite group.

I made the ground as a tileSprite, and on each update I changed the tilePositionX. my problem is how to set the velocity of the rocks to match the update in the background so they appear to be on the ground and moving at the same speed of the ground.



Solution 1:[1]

theoretically you could measure the passed time, from the last update function call, and calculate the difference, or just eye-ball the needed velocity. (aka. try different velocities until it matches up with the background-movement):

Update:
If no physics object is needed you could move the "rock" "manually", this is very easy.

Here a quick demo, that I eye-balled:

  • The red mushroom, uses physics and velocity. Warning: the speed of the object can/will vary depending on the browser and hardware.
  • Update: The green mushroom, is moved manually via the position.

// Minor formating for stackoverflow
document.body.style = "display: flex;flex-direction: column;";    

var config = {
    type: Phaser.AUTO,
    width: 536,
    height: 150,
    physics:{
        default: 'arcade',
        arcade: { debug: true }
    },
    scene: {
         preload,
         create,
         update
    }
}; 

var tilesprite;
var redRock;
var greenRock;

function preload ()
{
    this.load.image('mushroom', 'https://labs.phaser.io/assets/sprites/mushroom16x16.png');
}

function create ()
{
    tilesprite = this.add.tileSprite(400, 300, 800, 600, 'mushroom');

    redRock = this.add.image(400, 40, 'mushroom').setScale(2);
    redRock.setTint(0xff0000);

    this.physics.add.existing(redRock);
    redRock.body.setVelocityX(-60)

    greenRock = this.add.image(400, 90, 'mushroom').setScale(2);
    greenRock.setTint(0x00ff00);

}

function update (time, delta){
    tilesprite.tilePositionX += 1;
    
    let speedCorrection = (1000/60)/delta;
    redRock.body.setVelocityX(-60 * speedCorrection )

    greenRock.x -= 1;
    
    // extra "reset" Rock
    if( redRock.x + 16 < 0 ){
      redRock.x = this.sys.game.canvas.width + 16;
      greenRock.x = this.sys.game.canvas.width + 16;
    }
}


var game = new Phaser.Game(config);
<script src="//cdn.jsdelivr.net/npm/[email protected]/dist/phaser.min.js">
</script>

Disclaimer: It is not the most elegant solution, but it took me literally 30 Seconds to find a matching velocity.

Minor Update:
I improved the eye-ball-method with a speed correction, it can cause minor flickering/slipping(max 1-2 pixel skips), but should move constant on "all" device.

The change is just adding a small calculation let speedCorrection = (1000/60)/delta;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1