How to get AI to turn around at specific y-coordinate?

Hi,
I tried to make a guard move up and down the screen but each time it reaches the top of the screen he carries on moving and does not stop. Thanks

function init(self)
	--msg.post(".", "acquire_input_focus")

	--Initialises the position of the guard on the screen
	go.set_position(vmath.vector3(247, -76, 0))

	--Initialises the speed of the guard through the vmath vector function
	self.speed = vmath.vector3(0, 100, 0)
	--x = vmath.vector3(0, 100, 0)
end

function update(self, dt)
	--Initialises the local variable position
	local position = go.get_position()

	--The distance travelled will add to the initial distance
	go.set_position(position + self.speed * dt)

	--Stops the guard from leaving the boundary and turns them around
	--Only acting in the y-axis
	if (go.get_position().y == 0) then
		--self.speed.y = 100
		self.speed = vmath.vector3(0, 100, 0)
	end 
	
	if (go.get_position().y == 415) then
		--self.speed.y = -100
		self.speed = vmath.vector3(0, -100, 0)
	end
end```

These conditions will never be met because they are floating point values once you multiply by ‘dt’. Try the following instead:

if (go.get_position().y <= 0) then

if (go.get_position().y >= 415) then

1 Like

Thank you, that works perfectly