Tuesday, April 24, 2012

Recreating DemolitionFX

My goal for the evening was to recreate the bouncing beach balls and the exploding balloons for the game.  I decided to throw in my old crappy background image (I'll be replacing that eventually).  I managed to get everything done with only a couple of snafus...and a weird bug.
  As you can see in the pic on the left, my scene is set up with the 'building' set in front of my background image (just a jpg used as a texture for a rotated plane) and you can see my beach balls up above waiting to fall.
My 'beams' are simply cubes...scaled appropriately x/y/z and added one of the wood textures from the original game.  They have rigidbody physics components attached to them...and I am restricting the ability to rotate around the Y axis and limiting their movement on the X so that the game remains '2D' although it is obviously created with 3d objects.  I have attached fixed joints to each beam (just like in the original game) to give the structure some stability (including attaching the bottom beams to the concrete 'ground' and have assigned them realistic force/torque breaking points so that eventually (depending on what is happening in the scene), the stability will erode when joints start snapping.  I have not yet created the ability for the beams to 'take damage' and eventually split..but it's obviously on a to-do list.


The beach ball is a simple sphere mesh with the mass turned way down.  I added a special physics material to it to add the extra bounciness.
I have yet to constrain it's position or rotation, so they just sorta bounce all over the place wherever they want to. I had to tweak the mass and physics material a bit to make it look quasi-realistic..but that is where Unity really shines...was stupid easy to click/adjust a setting and just hit the 'play' button again.  Was amazed that a search for 'beach ball texture' generated a usable result with NO effort on my part...just dragged into the project and assigned the texture to the material associated with the ball.

The balloons were pretty easy as well.  I just went (for now because I couldn't get a free 3d studio max model of balloon to import properly) with a 'squashed' sphere mesh (just changed scale in Unity) and applied a downloaded 'latex' texture to it.  Made it's mass VERY low so that it would have no effect on anything as it was bouncing around.  Added a 'constant force' component to give it a slight 'upward' force to simulate the balloon floating up.  In the original DemolitionFX, I did something similar (except I executed this code manually every render/update cycle:


 if(c instanceof Balloon){
   c.physicsObject.applyForce(new Vec2(0,-0.000002*(physicsWorld.getGravity().y)), c.physicsObject.getPosition());
}


I added my 'explosion' logic to the balloon prefab (hit the space bar, generate explosive force on all objects within radius.  Worked like a charm except for an odd thing...the balloons disappear!  Now, I actually intended to do a little 'explosion' particle effect or something and have the balloons disappear anyway...but I have no idea where they are going.  I am assuming because of the stupid small mass of the balloon, that the explosive force is acting on the balloon itself and it is being rocketed into the multiverse by an explosion powerful enough to topple a wooden structure.  I'll change my explosion routine to ignore the balloon object that is generating the explosion and see what happens.





Game Engine versus Game Programming

I worked up some starting prototypes of DemolitionFX in Unity last night (mostly just working with beam primitives and joints..trying to get realistic structures with destructible joints).  Was very neat.  Didn't realize until towards the end that my primitive beams were WAY off scale in terms of size....my beams were some 120 feet long in some cases (intended them to be only 10-12 or so) and was effecting the physics a bit.  While I worked with several physics engines in the past (Phys2D, Box2D, etc) and am comfortable with concepts like adding force to rigid bodies, I was pleasantly surprised by some of the tools that Unity brought to the table as a true 'game engine'.  Example.  I created a small sphere that I placed 'near' my structure to act as a bomb.  Pressing the space bar would 'detonate it, generating an explosion.  Unity provided me some neato functions to help propagate that explosive force to my structure:


function explode(){
 var explosionPos : Vector3 = transform.position;
    var colliders : Collider[] = Physics.OverlapSphere (explosionPos, radius);
    for (var hit : Collider in colliders) {
        if (!hit)
            continue;
        if (hit.rigidbody)
            hit.rigidbody.AddExplosionForce(power, explosionPos, radius, 3.0);
    }
}
Essentially, the physics engine provides me with list of rigid bodies that are overlapped by a sphere of whatever radius and I can then use a super handy function to 'AddExplosiveForce' to each of them...theoretically exactly on their bodies where the explosion should effect them.  And..the explosive force will fall off linearly with the distance to the rigid body.

Here is the same code from my old JavaFX version of DemolitionFX:



  public static void explosion(World world, Vec2 position, float power, int maxApply)
      {
         AABB  aabb = new AABB();
         Vec2 vMin = position.clone();
         vMin = vMin.add(new Vec2(-1f*(float)power, -1f*(float)power));
         Vec2 vMax = position.clone();
         vMax = vMax.add(new Vec2(1f*(float)power, 1f*(float)power));
         aabb.lowerBound = vMin;
         aabb.upperBound = vMax;
         Shape[] shapes = null;
         shapes = world.query(aabb, maxApply);
         for (int i = 0; i < shapes.length; i++)
         {
            Body b  = shapes[i].getBody();
            if(b.getUserData()==null || b.getUserData() instanceof String){
                continue;
            }
            Vec2 explosionClosePoint = new Vec2(0f,0f);
            Vec2 bodyClosePoint = new Vec2(0f,0f);
            Shape bodyShape = b.getShapeList();


              PolygonDef sd = new PolygonDef();
              sd.setAsBox(.005f,.005f);
              sd.density = 0.0f;
              sd.friction =0f;
              BodyDef bd= new BodyDef();
              bd.position = position.clone();
              Body body= world.createBody(bd);
              Shape explosionShape = body.createShape(sd);
              world.destroyBody(body);
          float dist = Distance.distance(explosionClosePoint, bodyClosePoint,
explosionShape, body.getXForm(),
bodyShape, b.getXForm());
            Vec2 fv = bodyClosePoint.clone();
            fv = fv.sub(position);
            fv.normalize();
            fv = fv.mul(5500+(float)power * 5000f);
            b.wakeUp();
            b.applyForce(fv, bodyClosePoint);
           ((BeamData)b.getUserData()).setDamage(((BeamData)b.getUserData()).getDamage()+fv.length()/25f);
         }
      }



Essentially, I generate  rectangle around the position of my explosion....get a list of rigid bodies that overlap it...but I have to create a fake 'explosion' object in order to find the closest point from that object to each of the overlapping objects...and then calculate and apply the appropriate force.  Also...I did not take into consideration the distance between the explosion and the object...if it was in the rect...it got the same force as any other object in the rect.    The extra code I had was not THAT much extra work...but I was amazed that Unity provided me exactly what I needed with no fuss and muss.

Friday, April 20, 2012

Game Engine

Spent some time tonight watching videos and downloading/installing/playing with Unity...the cross platform game engine that supports web, Android, and IOS.  It is truly amazing.  I managed to get the IOS and Android 'options' for the free version before a recent price change (they now cost $400 and $500 respectively).  For the pro version, they each cost $1500 plus an additional $1500 for the core engine.  Anything I expect to do in the near future (I'm pretty sure) can be done with the free version.  My current plan is to port my DemolitionFX game to Unity and turn it into a quasi 3D game (2D physics with 3d objects) so that I can learn a lot about the engine.  Then I intend to push through with the mining game (tentatively called 'Claim Jumpin'.
There is a REASON why over 1,000,000 developers have licenses for this thing.  I would recommend watching these vids if you are interested:

http://www.youtube.com/watch?v=ZbUVbaTbzPQ (and 3 follow ups)
http://www.youtube.com/watch?v=CWG0AsyzP_w (and follow ups)

A link to a fairly complete list/comparison of game engines suitable for the indie game can be found here



Thursday, April 19, 2012

My only other completed game

Whipped this up for the JavaFX coding challenge back in 2009.  Didn't win anything, but I had a blast coding it. Enjoy the video

Wednesday, April 18, 2012

Earth Moving III

General outline for preliminary earth moving logic (I fully intend for this to get polished later)


start with bounding rectangle (mesh coordinates) denoting excavation selection and ‘depth’ to excavate to.


Also start with bounding rectangle denoting ‘deposit’ selection (usually smaller).  No ‘depth’ necessary.


Eventually may change the ‘deposit’ area selection to a ‘circle’ once I figure out 
the math.

  • create 2d array of vertices covered in the excavation selection
  • create a 2d array of vertices covered in the deposit selection
  • loop through excavation vertices
    • find the ‘highest’ one to excavate and excavate it once.
    • find the ‘lowest’ vertice in the deposit area selection and drop it off
  • end loop



psuedo code for vertice array creation for excavation OR deposit



var ppp = map_height/plots; //note that currently map height/width are same
plots_x = floor(selection_width / ppp);
plots_y = floor(selection_height / ppp);
var vertice_array = new Array();
for(var y = 0;y<plots_y;y++){

var row = new Array();
for(var x = 0;x<plots_x;x++)
{
     vertice = find_vertice(left_edge+x*ppp, top_edge+y*ppp);
//find_vertice function finds vertice in mesh closest to the x/y coordinate
   row.push(vertice);

}
vertice_array.push(row);
}
 
**UPDATE.  Yeah..silly of me...this assumes that each 'scoop' (excavation) of dirt will cover only a single vertice...and at the moment (because of performance reasons), it is actually about right...in the future (assuming I move to another platform or otherwise solve), I'll have to have a more complex algorithm that checks the height of ALL vertices in the selected area and based on the radius of the 'scoop' decide where to dig/dump.

Monday, April 16, 2012

Orders, AI and Fun

Ok...I have prototypes of the terrain deformation working....and some vehicle modeling.  I need to start working on some of the gameplay and AI elements.  I argue with my friend(s) about this...I don't think that players will want to control each individual piece of equipment...picking up each individual load of dirt...steering to the the staging pile and dropping it off.  Then controlling a front-end-loader to pick up a load of dirt from the staging pile and placing it in the washplant.  Or working the dozer that pushes the rocks away from the bottom of the washplant....

I mean...you don't do that in other RTS games, do you?  You click on one (or more units) and give them orders...point them at something to attack or build or whatever.  You have LOTS of work to do and shouldn't be bogged down with lowering the arm on the excavator into the 'glory hole' to pull up another load of dirt/mud....over and over and over again.  Who would want to do that?  But to that point...I don't understand how people do it in real life either....
     
I will certainly ALLOW the user to control individual pieces of machinery...but when your minesite gets productive and profitable, you might have a half-dozen pieces of machinery to manage...and doing everything yourself will take FOREVER to get anything done.   My next piece of work will concentrate on selecting an 'area' to excavate along with an area to deposit material....and the equipment will do your bidding 'automagically' I still have to develop a state-engine and order processing techniques for this and have been mulling it over for a while.

Sunday, April 15, 2012

Earth Moving part II

Well...I had some modicum of success in conceptually representing digging in one place and depositing dirt in another.  While I am not happy with the texturing of the placed dirt (too jaggedy along the edges), I did solve some of the slow 'brute force' techniques I was using to determine vertices under the dozer.
  Using a variation of the "Manhattan Distance" algorithms that I saw used elsewhere, I essentially calculate the nearest vertice under the x,z of the dozer and then walk a 'circle' of radius whatever to grab the vertices I need to either elevate or depress.  It sucks having to deal with true pixel x,y,z in some places and deal with triangulated mesh vertices in others...but so far it is manageable.




Note the new red 'circle' under the dozer...just playing with some schemes for equipment selection and such.  Probably will be using a rectangle selection tool of some kind for area selection when giving 'orders' to equipment.