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

Pygame开发塞尔达风格像素游戏:玩家移动报错'int' object has no attribute 'y'

Pygame角色移动报错:'int' object has no attribute 'y' 解决方法

问题描述

跟着YouTube教程开发塞尔达风格像素游戏,移动角色时编译器抛出错误:

'int' object has no attribute 'y'

已还原教程中的所有代码,但不清楚错误原因,希望角色能正常移动。

错误根源分析

  1. 核心错误:方向变量被错误覆盖
    在Player类的input方法中,松开方向键时你直接将self.direction赋值为整数0,而不是重置Vector2对象的单个分量。原本self.direction是pygame.math.Vector2类型(拥有x/y属性),赋值为0后会变成整数类型,后续代码访问self.direction.y自然会触发属性不存在的错误。
  2. 次要错误:速度变量类型错误
    self.speed = (5,)定义为元组类型,后续和Vector2执行乘法运算会导致异常,应改为整数类型。

修复后的Player代码

import pygame
from settings import *

class Player(pygame.sprite.Sprite):
    def __init__(self, pos, groups):
        super().__init__(groups)
        self.image = pygame.image.load(r'C:\Users\bekie\Desktop\projekt\graphics\test\player.png').convert_alpha()
        self.rect = self.image.get_rect(topleft = pos)

        self.direction = pygame.math.Vector2()
        self.speed = 5  # 修正:将元组改为整数

    def input(self):
        keys = pygame.key.get_pressed()

        # 上下方向:仅重置y分量,不替换整个direction对象
        if keys[pygame.K_UP]:
            self.direction.y = -1
        elif keys[pygame.K_DOWN]:
            self.direction.y = 1
        else:
            self.direction.y = 0
        
        # 左右方向:仅重置x分量,不替换整个direction对象
        if keys[pygame.K_RIGHT]:
            self.direction.x = 1
        elif keys[pygame.K_LEFT]:
            self.direction.x = -1
        else:
            self.direction.x = 0

    def move(self, speed):
        self.rect.center += self.direction * speed

    def update(self):
        self.input()
        self.move(self.speed)

修复说明

修改后self.direction始终保持pygame.math.Vector2类型,不会被替换为整数,访问x/y属性的逻辑恢复正常;同时速度变量改为整数后,与Vector2的乘法运算可正常执行,角色就能按预期响应方向键移动了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 12:10:20