gpt4 book ai didi

python - Pygame:如何让我的形象倒下?

转载 作者:太空宇宙 更新时间:2023-11-04 02:40:35 25 4
gpt4 key购买 nike

我正在尝试让物体像在地球上一样下落。我已经让它们在我想要的位置进行 blit,但我似乎无法为它们设置动画。

这就是我要掉落的物体

import pygame

class circle():

def __init__(self, screen):
planet_color = (255,0,0)
planet_radius = 20
self.screen = screen
ev = pygame.event.get()

self.image = pygame.image.load('../images/jupiter.bmp')
self.image = pygame.transform.scale(self.image, (80, 80))


def blitme(self):
self.x = pygame.mouse.get_pos()
self.rect = self.image.get_rect()
self.rect.center = self.x
self.screen.blit(self.image, self.rect)

这是运行它的代码。单击鼠标时,会在单击鼠标的位置制作一张木星的小图片。我如何让这个图像下降?

import pygame
import gravfunc as gf
from gravfunc import circle
import sys


def run_game():
screen_height = 670
screen_width = 1270
pygame.init()
screen = pygame.display.set_mode((screen_width, screen_height))
screen.fill((10,10,30))
running = True

circ = circle(screen)


while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
circ.blitme()


pygame.display.flip()


run_game()

最佳答案

给你的类一个 self.speed_y 属性,并在每一帧向它添加 GRAVITY 以加速对象。我还添加了一个 self.pos_y 属性,因为 pygame.Rect 不能将 float 作为它们的坐标。所以,

  1. 提高速度
  2. 将速度添加到位置 (self.pos_y)
  3. self.pos_y赋给self.rect.y

由于您已经在使用一个类,我建议将其设为 pygame sprite 子类(继承自 pygame.sprite.Sprite)。然后您可以将所有圆圈添加到 pygame.sprite.Group 并通过调用 sprite_group.update()sprite_grop.draw(screen)< 更新和绘制它们.

import pygame


GRAVITY = .2 # Pretty low gravity.

class Circle(pygame.sprite.Sprite):

def __init__(self, pos, screen):
super().__init__()
self.screen = screen
self.image = pygame.Surface((80, 80), pygame.SRCALPHA)
pygame.draw.circle(self.image, (30, 90, 150), (40, 40), 40)
self.rect = self.image.get_rect(center=pos)
self.pos_y = pos[1]
self.speed_y = 0

def update(self):
self.speed_y += GRAVITY
self.pos_y += self.speed_y
self.rect.y = self.pos_y

if self.pos_y > self.screen.get_height():
self.kill() # Remove off-screen circles.


def run_game():
pygame.init()
screen = pygame.display.set_mode((1270, 670))
clock = pygame.time.Clock()
running = True
circles = pygame.sprite.Group(Circle((600, 0), screen))

while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
elif event.type == pygame.MOUSEBUTTONDOWN:
circles.add(Circle(event.pos, screen))

circles.update()

screen.fill((10, 10, 30))
circles.draw(screen)

pygame.display.flip()
clock.tick(60)


run_game()
pygame.quit()

关于python - Pygame:如何让我的形象倒下?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46657585/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com