How To Find The Distance (in Pixels) Between The Sprite And Screen Corners?
I need to find the distance (in pixels) between the animated worker objects and the 4 corners of the screen (upper left, upper right, lower left, lower right). Which function of py
Solution 1:
You could create point vectors for the corners and then just subtract the position of the sprite (I just use the mouse pos here) to get vectors that point to the corners and finally call the length
method to get the lengths of these vectors.
import pygame as pg
from pygame.math import Vector2
pg.init()
screen = pg.display.set_mode((640, 480))
width, height = screen.get_size()
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
# Create point vectors for the corners.
corners = [
Vector2(0, 0), Vector2(width, 0),
Vector2(0, height), Vector2(width, height),
]
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
mouse_pos = pg.mouse.get_pos()
# Subtract the position from the point vectors and call the `length`
# method of the resulting vectors to get the distances to the points.
# Subtract the position from the point vectors and call the `length`
# method of the resulting vectors to get the distances to the points.
distances = []
for vec in corners:
distance = (vec - mouse_pos).length()
distances.append(distance)
# The 4 lines above can be replaced by a list comprehension.
# distances = [(vec - mouse_pos).length() for vec in corners]
# I just display the distances in the window title here.
pg.display.set_caption('{:.1f}, {:.1f}, {:.1f}, {:.1f}'.format(*distances))
screen.fill(BG_COLOR)
pg.display.flip()
clock.tick(60)
Post a Comment for "How To Find The Distance (in Pixels) Between The Sprite And Screen Corners?"