Sapling Planter Script has a noticiable offset

I am currently working on a server-startup auto tree planter that currently determines the location of each sapling

The issue I am currently having is that whenever I run the script, the locations are out of bounds of where they should normally be (which is underneath a designated part, dubbed the “ranger”):

I look at my initial math computations, and there shouldn’t be any errors (correct me if I’m wrong).

ServerScript:


local Ranger = workspace.Rangers.Ranger

local saplings = {}
local unitAmount = 300
local unitCount = 0
local saplingSpace = 50


function RangerPlanter()
	
	local RangerX = Ranger.Size.X
	local RangerZ = Ranger.Size.Z
	local faults = {}
	
	while unitCount <= unitAmount do
		
		--Initilization
		local PlaceX = math.random(-RangerX/2, RangerX/2)
		local PlaceZ = math.random(-RangerZ/2, RangerZ/2)
		
		local PlantPoint = Instance.new("Part")
		PlantPoint.Shape = "Ball"
		PlantPoint.Size = Vector3.new(10,10,10)
		PlantPoint.Anchored = true
		PlantPoint.BrickColor = BrickColor.Blue()
		PlantPoint.CFrame = Ranger.CFrame * CFrame.new(PlaceX, -2, PlaceZ)
		PlantPoint.Parent = workspace
		
		--Raycasting for planting to check if surface is possible
		local direction = PlantPoint.Position - Vector3.new(0,1000,0)
		local RaycastResult = workspace:Raycast(PlantPoint.Position, direction)
		
		PlantPoint.Position = RaycastResult.Position
		
		--check to see if ball is too close to other ball
		local rangeFault = false
		
		for i, v in pairs(saplings) do
			
			local altPos = v.Position
			local magnitude = (PlantPoint.Position-altPos).Magnitude
			
			if magnitude <= saplingSpace then
				
				rangeFault = true
				
			end
			
		end
		
		if RaycastResult.Material == Enum.Material.Grass and not rangeFault then
			
			PlantPoint.BrickColor = BrickColor.Red()
			table.insert(saplings, PlantPoint)
			unitCount = unitCount+1
			
		else
			
			table.insert(faults, PlantPoint)
			
		end
		
	end
	
	for i, v in pairs(faults) do

		v:Destroy()

	end
	
end

RangerPlanter()

Ranger Location:
image

Update: It appears the closer the ranger it is to the ground, the more accurate it appears to be:

I belive this is the issue: local direction = PlantPoint.Position - Vector3.new(0,1000,0) , change it to just Vector3.new(0, -1000, 0)

You got things confused here. In this case the raycasts direction needs to be straight down, but you are setting the direction as the parts position - 1000 on the Y axis.

(Basically what i’m trying to say is imagine your part has a position of (2, 10, 7), since you are subtracting the parts position by 1000 the direction becomes (2, -990, 7) and not (0, -1000, 0))

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.