Camera working specific (Camera following to mouse from player)

Godot Version

4.2.1

Question

Hello! Im new in godot and trying make camera what following mouse, i research all browser and found only ± working code:

extends Camera2D

const camera_dead_zone = 20

func _input(event: InputEvent) -> void:
	if event is InputEventMouseMotion:
		var _target = event.position - get_viewport().size * 0.5
		if _target.length() < camera_dead_zone:
			self.position = Vector2(0,0)
		else:
			self.position = _target.normalized() * (_target.length() - camera_dead_zone) * 0.5

When they in Node2D - All ok, but when in player (CharacterBody2D), they getting be crazy.

Godot_v4.2.1-stable_win64_hNdHP0uKyc

Godot_v4.2.1-stable_win64_Pai91OS7zw

Your camera script is based around the center of the screen, but you have tried to center it around something else (a character at the bottom left). You will have to change your algorithm to include the player’s position and maybe even global coordinates.

extends Camera2D

const camera_dead_zone = 20

func _input(event: InputEvent) -> void:
	if event is InputEventMouseMotion:
		
		var _target = event.global_position - (get_viewport().size + self.global_position) * 0.5
		if _target.length() < camera_dead_zone:
			self.position = Vector2(0,0)
		else:
			self.position = _target.normalized() * (_target.length() - camera_dead_zone) * 0.5

Heya, after month “of doing nothing” i did that dynamic camera!

For him need:

  • Node2D (Or other main node)
  • Camera2D (CoPO)
  • CharacterBody2D (PoPO)
    Godot_v4.2.1-stable_win64_Q8FbDxr1Rl

First, we need add in “CharacterBody2D” this code:

extends CharacterBody2D

# Exporting coordinates of position CharacterBody2D
@export var popoPos = Vector2()

func _process(delta):
	# Updating positions of player
	popoPos.x = global_position.x
	popoPos.y = global_position.y

Next, we need add that code in “Node2D”:

extends Node2D

func _process(delta):
	var mouse_position = get_global_mouse_position() #Getting mouse positions
	var cameraPoPOpos = $PoPO #Camera of CharacterBody2D position = CharacterBody2D
	var target_position = (cameraPoPOpos.get("popoPos") + mouse_position) / 2 #Calculating middle position of mouse and character
	
	$CoPO.global_position = target_position #Setting global position of Camera2D


#	print (target_position) #Printing in console middle position of camera

And you get full working camera what following to mouse from player! :3

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.