Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java equal too, but with a buffer

Tags:

java

swing

I have made a simple game and I have a simple way to detect when I have collected a coin but it is very hard to match its position exactly.

public class Token {
    private String name;
    int x;
    int y;
    private BufferedImage image;
    public Token (String nameIn, int xIn, int yIn, BufferedImage imageIn)
    {   
        name = nameIn;
        x = xIn;
        y = yIn;
        image = imageIn;
    }

    public boolean collected(Hero frylark) {
        if (frylark.getX() == x && frylark.getY() == y) {
            return true;
        }
        else {
            return false;
        }
    }
}

Is there any way i can have a buffer of say 10 pixels instead of
matching the position of the coin exactly.

like image 736
edwin Avatar asked Dec 02 '25 13:12

edwin


2 Answers

A distance between two points in a two-dimensional field is the sum of the squares of the differences between their corresponding coordinates:

public boolean collected(Hero frylark) {
    return Math.sqrt(Math.pow(frylark.getX() - x , 2) + 
                     Math.pow(frylark.getY() - y , 2)
                    ) <= 10.0;
}
like image 68
Mureinik Avatar answered Dec 05 '25 03:12

Mureinik


Based on Mureinik's answer, you can do this faster by not use Math.pow nor Math.sqrt.

double dx = frylark.getX() - x;
double dy = frylark.getY() - y;
return dx*dx + dy*dy <= 10.0*10.0;
like image 40
Peter Lawrey Avatar answered Dec 05 '25 02:12

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!