So this week I am trying to create a camera that “peeks” in the direction of the mouse location. I’ve read over a few different ways that people are doing it, but none have seemed to fit the use case for me.
The only problem with this code is that the further my player gets from the origin/spawn point, the further the camera becomes not centered on the player.
Any idea how to fix this issue?
Thanks!
P.S. I should note that I am a newbie at coding and game dev, so please bear with me!
It seems as if the camera position is in the mid-point between the character and the mouse position. You could optionally clamp the offset so it doesn’t go beyond a preset value.
How about something like this? (untested code below)
extends Camera2D
# set the character's node here so we can track its position
@export var target : Node2D
@export var max_offset: Vector2
func move_camera():
var mouse_pos = get_global_mouse_position()
var target_pos = target.global_position
offset = (mouse_pos + target_pos) / 2 # midpoint between target and mouse
# optionally, clamp the offset by some value
offset = offset.clamp(-max_offset, max_offset)
func _physics_process(delta):
move_camera()
extends Camera2D
onready var target = $"../this_thing"
func move_camera():
var mouse_pos = get_global_mouse_position()
var target_pos = target.global_position
offset = (mouse_pos + target_pos) / 2
func _physics_process(delta):
move_camera()
Now, there does some to be an issue when clamped()/limit_length() is used. I get the issue with the camera not centering on the target.
I’m going to mess around with finding some numbers that might work to limit how much it moves. Will post an update if I find something. Let me know if you find something that works, too!