회전하는 스프라이트로 사각형을 회전시키는 방법

창 남자

그래서 사각형 / 발사체 회전 에이 문제가 발생했습니다. 사각형 / 발사체가 회전하는 스프라이트와 함께 회전하도록하고 싶지만 내가 시도하는 코드가 작동하지 않습니다. 이 오류가 발생합니다. 'pygame.Surface' object has no attribute 'x'코드 이동을 시도했고 코드를 변경하여 더 이상 오류가 발생하지 않도록 시도했으며 히트 박스를 사용해 보았지만 여전히 오류가 발생합니다. 이것은 내 두 스프라이트입니다

여기에 이미지 설명 입력 여기에 이미지 설명 입력

내가 시도하고있는 코드

        self.dist = 100
        dx = self.pin.x + self.dist*math.cos(-self.pin.angle*(math.pi/180)) -65 # why offset needed ?
        dy = self.pin.y + self.dist*math.sin(-self.pin.angle*(math.pi/180)) -50 # why offset needed ?
        self.rect.topleft = (dx,dy)
        pygame.draw.rect(window,self.color,self.rect)

내 전체 코드

import pygame,math,random
pygame.init()

# Windowing screen width and height
width = 500
height = 500
window = pygame.display.set_mode((width,height))

# Name of window
pygame.display.set_caption("Game")

# The Background
background = pygame.image.load("img/BG.png")


def blitRotate(surf, image, pos, originPos, angle):

    # calcaulate the axis aligned bounding box of the rotated image
    w, h         = image.get_size()
    sin_a, cos_a = math.sin(math.radians(angle)), math.cos(math.radians(angle)) 
    min_x, min_y = min([0, sin_a*h, cos_a*w, sin_a*h + cos_a*w]), max([0, sin_a*w, -cos_a*h, sin_a*w - cos_a*h])

    # calculate the translation of the pivot 
    pivot        = pygame.math.Vector2(originPos[0], -originPos[1])
    pivot_rotate = pivot.rotate(angle)
    pivot_move   = pivot_rotate - pivot

    # calculate the upper left origin of the rotated image
    origin = (pos[0] - originPos[0] + min_x - pivot_move[0], pos[1] - originPos[1] - min_y + pivot_move[1])

    # get a rotated image
    rotated_image = pygame.transform.rotate(image, angle)

    # rotate and blit the image
    surf.blit(rotated_image, origin)
    
