I am trying to use python scripts on blender4.0 to do the following: detect whether the ray from the camera shooting point intersects with the obstacle, and find the global coordinates of the intersection point.
The key function ray_cast(), I can't find the official instructions, but it does work for now.
However, I encountered the following problems. When I changed the position of the obstacle (monkey head), I checked to see if the same ray was still blocked, only to find that the intersection position results were the same as the last time. Whether I use G to change the position or use a script to change the position, this problem occurs.
import bpy
import os
# Get the camera, target object, and obstacle object in the scene
camera = bpy.data.objects['Camera']
target_object = bpy.data.objects['Cube']
obstacle = bpy.data.objects['monkey']
# Define the ray origin and ray direction
ray_origin = camera.location
ray_direction = (target_object.location - camera.location).normalized()
output_directory = "F:/"
output_filename = "output.txt"
output_filepath = os.path.join(output_directory, output_filename)
for frame in range(5):
obstacle.location.z += 0.5
obstacle.update_from_editmode()
obstacle.update_from_editmode()
hit, location, normal, index = obstacle.ray_cast(ray_origin, ray_direction)
if hit:
output_file.write("Frame " + str(frame+1) + ": Ray intersects with the obstacle object at location: " + str(location) + "\n")
output_file.write(output_file.write("Frame " + str(frame+1) + ": Normal at the intersection point: " + str(normal) + "\n"))
else:
output_file.write("Frame " + str(frame+1) + ": Ray does not intersect with the obstacle object\n")
output_file.close()
I couldn't figure out what the problem was.
I also tried to keep the original relative position and press A to select all the objects and move them all together, which also resulted in an error (hit value changed to False).


