would map navigation camera with middle mouse

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

in my game if i press middle mouse button(or left) and move the mouse the wold map also have to move with like in the godot 2d editor window, here is my code but it’s not perfect because mouse is moving relative to the world map.

extends Node2D

var moving = false
var mouse_start
var camera_start

func _process(delta):
	if Input.is_mouse_button_pressed( BUTTON_LEFT) :
		if ! moving :
			moving = true
			mouse_start = get_global_mouse_position()
			camera_start = $Camera.position
		else:
			var mouse_displacement_vector = (get_global_mouse_position()-mouse_start)
			$Camera.position = camera_start - mouse_displacement_vector
	else:
		moving = false
		

how to resolve this?

:bust_in_silhouette: Reply From: AlienBuchner

My code sample using the ‘Input Map’ in the ‘Project Settings’ (there ‘move_map’ is caused by ‘Device 0, Middle Button’). The script is used by the Camera Node ‘Camera2D’:

extends Camera2D

var fixed_toggle_point = Vector2(0,0)

func _process(delta):
	# This happens once 'move_map' is pressed
	if Input.is_action_just_pressed('move_map'):
		var ref = get_viewport().get_mouse_position()
		fixed_toggle_point = ref
	# This happens while 'move_map' is pressed
	if Input.is_action_pressed('move_map'):
		move_map_around()

# moves the map around just like in the editor
func move_map_around():
	var ref = get_viewport().get_mouse_position()
	self.global_position.x -= (ref.x - fixed_toggle_point.x)
	self.global_position.y -= (ref.y - fixed_toggle_point.y)
	fixed_toggle_point = ref

But using Input.is_mouse_button_pressed(BUTTON_LEFT) surely works, too. Then you can spare defining the Projects Input Map:

extends Camera2D

var fixed_toggle_point = Vector2(0,0)

var currently_moving_map = false

func _process(delta):
	if Input.is_mouse_button_pressed(BUTTON_LEFT) or Input.is_mouse_button_pressed(BUTTON_MIDDLE):
		# This happens once 'move_map' is pressed
		if( !currently_moving_map ):
			var ref = get_viewport().get_mouse_position()
			fixed_toggle_point = ref
			currently_moving_map = true
		# This happens while 'move_map' is pressed
		move_map_around()
	else:
		currently_moving_map = false

# this stays the same
func move_map_around():
	var ref = get_viewport().get_mouse_position()
	self.global_position.x -= (ref.x - fixed_toggle_point.x)
	self.global_position.y -= (ref.y - fixed_toggle_point.y)
	fixed_toggle_point = ref