在pygame中旋转时,船向上和向左移动比向下和向右移动更快

本文介绍了在pygame中旋转时,船向上和向左移动比向下和向右移动更快的处理方法,对大家解决问题具有一定的参考价值

问题描述

我正在开发一个简单的游戏.我创建了一个 pygame 精灵,并通过使其向前移动并以一致的速度旋转来对其进行测试.但是,它似乎向左和向上(sin 和 cos 为负数)比向右和向下(sin 和 cos 为正数)更快.我测试了它没有移动,只是旋转,它可以工作.

代码如下:

import pygame导入系统从数学导入 cos, sin, pi从时间导入睡眠屏幕宽度 = 800屏幕高度 = 800每秒帧数 = 60pygame.init()DISPLAY = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))时钟 = pygame.time.Clock()红色 = (255, 0, 0)绿色 = (0, 255, 0)蓝色 = (0, 0, 255)白色 = (255, 255, 255)黑色 = (0, 0, 0)SHIP_BLUE_IMG = pygame.image.load('./spaceshooter/PNG/playerShip1_blue.png').convert()SHIP_RED_IMG = pygame.image.load('./spaceshooter/PNG/playerShip1_red.png').convert()LASER_BLUE_IMG = pygame.image.load('./spaceshooter/PNG/Lasers/laserBlue16.png').convert()LASER_RED_IMG = pygame.image.load('./spaceshooter/PNG/Lasers/laserRed16.png').convert()激光速度 = 10PLAYER_SHIP_SPEED = 5all_sprites = pygame.sprite.Group()类播放器(pygame.sprite.Sprite):def __init__(self, img, pos, angle):超级().__init__()img.set_colorkey((0, 0, 0, 0))self.angle = 角度self.original_img = pygame.transform.rotate(img, 180) # 因为这些图片倒过来了self.image = self.original_imgself.rect = self.image.get_rect()self.rect.center = posself._update_image()def _update_image(self):x, y = self.rect.centerself.image = pygame.transform.rotate(self.original_img, self.angle)self.rect = self.image.get_rect()self.rect.center = (x, y)def _get_radeons(self):返回 (self.angle*pi)/180def 旋转(自我,度数):self.angle += 度数self._update_image()定义更新(自我):自旋转(5)x, y = self.rect.centernx = sin(self._get_radeons())*PLAYER_SHIP_SPEED + xny = cos(self._get_radeons())*PLAYER_SHIP_SPEED + yself.rect.center = (nx, ny)玩家 = 玩家(SHIP_BLUE_IMG, (300, 300), 45)all_sprites.add(玩家)而真:对于 pygame.event.get() 中的事件:如果 event.type == pygame.QUIT:sys.exit()DISPLAY.fill(黑色)all_sprites.update()all_sprites.draw(显示)pygame.display.update()CLOCK.tick(FPS)

为了描述我运行它时的样子,它是一艘黑色背景上的船,逆时针旋转,同时在应该是一个圆圈的地方向前移动.但相反,它正在形成一种螺旋,慢慢靠近屏幕的左上角.

解决方案

这是一个准确性问题.由于

