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

How can I 'round' a Vector3 to the nearest stud?

Asked by 11 years ago

I'm trying to create an equivalent to the default ROBLOX 'Drag' HopperBin, but I want it to only work within a 20 stud radius. I've got that bit working, but actually moving the part I'm dragging is not how I'd like it. I want it 'rounded' to the nearest stud. The problem with that is that some studs are .5 and not just a solid 1. Here's my current code:

local player = script.Parent.Parent.Parent.Parent local mouse = player:GetMouse() local draggable = false local trg = nil

01mouse.Move:connect(function()
02    if trg ~= nil then
03        if mouse.Target ~= trg then
04            if (mouse.Hit.p - trg.Position).magnitude <= 50 then
05                trg.Position = Vector3.new(math.ceil(mouse.Hit.p.X),math.ceil(mouse.Hit.p.Y),math.ceil(mouse.Hit.p.Z))
06            end
07        end
08    end
09end)
10 
11mouse.Button1Down:connect(function()
12    if mouse.Target ~= nil then
13        if mouse.Target:findFirstChild("ForageItem") ~= nil then
14            if mouse.Target:findFirstChild("ForageItem").RemoveOnForage.Value == true then
15                if mouse.Target:findFirstChild("NoDrag") == nil then
View all 94 lines...

1 answer

Log in to vote
4
Answered by 11 years ago

I think this should work. Just tested with single number, so it should work with vectors just fine.

1function roundVector(vector, unit)
2    return vector - Vector3.new(vector.X%unit, vector.Y%unit, vector.Z%unit)
3end
0
What is the second argument to the function? Vector3.unit? YaYaBinks3 110 — 11y
0
No, it's not an argument of Vector3 API. The unit is argument of my custom function, and I use it to round to closest value using modulus operator. What I am doing, is: vector.X - (vector.X % 20) In that example it would snap X to 20 stud grid. ZarsBranchkin 885 — 11y
0
Thank you! I worked it out! :) YaYaBinks3 110 — 11y
Ad

Answer this question