Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Bullet sometimes doesnt go to the mouse's position?

Asked by 3 years ago

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)

1 answer

Log in to vote
0
Answered by 3 years ago

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!

1
it almost works but there is a problem, now the bullet wont go directly to the mouse's position GameBuilderLol 58 — 3y
0
It's probably because the bullet isn't traveling too fast so gravity has time to pull it down, try setting the number next to the .unit to a higher value, 10000 works quite well Vinceberget 1420 — 3y
1
if you’re going to make it instantaneously fast with a force of 10 000, you might as well use a body velocity or even raycasting instead (you can use the same script). although, I am not sure how fast 10 000 will actually go. Speedmask 661 — 3y
1
Thank you it worked! GameBuilderLol 58 — 3y
Ad

Answer this question