类型 函数 库 physics.* 返回值 描述每次碰撞的表数组 修订 版本 2024.3703 关键词 射线, 光线投射, 投射, 物理, 碰撞 另请参阅 physics.reflectRay()
此函数用于查找与直线碰撞的对象以及沿该直线的碰撞点。
返回的位置在内容空间中,而返回的法线在局部空间中。
如果起始位置在对象内部,则不会为该对象注册碰撞。
physics.rayCast( fromX, fromY, toX, toY, behavior )
数字。 射线的起始 **x** 位置。
数字。 射线的起始 **y** 位置。
数字。 射线的结束 **x** 位置。
数字。 射线的结束 **y** 位置。
字符串。 碰撞测试行为,按性能成本递增的顺序排列
"any"
— 返回一个结果,但不一定是最近的结果。"closest"
— 仅返回距起点最近的碰撞(如果有)。这是默认行为。"unsorted"
— 返回所有结果,顺序不限。"sorted"
— 返回所有结果,按从近到远排序。hits
将是一个包含以下属性的元素数组
object
— 与直线碰撞的 显示对象。position.x
— object
的 **x** 碰撞位置,在内容空间中。position.y
— object
的 **y** 碰撞位置,在内容空间中。normal.x
— 在局部空间中命中的表面法线的 **x** 分量。normal.y
— 在局部空间中命中的表面法线的 **y** 分量。fraction
— 沿射线发生碰撞的分数 (0
..1
)。0
是光线投射的起点,1
是终点。local hits = physics.rayCast( 0, 0, 200, 300, "closest" ) if ( hits ) then -- There's at least one hit print( "Hit count: " .. tostring( #hits ) ) -- Output the results for i,v in ipairs( hits ) do print( "Hit: ", i, v.object, " Position: ", v.position.x, v.position.y, " Surface normal: ", v.normal.x, v.normal.y ) end print( "The first object hit is: ", hits[1].object, " at position: ", hits[1].position.x, hits[1].position.y, " where the surface normal is: ", hits[1].normal.x, hits[1].normal.y, " and where the fraction along the ray is: ", hits[1].fraction ) else -- No hits on raycast end