# Player class
class Player:
    def __init__(self,x,y,width,height,color):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.color = color
        self.speed = 4
        self.cannon = pygame.image.load("img/Cannon.png")
        self.cannon = pygame.transform.scale(self.cannon,(self.cannon.get_width()//2, self.cannon.get_height()//2))
        self.rect = pygame.Rect(x,y,width,height)
        self.hitbox = (self.x,self.y,30,30)
        self.image = self.cannon
        self.rect  = self.image.get_rect(center = (self.x, self.y))
        self.look_at_pos = (self.x, self.y)

        self.isLookingAtPlayer = False
        self.look_at_pos = (x,y)

        self.angle = 0
    def get_rect(self):
        self.rect.topleft = (self.x,self.y)
        return self.rect
    def draw(self):
        self.rect.topleft = (self.x,self.y)
        pygame.draw.rect(window,self.color,self.hitbox)
    
        player_rect = self.cannon.get_rect(center = self.get_rect().center)
        player_rect.centerx -= 0
        player_rect.centery += 90
    
        # Another part of cannon rotating     
        dx = self.look_at_pos[0] - self.rect.centerx
        dy = self.look_at_pos[1] - self.rect.centery 
        
        angle = (180/math.pi) * math.atan2(-dy, dx) - 90
  
        gun_size = self.image.get_size()
        pivot_abs = player_rect.centerx, player_rect.top + 13
        pivot_rel = (gun_size[0] // 2, 105)
        
        pygame.draw.rect(window,self.color,self.rect)
        blitRotate(window, self.image,pivot_abs, pivot_rel, angle)

        
    def lookAt( self, coordinate ):
        self.look_at_pos = coordinate


        

# Players gun
class projectile(object):
    def __init__(self,x,y,dirx,diry,color):
        self.x = x
        self.y = y
        self.dirx = dirx
        self.diry = diry
        self.pin = pygame.image.load("img/Pin.png")
        self.pin = pygame.transform.scale(self.pin,(self.pin.get_width()//6, self.pin.get_height()//6))
        self.rect = self.pin.get_rect()
        self.topleft = ( self.x, self.y )
        self.speed = 10
        self.color = color
        self.hitbox = (self.x + 20, self.y, 30,40)
    def move(self):
        self.x += self.dirx * self.speed
        self.y += self.diry * self.speed
    def draw(self):
        self.rect.topleft = (round(self.x), round(self.y))
        
        window.blit(self.pin,self.rect)
        self.hitbox = (self.x + 20, self.y,30,30)

       # For rotating the the projectile
        self.dist = 100
        dx = self.pin.x + self.dist*math.cos(-self.pin.angle*(math.pi/180)) -65 # why offset needed ?
        dy = self.pin.y + self.dist*math.sin(-self.pin.angle*(math.pi/180)) -50 # why offset needed ?
        self.rect.topleft = (dx,dy)
        pygame.draw.rect(window,self.color,self.rect)


        


# The color white
white = (255,255,255)

# The xy cords, width, height and color of my classes[]

playerman = Player(350,385,34,75,white)



# This is where my balloons get hit by the bullet and disappers
# redrawing window
def redrawwindow():
    window.fill((0,0,0))

    # Drawing the window in
    window.blit(background,(0,0))

    # drawing the player in window
    playerman.draw()

    # Drawing the players bullet
    for bullet in bullets:
        bullet.draw()

# Frames for game
fps = 30
clock = pygame.time.Clock()
#projectile empty list
bullets = []
# main loop
run = True
while run:
    clock.tick(fps)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False


        if event.type == pygame.MOUSEBUTTONDOWN:

            if len(bullets) < 6700:
                mousex , mousey = pygame.mouse.get_pos()
                start_x , start_y = playerman.rect.x + 12, playerman.rect.y - 3
                mouse_x , mouse_y = event.pos
                dir_x , dir_y = mouse_x - start_x , mouse_y - start_y
                distance = math.sqrt(dir_x**2 + dir_y**2)
                if distance > 0:
                    new_bullet = projectile(start_x, start_y, dir_x/distance , dir_y/distance, (0,0,0))
                    bullets.append(new_bullet)

    for bullet in bullets[:]:
        bullet.move()
        if bullet.x < 0 or bullet.x > 900 or bullet.y < 0 or bullet.y > 900:
            bullets.pop(bullets.index(bullet))

    # gun rotation
    mousex, mousey = pygame.mouse.get_pos()
    if not playerman.isLookingAtPlayer:
        playerman.lookAt((mousex, mousey))

   
                    
    # telling game that key means when a key get pressed
    keys = pygame.key.get_pressed()

    # The player moving when the key a is pressed
    if keys[pygame.K_a] and playerman.x > playerman.speed:
        playerman.x -= playerman.speed

    # The player moving when the key d is pressed
    if keys[pygame.K_d] and playerman.x < 500 - playerman.width - playerman.speed:
        playerman.x += playerman.speed

    # Calling the redraw function
    redrawwindow()
    # updating game
    pygame.display.update()
# quiting the game
pygame.quit()


Rabbid76

projectile.move메서드 에서 이미 핀을 이동하고 있습니다. projectile.draw방법 에서는 핀을 회전하기 만하면됩니다. PyGame을 사용하여 이미지를 중심으로 회전하는 방법을 참조하십시오 . 방법 마우스 방향에 이미지 (플레이어) 회전? :


class projectile(object):
    # [...]

    def draw(self):
        self.rect.center = (round(self.x), round(self.y))
        
        angle = math.degrees(math.atan2(-self.diry, self.dirx)) - 90
        rotated_pin = pygame.transform.rotate(self.pin, angle)
        rotated_rect = rotated_pin.get_rect(center = self.rect.center)

        pygame.draw.rect(window,self.color, rotated_rect)
        window.blit(rotated_pin, rotated_rect)
        self.hitbox = (self.x + 20, self.y,30,30)

핀의 시작 위치를 찾아야합니다. 핀은 송풍관 상단에서 시작해야합니다. 클래스에 get_pivot메서드를 추가합니다 Player.

class Player:
    # [...]

    def get_pivot(self):
        player_rect = self.cannon.get_rect(center = self.get_rect().center)
        return player_rect.centerx, player_rect.top + 103

get_angle블로우 파이프의 각도를 계산 하는 방법을 추가합니다 .

class Player:
    # [...]

    def get_angle(self):
        pivot_abs = self.get_pivot()
        dx = self.look_at_pos[0] - pivot_abs[0]
        dy = self.look_at_pos[1] - pivot_abs[1]
        return math.degrees(math.atan2(-dy, dx))

이 방법을 사용하여 블로우 파이프의 상단을 계산합니다.

class Player:
    # [...]

    def get_top(self):
        pivot_x, pivot_y = self.get_pivot()
        angle = self.get_angle()
        length = 100
        top_x = pivot_x + length * math.cos(math.radians(angle))
        top_y = pivot_y - length * math.sin(math.radians(angle))
        return top_x, top_y

메서드에서 get_pivotget_angle메서드를 사용할 수도 있습니다 draw.

class Player:
    # [...]

    def draw(self):
        self.rect.topleft = (self.x,self.y)
        pygame.draw.rect(window,self.color,self.hitbox)

        gun_size = self.image.get_size()
        pivot_abs = self.get_pivot()
        pivot_rel = (gun_size[0] // 2, 105)
        angle = self.get_angle() - 90
        
        pygame.draw.rect(window,self.color,self.rect)
        blitRotate(window, self.image,pivot_abs, pivot_rel, angle)

get_top핀의 시작 위치를 설정하는 데 사용 합니다.

mousex, mousey = pygame.mouse.get_pos()
start_x, start_y = playerman.get_top()
mouse_x, mouse_y = event.pos
dir_x, dir_y = mouse_x - start_x , mouse_y - start_y
distance = math.sqrt(dir_x**2 + dir_y**2)
if distance > 0:
    new_bullet = projectile(start_x, start_y, dir_x/distance, dir_y/distance, (0,0,0))
    bullets.append(new_bullet)

블로우 파이프 앞에 핀을 그려서 블로우 파이프에서 핀이 나오는 것처럼 보이게합니다.

def redrawwindow():
    window.fill((0,0,0))

    # Drawing the window in
    window.blit(background,(0,0))

    # Drawing the players bullet
    for bullet in bullets:
        bullet.draw()

    # drawing the player in window
    playerman.draw()

완전한 예 :

import pygame,math,random
pygame.init()

# Windowing screen width and height
width = 500
height = 500
window = pygame.display.set_mode((width,height))

# Name of window
pygame.display.set_caption("Game")

# The Background
background = pygame.image.load("img/BG.png")


def blitRotate(surf, image, pos, originPos, angle):

    # calcaulate the axis aligned bounding box of the rotated image
    w, h         = image.get_size()
    sin_a, cos_a = math.sin(math.radians(angle)), math.cos(math.radians(angle)) 
    min_x, min_y = min([0, sin_a*h, cos_a*w, sin_a*h + cos_a*w]), max([0, sin_a*w, -cos_a*h, sin_a*w - cos_a*h])

    # calculate the translation of the pivot 
    pivot        = pygame.math.Vector2(originPos[0], -originPos[1])
    pivot_rotate = pivot.rotate(angle)
    pivot_move   = pivot_rotate - pivot

    # calculate the upper left origin of the rotated image
    origin = (pos[0] - originPos[0] + min_x - pivot_move[0], pos[1] - originPos[1] - min_y + pivot_move[1])

    # get a rotated image
    rotated_image = pygame.transform.rotate(image, angle)

    # rotate and blit the image
    surf.blit(rotated_image, origin)
    
# Player class
class Player:
    def __init__(self,x,y,width,height,color):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.color = color
        self.speed = 4
        self.cannon = pygame.image.load("img/Cannon.png")
        self.cannon = pygame.transform.scale(self.cannon,(self.cannon.get_width()//2, self.cannon.get_height()//2))
        self.rect = pygame.Rect(x,y,width,height)
        self.hitbox = (self.x,self.y,30,30)
        self.image = self.cannon
        self.rect  = self.image.get_rect(center = (self.x, self.y))
        self.look_at_pos = (self.x, self.y)

        self.isLookingAtPlayer = False
        self.look_at_pos = (x,y)

        self.angle = 0
    def get_rect(self):
        self.rect.topleft = (self.x,self.y)
        return self.rect

    def get_pivot(self):
        player_rect = self.cannon.get_rect(center = self.get_rect().center)
        return player_rect.centerx, player_rect.top + 103

    def get_angle(self):
        pivot_abs = self.get_pivot()
        dx = self.look_at_pos[0] - pivot_abs[0]
        dy = self.look_at_pos[1] - pivot_abs[1]
        return math.degrees(math.atan2(-dy, dx))

    def get_top(self):
        pivot_x, pivot_y = self.get_pivot()
        angle = self.get_angle()
        length = 100
        top_x = pivot_x + length * math.cos(math.radians(angle))
        top_y = pivot_y - length * math.sin(math.radians(angle))
        return top_x, top_y

    def draw(self):
        self.rect.topleft = (self.x,self.y)
        pygame.draw.rect(window,self.color,self.hitbox)

        gun_size = self.image.get_size()
        pivot_abs = self.get_pivot()
        pivot_rel = (gun_size[0] // 2, 105)
        angle = self.get_angle() - 90
        
        pygame.draw.rect(window,self.color,self.rect)
        blitRotate(window, self.image,pivot_abs, pivot_rel, angle)
        
    def lookAt( self, coordinate ):
        self.look_at_pos = coordinate


        

# Players gun
class projectile(object):
    def __init__(self,x,y,dirx,diry,color):
        self.x = x
        self.y = y
        self.dirx = dirx
        self.diry = diry
        self.pin = pygame.image.load("img/Pin.png")
        self.pin = pygame.transform.scale(self.pin,(self.pin.get_width()//6, self.pin.get_height()//6))
        self.rect = self.pin.get_rect()
        self.center = ( self.x, self.y )
        self.speed = 10
        self.color = color
        self.hitbox = (self.x + 20, self.y, 30,40)
    def move(self):
        self.x += self.dirx * self.speed
        self.y += self.diry * self.speed
    def draw(self):
        self.rect.center = (round(self.x), round(self.y))
        
        angle = math.degrees(math.atan2(-self.diry, self.dirx)) - 90
        rotated_pin = pygame.transform.rotate(self.pin, angle)
        rotated_rect = rotated_pin.get_rect(center = self.rect.center)

        pygame.draw.rect(window,self.color, rotated_rect)
        window.blit(rotated_pin, rotated_rect)
        self.hitbox = (self.x + 20, self.y,30,30)
        


# The color white
white = (255,255,255)

# The xy cords, width, height and color of my classes[]

playerman = Player(350,385,34,75,white)



# This is where my balloons get hit by the bullet and disappers
# redrawing window
def redrawwindow():
    window.fill((0,0,0))

    # Drawing the window in
    window.blit(background,(0,0))

    # Drawing the players bullet
    for bullet in bullets:
        bullet.draw()

    # drawing the player in window
    playerman.draw()

# Frames for game
fps = 30
clock = pygame.time.Clock()
#projectile empty list
bullets = []
# main loop
run = True
while run:
    clock.tick(fps)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False


        if event.type == pygame.MOUSEBUTTONDOWN:

            if len(bullets) < 6700:
                mousex, mousey = pygame.mouse.get_pos()
                start_x, start_y = playerman.get_top()
                mouse_x, mouse_y = event.pos
                dir_x, dir_y = mouse_x - start_x , mouse_y - start_y
                distance = math.sqrt(dir_x**2 + dir_y**2)
                if distance > 0:
                    new_bullet = projectile(start_x, start_y, dir_x/distance, dir_y/distance, (0,0,0))
                    bullets.append(new_bullet)

    for bullet in bullets[:]:
        bullet.move()
        if bullet.x < 0 or bullet.x > 900 or bullet.y < 0 or bullet.y > 900:
            bullets.pop(bullets.index(bullet))

    # gun rotation
    mousex, mousey = pygame.mouse.get_pos()
    if not playerman.isLookingAtPlayer:
        playerman.lookAt((mousex, mousey))

   
                    
    # telling game that key means when a key get pressed
    keys = pygame.key.get_pressed()

    # The player moving when the key a is pressed
    if keys[pygame.K_a] and playerman.x > playerman.speed:
        playerman.x -= playerman.speed

    # The player moving when the key d is pressed
    if keys[pygame.K_d] and playerman.x < 500 - playerman.width - playerman.speed:
        playerman.x += playerman.speed

    # Calling the redraw function
    redrawwindow()
    # updating game
    pygame.display.update()
# quiting the game
pygame.quit()

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

내 하드 드라이브를 회전시키는 프로그램을 추적하는 방법

분류에서Dev

내 하드 드라이브를 회전시키는 프로그램을 추적하는 방법

분류에서Dev

Modern OpenGL 및 Python으로 삼각형을 회전하는 방법

분류에서Dev

다각형을 회전하는 방법?

분류에서Dev

아이콘을 회전시키는 방법

분류에서Dev

D3을 사용하여 가상 휠 애니메이션, 현실적으로 회전시키는 방법?

분류에서Dev

OpenCV로 불규칙한 직사각형을 올바르게 회전하는 방법은 무엇입니까?

분류에서Dev

회전중인 다각형 쌍 사이의 충돌을 투영하는 방법은 무엇입니까?

분류에서Dev

회전하는 직사각형을 더 작은 직사각형으로 분할하면 원래의 큰 직사각형을 유지하기 위해 회전하는 방법은 무엇입니까?

분류에서Dev

cocos2d에서 스프라이트 회전을 테스트하는 방법

분류에서Dev

변형으로 모양을 회전하는 방법

분류에서Dev

Quaternion을 사용하여 Unity로 회전 각도를 늘리는 방법

분류에서Dev

gsap 회전-날카로운 전환을 피하는 방법

분류에서Dev

UILabel을 전체적으로 회전하는 방법

분류에서Dev

CSS를 사용하여 텍스트를 회전하는 방법

분류에서Dev

로그 회전 변경 사항을 적용하는 방법

분류에서Dev

두 점 사이의 각도를 계산하고 세 번째 점을 회전시키는 방법은 무엇입니까?

분류에서Dev

사이드 바에서 위젯을 회전하는 방법

분류에서Dev

회전하는 삼각형 스프라이트 안에 히트 박스를 중앙에 배치하는 방법은 무엇입니까?

분류에서Dev

원형 경로에서 이미지를 회전하는 방법

분류에서Dev

CSS 큐브를 각각 회전시키는 방법

분류에서Dev

회전 변경 UIImageView 프레임. 이것을 피하는 방법?

분류에서Dev

뷰 매트릭스에서 회전을 제거하는 방법

분류에서Dev

사용자 터치 좌표를 기준으로 스프라이트 킷을 사용하여 회전하는 방법

분류에서Dev

flast에있는 물체를 회전 각도로 이동시키는 방법은 무엇입니까?

분류에서Dev

JNA-시스템 기능을 호출하는 방법? (회전, 화면 꺼짐)

분류에서Dev

회전 값을 높이는 방법

분류에서Dev

자바에서 동전을 회전시키는 것처럼 이미지 회전

분류에서Dev

클릭시 햄버거 메뉴 아이콘을 회전하는 방법

Related 관련 기사

  1. 1

    내 하드 드라이브를 회전시키는 프로그램을 추적하는 방법

  2. 2

    내 하드 드라이브를 회전시키는 프로그램을 추적하는 방법

  3. 3

    Modern OpenGL 및 Python으로 삼각형을 회전하는 방법

  4. 4

    다각형을 회전하는 방법?

  5. 5

    아이콘을 회전시키는 방법

  6. 6

    D3을 사용하여 가상 휠 애니메이션, 현실적으로 회전시키는 방법?

  7. 7

    OpenCV로 불규칙한 직사각형을 올바르게 회전하는 방법은 무엇입니까?

  8. 8

    회전중인 다각형 쌍 사이의 충돌을 투영하는 방법은 무엇입니까?

  9. 9

    회전하는 직사각형을 더 작은 직사각형으로 분할하면 원래의 큰 직사각형을 유지하기 위해 회전하는 방법은 무엇입니까?

  10. 10

    cocos2d에서 스프라이트 회전을 테스트하는 방법

  11. 11

    변형으로 모양을 회전하는 방법

  12. 12

    Quaternion을 사용하여 Unity로 회전 각도를 늘리는 방법

  13. 13

    gsap 회전-날카로운 전환을 피하는 방법

  14. 14

    UILabel을 전체적으로 회전하는 방법

  15. 15

    CSS를 사용하여 텍스트를 회전하는 방법

  16. 16

    로그 회전 변경 사항을 적용하는 방법

  17. 17

    두 점 사이의 각도를 계산하고 세 번째 점을 회전시키는 방법은 무엇입니까?

  18. 18

    사이드 바에서 위젯을 회전하는 방법

  19. 19

    회전하는 삼각형 스프라이트 안에 히트 박스를 중앙에 배치하는 방법은 무엇입니까?

  20. 20

    원형 경로에서 이미지를 회전하는 방법

  21. 21

    CSS 큐브를 각각 회전시키는 방법

  22. 22

    회전 변경 UIImageView 프레임. 이것을 피하는 방법?

  23. 23

    뷰 매트릭스에서 회전을 제거하는 방법

  24. 24

    사용자 터치 좌표를 기준으로 스프라이트 킷을 사용하여 회전하는 방법

  25. 25

    flast에있는 물체를 회전 각도로 이동시키는 방법은 무엇입니까?

  26. 26

    JNA-시스템 기능을 호출하는 방법? (회전, 화면 꺼짐)

  27. 27

    회전 값을 높이는 방법

  28. 28

    자바에서 동전을 회전시키는 것처럼 이미지 회전

  29. 29

    클릭시 햄버거 메뉴 아이콘을 회전하는 방법

뜨겁다태그

보관