i working javascript file bounces ball 4 walls. want change color of ball when hits wall... trying 2 consecutive ifs second if not getting executed don't know why
var canvas = document.getelementbyid("mycanvas"); var ctx = canvas.getcontext("2d"); var ballradius = 10; var x = canvas.width/2; var y = canvas.height-30; var dx = 2; var dy = -2; if(dx>0){ alert("dx greater 0"); } if(dx<0){ alert("dx less 0"); } function drawball() { ctx.beginpath(); ctx.arc(x, y, ballradius, 0, math.pi*2); ctx.fillstyle = "#0095dd"; ctx.fill(); ctx.closepath(); } function draw() { ctx.clearrect(0, 0, canvas.width, canvas.height); drawball(); if(x + dx > canvas.width-ballradius || x + dx < ballradius) { dx = -dx; } if(y + dy > canvas.height-ballradius || y + dy < ballradius) { dy = -dy; } x += dx; y += dy; } setinterval(draw, 10);
you check if statements outside of loop. if statements checked once. in initial conditions, dx>0, calls 1 alert statement. "if" blocks never called again.
if(x + dx > canvas.width-ballradius || x + dx < ballradius) { dx = -dx; //######## new code ############# if (dx > 0) { alert('greater zero'); } else { alert('less zero'); } //################################ } if(y + dy > canvas.height-ballradius || y + dy < ballradius) { dy = -dy; }
Comments
Post a Comment