• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
robertosaget

I am doing something really simple incorectly[xna]

4 posts in this topic

Hello, I am doing something really fundamentally wrong but i can not put my finger on it. Yes i know the code is a mess and it should be much better but i am at least trying to get the concept down. What i am trying to do is have a character move around the screen and shoot on a tiled back drop. I did this. The problem is i want enemies to spawn at a specific location(The 0 squares)(I used nick gravelyn's tutorial and i liked the colors of the squares so i used them) and it is not working. I am not sure how to get the enemies to draw and collide with the bullets on the zero square. What happens is nothing is drawn. It worked up until i added the nested for loop and it drew everything in the center. Now it does not even draw. What i want to accomplish is drawing the enemies on the zero squares and having them be able to collide and vanish from the screen. Here is my code. I put it in the brackets but i am afraid it might be too large. I thought the code sometimes scrolls if it gets to large(Like in the preview). Thanks for reading and any help you may be able to give Robertosaget

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;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace ShootingGamePart1
{
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Sprite character = new Sprite();
        Sprite[] bullet;
        Sprite pointer = new Sprite();
        int numberofbullets = 10;
        MouseState prevmouse;
        List<Texture2D> tileTextures = new List<Texture2D>();
        Vector2 cameraPosition = Vector2.Zero;
        float cameraSpeed = 5;
        Vector2 healthbarpos = Vector2.Zero;
        Rectangle healthrect;
        Texture2D healthbar;
        Texture2D health;
        int width;
        int points = 0;
        int numberofzombies = 20;
        Vector2 textpos;
        SpriteFont arial;
        Sprite[] zombies;
        int[,] level1 = new int[,]
		{
			{ 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, },
			{ 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,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 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, },
			{ 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, },
			{ 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, },
			{ 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, },
			{ 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, },
		};

        int tileWidth = 64;
        int tileHeight = 64;
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }
        protected override void Initialize()
        {
            bullet = new Sprite[numberofbullets];
            zombies = new Sprite[numberofzombies];
            character.Position = new Vector2(graphics.GraphicsDevice.Viewport.Width / 2, graphics.GraphicsDevice.Viewport.Height / 2);
            base.Initialize();
        }

       
        protected override void LoadContent()
        {
            

            int tileMapWidth = level1.GetLength(1);
            int tileMapHeight = level1.GetLength(0);
            spriteBatch = new SpriteBatch(GraphicsDevice);
            arial = Content.Load<SpriteFont>("Arial");
            textpos = new Vector2(graphics.GraphicsDevice.Viewport.Width/2, 100);
            
            character.Texture = Content.Load<Texture2D>("Character");
            health = Content.Load<Texture2D>("Health");
            healthbar = Content.Load<Texture2D>("Healthbar");
            width = health.Width;

            
            for (int i = 0; i < zombies.Length; i++)
            {
                zombies[i] = new Sprite();
                zombies[i].Texture = Content.Load<Texture2D>("enemy");
                
            }



            for (int i = 0; i < bullet.Length; i++)
            {
                bullet[i] = new Sprite();
                bullet[i].Texture = Content.Load<Texture2D>("Bullet");
               
            }
            pointer.Texture  = Content.Load<Texture2D>("Pointer");
            character.Origin.X = character.Texture.Width / 2;
            character.Origin.Y = character.Texture.Height  / 2;
            for (int i = 0; i < bullet.Length; i++)
            {
                bullet[i].Position.X  = character.Position.X - 40;
                bullet[i].Position.Y  = character.Position.Y  - 40;
            }
            Texture2D texture;

            texture = Content.Load<Texture2D>("Tiles/se_free_dirt_texture");
            tileTextures.Add(texture);

            texture = Content.Load<Texture2D>("Tiles/se_free_grass_texture");
            tileTextures.Add(texture);

            texture = Content.Load<Texture2D>("Tiles/se_free_ground_texture");
            tileTextures.Add(texture);

            texture = Content.Load<Texture2D>("Tiles/se_free_mud_texture");
            tileTextures.Add(texture);

            texture = Content.Load<Texture2D>("Tiles/se_free_road_texture");
            tileTextures.Add(texture);

            texture = Content.Load<Texture2D>("Tiles/se_free_rock_texture");
            tileTextures.Add(texture);

            texture = Content.Load<Texture2D>("Tiles/se_free_wood_texture");
            tileTextures.Add(texture);
          
        }

        protected override void UnloadContent()
        {
        }

        protected override void Update(GameTime gameTime)
        {
            int tileMapWidth = level1.GetLength(1);
            int tileMapHeight = level1.GetLength(0);
            Vector2 motion = Vector2.Zero;
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();
            KeyboardState myboard = Keyboard.GetState();
            MouseState mymouse = Mouse.GetState();
            pointer.Position.X = mymouse.X;
            pointer.Position.Y = mymouse.Y;

            float xs = mymouse.X - character.Position.X;
            float ys = mymouse.Y - character.Position.Y;
            
            character.Rotation = (float)Math.Atan2(ys,xs);
           Rectangle  viewportRect = new Rectangle(0, 0,
                graphics.GraphicsDevice.Viewport.Width,
                graphics.GraphicsDevice.Viewport.Height);

            if (myboard.IsKeyDown(Keys.W))
            {
                motion.Y--;
            }


            if (myboard.IsKeyDown(Keys.S))
            {
                motion.Y++;
            }

            if (myboard.IsKeyDown(Keys.A))
            {
                motion.X--;
            }

            if (myboard.IsKeyDown(Keys.D))
            {
                motion.X++;
            }
            if (motion != Vector2.Zero)
            {
                motion.Normalize();
                cameraPosition += motion * cameraSpeed;
            }
            
            foreach (Sprite guy in zombies)
            {
                foreach (Sprite ball in bullet)
                {
                   ball.enemyrect = new Rectangle((int)ball.Position.X, (int)ball.Position.Y, ball.Texture.Width, ball.Texture.Height);
                   guy.enemyrect = new Rectangle((int)guy.Position.X, (int)guy.Position.Y, guy.Texture.Width, guy.Texture.Height);
                    if (ball.enemyrect.Intersects(guy.enemyrect))
                    {

                        guy.alive = false;
                    }
                }
            }
            
            for (int x = 0; x < tileMapWidth; x++)
            {
                for (int y = 0; y < tileMapHeight; y++)
                {
                    int textureIndex = level1[y, x];
                 
                    foreach(Sprite guy in zombies)
                    {
                        if (textureIndex == 0)
                        {

                            guy.Position.X = x * tileWidth - (int)cameraPosition.X;
                            guy.Position.Y = y * tileHeight - (int)cameraPosition.Y;
                        }
                    }
                         
                }
            }
      
            foreach (Sprite ball in bullet)
            {
                if (ball.isalive)
                {
                    ball.Position += ball.velocity;
                    if (!viewportRect.Contains(new Point(
                        (int)ball.Position.X,
                        (int)ball.Position.Y)))
                    {
                        ball.isalive = false;
                        continue;
                    }
                }
            }
            if (mymouse.LeftButton == ButtonState.Pressed && prevmouse.LeftButton == ButtonState.Released)
            {
                fire();
            }

          
            prevmouse = mymouse;
            base.Update(gameTime);
        }
        public void fire()
        {
            foreach (Sprite ball in bullet)
            {
                if (!ball.isalive)
                {
                    ball.isalive = true;
                    ball.Position = character.Position;
                    ball.velocity = new Vector2(
                        (float)Math.Cos(character.Rotation),
                        (float)Math.Sin(character.Rotation)) * 5.0f;
                    
                    return;
                }
            }
        }

        
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Red);
            int tileMapWidth = level1.GetLength(1);
            int tileMapHeight = level1.GetLength(0);
            healthrect = new Rectangle((int)healthbarpos.X, (int)healthbarpos.Y, width, health.Height);               

           spriteBatch.Begin();
            for (int x = 0; x < tileMapWidth; x++)
            {
                for (int y = 0; y < tileMapHeight; y++)
                {
                    int textureIndex = level1[y, x];
                    Texture2D texture = tileTextures[textureIndex];



                    spriteBatch.Draw(
                        texture,
                        new Rectangle(
                            x * tileWidth - (int)cameraPosition.X,
                            y * tileHeight - (int)cameraPosition.Y,
                            tileWidth,
                            tileHeight),
                        Color.White);
                }
            }
            foreach (Sprite guy in zombies)
            {

             
                if (guy.alive)
                {

                    guy.Draw(spriteBatch);
                }
            }
            foreach (Sprite ball in bullet )
            {
                if (ball.isalive)
                {
                    ball.Draw(spriteBatch);
                }
            }
            
            character.Draw(spriteBatch);
            spriteBatch.Draw(healthbar, healthbarpos, Color.White);
            spriteBatch.Draw(health, healthbarpos,healthrect, Color.White);
            spriteBatch.DrawString(arial, "Zombie # " + numberofzombies, textpos, Color.White);
            spriteBatch.DrawString(arial, "points " + points, new Vector2(textpos.X,textpos.Y+ 50), Color.White);
            pointer.Draw(spriteBatch);
            spriteBatch.End();
            base.Draw(gameTime);
        }
    }
}






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;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace ShootingGamePart1
{
    class Sprite
    {
        public Texture2D Texture;
        public Vector2 Position = Vector2.Zero;
        public Rectangle? SourceRect = null;
        public Color Color = Color.White;
        public float Rotation = 0f;
        public Vector2 Origin = Vector2.Zero;
        public float Scale = 1f;
        public SpriteEffects Effects = SpriteEffects.None;
        public float LayerDepth = 0;
        public bool isalive = false ;
        public Vector2 velocity = Vector2.Zero;
        public Rectangle enemyrect;
        public bool alive = true;
        public void Draw(SpriteBatch spriteBatch)
        {
            if (Texture == null)
                return;

            spriteBatch.Draw(
                Texture,
                Position,
                SourceRect,
                Color,
                Rotation,
                Origin,
                Scale,
                Effects,
                LayerDepth);
        }

    }
}


