【问题标题】:Need help rotating an object towards another moving object [duplicate]需要帮助将对象旋转到另一个移动对象[重复]
【发布时间】:2016-04-26 01:00:53
【问题描述】:

我制作了一个程序,其中一个对象将在屏幕上朝着您的鼠标旋转。现在我需要让它向另一个移动的物体旋转。这是我的代码:

import pygame
import math
import sys
from pygame.locals import *;
from sys import exit
pygame.init()


blk = pygame.Color(0,0,0)
BG = ('BG.png')
pygame.init()
screen = pygame.display.set_mode((800, 600))
B_G = pygame.image.load(BG).convert_alpha()
clock = pygame.time.Clock()
pygame.mouse.set_visible(False)
fpsclock = pygame.time.Clock()



class Shork(pygame.sprite.Sprite):


 def __init__(self):
  pygame.sprite.Sprite.__init__(self)
  self.image = pygame.image.load('SHORK.png')
  screen = pygame.display.get_surface()
  self.x = 62
  self.y = 50
  self.direction = "down"

 def Moving(self):

  if self.direction == "right":
   self.x += 2
  elif self.direction == "left":
   self.x -= 2
  elif self.direction == "down":
   self.y += 2
  elif self.direction == "up":
   self.y -= 2


 def Path(self):

  if self.x == 62 and self.y == 538:
   self.direction = "right"

  if self.x == 246 and self.y == 538:
   self.direction = "up"

  if self.x == 246 and self.y == 366:
   self.direction = "left"

  if self.x == 176 and self.y == 366:
   self.direction = "up"

  if self.x == 176 and self.y == 114:
   self.direction = "right"

  if self.x == 530 and self.y == 114:
   self.direction = "down"

  if self.x == 530 and self.y == 366:
   self.direction = "left"

  if self.x == 460 and self.y == 366:
   self.direction = "down"

  if self.x == 460 and self.y == 538:
   self.direction = "right"

  if self.x == 644 and self.y == 538:
   self.direction = "up"
  if self.y == 0:
   sys.exit()

Shork = Shork()

Run = True


while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == MOUSEBUTTONDOWN and event.button == 1:
            print("test1")
        elif event.type == MOUSEBUTTONDOWN and event.button == 3:
            print("test3")
    while Run:
      fpsclock.tick(60)

      for event in pygame.event.get():

       if event.type == pygame.QUIT:
          Run = False

    pos = pygame.mouse.get_pos()
    angle = 360-math.atan2(pos[1]-300,pos[0]-400)*180/math.pi
    rotimage = pygame.transform.rotate(B_G,angle)
    Shork.Moving() 
    Shork.Path()
    screen.blit(Shork.image, (Shork.x, Shork.y))
    pygame.display.update()
    rect = rotimage.get_rect(center=(400,300))
    screen.blit(rotimage,rect)
    pygame.display.update()
    screen.fill(blk)

BG 是我需要旋转的对象, SHORK 是 BG 需要旋转的对象。 代码的中间部分只是跟踪一个对象的路径。 我正在努力的代码是这样的:

pos = pygame.mouse.get_pos()
angle = 360-math.atan2(pos[1]-300,pos[0]-400)*180/math.pi
rotimage = pygame.transform.rotate(B_G,angle)
Shork.Moving() 
Shork.Path()
screen.blit(Shork.image, (Shork.x, Shork.y))
pygame.display.update()
rect = rotimage.get_rect(center=(400,300))
screen.blit(rotimage,rect)
pygame.display.update()

这目前适用于跟随鼠标,但我一生无法弄清楚如何使 BG 向 SHORK 旋转。 附言我刚开始学习python,所以请耐心等待。 :)

