Getting a nasty exception while trying to draw through a class in XNA.
Class
[CODE]namespace Dodge
{
class Background
{
private Texture2D BackA;
private Texture2D BackB;
private Texture2D BackC;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern uint MessageBox(IntPtr hWnd, String text, String caption, uint type);
public void LoadBackgroundContent(ContentManager theContentManager, string Assetnamea, string Assetnameb, string Assetnamec)
{
try
{
BackA = theContentManager.Load<Texture2D>(Assetnamea);
BackB = theContentManager.Load<Texture2D>(Assetnameb);
BackC = theContentManager.Load<Texture2D>(Assetnamec);
}
catch ( Exception ex )
{
MessageBox(new IntPtr(), Convert.ToString(ex), "aaaaa", 0);
}
}
public void DrawBackground(Vector2 BackAPos, Vector2 BackBPos, Vector2 BackCPos, Color Color,GraphicsDevice graphicsDevice)
{
try
{
SpriteBatch thespriteBatch = new SpriteBatch(graphicsDevice);
thespriteBatch.Draw(BackA, BackAPos, Color);
thespriteBatch.Draw(BackB, BackBPos, Color);
thespriteBatch.Draw(BackC, BackCPos, Color);
}
catch (Exception exa)
{
MessageBox(new IntPtr(), Convert.ToString(exa), "bbbbb", 0);
}
}
[/CODE]
How I'm calling the methods.
[CODE]
//Draw
BackgroundDraw.DrawBackground(new Vector2(0,0), new Vector2(50,0), new Vector2(100,0), Color.White,GraphicsDevice);
//Load
Backload.LoadBackgroundContent(this.Content,"backblue", "backyellow", "backgreen");[/CODE]
The exception
[CODE]DRAW : System.ArgumentNullException: This method does not accept null for this p
arameter.
Parameter name: texture
at Microsoft.Xna.Framework.Graphics.SpriteBatch.InternalDraw(Texture2D textur
e, Vector4& destination, Boolean scaleDestination, Nullable`1& sourceRectangle,
Color color, Single rotation, Vector2& origin, SpriteEffects effects, Single dep
th)
at Microsoft.Xna.Framework.Graphics.SpriteBatch.Draw(Texture2D texture, Vecto
r2 position, Color color)
at Dodge.Background.DrawBackground(Vector2 BackAPos, Vector2 BackBPos, Vector
2 BackCPos, Color Color, GraphicsDevice graphicsDevice) in C:\Users\Evan\Documen
ts\Visual Studio 2010\Projects\WindowsGame2\WindowsGame2\WindowsGame2\Background
.cs:line 47[/CODE]
Its probably something stupid, I'm still fairly new to both C# and XNA.
I haven't touched XNA in a while, but if I were you I'd start by trying to figure out which of the variables are null. The exception says one of the textures are null so it's either BackA, BackB or BackC. I would think it'd throw an exception if it failed to load which means maybe you're not calling LoadBackgroundContents in the right spot?
Another thing I noticed is [quote]SpriteBatch thespriteBatch = new SpriteBatch(graphicsDevice);[/quote]should have a thespriteBatch.Begin() after it, shouldn't it? Then a thespriteBatch.End() afterwards. I don't remember that much about how the sprite batches work but I remember having that problem in the past.
I can't tell if I am abusing lambdas or not
[csharp] public static readonly Dictionary<string, Func<HashAlgorithm>> HashTypes = new Dictionary<string, Func<HashAlgorithm>>
{
{"sha512", () => new SHA512Managed()},
{"sha256", () => new SHA256Managed()},
{"md5", () => new MD5Cng()},
{"sha512-xp", () => SHA512.Create()},
{"sha256-xp", () => SHA256.Create()},
{"md5-xp", () => MD5.Create()},
};[/csharp]
[QUOTE=jalb;31817929]I haven't touched XNA in a while, but if I were you I'd start by trying to figure out which of the variables are null. The exception says one of the textures are null so it's either BackA, BackB or BackC. I would think it'd throw an exception if it failed to load which means maybe you're not calling LoadBackgroundContents in the right spot?
Another thing I noticed is should have a thespriteBatch.Begin() after it, shouldn't it? Then a thespriteBatch.End() afterwards. I don't remember that much about how the sprite batches work but I remember having that problem in the past.[/QUOTE]
your right about begin and end but I have that in my game1 class befpre and after i call the method.
ill look into the textures.
Yeah easy fix, null textures.
Trying to get height map to work, but when I try and load the height maps function, I get this error;
[code]
Error 1 The name 'LoadHeightData' does not exist in the current context
C:\Users\smartass\Documents\Visual Studio 2010\Projects\WindowsGame1\WindowsGame1\WindowsGame1\Game1.cs
82 13 WindowsGame1[/code] This is my code;
[code]
Texture2D heightMap = Content.Load<Texture2D>("heightmap");
LoadHeightData(heightMap);
[/code]
[editline]19th August 2011[/editline]
Are there special code tags for C# code?
[QUOTE=Mr. Smartass;31818677]Trying to get height map to work, but when I try and load the height maps function, I get this error;
[code]
Error 1 The name 'LoadHeightData' does not exist in the current context
C:\Users\smartass\Documents\Visual Studio 2010\Projects\WindowsGame1\WindowsGame1\WindowsGame1\Game1.cs
82 13 WindowsGame1[/code] This is my code;
[code]
Texture2D heightMap = Content.Load<Texture2D>("heightmap");
LoadHeightData(heightMap);
[/code]
[editline]19th August 2011[/editline]
Are there special code tags for C# code?[/QUOTE]
Looks like the function LoadHeightData doesn't exist at all...?
Tags: [csharp] [/ csharp]
Quick Question.
Is there any quick way to tell if a bounding-box is intersecting nothing.
Example, this doesn't actually work just showing you what i mean :D
[Csharp]
if(PlayerSprite.BoundingBox.Intersects(false/null))
{
hitbool = true;
}
[/csharp]
Instead of having to check one bounding box with another, one at a time.
solved
[QUOTE=reevezy67;31822331]Quick Question.
Is there any quick way to tell if a bounding-box is intersecting nothing.
Example, this doesn't actually work just showing you what i mean :D
[Csharp]
if(PlayerSprite.BoundingBox.Intersects(false/null))
{
hitbool = true;
}
[/csharp]
Instead of having to check one bounding box with another, one at a time.[/QUOTE]
I'm pretty sure that you have to check with collision for every other box with the way that system is designed.
[QUOTE=thf;31822963]I'm pretty sure that you have to check with collision for every other box with the way that system is designed.[/QUOTE]
Ah ok, Its not a big problem. Won't take that much longer for what I'm doing
[QUOTE=Robbis_1;31819424]Looks like the function LoadHeightData doesn't exist at all...?
Tags: [csharp] [/ csharp][/QUOTE]
Thanks, I was following a tutorial, and I missed the part where they created that function, I feel retarded.
Does anyone know an equivalent to getch in c#? I'm trying to make a console based snake game and I want to be able to get the keypress checked "as soon as it happens".
How do I define a global in libtcod with python? It errors me out if I put: global new_floor.
-snippity-
Hey! I'm currently working on terrain generation from a bumpmap (based on a tutorial), and I ran into a roadblock. My current code is
[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 WindowsGame1
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
GraphicsDevice device;
VertexPositionColor[] vertices;
Effect effect;
Matrix viewMatrix;
Matrix projectionMatrix;
private float angle = 0f;
int[] indices;
private int terrainWidth = 4;
private int terrainHeight = 3;
private float[,] heightData;
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
/*graphics.PreferredBackBufferWidth = 500;
graphics.PreferredBackBufferHeight = 500;
* */
graphics.IsFullScreen = false;
graphics.ApplyChanges();
Window.Title = "THIS IS A MOTHERFUCKING WINDOW. IT WILL FUCK YOU UP.";
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);
device = graphics.GraphicsDevice;
//set up the vertices
SetUpVertices();
//load the shader
effect = Content.Load<Effect>("effects");
//load the camera
SetUpCamera();
//load the Index
SetUpIndices();
//load the height data
//load the height map for the terrain
Texture2D heightMap = Content.Load<Texture2D>("heightmap");
LoadHeightData(heightMap);
}
/// <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
}
private void SetUpVertices()
{
vertices = new VertexPositionColor[terrainWidth * terrainHeight];
for (int x = 0; x < terrainWidth; x++)
{
for (int y = 0; y < terrainHeight; y++)
{
vertices[x + y * terrainWidth].Position = new Vector3(x, heightData[x, y], -y);
vertices[x + y * terrainWidth].Color = Color.White;
}
}
}
private void SetUpIndices()
{
indices = new int[(terrainWidth - 1) * (terrainHeight - 1) * 6];
int counter = 0;
for (int y = 0; y < terrainHeight - 1; y++)
{
for (int x = 0; x < terrainWidth - 1; x++)
{
int lowerLeft = x + y * terrainWidth;
int lowerRight = (x + 1) + y * terrainWidth;
int topLeft = x + (y + 1) * terrainWidth;
int topRight = (x + 1) + (y + 1) * terrainWidth;
indices[counter++] = topLeft;
indices[counter++] = lowerRight;
indices[counter++] = lowerLeft;
indices[counter++] = topLeft;
indices[counter++] = topRight;
indices[counter++] = lowerRight;
}
}
}
private void LoadHeightData(Texture2D heightMap)
{
terrainWidth = heightMap.Width;
terrainHeight = heightMap.Height;
Color[] heightMapColors = new Color[terrainWidth * terrainHeight];
heightMap.GetData(heightMapColors);
heightData = new float[terrainWidth, terrainHeight];
for (int x = 0; x < terrainWidth; x++)
for (int y = 0; y < terrainHeight; y++)
heightData[x, y] = heightMapColors[x + y * terrainWidth].R / 5.0f;
}
private void SetUpCamera()
{
// define position, lens, and POV of the camera
viewMatrix = Matrix.CreateLookAt(new Vector3(60, 80, -80), new Vector3(0, 0, 0),
new Vector3(0, 1, 0));
// sets the FOV of the camera
projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,
device.Viewport.AspectRatio, 0.1f, 300.9f);
}
/// <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 (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
// I TOLD YOU ABOUT THOSE ROTATIONS. I TOLD YOU DOG.
angle += 0.005f;
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)
{
device.Clear(Color.MidnightBlue);
// declares the primitive
// sets the shader technique
// sets the view and projection matrices
// sets the world matrix
Matrix worldMatrix = Matrix.CreateTranslation(-terrainWidth / 2.0f, 0, terrainHeight / 2.0f);
effect.CurrentTechnique = effect.Techniques["ColoredNoShading"];
effect.Parameters["xView"].SetValue(viewMatrix);
effect.Parameters["xProjection"].SetValue(projectionMatrix);
effect.Parameters["xWorld"].SetValue(worldMatrix);
// removes back culling
RasterizerState rs = new RasterizerState();
rs.CullMode = CullMode.None;
rs.FillMode = FillMode.WireFrame;
device.RasterizerState = rs;
foreach (EffectPass pass in effect.CurrentTechnique.Passes)
{
pass.Apply();
device.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, vertices, 0, vertices.Length, indices, 0, indices.Length / 3, VertexPositionColor.VertexDeclaration);
}
base.Draw(gameTime);
}
}
}
[/csharp]
And the error returned is
[code]
System.NullReferenceException was unhandled
Message=Object reference not set to an instance of an object.
Source=WindowsGame1
StackTrace:
at WindowsGame1.Game1.SetUpVertices() in C:\Users\smartass\Documents\Visual Studio 2010\Projects\WindowsGame1\WindowsGame1\WindowsGame1\Game1.cs:line 100
at WindowsGame1.Game1.LoadContent() in C:\Users\smartass\Documents\Visual Studio 2010\Projects\WindowsGame1\WindowsGame1\WindowsGame1\Game1.cs:line 71
at Microsoft.Xna.Framework.Game.Initialize()
at WindowsGame1.Game1.Initialize() in C:\Users\smartass\Documents\Visual Studio 2010\Projects\WindowsGame1\WindowsGame1\WindowsGame1\Game1.cs:line 57
at Microsoft.Xna.Framework.Game.RunGame(Boolean useBlockingRun)
at Microsoft.Xna.Framework.Game.Run()
at WindowsGame1.Program.Main(String[] args) in C:\Users\smartass\Documents\Visual Studio 2010\Projects\WindowsGame1\WindowsGame1\WindowsGame1\Program.cs:line 15
InnerException:
[/code]
Help is appreciated!
you call SetUpVertices() before LoadHeightData(), which causes the former to use heightData before it's initialized, i.e. it's still a null reference.
[QUOTE=FlashStock;31831986]Does anyone know an equivalent to getch in c#? I'm trying to make a console based snake game and I want to be able to get the keypress checked "as soon as it happens".[/QUOTE]
C++?
WM_KEYDOWN if you're on windows.
This always confused me.
I know how to get key input in XNA, but how would one go about waiting till a key was released before executing the code attached to that keys input.
[QUOTE=reevezy67;31839571]This always confused me.
I know how to get key input in XNA, but how would one go about waiting till a key was released before executing the code attached to that keys input.[/QUOTE]
Have a "keyprevious" variable set to the current key state each step before you update the keyboard state variable- If keyprevious was down and it is no longer the key has been released.
[QUOTE=chaz13;31839596]Have a "keyprevious" variable set to the current key state each step before you update the keyboard state variable- If keyprevious was down and it is no longer the key has been released.[/QUOTE]
Ah ok that's fairly simple. Thanks.
[QUOTE=reevezy67;31839604]Ah ok that's fairly simple. Thanks.[/QUOTE]
No worries, I encorporate it into a function to make it even easier. E.G
private bool KeyReleased(key){
if KeyIsDown(keyprevious.key) && !KeyIsDown(currentkey.Key)
return true;
else
return false;
}
Then you can just do
if KeyReleased(space)
//do stuff
(I know that code above is horrific and won't do anything, I can't remember the right syntax and functions but you get the gist).
[QUOTE=FlashStock;31831986]Does anyone know an equivalent to getch in c#? I'm trying to make a console based snake game and I want to be able to get the keypress checked "as soon as it happens".[/QUOTE]
[url=http://msdn.microsoft.com/en-us/library/471w8d85.aspx]Console.ReadKey[/url]
Im making a platformer game in XNA and i cant get the player jumping to work. When i press W, the character does not move up and down, just quickly move down when i press W.
[code]if (ks.IsKeyDown(Keys.W))
{
if (JumpOn == true)
{
JumpOn = false;
for (int i = 1; i < 200; i++)
{
Position.Y -= i / 10;
}
for (int i = 200; i > 1; i--)
{
Position.Y += i / 10;
}
JumpOn = true;
}
}[/code]
Please help!
[QUOTE=Funley;31840556]Im making a platformer game in XNA and i cant get the player jumping to work. When i press W, the character does not move up and down, just quickly move down when i press W.
[code]if (ks.IsKeyDown(Keys.W))
{
if (JumpOn == true)
{
JumpOn = false;
for (int i = 1; i < 200; i++)
{
Position.Y -= i / 10;
}
for (int i = 200; i > 1; i--)
{
Position.Y += i / 10;
}
JumpOn = true;
}
}[/code]
Please help![/QUOTE]
What are you trying to achieve there? From what I can see those for loops cancel each other out and are completely unneccesary...
[QUOTE=thf;31840594]What are you trying to achieve there? From what I can see those for loops cancel each other out and are completely unneccesary...[/QUOTE] I want the character to move up, coasting when closing on to the top, then moving down speeding up when closing to the end.
[QUOTE=Funley;31840660]I want the character to move up, coasting when closing on to the top, then moving down speeding up when closing to the end.[/QUOTE]
I'd then make a velocity vector and each frame add it to the position vector. Then for gravity I'd subtract something like (0, 5) from the velocity vector each frame too.
[QUOTE=thf;31840738]I'd then make a velocity vector and each frame add it to the position vector. Then for gravity I'd subtract something like (0, 5) from the velocity vector each frame too.[/QUOTE] Thanks, it works now :D
Clicking on another program while my XNA game is running causes it to crash :/
Any common causes to something like this or is it something I have to dig in my code for.
Also minimizing and maximizing it causes it to crash as well.
Edit
According to the exception, I have an integer in the wrong place somewhere..
Oh what fun this is going to be.
Stairs for a roguelike on python with libtcod, How do I make them?
Code if its needed... [url]http://pastebin.com/4mNaMc9V[/url]
Sorry, you need to Log In to post a reply to this thread.