0

Share this post


Link to post
Share on other sites
Ok, well I have just downloaded and compiled you code to see the problem.

All of your Zombies are being drawn on the same sq (1024 * 768) go down to the very bottom corner of the map and you'll see it. you are not Updating it anywhere so it will not move.

However a bullet collision works for :)

also, i think this is a very inefficiently loop:
you are going through each zombie in the list on EVERY tile and not doing anything. Swap the foreach() and if() statements

for (int x = 0; x < tileMapWidth; x++)
{
for (int y = 0; y < tileMapHeight; y++)
{
int textureIndex = level1[y, x];

if (textureIndex == 0)
{
foreach(Sprite guy in zombies)
{
guy.Position.X = x * tileWidth - (int)cameraPosition.X;
guy.Position.Y = y * tileHeight - (int)cameraPosition.Y;
}
}

}
}




if you want the all to randomly spawn on a 0 indexed tile, I recommend a spawn control when you Load()

e.g.

public void SpawnEnamies()
{
/* Get a List<Vector2> of all the positions of tiles which have a 0 index
*
*
* randomly generate a number with Random r = new Random()
* r.Next(VectorList.Count);
*
* Spawn a zombie at this Point and set a velocity
*
*/

}
protected override void LoadContent()
{
..........
//Setting up Sprite[]'s
// SpawnEnamies()
..........
}




