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
var bal={};
var room={};
var hero={};
var mouse={};
startgame();
function startgame()
{
mouse.x=0;
mouse.y=0;
room.w=300;
room.h=250;
hero.w=50;
hero.h=20;
hero.x=room.w/2;
hero.y=room.h-hero.h;
hero.graphic=document.getElementById("hero_graphic");
bal.x=0;
bal.speed_x=2;
bal.y=0;
bal.speed_y=2;
bal.w=20;
bal.h=20;
bal.graphic=document.getElementById("bal_graphic");
$("body").mousemove(catchMouse);
setInterval(gameloop,25);
}
function catchMouse(event)
{
mouse.x=event.pageX;
mouse.y=event.pageY;
}
function gameloop()
{
// alles met de hero (balk)
hero.graphic.style.left=hero.x+"px";
hero.graphic.style.top=hero.y+"px";
hero.x=mouse.x;
// alles met de bal.
bal.graphic.style.left=bal.x+"px";
bal.graphic.style.top=bal.y+"px";
bal.x=bal.x+bal.speed_x;
bal.y=bal.y+bal.speed_y;
bal.speed_y=bal.speed_y+0.1;
bal.speed_y=bal.speed_y * 0.99;
if(bal.x<0)
{
bal.speed_x=Math.abs(bal.speed_x);
}
if(bal.x>(room.w-bal.w))
{
bal.speed_x=-Math.abs(bal.speed_x);
}
if(bal.y>(room.h-bal.h))
{
bal.speed_y=-bal.speed_y;
}
}