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

Is it possible to incorporate it with this setup?

in Engine by (81 points)
edited by

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

by (56 points)
selected by

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 Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.