title: Unity Android versus android SDK

text:
# Question
Title: Unity Android versus android SDK
I am familiar with Unity and in the process of learning android SDK when the announcement about unity android basic came out.

What would be the advantages and disadvantages of using the android SDK directly versus development using Unity Android?

# Answer
**Update Unity 5.x** There is a detailed manual on how to write native code plugins and call them from within Unity http://docs.unity3d.com/Manual/PluginsForAndroid.html

**!Since Unity 4.x has been already released, and Android went through a lot of changes you should consider this answer as a reference and not state of the art since it might be outdated!**

Sorry, but Ricket is wrong: Unity provides full access via API to the Android SDK, which is also required before working on Android Games with Unity:

> Before you can run Unity Android games on the actual device, you'll need to have your Android developer environment set up. This involves downloading and installing the Android SDK with the different Android plaforms and adding your physical device to your system (this is done a bit differently depending on whether you are developing on Windows or Mac). This setup process is explained on the Android developer website, and there may be additional information provided by the manufacturer of your device. Since this is a complex process, we've provided a basic outline of the tasks that must be completed before you can run code on your Android device or in the Android emulator. However, the best thing to do is follow the instructions step-by-step from the Android developer portal. Access Android Functionality
>
> Unity Android provides a scripting APIs to access various input data and settings. You can find out more about the new scripting classes on the Android scripting page. Exposing Native C, C++ or Java Code to Scripts
>
> Unity Android allows you to call custom functions written in C/C++ directly (and Java indirectly) from C# scripts. To find out how to bind native functions, visit the plugins page.

source unity manual

**Unity:**

* if you already have assets and more complex models
* take advantage of many file formats
* fast progress if you already have a design and know how the game should look like

**Android SDK:**

* might consider this for programming starter 2D games
* good start up to learn android basics which experience can be taken into further developement with Unity

If you want to start developing a game on a certain level of quality, and want quick success you should choose Unity over the pure SDK, because Unity gives you a lot of tools which make it easier to develop without worrying for little things.
> 13 votes

# Answer
Well they are completely different! The Android SDK lets you write Android apps from scratch in Java. Unity is a game creation package in which you drag-and-drop, add scripts, etc. and then hit a button to export a complete Android application.

**Android SDK:**

* Write the app from scratch
* Complete control over exactly what your game does and looks like; you can do anything
* Much more work and knowledge involved
* Write everything in Java

**Unity:**

* Make a game project, import assets, arrange your scenes, etc. within the Unity interface
* Script actions for the objects in JavaScript, C# or Boo
* Test the game on PC and deploy to multiple platforms including Android
* No Java needed (no Android SDK needed)
* No control over the final app; it runs with the Unity engine and you can't for example add an extra Android `Activity` (like a 'screen') to your app, or edit it in any way except in the Unity interface
* Large .apk size because the whole Unity engine (about 10MB) is packed into your application no matter how much of it you actually use.

Note that I don't have experience with the Android function of Unity (I do have general Unity experience though) so please correct me (or just edit this post) if the Unity category is wrong in any way.
> 5 votes

# Answer
Unless you know Java and absolutely no C++ or C#, I could never recommend using the android api for anything other then masochism or a front end to a web service. This is coming from 5 or so years of working on Android, for some of the major players. I'll spare you the book I could write on this topic, but the android api just isn't mature enough in design or implementation for prime time yet. And I think before it gets there, the folks at google will need to do some serious soul searching as to their dev methodologies. Just some food for thought, why are all the third part tools and API's blowing googles own tools out of the water?
> 1 votes

---
Tags: android, unity, platform
---


# Question
Title: No appropriate version of 'UnityEngine.Transform.RotateAround' for the argument list
Assets/CircularOrbit.js(11,26): BCE0023: No appropriate version of 'UnityEngine.Transform.RotateAround' for the argument list '(UnityEngine.Vector3, System.Type, float)' was found.

Here is what I what I did:

```
   var mountain : GameObject;
// This will return the game object named Hand in the scene.
   mountain = GameObject.Find("QuantumCold_B");
   transform.RotateAround(mountain.transform.position, Vector2,20 * Time.deltaTime);

```

Where mountain is mesh in the scene Perhaps its not really game object with a position? or position is not a Vector3?

# Answer
> 0 votes
Try replacing the 2nd parameter, `Vector2`, with `Vector3.Up`

# Answer
> 0 votes
The `RotateAround` function takes three parameters: a `Vector3` for the point, a `Vector3` for the axis, and a `float` representing the angle.

You are passing a position (a `Vector3`), the name of a type (an instance of `System.Type`), and the angle (a `float`). One of these things is not like the other: you are passing an incompatible value for the second parameter to the function.

Presumably you meant to pass an actual `Vector3` representing the rotation axis.

---
Tags: unity, unityscript
---


# Question
Title: 2D Circular View/Background Wrapping SDL for Game
In the games such as Defender (1980 arcade) and Defcon, the player can move/scroll in one direction infinitely because the level/terrain simply wraps over and over again(like if it was wrapped around the side of a cylinder).

I am more interested in the wrapping mechanics of Defcon which wrap(on the x-axis) and zoom the entire level. Here is a link to view the game.

To make images(such as a background) wrap is it a per-pixel approach? Is there a function? What methods are there to achieve the circular wrapping of a level?

# Answer
> 1 votes
When I have used a repeating background image, I used two copies of the image side by side and scrolled the pair. When one gets to the edge of the screen, reposition it off the screen.

---
Tags: c++, sdl
---


# Question
Title: Find the closest point along a rectangle, given an another point and direction
Given a rectangle, and a point with a vector direction towards the rectangle. How can I find the closest point on the outside of that rectangle to the point in question?

# Answer
> 6 votes
One technique which you could use is called "ray casting". It is commonly used for rendering graphics, but has other applications such as line-of-sight (as you are wanting to do) and path-finding. In general terms it works by finding the intersection of a ray and an object. In your example the ray is the vector for the character's direction.

A useful reference for ray/object intersections (and incidentally other object/object intersections) is www.realtimerendering.com/intersections.html (look under the references for ray/aabb and ray/obb).

# Answer
> 9 votes
The rectangle has four sides. Each side is a line segment.

Test each of the four sides for intersection with the ray. Track the closest hit.

Here's some code to find out where on the segment the ray hits:

```
bool intersect(const ray& ray, const segment& segment,point& hit) {
    // where do we intersect this line?
    float t = ((ray.direction.x * ray.origin.y + ray.direction.y *
        (segment[0].x - ray.origin.x)) -
        (ray.direction.x * segment[1].y)) /
        (ray.direction.y * (segment[0].x + segment[1].x) -
        ray.direction.x * (segment[0].y + segment[1].y));
    if(t >= 0.0 && t<=1.0) { // in the segment
        hit = segment[0] + (segment[1]-segment[0]*t);  // lerp
        return true;
    }
    return false; // no hit
}

```

# Answer
> 2 votes
If your box is axis aligned, you just have to clamp each coordinate axis to the box if the point is outside the box.

From RTCD pg 130:

```
// Do this for all 3 axes
if( point.x < min.x )  point.x = min.x ;
else if( point.x > max.x )  point.x = max.x ;

```

If you do this for x, y, z axes, then the `point` will be slammed to the nearest wall of the box, *if* it is outside the box to begin with. if it is already inside the box, it will be left alone (where it is).

# Answer
> 0 votes
Well, you can use just linear algebra (analytic geometry, to be more specific) to solve this. It depends on how you modeled the rectangle.

Here's a general case: http://paulbourke.net/geometry/lineline2d/

---
Tags: mathematics, geometry
---


# Question
Title: Writing an autopilot for a 2d game with newtonian physics
The subject says it all. I am making a 2d space game with newtonian physics and I need pointers on how to write an autopilot for it. The requirements are best explained by an example.

There is a target object which has speed and position vectors and there is a spaceship that is controlled by the autopilot. This spaceship also has speed, position and maximum acceleration. The autopilot needs to control the ship so that it either collides with the target or intercepts the target with matching speed and position.

