Setting player velocity doesn't cause it to move

Godot Version

4.2.2

Question

I’m following the “First 3D game” tutorial from the docs.
I’ve encountered a problem in the “Moving the player with code” section.
As the title suggests, whatever I do I can’t get the player to move.

Here’s the code:

extends CharacterBody3D
@export var speed = 14
@export var fall_acceleration = 75

var target_velocity = Vector3.ZERO

func _physics_process(delta):
	var direction = Vector3.ZERO
	
	if Input.is_action_pressed("move_right"):
		direction.x += 1
	if Input.is_action_pressed("move_left"):
		direction.x -= 1
	if Input.is_action_pressed("move_forward"):
		direction.z += 1
	if Input.is_action_pressed("move_back"):
		direction.z -= 1
		
	if direction != Vector3.ZERO:
		direction = direction.normalized()
		$Pivot.basis = Basis.looking_at(direction)
	
	target_velocity.x = direction.x * speed
	target_velocity.z = direction.z * speed

	if not is_on_floor():
		target_velocity.y = target_velocity.y - (fall_acceleration * delta)

	velocity = target_velocity
	# velocity = Vector3.ONE
	move_and_slide()

I know the inputs are working because the model changes direction.
I also tried setting velocity to a vector of ones but that didn’t fix it either.
The script is pretty much a copy of the code in the tutorial, but it doesn’t work.

Any help would be much appreciated.

Does your character move if you set velocity to Vector3.ONE * 20? If not it could be your sprite is not a child of the CharacterBody2D.

Nope, I even print position right after move_and_slide and it doesn’t change at all.
Here’s what the player scene looks like:
Screenshot from 2024-07-15 23-11-09

some suggestions for testing:

  • make sure that there is no collision thing preventing you to move (comment out gravity && move the player in the air). Or temporarily change your player CollisionShape3D to a sphere
  • play around with much bigger speed values
  • since you’ve already tested it: does velocity = Vector3.ONE work?
  • make sure you don’t reset the velocity somewhere else

Maybe something gives you a hint of what is (not) happening

1 Like

Finally it’s fixed!
Turns out the problem was the collision. I had set the size of the CollisionShape of the main scene to 60 so my player model would spawn inside of it and thus it couldn’t move. changing the scale of the CollisionShape object to 2 fixed it.
Thank you it didn’t occur to me that the problem was the collision.

1 Like

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