Search code examples
pythonpython-2.7pygamerect

How to change a regular image to a Rect in pygame


I need the simplest way of making an image a Rect, is there a function for this or do I need to make it a Rect from the beginning? I have a script were the player moves around but I want the image of the character to be a Rect, so I can do more with it.


Solution

  • I want the image of the character to be a rect doesn't make a lot of sense, but you're probably looking for the get_rect method of the Surface class:

    get_rect()
    get the rectangular area of the Surface
    get_rect(**kwargs) -> Rect
    Returns a new rectangle covering the entire surface. This rectangle will always start at 0, 0 with a width. and height the same size as the image...

    (I guess with regular image you mean a Surface, since a Surface is how pygame represents images)

    Note that the Rect returned by this function always starts at 0, 0. If you already track the position of your object somehow (say a x and y variable), you could either

    • drop those variables and only use a Rect to keep track of the position of your object. If you move your object, instead of altering the x and y variable (e.g. x += mx/y += my), you would just update the Rect (e.g. pos.move_ip(mx, my) where pos is the Rect).

    • create a new Rect whenever you need a Rect, and make sure it points to the right location, using named arguments (e.g. your_surface.get_rect(x=x, y=y))

    • use a Sprite, which is basically a combination of a Surface and a Rect.