Move an object towards another (Bresenhams Line)

Hi, i am trying to get a creature on a grid to move towards food that is scattered around the grid, i want the creature to move 1 position closer each cycle of the game loop however i cant figure out how to convert my code as I already have code that shows the best route to the food, but i cant use this to tell the creature to only move 1 space in the recommended direction

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
 void Creature::move(int x1, int y1, int x2, int y2)
{	
	//Bresenham's line algorithm
	bool steep = (abs(y2 - y1) > abs(x2 - x1));
	if (steep)
	{
		swap(x1, y1);
		swap(x2, y2);
	}
	if (x1 > x2)
	{
		swap(x1, x2);
		swap(y1, y2);
	}
	int dx = x2 - x1;
	int dy = abs(y2 - y1);
	float error = dx / 2.0f;
	int ystep = (y1 < y2) ? 1 : -1;
	int y = y1;
	int maxX = x2;
	int x = x2-1;
	
		if (steep)
		{
			xPos += x;
			yPos += y;
			
		}
		else
		{
			xPos += x;
			yPos += y;
			
		}
		error -= dy;
		if (error < 0)
		{
			y += ystep;
			error += dx;
		}
}
Last edited on
Can it only move North/South/West/East (Manhattan distance), or also in diagonals (Chebyshev distance)? You don't need Bresenham's algorithm for neither case.
Let's say that x0 = (a, b) and x1 = (c, d).

If using Manhattan distance, first move along the X axis c-a positions, then move along the Y axis d-b positions.

If using Chebyshev distance, pick a suitable vector out of (1, 1), (-1, 1), (-1, -1), (1, -1). Then add that vector to the current position until the current position and the target are on the same axis, then move along that axis until you reach the target.
Another way that I use in my chess engine is(in pseudocode)
1
2
3
4
5
6
7
int board[64]//however big the board is; put a "bonus" for the creature in the places with the food
GenMoves();
for(int m = 0; m < 64;/*however many places there are in your board*/m++)
{
    movestack[m].Score += board[m];
    //and so on
}

This will give a greater score to getting closer to the food. This is assuming you are using a decision search tree for the game(Alpha Beta, Minimax).
This code is used in my chess engine to checkmate the king in the endgame. I put the bonuses in the members of the array that correspond to the center of the board.

Does this help?
Last edited on
The creature can move also in diagonals, ah cool, i will take a look at chebyshev distance now to see if i can implement it.

thanks theturk1234, doesnt really help me though unfortunate, thanks anyway!
Topic archived. No new replies allowed.