How do I go about using Raycasting to detect if my part hits another part or a part of a player/npc?

I want my bullet beam to detect if it hits a part or an NPC/Player.
Somehow my raycasting doesn’t work and idk why it doesn’t, I’m new to Raycasting so please don’t judge.

Basically, what I’m trying to do is I want the bullet to detect if it hits a part or a NPC or player, then when it does, it will blow up, release an explosion mesh, and then rocks will outline over the mesh outside of it.

Like this:
image

ModuleScript that has the Bullet Shooting, Raycasting, ETC.
local functions = {}

local lightray = script["Light Ray Kick"]

function functions.Start(plr, humrp, beamcount)
	
	local pos = humrp.CFrame
	
	for i, work in pairs(workspace.Effects:GetChildren()) do
		if work.Name == "Light Ray Kick" then
			work:Destroy()
		else
			print("Light Ray doesnt exist!")
		end
	end
	
	local lightclone = lightray:Clone()
	lightclone.Parent = workspace.Effects
	lightclone.CFrame = pos * CFrame.new(-1, 0, -3)
	
	local function firelaser()
		local origin = lightclone.Position
		local direction = lightclone.Orientation * Vector3.new(1, 1, 1)
		
		local raycastnew = RaycastParams.new()
		local raycastresult = workspace:Raycast(origin, direction, raycastnew)
		
		if raycastresult then
			local HitPart = raycastresult.Instance
			for i, folders in pairs(workspace:GetDescendants()) do
				if folders:IsA("Folder") then
					if folders:IsAncestorOf(HitPart) then
						if folders.Name == "Player Characters" then
							print("IsAPlayer")
						elseif folders.Name == "NPCs" then
							print("IsANPC")
						end
					end
				end
			end
		end
		
	end
	
	if beamcount == 1 then
				
		local BodyVel = Instance.new("BodyVelocity")
		BodyVel.Parent = lightclone
		BodyVel.Velocity = humrp.Parent["Left Leg"].CFrame.UpVector * -150
		BodyVel.MaxForce = Vector3.new(math.huge, math.huge, math.huge)
		BodyVel.P = 1000000000

		game.Debris:AddItem(lightclone, 2)

	end
	
end

return functions

How my module scripts work is that I use a localscript to do the tool stuff to activate the skill, then a remote-event to require the modulescript server-sidedly.

You will see in these scripts:

Remote Event
local rs = game:GetService("ReplicatedStorage")
local remote = rs.Modules.ModulesRemote
local modules = rs.Modules
local fruitmodules = modules.Fruits

remote.OnServerEvent:Connect(function(plr, ability, move, functions, option1, option2, option3, option4)
	if plr then
		for i, k in pairs(fruitmodules:GetChildren()) do
			if k.Name == tostring(ability) then
				local abilitymove = k[move]
				local required = require(abilitymove)
				
				required[functions](plr, option1, option2, option3, option4)
			end
		end 
	end
end)
Tool's Local Script (The tool I use to do the skill move.)
local rs = game:GetService("ReplicatedStorage")
local sss = game:GetService("ServerScriptService")
local modulefolder = rs:FindFirstChild("Modules")
local serverscript = sss:FindFirstChild("FruitEvent")
local remote = modulefolder:FindFirstChild("ModulesRemote")
local equip = script:WaitForChild("Equip")
local Player = game.Players.LocalPlayer
local chr = Player.Character or Player.CharacterAdded:Wait() 
local humrp = chr:WaitForChild("HumanoidRootPart")
local humanoid = chr:WaitForChild("Humanoid")
local UIS = game:GetService("UserInputService")
local tweenservice = game:GetService("TweenService")

local anims = script:FindFirstChild("Animations")
local lightkickhold = humanoid:LoadAnimation(anims:FindFirstChild("PikaBeamHold"))
local lightkickrel = humanoid:LoadAnimation(anims:FindFirstChild("PikaBeamRelease"))

local Cooldown1 = false
local Holding1 = false
local Cooldown2 = false
local Holding2 = false

local lightleg = script:FindFirstChild("Light Leg")

local mouse = Player:GetMouse()

local facing = false

