Package org.samcrow.environment

Source Code of org.samcrow.environment.RectangleObstacle

package org.samcrow.environment;

import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.geom.Line2D;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;

import org.lekan.graphics.SGObject;
import org.lekan.graphics.SGRect;

/**
* @author scamper
*
*/
public class RectangleObstacle extends Obstacle {

  private Rectangle rectangle;

  /**
   * Construct a new RectangleObstacle with coordinates for the upper left point and its dimensions
   * @param inX The X-coordinate of the upper left corner
   * @param inY The Y-coordinate of the upper left corner
   * @param width The width
   * @param height The height
   */
  public RectangleObstacle(int inX, int inY, int width, int height){
    super(inX, inY);
    rectangle = new Rectangle(inX, inY, width, height);
  }

  /* (non-Javadoc)
   * @see org.samcrow.environment.Obstacle#collides(int, int)
   */
  @Override
  public boolean collides(double inX, double inY) {
    return rectangle.contains(new Point2D.Double(inX, inY));
  }

  /* (non-Javadoc)
   * @see org.samcrow.environment.Obstacle#drawObject()
   */
  @Override
  public SGObject drawObject() {
    return new SGRect(x, y, (int)rectangle.getWidth(), (int)rectangle.getHeight());
  }

  /**
   * Get the Rectangle that defines this Obstacle
   * @return the Rectangle
   */
  public Rectangle getRectangle(){
    return rectangle;
  }

  /* (non-Javadoc)
   * @see org.samcrow.environment.Obstacle#collides(java.awt.Shape)
   */
  @Override
  public boolean collides(Shape shape) {
   
    PathIterator iterator = shape.getPathIterator(null);
    Point2D.Double lastPoint = null;
    while(!iterator.isDone()){
      double[] coords = new double[8];
      int type = iterator.currentSegment(coords);
      if(type == PathIterator.SEG_MOVETO){
        lastPoint = new Point2D.Double(coords[0], coords[1]);
      }else if(type == PathIterator.SEG_LINETO){
        Point2D.Double thisPoint = new Point2D.Double(coords[0], coords[1]);
        Line2D.Double line = new Line2D.Double(lastPoint, thisPoint);
        if(rectangle.intersectsLine(line)){
          return true;
        }
        lastPoint = thisPoint;
      }

      iterator.next();
    }
    return false;
  }

}
TOP

Related Classes of org.samcrow.environment.RectangleObstacle

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.