Tuesday, December 17, 2013

Fire Arrows - Unity Asset - Smart and Performant AI Ballistics With or Without Flame!

Rain fire death on the enemy with this simple nifty package.

No coding knowledge required.




Asset Store Link

Designed so NPC or AI can strike out with projectile arrows with perfect (or imperfect) accuracy.

Arrow will 'stick' in designated objects (even those other than target objects - like terrain or buildings) and child to them - so that hitting an arrow embedded in a zombie's skull will move along with the zombie.

Optional rigidbody (works fine without - physics calculations are handled manually) allows you to load up a scene with many many arrows without the physics overhead. (NOTE that you must have a rigid body on any objects that an arrow can hit IF you go this route)

Set your own arrow 'force' to limit range or forcing 'arcing' of arrows to reach targets.

Predictive targeting available with configurable sampling rate to 'lead' targets (hit a moving target)

Handles different shooter/target heights. Will arc higher if force is too low to hit target on direct shot

Random 'inaccuracy' parameters

Ability to randomly aim for targets in scene or track a specific gameobject.

Arrow and flame 'destroy' time parameters

Optional/additional Blue and Green fire arrows.

Message callbacks to struck targets (to apply damage or whatever)

Multiple scenes with examples aplenty.

No use of tags - Targetable and Embedable scripts you can add to any gameobject


http://www.youtube.com/watch?feature=player_embedded&v=kLRTlKAPsms


http://www.youtube.com/watch?feature=player_embedded&v=aZlZT99ZljU

Sunday, April 7, 2013

Brick wall - terrain deformation

Still learning a lot about unity - things to do and not to do.
Like for example - can't have a collider trigger onEnter events with another collider if one of them is not a rigidBody.  I was planning on using a cube/rectangular mesh near the front of the bulldozer blade  - partially sunk into the terrain and look for collisions - and lower the terrain accordingly.  No dice.  God forbid, I give this 'scout' object a rigidbody - the bulldozer bucks like a wild bronco!


After a bunch of false starts, I landed on a technique with some promise - I placed a narrow plane out in front of the blade and fired raycasts through the vertices to the terrain below.  Upon intersection, I lowered the terrain below it.  I added another plane further in front to RAISE the terrain - to simulate the bulldozer scraping/pushing dirt.  It seemed to work ok - but I had to up the dozer scale to ensure I had enough terrain vertices to make a realistic 'flattened' area.  After a couple of hours of playing around (and adding an FPS display), I realized my performance had gone out the window.  After adding some ad-hoc profiling, my slowdown pointed towards the built-in Unity terrain setHeights functions.  After lots of web searches and reading, I determined this is a dead end.  The performance of setHeights for Unity Terrains is just way too prohibitive for this sort of work.   :(
If I were to create my own mesh based terrain 'thing', I'd run into the same performance issues that Unity had/has to deal with (and I am assuming they are a lot smarter than I).  I COULD abandon the bulldozer scrape/move capabilities and concentrate only on excavator/backhoe style digging - but that's not what I want.

Looks like I need to look at voxel based methods now- including such mathematical marvels as Marching Cubes!

Wednesday, April 3, 2013

I'm turning Toon!

While I don't intend to have a LOT of verts/polys in my game - I'm told that the Unity terrain alone on IOS can slow things down considerably.   No need for high-poly detailed models - and more so, not sure I need photo-realistic terrain or trees.   I ran into the same issue with DemolitionFX years ago.  I started out with it feeling like a more hardcore simulation - that didn't seem like that much fun.  It took my young son, Ben to point out that "everybody likes monkey's with hammers!".  So I will be ultimately switching to more of a toon-shaded (cel shaded) look and feel.
I'm enamored by some of the low-poly vehicles I find on SketchUp that I believe I can import (via Blender and then Unity.  I am hoping that at some point I can develop the skills to articulate these things (even if I just break them up into a few separate objects and control them with Unity scripting).
So I intend to continue prototyping - learning the bells and whistles of Unity and making sure I can implement all the features.  Then I will probably take a break and go on an 'asset' and 3d modeling bender where I find/create/buy the assets we need and learn to use the tools to properly manipulate them.  Finally - a clean write incorporating all I've learned.  Then probably an optimization cycle (playing with IOS and Android devices) and a re-write - then release!!

Tuesday, April 2, 2013

Birdseye view and transitioning into FP

Today I accomplished my goal early.  Wanted to prototype an overhead view (current my design says this will be one of the main views) that supported panning and zooming.  Works!  Then when clicking on vehicle I wanted smooth camera transition down from the sky into first person view on the vehicle.  Delved into the world of lerp and slerp (ended up using slerp because I liked the effect) and got a fairly cool effect.  I will probably play with Hotween or iTween later - I like their simplicity more.
      Next up is selecting units WITHOUT jumping into them - and showing info/fuel info.  Double click will bring you to first person view.  Eventually will probably create a context menu and eventually have to deal with mobile interface options like the long press and pinch-zoom.


Multiple Vehicles, Cameras and FP view

My goal for the day was to prototype having multiple vehicles shown in a 'birdseye' view and be able to select one, control that vehicle from an FP view and then revert back to birdseye view.
This forced me to understand communicating between scripts (objects) and some raycasting for the mouse pointing logic to select an object.

  I did raycasting before in my Three.js prototype to keep the vehicle along the normal to the ground  but in this prototype, however, I just let the physics engine deal with that aspect.  Not sure if the FP view will be one I end up using at all (was thinking an offset third person view would be better) but it might be an option.  2 additional goals for tomorrow - getting the camera to smoothly 'lerp' from birdseye to first person (instead of just snapping) and also allow user to pan/tilt birdseye camera as necessary (including a easy 'direct overhead' mode).
After that, the plan is to change the 'operate' function to be double click and single click will highlight the unit - giving floating health/fuel bar and other stats.

Monday, April 1, 2013

Re-Engaging Gold Mining Game with Unity

Fired up the latest version of Unity (4.1) this weekend to see how hard it would be to reproduce some of the terrain deformation work I prototyped using Three.js a while back.  Turns out, not too hard!

In a single day (a few hours here and there), I had basic terrain with moving vehicle (imported 3d model of bulldozer) and the ability to knock down trees.

Day 2 gave me ability to deform the terrain - not pretty yet but it works -AND adjusting the textures.  

Camera follows the vehicle and I worked a bit to get it to NOT steer like a car, but instead be able to pivot like a real tracked vehicle can do


I originally had mesh collider around the trees but they ended up doing crazy flip flops down hills when knocked over.  Tried cylinder - but they rolled too much.  Ended up with just a box collider around the trunk which did pretty well.





Started doing the scripting in javascript, but switched over to C# because it makes more sense to me.  It's easier for me when I find an example or code snipped to convert from javascript to C# than it is to go in the other direction.  Not too much code at the moment - just for the vehicle movement and camera follow - and of course, the terrain deformation.







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.