如何在pygame中将旋转限制为一定的度数? [英] how to restrict rotation to a set amount of degrees in pygame?

查看:125
本文介绍了如何在pygame中将旋转限制为一定的度数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题与以下问题的答案有关.

解决方案

您是否正在寻找这样的钳位功能?

def 钳位(值,min_,max_):"""将值限制在 min_ 和 max_ 之间的范围内."""返回最大值(min_, min(value, max_))

在您的情况下,您还必须检查 current_angle 是大于还是小于 0.

如果 current_angle <= 0:current_angle = 夹具(current_angle,-180,-120)elif current_angle >0:current_angle = 钳位(current_angle, 120, 180)

更新:这是带有向量的示例.我使用向量来确定精灵需要向哪个方向旋转.请注意,右边现在是 0 度,左边是 180°,从 0° 到 360°.

这里有一些有趣的链接,可以帮助我学习如何做到这一点:http://docs.godotengine.org/en/stable/tutorials/matrices_and_transforms.htmlhttp://www.wildbunny.co.uk/blog/vector-maths-a-primer-for-games-programmers/

导入数学导入pygamepygame.init()屏幕 = pygame.display.set_mode((300, 300))字体 = pygame.font.Font(None, 24)灰色 = pygame.Color('gray90')定义钳位(值,min_value,max_value):"""将值限制在 min_value 和 max_value 之间的范围内."""返回最大值(min_value, min(value, max_value))定义主():当前_角度 = 0时钟 = pygame.time.Clock()冲浪 = pygame.Surface((80, 50), pygame.SRCALPHA)pygame.draw.polygon(surf, (40, 100, 200), ((0, 0), (80, 25), (0, 50)))orig_surf = 冲浪rect = surf.get_rect(center=(150, 150))orig_direction = pygame.math.Vector2(0, 1)玩 = 真玩的时候:对于 pygame.event.get() 中的事件:如果 event.type == pygame.QUIT:播放 = 错误# 在这里我弄清楚目标是否在时钟上更近-# 或逆时针方向.`orientation` 是积极的# 如果目标在顺时针方向和负方向上更近# 如果是逆时针方向.vec_to_target = pygame.math.Vector2(pygame.mouse.get_pos()) - rect.center方向 = orig_direction.rotate(current_angle)方向 = vec_to_target.dot(direction)# 我使用方向 >3 和 <-3 而不是 0 到# 达到目标角度时避免抖动.如果方向 >3:current_angle += 3elif 方向 <-3:current_angle -= 3# 你可以使用这个模运算来保持两者之间的角度# 0° 和 360°,但由于夹具的原因,不需要.# current_angle %= 360# 将值限制在所需的范围内.current_angle = 钳位(current_angle, 120, 240)冲浪 = pygame.transform.rotate(orig_surf, -current_angle)rect = surf.get_rect(center=rect.center)# 画screen.fill((40, 40, 40))screen.blit(冲浪,矩形)txt = font.render('angle {:.1f}'.format(current_angle), True, GRAY)screen.blit(txt, (10, 10))txt = font.render('orientation {:.1f}'.format(orientation), True, GRAY)screen.blit(txt, (10, 25))pygame.display.update()时钟滴答(30)如果 __name__ == '__main__':主要的()pygame.quit()

My question is related to the answer of the question below.

rotating a rectangle.

How do i restrict the rotation to the area marked in red as in this picture? I tried various ways but was unsuccesfull. The code always keeps the poiter in the other area. my modified code below.

import pygame, math, base64
pygame.init()
screen = pygame.display.set_mode((200, 200))

surf = pygame.image.load("D:\\PYTHON\\SoftwareDG\\Games\\Platform_Suvivor\\assets\\rg.png").convert_alpha()

def rot_center(image, angle):
    orig_rect = image.get_rect()
    rot_image = pygame.transform.rotate(image, angle)
    rot_rect = orig_rect.copy()
    rot_rect.center = rot_image.get_rect().center
    rot_image = rot_image.subsurface(rot_rect).copy()
    return rot_image

current_angle = 0

while True:
    if pygame.event.get(pygame.QUIT): break
    pygame.event.get()

    mouseX, mouseY = pygame.mouse.get_pos()
    rect = surf.get_rect(center=(92, 92))
    target_angle = math.degrees(math.atan2(mouseY - rect.centery, mouseX - rect.centerx))
    if target_angle < -120:
        target_angle = -120
    if target_angle > 120:
        target_angle = 120
    print target_angle
    if current_angle > target_angle:
        current_angle -= 0.03
    if current_angle < target_angle:
        current_angle += 0.03

    screen.fill((40, 140, 40))
    screen.blit(rot_center(surf, -current_angle), rect)
    pygame.display.update()

解决方案

Are you looking for a clamp function like this?

def clamp(value, min_, max_):
    """Clamp value to a range between min_ and max_."""
    return max(min_, min(value, max_))

In your case you also have to check if the current_angle is greater or less than 0.

if current_angle <= 0:
    current_angle = clamp(current_angle, -180, -120)
elif current_angle > 0:
    current_angle = clamp(current_angle, 120, 180)

Update: Here's the example with vectors. I use the vectors to figure out in which direction the sprite needs to be rotated. Note that right is now 0 degrees, left is 180° and it goes from 0° to 360°.

And here are some interesting links that helped me to learn how to do this: http://docs.godotengine.org/en/stable/tutorials/matrices_and_transforms.html http://www.wildbunny.co.uk/blog/vector-maths-a-primer-for-games-programmers/

import math
import pygame


pygame.init()
screen = pygame.display.set_mode((300, 300))
font = pygame.font.Font(None, 24)
GRAY = pygame.Color('gray90')


def clamp(value, min_value, max_value):
    """Clamp value to a range between min_value and max_value."""
    return max(min_value, min(value, max_value))


def main():
    current_angle = 0
    clock = pygame.time.Clock()
    surf = pygame.Surface((80, 50), pygame.SRCALPHA)
    pygame.draw.polygon(surf, (40, 100, 200), ((0, 0), (80, 25), (0, 50)))
    orig_surf = surf
    rect = surf.get_rect(center=(150, 150))
    orig_direction = pygame.math.Vector2(0, 1)

    playing = True

    while playing:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                playing = False

        # Here I figure out if the target is closer in clock-
        # or counterclockwise direction. `orientation` is positive
        # if the target is closer in clockwise and negative
        # if it's in counterclockwise direction.
        vec_to_target = pygame.math.Vector2(pygame.mouse.get_pos()) - rect.center
        direction = orig_direction.rotate(current_angle)
        orientation = vec_to_target.dot(direction)
        # I use orientation > 3 and < -3 instead of 0 to
        # avoid jittering when the target angle is reached.
        if orientation > 3:
            current_angle += 3
        elif orientation < -3:
            current_angle -= 3

        # You can use this modulo operation to keep the angle between
        # 0° and 360°, but this is not needed because of the clamp.
        # current_angle %= 360
        # Clamp the value to the desired range.
        current_angle = clamp(current_angle, 120, 240)

        surf = pygame.transform.rotate(orig_surf, -current_angle)
        rect = surf.get_rect(center=rect.center)

        # Draw
        screen.fill((40, 40, 40))
        screen.blit(surf, rect)
        txt = font.render('angle {:.1f}'.format(current_angle), True, GRAY)
        screen.blit(txt, (10, 10))
        txt = font.render('orientation {:.1f}'.format(orientation), True, GRAY)
        screen.blit(txt, (10, 25))

        pygame.display.update()
        clock.tick(30)


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

这篇关于如何在pygame中将旋转限制为一定的度数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