27 Eylül 2026 Pazar

মনোগেমে 2D সংঘর্ষ সনাক্তকরণ: মৌলিক আয়তক্ষেত্র থেকে জিরো-অ্যালোকেশন পিক্সেল-পারফেক্ট সিস্টেম পর্যন্ত




মনোগেমে 2D সংঘর্ষ সনাক্তকরণ: মৌলিক আয়তক্ষেত্র থেকে জিরো-অ্যালোকেশন পিক্সেল-পারফেক্ট সিস্টেম পর্যন্ত

ইউনিটি বা গডোটের মতো ভিজ্যুয়াল ইঞ্জিনে 2D গেম তৈরি করার সময়, সংঘর্ষ শনাক্তকরণ প্রায়শই পরিদর্শক চেকবক্সের একটি সিরিজের মতো মনে হয়: আপনি একটি BoxCollider2D বা CircleCollider2D-এ থাপ্পড় দেন, একটি Rigidbody সংযুক্ত করেন এবং আশা করি মোবাইল ডিভাইসে অভ্যন্তরীণ পদার্থবিদ্যার পদক্ষেপটি তোতলাবে না।

MonoGame এবং C# এ, তবে, আপনি সম্পূর্ণ নিয়ন্ত্রণে আছেন। কোন লুকানো পদার্থবিদ্যা ওভারহেড নেই, কোন অবাঞ্ছিত ঘূর্ণন জড়তা, এবং কোন রহস্যময় আবর্জনা সংগ্রহ (GC) স্পাইক আপনার ফ্রেম বাজেট চুরি করা হয়.

Arar গেম-এ, যখন আমরা Blocked: Pixel Panzer এবং Paint Trek তৈরি করেছি, তখন আমাদের আর্কেড গেম লুপগুলি শত শত উচ্চ-গতির শত্রু বুলেট, বিস্ফোরিত ইট গ্রিড, ঘূর্ণায়মান ট্যাঙ্ক টারেট, ফাইটার জেট ফ্লাইবাই এবং Windows2 এবং Android 60 থেকে 60 পিসি উভয় ডিভাইসে কণা ঢাল প্রক্রিয়া করার জন্য প্রয়োজন। একটি সাধারণ-উদ্দেশ্য পদার্থবিদ্যা ইঞ্জিন প্রশ্নের বাইরে ছিল-আমাদের একটি উদ্দেশ্য-নির্মিত, টায়ার্ড সংঘর্ষের আর্কিটেকচার দরকার ছিল।

