Hey,
I’m currently trying to make a SurfaceGui follow the player’s cursor. I have surfed the internet for an answer to this but nothing seems to help.
So in detail, I have a character in-game which a player can move with their mouse. I need an arrow pointing to the player’s cursor so they can see where that character is going. Here is a picture so you can understand what I mean.
I would go about this by thinking about it as a simple placement or object movement script. Get the player’s mouse (raycasting or mouse position) and then determine where it is in correlation with the surface of your map.
This will create a CFrame pointed at the Mouse without vertical movement:
local BasePosition = Vector3.new(0, 10, 0) --wherever the ring is (change this)
local LookAt = CFrame.lookAt(BasePosition, game:GetService("Players").LocalPlayer:GetMouse().Hit.Position)
RingPartThingy.CFrame = CFrame.new(BasePosition) * CFrame.Angles(0, math.atan2(-LookAt.LookVector.X, -LookAt.LookVector.Z), 0)
I’m fairly sure if you use UserInputService you will need to project the MousePosition and use a raycast, which is more complicated than using mouse.Hit, but I get your concerns.
Yes, UIS and CAS are considered by Roblox to be “better”, however the Mouse will remain supported for the time being and as @Katrist just mentioned, using the Mouse is overall simpler and makes more sense to use in this scenario.
I agree with you on that part. It’s overcomplicates alotttttt of things and personally I’m not a fan of it. I guess what I’m trying to say is, if the poster is going to use Mouse, he should proceed with caution and not be surprised if Roblox randomly deprecates it one day.
I believe I worded my question incorrectly. I want the arrow to change its rotation and point to where the direction of the player’s cursor is. How would I find the direction of where the mouse is and change a GuiObject’s rotation based on that?
It seems to kind of work, but when I point the mouse to the middle it freaks out and starts pointing up. How do I prevent it from doing that?
Heres the code:
local mouse = game.Players.LocalPlayer:GetMouse()
game:GetService("RunService").Stepped:Connect(function()
local part = workspace.PlayerTemplate.GuiPart
part.CFrame = CFrame.lookAt(part.Position, mouse.Hit.Position)
end)
It’s because the Y value isn’t the same as that part’s Y value, so it increases the Y position to match. You can fix this by setting the returned position’s Y value to the part’s Y value.
Code:
--//Services
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
--//Variables
local mouse = Players.LocalPlayer:GetMouse()
local part = workspace.PlayerTemplate.GuiPart
--//Functions
RunService.RenderStepped:Connect(function()
local mousePosition = mouse.Hit.Position
part.CFrame = CFrame.lookAt(part.Position, Vector3.new(mousePosition.X, part.Position.Y, mousePosition.Z))
end)