When i try to normalize my vector my character wont stop moving(top down game)

Godot Version

4.3-stable

Question

after i tried normalizing my vector to prevent faster diagonal movement i found that my character will just keep moving even when im not touching anything

Heres my code:



var speed = 300.0
var deceleration = 20.0


func _physics_process(delta: float) -> void:


	# Add the gravity.
	if not is_on_floor():
		velocity += get_gravity() * delta

	velocity = velocity.normalized() * speed
	

	# Handle jump.
	var directiony := Input.get_axis("up", "down")
	if directiony:
		velocity.y = directiony * speed
	else:
		velocity.y = move_toward(velocity.y, 0, deceleration)
	# Get the input direction and handle the movement/deceleration.
	# As good practice, you should replace UI actions with custom gameplay actions.
	var directionx := Input.get_axis("left", "right")
	if directionx:
		velocity.x = directionx * speed
	else:
		velocity.x = move_toward(velocity.x, 0, deceleration)
		
	if Input.is_action_just_pressed("run"):
		speed += 150.0
	else:
		move_toward(velocity.x, 0, deceleration)
		move_toward(velocity.y, 0, deceleration)
		
	if Input.is_action_just_released("run"):
		speed = 300.0

	velocity = velocity.normalized() * speed

	move_and_slide()

type or paste code here

type or paste code here

That advice is for 2d top down or 3d games, you are making a game where the vertical axis is affected by gravity and is not directly controlled by player input. There’s no need to normalize it. Also, if you were making a game where you need to normalize, you would normalize the input vector and not the velocity since that would cause the player to never be able to slow down as their velocity can never be below 1.

normalizing means a vector always has a length of 1.
what this means is that a normalized vector will never be 0 0.

that’s your problem.

you could:


if not is_on_floor():
	velocity += get_gravity() * delta
	velocity = velocity.normalized() * speed

this would only normalize when there is gravity being applied.

this however will never work.

i came up with my own solution which only normalizes the vector when needed

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