Ok so, I have been trying to make raycast guns recently, but every time I make them, the bullets are weirdly positioned. I tried so many videos to learn to make a raycast gun, but they all have the same bullet position.
here is what I want it to be like [This example is from the FE gun kit made by Thienbao2109]
And this is what it looks like when I make the gun
How do developers archive this? I would really appreciate it if someone explains how to do this or give some information on how I could do this.
You didn’t provide any code, so I’ll have to keep it general.
When defining the unit direction of a ray to go towards you can do this by subtracting two vectors from one another or by using the .LookVector of a CFrame (which returns a 3d vector) then multiply this vector by the distance (number value) you’d like to cast a ray for which is either a constant or the exact distance between A to B.
Example:
function CastRay(Origin, Point)
---- Two different direction methods
-- Vector - Vector .unit
local Direction = (Point - Origin).unit
-- Camera CFrame's LookVector
local Direction = Camera.CFrame.LookVector
---- Two different distance methods
-- exact distance between A to B
local Distance = (Point - Origin).magnitude
-- constant
local Distance = 100 -- studs
-- defining the ray
local ray = Ray.new(Origin, Direction * Distance)
-- casting and returning the ray results
local IgnoreList = {Character} -- Add whatever you'd like
return rayHitPart, rayHitPosition, rayHitNormal, rayHitMaterial = workspace:FindPartOnRayWithIgnoreList(ray, IgnoreList)
end
local RayCast = Ray.new(FromP,(ToP-FromP).unit*100)
local Part,Position,Normal = game.Workspace:FindPartOnRay(RayCast,Player.Character, false,true)
local Dist = (ToP-FromP).magnitude
if not Dist then Dist = 300 end
local Lazer = Instance.new("Part")
Lazer.Parent = game.Workspace
Lazer.BrickColor = BrickColor.new("Electric blue")
Lazer.Anchored = true
Lazer.CanCollide = false
Lazer.Size = Vector3.new(0.1,0.1,Dist)
Lazer.CFrame = CFrame.new(FromP,Position)*CFrame.new(0,0,-Dist/2)
game.Debris:AddItem(Lazer,0.2)
if Part and Part.Parent:FindFirstChild("Humanoid") then
Part.Parent.Humanoid:TakeDamage(30)
end
end)```
game.ReplicatedStorage.RayCastEvent.OnServerEvent:Connect(function(Player, FromP, ToP)
local RayCast = Ray.new(FromP,(ToP-FromP).unit*100)
local Part,Position,Normal = game.Workspace:FindPartOnRay(RayCast,Player.Character, false,true)
local Dist = (ToP-FromP).magnitude
if not Dist then Dist = 300 end
local Lazer = Instance.new("Part")
Lazer.Parent = game.Workspace
Lazer.BrickColor = BrickColor.new("Electric blue")
Lazer.Anchored = true
Lazer.CanCollide = false
Lazer.Size = Vector3.new(0.1,0.1,Dist)
Lazer.CFrame = CFrame.new(FromP,Position)*CFrame.new(0,0,-Dist/2)
game.Debris:AddItem(Lazer,0.2)
if Part and Part.Parent:FindFirstChild("Humanoid") then
Part.Parent.Humanoid:TakeDamage(30)
end
end)