Search code examples
python-2.7pyglet

Understanding anchor_x and anchor_y attributes in Pyglet


I am new to Python and game development and just started learning Pyglet (1.3.2). I am trying to play with labels and their positioning.

I understand that x and y coordinates indicate the pixel position of the labels/images on window. In cases of images or sprints, anchor values determine the position from which the image is anchored to screen (which in turn affects their movement).

However, I do not fully understand the affect of anchor in labels. According to this pyglet document, it says:

The position of the text is given by the x and y coordinates. The meaning of these coordinates is given by the anchor_x and anchor_y parameters.

What kind of meaning is implied here? If they have no movement, shouldn't their position remain fixed irrespective of anchor values?

Additionally, when I run program with these labels:

   label1 = pyglet.text.Label('Window1',font_name='Times New Roman', font_size=36, x=200, y=100,anchor_x='center', anchor_y='center')        
   label2 = pyglet.text.Label('Window2',font_name='Times New Roman', font_size=36, x=200, y=100,anchor_x='left', anchor_y='center')

It produces output which is again difficult to understand as Window1 (anchor_x='center') is more towards left than Window2 (anchor_x='left'):

enter image description here

Can someone please elaborate the significance of anchors and how is the final position of label calculated. Thanks!


Solution

  • So the way anchors work, is that they simply just define the placement point of a object. Meaning, if you have center as your anchor, the objects center will be placed at the given coordinate (in your case, x=200, y=100)

    And a bottom left anchor, will tell Pyglet to place the objects bottom left corner at the given position, rather than the center at those coordinates.

    If you analyze your own image, this will be quite clear, here the two dots are directly in line with each other:

    enter image description here

    They're being positioned at the same coordinate, but because you've re-defined the anchor - it will place the center or a corner at that position.

    In red, you've defined center as your anchor. And in blue you've defined bottom left (default).

    (ignore that the dots aren't perfectly aligned, it was tricky to do on a laptop touch pad while on a rocking train)

    Hopefully this makes sense. Also see my above comment for another way of describing this.