Hello, so i recently made a gun script with mouse.Target then i fired an remote event for the damage part and my question is how will i make the remote event deal damage to that player i'm shooting at only, since my last attempt only damaged me.
How do i make a gun deal damage to the player i shot at and not me ?
1 answer
Firearms are commonly programmed with Raycasting. - Newer method (slightly advanced)
This is a procedure where two points are taken, and a line is drawn between them by using a special method of WorldRoot (workspace), called :FindPartOnRay().
The function above will return two Objects: The first Object the ray comes into contact with, and it's Vector3 position.
It will take two arguments: The Raycast Object, and an Instance to ignore; we can just pass your Character to resolve the scenario of you accidentally hitting yourself (the descendants of the Instance passed will also be discarded).
To get the point where the player has shot (final point), we can reference the positional component of the Mouse.Hit CFrame. Subsequently, we use the weapon's Handle as the Initial position (start point):
--###----------[[LocalScript within the Tool]]----------###--
local Players = game:GetService("Players")
local Player = Players.LocalPlayer
local Mouse = Player:GetMouse()
local Gun = script.Parent
local function FireGun()
local Character = Player.Character
if (Character) then
local RayOrigin = Gun.Handle.Position
local RayDirection = Mouse.Hit.Position
---------------
local Raycast = Ray.new(RayOrigin, RayDirection)
local Part, Position = workspace:FindPartOnRay(Raycast, Character)
---------------
if (Part) then
print(Part.Name)
--[[
It's parent will **likely** point to the Character hit,
you should filter for a Humanoid to ensure it is,
and simultaneously use the successfully returned
Object to call :TakeDamage() on.
]]
end
end
end
Gun.Activated:Connect(FireGun)
You should also worry about hit verification, I suggest a backward Raycast from the position of the part that the Ray intersected and the shooter's root; ensure that the line-of-fire is authentic and not obstructed, to help prevent faulty a Hit Vector (aimbot).
###Note:
The program above is to simply demonstrate the method suggested, it should be done within a regular Script and a regular Script only!! Use a RemoteEvent to connect the LocalScript listening for the weapon's use, and the ServerScript handling the firing.
RemoteEvent:FireServer(Mouse.Hit.P) will be what you send. There are a lot more things to be concerned about when scripting a firearm in ROBLOX, however, this is as far as I will guide you. Good luck!
- Feahren
If this answer helped, don't forget to hit the accept button! Upvote if you wish!
This discussion is preserved as it was. New answers, comments, and votes are closed.

2 comments
make mt code a local script
my