• Advertisement
Sign in to follow this  

Unity Why, oh why won't my sprite rotate?

This topic is 3822 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi again! After successfully viewing my sprite on the screen I go to the next step; to be able to rotate the sprite based on keyboard input. I have followed deviangels tutorial on rotating sprites, and I've checked my code against his numerous times. I don't understand how he makes the update function work since it is never called in his script (as far as I can see at least). Could you please help me out on this one? Thanks in advance!
import pygame
pygame.init()

class Pacman(pygame.sprite.Sprite):
    """ The class that creates Pacman """
    
    def __init__(self, posX, posY):
        """ Creates the creature """
        pygame.sprite.Sprite.__init__(self)
        self.imageMaster = pygame.image.load("data/pacman.gif").convert()
        self.image = self.imageMaster
        self.rect = self.image.get_rect()
        self.rect.center = (posX, posY)
        self.FacingDir = 0
        
    def Update(self):
        oldCenter = self.rect.center
        self.image = pygame.transform.rotate(self.imageMaster, self.FacingDir)
        self.rect = self.image.get_rect()
        self.rect.center = oldCenter
        
    def FaceUp(self):
        FacingDeg = 90
        
    def FaceDown(self):
        FacingDeg = 270
        
    def FaceLeft(self):
        FacingDeg = 180
        
    def FaceRight(self):
        FacingDeg = 0

def main():
    # set up the display
    screen = pygame.display.set_mode((390, 390))
    pygame.display.set_caption("Pacman clone")

    # set up the background
    background = pygame.Surface(screen.get_size())
    background.fill((0, 0, 0))

    hero = Pacman(100, 150)
    allSprites = pygame.sprite.Group(hero)

    # set up tha main loop
    keepGoing = True
    clock = pygame.time.Clock()
    pygame.mouse.set_visible(False)

    while keepGoing:
        clock.tick(30)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                keepGoing = False
                
            elif event.type == pygame.KEYDOWN:
                
                if event.key == pygame.K_LEFT:
                    hero.FaceLeft()
                
                elif event.key == pygame.K_RIGHT:
                    hero.FaceRight()
                    
                elif event.key == pygame.K_UP:
                    hero.FaceUp()
                    
                elif event.key == pygame.K_DOWN:
                    hero.FaceDown()

        allSprites.clear(screen, background)
        allSprites.update()
        allSprites.draw(screen)

        pygame.display.flip()

    pygame.mouse.set_visible(True)

if __name__ == "__main__":
    main()

Share this post


Link to post
Share on other sites
Advertisement
I just noticed I hade used a variable called FacingDeg instead of FacingDir. I changed this without any effect at the moment.

Share this post


Link to post
Share on other sites
In Python you must explicitly have "self." before any variables that are members of the class. Namely, "FacingDir" in the Face*() functions are referencing _local variables_, not FacingDir variable of Pacman. Hence, you should replace those with "self.FacingDir".

Share this post


Link to post
Share on other sites
Okay, finally I understand the use of self a little better :) Thank you. But this still doesn't make my Update function work. I tried to change the name of the Update function to update (with a lowercase "U") and it made my "game" work just like it should. Why? Do I override the update function of pygame.sprite.Sprite this way?

Share this post


Link to post
Share on other sites
Yes, the way pygame sprites work, the group update method just calls the update method of all the sprites (the default implementation does nothing). Python is case sensitive.

Share this post


Link to post
Share on other sites
Quote:
Original post by Zyndrof
Okay, finally I understand the use of self a little better :) Thank you. But this still doesn't make my Update function work. I tried to change the name of the Update function to update (with a lowercase "U") and it made my "game" work just like it should. Why? Do I override the update function of pygame.sprite.Sprite this way?

Yes, that's exactly what we are doing overriding the inherited sprite class update method since by default it does nothing.

Sprite.update

method to control sprite behavior
Sprite.update(*args):

The default implementation of this method does nothing; it's just a convenient "hook" that you can override. This method is called by Group.update - call the update method on contained Sprites with whatever arguments you give it.

There is no need to use this method if not using the convenience method by the same name in the Group class.

And if you are used to a case-insenstive language like VB Python does take some extra work to get used to.
A good Python ide like EasyEclipse I just started using for my Python programming would help out with such things.

Share this post


Link to post
Share on other sites
Well, I'm working mainly in PHP at the moment, so case-sensitivity isn't any problem. It's just that I have my own way of writing code, and function names allways start with an uppercase letter, whilst variables never do.

Share this post


