AI follow and avoid collision with obstacle - javascript

I'm making an AI navigation system based on polar coordinates. The purpose is to move an actor to a position, while also moving away from a possible obstacle on its path.
The code works perfectly most of the time but after testing, I discovered this: when the player, obstacle and actor are all perfectly aligned in either the X or Y direction or diagonally, the actor gets stuck in the obstacle. It's mostly noticeable when the player is "hugging" a wall because the actor's movement vector is clipped by the walls, making them aligned.
Click the buttons in the snippet to see what I'm on about.
Is there a way to prevent this?
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let playerX = 100;
let playerY = 200;
let obstacleX = 200;
let obstacleY = 200;
let actorX = 300;
let actorY = 201;
function loop() {
// Wall clipping
if (actorX > 490) {
actorX = 490;
} else if (actorX < 10) {
actorX = 10;
}
if (actorY > 490) {
actorY = 490;
} else if (actorY < 10) {
actorY = 10;
}
// Vector between player and actor
let vectorPlayerX = playerX - actorX;
let vectorPlayerY = playerY - actorY;
// Vector between obstacle and actor
let vectorObstacleX = obstacleX - actorX;
let vectorObstacleY = obstacleY - actorY;
// Where to move, defaults to player's position
const anglePlayer = Math.atan2(vectorPlayerY, vectorPlayerX);
let moveAngle = anglePlayer;
// If near obstacle, adjust course and try to avoid it
if (Math.sqrt(vectorObstacleX * vectorObstacleX + vectorObstacleY * vectorObstacleY) < 50) {
const angleObstacle = Math.atan2(vectorObstacleY, vectorObstacleX);
moveAngle += anglePlayer - angleObstacle;
}
// Move the vector to desired location
actorX += Math.cos(moveAngle);
actorY += Math.sin(moveAngle);
//Drawing
ctx.clearRect(0, 0, 500, 500);
ctx.beginPath();
ctx.fillStyle = "gray";
ctx.arc(actorX, actorY, 10, 0, Math.PI * 2, true);
ctx.fill();
ctx.beginPath();
ctx.fillStyle = "orange";
ctx.arc(obstacleX, obstacleY, 10, 0, Math.PI * 2, true);
ctx.fill();
ctx.beginPath();
ctx.fillStyle = "blue";
ctx.arc(playerX, playerY, 10, 0, Math.PI * 2, true);
ctx.fill();
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
function nonAligned() {
playerX = 100;
playerY = 200;
obstacleX = 200;
obstacleY = 200;
actorX = 300;
actorY = 201;
}
function alignedY() {
playerX = 100;
playerY = 490;
obstacleX = 200;
obstacleY = 490;
actorX = 300;
actorY = 490;
}
function alignedBoth() {
playerX = 200;
playerY = 200;
obstacleX = 300;
obstacleY = 300;
actorX = 400;
actorY = 400;
}
#options {
position: fixed;
top: 5px;
left: 5px;
}
<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
<div id="options">
<button onclick="nonAligned()">Spawn non-aligned</button>
<button onclick="alignedY()">Spawn Y aligned</button>
<button onclick="alignedBoth()">Spawn diagonally aligned</button>
</div>
</body>
</html>

