Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

186
Visualizações
Random rect generation generating all rects next to each other

I'm working on random rectangle generation for a game in canvas, and I added some code to prevent the randomly generated rectangles from overlapping, however rather than preventing my rectangles from overlapping, it's like it makes it so it has to overlap or else it wont place it. here is my code (I know it's messy and unoptimized)

function random_place(){
var x,y,height,width
x = Math.floor(Math.random() * 10000);
y = Math.floor(Math.random() * 100);
width = Math.floor(Math.random() * (85 - 20 + 1) + 20);
height = Math.floor(Math.random() * (85 - 20 + 1) + 20);
return([x,y,width,height])
}



function generate_obstacles(obstacles_count){
var counter = 0
var placement
var placement_colide = false;
console.log(obstacle_array.length)
while(counter < obstacles_count){
placement_colide = false;
x = Math.floor(Math.random() * 10000);
y = Math.floor(Math.random() * 10000);
width = Math.floor(Math.random() * 85);
height = Math.floor(Math.random() * 60);
placement = random_place();
for(let i=0; i<obstacle_array.length; i++){
if(obstacle_array[i][0]+100 > placement[0]+(placement[2]/2)+100 || obstacle_array[i][0]+(obstacle_array[i][2]/2)+40 < placement[0]) {
if(obstacle_array[i][1]+35 > placement[1]+(placement[3]/2)+35 || obstacle_array[i][1]+(obstacle_array[i][3]/2)+35 < placement[1]){placement_colide = true; break}
}
placement_colide = true; break
}
if((placement[0] > (player_x*2)+5 || placement[0] < (player_x/2)+1.5) && placement_colide == true){
obstacle_array.push(placement);
counter++;
i = obstacle_array.length
}
}

I also have the full code in jsfiddle if that would be easier to read https://jsfiddle.net/Fightingox/1dk0oaty/54/

anyone know the problem?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Messy code is buggy code

I could not work out what you have done wrong because the code is a mess.

Names are way to long. You set properties as array indexes rather than by named properties. And more..

Rather than fix your code I have re-written creating some functions and renaming many objects.

Rewrite in parts

To create a random rectangle

const randI = range => Math.random() * range | 0; // only for positive ints
function randomGameRect() {
    const x = randI(10000);
    const y = randI(100);
    const w = randI(61) + 20;
    const h = randI(61) + 20;
    return {x, y, w, h};
}

To check if two rectangles overlap.

function doRectsOverlay(rectA, rectB) {
    return !(                           // Overlaps if not any of...
        rectA.x > rectB.x + rectB.w ||  // left of rectA right of right of rectB
        rectB.x > rectA.x + rectA.w ||  // right of rectA left of left of rectB
        rectA.y > rectB.y + rectB.h ||  // top of rectA below bottom of rectB
        rectB.y > rectA.y + rectA.h);   // bottom of rectA above top of rectB
}

To add a rectangle rect to an array of rectangles rects if there is no overlap.

Note I also added the player check you do. I am not sure why you do it so I just put it in.

function addIfNotOverlap(rect, rects) {
    if (!rects.some(r => doRectsOverlay(r, rect)) {
        
        // check player stuff. I don't know why you do this.
        if (place.x > (player_x * 2) + 5 || place.x < (player_x / 2) + 1.5) {
            rects.push(rect);
        }
    }    
}

And the last function replaces yours. It adds count rectangles to the array of rectangles obstacleArray. This function requires all the functions above

function generateObstacles(count) {
    while (count-- > 0) {
        addIfNotOverlap(randomGameRect(), obstacleArray);
    }
}

Hope this helps you solve your problem.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda