PathEngine home previous: Translating the agentnext: Tutorial 3
Contents, Programmers Guide, Example Projects, Tutorials, Tutorial 2, SlideAgainst()

SlideAgainst()

SlideAgainst() is defined in 'code/sampleShared/Sliding.cpp' and is just a bit of quick and dirty vector maths.

The function is defined as follows:

void SlideAgainst(const int32_t* collidingline, int32_t currentx, int32_t currenty, int32_t& dx, int32_t& dy)
{
	float dotproduct = dx * (collidingline[2] - collidingline[0]) + dy * (collidingline[3] - collidingline[1]);
	float ratio = dotproduct;
	int32_t axisx = collidingline[2] - collidingline[0];
	int32_t axisy = collidingline[3] - collidingline[1];
	float axis_lengthsquared = axisx * axisx + axisy * axisy;
	ratio /= axis_lengthsquared;
	dx = axisx * ratio;
	dy = axisy * ratio;
	int32_t targetx, targety;
	targetx = currentx + dx;
	targety = currenty + dy;
	if(SideOfLine(collidingline, targetx, targety) == SIDE_RIGHT)
	{
		PushToLeftOfLine(collidingline, targetx, targety);
		dx = targetx - currentx;
		dy = targety - currenty;
	}
}

This basically takes the component of the movement vector along the line of the obstruction.
It is slightly complicated by the possibility that approximation may result in a point behind the line we are sliding against.
This is detected by the SideOfLine() test, and fixed by calling PushToLeftOfLine().

PushToLeftOfLine() is defined as follows, and basically just adds or subtracts one to or from one of the coordinates depending on the angle of the line.

inline void PushToLeftOfLine(const int32_t *line, int32_t &x, int32_t &y)
{
	int32_t axisx = line[2] - line[0];
	int32_t axisy = line[3] - line[1];
	int32_t absolute_x, absolute_y;

	absolute_x = axisx;
	if(absolute_x < 0)
	{
		absolute_x = -axisx;
	}
	absolute_y = axisy;
	if(absolute_y < 0)
	{
		absolute_y = -axisy;
	}
	
	// force rounding in axis with smaller component
	if(absolute_y > absolute_x)
	{
		if(axisy > 0)
		{
			x--;
		}
		else
		{
			x++;
		}
	}
	else
	{
		if(axisx < 0)
		{
			y--;
		}
		else
		{
			y++;
		}
	}
}

Documentation for PathEngine release 6.00 - Copyright © 2002-2016 PathEnginenext: Tutorial 3