Solucionado (ver solución)
Solucionado
(ver solución)
1
respuesta

Duda en diseñar Objetivo

Qué tal! Para no utilizar 3 veces la función "draw_circle" realicé un ciclo while dentro de la función "draw_target". Al ejecutar el código con un radio=30, el objetivo consta de 3 circunferencias pero al querer incrementar el radio en 50,70,etc el "target" se conforma con más circunferencias, a pesar que creé una var "num_de_circulos =3".

No encuentro el error dentro la lógica del while dentro de la funcion "diseñar objetivo", ya que según mi lógica cuando no cumpla la condición del while debería de dejar de ejecutarse la instrucción anidada y, en este caso, independientemente del radio siempre deberían ser solo 3 circulos en orden decreciente -10. De acuerdo a mi análisis deberían dibujarse 3 círculos, con radios 50,40 y 30 respectivamente, sin embargo, se dibujan 5.

Por lo demás el código funciona inclusive al hacer click en el centro del "target" manda el alert correctamente, sin embargo, al revisar la consola de desarrollador marca un error en cada actualización del setInterval señalando al radio como -10, a lo que no entiendo porqué calcula ese valor.

Saludos

<canvas width="600" height="400"></canvas>
<script type="text/javascript">

    var screen=document.querySelector("canvas");
    var brush=screen.getContext("2d");

    brush.fillStyle="lightgrey";
    brush.fillRect(0,0,600,400);

function draw_circle(x,y,rad,color){
        brush.fillStyle=color;
        brush.beginPath();
        brush.arc(x,y,rad,0,2*Math.PI);
        brush.fill();
}

function clean_screen(){
    brush.clearRect(0,0,600,400);
}

function raffle_coordinate(max){
    return Math.floor(Math.random()*max) 
}

var num_of_circles=3;
var i=0;
var color=["red","white"];
var rand_x;
var rand_y;
var rad;


function draw_target(){

    rand_x=raffle_coordinate(600);
    rand_y=raffle_coordinate(400);

    while(i<num_of_circles){

            if(i==color.length){
                i=0;
            }
        draw_circle(rand_x,rand_y,rad,color[i]);
        rad=rad-10;
        i++;

    }//end while

}//end function

function update_screen(){
    rad=50; 
    clean_screen();
    draw_target();
}

function click_on_center(event){
    var x=event.pageX-screen.offsetLeft;
    var y=event.pageY-screen.offsetTop;

    if( (x>rand_x-10)&&
        (x<rand_x+10)&&
        (y<rand_y+10)&&
        (y>rand_y-10)
        ){

            alert("Perfect Shot!")
    }
}

console.log(rad);

setInterval(update_screen,2000);

screen.onclick=click_on_center;



</script>
1 respuesta
solución!

Pues te lanzo una propuesta si crees que esta bien me regalas un check de solución a la duda. Todo el lio es porque estas afectando la variable que se usa para el condicional del while dentro del if (variable i) la igualas a cero cada vez que sea igual a 1 por lo tanto se crea un bucle infinito que se detiene al lanzarse el error de radio negativo. usando otro nombre de variable para controlar el color se soluciona por lo demás esta excelente el código vas muy bien. idcolor = 0; while (i < num_of_circles) { if (idcolor == color.length) { idcolor = 0; } draw_circle(rand_x, rand_y, rad, color[idcolor]); idcolor = idcolor + 1 rad = rad - 10; i++; }

Dejo el código completo para que lo puedas probar

<canvas width="600" height="400"></canvas>
<script type="text/javascript">

    var screen=document.querySelector("canvas");
    var brush=screen.getContext("2d");

    brush.fillStyle="lightgrey";
    brush.fillRect(0,0,600,400);

function draw_circle(x,y,rad,color){
        brush.fillStyle=color;
        brush.beginPath();
        brush.arc(x,y,rad,0,2*Math.PI);
        brush.fill();
}

function clean_screen(){
    brush.clearRect(0,0,600,400);
}

function raffle_coordinate(max){
    return Math.floor(Math.random()*max) 
}

var num_of_circles=3;
var i=0;
var color=["red","white"];
var rand_x;
var rand_y;
var rad;


function draw_target(){

    rand_x=raffle_coordinate(600);
    rand_y=raffle_coordinate(400);
    idcolor = 0;

    while (i < num_of_circles) {

        if (idcolor == color.length) {
            idcolor = 0;
        }
        draw_circle(rand_x, rand_y, rad, color[idcolor]);
        idcolor = idcolor + 1
        rad = rad - 10;
        i++;

    }//end while

}//end function

function update_screen(){
    rad=50; 
    clean_screen();
    draw_target();
}

function click_on_center(event){
    var x=event.pageX-screen.offsetLeft;
    var y=event.pageY-screen.offsetTop;

    if( (x>rand_x-10)&&
        (x<rand_x+10)&&
        (y<rand_y+10)&&
        (y>rand_y-10)
        ){

            alert("Perfect Shot!")
    }
}

console.log(rad);

setInterval(update_screen,2000);

screen.onclick=click_on_center;



</script>