title: How to do 2D Raycasting on a slope

text:
# Question
Title: How to do 2D Raycasting on a slope
I have a 2d platformer game where my slope can be set at any angle, so I've setup a middle raycast that points to the ground onto the player to handle the collision. This works perfectly fine on a flat platform, but when I rotate it to a slope the player is offset increasingly more.

Player falls onto the platform with no rotation (works fine).

The player falls onto a platform at an angle with no rotation on the player.

Then when I rotate the player to the angle of the platform.

As you can see the player is offset wrong. Do I have to rotate the rays attached to the player and then push him out of the platform? Or is this overkill and I'm doing something wrong?

# Answer
> 3 votes
> Do I have to rotate the rays attached to the player and then push him out of the platform? Or is this overkill and I'm doing something wrong?

This is not overkill, and is in fact the correct technique. It is not too difficult: Imagine this problem from the perspective of the platform... The "up" direction will be the vector \<0, 1\> rotated by the same amount that your platform is rotated. The code for rotating a vector `<x, y>` (counterclockwise) by an angle `a` is:

```
<x * cos(a) - y * sin(a), x * sin(a) + y * cos(a)>

```

---
Tags: 2d, collision-detection, platformer
---


title: Resolving 2D Collision with Rectangles

text:
# Question
Title: Resolving 2D Collision with Rectangles
For about a week I've been trying to grasp the basics of collision, but I've been driven to the point of wanting to just give up on everything when it comes to collision. I just don't understand it. Here's my code so far:

```
 public static void ObjectToObjectResponseTopDown(GameObject actor1, GameObject actor2)
        {
            if (CollisionDetection2D.BoundingRectangle(actor1.Bounds.X, actor1.Bounds.Y, actor1.Bounds.Width, actor1.Bounds.Height,
 actor2.Bounds.X, actor2.Bounds.Y, actor2.Bounds.Width, actor2.Bounds.Height)) //Just a Bounding Rectangle Collision Checker
            {
                if (actor1.Bounds.Top > actor2.Bounds.Bottom) //Hit From Top
                {
                    actor1.y_position += Rectangle.Intersect(actor1.Bounds, actor2.Bounds).Height;
                    return;
                }
                if (actor1.Bounds.Bottom > actor2.Bounds.Top) //Hit From Bottom
                {
                    actor1.y_position -= Rectangle.Intersect(actor1.Bounds, actor2.Bounds).Height;
                    return;
                }
                if (actor1.Bounds.Left > actor2.Bounds.Right)
                {
                    actor1.x_position += Rectangle.Intersect(actor1.Bounds, actor2.Bounds).Width;
                    return;
                }
                if (actor1.Bounds.Right > actor2.Bounds.Left)
                {
                    actor1.x_position -= Rectangle.Intersect(actor1.Bounds, actor2.Bounds).Width;
                    return;

                }
            }
        }

```

Essentially what it does so far is correctly collides when the bottom of the first rectangle collides with the top of the second rectangle, but with the left an right sides it corrects it either above or below the tile, and when the top of the first rectangle collides with the bottom of the second rectangle, it slides right through the second rectangle.

I'm really not sure what to do at this point.

# Answer
> 2 votes
Your collision detection code looks like it's working fine, however your **collision response** appears to be causing the issue. This is evident if you step through how you are actually resolving two colliding bodies.

Let's take a look at the following example (assume the blue rectangle is actor1 and moving left):

As your code checks the top and bottoms bounds first, these are the first to be resolved and actor1's y position is adjusted like so:

The two bodies are now no longer colliding, but the collision wasn't resolved in the best way. This will almost always happen (unless the two rectangles' top and bottom bounds are perfectly in line) and the last two if statements will never be checked.

A primitive way to handle collision response would be to offset the rectangles by the smallest overlap; this would solve the problem in the above example, but you would still find some problems. A better approach would take an object's velocity into consideration, such as the answer found here.

# Answer
> 0 votes
As Alex indicated, your collision response is a very sharp "snap to edge" type of reaction, where if the two rectangles collide, one of them will instantaneously adjust its position to place it adjacent to the other.

That's not ideal behavior, but it isn't necessarily a problem either. The problem is that you return from each of your sequential if(collision) checks, which is why you only get a top/bottom edge alignment.

The early exit (which are correct for AABB collision *detection*) is not necessary in your collision *response*. Try something more like:

```
            if (actor1.Bounds.Top > actor2.Bounds.Bottom) //Hit From Top
            {
                actor1.y_position += Rectangle.Intersect(actor1.Bounds, actor2.Bounds).Height;
            }
            else if (actor1.Bounds.Bottom > actor2.Bounds.Top) //Hit From Bottom
            {
                actor1.y_position -= Rectangle.Intersect(actor1.Bounds, actor2.Bounds).Height;
            }

            if (actor1.Bounds.Left > actor2.Bounds.Right)
            {
                actor1.x_position += Rectangle.Intersect(actor1.Bounds, actor2.Bounds).Width;
            }
            elseif (actor1.Bounds.Right > actor2.Bounds.Left)
            {
                actor1.x_position -= Rectangle.Intersect(actor1.Bounds, actor2.Bounds).Width;
            }

```

---
Tags: xna, c#, 2d, collision-resolution
---


# Question
Title: Relative cam movement and momentum on arbitrary surface
I have been working on a game for quite long, think sonic classic physics in 3D or Tony Hawk PSX, with Unity3D. However I'm stuck at the most fundamental aspect of movement.

The requirement is that I need to move the character in Mario 64 fashion (or sonic adventure) aka relative cam input:

1. the camera's forward direction always point input forward the screen, left or right input point toward left or right of the screen.
2. when input are resting, the camera direction is independent from the character direction and the camera can orbit the character
3. when input are pressed the character rotate itself until his direction align with the direction the input is pointing at.

It's super easy to do as long your movement are parallel to the global horizontal (or any world axis). However when you try to do this on arbitrary surface (think moving along complex curved surface) with the character sticking to the surface normal (basically moving on wall and ceiling freely), it seems harder. What I want is to achieve the same finesse of movement than in Mario but on arbitrary angled surfaces. There is more problem (jumping and transitioning back to the real world alignment and then back on a surface while keeping momentum) but so far I didn't even take off the basics.

So far I have accomplish moving along the curved surface and the relative cam input, but for some reason direction fail all the time (point number 3, the character align slowly to the input direction).

Do you have an idea how to achieve that?

Here is the code and some demo so far:

The demo:

https://dl.dropbox.com/u/24530447/flash%20build/litesonicengine/LiteSonicEngine5.html

Camera code:

```
using UnityEngine;
using System.Collections;

    public class CameraDrive : MonoBehaviour
    {
        public GameObject
            targetObject;

        public Transform
            camPivot,
            camTarget,
            camRoot,

            relcamdirDebug;

        float
            rot = 0;
    //----------------------------------------------------------------------------------------------------------
        void Start()
        {
            this.transform.position = targetObject.transform.position;
            this.transform.rotation = targetObject.transform.rotation;
        }

        void FixedUpdate()
        {
        //the pivot system
            camRoot.position    = targetObject.transform.position;

        //input on pivot orientation
            rot = 0;
            float mouse_x        = Input.GetAxisRaw( "camera_analog_X" );                //
            rot                 = rot + ( 0.1f * Time.deltaTime * mouse_x );            //
            wrapAngle( rot );                                                            //

        //when the target object rotate, it rotate too, this should not happen

            UpdateOrientation(this.transform.forward,targetObject.transform.up);

            camRoot.transform.RotateAround(camRoot.transform.up,rot);

        //debug the relcam dir
                RelativeCamDirection()
                ;

        //this camera
            this.transform.position    = camPivot.position;                            //set the camera to the pivot
            this.transform.LookAt( camTarget.position );                            //
        }
    //----------------------------------------------------------------------------------------------------------
        public float wrapAngle ( float Degree )
        {
            while (Degree < 0.0f)
            {
                Degree = Degree + 360.0f;
            }
            while (Degree >= 360.0f)
            {
                Degree = Degree - 360.0f;
            }
            return Degree;
        }

        private void UpdateOrientation( Vector3 forward_vector, Vector3 ground_normal )
        {
            Vector3
                projected_forward_to_normal_surface = forward_vector - ( Vector3.Dot( forward_vector, ground_normal ) ) * ground_normal;

            camRoot.transform.rotation = Quaternion.LookRotation( projected_forward_to_normal_surface, ground_normal );
        }

        float GetOffsetAngle( float targetAngle, float DestAngle )
        {
                return ((targetAngle - DestAngle + 180)% 360)  - 180;
        }
    //----------------------------------------------------------------------------------------------------------
        void OnDrawGizmos()
        {
            Gizmos.DrawCube(
                camPivot.transform.position,
            new Vector3(1,1,1)
                );

            Gizmos.DrawCube(
                camTarget.transform.position,
            new Vector3(1,5,1)
                );

            Gizmos.DrawCube(
                camRoot.transform.position,
            new Vector3(1,1,1)
                );
        }

        void OnGUI()
        {
            GUI.Label(new Rect(0,80,1000,20*10), "targetObject.transform.up : " + targetObject.transform.up.ToString());
            GUI.Label(new Rect(0,100,1000,20*10), "target euler : " + targetObject.transform.eulerAngles.y.ToString());
            GUI.Label(new Rect(0,100,1000,20*10), "rot : " + rot.ToString());

        }
    //----------------------------------------------------------------------------------------------------------
        void RelativeCamDirection()
        {

            float
                input_vertical_movement     = Input.GetAxisRaw( "Vertical" ),
                input_horizontal_movement     = Input.GetAxisRaw( "Horizontal" );

            Vector3
                relative_forward     = Vector3.forward,
                relative_right         = Vector3.right,

                relative_direction    =
                    ( relative_forward    * input_vertical_movement )
                    +
                    ( relative_right    * input_horizontal_movement )
                    ;

            MovementController MC = targetObject.GetComponent<MovementController>();

            MC.motion = relative_direction.normalized * MC.acceleration * Time.fixedDeltaTime;

            MC.motion = this.transform.TransformDirection( MC.motion );

            //MC.transform.Rotate(Vector3.up, input_horizontal_movement * 10f * Time.fixedDeltaTime);
        }
    }

```

Mouvement code:

