In Godot, I am making a 2D platformer, but in my player code I get the error:
Invalid get index 'y' (on base: 'int')
But only when the character touches the ground. My player code is this:
extends KinematicBody2D
const JUMP_FORCE = 1550
const MOVE_SPEED = 500
const GRAVITY = 60
const MAX_SPEED = 2000
var velocity = Vector2(0,0)
var can_jump = false
func _physics_process(delta):
var walk = (Input.get_action_strength("right") - Input.get_action_strength("left")) * MOVE_SPEED
velocity.y += GRAVITY
velocity.x += walk
move_and_slide(velocity, Vector2.UP)
velocity.x -= walk
velocity.y = clamp(velocity.y, -MAX_SPEED, MAX_SPEED)
velocity.x = clamp(velocity.x, -MAX_SPEED, MAX_SPEED)
var grounded = is_on_floor()
if grounded:
can_jump = true
if velocity.y >= 5:
velocity = 5
elif is_on_ceiling() and velocity.y <= -5:
velocity.y = -5
if Input.is_action_just_pressed("jump"):
if grounded:
velocity.y = -JUMP_FORCE
elif can_jump:
can_jump = false
velocity.y = -JUMP_FORCE
How do I fix this?
This is a close match to Invalid set index z with value of type float in gdscript. I would vote to close as duplicate but that question does not have an up-voted answer. Anyway, I will adapt the answer.
Types.
Look,
velocityis a Variant, initialized to aVector2:And - for example - here you use it as a
Vector2:But here
5is anintnot aVector2:So after that
velocity... Continues to be a Variant, but now it has anintvalue. So when you use it as aVector2it fails. Because anintdoes not havex,y.You can declare
velocityto be aVector2explicitly:Or implicitly (inferred from the value you assigned):
And then Godot will tell you that this line:
Is an error, because you are trying to set an
intto aVector2.You could either want to set only one component to
5, for example:Or you want to set the length of the vector to
5, which you could do like this:Or you want to set both components to
5, which can be this:Or this:
Write the code that you mean.