0
\$\begingroup\$

I'm developing a mirror for lazer beam(Ball sprite). There I'm trying to redirect the laze beam according to the ration degree of the mirror(Rectangle). How can I collide the ball to the correct angle if the colliding object is with some angle(45 deg) rather than colliding back.

here is an screen shot of my work enter image description here

here is my code

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;

namespace collision
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        Texture2D ballTexture;
        Rectangle ballBounds;
        Vector2 ballPosition;
        Vector2 ballVelocity;
        float ballSpeed = 30f;
        Texture2D blockTexture;
        Rectangle blockBounds;
        Vector2 blockPosition;
        private Vector2 origin;
        KeyboardState keyboardState;

        //Font
        SpriteFont Font1;
        Vector2 FontPos;
        private String displayText;
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            ballPosition = new Vector2(this.GraphicsDevice.Viewport.Width / 2,
                           this.GraphicsDevice.Viewport.Height * 0.25f);
            blockPosition = new Vector2(this.GraphicsDevice.Viewport.Width / 2,
                                       this.GraphicsDevice.Viewport.Height /2);
            ballVelocity = new Vector2(0, 1);

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            ballTexture = Content.Load<Texture2D>("ball");
            blockTexture = Content.Load<Texture2D>("mirror");

            //create rectangles based off the size of the textures
            ballBounds = new Rectangle((int)(ballPosition.X - ballTexture.Width / 2),
            (int)(ballPosition.Y - ballTexture.Height / 2), ballTexture.Width, ballTexture.Height);

            blockBounds = new Rectangle((int)(blockPosition.X - blockTexture.Width / 2),
            (int)(blockPosition.Y - blockTexture.Height / 2), blockTexture.Width, blockTexture.Height);

            origin.X = blockTexture.Width / 2;
            origin.Y = blockTexture.Height / 2;
            // TODO: use this.Content to load your game content here
            Font1 = Content.Load<SpriteFont>("SpriteFont1");
            FontPos = new Vector2(graphics.GraphicsDevice.Viewport.Width - 100, 20);

        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        ///
        private float RotationAngle;
          float circle = MathHelper.Pi * 2;
          float angle;

        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here
            //check for collision between the ball and the block, or if the ball is outside the bounds of the screen

            if (ballBounds.Intersects(blockBounds) || !GraphicsDevice.Viewport.Bounds.Contains(ballBounds))
            {

                //we have a simple collision!
                //if it has hit, swap the direction of the ball, and update it's position
                ballVelocity = -ballVelocity;
                ballPosition += ballVelocity * ballSpeed;

            }

            else
            {

                //move the ball a bit
                ballPosition += ballVelocity * ballSpeed;

            }

            //update bounding boxes
            ballBounds.X = (int)ballPosition.X;
            ballBounds.Y = (int)ballPosition.Y;

            blockBounds.X = (int)blockPosition.X;
            blockBounds.Y = (int)blockPosition.Y;


            keyboardState = Keyboard.GetState();

            float val = 1.568017f/90;

            if (keyboardState.IsKeyDown(Keys.Space))
                RotationAngle = RotationAngle + (float)Math.PI;

            if (keyboardState.IsKeyDown(Keys.Left))
                RotationAngle = RotationAngle - val;

            angle = (float)Math.PI / 4.0f;  // 90 degrees
            RotationAngle = angle;
            //   RotationAngle = RotationAngle % circle;
                displayText = RotationAngle.ToString();
            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here
            spriteBatch.Begin();

            // Find the center of the string
            Vector2 FontOrigin = Font1.MeasureString(displayText) / 2;
            spriteBatch.DrawString(Font1, displayText, FontPos, Color.White, 0, FontOrigin, 1.0f, SpriteEffects.None, 0.5f);
            spriteBatch.Draw(ballTexture, ballPosition, Color.White);
            spriteBatch.Draw(blockTexture, blockPosition,null, Color.White, RotationAngle,origin, 1.0f, SpriteEffects.None, 0f);

            spriteBatch.End();
            base.Draw(gameTime);
        }
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ If you plan to create a game a bit more complex, then you can use a physics engine (e. g. Farseer Physics for XNA). That makes it a lot easier to handle lots of collusion. \$\endgroup\$
    – jalgames
    Commented Sep 26, 2013 at 14:58

2 Answers 2

1
\$\begingroup\$

You should determine what side of the rectangle is colliding with the ball, and get the normal N of that side.

If the ball movement vector is V, then the reflected vector is:

 var reflected = Vector3.Reflect(V,N);

http://msdn.microsoft.com/en-us/library/bb198637.aspx

To determine if the ball is colliding you can work in the rectangle space:

   TrasnformToWorld = MatrixCreateTranslation(-origin )
                    * Matrix.CreateRotationZ(angle) 
                    * MatrixCreateTranslation(recPos);
   TransformToRectangleSpace = Matrix.Invert(TransformToWorld);

   BallPositionInRectangleSpace = Vector3.Transform(ballPos, TransformToRectangleSpace );
   BallDirectionInRectangleSpace = Vector3.TransformNormal(ballDir, TransformToRectangleSpace);

Now we have the ball pos and dir related to a rectangle with position in (0,0) and size (width, height) and knowing where is colliding is easy. When you are determined the reflection vector, you have to transform it to world coordinates:

 var newBallDir = Vector3.TransformNormal(reflectedInrectangleSpace, TrasnformToWorld );
\$\endgroup\$
0
\$\begingroup\$

Reflection follows a very simple law. The angle between the ray falling in to the mirror and the normal of the mirror is equal to the angle between the ray out of the mirror and the normal of the mirror.

I can think of two ways to calculate this. The first would be to reverse the velocity of the ball in to the mirror and then rotate it by two times the angle between the reversed velocity and the mirror normal.

The second would be to project the velocity on to the normal vector and reverse that component (i.e. subtract it twice).

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .