You'll probably need two rays, one attached to the gun and used for shooting (ray1
), the second attached to the camera and facing directly away from it (ray2
). The second is used to find out the closest point to shoot at. Next, rotate it randomly by your func. Finally, call look_at()
in ray1
. (if you need extra visual realism, call in the gun). Example:
var aim_point = ray2.get_collision_point()
ray1.look_at(random_spread(aim_point, spread))
random_spread(aim_point, spread)
will look like this:
func random_spread(aim_point, spread):
var axis = Vector3(
randf(),
randf(),
randf()
).normalized()
spread = (randf()+randf()-1.0)*spread
return (aim_point-ray1.global_translation).rotated(axis, spread)
Important notes:
1)ray1
should have negative Z local axis as its front, that's the look_at()
axis.
2)randomize()
should be moved out into the _ready()
func, or you'll end up with the same spread at all times.
3)No need to assign big length to the ray, get_colli*
all return the first object without checking for length. (Unless you need that, of course)
4)Both of these can be intersect rays and not nodes.