Tile Map para Jogo de Plataforma - Galeria de Exemplos
Tile Map para Jogo de Plataforma

Descrição: Este exemplo demonstra como ler um mapa de tiles de um arquivo e exibir o cenário. Também demonstra como movimentar a câmera pelo cenário.

Autor: Edirlei Soares de Lima

Download: Exemplos09.zip

 

Código Fonte:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include "Graphics.h"
#include <stdio.h>
#define MAP_WIDTH 100
#define MAP_HEIGHT 25
Graphics graphics;
char Mapa[MAP_WIDTH][MAP_HEIGHT];
Image bloco_grama;
Image bloco_terra;
float camera_position = 18;
void LoadMapa(char *filename)
{
    int c;
    int count_line = 25;
    int count_col = 0;
    FILE *file;
    file = fopen(filename, "r");
    if (file)
    {
        while ((c = getc(file)) != EOF)
        {
            if (count_col == MAP_WIDTH-1)
            {
                count_line--;
                count_col = 0;
            }
            else
            {
                Mapa[count_col][count_line] = (char)c;
                count_col++;
            }
        }
        fclose(file);
    }
}
void MainLoop()
{
    int x, y;
    for (x = camera_position - 18; x < camera_position + 18; x++)
    {
        for (y = 0; y < 25; y++)
        {
            if (Mapa[x][y] == 'G')
            {
                graphics.DrawImage2D(((x - (camera_position - 18))*24),y*24, 24, 24, bloco_grama);
            }
            if (Mapa[x][y] == 'T')
            {
                graphics.DrawImage2D(((x - (camera_position - 18))*24),y*24, 24, 24, bloco_terra);
            }
        }
    }
}
void KeyboardInput(int key, int state, int x, int y)
{
    if ((key == KEY_LEFT)&&(state == KEY_STATE_DOWN))
    {
        if (camera_position > 18)
            camera_position = camera_position - 0.1;
    }
    if ((key == KEY_RIGHT)&&(state == KEY_STATE_DOWN))
    {
        if (camera_position < MAP_WIDTH - 18)
            camera_position = camera_position + 0.1;
    
}
 
 
int main(void)
{
    graphics.CreateMainWindow(800, 600, "Exemplo 09 - TileMap");
    graphics.SetBackgroundColor(152,209,250);
    LoadMapa("Mapa01.txt");
 
    bloco_grama.LoadPNGImage("grass.png");
    bloco_terra.LoadPNGImage("stone.png");
    
    graphics.SetKeyboardInput(KeyboardInput);
 
    graphics.SetMainLoop(MainLoop);
    graphics.StartMainLoop();
    return 0;
}