Answered by
6 years ago Edited 6 years ago
Let's look at what you're asking here.
You say you want the target to be hit when:
The mouse is over it
X is pressed
Let's check for these two conditions. It's easier to start the check from a key press using ContextActionService
.
1 | local ContextActionService = game:GetService( "ContextActionService" ) |
3 | local function pressedXHandler() |
7 | ContextActionService:BindAction( "nameOfAction" , pressedXHandler, false , Enum.KeyCode.X) |
Now we have bound the X key to pressedXHandler
. Now, we should check inside the handler if the mouse is hovering over the target. We can use the :GetMouse()
method, like you already have, to get the mouse of the player.
I'm assuming the 'target' you are looking for is other players - so I will make the target look for a character object. If that's not the case, feel free to adjust the script and change the target.
01 | local ContextActionService = game:GetService( "ContextActionService" ) |
04 | local player = game.Players.LocalPlayer |
05 | local mouse = player:GetMouse() |
07 | local function pressedXHandler() |
08 | local hitCharacter = mouse.Target.Parent |
09 | local hitHumanoid = hitCharacter:FindFirstChildWhichIsA( "Humanoid" ) |
13 | hitHumanoid:TakeDamage( 25 ) |
17 | ContextActionService:BindAction( "nameOfAction" , pressedXHandler, false , Enum.KeyCode.X) |
This script should be sufficient. I hope it helps :)
EDIT: Adding Cooldowns (Debounce)
Add a variable in your script that only allows the pressedXHandler
function to run when the variable is set to true
or false
(usually depending on the name of the variable)
Here's what I mean:
01 | local ContextActionService = game:GetService( "ContextActionService" ) |
03 | local player = game.Players.LocalPlayer |
04 | local mouse = player:GetMouse() |
09 | local function pressedXHandler() |
10 | if debounce then return end |
12 | local hitCharacter = mouse.Target.Parent |
13 | local hitHumanoid = hitCharacter:FindFirstChildWhichIsA( "Humanoid" ) |
17 | hitHumanoid:TakeDamage( 25 ) |
23 | ContextActionService:BindAction( "nameOfAction" , pressedXHandler, false , Enum.KeyCode.X) |