```
using UnityEngine;
using System.Collections;

public class MovementController : MonoBehaviour
{
    public float
        deadZoneValue = 0.1f,
        angle,
        acceleration  = 50.0f;
    public Vector3
        motion ;

//--------------------------------------------------------------------------------------------
    void OnGUI()
    {
        GUILayout.Label( "transform.rotation : " + transform.rotation );
        GUILayout.Label( "transform.position : " + transform.position );
        GUILayout.Label( "angle : " + angle );
    }

    void FixedUpdate ()
    {

        Ray
            ground_check_ray = new Ray( gameObject.transform.position, -gameObject.transform.up );
        RaycastHit
            raycast_result;
        Rigidbody
            rigid_body = gameObject.rigidbody;

        if ( Physics.Raycast( ground_check_ray, out raycast_result ) )
        {
            Vector3
                next_position;

            //UpdateOrientation( gameObject.transform.forward, raycast_result.normal );
            UpdateOrientation( gameObject.transform.forward, raycast_result.normal );
            next_position = GetNextPosition( raycast_result.point );
            rigid_body.MovePosition( next_position );
        }
    }
//--------------------------------------------------------------------------------------------

    private void UpdateOrientation( Vector3 forward_vector, Vector3 ground_normal )
    {
        Vector3
            projected_forward_to_normal_surface = forward_vector - ( Vector3.Dot( forward_vector, ground_normal ) ) * ground_normal;

        transform.rotation = Quaternion.LookRotation( projected_forward_to_normal_surface, ground_normal );
    }

    private Vector3 GetNextPosition( Vector3 current_ground_position )
    {
        Vector3
            next_position;

//        //--------------------------------------------------------------------
//        angle = 0;
//        Vector3 dir = this.transform.InverseTransformDirection(motion);
//        angle = Vector3.Angle(Vector3.forward, dir);// * 1f * Time.fixedDeltaTime;
//
//        if(angle > 0) this.transform.Rotate(0,angle,0);
//        //--------------------------------------------------------------------

        next_position =
            current_ground_position +
            gameObject.transform.up * 0.5f
                + motion
                ;

        return next_position;
    }

}

```

Some observation:

I have the correct input, I have the correct translation in the camera direction ... but whenever I attempt to slowly lerp the direction of the character in direction of the input, all I get is wild spin! Sad

Also discovered that strafing to the right (immediately at the beginning without moving forward) has major singularity trapping on the equator!!

I'm totally lost and crush (I have already done a much more featured version which fail at the same aspect)

# Answer
> 1 votes
It's solved now! See the comment above to have the details!

Now another problem is to build in momentum ... the fun only begin lol

New Build: https://dl.dropbox.com/u/24530447/flash%20build/litesonicengine/LiteSonicEngine6.html Arrow to move, mouse to turn camera around

Movement code (lerp commented)

```
using UnityEngine;
using System.Collections;

public class MovementController : MonoBehaviour
{
    public float
        deadZoneValue = 0.1f,
        angle,
        acceleration  = 50.0f;
    public Vector3
        motion ;
    public Vector3
        ground_direction ;

//--------------------------------------------------------------------------------------------
    void OnGUI()
    {
        GUILayout.Label( "transform.rotation : " + transform.rotation );
        GUILayout.Label( "transform.position : " + transform.position );
        GUILayout.Label( "angle : " + angle );
        GUILayout.Label( "ground_direction : " + ground_direction );
        GUILayout.Label( "motion : " + ground_direction );
    }

    void FixedUpdate ()
    {

        Ray
            ground_check_ray = new Ray( gameObject.transform.position, -gameObject.transform.up );
        RaycastHit
            raycast_result;
        Rigidbody
            rigid_body = gameObject.rigidbody;

        if ( Physics.Raycast( ground_check_ray, out raycast_result ) )
        {
            Vector3
                next_position;

            //UpdateOrientation( gameObject.transform.forward, raycast_result.normal );
            UpdateOrientation( gameObject.transform.forward, raycast_result.normal );
            next_position = GetNextPosition( raycast_result.point );
            rigid_body.MovePosition( next_position );
            ground_direction = raycast_result.normal;
        }
    }
//--------------------------------------------------------------------------------------------

    private void UpdateOrientation( Vector3 forward_vector, Vector3 ground_normal )
    {
        Vector3
            projected_motion_to_normal_surface = motion - ( Vector3.Dot( motion, ground_normal ) ) * ground_normal;

        Quaternion target;
        if (motion.sqrMagnitude > 0)
        {
            target = Quaternion.LookRotation( projected_motion_to_normal_surface, ground_direction );
        }
        else
        {
            target = Quaternion.LookRotation( transform.forward, ground_direction );
        }
        transform.rotation  = target;//Quaternion.Slerp( transform.rotation, target, 0.1f );
        //transform.rotation = Quaternion.LookRotation( projected_forward_to_normal_surface, ground_normal );

        Debug.DrawRay(this.transform.position,motion*10,Color.yellow,0.0f,false);
    }

    private Vector3 GetNextPosition( Vector3 current_ground_position )
    {
        Vector3
            next_position;

//      //--------------------------------------------------------------------
//      angle = 0;
//      Vector3 dir = this.transform.InverseTransformDirection(motion);
//      angle = Vector3.Angle(Vector3.forward, dir);// * 1f * Time.fixedDeltaTime;
//
//      if(angle > 0) this.transform.Rotate(0,angle,0);
//      //--------------------------------------------------------------------

        next_position =
            current_ground_position +
            gameObject.transform.up * 0.5f
                + motion
                ;

        return next_position;
    }

}

```

Camera code

```
using UnityEngine;
using System.Collections;

public class CameraDrive : MonoBehaviour
{
    public GameObject
        targetObject;

    public Transform
        camPivot,
        camTarget,
        camRoot,

        relcamdirDebug;

    float
        rot = 0;
//----------------------------------------------------------------------------------------------------------
    void Start()
    {
        this.transform.position = targetObject.transform.position;
        this.transform.rotation = targetObject.transform.rotation;
    }

    void FixedUpdate()
    {
    //the pivot system
        camRoot.position    = targetObject.transform.position;

    //input on pivot orientation
        rot = 0;
        float mouse_x       = Input.GetAxisRaw( "camera_analog_X" );                //
        rot                 = rot + ( 0.1f * Time.deltaTime * mouse_x );            //
        wrapAngle( rot );                                                           //

    //when the target object rotate, it rotate too, this should not happen

        UpdateOrientation(this.transform.forward,targetObject.transform.up);

        camRoot.transform.RotateAround(camRoot.transform.up,rot);

    //this camera
        this.transform.position = camPivot.position;
    //set the camera to the pivot
        //Quaternion target = Quaternion.LookRotation(targetObject.transform.position - this.transform.position, targetObject.transform.up);

        //this.transform.rotation = Quaternion.Slerp(this.transform.rotation, target, 0.1f);

    //relcam dir
       RelativeCamDirection();

    this.transform.LookAt( camTarget.position );                            //
    }
//----------------------------------------------------------------------------------------------------------
    public float wrapAngle ( float Degree )
    {
        while (Degree < 0.0f)
        {
            Degree = Degree + 360.0f;
        }
        while (Degree >= 360.0f)
        {
            Degree = Degree - 360.0f;
        }
        return Degree;
    }

    private void UpdateOrientation( Vector3 forward_vector, Vector3 ground_normal )
    {
        Vector3
            projected_forward_to_normal_surface = forward_vector - ( Vector3.Dot( forward_vector, ground_normal ) ) * ground_normal;

        camRoot.transform.rotation = Quaternion.LookRotation( projected_forward_to_normal_surface, ground_normal );
    }

    float GetOffsetAngle( float targetAngle, float DestAngle )
    {
            return ((targetAngle - DestAngle + 180)% 360)  - 180;
    }
//----------------------------------------------------------------------------------------------------------
    void OnDrawGizmos()
    {
        Gizmos.DrawCube(
            camPivot.transform.position,
        new Vector3(1,1,1)
            );

        Gizmos.DrawCube(
            camTarget.transform.position,
        new Vector3(1,5,1)
            );

        Gizmos.DrawCube(
            camRoot.transform.position,
        new Vector3(1,1,1)
            );
    }

    void OnGUI()
    {
        GUI.Label(new Rect(0,80,1000,20*10), "targetObject.transform.up : " + targetObject.transform.up.ToString());
        GUI.Label(new Rect(0,100,1000,20*10), "target euler : " + targetObject.transform.eulerAngles.y.ToString());
        GUI.Label(new Rect(0,100,1000,20*10), "rot : " + rot.ToString());

    }
//----------------------------------------------------------------------------------------------------------
    void RelativeCamDirection()
    {
        Vector3
            relative_direction  =
                ( Vector3.forward   * Input.GetAxisRaw( "Vertical" ) )
                +
                ( Vector3.right     * Input.GetAxisRaw( "Horizontal" ) )
                ;

        MovementController MC = targetObject.GetComponent<MovementController>();

        Vector3 direction = relative_direction.normalized * MC.acceleration * Time.fixedDeltaTime;

        Vector3 abs_direction =  camRoot.transform.TransformDirection( direction );
        MC.motion = abs_direction;

        Debug.DrawRay (camRoot.position, camRoot.right,Color.red,0.0f,false);
        Debug.DrawRay (camRoot.position, camRoot.up,Color.green,0.0f,false);
        Debug.DrawRay (camRoot.position, camRoot.forward,Color.blue,0.0f,false);
        //MC.transform.Rotate(Vector3.up, input_horizontal_movement * 10f * Time.fixedDeltaTime);

    }
}

```

# Answer
> 0 votes
For the slerping, try someting as this (but only if your input vector is non-zero):

```
//MC.transform.Rotate(Vector3.up, input_horizontal_movement * 10f * Time.fixedDeltaTime);
Quaternion target = Quaternion.LookRotation( relative_direction, MC.transform.up );
MC.transform.rotation = Quaternion.slerp(MC.transform.rotation, target, 0.5);

```

For the singularity trapping: Why do you keep the movement vectors relative\_forward and relative\_right orientated as the camera? At the equator your movement vectors point in the same direction as your ground normal.

---
Tags: unity, vector, platformer
---


title: Pathfinding with different sized units

text:
# Question
Title: Pathfinding with different sized units
I am actually working on a general purpose pathfinding library (find it here), mostly oriented for grid-based maps. I was looking for ways to integrate support for pathfinding with units of different sizes. Actually, I am working with the assumption that all units are square (i.e. their widths and heights in tile units are the same).

