Jump to content

  • Log In with Google      Sign In   
  • Create Account

FREE SOFTWARE GIVEAWAY

We have 4 x Pro Licences (valued at $59 each) for 2d modular animation software Spriter to give away in this Thursday's GDNet Direct email newsletter.


Read more in this forum topic or make sure you're signed up (from the right-hand sidebar on the homepage) and read Thursday's newsletter to get in the running!


mistervirtue

Member Since 26 Aug 2009
Offline Last Active Mar 16 2014 02:01 PM

#5067149 XNA - Making A Sprite Fire A Projectile

Posted by mistervirtue on 03 June 2013 - 12:24 PM

Here is my code for the most part

 

--------- SpriteManager ---------

    public class SpriteManager : Microsoft.Xna.Framework.DrawableGameComponent
    {

        SpriteBatch spriteBatch;
        UserControlledSprite player;
        Texture2D testingRec;
        Texture2D projectileSprite;
        List<Sprite> spriteList = new List<Sprite>();

        public SpriteManager(Game game)
            : base(game)
        {
        }

        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(Game.GraphicsDevice);

            player = new UserControlledSprite(Game.Content.Load<Texture2D>(@"images/SmallHero"),
                Vector2.Zero, new Point(85, 97), 1, new Point(0, 0), new Point(1, 1), new Vector2(3, 3));
            
            testingRec = Game.Content.Load<Texture2D>(@"images/testRec");

            projectileSprite = Game.Content.Load<Texture2D>(@"images/fireblast");

            base.LoadContent();

        }

        public override void Initialize()
        {
            base.Initialize();
        }

        public override void Update(GameTime gameTime)
        {
            player.Update(gameTime, Game.Window.ClientBounds);
            base.Update(gameTime);
        }

        public override void Draw(GameTime gameTime)
        {
            spriteBatch.Begin();

            player.Draw(gameTime, spriteBatch);

            spriteBatch.Draw(testingRec,player.collisionRect ,Color.White);

            spriteBatch.End();

            base.Draw(gameTime);
        }
    }

 

----- My base Sprite Class -------

namespace ProjectGaslightKnights
{
    abstract class Sprite
    {
        public Texture2D textureImage;
        protected Vector2 position;
        protected Point frameSize;
        int collisionOffset;
        public Point currentFrame;
        public Point sheetSize;
        int timeSinceLastFrame = 0;
        protected Vector2 speed;
        int milisecondsPerFrame;
        const int defaultMillisecondsPerFrame = 16;


        SpriteEffects myEffect;
        Texture2D testingRecTexture;

        public Sprite(Texture2D textureImage, Vector2 position, Point frameSize,
            int collisionOffset, Point currentFrame, Point sheetSize, Vector2 speed)
            : this(textureImage, position, frameSize, collisionOffset, currentFrame, sheetSize, speed, defaultMillisecondsPerFrame)
        {

        }

        public Sprite(Texture2D textureImage, Vector2 position, Point frameSize, int collisionOffset, Point currentFrame,
            Point sheetSize, Vector2 speed, int millisecondsPerFrame)
        {
            this.textureImage = textureImage;
            this.position = position;
            this.frameSize = frameSize;
            this.collisionOffset = collisionOffset;
            this.currentFrame = currentFrame;
            this.sheetSize = sheetSize;
            this.speed = speed;
            this.milisecondsPerFrame = milisecondsPerFrame;
        }

        public virtual void Update(GameTime gameTime, Rectangle ClientBounds)
        {
            timeSinceLastFrame += gameTime.ElapsedGameTime.Milliseconds;
            if (timeSinceLastFrame > milisecondsPerFrame)
            {
                timeSinceLastFrame = 0;
                ++currentFrame.X;
                if (currentFrame.X >= sheetSize.X)
                {
                    currentFrame.X = 0;
                    ++currentFrame.Y;
                    if (currentFrame.Y >= sheetSize.Y)
                    {
                        currentFrame.Y = 0;
                    }
                }
            }
        }

        public virtual void Draw(GameTime gameTime, SpriteBatch spriteBatch)
        {
            spriteBatch.Draw(textureImage, position,
                new Rectangle(currentFrame.X * frameSize.X, currentFrame.Y * frameSize.Y,
                    frameSize.X, frameSize.Y), Color.White, 0, Vector2.Zero, 1f, myEffect, 0);

            spriteBatch.Draw(testingRecTexture, collisionRect, Color.White);
        }


        public abstract Vector2 direction
        {
            get;
        }


