首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >游戏教程-坦克与碰撞检测

游戏教程-坦克与碰撞检测
EN

Stack Overflow用户
提问于 2021-05-17 16:05:24
回答 1查看 99关注 0票数 3

我是刚开始玩游戏的,我试着学习精灵和碰撞检测。我找到了一些代码,并尝试向其添加一些功能。

基本思想是,我有一个多边形,可以旋转到位。当用户按空格键时,多边形会发射一个弹丸,它可以在框架周围弹跳。如果弹丸再次击中多边形,我想把程序写得很好。

首先,这是代码

代码语言:javascript
复制
import pygame

class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface((32, 32))
        self.image.fill((0, 0, 0))
        self.image.set_colorkey((0, 0, 0))
        self.fire_from = (36, 20)
        pygame.draw.polygon(self.image, pygame.Color('dodgerblue'), ((0, 0), (32, 16), (0, 32)))
        self.org_image = self.image.copy()
        self.angle = 0
        self.direction = pygame.Vector2(1, 0)
        self.rect = self.image.get_rect(center=(200, 200))
        self.pos = pygame.Vector2(self.rect.center)

    def update(self, events, dt):

        for e in events:
            if e.type == pygame.KEYDOWN:
                if e.key == pygame.K_SPACE:
                    bullet = Projectile(self.fire_from, self.direction.normalize())
                    self.groups()[0].add(bullet)
        pressed = pygame.key.get_pressed()

        if pressed[pygame.K_LEFT]:
            self.angle += 3
        if pressed[pygame.K_RIGHT]:
            self.angle -= 3

        self.direction = pygame.Vector2(1, 0).rotate(-self.angle)
        self.image = pygame.transform.rotate(self.org_image, self.angle)
        self.rect = self.image.get_rect(center=self.rect.center)

class Projectile(pygame.sprite.Sprite):
    def __init__(self, pos, direction):
        super().__init__()
        self.image = pygame.Surface((8, 8))
        self.image.fill((0, 0, 0))
        self.image.set_colorkey((0, 0, 0))
        pygame.draw.circle(self.image, pygame.Color('orange'), (4, 4), 4)
        self.rect = self.image.get_rect(center=pos)
        self.direction = direction
        self.pos = pygame.Vector2(self.rect.center)
        self.max_bounce = 10

    def update(self, events, dt):

        #print(self.pos)
        # Bounding box of the screen
        screen_r = pygame.display.get_surface().get_rect()

        # where we would move next
        next_pos = self.pos + self.direction * dt

        # we hit a wall
        if not screen_r.contains(self.rect):

            # after 10 hits, destroy self
            self.max_bounce -= 1
            if self.max_bounce == 0:
                return self.kill()

            # horizontal reflection
            if next_pos.x > screen_r.right or next_pos.x < screen_r.left:
                self.direction.x *= -1

            # vertical reflection
            if next_pos.y > screen_r.bottom or next_pos.y < screen_r.top:
                self.direction.y *= -1

            # move after applying reflection
            next_pos = self.pos + self.direction * dt

        # set the new position
        self.pos = next_pos
        self.rect.center = self.pos

def main():
    pygame.init()
    screen = pygame.display.set_mode((500, 500))
    tank = Player()
    sprites = pygame.sprite.Group()
    sprites.add(tank)
    #print(tank.groups()[0])
    clock = pygame.time.Clock()
    dt = 0
    running = True
    while running:
        #print(tank.groups()[0])
        events = pygame.event.get()
        for e in events:
            if e.type == pygame.QUIT:
                return
        sprites.update(events, dt)
        screen.fill((30, 30, 30))
        sprites.draw(screen)
        pygame.display.update()

        ## ALWAYS DETECTS A COLLISION, WHY?
        if len(tank.groups()[0])>1:
            if pygame.sprite.spritecollideany(tank, tank.groups()[0]):
                running = False

        dt = clock.tick(60)

if __name__ == '__main__':
    main()

我在这里收集到,玩家类(也就是我的坦克)本身就有一个精灵群,它将每一个弹丸作为其发射物添加到其中。此外,弹丸起源于多边形的矩形内(因此它最初总是发生碰撞)。

我只想把弹丸添加到雪碧组,如果它至少有1次反弹,这有可能吗?或者..。有更好的方法吗?

有什么帮助或指点吗?

谢谢你,努尔

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-05-17 16:23:42

tank与自身发生碰撞,因为它是tank.groups()[0]的一个成员。

if pygame.sprite.spritecollideany(坦克,tank.groups()):

添加一个只包含以下内容的组:

代码语言:javascript
复制
class Player(pygame.sprite.Sprite):
    def __init__(self):
        # [...]

        self.bullets = pygame.sprite.Group()

    def update(self, events, dt):

        for e in events:
            if e.type == pygame.KEYDOWN:
                if e.key == pygame.K_SPACE:
                    bullet = Projectile(self.fire_from, self.direction.normalize())
                    self.groups()[0].add(bullet)
                    self.bullets.add(bullet)

        # [...]

使用此组进行碰撞测试:

代码语言:javascript
复制
def main():
    # [...]

    while running:
        # [...]

        pygame.display.update()

        if pygame.sprite.spritecollideany(tank, tank.bullets):
            running = False

        dt = clock.tick(60)
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67573293

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档