I need help witch 3D camera Code

Godot Version

v4.2.1.stable.official [b09f793f5]

Question

Please help. I’m missing a couple of things in the code. First, the camera tilts and I want it to be perpendicular to the ground. Second, I want the character move in the same way that camera. And else I dont now how to highlight code.


var mouse_sens = 0.3
var camera_anglev = 0
var SPEED = 5.0
var JUMP_VELOCITY = 4.5
var gravity = ProjectSettings.get_setting("physics/3d/default_gravity")
func _physics_process(delta):
	if not is_on_floor():
		velocity.y -= gravity * delta

	if Input.is_action_just_pressed("jump") and is_on_floor():
		velocity.y = JUMP_VELOCITY

	
	var input_dir = Input.get_vector("left", "right", "up", "down")
	var direction = (transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()
	if direction:
		velocity.x = direction.x * SPEED
		velocity.z = direction.z * SPEED
	else:
		velocity.x = move_toward(velocity.x, 0, SPEED)
		velocity.z = move_toward(velocity.z, 0, SPEED)
	move_and_slide()

func _input(event): 
	Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
	if event is InputEventMouseMotion:
		$Camera3D.rotate_y(deg_to_rad(-event.relative.x*mouse_sens))
		var changev=-event.relative.y*mouse_sens
		if camera_anglev+changev>-50 and camera_anglev+changev<50:
			camera_anglev+=changev
			$Camera3D.rotate_x(deg_to_rad(changev))```

(use ``` to post code)
What do you mean by “perpendicular to the ground”? If you want a common FPS camera, do you mean it shouldn’t roll? Do you mean you want it to not pitch up and down?
To move the character in the direction the camera is pointing you need to rotate the direction of movement along the Y axis the same amount the camera is rotated.

1 Like

Yes, I mean it shouldn’t roll. And I change the code like you say, it work.

	Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
	if event is InputEventMouseMotion:
		rotate_y(deg_to_rad(-event.relative.x*mouse_sens))
		var changev=-event.relative.y*mouse_sens
		if camera_anglev+changev>-50 and camera_anglev+changev<50:
			camera_anglev+=changev
			$Camera3D.rotate_x(deg_to_rad(changev))```

To avoid roll, you can just set rotation.z = 0.0 after move_and_slide() I think.

1 Like

thank you :slight_smile:

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