Qartx
Qartx

Reputation: 27

Don't know how to spawn multiple enemies

My code should spawn multiple enemies that chase around my player. Instead, the enemy just stays in one place. This only happens when I try to input a value into the enemy-spawning function for the spawn coordinates. Heres the code:

class spawn(object):
def __init__(self,place1,place2):
    self.place1=place1
    self.place2=place2
def AIPrototype(self):#The important parts to this error star here
    global x,y,x1,y1
    pygame.draw.rect(screen,THECOLORS['blue'],(self.place1,self.place2,50,50))
    x1=self.place1
    y1=self.place2#end here
    if x1<x:
        xspeed1=1
        slopex1=x-x1
    if x1>x:
        xspeed1=-1
        slopex1=x1-x
    if y1<y:
        yspeed1=1
        slopey1=y-y1
    if y1>y:
        yspeed1=-1
        slopey1=y1-y       
#
    hypo1=((slopex1**2)+(slopey1**2))**0.5
    speedmark1=hypo1/3
    speedy1=slopey1/speedmark1
    speedx1=slopex1/speedmark1
    movex1=speedx1
    movey1=speedy1
    if x1<=640 and x1>=0:
        if x1>x:
            x1+=xspeed1*movex1
            if x1<x:
                xspeed1=0
    if y1<=480 and x1>=0:
        if y1>y:
            y1+=yspeed1*movey1
            if y1<y:
                yspeed1=0
    if x1<=640 and x1>=0:
        if x1<x:
            x1+=xspeed1*movex1
            if x1>x:
                xspeed1=0
    if y1<=480 and x1>=0:
        if y1<y:
            y1+=yspeed1*movey1
            if y1>y:
                yspeed1=0
#
    if x1>640:
        x1=640
    if x1<0:
        x1=0
    if y1>480:
        y1=480
    if y1<0:
        y1=0 
    self.place1=x1#start
    self.place2=y1#end

That's the fucntion for spawning the enemies. The fucntion is called here:

clock = pygame.time.Clock() 
keepGoing = True        

try:
    while keepGoing:
        clock.tick(60) 

        screen.fill(THECOLORS['red'])
        pygame.draw.rect(screen,THECOLORS['green'],(x,y,50,50))
        char()
        spawn1=spawn(200,200)#start
        spawn1.AIPrototype()#end
        pygame.display.flip()

I don't know where my error in the coding is, so if someone could help me out, that would be great.

Upvotes: 0

Views: 561

Answers (1)

skrx
skrx

Reputation: 20438

Here's an example with vectors. To get the velocity of the enemies, I calculate the vector to the player, then normalize it and scale by 4 (the final speed).

vel = (player.center - self.pos).normalize() * 4

Then you can just add the velocity to the pos and set the rect.center to the updated pos vector to move the object.


To spawn new enemies, first create a list that should hold the enemy instances and then just append new instances when an enemy spawns (press the f-key to spawn them). You can also use pygame sprites and sprite groups instead of the Enemy class and the list.

import sys
import pygame as pg


class Enemy:

    def __init__(self, pos, color):
        self.rect = pg.Rect(pos, (26, 45))
        self.color = color
        self.pos = pg.math.Vector2(pos)

    def update(self, player):
        vel = (player.center - self.pos).normalize() * 4
        self.pos += vel
        self.rect.center = self.pos

    def draw(self, screen):
        pg.draw.rect(screen, self.color, self.rect)


def main():
    screen = pg.display.set_mode((640, 480))
    bg_color = pg.Color('gray12')
    player_color = pg.Color('dodgerblue1')
    enemy_color = pg.Color('sienna1')
    clock = pg.time.Clock()
    player = pg.Rect((100, 300), (26, 50))
    enemy_list = [Enemy((100, 300), enemy_color)]

    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            elif event.type == pg.KEYDOWN:
                if event.key == pg.K_f:
                    enemy_list.append(Enemy((400, 0), enemy_color))

        keys = pg.key.get_pressed()
        if keys[pg.K_a]:
            player.x -= 5
        elif keys[pg.K_d]:
            player.x += 5
        if keys[pg.K_w]:
            player.y -= 5
        elif keys[pg.K_s]:
            player.y += 5

        for enemy in enemy_list:
            enemy.update(player)

        screen.fill(bg_color)
        pg.draw.rect(screen, player_color, player)
        for enemy in enemy_list:
            enemy.draw(screen)

        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()
    sys.exit()

Upvotes: 1

Related Questions