An Isometric Game Development Tutorial

The Isometrich is one of the most dynamic visions in the history of the game. From the Simulator City, the Age of the Empire, to The Darkness of the Darkness, to a mass of national production 2D Internet trips around the millennium, this "arranged 45 degrees overlooking" image has been the beginning of an entire era. I was involved in the development of a few of these 2.5D web-based clients, and then I studied similar systems in modern engines, and found that two generations of answers to this question constitute a very good learning path: **The same problem, with the two constraints of "soft rasters" and "modern engines", will evolve into two distinct but equally sophisticated structures. **

This is the course that goes through the path: from the coordinates, to the map rendering, to the real technical core of this kind of game — the masking sorting — and finally to the search and performance project. The codes in the text are indicative C++ pseudo-codes, which focus on the expression structure rather than on direct compilation.

I'm not sure it's the same as real.

The academicly defined isometrich projection (the like-axis projection) requires a two-and-a-half-cord angle of 120°, with an angle of about 35.26°, and a width ratio of ⁇ 3:1 ⁇ 1.73:1. And it's almost all used in the game. 2: 1 dimetric (second axis): The diamond is twice as wide as the height, and the equivalent angle is atan (0.5) ⁇ 26.57°.

Why is the game industry group choosing 2:1? Because of pixels. The two-to-one slope on the pixel grid is the perfect ladder of "two points across, one point across" and the line is clean and uncut; And the three-to-one is an unreasonable proportion, and it's all about the fury. So the industry's "Isometric Game" is the default of 2:1 dimetric, and this is the same practice used here.

The core contradiction of this kind of game is just one thing:**2D Rendering line does not have a deep buffer (Z-buffer), and who is blocking who on the screen is solely in the order of drawing. ** The first one will be covered by the later -- this is the painter's Algoritthm. So, "The first few drawings of each object" became the whole engine, and half the space of the paper was going around it.

I. Coordinate system: starting point for everything

There are at least three coordinates in the equation, and the newbies are the easiest to get lost here:

The change of logic grid to screen pixels is the first page of all the tutorials:

// 一个逻辑格投影到屏幕上是一个 64×32 的菱形(2:1)
const int TILE_W = 64;   // 菱形宽
const int TILE_H = 32;   // 菱形高

void WorldToScreen(int x, int y, int& sx, int& sy) {
    sx = (x - y) * (TILE_W / 2);   // (x - y) * 32
    sy = (x + y) * (TILE_H / 2);   // (x + y) * 16
}

void ScreenToWorld(int sx, int sy, int& x, int& y) {
    x = (sx / 32 + sy / 16) / 2;   // 整数运算,落地时向下取整
    y = (sy / 16 - sx / 32) / 2;
}

Geometric intuition is simple: the world X axis points to the screen. Bottom Right Y-Axis of the World Bottom Left One step in each direction, and the Y-screen moves down a garblywood-shaped height. So there was a natural order on the screen. The bigger you are, the closer you are to the bottom of the screen, the closer you are to the observer.. Remember that, it's the foundation of all sorted algorithms behind it.

Queue grid and coordinate conversion: World X Axis point to the bottom right of the screen and World Y Axis to the bottom left; A logic projection of 64 x 32

Mouse pick-up is a problem in the opposite direction: the player has ordered a pixel, you know which cell it is. First. ScreenToWorld Get the candidate. Do it again. Point-Ring Test Correct error - because the four angles of the diamond are adjacent:

// 判断点 (px, py) 在菱形 (cx, cy) 内的哪个区域
// 利用 2:1 斜率:|dx| / 32 + |dy| / 16 <= 1 即在菱形内
bool PointInDiamond(int px, int py, int cx, int cy) {
    int dx = abs(px - cx), dy = abs(py - cy);
    return dx * TILE_H + dy * TILE_W <= TILE_W * TILE_H / 2;
}

An observation that can subvert the perception.

This is a variant that's used in textbooks. But there's a more radical approach in business: **The projection was never done during the run-off. ** The entire map is baking in the art pipe with 3D software into a 2D bitmap with a equidistance angle, and running the period is only going to do one thing -- move this bitmap to the camera's original point of origin, blit:

void Map::Draw() {
    // m_Bitmap 是离线烘焙好的整张地图;m_CamX/m_CamY 是相机原点
    Blit(-m_CamX, -m_CamY, m_Bitmap);
}

This approach reduced the "3D Rendering" problem to the "2D Pixel Synthesis" problem: there was no projection math during run-time. Bitmap Coordinate = Screen Coordinate, all systems (cover, search, sorting of objects) share the same integer pixel coordinates and search each other for a zero conversion. The cost is the complexity of memory and art tubes, in exchange for the simplicity and stability of the operating period. This idea of "offline carrying complexity, online carrying performance" runs through the whole text.

II. Map drawing: from vagrancy to baking of the whole map

The equidistance map at the entry level is a double-cycle, tile-by-wall drawing, using a key technique - Staggered:

for (int row = 0; row < rows; ++row) {
    for (int col = 0; col < cols; ++col) {
        // 奇数行横向错开半格,纵向每行下移 1/4 格
        int sx = col * (TILE_W / 2) + (row % 2) * (TILE_W / 2);
        int sy = row * (TILE_H / 2);
        DrawSprite(tileSprite[map[row][col]], sx, sy);
    }
}

The tile-by-wall scheme is flexible (which can be run-time-changing, editor-editing), but commercial MMOs mostly choose another way: Fine arts set up the whole scene in 3D software and baked it into bits with a strictly aligned camera.. The parameters of this camera are the soul of the whole pipe:

Parameters Take Value Role
Projection Method Orthographic Destroying the trans-optic deformation is as big as it is in a distance.
azimuth 45° I'm looking at an angle.
Angle atan(0.5) ≈ 26.57° Force 2.1 dimetric ratio
Pixels Proportion 1 World Unit = 1 pixel Zero zooming of the dry map

