Ball-to-ball collision judgment

Page update date :
Page creation date :

summary

A sphere that encompasses each model is used to make a hit judgment. In this sample, collision detection is performed for two sphere models.

球と球のあたり判定

Operating environment

Prerequisites

Supported XNA Versions
  • 4.0
Supported Platforms
  • Windows (XP SP2 or later, Vista, 7)
  • Xbox 360
  • Windows Phone 7
Windows Required Vertex Shader Version 2.0
Windows Required Pixel Shader Version 2.0

Operating environment

platform
  • Windows 7
  • Xbox 360
  • Windows Phone 7 Emulator

How to work with the sample

Works keyboardXbox 360 controllermouse touch
Moving Ball 1 ↑↓←→ Left Stick Left Button & Drag -

substance

About Hit Judgment

In shooting games and action games, various collisions occur, such as collisions between characters and bullets, and collisions between characters, so it is necessary to write a program to judge them. In the program, this is generally referred to as collision detection. There are various patterns of hit judgment, from simple to complex mathematically and physically. In general, games are often made to reduce the processing load rather than accuracy, and if there is no extreme deviation in the area, it does not matter much if it is not accurate.

This tip describes the most common and least burdensome "ball-to-ball" hit detection. Since it is a sphere and a sphere, we are talking about collision judgment in three-dimensional space, but it is possible to substitute almost the same process for collisions between circles in two-dimensional space.

How the ball and ball hit judgment works

Two parameters are used to determine the collision of spheres and spheres: the "position" of each model and the "radius" of the size of the model. In order to determine whether these two parameters are correct, it is easy to understand by looking at the figure below.

  • P: Position of the model L: Distance between two points (P2-P1) R: Radius of the sphere

当たっていない 接触衝突

If the "distance between the two models" is "L" and the "sum of the radii of the two models" is "R", then "L < R" means that they are colliding. On the other hand, if it is "L > R", it means that there is no collision. The collision detection of "L = R" does not matter for either.

field

/// <summary>
/// モデル
/// </summary>
private Model model = null;

/// <summary>
/// モデルの基本包括球
/// </summary>
private BoundingSphere baseBoundingSphere = new BoundingSphere();

/// <summary>
/// 球1の位置
/// </summary>
private Vector3 sphere1Position = new Vector3(0.0f, 0.0f, 0.0f);

/// <summary>
/// 球2の位置
/// </summary>
private Vector3 sphere2Position = new Vector3(1.5f, 0.0f, -3.0f);

/// <summary>
/// 球1の包括球
/// </summary>
private BoundingSphere sphere1BoundingSphere = new BoundingSphere();

/// <summary>
/// 球2の包括球
/// </summary>
private BoundingSphere sphere2BoundingSphere = new BoundingSphere();

/// <summary>
/// 衝突フラグ
/// </summary>
private bool isCollision = false;

You can write your own program for the hit detection process, but the XNA Framework has a structure called "BoundingSphere" that makes it easy to handle the parameters of the sphere and the hit detection, so I would like to use it.

Each ModelMesh of the loaded Model class already contains the sphere information "BoundingSphere" that encompasses the model, so we have prepared a field "baseBoundingSphere" to retrieve it.

Other features include the position of each sphere, a BoundingSphere used to determine the impact of two spheres, and a collision flag.

Load

// モデルを作成 
this.model = this.Content.Load<Model>("Sphere"); 

// 包括球取得 
this.baseBoundingSphere = this.model.Meshes[0].BoundingSphere; 

// 各モデル用の包括球半径設定 
this.sphere1BoundingSphere.Radius = this.baseBoundingSphere.Radius; 
this.sphere2BoundingSphere.Radius = this.baseBoundingSphere.Radius;

Each ModelMesh in a Model has a BoundingSphere property that allows you to get information about the sphere that encompasses the model in the ModelMesh. Since the model we are using has a single ModelMesh, we have copied the inclusive sphere from the first index to the baseBoundingSphere.

Since the radius of the sphere is fixed, the radius is preset in the Radius property of the two BoundingSpheres.

Hit Judgment

// 衝突判定用の球を設定 
this.sphere1BoundingSphere.Center = 
    this.sphere1Position + this.baseBoundingSphere.Center; 
this.sphere2BoundingSphere.Center = 
    this.sphere2Position + this.baseBoundingSphere.Center; 

// 衝突判定 
this.isCollision = 
    this.sphere1BoundingSphere.Intersects(this.sphere2BoundingSphere);

Use the BoundingSphere.Intersects method to determine sphere-to-sphere collisions. Since we already have a radius set for the two BoundingSpheres, we set the BoundingSphere.Center property to the position of the sphere plus the center coordinates of the original umbrella sphere. The center coordinates of the original sphere are added because the center of the inclusive sphere is not necessarily the origin.

If you specify the other BoundingSphere as an argument to BoundingSphere.Intersects, it will return a bool to see if it is colliding or not, so we get it. This flag is used to draw characters to see if they are correct.

