# Animation of moving circle by square's outer surface

I want to make this animation in OpenGL, here I attached a simple gif how I want it to looks like: Main problem is that I can not figure out how to move by corner - circle should smoothly move by corner, not to just jump to another side's begin position.

import Blender
from Blender import Draw,BGL
from Blender.BGL import *
from math import sin,cos
import time

squareLength, squareX, squareY, circleRadius = 200, 200, 200, 20
movingX, movingY = 0, 0

def event(evt, val):
if evt == Draw.ESCKEY :
Draw.Exit()

def gui():
global movingX, movingY

glClearColor(0.17, 0.24, 0.31, 1.0)
glClear(BGL.GL_COLOR_BUFFER_BIT)
glLineWidth(1)
glColor3f(0.74, 0.76, 0.78)

glVertex2i(squareX, squareY)
glVertex2i(squareX, squareY + squareLength)
glVertex2i(squareX + squareLength, squareY + squareLength)
glVertex2i(squareX + squareLength, squareY)
glEnd()

glColor3f(0.58, 0.65, 0.65)

glPushMatrix()

if movingY < squareLength:
movingY += 1
else:
movingX = 0
else:
if movingY == squareLength + circleRadius:
if movingX < squareLength:
movingX += 1
else:
movingY = squareLength
else:
if movingY < 0:
if movingX > 0:
movingX -= 1
else:
movingY = 0
else:
if movingY > 0:
movingY -= 1
else:
movingX = squareLength

glTranslatef(movingX, movingY, 0)

glBegin(GL_LINE_LOOP)
for i in xrange(0, 360, 1):
glEnd()

glPopMatrix()

Draw.Redraw(1)

Draw.Register(gui, event, None)


Can you please say me, how can I optimize this code to make circle moving by corners?

Just start learning computer graphics and think up such exercises for training, so I will really appreciate for any help.

• the center follows a rounded rectangle – ratchet freak Nov 18 '13 at 17:46
• @ratchetfreak but in that way circle will a bit overlap a corner – Lu Vue Nov 18 '13 at 18:21
• offset it by the radius of the circle – ratchet freak Nov 18 '13 at 23:19

Just did this using SDL but the theory is the same.

Make your circle orbit your square by the distance from the center of the square to the corner plus the radius of your circle.

Then limit the distance your circle can be from your square. Minimum would be -half square width -circle radius, maximum would be +half square width +circle radius.

Here's the code I used:

circle.x = lim(cos(circlePos*(3.1415/180))*(sqrt((float)sqrd(square.w/2)+(float)sqrd(square.h/2))+(circle.w/2)),(-square.w/2)-(circle.w/2),(square.w/2)+(circle.w/2))+square.x;
circle.y = lim(sin(circlePos*(3.1415/180))*(sqrt((float)sqrd(square.w/2)+(float)sqrd(square.h/2))+(circle.h/2)),(-square.h/2)-(circle.h/2),(square.h/2)+(circle.h/2))+square.y;


circle and squares are SDL_Rect structs that just store an x,y,w,h. lim() and sqrd() are functions that I made to simplify stuff.