So sometimes the bullet doesnt go to the direction my mouse is clicking at
heres is the script and the video that showcases my error:
link: https://www.youtube.com/watch?v=6qeeu3uD46g
script:
local tool = script.Parent.Parent tool.Equipped:Connect(function(mouse) mouse.Button1Down:Connect(function() local bullet = game.ReplicatedStorage:WaitForChild("Part"):Clone() bullet.Parent = workspace bullet.CFrame = script.Parent.CFrame bullet.BodyForce.Force = mouse.Hit.p print(mouse.Hit.p) end) end)
I've made a script which fixes this issue.
local tool = script.Parent.Parent tool.Equipped:Connect(function(mouse) mouse.Button1Down:Connect(function() local bullet = game.ReplicatedStorage:WaitForChild("Part"):Clone() bullet.Parent = workspace bullet.CFrame = script.Parent.CFrame bullet.BodyForce.Force = (mouse.Hit.p - script.Parent.Position).unit * 1000 print(mouse.Hit.p) end) end)
The important part is the mouse.Hit.p - script.Parent.Position
, which offsets the force of the bodyforce so that the force is applied relative to the tool's position. Previously, if the mouse hit for example (10,0,0)
and the player was at (20,0,0)
you'd want to make the bullet go in the negative x direction, but instead the bullet would travel at (10,0,0)
, the opposite direction. By using mouse.Hit.p - script.Parent.Position
we fix this issue.
You might've also noticed that I added an additional piece of code to the force. unit
is a property of any vector3 which basically makes the vector's "distance" (more formally known as magnitude) a value of 1. By then multiplying this value with lets say 100, the bullet will travel at whatever you pointed at with a force that moves the bullet 100 studs every second. This makes the bullet's speed more consistent, as in your video you can see that the bullet travels way faster when you point it at the sky than when you point it at the ground.
Hope this script helps!