Link to post
Share on other sites
If function names always start with an uppercase letter, and variables never start with an uppercase letter, how would you pass a function as a parameter to another function? Temporarily allow a function to start with a lowercase letter? Technically there isn't even a difference between variables that contain functions and variables that contain other types, and Python actually treats member functions of an object as member variables of that object's class. It is possible (although not recommended in most circumstances) to replace a function of a class with an entirely different function at any time. Maybe it's best not to think about that too much...

class MyClass(object):
def talk(self):
print "Hello"

o = MyClass()
o.talk() # prints "Hello"

def f(self): print("Goodbye")
g = o.talk

MyClass.talk = f
o.talk() # prints "Goodbye"

g() #prints "Hello"


A bit confusing, but entirely legal in python. Don't do this sort of thing unless you really know what you're doing (and even then, think it over a few more times).

And then all functions and classes in python are objects and therefore both are stored in global variables anyway, and the standard python libraries sometimes use different conventions, and sometimes you don't even care if something is a function object or a function or a class...so I guess using what works for you is ok.

[Edited by - Vorpy on July 20, 2007 11:21:56 AM]

Share this post


Link to post
Share on other sites
Quote:
Original post by Vorpy
If function names always start with an uppercase letter, and variables never start with an uppercase letter, how would you pass a function as a parameter to another function?

Parameters are not variables:
object.Function(SomeOtherFunction)

Parameter values may be held in variables for function implementation:
def Function(func):
...
func(self.someVar)
...

Really, there is no conflict. func isn't a function, as far as Function is concerned; it is an object that implements __call__ - an instance, a variable.

The real problem is that Zyndrof's convention of functions-start-with-uppercase is incompatible with the library he is using (PyGame), and indeed with most Python libraries. His options are to adjust his code to match the library, wrap the library for consistency with his own code, or come to terms with the inconsistency and let usage describe type rather than visual signifiers.

Quote:
Original post by Vorpy
And then all functions and classes in python are objects and therefore both are stored in global variables anyway...

False. Functions and classes are scoped:
>>> class SomeClass:
... class OtherPrivateClass:
... def __init__(self, var):
... self.value = var
...
... def __init__(self, x):
... self.value = OtherPrivateClass(x)
...

>>> b = SomeClass(12)
...
NameError: global name 'OtherPrivateClass' is not defined

self.OtherPrivateClass works. SomeClass.OtherPrivateClass works. Also, dir() reveals that OtherPrivateClass is not a symbol in the default/global namespace, but it is in SomeClass.

Share this post


Link to post
Share on other sites
Quote:
Original post by Zyndrof
Well, I'm working mainly in PHP at the moment, so case-sensitivity isn't any problem. It's just that I have my own way of writing code, and function names allways start with an uppercase letter, whilst variables never do.


I guess you could alias it:


Pacman.update = Pacman.Update


