在 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