Jump to content

Is this a correct implementation of infinite scrolling? (It works by accident!)

MK Safi

Recommended Posts

If you drive this car (using cursor keys), you will see how the screen scrolls infinitely:




It seems to work, but I just wanna make sure I understand what I'm doing because I only got this to work by accident.


Here's the code for the custom camera that I built to achieve this behavior:

camera.update = function() {  var seventyPercentTheWidth = game.world.width * 0.7  var thirtyPercentTheWidth = game.world.width * 0.3  var seventyPercentTheHeight = game.world.height * 0.7  var thirtyPercentTheHeight = game.world.height * 0.3  if (car.p.body.speed > 0) {    if (car.p.x > seventyPercentTheWidth) {      ground.p.tilePosition.x -= car.p.x - seventyPercentTheWidth      car.p.x = seventyPercentTheWidth    }    if (car.p.x < thirtyPercentTheWidth) {      ground.p.tilePosition.x -= car.p.x - thirtyPercentTheWidth      car.p.x = thirtyPercentTheWidth    }    if (car.p.y > seventyPercentTheHeight) {      ground.p.tilePosition.y -= car.p.y - seventyPercentTheHeight      car.p.y = seventyPercentTheHeight    }    if (car.p.y < thirtyPercentTheHeight) {      ground.p.tilePosition.y -= car.p.y - thirtyPercentTheHeight      car.p.y = thirtyPercentTheHeight    }  }}

`ground.p` is a tileSprite and `car.p` is a normal sprite. 


The line that especially confuses me is this:

ground.p.tilePosition.x -= car.p.x - seventyPercentTheWidth

If I don't subtract "seventyPercentTheWidth" from the assigned value, it kind of screws things up in a way that is difficult to explain, like if I hardcode the boundaries instead of dynamically setting them, then some boundary numbers would work, and others would produce bizarre results...


In the example above, the number that gets assigned to tilePosition.x is between 0 and 10 or something...and that's how the tiles scroll, and I have no idea why. I'm unclear on what tilePosition.x really is and it is not documented.


Could someone verify that this code does what it is intended to do?


Thanks so much!


By the way, the whole thing is open source here: https://github.com/msafi/hejwel

Link to comment
Share on other sites


  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Create New...