        public Rectangle collisionRect
        {
            get
            {
                return new Rectangle(
                    (int)position.X + collisionOffset,
                    (int)position.Y + collisionOffset,
                    frameSize.X - (collisionOffset * 2),
                    frameSize.Y - (collisionOffset * 2));
            }
        }

        internal void Update(GameTime gameTime)
        {
            throw new NotImplementedException();
        }
    }
}

-------And my user Class -------

   class UserControlledSprite : Sprite
    {
        SpriteEffects myEffect;

        public UserControlledSprite(Texture2D textureImage, Vector2 position,
            Point frameSize, int collisionOffset, Point currentFrame, Point sheetSize,
            Vector2 speed)
            : base(textureImage, position, frameSize, collisionOffset,
            currentFrame, sheetSize, speed)
        {
        }

        public UserControlledSprite(Texture2D textureImage, Vector2 position,
             Point frameSize, int collisionOffset, Point currentFrame, Point sheetSize,
             Vector2 speed, int millisecondsPerFrame)
            : base(textureImage, position, frameSize, collisionOffset,
            currentFrame, sheetSize, speed, millisecondsPerFrame)
        {
        }

        public override Vector2 direction
        {
            get
            {
                Vector2 inputDirection = Vector2.Zero;

                if (Keyboard.GetState().IsKeyDown(Keys.Left))
                {
                    inputDirection.X -= 1;

                }
                if (Keyboard.GetState().IsKeyDown(Keys.Right))
                {
                    inputDirection.X += 1;

                }
                if (Keyboard.GetState().IsKeyDown(Keys.Down))
                {
                    inputDirection.Y += 1;

                }
                if (Keyboard.GetState().IsKeyDown(Keys.Up))
                {
                    inputDirection.Y -= 1;

                }

                return inputDirection * speed;
            }
        }


        public override void Update(GameTime gameTime, Rectangle ClientBounds)
        {
            //Move the spite according to the direction property
            position += direction;

            //If the player is facing left, flip it horizontally
            if (direction.X < 0)
            {
                this.myEffect = SpriteEffects.FlipHorizontally;
            }

            //If The player is facing right, no effect
            if (direction.X > 0)
            {
                this.myEffect = SpriteEffects.None;
            }

            //If the player leaves bounds off the screen put it back in play
            if (position.X < 0)
            {
                position.X = 0;
            }

            if (position.Y < 0)
            {
                position.Y = 0;
            }

            if (position.X > ClientBounds.Width - (frameSize.X))
            {
                position.X = ClientBounds.Width - (frameSize.X );
            }

            if (position.Y > ClientBounds.Height - (frameSize.Y))
            {
                position.Y = ClientBounds.Height - (frameSize.Y);

            }

            base.Update(gameTime, ClientBounds);
        }

       public override void Draw(GameTime gameTime, SpriteBatch spriteBatch)
        {
            spriteBatch.Draw(textureImage, position,
              new Rectangle(currentFrame.X * frameSize.X, currentFrame.Y * frameSize.Y,
        frameSize.X, frameSize.Y), Color.White, 0, Vector2.Zero, 1, myEffect, 0);

        }
    }

 

I feel like I am cheating though. This isn't a school project or anything but all my professers tell me that Programmers need to learn to solve their own problems. But I think problem solving should involve other people, see as most of us want to work with other programmers. Anyway I am trying to build it such that my UserClass will be able to fire projectiles. So i Think the way I am going to model my ProjecticleSprite with a it's own draw(), and Update() and not inherit from the base class sprite. Thanks for your help everyone.




#5067100 Suggestions on what sould i do after second game "project"

Posted by mistervirtue on 03 June 2013 - 08:28 AM

I would suggest you just keep working on your RPG in your spare time. It should grow as your tools and skills do. The more you learn how to do the more you should add into your game.




#5066255 Drawing A 2D Texture Border

Posted by mistervirtue on 30 May 2013 - 04:18 PM

I actually just solved my own problem! I feel so good. My issue was I wasn't draw the testingRec in the SpriteManager. 




#5011815 A Few Words of Encouragement

Posted by mistervirtue on 17 December 2012 - 02:03 PM

I talked to my CIS professor a few days ago and she gave me a real nugget of wisdom I want to share with all of my fellow beginners here on gamedev. This is a quote from her e-mail she sent me.

"Programming is just like any other skill, if you want to be good at it you have to do it a lot. That being said you have to willing to be really bad it for awhile before you can see the fruits of you labor. Don't feel bad because you haven't made Baulder's Gate in one semester. Build upon small realistic goals. Just do the basics and gain a real understanding of the foundational skills. Work hard and work consistently and you will be great at whatever you want."

