Results 1 to 3 of 3
  1. #1
    bayan is offline Member
    Join Date
    Apr 2010
    Posts
    55
    Rep Power
    0

    Default Checking if a point is in a rectangle

    Im trying to make a brick game and im trying to make a method that checks whether a point is in a rectangle i.e. the sprite.

    How would you do this?

    Here is the class:
    import java.awt.*;
    import javax.swing.*;

    public class Racket
    {
    private int length,width,midX,midY;
    private Color color;

    public Racket(int l, int w, int x, int y, Color c)
    {
    length=l;
    width=w;
    midX=x;
    midY=y;
    color=c;
    }


    public int getX()
    {return midX;}



    public int getY()
    {return midY;}

    public int getLength()
    {return length;}

    public Color getColor()
    {return color;}

    public void setX(int x)
    {midX=x;}

    public void setY(int y)
    {midY=y;}

    public void setLength(int l)
    {length=l;}

    public void setColor(Color c)
    {color=c;}

    public void fill(Graphics g)
    {
    Color old=g.getColor();
    g.setColor(color);
    g.fillRect(midX,midY,length,width);
    g.setColor(old);
    }

    public void move(int x)
    {midX+=x;}

    boolean containsPoint(int x, int y)//the one i'm talking about, this is . { //useless and inefficient.:(
    int startPoint=midX-(length/2);
    int checkVertical=midY-(width/2);
    for(int i=0; i<length; i++)
    {
    for(int j=0; j<width; j++)
    {
    if(x==i+startPoint && y==j+checkVertical)
    return true;
    }
    }
    return false;
    }
    }
    Last edited by bayan; 04-29-2010 at 10:06 AM.

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,656
    Blog Entries
    7
    Rep Power
    21

    Default

    If a rectangle is given by the two opposite points (xlo, ylo) and (xhi, yhi) a point (x, y) is inside that rectangle iff xlo<= x <= xhi and ylo <= y <= yhi.

    kind regards,

    Jos
    Last edited by JosAH; 04-29-2010 at 01:38 PM.

  3. #3
    bayan is offline Member
    Join Date
    Apr 2010
    Posts
    55
    Rep Power
    0

Similar Threads

  1. Construct a rectangle
    By cstokes91 in forum New To Java
    Replies: 1
    Last Post: 01-27-2010, 06:14 AM
  2. non-rectangle JPanel
    By itaipee in forum AWT / Swing
    Replies: 4
    Last Post: 04-30-2009, 11:58 PM
  3. Rectangle Intersection
    By Gwindow in forum Java 2D
    Replies: 1
    Last Post: 04-24-2008, 03:53 PM
  4. help with rectangle class
    By darkgt in forum New To Java
    Replies: 7
    Last Post: 11-14-2007, 06:19 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •