在pygame中向鼠标方向射击子d

在pygame中向鼠标方向射击子d,第1张

在pygame中向鼠标方向射击子d

首先,

pygame.transform.rotate
不变形对象本身,而是创建一个新的旋转曲面并将其返回。

如果要向特定方向发射子d,则在发射子d时即定义方向,但不会连续变化。发射子d后,设置子d的起始位置,然后将方向向量计算为鼠标位置:

self.pos = (x, y)mx, my = pygame.mouse.get_pos()self.dir = (mx - x, my - y)

方向向量不应取决于与鼠标的距离,而必须是Unit向量。通过除以欧几里得距离来归一化向量

length = math.hypot(*self.dir)if length == 0.0:    self.dir = (0, -1)else:    self.dir = (self.dir[0]/length, self.dir[1]/length)

计算向量的角度并旋转子d。通常,向量的角度可以通过来计算

atan2(y, x)
。由于y
atan2(-y,x)
轴通常指向上方,因此y轴需要反转(),但是在PyGame坐标系中y轴指向下方(请参阅如何知道两点之间的角度?):

angle = math.degrees(math.atan2(-self.dir[1], self.dir[0]))self.bullet = pygame.Surface((7, 2)).convert_alpha()self.bullet.fill((255, 255, 255))self.bullet = pygame.transform.rotate(self.bullet, angle)

要更新子d的位置,只需缩放方向(按速度)并将其添加到子d的位置即可:

self.pos = (self.pos[0]+self.dir[0]*self.speed,  self.pos[1]+self.dir[1]*self.speed)

要将旋转的项目符号绘制在正确的位置,请获取旋转的项目符号的边界矩形并使用设置中心点

self.pos
(请参阅如何使用PyGame围绕其中心旋转图像?):

bullet_rect = self.bullet.get_rect(center = self.pos)surf.blit(self.bullet, bullet_rect)

最小示例:

[![](https://i.stack.imgur.com/5jD0C.png) repl.it/@Rabbid76/PyGame-FireBulletInDirectionOfMouse](https://repl.it/@Rabbid76/PyGame-FireBulletInDirectionOfMouse#main.py)

import pygameimport mathpygame.init()window = pygame.display.set_mode((500, 500))clock = pygame.time.Clock()class Bullet:    def __init__(self, x, y):        self.pos = (x, y)        mx, my = pygame.mouse.get_pos()        self.dir = (mx - x, my - y)        length = math.hypot(*self.dir)        if length == 0.0: self.dir = (0, -1)        else: self.dir = (self.dir[0]/length, self.dir[1]/length)        angle = math.degrees(math.atan2(-self.dir[1], self.dir[0]))        self.bullet = pygame.Surface((7, 2)).convert_alpha()        self.bullet.fill((255, 255, 255))        self.bullet = pygame.transform.rotate(self.bullet, angle)        self.speed = 2    def update(self):          self.pos = (self.pos[0]+self.dir[0]*self.speed,          self.pos[1]+self.dir[1]*self.speed)    def draw(self, surf):        bullet_rect = self.bullet.get_rect(center = self.pos)        surf.blit(self.bullet, bullet_rect)bullets = []pos = (250, 250)run = Truewhile run:    clock.tick(60)    for event in pygame.event.get():        if event.type == pygame.QUIT: run = False        if event.type == pygame.MOUSEBUTTONDOWN: bullets.append(Bullet(*pos))    for bullet in bullets[:]:        bullet.update()        if not window.get_rect().collidepoint(bullet.pos): bullets.remove(bullet)    window.fill(0)    pygame.draw.circle(window, (0, 255, 0), pos, 10)    for bullet in bullets:        bullet.draw(window)    pygame.display.flip()


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5631632.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存