导入数学导入pygame类播放器(pygame.sprite.Sprite):def __init__(self, img, pos, angle):超级().__init__()img.set_colorkey((0, 0, 0, 0))self.angle = 角度self.original_img = pygame.transform.rotate(img, 180)self.image = self.original_imgself.rect = self.image.get_rect()self.rect.center = posself.pos = 位置自我速度 = 5self.angle_step = 5self._update_image()def _update_image(self):x, y = self.rect.centerself.image = pygame.transform.rotate(self.original_img, self.angle)self.rect = self.image.get_rect()self.rect.center = (x, y)定义更新(自我):self.angle += self.angle_stepself._update_image()nx = math.sin(math.radians(self.angle)) * self.speed + self.pos[0]ny = math.cos(math.radians(self.angle)) * self.speed + self.pos[1]self.pos = (nx, ny)self.rect.center = 圆形(nx),圆形(ny)pygame.init()窗口 = pygame.display.set_mode((300, 300))时钟 = pygame.time.Clock()背景 = pygame.Surface(window.get_size())背景.set_alpha(5)all_sprites = pygame.sprite.Group()ship_image = pygame.image.load('Rocket64.png').convert_alpha()player = Player(ship_image, (window.get_width()//2-40, window.get_height()//2+40), 45)all_sprites.add(玩家)运行=真运行时:时钟.tick(60)对于 pygame.event.get() 中的事件:如果 event.type == pygame.QUIT:运行 = 假all_sprites.update()window.blit(背景, (0, 0))all_sprites.draw(窗口)pygame.display.update()pygame.quit()出口()

I am working on a simple game. I created a pygame sprite which and tested it by making it move forward and rotating at a consistent speed. However, it seams to be moving left and up (where sin and cos are negative) quicker than right and down (where sin and cos are positive). I tested it without moving and just rotating and it works.

Here is the code:

import pygame
import sys
from math import cos, sin, pi
from time import sleep

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 800

FPS = 60

pygame.init()
DISPLAY = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
CLOCK = pygame.time.Clock()

RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)

SHIP_BLUE_IMG = pygame.image.load('./spaceshooter/PNG/playerShip1_blue.png').convert()
SHIP_RED_IMG = pygame.image.load('./spaceshooter/PNG/playerShip1_red.png').convert()
LASER_BLUE_IMG = pygame.image.load('./spaceshooter/PNG/Lasers/laserBlue16.png').convert()
LASER_RED_IMG = pygame.image.load('./spaceshooter/PNG/Lasers/laserRed16.png').convert()

LASER_SPEED = 10
PLAYER_SHIP_SPEED = 5

all_sprites = pygame.sprite.Group()


class Player(pygame.sprite.Sprite):
    def __init__(self, img, pos, angle):
        super().__init__()
        img.set_colorkey((0, 0, 0, 0))
        self.angle = angle
        self.original_img = pygame.transform.rotate(img, 180) # Becase these images come upside down
        self.image = self.original_img
        self.rect = self.image.get_rect()
        self.rect.center = pos

        self._update_image() 

    def _update_image(self):
        x, y = self.rect.center
        self.image = pygame.transform.rotate(self.original_img, self.angle)
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)

    def _get_radeons(self):
        return (self.angle*pi)/180

    def rotate(self, degrees):
        self.angle += degrees
        self._update_image()

    def update(self):
        self.rotate(5)
        x, y = self.rect.center
        nx = sin(self._get_radeons())*PLAYER_SHIP_SPEED + x
        ny = cos(self._get_radeons())*PLAYER_SHIP_SPEED + y
        self.rect.center = (nx, ny)


player = Player(SHIP_BLUE_IMG, (300, 300), 45)
all_sprites.add(player)

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    DISPLAY.fill(BLACK)
    all_sprites.update()
    all_sprites.draw(DISPLAY)
    pygame.display.update()
    CLOCK.tick(FPS)

To describe what it looks like when I run it, it is a ship on a black background that rotates counter-clockwise while moving forward in what should be a circle. But instead, it is creating a sort of spiral, slowly getting closer to the top left corner of the screen.

解决方案

This is an accuracy issue. Since pygame.Rect is supposed to represent an area on the screen, a pygame.Rect object can only store integral data.

The coordinates for Rect objects are all integers. [...]

The fraction part of the coordinates gets lost when the new position of the player is assigned to the Rect object:

self.rect.center = (nx, ny)

Since this is done every frame, the position error will accumulate over time.

If you want to store object positions with floating point accuracy, you have to store the location of the object in separate variables respectively attributes (self.pos) and to synchronize the pygame.Rect object. round the coordinates and assign it to the location (e.g. .center) of the rectangle:

class Player(pygame.sprite.Sprite):
    def __init__(self, img, pos, angle):
        # [...]

        self.pos = pos

    # [...]

    def update(self):
        self.rotate(5)
        nx = sin(self._get_radeons())*PLAYER_SHIP_SPEED + self.pos[0]
        ny = cos(self._get_radeons())*PLAYER_SHIP_SPEED + self.pos[1]
        self.pos = (nx, ny)
        self.rect.center = round(nx), round(ny)

See also Move and rotate.


Minimal example:

import math
import pygame

class Player(pygame.sprite.Sprite):
    def __init__(self, img, pos, angle):
        super().__init__()
        img.set_colorkey((0, 0, 0, 0))
        self.angle = angle
        self.original_img = pygame.transform.rotate(img, 180)
        self.image = self.original_img
        self.rect = self.image.get_rect()
        self.rect.center = pos
        self.pos = pos
        self.speed = 5
        self.angle_step = 5
        self._update_image() 

    def _update_image(self):
        x, y = self.rect.center
        self.image = pygame.transform.rotate(self.original_img, self.angle)
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)

    def update(self):
        self.angle += self.angle_step
        self._update_image()
        nx = math.sin(math.radians(self.angle)) * self.speed + self.pos[0]
        ny = math.cos(math.radians(self.angle)) * self.speed + self.pos[1]
        self.pos = (nx, ny)
        self.rect.center = round(nx), round(ny)

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
background = pygame.Surface(window.get_size())
background.set_alpha(5)

