Powerbot test

by Emre Erkan

HTML

<div id="room">
  <img src="https://www.log.com.tr/powerbot.png" id="powerbot" />
</div>

CSS

body {
  background: #000000;
}

#room {
  background: url("https://www.log.com.tr/zemin.jpg") repeat center center;
  position: absolute;
  width: 90vw;
  height: 90vh;
  border: 1px solid #ffffff;
  top: 5vh;
  left: 5vw;
}

#powerbot {
  width: 100px;
  height: 100px;
  opacity: 0;
  transform-origin: center;
}

JavaScript

var PB = {};
jQuery(function($) {
  PB = {
    "room": $('#room'),
    "device": $('#powerbot'),
    "position": {
      "x": 0,
      "y": 0
    },
    "rotation": 0,
    "speed": 1,
    "target_rotation": false,
    "_interval": 0,
    "init": function() {
      PB.rotation = PB.rnd(0, 359);
      PB.position.x = PB.rnd(42, PB.room.width() - 142);
      PB.position.y = PB.rnd(42, PB.room.height() - 142);
      PB.set_css();
      PB.device.animate( { "opacity": 1 }, 400 );
			PB._interval = requestAnimationFrame(PB.forward);
    },
    "turn": function() {
      if ( PB.target_rotation === false ) {
        PB.stop();
        PB.target_rotation = PB.rotation + PB.rnd( 10, 50 );
        PB._interval = requestAnimationFrame(PB.turn);
      } else {
				if ( ++PB.rotation < PB.target_rotation ) {
        	PB.set_css();
          PB._interval = requestAnimationFrame(PB.turn);
        } else {
	        PB.stop();
          PB.target_rotation = false;
          if ( PB.detect_collision(PB.position.x, PB.position.y) ) {
            PB.turn();
          } else {
          	PB._interval = requestAnimationFrame(PB.forward);
          }
        }
      }
    },
    "forward": function() {
      var rad = (90 + PB.rotation) * Math.PI / 180,
      		new_x = PB.position.x - ( Math.cos(rad) * PB.speed ),
      		new_y = PB.position.y - ( Math.sin(rad) * PB.speed );
      if ( PB.detect_collision(new_x, new_y) ) {
      	PB.turn();
      } else {
        PB.position.x = new_x;
        PB.position.y = new_y;
  			PB.set_css();
      	PB._interval = requestAnimationFrame(PB.forward);
      }
    },
    "detect_collision": function(x, y) {
      if ( x < 21 || (x > PB.room.width() - 121) || y < 21 || (y > PB.room.height() - 121) ) {
      	return true;
      }
			return false;
    },
    "stop": function() {
    	cancelAnimationFrame( PB._interval );
    },
    "set_css": function() {
      PB.device.css({"transform":"translate(" + PB.position.x + "px, " + PB.position.y + "px)...