In researching, I came across a very comprehensive article about Annotated A-star, using True clearance values for pathfinding. I tried it, and succeeded in implementing it, and got it working with a wide range of search algorithms (A-star, Theta\*, Dijkstra, DFS, Breadth-first search and Jump Point Search).

There are some small details of implementation I think I am still missing. First of all, when an agent is 2x2 sized (i.e it occupies 4 tiles on the grid map), what tile can be assumed to be the agent position ? On the same page, clearance based pathfinding will fail in some cases. Let's consider the following map, where 0's are passable tiles, 1's are obstacles and x's matches walkable goal to be reached. Let's assume we are pathing with a 2x2 sized unit:

```
00000000
00111100
001xx100
001xx100
00000000

```

For targets on the left (tiles 4,3 and 4,4), clearance value is 2, for both. No problem here. But for the others (tiles 5,3 and 5,4), clearance value is 1. So depending on how the agent position is taken, pathfinding will fail while obviously, for each of these target, the agent can properly fit into the dead-end space.

Another scenario, with the same 2x2 sized agent:

```
0000000x
0000000x
0000000x
0000000x
xxxxxxxx

```

Well, all tiles are walkable here, no obstacles. We want the object to reach any goal on the rightmost or bottom-most border. Each of these targets have a clearance of 1, so annotated pathfinding wil obviously fail here...depending on how the agent's position is taken.

How do I work around this issue?

# Answer
> 5 votes
I'd just modify the algorithm a tiny bit: Instead of evaluating the tile at `(x, y)` you evaluate four tiles: `(x, y)`, `(x + 1, y)`, `(x, y + 1)`, and `(x + 1, y + 1)` to calculate costs. If any is unpassable, you consider the tile unreachable. Other values might be combined on a min/max basis or just a median value (this really depends on how they impact movement).

However, there's one small additional modification: The goal is considered to be reached if any of the four tiles are the actual goal. It doesn't have to be the top left one.

Keep in mind that this might need further tweaking, depending on whether you add the remaining distance to your weighting (it might be skewed to the top left corner if you're not carefule).

---

As an alternative: Create another map using the points where four tiles meet as actual "tiles". Then just apply the standard algorithm.

---
Tags: path-finding
---


# Question
Title: Creating an update "Tick" on tiles for simulating growth of plants
In my 2D tile based platformer I have added plants to be able to farm such as the simplest, grass, to other things like corn. Now each of these speacial tiles must be updated to show how much it has grown (Simple states such as 0 = New, 1 = Mature, 2=Blooming)

My question is, what would be the best way to do this?

So far I belive I could:

1. Update every tile every few seconds, and if a random chance is met, make it grow
2. Choose a few tiles every frame to update (minecraft does this, same thing in 3D basicly)
3. ???

Now the timeframe for the updates would be something like, a flower blooms every game day (10 minutes in real life), grass spreads every in game hour, etc

Thanks for your help, I think I could do this, I'd just like a little advice if any of these are the right path.

# Answer
> 3 votes
For some types of objects, you can invert the logic.

Instead of *every N ticks, grow by X*, you can store the timestamp *T1* since the last growth, and then when the player next sees that object at time *T2*, you can grow the plant by *X * (T2 - T1) / N*.

That way, any plants not on screen don't take any CPU to update. Note that this only works for things that don't have any effects outside of the plant growth (e.g. it won't work if plants affect neighboring tiles).

# Answer
> 0 votes
Consider implementing a system that is designed to actively manage your tiles, taking the individual responsibility out of the tiles. The system would maintain its own timers relative to the game itself. A single tile manager would act as the central point for updating tiles based on your own constraints.

For instance, your tile manager could act as a singleton class, and processes "tile events" each frame. A tile event could be an abstract class that is extended to provide flexible behavior, and acts on a set of tiles passed in by the tile manager. This would decouple the tiles from the actual activity, making it easier to extend and maintain this system.

# Answer
> -1 votes
i dont know XNA, but you should think to use cooroutine\action instead putting all the code inside your update method (but i dont see your code, so maybe you already work in this way). Basically u should create a listener and when the action is called (for exemple, when a plant pass from his state "new" to "mature") starting the cooroutine.Also a behaviour tree should be pretty efficent in situations like this.

---
Tags: c#, xna, 2d, game-loop, timing
---


title: One AI object for each npc

text:
# Question
Title: One AI object for each npc
Let's think for a moment a game where you'll have around 1k npcs, each one has to take its own decisions. Should each one has an object that decides what to do, or maybe exist one to process every unit?

Also, let's think about a complex ai, not just check if npc can see the player nor decides if npc will attack or not. Something like Dwarf Fortress does.

# Answer
> 5 votes
**It depends on whether you want your NPCs to act as a collective or to act as individuals.**

In the game I am developing at the moment I decided to control all AI objects are controlled by one central AI Controller. This has the advantage that it's much easier to implement cooperative behavior between the AI agents. When the AI controller is responsible for all agents and not just for one, it can make much better strategic decisions.

An example is when there are multiple areas which require protection by the AI agents. When one area has less defenders than the other, the AI controller can pick specific agents and send them to defend it. But when each agent makes its own decisions, it is hard to ensure that not all agents decide to relocate to the new weakpoint simultaneously or none at all decide to do so.

On the other hand, you might want to have an AI which is less challenging through good organization and behaves more realistically like individuals. Individuals can't communicate and coordinate in real-time with all others. They don't have access to all information available to their faction, and exchange information by communicating. They make their own decisions which might be suboptimal due to not having all relevant information.A stealth-based game, for example, relies on the mechanic that all the guards don't immediately become aware that one of their comrades just got his throat slit by the player. That might be a weakness of the AI from the strategical point of view, but it makes the antagonists behavior much more realistic which can result in a more statisfying experience. In such a game each agent should have its own AI object.

# Answer
> 2 votes
First, what is DF? I can name a handful of games that might be called DF =)

So many ways to organize, let's call the objects Soldiers so this reads better.

1) One AI that maintains all states internally, when a new Soldier is created it asks the AI to create a state setup for it; the soldier is controlled by the AI and matches its animations and all that to what the AI says that it's doing right now. Pro: AI has full control, data is localized, tweaking is centralized, soldier is basically just a playback mechanism; Con: custom types pollute the generic handlers.

2) One AI and the soldiers carry around their own state as their class. Pro: less maintenance work for the main AI, soldiers can customize their state changes locally, Con: AI has to be more complex to handle unexpected inputs from soldiers, behavior changes have to be made through all soldier classes that work with state.

Pro to both of the above: coordinated soldier activity is easy.

3) Localized AI for each soldier, probably descended from an AI or includes one. Pro: easy to customize behavior without having to touch both local and AI code, Con: soldiers working together will be difficult/complex to make happen, making global changes to how AI works will involve many classes.

Assuming that you really, truly need each and every unit to be independent and act on its own like the special snowflake that it is, then probably #3 is a better option. I suspect, however, that what you really want is for each unit to act on local state but still under global guidelines, in which case #1 or #2 might work better.

I personally prefer #1, but thats' because I like to build simulations where unit "type" determines activity and it makes the most sense and is easier to maintain.

# Answer
> 1 votes
For many objets which share some common datastructures the flyweight pattern is ideal.

---
Tags: ai, performance
---


# Question
Title: Is using Box2D for simulating gravity "in space" a good idea?
I'm attempting to write a simulation of a solar system of planets in 2D space that are attracted to each other through Newton's law of universal gravitation.

I know that it is possible to simulate this in Box2D by applying forces between each body in the system each frame, however I've read that Box2D is tuned for objects between 0.1m and 10m - In my simulation I want to be able to simulate the motion of large and small bodies (e.g. planets and artificial satelites).

When such large scales are involved is using Box2D (or an alternative 2D physics engine) to simulate the gravity between bodies in this way a good idea (I know I can scale the system, e.g. so that the sun has a diameter of 10m), or am I better off doing this myself?

# Answer
If you can write an n-body simulation yourself, then it will ultimately give you significantly more control over the accuracy of the simulation. Is the goal of your simulation performance, or accuracy? Box2D is designed to be a real time physics engine, so it is geared more towards high performance simulations, meaning it will make assumptions where necessary to provide the best performance without sacrificing too much precision. You will be able to make it work, but it simply depends on what your goals are.

*edit* this is a characteristic that is true of all real time physics engines. I have found myself encountering this problem over and over when trying to use a physics engine for something that is a bit unorthodox or simply not what it was intended for.
> 0 votes

---
Tags: 2d, physics, box2d
---


# Question
Title: How to let game characters enter existing 3D buildings model in my own game?
I want to use ShiVa 3D game engine to build a 3D RPG game. And I want to load other people's 3D models into my game so that I wouldn't need to draw these things myself.

Here's a building model I loaded in 3ds Max, I don't know if I loaded this model in game engine, can my character enter this building and see the decoration inside? How can I verify this?

https://i.stack.imgur.com/j4MXB.png

And if I cannot let my character enter this building, is there any resources that I can use on the Internet?

Thanks in advance.

# Answer
> 0 votes
Loading 3D models is a pretty standard feature of game engines, and any engine worth its salt will be able to load at least a few formats, whether or not it is a proprietary format, or a common format such as 3DS/FBX/MB. Check the documentation you have for loading static geometry, and what formats are supported. The biggest issue you will have is going to be collision mesh generation. Depending on what your engine supports, it may load the entire model as one large object, and generate a single collision primitive for the entire building, at which point walking inside it wouldn't work. If the parsing system loads and generates the building on a per object basis, then you can get the ability to enter the building. This is also dependent on how the model was constructed in the editor (3ds max/maya/etc).

---
Tags: models, 3dsmax
---


title: How to do simple bump mapping

text:
# Question
Title: How to do simple bump mapping
I'm trying to do bump mapping, and I'm getting fairly close at achieving my goal. I miss one crucial piece of my puzzle to have bump mapped effect in my scene; I need to transform the normals from my bump map to match the direction my faces are pointing.

This is my scene rendered with my vertex normals:

This is my scene rendered with the bump map:

The last image is wrong, because all samples from the bump map are rendered relative to as if they are pointing upforwards from the ground. What I need to do, is transform the samples from the bump map to be relative to the face normals.

Now, I have tried researching how to achieve this for a while - I've been told that if I create a TNB matrix, and multiply the sample with it - things should behave like I want. This is however not the behaviour I am getting.

