Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How can I make KeyDown play sound near the player who pressed the key?

While working on my place I thought that it would be nice if players could interact with each other further by having their characters play a sound on the press of a key. When I had set out to to make the script however I ran into a few road blocks. First off I could not figure out how to make the play sound script even work with the key down script. second off I also realized that the sound would play in the entire place and not just near the player who pressed he key. After messing around with some scripts and even looking in the free models I came here for help. Here is a basic version of the script that I had tried to make work:

OnKeyDown(e) do function
game.Workspace.Sound:Play()

1 comment

0

Good effort.

1 answer

✓ Accepted answer

There are a few steps to this problem;

First: there is a more efficient way to make a function than you appear to have tried. It also appears you may have misunderstood how functions work, or tried to use a different coding language.

game.Players.PlayerAdded:connect(function (Player)
	local Mouse = Player:GetMouse()
	Mouse.Button1Down:connect(function ()
		--Code here
	end)
end)

Above is how you successfully find the mouse, and then connect the click to the code.

On to problem 2: the position of the sound.

To make it play near the player, there are 2 options: place it inside a player part, or place it inside a part near the player, depending on your desired effect.

Solution 1:

game.Players.PlayerAdded:connect(function (Player)
	local Mouse = Player:GetMouse()
	Mouse.Button1Down:connect(function ()
		local Sound = Instance.new("Sound", game.Workspace:FindFirstChild(Player.Name):WaitForChild("Head"))
		Sound.SoundId = "xxxxxxxxxxxxx" -- enter sound ID here
		Sound:Play()
	end)
end)

Solution 2:

game.Players.PlayerAdded:connect(function (Player)
	local Mouse = Player:GetMouse()
	Mouse.Button1Down:connect(function ()
		local Part = Instance.new("Part", game.Workspace)
		Part.Anchored = true
		Part.CanCollide = false
		Part.Position = game.Workspace:FindFirstChild(Player.Name):WaitForChild("Head").Position + Vector3.new(x, y, z) -- Input offset values here
		local Sound = Instance.new("Sound", Part)
		Sound.SoundId = "xxxxxxxxxxxxx" -- enter sound ID here
		Sound:Play()
	end)
end)

3 comments

0

"or tried to use a different coding language" I lol'd.

0

Also, there's almost never a reason to use a PlayerAdded event in a Local Script, and GetMouse only works with a Local Script, on the client.

0

Oh yeah, sorry I wrote that pretty late at night. He accepted it though so I think he worked it out.

This discussion is preserved as it was. New answers, comments, and votes are closed.