javascript - Why is my random value getting overwritten almost instantly? -
i having problem code. try make objects spawn in random locations can see drawhyperball(), and, getrandomintx(), , getrandominty(). happening though, random value gets overwritten instantly. how can fix this?
code below:
var canvas = document.getelementbyid("mycanvas"); var ctx = canvas.getcontext("2d"); var x = canvas.width/2; var y = canvas.height/2; var ballradius = 40; var hballradius = 10; var w = 5; var hunger = 630; var hypo = 0; var hyper = 0; var randomx; var randomy; var keys = { up: false, down: false, left: false, right: false }; function drawball() { ctx.beginpath(); ctx.arc(x, y, ballradius, 0, math.pi*2); ctx.fillstyle = "#00ff00"; ctx.fill(); ctx.linewidth= 3.5; ctx.stroke(); ctx.closepath(); } function drawconcebar() { ctx.strokerect(100,930,630,30) } function drawhungerbar() { ctx.fillstyle = "#73591c"; ctx.fillrect(1140,930,hunger,30) ctx.fillstyle = "black"; ctx.strokerect(1140,930,630,30) } function drawtitle() { ctx.fillstyle = "black"; ctx.font = "120px arial"; ctx.filltext("osmos.is",canvas.width/2 -210,120); } function drawborder() { ctx.strokerect(100,150,1670,730); } function getrandomintx(minx,maxx) { return math.floor(math.random() * (maxx- minx + 1)) + minx; } function getrandominty(miny,maxy) { return math.floor(math.random() * (maxy - miny + 1)) + miny; } function drawhyperball() { ctx.beginpath(); ctx.arc(getrandomintx(110, 1660), getrandominty(160, 720), hballradius, 0, math.pi*2); ctx.fillstyle = "#ff0000"; ctx.fill(); ctx.closepath(); } function draw() { ctx.clearrect(0, 0, canvas.width, canvas.height); drawball(); drawborder(); drawtitle(); drawconcebar(); drawhungerbar(); if(y > 830) { y -= 5; } else if(y < 195) { y += 5; } if(x < 150) { x += 5; } else if(x > 1720) { x -= 5; } if (keys.up) { y -= 5; } else if (keys.down) { y += 5; } if (keys.left) { x -= 5; } else if (keys.right) { x += 5; } if (hunger <= 0) { hunger += 1; } else { hunger -= 1; } } window.onkeydown = function(e) { var kc = e.keycode; e.preventdefault(); if (kc === 37) keys.left = true; // 1 key per event else if (kc === 38) keys.up = true; // check exclusively else if (kc === 39) keys.right = true; else if (kc === 40) keys.down = true; }; window.onkeyup = function(e) { var kc = e.keycode; e.preventdefault(); if (kc === 37) keys.left = false; else if (kc === 38) keys.up = false; else if (kc === 39) keys.right = false; else if (kc === 40) keys.down = false; }; setinterval(draw, 10); setinterval(drawhyperball, 1000); <canvas id="mycanvas"></canvas>
i've figured out problem. clearing of canvas, added new function clear specific things.
Comments
Post a Comment