Judici de col·lisió pilota a bola

Pàgina actualitzada :
Data de creació de la pàgina :

resum

Una esfera que engloba cada model s'utilitza per fer un judici de cop. En aquesta mostra es realitza detecció de col·lisions per a dos models d'esferes.

球と球のあたり判定

Entorn operatiu

Prerequisits

Versions XNA compatibles
  • 4.0
Plataformes suportades
  • Windows (XP SP2 o posterior, Vista, 7)
  • Xbox 360
  • Windows Phone 7
Windows Requerit Versió Vertex Shader 2.0
Windows requereix la versió de Pixel Shader 2.0

Entorn operatiu

plataforma
  • Finestres 7
  • Xbox 360
  • Windows Phone 7 emulador

Com treballar amb la mostra

tàctil
Funciona amb el teclat del controlador de l'Xbox 360 amb el ratolí
Bola en moviment 1 ↑↓←→ Pal esquerre Botó esquerre & Arrossegar -

substància

Sobre Hit Judgment

En els jocs de trets i els jocs d'acció, es produeixen diverses col·lisions, com ara col·lisions entre personatges i bales, i col·lisions entre personatges, per la qual cosa és necessari escriure un programa per jutjar-los. En el programa, això es coneix generalment com a detecció de col·lisions. Hi ha diversos patrons de judici d'èxit, des de simples fins a complexos matemàticament i físicament. En general, els jocs sovint es fan per reduir la càrrega de processament en lloc de la precisió, i si no hi ha una desviació extrema a l'àrea, no importa molt si no és precisa.

Aquest consell descriu la detecció de cops "pilota a bola" més comuna i menys onerosa. Com que és una esfera i una esfera, estem parlant de judici de col·lisió en l'espai tridimensional, però és possible substituir gairebé el mateix procés per col·lisions entre cercles en l'espai bidimensional.

Com funciona el judici de cops de pilota i pilota

Per determinar la col·lisió d'esferes i esferes s'utilitzen dos paràmetres: la "posició" de cada model i el "radi" de la mida del model. Per determinar si aquests dos paràmetres són correctes, és fàcil d'entendre mirant la figura següent.

  • P: Posició del model L: Distància entre dos punts (P2-P1) R: Radi de l'esfera

当たっていない 接触衝突

Si la "distància entre els dos models" és "L" i la "suma dels radis dels dos models" és "R", llavors "L < R" significa que xoquen. En canvi, si és "L > R", vol dir que no hi ha col·lisió. La detecció de col·lisions de "L = R" tampoc importa.

camp

/// <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;

Podeu escriure el vostre propi programa per al procés de detecció de peticions de fitxer, però el XNA Framework té una estructura anomenada "BoundingSphere" que facilita el maneig dels paràmetres de l'esfera i la detecció de peticions de fitxer, així que m'agradaria utilitzar-lo.

Cada ModelMesh de la classe Model carregada ja conté la informació de l'esfera "BoundingSphere" que engloba el model, així que hem preparat un camp "baseBoundingSphere" per recuperar-lo.

Altres característiques inclouen la posició de cada esfera, una BoundingSphere utilitzada per determinar l'impacte de dues esferes, i una bandera de col·lisió.

Càrrega

// モデルを作成 
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;

Cada ModelMesh d'un Model té una propietat BoundingSphere que permet obtenir informació sobre l'esfera que engloba el model en el ModelMesh. Com que el model que estem utilitzant té un únic ModelMesh, hem copiat l'esfera inclusiva des del primer índex fins a la baseBoundingSphere.

Com que el radi de l'esfera és fix, el radi està preestablert a la propietat Radius de les dues esferes limítrofes.

Encertar el judici

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

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

Utilitzeu el mètode BoundingSphere.Intersects per determinar les col·lisions esfera-esfera. Com que ja tenim un radi establert per a les dues BoundingSpheres, establim la propietat BoundingSphere.Center a la posició de l'esfera més les coordenades centrals de l'esfera paraigua original. S'afegeixen les coordenades centrals de l'esfera original perquè el centre de l'esfera inclusiva no és necessàriament l'origen.

Si especifiqueu l'altra BoundingSphere com a argument a BoundingSphere.Intersects, retornarà un bool per veure si està xocant o no, així ho obtenim. Aquesta bandera serveix per dibuixar caràcters per veure si són correctes.

Com calcular el judici de cop

El marc XNA proporciona una estructura útil de detecció de col·lisions anomenada BoundingSphere, que es pot utilitzar no només per a esferes, sinó també per a col·lisions amb diferents formes, com ara raigs (línies) i caixes.

Tanmateix, si es tracta d'una col·lisió entre esferes, es pot determinar mitjançant un càlcul senzill sense utilitzar BoundingSphere.Intersects.

  • Resultat (si és colpejat) = Distància entre la posició de l'Esfera 2 i la posició de l'Esfera 1 < Radi de l'Esfera 1 + Radi de l'Esfera 2

Si l'escrius programàticament

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

Es tracta de. (El procés de detecció de col·lisions anterior assumeix que el centre de l'esfera inclusiva és l'origen, com una esfera perfecta, de manera que no té en compte el centre de l'esfera inclusiva del model.) Si ho considereu, quedarà així)

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

Tots els codis

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);
        }
    }
}