UIS.InputBegan:Connect(function(Input, Processed)
	if Processed then
		print("Processed")
		return
	end
	if equip.Value == true then
		print("Is equipped")
		if Input.KeyCode == Enum.KeyCode.Z then
			print("Activated")
			if Cooldown1 == false then
				if Holding1 == false then
					
					local clonelol = lightleg:Clone()
					
					print("All false")
					Cooldown1 = true
					Holding1 = true
					lightkickhold:Play()
					clonelol.Parent = chr["Left Leg"]
					clonelol.CFrame = chr["Left Leg"].CFrame * CFrame.new(0, -0.5, 0)
					local weld = Instance.new("WeldConstraint", clonelol)
					weld.Name = "LegWeld"
					weld.Part0 = clonelol
					weld.Part1 = humrp.Parent:FindFirstChild("Left Leg")
					
					tweenservice:Create(clonelol, TweenInfo.new(0.5, Enum.EasingStyle.Cubic, Enum.EasingDirection.InOut), {Transparency = 0.6}):Play()
					for i, particles in pairs(clonelol.Attachment:GetChildren()) do
						if particles:IsA("ParticleEmitter") then
							particles.Enabled = true
						end
					end
					
					facing = true
					
					humanoid.WalkSpeed = 0
					humrp.Anchored = true
					local ePressCheck = false
					local startTime = tick()
					
					repeat task.wait()
						local currTime = tick() - startTime
						local keysPressed = UIS:GetKeysPressed()
						for _, key in ipairs(keysPressed) do
							if key == Enum.KeyCode.Z then
								ePressCheck = true
							end
							if ePressCheck then
								ePressCheck = false
								continue
							elseif not ePressCheck then
								return
							end
						end
					until currTime >= 5
					
					lightkickhold:Stop()
					facing = false
					humrp.Anchored = false
					lightkickrel:Play()
					tweenservice:Create(clonelol, TweenInfo.new(0.5, Enum.EasingStyle.Cubic, Enum.EasingDirection.InOut), {Transparency = 1}):Play()
					for i, particles in pairs(clonelol.Attachment:GetChildren()) do
						if particles:IsA("ParticleEmitter") then
							particles.Enabled = false
						end
					end
					
					lightkickrel:GetMarkerReachedSignal("Ray Release"):Connect(function()
						print("Rayed!")
						local sound = script.Release
						sound:Play()
						remote:FireServer("Pika Pika", "Light Kick", "Start", humrp, 1)
						clonelol:Destroy()
						task.wait(3)
						Cooldown1 = false
					end)
					
					humanoid.WalkSpeed = 18
					Holding1 = false
					print("Move done")
				end
			end
		end
	end
end)

UIS.InputEnded:Connect(function(Input, Processed)
	if Processed then
		print("Processed")
		return
	end
	if equip.Value == true then
		print("Is equipped")
		if Input.KeyCode == Enum.KeyCode.Z then
			print("Activated")
			if Cooldown1 == true then
				if Holding1 == true then
					print("All true")
					humrp.Anchored = false
					lightkickhold:Stop()
					facing = false
					lightkickrel:Play()
					local clonelol = chr["Left Leg"]["Light Leg"]
					tweenservice:Create(clonelol, TweenInfo.new(0.5, Enum.EasingStyle.Cubic, Enum.EasingDirection.InOut), {Transparency = 1}):Play()
					for i, particles in pairs(clonelol.Attachment:GetChildren()) do
						if particles:IsA("ParticleEmitter") then
							particles.Enabled = false
						end
					end
					lightkickrel:GetMarkerReachedSignal("Ray Release"):Connect(function()
						print("Rayed!")
						local sound = script.Release
						sound:Play()
						remote:FireServer("Pika Pika", "Light Kick", "Start", humrp, 1)
						clonelol:Destroy()
						task.wait(3)
						Cooldown1 = false
					end)
					humanoid.WalkSpeed = 18
					Holding1 = false
					print("Move done")
				end
			end
		end
	end
end)

while wait() do
	if facing == true  then
		humrp.CFrame = CFrame.lookAt(humrp.Position,Vector3.new(game.Players.LocalPlayer:GetMouse().Hit.Position.X,humrp.Position.Y,game.Players.LocalPlayer:GetMouse().Hit.Position.Z))
	end
end
3 Likes

i didnt understand that much but to detect if hit a player, npc or a part is kinda simple

local origin = hrp.Position -- this is the person casting the move humanoidrootpart
local direction = CFrame.lookAt(hrp.Position, mouseaim).lookVector * 1000
local rayParams = RaycastParams.new()
local rayresult = workspace:Raycast(origin, direction, rayParams)

if rayresult then
 if rayresult.Instance.Parent:FindFirstChild("Humanoid") then -- its either a plr or npc
   local char = rayresult.Instance.Parent
   local plr = game.Players:GetPlayerFromCharacter(char)
   if plr then
     -- its a player yay
   else
     -- npc yay
   end
 else
   -- its simply a part
 end
end
2 Likes

btw to get the mouse you gotta pass it to the server (idk if your skill is going to the mouse or not, so sorry)

You’re probably just calculating the direction wrong.
I’m assuming you’re trying to cast a ray using an object’s orientation as a direction. Try using CFrame to get the front direction of the object, and then multiply it by your desired length.
Should in practice look something like this:

local direction = lightclone.CFrame.lookVector * 100

Change the “100” number to modify the distance.
Try that and tell us if you need any more help!
(p.s in the future you might want to blacklist effects and invisible parts when raycasting, or your raycast might accidentally hit a visual effect and be used up)