Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to have a proper collision detection in placement games?

The code I have so far doesn't work, I am thinking that it does not update fast enough. Here is the code:

local player = game:GetService("Players").LocalPlayer
local mouse = player:GetMouse() 

local grass = script.Blocks.GrassBlock
local grassClone = grass:Clone()
grassClone.Parent = game.Workspace
local grid = 2
local finalPos = CFrame.new()

mouse.Move:Connect(function()	
	grassClone.PrimaryPart = grassClone.Hitbox
	local floorX = math.floor(mouse.Hit.X / grid + 0.5) * grid
	local floorZ = math.floor(mouse.Hit.Z / grid + 0.5) * grid
	finalPos = CFrame.new(floorX, 3, floorZ)
	local checkCollision = grassClone.PrimaryPart:GetTouchingParts()
	
	for _, p in next, checkCollision do
		print(p.Name)
		if p.Name == "Box" then
			grassClone.PrimaryPart.BrickColor = BrickColor.Red()	
			grassClone.PrimaryPart.Transparency = 0.5
		else
			grassClone.PrimaryPart.BrickColor = BrickColor.Green()	
			grassClone.PrimaryPart.Transparency = 0.9
		end
	end	
	
	grassClone:SetPrimaryPartCFrame(finalPos)
end)

mouse.Button1Down:Connect(function()
	local grassClone = grass:Clone()
	grassClone.Parent = game.Workspace
	local checkCollision = grassClone.PrimaryPart:GetTouchingParts()
	grassClone:SetPrimaryPartCFrame(finalPos)
	grassClone.PrimaryPart.Name = "Box"	
end)

Thanks for the Help!

1 answer

✓ Accepted answer

You could use GetTouchingParts() to check if anything is colliding with the object. Make sure to check if the colliding object isn’t a part of what you are placing, and that it is a part of a prop. You can also use CollisionGroups to make the item being placed have no collision for players, but still can be touched by other parts. Keep in mind that it has to be CanCollide true to check if anything is touching.

This discussion is preserved as it was. New answers, comments, and votes are closed.