Bouncing/reflecting projectiles using Raycasting

Hello! I am making a Touhou style bullet hell game where you avoid projectiles thrown at you by Rigs of some friends as a little project. I am currently working on trying to make projectiles reflect off of walls; this is all going well so far but on some walls of the arena the reflection doesn’t work. This is the formula I’m using:

(Projectile.CFrame.lookVector - (2 * Projectile.CFrame.lookVector:Dot(raycastresult.Normal) * raycastresult.Normal))

The raycast is casted correctly (I know because I’ve visualized the raycast) but this only bounces the projectile properly if being reflected off of one of four walls, like this:

Here is the full code I use for collision: (This code is ran whenever the projectile hits a wall)

local begin = Projectile.Position - Projectile.CFrame.lookVector * 25 -- To start the raycast a few studs before the projectile, to make sure the raycast isn't in the wall
local final = Projectile.CFrame.lookVector*50 -- 50 studs of distance
local raycastresult = workspace:Raycast(begin, final, params)
local r = visualizeRaycast(begin, final)
if not raycastresult then print(":("); r.Color = Color3.new(1, 0, 0); return end -- If the raycast didn't hit anything, paint the visualized raycast part red to show that it failed (can be ignored)
local newnorm = (Projectile.CFrame.lookVector - (2 * Projectile.CFrame.lookVector:Dot(raycastresult.Normal) * raycastresult.Normal)) -- Calculate the reflected normal
local reflect = newnorm
Projectile.Orientation = reflect
Projectile:SetAttribute("reflect", Projectile:GetAttribute("reflect") - 1) -- Decrement the amount of reflections left on the projectile by 1
table.insert(bypass, Projectile)
task.delay(0.2, function()
	table.remove(bypass, table.find(bypass, Projectile))
end)

Why would the behavior in the video be happening?

replace the original Projectile.CFrame.lookVector with the unit direction of the first ray then keep updating it. The best way to do this would be a function which you can iterate over by passing in a direction

Can you elaborate on what you mean by “unit direction of the first ray”? Sorry I’m kind of new to raycasting
Also, the reason I thought I didn’t need a function to iterate is because I have another script that handles the movement part of the projectile using the projectile’s lookVector, would this not work?

why are you putting a LookVector into Orientation?
Whouldn’t it be:

Projectile.CFrame = CFrame.lookAt(Projectile.Position, reflect)

Whoops. Makes sense. I’ll be closing this post now

A unit is just a normalized version of it so clamped between -1 and 1. And I can’t see the rest of your code so I don’t know how you have done it but for me iterating is easier as you can add in certain parameters and stop the bullet at certain points

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.