Estoy usando varios cuadros que flotan alrededor de la pantalla, quiero que reboten entre sí cuando chocan y estoy probando esto simplemente cambiando sus colores cuando chocan, por alguna razón su color cambia en el comienzo (su color inicial es blanco y si chocan, debería cambiar a rojo, pero comienzan y se mantienen rojos). ¿Hay algo que estoy haciendo mal? También me gustaría que todo se hiciera dentro de la función constructora. Lo siento por no comentar mi código todavía.
function BoxSplash() { this.sample = []; var test = false; this.col = color(129) this.changeColour = function() { this.col = color(random(0,255),random(0,128),random(0,255)) } this.intersect = function(other) { for(var i = 0; i < numberss; i++) { var currentBox = this.sample[i] var d = dist(currentBox.x,currentBox.y,other.x,other.y) if(d < currentBox.width + other.width) { return true; } else { return false } } noLoop() } this.draw = function() { stroke(255) line(0,windowHeight/2,windowWidth,windowHeight/2) stroke(0) for(var i = 0; i < numberss; i++) { var box = { x:random(0,windowWidth - 50), y:random(windowHeight/2 ,windowHeight - 50), width:50, height:50, speedX:random(1,5), speedY:random(1,5) } this.sample.push(box) } //use numberss variable to work with gui for(var i = 0; i < numberss; i++) { fill(this.col) rect(this.sample[i].x,this.sample[i].y,50,50) } this.move() } this.move = function() { for(var i = 0; i < numberss; i++) { var shape = this.sample[i] shape.x += shape.speedX shape.y += shape.speedY if(shape.x + shape.width >= windowWidth || shape.x <= 0 ) { shape.speedX = -shape.speedX } if(shape.y + shape.height >= windowHeight || shape.y <= windowHeight/2) { shape.speedY = -shape.speedY; } for(var j = 0; j < numberss; j++) { var others = this.sample[j] var d = dist(shape.x,shape.y,others.x,others.y) if( i != j && d < shape.width + others.width) { test = true; } else { test = false } if(test) { this.col = color(255,0,0) } } } } }Debes visitar este enlace y transformar sus círculos en tus casillas.
Primero: Calcular dist(object1.x, object.y, object2.x, object2.y) y guardar en una variable llamada d
2do:
if (d < object1.h + object2.h) { // Enter your code here }