Search code examples
pythongraphicskivywidgetkivy-language

Rotate a vertical rectangle to an horizontal one with Python Kivy - How?


I'm trying to program a game with Python Kivy, only get stuck on one thing, will be a simple question, but I have not found a solution anywhere.

I want the line in the middle of the screen (see picture attached) to be horizontal instead of vertical, meaning from left to right. Is there any method to rotate this? Or what do I have to change in the script?

Change vertical line to horizontal

Here is my script that creates the graphic:

<PongGame>:
    canvas:
       Rectangle:
          pos:    self.center_x - 5, 0
          size: 10, self.height

I would appreciate any help. Keep in mind, I'm still pretty much a beginner.

Best regards,

PyBeginner


Solution

  • A good way to do that is using kv, like this:

    <PongGame>:
        rotate: False  # property to control rotation
        canvas:
            Rectangle:
                pos:  (0, self.center_y - 5) if self.rotate else (self.center_x - 5, 0)
                size: (self.width, 10) if self.rotate else (10, self.height)
    

    This code define a property (rotate) of PongGame that controls the rotation. If rotate is False, then your original Rectangle is drawn, but if rotate is True, then a rotated Rectangle is drawn. A similar result could be attained using python code, but then you must write more code (bindings) to handle situations where the user changes the size of the PongGame. Doing it all in kv lets kivy handle those bindings.

    Once you have this code in place, you can just rotate the PongGame using a method such as:

    def rotate(self, dt):
        self.root.rotate = not self.root.rotate
    

    In your PongApp.