Search code examples
javascriptarrayskhan-academy

How do you load specific parts of an array based on a changing position?


I am having trouble with loading specific parts of an array around my player. I am doing this because ~12,000 blocks getting loaded at once doesn't seem like a good option.

In my code currently the array is loaded with this code:

for (var i = 0; i < levels[level].length; i++) { 
for (var j = 0; j < levels[level][i].length; j++) 
{ 
    switch (levels[level][i][j]) {

Then I list a strand of text like "b" for example like this:

case "b":
blocks.push(new Block(j * blockwidth, i * blockheight, "block"));
break;

I have tried constraining the levels[level].length to the players like this;

for (var i = 0; i < constrain(levels[level].length,player.y-player.y,player.y+player.y+30); i++) {
for (var j = 0; j < constrain(levels[level][i].length,player.x-player.x,player.x+player.x+30); j++) {
    switch (levels[level][i][j]) {

It had seemed to work until I moved around and saw that the view outside my player's spawn was unloaded

(I'm working on Khan Academy) here is a link to it:

https://www.khanacademy.org/computer-programming/colossus-warp-beta50-lvls-updates-with-reality-warp/4927982640349184

(copy some of the code examples and use ctrl+f in the code box to find where it is in the code)


Solution

  • So I figured it out

    for(var i = round(player.y/blockheight-1); i < round(player.y/blockheight)+2;i++){    
        for(var j = round(player.x/blockwidth)-1; j < round(player.x/blockwidth)+2;j++){
            switch(levels[level][i][j]){
    

    while doing this I figured out when loading an array
    example

    for(var i = -y1; i < +y1;i++){                                       
       for(var i = -y1; i < +y1;i++){
    

    when the y1 is - negative (-y1) and connected to a player's y pos it is negative y

    when the y1 is + positive (+y1) and connected to a player's y pos it is positive y

    when the x1 is - negative (-x1) and connected to a player's x pos it is negative x

    when the x1 is + positive (+x1) and connected to a player's x pos it is positive x

    like on a graph