I’m creating a simple 2D game where cubes fall from above and stop as soon as they collide with the ground or another cube. The cubes need to fall perfectly parallel from above and align perfectly on top of other cubes (a bit like in Tetris). To achieve this effect, I couldn’t use Roblox’s basic gravity, so I decided to set the objects as Anchored and manage their fall manually.
Below is my current code, but it doesn’t work very well. The fall is not very smooth, and most importantly, the blocks do not stop and align perfectly when they collide with a block underneath. They often stop slightly above or seem to move slightly. Can anyone give me some advice or help to solve this problem?
local part = script.Parent
local fallSpeed = 11
local falling = coroutine.create(function()
while true do
local newPosition = part.Position - Vector3.new(0, fallSpeed * wait(), 0)
local collision = workspace:GetPartBoundsInBox(CFrame.new(part.Position.X, part.Position.Y, part.Position.Z) - Vector3.new(0, fallSpeed * wait(), 0), Vector3.new(3,4,4))
--print(collision)
if #collision > 1 then
break
else
part.Position = newPosition
end
wait(0.01)
end
coroutine.yield()
end)
coroutine.resume(falling)
Firstly, see if swapping wait() with task.wait() can improve performance, since task.wait doesn’t have throttling while wait() does.
Secondly, calling wait() in the GetPartsBoundInBox (Edit: as well as when setting the newPosition variable) actually causes the function to wait, it’s better to make it so that you set a delta value to the time returned by the wait(0.01) and then use that as a measure of the time elapsed.
You can solve the misalignment by using ray casts, or if it is truly like Tetris storing the current height of each stack (Edit: If I’m correct in assuming its vertical misalignment)
In this case, isn’t it better to use RunService.Stepped instead of RunService.Heartbeat since it’s an update regarding the game’s custom physics? Also, I would like to ask if being a script run by the server, if the frames are indeed those of the server, or if they are calculated based on those of the connected player. In this case, if one player has a better PC than the other, there could be a desynchronization since the player with the better PC will run the code more times. Right?