If the angle to the player and the obstacle are the same then we continue the course, as the variables cancel each other out.
moveAngle += anglePlayer - angleObstacle;
If anglePlayer is 117 and angleObstacle is 117 and your moveAngle is 117 you get
117 + 117 -117 = 117 ...
You might want something like this (pseudo code)
moveAngle += anglePlayer + random(90)-45;
Or if hitting an obstacle move left or right
moveAngle += anglePlayer - 90;
if (random(2)==1 moveAngle += 180

The issue is indeed that moveAngle is unchanged when it is pointed directly at the obstacle. A small modification checks whether the moveAngle is clockwise or counter-clockwise from the obstacle, and veers further away (note: my code breaks the wall hugging and behaves badly in the "aligned in Y" case for that reason, which is fixable but I don't care to):
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let playerX = 100;
let playerY = 200;
let obstacleX = 200;
let obstacleY = 200;
let actorX = 300;
let actorY = 201;
function loop() {
// Wall clipping
if (actorX > 490) {
actorX = 490;
} else if (actorX < 10) {
actorX = 10;
}
if (actorY > 490) {
actorY = 490;
} else if (actorY < 10) {
actorY = 10;
}
// Vector between player and actor
let vectorPlayerX = playerX - actorX;
let vectorPlayerY = playerY - actorY;
// Vector between obstacle and actor
let vectorObstacleX = obstacleX - actorX;
let vectorObstacleY = obstacleY - actorY;
// Where to move, defaults to player's position
const anglePlayer = Math.atan2(vectorPlayerY, vectorPlayerX);
let moveAngle = anglePlayer;
// If near obstacle, adjust course and try to avoid it
obs_distance = Math.sqrt(vectorObstacleX * vectorObstacleX + vectorObstacleY * vectorObstacleY);
if (obs_distance < 100) {
const angleObstacle = Math.atan2(vectorObstacleY, vectorObstacleX);
delta = Math.PI/2.0;
if (obs_distance > 100.0/32.0) { delta = (100.0/32.0)*Math.PI/obs_distance; }
cross = Math.sin(moveAngle-angleObstacle);
if (cross>0) { moveAngle += delta; }
if (cross<0) { moveAngle -= delta; }
if (cross==0) {
if (Math.random(2)==1) {
moveAngle += delta;
} else {
moveAngle -= delta;
}
}
}
// Move the vector to desired location
actorX += Math.cos(moveAngle);
actorY += Math.sin(moveAngle);
//Drawing
ctx.clearRect(0, 0, 500, 500);
ctx.beginPath();
ctx.fillStyle = "gray";
ctx.arc(actorX, actorY, 10, 0, Math.PI * 2, true);
ctx.fill();
ctx.beginPath();
ctx.fillStyle = "orange";
ctx.arc(obstacleX, obstacleY, 10, 0, Math.PI * 2, true);
ctx.fill();
ctx.beginPath();
ctx.fillStyle = "blue";
ctx.arc(playerX, playerY, 10, 0, Math.PI * 2, true);
ctx.fill();
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
function nonAligned() {
playerX = 100;
playerY = 200;
obstacleX = 200;
obstacleY = 200;
actorX = 300;
actorY = 201;
}
function alignedY() {
playerX = 100;
playerY = 490;
obstacleX = 200;
obstacleY = 490;
actorX = 300;
actorY = 490;
}
function alignedBoth() {
playerX = 200;
playerY = 200;
obstacleX = 300;
obstacleY = 300;
actorX = 400;
actorY = 400;
}
#options {
position: fixed;
top: 5px;
left: 5px;
}
<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
<div id="options">
<button onclick="nonAligned()">Spawn non-aligned</button>
<button onclick="alignedY()">Spawn Y aligned</button>
<button onclick="alignedBoth()">Spawn diagonally aligned</button>
</div>
</body>
</html>

Related

How to add Start Game and Play Again to canvas game?

I created game using Javascript following YouTube video game tutorial. Game works just fine, but I would like to add ability to enter nickname at the beginning of the game. After entering nickname and hitting play button the game would begin and nickname would display on the middle upper side of the screen. Then after loosing the game, window with score and play-again button should pop up. After clicking play-again button another game starts.
const canvas = document.getElementById('canvas1');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const collisionCanvas = document.getElementById('collisionCanvas');
const collisionCtx = collisionCanvas.getContext('2d');
collisionCanvas.width = window.innerWidth;
collisionCanvas.height = window.innerHeight;
//obsluga gry
let gameOver = false;
let score = 0;
ctx.font = '50px Impact';
let lives = 3;
let hit = false;
let clicked = false;
//setup spawnow
let timeToNextZombie = 0;
let zombieInterval = 400;
let lastTime = 0;
let zombies =[];
//myszka
let innerCursor = document.querySelector('.inner-cursor');
let outerCursor = document.querySelector('.outer-cursor');
document.addEventListener('mousemove', moveCursor)
function moveCursor(e){
let x = e.clientX;
let y = e.clientY;
innerCursor.style.left = `${x}px`;
innerCursor.style.top = `${y}px`;
outerCursor.style.left = `${x}px`;
outerCursor.style.top = `${y}px`;
}
class Zombie{
constructor(){
this.spriteWidth = 200; //szerkosc klatki zombie
this.spriteHeight = 312; //wyskosc klatki zombie
this.sizeModifier = Math.random()* 0.8 + 0.6; //mnożnik wielkości zombiaka
this.width = this.spriteWidth * this.sizeModifier;
this.height = this.spriteHeight * this.sizeModifier;
this.x = canvas.width;
this.y =Math.random() * (canvas.height -this.height); //spawn zombie od dolu do gory ekranu
this.directionX = Math.random() * 4 + 1; //predkosc zombiakow
if(Math.floor(Math.random() * 20) == 0) this.directionX = 10; //5% szans na szybkiego lopeza
this.markedForDeletion = false; //oznaczenie czy mozna usunac obiekt
this.image = new Image();
this.image.src = 'walkingdead.png';
this.frame = 0;
this.maxFrame = 8;
this.timeSinceFlap = 0;
this.flapInterval = Math.random()*50+50; //flipowanie kazdego inne
this.randomColors = [Math.floor(Math.random()*255), Math.floor(Math.random()*255), Math.floor(Math.random()*255)];
this.color = 'rgb(' + this.randomColors[0] + ',' + this.randomColors[1] + ',' + this.randomColors[2] + ')';
}
update(deltatime){
this.x -= this.directionX;
this.timeSinceFlap +=deltatime;
if (this.x < 0-this.width){
this.markedForDeletion = true;
} //zombiak jest poza zasiegiem
if (this.timeSinceFlap > this.flapInterval){
if (this.frame > this.maxFrame) this.frame = 0;
else this.frame++;
this.timeSinceFlap = 0;
}
if (this.x < 0 -this.width){
lives-=1;
if(lives == 0){
gameOver = true;
}
}
}
//rysowanie zombiaka
draw(){
collisionCtx.fillStyle = this.color;
collisionCtx.fillRect(this.x, this.y, this.width, this.height);
ctx.drawImage(this.image, this.frame * this.spriteWidth, 0, this.spriteWidth, this.spriteHeight, this.x, this.y, this.width, this.height);
}
}
function drawScore(){
//kordy scora
if(lives == 0){
ctx.font = '200px Impact';
ctx.fillText('☠️', 0, 170);
return;
}
ctx.fillStyle = 'white';
ctx.fillText('Score: ' + score, 55, 80);
if(lives == 3) ctx.fillText('❤ ❤ ❤', 55, 130);
if(lives == 2) ctx.fillText('❤ ❤', 55, 130);
if(lives == 1) ctx.fillText('❤', 55, 130);
}
function drawGameOver(){
drawScore();
ctx.font = "bold 100px serif";
ctx.textAlign = 'center';
ctx.fillStyle = 'red';
ctx.fillText("GAME OVER!", canvas.width/2, canvas.height/2)
ctx.fillText("Your score is " + score, canvas.width/2, 100 + canvas.height/2)
}
window.addEventListener('click', function(e){
const detectPixelColor = collisionCtx.getImageData(e.x, e.y, 1, 1);
const pc = detectPixelColor.data; //popieranie info o hitboxie zombie
zombies.forEach(object =>{
if(object.randomColors[0] === pc[0] && object.randomColors[1] === pc[1] && object.randomColors[2] === pc[2]){
object.markedForDeletion = true; //usunąć gościa z mapy
hit = true;
}
clicked = true;
})
});
//obsluga klatki
function animate(timestamp) {
if(clicked){
if(hit) score+=12
else score-=6;
clicked = false;
hit = false;
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
collisionCtx.clearRect(0, 0, canvas.width, canvas.height);
let deltatime = timestamp - lastTime;
lastTime = timestamp;
timeToNextZombie += deltatime;
if (timeToNextZombie > zombieInterval){
zombies.push(new Zombie()); //tworzenie nowego zombiaka
timeToNextZombie = 0;
zombies.sort(function(a, b){
return a.width - b.width; //sort zeby mniejsze zombiaki byly za wiekszymi
})
};
drawScore();
//dla kazdego zombiaka przesuwamy zombiaka, object to pojedynczy (obiekt) zombiaka
[...zombies].forEach(object => object.update(deltatime));
[...zombies].forEach(object => object.draw());
zombies = zombies.filter(object => !object.markedForDeletion); //usuwanie zombiakow poza screenem
if(!gameOver) requestAnimationFrame(animate);
else{
drawScore();
drawGameOver();
}
}
animate(0);
*{
cursor: none;
}
canvas{
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-image: url('board-bg.jpg');
}
#collisionCanvas{
opacity: 0;
}
.inner-cursor{
position: fixed;
width: 15px;
height: 15px;
transform: translate(-50%, -50%);
background-color: white !important;
mix-blend-mode: difference;
border-radius: 50%;
pointer-events: none;
}
.outer-cursor{
position: fixed;
width: 70px;
height: 70px;
transform: translate(-50%, -50%);
border: 5px solid white;
mix-blend-mode: difference;
border-radius: 50%;
pointer-events: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Zadanie 12</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas2"></canvas>
<canvas id="collisionCanvas"></canvas>
<canvas id="canvas1"></canvas>
<div class="inner-cursor"></div>
<div class="outer-cursor"></div>
<script src="script.js"></script>
</body>
</html>
You have everything you need in that code...
let gameOver = false;
let zombies = [];
all we need is to change a bit your code to take advantage of those.
I'm not going to implement your "window with score and play-again button pop up" instead I'm going for a much simpler timeout to demonstrate how to restart your game.
The key point in your game that sets the "end" is the one below:
if (lives == 0) {
zombies = []
gameOver = true;
gameEnded = Date.now()
setTimeout(() => {
gameOver = false
lives = 3
}, 5000)
}
before you just had the gameOver now I'm doing a few more things, like that setTimeout that will restart the game in 5 seconds, restarting the game is just to set the gameOver back to false and give the user some lives.
Your function animate is where the drawing loop happens, I changed that a bit, now we no longer stop the loop but draw something else and we can add many conditions there:
function animate(timestamp) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (gameOver) {
drawGameOver();
} else if (abc < 20) {
drawABC();
} else if (def == "start_message") {
drawDEF();
} else {
...
}
requestAnimationFrame(animate)
}
Below is your simplified code with my additions
const canvas = document.getElementById('canvas1');
const ctx = canvas.getContext('2d');
canvas.width = canvas.height = 700;
let gameEnded = Date.now()
let gameOver = false;
let score = 0;
ctx.font = '50px Impact';
let lives = 3;
let hit = false;
let clicked = false;
let timeToNextZombie = 0;
let zombieInterval = 400;
let lastTime = 0;
let zombies = [];
class Zombie {
constructor() {
this.spriteWidth = 200; //szerkosc klatki zombie
this.spriteHeight = 312; //wyskosc klatki zombie
this.sizeModifier = Math.random() * 0.8 + 0.6; //mnożnik wielkości zombiaka
this.width = this.spriteWidth * this.sizeModifier;
this.height = this.spriteHeight * this.sizeModifier;
this.x = canvas.width;
this.y = Math.random() * (canvas.height - this.height); //spawn zombie od dolu do gory ekranu
this.directionX = Math.random() * 4 + 1; //predkosc zombiakow
if (Math.floor(Math.random() * 20) == 0) this.directionX = 10; //5% szans na szybkiego lopeza
this.markedForDeletion = false; //oznaczenie czy mozna usunac obiekt
//this.image = new Image();
//this.image.src = 'walkingdead.png';
this.frame = 0;
this.maxFrame = 8;
this.timeSinceFlap = 0;
this.flapInterval = Math.random() * 50 + 50; //flipowanie kazdego inne
}
update(deltatime) {
this.x -= this.directionX;
this.timeSinceFlap += deltatime;
if (this.x < 0 - this.width) {
this.markedForDeletion = true;
} //zombiak jest poza zasiegiem
if (this.timeSinceFlap > this.flapInterval) {
if (this.frame > this.maxFrame) this.frame = 0;
else this.frame++;
this.timeSinceFlap = 0;
}
if (this.x < 0 - this.width) {
lives -= 1;
if (lives == 0) {
zombies = []
gameOver = true;
gameEnded = Date.now()
setTimeout(() => {
gameOver = false
lives = 3
}, 5000)
}
}
}
draw() {
ctx.beginPath()
ctx.arc(this.x, this.y, 15, 0, 2 * Math.PI);
ctx.stroke()
}
}
function drawGameOver() {
ctx.beginPath()
ctx.font = "bold 100px serif";
ctx.textAlign = 'center';
ctx.fillStyle = 'red';
ctx.fillText("GAME OVER!", canvas.width / 2, canvas.height / 2)
ctx.fillText("Your score is " + score, canvas.width / 2, 100 + canvas.height / 2)
ctx.beginPath()
ctx.font = "bold 30px serif";
ctx.fillText("Game will restart in 5 seconds... " + String(Date.now()- gameEnded), canvas.width / 2, 100)
}
function animate(timestamp) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (gameOver) {
drawGameOver();
} else {
let deltatime = timestamp - lastTime;
lastTime = timestamp;
timeToNextZombie += deltatime;
if (timeToNextZombie > zombieInterval) {
zombies.push(new Zombie()); //tworzenie nowego zombiaka
timeToNextZombie = 0;
zombies.sort(function(a, b) {
return a.width - b.width; //sort zeby mniejsze zombiaki byly za wiekszymi
})
};
[...zombies].forEach(object => object.update(deltatime));
[...zombies].forEach(object => object.draw());
zombies = zombies.filter(object => !object.markedForDeletion);
}
requestAnimationFrame(animate)
}
animate(0);
<canvas id="canvas1"></canvas>

html5 canvas tooltip only visible for last drawn object, not for previous ones

what exactly I want to achieve is
to draw objects on canvas and
on mouseover display relevant data in tooltip.
here you can view the code.
var canvasBack;
var canvasLabel;
var canvasDraw;
var ctxBack;
var ctxLabel;
var ctxDraw;
var last_mousex = 0;
var last_mousey = 0;
var mousex = 0;
var mousey = 0;
var canWidth;
var canHeight;
var scaleParameter;
var radius;
var xVertex;
var yVertex;
var hotspots = [];
// initialization on loading of canvas
$('canvas').ready(function() {
init();
});
// initialization function used for binding events, and inital logic implemented.
function init() {
scaleParameter = 1;
canvasBack = document.getElementById('backSpace');
canvasLabel = document.getElementById('layerCanvas');
canvasDraw = document.getElementById('drawSpace');
ctxBack = canvasBack.getContext('2d');
ctxLabel = canvasLabel.getContext('2d');
ctxDraw = canvasDraw.getContext('2d');
canWidth = parseInt($(canvasBack).attr('width'));
canHeight = parseInt($(canvasBack).attr('height'));
var canvasx = $(canvasBack).offset().left;
var canvasy = $(canvasBack).offset().top
var mousedown = false;
//Mousedown
$('canvas').on('mousedown', function(e) {
$('#drawSpace').css('display', 'block');
last_mousex = mousex = parseInt(e.clientX - canvasx);
last_mousey = mousey = parseInt(e.clientY - canvasy);
mousedown = true;
});
//Mouseup
$('canvas').on('mouseup', function(e) {
hotspots.push({
x: xVertex,
y: yVertex,
radius: radius,
tip: 'You are over ' + mousex + ',' + mousey
});
let cw = canvasBack.width;
let ch = canvasBack.height;
ctxBack.drawImage(canvasDraw, 0, 0, cw, ch);
$('#drawSpace').css('display', 'none');
mousedown = false;
});
//Mousemove
$('canvas').on('mousemove', function(e) {
mousex = parseInt(e.clientX - canvasx);
mousey = parseInt(e.clientY - canvasy);
if (mousedown) {
// draw(mousedown);
drawEllipse(last_mousex, last_mousey, mousex, mousey);
} else {
hoverTooltip();
}
});
}
function drawEllipse(x1, y1, x2, y2) {
var leftScroll = $("#scrollParent").scrollLeft();
var topScroll = $("#scrollParent").scrollTop();
let cw = canvasBack.width;
let ch = canvasBack.height;
ctxDraw.clearRect(0, 0, cw, ch);
var radiusX = x2 - x1,
radiusY = y2 - y1,
centerX = x1 + radiusX,
centerY = y1 + radiusY,
step = 0.01,
a = step,
pi2 = Math.PI * 2 - step;
radius = Math.sqrt(radiusX * radiusX + radiusY * radiusY) / 2;
ctxDraw.beginPath();
ctxDraw.arc(centerX, centerY, radius, 0, 2 * Math.PI, true);
ctxDraw.closePath();
ctxDraw.fillStyle = 'green';
ctxDraw.fill();
ctxDraw.strokeStyle = '#000';
ctxDraw.stroke();
xVertex = centerX;
yVertex = centerY;
}
// tooltip show on hover over objects
function hoverTooltip() {
var leftScroll = $("#scrollParent").scrollLeft();
var topScroll = $("#scrollParent").scrollTop();
let cw = canvasBack.width;
let ch = canvasBack.height;
for (var i = 0; i < hotspots.length; i++) {
var h = hotspots[i];
var dx = mousex - h.x;
var dy = mousey - h.y;
if (dx * dx + dy * dy < h.radius * h.radius) {
$('#console').text(h.tip);
ctxLabel.clearRect(0, 0, cw, ch);
ctxLabel.fillText(h.tip, mousex + leftScroll, mousey + topScroll);
} else {
ctxLabel.clearRect(0, 0, cw, ch);
}
}
}
#scrollParent {
width: 644px;
height: 364px;
overflow: auto;
position: relative;
}
#scrollParent>canvas {
position: absolute;
left: 0;
top: 0;
border: 1px solid #ababab;
}
#backSpace {
z-index: 0;
}
#drawSpace {
display: none;
z-index: 1;
}
#layerCanvas {
z-index: 2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="scrollParent">
<!-- actual canvas that is visible -->
<canvas width="640" height="360" id="backSpace"></canvas>
<!-- canvas used for drawing new objects -->
<canvas width="640" height="360" id="drawSpace"></canvas>
<!-- canvas used to display tooltip -->
<canvas width="640" height="360" id="layerCanvas"></canvas>
</div>
<div id="console"></div>
</div>
actual problem is in the bellow image, tooltip worked fine when the 1st object was drawn, but once the second object was drawn tooltip worked only for the second one, not for previously drawn objects.
what is causing this issue, and how to fix it ?
Removing else will not remove the label when leaving the elipse.
You need to exit the loop once you found the correct elipse from the array using break.
function hoverTooltip() {
var leftScroll = $("#scrollParent").scrollLeft();
var topScroll = $("#scrollParent").scrollTop();
let cw = canvasBack.width;
let ch = canvasBack.height;
for (var i = 0; i < hotspots.length; i++) {
var h = hotspots[i];
var dx = mousex - h.x;
var dy = mousey - h.y;
if (dx * dx + dy * dy < h.radius * h.radius) {
$('#console').text(h.tip);
ctxLabel.clearRect(0, 0, cw, ch);
ctxLabel.fillText(h.tip, mousex + leftScroll, mousey + topScroll);
break; // exit the loop
} else {
ctxLabel.clearRect(0, 0, cw, ch);
}
}
}
UPDATE
I figured that if you draw two objects over each other, it will behave poorly. Try this instead. It will display information of the latest drawn spot.
function hoverTooltip() {
var leftScroll = $("#scrollParent").scrollLeft();
var topScroll = $("#scrollParent").scrollTop();
let cw = canvasBack.width;
let ch = canvasBack.height;
var spots = hotspots.filter((h) => {
var dx = mousex - h.x;
var dy = mousey - h.y;
return (dx * dx + dy * dy < h.radius * h.radius);
})
if (spots.length > 0) {
var h = spots[spots.length - 1]; // latest drawn spot
$('#console').text(h.tip);
ctxLabel.clearRect(0, 0, cw, ch);
ctxLabel.fillText(h.tip, mousex + leftScroll, mousey + topScroll);
}
else
{
ctxLabel.clearRect(0, 0, cw, ch);
}
}
I see there are already a few answers. This is mine:
In order to be able to show the label for every circle on hover you need to save all your circles in am array: the circles array. I'm using the ctx.isPointInPath() method to know if the mouse is over the circle, and if it is I paint the label.
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
let cw = canvas.width = 640;
let ch = canvas.height = 360;
let found = false;//is a circle found?
const cText = document.querySelector("#text");
const ctxText = cText.getContext("2d");
cText.width = 640;
cText.height = 360;
ctxText.font="1em Verdana";
let drawing = false;
let circles = []
class Circle{
constructor(x,y){
this.x = x;
this.y = y;
this.r = 0;
}
updateR(m) {
this.r = dist(this,m);
}
draw(){
ctx.beginPath();
ctx.arc(this.x,this.y,this.r,0,2*Math.PI);
}
paint(){
ctx.fillStyle = "green";
ctx.strokeStyle = "black";
this.draw();
ctx.stroke();
ctx.fill();
}
label(m){
this.draw();
if (ctx.isPointInPath(m.x, m.y)) {
ctx.beginPath();
ctx.arc(this.x, this.y, 4, 0, 2 * Math.PI);
ctxText.fillStyle = "black";
ctxText.fillText(`you are over ${this.x},${this.y}`,m.x,m.y)
found = true;
}
}
}
let m = {}// mouse
cText.addEventListener("mousedown",(e)=>{
drawing = true;
m = oMousePos(canvas, e);
let circle = new Circle(m.x,m.y)
circles.push(circle);
})
cText.addEventListener("mouseup",(e)=>{
drawing = false;
})
cText.addEventListener("mousemove",(e)=>{
m = oMousePos(canvas, e);
found = false;
if(drawing){
let circle = circles[circles.length-1];//the last circle in the circles arrey
circle.updateR(m);
}
ctx.clearRect(0,0, cw,ch);
ctxText.clearRect(0,0,cw,ch)
circles.map((c) => {c.paint();});
for(let i = circles.length-1; i >=0 ; i--){
circles[i].label(m);
if(found){break;}
}
})
function oMousePos(canvas, evt) {
var ClientRect = canvas.getBoundingClientRect();
return { //objeto
x: Math.round(evt.clientX - ClientRect.left),
y: Math.round(evt.clientY - ClientRect.top)
}
}
function dist(p1, p2) {
let dx = p2.x - p1.x;
let dy = p2.y - p1.y;
return Math.sqrt(dx * dx + dy * dy);
}
canvas{border:1px solid;position:absolute; top:0; left:0;}
#scrollParent{position:relative;}
<div id="scrollParent">
<!-- actual canvas that is visible -->
<canvas width="640" height="360"></canvas>
<canvas width="640" height="360" id="text"></canvas>
</div>
I've updated the code in base of the comment of #HelderSepu
A SECOND UPDATE in base of a second message from #HelderSepu. He wants to see "multiple message but avoid overlapping the messages"
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
let cw = canvas.width = 640;
let ch = canvas.height = 360;
let text = "";
const cText = document.querySelector("#text");
const ctxText = cText.getContext("2d");
cText.width = 640;
cText.height = 360;
ctxText.font="1em Verdana";
let drawing = false;
let circles = []
class Circle{
constructor(x,y){
this.x = x;
this.y = y;
this.r = 0;
}
updateR(m) {
this.r = dist(this,m);
}
draw(){
ctx.beginPath();
ctx.arc(this.x,this.y,this.r,0,2*Math.PI);
}
paint(){
ctx.fillStyle = "green";
ctx.strokeStyle = "black";
this.draw();
ctx.stroke();
ctx.fill();
}
label(m){
this.draw();
if (ctx.isPointInPath(m.x, m.y)) {
this.text = `[${this.x},${this.y}]`
}else{
this.text = "";
}
}
}
let m = {}// mouse
cText.addEventListener("mousedown",(e)=>{
drawing = true;
m = oMousePos(canvas, e);
let circle = new Circle(m.x,m.y)
circles.push(circle);
})
cText.addEventListener("mouseup",(e)=>{
drawing = false;
})
cText.addEventListener("mousemove",(e)=>{
m = oMousePos(canvas, e);
if(drawing){
let circle = circles[circles.length-1];//the last circle in the circles arrey
circle.updateR(m);
}
ctx.clearRect(0,0, cw,ch);
ctxText.clearRect(0,0,cw,ch);
text="";
circles.map((c) => {c.paint();c.label(m);});
circles.map((c) => {text += c.text;});
ctxText.fillStyle = "black";
ctxText.fillText(text,m.x,m.y)
})
function oMousePos(canvas, evt) {
var ClientRect = canvas.getBoundingClientRect();
return { //objeto
x: Math.round(evt.clientX - ClientRect.left),
y: Math.round(evt.clientY - ClientRect.top)
}
}
function dist(p1, p2) {
let dx = p2.x - p1.x;
let dy = p2.y - p1.y;
return Math.sqrt(dx * dx + dy * dy);
}
canvas{border:1px solid;position:absolute; top:0; left:0;}
#scrollParent{position:relati
<div id="scrollParent">
<!-- actual canvas that is visible -->
<canvas width="640" height="360"></canvas>
<canvas width="640" height="360" id="text"></canvas>
<div id="console"></div>
</div>

