Hello.
I would like to get help on how to handle a raycast that originates from your player’s head and moves straight until it hits something or times out (no mouse.hit.p required). Can you help me? I need it for an FPS game.
Hello.
I would like to get help on how to handle a raycast that originates from your player’s head and moves straight until it hits something or times out (no mouse.hit.p required). Can you help me? I need it for an FPS game.
local origin = char.Head.Position
local target = origin + origin.LookVector * 5000 -- Decide the length to shoot
-- Might need to be -origin.ZVector
local direction = target - origin
This codes takes the position of the head, adds the coordinate of a stud 5000 studs in front of the head onto it’s current position and then calculates the direction required for Raycasting.
Let me know if you have any questions.
local Enumeration = Enum
local Game = game
local Workspace = workspace
local Players = Game:GetService("Players")
local Player = Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local function HeadRaycast(Distance) --'Distance' specifies the ray's distance.
local Head = Character:FindFirstChild("Head")
if not Head then return end
local Parameters = RaycastParams.new()
Parameters.FilterDescendantsInstances = {Character}
Parameters.FilterType = Enumeration.RaycastFilterType.Blacklist
local Result = Workspace:Raycast(Head.Position, Head.CFrame.LookVector * Distance, Parameters)
--Check if 'Result' is non-nil and repond accordingly.
end
The code will error with LookVector is not a valid member of Vector3 "origin"
, replace origin = char.Head.Position
with origin = char.Head.CFrame
Disgusting…
Personally, I’d do it like this;
local UserInputService = game:GetService("UserInputService")
local Camera = workspace.Camera
local RayInfo = RaycastParams.new()
RayInfo.FilterType = Enum.RaycastFilterType.Blacklist
RayInfo.FilterDescendantsInstances = {Character, ...}
local RayLength = 5000
local function GetMousePosition()
local MouseLocation = UserInputService:GetMouseLocation()
local UnitVector = Camera:ViewportPointToRay(MouseLocation.X, MouseLocation.Y)
local RayHit = workspace:Raycast(
UnitVector.Origin,
UnitRay.Direction * RayLength,
RayInfo
)
if RayHit then
--Damage hit
end
end
For first-person only games, it would be more efficient to use Head.Position
as the origin and Head.CFrame.LookVector * RayLength
as the direction.
Yes, thank you for correcting me. Was rather late when I wrote it and somehow forgot that origin was a Vector3
and not a CFrame
.