Thursday, June 13, 2013

A moving point within a bounded square

Q: If you are given a bounded square with cartesian co-ordinates of a 100 * 100 and a point within the square that moves in straight lines and rebounds of the edges, write a function that gives the new position of the point in each update.
A: Here's the code for the update method where previous and current are two points on the  board.

Point Update ( Point previous, Point current )
{
   var next = new Point();

   if (previous.X < current.X)
   {
       next.X = current.X + (current.X - previous.X);
       if  (next.X > 99) next.X = previous.X;
    }

   if (previous.Y < current.Y)
  {
     next.Y = current.Y + (current.Y - previous.Y);
     if (next.Y > 99) next.Y = previous.Y;
   }

  if (previous.X > current.X)
  {
     next.X = current.X - (previous.X - current.X);
     if (next.X < 0) next.X = previous.X;
   }

  if (previous.Y > current.Y)
  {
     next.Y = current.Y - (previous.Y - current.Y);
     if (next.Y < 0) next.Y = previous.Y;
   }

  if (previous == current)
  {
    var random = new Random();
    next.X = random.Next(99);
    next.Y = random.Next(99);
  }

  return next;
}
 

No comments:

Post a Comment