Remove objects in the canvas in certain coordinates

I would like to remove the balls already generated in the canvas on the click and decrease the counter on the bottom, but my function does not work. Here is my code concerning the part of the ball removal.
Is it possible to use a div to get the same result and to facilitate the removal of the balls? thank you
ball.onclick = function removeBalls(event) {
var x = event.clientX;
var y = event.clientY;
ctx.clearRect(x, y, 100, 50);
ctx.fillStyle = "#000000";
ctx.font = "20px Arial";
ctx.fillText("Balls Counter: " + balls.length - 1, 10, canvas.height - 10);
}
below I enclose my complete code
// GLOBAL VARIBLES
var gravity = 4;
var forceFactor = 0.3; //0.3 0.5
var mouseDown = false;
var balls = []; //hold all the balls
var mousePos = []; //hold the positions of the mouse
var ctx = canvas.getContext('2d');
var heightBrw = canvas.height = window.innerHeight;
var widthBrw = canvas.width = window.innerWidth;
var bounciness = 1; //0.9
window.onload = function gameCore() {
function onMouseDown(event) {
mouseDown = true;
mousePos["downX"] = event.pageX;
mousePos["downY"] = event.pageY;
}
canvas.onclick = function onMouseUp(event) {
mouseDown = false;
balls.push(new ball(mousePos["downX"], mousePos["downY"], (event.pageX - mousePos["downX"]) * forceFactor,
(event.pageY - mousePos["downY"]) * forceFactor, 5 + (Math.random() * 10), bounciness, random_color()));
ball
}
function onMouseMove(event) {
mousePos['currentX'] = event.pageX;
mousePos['currentY'] = event.pageY;
}
function resizeWindow(event) {
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
}
function reduceBounciness(event) {
if (bounciness == 1) {
for (var i = 0; i < balls.length; i++) {
balls[i].b = bounciness = 0.9;
document.getElementById("btn-bounciness").value = "⤽ Bounciness";
}
} else {
for (var i = 0; i < balls.length; i++) {
balls[i].b = bounciness = 1;
document.getElementById("btn-bounciness").value = " ⤼ Bounciness";
}
}
return bounciness;
}
function reduceSpeed(event) {
for (var i = 0; i < balls.length; i++) {
balls[i].vx = velocityX = 20 + c;
balls[i].vy = velocityY = 20 + c;
}
}
function speedUp(event) {
for (var i = 0; i < balls.length; i++) {
balls[i].vx = velocityX = 120 + c;
balls[i].vy = velocityY = 120 + c;
}
}
function stopGravity(event) {
if (gravity == 4) {
for (var i = 0; i < balls.length; i++) {
balls[i].g = gravity = 0;
balls[i].vx = velocityX = 0;
balls[i].vy = velocityY = 0;
document.getElementById("btn-gravity").value = "►";
}
} else {
for (var i = 0; i < balls.length; i++) {
balls[i].g = gravity = 4;
balls[i].vx = velocityX = 100;
balls[i].vy = velocityY = 100;
document.getElementById("btn-gravity").value = "◾";
}
}
}
ball.onclick = function removeBalls(event) {
var x = event.clientX;
var y = event.clientY;
ctx.clearRect(x, y, 100, 50);
ctx.fillStyle = "#000000";
ctx.font = "20px Arial";
ctx.fillText("Balls Counter: " + balls.length - 1, 10, canvas.height - 10);
}
document.getElementById("btn-gravity").addEventListener("click", stopGravity);
document.getElementById("btn-speed-up").addEventListener("click", speedUp);
document.getElementById("btn-speed-down").addEventListener("click", reduceSpeed);
document.getElementById("btn-bounciness").addEventListener("click", reduceBounciness);
document.addEventListener("mousedown", onMouseDown);
document.addEventListener("mousemove", onMouseMove);
window.addEventListener('resize', resizeWindow);
}
// GRAPHICS CODE
function circle(x, y, r, c) { // x position, y position, r radius, c color
//draw a circle
ctx.beginPath(); //approfondire
ctx.arc(x, y, r, 0, Math.PI * 2, true);
ctx.closePath();
//fill
ctx.fillStyle = c;
ctx.fill();
//stroke
ctx.lineWidth = r * 0.1; //border of the ball radius * 0.1
ctx.strokeStyle = "#000000"; //color of the border
ctx.stroke();
}
function random_color() {
var letter = "0123456789ABCDEF".split(""); //exadecimal value for the colors
var color = "#"; //all the exadecimal colors starts with #
for (var i = 0; i < 6; i++) {
color = color + letter[Math.round(Math.random() * 15)];
}
return color;
}
function selectDirection(fromx, fromy, tox, toy) {
ctx.beginPath();
ctx.moveTo(fromx, fromy);
ctx.lineTo(tox, toy);
ctx.moveTo(tox, toy);
}
//per velocità invariata rimuovere bounciness
function draw_ball() {
this.vy = this.vy + gravity * 0.1; // v = a * t
this.x = this.x + this.vx * 0.1; // s = v * t
this.y = this.y + this.vy * 0.1;
if (this.x + this.r > canvas.width) {
this.x = canvas.width - this.r;
this.vx = this.vx * -1 * this.b;
}
if (this.x - this.r < 0) {
this.x = this.r;
this.vx = this.vx * -1 * this.b;
}
if (this.y + this.r > canvas.height) {
this.y = canvas.height - this.r;
this.vy = this.vy * -1 * this.b;
}
if (this.y - this.r < 0) {
this.y = this.r;
this.vy = this.vy * 1 * this.b;
}
circle(this.x, this.y, this.r, this.c);
}
// OBJECTS
function ball(positionX, positionY, velosityX, velosityY, radius, bounciness, color, gravity) {
this.x = positionX;
this.y = positionY;
this.vx = velosityX;
this.vy = velosityY;
this.r = radius;
this.b = bounciness;
this.c = color;
this.g = gravity;
this.draw = draw_ball;
}
// GAME LOOP
function game_loop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (mouseDown == true) {
selectDirection(mousePos['downX'], mousePos['downY'], mousePos['currentX'], mousePos['currentY']);
}
for (var i = 0; i < balls.length; i++) {
balls[i].draw();
}
ctx.fillStyle = "#000000";
ctx.font = "20px Arial";
ctx.fillText("Balls Counter: " + balls.length, 10, canvas.height - 10);
}
setInterval(game_loop, 10);
* {
margin: 0px; padding: 0px;
}
html, body {
width: 100%; height: 100%;
}
#canvas {
display: block;
height: 95%;
border: 2px solid black;
width: 98%;
margin-left: 1%;
}
#btn-speed-up, #btn-speed-down, #btn-bounciness, #btn-gravity{
padding: 0.4%;
background-color: beige;
text-align: center;
font-size: 20px;
font-weight: 700;
float: right;
margin-right: 1%;
margin-top:0.5%;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Power Balls</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<canvas id="canvas"></canvas>
<input type="button" value="⤼ Bounciness" id="btn-bounciness"></input>
<input type="button" onclick="c+=10" value="+ Speed" id="btn-speed-up"></input>
<input type="button" value="◾" id="btn-gravity"></input>
<input type="button" onclick="c+= -10" value=" - Speed" id="btn-speed-down"></input>
<script src="js/main.js"></script>
</body>
</html>
I see two problems:
ball.onclick will not get triggered, as ball it is not a DOM object. Instead, you need to work with canvas.onclick. Check whether the user clicked on a ball or on empty space to decide whether to delete or create a ball.
To delete the ball, ctx.clearRect is not sufficient. This will clear the ball from the currently drawn frame, but the object still remains in the array balls and will therefore be drawn again in the next frame via balls[i].draw();. Instead, you need to remove the clicked ball entirely from the array, e. g. by using splice.
Otherwise, nice demo! :)
This cannot be done because the canvas is an immediate mode API. All you can do is draw over the top but this is not reliable.
https://en.wikipedia.org/wiki/Immediate_mode_(computer_graphics)
You will have to store each item in a separate data structure, then re-draw whenever a change occurs. In your case there is an array of balls, so you should remove the one that was clicked, before redrawing the entire array.
Each time you remove something, clear the canvas then re-draw each ball.
There are optimisations you can make if this is too slow.

