Need to constantly create new rays for CFrame of ray to update?

I am making a gun that will use raycasting to detect any parts hit. However, to use raycasting, you need to input the position where the ray starts (nothing wrong with this) and the direction (the main problem) where the ray will be pointed. Since the ray will be casted on a gun, I need to keep updating the direction of the ray with a loop. What I realised however, correct me if I am wrong, is that you have to include the code ray.new() into the loop itself, meaning that useless rays are created every loop whereas I only need 1 ray. Unless I am misunderstanding something, this is highly inefficient for the server. So how do games with guns solve this?

Thanks.

2 Likes

Why would you need to keep on changing the direction of the ray? If you want to raycast to see what is hit, simply fire a raycast whenever the gun is shot.

Rays are immutable, so you need a new direction and origin. Whenever you move around, the origin is bound to change. When you point in a different direction, you well, cast in a new direction!

1 Like

I want the gun be automatic, meaning that by holding down the mouse, a loop plays and the gun continues shooting out bullets until the bullets run out. I don’t want the player to repeated click the mouse just to fire each bullet.

Then yes, you would need to create a new ray each iteration because as @sjr04 said, rays are immutable so you cannot change them. I am not sure but I think that Roblox deletes the rays after you use them (as long as nothing is referring to them anywhere else in your code). So you don’t need to worry about lagging if you are creating a new ray each iteration of the loop.

@sjr04 @Quackers337 I see, thanks for your help! I’ve just read on a forum post regarding which types of rays get destroyed. According to @Muoshoob,

Ray.new(...) -- A ray is created but then immediately garbage collected, since you can't access it anyways
local ray = Ray.new(...) -- This ray is not garbage collected yet because the variable has been declared
print(ray)
-- Now, if there's nothing else that'll be using this variable, the ray is garbage collected.

Does this mean that I should not make the rays a local variable to ensure that it gets deleted?

1 Like

No, you should make it a local variable if you are only using the ray in the loop. That way it gets garbage collected at the end of the loop.


while true do
    local ray = Ray.new(...) -- creates ray in this scope
    -- code using ray
end -- ray gets cleaned up because it is the end of the scope

(Obviously dont do it in a while true loop, I just used that to make an example)

3 Likes

You should always be using local variables anyways. But yes

1 Like

@Quackers337 Thanks for your help, this clears things up very much.

@sjr04 Thanks for your help as well, I can understand rays much better now.