https://i.gyazo.com/cf40836e435b46a0afeba99c00ad7809.mp4
What’s the best way to check when a beam is touched and return the part that is touched?
At the moment I can only think of Ray Casting to do this.
Is there a simpler way to achieve this?
https://i.gyazo.com/cf40836e435b46a0afeba99c00ad7809.mp4
What’s the best way to check when a beam is touched and return the part that is touched?
At the moment I can only think of Ray Casting to do this.
Is there a simpler way to achieve this?
Since this is a laser that goes in a straight path, a ray cast would be good enough. Be wary that something might block the laser, so you may need multiple raycast.
If the laser is static (i.e. it doesn’t move, unlike in the gif), then you can just use a part that overlaps with the laser and then listen to the part’s .Touched
event.
If the laser moves, then you can still use a part, it’s just that you’ll have to CFrame/resize it whenever the laser moves.
^ and if it becomes a curved beam you would use bezier curves and cast between points
I would actually suggest not casting rays.
Someone else recently had an issue with a Gatling gun causing lag, so I suggested that they combine all of the bullets into a single beam, and collision test on that beam using a proxy part. The discussion is found here:
The reason why I suggested switching from raycasts to a proxy part has to do with the way that raycasts work. Each raycast is an autonomous operation, and retains no memory or optimizations between calls. Each time it is called it must search whatever spacial data structures Roblox uses to find which parts are near the beam. Then, it must run a collision test on the ray and the parts that are close. The physics collision system, however, is optimized for running collision tests only when they are needed. It stores information to help speed up the collision detection process. Some of that information may be, for example, which parts are near which parts, and their velocity. It can update its information as forces/scripts act on parts, and use that information every frame to determine if a collision test is needed.
So, to summarize, use an invisible proxy part, or parts if the beam is curved. This is much more scalable than raycasting because the physics collision system is optimized to perform collision tests on objects over time. If your beam wasn’t going to stay in the world for very long, then a single raycast will do.