How to calculate the hit judgment

The XNA Framework provides a useful collision detection structure called BoundingSphere, which can be used not only for spheres but also for collisions with different shapes such as rays (lines) and boxes.

However, if it is a collision between spheres, it can be determined by a simple calculation without using BoundingSphere.Intersects.

  • Result (whether it is hit) = Distance between the position of Sphere 2 and the position of Sphere 1 < Radius of Sphere 1 + Radius of Sphere 2

If you write it programmatically

this.isCollision = (this.sphere2Position - this.sphere1Position).Length() <
                   (this.sphere1BoundingSphere.Radius + this.sphere2BoundingSphere.Radius);

It comes to. (The collision detection process above assumes that the center of the inclusive sphere is the origin, like a perfect sphere, so it does not take into account the center of the inclusive sphere of the model.) If you consider it, it will look like the following)

this.isCollision = ((this.sphere2Position + this.baseBoundingSphere.Center) -
                        (this.sphere1Position + this.baseBoundingSphere.Center)).Length() <
                   (this.sphere1BoundingSphere.Radius + this.sphere2BoundingSphere.Radius);

All Codes

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
#if WINDOWS_PHONE
using Microsoft.Xna.Framework.Input.Touch;
#endif

namespace CollisionSphereAndSphere
{
    /// <summary>
    /// ゲームメインクラス
    /// </summary>
    public class GameMain : Microsoft.Xna.Framework.Game
    {
        /// <summary>
        /// グラフィックデバイス管理クラス
        /// </summary>
        private GraphicsDeviceManager graphics = null;

        /// <summary>
        /// スプライトのバッチ化クラス
        /// </summary>
        private SpriteBatch spriteBatch = null;

        /// <summary>
        /// スプライトでテキストを描画するためのフォント
        /// </summary>
        private SpriteFont font = null;

        /// <summary>
        /// モデル
        /// </summary>
        private Model model = null;

        /// <summary>
        /// モデルの基本包括球
        /// </summary>
        private BoundingSphere baseBoundingSphere = new BoundingSphere();

        /// <summary>
        /// 球1の位置
        /// </summary>
        private Vector3 sphere1Position = new Vector3(0.0f, 0.0f, 0.0f);

        /// <summary>
        /// 球2の位置
        /// </summary>
        private Vector3 sphere2Position = new Vector3(1.5f, 0.0f, -3.0f);

        /// <summary>
        /// 球1の包括球
        /// </summary>
        private BoundingSphere sphere1BoundingSphere = new BoundingSphere();

        /// <summary>
        /// 球2の包括球
        /// </summary>
        private BoundingSphere sphere2BoundingSphere = new BoundingSphere();

        /// <summary>
        /// 衝突フラグ
        /// </summary>
        private bool isCollision = false;

        /// <summary>
        /// 前回のマウスの状態
        /// </summary>
        private MouseState oldMouseState;


        /// <summary>
        /// GameMain コンストラクタ
        /// </summary>
        public GameMain()
        {
            // グラフィックデバイス管理クラスの作成
            this.graphics = new GraphicsDeviceManager(this);

            // ゲームコンテンツのルートディレクトリを設定
            this.Content.RootDirectory = "Content";

#if WINDOWS_PHONE
            // Windows Phone のデフォルトのフレームレートは 30 FPS
            this.TargetElapsedTime = TimeSpan.FromTicks(333333);

            // バックバッファサイズの設定
            this.graphics.PreferredBackBufferWidth = 480;
            this.graphics.PreferredBackBufferHeight = 800;

            // フルスクリーン表示
            this.graphics.IsFullScreen = true;
#endif
        }

        /// <summary>
        /// ゲームが始まる前の初期化処理を行うメソッド
        /// グラフィック以外のデータの読み込み、コンポーネントの初期化を行う
        /// </summary>
        protected override void Initialize()
        {
            // TODO: ここに初期化ロジックを書いてください

            // コンポーネントの初期化などを行います
            base.Initialize();
        }

        /// <summary>
        /// ゲームが始まるときに一回だけ呼ばれ
        /// すべてのゲームコンテンツを読み込みます
        /// </summary>
        protected override void LoadContent()
        {
            // テクスチャーを描画するためのスプライトバッチクラスを作成します
            this.spriteBatch = new SpriteBatch(this.GraphicsDevice);

            // フォントをコンテントパイプラインから読み込む
            this.font = this.Content.Load<SpriteFont>("Font");

            // モデルを作成
            this.model = this.Content.Load<Model>("Sphere");

            // 包括球取得
            this.baseBoundingSphere = this.model.Meshes[0].BoundingSphere;

            // 各モデル用の包括球半径設定
            this.sphere1BoundingSphere.Radius = this.baseBoundingSphere.Radius;
            this.sphere2BoundingSphere.Radius = this.baseBoundingSphere.Radius;

            // あらかじめパラメータを設定しておく
            foreach (ModelMesh mesh in this.model.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    // デフォルトのライト適用
                    effect.EnableDefaultLighting();

                    // ビューマトリックスをあらかじめ設定
                    effect.View = Matrix.CreateLookAt(
                        new Vector3(0.0f, 10.0f, 1.0f),
                        Vector3.Zero,
                        Vector3.Up
                    );

                    // プロジェクションマトリックスをあらかじめ設定
                    effect.Projection = Matrix.CreatePerspectiveFieldOfView(
                        MathHelper.ToRadians(45.0f),
                        (float)this.GraphicsDevice.Viewport.Width /
                            (float)this.GraphicsDevice.Viewport.Height,
                        1.0f,
                        100.0f
                    );
                }
            }
        }

