I am trying to build a gun for my game, but it does not seem to work. (Just to be clear its on purpose that I want the gun to aim based off where my character is looking and not the mouse)
It only shoots north though.
This is the code, do you see any issues with it?
And yes I checked the spelling and everything no problems there.
Gun Script:
script.Parent.GunRemote.OnServerEvent:Connect(function(plr, lookingat)
local gun = plr.Backpack:FindFirstChild("Musket1777") or plr.Character:FindFirstChild("Musket1777")
local cfr = gun.MusketNuzzle.CFrame
local bullet = game.ServerStorage.Bullet:Clone()
bullet.Parent = game.Workspace
bullet.CFrame = cfr
local flight = Instance.new("BodyForce", bullet)
flight.Force = Vector3.new(0, bullet:GetMass()*196.2, -1)
task.wait()
bullet.Touched:Connect(function()
task.wait(3)
bullet:Destroy()
end)
end)
Gun LocalScript:
script.Parent.Activated:Connect(function()
local pos = script.Parent.Parent.Humanoid.TargetPoint
local lookingat = (pos - script.Parent.Parent.Head.Position).Unit
script.Parent.GunRemote:FireServer(lookingat)
end)
I’d imagine because vector 3 doesn’t factor in orientation, so when you apply force you’re using - 1 on the z axis but to the vector that’s just north. I’m on my phone so i can’t test but you could try converting your cframe to a vector 3 world space, and then use the unit function to get your force to apply, then remove the y value on the vector received to not mess with your gravity.
if you want the bullet to go where the gun/character is facing then either use head/humanoidrootpart lookVector, or for a better result, an invisible muzzle part on the gun and use that parts lookvector
code example:
local startPosition = muzzle.Position
local startCFrame = muzzle.CFrame
local direction = muzzle.CFrame.LookVector
Youll see this this function under this, it has a “Raycast” function, in my personal game I fire a raycast and a physical bullet so that we can get accurate checking and cool bullets
bullet.CFrame = CFrame.new(startPosition, startPosition + direction) * CFrame.new(0, 0, -0.7)
RayCast() -- Initial checking
local createBulletTrajectory = coroutine.wrap(function()
while bullet do
bullet.CFrame = bullet.CFrame * CFrame.new(0, 0, -bulletVelocity) * CFrame.Angles(-bulletDropAngle, 0, 0)
RayCast() -- Hit detection
task.wait() -- *if you want tracers, visible bullets, and debug mode :)*
end
end)
and an example of the function would be
local function RayCast()
ray = Ray.new(bullet.CFrame.p, bullet.CFrame.LookVector * bulletVelocity)
object, position = game.Workspace:FindPartOnRayWithIgnoreList(ray, {tool.Parent}, false, true)
if object and bullet then
-- do stuff like, if humanoid, etc
end
end
edit: yes you should be using raycasting for detection, it runs smoother and is more accurate