local loop
local Bullet = Instance.new("Part")
Bullet.Size = Vector3.new(0.1, 0.1, 5)
Bullet.Anchored = true
Bullet.CanCollide = false
Bullet.Color = Color3.fromRGB(219, 239, 0)
Bullet.Material = Enum.Material.Neon
Bullet.Parent = game.Workspace
Bullet.CFrame = CFrame.new(origin, endposition)
loop = game:GetService("RunService").RenderStepped:Connect(function(dt)
Bullet.CFrame *= CFrame.new(0, 0, -velocity * (dt * 60))
local hit = workspace:Raycast(Bullet.Position, Bullet.CFrame.LookVector * velocity * 1.5)
--if (Bullet.Position - origin).Magnitude > 5000 then
if hit then
print("HIT: "..hit.Instance.Name)
if damage ~= nil then
game.ReplicatedStorage.Events.Damage:FireServer(hit.Instance, 10)
else
loop:Disconnect()
Bullet:Destroy()
--end
end
end
end)
I don’t know if the bug is in this code tho, but seems like it.
the origin is:
local castParams = RaycastParams.new()
castParams.IgnoreWater = true
castParams.FilterType = Enum.RaycastFilterType.Exclude
castParams.FilterDescendantsInstances = {viewmodel, game.Players.LocalPlayer.Character}
local Mouse = module.GetMouse(1000, castParams)
and the getmouse function is:
function module.GetMouse(Distance, CastParams)
local MouseLocation = game:GetService("UserInputService"):GetMouseLocation()
local UnitRay = game:GetService("Workspace").Camera:ViewportPointToRay(MouseLocation.X, MouseLocation.Y)
local origin = UnitRay.Origin
local endp = UnitRay.Direction * Distance
local Hit = game:GetService("Workspace"):Raycast(origin, endp, CastParams)
if Hit then
return Hit.Position
else
return UnitRay.Origin + UnitRay.Direction * Distance
end
end
You are making your bullet face towards wherever the mouse hit. If your mouse happens to hit behind to the barrel of your gun then it’s just going to make your bullet face backwards.
I’d recommend just taking the direction of your camera (assuming you are in first person) and applying that on top.
Your bullet is just spawning too far forward, I think fastcast also has this same issue (as they handle projectiles practially the same as you are right now).
The easiest solution would probably just be to draw a raycast between where your bullet spawns and the barrel of your gun.
local FilterSelf = RaycastParams.new()
FilterSelf.FilterType = Enum.RaycastFilterType.Exclude
FilterSelf.FilterDescendantsInstances = {Character}
--do this *before* you spawn your bullet
--instead of barrel origin you can also (maybe?) use something a bit further back just in case you stick your barrel inside of a wall
--doing that would also probably stop any weird shooting through walls shenanigans
local PrefireCast = workspace:Raycast(BarrelOrigin, BulletOrigin-BarrelOrigin, FilterSelf)
if PrefireCast then
--we hit an object, dont spawn a bullet and immediately skip to the hit routine
end