Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (function() {
- var ball = undefined;
- var data = {
- 'x': 50,
- 'y': 50,
- 'dirX': 90,
- 'dirY': 90
- };
- var currentDirection = [0, 3];
- const changeDirection = function() {
- currentDirection[0] = Math.floor(Math.random() * 2);
- currentDirection[1] = Math.floor(Math.random() * 2 + 2);
- }
- const createBall = function() {
- var elem = document.createElement('div');
- elem.id = 'gameBallMovable';
- elem.style.display = 'block';
- elem.style.position = 'absolute';
- elem.style.background = 'radial-gradient(circle at 100px 100px, #00ffff, #000)';
- elem.style.width = elem.style.height = '50px';
- elem.style.borderRadius = '50%';
- elem.style.top = elem.style.left = '0';
- elem.style.userSelect = 'none';
- document.body.appendChild(elem);
- ball = document.getElementById('gameBallMovable');
- };
- const touchingElement = function(obj) {
- const x = obj.x,
- y = obj.y,
- elems = document.getElementsByTagName('*'),
- ignore = ['div', 'span', 'body', 'head', 'html', 'style', 'script', 'link', 'meta', 'title', 'option', 'optgroup', 'link'];
- for (let i = 0; i < elems.length; i++) {
- info = elems[i].getBoundingClientRect();
- if (elems[i].tagName && ignore.join(',').indexOf(elems[i].tagName.toLocaleLowerCase()) == -1 && elems[i].id != 'gameBallMovable' && elems[i].style.visibility !='hidden' && elems[i].style.display != 'none' && elems[i].style.opacity != '0' && (info.width > 5 || info.height > 5) && x > info.x && x < info.x + info.width && y > info.y && y < info.y + info.height) {
- return [true, elems[i]];
- }
- }
- return [false, undefined];
- }
- const gameLoop = function() {
- ball.style.left = (data.x - 25) + 'px';
- ball.style.top = (data.y - 25) + 'px';
- ball.style.transform = `rotate(${data.angle}deg)`;
- if (data.x > window.innerWidth || data.y > window.innerHeight || data.x < 0 || data.y < 0) {
- changeDirection();
- }
- for (let i = 0; i < currentDirection.length; i++) {
- switch (currentDirection[i]) {
- case 0:
- data.x += 10;
- break;
- case 1:
- data.x -= 10
- break;
- case 2:
- data.y += 10;
- break;
- case 3:
- data.y -= 10;
- break;
- }
- }
- data.x < 25 && (data.x = 25, changeDirection());
- data.x > window.innerWidth - 25 && (data.x = window.innerWidth - 25, changeDirection());
- data.y < 25 && (data.y = 25, changeDirection());
- data.y > window.innerHeight - 25 && (data.y = window.innerHeight - 25, changeDirection());
- const touchingObj = touchingElement(data);
- if (touchingObj[0]) {
- touchingObj[1].style.opacity = '0';
- changeDirection();
- }
- window.requestAnimationFrame(gameLoop);
- }
- const initiate = function() {
- createBall();
- gameLoop();
- }
- initiate();
- })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement