Problem with raycast placement

I want to make a tycoon game but i want to make it little bit different So i made a placement script where you can place your droppers, upgraders etc. But with raycasting it doesn’t dedect good if its outside of placeable base or if its inside of a another object it dedects it buggy beacuse raycasting only casts like thin stick I need help!

local function CanPlace(targetobject)
	local Position = round(Mouse.Hit.Position,4)
	local TargetSurface = Mouse.TargetSurface.Name
	local SizeY = targetobject.PrimaryPart.Size.Y
	local SizeX = targetobject.PrimaryPart.Size.X
	local SizeZ = targetobject.PrimaryPart.Size.Z
	local Origin = Position + Vector3.new(SizeX/2, SizeY/2, SizeZ/2)
	
	local ignoreTable = {
		character,
		DropperParts.parts
	}

	local raycastParams = RaycastParams.new()
	raycastParams.FilterType = Enum.RaycastFilterType.Exclude
	raycastParams.FilterDescendantsInstances = {ignoreTable}
	
	local RaycastResult = workspace:Raycast(Origin + Vector3.new(0,150,0),  Vector3.new(0,-250,0), raycastParams)--Vector3.new(0,-250,0))
	
	
	local Hightlight = targetobject.Highlight
	
	if RaycastResult and RaycastResult.Instance and RaycastResult.Instance.Parent and
		(RaycastResult.Instance.Parent.Parent.Name == "Structures" or RaycastResult.Instance.Parent.Name == "Objects" or not (RaycastResult.Instance.Parent.Name == "Plot")) then
		
		Hightlight.FillColor = Color3.new(1, 0, 0)
		Hightlight.OutlineColor = Color3.new(1, 0, 0)
	else
		Hightlight.FillColor = Color3.new(0, 1, 0)
		Hightlight.OutlineColor = Color3.new(0, 1, 0)
	end
end

Simply check whether the bounds of the object being placed are in the bounds of the base.

In the 2D case, given points a1, a2, a3, a4 which are the corners of the object being placed, and points b1, b2, b3, b4 which are the corners of the base:

This is pseudocode. This means it is not real code and doesn’t work.

let b1, b4  -- turns out b2, b3 are not necessary
let object_points = {a1, a2, a3, a4}

for point in object_points
  -- if statement checks whether point is outside of bounds
  if point.X < b1.X or point.Y < b1.Y
     or point.X > b4.X or point.Y > b4.Y
  then
    reject object placement
  end
end

accept object placement
1 Like

You’ll also need to check if an object does not intersect another object. The process of doing so is much the same, but inverted, so it is left as an exercise to the reader :slight_smile:

1 Like