Following Test

by blindman67

HTML

<!-- this code is a fork from another source and is not writen by BLINDMAN67 It is an example of how to solve a problem asked by the author on stackOverflow http://stackoverflow.com/q/39574663/3877726 --> 
 
 <title>Target Following Test</title>

  <body>
      <script src="https://code.jquery.com/jquery-2.1.0.js"></script>
<center>
  <canvas id="canvas" width="300" height="300"></canvas>
   </center>
      <script>

JavaScript

/*this code is a fork from another source and is not writen by BLINDMAN67 It is an example of how to solve a problem asked by the author on stackOverflow http://stackoverflow.com/q/39574663/3877726 */

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var width = canvas.width;
var height = canvas.height;


var circle = function (x, y, radius, fillCircle, color) {
  ctx.beginPath();
  ctx.fillStyle = color;
  ctx.arc(x, y, radius, 0, Math.PI * 2, false);
  if (fillCircle) {
ctx.fill();
  } else {
ctx.stroke();
  }
};

var drawRect = function (x, y, color) {
  ctx.fillStyle = color;
ctx.fillRect(x, y, 20, 20)
}

//Moving Obstacle
var Obstacle = function (x, y) {
  this.x = x;
  this.y = y;
  this.vSpeed = 0;
  this.hSpeed = 0;
}

Obstacle.prototype.drawOb = function (color) {
  drawRect(this.x, this.y, "Red")
}

Obstacle.prototype.follow = function () {
  //this.y += this.vSpeed
  //this.x += this.hSpeed
  var dist = Math.sqrt(Math.pow(ball.x-this.x,2) + Math.pow(ball.y-this.y,2));  // distance
  var dx = (ball.x-this.x)/dist;
  var dy = (ball.y-this.y)/dist;
  var speed = 1;
  dx *= speed;
  dy *= speed;
  this.x += dx;
  this.y += dy;
}

Obstacle.prototype.checkCollision = function (direction) {
  return (ball.x-ball.radius < this.x + 20)
  && (ball.x+ball.radius > this.x)
  && (ball.y-ball.radius < this.y + 20)
  && (ball.y+ball.radius > this.y)
  ;
}

// The Ball constructor
var Ball = function () {
  this.x = 20
  this.y = 20
  this.xSpeed = 0;
  this.ySpeed = 0;
  this.radius = 10;
};

// Draw the ball at its current position
Ball.prototype.draw = function () {
  circle(this.x, this.y, 10, true, "Black");
};

Ball.prototype.reposition = function (reX, reY) {
  this.x = reX;
  this.y = reY;
}

// Update the ball's position based on its speed
Ball.prototype.move = function () {
  this.x += this.xSpeed;
  this.y += this.ySpeed;

  if (this.x < 11) {
this.x = 11;
  } else if (this.x > width - 11) {
this.x = width - 11;
  } else if...