gpt4 book ai didi

python - 无法让 blender 中的 ray_cast 工作

转载 作者:太空狗 更新时间:2023-10-30 03:04:02 34 4
gpt4 key购买 nike

我一直在尝试使用搅拌器进行“视线”类型的测试。为此,我想使用 ray_cast 函数(blender 游戏引擎中没有的光线转换函数)。无论我尝试什么,我都无法让代码正常工作。

(假设我有 2 个对象,a 和 b)

当我尝试从 a 到 b 进行 ray_cast 时,如果这是我自打开搅拌器以来第一次使用该功能,并且至少有一个开始或结束位置打开,我才能得到正确的答案起源。移动一个对象后完成的后续 ray_casts 即使在手动更新场景后也不会改变结果(如,我得到与第一次相同的结果)。如果我尝试在起点或终点不在原点的情况下进行转换,则返回 null (Vector<0,0,0>, Vector<0,0,0>, -1)

我注意到其他渲染函数也会发生类似的事情,例如 Object.closest_point_on_mesh 等...有人可以帮助我吗?下面是我用于光线转换的代码。

#

import bpy

def main():

a = bpy.data.objects['a']
b = bpy.data.objects['b']

x = a.ray_cast(a.location,b.location)
print(x[0])

main()

#

最佳答案

好吧,ray_cast 函数期望起始坐标和结束坐标都在 object.ray_cast 中对象的 LOCAL 坐标系中这意味着您的 a.location 和 b.location 坐标(全局/世界坐标)需要转换为本地坐标。

这样:

globalcoordinate = Vector((x, y, z))
localcoordinateforobject = (globalcoordinate - object.location) * object.matrix_world.inverted()

通常人们会像上面那样使用 matrix_world,但这不适用于在没有应用此旋转和缩放 (Ctrl-A) 的情况下旋转/缩放的对象。所以我分享了这段代码,我在我的很多插件中都使用了它:

def adapt(selobj):

# Rotating / panning / zooming 3D view is handled here.
# Creates a matrix.
if selobj.rotation_mode == "AXIS_ANGLE":
# object rotation_quaternionmode axisangle
ang, x, y, z = selobj.rotation_axis_angle
matrix = Matrix.Rotation(-ang, 4, Vector((x, y, z)))
elif selobj.rotation_mode == "QUATERNION":
# object rotation_quaternionmode euler
w, x, y, z = selobj.rotation_quaternion
x = -x
y = -y
z = -z
quat = Quaternion([w, x, y, z])
matrix = quat.to_matrix()
matrix.resize_4x4()
else:
# object rotation_quaternionmode euler
ax, ay, az = selobj.rotation_euler
mat_rotX = Matrix.Rotation(-ax, 4, 'X')
mat_rotY = Matrix.Rotation(-ay, 4, 'Y')
mat_rotZ = Matrix.Rotation(-az, 4, 'Z')
if selobj.rotation_mode == "XYZ":
matrix = mat_rotX * mat_rotY * mat_rotZ
elif selobj.rotation_mode == "XZY":
matrix = mat_rotX * mat_rotZ * mat_rotY
elif selobj.rotation_mode == "YXZ":
matrix = mat_rotY * mat_rotX * mat_rotZ
elif selobj.rotation_mode == "YZX":
matrix = mat_rotY * mat_rotZ * mat_rotX
elif selobj.rotation_mode == "ZXY":
matrix = mat_rotZ * mat_rotX * mat_rotY
elif selobj.rotation_mode == "ZYX":
matrix = mat_rotZ * mat_rotY * mat_rotX
# handle object scaling
sx, sy, sz = selobj.scale
mat_scX = Matrix.Scale(sx, 4, Vector([1, 0, 0]))
mat_scY = Matrix.Scale(sy, 4, Vector([0, 1, 0]))
mat_scZ = Matrix.Scale(sz, 4, Vector([0, 0, 1]))
matrix = mat_scX * mat_scY * mat_scZ * matrix

return matrix

它返回对象“selobj”的称为“矩阵”的正确变换矩阵。使用它代替上面代码示例中的 object.matrix_world。

关于python - 无法让 blender 中的 ray_cast 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17181778/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com