Hello,
I'm working on a point'n'click engine, and I've having some issues with the walkable area (that's the area in the screen where the character can walk to). I define the walkable area using a polygon class where I add the vertices of the polygon (in green). Every time the player clicks on the screen, I check if the destination position (pixel) belongs to the walkable area. If it belongs, I calculate the shortest path to the destination (using Dijkstra algorithm). If not, I calculate the intersection point between the polygon and line from the current char position and the destination position (in blue). The char wont go further the green line.
To check if two segments intersect, I'm using a very common algorithm you can find in Internet:
int LPolygon::getIntersection( int _mouseX, int _mouseY, int _srcX, int _srcY, int* _crossX, int* _crossY ) {
// Function to return IF and WHERE the trajectory from the char and the mouse position intersects with the WalkableArea
float s1_x, s1_y, s2_x, s2_y;
float s, t;
s2_x = _mouseX - _srcX;
s2_y = _mouseY - _srcY;
// Loop through all edges of the polygon
for( int i = 0; i < mNumVertex-1; i++ ) {
s1_x = mVertexArray[i+1].x - mVertexArray[i].x;
s1_y = mVertexArray[i+1].y - mVertexArray[i].y;
s = (-s1_y * (mVertexArray[i].x - _srcX) + s1_x * (mVertexArray[i].y - _srcY)) / (-s2_x * s1_y + s1_x * s2_y);
t = ( s2_x * (mVertexArray[i].y - _srcY) - s2_y * (mVertexArray[i].x - _srcX)) / (-s2_x * s1_y + s1_x * s2_y);
if (s >= 0 && s <= 1 && t >= 0 && t <= 1) {
*_crossX = (int)(mVertexArray[i].x + (t * s1_x));
*_crossY = (int)(mVertexArray[i].y + (t * s1_y));
return true;
}
}
return false;
}
The issue I have is, from this intersection point, next time you click outside the walkable area, sometimes the char escapes the walkable area, depending on the angle (or so I think).
Any ideas/recommendations on how to solve this issue?
Thank you!