2013-11-24 4 views
0

Я пытаюсь найти способ получить вращение корабля и применить его к лучу, чтобы он двигался в том направлении, в котором оно было снято. Я действительно не знаю, как бы я сделайте это, но вот мой код: Пожалуйста, извините беспорядок, я помещаю комментарии, чтобы вы знали, что.Пулевые движения Python - Pygame

import sys, pygame, math, time; 
from pygame.locals import *; 
spaceship = ('spaceship.png') 
mouse_c = ('crosshair.png') 
backg = ('background.jpg') 
fire_beam = ('beams.png') 
pygame.init() 
screen = pygame.display.set_mode((800, 600)) 
bk = pygame.image.load(backg).convert_alpha() 
mousec = pygame.image.load(mouse_c).convert_alpha() 
space_ship = pygame.image.load(spaceship).convert_alpha() 
f_beam = pygame.image.load(fire_beam).convert_alpha() 
f_beam = pygame.transform.scale(f_beam, (50, 50)) 
f_beam_rect = f_beam.get_rect() 
clock = pygame.time.Clock() 
pygame.mouse.set_visible(False) 
space_ship_rect = space_ship.get_rect() 
space_ship_rect.centerx = 375 
space_ship_rect.centery = 300 
speed = 3.5 
pressed_down = 0 
while True: 
    clock.tick(60) 
    screen.blit(bk, (0, 0)) 
    for event in pygame.event.get(): 
     if event.type == QUIT: 
      pygame.quit() 
      sys.exit() 
     elif event.type == MOUSEBUTTONDOWN and event.button == 3: 
      pressed_down = 1 
     elif event.type == MOUSEBUTTONUP: 
      pressed_down = 0 
     if pressed_down == 1: 
      x, y = pygame.mouse.get_pos() 
      x1, y1 = x - space_ship_rect.x, y - space_ship_rect.y 
      angle = math.atan2(y1, x1) 
      dx = speed*math.cos(angle) 
      dy = speed*math.sin(angle) 
      movex = space_ship_rect.centerx = space_ship_rect.centerx + dx#ship x 
      movey = space_ship_rect.centery = space_ship_rect.centery + dy#ship y 
     if event.type == MOUSEMOTION: 
      x1, y1 = pygame.mouse.get_pos() 
      x2, y2 = space_ship_rect.x, space_ship_rect.y 
      dx, dy = x2 - x1, y2 - y1 
      rads = math.atan2(dx, dy) 
      degs = math.degrees(rads) 
      display_s = pygame.transform.rotate(space_ship, (degs))#rotation of ship 
     if event.type == MOUSEBUTTONDOWN and event.button == 1: 
      #Is it possible for me to get the degree rotation of the space_ship and apply it to here so the beam will travel in the direction it was shot in? 
    screen.blit(display_s, (space_ship_rect.centerx, space_ship_rect.centery)) 
    pos = pygame.mouse.get_pos() 
    screen.blit(mousec, (pos)) 
    pygame.display.update() 
+0

Пожалуйста, проверьте отступы перед публикацией коды (Python ГКА.) Я отформатированный код, но я хочу, чтобы обеспечить его. – adil

+0

Вы имеете в виду, что «лазерный луч» уволен с космического корабля, и вы хотите стрелять лучом в направлении, в котором ориентирован космический корабль? – adil

+0

@adil Да, отступ теперь прав, сожалею об этом, и да, это то, что я ищу adil :) – user2993584

ответ

2

У меня проблемы с вращением корабля.

Если вы создаете повернутый космический корабль display_s вы получаете изображение с различными размерами, чем space_ship размера, так что вы должны получить display_s прямоугольник и назначить космический корабль center для display_s центра.

display_s_rect = display_s.get_rect(center=spaceship_rect.center) 

Теперь вы должны использовать display_s_rect для отображения display_s

screen.blit(display_s, display_s_rect) 

Кстати:

blit() ожидать позиции, где поставить левый верхний угол blited изображения на экране.

С

screen.blit(display_s, (space_ship_rect.centerx, space_ship_rect.centery)) 