This is my vertex shader:

```
uniform mat4 u_projectionMatrix;
uniform mat4 u_viewMatrix;
uniform mat4 u_modelMatrix;
attribute vec3 a_position;
attribute vec2 aTextureCoord;
attribute vec3 aNormalCoord;
attribute vec3 aTangentCoord;
attribute vec3 aBitangentCoord;
varying vec2 vTextureCoord;
varying vec3 vNormalCoord;
varying vec3 vVertexCoord;
varying mat3 vTNBMatrix;

void main()
{
    vec4 pos = vec4(a_position, 1.0);
    vTNBMatrix = mat3(
        aTangentCoord,
        aNormalCoord,
        aBitangentCoord
      );

    gl_Position = u_projectionMatrix * u_viewMatrix * pos;
    vTextureCoord = aTextureCoord;
    vNormalCoord = aNormalCoord;
    vVertexCoord = a_position;
}

```

And this is my fragment shader:

```
varying vec2 vTextureCoord;
varying vec3 vNormalCoord;
varying vec3 vVertexCoord;
varying mat3 vTNBMatrix;

uniform sampler2D mytex;
uniform sampler2D mynormal;

void main()
{
    vec3 nt = normalize(texture2D(mynormal, vTextureCoord.st).rgb * 2.0 - 1.0);

    vec3 lightpos = vec3(15.0, 26.5, 0.5);
    vec3 L = normalize(lightpos - vVertexCoord);

    vec3 finalNormal = nt * vTNBMatrix;

    vec3 ld = vec3(1.0, 1.0, 1.0) * max(dot(finalNormal, L), 0.0);

    ld = clamp(ld, 0.0, 1.0);

    gl_FragColor = vec4(texture2D(mytex, vTextureCoord.st).rgb * ld, 1.0);
}

```

Which are giving me the following, undesireable result:

Would anyone be so kind and give me some pointers at what I'm doing wrong?

Update:

These are the textures I'm using for this

Normal map:

Texture:

# Answer
Your problem is in your Light vector calculation.

```
vec3 lightpos = vec3(15.0, 26.5, 0.5);
vec3 L = normalize(lightpos - vVertexCoord);

```

Here `lightpos` is in World space, whilst `vVertexCoord` in is Object space. You need all your operands in the same space.

Furthermore your *TBN* matrix(its not TNB) is wrong., it should be as follows:

```
mat3 TBNmatrix = transpose( mat3( Tangent, Bitangent, Normal ) );

```

This is the transformation from Tangent space to Eye(camera) space. but we need the inverse of this transform, because we want to transform from eye space to tangent space(because the textured normal is in tangent space). To do this we can transpose it to get the final matrix we want.

Additionally you need to transform the Light vector from Eye space to Tangent space too. Here is the final shader code to clarify what I mean(I took it from my working project, so it should be correct ). It moves most of the work to the Vertex shader.

Vertex:

```
uniform mat4 u_projectionMatrix;
uniform mat4 u_viewMatrix;
uniform mat4 u_modelMatrix;
uniform vec3 W_LightPos;

attribute vec3 in_Position;
attribute vec2 in_TexCoord;
attribute vec3 in_Normal;
attribute vec3 in_Tangent;
attribute vec3 in_Bitangent;

varying vec2 ex_TexCoord;
varying vec3 ex_LightVec;

void main()
{

    mat4 MVMatrix = u_viewMatrix * u_modelMatrix;
    mat4 MVPMatrix = u_projectionMatrix * MVMatrix;
    //Normalmatrix should be passed as uniform, calculated on clientside(in your program)
    mat3 NormalMatrix = mat3( inverse( MVMatrix ) );
    vec4 E_VertexPos = MVMatrix * vec4(in_Position, 1.0);
    vec4 E_LightPos  = u_viewMatrix * vec4(W_LightPos, 1.0);
    vec3 E_LightVec  = vec3( E_LightPos - E_VertexPos );

    vec3 E_Normal   = normalize( NormalMatrix * in_Normal );
    vec3 E_Tangent  = normalize( NormalMatrix * in_Tangent );
    vec3 E_BiTangent = normalize(cross( E_Normal, E_Tangent ));

    // Eye -> TBN matrix
    // no need to inverse, transpose will do as we wont do non-uniform scaling
    mat3 E_TBN = transpose( mat3( E_Tangent, E_BiTangent, E_Normal ) );

    vec3 T_LightVec = normalize( E_TBN * E_LightVec );
    vec3 T_Normal = normalize( E_TBN * E_Normal );

    ex_LightVec = T_LightVec;
    ex_TexCoord = in_TexCoord;

    gl_Position = MVPMatrix * vec4(in_Position, 1.0);
}

```

Fragment:

```
uniform sampler2D DiffuseMap;
uniform sampler2D NormalMap;

attribute vec2 ex_TexCoord;
attribute vec3 ex_LightVec;

void main()
{
    vec3 DiffuseColor = texture2D( DiffuseMap, ex_TexCoord ).rgb;

    //get normal from map, and rescale from [0,1] to [-1,1]
    vec3 Ntex = texture( NormalMap, ex_TexCoord ).rgb;
    N = Ntex*2.0 - 1.0;
    N = normalize( N );
    vec3 L = normalize( ex_LightVec );

    float LambertFactor = max( dot( N, L ), 0.0 );

    out_Color = vec4( DiffuseColor*LambertFactor, 1.0 );
}

```
> 4 votes

---
Tags: opengl, glsl, normals, normal-mapping
---


title: Shaders and Performance

text:
# Question
Title: Shaders and Performance
I'm coding my first Shader in my little game engine, and I have some questions about it's performance and common approaches.

1. Is the Shader code processed by the video card instead of the PC processor? Just so I know if it's possible to share some calculations to save some processor power.
2. Generally, should I do the math calculations in my code or the Shader? I could calculate them all (lightning for example) and just send the final values to be multiplied/used to the Shader, but what's the best approach?
3. Shaders as far as I could understand are the main party responsible for visual effects, so for example, if I want to add a "blur" effect to only one object on screen, should I use an if/switch statement in the Shader or should I have different Shader/ProgramIDs and I just switch the call **glUseProgram(programID)**?

Sorry if some questions seems stupid, and thanks for your time!

# Answer
Shader code is uploaded to the video card and compiled by it, usually at the beginning of your program. The video card uses one of it's hundreds (or thousands) of cores to run through your shaders for each vertex or fragment (etc).

You should avoid doing work multiple times. If you can calculate something once on the CPU and make the calculation available to the shader, that's a lot better than asking the shader to calculate it multiple times.

Conditional logic (loops, if statement, etc) can cause some really nasty performance hits in your shaders, so avoid using them whenever you can. I would expect you to be changing the shader program many times as you draw a scene.
> 4 votes

# Answer
For performance issues, you might want to check out the AMD GPU ShaderAnalyzer. It's free software, and helps you see the bottleneck of your shader, as well as approximate performance with ATI/AMD cards. I don't know if it supports Nvidia cards though.
> 2 votes

---
Tags: opengl, shaders
---


title: Black bars on 720p emulator?

text:
# Question
Title: Black bars on 720p emulator?
I'm making a game for Windows Phone 8 using XNA 4.0 in Visual Studio express 2012. I'm trying to add a background image to the game with a size of 1366x768 (as I believe WP8 only supports up to 720p). Everything stretches well on the other emulators (WVGA and WXGA) until I use the 720p emulator and I get black bars on the sides:

How can I fix this, or is this normal?

This is all the code I have used so far:

```
GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    Texture2D Background;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";

        graphics.SupportedOrientations = DisplayOrientation.LandscapeLeft | DisplayOrientation.LandscapeRight;

        this.graphics.IsFullScreen = true;

        // Frame rate is 30 fps by default for Windows Phone.
        TargetElapsedTime = TimeSpan.FromTicks(333333);

        // Extend battery life under lock.
        InactiveSleepTime = TimeSpan.FromSeconds(1);
    }

    /// <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

        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);

        Background = Content.Load<Texture2D>("SkyBackground");

    }

    /// <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
    }

    /// <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();

        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)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        // TODO: Add your drawing code here
        spriteBatch.Begin();
        drawBackground();
        spriteBatch.End();

        base.Draw(gameTime);
    }

    private void drawBackground()
    {
        spriteBatch.Draw(Background, GraphicsDevice.Viewport.Bounds, Color.White);
    }

```

# Answer
> 4 votes
It looks like XNA games are always clamped at a maximum resolution of 800x480; even changing the `PreferredBackBufferWidth` and `PreferredBackBufferHeight` parameters doesn't prevent it from using a scaled-up + letterboxed framebuffer.

# Answer
> 0 votes
I've run into this problem before and I've described how to solve it (or to better phrase it, how to work around it) on Nokia Community Wiki article: Fullscreen XNA games on Windows Phone 8 devices.

r2d2rigo is right, you need to change aspect ratio when running on WP8 devices.

---
Tags: xna, c#, windows-phone-7
---


# Question
Title: Is it possible to use industrial models in games?
Now days major of models in games only have outward appearance. E.g. autocars in action games usually have chassis, shell, tires. Some of them also have seats designed. But rarely one has engine, bearings or gears. So I'm curious about **whether industrial models can be used in games**?

# Answer
> 4 votes
As long as they're saved in a format which can be read by the game engine, industrial models can be used in games like any other model. Of course, Rendering all the extra faces you won't normally see (e.g. parts on the inside) will have an impact on performance.

Also, while it certainly would be cool to have e.g. the results of a car crash calculated with realistic elastic and plastic deformations (e.g. using FEM), I don't know of any current game doing this at industrial level detail (again, due to performance issues).

Industrial simulations are often executed on specialized server clusters and still take up to multiple days, if not weeks.

# Answer
> 4 votes
It's possible, but not practical. There's no reason to model the inner workings of a car in game. If you want to make the industrial specs available to the user, you can provide them in other ways.

For example, if you wanted the user to be able to print out the specs, you would provide blueprints in the appropriate format along with the game.

There's also the level of detail route available. You can use a simpler model for when the car is racing around in game, and use a highly detailed model for when the user is looking at their car in the garage.

All in all, like many things in life, there's a balancing act between two desirable features, and you need to find the balance between them that works for you. In this case you need to balance realistic models with performance.

# Answer
> 2 votes
I would say yes, but could only imagine a performance issue. Typically, you want your models to be as simple as possible. Adding hidden features to models requires the application (game) to think more and harder.

