Reputation: 32071
This is really a silly question, but I've been staring at this problem for way too long and I just cant figure out what the problem is:
/**
* public boolean overlap(int targetX, int targetY) {
* Returns true if the target position is sufficient close to this ghost
* If target position is 16 pixels or less in the x direction
* and similarly in y direction, return true. Otherwise return false
*
* @param targetX
* @param targetY
* @return
*/
public boolean overlap(int targetX, int targetY){
double x=this.getX();
double y=this.getY();
double deltaX=targetX-x;
double deltaY=targetY-y;
if(deltaX<=16 && deltaX>=0 && deltaY<=16 && deltaY>=0)
return true;
else
return false;
}
This should work right? But it doesnt. If I run this test, it fails the assertTrue. (g1.x=100 and g1.y=1000)
double theta = 2 * Math.PI * Math.random();
int x = 100 + (int) (16 * Math.cos(theta));
int y = 1000 + (int) (16 * Math.sin(theta));
assertTrue(g1.overlap(x, y));
Does anyone see something I dont?
Upvotes: 1
Views: 298
Reputation: 1
If you want the distance regardless of direction shouldn't you have:
deltaX = Math.abs(targetX-x);
deltaY = Math.abs(targetY-y);
If your target is within 16px but to the left or above you would get a negative delta value and the method would return false.
Upvotes: 0
Reputation: 3219
Looks like deltaX and deltaY will be negative about half the time, and so your test will fail about 3/4 of the time.
Upvotes: 2
Reputation: 4365
Based on the javadoc of the overlap
method, you need to take the absolute value of targetX-x
and targetY-y
, and return true if both of those are less than or equal to 16.
So it would look like:
public boolean overlap(int targetX, int targetY){
double x=this.getX();
double y=this.getY();
double deltaX = Math.abs(targetX-x);
double deltaY = Math.abs(targetY-y);
return (deltaX<=16 && deltaY<=16);
}
Upvotes: 3
Reputation: 30828
You're returning true
if deltaX
and deltaY
are each between 0 and 16. But sin()
and cos()
aren't guaranteed to return positive numbers.
Upvotes: 2