I'm new to scripting, so I decided to create various tools to help me learn bit by bit. At the moment, I am trying to create a hopperbin that shoots a missile when then e key is pressed. The part I'm having a problem with is creating the rocket itself.
I made it so that there is a part inside the hopperbin and that the code will then clone that part, but it doesn't seem to be working. No errors are appearing either, so I can't tell where the problem is. Any help would be welcomed.
local Tool = script.Parent local Bullet = Tool.FindFirstChild("Part") local Rocket = Bullet:Clone() function onKeyDown(key) key:lower() if key == "e" then Instance.new("Rocket") Rocket.Parent = game.Workspace Rocket.Position = script.Parent.Parent.Parent.Character.Torso.Position end end function onSelected(mouse) mouse.KeyDown:connect(onKeyDown) end script.Parent.Selected:connect(onSelected)
You're cloning the part on line 3
, this is outside of the KeyDown
event.. therefore making it so the part only clones once, rather than everytime you press the key.
Also, on line 8
, you're trying to make an Instance type of 'Rocket'. This instance type does not exist! You have to clone a premade rocket.. which you did on the beginning!
Move the cloning inside the KeyDown event. This way, the part will clone whenever you press said key(:
By making this code a localscript, you can access the player by indexing LocalPlayer from Players like game.Players.LocalPlayer
. Also, you cannot get the mouse of the client without a localscript
KeyDown
Event, use the InputBegan
Event of UserInputServiceThe InputBegan Event can detect any user input.. meaning virtually any key on the keyboard.
local Tool = script.Parent local Bullet = Tool:FindFirstChild("Part") --Player local plr = game.Players.LocalPlayer --UserInputService local uis = game:GetService('UserInputService') --Input Function function Input(i) --Check key if i.KeyCode == Enum.KeyCode.E then --Clone Rocket local Rocket = Bullet:Clone() --Parent clone Rocket.Parent = workspace --Position clone Rocket.Position = plr.Character.Torso.Position end end function onSelected() --Connect function uis.InputBegan:connect(Input) end script.Parent.Selected:connect(onSelected)
If you want to make the code look cleaner.. use Anonymous functions!
local Tool = script.Parent local Bullet = Tool.FindFirstChild("Part") local plr = game.Players.LocalPlayer local uis = game:GetService('UserInputService') script.Parent.Selected:connect(function() uis.InputBegan:connect(function(i) if i.KeyCode == Enum.KeyCode.E then local Rocket = Bullet:Clone() Rocket.Parent = workspace Rocket.Position = plr.Character.Torso.Position end end) end)