Changeset 39:34038447be23


Ignore:
Timestamp:
Apr 3, 2011, 6:24:17 PM (9 years ago)
Author:
Simon Cross <hodgestar@…>
Branch:
default
Message:

Very basic world physics.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • skaapsteker/physics.py

    r23 r39  
    55
    66import pygame.sprite
     7import pygame
     8import time
    79
    810
     
    1214    gravitates = True # whether gravity applies to the sprite
    1315
     16    terminal_velocity = (100.0, 100.0) # maximum horizontal and vertial speeds
     17
     18    def __init__(self, *args, **kwargs):
     19        super(Sprite, self).__init__(*args, **kwargs)
     20        self.velocity = (0.0, 0.0)
     21        self.rect = pygame.Rect(0, 0, 10, 10) # sub-classes should override
     22
     23    def deltav(self, dv):
     24        v_x, v_y = self.velocity
     25        v_x, v_y = v_x + dv[0], v_y + dv[1]
     26
     27        t_v = self.terminal_velocity
     28        v_x = max(min(v_x, t_v[0]), -t_v[0])
     29        v_y = max(min(v_y, t_v[1]), -t_v[1])
     30
     31        self.velocity = (v_x, v_y)
     32
     33    def deltap(self, dt):
     34        v_x, v_y = self.velocity
     35        d_x, d_y = v_x * dt, v_y * dt
     36        self.rect.move(d_x, d_y)
     37
    1438
    1539class World(object):
     40
     41    GRAVITY = -9.8 # m/s^2
    1642
    1743    def __init__(self):
     
    1945        self._mobiles = pygame.sprite.Group()
    2046        self._gravitators = pygame.sprite.Group()
     47        self._last_time = None
    2148
    2249    def add(self, sprite):
     
    2653        if sprite.gravitates:
    2754            self._gravitators.add(sprite)
     55
     56    def update(self):
     57        if self._last_time is None:
     58            self._last_time = time.time()
     59            return
     60
     61        # find dt
     62        now = time.time()
     63        self._last_time, dt = now, now - self._last_time
     64
     65        # gravity
     66        dv = (0, self.GRAVITY * dt)
     67        for sprite in self._gravitators:
     68            sprite.deltav(dv)
     69
     70        # position update (do last)
     71        for sprite in self._mobiles:
     72            sprite.deltap(dt)
     73
     74    def draw(self, surface):
     75        self._all.draw(surface)
Note: See TracChangeset for help on using the changeset viewer.