Ad
Still have questions? Join our Discord server and get real time help.
Log in to vote
2

Can someone explain ray casting to me?

Asked by
XDvvvDX 186
5 months ago

Hey. Before you answer I want to understand the subject itself, not how to make a ray cast gun. It would be much appreciated. Thanks!

2 answers

Log in to vote
3
Answered by 5 months ago

In Geometry, a ray is just a straight line that has an origin, but not an end.. there's also a segment, which has an origin and an end.. mathematically, you wouldn't say that Roblox has concepts of rays, because a ray in Roblox has an origin and an end, which makes it a segment (or line segment) in Geometry. but either ways, the 2 concepts are straight lines and that's what's most important here..

now ray casting is the process of creating rays(or at this point a segment).. and given you prompt in the question body, looks like you know how to do that..

Ad
Log in to vote
0
Answered by
SteamG0D 1488 Moderation Voter
5 months ago
Edited 5 months ago

In Roblox, a ray is not a physical object, it isn't something to be rendered. It happens all behind the scenes instantaneously, and because of this, they take up almost no computational power, so if you set a max distance to something reasonable like under 1000, you can send of a lot of rays in a very short amount of time without a serious hit to performance.

Now to explain how to use it in a script, I won't show you the laser gun tutorial, I'll just go over the basics using snippets of code:

Ray.new ( Vector3 Origin, Vector3 Direction )

So the origin is a point in space, like the position of a part. The direction is a vector3 direction, it is not a position in space that is like the 2nd Vector3 in CFrame: CFrame.new ( Vector3 pos, Vector3 lookAt )

It is an angle in a 3D space that is determined from the lengths of the X, Y, and Z values that you have given it. For example, in a 2D plane, it can be visualized like this.

Now the direction also determines how far the ray will go. For instance, if you make a ray using Camera:ScreenPointToRay, you can take that ray and set the distance by multiplying a number by the direction. Example:

local ray1 = Camera:ScreenPointToRay(x, y, 0)
local ray = Ray.new(ray1.Origin,ray1.Direction * 1000)

This sends a ray 1000 studs towards where the the mouse is looking by giving it the x and y values of the mouse.

Now, you can use rays for a number of things such as calculating bullet drop by sending dozens of short rays recursively over the path of trajectory, or using it to get an object in the path of a ray by using Workspace:FindPartOnRay.

If this answers your question, then mark it as the accepted answer, but if it doesn't then feel free to ask me anymore questions that you may have.

Answer this question