0 votes

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):
    randomize()
    return Vector3(
        rand_range(-spread, spread), 
        rand_range(-spread, spread), 
        rand_range(-spread, spread)
    )

Is it possible to incorporate it with this setup?

asked Sep 21, 2019 in Engine by wowzzers (68 points)
edited Sep 21, 2019 by wowzzers

1 Answer

+1 vote
Best answer

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.

answered Sep 22, 2019 by levon00 (56 points)
selected Oct 2, 2019 by wowzzers

Thank you for the answer!

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.