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?
CodePudding user response:
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, velocity
is a Variant, initialized to a Vector2
:
var velocity = Vector2(0,0)
And - for example - here you use it as a Vector2
:
velocity.y = clamp(velocity.y, -MAX_SPEED, MAX_SPEED)
velocity.x = clamp(velocity.x, -MAX_SPEED, MAX_SPEED)
But here 5
is an int
not a Vector2
:
velocity = 5
So after that velocity
... Continues to be a Variant, but now it has an int
value. So when you use it as a Vector2
it fails. Because an int
does not have x
, y
.
You can declare velocity
to be a Vector2
explicitly:
var velocity:Vector2 = Vector2()
Or implicitly (inferred from the value you assigned):
var velocity:= Vector2()
And then Godot will tell you that this line:
velocity = 5
Is an error, because you are trying to set an int
to a Vector2
.
You could either want to set only one component to 5
, for example:
velocity.y = 5
Or you want to set the length of the vector to 5
, which you could do like this:
velocity = velocity.normalized() * 5
Or you want to set both components to 5
, which can be this:
velocity.x = 5
velocity.y = 5
Or this:
velocity = Vector2(5, 5)
Write the code that you mean.