---
Tags: 3d, models
---


title: Level editors compatible with MonoGame?

text:
# Question
Title: Level editors compatible with MonoGame?
I'm thinking about a future project using MonoGame and it seems there are no level editors that outright support it, though obviously there are those for XNA that may possibly be compatible. So I suppose this is a two-part question; are there any existing level editors that can be made work with MonoGame, and also is it possible to create levels that are then inbuilt into the codebase and thus work cross-platform (for example, Android or iOS, or does the level editor have to support the platform)?

Thanks in advance.

# Answer
tIDE can be ported to MonoGame quite easily.

Also this discussion might be of interest to you.
> 1 votes

# Answer
I agree that you will have to write your own level editor, or at least a portion of it. Unity3D is a very spectacular program, in that it is an engine, but also a generic and flexible platform for creating level editing solutions. Myself, and others I work with have used Unity3D to develop levels for various 3D platforms such as the Xbox, and we are currently using it to push content into the Havok Vision engine (post development goal). You will still have to design the constraints, formats, and loading procedures yourself though.
> 0 votes

---
Tags: c#, monogame
---


title: How to do Triplanar Texturing

text:
# Question
Title: How to do Triplanar Texturing
Ok maybe i'm missing something because its getting late and i've been programming now for about 72 hours straight (minus a nap or 2) ...

I'm trying to write a shader for unity that will apply triplanar texturing to a mesh, here's my shader code ...

```
Shader "My Shaders/TriPlanar" {
    Properties {
        Tex1 ("Texture 1", 2D) = "white" {}
        Tex2 ("Texture 2", 2D) = "white" {}
        Tex3 ("Texture 3", 2D) = "white" {}
    }

    SubShader {
        Pass {
             CGPROGRAM
                #pragma target 3.0
                #pragma glsl
                #pragma vertex Vert
                #pragma fragment Frag
                #include "UnityCG.cginc"

                sampler2D Tex1;
                sampler2D Tex2;
                sampler2D Tex3;

                struct data
                {
                    float4 position : POSITION;
                    float3 normal;
                    float4 uv : TEXCOORD0;
                };

                data Vert(appdata_base v)
                {
                    data res;
                    res.position = mul( UNITY_MATRIX_MVP, v.vertex);
                    res.normal = v.normal;
                    res.uv = v.texcoord;
                    return res;
                }

                float4 Frag( data input ) : COLOR
                {
                    float4 result;

                    float norX = abs(input.normal.x);
                    float norY = abs(input.normal.y);
                    float norZ = abs(input.normal.z);

                    float total = (norX + norY + norZ);
                    norX /= total;
                    norY /= total;
                    norZ /= total;

                    // get sample from tex1 and apply norX amount to pixel color
                    float4 texXZ = tex2D(Tex1, input.uv.xz);
                    float4 texXY = tex2D(Tex1, input.uv.xy);
                    float4 texYZ = tex2D(Tex1, input.uv.yz);
                    result = (texXZ * norX);

                    // get sample from tex2 and blend norY amount
                    texXZ = tex2D(Tex2, input.uv.xz);
                    texXY = tex2D(Tex2, input.uv.xy);
                    texYZ = tex2D(Tex2, input.uv.yz);
                    result += (texXY * norY);

                    // get sample from tex3 and blend norZ amount
                    texXZ = tex2D(Tex3, input.uv.xz);
                    texXY = tex2D(Tex3, input.uv.xy);
                    texYZ = tex2D(Tex3, input.uv.yz);
                    result += (texYZ * norZ);

                    return result;
                }
            ENDCG
        }
    }
}

```

The problem is that I only get 1 pixels worth of sample from the texture so I end up ultimately just "colouring" the verts instead of actually texturing them.

How do I tell my shader to build a colour that results in the texture being drawn not just 1 corner pixels worth of it?

EDIT:

The code in the shader is an implementation of a vertex and fragment but the fragment part came from a pixel shader ... i don't understand the difference there (my first problem)

I can't say i've ever written a fragment shader before (a second problem)

Also i'm not setting any uv's in my cpu code (a problem when I come to use my shader but i'll face that later) ... odd that I get anything at all to be honest, however I'm applying this to a cube game object generated by unity and I get strips of texture so i can't be that far off.

# Answer
> 1 votes
Um ... well ... it's a pretty basic example of triplanar texturing but it works ...

```
Shader "My Shaders/TriPlanar" {
    Properties {
        Tex1 ("Texture 1", 2D) = "white" {}
        Tex2 ("Texture 2", 2D) = "white" {}
        Tex3 ("Texture 3", 2D) = "white" {}
    }

    SubShader {
        Pass {
             CGPROGRAM
                #pragma target 3.0
                #pragma glsl
                #pragma vertex Vert
                #pragma fragment Frag
                #include "UnityCG.cginc"

                sampler2D Tex1;
                sampler2D Tex2;
                sampler2D Tex3;

                struct data
                {
                    float4 position : POSITION;
                    float3 normal;
                    float4 uv : TEXCOORD0;
                };

                data Vert(appdata_base v)
                {
                    data res;
                    res.position = mul( UNITY_MATRIX_MVP, v.vertex);
                    res.normal = v.normal;
                    res.uv = v.texcoord;
                    return res;
                }

                float4 Frag( data input ) : COLOR
                {
                    float4 result;

                    float norX = abs(input.normal.x);
                    float norY = abs(input.normal.y);
                    float norZ = abs(input.normal.z);

                    float total = (norX + norY + norZ);
                    norX /= total;
                    norY /= total;
                    norZ /= total;

                    // get sample from tex1 and apply norX amount to pixel color
                    float4 texXY = tex2D(Tex1, input.uv.xy);
                    result = (texXY * norX);

                    // get sample from tex2 and blend norY amount
                    texXY = tex2D(Tex2, input.uv.xy);
                    result += (texXY * norY);

                    // get sample from tex3 and blend norZ amount
                    texXY = tex2D(Tex3, input.uv.xy);
                    result += (texXY * norZ);

                    return result;
                }
            ENDCG
        }
    }
}

```

Now I just need to add in things like variances for lighting and such :)

I hope this is helpful to someone out there getting to grips with triplanar texturing :)

---
Tags: unity, shaders, cg, fragment-shader
---


# Question
Title: The game-server model to handle user actions
I'm starting to work on a mobile game that will have a server-side part (to handle user's interactions between them) and, of course, the client (game itself) part. It's not meant to be a browser game and the goal is for it to run even when not connected to the internet.

I would want to have the network-requireing functions disabled when the network isn't accessible (so user can't send a message to another user when offline, obviously, or trade with other users) but when the network becomes available, the game should sync with the server.

Now, my main concerns are:

* how to handle the syncing part? What would be the best way to handle it? Should I just send full game state from the device to the server? This way if a user plays the game on 2 different devices, one of them can get out of sync, but lets say I can live with that...
* how to ensure there's no "cheating"? I mean, having some kind of server API exposed, would there be a possibility that someone makes a request that creates some powerful item on the server for him, right?

What would be best practices to approaching thos

# Answer
Offline play means that the players can cheat as much as they want. The only way to prevent cheating is to calculate any mechanics which are relevant for the gameplay on the server.

That means you have two very conflicting goals here: A) to let the player play while being offline and B) to prevent them from cheating.

The only compromise between both goals would be to limit the options of the player severely in offline mode. Any decision by the player which has effect on the gameplay would have to be queued, and the player wouldn't receive the results of their actions before the network connection is back on and the server can tell them the results.
> 2 votes

---
Tags: mmo, client-server
---


# Question
Title: Generate different types of enemies with different randomness
What I want - I want to have some magic function `getEnemyType(currentLevel)`, which will return, for example, a number. Number is enemy type, let's say, there are ten (10) types. 1 - the easiest, 10 - the hardest. I can't even find the idea, where to dig, to get such algorythm: I give this magic function current level number and it calculate suitable enemy type with increasing and decreasing chanse of getting hard or easy enemy. Example:

* Level 1: function will generate random type from array of one element: \[1\], okay
* Level 2: generating random types from such set: \[1,1,2\], reason is to have more easy and less hard enemies.
* Level 3: \[1,1,1,2,2\]
* ...
* Level 50: \[1,7,7,9\] (more 7s, less 9s for challenge, and little number of 1s for fun)
* Level 10000: \[1, 10, 10, 10, 10, 10, 10\]

Ideally game must be infinite, so I can just add enemy types to suit increasing difficulty. Is this real? :)

# Answer
> 0 votes
One solution for solving this problem:

Python (pseudo) code:

```
def getEnemyTypesByLevel(Level):
   # max is maximal Difficulty
   Options = [
      {"Count":1, "Max":1, "Exponent":1.0},
      {"Count":3, "Max":2, "Exponent":1.2},
      {"Count":5, "Max":2, "Exponent":1.3},
      ...
      {"Count":8, "Max":10, "Exponent":42.0}
   ]

   DifficultyArray = []

   CurrentOption = Options[Level]

   Base = 1.5

   i = 0
   while i < CurrentOption["Count"]:
      Difficulty = (random.random() * Base) ** CurrentOption["Exponent"]
      Difficulty = max(CurrentOption["Max"], Difficulty)

      DifficultyArray.append(Difficulty)

      i += 1

   return DifficultyArray

```

instead of using the Exponent function you can use logarithmic functions or any arbitary function, depending on your wishes.

I hope this helps.

**Edit 1**: Added the Base constant/value, without it it doesn't really do what you want.

# Answer
> 1 votes
It might not be exactly what you are looking for, but I'd suggest attaching the chance of appearance to the actual enemy type. That way you can fine tune it a bit more without needing to modify the actual algorithm, for example you seem to want enemy type 1 to appear at all levels, but not type 2, 3, 4 etc.

EG

```
struct EnemyType
{
   unsigned int id; //Generic id number
   int baseLevel; //The player level where this enemy starts to appear but is rare.
   int commonLevel; //The player level where the enemy becomes common.
   int rareLevel; //The player level where the enemy stops being common again.
   int extinctLevel; //The player level where the enemy stops appearing.
}

```

Then maybe assign a weight to each enemy type based upon the player level:

```
float getWeight(EnemyType enemyType, int playerLevel)
{
   if(playerLevel < enemyType.baseLevel ||
      playerLevel >= enemyType.extinctLevel) return 0.0f;
   else if(playerLevel >= enemyType.rareLevel ||
           playerLevel < enemyType.commonLevel) return 0.5f;
   else return 1.0f;
}

```

