How to rotate a RayCast node towards the center of the screen?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By wowzzers

I have a RayCast node attached to a gun. Is it possible to rotate it towards the center of the screen? I know that you can shoot a ray from the center of the screen with direct space state intersect ray but I’m interested in this exact setup. The green arrow on the image is what I’m trying to achieve.

I also have a random spread function like this:

func random_spread(spread):
	return Vector3(
		rand_range(-spread, spread), 
		rand_range(-spread, spread), 
		rand_range(-spread, spread)

Is it possible to incorporate it with this setup?

:bust_in_silhouette: Reply From: levon00

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(
    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.

Thank you for the answer!

wowzzers | 2019-09-26 11:06