简体   繁体   English

使用pygame.transform.rotate()时出现奇怪的移位

[英]Weird shifting when using pygame.transform.rotate()

def rotate(self):
    #Save the original rect center
    self.saved_center=self.rect.center

    #Rotates a saved image every time to maintain quality
    self.image=pygame.transform.rotate(self.saved_image, self.angle)

    #Make new rect center the old one
    self.rect.center=self.saved_center

    self.angle+=10

When I rotate the image, there is a weird shifting of it despite the fact that I'm saving the old rect center and making the rotated rect center the old one. 当我旋转图像时,尽管我正在保存旧的矩形中心并使旋转的矩形中心成为旧的矩形中心,但仍有一种奇怪的移动。 I want it to rotate right at the center of the square. 我希望它在广场的中心旋转。

Here's what it looks like: http://i.imgur.com/g6Os9.gif 这是它的样子: http//i.imgur.com/g6Os9.gif

You are just calculating the new rect wrong. 你只是在计算新的rect错误。 Try this: 尝试这个:

def rotate(self):
    self.image=pygame.transform.rotate(self.saved_image, self.angle)
    self.rect = self.image.get_rect(center=self.rect.center)
    self.angle+=10

It tells the new rect to center itself around the original center (the center never changes here. Just keeps getting passed along). 它告诉新的矩形在原始中心周围居中(中心在这里永远不会改变。只是不断传递)。

The issue was that the self.rect was never being properly updated. 问题是self.rect从未被正确更新。 You were only changing the center value. 你只是改变了中心值。 The entire rect changes as the image rotates because it grows and shrinks in size. 随着图像的旋转,整个矩形会发生变化,因为它会变大和缩小。 So what you needed to do was completely set the new rect each time. 所以你需要做的就是每次都完全设置新的矩形。

self.image.get_rect(center=self.rect.center)

This calculates a brand new rect, while basing it around the given center. 这将计算一个全新的矩形,同时将其基于给定的中心。 The center is set on the rect before it calculate the positions. 在计算位置之前,将中心设置在矩形上。 Thus, you get a rect that is properly centered around your point. 因此,你得到一个正确围绕你的点的矩形。

I had this issue. 我有这个问题。 My method has a bit of a different purpose, but I solved it quite nicely. 我的方法有一些不同的目的,但我很好地解决了它。

import pygame, math

def draw_sprite(self, sprite, x, y, rot):
    #'sprite' is the loaded image file.
    #'x' and 'y' are coordinates.
    #'rot' is rotation in radians.

    #Creates a new 'rotated_sprite' that is a rotated variant of 'sprite'
    #Also performs a radian-to-degrees conversion on 'rot'.
    rotated_sprite = pygame.transform.rotate(sprite, math.degrees(rot))

    #Creates a new 'rect' based on 'rotated_sprite'
    rect = rotated_sprite.get_rect()

    #Blits the rotated_sprite onto the screen with an offset from 'rect'
    self.screen.blit(rotated_sprite, (x-(rect.width/2), y-(rect.height/2)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM