2D Collision Math Help

I have almost everything working perfectly

however is this a challenge I’m having

I don’t know how to keep the White Box inside the frame

I want to keep the white box inside the frame like how the Black box is.

8 Likes

You can either just create other parts to collide with on the border of the frame. Or just check if the white box is outside the frame of the red one.

If you need code help for the latter, I can help in like ~30-60 minutes (assuming somebody else doesn’t help first).

1 Like

Since it’s cleaner than the first option.

I’ll send a place file to you.

I can wait, I need to eat atm

When the black box pushes the white box, you don’t have it check for the white box’s collision. You’d need to clamp the whitebox’s position so that it can only be pushed within the bounds of the red and blue boxes.

1 Like

Alright so here’s the result. It’s a function with two GUIs as arguments. If the first one isn’t inside the boundaries of the second one, it will move it as appropriate. Main limitation is that you can only use one boundary per GUI (and thus the boundary has to be a rectangle).

It’s basically clamping it like @antonio6643 mentioned.

Code Here
``````--[[
Makes sure Gui1 is inside of Gui2. If not, it will move it so it remains within boundary.

This won't work perfectly to make sure it's within two different GUIs however.

Also, this assumes the AnchorPoint of both GUIs are 0,0. If you use anything else,
you'll need to use this new code:

--Using Anchor
local pos1, size1, anchor1 = Gui1.AbsolutePosition, Gui1.AbsoluteSize, Gui1.AnchorPoint;
local pos2, size2, anchor2 = Gui2.AbsolutePosition, Gui2.AbsoluteSize, Gui2.AnchorPoint;

local top = pos2.Y-size2.Y*anchor1.Y-(pos1.Y-size1.Y*anchor2.Y)
local bottom = pos2.Y+size2.Y*(1-anchor1.Y)-(pos1.Y+size1.Y*(1-anchor1.Y))
local left = pos2.X-size2.X*anchor1.X-(pos1.X-size1.X*anchor2.X)
local right = pos2.X+size2.X*(1-anchor1.X)-(pos1.X+size1.X*(1-anchor1.X))
--]]
local function BoundaryCheck(Gui1, Gui2)
local pos1, size1 = Gui1.AbsolutePosition, Gui1.AbsoluteSize;
local pos2, size2 = Gui2.AbsolutePosition, Gui2.AbsoluteSize;

local top = pos2.Y-pos1.Y
local bottom = pos2.Y+size2.Y-(pos1.Y+size1.Y)
local left = pos2.X-pos1.X
local right = pos2.X+size2.X-(pos1.X+size1.X)

if top > 0 then
Gui1.Position = Gui1.Position + UDim2.new(0,0,0,top)
elseif bottom < 0 then
Gui1.Position = Gui1.Position + UDim2.new(0,0,0,bottom)
end
if left > 0 then
Gui1.Position = Gui1.Position + UDim2.new(0,left,0,0)
elseif right < 0 then
Gui1.Position = Gui1.Position + UDim2.new(0,right,0,0)
end
end
``````
13 Likes

Thank you very much!

1 Like

Well yes that does work, but it only fires if it’s in it. If it’s not in the ui but still touching it, it doesn’t work.

1 Like