Given that this only actually changes the direction if the player has selected something, you can use on_selected_entity_changed
instead of on_tick
:
script.on_event(defines.events.on_selected_entity_changed, function(event)
local player = game.players[event.player_index]
if player.selected and player.character and player.character.valid and player.surface.darkness >= 0.3 and not player.vehicle and not player.walking_state.walking then
player.character.direction = math.floor((math.atan2(player.position.x - player.selected.position.x, player.selected.position.y - player.position.y) / math.pi + 1) * 4 + 0.5) % 8
end
end)