我一直在致力于“小行星”的翻拍。但是我无法让物体随机移动。我确定这是使用向量演变而来的,但是我不知道如何为每个小行星随机生成一个向量。
我正在寻找与此 asteroid game 中显示的此 Action 类似的 Action ,但是我什至不知道如何开始。到目前为止,这是我的代码:
import pygame as game
import random as r
import math
game.init()
game.display.set_caption("Asteroids")
screen = game.display.set_mode([800,600])
time=0
gameon=True
bgcolor = game.color.Color("#f6cb39")
black=game.color.Color("black")
badguy = game.image.load("asteroid.png")
badguy = game.transform.scale(badguy, (50, 50))
badguys=[]
SPAWNENEMY=10
CLOCK=11
game.time.set_timer(SPAWNENEMY,800)
game.time.set_timer(CLOCK,1000)
font=game.font.Font(None,20)
timetext=font.render("Time: 0", 0, black)
while gameon:
screen.fill(bgcolor)
event=game.event.poll()
if event.type==SPAWNENEMY:
bgbox = game.Rect(badguy.get_rect())
bgbox.x = r.randint(50,800)
bgbox.y = r.randint(50,600)
badguys.append(bgbox)
if event.type==game.QUIT:
gameon=False;
for bg in badguys:
'''
This is where I tried to put the mocment code,
but I was unableto get randmom movments,
only for asteroids to randomly appear or consistently
move in one direction something like "bg.x+=2"
'''
for bg in badguys:
screen.blit(badguy,(bg.x,bg.y))
game.display.flip()
如果它有点长,我很抱歉,我不知道我还能删掉什么来创建一个 MCV。
最佳答案
下面是如何使用向量来完成它。 badguy
列表中的每个项目现在都是一对项目,它的当前位置和关联的速度向量。请注意,位置本身也是一个向量(也称为“位置向量”)。
更新当前位置只需将每个 badguy 的速度矢量添加到其当前位置即可。即 bg[0] += bg[1]
。
import pygame as game
import pygame.math as math
from pygame.time import Clock
import random as r
game.init()
game.display.set_caption("Asteroids")
screen = game.display.set_mode([800, 600])
time = 0
gameon = True
bgcolor = game.color.Color("#f6cb39")
black = game.color.Color("black")
clock = Clock()
badguy = game.image.load("asteroid.png")
badguy = game.transform.scale(badguy, (50, 50))
badguys = []
SPAWNENEMY = 10
CLOCK = 11
game.time.set_timer(SPAWNENEMY, 800)
game.time.set_timer(CLOCK, 1000)
font=game.font.Font(None,20)
timetext=font.render("Time: 0", 0, black)
while gameon:
screen.fill(bgcolor)
event = game.event.poll()
if event.type == SPAWNENEMY:
# Select a random initial position vector.
posn = math.Vector2(r.randint(50, 800), r.randint(50, 600))
# Create a random speed vector.
speed = r.randint(1, 10)
dx = r.random()*speed * r.choice((-1, 1))
dy = r.random()*speed * r.choice((-1, 1))
vector = math.Vector2(dx, dy)
# Each badguy item is a [position, speed vector].
badguys.append([posn, vector])
if event.type == game.QUIT:
gameon = False;
for bg in badguys:
# Update positions.
bg[0] += bg[1] # Update position using speed vector.
for bg in badguys:
screen.blit(badguy, bg[0])
clock.tick(60)
game.display.flip()
关于python - 如何让对象在pygame中以随机模式移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54238277/