I need help with figuring out the error: Invalid get Index 'x' (on base: 'float')

Godot 4.2.1
Here is my code:
extends Sprite2D

var speed = 300
var screensize
var pos
var velocity = Vector2(100, 50)

func _ready():
screensize = get_viewport_rect().size.x
pos = screensize / 2
set_process(true)
pass

func _process(delta):
if Input.is_action_pressed(“ui_right”) or Input.is_key_pressed(KEY_D):
position.x += speed * delta
if Input.is_action_pressed(“ui_left”) or Input.is_key_pressed(KEY_A):
position.x -= speed * delta
if Input.is_action_pressed(“ui_up”) or Input.is_key_pressed(KEY_W):
position.y -= speed * delta
if Input.is_action_pressed(“ui_down”) or Input.is_key_pressed(KEY_S):
position.y += speed * delta
if pos.x >= screensize.width or pos.x <= 0:
velocity.x *= -1
if pos.y >= screensize.height or pos.y <= 0:
velocity.y *= -1
pos += velocity * delta
set_position(pos)

So im trying to follow a tutorial i found on Godot engine and part of it talks about making a sprite bounce/ hit off the wall. However every time i try to do it keeps on giving me the error: Invalid get Index ‘x’ (on base:‘float’) and im overall just confused if its a piece of code im missing or not.

If you have any suggestions or a solution to fix this then let me know ASAP!

Since you haven’t explicitly assigned a type to your variables (for example var pos:Vector2) Godot will try to guess and assign what types the variables are based on what you do with them.
In your case you set screensize = get_viewport_rect().size.x which makes screensize a float variable (you probably expect it to be a Vector2). The you set pos = screensize / 2 which also makes pos as float. And then later when you try to access the .x component of pos you get the error since float variables don’t have an x component.

To fix it in this case you can probably just change the row to correctly set screensize to the size screensize = get_viewport_rect().size. But a better way to avoid this is to assign types to all your variables ahead of time so you’re sure they’re what you expect, and you’ll spot mistakes like this easily as they’ll give you warnings when you write the code.

2 Likes