Is this the right way to use RunService.Heartbeat to detect position?

Forgive me if this has some obvious mistake in it, I’m very new to using RunService.

local RunService = game:GetService("RunService")
car = script.Parent
fOne = car.Parent.Parent.Floors.P1

RunService.Heartbeat:Connect(function(step)
	if (car.Position.Y >= fOne.floor1.WorldPosition.Y - 1) then
		if (car.Position.Y <= fOne.floor1.WorldPosition.Y + 1) then
			fOne.atFloor.Value = true
			print("at floor 1")
		elseif (car.Position.Y >= fOne.floor1.WorldPosition.Y + 2) then
			print("not at floor 1")
		end
	end
end)

I’ve looked at articles and posts with information or similar questions respectively, but none of them have actually explained how I should do this so this is my first go.

I feel like its wrong because this is constantly printing the part position rather than only printing when it’s actually changed.
It makes it effectively the same as a while loop. So, is this the correct way to use Heartbeat to detect when a position has changed?

I would use .Changed or :GetPropertyChangedSignal()

These do not detect Position changes.

position does not replicate, run service is recommended or camera.CFrame

1 Like

If you are knowledgeable about this subject, do you think my code is perhaps too heavy on performance/have any large mistakes? Or is there a better way I could detect position changes?

i suggest doing something similar but using tables instead of if statements (since it will get crowded)

local RunService = game:GetService("RunService")
car = script.Parent
fOne = car.Parent.Parent.Floors.P1

local Floors = {
	Floor1 = 30 -- hight of floor
}

RunService.Heartbeat:Connect(function(step)
	local Floor = "Floor0"
	local CarHeight = Car.Position.Y

	for flor,height in Floors do
		if height <= CarHeight then
			Floor = flor
		end
	end

	print(Floor) -- prints the floor
end)
1 Like