Invalid assignment of 'x'

Godot Version

Godot 4.6.2

Question

It’s my first time using Godot, and i tried to code a simple move command:

extends CharacterBody2D

@export var speed = 14

@export var fall_accelleration = 75

var player_vel = Vector2.ZERO

func _ready() → void:
pass

func _process(delta: float) → void:
var direction = Vector2.ZERO

if Input.is_action_pressed("move_left"):
	direction.x -= 1
if Input.is_action_pressed("move_right"):
	direction.x += 1

player_vel.x = direction.x * speed
player_vel.y = direction.y * speed
player_vel = (direction.x + direction.y) / 2

and i keep getting this error: Invalid assignment of property or key ‘x’ with value of type ‘float’ on a base object of type ‘float’. And i don’t know how to fix this

Which line specifically generates the error?

After executing the line

	player_vel = (direction.x + direction.y) / 2

the player_vel is no longer a Vector2 but only a float.

The next time your code tries to assign

	player_vel.x = direction.x * speed

your code will fail.

You can improve your error messages by declaring

var player_vel: Vector2 = Vector2.ZERO

because with this declaration Godot will show you an error message the moment you try to assign a float value to player_vel - i.e. on the line

	player_vel = (direction.x + direction.y) / 2

How to fix this? If you need the value of (direction.x + direction.y) / 2 somewhere then you need to assign it to a different variable.

But I’m not sure what you would need this value for:

  • Moving in x=1, y=1 gives you 1
  • Moving in x=-1, y=1 gives you 0
3 Likes