How to run multiple instances of a single object JavaScript

Currently attempting to make a physics simulation for elastic collisions of circles. I am having an issue where I do not know how to run the simulation with two circles interacting at the same time. I am not yet looking to create the interaction between the circles just to have them both running simultaneously. Any help is much appreciated. This is my first post so I apologize if I formatted something incorrectly.
var width = 400;
var height = 400;
var canvas = ctx = false;
var frameRate = 1 / 60; // Seconds
var frameDelay = frameRate * 1000; // ms
var loopTimer = false;
var ball = {
position: {
x: width / 2,
y: height / 2
},
velocity: {
x: 0,
y: 0
},
radius: 15, // 1px = 1cm
restitution: -1
};
var mouse = {
x: 0,
y: 0,
isDown: false
};
function getMousePosition(event) {
mouse.x = event.pageX - canvas.offsetLeft;
mouse.y = event.pageY - canvas.offsetTop;
}
var mouseDown = function(event) {
if (event.which == 1) {
getMousePosition(event);
mouse.isDown = true;
ball.position.x = mouse.x;
ball.position.y = mouse.y;
}
}
var mouseUp = function(event) {
if (event.which == 1) {
mouse.isDown = false;
ball.velocity.y = (ball.position.y - mouse.y) / 10;
ball.velocity.x = (ball.position.x - mouse.x) / 10;
}
}
var setup = function() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
canvas.onmousemove = getMousePosition;
canvas.onmousedown = mouseDown;
canvas.onmouseup = mouseUp;
ctx.fillStyle = 'blue';
ctx.strokeStyle = '#000000';
loopTimer = setInterval(loop, frameDelay);
}
var loop = function() {
if (!mouse.isDown) {
ball.position.x += ball.velocity.x * frameRate * 100;
ball.position.y += ball.velocity.y * frameRate * 100;
}
if (ball.position.y > height - ball.radius) {
ball.velocity.y *= ball.restitution;
ball.position.y = height - ball.radius;
}
if (ball.position.x > width - ball.radius) {
ball.velocity.x *= ball.restitution;
ball.position.x = width - ball.radius;
}
if (ball.position.x < ball.radius) {
ball.velocity.x *= ball.restitution;
ball.position.x = ball.radius;
}
if (ball.position.y < ball.radius) {
ball.velocity.y *= ball.restitution;
ball.position.y = ball.radius;
}
ctx.clearRect(0, 0, width, height);
ctx.save();
ctx.translate(ball.position.x, ball.position.y);
ctx.beginPath();
ctx.arc(0, 0, ball.radius, 0, Math.PI * 2, true);
ctx.fill();
ctx.closePath();
ctx.restore();
if (mouse.isDown) {
ctx.beginPath();
ctx.moveTo(ball.position.x, ball.position.y);
ctx.lineTo(mouse.x, mouse.y);
ctx.stroke();
ctx.closePath();
}
}
setup();
#canvas {
border: solid 1px #ccc;
}
<canvas id="canvas"></canvas>
Here is how I would do it:
Instead of making the ball a kind of static object I made a constructor function (More about that here).
Then I made a ball array to store all the balls.
To make the dragging possible I store a seperate ball, which is not being moved by "physics" in the newBall variable. This ball is either invisible or is the ball currently being dragged.
In mouseDown() the newBall gets positioned under the cursor.
In mouseUp() it gets it's velocity and gets added to the array of animated balls. Also a new newBall gets created.
In loop() I loop two times through the array of animated balls. Once for the physics, once for the painting.
(Normally you would use two different methods with different tickRates to make animation more smooth, because physics calculation doesn't need to happen 60 times per second.
var width = 400;
var height = 400;
var canvas = ctx = false;
var frameRate = 1 / 60; // Seconds
var frameDelay = frameRate * 1000; // ms
var loopTimer = false;
function ball() {
this.position = {
x: width / 2,
y: height / 2
};
this.velocity = {
x: 0,
y: 0
};
this.radius = 15; // 1px = 1cm
this.restitution = -1
};
var balls = [];
var newBall = new ball();
var mouse = {
x: 0,
y: 0,
isDown: false
};
function getMousePosition(event) {
mouse.x = event.pageX - canvas.offsetLeft;
mouse.y = event.pageY - canvas.offsetTop;
}
var mouseDown = function(event) {
if (event.which == 1) {
getMousePosition(event);
mouse.isDown = true;
newBall.position.x = mouse.x;
newBall.position.y = mouse.y;
}
}
var mouseUp = function(event) {
if (event.which == 1) {
mouse.isDown = false;
newBall.velocity.y = (newBall.position.y - mouse.y) / 10;
newBall.velocity.x = (newBall.position.x - mouse.x) / 10;
balls.push(newBall);
newBall = new ball();
}
}
var setup = function() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
canvas.onmousemove = getMousePosition;
canvas.onmousedown = mouseDown;
canvas.onmouseup = mouseUp;
ctx.fillStyle = 'blue';
ctx.strokeStyle = '#000000';
loopTimer = setInterval(loop, frameDelay);
}
var loop = function() {
for (var ball of balls) {
ball.position.x += ball.velocity.x * frameRate * 100;
ball.position.y += ball.velocity.y * frameRate * 100;
if (ball.position.y > height - ball.radius) {
ball.velocity.y *= ball.restitution;
ball.position.y = height - ball.radius;
}
if (ball.position.x > width - ball.radius) {
ball.velocity.x *= ball.restitution;
ball.position.x = width - ball.radius;
}
if (ball.position.x < ball.radius) {
ball.velocity.x *= ball.restitution;
ball.position.x = ball.radius;
}
if (ball.position.y < ball.radius) {
ball.velocity.y *= ball.restitution;
ball.position.y = ball.radius;
}
}
ctx.clearRect(0, 0, width, height);
for (var ball of balls) {
ctx.save();
ctx.translate(ball.position.x, ball.position.y);
ctx.beginPath();
ctx.arc(0, 0, ball.radius, 0, Math.PI * 2, true);
ctx.fill();
ctx.closePath();
ctx.restore();
}
ctx.save();
ctx.translate(newBall.position.x, newBall.position.y);
ctx.beginPath();
ctx.arc(0, 0, newBall.radius, 0, Math.PI * 2, true);
ctx.fill();
ctx.closePath();
ctx.restore();
if (mouse.isDown) {
ctx.beginPath();
ctx.moveTo(newBall.position.x, newBall.position.y);
ctx.lineTo(mouse.x, mouse.y);
ctx.stroke();
ctx.closePath();
}
}
setup();
#canvas {
border: solid 1px #ccc;
}
<canvas id="canvas"></canvas>
Now to get a bit more complex:
I added tickDelay and tickTimer to use them in a tickLoop
The ball constructor now has two methods:
show() draws the ball on the canvas
tick() does the pysics stuff (dt= deltaTime: time since last tick)
newBall is now null if the mouse isn't pressed
setup() initializes the width and height according to the <canvas> elements real size
tick() loops through the balls and calls .tick() tickDelay is in milliseconds so it gets divided by 1000
drawFrame() is your former loop() and does the drawing stuff
var width = 400;
var height = 400;
var canvas = ctx = false;
var frameRate = 1 / 60; // Seconds
var frameDelay = frameRate * 1000; // ms
var tickDelay = frameDelay * 2; //ticks 2 times slower than frames
var frameTimer;
var tickTimer;
function ball() {
this.position = {
x: width / 2,
y: height / 2
};
this.velocity = {
x: 0,
y: 0
};
this.radius = 15; // 1px = 1cm
this.restitution = -.99;
this.show = function() {
ctx.save();
ctx.translate(this.position.x, this.position.y);
ctx.beginPath();
ctx.arc(0, 0, this.radius, 0, Math.PI * 2, true);
ctx.fill();
ctx.closePath();
ctx.restore();
};
this.tick = function(dt) {
this.position.x += this.velocity.x * dt;
this.position.y += this.velocity.y * dt;
if (this.position.y > height - this.radius) {
this.velocity.y *= this.restitution;
this.position.y = height - this.radius;
}
if (this.position.x > width - this.radius) {
this.velocity.x *= this.restitution;
this.position.x = width - this.radius;
}
if (this.position.x < this.radius) {
this.velocity.x *= this.restitution;
this.position.x = this.radius;
}
if (this.position.y < this.radius) {
this.velocity.y *= this.restitution;
this.position.y = this.radius;
}
}
};
var balls = [];
var newBall;
var mouse = {
x: 0,
y: 0,
isDown: false
};
function getMousePosition(event) {
mouse.x = event.pageX - canvas.offsetLeft;
mouse.y = event.pageY - canvas.offsetTop;
}
function mouseDown(event) {
if (event.which == 1) {
getMousePosition(event);
mouse.isDown = true;
if (!newBall) newBall = new ball();
newBall.position.x = mouse.x;
newBall.position.y = mouse.y;
}
}
function mouseUp(event) {
if (event.which == 1) {
mouse.isDown = false;
newBall.velocity.y = (newBall.position.y - mouse.y);
newBall.velocity.x = (newBall.position.x - mouse.x);
balls.push(newBall);
newBall = null;
}
}
function setup() {
canvas = document.getElementById("canvas");
width = canvas.getBoundingClientRect().width;
height = canvas.getBoundingClientRect().height;
ctx = canvas.getContext("2d");
canvas.onmousemove = getMousePosition;
canvas.onmousedown = mouseDown;
canvas.onmouseup = mouseUp;
ctx.fillStyle = 'blue';
ctx.strokeStyle = '#000000';
requestAnimationFrame(drawFrame);
frameTimer = setInterval(drawFrame, frameDelay);
tickTimer = setInterval(tick, tickDelay);
}
function tick() {
for (var ball of balls) ball.tick(tickDelay * .001);
}
function drawFrame() {
ctx.clearRect(0, 0, width, height);
for (var ball of balls) ball.show();
if (newBall) newBall.show(ctx);
if (mouse.isDown && newBall) {
ctx.beginPath();
ctx.moveTo(newBall.position.x, newBall.position.y);
ctx.lineTo(mouse.x, mouse.y);
ctx.stroke();
ctx.closePath();
}
}
setup();
#canvas {
border: solid 1px #ccc;
}
<canvas id="canvas"></canvas>
A really simple way would to do exactly the same as you do now, but not initiate all functions as a variable. Change all the variables that are functions to just functions, and where you call them. At least the variable called ball. Then after that you could make two variables like this
ball1 = new ball();
ball2 = new ball();
Your script is kind of messy so hard for me to say if this will go through without any errors, but if it does, I am more than happy to help. This is not the very best solution if you only go for the way i presented now so please do not use this as you solution, but more as a way to get started. Also you will not really learn anything of it if we just gave you the answer
Edit:
Another thing to mark is that using setInterval for games and graphical projects may be a bad idea since JavaScript is single threaded. A better solution is using requestAnimationFrame()
It would look something like this
function mainLoop() {
update();
draw();
requestAnimationFrame(mainLoop);
}
// Start things off
requestAnimationFrame(mainLoop);

