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

How can I get a Vector3 position from mouse?

Asked by 2 years ago

Is there a way I can get a Vector3 value from where my mouse is? What I'm trying to say is, is there a way where, wherever I point my mouse, a part will go to that place in the 3d workspace? Kinda like a drag feature? I'm assuming I use the raycast feature? I'm still new to the raycasting stuff, so it'll take me some time to figure this out. Any help would be appreciated. Thanks!

1 answer

Log in to vote
0
Answered by
Rinpix 639 Moderation Voter
2 years ago

Here's a little script I wrote:

local part = Instance.new("Part")
part.TopSurface = 0
part.BottomSurface = 0
part.Size = Vector3.new(1, 1, 1)
part.Anchored = true
part.Parent = game.Workspace

local userInputService = game:GetService("UserInputService")
local runService = game:GetService("RunService")
local moving = false

local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
mouse.TargetFilter = part

local function toggleMovement(input, processed)
    if (processed) then return end
    if (input.UserInputType == Enum.UserInputType.MouseButton1) then
        moving = not moving
    end
end

runService.RenderStepped:Connect(function()
    if (moving) then
        part.Position = mouse.Hit.Position
    end
end)

userInputService.InputBegan:Connect(toggleMovement)
userInputService.InputEnded:Connect(toggleMovement)

It creates a part and listens for whenever the player left clicks. When they press it, the part will follow their mouse until they release left click.

1
I tried it, and it worked. Thank you! I didn't notice this, but I guess my original script was actually kind of close to this. The original script wasn't working and I thought I'd have to use Rays, but I guess not! I've just learned something new because of this. Voltaicmimic 43 — 2y
Ad

Answer this question