2017-12-12 5 views
3

에 따라 총알을 회전하지만 지금은 선수의 머리의 회전에 총알의 출처를 회전합니다. 이제는 x 라인에서 똑바로 쏠뿐입니다. 폭도들은 잘 작동합니다. 나는 플레이어의 각도로 회전하는 총알과 충돌을 추가하기 만하면됩니다. 나는 누군가를 나에게 암시 할 수 있으면 나 자신을 충돌 할 것이다. 그것은 인정 될 것이다. 나의 주요 초점은 현재 플레이어의 각도에 따라 총알을 회전시키고 화면에서 날아갈 때 총알을 '죽이는'것입니다.은 어떻게 마지막 총알을 촬영하는 방법을 알아 냈어요 플레이어의 회전

import pygame 
import random 
import math 
GRAD = math.pi/180 

black = (0,0,0) 

class Config(object): 
    fullscreen = True 
    width = 1366 
    height = 768 
    fps = 60 

class Player(pygame.sprite.Sprite): #player class 
    maxrotate = 180 
    down = (pygame.K_DOWN) 
    up = (pygame.K_UP) 

    def __init__(self, startpos=(102,579), angle=0): 
     super().__init__() 
     self.pos = list(startpos) 
     self.image = pygame.image.load('BigShagHoofdzzz.gif') 
     self.orig_image = self.image 
     self.rect = self.image.get_rect(center=startpos) 
     self.angle = angle 

    def update(self, seconds): 
     pressedkeys = pygame.key.get_pressed() 
     if pressedkeys[self.down]: 
      self.angle -= 2 
      self.rotate_image() 
     if pressedkeys[self.up]: 
      self.angle += 2 
      self.rotate_image() 

    def rotate_image(self):#rotating player image 
     self.image = pygame.transform.rotate(self.orig_image, self.angle) 
     self.rect = self.image.get_rect(center=self.rect.center) 

class Mob(pygame.sprite.Sprite):#monster sprite 
    def __init__(self): 
     pygame.sprite.Sprite.__init__(self) 
     self.image = pygame.image.load('Monster1re.png') 
     self.rect = self.image.get_rect() 
     self.rect.x = 1400 
     self.rect.y = random.randrange(500,600) 
     self.speedy = random.randrange(-8, -1) 

    def update(self): 
     self.rect.x += self.speedy 
     if self.rect.x < -100 : 
      self.rect.x = 1400 
      self.speedy = random.randrange(-8, -1) 

class Bullet(pygame.sprite.Sprite):#bullet sprite needs to rotate according to player's angle. 
    """ This class represents the bullet . """ 
    def __init__(self): 
     # Call the parent class (Sprite) constructor 
     super().__init__() 

     self.image = pygame.image.load('lols.png').convert() 
     self.image.set_colorkey(black) 
     self.rect = self.image.get_rect() 

    def update(self): 
     """ Move the bullet. """ 
     self.rect.x += 10 



#end class 

player = Player() 

mobs = [] 
for x in range(0,10): 
    mob = Mob() 
    mobs.append(mob) 

print(mobs) 

all_sprites_list = pygame.sprite.Group() 
allgroup = pygame.sprite.LayeredUpdates() 
allgroup.add(player) 

for mob in mobs: 
    all_sprites_list.add(mob) 








def main(): 
    #game 
    pygame.mixer.pre_init(44100, -16, 1, 512) 
    pygame.mixer.init() 
    pygame.init() 
    screen=pygame.display.set_mode((Config.width, Config.height),   
    pygame.FULLSCREEN) 
    background = pygame.image.load('BGGameBig.png') 
    sound = pygame.mixer.Sound("shoot2.wav") 
    bullet_list = pygame.sprite.Group 

    clock = pygame.time.Clock() 
    FPS = Config.fps 


    mainloop = True 
    while mainloop: 
     millisecond = clock.tick(Config.fps) 

     for event in pygame.event.get(): 
      if event.type == pygame.QUIT: 
       mainloop = False 
      if event.type == pygame.KEYDOWN: 
       if event.key == pygame.K_ESCAPE: 
        mainloop = False 
       if event.key == pygame.K_SPACE: #Bullet schiet knop op space 
        bullet = Bullet() 
        bullet.rect.x = player.rect.x 
        bullet.rect.y = player.rect.y 
        all_sprites_list.add(bullet) 
        bullet_list.add(bullet) 
        sound.play() 
       if event.key == pygame.K_ESCAPE: 
        mailoop = False 


     pygame.display.set_caption("hi") 
     allgroup.update(millisecond) 
     all_sprites_list.update() 
     screen.blit(background, (0,0)) 
     allgroup.draw(screen) 
     all_sprites_list.draw(screen) 
     pygame.display.flip() 


if __name__ == '__main__': 
    main() 
    pygame.quit() 

그래서 키를 올리거나 내릴 때 업데이트되는 플레이어 self.angle에서 회전해야합니다.

+0

귀하의 질문은 무엇인가? –

+0

총알이 플레이어의 위치와 각도의 회전으로 회전하게하십시오. 그것은 지금 X에서 직선을 찍을뿐입니다. – Ectrizz

+0

삼각법이나 벡터에 대한 경험이 있습니까? – skrx

답변

2

당신은 총알 (내가 여기 삼각 사용한다)의 속도를 계산하기 위해 삼각법 또는 벡터를 사용해야합니다. 플레이어의 각도를 Bullet에 전달하고 math.cosmath.sin을 음의 각도로 사용하여 총알의 방향을 얻고 원하는 속도로 조절합니다. pygame.Rect에는 좌표로 int가있을 수 있기 때문에 실제 위치는 목록 또는 벡터에 저장해야합니다.

class Bullet(pygame.sprite.Sprite): 
    """This class represents the bullet.""" 
    def __init__(self, pos, angle): 
     super().__init__() 
     # Rotate the image. 
     self.image = pygame.transform.rotate(your_bullet_image, angle) 
     self.rect = self.image.get_rect() 
     speed = 5 # 5 pixels per frame. 
     # Use trigonometry to calculate the velocity. 
     self.velocity_x = math.cos(math.radians(-angle)) * speed 
     self.velocity_y = math.sin(math.radians(-angle)) * speed 
     # Store the actual position in a list or a vector. 
     self.pos = list(pos) 

    def update(self): 
     """ Move the bullet. """ 
     self.pos[0] += self.velocity_x 
     self.pos[1] += self.velocity_y 
     # Update the position of the rect as well. 
     self.rect.center = self.pos 


# In the event loop. 
if event.key == pygame.K_SPACE: 
    # Pass the position and angle of the player. 
    bullet = Bullet(player.rect.center, player.angle) 
    all_sprites_list.add(bullet) 
    bullet_list.add(bullet) 
+0

아, 이제 알겠습니다. 한 줄의 코드를 더 추가해야했습니다. 그 코드를 사용하면 오류가 발생합니다. 나는 코드를 추가했다 : self.image = pygame.image.load ('mypicture'). 그것은 나에게 파이 게임에 관한 에러를 내기 때문에. str이 아닌. 하지만 지금은 잘 작동합니다! 감사! 이제 나는 충돌로 나아갈 것이다 : P 그걸 알아낼 수있게하자. – Ectrizz

+0

인스턴스를 만들 때 하드 디스크에서 여러 번로드해야하기 때문에 이미지를'__init__' 메소드로로드하지 마라. 그리고 그것은 느립니다. 전역 범위 또는 다른 모듈에서 이미지를로드하고 가져 와서 프로그램에서 다시 사용하십시오. – skrx

관련 문제