এই বিস্তৃত, কোড-চালিত গাইডে, আমরা MonoGame সংঘর্ষের নিখুঁত মৌলিক বিষয়গুলি থেকে শুরু করব (আসল বুলেটএবংশত্রুস্প্রাইটের সাথেআয়তক্ষেত্র. ছেদ করে`) এবং উন্নত সার্কেল চেক, মিশ্র ক্ল্যাম্পিং, অ্যান্টি-টানেলিং রেকাস্ট, প্রোডাকশন-গ্রেড-প্লিক্স-প্লিক্স** এবং পি-লিক্স**** জিরো-অ্যালোকেশন স্পেশিয়াল গ্রিড মোবাইল জিসি বেঁচে থাকার জন্য অপ্টিমাইজ করা হয়েছে।


1. ফাউন্ডেশন: একটি সহজ মনোগেম স্প্রাইট শ্রেণিবিন্যাস

সংঘর্ষ সনাক্ত করার আগে, আমাদের পরিষ্কার গেম সত্তা প্রয়োজন। MonoGame-এ, একটি সত্তা মৌলিকভাবে একটি অবস্থান, একটি টেক্সচার এবং একটি আবদ্ধ আয়তক্ষেত্রের অধিকারী।

এখানে আমাদের গেম জুড়ে ব্যবহৃত বেসলাইন সত্তা আর্কিটেকচার রয়েছে:

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

public class Sprite
{
    public Vector2 Position;
    public Texture2D Texture;
    public Color Tint = Color.White;
    public bool IsActive = true;

    // The raw Axis-Aligned Bounding Box (AABB)
    public virtual Rectangle Bounds => new Rectangle(
        (int)Position.X,
        (int)Position.Y,
        Texture != null ? Texture.Width : 0,
        Texture != null ? Texture.Height : 0
    );

    public virtual void Draw(SpriteBatch spriteBatch)
    {
        if (!IsActive || Texture == null) return;
        spriteBatch.Draw(Texture, Position, Tint);
    }
}

এখন কংক্রিট প্লেয়ার, শত্রু এবং বুলেট ক্লাস তৈরি করি:

public class Bullet : Sprite
{
    public Vector2 Velocity;
    public int Damage = 25;

    public void Update(GameTime gameTime)
    {
        Position += Velocity * (float)gameTime.ElapsedGameTime.TotalSeconds;
    }
}

public class Enemy : Sprite
{
    public int Health = 100;

    public void TakeDamage(int damage)
    {
        Health -= damage;
        if (Health <= 0)
        {
            IsActive = false;
        }
    }
}

public class Player : Sprite
{
    public int Health = 100;
    public bool IsInvulnerable = false;

    public void TakeDamage(int damage)
    {
        if (IsInvulnerable) return;
        Health -= damage;
    }
}

এই সত্ত্বাগুলিকে জায়গায় রেখে, আসুন সহজ পদ্ধতি থেকে শুরু করে কীভাবে তাদের মধ্যে সংঘর্ষ সনাক্ত করা যায় তা অন্বেষণ করি।


2. স্তর 1: সরলতম সংঘর্ষ - `আয়তক্ষেত্র. ছেদ' (AABB)

MonoGame-এ সবচেয়ে মৌলিক 2D সংঘর্ষের পরীক্ষা হল অ্যাক্সিস-অ্যালাইনড বাউন্ডিং বক্স (AABB) পরীক্ষা। "অক্ষ-সারিবদ্ধ" শব্দের সহজ অর্থ হল আয়তক্ষেত্রের প্রান্তগুলি পর্দার \(X\) এবং \(Y\) অক্ষগুলির সম্পূর্ণ সমান্তরাল (কোন ঘূর্ণন নেই)৷

MonoGame একটি দ্রুত, অন্তর্নির্মিত পদ্ধতি প্রদান করে: Rectangle.Intersects(rectangle value)।

কিভাবে আয়তক্ষেত্র. ছেদ হুডের নিচে কাজ করে

পৃষ্ঠের নীচে, MonoGame চারটি পূর্ণসংখ্যার তুলনা সম্পাদন করে:

public bool Intersects(Rectangle value)
{
    return value.Left < this.Right &&
           this.Left < value.Right &&
           value.Top < this.Bottom &&
           this.Top < value.Bottom;
}

চারটি শর্ত পূরণ হলে, আয়তক্ষেত্রগুলি ওভারল্যাপ হয়। এমনকি একটি শর্তও ব্যর্থ হলে, একটি খালি অক্ষ তাদের পৃথক করে এবং কোন সংঘর্ষ সম্ভব নয়।

বাস্তব গেমপ্লে কোড: Game1.Update-এ বুলেট বনাম শত্রু

এখানে আপনি কীভাবে সক্রিয় বুলেটের তালিকা এবং আপনার প্রধান MonoGame আপডেট লুপের মধ্যে সক্রিয় শত্রুদের একটি তালিকার মধ্যে সংঘর্ষ পরীক্ষা করবেন:

public class Game1 : Game
{
    private List<Bullet> _bullets = new List<Bullet>();
    private List<Enemy> _enemies = new List<Enemy>();

    protected override void Update(GameTime gameTime)
    {
        // 1. Update bullet and enemy positions
        foreach (var bullet in _bullets) bullet.Update(gameTime);

        // 2. Collision Check: Bullets vs Enemies
        for (int b = _bullets.Count - 1; b >= 0; b--)
        {
            var bullet = _bullets[b];
            if (!bullet.IsActive) continue;

            for (int e = _enemies.Count - 1; e >= 0; e--)
            {
                var enemy = _enemies[e];
                if (!enemy.IsActive) continue;

                // The AABB check!
                if (bullet.Bounds.Intersects(enemy.Bounds))
                {
                    // Collision occurred!
                    enemy.TakeDamage(bullet.Damage);
                    bullet.IsActive = false;

                    // Remove inactive bullet immediately
                    _bullets.RemoveAt(b);
                    
                    if (!enemy.IsActive)
                    {
                        _enemies.RemoveAt(e);
                    }

                    // A bullet can only hit one enemy; break the inner loop
                    break;
                }
            }
        }

        base.Update(gameTime);
    }
}

পারফরম্যান্স টিপ: লক্ষ্য করুন আমরা পিছনের দিকে পুনরাবৃত্তি করি (এর জন্য (int i = list.Count - 1; i >= 0; i--))! আপনি যদি foreach ব্যবহার করেন এবং _bullets.Remove(bullet) কল করার চেষ্টা করেন, C# একটি InvalidOperationException: Collection was modified ছুড়ে দেয়। পিছনের দিকে পুনরাবৃত্তি করা মেমরি রি-ইনডেক্সিং সমস্যা ছাড়াই নিরাপদ উপাদান অপসারণের অনুমতি দেয়।

আর্কেড সিক্রেট: "ইনফ্লেট" এর মাধ্যমে "ফেয়ার হিটবক্স"

ব্লকড: পিক্সেল প্যানজার-এর মতো বিপরীতমুখী গেমগুলিতে, স্প্রাইট টেক্সচারে প্রায়ই স্বচ্ছ মার্জিন বা অ্যান্টেনা স্পাইক থাকে। যদি খেলোয়াড়ের ট্যাঙ্ক বিস্ফোরিত হয় কারণ একটি বুলেট তার টেক্সচারের একটি খালি স্বচ্ছ কোণে স্পর্শ করে, তাহলে খেলোয়াড় প্রতারিত বোধ করবে।

সংঘর্ষকে প্রতিক্রিয়াশীল এবং ন্যায্য মনে করতে, গেমগুলি Rectangle.Inflate ব্যবহার করে স্প্রাইটের ভিতরে একটি ছোট হিটবক্স ব্যবহার করে:

public class EnemyTank : Enemy
{
    // Shrink the bounding box by 6 pixels on all sides for fair collision
    public override Rectangle Bounds
    {
        get
        {
            Rectangle raw = base.Bounds;
            raw.Inflate(-6, -6); // Reduces width and height by 12px
            return raw;
        }
    }
}

3. লেভেল 2: সার্কেল টু সার্কেল সংঘর্ষ (ঘূর্ণন প্রতিরোধ ক্ষমতা)

আয়তক্ষেত্রগুলি স্ট্যাটিক ব্লক এবং গ্রিড টাইলগুলির জন্য দুর্দান্ত কাজ করে, কিন্তু যখন স্প্রাইটগুলি ঘোরে তখন তারা ব্যর্থ হয়। পেইন্ট ট্রেক-এ যখন একটি নন-স্কোয়ার স্পেসশিপ ঘোরে, তখন একটি অক্ষ-সারিবদ্ধ বাউন্ডিং বক্সকে অবশ্যই প্রসারিত করতে হবে যাতে ঘূর্ণায়মান কোণগুলি ঘেরা হয়, যার ফলে খালি বাতাসে হতাশাজনক "ফ্যান্টম সংঘর্ষ" হয়।

বৃত্তাকার গ্রহাণু, হোমিং এনার্জি কক্ষপথ এবং ঘূর্ণায়মান মহাকাশযানের জন্য, বাউন্ডিং সার্কেল হল আদর্শ সমাধান।

স্কয়ার রুট ট্র্যাপ

দুটি বৃত্তের সংঘর্ষ হয় যখন তাদের কেন্দ্রগুলির মধ্যে দূরত্ব তাদের ব্যাসার্ধের যোগফলের কম বা সমান হয়:

\(\text{Distance}(C_A, C_B) \le r_A + r_B\)

কোডে, ইউক্লিডীয় দূরত্ব গণনা করতে Math.Sqrt (বা Vector2.Distance) ব্যবহার করে। যাইহোক, 200টি প্রজেক্টাইল সহ একটি লুপে বর্গমূল গণনা করা শত শত অপ্রয়োজনীয় CPU চক্রকে পুড়িয়ে দেয়!

বর্গ ব্যাসার্ধের যোগফল-এর সাথে বর্গ দূরত্ব তুলনা করে, আমরা বর্গমূলটি সম্পূর্ণরূপে বাদ দিই:

\(\text{DistanceSquared} \le (r_A + r_B)^2\)

মনোগেম বাস্তবায়ন: বৃত্ত বনাম বৃত্ত

public struct Circle
{
    public Vector2 Center;
    public float Radius;

    public Circle(Vector2 center, float radius)
    {
        Center = center;
        Radius = radius;
    }

    public bool Intersects(Circle other)
    {
        float radiusSum = this.Radius + other.Radius;
        
        // MonoGame built-in Vector2.DistanceSquared
        return Vector2.DistanceSquared(this.Center, other.Center) <= (radiusSum * radiusSum);
    }
}

এখন এটিকে সরাসরি একটি সত্তার সাথে সংহত করুন:

public class PaintTrekFighter : Sprite
{
    public float CollisionRadius = 18f;
    public Vector2 Center => Position + new Vector2(Texture.Width * 0.5f, Texture.Height * 0.5f);

    public Circle BoundingCircle => new Circle(Center, CollisionRadius);

    public bool CollidesWith(PaintTrekFighter other)
    {
        return this.BoundingCircle.Intersects(other.BoundingCircle);
    }
}

শূন্য বর্গমূল, স্প্রাইট ঘূর্ণন প্রতিরোধী, এবং বাজ-দ্রুত।


4. স্তর 3: মিশ্র আকার – বৃত্ত বনাম বক্স (ম্যাথহেল্পার. ক্ল্যাম্প)

পেইন্ট ট্রেক-এ একটি বৃত্তাকার স্পেসশিপ যখন আয়তক্ষেত্রাকার প্রতিরক্ষা বাধাগুলির একটি আঁটসাঁট গোলকধাঁধাঁর মধ্য দিয়ে নেভিগেট করে, বা অবরুদ্ধ: পিক্সেল প্যানজার-এর একটি বর্গাকার ব্লকে যখন একটি গোলাকার বুলেট আঘাত করে তখন কী ঘটে?

আমাদের প্রয়োজন বৃত্ত বনাম আয়তক্ষেত্র সংঘর্ষ।

ক্ল্যাম্পিং অ্যালগরিদম

কৌশলটি হল বৃত্তের কেন্দ্রের সবচেয়ে কাছের আয়তক্ষেত্রের বিন্দুটি খুঁজে বের করা এবং তারপর পরীক্ষা করা যে কেন্দ্রের নিকটতম বিন্দু থেকে দূরত্ব বৃত্তের ব্যাসার্ধের চেয়ে কম কিনা।

MonoGame এর MathHelper.Clamp এটিকে তুচ্ছ করে তোলে:

public static class Collision2D
{
    public static bool CircleIntersectsRectangle(Circle circle, Rectangle rect)
    {
        // Find the closest point on the rectangle to the circle center
        float closestX = MathHelper.Clamp(circle.Center.X, rect.Left, rect.Right);
        float closestY = MathHelper.Clamp(circle.Center.Y, rect.Top, rect.Bottom);

        // Vector from closest point to circle center
        float distanceX = circle.Center.X - closestX;
        float distanceY = circle.Center.Y - closestY;

        // Check squared distance against squared radius
        float distanceSquared = (distanceX * distanceX) + (distanceY * distanceY);
        return distanceSquared <= (circle.Radius * circle.Radius);
    }
}

আপনি এখন শূন্য বরাদ্দ এবং উচ্চ নির্ভুলতার সাথে আয়তক্ষেত্রাকার ইটের বিরুদ্ধে প্লেয়ার শিল্ড পরীক্ষা করতে পারেন!


5. Level 4: Continuous Collision Detection (CCD) & Swept Rays

Have you ever fired a hyper-velocity sniper round or a railgun laser in your game, only to watch the bullet magically pass straight through a thin enemy ship without dealing damage?

This bug is known as tunneling.

Because discrete games update in time steps (\(\Delta t = 16.6\text{ms}\) at 60 FPS), an object moving at 1,800 pixels per second travels 30 pixels in a single frame. If the enemy hull is only 15 pixels thick, the bullet was in front of the enemy on Frame 1, and completely behind the enemy on Frame 2.

Frame 1:  [ Bullet ]  --->       | Enemy Wall |
Frame 2:                          | Enemy Wall |       --->  [ Bullet ]
                               (NO HIT DETECTED!)

The Solution: Swept Segment vs. Box (Slab Method)

Instead of testing a single point, we test the entire line segment connecting the bullet's position on Frame 1 (previousPosition) to Frame 2 (currentPosition).

Here is the production raycasting slab-intersection method from our companion title SpiralWar:

public static class ContinuousCollision
{
    public static bool IntersectsSweptRay(Vector2 rayStart, Vector2 rayEnd, Rectangle box, out Vector2 hitPoint)
    {
        hitPoint = Vector2.Zero;

        Vector2 direction = rayEnd - rayStart;
        float tMin = 0f;
        float tMax = 1f;

        // Clip against X slabs
        if (MathF.Abs(direction.X) > 1e-6f)
        {
            float invX = 1f / direction.X;
            float t1 = (box.Left - rayStart.X) * invX;
            float t2 = (box.Right - rayStart.X) * invX;
            if (t1 > t2) (t1, t2) = (t2, t1);

            tMin = MathF.Max(tMin, t1);
            tMax = MathF.Min(tMax, t2);
            if (tMin > tMax) return false;
        }
        else if (rayStart.X < box.Left || rayStart.X > box.Right)
        {
            return false;
        }

        // Clip against Y slabs
        if (MathF.Abs(direction.Y) > 1e-6f)
        {
            float invY = 1f / direction.Y;
            float t1 = (box.Top - rayStart.Y) * invY;
            float t2 = (box.Bottom - rayStart.Y) * invY;
            if (t1 > t2) (t1, t2) = (t2, t1);

            tMin = MathF.Max(tMin, t1);
            tMax = MathF.Min(tMax, t2);
            if (tMin > tMax) return false;
        }
        else if (rayStart.Y < box.Top || rayStart.Y > box.Bottom)
        {
            return false;
        }

        hitPoint = rayStart + direction * tMin;
        return true;
    }
}

In Blocked: Pixel Panzer, the player's continuous Laser Beam skill uses this exact raycast to slice through rows of descending blocks without missing a single collision.


6. Level 5: Production-Grade Pixel-Perfect Collision Detection

Now we reach the ultimate level of 2D accuracy: Pixel-Perfect Collision.

In a retro tank shooter or spaceship dogfight, irregular shapes (tank barrels, wings, cockpit cockpits) are surrounded by transparent pixels in the sprite texture. When an enemy missile hits that transparent space, players notice immediately.

Pixel-perfect collision inspects the actual alpha (transparency) channels of the overlapping textures. If two non-transparent pixels overlap at the same world coordinate, a true physical hit has occurred.

The Fatal Mistake: GetData inside Update()

Many tutorials instruct beginners to do this:

// DO NOT DO THIS!
Color[] dataA = new Color[textureA.Width * textureA.Height];
textureA.GetData(dataA); // STALLS GPU, CREATES MASSIVE GC LAG!

Calling Texture2D.GetData() during runtime forces the CPU to wait for the GPU pipeline to flush, pulling texture memory back over the bus. Doing this for dozens of sprites every frame will tank your game from 60 FPS to 5 FPS and trigger Android ANRs immediately!

The Battle-Tested Solution from Blocked: Pixel Panzer

In Blocked: Pixel Panzer, our Sprite.cs implements an ultra-optimized IntersectsPixel routine built around 5 crucial rules:

  1. Static Color Array Cache: GetData is called exactly once when the texture loads, and stored in a Dictionary<Texture2D, Color[]>.
  2. AABB Early Exit Guard: If Bounds.Intersects(other.Bounds) is false, we bail out immediately. 99% of checks are eliminated before inspecting a single pixel.
  3. Texture Atlas & SourceRectangle Support: Handles sprites packed into texture atlases using source rectangle offsets.
  4. Calculated Overlap Window: We only loop over the exact intersection rectangle between both sprites (Math.Max(a.Top, b.Top), etc.).
  5. Alpha Short-Circuiting: If Sprite A's pixel is transparent (A <= 20), Sprite B is completely skipped.
  6. Property Hoisting: Accessing virtual properties (Bounds) in nested loops creates thousands of struct copies. We store them in local stack variables before entering the loop.

Here is the complete, production-ready code:

using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

public class AdvancedSprite : Sprite
{
    private static readonly Dictionary<Texture2D, Color[]> _textureDataCache = new();

    public Rectangle? SourceRectangle { get; set; }

    public static Color[] GetCachedTextureData(Texture2D texture)
    {
        if (!_textureDataCache.TryGetValue(texture, out var data))
        {
            data = new Color[texture.Width * texture.Height];
            texture.GetData(data);
            _textureDataCache[texture] = data;
        }
        return data;
    }

    public bool IntersectsPixel(AdvancedSprite other)
    {
        // 1. Hoist bounds into local stack variables
        Rectangle a = this.Bounds;
        Rectangle b = other.Bounds;

        // 2. Fast AABB Broad-Phase check
        if (!a.Intersects(b)) return false;

        // Fallback to rectangle check if textures are missing
        if (this.Texture == null || other.Texture == null) return true;

        // 3. Retrieve pre-cached color arrays (Zero GPU latency)
        Color[] dataA = GetCachedTextureData(this.Texture);
        Color[] dataB = GetCachedTextureData(other.Texture);

        int aTexW = this.Texture.Width;
        int bTexW = other.Texture.Width;

        // Atlas / SourceRectangle offset mapping
        bool aHasSrc = this.SourceRectangle.HasValue;
        Rectangle aSrc = aHasSrc ? this.SourceRectangle.Value : Rectangle.Empty;
        int aOriginX = aHasSrc ? aSrc.X : 0;
        int aOriginY = aHasSrc ? aSrc.Y : 0;
        int aSpanX   = aHasSrc ? aSrc.Width  : this.Texture.Width;
        int aSpanY   = aHasSrc ? aSrc.Height : this.Texture.Height;

        bool bHasSrc = other.SourceRectangle.HasValue;
        Rectangle bSrc = bHasSrc ? other.SourceRectangle.Value : Rectangle.Empty;
        int bOriginX = bHasSrc ? bSrc.X : 0;
        int bOriginY = bHasSrc ? bSrc.Y : 0;
        int bSpanX   = bHasSrc ? bSrc.Width  : other.Texture.Width;
        int bSpanY   = bHasSrc ? bSrc.Height : other.Texture.Height;

        // 4. Calculate the overlapping sub-rectangle
        int top    = Math.Max(a.Top, b.Top);
        int bottom = Math.Min(a.Bottom, b.Bottom);
        int left   = Math.Max(a.Left, b.Left);
        int right  = Math.Min(a.Right, b.Right);

        // 5. Scan only overlapping pixels
        for (int y = top; y < bottom; y++)
        {
            // Row offsets hoisted outside the inner X loop!
            int colorA_Y = aOriginY + (int)((y - a.Y) / (float)a.Height * aSpanY);
            int colorB_Y = bOriginY + (int)((y - b.Y) / (float)b.Height * bSpanY);
            int rowA = colorA_Y * aTexW;
            int rowB = colorB_Y * bTexW;

            for (int x = left; x < right; x++)
            {
                int colorA_X = aOriginX + (int)((x - a.X) / (float)a.Width * aSpanX);

                // Early Bailout: If Pixel A is transparent, skip B entirely!
                if (dataA[colorA_X + rowA].A <= 20) continue;

                int colorB_X = bOriginX + (int)((x - b.X) / (float)b.Width * bSpanX);

                // If Pixel B is also opaque, we have confirmed contact!
                if (dataB[colorB_X + rowB].A > 20)
                {
                    return true;
                }
            }
        }

        return false;
    }
}

This routine executes in under 0.1 milliseconds on modern Android hardware and desktop systems.


7. Level 6: Broad-Phase Spatial Grid & Zero-Allocation Mobile GC

Imagine your game has 100 blocks, 60 bullets, and 20 enemies. If you test every entity against every other entity using nested for loops, you perform:

\(\frac{180 \times 179}{2} = 16,110 \text{ checks per frame!}\)

At 60 FPS, that is nearly 1,000,000 collision checks every second.

To scale your game, you must implement Broad-Phase Spatial Partitioning.

The Uniform Spatial Hash Grid

We divide the screen into a 2D grid of uniform cells (in Blocked: Pixel Panzer, each cell is \(150 \times 150\) pixels). An entity only tests collisions against other entities that reside in the same grid cells.

The Mobile Memory Problem: GC Thrashing

If your SpatialGrid creates new List<Point>() or new List<Block>() every frame, you allocate megabytes of garbage every minute on the managed heap.

On Android's Mono runtime, this triggers frequent Gen-0 Garbage Collections, causing: mono runtime: Native lock contention (mono_class_is_subclass_)

The game stutters and Google Play flags your game with ANR warnings!

The Solution: Reusable Scratch Buffers

Here is the Zero-Allocation Spatial Hash Grid from CollisionManager.cs in Blocked: Pixel Panzer:

public class SpatialGridManager
{
    private const int CELL_SIZE = 150;
    private readonly Dictionary<Point, List<Sprite>> _grid = new();

    // Zero-GC: Reusable scratch buffers allocated ONCE at startup
    private readonly List<Point> _scratchCells = new();
    private readonly HashSet<Sprite> _scratchCheckedEntities = new();

    public void BuildGrid(List<Sprite> entities)
    {
        // Clear lists without re-allocating new List objects
        foreach (var list in _grid.Values)
        {
            list.Clear();
        }

        foreach (var entity in entities)
        {
            if (!entity.IsActive) continue;

            GetOccupiedCells(entity.Bounds, _scratchCells);
            foreach (var cell in _scratchCells)
            {
                if (!_grid.TryGetValue(cell, out var list))
                {
                    list = new List<Sprite>();
                    _grid[cell] = list;
                }
                list.Add(entity);
            }
        }
    }

    private void GetOccupiedCells(Rectangle bounds, List<Point> outCells)
    {
        outCells.Clear();

        int startX = bounds.Left / CELL_SIZE;
        int startY = bounds.Top / CELL_SIZE;
        int endX = bounds.Right / CELL_SIZE;
        int endY = bounds.Bottom / CELL_SIZE;

        for (int x = startX; x <= endX; x++)
        {
            for (int y = startY; y <= endY; y++)
            {
                outCells.Add(new Point(x, y));
            }
        }
    }

    public void CheckCollisions(Player player)
    {
        if (player.IsInvulnerable) return;

        GetOccupiedCells(player.Bounds, _scratchCells);
        _scratchCheckedEntities.Clear();

        foreach (var cell in _scratchCells)
        {
            if (_grid.TryGetValue(cell, out var entitiesInCell))
            {
                foreach (var other in entitiesInCell)
                {
                    if (other == player || _scratchCheckedEntities.Contains(other)) continue;
                    _scratchCheckedEntities.Add(other);

                    // 1. Broad-phase AABB test
                    if (player.Bounds.Intersects(other.Bounds))
                    {
                        // 2. High-precision Pixel-Perfect test
                        if (player is AdvancedSprite advPlayer && other is AdvancedSprite advOther)
                        {
                            if (advPlayer.IntersectsPixel(advOther))
                            {
                                player.TakeDamage(10);
                            }
                        }
                    }
                }
            }
        }
    }
}

By reusing _scratchCells and _scratchCheckedEntities, the entire collision step runs with 0 bytes of heap allocation per frame.


8. Summary Comparison Table

Technique Mathematical Cost Rotational Support Tunneling Safe? Best Use Case in MonoGame
AABB (Rectangle.Intersects) Ultra-Fast (~4 integer comparisons) No No Grid blocks, bullet broad-phase, UI
Circle (DistanceSquared) Very Fast (3 muls, 0 sqrt) Yes (Invariant) No Round ships, fireballs, energy orbs
Circle vs Box (Clamp) Fast (Local MathHelper.Clamp) Yes No Circular player navigating tight walls
Swept Ray (Slab CCD) Moderate (Parametric Raycast) Yes Yes Fast sniper bullets, railguns, lasers
Pixel-Perfect (IntersectsPixel) Selective (Restricted Sub-rect) Yes No Irregular sprite contours, fair hitboxes
Spatial Grid (Zero-GC) Broad-phase (\(O(N^2) \to O(N)\)) N/A N/A Dense waves, bullet hells, Android 60 FPS

Real-World Production Showcases: Arar Games

These collision architectures are not theoretical experiments—they are the real engineering foundation powering our commercially released titles:

  • Blocked: Pixel Panzer: Our retro tank survival arcade game on Google Play and Microsoft Store. It features our complete two-tier collision system: a zero-allocation spatial hash grid filtering falling blocks, and pixel-perfect contact checking for tanks, fighter jets, turret shells, and ColorWheel elemental ammunition.
  • Paint Trek: Our fast-paced space shooter featuring rotational circle collision, continuous raycasting, and swept-volume missile defense systems.

Conclusion & Next Steps

MonoGame gives you the power to design collision detection that perfectly matches the needs of your game. By gating expensive Pixel-Perfect checks behind fast AABB tests, utilizing Squared Distances for circles, and eliminating garbage collection with Reusable Scratch Buffers, you can deliver console-smooth 60/120 FPS performance on both desktop and mobile platforms.

Check out our games on the app stores to see these collision systems in action, and start implementing these patterns in your own MonoGame projects today!



SEO Keywords & Hashtags

Keywords: MonoGame 2D collision detection, C# game development, Rectangle.Intersects MonoGame, pixel perfect collision C#, spatial hash grid MonoGame, swept ray continuous collision, indie game performance optimization, zero allocation game loop, Android MonoGame optimization, Arar Games, Blocked Pixel Panzer, Paint Trek.

#MonoGame #CSharp #GameDev #IndieDev #GamePhysics #DotNet #2DGameDev #MobileGameDev #PerformanceOptimization #CleanCode #BlockedPixelPanzer #PaintTrek #ArarGames #GameProgramming




Hiç yorum yok:

Yorum Gönder