I’m trying to add mouse aiming to a simple ball projectile that’s actually a grenade. I have a localscript set up that fires an event when the mouse is clicked with the tool equipped.
Here is a snippet of the firing script,
script.Parent["CLICK!!!"].Activate.OnServerEvent:Connect(function(user,parent, mousepos)
if user.Name == script.Parent.Parent.Name or user.Name == script.Parent.Name then
script.Parent.Barrel.LaunchFXAttachment.Launch:Play()
script.Parent.Barrel.LaunchFXAttachment.LaunchFX:Emit(50)
script.parent.FullBullet.Transparency = 1
script.parent.Casing.Transparency = 0
local grenade = game.ServerStorage.Grenade:Clone()
--local mousepos = mousevent:InvokeClient(player) we'll just keep this here for later
grenade.Parent = workspace
local rayc = Ray.new(script.Parent.Barrel.Position, mousepos)
grenade.CFrame = CFrame.new((script.Parent.Barrel.LaunchFXAttachment.CFrame * CFrame.new(1,0,0)).Position, Vector3.new(mousepos))
grenade.Rotation = rayc.Direction
print(grenade.Rotation)
grenade.Position = script.Parent.Barrel.LaunchFXAttachment.WorldPosition
grenade.Sender.Value = user.Name
grenade:ApplyImpulse(rayc.Direction/3) --+ Vector3.new(0,20,0))
--grenade:ApplyImpulse(mousepos + Vector3.new(0,20,0))
and here’s the localscript in the tool.
script.Parent.Activated:Connect(function()
if script.Parent.Cooldown.Value == false then
script.Parent.Cooldown.Value = true
local pos = game.Players.LocalPlayer:GetMouse().Hit.Position
script.Pointer.Position = pos
script.Activate:FireServer(script.parent, pos)
wait(1.1)
script.Parent.Cooldown.Value = false
end
end)
How can I make it better?
When I’ve tried to do mouse aiming before, it’s inaccurate after a few twirls.
If you have a known throwing speed you can calculate the arc required to hit your target exactly, assuming its possible to reach. There will always be two possible angles and you usually want to pick the lower one. This is a good way to do it if your gameplay requires grenades be very precise.
If your game is PVP it might be better to do something different as people will have more fun if they can learn the grenade throws and get better. In that case just use the mouse direction as the throwing direction, optionally letting the player charge up a stronger throw by holding the button.
What doesn’t seem to be working? The code sets the impulse, does that seem to work properly?
To add an impulse you probably want to multiply your rayc.Direction/3 by your object’s mass.
Basically apply impulse changes the assembly’s velocity by inputVector * (1/assembly mass), so get your desired velocity and multiply it by the mass to get that velocity.
Egomoose’s tutorial has stuff on creating a basketball that is thrown towards a click position with physics.
Not sure, when I spin around a few times while shooting, the gun starts becoming wildly inaccurate to the mouse position, however, if I don’t make it physics based, it works.