Get color of pixel for JavaFX window

486 Views Asked by At

Note: I'm using TornadoFX and kotlin, but it is based of JavaFX with some kotlin additions, which is why I'm mentioning JavaFX instead, since it seems more related to JavaFX than TornadoFX.

I'm trying to get the color of a specific location on the JavaFX window (the scene). The reason is because for my 2D game, I'm trying to build a map. For example, if I touch black, then stop moving in that direction (so the border). Or if it's red, then lose a life (obstacle). Rather than hardcoding that (I've got no idea how I'd be able to do that, since I don't want the map to just be a square), I'm trying to get the pixels and get the color. Note that since this is part of the hit detection system, it'll be ran 100+ a second, so I'll need a solution that doesn't take too much time.

Also, note that I'm not trying to get a pixel from an image, but the window that the user sees. (Just clarifying so that someone doesn't misunderstand) EDIT: I just realized that I could maybe use the image and get the color from that... although if I zoom in the image to make the map larger.. that part confuses me of how I could do it then.

1

There are 1 best solutions below

5
AmrDeveloper On

You can use Robot API to do this, to get the colour of the current mouse position you can do this

int xValue = MouseInfo.getPointerInfo().getLocation().x;
int yValue = MouseInfo.getPointerInfo().getLocation().y;
Robot robot = new Robot();
Color color = robot.getPixelColor(xValue, yValue);

To get the current position when the cursor is moved you need to use the setOnMouseMoved listener

yourViewNode.setOnMouseMoved(event -> {
    int xValue = MouseInfo.getPointerInfo().getLocation().x;
    int yValue = MouseInfo.getPointerInfo().getLocation().y;
    Robot robot = new Robot();
    Color color = robot.getPixelColor(xValue, yValue);
});

Then you can compare the color and check with it, if you want the color when the user clicks only you need to listen for the right or left click then use the same code in the listener to get the color at this moment

I have used this solution in my bot creator project to provide tools that can take action depend on the current position color