What do you want to achieve?
I’ve been wanting to make a turret/sentry that shoots enemies automatically.
What is the issue?
The Bullets.
For so long i have searched, i can’t seem to find a way to make bullets be accurate, they may bounce off without trigering the touched event, or i would need to make a hitbox for them, which consumes resources.
What solutions have you tried so far?
I tried doing the hitbox trick, it works but makes an unbearable amount of lag due to the large hitbox and small bullet.
the code is as simple as a
local p = rs.bullet:Clone
and making it go towards the target.
Yeah i’ve heard of raycast, what i want is to replicate the bullets and make then travel to the enemy. Unless raycast is the absolute ultimate way to do it, im willing to go further
even for traveling bullets you should still use raycasting. For an instand bullet you would raycast from point A to the target. However what you want to do is have the bullet travel. Depending on how realistic you want the bullet to move you might need one physics kinematics equation. Only if you want it to fall due to gravityl tho. If youre find with it moving in a straight line you can just use the direction vector. Either way you do it youd need to raycast each frame and move the bullet by a speed * change in time between frames. You would only raycast to the position of the bullet in the next frame. This is what the code would look like
local RunService = game:GetService("RunService")
local currPos = bullet.Position
local nextPos
local bulletStudsPerSec = 50
RunService.HeartBeat:Connect(function(dt)
nextPos = currPos * (bullet.CFrame.LookVector * bulletStudsPerSec * dt)
local success, hit = pcall( function()
return workspace:Raycast(currPos, nextPos - currPos, params)
end)
if hit then
*bullet hit something code goes here youre gonna have to figure this part out and destroy
and stop the code from running for the bullet.
end
end)
Yup, i managed to find something that works with what you gave me
connection = RunService.Heartbeat:Connect(function(dt)
local currPos = bullet.Position
local nextPos = bullet.CFrame.LookVector * dt * bulletStudsPerSec
local hit = workspace:Raycast(currPos, nextPos, params)
if hit then
bullet:Destroy()
connection:Disconnect()
if hit.Instance.Parent then
if hit.Instance.Parent:FindFirstChild("Humanoid") then
hit.Instance.Parent.Humanoid:TakeDamage(20)
end
end
else
bullet.Position = currPos + nextPos
end
end)