all_sprites = pygame.sprite.Group()
ship_image = pygame.image.load('Rocket64.png').convert_alpha()
player = Player(ship_image, (window.get_width()//2-40, window.get_height()//2+40), 45)
all_sprites.add(player)

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    all_sprites.update()

    window.blit(background, (0, 0))
    all_sprites.draw(window)
    pygame.display.update()

pygame.quit()
exit()

这篇关于在pygame中旋转时,船向上和向左移动比向下和向右移动更快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2

admin_action_{$_REQUEST[‘action’]}

do_action( "admin_action_{$_REQUEST[‘action’]}" )动作钩子::在发送“Action”请求变量时激发。Action Hook: Fires when an ‘action’ request variable is sent.目录锚点:#说明#源码说明(Description)钩子名称的动态部分$_REQUEST['action']引用从GET或POST请求派生的操作。源码(Source)更新版本源码位置使用被使用2.6.0 wp-admin/admin.php:...

日期:2020-09-02 17:44:16 浏览:1167

admin_footer-{$GLOBALS[‘hook_suffix’]}

do_action( "admin_footer-{$GLOBALS[‘hook_suffix’]}", string $hook_suffix )操作挂钩:在默认页脚脚本之后打印脚本或数据。Action Hook: Print scripts or data after the default footer scripts.目录锚点:#说明#参数#源码说明(Description)钩子名的动态部分,$GLOBALS['hook_suffix']引用当前页的全局钩子后缀。参数(Parameters)参数类...

日期:2020-09-02 17:44:20 浏览:1069

customize_save_{$this->id_data[‘base’]}

do_action( "customize_save_{$this->id_data[‘base’]}", WP_Customize_Setting $this )动作钩子::在调用WP_Customize_Setting::save()方法时激发。Action Hook: Fires when the WP_Customize_Setting::save() method is called.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分,$this->id_data...

日期:2020-08-15 15:47:24 浏览:806

customize_value_{$this->id_data[‘base’]}

apply_filters( "customize_value_{$this->id_data[‘base’]}", mixed $default )过滤器::过滤未作为主题模式或选项处理的自定义设置值。Filter Hook: Filter a Customize setting value not handled as a theme_mod or option.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分,$this->id_date['base'],指的是设置...

日期:2020-08-15 15:47:24 浏览:898

get_comment_author_url

过滤钩子:过滤评论作者的URL。Filter Hook: Filters the comment author’s URL.目录锚点:#源码源码(Source)更新版本源码位置使用被使用 wp-includes/comment-template.php:32610...

日期:2020-08-10 23:06:14 浏览:930

network_admin_edit_{$_GET[‘action’]}

do_action( "network_admin_edit_{$_GET[‘action’]}" )操作挂钩:启动请求的处理程序操作。Action Hook: Fires the requested handler action.目录锚点:#说明#源码说明(Description)钩子名称的动态部分$u GET['action']引用请求的操作的名称。源码(Source)更新版本源码位置使用被使用3.1.0 wp-admin/network/edit.php:3600...

日期:2020-08-02 09:56:09 浏览:876

network_sites_updated_message_{$_GET[‘updated’]}

apply_filters( "network_sites_updated_message_{$_GET[‘updated’]}", string $msg )筛选器挂钩:在网络管理中筛选特定的非默认站点更新消息。Filter Hook: Filters a specific, non-default site-updated message in the Network admin.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分$_GET['updated']引用了非默认的...

日期:2020-08-02 09:56:03 浏览:863

pre_wp_is_site_initialized

过滤器::过滤在访问数据库之前是否初始化站点的检查。Filter Hook: Filters the check for whether a site is initialized before the database is accessed.目录锚点:#源码源码(Source)更新版本源码位置使用被使用 wp-includes/ms-site.php:93910...

日期:2020-07-29 10:15:38 浏览:833

WordPress 的SEO 教学:如何在网站中加入关键字(Meta Keywords)与Meta 描述(Meta Description)?

你想在WordPress 中添加关键字和meta 描述吗?关键字和meta 描述使你能够提高网站的SEO。在本文中,我们将向你展示如何在WordPress 中正确添加关键字和meta 描述。为什么要在WordPress 中添加关键字和Meta 描述?关键字和说明让搜寻引擎更了解您的帖子和页面的内容。关键词是人们寻找您发布的内容时,可能会搜索的重要词语或片语。而Meta Description则是对你的页面和文章的简要描述。如果你想要了解更多关于中继标签的资讯,可以参考Google的说明。Meta 关键字和描...

日期:2020-10-03 21:18:25 浏览:1718

谷歌的SEO是什么

SEO (Search Engine Optimization)中文是搜寻引擎最佳化,意思近于「关键字自然排序」、「网站排名优化」。简言之,SEO是以搜索引擎(如Google、Bing)为曝光媒体的行销手法。例如搜寻「wordpress教学」,会看到本站的「WordPress教学:12个课程…」排行Google第一:关键字:wordpress教学、wordpress课程…若搜寻「网站架设」,则会看到另一个网页排名第1:关键字:网站架设、架站…以上两个网页,每月从搜寻引擎导入自然流量,达2万4千:每月「有机搜...

日期:2020-10-30 17:23:57 浏览:1308