」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在 Pygame 中向滑鼠方向發射子彈?

如何在 Pygame 中向滑鼠方向發射子彈?

發佈於2024-11-07
瀏覽:462

How to shoot a bullet in the direction of the mouse in Pygame?

如何在 Pygame 中朝滑鼠方向發射子彈

在 Pygame 中,可以創建一顆朝滑鼠方向發射的子彈。為此,需要建立一個代表子彈的類,並根據滑鼠位置設定其初始位置和方向。

子彈的類別

首先,為項目符號建立一個類別。該類別應包含子彈的位置、大小和表面的屬性。表面就是將在螢幕上渲染的內容。

import pygame

class Bullet:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.height = 7
        self.width = 2
        self.bullet = pygame.Surface((self.width, self.height))
        self.bullet.fill((255, 255, 255))

遊戲類別函數

接下來,為遊戲建立一個類別。該類別將包含射擊和生成子彈的函數。

class Game:
    def __init__(self):
        self.bullets = []
    
    def shoot_bullet(self):
        mouse_x, mouse_y = pygame.mouse.get_pos() # Get the mouse position
        for bullet in self.bullets:
            rise = mouse_y - bullet.y # Calculate the difference between mouse and bullet y position
            run = mouse_x - bullet.x # Calculate the difference between mouse and bullet x position
            angle = math.atan2(rise, run) # Calculate the angle between mouse and bullet

            bullet.x  = math.cos(angle) * 10 # Update bullet x position
            bullet.y  = math.sin(angle) * 10 # Update bullet y position

            # Rotate and draw the bullet
            rotated_bullet = pygame.transform.rotate(bullet.bullet, -math.degrees(angle))
            screen.blit(rotated_bullet, (bullet.x, bullet.y))

    def generate_bullet(self):
        mouse_buttons = pygame.mouse.get_pressed() # Check if mouse is clicked
        if mouse_buttons[0]: # If left mouse button is clicked
            self.bullets.append(Bullet(player.x, player.y)) # Create a new bullet

使用Bullet Class

在主遊戲循環中,建立Game 類別的實例並呼叫shoot_bullet 和generate_bullet 函數。

game = Game()

while running:
    # Event handling

    # Update
    game.shoot_bullet()
    game.generate_bullet()
    
    # Draw
    screen.fill((0, 0, 0))
    for bullet in game.bullets:
        screen.blit(bullet.bullet, (bullet.x, bullet.y))
    pygame.display.update()

此程式碼將建立一個朝滑鼠方向發射的子彈。子彈會移動直到離開螢幕。

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3