Spriedums par sadursmi no bumbas pret bumbu

Lapa atjaunota :
Lapas izveides datums :

Kopsavilkuma

Sfēra, kas aptver katru modeli, tiek izmantota, lai izdarītu trāpījumu. Šajā paraugā sadursmes noteikšana tiek veikta diviem sfēras modeļiem.

球と球のあたり判定

Darbības vide

Priekšnoteikumi

Atbalstītās XNA versijas
  • 4.0
Atbalstītās platformas
  • Windows (XP SP2 vai jaunāka versija, Vista, 7)
  • Xbox 360
  • Windows tālrunis 7
Windows nepieciešamā Vertex Shader versija 2.0
Windows nepieciešamā Pixel Shader versija 2.0

Darbības vide

platforma
  • Operētājsistēmā Windows 7
  • Xbox 360
  • Windows Phone 7 emulators

Kā strādāt ar paraugu

Darbojas tastatūraXbox 360 kontrolierismouse touch
Kustīgā bumba 1 ↑↓←→ Kreisā nūja Poga pa kreisi un vilkšana -

viela

Par Hit spriedumu

Šaušanas spēlēs un darbības spēlēs notiek dažādas sadursmes, piemēram, sadursmes starp rakstzīmēm un lodēm, kā arī sadursmes starp rakstzīmēm, tāpēc ir nepieciešams uzrakstīt programmu, lai tās spriestu. Programmā to parasti sauc par sadursmes noteikšanu. Ir dažādi trāpījumu vērtēšanas modeļi, sākot no vienkāršiem līdz sarežģītiem matemātiski un fiziski. Kopumā spēles bieži tiek veiktas, lai samazinātu apstrādes slodzi, nevis precizitāti, un, ja apgabalā nav ārkārtējas novirzes, tas nav svarīgi, ja tas nav precīzs.

Šis padoms apraksta visizplatītāko un vismazāk apgrūtinošo "bumba-bumba" trāpījumu noteikšanu. Tā kā tā ir sfēra un sfēra, mēs runājam par sadursmes spriedumu trīsdimensiju telpā, bet gandrīz tādu pašu procesu ir iespējams aizstāt ar sadursmēm starp apļiem divdimensiju telpā.

Kā darbojas bumbas un bumbas trāpījums

Lai noteiktu sfēru un sfēru sadursmi, tiek izmantoti divi parametri: katra modeļa "pozīcija" un modeļa lieluma "rādiuss". Lai noteiktu, vai šie divi parametri ir pareizi, to ir viegli saprast, aplūkojot zemāk redzamo attēlu.

  • P: Modeļa atrašanās vieta L: Attālums starp diviem punktiem (P2-P1) R: Sfēras rādiuss

当たっていない 接触衝突

Ja "attālums starp abiem modeļiem" ir "L" un "abu modeļu rādiusu summa" ir "R", tad "L < R" nozīmē, ka tie saduras. No otras puses, ja tas ir "L > R", tas nozīmē, ka sadursmes nav. "L = R" sadursmes noteikšanai arī nav nozīmes.

lauks

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

Jūs varat uzrakstīt savu programmu trāpījumu noteikšanas procesam, bet XNA Framework ir struktūra ar nosaukumu "BoundingSphere", kas ļauj viegli apstrādāt sfēras parametrus un trāpījumu noteikšanu, tāpēc es vēlētos to izmantot.

Katrs ielādētās modeļa klases ModelMesh jau satur sfēras informāciju "BoundingSphere", kas ietver modeli, tāpēc mēs esam sagatavojuši lauku "baseBoundingSphere", lai to izgūtu.

Citas funkcijas ietver katras sfēras atrašanās vietu, ierobežojošo sfēru, ko izmanto, lai noteiktu divu sfēru ietekmi, un sadursmes karodziņu.

Slodze

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

Katram ModelMesh modelim ir rekvizīts BoundingSphere, kas ļauj iegūt informāciju par sfēru, kas ietver modeli ModelMesh. Tā kā mūsu izmantotajam modelim ir viens ModelMesh, mēs esam nokopējuši iekļaujošo sfēru no pirmā indeksa uz baseBoundingSphere.

Tā kā sfēras rādiuss ir fiksēts, rādiuss ir iepriekš iestatīts abu ierobežojošo sfēru rādiusa īpašībā.

Hit spriedums

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

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

Izmantojiet metodi BoundingSphere.Intersects, lai noteiktu sfēras-sfēras sadursmes. Tā kā mums jau ir iestatīts rādiuss abām BoundingSpheres, mēs iestatām BoundingSphere.Center rekvizītu uz sfēras stāvokli plus sākotnējās lietussarga sfēras centra koordinātas. Sākotnējās sfēras centra koordinātas tiek pievienotas, jo iekļaujošās sfēras centrs ne vienmēr ir izcelsme.

Ja jūs norādāt otru BoundingSphere kā argumentu BoundingSphere.Intersects, tas atgriezīs bool, lai redzētu, vai tas saduras vai nē, tāpēc mēs to iegūstam. Šis karodziņš tiek izmantots, lai zīmētu rakstzīmes, lai redzētu, vai tās ir pareizas.

Kā aprēķināt trāpījuma spriedumu

XNA Framework nodrošina noderīgu sadursmju noteikšanas struktūru ar nosaukumu BoundingSphere, ko var izmantot ne tikai sfērām, bet arī sadursmēm ar dažādām formām, piemēram, stariem (līnijām) un kastēm.

Tomēr, ja tā ir sadursme starp sfērām, to var noteikt ar vienkāršu aprēķinu, neizmantojot BoundingSphere.Intersects.

  • Rezultāts (vai tas ir trāpīts) = Attālums starp 2. sfēras stāvokli un 1. sfēras stāvokli < 1. sfēras rādiuss + 2. sfēras rādiuss

Ja rakstāt to programmiski

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

Tā sanāk. (Iepriekš minētais sadursmes noteikšanas process pieņem, ka iekļaujošās sfēras centrs ir izcelsme, tāpat kā perfekta sfēra, tāpēc tajā netiek ņemts vērā modeļa iekļaujošās sfēras centrs.) Ja jūs to uzskatāt, tas izskatīsies šādi)

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

Visi kodi

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