자동차가 창문 가장자리에 부딪히면 움직이고 방향이 바뀝니다. [닫힘]

Nov 25 2020

차가 똑바로 움직입니다. 창 가장자리에 닿으면 뒤로 이동 한 다음 시계 방향으로 45도 각도로 방향을 바꾸고 계속 똑바로 이동합니다. 창 가장자리에 다시 닿으면 똑같이

아래 코드를 만들었습니다. 나는 차가 창문 가장자리에 닿을 때만 차를 멈췄다가 후진 할 수 있었다. 차의 방향을 바꾸고, 직진하고, 프로그램을 계속 실행하면 창문을 닫아야 만 멈출 수 있습니까?

import pygame, sys
from pygame.locals import *

def base(cX,cY):
    screen.fill(whitdull)
    pygame.draw.rect(screen,whitdull,[0,0,1050,600],4)
    
    screen.blit(text1,[150,230])
    
    # Copy image to screen:
    screen.blit(player_image, [cX,cY])
    
    pygame.display.flip()
    clock.tick(ct)


def carMovement(b0XX,b0YY,bDirection):
    sX = 5      # 5 pixel/clock  Direction right-left
    sY = 5      # 5 pixel/clock  Direction upward-downward
    
    while True:
        
        # Direction to the right
        pX = sX
        pY = 0
        
        b0XX = b0XX + pX
        b0YY = b0YY + pY
        if b0XX == 970:
            b0XX = 970 - sX
            backward(b0XX,b0YY,Direction)
            
        # Copy image to screen:
        base(b0XX,b0YY)

    return b0XX,b0YY

def backward(b0XX,b0YY,bDirection):
    sX = 5      # 5 pixel/clock  Direction right-left
    sY = 5      # 5 pixel/clock  Direction upward-downward
    
    while b0XX >= 900:
        
        # Direction to the right
        pX = sX
        pY = 0
        
        b0XX = b0XX - pX
        b0YY = b0YY - pY
        if b0XX == 900:
            b0XX = 900 + sX
            
            
        base(b0XX,b0YY)
    return b0XX, b0YY

# Initialize Pygame
pygame.init()

# Define some colors
white=(250,250,250);   whitdull=(247,247,247)
black=(70,70,70)   ;   blue =(45,127,184) 
gold  =(248,179,35);   green=(0,176,80)
yellow=(254,240,11);   gray=(208,206,206)

#Setting font-size
font1 = pygame.font.Font(None,150)

text1 = font1.render("Bom-bom  Car",True,white)


# preparing  the  screen
width = 1050 ; height = 600
screen = pygame.display.set_mode([width, height])
pygame.display.set_caption('Bom-bom Car')
screen.fill(whitdull) 


player_image = pygame.image.load("Car-2.jpeg").convert()
#rotasi = pygame.transform.rotate(player_image, -45)


#initial condition
b0X = 0; b0Y = 250; Direction = 2      # initial car position, Direction 2 = to the right

ct = 20
clock = pygame.time.Clock()


# program utama Pygame
while True:
        
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            b0X,b0Y = carMovement(b0X,b0Y,Direction)
            
    base(b0X,b0Y)
    
    # Get the current mouse position (x,y)
    player_position = pygame.mouse.get_pos()
    xm=player_position[0]
    ym=player_position[1]
       
#end program

산출

이미지 소스

답변

Rabbid76 Nov 25 2020 at 18:10

게임을 제어하기 위해 추가 루프를 구현하지 마십시오. 응용 프로그램 루프가 있습니다. 그걸 써!

pygame.math.Vector2개체를 사용 하여 플레이어의 위치와 움직임을 정의합니다. 초기 이동은 (0, 0)입니다. 플레이어의 속도를 추가로 정의하십시오.

