簡體   English   中英

所有精靈必須在pygame中移動

[英]All the sprites have to move in pygame

我在我的游戲中使用Vector2制作相機。 但是,當我與牆壁碰撞時,所有的精靈都開始移動,因此我將其固定在牆壁和地板上,但是我不知道該如何修復敵人。 有任何想法嗎?

這是我的代碼:

import sys
import pygame as pg
from pygame.math import Vector2

width = 1280
height = 720
x1 = 200
y1 = 100
x2 = 500
y2 = 400
x3 = 100
y3 = 300
x = 0
y = 0

class Player(pg.sprite.Sprite):

    def __init__(self, pos, *groups):
        super().__init__(*groups)
        pg.sprite.Sprite.__init__(self)
        self.image = pg.image.load("character.png")
        self.rect = self.image.get_rect(center=pos)
        self.vel = Vector2(0, 0)
        self.pos = Vector2(pos)

    def update(self):
        self.pos += self.vel
        self.rect.center = self.pos

#enemy class
class Enemy(pg.sprite.Sprite):

    def __init__(self, pos, waypoints, *groups):
        super().__init__(*groups)
        self.image = pg.image.load("enemy.png")
        self.image = pg.transform.scale(self.image, (int(50), int(50)))
        self.rect = self.image.get_rect(center=pos)
        self.vel = Vector2(0,0)
        self.max_speed = 5
        self.pos = Vector2(pos)
        self.waypoints = waypoints
        self.waypoint_index = 0
        self.target = self.waypoints[self.waypoint_index]
        self.target_radius = 50
        self.rect.x = width / 2
        self.rect.y = height / 2

    def update(self):
# A vector pointing from self to the target.
        heading = self.target - self.pos
        distance = heading.length()  # Distance to the target.
        heading.normalize_ip()
        if distance <= 2:  # We're closer than 2 pixels.
          # Increment the waypoint index to swtich the target.
          # The modulo sets the index back to 0 if it's equal to the length.
          self.waypoint_index = (self.waypoint_index + 1) % len(self.waypoints)
          self.target = self.waypoints[self.waypoint_index]
        if distance <= self.target_radius:
                # If we're approaching the target, we slow down.
          self.vel = heading
        else:  # Otherwise move with max_speed.
          self.vel = heading * self.max_speed

        self.pos += self.vel
        self.rect.center = self.pos

#Enemy waypoints
waypoints = [[x1, y1], [x2, y2], [x3, y3]]


class Floor(pg.sprite.Sprite):

    def __init__(self, x, y, *groups):
        super().__init__(*groups)
        self.image = pg.image.load("floor.png")
        self.rect = self.image.get_rect(topleft=(x, y))
        self.rect.x = x
        self.rect.y = y

class SideWall(pg.sprite.Sprite):

    def __init__(self, x, y, *groups):
        super().__init__(*groups)
        self.image = pg.image.load("sidewall.png")
        self.rect = self.image.get_rect(topleft=(x, y))
        self.rect.x = x
        self.rect.y = y

class TopAndBottomWall(pg.sprite.Sprite):

    def __init__(self, x, y, *groups):
        super().__init__(*groups)
        self.image = pg.image.load("topandbottomwall.png")
        self.rect = self.image.get_rect(topleft=(x, y))
        self.rect.x = x
        self.rect.y = y


def main():
    screen = pg.display.set_mode((1280, 720))
    clock = pg.time.Clock()
    #all the sprites group
    all_sprites = pg.sprite.Group()

    #the floor
    floor = Floor(540, -620, all_sprites)

    #player
    player = Player(((width / 2), (height / 2)), all_sprites)

    #walls group
    walls = pg.sprite.Group()

    #all walls
    walltop = TopAndBottomWall(540, -620, all_sprites, walls)
    wallbottom = TopAndBottomWall(540, 410, all_sprites, walls)
    wallleft = SideWall((width / 2) - 100, (height / 2) - 930, all_sprites, walls)
    wallright = SideWall((wallleft.rect.x + (1920 - 50)), (height / 2) - 930, all_sprites, walls)

    #all enemy's
    enemy = Enemy((100, 300), waypoints, all_sprites)

    camera = Vector2(0, 0)

    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            #player movement    
            elif event.type == pg.KEYDOWN:
                if event.key == pg.K_d:
                    player.vel.x = 5
                elif event.key == pg.K_a:
                    player.vel.x = -5
                elif event.key == pg.K_w:
                    player.vel.y = -5
                elif event.key == pg.K_s:
                    player.vel.y = 5
            elif event.type == pg.KEYUP:
                if event.key == pg.K_d and player.vel.x > 0:
                    player.vel.x = 0
                elif event.key == pg.K_a and player.vel.x < 0:
                    player.vel.x = 0
                elif event.key == pg.K_w:
                    player.vel.y = 0
                elif event.key == pg.K_s:
                    player.vel.y = 0

        camera -= player.vel

        all_sprites.update()

        if pg.sprite.spritecollide(player, walls, False):
            #stop the left wall from moving
            wallleft.rect.x = wallleft.rect.x + player.vel.x
            wallleft.rect.y = wallleft.rect.y + player.vel.y
            #stop the top wall from moving
            walltop.rect.y = walltop.rect.y + player.vel.y
            walltop.rect.x = walltop.rect.x + player.vel.x
            #stop the right wall from moving
            wallright.rect.x = wallright.rect.x + player.vel.x
            wallright.rect.y = wallright.rect.y + player.vel.y
            #stop the bottom wall from moving
            wallbottom.rect.x = wallbottom.rect.x + player.vel.x
            wallbottom.rect.y = wallbottom.rect.y + player.vel.y
            #stop the floor from moving
            floor.rect.x = floor.rect.x + player.vel.x
            floor.rect.y = floor.rect.y + player.vel.y


        screen.fill((0, 0, 0))

        for sprite in all_sprites:
            screen.blit(sprite.image, sprite.rect.topleft+camera)

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

main()
pg.quit()

如果要運行它,這是文件的鏈接。 https://geordyd.stackstorage.com/s/hZZ1RWcjal6ecZM

您正在使用屏幕坐標 您僅在檢查按鍵時才移動牆壁; 您應該同時移動敵人。

但是還有更好的方法。 如果您添加更多的類,則擴展性更高,並且混亂程度更低。

Wall取出按鍵支票並放入Player 這將改變玩家在世界坐標中的位置,該坐標與牆壁(靜態)相同,而敵人在(動態)中移動。

然后在world_position - players_position繪制牆和敵人,根據玩家在中心的相對位置進行調整。 從技術上講,甚至是玩家本身都被繪制在該位置上-他的計算結果是相對於屏幕的零移動。

為了獲得更大的靈活性,您可以考慮單獨的Camera類,默認情況下,該類設置為跟隨播放器。 這樣一來,您就可以讓相機“移到其他地方”,或者如果播放器在您的世界邊緣附近,請讓他離開屏幕中心。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM