How to assign a type "float" to a Vector2?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Exoph

Version 3.5.1, it’s giving me this error at two places the first at
“velocity = calculate_move_velocity(velocity, direction, speed)”
and
“new_velocity =+ gravity * get_physics_process_delta_time()”
I’m following GDQuest’s First 2D game tutorial and he didn’t get this error but his version is outdated so does anyone know how I would fix this?

:bust_in_silhouette: Reply From: Ha-kuro

Hard to tell without seeing the code for the functions calculatemovevelocity() and getphysicsprocessdelta_time() but one error here is using =+ instead of +=.

e.g. it should be newvelocity += gravity * getphysicsprocessdelta_time()

Also to make your code more readable, try using snake_case for your functions names like: get_physics_process()

I was fiddling around with the + which is why it ended up where it is and I do use snake_case. It didn’t transfer over and I didn’t notice until now but for the functions

func _physics_process(_delta: float) -> void:
	var direction: = get_direction()
	velocity = calculate_move_velocity(velocity, direction, speed)
	velocity = move_and_slide(velocity,Vector2.UP)

and the other is

func calculate_move_velocity(
		linear_velocity: Vector2,
		direction: Vector2,
		speed: Vector2
	) -> Vector2:
	var new_velocity: = linear_velocity
	new_velocity.x = speed.x * direction.x
	new_velocity += gravity * get_physics_process_delta_time()
	if direction.y == -1.0:
		new_velocity.y =  speed.y * direction.y
	return new_velocity

Exoph | 2022-12-01 06:09

When pasting code into the forum, you need to:

  • paste the code block
  • select it
  • press the { } button in the forum editor’s mini toolbar to format it as code

Otherwise, weird things happen - including the underscores in snake-case code being interpreted as italics markup.

jgodfrey | 2022-12-01 15:11

thanks, probably wouldn’t have figured that out.

Exoph | 2022-12-01 21:57

Is gravity a vector?

It looks like the line new_velocity += gravity * get_physics_process_delta_time() is trying to add a float to a Vector if gravity is a float.

e.g. if gravity * get_physics_process_delta_time() = 5
Then you’re trying to do:
Vector2 = Vector2 + 5
Which causes an error, instead use new_velocity.y

new_velocity.y += gravity * get_physics_process_delta_time()

Ha-kuro | 2022-12-01 23:53

Yep that did the job, thanks a lot.

Exoph | 2022-12-02 05:40