Currently working on an incremental game and one of my main issues with the last project I made was detecting when the part is in a range.
I’ve tried researching on the devforum and other sites however have not found a fix.
I’ve linked the code below. My main issue is that it finds parts from ~0.25 studs in advance and deletes them rather than my range part touching it and it deleting.
Here’s a video of my issue:
local function ArePartsTouching(part1, part2)
local pos1 = part1.Position - part1.Size / 2
local pos2 = part2.Position - part2.Size / 2
local distance = (pos1 - pos2).Magnitude
local sizeSum = (part1.Size.magnitude + part2.Size.magnitude) / 2
if distance <= sizeSum then
return true
else
return false
end
end
Hard to say, but it looks like because the Part is 2x4 studs it’s reading the size as the max dimension.
Try using a gray Part that’s 2x10 studs to see if it ‘hits’ at 4 studs away.
You could shoot a Shapecast instead the size of your green Part. You could also use a cylinder so it only touches parts that are 1.5 studs away instead of the diagonal of the 3x3 green Part.
WorldRoot:GetPartsInPart() returns an array of parts whose occupied space is shared with the given part (which must exist in the same WorldRoot as the parts to be queried). This method can be used in place of BasePart:GetTouchingParts() and is generally a better choice.
You can use what’s known as a signed distance function, which returns exact distance from a point to an object, it’s called signed as it’s negative inside the shape and position outside of it. For a simple box/cube/cuboid, you can use:
local function sdBox(position: Vector3, size: Vector3): number
local distance = position:Abs() - size
return distance:Max(Vector3.zero).Magnitude + math.min(math.max(distance.x, distance.y, distance.z), 0.0);
end
This assumes the box is at 0,0 which u can change by doing position - box position before passing it to this function
Just noticed you marked a previous reply as a solution, will leave this here for others tho.