JSFiddle - React, Tailwind, and code Playground
HTML
<div id="room">
</div>
<div id="bal_graphic">
</div>
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;
}
JavaScript
var bal={};
var room={};
startgame();
function startgame()
{
room.w=300;
room.h=250;
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)
{
bal.x=event.pageX;
bal.y=event.pageY;
}
function gameloop()
{
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;
}
}