Using Raycast to prevent high-speed projectiles from shooting through objects

So I’m workin’ on an Machine Gun/Auto-Cannon Template for my big WWII project. So far everything seems to be moving along nicely, though I want to make it more realistic by not having the projectile that it fires to penetrate anything amid its high speed of travel.

As far as Raycasting, I only know how to create a Ray, and it seems there’s more to it for what I’m trying to accomplish. I’ve seen many answers around, and most of them were to resort to trying out FastCast, and that doesn’t really help my case.

Here’s how it looks. The projectiles are tiny and has tracers.

I haven’t yet implemented anything regarding Raycast into the script that handles the firing event yet, I’ve been trying to figure out where to start. How should I go about it without relying on FastCast?

3 Likes

To prevent the projectile from relying on a .Touched event on collision, which creates delay, you can use Ray’s to figure out the endpoint before you shoot her projectile. Then use either TweenService, or Lerp()ing to move the bullet to that position. This is only one of the many routes to making something like this, but it is the one I would try first. Lerping if you are more math savy, and TweenService if you are looking for a easily customizable, quick option.

Resources:

https://developer.roblox.com/en-us/articles/Raycasting
https://developer.roblox.com/en-us/api-reference/datatype/Ray
https://developer.roblox.com/en-us/api-reference/class/TweenService
https://developer.roblox.com/en-us/recipes/Use-Lerp-to-an-Object-between-Two-Object

Awesome machine gun turret by the way!

3 Likes

Normally what you’d do is assume that the bullet is moving much faster than anything it’s likely to hit, and you’d do a raycast every frame from the bullet’s position on the previous frame, to where it should be on the current frame, which is previous position + velocity * time since last frame. The time since the last frame is the dt parameter of the Heartbeat, Renderstepped, or Stepped event where this calculation is being done. Then, if you get a hit position, you either stop your projectile there and do the damage, or if it’s meant to ricochet, you move it to where it should be if it bounced off the hit object instead of passing through it (the usual vector reflection across the surface normal).

7 Likes