JSFiddle - React, Tailwind, and code Playground
by kinduff
HTML
<div id="area">
<div id="ball"></div>
<div id="obstaculo"></div>
</div>
<a href="#" id="move">Move</a>
CSS
#area {
border: 1px solid;
width: 500px;
height: 300px;
margin: 0 auto;
position: relative;
}
#ball {
width: 50px;
height: 50px;
background-color: red;
position: absolute;
top: 180px;
left: 125px;
border-radius: 50%;
}
#obstaculo {
width: 50px;
height: 150px;
position: absolute;
background-color: blue;
top: 130px;
left: 350px;
}
JavaScript
var area = document.getElementById("area");
var ball = document.getElementById("ball");
var fps = 5; // lower is faster
var step = 1;
var ctop = ball.offsetTop;
var cleft = ball.offsetLeft;
var coltop = area.clientHeight - ball.clientHeight;
var colleft = area.clientWidth - ball.clientWidth;
var ntop = false;
var nleft = false;
function obstaculo(top, left) {
/* elems = document.getElementsByClassName("obstaculo");
for (var i = 0; i < elems.length; i++) {
elem = elems[i];
elemtop = elem.offsetTop - ball.clientHeight;
elembottom = elem.offsetTop + elem.clientHeight;
elemtopli = elem.offsetTop + ball.clientHeight;
elemleft = elem.offsetLeft - ball.clientWidth;
elemright = elemleft + elem.clientWidth;
elemleftli = elem.offsetLeft + ball.clientWidth;
if (!ntop) {
if (top == elemtop && (left >= elemleft && left <= elemleftli )) {
ntop = true;
console.log('ntop '+ ntop);
} }
if (ntop) {
if (top == elembottom && (left >= elemleft && left <= elemleftli ) ) {
ntop = false;
console.log('ntop '+ ntop);
}}
if (!nleft) {
if (left == elemleft && (top <= elemtop && top >= elemtopli)) {
nleft = true;
console.log('nleft'+ nleft);
} }
if (nleft) {
if (left == elemright && (top <= elemtop && top >= elemtopli ) ) {
nleft = false;
console.log('nleft'+ nleft);
}}
} */
obs = document.getElementById("obstaculo");
arriba = obs.offsetTop - obs.clientHeight;
arriba_izq = obs.offsetLeft;
arriba_der = arriba_izq + obs.clientWidth;
abajo = obs.offsetTop + obs.clientHeight;
izquierda = arriba_izq - obs.clientWidth;
if ( top == arriba && left >= arriba_izq && left <= arriba_der ) {
ntop = true;
}
if ( top == abajo && left >= arriba_izq && left <= arriba_der ) {
...