Could someone give me some pointers how to achieve this behavior or perhaps even a ready implementation? I am sure someone has written something like this before and there is no point in reinventing the wheel.

# Answer
> 2 votes
You will probably find what you're looking for here:

Steering Behaviors For Autonomous Characters

Maybe in this article:

Steering behaviors (full article)

# Answer
> 2 votes
Many of the currently available steer libraries are based on either OpenSteer or Programming AI by Example and have one fatal flaw: they rely on forward-facing physics which are out-of-the-box incompatible with physics libraries such as Box2d.

To illustrate the problem: in almost every single one of the steering examples, the direction of the agent, is the same as its force. This, however, doesn't hold true with physics libraries, where the force of the object can be different to the direction the object is actually facing.

Solving this can be fairly non-trivial. However,there is a video that seems to be doing something similar related to the book "The Nature Of Code". In the book, the implementation has been left as an excercise (6.21), unfortunately.

Trivial way to handle this is to cheat, and adjust your agents graphics heading independently of physics, but this seem like a sub-optimal solution to me. What about situations where you want to preserve non-forward facing physics of the physics library, but yet be able to steer the craft using autonomous agents?

# Answer
> -1 votes
In case you decided to write your own autopilot, I would always start by asking myself the question: What would I do in that situation? How would I plan my course, what maneuvers would I take? Surely you have mastered the task multiple times yourself. What steps did you take to arrive at your destination?

I know it still will be a pretty sophisticated autopilot. I would break it into smaller problems, i.e. a simple autopilot for making a course correction, one to kill rotation, one to come to a complete halt etc... Then later I would write more sophisticated ones that rely on the more simple ones - to automatically go from orbit of planet A to orbit of planet B, or one to intercept another ship etc...

I have thought about writing my own game for years now, and I think eventually I will have to face these problems myself...

---
Tags: physics
---


# Question
Title: What does Mecanim's "loop pose" parameter do?
What exactly does the *loop pose* parameter do?

What's the difference between enabling or disabling it on animation clips?

# Answer
> 4 votes
Loop Pose: Enable to make the motion loop seamlessly.

It keeps looping the pose. Meaning, that you have same pose at begin frame and end frame.

---
Tags: unity, skeletal-animation, mecanim
---


# Question
Title: Input management techniques in large games
Is there a standard technique for managing input in large games. Currently, in my project, all input handling is done in the game loop, like so:

```
while(SDL_PollEvent(&event)){
            switch(event.type){
                case SDL_QUIT:
                    exit = 1;
                    break;
                case SDL_KEYDOWN:
                    switch(event.key.keysym.sym){
                        case SDLK_c:
                            //do stuff
                            break;
                    }
                    break;
                case SDL_MOUSEBUTTONDOWN:
                    switch(event.button.button){
                        case SDL_BUTTON_MIDDLE:
                                //do stuff
                                break;
                            }
                    }
                    break;
            }

```

(I am using SDL, but I expect the main practice applies libraries and frameworks as well). For a large project this doesn't seem the best solution. I may have several objects all wanting to know what the user has pressed, so it would make more sense for those objects to handle input. However, they can't all be handling input, as after one gets an event, it will be pushed off the event buffer, so another object won't receive that input. What method is most commonly used to counteract this?

# Answer
> 11 votes
Since asked by the thread starter, I elaborate on event managers. I think this is a good way to handle input in a game.

An event manager is a global class which allows to both register callback functions to keys and to fire off those callbacks. The event manager stores registered functions in a private list grouped by their key. Each time a key gets fired, all registered callbacks are executed.

The callbacks could be `std::function` objects which can hold lambdas. The keys could be strings. Since the manager is global, components of your application can register to keys fired from other components.

```
// in character controller
// at initialization time
Events->Register("Jump", [=]{
    // perform the movement
});

// in input controller
// inside the game loop
// note that I took the code structure from the question
case SDL_KEYDOWN:
    switch(event.key.keysym.sym) {
    case SDLK_c:
        Events->Fire("Jump");
        break;
    }
    break;

```

You could even extend this event manager to allow passing values as additional arguments. C++ templates are great for this. You could use such a system to, say, for a `"WindowResize"` event pass the new window size, so that listening components don't need to fetch it themselves. This can reduce code dependencies quite a bit.

```
Events->Register<int>("LevelUp", [=](int NewLevel){ ... });

```

I've implemented such an event manger for my game. If you are interested, I'll post the link to the code here.

Using an event manager, you can easily broadcast input information within your application. Moreover, this allows for a nice way to let the user customize key bindings. Components listen to semantic events instead of keys directly (`"PlayerJump"` instead of `"KeyPressedSpace"`). Then you can have an input mapping component that listens for `"KeyPressedSpace"` and triggers whatever action the user bound to that key.

# Answer
> 24 votes
Split this into several layers.

At the lowest layer you have raw input events from the OS. SDL keyboard input, mouse input, joystick input, etc. You might have several platforms (SDL is a least-common-denominator lacking several input forms, for instance, which you might later care about).

You can abstract these with a very low-level custom event type, like "keyboard button down" or the like. When your platform layer (SDL game loop) receives input, it should create these low-level events and then forward them on to an input manager. It can do these with simple method calls, callback functions, a complicated event system, whatever you like best.

The input system now has the job of translating low-level input into high-level logical events. Game logic does not at all care that SPACE was pressed. It cares that JUMP was pressed. The input manager's job is to collect these low-level input events and generate high-level input events. It is responsible for knowing that the spacebar and the 'A' gamepad button both map to the logical command Jump. It deals with gamepad vs mouse look controls and so on. It emits high-level logical events that are as abstract as possible from the low-level controls (there are some limitations here, but you can abstract things away completely in the common case).

Your character controller then receives these events and processes these high-level input events to actually respond. The platform layer sent the event "Key down spacebar." The input system received that, looks at its mapping tables/logic, and then sends the event "Pressed jump." The game logic / character controller receives that event, checks that the player is actually allowed to jump, and then emits the "Player jumped" event (or just directly causes a jump to happen), which the rest of game logic uses to do whatever.

Anything dependent on game logic goes into the player controller. Anything OS dependent goes in the platform layer. All the rest goes into the input management layer.

Here's some amateurish ASCII art to describe this:

```
-----------------------------------------------------------------------
Platform Abstraction | Collect and forward OS input events
-----------------------------------------------------------------------
                          | |
                          | |
                         \   /
                          \_/
-----------------------------------------------------------------------
    Input Manager    | Translate OS input events into logical events
-----------------------------------------------------------------------
                          | |
                          | |
                         \   /
                          \_/
-----------------------------------------------------------------------
Character Controller | React to logical events and affect game play
-----------------------------------------------------------------------
                          | |
                          | |
                         \   /
                          \_/
-----------------------------------------------------------------------
      Game Logic     | React to player actions and provides feedback
-----------------------------------------------------------------------

```

---
Tags: c++, sdl, input, standards
---


# Question
Title: 3D movement on an authoritiative server?
I'm developing an MMORPG, using Unity for the client and "standard" C# 4.0 for the authoritative server. The server should check each player's movement and ensure that it does not collide with props or walk through unpassable terrain (like a cliff). Collisions with other players and such are not checked. In addition, the server must be able to retrieve/calculate the position of a player at any time so it can be sent to other players (who just walked into range, for example).

To make this all a little more complex, the game is a 3D space, meaning you can have things such as a spiral staircase and flight, and it has multiple maps.

I've run into a problem, though. I'm not quite sure how to actually implement all this.

I've come up with two ideas:

* Make the server interop with a Unity client tasked solely with tracking player positions and validating movement
* Get the props and terrain onto the server and use math to define the character's movement and check for collisions.

The first one seems ugly to me, and I don't even know if Unity will allow me to load multiple maps onto the same client. I've made some progress on the second one: I managed to export props as OBJ files and read them on the server. But from there, I'm kinda lost.

My question is two parts: Is there a better way to achieve what I want? And if not, how should I proceed with my current plan?

# Answer
You seem to allow in your game to flight, so traversable area is not a good solution.