Any weighted random selection algorithm should then finish the job, but the probability of getting any one enemy type returned from getEnemyType() should be:

```
 weight of type / total weights of all types

```

This is a bit rough, as there are many good ways of implementing such an algorithm. But the main point I'm trying to make is specify the probability changes on the enemy type instead of in the actual selection algorithm.

EDIT: Here's an example of the selection algorithm (psuedocode):

```
//Initialize these somewhere, maybe use a vector or whatever your language's equiv is.
const unsigned int numEnemyTypes;
EnemyType enemyTypeArray[];

EnemyType getEnemyType(int playerLevel)
{
   floatrandom = someRNG(); //Gives a number between 0 and 1.

   //Find total weights
   float totalWeight = 0.0;
   for(int i = 0; i < numEnemyTypes; i++)
   {
       EnemyType enemyType = enemyTypeArray[i]
       totalWeight += getWeight(enemyType, playerLevel);
   }

   //Find enemy type
   float range = 0.0;
   for(int i = 0; i < numEnemyTypes; i++)
   {
       EnemyType enemyType = enemyTypeArray[i]
       range += getWeight(enemyType, playerLevel)/totalWeight;
       if(range >= random) return enemyType;
   }
}

```

Essentially each enemy type gets a portion of the number range between 0 and 1, if the random number falls into that enemy type's range that is the enemy type selected. EG if you have 2 enemies, one with weight 0.5 and one with weight 1.0 then the first will have the range 0.0 to 3.33 while the second will have the range 3.33 to 1.0. If you add a third enemy with weight 1.0 then the ranges will look like:

0 to 0.2 (0.5 / 2.5 = 0.2) 0.2 to 0.6 (1.0 / 2.5 = 0.4) 0.6 to 1.0 (as above)

The code above isn't exactly optimal but hopefully it gives an idea of what I am talking about.

---
Tags: random
---


title: Creating stable tentacle structures

text:
# Question
Title: Creating stable tentacle structures
I am using verlet integration to simulate some tentacles. So far it works great and I am satisfied with how it looks in general. Here is how a tentacle is built:

The very stiff sticks are colored red, in addition I added angular constraints of 180° in order to keep everything together.

But still, sometimes this happens:

When forces are too big at the peak, it flips around and gets stuck in a very ugly state.

Of course I could increase the number of iterations for satisfying the constraints, but then the tentacles get too stiff and the performance suffers.

What can I do about this? Some ideas:

* add more points at the peak
* more constraints overall
* limit possible forces
* maybe rethink my tentacle design completely?
* detect flip over and undo it

# Answer
Rather than building a solid object for your tentacles, I would suggest instead using a single linear chain — a 'skeleton' for the tentacle — and then procedurally wrapping a descending sequence of trapezoids around it, out to the tip. Use the local orientation information to define crossbars at each vertex (e.g., normal to the average or possibly weighted average of the two skeleton segments that share that vertex) and then define the 'body' of the tentacle using quadrilaterals built from one crossbar to the next all the way out to the tip. You'll want to use slightly more clever physics for your skeleton — in particular, the curvature constraints should be tighter near the base of the tentacle than at the tip, to account for the thickness at the base — but this approach should still give you realistic motion without having to worry about keeping the outer structure consistent. With a little care you can even use an approach like this to simulate contact with the tentacle, by 'backsolving' the force on the surface of the tentacle to an appropriate force or impulse on the tentacle's skeleton.
> 2 votes

# Answer
Tentacles work in nature (and robotics) because of muscles inside, this means that each segment or three is only locally affected by a small number of forces. It sounds like you have a setup where all the force starts at the base and propagates outwards, which gets you a whip instead of a twisting tentacle.

You may want to build a system with small forces between nodes that will mimic muscles, then have a "brain" animate the forces by propagating over time.
> 2 votes

---
Tags: physics, libgdx, rigid-body-dynamics, mesh
---


title: Overload C++ functions in lua

text:
# Question
Title: Overload C++ functions in lua
I have had a look around but I believe this to be impossible due to compile time of c++.

However is it possible to have a class registered in lua and c++ that has a overload update function which I can then overload within lua rather than c++.

If this is not possible would it be viable to just have a register function for the class and then register the lua function with.

so for example i would have:

```
local myclass = RegClass.new()

function update()
   io.write("Update")
end

myclass:RegisterFunction(Reg.Update, update)

```

Another question I have is how would I go about registering a static class or a predefined class within lua (just a link with any information will be helpful).

Thanks for any help or device Dekowta

# Answer
> 2 votes
The short answer is (probably) no, if you're expecting to call update() from C++ code. I'll go into some depth for you:

The C++ compiler will call an overloaded function only if the base class is declared virtual. Behind the scenes, it creates a vtable, which it uses to look up which function to call when appropriate. The vtable is created implicitly by the compiler, and you have no direct means of interfacing with it (practically speaking). Here's an example that doesn't use the keyword *virtual*:

```
// some class declarations
class Foo {
    void call() { printf( "Foo::call()" ); }
};

class Bar : public Foo {
    void call() { printf( "Bar::call()" ); }
}

// somewhere in code, perhaps main
Foo* foo = new Bar();
foo->call();

```

In this case, you would actually see "Foo::call()" because you're calling call() on an instance of Foo, and call() was not declared virtual.

Here's a crude way you could call Bar::call():

```
Bar* bar = (Bar*)foo;
bar->call();

```

Here you would see "Bar::call()". As you can see, the compiler is directly calling the function for the type which you are using (we changed the type to Bar by casting in this example).

Declaring Foo::call() virtual will fix this. Revise our declaration for Foo:

```
// some class declarations
class Foo {
    virtual void call() { printf( "Foo::call()" ); }
};

```

And try using our inheritance again:

```
// somewhere in code, perhaps main
Foo* foo = new Bar();
foo->call();

```

Now you would see "Bar::call()". Since we declared Foo::call() virtual, whenever the compiler sees an instance of Foo (regardless of it's real type), it will look at the vtable for the object to determine which function it should actually call.

So lets take a look at how this relates to Lua. I'm not sure how you're integrating your C++ code with Lua, but I can probably safely assume a couple things:

1) *local myclass = RegClass.new()* is actually creating a new instance of your class, and storing the pointer in the metatable of myclass (probably as userdata).

2) The implementation of update() in C++ of RegClass (or one of its base classes) is declared virtual.

What you want to do will work, provided one of the two conditions:

1) The concrete implementation of update() calls into Lua. To work with your code sample, it would probably need to keep up with the Lua object itself, and do some tedious stack manipulation in order to provide the 'self' object and/or the function to be called. I give a rough outline of how this could work below. If you're using a Lua binding framework, this may be handled for you.

2) You're calling from Lua, in which case none of the C++ stuff even matters.

Specifically, here is a case that won't work unless your framework does a lot of magic behind the scenes:

```
// in C++
class Foo {
    Foo() { ... };
    virtual void call() { ... };
};

-- in Lua
local foo = Foo:new();
foo.call = function( self )
    print( "hello from Lua" )

```

In order to "glue" these together, the implementation of call() that is called at runtime in C++ would need to actually call into Lua with references to the "local foo" object that's created, as well as the "foo.call" function. This can certainly be done, and there are quite a few frameworks out there that help manage some (or all?) of the gory details.

Here's an example that might get you started thinking down the right track:

```
// C++
class LuaFoo : public Foo /* using Foo defined directly above */ {

    LuaFoo( lua_State* L ) {
        // TODO:
        // pull a reference to the created class out of the lua state
        // store it as a member variable of our LuaFoo class
    }

    virtual void call() {
        // TODO:
        // get the lua state from somewhere, being wary of threading issues, and the state of the lua stack
        // push stuff onto the lua stack, namely the reference to the object in lua
        // call the lua function
        // handle errors and/or return values
        // be sure that the lua stack is left in the same condition (depth) that you got it in
    }
};

// somewhere else (still in C++), where we initialize our Lua environment:
// TODO:
// push a table called LuaFoo, or just Foo if you want to bury the Lua part of the name
// set it up so that calling LuaFoo:new() will invoke the constructor above

-- in Lua, create our actual object:
local foo = LuaFoo:new()
foo.call = function( self )
    printf( "hello from Lua!" )

// and finally, back in C++, the money shot:
Foo* foo = // somehow we get a reference to the object we created in Lua, perhaps it's in a big list with lots of other Foo's
foo->call(); // we'd see "hello from Lua!" here

```

If you don't find this particularly encouraging, take a look at some of the Lua binding frameworks out there which may help take care of some or all of these details. In any case, hopefully it gives you some idea of what's actually going on.

---
Tags: c++, entity-system, lua, callbacks
---


title: Implementing a homing missile

text:
# Question
Title: Implementing a homing missile
I'm having some trouble implementing a homing missile that satisfies what I'm looking for. I have already tried the Seeking and Arrival behaviours described in this link, but none of them were what I wanted. With Seeking, it winds up orbiting the object indefinitely, and Arrival is simply unavoidable.

I'm aiming for something similar to the missiles of this video and the ones of Super Meat Boy \- avoidable missiles that nevertheless do the job. It actually looks like a mix of Seek and Arrival, or maybe even the Path Following behaviour described in the first link.

This is my idealized behaviour, with a user-controlled target:

Can I have some insight on the matter? I know that questions regarding homing missiles have popped up quite often around here, but I feel that I'm missing something basic. The first video has an explanation from its creator in the second answer of this question, I didn't quite grasp it, though.

# Answer
What you have to do is **estimate the future position of the moving target and steer towards that**.

Here is bobobobo's super 5 step simplified process

## 1. Initial picture of the system.

---

## 2. Really what we are doing here is subtracting the rocket's velocity from both bodies in the system, so the rocket is effectively "stationary", and the target is moving

---

## 3. vc is really *the scalar speed at which the gap between the 2 bodies is closing*.

---

## 4. Must not have a=0! If a=0, then eta=inf, which makes sense

## Derivation of `eta`: Sorry, I lied in the image above. The `eta=` formula comes from:

---

Some C code:

