Im trying to make 8 Direction Input System so that it prints what angle the player is pressing on the d-pad/analog stick. This is what i got:

func input_movement():
	var input_direction = Input.get_vector("move_left", "move_right", "move_up", "move_down").normalized()
	
	if input_direction.length () < 0.2:
		input_angle = "Neutral"
	
	if input_direction.x != 0 || input_direction.x >= 0:
		if input_direction.y < 0:
			input_angle = "NORTH"
			if input_direction.x > 0:
				input_angle = "NORTH EAST"
			elif input_direction.x < 0:
				input_angle = "NORTH WEST"
		elif input_direction.y > 0:
			input_angle = "SOUTH"
			if input_direction.x > 0:
				input_angle = "SOUTH EAST"
			elif input_direction.x < 0:
				input_angle = "SOUTH WEST"
		elif input_direction.x > 0:
			input_angle = "EAST"
		elif input_direction.x < 0:
			input_angle = "WEST"

But, sometimes the "South" input wont work, and this system isnt very accurate. How can i improve it to make it better?

  • xyz replied to this.
  • RetroApple21 Using that many ifs can make computers malfunction 😉

    Here's a better way to do it. Given that stick axes are properly mapped:

    func get_8_direction_input(tolerance = .2):
    	var dir = Input.get_vector("move_left", "move_right", "move_up", "move_down")
    	if dir.length() < tolerance: return "NEUTRAL"
    	var angle = posmod(rad_to_deg(dir.angle()), 360)
    	var sector = wrapi(snapped(angle, 45) / 45, 0, 8)
    	return ["E", "SE", "S", "SW", "W", "NW", "N", "NE"][sector]

    RetroApple21 Using that many ifs can make computers malfunction 😉

    Here's a better way to do it. Given that stick axes are properly mapped:

    func get_8_direction_input(tolerance = .2):
    	var dir = Input.get_vector("move_left", "move_right", "move_up", "move_down")
    	if dir.length() < tolerance: return "NEUTRAL"
    	var angle = posmod(rad_to_deg(dir.angle()), 360)
    	var sector = wrapi(snapped(angle, 45) / 45, 0, 8)
    	return ["E", "SE", "S", "SW", "W", "NW", "N", "NE"][sector]