"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > 플레이어가 보이게 유지하면서 게임에서 총알을 촬영하는 방법은 무엇입니까?

플레이어가 보이게 유지하면서 게임에서 총알을 촬영하는 방법은 무엇입니까?

2025-02-22에 게시되었습니다
검색:751

How to Make a Player Shoot Bullets in a Game While Keeping the Player Visible?

문제와 솔루션

Asker의 코드는 처음에는 촬영할 때 플레이어 캐릭터가 사라지는 문제가있었습니다. 촬영과 플레이어 움직임이 다른 루프로 분리 되었기 때문입니다. 이를 해결하기 위해서는 두 동작이 동시에 업데이트되는 단일 기본 루프로 결합해야합니다.

또 다른 문제는 총알이 화면 상단에 도달했을 때 촬영 루프를 깨뜨릴 수 없다는 것이 었습니다. 원래 코드는 무한히 계속 된 while 루프를 사용했습니다. 이 문제를 해결하려면 총알이 최상위에 도달했는지 확인하는 조건이있는 while 루프를 사용해야합니다.

코드 설명

코드의 수정 된 버전은 다음과 같습니다.

[

import pygame, os # 보일러 플레이트 설정은 간결하게 생략되었습니다 클래스 플레이어 : def __init __ (자체, X, Y, 높이, 너비) : ... def draw (self) : ... def move_left (self) : ... def move_right (self) : ... 클래스 총알 : def __init __ (self, x, y) : ... def update (self) : ... def draw (self) : ... # 총알 목록 총알 = [] # 플레이어 초기화 P = 플레이어 (600, 500, 50, 30) # 메인 게임 루프 run = true 실행 중 : clock.tick (100) # 이벤트 처리 pygame.event.get ()의 이벤트 : event.type == pygame.quit : run = false event.type == pygame.keydown 인 경우 : If event.key == pygame.k_space : Bullets.Append (Bullet (p.x p.width // 2, p.y))) # 개체 업데이트 키 = pygame.key.get_pressed () Keys [pygame.k_left] : p.move_left () Keys [pygame.k_right] 인 경우 : p.move_right () 총알의 B의 경우 : b.update () # 스크린 오프 스크린이 발생하면 포지션 업데이트 및 총알 제거 B.y & lt; 0 : 총알. # 프레임 업데이트 D.Fill ((98, 98, 98)) 총알의 B의 경우 : B.Draw () P.Draw () win.update ()

키 변경 :
import pygame, os

# Boilerplate setup omitted for brevity

class Player:
    def __init__(self, x, y, height, width):
        ...

    def draw(self):
        ...

    def move_left(self):
        ...

    def move_right(self):
        ...


class Bullet:
    def __init__(self, x, y):
        ...

    def update(self):
        ...

    def draw(self):
        ...


# Lists of bullets
bullets = []

# Initialize player
p = Player(600, 500, 50, 30)

# Main game loop
run = True
while run:
    clock.tick(100)
    
    # Handle events
    for event in pygame.event.get():
        if event.type ==  pygame.QUIT:
            run = False
        if event.type ==  pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                bullets.append(Bullet(p.x p.width//2, p.y))

    # Update objects
    keys = pygame.key.get_pressed()        
    if keys[pygame.K_LEFT]:
        p.move_left()
    if keys[pygame.K_RIGHT]:
        p.move_right()
    for b in bullets:
        b.update()
        # Update position and remove bullet if it goes off-screen
        if b.y < 0:
            bullets.remove(b)

    # Update frame
    d.fill((98, 98, 98))
    for b in bullets:
        b.draw()
    p.draw()
    win.update()
촬영 및 플레이어 움직임 로직은 이제 단일 기본 게임 루프로 결합되었습니다. 총알이 화면 밖으로 나갔는지 확인하고 그에 따라 제거합니다.

기본 루프는 연속적으로 업데이트하고 플레이어와 총알을 그립니다. 둘 다 화면에 존재하도록합니다.
최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3