Introduction to 2D Linux Game Programming/Algorithms/Simple Software Transformations/Flip Image

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Flip Image[edit | edit source]

Probably the most common reason to flip an image in gaming is to reverse the direction a character is running. For instance, if our Ragamuffin is running left, we could use this algorithm to flip his image and have him run to the right. You'd typically do this before you actually needed to have him run in the other direction. This algorithm may actually be more beneficial in a sprite creation program than in the game itself, but either way it neatly flips the image horizontally, or vertically.

The Source:[edit | edit source]

// Flip.cpp
#include <iostream>
#include "include/S.h"

using namespace std;

int main()
	static int width=S::sw();
	static int height=S::sh(width);
	int horizontal;
	int *position;
	int source[width*height];
	int dest[width*height];

	cout << "\n\n";

        for(int x = 0; x < width*height; x++)

	S::print_rect(width, height, &source[0]);

	cout << "\nFlip horizontally?"
	     << "\nEnter 1 for true, 0 for false: ";
	cin >> horizontal;
	cout << endl;

		for(int h = 0; h < height; ++h)
			for(int w = width - 1, i = 0; w > -1; --w, ++i)
				dest[h*width + i] = position[w];
		for(int h = height - 1, i = 0; h > -1; --h, ++i)
			for(int w = 0; w < width; ++w)
				dest[i*width+w] = position[w];

	S::print_rect(width, height, &dest[0]);
	cout << endl;