在 PyGame 中向光标发射子弹
在 PyGame 中,创建跟随鼠标光标方向的射弹可能会带来挑战。让我们检查一下提供的代码并解决其缺点。
现有代码分析
当前代码的目标是:
但是,实现有一些缺陷:
正确的方法
为了解决这些问题,我们采用不同的方法:
在创建时初始化项目符号参数:
预旋转子弹:
连续位置更新:
示例实现
<code class="python">import pygame import math # Bullet Class class Bullet: def __init__(self, x, y): # Calculate initial position and direction self.pos = (x, y) mx, my = pygame.mouse.get_pos() self.dir = (mx - x, my - y) # Normalize direction vector length = math.hypot(*self.dir) self.dir = (self.dir[0]/length, self.dir[1]/length) # Create bullet surface and rotate it self.bullet = pygame.Surface((7, 2)).convert_alpha() self.bullet.fill((255, 255, 255)) angle = math.degrees(math.atan2(-self.dir[1], self.dir[0])) self.bullet = pygame.transform.rotate(self.bullet, angle) self.speed = 2 # Adjust bullet speed as desired def update(self): # Update position based on scaled direction vector self.pos = (self.pos[0]+self.dir[0]*self.speed, self.pos[1]+self.dir[1]*self.speed) def draw(self, surface): # Draw bullet aligned with the correct direction bullet_rect = self.bullet.get_rect(center=self.pos) surface.blit(self.bullet, bullet_rect) # PyGame Main Loop pygame.init() window = pygame.display.set_mode((500, 500)) clock = pygame.time.Clock() bullets = [] # List to store bullet objects while True: clock.tick(60) # Set desired frame rate for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: # Create a new bullet and add it to the list bullets.append(Bullet(*pygame.mouse.get_pos())) # Update and draw bullets for bullet in bullets[:]: bullet.update() if not window.get_rect().collidepoint(bullet.pos): # Remove bullets that leave the window boundary bullets.remove(bullet) else: # Draw bullet at its current position bullet.draw(window) # Render the updated display pygame.display.update()</code>
以上是如何在 PyGame 中让子弹跟随鼠标光标?的详细内容。更多信息请关注PHP中文网其他相关文章!