The bullet collision is working fine as far as I can see;)
0

Share this post


Link to post
Share on other sites
Hello again,
Thanks for the advice on the useless loop i put in. I feel so stupid but for some reason i can not wrap my brain around spawning the enemies at random locations for the life of me. I decided to make it truly random and use Random rand = new Random(). But i am having a problem. This is my naivete but they still all spawn at the same location. I know i am doing something really wrong but still my brain is not kicking in. I do not want to make excuses for myself but this is getting very frustrating. Here is the code

foreach (Sprite guy in zombies)
{
Vector2 temppos;
float temp;
Random rand = new Random();
temp = (float)rand.NextDouble();
temppos.X = temp * 1000;
temp = (float)rand.NextDouble();
temppos.Y = temp * 1000;


guy.Position = temppos;

}

This is what i want it to do.
Generate a random number. Multiply it by 1000 (to get a range from 0 to 1000)and have that as the x position. Do the same for the y. At that point make this the new zombies position. What is happening is they are all spawning at the same location. Is it random is generating the same random number? Am i using the foreach loop wrong? What should i do? Can you post an example of the correct way. The only thing that has changed is the loop is removed and the following code was put int the load method.

Thanks
0

Share this post


Link to post
Share on other sites
2 things:

1/ Very very close there, Rand.NextDouble() Selects a random double from 0.0 to 1.0 this mean you'd be seeting the position at (0,0) all the time. Use

tempPos.X = rand.Next(MAXWIDTH);
temppos.Y = rand.NExt(MAXHEIGHT);

This picks a random INTEGER between 0 and your maxWIDTH/HEIGHT

2/ In your Update method:

//for (int x = 0; x < tileMapWidth; x++)
//{
// for (int y = 0; y < tileMapHeight; y++)
// {
// int textureIndex = level1[y, x];
// if (textureIndex == 0)
// {
// foreach (Sprite guy in zombies)
// {
// guy.Position.X = x * tileWidth - (int)cameraPosition.X;
// guy.Position.Y = y * tileHeight - (int)cameraPosition.Y;
// }
// }
// }
//}




This is not Helping your cause
At the end of the update method you where setting the position of ALL the Zombies at a tile which had a Zero Index, this is why the zombies always draw where they did, coincidently that was the last tile on your map with the Index '0'.
Remove this loop and you will see them Drawn at the correct locations :)



EDIT :
There is one Problem with the code at the moment, all the Zombies are drawn correctly however they move when the camera is moved, make the Zombies stay in the same place (draw them and subtract the camera Offsets) if you want to see them :)
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0