Topic was automatically imported from the old Question2Answer platform.
Asked By
Lazulily
I have a script that allows the camera to be moved around by holding down middle mouse and dragging around the play area, but if you just hold down the middle mouse and don’t move the camera will violently shake and then carry through the movement it makes when you let go of the button. This can be worked around but the outcome is still not desirable, enabling smoothing tames the shaking but if you smooth too fast the camera will violently shake again, and if you make the smoothing too slow the camera moves too slow and I don’t really want any smoothing on the camera to begin with. I am using self.translate() for the camera movement because when I use self.position to move the camera it only moves mostly around a specific position.
extends Camera2D
var lastMousePos = get_global_mouse_position()
var currentMousePos = lastMousePos
func _process(delta):
if Input.is_action_pressed("cam_drag"):
currentMousePos = get_global_mouse_position()
var diff = (lastMousePos - currentMousePos).normalized()
self.translate(diff * 30)
lastMousePos = currentMousePos #I'm assuming the jittering is because of - these variables, not sure though
it’s because you use global_mouse_position so when your camera moves, your ‘lastMousePos’ that you record when your camera is at previous position isn’t correct anymore
use mouse position in viewport instead
and use onready at variable declaration to prevent getting null mouse position when the game starts
onready var lastMousePos = get_viewport().get_mouse_position()
onready var currentMousePos = lastMousePos
SUGGESTION:
1.reset your ‘lastMousePos’ every time you begin a new drag so your camera didn’t move when you just click
if Input.is_action_just_pressed("cam_drag"):
lastMousePos = get_viewport().get_mouse_position()
2.currently, all your camera drag will round to 30 even if it slightly drag. make you can’t drag in small distance.
seperate the case to enable small drag with this
if lastMousePos.distance_to(currentMousePos) < 30:
# SMALL DRAG
self.translate(lastMousePos - currentMousePos)
else :
var diff = (lastMousePos - currentMousePos).normalized()
self.translate(diff * 30)
with all code above, we get this
extends Camera2D
onready var lastMousePos = get_viewport().get_mouse_position()
onready var currentMousePos = lastMousePos
func _process(delta):
if Input.is_action_just_pressed("cam_drag"):
lastMousePos = get_viewport().get_mouse_position()
if Input.is_action_pressed("cam_drag"):
currentMousePos = get_viewport().get_mouse_position()
if lastMousePos.distance_to(currentMousePos) < 30:
# SMALL DRAG
self.translate(lastMousePos - currentMousePos)
else :
var diff = (lastMousePos - currentMousePos).normalized()
self.translate(diff * 30)
lastMousePos = currentMousePos
Thank you very much! I’ll be sure to try this out!