How to detect collision with raycasting inside a part

I want to detect whenever a player’s camera is inside a specific part. I do this by raycasting between the humanoidrootpart and the player’s camera.

The problem with this is that whenever the player and camera are both inside the same part, the raycast will only travel inside this part not detecting any collision.

the code I use:

local Players = game:GetService("Players")
local Player = Players.LocalPlayer or Players:GetPropertyChangedSignal("LocalPlayer"):wait()
local Character = Player.Character or Player.CharacterAdded:Wait()
local Camera = ws.CurrentCamera
local Ignore = {
    Character
}

local hmrootpart = Character:WaitForChild("HumanoidRootPart")

while true do

    local CameraRay = Ray.new(hmrootpart.Position, Camera.CFrame.Position - hmrootpart.Position)
    local HitPart, HitPosition = ws:FindPartOnRayWithIgnoreList(CameraRay, Ignore)

    print(HitPart, HitPosition) --HitPart will print nil when camera and humanoidrootpart are both inside part
end

Picture1: Raycast is detecting the collision and knows the camera is inside a part.

Picture2: Raycast is NOT detecting the collision and returns nil.

So my question is:
How can I detect the part in which the raycast is traveling shown in picture2?

1 Like

Try Workspace:FindPartOnRayWithWhitelist().

4 Likes

I’m really late but you could try making a little part that follows your camera. on every frame just check if the part is inside anything using Region3

You can use RotatedRegion3 module to do point-cube collision detection, or do AABB if the part is always axis-aligned