Game Development 8 min read

Implementing Polygon Click Detection in Cocos and Optimizing a Sudoku Solver

This article explains two techniques for accurate polygon click detection in Cocos—pixel‑alpha testing and PolygonCollider2D with ray‑casting—and describes a bit‑mask based Sudoku solver that uses depth‑first search and solution counting to ensure puzzle uniqueness and improve performance.

TAL Education Technology
TAL Education Technology
TAL Education Technology
Implementing Polygon Click Detection in Cocos and Optimizing a Sudoku Solver

The article records two implementations for polygon click detection in Cocos and shares optimization insights from developing a Sudoku solver.

Background: In a tangram puzzle built with Cocos, the default rectangular click area does not match the visual shape of triangular pieces, leading to poor user experience and motivating more precise hit testing.

Method 1 – Pixel Alpha Test : Convert the click coordinates to the corresponding pixel of the sprite, read the pixel’s alpha value, and consider the point a hit if the alpha exceeds a defined opacity threshold. The following code demonstrates this approach:

/**
 * Check the alpha value of the clicked pixel against a threshold OPACITY
 * @param x
 * @param y
 * @returns whether the pixel is opaque
 */
checkHit(x: number, y: number) {
    let sprite = this.node.getComponent(Sprite);
    if (!sprite) {
        return false;
    }
    let texture =
sprite.spriteFrame.texture;
    // 3.x
    let data =
texture.image.data;
    // 2.x
    // let data = texture.getHtmlElementObj();
    let cvs = document.createElement("canvas");
    let ctx = cvs.getContext("2d");
    cvs.width = 1;
    cvs.height = 1;
    ctx.drawImage(data, x, y, 1, 1, 0, 0, 1, 1);
    // Get pixel data
    let pxData = ctx.getImageData(0, 0, 1, 1).data;
    console.log(pxData);
    return pxData[3] > OPACITY;
}

Method 2 – PolygonCollider2D Component : Use Cocos’s PolygonCollider2D, which automatically generates a polygon based on the sprite’s transparent area. Click detection then uses the even‑odd (ray‑casting) rule to determine if the point lies inside the polygon, a technique that works for concave shapes as well. The implementation is shown below:

/**
 * Determine whether the click position is inside the polygon
 * @param event Click event
 * @returns boolean
 */
checkHitPoly(event: EventTouch) {
    let targetPos = event.touch.getUILocation();
    let poly = this.node.getComponent(PolygonCollider2D);
    if (!poly) {
        return false;
    }
    let count = 0;
    // Get ordered world points of the polygon
    let arrPoints = poly.worldPoints;
    for (let i = 0; i < arrPoints.length; i++) {
        let point1 = arrPoints[i];
        let point2 = arrPoints[0];
        if (i != arrPoints.length - 1) {
            point2 = arrPoints[i + 1];
        }
        // Check if the edge spans the target Y coordinate
        if (point1.y < targetPos.y && point2.y > targetPos.y || point1.y > targetPos.y && point2.y < targetPos.y) {
            let t = (targetPos.y - point1.y) / (point2.y - point1.y);
            let xt = point1.x + t * (point2.x - point1.x);
            // On the edge, return true
            if (targetPos.x == xt) return true;
            // Ray to the right intersects the edge
            if (targetPos.x < xt) ++count;
        }
    }
    // Odd number of intersections means inside
    return count % 2 == 1;
}

Sudoku Solver: The second mini‑game is a Sudoku puzzle where the author needed to verify that each imported puzzle has a unique solution. Data is stored using bit masks: a 9‑element array represents rows, each element using 9 bits to indicate used numbers; empty cells are encoded with an 8‑bit value (high 4 bits for row, low 4 bits for column).

Solving algorithm: A depth‑first search with backtracking enumerates all possible solutions, counting them to ensure uniqueness. The algorithm also applies a heuristic of selecting the empty cell with the fewest candidate numbers first, which aligns with later plans for automated explanation features.

Results: Running the script on 400 Sudoku levels revealed 29 puzzles without a unique solution—some due to entry errors, others because the original puzzles were inherently ambiguous. After correcting the problematic entries, uniqueness was restored.

Conclusion: Both the polygon click detection methods and the optimized Sudoku solver illustrate the importance of algorithmic precision and performance tuning in game development, providing reliable interaction handling and robust puzzle validation.

OptimizationAlgorithmGame developmentcollision detectioncocosPolygon ClickSudoku Solver
TAL Education Technology
Written by

TAL Education Technology

TAL Education is a technology-driven education company committed to the mission of 'making education better through love and technology'. The TAL technology team has always been dedicated to educational technology research and innovation. This is the external platform of the TAL technology team, sharing weekly curated technical articles and recruitment information.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.