【问题讨论】:

    标签: python-2.7 pygame


    【解决方案1】:

    您需要更改angle 以使用Shork 的x/y 值而不是pos。您还应该在计算角度之前更新Shork 的值,所以我将Shork.MovingShork.Path 移到了块的开头。

    Shork.Moving() 
    Shork.Path()
    pos = pygame.mouse.get_pos()
    angle = 360-math.atan2(Shork.y-300,Shork.x-400)*180/math.pi
    rotimage = pygame.transform.rotate(B_G,angle)
    screen.blit(Shork.image, (Shork.x, Shork.y))
    pygame.display.update()
    rect = rotimage.get_rect(center=(400,300))
    screen.blit(rotimage,rect)
    pygame.display.update()
    

    【讨论】:

    • 天哪,它成功了。十分感谢你的帮助。几个小时以来,我一直试图弄清楚这一点。
    • 注意:这段代码可能会旋转到对象的角落(除非 Pygame 的 x/y 值是中心)
    【解决方案2】:

    如果这可能对您有所帮助,这里是我几年前在学习 Python 和 Pygame 时编写的具有多个级别的完整游戏的回购。它有旋转到任意角度的旋转宇宙飞船、转向并跟随你的敌舰、被射击(人工智能)时转向和逃跑的敌舰、小行星等。

    Space Gladiator - The Spiritual Warrior

    【讨论】:

    • 感谢您的帮助!它应该有助于理解 pygame 的工作原理。
    【解决方案3】:

    我建议使用向量。

    # To get the distance to the mouse just subtract the position vector
    # of the sprite from the mouse position.
    x, y = pg.mouse.get_pos() - self.pos
    self.angle = math.degrees(math.atan2(y, x))
    # Rotate the image (keep a copy of the original image around).
    self.image = pg.transform.rotozoom(self.orig_image, -self.angle, 1)
    self.rect = self.image.get_rect(center=self.rect.center)
    

    您还可以通过调用返回polar coordinatesas_polar 方法来获取pygame.math.Vector2 的角度。

    distance = pg.mouse.get_pos() - self.pos
    radius, self.angle = distance.as_polar()
    

    这是一个最小的工作示例,其中包含一个向鼠标旋转的移动精灵(使用“a”和“d”左右移动)。

    import sys
    import math
    
    import pygame as pg
    from pygame.math import Vector2
    
    
    pg.init()
    
    BLUEGREEN = pg.Color(0, 90, 100)
    GREEN = pg.Color('springgreen1')
    
    
    class Player(pg.sprite.Sprite):
    
        def __init__(self, x, y, *spritegroups):
            super().__init__(spritegroups)
            self.image = pg.Surface((50, 30), pg.SRCALPHA)
            pg.draw.polygon(self.image, GREEN, ((1, 1), (49, 14), (1, 29)))
            self.orig_image = self.image
            self.rect = self.image.get_rect(center=(x, y))
            self.pos = Vector2(x, y)
            self.vel = Vector2(0, 0)
            self.angle = 0
    
        def handle_event(self, event):
            if event.type == pg.KEYDOWN:
                if event.key == pg.K_a:
                    self.vel.x = -3.5
                elif event.key == pg.K_d:
                    self.vel.x = 3.5
            if event.type == pg.KEYUP:
                if event.key == pg.K_a and self.vel.x < 0:
                    self.vel.x = 0
                elif event.key == pg.K_d and self.vel.x > 0:
                    self.vel.x = 0
    
        def update(self):
            # Update the position vector by adding the velocity vector.
            self.pos += self.vel
            self.rect.center = self.pos
            # Get the distance and angle to the target.
            x, y = pg.mouse.get_pos() - self.pos
            self.angle = math.degrees(math.atan2(y, x))
            # Rotate the image (rotozoom looks better than transform.rotate).
            self.image = pg.transform.rotozoom(self.orig_image, -self.angle, 1)
            self.rect = self.image.get_rect(center=self.rect.center)
    
    
    def main():
        screen = pg.display.set_mode((640, 480))
        pg.display.set_caption('Rotation')
        clock = pg.time.Clock()
    
        sprite_group = pg.sprite.Group()
        player = Player(200, 300, sprite_group)
        done = False
    
        while not done:
            for event in pg.event.get():
                if event.type == pg.QUIT:
                    done = True
                player.handle_event(event)
    
            sprite_group.update()
    
            screen.fill(BLUEGREEN)
            sprite_group.draw(screen)
    
            pg.display.flip()
            clock.tick(30)
    
    
    if __name__ == '__main__':
        main()
        pg.quit()
        sys.exit()
    

    【讨论】:

    • 不加评论就投反对票是非常蹩脚的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    • 2016-06-13
    • 2013-07-03
    • 2012-04-03
    • 1970-01-01
    相关资源
    最近更新 更多