gpt4 book ai didi

python - 如何在 Pygame 中获取坐标/碰撞区域

转载 作者:行者123 更新时间:2023-12-01 02:44:14 25 4
gpt4 key购买 nike

我有一个游戏,其中子弹移动得非常快,以至于在一帧中它就已经穿过了屏幕。话虽如此,它已经与多堵墙壁相撞了。目前,我有一个矩形图像,从子弹当前所在的位置到子弹在下一帧中的位置,以便不错过中间可能存在的任何僵尸。

如果子弹与任何墙壁相撞,我也会杀死子弹,然后再检查它是否与任何僵尸相撞,因为发生的情况是,如果墙后有僵尸,并且我首先检查僵尸碰撞,它会杀死它僵尸然后杀死子弹。

所以基本上,我想知道一种方法来找到子弹与墙壁碰撞的坐标,这样我就不会以全速推进子弹,而是将其推进到碰撞之前的位置,检查僵尸碰撞,然后杀死子弹。

我正在使用蒙版碰撞。

最佳答案

如果子弹移动速度太快而无法与墙壁或敌人碰撞,则需要光线转换(或者以多个小步移动子弹)。这是一个简单的光线转换示例,它返回最近的碰撞点。我用vectorspygame.Rect.collidepoint查看heading 向量上的点是否与障碍物发生碰撞。

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


class Wall(pg.sprite.Sprite):

def __init__(self, x, y, w, h, *groups):
super().__init__(*groups)
self.image = pg.Surface((w, h))
self.image.fill(pg.Color('goldenrod4'))
self.rect = self.image.get_rect(topleft=(x, y))


def ray_cast(origin, target, obstacles):
"""Calculate the closest collision point.

Adds the normalized `direction` vector to the `current_pos` to
move along the heading vector and uses `pygame.Rect.collidepoint`
to see if `current_pos` collides with an obstacle.

Args:
origin (pygame.math.Vector2, tuple, list): Origin of the ray.
target (pygame.math.Vector2, tuple, list): Endpoint of the ray.
obstacles (pygame.sprite.Group): A group of obstacles.

Returns:
pygame.math.Vector2: Closest collision point or target.
"""
current_pos = Vector2(origin)
heading = target - origin
# A normalized vector that points to the target.
direction = heading.normalize()
for _ in range(int(heading.length())):
current_pos += direction
for sprite in obstacles:
# If the current_pos collides with an
# obstacle, return it.
if sprite.rect.collidepoint(current_pos):
return current_pos
# Otherwise return the target.
return Vector2(target)


def main():
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
all_sprites = pg.sprite.Group()
walls = pg.sprite.Group()
Wall(100, 170, 90, 20, all_sprites, walls)
Wall(200, 100, 20, 140, all_sprites, walls)
Wall(400, 60, 150, 100, all_sprites, walls)

pos = Vector2(320, 440)
done = False

while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True

all_sprites.update()
collision_point = ray_cast(pos, pg.mouse.get_pos(), walls)
screen.fill((30, 30, 30))
all_sprites.draw(screen)
pg.draw.line(screen, (50, 190, 100), pos, pg.mouse.get_pos(), 2)
pg.draw.circle(screen, (40, 180, 250), [int(x) for x in collision_point], 5)

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


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

关于python - 如何在 Pygame 中获取坐标/碰撞区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45389563/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com