JSFiddle - React, Tailwind, and code Playground
HTML
<div id="room">
</div>
<div id="bal_graphic">
</div>
<div id="hero_graphic">
CSS
body{
margin: 0px;
padding; 0px;
}
#room{
position: absolute;
background-color: #ccc;
width: 300px;
height: 250px;
}
#bal_graphic{
position: absolute;
background-color: #f00;
width: 20px;
height: 20px;
}
#hero_graphic{
position: absolute;
background-color: #ff0;
width: 50px;
height: 20px;
}
JavaScript
// global scope variables
var bal={};
var room={};
var hero={};
var mouse={};
// Dit zijn alles objecten in de game.
startgame(); // voer blokje code startgame uit.
// einde programma.
// blokje start game.
function startgame()
{
// initieert waardes voor alle objecten
mouse.x=0; // positie
mouse.y=0;
room.w=300; //( width + height)
room.h=250;
hero.w=50; // hero width height
hero.h=20;
hero.x=room.w/2-hero.w/2; // hero begint in midden
hero.y=room.h-hero.h; // hero begint onderaan.
hero.graphic=document.getElementById("hero_graphic");
// pak het pagina element hero en bewaar.
// zelfde voor de bal.
bal.x=0;
bal.speed_x=2; // bal start met x-snelheid 2
bal.y=0;
bal.speed_y=2;// bal start met y-snelheid 2
bal.w=20;
bal.h=20;
bal.graphic=document.getElementById("bal_graphic");
// zet mouse catch aan.
$("body").mousemove(catchMouse);
// zet animatie aan: gameloop iedere 25 milliseconden.
setInterval(gameloop,25);
}
// function om de muispositie te bewaren
function catchMouse(event)
{
mouse.x=event.pageX;
mouse.y=event.pageY;
}
// functie om alle beweging van de balk te doen.
function moveHero()
{
// alles met de hero (balk)
// maak hero.x gelijk aan mouse.x;
hero.x=mouse.x;
// zet positie van balk in pagina op hero.x, hero.y
hero.graphic.style.left=hero.x+"px";
hero.graphic.style.top=hero.y+"px";
}
// functie om alle beweging van de bal te doen.
function moveBal()
{
// alles met de bal.
// zet positie van bal in pagina op bal.x, bal.y
bal.graphic.style.left=bal.x+"px";
bal.graphic.style.top=bal.y+"px";
// verplaats de bal met speed_x, speed_y;
bal.x=bal.x+bal.speed_x;
bal.y=bal.y+bal.speed_y;
// zwaartekracht (speedy wordt groter);
bal.speed_y=bal.speed_y+0.1;
// wrijving.
bal.speed_y=bal.speed_y * 0.99;
// stuiteren tegen muren
// linkermuur
if(bal.x<0)
{
// maak de bal snelheid (x) abs...