mattwood2855

Members
  • Content count

    13
  • Joined

  • Last visited

Community Reputation

114 Neutral

About mattwood2855

  • Rank
    Member
  1. Unfortunately reflection isn't an option. While the console is for debugging purposes on the PC, my game will be incorporating scripts that need access to the same functions and variables for things like AI and game logic. Reflection isn't supported on the XBox. My solution in the end was just to turn the Variable Tracker into an object that calls a get function on every iteration of update. I was just hoping there was some way to reference the Vector without having to make a wrapper class. Thanks though guys
  2. I see what you're saying. While that would work I dont want to have to hardcode in a reference for every new object type i make in my game, it defeats the purpose of having the console/VM. I want to be able to create a widget to watch any variable and pass it at runtime.... thanks for the help ill have to think of a different solution though methinks
  3. Thanks for the links, my C# is pretty good though. Ive been porting my engine from OpenGL to C# and XNA. And lemme say, C# and XNA = half the lines of code to get the same stuff done. However I think i'm not describing my problem properly. My virtual machine can be passed any set of variables as a parameter. The problem is that they're not being referenced. and i think the problem is here: Object[][] args2 = new object[1][] { new object[2] { camera.Position, camera.Target.Position } }; i have to pass the arguements as an array of objects. How would I create this array with the reference to the camera's position? Object[][] args2 = new object[1][] { new object[2] { ref camera.Position, ref camera.Target.Position } }; <----doesnt work. Whats happening is the position isnt updating to match the true position of the camera. Its staying at whatever the position is at the time of creating the widget....
  4. So I have a new question haha I have a function that returns the angle between two objects. It takes two arguments position1 and position2. In my VM i have registered the function GET_ANGLE_BETWEEN with 2 vector3's as parameters. In my HUD class I made a widget in my game, called a Variable Tracker. It displays results returned from a function registered in the VM. My problem specifically is that I register the Variable Tracker with the camera's position and the camera's target position in the beginning of the game. however as the camera moves and targets move the values that are passed to the function aren't changing. In c# aren't all variables passed by reference? In my c++ engine I would pass pointers of the camera position, but I thought c# automatically passes a reference??? Heres the VariableTracker: [CODE] using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace AnoeTech { class HUDVarWatcher : HUDObject { private float _fontSize; private string[] _VMCommands; private object[][] _args; public override void Destroy() { throw new NotImplementedException(); } public override void Draw() { _engine.spriteBatch.Draw(_bgTexture, new Rectangle((int)_position.X, (int)_position.Y, (int)_size.X, (int)_size.Y), new Color(255,255,255, 100)); for (int x = 0; x < _VMCommands.Length; x++) { if(_args != null) _engine.spriteBatch.DrawString(_engine.font, _engine.virtualMachine.Execute(_VMCommands[x], _args[x]).ToString(), _position, Color.White, 0, new Vector2(0, 0), _fontSize, SpriteEffects.None, 0.5f); else _engine.spriteBatch.DrawString(_engine.font, _engine.virtualMachine.Execute(_VMCommands[x], null).ToString(), _position, Color.White, 0, new Vector2(0, 0), _fontSize, SpriteEffects.None, 0.5f); } } public override void Initiate(Game1 engine, Vector2 position, Vector2 size) { _engine = engine; _position = position; _size = size; _bgTexture = engine.Content.Load<Texture2D>("HUD/hudPanelGeneric"); } public void LockToVariable(string[] VMCommands, object[][] args, float fontSize) { _args = args; _VMCommands = VMCommands; _fontSize = fontSize; } public override void Update() { if (_transitioningIn) TransitionIn(); if (_transitioningOut) TransitionOut(); } } } [/CODE] and the creation of the object in my main file: [CODE] /// Angle tracker widget HUDVarWatcher tester2 = new HUDVarWatcher(); tester2.Initiate(this, new Vector2(100, 200), new Vector2(75, 25)); String[] str2 = new String[1]; str2[0] = "GET_ANGLE_BETWEEN"; Object[][] args = new object[1][]{ new object[2] {camera.position, camera.Target.position}}; tester2.LockToVariable(str2, args, 0.7f); hud.Add(tester2); [/CODE] When the HUD is updated it executes the command used by the VarWatcher - GET_ANGLE_BETWEEN - but the values arent changing... Any suggestions on how i can make sure the widget is always displaying the current angle between the two?
  5. A few things: - Namely just knowledge. I'm interested in knowing how to create and implement my own solutions into my software so that i understand how it works. Its how I learn, I cant afford school so I geek out. Just me and my IDE. - The other problem is that Lua can be used in XNA and C# through LuaInterace, but its unmanaged code, so cannot be executed on the Xbox360 (which is a requirement for my game). Do you know of a library that would work?
  6. Spaceship Movement

    Quaternions are best for flight motion since they allow you to travel upside down without having to keep track of your angles as much [CODE] void IMovable::accelerateForward( float scaleFactor ) { float Matrix[16]; Quaternion q; calculateQuats(); // calculates Quaternions from our heading and pitch into _qHeading and _qPitch q = _qPitch * _qHeading; // Combine the 2 vectors and rotations - Order specific multiplication! q.CreateMatrix(Matrix); // Store our new vector and its rotation glMultMatrixf(Matrix); // This is the same as glRotatef _qPitch.CreateMatrix(Matrix); // Load this new Matrix into _qPitch _localVelocity.y += Matrix[9] * _acceleration * scaleFactor; // Location [9] will always contain our Y movemet q = _qHeading * _qPitch; // Combine the Quarts again to get our X and Z vectors q.CreateMatrix(Matrix); // Store our new vector and its rotation _localVelocity.x += Matrix[8] * _acceleration * scaleFactor; // Location [8] will always contain our X movemet _localVelocity.z += -Matrix[10] * _acceleration * scaleFactor; // Location [10] will always contain our Z movemet (negate Z in OpenGL) } void IMovable::calculateQuats() { _qPitch.CreateFromAxisAngle(1.0f, 0.0f, 0.0f, _pitch); _qHeading.CreateFromAxisAngle(0.0f, 1.0f, 0.0f, _heading); } [/CODE] And in your quaternion class: [CODE] void Quaternion::CreateFromAxisAngle(float x, float y, float z, float degrees) { // First we want to convert the degrees to radians // since the angle is assumed to be in radians float angle = degreesToRadians(degrees); // Here we calculate the sin( theta / 2) once for optimization float result = (float)sin( angle / 2.0f ); // Calcualte the w value by cos( theta / 2 ) _w = (float)cos( angle / 2.0f ); // Calculate the x, y and z of the quaternion _x = float(x * result); _y = float(y * result); _z = float(z * result); } void Quaternion::CreateMatrix(float *pMatrix) { // Make sure the matrix has allocated memory to store the rotation data if(!pMatrix) return; // First row pMatrix[ 0] = 1.0f - 2.0f * ( _y * _y + _z * _z ); pMatrix[ 1] = 2.0f * (_x * _y + _z * _w); pMatrix[ 2] = 2.0f * (_x * _z - _y * _w); pMatrix[ 3] = 0.0f; // Second row pMatrix[ 4] = 2.0f * ( _x * _y - _z * _w ); pMatrix[ 5] = 1.0f - 2.0f * ( _x * _x + _z * _z ); pMatrix[ 6] = 2.0f * (_z * _y + _x * _w ); pMatrix[ 7] = 0.0f; // Third row pMatrix[ 8] = 2.0f * ( _x * _z + _y * _w ); pMatrix[ 9] = 2.0f * ( _y * _z - _x * _w ); pMatrix[10] = 1.0f - 2.0f * ( _x * _x + _y * _y ); pMatrix[11] = 0.0f; // Fourth row pMatrix[12] = 0; pMatrix[13] = 0; pMatrix[14] = 0; pMatrix[15] = 1.0f; // Now pMatrix[] is a 4x4 homogeneous matrix that can be applied to an OpenGL Matrix } [/CODE] as you receive input to change the direction you adjust q_pitch and q_heading accordingly and it will get calculated. I recommend creating a movable interface/class and deriving all your objects that need to move from it.
  7. game state management not working?

    if( showGameMenu == true ) 'showGameMenu = true' will always return true
  8. *BUMP* I want to have compiled scripts but be able to deploy on XBOX. Will simply including them in the Content make them compiled???
  9. Hi I've been creating a 3D engine in C# and XNA, with the hopes of deploying on PC and XBL. One tool I've wanted to make (for the sake of development and education) is a Quake/Half-Life style console that I could use to run commands and scripts. I'm aware having a console is pointless on the XBOX but its useful in the dev cycle. I've created a "Virtual Machine" that is basically a dictionary of all the functions i want to make accessible to the console and the script manager. Different classes can register their Functions with the VM with a meta tag so that it can be called by the user or script. My next step is to add support for scripting. But I have a few questions.... 1. Am i taking the most efficient approach to implementing this type of functionality? 2. And if i place a script in my content and Build the solution is my script being compiled as well? (From what I've read parsing text is very slow and doesnt scale well - but the Xbox doesn't support the compiler class!) Here is the start of my VM and Console: VirtualMachine.cs [CODE] namespace AnoeTech { public class VirtualMachine { #region Structs private struct FunctionHeader { public Func<object[], object> Function; public int NumberOfParameters; public Type[] ParameterType; } #endregion #region Variables VMConsole _console; Game1 _engine; Dictionary<string, FunctionHeader> FunctionDictionary = new Dictionary<string, FunctionHeader>(); #endregion #region Accessors public VMConsole Console{ get{ return _console;} } public Game1 Engine{ get{ return _engine;} } #endregion #region Functions public void Initiate( Game1 engine ) { _engine = engine; // Link the VM to the engine - this gives the VM access to the entire scope of the game // so you can make calls to any class within the game. _console = new VMConsole(); // Create a new console _console.Initiate(this); // and Initiate it } public void RegisterFunction<T>(string command, int numberOfArguments, Type[] parameterTypes, Func<object[], T> function) { FunctionHeader functionHeader = new FunctionHeader(); // Create a new Function Header functionHeader.Function = args => function(args); // Pass the Function into the Header functionHeader.NumberOfParameters = numberOfArguments; // Set the number of parameters the function takes functionHeader.ParameterType = parameterTypes; // Set the array of parameter types FunctionDictionary.Add(command, functionHeader); // Add the Meta Tag and Function Header to the Dictionary Console.Output("Function " + command + " has been registered with the VM."); } public void RegisterFunction(string command, int numberOfArguments, Type[] parameterTypes, Action<object[]> function) { FunctionHeader functionHeader = new FunctionHeader(); // This code does the same as above functionHeader.Function = args => { function.Invoke(args); return null; }; // but is responsible for handling functionHeader.NumberOfParameters = numberOfArguments; // functions that have no return value. functionHeader.ParameterType = parameterTypes; FunctionDictionary.Add(command, functionHeader); Console.Output("Function " + command + " has been registered with the VM."); } public object Execute(string command, object[] args) { return FunctionDictionary[command].Function.Invoke(args); // Execute a command and pass the result to the caller } public void ExecuteFromConsole( string command, object[] args) { if (FunctionDictionary.ContainsKey(command)) // If the Command is registered { if (args.Length == FunctionDictionary[command].NumberOfParameters) // And the correct number of parameters were used { bool allIsGood = true; for (int counter = 0; counter < FunctionDictionary[command].NumberOfParameters; counter++) if (args[counter].GetType() == FunctionDictionary[command].ParameterType[counter]) // And the parameters are all the correct type continue; else allIsGood = false; if (allIsGood) { FunctionDictionary[command].Function.Invoke(args); //Then execute the command Console.Output("Executed: " + Console.Command); } else Console.Output("=Command " + command + " takes different type for parameter="); } else Console.Output("=Command " + command + " takes " + FunctionDictionary[command].NumberOfParameters + " parameters="); } else Console.Output("=Command " + command + " not recognized="); } public void Update() { } #endregion } } [/CODE] VMConsole.cs [CODE] namespace AnoeTech { public class VMConsole { #region Variables private Texture2D _consolePanel; private string[] _consoleData; private string _command; private Vector2 _consoleTextPosition; private char[] _delimiterChars = { ' ', '(', ',', ')' }; private int _maxLines = 8; private Vector2 _position, _targetPosition; private bool _slidingIn = false; private bool _slidingOut = false; private bool _visible = false; private VirtualMachine _vm; private int _width, _height; #endregion #region Accessors public bool IsVisible { get { return _visible; } private set { _visible = value; } } public string Command { get { return _command; } private set { _command = value; } } #endregion #region Public Functions public void Draw() { if (IsVisible) { // Draw the console panel graphic _vm.Engine.spriteBatch.Draw(_consolePanel, new Rectangle((int)_position.X, (int)_position.Y, _width, _height), Color.White); // Draw the current command _vm.Engine.spriteBatch.DrawString(_vm.Engine.Font, _command, _consoleTextPosition, Color.White, 0, new Vector2(0, 0), 0.7f, SpriteEffects.None, 0.5f); // Draw the command/debug history if (_consoleData != null) // If there is prior data { Vector2 originalPosition = _consoleTextPosition; // Save the original start position for( int counter = 0; counter < _consoleData.Length; counter++ ) // Go through all the lines of debug info { _consoleTextPosition.Y -= 14; // Move up to print the next line of debug info _vm.Engine.spriteBatch.DrawString(_vm.Engine.Font, // Write the info onto the console _consoleData[counter], _consoleTextPosition, Color.White, 0, new Vector2(0, 0), 0.7f, SpriteEffects.None, 0.5f); if (counter == _maxLines) break; // If we are at the max # of visible lines then break } _consoleTextPosition = originalPosition; // Reset the console text position back to the original } } } public void Hide() { _slidingOut = true; } public void Initiate(VirtualMachine vm) { _vm = vm; _consolePanel = vm.Engine.Content.Load<Texture2D>("HUD/consolePanel"); _position = new Vector2(0, vm.Engine.Resolution.Y); _targetPosition = new Vector2(0, (int)Math.Ceiling(vm.Engine.Resolution.Y - vm.Engine.Resolution.Y * 0.2f)); _consoleTextPosition = new Vector2(10, _position.Y + vm.Engine.Resolution.Y * 0.2f - 26); _width = (int)vm.Engine.Resolution.X; _height = (int)(vm.Engine.Resolution.Y * 0.2); // Register console based functions with the VM Type[] y = new Type[1]; y[0] = typeof(string); vm.RegisterFunction("CONSOLE2FILE", 1, y, arg => SaveToFile((string)arg[0])); // Saves the console to a txt file } public void Output(string line) { _command = line; UpdateText(); } public void Show() { IsVisible = true; _slidingIn = true; _vm.Engine.Pause(true); } public void Update(KeyboardState keyState, KeyboardState oldkeyState) { if (_slidingIn) // If sliding in { _position.Y -= 0.1f * (_position.Y - _targetPosition.Y); // Move 10% of the total distance to target _consoleTextPosition.Y -= 0.1f * (_position.Y - _targetPosition.Y); // Move the text 10% of the totale distance too if (Math.Abs(_position.Y - _targetPosition.Y) < 0.1f) // If we are within .1 of the target { _position.Y = _targetPosition.Y; // Snap to the target _consoleTextPosition.Y = _position.Y + _vm.Engine.Resolution.Y * 0.2f - 14; // Snap the text to the target _targetPosition = new Vector2(0, _vm.Engine.Resolution.Y); // Set the target to the original starting pos _slidingIn = false; // Set liding in to false } } else if (_slidingOut) // If sliding out { _position.Y -= 0.1f * (_position.Y - _targetPosition.Y); // Opposite code of sliding in _consoleTextPosition.Y -= 0.1f * (_position.Y - _targetPosition.Y); if (Math.Abs(_position.Y - _targetPosition.Y) < 0.1f) { _position.Y = _targetPosition.Y; _consoleTextPosition.Y = _position.Y + _vm.Engine.Resolution.Y * 0.2f - 26; _targetPosition = new Vector2(0, (int)(_vm.Engine.Resolution.Y - _vm.Engine.Resolution.Y * 0.2f)); _slidingOut = false; IsVisible = false; _vm.Engine.Pause(false); // Unpause the engine } } else // If not sliding in or out { Keys[] keys = keyState.GetPressedKeys(); // Make an array of all the pressed keys foreach (Keys key in keys) // For each key { if (oldkeyState.IsKeyUp(key)) // If not pressed last iteration ( done to avoid registering a key press twice or more ) if (key == Keys.Back) // If user pressed BackSpace { if (_command.Length > 0) // If there is text _command = _command.Remove(_command.Length - 1, 1); // Remove the last character in the string } else if (key == Keys.Space) // If user presses SPACE _command = _command.Insert(_command.Length, " "); // Add a space else if (key == Keys.Enter) // If user presses ENTER BuildCommand(); // Build and attempt to execute the command else if ((int)key >= 48 && (int)key <= 57) // If the users presses 0-9 _command += ((int)key - 48); // Add "0" - "9" (as a char) else if ((int)key >= 96 && (int)key <= 105) //.. _command += ((int)key - 96); else if (key == Keys.OemPeriod) // If user presses period _command += "."; // Add "." else // If any other entry _command += key.ToString(); // Add the entry as a string } } } #endregion #region Private Functions private void BuildCommand() { string[] words = _command.Split(_delimiterChars); // Create an array of all the words entered string command = words[0]; // Assign the first word as the command object[] args = new object[words.Length-1]; // Create an array to hold all the arguements in the command bool tmpBool; float tmpFloat; int tmpInt; for (int counter = 1; counter < words.Length; counter++ ) // Build the list of arguements from the command string { if(int.TryParse(words[counter], out tmpInt)) // If the string is an Integer convert it args[counter - 1] = tmpInt; else if (float.TryParse(words[counter], out tmpFloat)) // If the string is a Float convert it args[counter - 1] = tmpFloat; else if (bool.TryParse(words[counter], out tmpBool)) // If the string is a Bool convert it args[counter - 1] = tmpBool; else // Otherwise its a string args[counter - 1] = words[counter]; } _vm.ExecuteFromConsole(command, args); // Execute the command } public void SaveToFile( string filename ) { System.IO.File.WriteAllLines(System.IO.Directory.GetCurrentDirectory() + "'\'" + filename, _consoleData); } private void UpdateText() { int length = 0; // Assume there are no lines of text in the console cache if (_consoleData != null) // But if there is lines of data in the console cache length = _consoleData.Length; // Set length to the number of lines there are string[] consoleData = new string[length + 1]; // Make a new string array with space for the new line for (int x = length; x > 0; x--) // Go through each line in the console starting from the back { consoleData[x] = _consoleData[x - 1]; // Place them in the new array, filling from the end of the array towards the front } consoleData[0] = _command.ToString(); // Put the newest command in the the first slot of the array _consoleData = consoleData; // Assign the new array to _consoleData _command = ""; // Clear the command line for the next command } #endregion } } [/CODE]
  10. Quaternion Interface

    One of the first tasks to accomplish in creating your own 3D engine is creating a way to move around in your potential world. While most will start with a simple untextured cube, its not much fun to stare at it from the same angle and position. We need to create a way to move in this beautiful world we are about to create! While it may be tempting to run to your Input Handling class and start hard coding in a bunch of Trig to achieve a sort of pseudo movement - STOP! There is a better way. First I will explain why trig will fail: GIMBAL LOCK - [url="http://en.wikipedia.org/wiki/Gimbal_lock"]http://en.wikipedia....iki/Gimbal_lock[/url] Long story short gimbal lock, as it applies to issues in gaming, will cause a freaky math problem when you attempt to look passed straight up or down - causing axes to flip and become oriented in a way that is difficult to deal with. While it may be possible to use a plethora of if statements to avoid the issue, it is not going to be fun if you need to ever allow your camera to be controlled while upside down. The solution? Quaternions! - [url="http://en.wikipedia.org/wiki/Quaternion"]http://en.wikipedia....wiki/Quaternion[/url] Quaternions provide a vector based solution to 3D calculations and movement that when properly coded the first time will provide you with a beautiful way to interact with your world objects. The math behind quaternions is definitely more advanced than trig, but a deep understanding is not necessary for their implementation. The goal of this article is the implementation not the explanation of quats. The most effective way to implement quaternions in your code is to create an Interface (not a class) that has all the variables and functions that define being movable, and derive any new classes that you want movable from that interface. Logically this makes sense. Creating a Interface called IMovable allows you to think "well my camera is moveable, so i will derive it from the interface moveable" so you would use something like: Class Camera : Public IMovable { public: Camera(); ~Camera(); ... When you get to more advanced stages of your engine this will be essential. You will most likely use some sort of scene graph and make nodes movable instead of individual objects. And you will use pointers so that you can call update on any object/node in the graph without needing to know what it is and blah blah blah - trust me once you get there its ease will make sense ;) I've included the interface files and code for a vector and quaternion. You will need your own code for handling matrix math. PM me for mine if you'd like. Unfortunately working my code into your engine wont be as easy as drag and drop but it is very clean and easy to figure out. Heres the header class IMovable public: void moveTo( float x, float y, float z ); void moveTo(Vector3D &v); void moveTo(Vector3D *v); // Warps the object to a given vertex void setX(double x); // Set the x value of the position void setY(double y); // Set the y value of the position void setZ(double z); // Set the z value of the position void accelerateForward( float scaleFactor = 1 ); void accelerateBack( float scaleFactor = 1 ); void accelerateLeft( float scaleFactor = 1 ); void accelerateRight( float scaleFactor = 1 ); void accelerateUp( float scaleFactor = 1 ); void accelerateDown( float scaleFactor = 1 ); void accelerateXAxis( float scaleFactor = 1 ); void accelerateYAxis( float scaleFactor = 1 ); void accelerateZAxis( float scaleFactor = 1 ); void zeroAxisVelocity( bool x = true, bool y = true, bool z = true ); void zeroLocalVelocity( bool x = true, bool y = true, bool z = true ); void changePitch(float degrees); void changeHeading(float degrees); void setPitch( float degrees ); void setHeading( float degrees ); void setAcceleration( float acceleration ); void setFriction( float friction ); virtual void update(); Vector3D* getPosition(); Vector3D* getLookAngles(); Vector3D* getUpVector(); protected: void calculateQuats(); Vector3D _pos, _lookVector, _upVector, _localVelocity, _axisVelocity; Quaternion _qHeading, _qPitch; float _pitch, _heading, _roll, _acceleration, _friction; bool _xLocked, _yLocked, _zLocked, _xViewLocked, _yViewLocked, _zViewLocked, _moving; So any object you want to be movable derive from this interface and it will have all these functions and variables accessible. The update function that is in the Imovable class is the bare minimum needed as far as math calculations to include and must be called every iteration of your engine to achieve fluid movement. It is a virtual function because most likely every object will have a different need for how it updates. The interface doesnt provide any drawing either, because not all movable objects are drawn (e.g. waypoints, cameras, etc ). So you will have to do that yourself. At the very least the accelerate forward, up, and left code aaaand retrieving and up vector is useful and where most people have math problems, so feel free to use the code in your own. There is a list of variables that must be set at initiation. They are all listed in the header file. Happy programming!!! [attachment=8554:IMovable.zip]
  11. MD5 model movement synching

    [quote name='Matthew Wood' timestamp='1299616120' post='4783265'] Hi, im making a game that uses md5 format models and need some help with moving the units. I am using quake models to test and i noticed in their 'run' animations, the models move forward (within the animation) - im assuming they do this so for collision testing. My question is how do i update my objects position to match the distance the model has moved to by the end of the animation? what im observing is my object moving towards its target, but at the end of the animation it is a little ahead of my objects actual location. when the animation restarts it jumps back to the objects location. so i have this weird 'jumping back' problem... [/quote] so i wrote a function to return me the position of the base joint and can just use that to calculate where i should be. waste o forum space, sorry guys
  12. Hi, im making a game that uses md5 format models and need some help with moving the units. I am using quake models to test and i noticed in their 'run' animations, the models move forward (within the animation) - im assuming they do this so for collision testing. My question is how do i update my objects position to match the distance the model has moved to by the end of the animation? what im observing is my object moving towards its target, but at the end of the animation it is a little ahead of my objects actual location. when the animation restarts it jumps back to the objects location. so i have this weird 'jumping back' problem...