XNA / C# random

Started by
7 comments, last by Chipmonk 14 years ago
Hi I've recently started to touch shallow grounds on XNA game development along with the awesome language C#, and have an ongoing project with a simple simple game. There are basically a lot of blocks that bounce on the screen and your goal is to avoid them with the cursor. Yes, sounds boring, simple and unoriginal but I don't have any better ideas. I want to ask a whole lot of questions, but I'll start with my main problem. I have assigned an array placeholding each burokku-sans that are basically the enemy objects that are bouncing like madmen because they're pissed. They have their own position, x and y speed along with a random value that generates each time they hit the wall. What it won't do is exactly that, assign a unique different number, so the sprites will hold the same position all the time so the 30 burokkus look like they have merged to one. How do I make it so they go different directions using my idea or maybe another. My second problem which is not so important right now are ideas. I've got into programming several times and am genuinley passionate about it, but I always get stuck up with null ideas in my head. How do everyone actually come up with them? I am starting to seriously wonder if it's my brain that severly lacks imagination. Thanks
Advertisement
Is this a 2D game? I assume it is. To make them go into different directions you need to actually modify the x,y positions every frame based on the direction you want the object to go. So, in addition to you x,y position you also have a vx and vy (velocity-x and velocity y). That gets added to x,y every frame.

Ex: if you want them to go up, add -1 from y each frame (assuming y-negative is "up"). If you want to go left and down, add -1 from x, and add +1 to y:

x = x + vx;
y = y + vy;

Every time you hit a wall, just provide new values for vx and vy.

Now, in terms of ideas, I had the same problem a long time ago. Couldn't think of cool concepts if my life depended on it. The way I got to getting ideas *all the damn time* is by forcing myself to come up with a random idea by using *anything* as a starting point. For example, right now, there's a tree growing outside my window. If someone told me I had to make a game, any game, out of that particular tree, what would I do? Well, I see branches, and they all grow upward. Maybe I can make a game where the player has to help the tree grow by making creating new branches. Maybe there are obstacles to avoid, so you have to grow around like, a fence or something. Maybe the tree-trimmer comes around every so often and you need to make sure you can fend him off. Perhaps you can grow fruit and use that to make new trees? Or attract life into the tree? Maybe I forget about the tree, and just use the branching idea and make a tunneling (branching tunnels, perhaps?) game, with earthworms. Goal is to tunnel around and find things to eat, but avoid a roaming mole. And so it goes. That's just from looking at a single friggin' tree growing outside my window :)

The trick, though, is they don't have to be good ideas or even feasible ideas. You just get yourself into the habit of looking at random things and getting ideas. Pretty soon you'll have a new problem: How to STOP coming up with ideas, because you won't be able to help it and you'll start annoying your friends with things like: "Ooh, your weird handwriting gave me a great idea for a game! What if you had to..."
Are you having trouble with the random generator? Or with how to use the random?

theTroll
Hey guys thanks for the reply.

I have already figured the theory (with some help from a template) about making them go different directions, but let me declare myself more accurately. Yes, actually I am having problems with the random number generator, or it is my method that isn't working like it should. Got any idea what I could do to make them change direction more noticably? It may be more like me doing something wrong than the random number generator. Bah, me always laying the blame on something else.

Here's the code, it might give you a clearer idea on what I'm trying to achieve.

