Heyo! Does anyone know of a script that will make it so if you hit “b” a part you made will spawn 1 stud away from where you are standing? I already have the part I want to spawn I just can’t figure how to spawn it in by pressing “b”.
You need to use a Remote Event and CFrame.
When you press the key, send a signal and have the server script do it for everyone to see.
On the CFrame, you must use LookVector, here is a little help:
local LV = Char.HumanoidRootPart.CFrame.LookVector
Part.Position = Char.HumanoidRootPart.Position + LV * 2
Just define Char as the character of the player and Part as the part you want to change the position.
If the piece is too close, change the 2 for another number.
Thank you. I’m confused though, do you know what the whole script would be? I’m sorry!
Server script:
RemoteEvent =
RemoteEvent.OnServerEvent:Connect(function(Player)
local LV = Player.Character.HumanoidRootPart.CFrame.LookVector
local Part = Instance.new("Part",workspace)
Part.Position = Player.Character.HumanoidRootPart.Position + LV * 2
end)
Define RemoteEvent.
You make a script with UserInputService or ContextActionService and put inside RemoteEvent:FireServer() obviously it must be the same remote event
This wouldn’t work properly, since LookVector
is a unit vector of the direction and does not contain the position coordinates.
You have to add the original position to it in order to maintain it:
RemoteEvent.OnServerEvent:Connect(function(plr)
local p = Instance.new("Part")
p.Anchored = true
p.CFrame = plr.Character.HumanoidRootPart.CFrame + plr.Character.HumanoidRootPart.CFrame.LookVector * 2
p.Parent = workspace
end)
Or you can take advantage of the fact that CFrame multiplication takes rotation into account and do it like this:
RemoteEvent.OnServerEvent:Connect(function(plr)
local p = Instance.new("Part")
p.Anchored = true
p.CFrame = plr.Character.HumanoidRootPart.CFrame * CFrame.new(0,0,-2)
p.Parent = workspace
end)
Also for the OP, an example localscript would look like this:
game:GetService("UserInputService").InputBegan:Connect(function(iobj, gp)
if not gp and iobj.KeyCode == Enum.KeyCode.B then
game.ReplicatedStorage.RemoteEvent:FireServer()
end
end)
It uses UserInputService’s InputBegan event, which in a nutshell let’s you detect key presses
In that code snippet iobj
stands for “input object”, we check if its KeyCode is B
gp
stands for “game processed”, it’s true if the player was ex. typing something in chat, so we only fire the remote if it’s false
Oops, I forgot to add the starting position in my second post. Solved
Adding a CFrame is the same as I did, only @oatins asked to add something to the front of the player, if I wanted it to keep the orientation I would have said so.