Pygame 移动对象 [英] Pygame moving an object

查看:65
本文介绍了Pygame 移动对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想简单地在 pygame 中移动一个对象.我一直在寻找教程,但我能找到的只是如何让它看起来像在下雪,哈哈.我一直在尝试实现该方法来移动对象,但我没有运气.我想要做的就是在屏幕上移动一个对象,当它到达屏幕末端时,它会重置并再次移动.所以我试图在屏幕上水平或垂直移动我放在代码中的对象(两个多边形、线和圆),这并不重要.

So I am trying to simply move an object in pygame. I have been looking up tutorials but all I can find is how to make it look like it is snowing, lol. I have been trying to implement that method into moving an object but I am having no luck. All I want to do is move an object across the screen and when it reaches the end of the screen it resets and goes again. So I am trying to move the object that I put in my code (the two polygons, line, and circle) across the screen, horizonally or vertically, doesnt really matter.

import pygame, sys, time, random
from pygame.locals import *

pygame.init()

windowSurface = pygame.display.set_mode((500, 400), 0, 32)
pygame.display.set_caption("Paint")

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

windowSurface.fill(WHITE)

pygame.draw.polygon(windowSurface,BLUE,((146, 0), (250, 100), (230, 265), (44, 250), (0,110)))
pygame.draw.polygon(windowSurface,RED,((70, 0), (150, 200), (0, 50)))
pygame.draw.line(windowSurface,BLACK,(60, 60), (120, 60), 8)
pygame.draw.circle(windowSurface, GREEN , (150,150), 15, 0)


pygame.display.update()

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

推荐答案

用你的方法,你不能.使用 pygame 背后的想法是绘制每一帧你想要绘制的所有对象.您必须首先在 while True 循环中移动绘图.然后,由于您要绘制每一帧的所有内容,您可以:

With your approach, you can't. The idea behind using pygame is to draw all the objects you want to draw each frame. You must move the drawing inside your while True loop first. Then, since you're drawing everything each frame, you could:

  • 创建用于存储对象位置和方向的对象/变量
  • 检查对象是否到达屏幕的一个边界
  • 使用新位置绘制多边形

所以最后,你可以有类似的东西(改变对象是你的任务)

So at the end, you could have something like that (it's your task to change to an object)

# ... pygame and app initialization

# get screen size
info = pygame.display.Info()
sw = info.current_w
sh = info.current_h

# initial position
x = y = 0
# initial direction
dx = 5
dy = 2

while True:

    # update position with direction
    x += dx
    y += dy

    # check bounds
    if x - dx < 0 or x + dx > sw:
        dx = -dx
    if y - dy < 0 or y + dy > sh:
        dy = -dy

    # then draw and use x/y in your drawing instructions!
    # ... pygame events ...

这篇关于Pygame 移动对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