[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] fast sqrt? and profiling



On Thu, Jan 22, 2009 at 3:28 AM, Jake b <ninmonkeys@xxxxxxxxx> wrote:
> On Wed, Jan 21, 2009 at 11:11 AM, Casey Duncan <casey@xxxxxxxxxxx> wrote:
>>
>> Others have made good suggestions about reducing the amount of work you do
>> detecting collision (i.e., partitioning) and using complex numbers instead
>> of euclid for 2d vectors. The latter made a big performance difference for
>> me in a vector-heavy game I was working on.
>
> 1) How do you use complex(imaginary) numbers in place of euclid vectors? I
> tried searching for a tut/article, but, not having luck.

Just use complex numbers as the standard data format for all your 2D
vectors (positions, speeds, accelerations, directions ...)

So you're making asteroids, you may have a spaceship that looks like this:

class Spaceship:
    def __init__(self, pos, max_accel):
        self.pos = pos
        self.speed = 0j
        self.direction = 1j
        self.boosters_on = False
        self.max_accel = max_accel

    def update(self, dt):
        if self.boosters_on:
            self.speed += self.direction * self.max_accel * dt
        self.pos += self.speed * dt

    def render(self):
        screen_coords = self.pos.real, self.pos.imag
        # (Have somthing that draws the right sprite or polygon there)


... it's missing a lot of code, like turning the boosters on or off
when you press buttons, turning (a bit more painful), and drawing, but
you can at least see that the "physics" logic is pretty
straightfoward, more than it would be if you were using tuples or
something like that to represent vectors.

Cheers,

Emile