Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 10th, 2012  |  syntax: JavaScript  |  size: 1.71 KB  |  hits: 22  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. <!doctype html>
  2. <title>Agent Game</title>
  3. <style>
  4.  
  5.   #circle {
  6.   background: hsl(0,90%,50%);
  7.   border: 1px solid hsl(0,100%,20%);
  8.   position: absolute;
  9.   width: 100px;
  10.   height: 100px;
  11.   background: red;
  12.   --webkit-border-radius: 50px;
  13.   border-radius: 50px;
  14.   }
  15.  
  16. </style>
  17.  
  18. <html id="main"></html>
  19. <script>  
  20.   function Circle(){
  21.     this.position = { x: 100, y: 100};
  22.     this.target   = { x: 200, y: 200};
  23.     this.element = document.createElement('div');
  24.     this.element.setAttribute('id','circle');
  25.     this.element.setAttribute('style','left:'+this.position.x+'px;top:'+this.position.y+'px;');
  26.    
  27.     document.getElementById('main').appendChild(this.element);
  28.   };
  29.  
  30.   Circle.prototype = {    
  31.         updateTarget : function(event){
  32.     console.log(event);
  33.             this.target.x = event.pageX;
  34.             this.target.y = event.pageY;
  35.         },
  36.         updatePosition : function(){
  37.             var moveDirection = { x: (this.target.x - this.position.x), y:    (this.target.y - this.position.y)};    
  38.             var laengeMoveDirection = Math.sqrt((moveDirection.x * moveDirection.x) + (moveDirection.y * moveDirection.y));    
  39.             var normalised = { x: moveDirection.x / laengeMoveDirection, y: moveDirection.y / laengeMoveDirection};
  40.        
  41.             this.position.x += normalised.x;
  42.             this.position.y += normalised.y;
  43.             this.element.setAttribute('style','left:'+this.position.x+'px;top:'+this.position.y+'px;');
  44.         }  
  45.     };
  46.     var currentCircle = new Circle();
  47.   var timer = setInterval(function(){currentCircle.updatePosition();}, 10);
  48.  
  49.   document.addEventListener('mousemove', function(event){currentCircle.updateTarget(event);});
  50. </script>