[pygame ex] Rotating Laser-Turret

[pygame ex] Rotating Laser-Turret

Postby Mekire » Wed May 08, 2013 1:49 am

Just a simple rotating turret. One of the things I had constant issues with early on is that pygame rects int() everything you give them. This means that if it is necessary to update the position of the rect by less than a quantum pixel it will just ignore you. As such it is unfortunately better to keep track of the movement somewhere where you can hold the floats correctly.

Anyway... just a simple example with some simple trig (started it when hansn was asking about circular rotation and such).

Uses the image below (loaded via urllib so no worries):

Left and Right to rotate; Spacebar to fire:
Code: Select all
import pygame as pg
import sys,os,math

class Turret:
    def __init__(self,loc):
        self.orig_barrel = TURRET.subsurface((0,0,150,150))
        self.barrel = self.orig_barrel.copy()
        self.base   = TURRET.subsurface((300,0,150,150))
        self.rect = self.barrel.get_rect(center = loc)
        self.base_rect = self.rect.copy()
        self.angle = 90
        self.spin = 0
        self.rotate_speed = 3
    def event_manager(self,event,Objects):
        keys = pg.key.get_pressed()
        self.spin = 0
        #Ifs not elifs; these all need to run.
        if keys[pg.K_RIGHT]:
            self.spin -= 1
        if keys[pg.K_LEFT]:
            self.spin += 1
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_SPACE:
    def update(self,Surf):
        oldcenter = self.rect.center
        self.angle += self.rotate_speed*self.spin
        self.barrel = pg.transform.rotate(self.orig_barrel,self.angle)
        self.rect = self.barrel.get_rect(center = oldcenter)

class Laser:
    def __init__(self,loc,angle):
        self.orig_laser = TURRET.subsurface((150,0,150,150))
        self.angle = angle
        self.image = pg.transform.rotate(self.orig_laser,self.angle)
        self.start_rect = self.image.get_rect(center=loc)
        self.rect = self.start_rect.copy()
        self.move = [0,0]
        self.speed = 5
        self.done = False
    def update(self,Surf):
        rad_ang = -math.radians(self.angle-135) #Annoying
        self.move[0] += self.speed*math.cos(rad_ang)
        self.move[1] += self.speed*math.sin(rad_ang)
        self.rect.topleft = self.start_rect.move(self.move).topleft
    def remove(self,Surf):
        if not self.rect.colliderect(Surf.get_rect()):
            self.done = True

class Control:
    def __init__(self,Screen):
        self.screen = Screen
        self.done = False
        self.Clock = pg.time.Clock()
        self.rect = pg.Rect((0,0,600,600))
        self.Cannon = Turret((250,250))
        self.Objects = []
    def event_loop(self):
        keys = pg.key.get_pressed()
        for event in pg.event.get():
            if event.type == pg.QUIT or keys[pg.K_ESCAPE]:
                self.done = True
    def update(self):
        for Obj in self.Objects[:]:
            if Obj.done:
    def main(self):
        while not self.done:

def image_from_url(url):
        from urllib2 import urlopen
        from cStringIO import StringIO as inout
    except ImportError:
        from urllib.request import urlopen
        from io import BytesIO as inout
    myurl = urlopen(url)
    return inout(myurl.read()) #Can be loaded by pygame.image.load

if __name__ == "__main__":
    os.environ['SDL_VIDEO_CENTERED'] = '1'
    SCREENSIZE = (500,500)
    SCREEN = pg.display.set_mode(SCREENSIZE)
    TURRET_URL = "http://i1192.photobucket.com/albums/aa340/Mekire/turret.png"
    TURRET = pg.image.load(image_from_url(TURRET_URL)).convert()
##    TURRET = pg.image.load("turret.png").convert()

    RunIt = Control(SCREEN)


Edit: Oh, yeah. Art by John McKiernan. No stealing now. Code free for any and all purposes as it should be (with the general no warranty expressed or implied nonsense that goes along with that).
New Users, Read This
  • Use code tags when posting code.
  • Include any errors with your post (in code tags).
  • Describe your problem; not your chosen solution.
  • Make examples the minimum length to demonstrate your issue.
User avatar
Posts: 1367
Joined: Thu Feb 07, 2013 11:33 pm
Location: Tucson, Arizona

Re: [pygame ex] Rotating Laser-Turret

Postby hansn » Wed May 08, 2013 5:01 pm

What is TURRET.subsurface?
Posts: 87
Joined: Thu Feb 21, 2013 8:46 pm

Re: [pygame ex] Rotating Laser-Turret

Postby metulburr » Wed May 08, 2013 5:48 pm

What is TURRET.subsurface?

if your asking waht TURRET is:
Code: Select all
TURRET = pg.image.load(image_from_url(TURRET_URL)).convert()

if your asking what subsurface is:
http://www.pygame.org/docs/ref/surface. ... subsurface
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
User avatar
Posts: 1726
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Re: [pygame ex] Rotating Laser-Turret

Postby hansn » Wed May 08, 2013 7:14 pm

Ah. I didn't even check if TURRET was defined :oops:

Thanks. And that's a nice example.
Posts: 87
Joined: Thu Feb 21, 2013 8:46 pm

Return to Game Development

Who is online

Users browsing this forum: No registered users and 1 guest