левом верхнем углу display_s будет поставлен в (space_ship_rect.centerx, space_ship_rect.centery), но я думаю, что вы хотите поставить display_s центр в (space_ship_rect.centerx, space_ship_rect.centery)

значений Присвоить центра (как раньше), чтобы (space_ship_rect.centerx, space_ship_rect.centery) но использовать (space_ship_rect.x, space_ship_rect.y) в blit().

Вы можете использовать space_ship_rect вместо (space_ship_rect.x, space_ship_rect.y) в blit() с тем же результатом.


Я думаю, что у вас есть такая же проблема с mousec позиции в blit().

Получить прямоугольник mousec, назначить положение мыши центру прямоугольника и использовать прямоугольник x, y для blit.

mousec_rect = mousec.get_rect(center = pygame.mouse.get_pos()) 
screen.blit(mousec, mousec_rect) 

EDIT:

ваш MainLoop после моей модификации - теперь корабль поворачивает, как должно

display_s = space_ship # default value at start when ship wasn't rotate 

while True: 
    clock.tick(60) 
    screen.blit(bk, (0, 0)) 
    for event in pygame.event.get(): 
     if event.type == QUIT: 
      pygame.quit() 
      sys.exit() 
     elif event.type == MOUSEBUTTONDOWN and event.button == 3: 
      pressed_down = 1 
     elif event.type == MOUSEBUTTONUP: 
      pressed_down = 0 
     if pressed_down == 1: 
      x, y = pygame.mouse.get_pos() 
      x1, y1 = x - space_ship_rect.x, y - space_ship_rect.y 
      angle = math.atan2(y1, x1) 
      dx = speed*math.cos(angle) 
      dy = speed*math.sin(angle) 
      movex = space_ship_rect.centerx = space_ship_rect.centerx + dx#ship x 
      movey = space_ship_rect.centery = space_ship_rect.centery + dy#ship y 
     if event.type == MOUSEMOTION: 
      x1, y1 = pygame.mouse.get_pos() 
      x2, y2 = space_ship_rect.centerx, space_ship_rect.centery 
      dx, dy = x2 - x1, y2 - y1 
      rads = math.atan2(dx, dy) 
      degs = math.degrees(rads) 

      display_s = pygame.transform.rotate(space_ship, (degs))#rotation of ship 
      display_s_rect = display_s.get_rect(center = space_ship_rect.center)    

     if event.type == MOUSEBUTTONDOWN and event.button == 1: 
      #Is it possible for me to get the degree rotation of the space_ship and apply it to here so the beam will travel in the direction it was shot in? 
      pass 

    screen.blit(display_s, display_s_rect) 
    #screen.blit(display_s, space_ship_rect) 

    pos = pygame.mouse.get_pos() 
    mousec_rect = mousec.get_rect(centerx=pos[0], centery=pos[1]) 

    screen.blit(mousec, mousec_rect) 

    pygame.display.update() 
0

Перед While Loop:
beam_speed=<somevalue>
f_beam_rect=space_ship_rect #initialise beam position
fired=False #check if beam is fired or not

Внутри While Loop

##If beam is fired(right click) blit images through-out the path 
if fired: 
    b_angle = math.atan2(by1, bx1) 
    bdx = beam_speed*math.cos(b_angle) 
    bdy = beam_speed*math.sin(b_angle) 
    f_beam_rect.centerx = f_beam_rect.centerx + bdx 
    f_beam_rect.centery = f_beam_rect.centery + bdy 
    screen.blit(f_beam,f_beam_rect) 

for event in pygame.event.get(): 

    if event.type == QUIT: 
     pygame.quit() 
     sys.exit() 

###If mouse is clicked then find the direction (mouse position and spaceship) 

    elif event.type == MOUSEBUTTONDOWN and event.button == 1: 
     bx, by = pygame.mouse.get_pos() 
     bx1, by1 = bx - space_ship_rect.x, by - space_ship_rect.y 
     fired=True 

Теперь вы можете создать функцию, которая проверяет, что луч сталкивается с вражескими объектами, и если правда, то остановить блиттинг как луч и этот объект.
сброс также переменную fired=False и сброс положения луча начать с космического корабля снова f_beam_rect=space_ship_rect

Смежные вопросы