jeudi 17 janvier 2019

How to get object to move in a random pattern in pygame?

I have been working on an "Asteroids" remake. However I can not get the objects to move in a random motion. I'm sure this evolves using vectors, however I do not know hot to randomly generate a vector for each individual asteroid. I am looking for a motion similar to this motion, from this asteroid game, however I have no idea how to even start. This is my code so far

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()

I appologize if its a little long, I dont know what else I can cut out to create an MCV.




Aucun commentaire:

Enregistrer un commentaire