If Unity has a library or somthing like that you may embed into your server and it run fast enough to work with lot of client, I think you should use it, because implementing a collision engine is a huge job. You may always prepare your code to allow a further transition to your own collision engine.

Accuracy for a simple collision engine:

* It is important your server colision engine be less strict that your Unity client colision engine: if not, the server will be every time fixing players movement, and with the network lag, that is very painful for players.
* The server should test colision using the (near) full player trajectory, not only the start-end position.
* If the server is much less strict than your client, you allow cheaters to use this margin to get advantages.

Considerations for a simple collision engine:

* You should use a simplification of the entire world, which exclude small objects and simplify geometries.
* There is lot of libraries that you may use to avoid the bigger part of this task: collision and physic, some of them use GPU hardware acceleration (like phyx)

Finally: take your time to evaluate all options, because this decision has big impact on the result quality and implementation time.
> 2 votes

---
Tags: c#, collision-detection, unity
---


# Question
Title: How can I record from a second in-game camera and later export it to a video file?
I'm making a PC Horror game in Unity, and I want to have a camera recording simulation in-game - so you can leave a creepy location anytime, and you will have a tape with what you recorded on camera while exploring.

Technically, I need to attach a second camera (hand-cam) to the character's hand, and let the player look through the viewfinder by pushing a button. But in any position, the hand-cam must record everything that is in its focus at that point - floor, stairs, rubbish, etc, whether it's lowered at hand level or raised to match the player's viewpoint.

When the game ends (player leaves or dies), I'd like to have an option to save recorded tapes to a video file (if this is not possible, then to some save file).

**How can I implement such a feature in my game?** Are there some special Unity tricks, or add-ons and additional modules? Saving decorations and scenes with active triggers, or just grabbing video from screen?

Below is a quick MSPaint concept of what I mean:

# Answer
> 6 votes
You need to render your scene twice.

First, you render the scene from the **view of the camera to texture**.

Then you render the scene from the **players point of view**, but with the **texture applied to the cameras screen**.

What changes between the two render passes is the **camera transform** used, while the camcorder uses the orientation & location of the camera, the players view uses the orientation & location of the players head. If you're using skeletal animation, this would be as easy as attaching the camera model to the player models hand.

Since you already render to texture then, saving a video would be as easy as **saving the texture each frame**. When the user chooses to save the video, you could convert this **sequence of images** to a **video format**.

---
Tags: unity, camera, export, screen-recording
---


# Question
Title: How do you reference one game object from another?
I am trying to reference a game object that was created in the editor and added to the scene (not created dynamically). How can I reference this object in a script added to another gameobject?

For example I have a Mesh called `QuantumCold_B` (in the editor), and I try to get its position in a script to be added to First Person Player, but instead I get

> Unknown identifier ('QuantumCold\_B').

Here is my script:

```
function Update () {
   transform.RotateAround(QuantumCold_B.position, Vector2,20 * Time.deltaTime);
}

```

Also is position the right way to get the Vector position on `QuantumCold_B`?

# Answer
> 4 votes
Since `QuantumCold_B` is not defined as a variable, you won't be able to use it that way.

If "QuantumCold\_B" is the name of the object in the editor, you can use the GameObject.Find function to get the game object that has the name you want.

So, you would use:

```
var myObject : GameObject;
// This will return the game object named Hand in the scene.
myObject = GameObject.Find("QuantumCold_B");

```

Then, to get the position you'd use:

```
myObject.transform.position

```

I suggest you familiarize yourself with the scripting reference in general to find a lot of these types of answers on your own. Good luck!

# Answer
> 5 votes
You should add a game-object as a public member to your class.

Let's assume you write a behavior for your Camera and name it `CameraController`. Here's how this could look like:

```
using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour {
    // this will turn up in the Inspector where you can assign
    // an object to CameraTarget and use it later in your code.
    public GameObject CameraTarget;

    void Update () {
        // update position while looking at CameraTarget
        Vector3 pos = transform.position;
        pos.z += Time.deltaTime;
        transform.position = pos;
        transform.LookAt(CameraTarget.transform);
    }
}

```

Once you add this script to your camera (or any other game-object for that matter), the `CameraTarget` it will show up in the "Inspector" as soon as you select this object. Then you can drag'n'drop any object from your scene or even your assets panel (think prefabs) to the `Camera Target` of your script.

Here's a screenshot how this looks like (added a Cube GameObject as the camera target):

This feature is not limited to Game-Objects. You can use it for almost any type, eg. use an `int` for hitpoints, `Vector3` for velocity, etc. It's a really powerful concept and you should use it (you can also modify these values on the fly while running your game in the editor to test/tweak your game).

---
Tags: unity, unityscript
---


title: Calculating distance by force

text:
# Question
Title: Calculating distance by force
I am trying to predict a ball(sphere) movement. The formula of force which I know is

```
Force=Mass*Accelaration

```

What I want is how can I get distance or displacement by giving particular force? I want to consider drag, angular drag and friction also included in the equation. Or if it can be vice-versa, calculating force needed by providing distance.

The equation I could find doesn't include drag and friction, thus they are not as accurate as I needed. Any help in generating the exact formula would be appreciated.

# Answer
> 2 votes
The Force and Acceleration components in that equation are actually vectors (2D vectors in 2D space and 3D vectors in 3D space). It can be rewritten as (forgive my lack of math notation)

```
sum(force_vectors) = mass * acceleration_vector

```

Let's consider you're working in a 3 dimensional game. We'll define the forces present according to your question

```
v_drag
v_angular_drag
v_friction
v_gravity
v_push (a force exerted by something else on this object)

```

All of those are 3D vectors in the form of `{ f_x, f_y, f_z }` where every component is the component of the resulting force along the corresponding axis. In that case,

`sqrt(f_x^2 + f_y^2 + f_z^2) = force_scalar`

according to the Pythagorician theorem.

Now, your `Force` expression in your equation becomes

```
v_drag + v_angular_drag + v_friction + v_gravity + v_push

```

where `+` is obviously a component-wise vector sum. At this point, since you know the mass of your object you can calculate the vector of it's acceleration using

```
v_acceleration = Force / Mass

```

That vector represents the variation of your objects velocity. Let's say your object is at rest (`velocity = { 0, 0, 0 } m/s`) at position `{ 0, 0, 0 }`. Its velocity at `time = t` is expressed as

```
velocity = initial_velocity + t * acceleration

```

Likewise, its position is expressed as a function of its previous position, time and velocity. Therefore

```
position = initial_position + t * velocity

```

A crude implementation of such a physics simulation would then look like

```
PhysicsBody body;

while(true) {
    float delta_time = get_time_delta();
    float acceleration = (v_drag + v_angular_drag + v_friction + v_gravity + v_push) / body.Mass;
    body.velocity += delta_time * acceleration;
    body.position += delta_time * velocity;
}

```

Where `delta_time` is the time elapsed since your last physics update.

