0

このチュートリアルをPygame(Python)で作成しようとしていますが、平面間のポイントの保持に問題があります。

私のコードは:fiz2.py

ベクトルクラス:vector.py

Pygame画面でマウスを動かすと、飛行機が回転します。そして、平面が回転しているとき、点は平面を通過して外に出ています。

反復ごとにポイントの位置を修正しようとしましたが、それでもプレーンを通過しました。どこに固定すればいいのかわからない。

注:コードが少し乱雑であることはわかっています。これは私の最初の2Dプログラムであり、Pygameの座標平面とベクトルに慣れるのに非常に苦労しました。これを解決したら書き直します。

注2:はい、チュートリアルで平面間のポイントを保持する方法についてコメントを書きました。彼が位置を修正する方法は理解していますが、それを実装する方法(およびコード内のどこ)についてはわかりません。

ありがとう。

4

1 に答える 1

4

コードを見てもわかりません。私の推測では、可変タイムステップであり、不安定性を引き起こしています。しかし、計算が正しいかどうかは確認できません。ただし、役立つ情報があります。

ベクトル

ベクトルをクラス対リスト/タプルとして使用することで、コードを簡素化できます。(速度、加速度、位置) は 1 つのオブジェクトとして扱われ、.x 値と .y 値は分離されます。

# example:
pos[0] += vel[0]
pos[1] += vel[1]

# vs
pos += vel

Python のみの実装があります: euclid.pyを使用して、vector.py と比較できます。

または、openGL で 3D グラフィックスに使用されるNumPy [ を使用します。】 人気の大人っぽいリブです。

物理

(自分で物理学を書いて学びたいようです)しかし、PyMunkをチェックしてください

使用できます: pygame.Color

import pygame
from pygame import Color
color = Color('white')
color2 = Color('lightgray')
color3 = Color(0,128,128)

衝突 #

pygame.sprite.*collidepygame.Rect.*collideを見てください。

numpy ベクトルを使用した pygame ゲーム ループ

私が書いたボイラープレート

""" Pygame boilerplate. <ninmonkey>2011/04
        pygame main Game() loop, and numpy for vector math.

note:
        this might not be the most effecient way to use numpy as vectors, but it's an intro.

        And this does not force fixed-timesteps. If you want a stable simulation, you need to use a fixed timestep.
        see: http://gafferongames.com/game-physics/fix-your-timestep/

Keys:
    ESC : exit
    Space : game_init()
"""

import pygame
from pygame.locals import * 
from pygame import Color, Rect

import numpy as np

def get_screen_size():
    """return screen (width, height) tuple"""
    screen = pygame.display.get_surface()
    return screen.get_size()

class Actor():
    """basic actor, moves randomly.

    members:
        loc = position vector
        velocity = velocity vector
        width, height        
    """
    def __init__(self, loc=None, velocity=None):
        """optional initial loc and velocity vectors"""
        self.width = 50
        self.height = 50

        # if loc or velocity are not set: use random
        if loc is None: self.rand_loc()
        else: self.loc = loc

        if velocity is None: self.rand_velocity()
        else: self.velocity = velocity

    def update(self):
        """update movement""" 
        self.loc += self.velocity

    def rand_velocity(self):
        """set a random vector , based on random direction. Using unit circle:        
                x = cos(deg) * speed
        """
        rad = np.radians( np.random.randint(0,360) )
        speed = np.random.randint(1,15)
        x = np.cos(rad)
        y = np.sin(rad)
        velocity = np.array( [x,y])
        velocity *= speed
        self.velocity = velocity 

    def rand_loc(self):
        """random location onscreen"""
        width,height = get_screen_size()
        x = np.random.randint(0,width)
        y = np.random.randint(0,height)
        self.loc = np.array([x,y])

    def is_onscreen(self):
        """test is screen.colliderect(actor) true?"""
        x,y = self.loc
        w,h = get_screen_size()

        screen = Rect(0, 0, w, h)
        actor = Rect(x, y, self.width, self.height)

        if screen.colliderect(actor): return True
        else: return False

class GameMain():
    """game Main entry point. handles intialization of game and graphics."""
    done = False
    debug = False
    color_gray = Color('lightgray')

    def __init__(self, width=800, height=600, color_bg=None):
        """Initialize PyGame"""        
        pygame.init()
        self.width, self.height = width, height
        self.screen = pygame.display.set_mode(( self.width, self.height ))
        pygame.display.set_caption( "boilerplate : pygame" )        

        self.clock = pygame.time.Clock()
        self.limit_fps = True
        self.limit_fps_max = 60  

        if color_bg is None: color_bg = Color(50,50,50)       
        self.color_bg = color_bg

        self.game_init()

    def game_init(self):
        """new game/round"""
        self.actors = [Actor() for x in range(10)]

    def loop(self):
        """Game() main loop"""
        while not self.done:
            self.handle_events()
            self.update()
            self.draw()

            if self.limit_fps: self.clock.tick( self.limit_fps_max )
            else: self.clock.tick()

    def update(self):        
        """update actors, handle physics"""
        for a in self.actors:
            a.update()

            if not a.is_onscreen():
                a.rand_loc()

    def handle_events(self):
        """handle regular events. """        
        events = pygame.event.get()
        # kmods = pygame.key.get_mods() # key modifiers

        for event in events:
            if event.type == pygame.QUIT: sys.exit()
            elif event.type == KEYDOWN:
                if (event.key == K_ESCAPE): self.done = True
                elif (event.key == K_SPACE): self.game_init()

    def draw(self):
        """render screen"""
        # clear screen
        self.screen.fill( self.color_bg )

        # Actor: draw
        for a in self.actors:
            x,y = a.loc
            w,h = a.width, a.height
            r = Rect(x, y, w, h)
            self.screen.fill(self.color_gray, r)

        # will call update on whole screen Or flip buffer.
        pygame.display.flip()

if __name__ == '__main__':
    g = GameMain()
    g.loop()
于 2011-04-27T05:04:17.837 に答える