Can't see why my code wouldn't work

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Elayon

It’s supposed to detect which direction the mouse is headed to from the players perspective and get a gun out from that direction. I’ve been trying so hard to fix it. I’d also really appreciate any tips on how could I improve this code.

if Input.is_action_pressed("MouseClick"):
	
	var mousePos = get_local_mouse_position()
	
	var direction : String
	
	if $Weapon.offset.y == 0:
		
		if abs(mousePos.x) - abs(mousePos.y) >= 0:
			
			if mousePos.x >= 0:
				
				direction = "right"
				$Weapon.rotation_degrees = 90
				
			else:
				
				direction = "left"
				$Weapon.rotation_degrees = -90
				
			
		else:
			
			if mousePos.y <= 0:
				
				direction = "top"
				$Weapon.rotation_degrees = 0
				
			else:
				
				direction = "bottom"
				$Weapon.rotation_degrees = 180
			
		
	
	while Input.is_action_pressed("MouseClick") and direction == get_direction_changed():
		print(direction)
		if $Weapon.offset.y >= -188:
			
			$Weapon.offset.y -= 4
			
			$WeaponGetOut.start(0.1)
			yield($WeaponGetOut, "timeout")
			
		else:
			
			$Weapon.play("MinigunSpin")
			
			if $Weapon.speed_scale < 60:
				
				$Weapon.speed_scale += 0.05
				$WeaponGetOut.start(0.1)
				yield($WeaponGetOut, "timeout")
	
	while (!Input.is_action_pressed("MouseClick") or direction != get_direction_changed()) and $Weapon.offset.y != 0:
		
		get_back_in()
		$WeaponGetOut.start(0.1)
		yield($WeaponGetOut, "timeout")
	
	
else:
	
	get_back_in()
	$WeaponGetOut.start(0.1)
	yield($WeaponGetOut, "timeout")
	
	

func get_back_in():

if $Weapon.speed_scale > 3:
	
	$Weapon.speed_scale -= 0.1
	
else:
	
	$Weapon.playing = false
	
	if $Weapon.offset.y != 0:
		
		$Weapon.offset.y += 4

func get_direction_changed():

var mousePos = get_local_mouse_position()

if abs(mousePos.x) - abs(mousePos.y) >= 0:
	
	if mousePos.x >= 0:
		
		return "right"
		
	else:
		
		return "left"
		
		
	
else:
		
		if mousePos.y <= 0:
			
			return "top"
			
		else:
			
			return "bottom"

Sorry, could you say what the result you’re getting right now is? That would make it a lot easier to answer.

exuin | 2021-02-23 16:23

:bust_in_silhouette: Reply From: Whalesstate

i checked it fast and it could be implemented easier than this , you can replace the order of mouse_dir values if it’s inverted

var player := KinematicBody2D.new()
var gun := Sprite.new()
func _process(_delta : float) -> void:
	var mouse_dir = get_global_mouse_position() - player.global_position
	gun.look_at(mouse_dir)