namespace WindowsGame1{    public class Game1 : Microsoft.Xna.Framework.Game    {        GraphicsDeviceManager graphics;        SpriteBatch spriteBatch;        Texture2D bg;        Rectangle frame;        Burokku[] burokku;        Random[] randX;        Random[] randY;        int blockMax = 30;        int blockCount = 0;        int[] x;        int[] y;        Vector2[] spriteSpeed;        Vector2 spritePosition = Vector2.Zero;        public Game1()        {                        graphics = new GraphicsDeviceManager(this);            Content.RootDirectory = "Content";        }        protected override void Initialize()        {            // TODO: Add your initialization logic here            graphics.PreferredBackBufferHeight = 500;            graphics.PreferredBackBufferWidth = 600;            graphics.ApplyChanges();            burokku = new Burokku[blockMax];            spriteSpeed = new Vector2[30];            randX = new Random[blockMax];            randY = new Random[blockMax];            x = new int[blockMax];            y = new int[blockMax];            for (int i = 0; i < burokku.Length; i++)            {                burokku = new Burokku();                spriteSpeed = new Vector2(50.0f, 50.0f);                x = 10;                y = 10;            }            base.Initialize();        }        protected override void LoadContent()        {            // Create a new SpriteBatch, which can be used to draw textures.            spriteBatch = new SpriteBatch(GraphicsDevice);            for (int i = 0; i < burokku.Length; i++) {                burokku.LoadContent(this.Content);            }            bg = Content.Load<Texture2D>("background");            frame = new Rectangle(0, 0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);            // TODO: use this.Content to load your game content here        }        protected override void UnloadContent()        {            // TODO: Unload any non ContentManager content here        }        protected override void Update(GameTime gameTime)        {            // Allows the game to exit            if (GamePad.GetState(PlayerIndex.One).Buttons.Back ==                ButtonState.Pressed)                this.Exit();            // Move the sprite around.            UpdateSprite(gameTime);            base.Update(gameTime);        }        void UpdateSprite(GameTime gameTime)        {            // Move the sprite by speed, scaled by elapsed time.            for (int i = 0; i < burokku.Length; i++)            {                randX = new Random();                randY = new Random();                x = randX.Next(1, 20);                y = randY.Next(1, 40);                int MaxX =                    graphics.GraphicsDevice.Viewport.Width - burokku.Get().Width;                int MinX = 0;                int MaxY =                    graphics.GraphicsDevice.Viewport.Height - burokku.Get().Height;                int MinY = 0;                burokku.pos.X = burokku.pos.X + x * spriteSpeed.X * (float)gameTime.ElapsedGameTime.TotalSeconds;                burokku.pos.Y = burokku.pos.Y + y * spriteSpeed.Y * (float)gameTime.ElapsedGameTime.TotalSeconds;                // Check for bounce.                if (burokku.pos.X > MaxX)                {                    x = randX.Next(3, 18);                    y = randY.Next(5, 14);                    spriteSpeed.X *= -1;                    burokku.pos.X = MaxX;                }                else if (burokku.pos.X < MinX)                {                    x = randX.Next(2, 14);                    y = randY.Next(6, 11);                    spriteSpeed.X *= -1;                    burokku.pos.X = MinX;                }                if (burokku.pos.Y > MaxY)                {                    x = randX.Next(9, 13);                    y = randY.Next(4, 14);                    spriteSpeed.Y *= -1;                    burokku.pos.Y = MaxY;                }                else if (burokku.pos.Y < MinY)                {                    x = randX.Next(3, 14);                    y = randY.Next(2, 20);                    spriteSpeed.Y *= -1;                    burokku.pos.Y = MinY;                }            }        }        {            graphics.GraphicsDevice.Clear(Color.CornflowerBlue);            // Draw the sprite.            spriteBatch.Begin(SpriteBlendMode.AlphaBlend);            spriteBatch.Draw(bg, frame, Color.White);            for (int i = 0; i < burokku.Length; i++ )                burokku.Draw(spriteBatch);            spriteBatch.End();                        base.Draw(gameTime);        }    }}


formatted it to shorten the wall of text down.

[Wasn't really formatted as it ought to be. Read the sticky. Grr. - Zahlman]

[Edited by - Zahlman on March 31, 2010 2:36:53 PM]
randX = new Random();randY = new Random();x = randX.Next(1, 20);y = randY.Next(1, 40);


I think this is your problem, or in particular, creating new Random objects inside the loop. I believe they are seeded by the current system time, and it looks like your code is executing fast enough for the seed to be the same for each enemy each frame.

A better idea is to create a single Random object- maybe it could be a member of the Game class, which will be seeded only once - possibly in the constructor, and get a random velocity for each enemy from this.
It's insane how many ideas gets flooded into your brain when looking at the world. Peeking out from the window, taking a walk, just laying on the bed and think void and whoa - pop pop pop. The question that comes afterwards is how to do it though, and many are too complex for me to make it. I think.

Anyways, double thanks to the last poster. I dunno why I never though of setting random values initally, I'm sometimes dumb like that and get overly compulsive about what I'm doing forgetting all logic. Thanks thanks.
The way that I deal with Random is a bit of a cheat but it works pretty well.

public class RandomGenerator
{
private Random random;

public static RandomGenerator
{
random = new Random();
}

}


Then put in static functions to do the random calls that you need.

The advantage is that you can access the random numbers no matter where you need them. It also makes sure you have one random generator so it seems like you get a better random spread (not really true, but it often seems that way). That static constructor makes sure that random is valid before your first static call.

theTroll

Quote:Original post by TheTroll
The way that I deal with Random is a bit of a cheat but it works pretty well.

public class RandomGenerator
{
private Random random;

public static RandomGenerator
{
random = new Random();
}

}


Then put in static functions to do the random calls that you need.


Wow, the library doesn't already offer this sort of static interface (in addition to the class)? :( This is one of the library design things that I've gotten accustomed to with Python...
Yeah, I figured the wall of text was still a wall of text, but sadly I was lazy enough to not try finding a "isnert code" button or the actual command. Well, sorry. I got the random thingy working now at least and finished my first serious game ever. First step accomplished.

Now for my next project.

This topic is closed to new replies.

Advertisement