The same scene usually bakes two products: Main Pixmap(Photo image) and Cover the mask.(Each alpha clipping of lifts — walls, houses, trees — + it's in the outside rectangle in the bitmap). The masked rectangular angle points are adsorbed to the grid, which allows a smooth indexing of the running period. This masked data is the lead in chapter V, remembering its existence.

The run-time was so simple and boring: camera rolling was just a change. (camX, camY) Two integers, drawing a whole picture, blit. All the real complexity was pushed into the offline.

iii. Painter algorithms and Y sequences: 80% of the scene is enough.

After the map is finished, it's the turn of the dynamic object: the player, the NPC, the falling object, the magic effect. They have no deep buffers available, and the only weapon is a drawing order - From far to near painting, it covers far away..

The simplest sort of view of the first section is the Y row at the bottom of the foot:

struct Obj {
    int x, y;          // 脚底点(位图像素坐标)
    Sprite* sprite;    // 绘制时以脚底点为锚,向上画
};

// 每帧:按脚底 Y 升序排序,依次绘制
std::sort(objs.begin(), objs.end(),
          [](Obj* a, Obj* b) { return a->y < b->y; });
for (Obj* o : objs) DrawSprite(o->sprite, o->x, o->y);

If the object has a logical grid coordinates, the equivalent is depth = x + yExactly. screenY = (x+y)×16 The monotonous. Many of the courses ended here, and in practice it did cover about 80 per cent of the cases. But as a developer, it has to know in which three situations it will be able to break through:

Three classic scenarios with Y sorting invalids: Y-same, tree crowns of high individuals, vertical stacking

  1. Y is different from X: two characters standing in the same row, almost equal to the bottom of the foot, the Y-ordered order, who can draw after all, and who can flash back and forth between the frames;
  2. High Individual: A tree has a far lower foot than a character (Y), but a tall canopy crosses the role on the screen. Sort by y foot, tree first, role later, role head over the tree crown -- visual characters like they're squeezed from the tree crown front;
  3. Vertical Stack: The same grid folds three boxes, and Y is exactly the same, and Z dimension must be involved.

The remaining section is the two generations of engineers' different answers to the three questions.

iv. Extracting business rules from geometry first

Before entering geometry, old-school engineers ask one question: **Is it all geometry that determines all the hidden relationships? **

The answer is no. There is a kind of iron law that works in the Internet: the body must lie at the feet of all living people; The fall of the object was to be pressed on the body but was trampled by the living; Magical effects always float at the top. Such rules have nothing to do with geometry, so geometry sort of meets the risk they are.

It's a simple and effective solution: Preclassification of barrel. The drawing and collection phase is divided by type of business, with the absolute painter order between the drum and the barrel, and geometry occurs only in the barrel:

class DrawQueue {
    List m_DieList;   // 尸体(躺平的)
    List m_ItmList;   // 地面物品
    List m_ObjList;   // 活物:NPC / 玩家 / 特效

    void Collect(Obj* o) {
        if (o->state == DEAD && o->frame >= FALL_FRAMES) {
            InsertSorted(m_DieList, o);      // 死透了:平躺的尸体
            return;
        }
        if (o->type == ITEM) {
            InsertSorted(m_ItmList, o);
            return;
        }
        InsertSorted(m_ObjList, o);          // 其余都是"站着的"
    }

    void Flush() {                           // 提交:严格按 尸体→物品→活物
        DrawList(m_DieList);
        DrawList(m_ItmList);
        DrawList(m_ObjList);
    }
};

Watch out for the first judgment. frame >= FALL_FRAMES: Animation of Role Death Falling Process(Preliminary) or "scientific" to participate in geometry with the living; Only when it was finished and laid flat was the barrel of the body sank. A line of code separates the visual entities of "closure" and "casualty" -- the details of which are replaced by the bugs that debug the countless bodies that cover the living.

What's the algorithm for sorting in a barrel? The answer may be unexpected: Insert Sort. The reason is a series of specific engineering facts, not the complexity of textbooks:

void InsertSorted(List& list, Obj* o) {
    for (Node* p = list.head; p; p = p->next) {
        if (Compare(p->obj, o) >= 0) {   // 找到第一个"不比 o 远"的位置
            list.InsertBefore(p, o);
            return;
        }
    }
    list.AddTail(o);
}

The whole collection-submission process Do not maintain any framework status: Redistributed, reordered, painted and discarded per frame. This "no state" has been replaced by absolute strength, with the number of objects being subject to the eye-to-eye limit -- without the constant "permanent confusion caused by the memory of a given frame" in the incremental sequence.

V. Proximity arbitration: the static mask programme (the end-of-life answer)

Now deal with hard bones: what if two close objects in the same barrel, Y, fail to sort?

Two-part comparison: far shortcuts, near actuarial

The first insight is... Most objects don't need to be judged.. The first section of the memoirs: a logical grid on the screen is 64 x 32 of a diamond. If the bottom of the feet of two objects is greater than 64 (vertical cross-breed) or X is more than 128, they're wrapped in a diamond convex. There's no overlap.— At this point simple y-orders are necessarily correct:

int Compare(Obj* a, Obj* b) {
    int dx = a->x - b->x;
    int dy = a->y - b->y;

    // 快路径:离得够远,Y 说了算
    if (dy > 64 || dy < -64 || dx > 128 || dx < -128)
        return dy;

    // 慢路径:近邻冲突,请"裁判"仲裁(下文)
    for (Mask* m : QueryMasksNear(a->x, a->y - BODY_OFFSET)) {
        int c1 = m->quad.Classify(a->x, a->y);   // a 相对掩码:前/内/后
        int c2 = m->quad.Classify(b->x, b->y);   // b 相对掩码:前/内/后
        if (c1 > c2 && dy >= 0) return -1;       // a 在掩码之后且屏幕更低 → a 实际更远
        if (c1 < c2 && dy <= 0) return +1;       // a 在掩码之前且屏幕更高 → a 实际更近
    }
    return dy;   // 没有掩码命中,退回 Y 排序
}

This structure guarantees:98% compared to O(1) fast track, only a very small number of neighboring conflicts get into a cover arbitration. Geometric accuracy and sequencing.

Where did the referee come from: pre- baking diamond-shaped encirclement frame?

Arbitration requires a third-party reference. It's a second-class baking line. Static Mask. Each lifting (wall, house, tree) generates two data during the baking period: a pixel-by-pixel alpha clipping, and one 2:1 diamond-shaped siege frame—from an external rectangle diagonal inverted:

struct Quad {
    Point v[4];   // 固定顺序:上、左、下、右

    // 只给外接矩形的对角线 (x1,y1)-(x2,y2),强制反算出 2:1 菱形
    void Make(int x1, int y1, int x2, int y2) {
        int W = x2 - x1, H = y2 - y1;
        int a = (2 * H - W) / 2;      // 左右顶点相对上下对角线的水平外扩
        int b = (2 * H - W) / 4;      // 垂直外扩,保持 2:1 斜率
        v[0] = {x1, y1};              // 上
        v[1] = {x1 - a, y1 + b};      // 左
        v[2] = {x2, y2};              // 下
        v[3] = {x2 + a, y2 - b};      // 右
    }
};

Why do you have a diamond instead of a rectangle? Because the dividing line between "front/back" and "front/back" in the world is itself an oblique one -- a two-to-one of the four sides of the diamond-shaped is exactly the same as the two axes in the coordinates of the world, and it is used to divide "front/inner/back" and the geometrical meaning is the cleanest:

Dot-Ring determination: Aggression of roughness of the encirclement box, fine four fork mark, return ex (0)/inner (1)/after (2)

// 返回 0=前方(屏幕下方,会遮挡别人)1=内部 2=后方(屏幕上方)
int Quad::Classify(int px, int py) {
    if (py < v[0].y) return 2;              // 包围盒粗判:上面
    if (py > v[2].y) return 0;              // 下面
    if (px < v[1].x || px > v[3].x) {       // 左右两侧:看斜边再定
        // …… 同样用叉积符号判断
    }
    // 包围盒内:对四条边各做一次叉积符号测试
    // 叉积 > 0 表示点在这条边的"外侧后方/前方"
    if (Cross(v[0], v[1], px, py) > 0) return 2;   // 上边外侧 → 后
    if (Cross(v[1], v[2], px, py) > 0) return 0;   // 左边外侧 → 前
    if (Cross(v[2], v[3], px, py) > 0) return 0;   // 下边外侧 → 前
    if (Cross(v[3], v[0], px, py) > 0) return 2;   // 右边外侧 → 后
    return 1;                                       // 内部
}

So the logic of arbitrage goes to the following: two near-neighbors A, B, who are on the bottom Y, who are more "post" than the diamond shape of the same wall. Compare The one in there. (c1, c2, dy) The three-member team judged that the essence of the question was: **Who should be blocked by the cover when it's between them? **

Two details of the project merit a separate description:

  1. Mask-barrel index. The masked external rectangular adsorption to 32x32 grid, and then build a map. 桶[格W × 格H] array, each cell is hung over it in the mask list. Query x/32, y/32 One-time positioning, O(1) getting a candidate, usually with only 0-2 masks per cell;
  2. Query points need to move up one position. It's on the floor, but the wall covers it. Body height That area. So when you look for the mask, you don't have to use the bottom Y, but rather the bottom Y. y - 身高偏移(e.g. 50 pixels ⁇ + half-heavy) Put the query point in the position of the body of the character -- that's the "the rowing box behind you" and the most sensitive place to cover the relationship. This rigid deviator code is the most common practice, at the expense of the wrong size of a giant animal or young child, and the way to save up to the object.

End: Pixels-level mask correction

Sorting solves "who draws first" but there are some kind of residual problem: the role is standing behind the wall, sorting it right, and the whole part of the role is still stuck on the wall pixels (because the wall is baked into the map and the role is painted later). The way is... Once you're done with the role, use the same mask to fix it.: calculate the grid range covered by the role sprite, reset the mask pixels "in front of the role" and erase the lower half of the gang.

Cover correction: Sorting ensures big relationship, mask pixels recapturing the lower part of the role

Watch the beauty here: Sorting arbitrations are made with a diamond-shaped frame, and pixels are modified with it.— The same geometric object, with a rough determination at the object level, then a fine correction at the pixel level, and the natural agreement between the two conclusions, without the contradiction of "sorting behind the wall, correcting the wall, and rubbing it in the face."

The last piece of the puzzle is... Remove prefix: Use the object before entering the barrel 脚底点 ± 安全余量(About 100 pixels, take care of the " tall man with the soles of his feet but the upper half is still inside the screen") Filtering off the screen. I'm not sure if it's the first time I've been able to do this. Never again in a barrel.- Because blocking the ruling requires A to know B exists, even B not to be painted.

VI. Another road for modern engines: relying on charting and mapping

Time is coming to the age of modern engines. The binding changes: the object is no longer "a sprite + a foot bottom point" but an entity with a complete 3-D encirclement (AABB); Rendering line lines support automatic sorting by Z value; The CPU is also coming up with a few orders of magnitude. The same sort of sorting problem, which evolved into a very different solution: **Modelling "who's against whom" into a dependency map and "what floor is the painting" into a visible depth. **

Step 1: Who draws the front of two objects - the penetrating depth and the dominant axis

Two sets of world coordinates AABB (minimal angle + dimension) were determined for input. There are two layers of thinking:

  1. **Do you want to sort it out? ** The two AABBs have a projection overlap on the X/Y plane and Z also have a Z superheavy, which may create a shield;
  2. Who's in front? ** Calculating the depth of penetration on the three axes -- the shortest distance that would be required to stagger the two along the axis -- the axis is the one that's the one that's the one that's the one that's the one that's the one that's the one that's the one that's the one that's the one. Main axis**(They're the "most unlikely to separate" directions); On the dominant axis, the other side that invaded the other side drew in front.

AABB Main Axe: The most convenient thing to stagger with X is the main axis.

// 返回 true 表示 "b 应画在 a 前面"
bool Depends(Vec3 aMin, Vec3 aSize, Vec3 bMin, Vec3 bSize) {
    Vec3 aMax = aMin + aSize, bMax = bMin + bSize;

    // 高度不交叠(一个在另一个正上方且足够高)→ 无遮挡关系
    bool overlapZ = (bMax.z > aMin.z) && (aMax.z > bMin.z);
    bool overlapXY = (aMax.x > bMin.x) && (aMax.y > bMin.y);
    if (!overlapZ || !overlapXY) return false;

    // 三个轴上的互相侵入量
    Vec3 dA = {aMax.x - bMin.x, aMax.y - bMin.y, bMax.z - aMin.z};
    Vec3 dB = {bMax.x - aMin.x, bMax.y - aMin.y, aMax.z - bMin.z};

    // 沿各轴错开所需的最小距离;越小越"难舍难分"
    Vec3 dP = aSize + bSize - Abs(dB - dA);

    if (dP.x <= dP.y && dP.x <= dP.z) return dA.x > dB.x;  // X 主导
    if (dP.y <= dP.x && dP.y <= dP.z) return dA.y > dB.y;  // Y 主导
    return dA.z > dB.z;                                    // Z 主导(垂直堆叠)
}

Note that this determination naturally solves the three failures of Chapter III: vertical stacking is handled by Z-axis; High-level individuals are automatically correct because AABB has a real height; The objects close to Y are divided by the x or Y-lead axis. One decision, O (1).

Step 2: Sorting from two to two in global order - scale up

For each of the overlapping objects, a dependency edge ( "A relies on B" = B first drawing), the whole scene is covered by a directional map. Turn it into linear drawing order, with a Depth priority going through:

float Place(Obj* o, float startDepth) {
    if (o->placed) return startDepth;    // 防重入,顺带破环
    o->placed = true;

    for (Obj* dep : o->depends)          // 先递归安置所有"比我远"的
        startDepth = Place(dep, startDepth);

    o->z = startDepth;                   // 给 o 分配独占的深度层
    return startDepth + o->zExtent + STEP; // 下一个对象从"我的顶"开始
}

Three design points:

Step 3: Do not do useless work -- spatial indexing and dirty markings

The two decisions are O (N2) and a screen is not acceptable to hundreds of objects. Two packages:

Bigenerational programme comparison

Dimensions End-to-end programme (chapter V) Modern programmes (chapter VI)
Object Model Two integers at the bottom Complete 3D AABB
Reference Pre- baking static mask (Broar) Two or two sentences for the subject.
Global Order Bar + Insert Sorting Sort based on +DFS Popup
Depth Expression Invisible (in the order itself) Visible (separate Z area)
Static expenses Full reordering per frame Dirty mark, static zero.
The neighbors found out. 32x32 cylinder index Four fork tree.
I'm good at it. Mass the same type sprite, soft raster 2D/3D Mixed, vertical stacking, dynamic scene
Soft ribs. Dynamic Object Covers Under Cover AABB will underestimate the revolving object screen.

No good or bad, only the constraints are different: one saves every CPU operation to the floppy glit, one can build a lot of plans, run a lot, distribute the depth of the floating point. **It is more important to understand how constraints shape structures than to remember any algorithm. **

VII. MOBILIZATION AND FINDING: DON'T USE THE ROBIN PACKAGE

A counterintuitive conclusion: **The road-seeking grid of the equidistance game is not a diamond, but a rectangle. **

The diamond shape is a visual concept, not a grid concept -- it doesn't have a clean definition of "neighbor." # Dotting next to each other # # Write about the road # # will come and go # In practice, it is the practice to break down each 64x32 diamond formation into 2x2 = 4 rectangular sub-bar for 16x8 The search is standard for this regular rectangular grid 8 Neighbor Extension:

// 子格粒度:宽 = 格宽/2,高 = 格高/4
const int SUB_W = 16, SUB_H = 8;

// 8 邻 BFS / A*:就是最普通的矩形网格寻路
const int DIRS[8][2] = {
    {-1,0},{1,0},{0,-1},{0,1},      // 四邻
    {-1,-1},{1,1},{1,-1},{-1,-1}    // 四对角
};

Diamonds and Pathfinders: Visually 64x32 diamond, logically 16x8 rectangular grid

16x8 This ratio of 2:1 is not random: it allows the nick to fit the visual shape of the equidistance space on the screen (just four positions per diamond), while keeping all the conveniences of the rectangular grid - the direct mapping of arrays,8 the neighbour's extension is the axle alignment shift, and the cost of moving the corner is good.

There's another data design worth copying: The barrier map and the road search site share the same memory. Both are identical in particle size (all 16x8 sub-gauges, equal sizes) and BFS writing distance and backtracking is done directly on the barrier map during the road search. Zero redundancies, automatic consistency -- never "the barriers are renewed, but the road cache is forgotten."

VIII. SUMMIT OF PROGRESS ISSUES

**Altitude and terrain rise and fall. ** Draw position upwards after each +z coordinates z × 层间距, the Depth formula becomes depth = x + y + z. This is reflected in the old scheme as a masked "height shift" and multi-layer maps; Z in the new scheme is already an axle of AABB, which is directly free of charge.

**Performance list. ** (a) Sorting of inputs by output: 1 ejection of permanently prefixed by mouth, which is the optimization of the order of magnitude; 2 Sorting data structure sieve table + insert sorting, using inter-frame correlation; 3 Space index (barrells or fork trees) reduces a neighbour's discovery to O (N.K); 4 Obsolete markings allow static scenes to spend no cost; 5 Target pool elimination frame-by-frame distribution.

A list of traps (all of the real bugs):

Concluding remarks

The technology of the equidistance game is essentially an answer to a question: **How to simulate a 3D space containment order using a 2D means of certainty. **

The path down this course is: the coordinate system establishes the foundation of the "Y" or depth, pre-cooks the projection out of the running period, the painter algorithm + Y sorts out most of the problems, the barrel classification strips the business rules from geometry, the static mask arbitration close conflict, the modern solution is to generalize the problem by relying on maps and pouncer sorting, the search path back to rectangular grids.

Today, writing a quid pro quo game, you may be able to meet 80% of the demand directly with the engine YSort or staking Order. But when the day comes when the characters are modeled, objects blinking and the sequences are confused, it is hoped that the lesson will let you know that every inch of land beneath your feet is filled with real pits by two generations of engineers.