SasuX
SasuX

Reputation: 11

How to rotate a Vector2 in pygame

I am trying to make something like a clock, but I am having trubles rotating the vector. For what I can tell the vector is rotating in respect of the point (0, 0) of the screen, but I want it to rotate in respect of the 'center' vector.

Another problem I am having is that, even tho the fps are locked on 60, it seems like the vector is speeding up.

Here's the code:

import pygame, sys
from pygame import Vector2

pygame.init()
screen = pygame.display.set_mode((500, 500))
clock = pygame.time.Clock()
SCREEN_UPDATE = pygame.USEREVENT
pygame.time.set_timer(SCREEN_UPDATE, 100)

angle = 0
vector = Vector2(250, 100)
center = Vector2(250, 200)

while True:
    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        if event.type == SCREEN_UPDATE:
            vector.rotate_ip(angle)
            angle += 1


    screen.fill('black')
    pygame.draw.line(screen, 'white', center, vector)

    pygame.display.flip()
    clock.tick(60)

I was expecting the vector to rotate with a constant speed and in respect to the 'center' vector.

Upvotes: 1

Views: 417

Answers (1)

Rabbid76
Rabbid76

Reputation: 210909

rotate_ip rotates the vector itself. As you increase the angle, the vector rotates more and more with each iteration. You must rotate the vector in place by a constant angle at each iteration:

vector.rotate_ip(1)

The other option is to create a new vector from the original vector with increasing angle with the rotate function:

original_vector = Vector2(250, 100)
vector = Vector2(original_vector)

while True:
    for event in pygame.event.get():
        # [...]

        if event.type == SCREEN_UPDATE:
            vector = original_vector.rotate(angle)
            angle += 1

Upvotes: 2

Related Questions