```
Vector3f exactTrackHeading( Vector3f mePos, // your pos
      Vector3f meVel, // your speed
      Vector3f target,  // position of what you're following
      Vector3f velTarget, // velocity of your target
      float a, // your capability to accelerate.
      float &eta //, // impact time
      //Vector3f& impactPos // exactly where you'll impact (if needed)
    )
{
  if( !a ){
    error( "predictPos: accel cannot be 0" ) ;
    a=EPS_MIN;
  }
  Vector3f toFollow = target - mePos ;
  float d = toFollow.safeNormalize() ;

  // his speed relative to me
  Vector3f vTarget = velTarget - meVel ;

  // Find the component of -vTarget along toFollow
  float v = (-vTarget).dot( toFollow ) ;

  // TIME ESTIMATE TO REACH MY TARGET
  eta = -v/a + sqrtf( v*v/(a*a) + 2*d/a ) ;
  // Use ETA to estimate WHERE we should aim.

  Vector3f impactPos = target + vTarget * eta ;

  return impactPos - mePos ; // ME TO IMPACTPT is suggested heading.
  // len of this is dist to that target
}

```
> 8 votes

# Answer
Try increasing the turn speed or slowing the missile based on flight time or distance to the target. Those would help prevent orbiting. (some of the comments in the last link hinted at this and is kind of depicted in your illustration)

EDIT: could also increase turn speed based on the velocity of the missile (probably more realistic but could still end up orbiting, haven't tried to code any of this yet though)
> 0 votes

---
Tags: xna, physics, steering-behaviors
---


title: change bullets java

text:
# Question
Title: change bullets java
i need some help with java. i am creating a game where i have a player and he shoot bullets. u can also change u types of bullet. bullets are just fillOval. and change types of bullets is different colo.

i have created a class bullet. which just create one bullet. than if player hit space bar. than create a bullet and store in arraylist.

```
if(space)
{
    bulletObject = new Bullet();    //create bullet
    bulletStore.add(bulletObject);  //store in arraylist
}

```

now to change bullets. i have create a variable call bulletName. if it has a value of 1 than its bullet type is 1. If it has value of 2 than its bullet type is 2.

if user hit 'f' key than change bullet type.

```
if(f){
    bulletName ++;  //go to next bullet type

```

}

now to draw the bullets.

```
pubic void paint(Graphics g)
{
    if(bulletName == 1)
        g.setColor(Color.green);
   if(bulletName == 2)
        g.setColor(Color.blue);
    if(bulletName == 3)
        g.setColor(Color.red);

     g.fillOval(x,y,width,height);
}

```

The problem is that if user hit space bar than it will shoot one bullet. than if user hit 'f' key than it will change color of all bullets on screen.

i want it so that it doesnt change color of bullets on screen. it only change color of bullet that are about to get shoot.change

# Answer
> 2 votes
I think this is a problem of you thinking in the wrong abstraction level.

Your `bulletName` variable is in global space (accessible to all methods), right? If it's shared among all `Bullet`s then what else would you expect but it to change all of the `Bullet`s colors?

Objects are nouns (they are things). If you already have a noun (`Bullet`), why not also give it a noun to describe its representation (a property `color`) and possibly a verb to change it (a method `setColor()`)?

That way, when you fire a bullet, you get to tell it what color it is then and there - it will be set for that object.

Let's make some pseudocode:

In `Bullet`, add a property `color`:

```
class Bullet {
    private int color;
    public void setColor(int color) {
        this.color = color;
    }
    public int getColor() {
        return this.color;
    }
}

```

Also retain your `bulletName` property but rename it to `bulletColor`. Makes more sense, right? Then to shoot:

```
if(space)
{
    bulletObject = new Bullet();    //create bullet
    bulletObject.setColor(bulletColor);
    bulletStore.add(bulletObject);  //store in arraylist
}

```

and to draw (paint is in `Bullet`, right? Then it has access to `color`):

```
pubic void paint(Graphics g)
{
    if(color == 1)
        g.setColor(Color.green);
    // ...
}

```

---
Tags: java
---


title: What is the integrator used in PhysX?

text:
# Question
Title: What is the integrator used in PhysX?
What type of integrator is used in the PhysX engine? Euler? Runge-Kutta?

I tried to look through the comments in the SDK header and source files. But, could not find any information about this.

# Answer
> 4 votes
From my research, it uses a Symplectic integrator. I found this in a paper comparing various physics simulation systems.

---
Tags: physx
---


# Question
Title: using DirectX to generate a sprite sheet
I am building a site in HTML5 for my client and it must run on the iPad/iPhone (i.e. Safari on iOS).

They want a 3D effect where they have a simple, yet, specific product they want to show on the site in 3D with user generated data as the texture.

Normally, I would use either flash/silverlight/webgl but these are not supported on iOS.

Also, CSS 3D transforms are close, but since I need a specific shape and size, creating hundreds of div elements and transforming them just wont work in the long run.

My idea, is to use server side code to generate a sprite sheet that could be used on the site to fake the 3D-ness of the object.

What I really lack is the knowledge around DirectX/OpenGL in order to automate this process.

My question is, can I use DirectX/OpenGL from a command line (or programatically) to pass is a model and textures to generate a PNG/JPG sprite sheet of a rotating object?

# Answer
Unfortunately, no. At least not in the way you propose it.

DirectX and OpenGL are not programs, but libraries you can use to develop your programs. In fact, they are quite low-level, and even seemingly simple tasks such getting a simple model to be displayed on the screen, are by far not trivial when using these libraries.

In that sense, there is no "command line version" of DirectX or OpenGL.

However, there are many rendering tools you can probably use for your purposes. If you have 3D modeling experience, then Maya, 3DS Max or Blender are all very good choices. If you don't, then Google SketchUp is very easy to learn.

All of these programs support exporting a model to a bitmap, and they probably support doing so from the command line, you should check that tool's documentation to see if it does what you want.
> 2 votes

# Answer
You can write such a tool yourself. By default, DirectX renders to a render target. This target is just a piece of memory and you can get those bytes and then save that as a file. Or you can display them on screen.

If you could set it up as a service, you could invoke the service and it would serve png images. Albeit it might be slow :)
> 1 votes

---
Tags: opengl, directx, ios, spritesheet
---


# Question
Title: Bullet physics: how to make a soft body "static" (kind of)?
I'm fairly new to Bullet and started using it a week ago. I mainly played with rigid bodies and everything works as expected but now that I also need to add soft bodies into my simulation, things got a bit complicated.

**What I want:** I have to create a simple but unrealistic scene: the main object is a deformable ball levitating at the center of the world, it does not rest on anything and only "floats" there. Then, I should be able to throw various rigid bodies towards the ball so that it deforms BUT DOES NOT MOVE.

**What I tried:** My issue is that I don't know how to make my main soft body float in the center of the scene. I tried setting the mass of each of its node to zero but then it does not deform anymore, obviously. I also changed its total mass and it gives the same result (I'm not sure if it's the same as setting all masses to 0). I also tried to give it the STATIC flag but that doesn't change anything.

**What I could try (but seems overcomplicated):** A possibility would be to hang the ball to a fixed position with a point-to-point constraint but I'm afraid that it will deform the ball and could create an unwanted swinging motion. Another idea I had is to enclose the ball into an invisible box made of planes that would keep it in the air but that would not react with other bodies (notably the rigid ones that I will throw) but I'm afraid that this solution would be cumbersome to implement and that the faces of the box would be discernible when the ball is pressed against it.

**In summary:** I need to have a spherical soft body that keep the same center. It I throw something towards it, I should see its surface riple but it should not move "globally". Is there any way to cleanly do that?

Thank you for your help!

(I asked the same question on the Bullet forum but had no answers)

# Answer
I finally found a solution.

As Roy T. mentionned, Bullet have joints that help achieve the desired result (for soft bodies only, rigid bodies rather use constraints). For examples, you can see the soft body demos bundled with the source code, especially `ClusterRobot` and `ClusterCar`.

TO solve my problem, I used a linear joint to pin the deformable sphere and an angular joint that cancels speed in order to stop its rotation.
> 1 votes

---
Tags: physics-engine, bullet-physics
---


# Question
Title: Optimize maximum performance "Frustum.contain ()" on XNA?
I wonder if it is possible to optimize the performance of "BoundingFrustum" requesting return of the visible elements that are found only on the part of the ground before the player .. Checker and not all over the field unnecessarily?

**This picture shows a Region 250X250 or 62,500 cubic! I thought it would be optimized to calculate the "Frustum" in half of the region! 31'250 cubic or less**

Here my incomplete function:

```
foreach (Octree.Node node in regions.Where( /* ? only before the player... */).Where(r => arcadia.camera.Frustum.Contains(r.boundingBox) != ContainmentType.Disjoint))
{

}

```

Here's a better picture of what I want.

Here is a complete example of the world loaded in my games! Where each region has 62,500 cubic. My problem is that if the player looks towards another region, I have to calculate my "Frustum" in four parts! Or 4 * 62'50 = 250,000 cubic cubes. And every call my function 'update ()'

# Answer
> 1 votes
I wonder why are you thinking to optimize this.. you are already using octrees which is supposed to eliminate most of the scene with a couple of tests, so the remaining frustum/bounding testing for even hundreds of objects probably wont event affect your performance unless you are wokring on a very performance critical game, so I think using octree is good enough.

Edit based on comment:

