• Welcome to Overclockers Forums! Join us to reply in threads, receive reduced ads, and to customize your site experience!

XNA4 Help

Overclockers is supported by our readers. When you click a link to make a purchase, we may earn a commission. Learn More.

Ronbert

Member
Joined
Jan 30, 2010
Location
La Crosse, WI
So the simply run down on what I'm trying to do here is this... I'm trying to shoot a bullet and I want said bullet to follow a vector towards the mouse. Now currently my code DOES this but the bullet stops AT the mouse. I want the bullet to continue on until it leaves the edge of the screen. How can I go about doing this?

This calculates the distance between the bullet and my mouse using Pythagorean therm.
Code:
private float calculateDistance(Vector2 A, Vector2 B)
        {
            A = new Vector2(Math.Abs(A.X), Math.Abs(A.Y));
            B = new Vector2(Math.Abs(B.X), Math.Abs(B.Y));

            float Y_diff, X_diff, distance;

            Y_diff = A.Y - B.Y;
            X_diff = A.X - B.X;

            distance = (float)Math.Sqrt(Math.Pow(X_diff,2) + Math.Pow(Y_diff,2));


            return Math.Abs(distance);
        }

This launches the bullet
Code:
//define some variable for later on
            Vector2 mouse_pos = new Vector2(MS.X - bullet.Width/2, MS.Y - bullet.Height/2);//where mouse is
            Vector2 direction = mouse_pos - position;//get xy diff
            float distance = calculateDistance(mouse_pos, position);
            velocity = Vector2.Zero;

            if (direction != Vector2.Zero)
            {
                direction.Normalize();
            }


            if (MS.LeftButton == ButtonState.Pressed)
            {
                if (distance < baseSpeed)
                    velocity += direction * distance;
                else
                    velocity += direction * baseSpeed;
            }

            

            position += velocity * baseSpeed;

Any help is greatly appreciated because I'm totally stuck here...
 
Calculate direction of vector then normalize it.

You can multiply the dir vector by a coefficient (generally the frame time) to make it frame independent.
Each frame you add the Dir vector to the bullets position.

Now this problem is easy but if you need still help just ask again.

e.g

Vector2 mouse,bullet,dir;

dir = (mouse - bullet);
dir.normalize();
//ofc you don't need to calculate dir every frame

dir *= frameTime * speedCoeffiecient;

bullet += dir;

profit.
 
Last edited:
Pretty helpful :) I've spent a lot of time researching this over the past couple days just to more understand the use of lists and bounding boxes. Thank goodness for google.
 
Back