Mathematic hidden collision

有些话、适合烂在心里 提交于 2019-12-11 16:22:56

问题


I'm working on a project that uses tile engine (self made), and my next task is to create an AI (besides other AIs that are done), this one is tricky because the AI should only spot the player if the player is in the AI's sight. Tried it with for cycles to after calculating the ranges (in tiles) [1 tile = 32*32].
Then I thought about creating an equation of a straight line. And here I am, puzzled in math.

Any idea how could I calculate if it's overlaps one of these "hidden" tiles?
NOTE that I want only use math!

TileInfo.tileData[la[floor(y / 32)][floor(x / 32)]];
//la -> array of tile positions, if it's >0 then there is a tile.

回答1:


Say that the viewer is at position (x1,y1) and the target at (x2,y2). Now, I am assuming that there is a set of n contiguous tiles along along x and m along y. The lower, left corner of the first of these tiles is at position (x0,y0). The size of tiles are d along x and t along y. Now the math:

The line connecting viewer and target is

y = y1 + (y2 - y1) * (x - x1) / (x2 - x1)

The tiles corners are at points p1 = (x0,y0); p2 = (x0 + n * d, y0); p3 = (x0 + n * d, y0 + m * t); p4 = (x0, y0 + m * t). Now the job is to find if that line crosses any of the 4 segments connecting two consecutive corners. Let's take the segment between p1 and p2 (a horizontal line) defined by y = y0. If you set this into the line equation you can find the possible interception x which I named xi:

y0 = (y2 - y1) * (xi - x1) / (x2 - x1) + y1

You can invert this equation and find the possibx:

xi = x1 + (y0 - y1) * (x2 - x1) / (y2 - y1)

Now if xi > x0 and xi < x0 + n * d you have an interception for this segment. Otherwise you have a free line of sight.

Do the same for the other three segments whose straight lines are defined by p2 -> p3: x = x0 + n * d; p3 -> p4: y = y0 + m * d; and p4 -> p1: x = x0.

Note that when the segment is horizontal (y = const) you have to put this y in the line of sight straight line, calculate x and compare this x with the intercept. If the segment is vertical (x = const) then you have to put x in the straight line equation, calculate y and check if it falls in the interval or not.

A final remark is that you have to take particular care of cases where x1 = x2 or y1 = y2. This are vertical and horizontal line of sights and may lead to division by zero in the above equations. The solution: deal with these cases separately.



来源:https://stackoverflow.com/questions/12123047/mathematic-hidden-collision

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!