I'm encountering an issue with my code. I am attempting to generate objects in random locations using drawHyperBall()
, getRandomIntX()
, and getRandomIntY()
. However, the random value seems to be constantly overwritten. How can I resolve this problem?
See the 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;
else if (kc === 38) Keys.up = true;
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>