The function EntityMoving_canMove checks whether an EntityMoving can move in a given direction based on collision boundaries and world edge constraints. While the code is functional, there are several issues and improvements related to readability, maintainability, redundancy, and correctness that should be addressed.
✅ Summary of Issues
| Issue | Description |
|---|
| 🔁 Code Duplication | X and Y axis checks are nearly identical; logic should be abstracted. |
| ❌ Incorrect World Edge Check | Uses minTileDistFromWorldEdge = 8, but checks absolute tile coordinates instead of relative to entity. |
| 🚫 Assumes Only One Axis Moves | Excludes diagonal movement by using else if, but doesn't clarify intent. |
| 🧱 Hardcoded Constants | WORLD_TILE_SIDE_COUNT, minTileDistFromWorldEdge — magic numbers without explanation. |
| ⚠️ Potential Integer Overflow / Underflow | No bounds checking on signed int when subtracting crossCollisionBoxBoundaryOne. |
| 💡 Confusing Variable Names | crossCollisionBoxBoundaryOne, tilePosAdd, unclear purpose. |
| 📏 Collision Box Logic May Be Flawed | Only checks edge tiles — may miss internal collisions or allow clipping. |
| 🔄 Inefficient Memory Access | Repeated calls to getTileCollisionData() without early exit optimization. |
| 📚 Missing Documentation | No comments explaining what the function does or assumptions made. |
🔍 Detailed Review
1. Code Duplication (X and Y Axis Logic)
Both the X and Y movement checks perform the same kind of loop: iterate along one dimension of the collision box at the leading edge, check for world boundaries and tile collisions.
✅ Suggestion: Extract common logic into a helper or refactor using symmetry.
2. Edge Boundary Check Is Likely Wrong
if (testWorldPos.tilePos.x < minTileDistFromWorldEdge)
This prevents movement if the tested tile is within 8 tiles of the left edge. But:
- This is applied per-tile during movement, not for the whole entity.
- It effectively creates a 8-tile "no-go" zone near edges.
- However, it's inconsistent: you're allowing the entity to exist inside the world, but not move toward the edge?
🛑 Problem: If the entity is already near the edge (say at x=7), it cannot move further in that direction even if it's allowed to be there.
💡 Fix: Either:
- Remove this check (let
getTileCollisionData handle impassable border tiles), OR
- Define explicit world bounds and check entity position against them before movement.
3. Only One Axis Allowed at a Time
if (moveDirection.x) { ... }
else if (moveDirection.y) { ... }
else { result = 0; }
This means:
- Diagonal moves (
x != 0 && y != 0) are rejected.
- Zero move →
result = 0 (correct).
❓ Question: Is diagonal movement intentionally disallowed?
✅ If yes → document clearly.
✅ If no → need to handle both components (possibly with two-phase check or full bounding box test).
4. crossCollisionBoxBoundaryOne Is Misleading
int crossCollisionBoxBoundaryOne = 1;
This appears to be an offset/padding used to check just outside the current collision box.
But:
- Name is cryptic.
- Hardcoded as
1 — why?
- Could be a
#define or named constant like PROBE_OFFSET.
✅ Rename to something like EDGE_PROBE_OFFSET.
5. Collision Size Interpretation
You're using:
entityMoving->collisionSize.x
entityMoving->collisionSize.y
entityMoving->collisionSize.w
entityMoving->collisionSize.h
Assuming collisionSize is a rectangle (x,y,w,h). That’s fine, but:
- Are these in tiles or pixels?
- Given usage with
WorldTilePos, likely tile units.
Ensure consistency across codebase.
Also, when checking forward movement, you're probing:
x = entityMoving->collisionSize.x + entityMoving->collisionSize.w - 1;
x += EDGE_PROBE_OFFSET;
That’s the rightmost column + 1, which makes sense for rightward movement.
✅ So logic for edge selection is correct.
6. Use of Signed Types for Tile Positions
(i8)x, (i8)(y + ...)
Casting int to i8 (likely int8_t) risks overflow if values exceed ±127.
🛑 Risk: If world is large (>256 tiles), this breaks.
✅ Ensure WorldTilePos uses appropriate types (i16 or u16), or validate ranges.
7. Performance: Redundant Work
Each iteration:
- Computes
testWorldPos = worldPosOrigin + tilePosAdd
- Calls
getTileCollisionData(...)
- Checks boundary
This is acceptable, but could be optimized by precomputing base offsets.
✅ Improved Version (Refactored)
// Helper: Check if a tile position is blocked
static int isTileBlocked(tpl_Data* data, const WorldTilePos* pos)
{
u8* collision = getTileCollisionData(data, pos);
return collision ? (*collision != 0) : 1; // Assume blocked if out-of-bounds
}
// Helper: Clamp and validate tile position within world
#define WORLD_MIN_TILE 0
#define WORLD_MAX_TILE (WORLD_TILE_SIDE_COUNT - 1)
static int isWithinWorldBounds(const WorldTilePos* pos, int margin)
{
return pos->x >= margin && pos->x < (WORLD_TILE_SIDE_COUNT - margin) &&
pos->y >= margin && pos->y < (WORLD_TILE_SIDE_COUNT - margin);
}
tF int EntityMoving_canMove(
tpl_Data* data, EntityMoving* entityMoving, WorldTilePos moveDirection)
{
// Reject zero movement
if (moveDirection.x == 0 && moveDirection.y == 0)
return 0;
// Reject diagonal moves (if not supported)
if (moveDirection.x != 0 && moveDirection.y != 0)
return 0; // Or handle diagonals separately if needed
const int EDGE_PROBE_OFFSET = 1;
const int BOUNDARY_MARGIN = 8; // Or make configurable
WorldPos worldPosOrigin = entityMoving->worldPos;
Rect* col = &entityMoving->collisionSize;
// Determine scan line: which edge to probe
int probeX = -1, probeY = -1;
int startX, startY, endX, endY;
if (moveDirection.x != 0)
{
if (moveDirection.x > 0)
{
probeX = col->x + col->w - 1 + EDGE_PROBE_OFFSET;
startX = col->y;
endY = col->y + col->h;
startY = startX;
}
else
{
probeX = col->x - EDGE_PROBE_OFFSET;
startX = col->y;
endY = col->y + col->h;
startY = startX;
}
for (int y = startY; y < endY; y++)
{
WorldTilePos testTile = { (i8)probeX, (i8)y };
WorldPos testWorldPos = worldPosOrigin;
testWorldPos.tilePos.x += testTile.x;
testWorldPos.tilePos.y += testTile.y;
// Check world boundaries
if (testWorldPos.tilePos.x < BOUNDARY_MARGIN ||
testWorldPos.tilePos.x >= WORLD_TILE_SIDE_COUNT - BOUNDARY_MARGIN)
return 0;
if (isTileBlocked(data, &testWorldPos.tilePos))
return 0;
}
}
else if (moveDirection.y != 0)
{
if (moveDirection.y > 0)
{
probeY = col->y + col->h - 1 + EDGE_PROBE_OFFSET;
startX = col->x;
endX = col->x + col->w;
startY = startX;
}
else
{
probeY = col->y - EDGE_PROBE_OFFSET;
startX = col->x;
endX = col->x + col->w;
startY = startX;
}
for (int x = startX; x < endX; x++)
{
WorldTilePos testTile = { (i8)x, (i8)probeY };
WorldPos testWorldPos = worldPosOrigin;
testWorldPos.tilePos.x += testTile.x;
testWorldPos.tilePos.y += testTile.y;
if (testWorldPos.tilePos.y < BOUNDARY_MARGIN ||
testWorldPos.tilePos.y >= WORLD_TILE_SIDE_COUNT - BOUNDARY_MARGIN)
return 0;
if (isTileBlocked(data, &testWorldPos.tilePos))
return 0;
}
}
return 1;
}
✅ Recommendations
-
Clarify Movement Rules
- Can entities move diagonally?
- Is 8-tile margin required, or can borders be handled via collision map?
-
Replace Magic Numbers
#define WORLD_EDGE_MARGIN_TILES 8
#define COLLISION_PROBE_OFFSET 1
-
Improve Naming
crossCollisionBoxBoundaryOne → COLLISION_PROBE_OFFSET
tilePosAdd → offsetInTiles
-
Consider Full Bounding Box Check
For robustness, consider checking all tiles in the target position after movement, not just the leading edge.
-
Add Unit Tests
Test cases:
- Moving into wall
- Moving toward world edge
- Standing still
- Diagonal input (expected rejection)
-
Document Assumptions
Add comment:
/**
* Checks if entity can move one tile in moveDirection.
* Only cardinal directions supported. Diagonals rejected.
* Uses leading-edge tile probe with offset=1.
* Entity cannot move within 8 tiles of world edge.
*/
✅ Final Verdict
Status: ❌ Needs improvement
Rating: 6/10 — Logic is mostly sound but suffers from duplication, unclear intent, and fragile edge handling.
With refactoring and clearer design, this can become robust and reusable.
Let me know if you want support for diagonal movement, sliding, or pixel-level collision!