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

How do I make a block point in the direction my mouse points?

Asked by 3 years ago

I am making an artillery gun for my game, and so far it is working well, but I need it to be able to spin freely so the player can aim and hit his target. I only know the basics of Roblox Lua, but it was enough to make the weapon work. But I need it to turn, to point, in the direction according to the mouse pointer. Example, my mouse points in that direction, and the weapon turns, and it is pointed in that direction, so the player would use that to aim, and could shoot and hit his target. Since I don't know more than the basic Roblox Lua, I tried to look for something like this in the ToolBox, but all I found were the same scripts, which made your avatar's head spin according to the camera's position. The gun has a part in the middle of it, if someone can help with the script that does this for me, if I put it in this part, which is welded with the rest of the gun, will it still work? Please help this is practically the last step to build this model.

PS: this need to work, only if the player is seated at the seat.

1 answer

Log in to vote
0
Answered by 3 years ago
--First thing you have to do, is make sure you're using a Local Script.


1   -- Local Script
Now you have to make sure the Local Script is placed somewhere where it can run. I'll be using the StarterPack.

--view source

1   -- Local Script In StarterPack
You could also you StarterGui, and other places as well. It really doesn't matter as long as the local script isn't in Workspace or ServerScriptService.
Now get the player and the mouse,



1   -- Local Script In StarterPack
2   local plr = game.Players.LocalPlayer
3   local Mouse = plr:GetMouse()
--Let's also define our brick at we want to follow the mouse,



1   -- Local Script In StarterPack
2   local plr = game.Players.LocalPlayer
3   local Mouse = plr:GetMouse()
4   local Brick = workspace:WaitForChild("Brick")
--I'll be using a mouse move event instead of a loop because it's more efficient and less choppy.



1   -- Local Script In StarterPack
2   local plr = game.Players.LocalPlayer
3   local Mouse = plr:GetMouse()
4   local Brick = workspace:WaitForChild("Brick")
5    
6   Mouse.Move:connect:function()
7       --Do stuff later
8   end)
Now we can use Mouse.Hit to get the CFrame of the mouse in the 3d world and set it to the brick's CFrame.

--view source

1   -- Local Script In StarterPack
2   local plr = game.Players.LocalPlayer
3   local Mouse = plr:GetMouse()
4   local Brick = workspace:WaitForChild("Brick")
5    
6   Mouse.Move:connect:function()
7       Brick.CFrame = Mouse.Hit
8   end)

source: https://scriptinghelpers.org/questions/32438/how-do-i-make-a-block-follow-the-players-mouse

Ad

Answer this question