scale variable by mouse distance to centre of the screen

Godot Version

4.5

Question

wondering how to scale a variable by the mouse’s x distance from the centre of the screen
so for example the further from the centre of the screen the mouse is the faster the camera moves

You need to find 2 things to make it happen:

  1. Mouse position
  2. Window center (derived from window size)

Both of these are part of the Viewport, so you can grab it from there.
The following function will retrieve both and give you the difference vector and the length of this difference to play around in your code.

extends Node

func _process(_delta: float) -> void:
	var mouse_position: Vector2 = get_viewport().get_mouse_position()
	var window_center: Vector2 = get_viewport().get_window().size / 2
	var difference_vector: Vector2 = mouse_position - window_center
	var difference_length: float = difference_vector.length()
	prints(difference_vector, difference_length)

Let me know if you have troubles implementing this into your codebase.

3 Likes

thanks so much, worked perfectly!

1 Like