So I just want to say to everyone out there to keep trying and stay in good cheer, even when things get hard. Push through your obstacles and you will become the programmer you want to be. Keep working hard, you will be rewarded for it!


#4998499 --- Finished Breakout ---

Posted by mistervirtue on 07 November 2012 - 12:02 PM

Sure, Posting the source code wouldn't hurt.
Source Code HOOOOO!

Sprite Manager / Game Compentent
[source lang="csharp"]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 Jreakout_BreakOutClone_ { /// <summary> /// This is a game component that implements IUpdateable. /// </summary> public class SpriteManager : Microsoft.Xna.Framework.DrawableGameComponent { SpriteBatch spriteBatch; PlayerPaddle playerPaddle; Rectangle screenRectangle; Ball ball; //Columns and rows for brick int bricksWide = 10; int bricksHigh = 5; //Texture for the brick Texture2D brickImage; //Array for the placement for the bricks Brick[,] bricks; public SpriteManager(Game game) : base(game) { // TODO: Construct any child components here } protected override void LoadContent() { spriteBatch = new SpriteBatch(Game.GraphicsDevice); screenRectangle = new Rectangle(0, 0, Game.Window.ClientBounds.Width, Game.Window.ClientBounds.Height); Texture2D playerPaddleTexture = Game.Content.Load<Texture2D>("paddle"); playerPaddle = new PlayerPaddle(playerPaddleTexture, screenRectangle); Texture2D ballTexture = Game.Content.Load<Texture2D>("ball"); ball = new Ball(ballTexture, screenRectangle); brickImage = Game.Content.Load<Texture2D>("brick"); StartGame(); base.LoadContent(); } /// <summary> /// Allows the game component to perform any initialization it needs to before starting /// to run. This is where it can query for any required services and load content. /// </summary> public override void Initialize() { // TODO: Add your initialization code here base.Initialize(); } /// <summary> /// Allows the game component to update itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> public override void Update(GameTime gameTime) { playerPaddle.Update(); ball.Update(); //Check For Collisions ball.CheckForWallCollision(); ball.CheckForPlayerCollision(playerPaddle.GetBounds()); foreach (Brick brick in bricks) { brick.CheckCollision(ball); } if (ball.CheckForBottom()) { StartGame(); } base.Update(gameTime); } public override void Draw(GameTime gameTime) { spriteBatch.Begin(); foreach (Brick brick in bricks) { brick.Draw(spriteBatch); } ball.Draw(spriteBatch); playerPaddle.Draw(spriteBatch); spriteBatch.End(); base.Draw(gameTime); } public void StartGame() { playerPaddle.SetInStartPosition(); ball.SetInStartPosition(); //When the game starts Place the bricks //Layer them by color //Create an array to hold the bricks bricks = new Brick[bricksWide, bricksHigh]; //Loop thr for (int y = 0; y < bricksHigh; y++) { Color tint = Color.White; switch (y) { case 0: tint = Color.Blue; break; case 1: tint = Color.Red; break; case 2: tint = Color.Green; break; case 3: tint = Color.Yellow; break; case 4: tint = Color.Purple; break; } for (int x = 0; x < bricksWide; x++) { bricks[x, y] = new Brick( brickImage, new Rectangle( x * brickImage.Width, y * brickImage.Height, brickImage.Width, brickImage.Height), tint); } } } } }[/source]
Brick Class
[source lang="csharp"]using System;using System.Collections.Generic;using System.Linq;using System.Text;using Microsoft.Xna.Framework;using Microsoft.Xna.Framework.Input;using Microsoft.Xna.Framework.Graphics;using Microsoft.Xna.Framework.Media;namespace Jreakout_BreakOutClone_ { class Brick { //Holds the texture for the brick Texture2D texture; //Holds the position of the brick Vector2 position; //Holds the location of the brick Rectangle location; //Allows to change the color of the bricks Color tint; //A boolean value to see if the brick is alive or not. bool alive; public Rectangle Location { get { return location; } } //Constructor for the brick class public Brick(Texture2D texture, Rectangle location, Color tint) { this.texture = texture; this.location = location; this.tint = tint; this.alive = true; } //Check to see if anything has collided with the brick public void CheckCollision(Ball ball) { if (alive && ball.Bounds.Intersects(location)) { alive = false; ball.Deflection(this); } } public void Draw(SpriteBatch spriteBatch) { if (alive) { spriteBatch.Draw(texture,location,tint); } } } }[/source]
Ball Class
[source lang="csharp"]using System;using System.Collections.Generic;using System.Linq;using System.Text;using Microsoft.Xna.Framework;using Microsoft.Xna.Framework.Input;using Microsoft.Xna.Framework.Graphics;using Microsoft.Xna.Framework.Media;namespace Jreakout_BreakOutClone_ { class Ball { //Holds for the direction the ball is travelling Vector2 motion; //Holds for the the current position of the ball Vector2 position; //Holds for the speed of the ball float ballSpeed = 5; //Holds for the texture Image of ball; Texture2D texture; //Holds for the bounds of the screen Rectangle screenBounds; //Rectangle Bounds Rectangle bounds; public Rectangle Bounds { get { bounds.X = (int)position.X; bounds.Y = (int)position.Y; return bounds; } } //Consturtor for the ball class //This allows for the creation of instances of ball. Pass texture and screenbounds as parameters public Ball(Texture2D texture, Rectangle screenBounds) { this.texture = texture; this.screenBounds = screenBounds; } //Upate for the ball class //Check for Ccollisions with the wall and the player public void Update() { position += motion * ballSpeed; CheckForWallCollision(); } //Check to see if the ball is hitting the window bounds on the left and right and top //Reverse it's direction upon collision public void CheckForWallCollision() { //Top of the Screen if (position.Y < 0) { position.Y = 0; motion.Y *= -1; } //Left Bound if (position.X < 0) { position.X = 0; motion.X *= -1; } //Right Bound if (position.X + texture.Width > screenBounds.Width) { position.X = screenBounds.Width - texture.Width; motion.X *= -1; } } //Check to see if the ball is hitting the player paddle //Reverese it's direction upon collision public void CheckForPlayerCollision(Rectangle paddleLocation) { Rectangle ballLocation = new Rectangle((int)position.X, (int)position.Y, texture.Width, texture.Height); if (paddleLocation.Intersects(ballLocation)) { position.Y = paddleLocation.Y - texture.Height; motion.Y = -1; } } //Check to see if the ball has gone of the bottom of the screen //If so return true public bool CheckForBottom() { if (position.Y + texture.Height > screenBounds.Height) { return true; } return false; } public void SetInStartPosition() { motion = new Vector2(-1,1); position.X = (screenBounds.Width - texture.Width) / 2; position.Y = (screenBounds.Height - texture.Height) / 2; } public void Draw(SpriteBatch spriteBatch) { spriteBatch.Draw(texture, position, Color.White); } public void Deflection(Brick brick) { motion.Y *= -1; } } }[/source]

Game1.cs

[source lang="csharp"]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 Jreakout_BreakOutClone_ { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; SpriteManager spriteManager; Rectangle screenRectangle; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; graphics.PreferredBackBufferHeight = 600 ; graphics.PreferredBackBufferWidth = 750; screenRectangle = new Rectangle(0, 0, graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight); } /// <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() { //Instantiate the spriteManager spriteManager = new SpriteManager(this); Components.Add(spriteManager); 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); // TODO: use this.Content to load your game content here } /// <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> protected override void Update(GameTime gameTime) { // Allows the game to exit if(Keyboard.GetState().IsKeyDown(Keys.Escape)) { this.Exit(); } // TODO: Add your update logic here 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 base.Draw(gameTime); } } }[/source]

PlayerPaddle Class
[source lang="csharp"]using System;using System.Collections.Generic;using System.Linq;using System.Text;using Microsoft.Xna.Framework;using Microsoft.Xna.Framework.Input;using Microsoft.Xna.Framework.Graphics;using Microsoft.Xna.Framework.Media;namespace Jreakout_BreakOutClone_ { class PlayerPaddle { //Variable Declaration// //Holds the Position of the PlayerPaddle Vector2 position; //Holds the Direction the PlayerPaddle is move Vector2 direction; //Holds the speed of the player paddle float paddleSpeed =8; //Holds the texture Image for the ball Texture2D texture; //Allow for player Input KeyboardState keyboardState; //Holds the Rectangle for the GameWindow Rectangle screenBounds; //End of Variable Declaration// //Consturctor for the PlayerPaddle // Used to create an instance of PlayerPaddle (Pass texture,screenbounds as parameters) public PlayerPaddle(Texture2D texture, Rectangle screenBounds) { this.texture = texture; this.screenBounds = screenBounds; } //Update for Paddle //Use Keyboard to allow for Movment only in the X direction public void Update() { direction = Vector2.Zero; keyboardState = Keyboard.GetState(); if(keyboardState.IsKeyDown(Keys.Left)) { direction.X = -1; } if (keyboardState.IsKeyDown(Keys.Right)) { direction.X = 1; } direction.X *= paddleSpeed; position += direction; CheckScreenBounds(); } //Draw for Paddle //Draw the Paddle Yellow public void Draw(SpriteBatch spriteBatch) { spriteBatch.Draw(texture, position, Color.Purple); } //CheckScreenBounds for PlayerPaddle //Do not Allow the Paddle to leave the clientBounds public void CheckScreenBounds() { if (position.X < 0) { position.X = 0; } if (position.X + texture.Width > screenBounds.Width) { position.X = screenBounds.Width - texture.Width; } } //GetBounds for PlayerPaddle //Create A Rectangle around the texture image of playerPaddle public Rectangle GetBounds() { return new Rectangle ((int)position.X, (int)position.Y, texture.Width, texture.Height); } public void SetInStartPosition() { position.X = (screenBounds.Width - texture.Width) / 2; position.Y = screenBounds.Height - texture.Height - 5; } } }[/source]

There you go.


#4998239 --- Finished Breakout ---

Posted by mistervirtue on 06 November 2012 - 05:09 PM

I finsihed my breakout project. I feel like things are coming together, my next step is going to snake. I feel like am making some right moves, I am really starting like programming.

MisterVirtue's Breakout Game

Tell me what you think.


#4994264 Finished Pong - What I Learned

Posted by mistervirtue on 26 October 2012 - 03:21 PM

So I finished PONG for the most part and I am super happy. Their are still a few polish things I need to add, but the basic structure for the game is done. I plan on randomize the ball start and adding a score tonight after work. I really happy i 'finished' this though. I have really learned a lot and I want to share it with someone. I hope this helps someone else.

--------
A link to the game using dropbox
MisterVirtue's Pong Clone
-------

- You can do it -

I have very little programming experience outside the classroom, I have never tried to make a game before but I learned if you really want to do something you can make it happen.

- Ask Questions, Gain Knowledge -

Gamedev.net is a great reasource with lots of friendly people who want to help you. People here are really nice and quickly come to your rescue, but people can't help you if you don't ask. Don't be afraid to ask questions, you have nothing to lose and you often more than just the knowledge you seek.

-Dig around, there is treasure everywhere -

Use the net to your advantage, there are plenty of resources to help a beginner. I used this sites and many other with code help, logic help, and other general support.

- You Can't Play Games and Make Games at The Same Time -

I learned the less time i spent playing games, the better i got at staying focused on my project. I love games and it's hard to put them down sometimes but if your project is important, you have to make sacrifices.

- Start Today -
Don't be lazy, or you will get nothing done. Try to start doing a little bit each day on your project you can ride that momentum to get more done.

I hope this helps someone else who is looking to get started. Like I said before I plan on give my Pong Clone the polish it needs tonight. After that my next plan is to start working on a break out clone. I really like programming, and I feel like i am having a good start.


#4984825 Code Help - My First Roadblock

Posted by mistervirtue on 28 September 2012 - 01:10 PM

ALL RIGHT! WE ARE BACK IN ACTION Gamedev'ers! Thanks for all your help! It totally worked. I had never seen some like Haps stuff. But I get my research on and get better! LET'S DO THIS!


#4984815 Code Help - My First Roadblock

Posted by mistervirtue on 28 September 2012 - 12:35 PM

Well I haven't really changed my drawing code it's still the same. That is my problem I don't know how to pass myFlip in to my draw
[source lang="csharp"] public void Draw(SpriteBatch spriteBatch) { spriteBatch.Draw(texture, position, Color.White); }[/source]


#4984172 What Is My Next Move

Posted by mistervirtue on 26 September 2012 - 06:07 PM

Thanks for all of the positive advice and direction everyone. I am going to take my level 3 programmer gear and go quest and see what i can do. Hopefully I will return as a strong better programmer with shinier gear.


#4984048 What Is My Next Move

Posted by mistervirtue on 26 September 2012 - 12:18 PM

You know what Arthur Sourza, I think I will. I will try and expolre and see what I can do. Thanks for the help.


#4984017 What Is My Next Move

Posted by mistervirtue on 26 September 2012 - 10:56 AM

So I just finished a DIY XNA (Learning XNA 3.0 by Aaron Reed) book and I don't know what to do next. I feel like still need training wheels as far a logic and programming goes. I have a set aside enough time everyday to practice and get better, just don't know exactly what to do for practice and getting better. I am CS college student, but my classes haven't really gone in to any real programming yet. I try to read as much as i can here on gamedev, a lot of it i don't understand but I read it anyway. I know a still only a low level programmer but I have a desire to get better. Should I get another book or just do more online tutorials? I don't know where to go or what to do. I feel like a level 3 programmer who just left the starter area but I don't quite know where i should quest next. Any advice would be most helpful.


PARTNERS