You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Godot开发2D平台角色触地时出现Invalid get index 'y'错误求解决

Godot 2D平台角色错误修复:Invalid get index 'y' (on base: 'int')

错误信息

Invalid get index 'y' (on base: 'int')

该错误仅在角色接触地面时触发。

问题代码

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

错误分析

velocity初始是Vector2类型,但在地面检测分支中,你直接将它赋值为整数5,导致变量类型被覆盖成了int。后续代码(比如下一轮_physics_process里的velocity.y += GRAVITY)再尝试访问y属性时,就会因int类型没有该索引而报错。

修复代码

只需修改错误行,保持velocity的Vector2类型,仅调整其y分量:

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.y = 5  # 修复:仅修改y分量
    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

内容的提问来源于stack exchange,提问作者TheJalfireKnight

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 05:25:54