one way is to use a faster (maybe your own) method Frustum.contain(). One approach comes to mind is to use radar based frustum culling (assuming Frustum.Contain checks with every plane in the frustum (which I suppose why Frustum.contain() is not so fast in the first place. http://www.lighthouse3d.com/tutorials/view-frustum-culling/radar-approach-testing-points/

---
Tags: xna, camera, performance, frustum
---


# Question
Title: graphics.GraphicsDevice.Clear strange result (XNA)
I have such Execution:

```
graphics.GraphicsDevice.Clear(new Color(255, 0, 0, 0));

```

Alpha is 0. So why it draws me Red color?

```
graphics.GraphicsDevice.Clear(new Color(255, 0, 0, 255));

```

Also draws the same red color. Changing alpha value doesn't affects the color on the screen. Why?

# Answer
The alpha value in the backbuffer does not affect what is scanned out to the screen.

However it does affect blending. For example, non-premultiplied alpha blending is:

```
output = source * sourceAlpha + destination * (1-sourceAlpha)

```

While the above uses the **source** alpha only (giving you the "transparency" effect you expect), you can also set up the blending stage to use the **destination** alpha. Most sane blend modes only use the source alpha - but using the destination alpha lets you do some fun special effects (example).

In XNA you can change the blend function by creating an instance of `BlendState` (MSDN).

The other reason to have an alpha value for the destination buffer is if it is a render target. When you go to use that render target as a texture, the alpha values stored in its buffer will behave as you would expect for a texture.
> 3 votes

---
Tags: xna, c#
---


title: Server Based High Scores

text:
# Question
Title: Server Based High Scores
I'm currently using the following MySQL example to make a server side high score table: Unity Server Side high score

The above example allows me to create a top 5 player high score table that sorts itself based on the score amount. However, my knowledge of PHP and MySQL is limited to only that of the above example and I wish to expand upon it.

What I now want to do is create a local score amount (the score the player accumulates during game play) that is updated on my server. At the moment, the server only calls the total scores once, and I want it to be polled so that it updates the moment the player earns some points. And displays this score.

The reason for this, is because my high score, and local score, are going to be displayed on another device. Say your playing my game on a PC but the score is updating and showing you on an iPad (rubbish example, but you get the idea).

Can anyone point me in the right direction as to how I would go about doing this, using the example I've already used?

# Answer
You can implement a function that will run as a callback when the player's score changes, this function can open a socket and send the required data to the server. I don't think it is necessary to do this asynchronously since the player's score is usually an integer (4 bytes) so sending it to the server won't be a great deal (along with the bytes of the protocol you are using, if you are using one).

The only case you need to do it in async is when there are lots of people sending data simultaneously and your server doesn't have enough unused connections to accept another incoming request, thus blocking the client (your game).
> 0 votes

---
Tags: c#, unity, databases, mysql
---


# Question
Title: Pre-render 3D object from multiple angles, save as PNG
I'm looking for a tool or script that takes a 3D object (any format) and makes multiple renders of it *automatically* (using a raytracer or other high-quality offline renderer). It would then save the output as a series of PNG files.

Example: let me render a car from angles 0,90,180,270 and save the images to car0.png, car1.png, car2.png and car3.png with a single command.

Is there such a tool?

# Answer
How about POVRay? It's free and can be automated.

http://www.povray.org/documentation/view/3.6.0/792/

See this page for info on generating several different images:

http://www.povray.org/documentation/view/3.6.0/109/
> 5 votes

# Answer
Checkout Blender, it's an OSS 3D modeling and animation suite scriptable with Python
> 2 votes

# Answer
3D Studio Max ,

Maya

Both are quite expensive though
> 0 votes

---
Tags: 3d
---


title: Android game adaptative game flux

text:
# Question
Title: Android game adaptative game flux
¡Hi mates! Two friends and I are planning to code a game for Android using AndEngine GLES 2.0 Anchor but we have a concept problem, we need the game to be as adaptative as possible, I mean, if we make a new map or a video, it has to be easily included on the game, making them plugable. For example:

When the game starts, shows a video as an introduction. After that, the game loads a level. When the level is finished, loads another level which is the second part of the mision, then, shows another video as outro, then shows another video, and then loads three more levels which are another mision and so.

My idea is to have a class that queries a DB or reads an XML file to determine which is the next thing the game has to load, sequentially, every time the last thing ended.

My mates said to me that it is a bad idea, a idea that breaks with the MVC pattern, because the Controller has to know by itself programatically which is the next thing that has to be loaded, but I think that my idea fits perfect on the Model, because the Controller is only a bridge between the View and the Model and I really don't like to hard code that, because I want the game to be extensible without touching any line of logic code to do that "simple task".

My mates said that one plausible solution to make adaptative without external resources is to hard code the flux secuentially on a Map on a class with constant values only, but that invalidates their argument about "Controller has to know everything" because works so similar as my idea but only a little faster because it hasn't to be loaded from a file or a DB.

There's another better way to do what we need?

(I do not look for an easy answer, I do not want someone make my job, I'm not a lecher, If someone says me that AndEngine does it for me, but not how, I will look for that by myself, but I need some guidance, because I've never programmed a game with multiple levels or some kind of "variable flux").

Thanks every one for your answers!

(I've post this on StackOverflow also, but I've found that page that seems more specialized on game development)

# Answer
This sounds like a pretty straightforward example of a need for data driven design. Using something such as XML to represent a manifest is not uncommon or even remotely "hard coded". Either way, your game will need to parse something for a list of levels and videos that are available to it, whether that means auto identifying files in a particular folder, or using XML to parse the list at run time.

Neither of these ideas are uncommon, and it is simply up to you as to which you would prefer. Loading all the files in a folder can represent a larger risk than loading specific files listed in an xml/txt manifest.
> 2 votes

---
Tags: android
---


title: gbuffer - how to store an integer data

text:
# Question
Title: gbuffer - how to store an integer data
In a gbuffer I store a diffuse color in following texture:

```
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);

```

I want to store an integer data which represents a pixel type in channel A. Here is part of the fragment shader:

```
#version 420
in vec2 tCoord;
layout (location = 2) out vec4 diffuseColorData;
uniform sampler2D texture0;
uniform int pixelType;
void main(void)
{
    diffuseColorData.xyz = texture(texture0, tCoord).xyz;
    diffuseColorData.w = pixelType;
}

```

Is it possible ? How to decode a pixel type when reading from texture ?

**Edit**

I use a pixel type to choose a shading function (standard shading - int 1, shading with normal maps - int 2, shading with uniform color - int 3). I need to use additive blending because of multiple light sources (point lights).

I changed the code as you suggested:

```
diffuseColorData.w = pixelType / 4.0;

```

In the next fragment shader I read a data this way (I post only relevant part of the code):

```
uniform sampler2D texture2;
vec4 diffandPixelType = texture(texture2, texCoord);
vec4 diff = vec4(diffandPixelType.xyz, 1.0);
float pixelType = diffandPixelType.w * 4.0;

if(pixelType == 1)
{
    outColor = shadingfun1(/*arguments*/)
}
else if(pixelType == 2)
{
   outColor = shadingfun2(/*arguments*/)
}
else if(pixelType == 3)
{
   outColor = shadingfun3(/*arguments*/)
}

```

The code doesn't work properly and I don't know how to explain that. What is wrong ?

I found other solution which works perfectly, but it require extra integer texture in the gbuffer:

```
glTexImage2D(GL_TEXTURE_2D, 0, GL_R8I, width, height, 0, GL_RED_INTEGER, GL_INT, NULL);

//fragment shader
layout (location = 4) out int shadingData;
uniform int pixelType;
shadingData = pixelType;

//fragment shader
uniform isampler2D texture6;
int pixelType = texture(texture6, texCoord).x;

if(pixelType == 1)
{
    outColor = shadingfun1(/*arguments*/)
}
else if(pixelType == 2)
{
    outColor = shadingfun2(/*arguments*/)
}
else if(pixelType == 3)
{
    outColor = shadingfun3(/*arguments*/)
}

```

# Answer
> 2 votes
It is possible, you just need to scale it to the 0-1 range, and make sure to avoid precision issues.

For example if you have 6 pixel types, you can do

```
diffuseColorData.w = pixelType / 5.0;

```

Of course I would suggest setting up a define in the shader, possibly programatically.

When reading from the texture just do the exact opposite, multiply it by 5 and round the result to an int. You're probably safe from rounding and precision issues unless the number of possible pixel types is really high (I'd start worrying above 127).

You also need to make sure that you write each fragment exactly once (no alpha blending), otherwise you'll get some kind of interpolation between pixel types, which may not be something you want to achieve.

---
Tags: opengl, glsl, deferred-rendering
---


title: A.I. dependencies based on components

text:
# Question
Title: A.I. dependencies based on components
I'm working on a turn based game in Unity. I need to perform field/grid analysis(2D grid) when i'm iterating trough each unit "entity". The A.I. should be able to plan ahead and therefor needs to consider the components each unit have. Not every unit will have the same ability. These abilities are defined as components.

I want to make it flexible in the sense that I can plug in new abilities and my A.I. will take it into consideration.

While user control is somewhat implemented, A.I. hasn't even been written. So I'm open to any suggestion.

Q : What is a way for the A.I. system to collect all abilities of one unit and make decisions depending on each component?

edit: I know there is the "null" checking method to see if the gameobject contains a component. But this is highly inflexible because you are hard coding a stack of if else. Something I want to prevent.

# Answer
> 1 votes
http://en.wikipedia.org/wiki/Polymorphism\_(computer\_science)

Polymorphism is probably one of the primary solutions to component based algorithms. I do not know how well unity can handle this sort of thing but this is likely going to lead you in the direction you are looking for.

The idea is each ability a unit has is derived from a basic ability class, and added into an ability list, then the AI can look at each ability in the list and determine how to handle the ability.

Your best bet is to have a function in said ability that returns a data structure to the AI that contains analysis data the AI can use to learn about the ability.

---
Tags: unity, ai, component-based
---


title: Top Down bounds of vision

text:
# Question
Title: Top Down bounds of vision
Obviously in a first person view point the player sees only what's in front of them (with the exception of radars and rearview mirrors, etc). My game has a top down perspective, but I still want to limit what the character sees based on their facing.

I've already worked out having objects obstruct vision, but there are two other factors that I worry would be disorienting and want to do right.

1. I want the player to have reduced peripheral vision and very little view behind them. The assumption is he can turn his head and so see fairly well out to the sides, but hardly at all behind without turning the whole body. How do I make it clear you are not seeing behind you?
2. I want the map to turn so the player is always facing up. Part of the game is to experience kind of a maze and the player should be able to lose track of North. How can I turn the map rather than the player avatar without causing confusion?

# Answer
Have you considered making your game isometric or 3D 3rd-person? Then you'd get both of your requirements for free, simply by virtue of the fact that you can't see behind the camera.

If you're absolutely set on top-down, you could try graying-out the areas that can't be seen, like Monaco does.

As for rotating the map rather than the player - there's no technical difficulty to doing this, but it might become disorienting. Try adding a minimap, and see if it still "feels right."
> 4 votes

# Answer
There are a couple ways of doing this:

You can create an invisible triangle that represents the view arc and translate it to the proper position and draw anything that collides with.

You can do the same thing but instead get the angle (radians/degrees) the player is facing and draw anything within the arc at a distance (probably more process intensive than triangle collision).

The other option is to only draw the hallway the player is in. Not sure how your data is set up but a recursive function that finds connected visible tiles and flags them to be drawn would probably get the job done.
> 2 votes

---
Tags: 2d, view, third-person-view, maze
---