0

I am making a cat and mouse concept game inspired by a numberphile video I watched a couple years ago. My main goal is to be able to rotate a rectangle around a circle while always tangent.cat rotating to another spot on circle

the filled in rectangle should be facing towards the right

I believe I know how to make a rectangle rotate around a circle, it's just making it tangent to it all the time is the difficult part.

Here is some of the relevant code:

class Cat:
    def __init__(self, surface:pygame.Surface, bound:Boundry) -> None:
        self.surf = surface
        self.boundry = bound
        self.w, self.h = 20, 30
        
        
        self.x = self.boundry.x + self.boundry.radius *  + math.cos(0) - self.w // 2
        self.y = self.boundry.y + self.boundry.radius * math.sin(0) - self.h

        self.angle = math.atan2(self.x, self.y)

        self.rect_surface = pygame.Surface((self.x, self.y))
        self.rect = pygame.Rect((self.x, self.y), (self.w, self.h))


    def draw(self):
        pygame.draw.rect(self.surf, (255, 0, 0), self.rect)

Also github incase you want to contribute: https://github.com/cranberry0620/Cat-Mouse

MBo
  • 77,366
  • 5
  • 53
  • 86
cranberry
  • 73
  • 2
  • 7
  • 1
    It's all simple trigonometry. Your variable here is the angle. Your solid rectangle is at 0 degrees, your hollow one is at 45 degrees. The tangent point is then `center.x + radius * math.cos(theta)` and `center.y + radius * math.sin(theta)`, where theta is the degree in radians. – Tim Roberts Jun 15 '23 at 03:18
  • I should point out that the way I programmed it is based on where the center of the circle is. The rectangle is using that radius and other parameters to define where the rectangle should be placed. I'll go ahead and edit it to show the code that makes this. – cranberry Jun 15 '23 at 03:38

1 Answers1

0

Seems pygame rect is only axis-aligned (it is defined by two corners), so you'll need 4-sided polygon. To calculate it's vertices, we can do the next:

dx, dy are components of unit direction vector. They are cosine and sine of direction angle, but we don't need to use trigonometry intensively.

cx, cy, radius are circle parameters

w, h are width and height of rectangle

Tangent point is

tx = cx + radius * dx
ty = cy + radius * dy

Vertices in order:

v[0].x = tx + dy * w/2
v[0].y = ty - dx * w/2

v[1].x = v[0].x + dx * h
v[1].y = v[0].y + dy * h

v[2].x = v[1].x - dy * w
v[2].y = v[1].y + dx * w

v[3].x = tx - dy * w/2
v[3].y = ty + dx * w/2
MBo
  • 77,366
  • 5
  • 53
  • 86