Pygame's rect object 'stretches' instead of moving [duplicate] - python

This question already has answers here:
How can I move the ball instead of leaving a trail all over the screen in pygame?
(1 answer)
Why is nothing drawn in PyGame at all?
(2 answers)
Closed 2 years ago.
I am currently creating my first Python game using pygame and have now come across something that baffles me so I would appreciate your help.
In the current statues of the game, all that there is on the screen is an image of a space ship over a white background (gameDisplay.fill(white)) that can only move up and down, located at the left side of the screen. When clicking on the space bar, the space ship shoots two laser beams (or basically creates two thin rects that move from left to right, changing x position but keeping the y position so that the movement would be only horizontal).
The problem that I have is that instead of moving from left to right, it seems as though the 'lasers' stretch out to the right, so that the left side of the rect stays near the space ship image on the left of the screen while the right side of the rect moves to toward the right side of the screen.
As shown in the image below:
Laser stretching out
After playing around with the problem, I found that if I use an image as a background instead of filling the background with the color white, everything works as it should.
In the image below you can see how it looks when I use a plain white picture as a background image (Using bg = pygame.image.load("img\white_background.png" and then blitting it inside the game loop before all other drawings):
Laser working fine
I currently have 4 files that make up the game:
1 main.py:
import time
import pygame
from first_game.game_loop import game_loop
from first_game.space_ship import space_ship
pygame.init()
display_width = 800
display_height = 600
colors = {
'black':(0, 0, 0),
'white':(255, 255, 255),
'red':(255, 0, 0)
}
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('First game')
clock = pygame.time.Clock()
gameDisplay.fill(colors['white'])
player = space_ship("img\\space_ship.png","player",103,103)
game_loop(gameDisplay,display_width,display_height,clock, player, bg)
2 game_loop.py:
import pygame
import first_game.methods
def game_loop(gameDisplay, display_width, display_height, clock, space_ship, bg):
space_ship_x = (display_width * 0.05)
space_ship_y = (display_height * 0.45)
space_ship_y_change = 0
both_laser_x = 0
top_laser_y = 0
bottom_laser_y = 0
both_laser_width = 50
both_laser_height = 5
laser_speed = 15
laser_adjustment_x = 70
laser_adjustment_y = 18
laser_fired = False
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
space_ship_y_change = -5
if event.key == pygame.K_DOWN:
space_ship_y_change = 5
if event.key == pygame.K_SPACE:
top_laser_y = space_ship_y + laser_adjustment_y
bottom_laser_y = space_ship_y + space_ship.height - laser_adjustment_y
both_laser_x = space_ship_x + space_ship.width - laser_adjustment_x
laser_fired = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
space_ship_y_change = 0
if both_laser_x>display_width:
laser_fired=False
first_game.methods.space_ship(space_ship.img_location, space_ship_x, space_ship_y, gameDisplay)
if laser_fired == True:
first_game.methods.laser(gameDisplay,both_laser_x, top_laser_y,bottom_laser_y,both_laser_width,both_laser_height)
both_laser_x += laser_speed
if space_ship_y == -20:
if space_ship_y_change<0:
space_ship_y_change=0
if space_ship_y+space_ship.height>=display_height+20:
if space_ship_y_change>0:
space_ship_y_change=0
space_ship_y = space_ship_y + space_ship_y_change
pygame.display.update()
clock.tick(60)
3 methods.py:
def space_ship(space_ship_location, x, y, gameDisplay):
space_ship_img = pygame.image.load(space_ship_location)
gameDisplay.blit(space_ship_img, (x, y))
def laser(gameDisplay,x,y1,y2,w,h):
pygame.draw.rect(gameDisplay, (255,0,0), [x, y1, w, h])
pygame.draw.rect(gameDisplay, (255,0,0), [x, y2, w, h])
4 space_ship.py
class space_ship():
def __init__(self,img_location, type, width, height):
self.img_location = img_location
self.type = type
self.width = width
self.height = height

Related

How to change variables inside a class at runtime?

Follow-up question on my previous question.
After I got the circle to show up properly, I wish to be able to move that circle now with keyboard input.
Since it is a class I am trying to change I must have an instance so that I change the same instance of the class all the time, and I do have one.
import pygame
pygame.init()
#Colors
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
#Display
display_width, display_height = 800, 600
screen_center = int(display_width * 0.5), int(display_height * 0.5)
screen = pygame.display.set_mode((display_width, display_height))
#Clock
clock = pygame.time.Clock()
class Player():
def __init__(self):
self.xPos = int(display_width * 0.5)
self.yPos = int(display_height * 0.5)
self.color = blue
self.radius = 15
self.width = 0
pygame.draw.circle(screen, self.color, (self.xPos, self.yPos), self.radius, self.width)
def game_loop():
player = Player() #PLAYER CLASS INSTANCE
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.color = blue # THESE COLORS ARE MAINLY HERE FOR DEBUGGING
if event.key == pygame.K_RIGHT:
player.color = red # THESE COLORS ARE MAINLY HERE FOR DEBUGGING
if event.key == pygame.K_UP:
pass
if event.key == pygame.K_DOWN:
pass
#Background
screen.fill(white)
#Draw everything in order, each drawn object will be drawn beneath the next drawn object.
player
#Update
pygame.display.update()
clock.tick(60)
game_loop()
So whenever I press the left key for example, the xPos inside the class must change so that my circle moves.
You could try changing your player class to make it have a separat emethod for drawing itself:
class Player():
def __init__(self):
self.xPos = int(display_width * 0.5)
self.yPos = int(display_height * 0.5)
self.color = blue
self.radius = 15
self.width = 0
def draw(self):
pygame.draw.circle(screen, self.color, (self.xPos, self.yPos), self.radius, self.width)
Then inside your main loop, call player.draw() after you've done the screen fill:
#Background
screen.fill(white)
#Draw everything in order, each drawn object will be drawn beneath the next drawn object.
player.draw()
Now the player object wont draw itself when it's created, instead it will be drawn during every iteration of your main loop.

pygame: drawing a selection rectangle with the mouse

I have written a simple breakout game in pygame and am writing a level editor. Everything was working until I tried to add a selecting rectangle that has the transparent look (like the one on my desktop background). I can get a rectangle (sorta) but everything else vanishes, and it isn't semi-transparent.
code:
pygame.init()
screen = pygame.display.set_mode(size)
mousescreen = pygame.Surface((screen.get_size())).convert_alpha()
...
in the designing loop:
global xpos, ypos, theBricks, clock, mousedrag, mouseRect
global designing, titles
global theLevels, level, cur_max_level, max_level
mousedrag = False
mouseRect = None
mouseDown = False
while designing:
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
mouseDown = True
mpos = pygame.mouse.get_pos()
x_position = mpos[0]
y_position = mpos[1]
xpos = ((x_position-left)/BRW) * BRW + left
ypos = ((y_position-top)/BRH) * BRH + top
elif event.type == MOUSEMOTION:
if mouseDown:
newx_pos = mpos[0]
newy_pos = mpos[1]
mousedrag = True
if mousedrag:
mouseRect = Rect(newx_pos, newy_pos, xpos, ypos)
elif event.type == MOUSEBUTTONUP:
if mousedrag:
mousedrag = False
else:
if is_a_brick(xpos, ypos):
del_brick(xpos, ypos)
else:
make_brick(xpos, ypos)
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
designing = False
titles = True
...
in the update screen function:
for bricks in theBricks:
pygame.draw.rect(screen, GREEN, bricks.rect)
if mousedrag:
pygame.draw.rect(mousescreen, RED, mouseRect, 50)
screen.blit(mousescreen, (0,0))
pygame.draw.rect(screen, WHITE, (xpos, ypos, BRW, BRH))
pygame.display.update()
The rectangle is not transparent and everything else vanishes off the screen? Where am I going wrong?
I'm not sure if .convert_alpha() is creating a transparent screen like you think. Try setting the alpha level on mousescreen explicitly:
mousescreen = pygame.Surface((screen.get_size()))
mousescreen.set_alpha(100) # this value doesn't have to be 100
Another way to achieve the same effect is to draw your rect as 4 lines directly onto the screen which means you don't have to have mousescreen at all. In your update screen function:
if mousedrag:
mouseRectCorners = [mouseRect.topleft,
mouseRect.topright,
mouseRect.bottomright,
mouseRect.bottomleft]
pygame.draw.lines(screen, RED, True, mouseRectCorners, 50)
Just make sure you draws these lines after any other objects or they might get hidden. I'm not sure if this option is really considered best practice but it's always good to have options.

Python pygame balls moving

I am writing a simple "game" and I have three questions for you:
How can I make all the balls moving independetly?
When I drag a ball with a mouse and click on the screen, how can i make the ball stay there. I want to draw it on that specific coordinate where the mouse key was pressed. It has to stay there all the time.
If a small ball touches the large one it shoud become a large one and dissapear after 10 seconds.
I have no idea how to do this. Can you please help me.
My code:
import pygame
import sys
from pygame.locals import *
import random
pygame.init()
width = 800
height = 600
fps = 25
clock = pygame.time.Clock()
black = (0, 0, 0)
white = (255, 255, 255)
display_window = pygame.display.set_mode((width, height))
pygame.display.set_caption('Bouncy')
game_over = False
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
x_cor = random.randint(15, width - 15)
y_cor = random.randint(15, height - 15)
x_change = random.randint(3, 7)
y_change = random.randint(3, 7)
coordinates = []
for i in range(10):
x = random.randint(0, width)
y = random.randint(0, height)
coordinates.append([x, y])
while not game_over:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
if event.type == pygame.mouse.get_pressed():
pass
x_cor += x_change
y_cor += y_change
display_window.fill(white)
mouse_x, mouse_y = pygame.mouse.get_pos()
for coordinate in coordinates:
pygame.draw.circle(display_window, (r, g, b), (coordinate[0], coordinate[1]), 15, 0)
pygame.draw.circle(display_window, black, (mouse_x, mouse_y), 25, 0)
pygame.draw.circle(display_window, (r, g, b), (x_cor, y_cor), 15, 0)
if x_cor > (width - 15) or x_cor < 15:
x_change = x_change * -1
if y_cor > (height - 15)or y_cor < 15:
y_change = y_change * -1
clock.tick(fps)
pygame.display.update()
First and foremost, do the research required before you post here (see the help documents on the intro tour). There are many tutorials on the Internet, and many answered questions in SO (StackOverflow) that deal with moving objects. To get you started in general:
You move the balls independently by keeping a separate set of coordinates for each ball. On each iteration of the game clock, you have to reiterate the new coordinates of each ball.
To make a ball stay in one place, simply do not change its coordinates.
To change the size of a ball, draw it with a larger radius. This means that you also have to remember the radius of each ball. To give it a 10-second lifetime, keep a "lifespan" for each ball; decrement it on each tick of the game clock.
Bascially, you need a Ball object (make a class Ball); instantiate a new object for each ball you need. Write methods to change the position, size, and life span of each ball.

How to make the object move during a while infinite loop?

I've been trying to create a game. In the game there is a jet that would fly into the recursive background rectangles. The rectangles are created through an infinite loop so once it enters the loop rest of the functions don't work for example the object. My code is below and the problem arises in the main loop. I want the object to move with the recursive rectangles but it freezes when the rectangles start being drawn in the loop. PS help to fix this as I've tried almost every code sample out there to fix it. Thank you
EDIT: the main function of the game is to make the jet go through what seems like recursive like rectangles (there are two of them and the while loop makes it simultaneously move up and down giving the feeling that the jet is going into the screen.). But since the jet is drawn first, when the program enters the rectangle loop the jet freezes and wont be able to move. I want the jet to move while the background is also moving.
import pygame
import random
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
Blue = (2,55,55)
black=(0,0,0)
end_it=False
def recursive_draw(x, y, width, height):
""" Recursive rectangle function. """
pygame.draw.rect(screen, WHITE,
[x, y, width, height],
1)
speed = [10,0]
rect_change_x = 10
rect_change_y = 10
# Is the rectangle wide enough to draw again?
if (width > 25):
# Scale down
x += width * .1
y += height * .1
width *= .8
height *= .8
# Recursively draw again
recursive_draw(x, y, width, height)
def recursive_draw2(x, y, width, height):
""" Recursive rectangle function. """
pygame.draw.rect(screen, Blue,
[x, y, width, height],
1)
speed = [10,0]
rect_change_x = 10
rect_change_y = 10
# Is the rectangle wide enough to draw again?
if (width > 25):
x += width * .1
y += height * .1
width *= .8
height *= .8
# Recursively draw again
recursive_draw2(x, y, width, height)
'''
def timer(self):
screen.fill(black)
myfont=pygame.font.SysFont("Britannic Bold", 40)
label2=myfont.render("Ready?", 1, (255, 0, 0))
screen.blit(label2, (350,250))
self =3
nlist=[]
for i in range (2):
score = myfont.render(str(self),1,(255,0,0))
screen.blit((score), (350,250))
self = self - 1
nlist.append(self)
pygame.display.flip()
'''
pygame.init()
#rectanglelist = [big()]
# Set the height and width of the screen
size = [700, 500]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("My Game")
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
USEREVENT = 0
pygame.time.set_timer(USEREVENT+1, 10)
milliseconds = 0
seconds = 0
start_it = False
while (end_it==False):
screen.fill(black)
myfont=pygame.font.SysFont("Britannic Bold", 40)
nlabel=myfont.render("Welcome to "+ " Jet shooter ", 1, (255, 0, 0))
label=myfont.render("Click on the mouse to start ", 1, (255, 0, 0))
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
end_it=True
screen.blit(nlabel,(200, 100))
screen.blit(label, (170,300))
pygame.display.flip()
while (start_it==False):
screen.fill(black)
myfont2=pygame.font.SysFont("Britannic Bold", 40)
label2=myfont2.render("Ready?", 1, (255, 0, 0))
screen.blit(label2, (300,250))
pygame.display.flip()
pygame.time.wait(3000)
start_it = True
fall = False
while (fall==False):
nlist = [3,2,1]
for i in (nlist):
screen.fill(black)
n = str(i)
myfont3=pygame.font.SysFont("Britannic Bold", 40)
score = myfont3.render(n,1,(255,0,0))
screen.blit((score), (350,250))
pygame.display.flip()
pygame.time.wait(1000)
screen.fill(black)
myfont4=pygame.font.SysFont("Britannic Bold", 40)
label4=myfont3.render("GOOO!!!", 1, (255, 0, 0))
screen.blit(label4, (300,250))
pygame.display.flip()
pygame.time.wait (1000)
fall = True
b = 0
flip = 1
a = 0
time = 100
x_speed = 0
y_speed = 0
x_coord = 320
y_coord = 400
image = pygame.image.load("spaceship.gif").convert()
# -------- Main Program Loop -----------
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# User pressed down on key
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_speed = -10
if event.key == pygame.K_RIGHT:
x_speed = 10
if event.key == pygame.K_UP:
y_speed = -10
if event.key == pygame.K_DOWN:
y_speed = 10
# User let go of key
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
x_speed = 0
if event.key == pygame.K_RIGHT:
x_speed = 0
if event.key == pygame.K_UP:
y_speed = 0
if event.key == pygame.K_DOWN:
y_speed = 0
x_coord += x_speed
y_coord += y_speed
# Set the screen background
screen.fill(BLACK)
screen.blit(image, [x_coord,y_coord])
pygame.display.flip()
clock.tick(60)
# ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
# ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT
# Go ahead and update the screen with what we've drawn.
# Limit to 60 frames per second
# Be IDLE friendly. If you forget this line, the program will 'hang'
# on exit.
while a == 0 :
if flip == 1 :
recursive_draw(35,25,625,450)
recursive_draw2(0, 0, 700, 500)
flip = flip + 1
pygame.display.flip()
clock.tick(60)
if flip == 2 :
recursive_draw(0, 0, 700, 500)
recursive_draw2(35, 25, 625, 450)
flip = flip - 1
pygame.display.flip()
clock.tick(60)
pygame.quit()
As #Paul Rooney has stated, you'll want to use threads. Here's how you would
import thread
.
.
.
# Instead of calling the function as you are, run it on a new thread
thread.start_new_thread(drawRectanglesFunction, ())
From what I can tell is that you're drawing things in the incorrect order, and I believe that while loop is not needed. (while a == 0). Another thing is that you're flipping the display too often it is hard to keep track of what gets drawn first, and what gets drawn afterwards. My suggestion would be to quickly rewrite your program so that it looks something similar to this:
flip = 1
while not done:
##Catch and handle events()
screen.fill(BLACK)
if flip == 1 :
recursive_draw(35,25,625,450)
recursive_draw2(0, 0, 700, 500)
flip = flip + 1
elif flip == 2 :
recursive_draw(0, 0, 700, 500)
recursive_draw2(35, 25, 625, 450)
flip = flip - 1
screen.blit(image, [x_coord,y_coord])
pygame.display.flip()
clock.tick(60);
I hope this helps out a little.
(Edit: I did this on my own and got the program to run)

Pygame Making A Sprite Face The Mouse [duplicate]

This question already has answers here:
Can't understand how to make character face mouse in PyGame
(2 answers)
How do I make my player rotate towards mouse position?
(1 answer)
How do I rotate an image around its center using Pygame?
(6 answers)
Closed 2 years ago.
Im New To Pygame But Kinda OK On Python, Im Creating A Zombie Shooting Game With an overhead view.
I managed to make the character move when pressing the arrow keys. But now i need to get the player to FACE the mouse/cursor without clicking the screen all the time.
Any Help?
for event in pygame.event.get():
if event.type == MOUSEMOTION:
mousex, mousey = event.pos
# build a vector between player position and mouse position
moveVector = (mousex-playerx, mousey-playery)
"""
compute the angle of moveVector from current vector that player is facing (faceVector).
you should be keeping and updating this unit vector, with each mouse motion
assume you have initial facing vector as (1,0) - facing East
"""
# compute angle as in [1]
# rotate the image to that angle and update faceVector
[1] - How to Find the Angle Between Two Vectors:
http://www.euclideanspace.com/maths/algebra/vectors/angleBetween/index.htm
Your image may lose quality when rotated at a small angle. It's discussed in Pygame documentation page: http://pygame.org/docs/ref/transform.html#pygame.transform.rotate
import math
mouseX, mouseY = pygame.mouse.get_pos()
playerX, playerY = player.get_pos()
angle = math.atan2(playerX-mouseX, playerY-mouseY)
You might have to fiddle with the order of subtraction (ie, it might be mousePosition-playerPosition) or the order of the x and y parameters to atan2 (ie, you might need to pass in the Y difference as the first parameter rather than the X) but that depends on your coordinate system.
working code :
import pygame, sys, math
from pygame.locals import *
#converte in base ai gradi le cordinate x,y
#maxXY= surface MaxXY
#gradoRot = grado di rotazione
#distXY = spostamento in x,y lungo il vettore di cordinate locali dalle cordinate x,y
#movement from one point to another
def Move(t0,t1,psx,psy,speed):
global mx
global my
speed = speed
distance = [t0 - psx, t1 - psy]
norm = math.sqrt(distance[0] ** 2 + distance[1] ** 2)
direction = [distance[0] / norm, distance[1 ] / norm]
bullet_vector = [direction[0] * speed, direction[1] * speed]
return bullet_vector
# Main Function
if __name__ == '__main__':
pygame.init()
FPS = 30 # frames per second setting
fpsClock = pygame.time.Clock()
# set up the window
DISPLAYSURF = pygame.display.set_mode((800, 600), 0, 32)
alfhaSurface = DISPLAYSURF.convert_alpha()
pygame.display.set_caption('test')
shipImg = pygame.image.load('ship.png')
shipImgcpy=shipImg.copy()
vetShip=pygame.math.Vector2(400,300)
gradi = 0
gradiRot=0
mouseX=0
mouseY=0
SHIP_W=40
SHIP_H=40
vetMouse=pygame.math.Vector2(mouseX,mouseY)
#main loop
while True:
DISPLAYSURF.fill((0,0,0))
alfhaSurface.fill((0,0,0))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == MOUSEBUTTONDOWN:
mouseX, mouseY = pygame.mouse.get_pos()
vetMouse=pygame.math.Vector2(mouseX,mouseY)
gradiRot=**math.atan2(vetShip.x-vetMouse.x, vetShip.y-vetMouse.y)**
gradiRot=**math.degrees(gradiRot)**
pygame.display.set_caption(""+str(gradi) +"="+ str(gradiRot)+" "+ str(vetMouse.angle_to(vetShip)) )
pygame.draw.line(alfhaSurface, (255,255,255), (vetShip.x+SHIP_W,vetShip.y+SHIP_H),(vetMouse.x,vetMouse.y),1)
if gradi != int(gradiRot) :
if gradiRot > gradi and gradi != gradiRot :
gradi=gradi+1
if gradiRot < gradi and gradi != gradiRot :
gradi=gradi-1
shipImgcpy=pygame.transform.rotate(shipImg.copy(),gradi)
elif int(vetMouse.distance_to(vetShip)) >0:
posNext=Move(mouseX,mouseY,vetShip.x+SHIP_W,vetShip.y+SHIP_H,1)
vetShip=pygame.math.Vector2(vetShip.x+posNext[0],vetShip.y+posNext[1])
alfhaSurface.blit(shipImgcpy, tuple(vetShip))
DISPLAYSURF.blit(alfhaSurface,(0,0))
pygame.display.update()
fpsClock.tick(FPS)
_, angle = (pg.mouse.get_pos()-self.pos).as_polar()
This line first calculates a vector to the mouse position (self.pos has to be a pygame.math.Vector2) and .as_polar() returns the polar coordinates of the vector which consist of the radial distance and the angle. Finally use the negative angle (because pygame's y-axis is flipped) to rotate the image of the sprite and recalculate the rect.
import pygame as pg
class Player(pg.sprite.Sprite):
def __init__(self, pos):
super().__init__()
self.image = pg.Surface((50, 30), pg.SRCALPHA)
pg.draw.polygon(
self.image,
pg.Color('dodgerblue1'),
((1, 1), (49, 15), (1, 29)))
self.orig_img = self.image
self.rect = self.image.get_rect(center=pos)
self.pos = pg.math.Vector2(pos)
self.vel = pg.math.Vector2(0, 0)
def update(self):
self.rotate()
self.pos += self.vel
self.rect.center = self.pos
def rotate(self):
_, angle = (pg.mouse.get_pos()-self.pos).as_polar()
self.image = pg.transform.rotozoom(self.orig_img, -angle, 1)
self.rect = self.image.get_rect(center=self.rect.center)
def main():
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
all_sprites = pg.sprite.Group()
all_sprites.add(Player((300, 200)))
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
all_sprites.update()
screen.fill((30, 30, 30))
all_sprites.draw(screen)
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
pg.init()
main()
pg.quit()
math.atan2 can be used as an alternative.
def rotate(self):
rel_x, rel_y = pg.mouse.get_pos() - self.pos
angle = -math.degrees(math.atan2(rel_y, rel_x))
self.image = pg.transform.rotozoom(self.orig_img, angle, 1)
self.rect = self.image.get_rect(center=self.pos)
if event.type == MOUSEBUTTONDOWN:
mouseX, mouseY = pygame.mouse.get_pos()
vetMouse=pygame.math.Vector2(mouseX,mouseY)
gradiRot=vetMouse.angle_to(vetShip)

Categories