# Checking if a point is in a rectangle

• 04-29-2010, 09:55 AM
bayan
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;
}
}
• 04-29-2010, 10:35 AM
JosAH
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
• 04-29-2010, 10:51 AM
bayan
Tyvm :D I owe you