How do you implement Key Press event for this?

Hello. I have recently developed a script where the player can teleport objects by right clicking. It works fine, but I need to give the player a way to look around by right clicking without teleporting objects when they don’t need to. Here is the script without my attempt at keypress:

    function clickObj()
	if mouse.Target ~= nil and mouse.Target.name ~= "Baseplate" then
		mtarget = mouse.Target
		print(mtarget)
		mouse.TargetFilter = mtarget
		down = true
	end
end

mouse.Button1Down:connect(clickObj)

--When you click

function mouseup()
	down = true
	if mouse.Target ~= nil and mouse.Target.name ~= "Baseplate" then
		mtarget = mouse.Target
	end
end

mouse.Button1Up:connect(mouseup)

--After clicking and releasing the mouse, this keeps the object selected

function rightclick()
	if down and mtarget then
		local clickspot = mouse.Hit.p
		mtarget.Position = clickspot
	end
end

mouse.Button2Down:connect(rightclick)

--After right clicking, the part teleports to the right click.

The script teleports and all, but I need a way for the player to “deselect” a part if they don’t want to teleport something at the moment. I tried to make the mouse.Target nil and make some variables false, but it didn’t work. I can’t really figure out a way to deselect. What would be a good way for the player to hit the “F” key to stop teleporting until they select a part again?

You could use the UserInputService or ContextActionService to disable teleportation when the player presses F.

https://developer.roblox.com/en-us/api-reference/class/UserInputService

https://developer.roblox.com/en-us/api-reference/class/ContextActionService

How about assigning your rightclick connection to a variable, and then disconnecting and reconnecting it when the player presses F/selects a part.

For example:

–OnSelect:

Connection = mouse.Button2Down:connect(rightclick)

–OnUnSelect:
Connection: Disconnect()

Hope this helps!

I’ll try that in the morning, as I saw this literally before I went to go to bed. I’ll edit this to be my response tomorrow. Thanks!

1 Like