R
R
Roma Kotolup2021-04-29 21:52:43
Python
Roma Kotolup, 2021-04-29 21:52:43

How to make an object rotate to the mouse cursor in python pygame?

How to make an object rotate to the mouse cursor in python pygame?
There was a question here . but I don't understand anything! Can someone give me the code (on scratch, you can do it like this: 608b006e0d701254714995.png)? (what I punched:

import pygame
import pygame as pg
import sys
import ctypes
from random import *
import time
import tkinter as tk
from PIL import ImageGrab
import os
import math
print(os.getcwd())
FPS = 60
W = 900  # ширина экрана
H = 900  # высота экрана
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
BLUE = (0, 70, 225)
BLACK = (0, 0, 0)
RED = (220, 0, 0)
DARKGRAY = (40, 40, 40)
PURPLE = (120, 0, 120)
BROWN = (148, 19, 19)
ORANGE = (255, 179, 0)
pg.init()
clock = pygame.time.Clock()
camera = bool(input())
if camera == True:
    sc = pygame.display.set_mode((W, H))
else:
    sc = pygame.display.set_mode((W, H), pygame.FULLSCREEN)

bmp = "ball.png"
bmp_дерево = pygame.image.load(bmp)
bmp_дерево.set_colorkey((255, 255, 255))
bmp_image = bmp_дерево.get_rect(center=(150, 700))
sc.blit(bmp_дерево, bmp_image)
def rotate(oject2):
    mouse_x, mouse_y = pygame.mouse.get_pos()
    rel_x, rel_y = mouse_x - 0, mouse_y - 0
    angle = (180 / math.pi) * -math.atan2(rel_y, rel_x)
    return angle
while 1:
    sc.fill((110, 180, 110))
    for i in pygame.event.get():
        if i.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
    bmp_дерево = pygame.transform.rotate(bmp_дерево, rotate(bmp_image))
    bmp_image = bmp_дерево.get_rect(center=(150, 700))
    sc.blit(bmp_дерево, bmp_image)
    pressed = pygame.mouse.get_pressed()
    pos = pygame.mouse.get_pos()
    pygame.draw.rect(sc, GREEN, (pos[0] - 10, pos[1] - 10, 20, 20))
    pygame.display.update()
    pygame.time.delay(20)
    clock.tick(FPS)
, but the ball just stands still and sometimes barely spins!)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
o5a, 2021-05-01
@roma2

Problem 2.
1. You need to rotate the original image, and not a copy already changed by the previous rotation. Because of this, memory will be clogged, and most likely that's why he

sometimes it barely spins!)

Those. change something like this:
bmp_дерево_rot = pygame.transform.rotate(bmp_дерево, rotate(bmp_image))
bmp_image = bmp_дерево_rot.get_rect(center=(150, 700))
sc.blit(bmp_дерево_rot, bmp_image)

2. To calculate the rotation angle, in addition to the mouse coordinates, you must specify the correct coordinates of the image itself, and not 0.0.
def rotate(oject2):
    mouse_x, mouse_y = pygame.mouse.get_pos()
    x, y = bmp_image.center
    rel_x, rel_y = mouse_x - x, mouse_y - y
    angle = (180 / math.pi) * -math.atan2(rel_y, rel_x)
    return angle

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question