How can i add a Start button to this function?

I'm trying to figure out how I can add a start button to play a javascript game by replacing the audio in the background. I came across this game, the way it works is as soon as you load the page the music plays in the background and the games already started. When I removed the audio link, the game paused after the players 3 lives are up, if I leave the audio in, then when the 3 lives are up you can see your points and a pop up message, can someone please help me understand this
here is a link to the game so you can look at the code and understand what I'm trying to say : https://jsfiddle.net/74nbrdak/embedded/result/
<div>
<canvas id="canvas" width="1000" height="500"></canvas>
</div>
<audio id="background-music" preload="auto" autoplay loop>
<source
src="https://dl.dropbox.com/s/5r3iu7kjsl0mx81/Wildfire%20Cut%20Loopable.wav" type="audio/wav">
function ShowGamesFinished() {
var message = gamesfinished[Math.floor(Math.random() * gamesfinished.length)];
document.getElementById("background-music").pause();
When I removed the audio link, the game paused after the players 3 lives are up, if I leave the audio in, then when the 3 lives are up you can see your points and a pop up message, can someone please help me understand this
So, In the second scenario when the audio element is on the page, the game works just as the creator intended.
In the first scenario when the audio element isn't on the page, the game works fine until the function that handles the game over is called. What causes the problem in that function is this line document.getElementById("background-music").pause();. Since the audio element doesn't exist, it throws an error and the game over screen isn't drawn. Hope that this helps
If you are using pure javascript Without any external libraries, you can initialize your canvas and on a click of the button you can start animating the canvas and your game starts.
let me know If you don't get my answer.
At first glance, removing the audio tag should not have any effect at all on the javascript. The audio plays upon openeing the page because the audio tag has the autoplay attribute.
All of the javascript code seems to be just within a script tag, so it will also autorun once the page gets opened. What you could try is wrapping the entire code from the fiddle into a function and just bind it to your button.
Something like:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
h1 {
font-family: Architects Daughter;
text-align: center;
font-size: 48pt;
margin-top: 50px;
margin-bottom: 0px;
}
h2 {
font-family: Architects Daughter;
text-align: center;
font-size: 28pt;
margin-top: 0px;
margin-bottom: 50px;
}
span {
display: block;
font-family: Arial;
text-align: center;
margin-bottom: 2px;
}
div {
display: flex;
justify-content: space-around;
}
canvas {
border: 2px solid #CC3333;
}
</style>
</head>
<body>
<div>
<canvas id="canvas" width="640" height="360"></canvas>
</div>
<button id="start_game">Start</button>
<script>
var run_game = function() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var WIDTH = canvas.width;
var HEIGHT = canvas.height;
var updateTime = 20; // Milliseconds
var keys = [false, false, false];
var score = 0;
var kills = 0;
// Player Size = 50x18
var playerHealth = 3;
var playerX = WIDTH / 2;
var playerY = HEIGHT - 20;
var playerSpeed = 6;
var lazerSpeed = 16;
var lazerReloadDistance = playerY - 120;
var lazerLoaded = true;
var lazers = [];
var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var maxEnemies = 12;
var enemySpeed = 4;
var enemies = [];
function Clear() {
ctx.fillStyle = "#404040";
ctx.fillRect(0, 0, WIDTH, HEIGHT);
}
function DrawHealth(health) {
ctx.fillStyle = "#E52B50";
ctx.shadowColor = "#E52B50";
ctx.shadowBlur = 15;
ctx.font = "18px Arial";
ctx.textAlign = "start";
var hearts = "";
if (health == 3) {
hearts = "<3 <3 <3";
}
else if (health == 2) {
hearts = "<3 <3 X";
}
else if (health == 1) {
hearts = "<3 X X";
}
else {
hearts = "X X X";
}
ctx.fillText(hearts, 10, 25);
}
function DrawScore() {
ctx.fillStyle = "#FFFF00";
ctx.shadowColor = "#FFFF00";
ctx.shadowBlur = 15;
ctx.font = "18px Arial";
ctx.textAlign = "end";
ctx.fillText(score, WIDTH - 10, 25);
}
function DrawPlayer(x, y) {
ctx.fillStyle = "#1E90FF";
ctx.shadowColor = "#1E90FF";
ctx.shadowBlur = 15;
ctx.font = "24px Arial";
ctx.textAlign = "center";
ctx.fillText("</^\\>", x, y);
}
function Lazer() {
this.x = playerX;
this.y = playerY - 38;
this.draw = function() {
ctx.fillStyle = "#FFFF00";
ctx.shadowColor = "#FFFF00";
ctx.shadowBlur = 15;
this.y -= lazerSpeed;
ctx.fillRect(this.x, this.y, 2, 18);
}
}
function DrawLazers() {
// Check if the last lazer fired is far enough away to fire another
if (lazers.length != 0) {
if (lazers[lazers.length - 1].y <= lazerReloadDistance) {
lazerLoaded = true;
}
}
else {
lazerLoaded = true;
}
for (var i = 0; i < lazers.length; i++) {
var currentLazer = lazers[i];
// Still on screen
if (currentLazer.y > -20) {
currentLazer.draw();
}
else {
lazers.splice(i, 1);
}
}
}
function Enemy(x) {
this.x = x;
this.y = 0;
this.health = Math.ceil(Math.random() * 4);
this.speed = enemySpeed / this.health;
var letterIndex = Math.floor(Math.random() * letters.length);
this.letter = letters.substr(letterIndex, 1);
this.size = 24 + (this.health * 4); // Font size based on health
ctx.font = this.size+"px Arial";
this.width = ctx.measureText(this.letter).width;
this.height = this.size * 0.75; // Approximate height;
this.draw = function() {
ctx.fillStyle = "#FF0040";
ctx.shadowColor = "#FF0040";
ctx.shadowBlur = 15;
ctx.font = this.size+"px Arial";
ctx.textAlign = "center";
this.y += this.speed;
ctx.fillText(this.letter, this.x, this.y);
}
}
function DrawEnemies() {
// Spawn new enemies
if (Math.random() <= 0.05 && enemies.length < maxEnemies) {
var randX = 40 + Math.floor(Math.random() * (WIDTH - 80));
enemies.push(new Enemy(randX));
}
for (var i = 0; i < enemies.length; i++) {
var currentEnemy = enemies[i];
if (currentEnemy.health <= 0) {
enemies.splice(i, 1);
score += 25;
kills++;
continue;
}
// Put enemies that passed the player back at the top
if (currentEnemy.y > HEIGHT + currentEnemy.height) {
currentEnemy.y = 0;
continue;
}
currentEnemy.draw();
}
}
var gameOverMessages = [
"You're in a better place",
"You're Cooked!",
"You gave it your all",
"At least you tried",
"You're Ruined!",
"You're Finished!"
];
function DrawGameOver() {
var message = gameOverMessages[Math.floor(Math.random() * gameOverMessages.length)];
// after deleting the audio element, this doesnt work anymore.
// document.getElementById("background-music").pause();
ctx.fillStyle = "#505050";
ctx.shadowColor = "#505050";
ctx.shadowBlur = 15;
ctx.fillRect(50, (HEIGHT / 2) - 100, WIDTH - 100, 200)
ctx.fillStyle = "#FFFFFF";
ctx.shadowColor = "#FFFFFF";
ctx.shadowBlur = 15;
ctx.textAlign = "center";
ctx.font = "36pt Arial";
ctx.fillText(message, WIDTH / 2, HEIGHT / 2 - 40);
ctx.textAlign = "end";
ctx.font = "18pt Arial";
ctx.fillText("Final Score - ", WIDTH / 2, HEIGHT / 2 + 30);
ctx.textAlign = "start";
ctx.fillStyle = "#FFFF00";
ctx.shadowColor = "#FFFF00";
ctx.fillText(score, WIDTH / 2, HEIGHT / 2 + 30);
ctx.fillStyle = "#FFFFFF";
ctx.shadowColor = "#FFFFFF";
ctx.textAlign = "end";
ctx.font = "18pt Arial";
ctx.fillText("Total Kills - ", WIDTH / 2, HEIGHT / 2 + 60);
ctx.textAlign = "start";
ctx.fillStyle = "#FF0040";
ctx.shadowColor = "#FF0040";
ctx.fillText(kills, WIDTH / 2, HEIGHT / 2 + 60);
}
////////////////////
// Core Functions //
////////////////////
var collidedEnemyIndex = -1;
function CheckCollision() {
for (var i = 0; i < enemies.length; i++) {
var currentEnemy = enemies[i];
// Check if enemy hits player. The 2 is to account for the text width of the player
if (
currentEnemy.x <= playerX - 2 + 25 + (currentEnemy.width / 2) &&
currentEnemy.x >= playerX - 2 - 25 - (currentEnemy.width / 2) &&
currentEnemy.y >= playerY - 18 &&
currentEnemy.y <= playerY + currentEnemy.height &&
collidedEnemyIndex != enemies.indexOf(currentEnemy)
)
{
collidedEnemyIndex = enemies.indexOf(currentEnemy);
playerHealth--;
}
// Reset the index of the enemy colliding with the player
if (collidedEnemyIndex == enemies.indexOf(currentEnemy) && currentEnemy.y < HEIGHT / 2) {
collidedEnemyIndex = -1;
}
for (var j = 0; j < lazers.length; j++) {
var currentLazer = lazers[j];
if (
currentLazer.x <= currentEnemy.x + (currentEnemy.width / 2) &&
currentLazer.x >= currentEnemy.x - (currentEnemy.width / 2) &&
currentLazer.y <= currentEnemy.y
)
{
currentEnemy.health--;
score += 10;
lazers.splice(lazers.indexOf(currentLazer), 1);
}
}
}
}
function HandleInput() {
if (keys[0] == true && keys[1] == false && playerX <= WIDTH - 30) {
playerX += playerSpeed;
}
if (keys[1] == true && keys[0] == false && playerX >= 30) {
playerX -= playerSpeed;
}
if (keys[2]) {
if (lazerLoaded) {
lazers.push(new Lazer());
lazerLoaded = false;
}
}
}
function KeysDown(e) {
e.preventDefault();
// Right
if (e.keyCode == 39) {
keys[0] = true;
}
// Left
else if (e.keyCode == 37) {
keys[1] = true;
}
// Up/Fire
if (e.keyCode == 38) {
keys[2] = true;
}
}
function KeysUp(e) {
// Right
if (e.keyCode == 39) {
keys[0] = false;
}
// Left
else if (e.keyCode == 37) {
keys[1] = false;
}
// Up/Fire
if (e.keyCode == 38) {
keys[2] = false;
}
}
document.addEventListener("keydown", KeysDown, true);
document.addEventListener("keyup", KeysUp, true);
function Update() {
Clear();
HandleInput();
CheckCollision();
DrawEnemies();
DrawLazers();
DrawPlayer(playerX, playerY);
DrawHealth(playerHealth);
DrawScore();
if (playerHealth <= 0) {
clearInterval(gameLoop);
DrawGameOver();
}
}
var gameLoop = setInterval(Update, updateTime);
};
document.querySelector( '#start_game' ).addEventListener( 'click', run_game );
</script>
</body>
</html>

Categories