I’m working on a 2D platformer using GUI objects, and I’ve been trying to get collisions with player and ground just right, but the player always ends up a bit deep in the ground than supposed to.
local player = script.Parent.player
local speedX = 0
local speedY = 0
local GRAVITY = 1
local x = player.Position.X.Offset
local y = player.Position.Y.Offset
local startX = player.Position.X.Scale
local startY = player.Position.Y.Scale
local playerSizeX = player.AbsoluteSize.X
local playerSizeY = player.AbsoluteSize.Y
local lastPos
local function changeVariable(var, by)
local returnVal = var + by
return returnVal
end
local function moveX()
x += speedX
player.Position = UDim2.new(startX, x, startY, player.Position.Y.Offset)
end
local function moveY()
y += speedY
player.Position = UDim2.new(startX, player.Position.X.Offset, startY, y)
end
local function checkForCollision(groundContainer)
lastPos = y
moveY()
for i, v in pairs(groundContainer:GetChildren()) do
local x1 = v.AbsoluteSize.X
local y1 = v.AbsoluteSize.Y
print(v.AbsoluteSize.Y)
if player.AbsolutePosition.Y - playerSizeY >= v.AbsolutePosition.Y - v.AbsoluteSize.Y then
y = lastPos
speedY = 0
moveY()
end
end
end
local function movement()
speedY = changeVariable(speedY, GRAVITY)
checkForCollision(script.Parent.ground)
--player.Position = UDim2.new(startX, x, startY, y)
end
while game:IsLoaded() do
movement()
wait()
end