player_pos = pygame.math.Vector2(player_image.get_width() // 2, screen.get_height() // 2)
player_move = pygame.math.Vector2(0, 0)
speed = 10

마우스를 누르 자마자 이동 방향을 정의하고 speedwith로 이동 벡터의 길이를 조정합니다 scale_to_length().

if event.type == pygame.MOUSEBUTTONDOWN:
    dx = event.pos[0] - player_pos.x
    dy = event.pos[1] - player_pos.y
    if dx != 0 or dY != 0:
        player_move = pygame.math.Vector2(dx, dy)
        player_move.scale_to_length(speed)

응용 프로그램 루프 player_move의 플레이어 ( player_pos) 위치에 모션 벡터 ( )를 더 합니다.

while True:
    # [...]

    player_pos += player_move

플레이어의 경계 사각형을 가져옵니다. 내 충돌 테스트가 항상 'true'를 반환하는 이유와 이미지의 사각형 위치가 항상 잘못된 이유 (0, 0) 를 읽는 것이 좋습니다 . :

player_rect = player_image.get_rect(center = (round(player_pos.x), round(player_pos.y)))

플레이어가 창 가장자리에 도달하면 당구 공처럼 가장자리에 플레이어를 반사 합니다. 파이 게임으로 공이 벽에서 튀어 나오게하는 방법 도 참조하십시오 . :

if player_rect.left < 0:
    player_rect.left = 0 
    player_pos.x = player_rect.centerx
    player_move.x = abs(player_move.x)
if player_rect.right > screen.get_width():
    player_rect.right = screen.get_width()
    player_pos.x = player_rect.centerx
    player_move.x = -abs(player_move.x)
if player_rect.top < 0:
    player_rect.top = 0 
    player_pos.y = player_rect.centery
    player_move.y = abs(player_move.y)
if player_rect.bottom > screen.get_height():
    player_rect.bottom = screen.get_height()
    player_pos.y = player_rect.centery
    player_move.y = -abs(player_move.y)

이동 벡터의 각도를 계산하고 플레이어를 중심을 중심으로 회전합니다. PyGame을 사용하여 이미지를 중심으로 회전하는 방법을 참조하십시오 . 및 방법 마우스 방향에 이미지 (플레이어) 회전? :

angle = player_move.angle_to((1, 0))
rotated_player = pygame.transform.rotate(player_image, angle)
rotated_rect = rotated_player.get_rect(center = player_rect.center)

마지막으로 장면을 다시 그립니다.

screen.fill(whitdull)
pygame.draw.rect(screen, whitdull,[0,0,1050,600],4)
screen.blit(text1,[150,230])
screen.blit(rotated_player, rotated_rect)
pygame.display.flip()

완전한 예 :

import pygame, sys
from pygame.locals import *

# Initialize Pygame
pygame.init()
clock = pygame.time.Clock()

# Define some colors
white=(250,250,250);   whitdull=(247,247,247)
black=(70,70,70)   ;   blue =(45,127,184) 
gold  =(248,179,35);   green=(0,176,80)
yellow=(254,240,11);   gray=(208,206,206)

#Setting font-size
font1 = pygame.font.Font(None,150)
text1 = font1.render("Bom-bom  Car",True,white)

# preparing  the  screen
width, height = 1050, 600
screen = pygame.display.set_mode([width, height])
pygame.display.set_caption('Bom-bom Car')

player_image = pygame.image.load("Car-2.jpeg").convert()

#initial condition
ct = 20
player_pos = pygame.math.Vector2(player_image.get_width() // 2, screen.get_height() // 2)
player_move = pygame.math.Vector2(0, 0)
speed = 10

# program utama Pygame
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            dx = event.pos[0] - player_pos.x
            dy = event.pos[1] - player_pos.y
            if dx != 0 or dY != 0:
                player_move = pygame.math.Vector2(dx, dy)
                player_move.scale_to_length(speed)

    player_pos += player_move
    player_rect = player_image.get_rect(center = (round(player_pos.x), round(player_pos.y)))
    if player_rect.left < 0:
       player_rect.left = 0 
       player_pos.x = player_rect.centerx
       player_move.x = abs(player_move.x)
    if player_rect.right > screen.get_width():
       player_rect.right = screen.get_width()
       player_pos.x = player_rect.centerx
       player_move.x = -abs(player_move.x)
    if player_rect.top < 0:
       player_rect.top = 0 
       player_pos.y = player_rect.centery
       player_move.y = abs(player_move.y)
    if player_rect.bottom > screen.get_height():
       player_rect.bottom = screen.get_height()
       player_pos.y = player_rect.centery
       player_move.y = -abs(player_move.y)

    angle = player_move.angle_to((1, 0))
    rotated_player = pygame.transform.rotate(player_image, angle)
    rotated_rect = rotated_player.get_rect(center = player_rect.center)
    
    screen.fill(whitdull)
    pygame.draw.rect(screen, whitdull,[0,0,1050,600],4)
    screen.blit(text1,[150,230])
    screen.blit(rotated_player, rotated_rect)    
    pygame.display.flip()
    clock.tick(ct)