0

# Help with detecting incoming projectiles in front of my character?

Asked by 21 days ago

Could someone please help me with my script? I am uncertain as to why it is killing me despite the absence of a moving part heading in my direction. Any help would be greatly appreciated.

-- Get the position of the player character
local charPosition = game.Players.LocalPlayer.Character.HumanoidRootPart.Position

-- Create a box that encompasses 20 blocks in front of the character
local boxSize = Vector3.new(20, 20, 20)
local boxCFrame = CFrame.new(charPosition + Vector3.new(10, 0, 0), charPosition)

-- Use GetPartBoundsInBox to find any parts that are in the box
local parts = game.Workspace:GetPartBoundsInBox(boxCFrame, boxSize)

-- Check each part to see if it is moving and if it will hit the character's torso
for _, part in pairs(parts) do
local partVelocity = part.Velocity
local partPosition = part.Position
local partToCharVector = charPosition - partPosition
local partToCharDistance = partToCharVector.magnitude

-- If the part is moving and it is closer than 20 blocks from the character,
-- then it might hit the character's torso; destroy my Head
if partVelocity.magnitude > 0 and partToCharDistance < 20 then
if partVelocity:Dot(partToCharVector) > 0 then
-- If the part is moving towards the character,destroy my characters head
end
end
end


0
Answered by 20 days ago
Edited 20 days ago

The script only runs once. To repeat it, you should use a loop, more specifically a while loop.

local Players = game:GetService("Players")
local player = Players.LocalPlayer

while true do
local character = player.Character
if not character or not character.Parent then
end
local charPosition = character:GetPivot().Position

local boxSize = Vector3.new(20, 20, 20)
local boxCFrame = CFrame.new(charPosition + Vector3.new(10, 0, 0), charPosition)

local parts = game.Workspace:GetPartBoundsInBox(boxCFrame, boxSize)
for _, part in pairs(parts) do
if part ~= nil and part:IsA("BasePart") then -- just to make sure :>
local partVelocity = part.AssemblyLinearVelocity
local partPosition = part.Position
local partToCharVector = charPosition - partPosition
local partToCharDistance = partToCharVector.Magnitude
local partToCharUnit = partToCharVector.Unit

if partVelocity.Magnitude > 0 and partToCharDistance < 20 then
if partVelocity:Dot(partToCharUnit) > 0 then