检查点是否位于多边形内部 Lua
2015-7-31 0:43:22
收藏:0
阅读:138
评论:4
如何检查一个点是否在多边形或其他有多个顶点但相互连接的形状(如星形)内?在谷歌搜索了两个小时后,这是我到目前为止想出的代码。它并不能按我希望的方式工作。有时它即使点不在多边形内也会返回 true。以下是代码。
function isPlayerinBounds (point, vertices)
local len = #vertices
local j = 0
for i=1, len do
if i == 1 then
j = len -1
end
local result = false
local ix, iy, jx, jy = vertices[i][1], vertices[i][2], vertices[j][1], vertices[j][2]
local tx, ty = point[1], point[2]
if(((iy< ty and jy>=ty) or (jy< ty and iy>=ty) and (ix<=tx or jx<=tx)) then
j = i
return true
end
end
return false
end
点赞
用户107090
你的代码有问题。它试图实现 射线法 来计算水平射线与多边形的交点数量,但是你的代码一旦找到一个交点就返回了。
你需要将 return true 替换为 result = not result,并在最后添加 return result。
请检查你的代码是否基于 确定一个点是否在复杂多边形内部,并尝试提高代码的可靠性。
2015-07-31 11:12:33
用户7007149
最终为您使其工作。这与您的代码相同,只不过使用具有 .x 和 .y 属性的顶点列表,而不是 [1] 和 [2]。
local function insidePolygon(polygon, point)
local oddNodes = false
local j = #polygon
for i = 1, #polygon do
if (polygon[i].y < point.y and polygon[j].y >= point.y or polygon[j].y < point.y and polygon[i].y >= point.y) then
if (polygon[i].x + ( point.y - polygon[i].y ) / (polygon[j].y - polygon[i].y) * (polygon[j].x - polygon[i].x) < point.x) then
oddNodes = not oddNodes;
end
end
j = i;
end
return oddNodes
end
2016-10-12 10:22:58
用户12968803
-- 由 Pedro Gimeno 编写,捐赠入公共领域
function isPointInPolygon(x, y, poly)
-- poly 是一个 Lua 列表,包含像 {x1, y1, x2, y2, ... xn, yn} 这样的对
local x1, y1, x2, y2
local len = #poly
x2, y2 = poly[len - 1], poly[len]
local wn = 0
for idx = 1, len, 2 do
x1, y1 = x2, y2
x2, y2 = poly[idx], poly[idx + 1]
if y1 > y then
if (y2 <= y) and (x1 - x) * (y2 - y) < (x2 - x) * (y1 - y) then
wn = wn + 1
end
else
if (y2 > y) and (x1 - x) * (y2 - y) > (x2 - x) * (y1 - y) then
wn = wn - 1
end
end
end
return wn % 2 ~= 0 -- 奇偶性规则
end
2022-07-06 20:57:28
评论区的留言会收到邮件通知哦~
推荐文章
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?
- addEventListener 返回 nil Lua
- Lua中获取用户配置主目录的跨平台方法
你可能希望采用标准方法,并强迫其他人替你完成。将物理引擎转换为类似[Hadron Collider](http://vrld.github.io/HardonCollider/)或[LÄ * E的物理模块](https://love2d.org/wiki/love.physics)的库(基于Box2D,所以比HC的基本方法复杂得多)。我对它们都不是专家,但我相当确定可以在不使用它的情况下使用HC,尽管它被设计为在LÄ上运行
如果你想自己解决问题,可以在[此SO问题](https://stackoverflow.com/questions/5247994/simple-2d-polygon-triangulation)上找到一些有用的链接,基于[多边形三角剖分](https://en.wikipedia.org/wiki/Polygon_triangulation),包括C和JS复杂多边形碰撞器实现的源代码。