I need help telling when a raycast hits an object that isn't its final destination

(Don’t judge pls, I’m new to the concept of Raycast)

  1. What do you want to achieve?

I am beginning the process of making a single player game, and a step in it is to have NPCs shoot guns at the player with rays. Objects like parts in the workplace should be able to stop the ray from continuing to its final destination.

  1. What is the issue?

The ray is not stopping when the player’s character is behind a wall. This is the issue. How would I stop the ray from damaging the player when they are behind something? Is it possible for the ray to stop midway if it hits an object?

  1. What solutions have you tried so far?

I attempted to use RaycastParams to exclude parts in the workspace but that clearly didn’t work.

Script

task.wait(5)
local NPC = script.Parent.Parent
local Following = 1
local Players = game:FindFirstChild(“Players”)
local Player = Players:FindFirstChildOfClass(“Player”)
local Character = Player.Character
local Position = nil
local Distance = nil
local ChatService = game:GetService(“Chat”)
local PlayerX = nil
local PlayerZ = nil
local PlayerY = nil
local Gun = NPC.Patriot – Replace (Patriot is the name of the placeholder gun)
local Direction = nil
local RaycastParams = RaycastParams.new()

–RaycastParams.FilterDescendantsInstances = {workspace.Parts.Model1:GetDescendants(),workspace.Parts.Model2:GetDescendants()}
–(Didn’t work, these two models contained parts.)

while true do

task.wait()

local Player = Players:FindFirstChildOfClass("Player")
local Character = Player.Character
Distance = (NPC.HumanoidRootPart.Position - Character.HumanoidRootPart.Position).Magnitude

if Distance <= 60 then

local RayDestination = Character.HumanoidRootPart.Position
local RayOrigin = Gun.Handle.Position
local RayDirection = RayDestination - RayOrigin
RaycastParams.FilterType = Enum.RaycastFilterType.Exclude

local RayCastResult = game.Workspace:Raycast(RayOrigin, RayDirection)

if RayCastResult then
	
	Character.Humanoid:TakeDamage(3)
	
	wait(0.25)
	
	end
	
	end

end

That’s it. Again, sorry for the possibly really easy fix. Raycast has been a really new concept for me.

Check if the RaycastResult.Instance is anything but the player’s character

3 Likes

Just like what @astraIboy said.

What he basically mean is that you’re not using RaycastResult.Instance, which it returns the part that the ray has hit.

1 Like

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