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

Pygame中使用Surface实现矩形类时钟指针旋转效果的问题求助

Pygame矩形旋转效果修复方案

你的代码轨迹异常是两个核心原因导致的:

  1. math.cos()、math.sin() 接收的参数为弧度值,你当前直接传入累加的角度值,计算出的位移完全不符合预期
  2. Pygame的transform.rotate操作会改变原Surface的外框尺寸,且默认围绕Surface左上角旋转,你直接使用原Surface的topleft属性定位,会导致旋转中心持续偏移,无法固定在期望的时钟中心位置

最小改动修改点(完全保留你原有代码逻辑)

  • 三角函数调用时,用math.radians()将角度转换为弧度
  • 旋转后通过get_rect(center=固定中心点)的方式自动适配旋转后的外框偏移,无需手动计算dx、dy
  • 增加简单偏移量让矩形的一端固定在中心,符合时钟指针的转动逻辑

修改后完整代码

import random, pygame, math, sys
from pygame.locals import *
 
Blue = (0,0,255)
Black = (0, 0, 0) 
Green = (0,255,0)
White = (255,255,255)
  
pygame.init()
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Sailing!')
  
FPS = 30
fpsClock = pygame.time.Clock()
  
Sail = pygame.Surface([100,10])
Sail.set_colorkey (Black)
Sail.fill(White)
  
degrees = 0
# 时钟中心固定坐标
center_pos = (200, 150)


while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    
    rotatedSail = pygame.transform.rotate(Sail, degrees)
    # 获取旋转后Surface的rect,先对齐到中心
    rotated_rect = rotatedSail.get_rect(center=center_pos)
    # 矩形长度为100,偏移半个长度让指针根部固定在中心
    rad = math.radians(degrees)
    rotated_rect.centerx += 50 * math.cos(rad)
    rotated_rect.centery -= 50 * math.sin(rad)
    
    DISPLAYSURF.fill(Blue)
    DISPLAYSURF.blit(rotatedSail, rotated_rect)
    pygame.display.flip()
  
    fpsClock.tick(FPS)
    # 要顺时针旋转就修改为 degrees -= 1
    degrees += 1

如果需要调整指针的转动速度,修改degrees的累加/累减值即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 06:06:03