在 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中文網其他相關文章!