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

Mouse Position over a block and key is pressed not working?

Asked by 9 years ago

The propose of this code was to run a block of code if a players mouse is over a specific part, in this case Part1, and if there are pressing the specified key, z, in this case. Im not sure how to do this, so all help is much appreciated. here is my attempt, i though if the two positions match it would work, but i guess i was painfully wrong, here's what i got:

if Mouse.position == workspace.Part1.Position then
function keyDown(key)
    if key == "z" then 
--preform action
    end
end 
end

THANKS FOR READING

1 answer

Log in to vote
0
Answered by
Discern 1007 Moderation Voter
9 years ago

This script must be in a LocalScript inside the player for this to work. Placing this script in StarterGui would allow this to work.

Mouse = game.Players.LocalPlayer:GetMouse() --You need to set a variable for the actual Mouse. You cannot just say "Mouse". This sets the player's mouse as the variable "Mouse".

function keyDown(key)
    if Mouse.Target == workspace.Part1 then --Place this if statement inside of the function so it will run whenever the player presses z. If you place it outside, it will check it right when you join the game instead of when you press z. Also, Mouse.Target is a better property than Mouse.Position because it refers to the entire block on the screen, not the exact center.
    if string.lower(key) == "z" then --string.lower in case they're in caps lock or something.
--preform action
    end --Ends the if statement.
end  --Ends the other if statement.
end --Ends the function.

Mouse.KeyDown:connect(keyDown) --Connects the function to the mouse using the event KeyDown so when you press "z", the script actually does something.

If I helped you, please accept my answer!

0
Thank You viralmoose 65 — 9y
Ad

Answer this question