Getting a Circle to Move in a Continuous Path

Hey guys,
I’m trying to get my “enemy” which is a circle to move in a continuous path going right up left down and returning to its starting position. You can imagine the enemy to be moving along this path as a sentry or guard moving along the same route constantly.

The way I thought of doing this was manipulating the Enemy::update() in my Enemy.cpp file in order to simulate this movement:

This is the code in my Enemy.cpp class:

#include "Enemy.h"
#include "ofMain.h"

Enemy::Enemy() {
	// Initial Position
	middle.x = 300;
	middle.y = 300;
	loop = 0;
}

void Enemy::update() {
	// moves right to 400 x
	if (loop == 0) {
		while (middle.x <= 400) {
			middle.x = middle.x + 2;
		}
		if (middle.x == 400) {
			loop = 1;
		}
	}
	// moves up to 400 y

	if (loop == 1) {
		while (middle.y <= 400) {
			middle.y = middle.y + 2;
		}
		if (middle.y == 400) {
			loop = 2;
		}
	}
	// moves left to 300 x
	if (loop == 2) {
		while (middle.x >= 300) {
			middle.x = middle.x - 2;
		}
		if (middle.x == 300) {
			loop = 3;
		}
	}
	// moves down to 300 y
	if (loop == 3) {
		while (middle.y >= 300) {
			middle.y = middle.y - 2;
		}
		if (middle.y == 300) {
			loop = 0;
		}
	}
}
void Enemy::draw() {
	ofDrawCircle(middle.x, middle.y, 20);
}

As you can see I am using simple if and while loops, but it doesn’t work. There has to be a simpler way of doing this would anyone know?

Hi,
The while loop seems to be the problem.
You basically run through all ‘loop’-states within one update()-call.
Changing it simply to if will make it work I think.
Then the update()-function will reach its end, so you can call draw() afterwards.
Good luck

1 Like

Thank you very much! I removed the while loops and now it works.

1 Like