Closest x and y ??

how to seperate the closest x and y and go to that direction
my code



	int targetX = x;
	int targetY = y;
	public int speed = 5;
	public int dirY, dirX;

	public void moveLogic() {
		getFood1();
		if (targetX != x || targetY != y) {
			int pathX = targetX - x;
			int pathY = targetY - y;

			double distance = Math.sqrt(pathX * pathX + pathY * pathY);
			double directionX = pathX / distance;
			double directionY = pathY / distance;

			double movementX = directionX * speed;
			double movementY = directionY * speed;
			dirX = (int) movementX;
			dirY = (int) movementY;
		}
		move();
	}

	public void move() {
		x += dirX;
		y -= dirY;
	}

	public void getFood1() {
		if (targetX == x && targetY == y) {
			int[] foodX = new int[game.food.size()];
			int[] foodY = new int[game.food.size()];

			for (int i = 0; i < game.food.size(); i++) {
				foodX[i] = game.food.get(i).x;
				foodY[i] = game.food.get(i).y;
			}
			for (int i = 0; i < foodX.length; i++) {
				for (int j = 0; j < foodY.length; j++) {
					if (game.food.get(i).x - x < 40) {
						targetX = game.food.get(i).x;
						if (game.food.get(i).y - y < 40) {
							targetY = game.food.get(i).y;
						}
					}
				}
			}
		}
	}


and it is not working please help

could you elaborate on what you need help with.

To determine the closest point, you only need to get the X and Y differences, then square each of them and add them together. The smallest value that results will be from the closest point. There is no need to calculate the actual distance by including the square root step.

Assuming points[] has the test points, and you’ve set up variables to hold the minimum distance and the closest known point, something along these lines should suffice (not tested yet):

for (Point p : points)
{
    int x = currentX - p.getX();
    int y = currentY - p.getY();
    if (minimumD > (x * x) + ( y * y))
    {
        minimumDistance = (x * x) + ( y * y);
        closestPoint = p;
    }
}

I’d set the above up as a function to return the closest point with parameters being an array of target points and a given X and Y. That would make it easy to test and verify.

I’ll let someone else fill in the trig for the movement calculation. I think it would be pretty straightforward once you have the target and can use it to determine the slope of the desired movement.