        /// <summary>
        /// ゲームが終了するときに一回だけ呼ばれ
        /// すべてのゲームコンテンツをアンロードします
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: ContentManager で管理されていないコンテンツを
            //       ここでアンロードしてください
        }

        /// <summary>
        /// 描画以外のデータ更新等の処理を行うメソッド
        /// 主に入力処理、衝突判定などの物理計算、オーディオの再生など
        /// </summary>
        /// <param name="gameTime">このメソッドが呼ばれたときのゲーム時間</param>
        protected override void Update(GameTime gameTime)
        {
            KeyboardState keyboardState = Keyboard.GetState();
            MouseState mouseState = Mouse.GetState();
            GamePadState gamePadState = GamePad.GetState(PlayerIndex.One);

            // Xbox 360 コントローラ、Windows Phone の BACK ボタンを押したときに
            // ゲームを終了させます
            if (gamePadState.Buttons.Back == ButtonState.Pressed)
            {
                this.Exit();
            }

            float speed = 0.1f;

            // 球1の位置を移動させる
            if (gamePadState.IsConnected)
            {
                this.sphere1Position.X += gamePadState.ThumbSticks.Left.X * speed;
                this.sphere1Position.Z -= gamePadState.ThumbSticks.Left.Y * speed;
            }
            if (keyboardState.IsKeyDown(Keys.Left))
            {
                this.sphere1Position.X -= speed;
            }
            if (keyboardState.IsKeyDown(Keys.Right))
            {
                this.sphere1Position.X += speed;
            }
            if (keyboardState.IsKeyDown(Keys.Down))
            {
                this.sphere1Position.Z += speed;
            }
            if (keyboardState.IsKeyDown(Keys.Up))
            {
                this.sphere1Position.Z -= speed;
            }
            if (mouseState.LeftButton == ButtonState.Pressed)
            {
                // 直前にマウスの左ボタンが押されていない場合は差分を0にする
                if (this.oldMouseState.LeftButton == ButtonState.Released)
                {
                    this.oldMouseState = mouseState;
                }

                this.sphere1Position += new Vector3((mouseState.X - this.oldMouseState.X) * 0.01f,
                                                   0,
                                                   (mouseState.Y - this.oldMouseState.Y) * 0.01f);
            }

            // マウスの状態記憶
            this.oldMouseState = mouseState;

            // 衝突判定用の球を設定
            this.sphere1BoundingSphere.Center =
                this.sphere1Position + this.baseBoundingSphere.Center;
            this.sphere2BoundingSphere.Center =
                this.sphere2Position + this.baseBoundingSphere.Center;

            // 衝突判定
            this.isCollision =
                this.sphere1BoundingSphere.Intersects(this.sphere2BoundingSphere);

            // 登録された GameComponent を更新する
            base.Update(gameTime);
        }

        /// <summary>
        /// 描画処理を行うメソッド
        /// </summary>
        /// <param name="gameTime">このメソッドが呼ばれたときのゲーム時間</param>
        protected override void Draw(GameTime gameTime)
        {
            // 画面を指定した色でクリアします
            this.GraphicsDevice.Clear(Color.CornflowerBlue);

            // 深度バッファを有効にする
            this.GraphicsDevice.DepthStencilState = DepthStencilState.Default;

            foreach (ModelMesh mesh in this.model.Meshes)
            {
                // 球1を描画
                foreach (BasicEffect effect in mesh.Effects)
                {
                    // ワールドマトリックス(位置指定)
                    effect.World = Matrix.CreateTranslation(this.sphere1Position);
                }
                mesh.Draw();

                // 球2を描画
                foreach (BasicEffect effect in mesh.Effects)
                {
                    // ワールドマトリックス(位置指定)
                    effect.World = Matrix.CreateTranslation(this.sphere2Position);
                }
                mesh.Draw();
            }

            // スプライトの描画準備
            this.spriteBatch.Begin();

            // 衝突判定表示
            this.spriteBatch.DrawString(this.font,
                "IsCollision : " + this.isCollision,
                new Vector2(30.0f, 30.0f), Color.White);

            // スプライトの一括描画
            this.spriteBatch.End();

            // 登録された DrawableGameComponent を描画する
            base.Draw(gameTime);
        }
    }
}