Ah, the beauty of "everything is an object" :)

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
  • Advertisement
  • Popular Now

  • Advertisement
  • Similar Content

    • By Chamferbox
      Chamferbox, a mini game asset store has just opened with some nice game assets, 
      Here you can find a free greek statue asset 

      Also check their dragon, zombie dragon and scorpion monster out:



      They're running the Grand Opening Sale, it's 30% off for all items, but for gamedev member, you can use this coupon code:
      GRANDOPEN
      to get 50% off prices What are you waiting for, go to
      http://chamferbox.com
      and get those models now!

      View full story
    • By Dafu
      FES Retro Game Framework is now available on the Unity Asset Store for your kind consideration!
      FES was born when I set out to start a retro pixel game project. I was looking around for an engine to try next. I tried a number of things, from GameMaker, to Fantasy Consoles, to MonoGame and Godot and then ended up back at Unity. Unity is just unbeatable in it's cross-platform support, and ease of deployment, but it sure as heck gets in the way of proper retro pixel games!
      So I poured over the Unity pipeline and found the lowest levels I could tie into and bring up a new retro game engine inside of Unity, but with a completely different source-code-only, classic game-loop retro blitting and bleeping API. Months of polishing and tweaking later I ended up with FES.
      Some FES features:
      Pixel perfect rendering RGB and Indexed color mode, with palette swapping support Primitive shape rendering, lines, rectangles, ellipses, pixels Multi-layered tilemaps with TMX file support Offscreen rendering Text rendering, with text alignment, overflow settings, and custom pixel font support Clipping Sound and Music APIs Simplified Input handling Wide pixel support (think Atari 2600) Post processing and transition effects, such as scanlines, screen wipes, screen shake, fade, pixelate and more Deploy to all Unity supported platforms I've put in lots of hours into a very detail documentation, you can flip through it here to get an better glimpse at the features and general overview: http://www.pixeltrollgames.com/fes/docs/index.html
      FES is carefully designed and well optimized (see live stress test demo below). Internally it uses batching, it chunks tilemaps, is careful about memory allocations, and tries to be smart about any heavy operations.
      Please have a quick look at the screenshots and live demos below and let me know what you think! I'd love to hear some opinions, feedback and questions!
      I hope I've tickled your retro feels!



      More images at: https://imgur.com/a/LFMAc
      Live demo feature reel: https://simmer.io/@Dafu/fes
      Live blitting stress test: https://simmer.io/@Dafu/fes-drawstress
      Unity Asset Store: https://www.assetstore.unity3d.com/#!/content/102064

      View full story
    • By DevdogUnity

      Ho ho ho
      Tis the season of Christmas surprises, and we have a awesome one for you! 🎅  
      Sponsored by all your favorite Unity Asset Store developers, Nordic Game Jam, Pocket Gamer Connects, and co-hosted by Game Analytics, we (Joris and I – Devdog) are launching the second edition of our yearly Christmas Giveaway Calendar for all Unity game developers!
      You can already now sign up right here.
       
      So what’s this all about?
      For the past weeks, we’ve been collecting sponsored gifts related to Unity (asset vouchers, product keys, conference tickets etc.), and throughout each day of December leading up to Christmas Day on the 25th, we will be sending out these sponsored gifts as early gamedev Christmas presents via e-mail to hundreds of lucky winners.
      The total prize pool is at $35,000, with over 1200 presents donated by the awesome sponsors!
       
      Merry Christmas from Devdog, Game Analytics, and every single one of the sponsors.

      View full story
    • By sveta_itseez3D
      itSeez3D, a leading developer of mobile 3d scanning software, announced today a new SDK for its automatic 3D avatar generation technology, Avatar SDK for Unity. The Avatar SDK for Unity is a robust plug-n-play toolset which enables developers and creatives to integrate realistic user-generated 3D avatars into their Unity-based applications. SDK users can allow players to create their own avatars in the application or integrate the SDK into their own production processes for character design and animation.
      “Virtual avatars have recently become increasingly popular, especially in sports games and social VR apps. With the advance of VR and AR, the demand to get humans into the digital world is only increasing”, said Victor Erukhimov, itSeez3D CEO. “Our new Avatar SDK for Unity makes it super-easy to bring the avatar technology into any Unity-based game or VR/AR experience. With the Avatar SDK for Unity now every developer can bring face scanning technology into their games and allow players to create their own personalized in-game avatars, making the gameplay much more exciting and immersive.”
      Key features of the Avatar SDK for Unity:
      Automatic generation of a color 3D face model from a single selfie photo in 5-10 seconds (!). Works best with selfies, but can be used with any portrait photo.
      Shape and texture of the head model are unique for each person, synthesized with a deep learning algorithm crafted by computer vision experts
      Head models support runtime blendshape facial animations (45 different expressions)
      Generated 3D heads include eyes, mouth, and teeth
      Algorithms synthesize 3D meshes in mid-poly resolution, ~12k vertices, and ~24k triangles
      Six predefined hairstyles with hair-recoloring feature (many more available on request)
      Avatar generation API can be used in design-time and in run-time, which means you can allow users to create their own avatars in your game
      Cloud version is cross-platform, and offline version currently works on PCs with 64-bit Windows (support for more platforms is coming soon)
      Well-documented samples showcasing the functionality.
       
      Availability
      The Avatar SDK for Unity is offered in two modes - “Cloud” and “Offline”. The “Cloud” version is available at http://avatarsdk.com/ and the “Offline” version is available by request at support@itseez3d.com.
      ###
      About itSeez3D
      At itSeez3D, we are working on the computer vision technology that turns mobile devices into powerful 3D scanners. itSeez3D has developed the world's first mobile 3D scanning application that allows to create high-resolution photorealistic 3D models of people's' faces, bodies and objects. The application is available for iOS and Windows OS mobile devices powered with 3D cameras. In 2016 the company introduced Avatar SDK that creates a realistic 3D model of a face from a single selfie photo. To learn more about itSeez3D scanning software and 3D avatar creation technology, please visit www.itseez3d.com and www.avatarsdk.com.

      View full story
    • By khawk
      Unity has posted the Unity Austin 2017 playlist on YouTube. From their tweet:
      View the full playlist at https://www.youtube.com/playlist?list=PLX2vGYjWbI0TI_C4qouDw7MSSTFhKJ6uS or below:
      .

      View full story
  • Advertisement