There are a few things wrong with this naive implementation, particularly that a long update time would render the whole calculation extremely imprecise. However, you'd need to get into some calculus to solve the related equations and I'll let someone more qualified than me get into that mess (although I don't think the question implied it needed to go into that much detail).

---
Tags: physics
---


title: What is data-driven design?

text:
# Question
Title: What is data-driven design?
I've been reading up on a lot of articles covering data driven design for games. It seems to come down to:

* No hard coding
* No game-specific code in the engine
* Scripting for AI, cutscenes, et cetera.
* Generalizing code for reusability
* Component design
* Modularity
* Low coupling
* Editors (for data, maps, scripts)
* External data retrieval
* Constants kept in text files (`.ini` or otherwise)
* Expose data through editors for scripting and manipulation by designers

Now, my question is, is this understanding correct?

# Answer
> 11 votes
I'd say this is not correct. I believe the most important idea in data driven design is *separating your data from what modifies (or updates) the data*.

So going from a standard OO deep hierarchy like this:

```
class MyCreature{
     vector position;
     void update(){ position += 1; }
}

```

to a separate state and system

```
class CreatureState{
    vector postion;
}

class MovementSystem{
    list<CreatureState> states;
    void update() {
        for each CreatureState state in states {
            state.position += 1;
        }
}

```

On of the most influential DDD paradigms at this moment are Entity Systems. Some nice resources to look up are:

http://gamedevrubberduck.wordpress.com/2012/12/26/a-hybrid-entity-system-component-architecture/

http://entity-systems.wikidot.com/

Of course as with all paradigms/ideas there isn't an exact definition and not everybody understands the same idea when talking DDD but this is what I believe the most important thing.

# Answer
> 4 votes
I think you are overcomplicating the definition. Certainly, many of the principles contained in your bulleted list of points are *good* ones from a software engineering perspective, but they aren't all necessarily part of the definition of "data-driven." Many of them have some overlap, or are best implemented *using* a data-driven approach, but don't constitute the act of data-driving something.

The actual definition of data-driven software development is generally fairly simple: a program performs actions mainly based on some outside information (a piece of level data, script data, et cetera) instead of having a series of predefined and fixed steps within the code itself that determine control flow.

---
Tags: terminology
---


# Question
Title: Understanding VAOs and adding different arrays to VAOs
I'm really confused on what you do. I can do them, however I got this problem. Say you have several squares, say 1,000 squares. Now I can make a VAO for each 1,000 squares and then do some for loop to render all of the squares. I can also use shaders to move the squares.

However, is it possible to put all 1,000 squares in one VAO.

The problem is I'm going to create a voxel game. So I need to render about 10,000 cubes. However, the game will lag a lot even if I render 200 squares how I'm currently doing it.

```
float points[] = {
    0.0f, 0.0f, 0.0f,
    0.3f, 0.0f, 0.0f,
    0.3f, 0.3f, 0.0f,
    0.0f, 0.0f, 0.0f,
    0.0f, 0.3f, 0.0f,
    0.3f, 0.3f, 0.0f
};

float colours[] = {
    1.0f, 0.0f,  0.0f,
    1.0f, 0.0f,  0.0f,
    1.0f, 0.0f,  0.0f,
    1.0f, 0.0f,  0.0f,
    1.0f, 0.0f,  0.0f,
    1.0f, 0.0f,  0.0f
};

unsigned int points_vbo = 0;
glGenBuffers (1, &points_vbo);
glBindBuffer (GL_ARRAY_BUFFER, points_vbo);
glBufferData (GL_ARRAY_BUFFER, 18 * sizeof (float), &points, GL_STATIC_DRAW);

unsigned int colours_vbo = 0;
glGenBuffers (1, &colours_vbo);
glBindBuffer (GL_ARRAY_BUFFER, colours_vbo);
glBufferData (GL_ARRAY_BUFFER, 18 * sizeof (float), &colours, GL_STATIC_DRAW);

unsigned int vao = 0;
glGenVertexArrays (1, &vao);
glBindVertexArray (vao);
glBindBuffer (GL_ARRAY_BUFFER, points_vbo);
glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, (GLubyte*)NULL);
glBindBuffer (GL_ARRAY_BUFFER, colours_vbo);
glVertexAttribPointer (1, 3, GL_FLOAT, GL_FALSE, 0, (GLubyte*)NULL);

glEnableVertexAttribArray (0);
glEnableVertexAttribArray (1);

//Setup shaders
std::string vertex_shader = loadshaders("test_vs.txt");
std::string fragment_shader = loadshaders("test_fs.txt");

unsigned int vs = glCreateShader (GL_VERTEX_SHADER);
const char* str = vertex_shader.c_str ();
glShaderSource (vs, 1, &str, NULL);
glCompileShader (vs);
unsigned int fs = glCreateShader (GL_FRAGMENT_SHADER);
const char* strb = fragment_shader.c_str ();
glShaderSource (fs, 1, &strb, NULL);
glCompileShader (fs);

unsigned int shader_programme = glCreateProgram ();
glAttachShader (shader_programme, fs);
glAttachShader (shader_programme, vs);
glLinkProgram (shader_programme);

// main loop
while (!glfwWindowShouldClose(window))
{
    float ratio;
    int width, height;
    glfwGetFramebufferSize(window, &width, &height);

    glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glClearColor (0.6f, 0.6f, 0.8f, 1.0f);
    glUseProgram (shader_programme);
    glBindVertexArray (vao);
    glDrawArrays (GL_TRIANGLES, 0, 6);

    glfwSwapBuffers(window);
    glfwPollEvents();
}

```

So how would I say add points2\[\], points3\[\] and put them into the same VAO. How can I design my shader so I can then do transformation on the points in the arrays say translate points2\[\] array 4 blocks right, without effecting every other point.

# Answer
You can do it in the shader *but* it makes things really complicated.

So the alternative i think of is to bake your geometry into one VBO/VAO for say... 16x16x16 boxes/voxels. If you need to change that data just change it and rebake the VBO/VAO for it.

You need also some abstractions for the Shader Objects, a thing i call Buffer (Manages the VBO/VAO for the gometry) and in Buffer you need to dynamically allocate/reallocate/free memory, don't do it with static arrays.
> 1 votes

---
Tags: opengl, c++
---


title: libgdx: how to manage entity classes

text:
# Question
Title: libgdx: how to manage entity classes
Good day sirs, I know this is a newbie question but I really need to ask it. I've been reading a lot of sample codes on libgdx, and I have seen entities(player, enemy, boss,etc.).

my question is what should an entity class contain?as I have seen it contains states which i will use to animate my sprite, should I also put my inputs/controls, and animation in this entity class?

# Answer
It sounds like you're struggling with basic object-orientation. There are really two ways you can do this:

1. Use classes. This is tricky, because your `Player` class will have data (player health, etc.) but also the current view to draw (sprites, etc.) A better way would be option #2
2. Use a component-entity system. This article describes it quite well, as an improvement over option #1; you basically create small components (eg. Sprite, KeyboardInput) and entities (eg. Player) that are a composite of multiple components and "wiring" to make them work together.

If option #2 seems too "hard," try option #1 first. If your game is a small size, it may be "good enough" for you.
> 2 votes

---
Tags: java, game-design, sprites, libgdx, game-mechanics
---


title: What is an acceptable input delay?

text:
# Question
Title: What is an acceptable input delay?
It is common knowledge that if the framerate of a game is over 25-30 fps, we humans perceive it as running smoothly. More is better, but if it is above that, it at least doesn't lag.

I have been looking for research as to how long a mouse input can take to reach the screen, and still feel instantaneous to the average person, for example. I'm sure it may vary a little bit, from person to person, but I'm sure we all have a limit on how fast anyone can perceive small time differences between events.

I'm interested in this because I want to try and statically update the data for my game, for example every 0.05 seconds, instead of as soon as I get a new input. This will save computer power, while still not causing delay in the game.

What is an acceptable input delay?

# Answer
This is essentially the same (update your input around 30+ times per second). If you update less often, you'll experience "input lag."

This is even more noticeable when a game uses a hardware cursor and has some icon following the cursor (such as during drag-and-drop operations). You'll most likely see the icon lagging behind.

In the end this really depends on how often you update your game logic. There's no real need to update inputs if you don't handle game logic anyway (unless we're talking about something like a mouse cursor). But either way, I'd pick the bigger value of your frame rate and your game update rate for inputs. If the update rate is higher, you'll need it for fast reactions, if your frame rate is higher you'll need it to avoid visible lag.

Also, as a note regarding power consumption: querying inputs x times per second will most likely cause more power consumption than simply reacting to input happening. Always think about situations where no input happens.
> 6 votes

# Answer
I'm not sure there is much in the way of formal research into this area. You could perhaps posit some numbers based on an understanding of human reaction times (which has had extensive academic study), although note that this and what you are talking about are *not* the same thing. The acceptable delay between making a motion with a mouse and seeing a result is almost certainly much smaller than the time it would take a human to react to something displayed on the screen *with* the mouse.

This is, in fact, an important consideration. While in some cases it may be acceptable to only process new input around 30 frames-per-second, as with rendering (the idea being that that's the persistence of vision interval anyway), you could in some implementations of this approach have too much round-trip delay between an action happening on the screen and the player's reactionary input getting back into the game logic.

In the real world, usability tests and general playtesting usually catches this kind of thing (especially for games that *also* have a networking component and can have the additional network round-trip delay). Based on feedback from playtesters about how "laggy" or "floaty" your controls feel, you will adjust your input timing or optimize the round-trips to achieve better results.

Consequently I think it's a bad idea (premature optimization, in a way, as Byte56 commented) to focus on achieving a theoretical ideal input delay on the misguided attempt that you will "reduce computer power." You almost certainly won't, first of all, and you'll be solving the problem with the wrong constraints and flexibility areas in mind.
> 4 votes

---
Tags: input
---


# Question
Title: Get sprites from XML and spritesheet in Java
I have a SpriteSheet that have a lot of images in one in .png format, and the XML file with the all names of every sprite (x,y,width,height) like this:

`<TextureAtlas imagePath="sheet.png">`

`<SubTexture name="box.png" x="0" y="864" width="70" height="70"/>`

`</TextureAtlas>`

Im using Slick2D to make a BasicGame, SpriteSheet and XStream lib to manage the sprites, but i cant do, that load the image correctly. How I can do?

# Answer
> 1 votes
You have to parse the xml file. It's not hard thing to do and this should get you started.

```
File file = new File("spritesheet.xml");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
    .newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(file);
NodeList subTextureNodeList = document.getElementsByTagName("SubTexture");

```

Now we have all the subtexture-data of spritesheet stored in subTextureList as an XML node. To read name,x,y, width and height of all images, do this:

```
for(int i = 0 ; i < subTextureNodeList.getLength(); i++){
    Element subTextureElement = (Element)subTextureNodeList.item(i);
    String name = subTextureElement.getAttribute("name");
    String x= subTextureElement.getAttribute("x");
    String y= subTextureElement.getAttribute("y");
    String width = subTextureElement.getAttribute("width");
    String height= subTextureElement.getAttribute("height");

    // DO SOMETHING WITH THIS DATA HERE
    // GET THE PICTURE FROM SHEET WITH THESE.
    }
}

```

---
Tags: java, spritesheet, xml
---


# Question
Title: (Java + Slick) How to rotate the Graphics (g) around the X-Axis?
I already tried it by using `GL11.glRotatef(45, 1, 0, 0)`, but the result looks like this:

# Answer
> 0 votes
I just want to tell you that I actually found a solution:

The trick was to set the `near` & `far` values via `GL11.glOrtho(...)` to a higher value, so the "space" for the drawn "things" on the z-axis is enough. For me, I chose 10000 & -10000.

Hope it helps someone else, too. `:)`

---
Tags: java, lwjgl, isometric, slick
---


# Question
Title: UDK or Unity Dynamic Runtime Mesh Boolean subtraction (or alternative)
I'm new to 3D game dev and was wondering if anyone could help me out.

I'm planning to use UDK and would like to have deformable items in the world.

So a projectile strikes a target, and a dent or hole is inflicted.

At first I thought there might be a way to load a mesh at the impact point and then "subtract" that mesh from the target mesh. Is this possible? This would allow me to have different "impact effect" - like thin and deep, or wide and shallow. (Similar to this, but without requiring DX11)

I've searched for this but not sure what to call it (deformable meshes, boolean mesh operations, etc), but if it already has an answer then that would be great.

If my approach is wrong, could you point me to any alternatives? Don't really want to go down the chunks route.

Or, if Unity etc. supported it, then it's not too late for me to change engine.

Thanks very much, Martin

# Answer
> 1 votes
You could consider the approach outlined here:

http://answers.unity3d.com/questions/316064/can-i-obscure-an-object-using-an-invisible-object.html

(The answer is written in terms of unity, but the same shared based applies to Unreal as well.)

Basically you add geometry to your game that only writes to the Z buffer, and then draw the objects that need holes in them. This is pretty speedy, as it can be done without modifying the meshes at the cost of two additional draw calls.

The biggest problem is that if two bullet hole receiving objects are back to back, a bullet hole will go though all such objects until a bullet proof object is reached. (This may actually be desired in some cases). However if only some geometry in your game like wooden doors and the like can receive bullet holes, the effect could be pretty convincing.

# Answer
> 0 votes
Typically what you're asking for is non-trivial. There are some expensive middleware packages for this feature, but not a lot of free ones.

A straight-forward (but still non-trivial) approach is generate pre-broken versions of geometry and then to switch to those. This requires more art investment and has a number of limits, of course. Good investment in tools can improve the workflow but will take some time to get up and running.

Difficulties of this in general are those objects are 3D (with multiple "materials" internally). If you blow up a hill, you don't just want to depress the grass on it. You want to generate dirt, stone, and clumps of turf that landed nearby. To put a hole in a wall, you need to know what the inside of the wall looks like (walls are not infinitely thin planes in real life). Putting a hole through an entire building in your scenery is that much harder. Handling physics appropriately (e.g., ensuring a structure collapses if you remove its supports) is even harder still, since you need to model the structure intricately both visually and physically.

You can hack around a lot of this with some basic assumptions and tricks. Walls can have "decal" objects that are placed around a hole to make it look rougher and hide/cover the spaces between the inside and outside of the wall. Generating the hole in real-time is still a trick, though; AAA solutions precompute these holes, often with high-powered algorithms and very extensive and complex tools integration.

The difficulty of properly handling deformable terrain is partly why you almost never see it outside of a few precomputed cases and games like Scorched Earth (which is all 2D). It's possible, but not easy, and potentially unfeasible for complex types of terrains and structures.

Note that both UDK and Unity use NVIDIA's PhysX, which is one such middleware with "destruction" capabilities. UDK includes a "fracture" tool in UnrealEd using the APEX Destruction toolkit with PhysX to do things the precomputed way mentioned above. It's up to you to decide if this is "good enough" for your needs or not.

# Answer
> 0 votes
If it is still not too late to use Unity you can try this: https://www.assetstore.unity3d.com/#/content/9411

In the description you can check out a video and a realtime webplayer demo showcasing the main features :)

---
Tags: unity, udk, 3d-meshes
---


title: How to manage maps in 2D MMO?

text:
# Question
Title: How to manage maps in 2D MMO?
I'm curious about how I should be drawing my game world. I'm going to have a map, let's say 1000 by 1000 tiles in size, with many players on it. Each player will be at a position in a map, and when they move I want their sprite to stay in the centre of the screen (so I want the map itself to move).

Is it efficient to do this by drawing a map 1 square bigger on each edge than the game window itself, then having the extra bits chopped off? Or should I be slicing and dicing sprites?

If you're curious as to what sorta thing I'm looking at, think tibia.com crossed with Pokemon, with graphics somewhere in between, and a turn-based attack / defence system.

# Answer
> 5 votes
Just draw slightly outside the screen. Essentially, only cull tiles/objects that are completely outside the view frustrum/rectangle.

Slicing sprites manually is something you cannot possibly hope to do as fast as the GPU can. You'll have to do a lot of clipping manually in your own code, which the GPU has dedicated hardware for. It's significantly easier to calculate the visible or partially visible subsection, generate a vertex buffer for the tiles, and draw that.

I'd also suggest searching the other tilemap related questions on this site for further recommendations on culling, map representation, and so on.

# Answer
> 2 votes
Your basic tiles will be represented twice.

* The 'game' tiles, that will just be things like 'collides' and a reference to some visual content. Probably an id number for a sprite, or possible multiple if you want more complex maps. If you think about a tree on grass the tree is probably better as a separate object rather than part of the tile.
* The 'graphics' tiles. This is what is visible on the screen. It could be a big pre-rendered bitmap, or a bunch of preloaded images that you look up based on indices (or even both).
* Objects. Efficiency says you probably won't want this in an array unless you have an extremely high density. Possibly look at a QuadTree although a basic list could probably work too.

The choice between using an array (a good choice for tiles), or a list/quadtree will depend on your *data density*. For tiles you know you will have 100% data density because each cell on your map requires a visible tile (although for a massive 'growing' game world like some kind of a Tile based MUD this might not be the case). Choosing between a list/quadtree will probably depend on your total object count and the types of operations you are performing (a list would be quicker for updating every object once per gametick, a quadtree would be quicker for locating an object based on its position in the game world).

But you don't have to choose just one representation. You can store reference (pointer/smart pointer) to objects in multiple different data structures. Rather than scan though *all* your objects every game tick, just make a list of objects that need to be updated *and* also have them in a quadtree for position lookup information and rendering purposes. This way only objects that need to be updated will be check. Just remember to remove them from all the possible locations when they are destroyed.

So don't have any operations that require you to 'scan' your map, that will kill performance. The possible exception to this rule would be path finding.

There are also many kinds of 'lists'. Rather than a basic 'linked list'. A que or cirque might be a better choice for a list of things to be updated. You will want to learn about different data structures (or containers in C++ terminology).

There are different types of 'arrays' as well. Some kind of dynamic array (or C++ vector\_ might be a better choice if you need resizing (maybe you want a client to request chunks from the server based on the resolution of the screen, so you need to be able to resize all your arrays on the fly. But that is probably overkill for most purposes, it would probably be simpler to just blow away your arrays.

When it comes down to it, 'graphics' and 'game' tiles are basically the same thing but the graphics could use much more data pertile since it has to have the rendered graphics there. Both of them can use the same buffering algorithms to store nearby tiles.

For the 'game' tiles, 1000x1000 isn't a huge number of tiles on a modern system. You could probably load the whole thing into memory in a grid array. At 4 bytes pertile (just enough for a int for a tile index id, it's about 3MB) At 32 bytes a tile (kind of a lot, it's 30MB). This is only the game datastore side of things, for graphics prerendering the whole map into memory would be excessive. Although you could probably get away with having all your tile sprites loaded in at a set and just using an index pertile and looking it up on the fly when rendering, of course then your maps are limited to a specific 'style' such as 'dungeon', 'snow', 'desert', 'forest', etc... Something like Zelda would have worked that way but now days I think we can do better and remove the need to limit graphics to a fixed set. So for the graphics you will defiantly want a buffer system

A game like Minecraft breaks the game world into chunks rather than loading tiles. This allows for an entire area to be loaded at once which is much more efficient. Also you can do things like memory alignment. Or having some chunks hosted on a totally different server. Minecraft uses something like 64\*64\*128, but for a flat 2D game you would probably want something bigger. But don't worry about things like memory alignment at this stage, optimize later.

So for a MMO with a big map I would probably recommend streaming in the 'game' tiles into a buffer too (just like the graphics tiles). Just load chunks off the side of the screen. Do remember that the number of chunks you need will be based on the resolution of the client. Aim for having basically an infinity sized map. All you need to ensure is that loading the tiles is faster than walking the distance (not hard on a modern system).

On the client side when you walk, don't 'move' all the tiles in memory. Instead have a tile\_offset that represents the first left tile (either the buffer or visible tile). When you walk change this offset and load in new tiles behind it. You will also want a scrolling animation so have another pixel\_offset that represents how many pixels each tile is moved over by (this will just cycle once per step). Use the % modulus operator to handle wrapping on these offsets.

Chucks can be a hassle as you have to be able to handle boundary conditions.

Another thing to consider is if you want your maps to be based on the client-side or server-side. Most MMO's use client-side maps where the client and the server have an identical copies that are shipped with the game (or possibly via an update). Something like a MUD or SecondLife has server-side 'maps' that are stored on the server and sent to the client. Server side maps allow for continuous changes to the game world, if you allow others to get the server software then also totally different worlds, and can even be edited live if you want. But the down side is they will delay the tile loading time, will need a larger buffer for tiles off the edge (in case there is an intermittent network interruption), it will put more strain on the server (since now it has to stream chunks/tiles to the client). You could possibly make a 'hybrid' version, where when the client enters a map it checks to see if they have the current version of it and if they don't will download it all from the server in one go (or you can download it perchunk to stop a 30MB transfer for a small edit to a single tile somewhere, or you could look at something that lets you make a 'diff' between 2 maps and just send the diff).

The main difference between implanting client/server side maps will be where the 'game' tiles are loaded from. Either from disk (client) or from a network connection (socket). You might also have to implement the 'graphics' tiles transfer/synchronization if you want to be able to make new tiles as opposed to just maps. In that case you would need to transfer image sprites (simple file transfer would work fine), maintain a list of all the tile\_id to image\_file mappings, and transfer/synchronize that to clients.

If you are doing a MMO you can try to separate the visual components from the ones that effect gameplay/physics. The server only need to know about collisions and any possible interactions. But this will depend a lot on your specific setup (is it pertile collisions or perpixel). For example World of Warcraft looks like a 3D game but if you think about it, it's probably only taking place on a 2D plane (I haven't played it that much so I could be wrong), they could theoretically treat the entire this as a 2D game at the server side.

---
Tags: 2d, tiles, maps
---


# Question
Title: Do I need to ask Microsoft for permission to use their products logo?
I am currently making a trailer of my game for my college project, I would like to note that my game is cross platform. Do I need to ask for permission to use those images in such situation? - When I want to say that their game will be on playable on Windows/Mac/Linux.

# Answer
Microsoft has an FAQ about the use of their trademark.

From that FAQ:

> **Can I use a Microsoft logo to indicate that my product or service runs on or is compatible with a Microsoft technology or service?**
>
> Yes, as long as you have a signed logo license agreement with Microsoft. Microsoft has many logo programs to indicate compatibility with various software, products, and services. For your product to be eligible to display a Microsoft logo, you will be required to demonstrate Microsoft-defined performance and compatibility standards for your product or service. If you do not have a signed logo license agreement from Microsoft, you may not use any Microsoft logo to indicate compatibility with Microsoft software, products, or services.

So it looks like technically, to claim your software runs on Windows, you need to have it logo certified. More information about getting your project certified can be found here.

You *might* be able to fudge the legal lines with the follow:

> **Can I use a Microsoft logo in my school project?**
>
> It is okay to use Microsoft logos in school projects such as book reports, stories, or articles about or involving Microsoft or its software, products, and services. The project should be displayed, used in, or directed to an academic environment.

But it's a stretch. Universities often have legal departments you can ask them if you're uncertain.

Other companies likely have similar requirements, and you'll need to research each company individually if you want to know the true requirements.
> 59 votes

# Answer
Couldn't find the right phrase for search but finally found it, "using corporation trademark". It seems you are allowed to freely use their logo's and trademarks as long as the product is really compatible with their software.

For Apple

> 1. Compatibility: If you are a developer, you may show an image of an Apple product in your promotional/advertising materials to depict that your product is compatible with, or otherwise works with, the Apple product or technology, provided you comply with the following requirements:
>
> a. Your product is in fact compatible with, or otherwise works with, the referenced Apple product.
>
> b. The image is an actual photograph of the genuine Apple product and not an artist’s rendering (Note: You must obtain express written permission from Apple before using any photograph owned or licensed by Apple).
>
> c. The Apple product is shown only in the best light, in a manner or context that reflects favorably on the Apple products and on Apple Inc.
>
> d. The reference to Apple does not create a sense of endorsement or sponsorship by, or other false association with, Apple or Apple products.
>
> For further information with respect to Apple’s copyrights, please submit your request in writing to the Copyright Team.

I guess the "picture" logo will require sending a mail to the copyright department

> http://www.apple.com/legal/contact/#copyright

For Windows

For Linux
> 10 votes

# Answer
I do know if you happen to have an app available in the Mac App Store, iOS App Store, or Google Play, they have available banners at your disposal to post on your website. Microsoft used to have the Microsoft Compatibility logo available to Software Manufacturers that pass the hardware guidelines for said software. I know Apple is very meticulous about what kind of logos you can use, and they specifically have a press kit with different logos and resolutions.

That being said, your Chrome, IE, and Firefox logos above are antiquated, and there are newer versions out there. Windows is the logo from XP, and the Mac logo looks a bit old, too.
> 5 votes

# Answer
Legally, no. It is explicitly allowed to use a trademark when the use is limited to describing a factual aspect of your product. This is called Nominative Use.

It doesn't mean that the owners of these logos will like you. They will generally suggest that you are not allowed to use them, but their opinion does not have the force of law.
> 2 votes

# Answer
Since answers here mostly seem to concentrate around other operating systems, let me answer in the context of Linux, since you've asked about that as well.

**Yes**, you can do *anything you want* with Tux, the Linux *mascot*.

source: http://www.isc.tamu.edu/~lewing/linux/
> 2 votes

# Answer
Yes you can but only for a non commercial use or a private use, see here: http://www.microsoft.com/en-us/legal/intellectualproperty/Trademarks/Usage/Logo.aspx
> 0 votes

---
Tags: windows, trademark
---


# Question
Title: Storing player's tilemap position inside the player object
I'm trying to create a multidimensional array as a sort of 2D map for a text-based RPG game. I want to create a multidimensional array that's, for example, 5x5. The array would be filled with 0s to represent a space void of an object. Other numbers would represent the `player` on the map, an `enemy`, an `npc`, a `skill-object` (like an enchantment table, etc.), `doors` that link to maps, and `chests`. They would all have different values to represent what object is there. If a `player` tries walking into a `chest`, it would instead loot the `chest`. Then the `chest` would be reset to 0 to represent the empty space, letting the `player` walk there and representing that there is no more chest. If the `player` tries walking over an `enemy`, it would instead engage combat (handled by a separate class and functions). Walking over a number representing a `door` would link to another multidimensional array that represents another map.

I want to know what kind of property I need to put inside the `player` class to handle where he is on the map. A function would then change that value to move him around the map. Would creating a class for a map be a good idea? Would I store the values for the objects there or in the individual classes for those objects? How would I go about this? Thank you for your help. For reference, here's my player class (careful, it's long...):

```
public class Player
{
    public string   name        { get; set; }        //Name of Player
    public int      level       { get; set; }        //Player's combat level         (average of combat-related skills' levels)
    public int      health      { get; set; }        //Player's health               (player dies when this value reaches 0)
    public int      health_max  { get; set; }        //Player's maximum health
    public int      stamina     { get; set; }        //Player's stamina              (used for power attacks, slowly recharges on own)
    public int      stamina_max { get; set; }        //Player's maxiumum stamina
    public int      fatigue     { get; set; }        //Player's fatigue rate         (player cannot fight or run while fatigue is 100)
    public int      hunger      { get; set; }        //Player's hunger level         (player becomes weaker as hunger increases)
    public int      style       { get; set; }        //Player's fighting style       (refer to styles.txt)
    // tons of skills fields
}

```

# Answer
> I want to know what kind of property I need to put inside the player class to handle where he is on the map

A point.

```
 public Point Location;

```

Or two coordinates:

```
 public int X,Y;

```

In other way, for the skills, I would use a Dictionary, is more versatile.

```
 Dictionary<SkillType, Skill> Skills;

 void InitializeSkills()
 {
     foreach (var key in Enum.GetValues(typeof(SkillType)).Cast<SkillType>())
     {
         Skills.Add(key, new Skill()));
     }
 }

```

This is equivalent to your players class skill definition area... I think that is not your final code, but it you need load skill definitions from xml is easier now to adapt the code, and create them programatically.
> 1 votes

---
Tags: c#, text-based
---


# Question
Title: Procedural river or road generation for infinite terrain
I should say paths, not roads as I'm thinking more medieval-like. Also, not looking for realism. The answer I'm looking for will be to fit into the mold I describe rather than realism.

I am looking for a method to generate procedural roads/rivers in a curvy sort of fashion, but I'm wanting to do so for a infinite terrain type system. Just like how perlin noise generates blobs, I'm wanting to generate random length line segments (possibly infinite length).

I'm aware of strategies like the suggested answer found here, however it relies on a specified start and end point to work, I don't have a specified start and end point. I'd like to be able to simply call a function using arbitrary coordinates and have it return whether the specific coordinates are part of the river/road.

**I am not wanting to require terrain to be generated in advance. That includes a heightmap (like used for rainfall simulations or similar). I would also not want to require a start/end point.**

Is there such an algorithm or tweak to a noise algorithm someone might know of to accomplish what I'm trying to explain?

The closest I've came to so far is multi-ridged fractals, if I'm using the name properly. I'm just taking the absolute value of value noise (assuming it is scaled to -1 to +1) and setting a threshold. My primary issue with this is the lines overlap way too often, are mostly circular, sometimes converge to form large lakes which is neat but undesired, and often times the thickness of the lines vary too much.

Here's a picture of what I have so far in 2D, but at a very high frequency to show more detail:

# Answer
Just my idea to archive this what you want without (much) precomputation and the possibility for an infinite world.

The first pice of the algorithm is the usage of Voronoi-Diagramms. You divide your world into grids, each grid does have an adress in the form (xgrid, ygrid). For each cell in which you need to create roads you put the xgrid and ygrid variables into a hash function which returns a number *CellSeed*. You use *CellSeed* as the seed for a random number generator which generates the coordinates of the points for the Voronoi Diagramm.

Now you need to search the edges of the diagram and the nodes where multiple edges collide. You can also store the information into a graph for more easy access.

After this step you can search paths through the network which are valid.

For valid paths you can now create the roads (they do have sharph edges).

*Note*: You also need to generate the coordinates of the Voronio diagram for all neightbor cells so you don't have borders on the edges of the cell.

If you don't want sharph edges you can calculate the middlepoint of each connection and use the direction as a tangent for a bezier interpolation between two edges in the graph.

**About the usage of Voronoi-Diagramms**

To archive city like road structures the points from the pseudo random function can be aligned on a grid, so the ways are rectangle shaped.

For more county like roads the points have to be more unordered.

**About the Pseudo Random function to generate the positions of the points for the Voronoi-Diagramms**

It can be a normal random function or a Hammersley set for a more uniform non-clumpy distribution of the points.
> 12 votes

# Answer
For road (and city) creation, the best paper I found is this one :

Procedural Modeling of Cities by Y Parish and P Müller

This uses L-System and it can generate US and EU road patterns. If you don't want to generate roads for a whole city, you can just generate the main roads. It can take a height map, a water map and a population density map in input.
> 8 votes

# Answer
http://vterrain.org/Culture/Roads/ section "Generating 3D Roads" has some **information on road generation**.

The problem with **roads** is that they **connect landmarks** (although they often **follow the terrain** instead of going straight from A to B).

Personally, I'd generate the terrain, then place rivers (maybe using erosion, see http://vterrain.org/Water/ section "hydrogeology"), then place cities in places where it makes sense (e.g. near a river or other source of water, or in a place where water could be transported to using aqueducts or water towers and pipes) and finally generate roads between cities.

To make this more easy to use in a procedural world, you could create intermediate points on the terrain where roads would be most likely to go when generated in that place, then connect the intermediate points if a road is actually created in that place.
> 6 votes

# Answer
First, rivers and roads are very different. Roads tend to follow isolines (same/similar elevation) - the reason being it is much easier to travel on roads that don't rise or fall much. Rivers, on the other hand, travel perpendicular to isolines/isoclines (downhill). Rivers form in basins (collections of mountains that all flow downwards to a given valley) and tend to form tree-like structures. Additionally, roads often travel perpendicular to rivers, in order to form logical bridges. Best idea is to first generate rivers, and then create logical roads (i.e. roads between cities). I don't have time to go into more detail unfortunately but hopefully this will get you on the right track.

It might seem obvious, but look at Google maps at various types of terrain and roads; you will get a better sense of how they should look.
> 4 votes

---
Tags: algorithm, procedural-generation
---


# Question
Title: How can I maintain a rectangular formation when units are added or removed?
I've got bots in a rectangular formation with rows and columns. A problem arises when a bot is added or removed from the formation. When this happens, the bots have to **rearrange themselves** so that the rectangular formation is still roughly the same aspect ratio, and is as rectangular as possible. How to do this?

Some ideas:

* When a bot is added or removed, use the new total number of bots and a desired constant aspect ratio to calculate the new width and height of the formation that most closely fits that aspect ratio. Then somehow reshuffle the bots to fit the new dimensions.
* When a bot is removed, move the bot that was behind it into it's place, and continue until you reach the end of the formation. Then even out the back rank as much as possible by somehow shuffling the bots in the back rank.
* Another idea that's completely different is to mimic the way molecule structures stay together. Make every bot want to be surrounded by four other bots by attracting the four closest bots, and repelling the rest. Repel all bots (including the four) that are too close to ensure separation using inverse square law. You'd also need an additional force to shape of the entire structure. But, this sounds very computationally expensive.

**UPDATE**: So looking into sarahm's answer, I came up with a good general function that gives good dimensions.

First I solved the below simultaneous equation for width and height, and then rounded the answers.

```
width/height=aspect ratio of your choice
width*height=number of bots

```

This gives you the closest integer rectangle to that aspect ratio for your number of bots. The closest rectangle will half the time be a too large, and half the time be a too small (of course sometimes it will be just right but who cares about those). In the cases where the rectangle is a *little* too large, nothing needs to be done. The back rank will just end up being almost full, which is ideal. In the cases where the rectangle is a *little* too small, you got problems because that teeny tiny overflow will have to go to its own rank created a rank with only a few bots on it, which doesn't look pretty. There are also cases where the difference is *large* (larger than half the width), in which case add or subtract one rank to make the difference small. Then, when the rectangle is too small, add one column to make it just a little bit larger. After doing that it *looks* like the back rank will always have at least *half* as many bots as the other ranks.

**UPDATE**

Once you got the dimensions, compare them to the current dimensions. If the frontage of the new dimension is bigger, for every rank, pop bots from the rank below, and push them onto the current rank until that the number of bots on that rank is equal to the frontage. Continue that algorithm until you get to the back rank. Using this algorithm, bots will move to fit into the new dimension efficiently. After that, I simply push the new old onto the back rank. The algorithm is slightly different for the cases where the new frontage is smaller, but you can figure it out!

There's two more problems next. Deletion, and a more flexible addition method where new bots are not necessarily assigned to the back rank but whichever position is closest to them at the moment they are added.

# Answer
> 16 votes
Another technique is to mimic that used by Napoleonic battalions (and probably as far back as Greek phalanxes if not further).

Frontage is generally maintained constant, and as a man falls (in any rank except the back) he is replaced by the man directly behind him stepping forward. The back rank is shuffled by the NCO's to ensure a few men at the extreme of each flank, and otherwise to fill in evenly.

The frontage is only reduced when the back rank falls below pre-specified densities. Likewise, when the back rank is overfull the extras first start filling in an additional rank from both flanks in, and then the frontage is increased.

When changing frontage, I suggest having your bots file out from the back rank to both flanks when increasing frontage, and filing in from both flanks to the back rank when reducing frontage.

If I am correct in inferring that you are looking for a "military" impression, and having your bot organizations look like phalanxes, I believe this ordered re-arrangement is a better way to achieve that end.

**Update**:
One simple way to manage the back row is to divide the back-row units into three squads: one on each flank and one in the centre. Depending on whether the frontage is odd or even, and whether the number of back-row units is congruent to 0,1,or 2 mod 3, there are exactly six cases to manage.

As an enhancement to the above, consider spacing the last unit(s) of each back-row squad once the fill drops below a threshold, like this:
xxx.x....x.xxx.x....x.xxx
or this:
xx.x.x...x.xxx.x...x.x.xx
A bit more work, for an even better appearance.

**Update #2**:
An additional thought on formation depth. The impact of volley fire, combined with the modern bayonet, made depths of 3 or 4 adequate in the late 18th and early 19th century. (The British **rarely** fought in 2 ranks, contrary to popular belief, until late in a battle; for one, it made their lines too long to form square quickly.) Prior to that it was common to have greater depths, perhaps up to 8 or 10 for a Greek phalanx equipped with Sarissa. Choose a depth that creates the impression you desire.

Armies in real life try to maintain unit frontage as long as possible, at the expense of increased unit brittleness, as this makes laying out a battlefield simpler. Caesar at Pharsalus deliberately reduced his unit depth to increase frontage to match that of Pompey's forces. As the quote goes: "We win or die today; Pompey's men have other choices." (which Caesar had cleverly and carefully ensured, of course).

# Answer
> 7 votes
Assuming a unit is a linear datastructure (e.g. a **list**) of bots.

First, you have to **add/remove the bot to/from the datastructure** and determine the new number of bots in the unit.

Then, you have to determine the new amount of rows and columns using https://en.wikipedia.org/wiki/Integer\_factorization.

Of course, this is not always possible due to **prime numbers**. When the new unit size is a prime number, you need to use the next larger unit size which isn't.

Then, just iterate over the datastructure, assigning bots in order to the rows and columns.

For placing the bots, just iterate over the datastructure, assigning each bot a position offset from the units position by an amount determined by the row and column the bot is in (or, set that point as a target for the bots movement).

To make a unit with the **center at one corner**, the position of a bot is given by

unitPosition + *heading* * columnNumber * botSeparationDistance + *rightVector* * rowNumber * botSeparationDistance

To make a unit with the **center in the middle**, the position of a bot is given by

unitPosition + *heading* * (columnNumber * unitSeparationDistance - 0.5 * (numberOfColumns * botSeparationDistance) + *rightVector* * rowNumber * botSeparationDistance - 0.5 * (numberOfRows * botSeparationDistance)

where *heading* is a vector pointing in the direction the unit is facing and *rightVector* is a vector orthogonal to *heading*.

botSeparationDistance can be tweaked to make bots stand further apart or closer together.

If you're feeling fancy, you can offset the **last row of bots** by *rightVector* * 0.5 * (numberOfColumns - actualNumberOfBotsInRow) to **center** them **on the formation**.

# Answer
> 2 votes
I would store the possible positions in a graph with larger values being smaller rectangles.

```
[4][3][2][1]
[3][3][2][1]
[2][2][2][1]
[1][1][1][1]

```

Every time a robot is removed search though all the other robots and find the one in a node with the smallest value. Use A\* or a BST algorithim to find it a path from the that smallest value to the vacant space. If there is no robot with a smaller value than the removed one do nothing.

You should also be able to control how the rectangle decays doing this. For example in the below graph when a robot leaves the bottom one from the side would come fill its place.

```
[4.9][3.8][2.7][1.0]
[4.8][3.7][2.6][1.0]
[3.9][3.6][2.5][1.0]
[3.5][3.4][2.4][1.0]
[2.9][2.8][2.3][1.0]
[2.0][2.1][2.2][1.0]
[1.9][1.8][1.7][1.0]
[1.6][1.5][1.4][1.0]

```

Here the one at 3.8 is removed so the one at 2.5 comes and fills its place.

```
[o][x][o][ ]
[o][o][o][ ]
[o][o][r][ ]
[o][o][ ][ ]
[o][o][ ][ ]
[ ][ ][ ][ ]
[ ][ ][ ][ ]
[ ][ ][ ][ ]

```

Another example. Here 2.8 is removed so the smallest node 2.2 comes an fills its place.

```
[o][o][o][ ]
[o][o][o][ ]
[o][o][o][ ]
[o][o][o][ ]
[o][x][r][ ]
[ ][ ][ ][ ]
[ ][ ][ ][ ]
[ ][ ][ ][ ]

```

You probably want a ring of nodes with value 0 that you never populate around the outside for your pathfinding algorithim to find the hole with.

```
[0.0][0.0][0.0][0.0][0.0][0.0]
[0.0][4.9][3.8][2.7][1.0][0.0]
[0.0][4.8][3.7][2.6][1.0][0.0]
[0.0][3.9][3.6][2.5][1.0][0.0]
[0.0][3.5][3.4][2.4][1.0][0.0]
[0.0][2.9][2.8][2.3][1.0][0.0]
[0.0][2.0][2.1][2.2][1.0][0.0]
[0.0][1.9][1.8][1.7][1.0][0.0]
[0.0][1.6][1.5][1.4][1.0][0.0]
[0.0][0.0][0.0][0.0][0.0][0.0]

```

A good tutorial on A\* can be found here.

---
Tags: mathematics, algorithm, ai, software-engineering
---