title: 2D Rain Creation (and Fluid Dynamics)

text:
# Question
Title: 2D Rain Creation (and Fluid Dynamics)
I am experimenting with weather conditions in a game of mine, and I was impressed by the way Starbound handled the rain. Basically, when rain hits the ground, it's either dispersed horizontally (and absorbed by the ground), or it creates piles of water (when raindrops land inside a hole in the ground).

This video demonstrates this clearly: https://i.stack.imgur.com/AGpgX.jpg

I know how to make rain fall and check where it hits the ground, but that's where I get stuck. My question is: how could this have been created? And how could one model the water flow so perfectly, without killing performance?

Thanks in advance!

# Answer
Starbound's water system is actually 2D tile based cellular automata. Each tile on the screen that does not contain a front tile layer, is capable of holding water. The amount of water is calculated via cellular automata.

More information on this technique here:

http://www.gamasutra.com/view/feature/134736/an\_intro\_to\_cellular\_automation.php

http://www.jgallant.com/2d-liquid-simulator-with-cellular-automaton-in-unity/

As for the rain drops, those are particles. They serve mainly to fake that there is actually water falling from the sky. The water accumulates only because the game knows it is currently raining. The individual drops have nothing to do with the actual formation of the water pools.

The way they get it to accumulate, is by determining where there are holes in the top layer of the ground. If there is an area that can accumulate water, the cells in that area increment their water levels accordingly.

Starbound also deals with water pressure, and their rendering technique is pretty amazing. They have the best 2D implementation of water simulations physics using cellular automata that I have ever seen.

Here is a primitive view of a liquid physics engine, utilizing the above mentioned cellular automata technique. The rendering portion becomes a little more complex, as your water is represented by a numerical value.

http://www.jgallant.com/images/pressuretest.gif

In this example, a very simple improvement would be to hide water cells that have less than 1 full unit of water in it's tile if there is no solid tile below it. But then, you are hiding the water flow. Instead of hiding it, you would have to determine how the water is flowing, and then draw the appropriate water sprite in its place.
> 8 votes

# Answer
There's a bunch of ways to approach this. As always 'it depends'

And so I guess one way would be this way.. Given an arbitrary 'dip in the ground' Overlay a 'water box' that bounds it. The ground and waterbox are drawn in layers so that the ground is shown first, the waterbox after.

every time a water drop hits the dip in the ground add one to the waterbox. When the waterbox reaches a magic number, add a line of water. So say 10 drops land in the dip, this adds one line to the waterbox.

So say the waterbox is 32X32 pixels. Add one line of water colour from 0,31- 31,31. Another 10 drops, draw a line from 0,30 - 31,30. So as drops accumulate, you build up the waterbox from the bottom until its full.

Hope that makes sense.
> 3 votes

---
Tags: 2d, water, fluid-dynamics
---


# Question
Title: How to create and choose sprite sheet for different mobile screen resolution in Unity
## Background

We’re working on a 2D mobile game. We want to publish the game on all apple devices which at least support iOS 7 and to all android devices which at least support Android 4 OS. These devices come with different screen size and resolution. For example, in following image we have different Aspect ratios and resolutions that we almost found in every mobile device.

## Question

1. Do we need to choose a higher resolution to design a sprite sheet for those devices which share same aspect ratio? For example, iPhone 3Gs and iPhone 4s share aspect ratio of 3:2. But they have different screen resolution.
2. If those devices come with different aspect ratio. Do we need to create multiple sprite sheet for multiple aspect ratio?
3. What are the best practices that unity offer us to design and create sprite sheet for multiple mobile device, which are optimize to even lower mobile device?

# Answer
You do not need to have different sprite sheets or individual sprites for different aspect ratio.

**ANSWERS TO YOUR 3 QUESTIONS**

1. It's a good idea to have sprites made for the largest resolution possible. In that way it won't have pixelation on HD or higher end screens. But also note that they will increase the size of your build, and that is also always a thing to look out for.
2. No. You can create sprite sheets for the maximum size that you want to fulfill. Then you can choose to either crop out the remaining of the sprites from the sides for smaller aspect ratios, or you could scale them. Sometimes art cannot be scaled else it'd look bad, in which case you'd want to keep it the same. If you're working with UGui or any other GUI tools, look at how pixel perfection and preserve aspect ratios is handled. You may need to reposition some items from code if you do this. **MIGHT (NOT NECESSARILY)** have to.
3. Use the concept of atlasing sprites instead of having single image. Usually for mobile devices, have a maximum of 2048\*2048 size atlases. Look into assetbundles, as they are very useful if your game uses tons of art. It's also useful to push updates without updating the appstore build \*conditions apply. When you have a sprite/psd selected in the editor, instead of keeping the image as a sprite type, you could change it to advanced, and then play around with the Aniso level, the Generate MipMaps option and the compression types. As far as I know, the DXT5 compression servers the best compression.

Hope this helps :)
> 0 votes

---
Tags: unity, android, ios, spritesheet, aspect-ratio
---


# Question
Title: Is it possible to get vertices after Primitive Assembly step (after face culling)?
I would like to check which vertices will be rendered from direction A (with face culling enabled) and render it from another direction to visualize face culling effect.

I have found information that using Transform Feedback I can received data from vertex or geometry shader. My question is if is it possible to get data from primitive assembly step and use it to render scene from another direction or should I calculate by myself which faces should not be rendered?

Any help and information would be greatly appreciated

# Answer
If you have enabled culling, then the vertices won't be available after the vertex shading stage. They will be culled.

If you wish to visualize the culled faces, you could * provide some option to toggle between front & back face culling at runtime. * or, disable culling and instead detect backwards facing triangles in the geometry shader and modify them somehow to distinguish them from non-culled triangles.

You can detect that a triangle is backwards facing by taking the dot product of your viewing direction and the triangles normal. If its \<0, triangle is facing away from view.
> 1 votes

---
Tags: opengl, rendering
---


# Question
Title: Why doesn't my wave movement code account for the game object's initial position?
I want an object to move like wave. Currently, when I start the game the object's position doesn't account for its initial position. How would I fix this?

```
float amplitudeX = 5.0f;
float amplitudeY = 2.5f;
float omegaX = 0.5f;
float omegaY = 2.5f;
float index;

public void Update() {
    index += Time.deltaTime;
    float x = amplitudeX*Mathf.Cos (omegaX*index);
    float y = Mathf.Abs (amplitudeY*Mathf.Sin (omegaY*index));
    transform.localPosition= new Vector3(x,y,0);
}

```

# Answer
> 2 votes
You are overriding the initial position by setting the `localPosition` directly. You probably want to instead either use the calculated value as a velocity, which I believe would be applied to the rigid body component, or you could calculate the translation manually. That could be done by saving the original initial position at the `Start` method and adding your wave position to that position. So something along the lines of

```
public void Start() {
    InitialPosition = transform.localPosition;
}

public void Update() {
    transform.localPosition = InitialPosition + WaveMovement;
}

```

---
Tags: unity
---


# Question
Title: Why do we multiply perspective * modelview * point?
A common line in vertex shaders is:

```
gl_Position = projection_matrix * model_view_matrix * object_space_vertex;

```

I've seen this a lot, why isn't it written like

```
gl_Position = object_space_vertex * model_view_matrix * projection_matrix;

```

?

That would be more intuitive I suppose. Is it mathematically wrong?

# Answer
Yes, it isn't what we want to do. Matrix multiplication is not communative, which is to say that switching the order produces different things.

Think of it this way, if you do these operations:

* Turn left 90 degrees
* Go forward 10 meters

You end up at a different position then if you did:

* Go forward 10 meters
* Turn left 90 degrees

This doesn't mean it's mathematically *wrong*, you could very well have a need for doing it in a different order, it's just that for this thing we want to do P\*M\*O and not some other order.
> 9 votes

---
Tags: opengl, shaders, glsl, vertex-shader
---


title: Finding the Distance between 2 Objects

text:
# Question
Title: Finding the Distance between 2 Objects
I have `2` objects One Having a Transformation Matrix `T1` and other Having Transformation Matrix `T2`. And We are having a View Matrix `V` and Projection Matrix `P`. Basically 2 Object are render using this function

```
Render(vec3 position,X Rotation , Y Rotation, Z Rotation, Scaling);

```

So i am having 2 different `T1` and `T2` transformation matrix.

How should i find the `distance between these` `2` objects ? Please Explain ? I have tried by simple formula using position vector but it is giving me incorrect distance ?

# Answer
> 2 votes
The distance formula is as follows. v1 and v2 are your two vectors, type `vec3`. Each one has an x, y, and z property, type `double`.

```
vec3 delta = v2 - v1
double distance = math.sqrt(delta.x^2 + delta.y^2 + delta.z^2)

```

Vector subtraction, as used in the distance formula, can be calculated as follows:

```
double subX = v2.x - v1.x
double subY = v2.y - v1.y
double subZ = v2.z - v1.z
vec3 result = new vec3(subX, subY, subZ)

```

You should try to find a library that does vector math and matrix math for you. Most languages have a good one it'll save you lots of time rewrite needless things, that is unless you're doing it to learn the math.

# Answer
> 0 votes
I'm no expert in programming, but I know mathematics. From what I understand the distance formula is p1 = x2 - x1 ; p2 = y2 - y1; d= math.sqrt(p1+P2)

I'm not sure where to begin on making z move however. . . .I think that would go into the realm of circumference which is my worst subject currently.

---
Tags: collision-detection, mathematics, matrix, transformation
---


# Question
Title: Passing heightmap data to btHeightfieldTerrainShape constructor
I was searching for a couple of hours, but I didn't find final solution, after trying many ways.

I'm trying to get heightmap heights data, and pass it to btHeightfieldTerrainShape.

Let's say my heightmap has 1024x1024 resolution. I've stored each pixel color of my heightmap inside dynamic array as a final vertex height.

I use them to create and render terrain's model and it works fine.

But my question is: how to correctly convert those heights for bullet? I've tried like this:

```
std::vector<float> dataVector;

for (size_t i = 0; i < terrainWidth; ++i)
    for (size_t j = 0; j < terrainHeight; j++)
        dataVector.push_back(getHeight(i, j));

```

Then pass it to the constructor: `new btHeightfieldTerrainShape(terrainWidth, terrainHeight, &dataVector[0], ...);`

...but I expected that it won't be working.

# Answer
Don't create dataVector as you do, it will be destroyed when reaching the end of his environment, better store that array in an object member, or if you can't do otherwise in a global variable.
> 0 votes

---
Tags: c++, terrain, bullet-physics
---


title: Data Structures for Game State

text:
# Question
Title: Data Structures for Game State
I'm writing my first game. It's an adventure-RPG in the style of Starflight. I'm thinking about how to represent game state. There are three obvious parts of game state: dialog, combat, and story/quest.

I could have three separate data structures, but some state elements don't fall clearly into a single jurisdiction. For example, maybe a quest requires that you damage several ships without destroying them. Quest directives are generally story elements, and ship damage is an element of combat, so in this case a collection of combat elements is equivalent to a story element.

You might suggest a workaround where the quest element is separate, and isn't updated until combat ends. This is limited, though. What if a particular ship is supposed to spawn during combat once the quest directive is met? Now you have a dependence between elements in two different data structures -- elements that represent essentially the same piece of information.

This might lead me to a use a monolithic structure that houses all state elements, but intuitively this strikes me as sloppy and error-prone.

So how is it generally done?

# Answer
This is sort of open ended, but I would generally recommend that you have a list of open quests, separate from your other state.

When something interesting happens, you generate an event that describes what happened ("player ship took 9 points damage from enemy Foo"), and pass that event through your quest queue - each quest would then decide if it cared about the event, and would react accordingly. Depending on your implementation language, you can have an event hierarchy to let you decide how to react - for example, you could have a "combat" event (if a quest cared about any hostilities to break a truce), then a "combat damage" or "combat miss" set (to trigger an ally's help, or give bonus points to the player for avoiding damage), etc.

In your example case, once a quest was satisfied by seeing a particular event, you could simply spawn your ship.

This sort of de-coupling has proved useful on a number of shipping titles.
> 4 votes

---
Tags: data-structure, game-state
---


# Question
Title: Rotation smoothing with Slerp snaps to center when switching between different destination vectors
I'm making a 3D space shooter in Unity (think Star Fox). The ship, when I move it around the map, should rotate slightly (smoothly) in the direction I'm controlling it.

I have smoothness mostly working. When I press an arrow key, the ship banks in that direction, and when I release it, it smoothly returns to the default rotation.

However, if I quickly change the direction it's rotating before it has the chance to get back to the default rotation, instead of rotating from "banking left" to "banking right", for example, it instantly snaps to the default rotation before beginning the smooth rotation.

Here's what it looks like:

In addition, when I connect a joystick (instead of using arrow keys) to control the ship, I get a different problem: The ship has literally no smoothing at all, rotating one-to-one with the direction the joystick is rotated in. Here's what *that* looks like:

Here's the code that controls ship movement:

```
public bool inverted = true;
public float speed = 20; //speed modifier of horizontal/vertical movement
public float rotSpeed = 120; //speed modifer of rotation (ship tilting)
public float ZRotMax = 30f;
public float YRotMax = 50f;
public float XRotMax = 30f;
public float width = 30;
public float height = 15;
public float centerDriftStrength = 5; //lower is stronger, higher is weaker.

// Update is called once per frame
void Update () {
    //Get input
    float controlHorizontal = Input.GetAxis("Horizontal");
    float controlVertical = (inverted ? -Input.GetAxis("Vertical") :
        Input.GetAxis("Vertical"));

    //Add mild center drift
    float moveHorizontal = controlHorizontal - ((transform.position.x)
        / (width * centerDriftStrength));
    float moveVertical = controlVertical - ((transform.position.y)
        / (height * centerDriftStrength));

    //Modify position
    transform.position += (new Vector3(moveHorizontal, moveVertical, 0)
        * speed * Time.deltaTime);

    //Cosmetic rotation based on controller input
    Quaternion oldRot = Quaternion.identity;
    Quaternion newRot = Quaternion.Euler(XRotMax * -controlVertical,
        YRotMax * controlHorizontal, ZRotMax * -controlHorizontal);
    transform.rotation = Quaternion.Slerp(oldRot, newRot,
        Time.deltaTime * rotSpeed);
}

```

In particular:

```
transform.rotation = Quaternion.Slerp(oldRot, newRot, Time.deltaTime * rotSpeed);

```

Seems to be what I need to look at.

rotSpeed should cap the speed of rotation on the ship, so that it can't instantly rotate in a different direction. **Right now, when rotSpeed is less than 120 or so, the ship twitches while rotating, and if it's particularly low, like 10, the ship barely rotates at all.**

(The rotSpeed variable doesn't seem to be working anyways -- setting it to 30000 or something doesn't make the rotation any faster.)

Basically, **I want the ship to always rotate smoothly, never jumping instantly from one rotation to the next.** I'm not sure if I need to use Slerp for this, or if there's some better smoothing method available to Unity.

Thanks, and if anybody knows of other ways to smooth rotation between constantly-changing Vector3s/Quaternions, please tell me!

# Answer
You never told Unity you wanted the plane to rotate from its current rotation. By setting `oldRot` to the identity quaternion, you've said "only ever start from the default orientation, no matter how the plane was oriented last frame"

Secondly, you haven't described a rate of rotation over time. You don't store any kind of rotation progress that can accumulate frame to frame — you're choosing your bank angle using just the time since the last frame (`Time.deltaTime`) and snapping to it immediately — which means at high framerates your plane will bank less, and if the framerate drops it will bank more sharply.

Overall, it looks like what you really want is something like:

```
transform.rotation =
Quaternion.RotateTowards(
       transform.rotation, // start from our current orientation
       newRot, // blend toward the target rotation
       Time.deltaTime * rotationSpeed // turn at most rotationSpeed degrees per second
       );

```

Here, we're using `transform.rotation` to accumulate change over multiple frames, always starting from where we are now.

This will turn at a constant rate until it reaches the target orientation, which can feel abrupt / mechanical. For a smoother feeling, you can scale rotationSpeed down as you change directions or close in on the desired angle.
> 1 votes

---
Tags: unity, rotation, vector, quaternion, lerp
---


# Question
Title: how to make weapon charge up behavior using composition
I am trying to design different weapon behaviors.

Right now, there are 3 different types of weapon behaviors that i would like to implement.

1. When not pressing anything, weapon fires at a regular slow interval. When mouse Pressed, weapon fires at a rapid interval
2. when not pressing anything, weapon does nothing. when mouse pressed, weapon charges up. when mouse released, weapon fires
3. when not pressing anything, weapon charges up automatically. when mouse Pressed, weapon fires, and then automatically the weapon charges up.

I'm sure there are more to add, but I'm just starting to learn about composition. Can someone explain to me how I might generally write such behaviors for the weapons in a composition over inheritance manner? I'd like to be able to simply swap out one weapon behavior for another just to see how the game might change, and I don't want to have to keep copying and pasting code which is what I seemed to be doing.

I'm guessing that I should use an interface (I'm using Java) called WeaponBehavior perhaps? So then should every base weapon implement this interface? And then i put that interface somewhere within my weapon.run() loop that I have made? (Heroes have weapons, and when heroes run, they run their weapons). Or is it that there is a behavior object instead? I think this is what I'm confused about.

I'd just like to know what skeleton code might look like as opposed to what I am currently doing, which is making the behaviors for each specific weapon that inherits from some base weapon.

```
abstract Class Weapon //implements WeaponBehavior??
{
// should I have an object called WeaponBehavior instead of implementing an interface?
Weapon()
{
}

void run()
{
  update();
  //behavior somewhere here?
  render();

}
void update()
{
  //does behavior go in here?
}
abstract void render();//how does the weapon look
abstract void fire(); // this has to be called at some point
abstract void handleMousePress(); //

}

```

# Answer
> 2 votes
Something like the *input handler using Command pattern* should work. The goal is to isolate weapons and their basic operations like `fire()`, `charge()` from the weapon's input behaviour, like the ones you've described.

The example on that page, which is typically encountered, is to translate basic input events - like mouse clicks, key presses - into game commands, like jump/fire. Doing so allows you to easily extend support to other input devices or remap controls. Your scenario is slightly different, with a different goal: of modelling different weapon behaviours.

The role of this handler - let's call it `WeaponBehavior` \- will be to take mouse inputs, and translate that to weapon operations.

Either inheritance or composition will work here; if you choose to use composition, you will pass off mouse events to the weapon's behaviour component:

```
weapon.getBehavior().handleMousePress();

```

And you never have to operate the weapon directly - all will be handled by the behaviour component. Since this is using composition, you can replace that behaviour dynamically to get different input handling characteristics for the same weapon.

---
Tags: java, component-based, design-patterns, inheritance
---


# Question
Title: Texture Tiling and Texture Coordinates in Unreal Engine
I've just started to learn how to develop games and everything is new for me now.

I don't know where to start and I decided to start with Textures and there is something it is difficult to understand for me: `Texture Tiling`.

I'm not an English speaker and I have searched the meaning of tile and tiling on my own language (Spanish) and I think tile is a way to say repeat the texture across the model instead of stretching it.

I have found PolyCount Wiki and this is how they explain tiling:

> Textures can be repeated across a model, by Tiling the TextureCoordinates.

My problem here is that I don't understand the meaning of `Tiling`. Can I replace Tiling with Repeating without changing the meaning of the sentence?

I have another question is about `Texture Coordinates`. On PolyCount Wiki they say that:

> Texture coordinates are measured in a scale of 0.0 to 1.0, with 0.0 and 1.0 at opposite sides of the texture. When a model has a UV distance greater than 1 (for example, UV goes from -1 to 2) then the texture will tile across the model.

How can I know if I model has a UV distance greater that 1?

By the way, I'm using Unreal Engine, and on its Texture Coordinate element I don't understand the meaning of amount of tiling in their UTiling and VTiling properties.

# Answer
You shouldn't care about checking if the UV coordinates are bigger than 1. Every Graphics API (D3D and OpenGL) handles such UV coordinates by taking the modulo 1 of them.

Tiling in graphics world means almost the same thing as in the real world. You take a small piece of texfure abd your repeat it over and over until it fills the whole surface.
> 1 votes

---
Tags: textures, models
---


# Question
Title: How to leave a permanent skid mark on the ground in Unity2D?
I am working on a 2D driving game.

I have a sprite of a car and I set the car movement. Now I need to create a skid mark on the ground. For that I have created an empte game object and added a Trial Renderer component and set the skid mark material to it.

The problem is that when I start moving the car, the skid mark follows the car as if the skid mark is attached to the car.

Is there any simple way to leave a permanent skid mark on the ground in Unity2D?

# Answer
Create a prefab for the skidmark. When you want to draw a skidmark to your scene, you would instantiate this prefab.

```
List<GameObject> Skidmarks = new List<GameObject>();

...

void AddSkidMark() {
    //instantiate the prefab
    GameObject skid = GameObject.Instantiate(Resources.Load("SkidMark")) as GameObject;

    //Set some properties
    skid.transform.position = NewPosition;
    skid.transform.rotation = NewRotation;

    //keep reference of all skidmarks
    Skidmarks.Add(skid);
}

```

If you run into problems with slowdowns because you are instantiating too many skidmarks at once, you are going to want to look into pre-instantiating a bunch of skidmarks and then pooling them for future use.

Utilizing a object pooling is the proper way to tackle this issue.
> 1 votes

---
Tags: unity, c#, 2d, physics, sprites
---


title: On screen enemy indicating arrow

text:
# Question
Title: On screen enemy indicating arrow
I am working on indicating on screen arrow to point towards the enemy. I have a environment which consist of a player and three enemy placed at different position on the environment.I need an arrow indicating the enemy,so that the player can move towards the enemy in the environment.

How can I do this?Can anybody please help me out.

I have got a script on searching.

```
public Texture2D icon; //The icon. Preferably an arrow pointing upwards.
public float iconSize = 50f;
[HideInInspector]
public GUIStyle gooey; //GUIStyle to make the box around the icon invisible. Public so that everything has the default stats.
Vector2 indRange;
float scaleRes = Screen.width / 500; //The width of the screen divided by 500. Will make the GUI automatically
//scale with varying resolutions.
Camera cam;
bool visible = false; //Whether or not the object is visible in the camera.

void Start () {
    visible = GetComponent<SpriteRenderer> ().isVisible;

    cam = Camera.main; //Don't use Camera.main in a looping method, its very slow, as Camera.main actually
    //does a GameObject.Find for an object tagged with MainCamera.

    indRange.x = Screen.width - (Screen.width / 6);
    indRange.y = Screen.height - (Screen.height / 7);
    indRange /= 2f;

    gooey.normal.textColor = new Vector4 (0, 0, 0, 0); //Makes the box around the icon invisible.
    visible=false;
}

void OnGUI () {
    if (visible) {
        Vector3 dir = transform.position - cam.transform.position;
        dir = Vector3.Normalize (dir);
        dir.y *= -1f;

        Vector2 indPos = new Vector2 (indRange.x * dir.x, indRange.y * dir.y);
        indPos = new Vector2 ((Screen.width / 2) + indPos.x,
            (Screen.height / 2) + indPos.y);

        Vector3 pdir = transform.position - cam.ScreenToWorldPoint(new Vector3(indPos.x, indPos.y,
            transform.position.z));
        pdir = Vector3.Normalize(pdir);

        float angle = Mathf.Atan2(pdir.x, pdir.y) * Mathf.Rad2Deg;

        GUIUtility.RotateAroundPivot(angle, indPos); //Rotates the GUI. Only rotates GUI drawn after the rotate is called, not before.
        GUI.Box (new Rect (indPos.x, indPos.y, scaleRes * iconSize, scaleRes * iconSize), icon,gooey);
        GUIUtility.RotateAroundPivot(0, indPos); //Rotates GUI back to the default so that GUI drawn after is not rotated.
    }
}

void OnBecameInvisible() {
    visible = false;
}
//Turns off the indicator if object is onscreen.
void OnBecameVisible() {
    visible = true;
}

```

}

The problem is start when I play the scene the arrow is seen at the start but its get invisible soon

# Answer
> 1 votes
Not sure if it is the best option but what I would do is:

* initialize an image arrow.png loaded in a variable
* get currently selected enemy position x,y
* get your position x2,y2
* get the angle angle1 between you and the enemy with Vector2.Angle method
* draw your arrow at (x+x2)/2 , (y+y2)/2 rotated with the angle1 you got

I do not know Unity and it is possible that there is a class which already cover this.

---
Tags: unity, c#, 2d, physics
---


title: How to make "Events"/ Scripted Scenes

text:
# Question
Title: How to make "Events"/ Scripted Scenes
I want to make cutscenes etc, in my game.

I thought of a similar System like in the RPG Maker:

If you enter a certain Area, a list of commands and arguments is played.

E.g. like this:

\[Move Object: Right, right, right; Wait until done;\]
\[play Sound: sound.sfx\]
\[Show Message: Speaker: player, message\]

I don't want to use external libraries.
Someone has a basic idea on how to implement this?

I thought of a "stack" for these kind of "events", but I'm not sure about it.

# Answer
> 1 votes
You can create a static Script class to handle to handle scripted sequences and have a state in code that allows the script class to run its sequence without interruption. Here is an idea:

Instances

```
Arraylist<Event> events;

class Event {
  boolean eventComplete;

  //different Initializations based on what the event is.
  //EXAMPLE Timer event
  public Event(float timer);
  //EXAMPLE move event();
  public Event(vector2 target);
}

```

Methods

```
setCountDowntimer(float seconds);
lerpPositiontoTarget(Vector2 target);
MovePositiontoTarget(Vector2 target);
setActive(Object object, boolean active);

```

It's a bit tedious because I'm mobile right now.

# Answer
> 0 votes
You could develop a bytecode language for this. Take a look at this: http://gameprogrammingpatterns.com/bytecode.html

Instead of spells as in that example, see the commands as 'walk to' and 'display message' and so on.

---
Tags: java, data-structure, architecture
---


# Question
Title: MMO RTS - Implementing a waiting time with a real time battlefield at the end
So, this is a "how to mix concepts and still remain playable" type of question, with concepts being the *real-timeness* of Age of Empires and *waiting-time-dependency* of Ikariam.

### What I mean?

What I mean by *waiting-time-dependency* is: In Ikariam, once you send your troops out there for war, you can just log-off, because there is nothing you can do besides calling them back mid-journey. The only thing that prevents you from sending troops all over the place in 5 minutes and raiding everything is the time required for sending your troops over to enemy city and leaving your city undefended for the time being.

What I mean by *real-timeness* is: Simply everything happens in real time and your opponent can see it too. You send your troops, you decide which path they will take, you decide who they will attack, and you basically can micro-controll everything (except for wo-lo-lo-lo, yeah...).

### What is the problem?

The problem begins when you try to merge these concepts. The reason first concept works is, no mater if you are online or not, you cannot controll anything happening in the battlefield, it is basically an auto-resolve battle with results being delivered after a waiting time. So you don't have to sit in front of computer for 1 hour and wait for the beginning of the battle, you can simply log-out.

But if you make the battles real-time, then player must be present in game at the time of battle to control his troops. There comes two possibility: Either player must sit in front of the computer whole time, or he must set some kind of an alarm to open his game at the time of the beggining of the battle.

Neither of the options are fun.

So what do you suggest? What can be a great mixture of two concepts?

# Answer
> 4 votes
In a real-time game played over multiple days, any real-time interaction can only happen between two players who are online *right now*. When you have a time-delayed interaction between two players, then you can't expect that the other player will be present when that time is up. People have a life outside of your game, and you should really avoid punishing players who prioritize work, family, friends and sleep over your game. That means you can't have time-delayed player-vs-player realtime combat.

But what you could do is time-delayed player-vs-ai combat.

When the army of a player reached the enemy, they could set up a camp on the overworld-map and wait for the controlling player to log back in and order the attack. The attack will then play out as RTS combat on a regional map with the troops of the defender controlled by the AI. In most RTS systems, an AI will usually be much worse than a skilled human player. So to make sure that the defending player doesn't feel at a disadvantage, the result of losing should not be too harsh for the defender. No player should ever feel like they lost something important because they got screwed by the AI.

# Answer
> 1 votes
I would put both option available: the battle can be auto-managed without having any of the players logged online but one player can log at any moment and take lead and action on the battle giving him an advantage on the AI of the other army.

If a user wants to take the lead on a battle started as auto-managed, the user will be able to do any actions only 10min after asking for manually control his army. In the meantime, a mail is sent to the opposent to allow him to log in time to manually control his army as well.

I always wished to be able to control my team in football manager time to time and let the AI do its job the other times.

---
Tags: game-design, mmorts
---


# Question
Title: Using AddForce() to implement a follow script
Not looking for an implementation to the problem (although that would be good :P), mainly looking to be pointed in the right direction for solving it.

Basically, I want to have various game objects following a single game object, using `rigidbody.AddForce()`. This is to allow for realistic physics simulations as collisions will be a key part of this and using anything but `rigidbody.AddForce()` doesn't really allow for it.

I have been working on implementing this, but the GameObjects which are following always tend to overshoot their target, or they can't quite stop in time when applying reverse force to slow them.

As I've said, I'm mainly looking to be pointed in the right direction, be it some mathematical formulae that I require, or another method that I am overlooking. With that said, a very simple implementation to build-on would be awesome.

All help is greatly appreciated!

Thanks!

# Answer
With AddForce you are not going to have much control over where your character is going to stop. You are going to want to implement your own velocity change calculations on your RigidBody instead of relying on AddForce().

For example:

```
float Speed = 10;
Vector2 Direction = CalculationCurrentDirection();

RigidBody.velocity += Direction * Speed * Time.deltaTime;

```

This will still allow your physics engine to do its thing, and will allow you to be able to control your character a lot better. You can then stop your character when he is near your target position.

Sample implementation:

```
Rigidbody2D RigidBody;

bool ArrivedAtTarget;
float Speed = 10;
float Threshold = 1;

//random target
Vector2 Target = new Vector2(10, 5);

void Start() {
    RigidBody = GetComponent<Rigidbody2D> ();
}

void Update() {
    if (!ArrivedAtTarget) {
        //Get Direction to go straight towards this target
        Vector2 Direction = Target - RigidBody.position;
        Direction.Normalize();
    }
}

//Check position in FixedUpdate
void FixedUpdate() {
    if ((RigidBody.position - Target).magnitude <= Threshold) {
        ArrivedAtTarget = true;
        RigidBody.velocity = Vector2.zero;
    }

    //Set RigidBody Velocity
    RigidBody.velocity += Direction * Speed * Time.deltaTime;
}

```
> 1 votes

---
Tags: unity, c#
---


title: opengl - texture clamping not working

text:
# Question
Title: opengl - texture clamping not working
I'm having a problem with post processing in my deferred renderer. When I'm applying an effect like bloom on top of my scene, the bottom of the bloom effect texture leaks into the top of my screen, the top of the texture leaks into the bottom of the screen, the left into the right of the screen and so on. Looks like the uv coords don't get clamped correctly, although I thought I'd have set that all correctly.

The bloom effect in this case is created in a lower resolution and the gets upsampled using linear filtering.

This image shows the problem:

I render the postprocessing effects using a simple quad:

```
glm::vec3(-1.f, -1.f, 0.f),
glm::vec3(1.f, -1.f, 0.f),
glm::vec3(1.f, 1.f, 0.f),
glm::vec3(-1.f, 1.f, 0.f)

```

This is the vertex shader I use to render the quad:

```
#version 430 core

layout(location = 0) in vec3 POSITION;

noperspective out vec2 tex_coord;

void main(void)
{
    tex_coord = POSITION.xy * 0.5 + 0.5;

    gl_Position = vec4(POSITION.xy, 0.0, 1.0);
}

```

And of course in the fragment shader I'm doing something like this:

```
#version 430 core

uniform sampler2D uTexture;

noperspective in vec2 tex_coord;

out vec4 frag_color;

void main(void)
{
    frag_color = texture(uTexture, tex_coord);
}

```

The effect got rendered into a frame buffer object which got set up like this:

```
glGenFramebuffers(1, &_filterFbo);
glBindFramebuffer(GL_FRAMEBUFFER, _filterFbo);

// filter texture
glGenTextures(1, &_filterTexture);
glBindTexture(GL_TEXTURE_2D, _filterTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, _effectWidth, _effectHeight, 0, GL_RGB, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _filterTexture, 0);

```

I really don't know what's the problem here, I hope anyone got an idea.

Thanks in advance

# Answer
You are creating a 2D texture but you are setting clamping to 2D array texture. Replace this:

```
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

```

with

```
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

```
> 1 votes

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


# Question
Title: Coding style about collisions with geometry
Let's say I'm writing 3D Pacman. I have "Dot" objects throughout my maze, that are structured as follows in the Inspector:

```
Dot (GameObject)
- Sphere w/Collider

```

When I run into the sphere trigger, I can trivially say:

"Get me your parent and check if it's a Dot"

However, I hate baking in the knowledge that some spheres have parents that are Dot objects. If the trigger were on the Dot itself that problem would solve itself, as I could just call GetComponent().

What's a good programmatic style approach to finding out what logical Game Object actually owns the geometry you've collided with? I could add a Tag of "Dot" to the sphere but that's just a level of confirmation, I still would have to walk up to it's parent and check.

# Answer
I have done similar in a few projects... and using Tags (on both parent and child) would be the easiest way (I think). On the collision trigger detection you could do a comparetag like this one :

```
if (hitColliders.gameObject.CompareTag("TagName"))
{
do your stuff here if tag match;
}

```

I am also unsure why there is a "sphere" as a child... is it invisible and only there for the collision? If that is the case, I would get rid of the sphere and put the sphere-collision directly on the dot itself... that would make it way easier if you had to do a Destroy() after collision with tag "player" :)
> 1 votes

# Answer
There are multiple ways to do this.

* Check in a HashSet, a **simple** way of doing this behaviour without the overhead or complexity would be to just add each dot collider to a hashset then when you collide with a sphere collider you check the hashset if the collider is in there. Since it's a hashset very few objects will need to be compared to get the result so it would be **fast** and you wouldn't have to check the parent at all as the colliders themselves would be added to the hashset. All the computation of finding the dot would be at the start or possibly hidden in a loading screen or even though a coroutine (depending on how you choose to search for dots)...
* Create a script called `Dot` (for example) you could then add this to the dot object and do a `getComponent` on it to check if it's a dot.
* Rename to collider, though this would be similar to just having a tag or having the sphere collider on the parent object in the first place.

I'm sure there are many other ways of doing this, these are just of the top of my head.

Hope this helps :)
> 0 votes

---
Tags: unity, c#
---


# Question
Title: How to make enemies randomly choose a path and then come back if wrong one?
So I'm making a 2D Tower Defense-game in Unity with C# where the enemy has to go to the base, but can go to the wrong path randomly and then turns around when the road ends. How can I achieve this?

# Answer
> 1 votes
check the manual for navigation, https://docs.unity3d.com/Manual/nav-NavigationSystem.html. I am guessing that you are able to set a nav mesh even on 2D. And have a value in your enemies that if they reach a point where they can't move forward (combine it with a raycast from the object) they turn back...

I hope i was of some help

# Answer
> 1 votes
Dig up your Dijkstra shortest path algorithm and make the enemy go to the current active node before advancing it.

# Answer
> 0 votes
In order to do the behavior you describe your enemies are going to have to be aware of where there is a choice on which direction to go and (to guarantee they get to the base eventually) what they have already tried.

One way to do this is to **treat the path as a simple graph of nodes with a position and one or more linked nodes**. Once you've done that, your enemies can simply walk from their current position to their next target node. Once they've reached a node, they then pick their next node based on simple logic:

1. Increment the value for the path from the new node that goes to my previous node (note these values should be located on the monster, not the actual shared node, each monster has to figure it out for themselves!)
2. Store the node that goes from this one that has lowest value. If there is a tie choose randomly from the lowest ones available.
3. Increment the value on the current node for the way you're going (this is to make sure we don't turn around unless we're at a dead end)
4. Start walking towards the next target node.

This will cause a monster to wander until it finds the base while always trying the most recent other option when one is available.

* When reaching a dead end (node with 1 linked node) the monster will increment the way it came, and then choose the lowest value path which is... the way it came from (since there are no others)
* When continuing a path (node with 2 linked nodes, think of a corner) the monster will increment the way it came from and continue on to the other option naturally (The increment the way we're going step keeps us from returning to this node with all directions at the same value).
* When reaching an intersection with more than one path forward (node with 3+ linked nodes, your example has 4) the monster will pick randomly from the available nodes one it hasn't tried yet, since the nodes it has tried will all have higher values. In the case that all directions are dead ends, then the lowest valued path will be back the way the monster originally came.

Note that this method makes some assumptions. If your monsters can be teleported then it will cause issues with this method. Likewise if your path has intersections where both paths meet further ahead then you're going to need a better way to keep track of tried paths as this method assumes that the path was exhaustively searched before returning. This will however give you a good start to your framework which you should be able to expand upon, while also allowing twisty paths for free as a bonus.

---
Tags: unity, c#
---


# Question
Title: Infinite space 2d map - how to implement in js
Im not exactly sure how to implement this in JS.

So I want to have a 2d infinite map, but not tiled. The coordinates are there only so that if you are travelling around space you know in what coordinates you are. Or if I want to add a couple of things here and there I can specify the coordinates for the placement.

So the coordinates only serve as grid points, but how would I got about implementing this in JS?

Also, how would I go about storing the different things I want to add to the map. Meaning this is not procedural or anything, it's static, a static map.

Could I just use the canvas grid system?

# Answer
Simple Implementation

```
map = {
    this.mapObjects: [],
    this.myCoords: [0,0,0],
    this.whereAmI: function(){
        console.log(this.myCoords);
    },
    this.AddObjectToMap: function(obj,x,y,z){
        //assume obj contains it's own coordinates in the map.
        obj.x = x;
        obj.y = y;
        obj.z = z;
        this.mapObjects.push(obj);
    },
    this.findobj: function(x,y,z){
        for each (obj in this.mapObjects) {
            //will fail if the coords are stored as floats, doubles, etc.
            if ((x==obj.x) && (y==obj.y) && (z==obj.z)){
                return obj;
            }
        }
    }
}

```

This implementation uses an *implicit* space of infinite size (without bounds). If your system had a fixed boundary (say 2000 x2000), an array would suffice, and would probably be better due to faster indicing. Since it isn't, I recommend using a list containing the map objects, which in turn contains their positions. The trade-off here lies in the speed of retrieval of objects from that list as when the list gets **long**, it'll take **much longer** to loop through it.

Personally, I'd recommend using a tree to store the map objects. It's more complex, but becomes much faster since tree mechanics could be exploited to remove sections of the search space rapidly. (see the binary tree or k-d tree on wikipedia for an example.) Unfortunately, the tradeoff here is the complexity, as you'd have to insert objects into the tree based upon their coordinates.
> 2 votes

---
Tags: 2d, maps, html-canvas, grid
---


# Question
Title: How do I efficiently manage a tile-based map with items and characters?
I'm working on a simple C++ game to learn the language. It's ASCII, and features a tile-based map, enemies and items that spawn randomly. The player is, as usual, the '@' character. I'm trying to find the best way to handle the map and characters. I have the map in a 2D vector. Originally, it was a vector of characters, but then that became too hard to manage and too fixed, so the map is now a 2D vector of `Tile` objects. My enemies are contained in a vector called `NPCs`, and the items that get spawned are contained in a vector called `Items`.

My problem is in handling the relation between my map tiles and enemies/items. When an enemy stands on a tile, I have a pointer in the tile that points to that enemy, called `npcPtr`. Same goes for items, with another attribute of that object called `itemPtr`. This creates problems, because when an enemy dies and gets deleted from the `NPCs` vector, the pointers in the map don't dynamically update, and now point to the wrong enemies. The same happens for items. I partially solved this by updating the pointers in all the tiles after every move, but that does not seem like the best approach. How should I handle this tile/character relation?

I read this similar question, and that's pretty much how I handle things, but it doesn't seem to be an optimal approach. The advantage to having pointers in the tile is that I can check whether that tile is an enemy, an item or nothing; I don't want to lose that functionality. I can also obtain the NPC/item data right away, using the pointer, without having to parse through the `NPCs` vector.

---

## My Code:

```
vector <vector <Tile>> _level //this is my level vector
vector <Character> _NPCs //this is my enemies vector

```

### Making a new tile

```
Tile t //and then I set the tile parameters

```

### Adding a tile to the level

```
levelLine.push_back(t)

```

### Adding a whole line to the level

```
_level.push_back(levelLine)

```

### Making an enemy

```
Character c //and then I set the parameters

```

### Adding an enemy to the `_NPCs` vector

```
_NPCs.push_back(c)

```

### Positioning the enemy objects in the level

```
//for j in level lines and k in level colums
if (j = _NPCs[i].getY() && k = NPCs[i].getX()){
    _level[j][k].setNPCptr(&_NPCs[i]); }

```

### Handling enemy death

```
//re-initialize tile where enemy was to empty tile,
//_NPCptr gets set to nullptr
_NPCs.erase(_NPCs.begin() + npcPosition) //erase NPC from enemy vector

for (size_t i=0; i<_NPCs.size(); i++){
    _level[_NPCs[i].getY()][_NPCs[i].getX()].setNPCptr(&_NPCs[i]);
}

```

# Answer
> 1 votes
The way I handled entities as I call them in my game is to break the map into sectors (4^2 tiles per sector in my case). And further, a separate set of 'active' entities, those which are visible or marked 'always active'.

Each frame, I check to see if the camera has moved and figure out which entities should be moved from their sector to the active set and then which should be removed. Then, I only update/handle entities in the active set.

(This would detach entity position from sector directly, and cut down on the amount of copying things around).

This also helps with spawning, simply add the entity to the active set on spawn and it will be moved to the correct location during the next update cycle.

Using pointers for all entities (sectors and the active set could be vector), you can allocate a new entity when you spawn, and only delete it when the entity is removed completely from the map

One optimization to make (especially on the active set) when removing from a list is to swap the index of the entity you want to remove with the last one, and then decrease the size by one. This way you won't have to shift \[potentially\] an entire list every time you remove something. Note: this will possibly make things change their render order (this could be solved by some Z ordering if you want)

# Answer
> -1 votes
How do you manage the life cycle of your pointer? When an enemy dies, do you free it before reassigning it to another enemy or do you update the pointing directly?

This could help: https://stackoverflow.com/questions/2654415/proper-way-to-reassign-pointers-in-c

---
Tags: tiles, tilemap
---


title: Negative timeout error in game loop

text:
# Question
Title: Negative timeout error in game loop
```
try {
            Thread.sleep( (long) ((lastTime - System.nanoTime() + ns) /1000000) );
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

```

The above code seems to catch a negitive timeout value whenever I close out the program. How do I fix it?

# Answer
> 2 votes
If your last loop took longer than `ns` then your formula will give you a negative wait time since it fell behind schedule.

You have to check if the wait time is negative and skip waiting when that is the case.

Closing the program causes a lot of processing to happen during cleanup making that final loop take a very long time.

---
Tags: java
---


# Question
Title: Is there a way to start UI animation transition with code in unity?
I have made an animation for a button in unity's UI prefab, but i want it to start only at certain times, when i command it with code. How can i do this?

# Answer
So i did this: The button is for jumping, and as long as you hold your finger on it, it will loop the animation. So in the code where i coded the game to check when the +Y force should be added to the player, i set the button to `button.GetComponent<Button>().interactable = true;`, and when the force shouldn't be added, to `button.GetComponent<Button>().interactable = false;`. For this to work, you should add this to the cs file: `public Transform button;`, and in the editor, add the ui button to the script.
> 0 votes

---
Tags: unity, animation, gui
---


# Question
Title: How to set rotation of a projectile in a parabolic arc in Box2D?
I have trouble making my projectile - in this case an arrow - rotate as it should when it's travelling in a parabolic arc. It doesn't rotate at all while travelling, only until it collides with something.

Below is the relevant code I'm using.

```
public class Arrow extends BodyDef{

private Body body;

public Arrow(float x, float y, float halfWidth, float halfHeight, float rotation, float velocity) {
    type = BodyDef.BodyType.DynamicBody;
    position.set(x, y);
    angle = rotation;

    body = Box2DTest.world.createBody(this);
    PolygonShape shapeShaft = new PolygonShape();
    shapeShaft.setAsBox(halfWidth, halfHeight);

    /* Creation of the shaft of the arrow */
    FixtureDef fixtureShaft = new FixtureDef();
    fixtureShaft.shape = shapeShaft;
    fixtureShaft.density = 6.5f;
    fixtureShaft.restitution = 0.4f;
    body.createFixture(fixtureShaft);

    /* Creation of the tip of the arrow, note the higher density */
    PolygonShape shapePoint = new PolygonShape();
    float[] shapePointV = {
            halfWidth, halfHeight * 2,
            halfWidth * 1.5f, 0,
            halfWidth, - halfHeight * 2};
    shapePoint.set(shapePointV);

    FixtureDef fixturePoint = new FixtureDef();
    fixturePoint.shape = shapePoint;
    fixturePoint.density = 26.0f;
    fixturePoint.restitution = 0.05f;
    fixturePoint.friction = 0.5f;
    body.createFixture(fixturePoint);

    body.applyLinearImpulse(MathUtils.cos(rotation) * velocity, MathUtils.sin(rotation) * velocity,
            body.getWorldCenter().x, body.getWorldCenter().y, true);

    //body.applyTorque(-90.0f, true); <-- My attempts to fix this but still doesn't work well
    //body.applyAngularImpulse(-0.5f, true);
    shapeShaft.dispose();
    }

}

```

The Box2DWorld is initialized as such:

> world = new World(new Vector2(0, -9.8f), true);

Here's a picture explaining how it looks and what I want to achieve (Courtesy of vilbeyli in github):

I have also attempted to apply the initial impulse in the bottom-left corner of the arrow but the resulting spin is very imprecise and random.

* Why doesn't the heavier tip make the arrow rotate by itself?
* How can this be fixed?

# Answer
So what you are looking to do is to orient the arrow in the direction it is moving. You can use the velocity on each frame to calculate the rotation angle. You can get the rotation using atan2, so you would call atan2(velocity.y, velocity.x) to get the rotation angle, and then you can use Box2d's SetTransform(position, angle) to set the angle you want the arrow rotated to. You'll need to run this each time the step function is called.
> 1 votes

---
Tags: java, libgdx, physics, box2d, projectile-physics
---


# Question
Title: How to force XNA to render model very far away as a light dot?
Making a space strategy game focusing on commanding a large fleet, with 1000+ ships per side.(I'm new in XNA 3D...below is a test screenshot. The ships will be scaled down another 2-5 times) When a unit is too far away, it's not rendered anymore.(obviously...when people get killed, they die) are there any way (as fast as possible) to force XNA to render the model into a 1-pixel dot if it's too far/smaller than 1 pixel? (I'm thinking about dynamic scaling, but that will probably drag down the performance severely)

# Answer
> 5 votes
Problem is two-fold:

1. Determine how many pixels the model will take when rendered
2. Replace model with a dot

Suggestions:

1. Pick the cut-off distance by eye. So when the model is *this big* and *this far* \- it should be replaced with a dot. I would make it a property of the ship.
2. Render all models that are closer than their cutoff distance as usual. Do not render all models that are farther. Instead render dots (single pixels or sprites, whichever is simpler for you) in their places.

# Answer
> -1 votes
Hmm interesting but I'm not sure if that's the strategy I'd use.. what about using distance as a determining factor or have you looked into or considered camera culling? Something like this article.

---
Tags: 3d, xna-4.0, hlsl
---


# Question
Title: My perlin noise height map doesn't have smooth transitions and goes directly from black to white
I am using lua with the love2d engine to make infinite 2d tiled terrain with perlin noise. This is just the first step and I want to fix the bugs early. The problem is that there is no gradient between the black and white islands. There should be a smooth transition all through the map.

Also there is a line between the two chunks that I can't get rid of. I am completely lost and cannot figure these problems out. Here is what I am going for:

Here is my code.

```
seed = 257
local canvas = love.graphics.newCanvas()

function Interpolate(a, b, x)
    ft = x * 3.1415927
    f = (1 - math.cos(ft)) * 0.5

    return  a*(1-f) + b*f
end

function Noise(x, y)
    n = x + y * seed
    n = bit.bxor((bit.lshift(n,13)),n)
    return ( 1.0 - ( bit.band((n * (n * n * 15731 + 789221) +
      1376312589), 0x7fffffff) / 1073741824.0))
end

function SmoothedNoise1(x, y)
    corners = ( Noise(x-1, y-1)+Noise(x+1, y-1)+Noise(x-1,
      y+1)+Noise(x+1, y+1) ) / 16
    sides   = ( Noise(x-1, y)  +Noise(x+1, y)  +Noise(x, y-1)  +Noise(x,
      y+1) ) /  8
    center  =  Noise(x, y) / 4
    return corners + sides + center
end

function InterpolatedNoise_1(x, y)
    integer_X, fractional_X = math.modf(x)
    integer_Y, fractional_Y = math.modf(y)

    v1 = SmoothedNoise1(integer_X,     integer_Y)
    v2 = SmoothedNoise1(integer_X + 1, integer_Y)
    v3 = SmoothedNoise1(integer_X,     integer_Y + 1)
    v4 = SmoothedNoise1(integer_X + 1, integer_Y + 1)

    i1 = Interpolate(v1 , v2 , fractional_X)
    i2 = Interpolate(v3 , v4 , fractional_X)

    return Interpolate(i1 , i2 , fractional_Y)
end

function getExampleMap()
    mapWidth = 400
    mapHeight = 400
    mapMin = InterpolatedNoise_1(0, 0)
    mapMax = mapMin
    map = {}
    amp = 128
    freq =32
    octaves = 6
    for x = 0, mapWidth - 1 do
        map[x] = {}
        for y = 0, mapHeight - 1 do
            map[x][y] = 0
            for i = 1, octaves do
                map[x][y] = map[x][y] + getNoiseValue(x, y, freq / i,
                  amp / i)
            end
            mapMin = math.min(mapMin, map[x][y])
            mapMax = math.max(mapMax, map[x][y])
        end
    end
    -- /*scale the values between 0 and 255 for rendering in grey
    scale.*/
    mapMultiplier = 255 / (mapMax - mapMin)
    for x = 0, mapWidth - 1 do
        for y = 0, mapHeight - 1 do
            map[x][y] = map[x][y] * mapMultiplier
        end
    end
end

function getExampleMap2()
    mapWidth = 400
    mapHeight = 400
    mapMin = InterpolatedNoise_1(0, 0)
    mapMax = mapMin
    map2 = {}
    amp = 128
    freq =32
    octaves = 6
    for x = 400, (mapWidth + 400) do
        map2[x] = {}
        for y = 0, mapHeight - 1 do
            map2[x][y] = 0
            for i = 1, octaves do
                map2[x][y] = map2[x][y] + getNoiseValue(x, y, freq / i,
                  amp / i)

            end
            mapMin = math.min(mapMin, map2[x][y])
            mapMax = math.max(mapMax, map2[x][y])
        end
    end
    -- /*scale the values between 0 and 255 for rendering in grey
      scale.*/
    mapMultiplier = 255 / (mapMax - mapMin)
    for x = 400, (mapWidth + 400) do
        for y = 0, mapHeight - 1 do
            map2[x][y] = map2[x][y] * mapMultiplier
        end
    end
end

function getNoiseValue(x, y, freq, amp)
    return InterpolatedNoise_1(x / freq, y / freq) * amp
end

function love.load()
    love.window.setMode( 1920, 1080, {fullscreen=false})
    getExampleMap()
    getExampleMap2()
end

function love.draw()

    for x = 0, mapWidth - 1 do
        for y = 0, mapHeight - 1 do
            love.graphics.setColor(map[x][y], map[x][y], map[x][y], 255)
            love.graphics.point(x,y)
        end
    end
    for x = 400, (mapWidth + 400) do
        for y = 0, mapHeight - 1 do
            love.graphics.setColor(map2[x][y], map2[x][y], map2[x][y],
              255)
            love.graphics.point(x,y)
        end
    end

end

function love.update()

end

function love.keyreleased(key)
    if key == "escape" then
        love.event.quit()
    end
end

```

# Answer
There is a bug in the final normalisation code, fortunately it’s easy to fix. You only need to change:

```
map2[x][y] = map2[x][y] * mapMultiplier

```

into:

```
map2[x][y] = (map2[x][y] - mapMin) * mapMultiplier

```
> 2 votes

# Answer
As I said in the comments, what you are using is just value noise, not true Perlin noise. Here's my Lua implementation of true Perlin noise:

```
local function f(t)
  return t * t * t * (t * (6 * t - 15) + 10)
end

local function l(t, a, b)
  return a + t * (b - a)
end

local function g(h, x, y, z)
 local h, u, v, r = h % 16
  if h < 8 then u = x else u = y end
 if h < 4 then v = y elseif h == (12 or 14) then v = x else v = z end
  if h % 2 == 0 then r = u else r = -u end
  if h % 4 == 0 then r = r + v else r = r - v end
  return r
end

local m = math.modf
local function noise(o, x, y, z)
 y, z = y or 1 / 3, z or 2 / 3
    local f, l, g, m = f, l, g, m
  local X, x = m(x % 256)
  local Y, y = m(y % 256)
    local Z, z = m(z % 256)
 local u, v, w = f(x), f(y), f(z)
 local A = o[X] + Y
 local AA = o[A] + Z
 local AB = o[A + 1] + Z
  local B = o[X + 1] + Y
 local BA = o[B] + Z
   local BB = o[B + 1] + Z
 return l(w, l(v, l(u, g(o[AA], x, y, z),
                          g(o[BA], x - 1, y, z)),
                    l(u, g(o[AB], x, y - 1, z),
                        g(o[BB], x - 1, y - 1, z))),
              l(v, l(u, g(o[AA + 1], x, y, z - 1),
                         g(o[BA + 1], x - 1, y, z - 1)),
                   l(u, g(o[AB + 1], x, y - 1, z - 1),
                         g(o[BB + 1], x - 1, y - 1, z - 1))))
end

local m = {
 __index = function(t, i)
        return type(i) == "number" and t[i % 256] or noise
 end}

return function(s)
   local o = {}
  local rand = math.random
 local _ = s and math.randomseed(tonumber(s) or os.time())
 for n = 0, 255 do
     local t = rand(0, 255)
      while o[t] do
           t = rand(0, 255)
     end
      o[t] = n
 end
 return setmetatable(o, m)
end

```

Paste this code in a separated file in the same directory, then in your main.lua file do:

```
function love.load()
    --Assuming you called the module perlin.lua
    newperlin = require("perlin")
    --newperlin is a function that generates Perlin noise objects:

    myperlin = newperlin()
    --when provided no arguments, newperlin seeds the Perlin object with the current time to create an always different result, but you can provide a seed which will create always the same result:
    myperlin = newperlin(seed)

    --then, to create noise:
    local noise = myperlin:noise(x, y, z)
    --y and z are optional; x is mandatory
end

```

Then see this question to understand how to actually get the result you asked for.
> 0 votes

---
Tags: lua, heightmap, love2d, noise
---


# Question
Title: How should I use this 1D perlin noise function?
I'm trying to create a terraria like terrain with SDL2 and C++. For generating the terrain I'm trying to use the 1D noise function from here: https://github.com/SRombauts/SimplexNoise

It's pretty basic and only takes a x value. I've been messing around with it for a while but can't work out what to pass into the function as the x value. I first tried passing just the x value of the column I'm finding the noise for. This just returned 0 every time. Next I tried passing a value between 0 and 1, so I passed it `x / width`. This sort of worked, but the wider I made the terrain, the more spaced out it became.

Hope you understand, what I do give the function for the x value? Thanks in advance.

# Answer
> 0 votes
What Pikalek said is absolutely true about the return value, but the workaround he suggest is not very good.

Instead of adding a random offset, you should divide the current x position with a cobstant value. Let's call this value "smoothness". Higher smoothness means smokther terrain:

```
float smoothness = 20;
float height = 20; // Max height of terrain
for (float x = 0; x < COLUMN_MAX; x++) {
    float val = SimplexNoise::noise(x / smoothness) * height;
    // Stuff
}

```

# Answer
> 0 votes
The function documentation explicitly says:

> @return Noise value in the range\[-1; 1\], value of 0 on all integer coordinates

Since the column number is an integer coord, passing it as input will always give 0 as output. An easy way around that is to add a constant decimal offset to the column number:

```
// seed RNG however you need
randomOffset = ((float) rand() / (RAND_MAX));

// do other setup as needed

// iterate over columns getting a noise value for each
for(int a=0; a<COLUMN_MAX; a++){
   float noiseValue = SimplexNoise::noise(a + randomOffset);

   // use noise value for the current column
}

```

---
Tags: c++, sdl2, perlin-noise, noise, simplex-noise
---


# Question
Title: Libgdx/Android/2D RPG game: optimizing time consuming when switching from Map to Map
I am completely new in game developing and even more new in the use of Libgdx. So far I have successfully done great thing on my game project thanks to all the advices I could have gathered on this forum. I would need your brilliant help once again.

**\- Context:**

I have several TiledMaps and on each one of them, there is an object layer named “trigger”. This layer contains objects with name corresponding to an animation in my code. All the animations of this layer are loaded thanks to TextureRegion.split.

**\- Issue:**

When I load a new map or for instance a new floor in a house, the time spent to preload the animations of this new floor is too high. Here are the tests of the time spent to load 3 animations of 4 frames each and dimension 64x64 pixels (corresponding to 16 tiles):

* 0.7 sec on a Samsung Galaxy S6 (this is far too much for a powerful device and only 3 animations).
* 1.1 secs on a 4 years old Samsung Galaxy Note2.
* 2.2 secs on a 4 years old Sony Xperia M (pretty old and powerless though).

Here is the logic of my gamescreen class:

**\- Possible solutions:**

**1)** *Preload all the animations of the game in the OnCreate and loading screen:*

Far from being a good idea with my current game architecture. I expect having 300+ animations (with the fighting ones, cutscenes…). With above tests, it would take 3+ minutes on a powerful device as the Samsung Galaxy S6 for instance.

**2)** *Preload new map animations in another Thread when the user is approaching a teleport trigger:*

It will be a good idea on device with good double core CPU but I am afraid of a big FPS drop on single core device or not good double core CPU (like double 600Mhz ones).

**3)** *Label a group of animations with a level-flag and preload them only if level flag changes:*

For instance: Level1 flag for 2 exteriors which contains 10 interiors (houses for example)

Level2 flag for 1 exterior and 6 interiors.

On that example, it will just require to preload and having a loading screen when we change of level but with the current architecture of my game code, it will still be a lot of time consuming.

If there is 20 animations and 20 fights animation per level it will be still 40 animations which represent about 7-9 sec on Samsung Galaxy S6 without including sounds loading…

**4)** *Refactor all my code and include logic I was not aware of.*

I think it is the best option here. I heard of AsseManager for instance but I have no idea how it is working with Animation object.

Thank you all for your help in advance!

# Answer
Thanks to Philipp's advice, the profiler made me found that I was calling tmx.loader in a forgotten loop somewhere (I was so stupid back then).

By correcting it, my loading time went from 0.7 sec on my S6 to 0.02. Thank you so much.
> 1 votes

---
Tags: android, libgdx, optimization
---


# Question
Title: Sending Vector3 from Unity to custom C# server
I'm working on a multiplayer game in which the server is a custom C# server. What I want to do is to store the position of each player in my database.

In my case I'm sending Vector3 as an object through NetworkStream, the problem is how to access to that object in the server side. As you know there is no Vector3 class out there.

I don't want to get the object sent by the client as a string, manipulate it to get the coordinate. I want directly to access the coordinate of the Vector3 in the server side.

# Answer
You cannot just send a Vector3 over the network, the data has to be serialized first. Either you are going to serialize it manually, or you use some sort of helper libraries that obfuscate all the serialization process from you.

Personally I prefer to construct my own serializer/deserializer when dealing with network packets.

A vector3 can be easily serialized to a short string, and then deserialized into a container object server side in order to consume the data.

```
string data = v3.x + "," + v3.y + "," + v3.z;

```

On server:

```
//custom vector3
struct Vector3 {
    float X;
    float Y;
    float Z;
    public Vector3(float x, float y, float z) {
        X = x;
        Y = y;
        Z = z;
    }
}

//Data comes in
string[] data = networkData.Split(',');
Vector3 v3 = new Vector3(Single.Parse(data[0]), Single.Parse(data[1]), Single.Parse(data[2]));

//Use data
print(v3.x);

```
> 1 votes

# Answer
If you insist on sending the `Vector3` object, you will need to create a `Vector3` class on your "custom C# server" to parse the object. If you don't want to do that, you should be sending data out of the `Vector3` to your server. You can't just take an object and parse it's contents without your server knowing anything about the object.
> 0 votes

---
Tags: unity, c#, networking, udp
---


# Question
Title: change the image of button click in unity2D
I want to change the image on the button click.I have two two button(front and back).When I click on front button the image should get changed.When I click backward the previous image should be loaded.

How can I do it

# Answer
> 1 votes
1.

You have an Image component or Texture2D component

Image image;

// or Texture2D texture;

2.

You have an array of sprites

Texture2D\[\] mySprites;

3.

for right button click -\> i++

for left button click -\> i--

image.sprite=mySprites\[i\];

// or texture = mySprites\[i\];

I think that's what you are looking for :)

# Answer
> 0 votes
Here its a working script .

```
public Sprite[] gallery; //store all your images in here at design time
public Image displayImage; //The current image thats visible
public Button nextImg; //Button to view next image
public Button prevImg; //Button to view previous image
public int i = 0; //Will control where in the array you are

public void BtnNext () {
    if(i + 1 < gallery.Length){
        i++;
    }
}

public void BtnPrev () {
    if(i - 1 > 0){
        i--;
    }
}

void Update () {
    displayImage.sprite = gallery[i];
}

```

---
Tags: unity, c#
---


title: How to name key RPG concepts in Java?

text:
# Question
Title: How to name key RPG concepts in Java?
I'm writing a basic RPG at the moment, with characters, races, classes, and the characters evolve on maps, naturally.

How to go around the default names that exist in `java.lang` and `java.util`. I'm having a hard time trying to find equivalent names to the following RPG concepts that do not clash with Java basic utilities. Typically, the words `Character`, `Class` and `Map` cause me trouble. For instance this is how typically clashes would occur:

```
// Line 322, well below the imports
char[] characters = new String("foo").toCharArray();
Character character = new Character();
Map map = getMap();
Class heroClass = getDefaultClass();
// do stuff

```

In this example, it's hard to tell if `Character` is `java.lang.Character` or `mygame.engine.Character`. What type is `Map`? Can anyone answer without seeing the imports?

I could use the fully qualified name:

```
java.lang.Character c = new String("foo").toCharArray()[0];
mygame.engine.Character character = new mygame.engine.Character();
java.util.Map map = getMap();
mygame.engine.Class heroClass = getDefaultClass();
// Do stuff.

```

But in the long run, and from experience, this is barely readable.

So I'd like to know what are usual techniques and/or synonyms that people use to both avoid confusion and unreadable code.

I have personally thought of using the prefix `Game`, which will lead to using `Game` a lot of times: `GameClass`, `GameCharacter`, `GameMap`. I think this is meh, but I can get over with it if people say it's not so unusual.

I'm not asking opinions: I'm looking for alternatives, such as which synonyms are used and are clear enough, or other techniques that don't decrease the readability of the code.

# Answer
I would probably prefix Game onto the start of my classes. GameMap, GameCharacter. or if you have a name or codename for your game prefix that. If your game was called Skyrim; SkyrimMap and SkyrimCharacter could make nice class names.

Also if its only for your own use, you could name the abc or xyz for what its worth.

I personally would avoid using custom class names that look close to language stuff, for example at work we have custom namespace (package) names that are the same as .NET namespaces, it can get very confusing and leads to you qualifying the full name

Hope that helps.

P.S. alternatively as others suggested just use the names but in your own package, so it all looks like Game.Character, Game.Class etc.
> 5 votes

# Answer
I strongly advice to use java analog of namespaces.

They are called **packages**.

You can read about packages there:

http://docstore.mik.ua/orelly/java-ent/jnut/ch02\_11.htm
> 0 votes

---
Tags: java, rpg
---


title: Best practice for map coordinate system

text:
# Question
Title: Best practice for map coordinate system
Are there any conventions and/or best known methods around coordinate systems in game maps? Is the origin usually positioned in the center of the map? Or does it live in a corner and the map is built in a single octant of the 3D space?

# Answer
> 37 votes
Most games place the map origin in a corner. The main reason for this is that tilemaps are often internally stored in two-dimensional arrays, and most programming languages don't allow negative array indexes. There are a lot of discussions about *which* corner should be the origin, but I don't consider any of the arguments particularly strong. In the end it's just personal preference. I would recommend to just use the same corner your graphics API is using to minimize headache.

Exceptions are often games which allow maps which grow infinitely in all directions. That doesn't work properly without negative indexes, so a simple 2d array is out of the question. You will need to store your map data in a more complex data-structure. In this situation it usually makes most sense to place the origin at the start position.

# Answer
> 12 votes
In theory the location of the origin doesn't matter. All math operations you do when the map is rendered or when objects move on the map work fine regardless of where the origin actually.

However in practice there is one reason why you might want to make the center of the map be the origin - and that is limited precision of floating point values.

With floating point numbers the farther you get from 0, the less precision there is in the smaller digits.

While working on an open world game that had a very large map we actually encountered problems where physics and other things would start to break down as you got farther away from the origin.

The fix was to do some trickery where the origin was always pretty near to the player, by intelligently teleporting things (the player, the map tiles, the camera etc) around to not get too far away from the origin.

# Answer
> 1 votes
It doesn't really matter. What some people change in their coordinate system is often the y-axis. Instead of having (0,0) in the top left, they prefer having it in the bottom left for easier physics.

---
Tags: tilemap, maps, level-design
---


title: 2D Lighting From Sun

text:
# Question
Title: 2D Lighting From Sun
I have been developing a game for over a year now and I have successfully implemented the basic foundation for lighting, but there are still a few things I'm struggling with. The biggest issue right now is the lighting that should be cast from the "sun". The sun should technically light up any block that doesn't have a lot of blocks above it covering up the light that should be reaching it.

The way the current light system works is through a flood-fill algorithm that goes block to block recursively setting light based on different conditions. The light is recalculated when a light source is placed or a block is broken and the algorithm is very efficient. Currently I have a basic implementation of sun where the highest block has light generated straight down from it until the light "runs out". This works when first generated, but doesn't look natural. One case where there's problems is if there is a single block 10 blocks above the terrain which would cause the terrain to be unlit under that block because it didn't receive any sun.

I have been doing research and trying out different techniques, but nothing has worked well and efficiently. Any suggestions are appreciated.

Here is an image of the game in it's current state. You can see the lighting issue with the tree blocking the light of the ground.

# Answer
> 1 votes
I think your problem is in the way you have chosen to structure your lighting model. It looks like you want the tiles closer to the surface to be more lit than the tiles deep in the ground (if I'm wrong, clarify this). That's all well and good, but that shouldn't be done with a lighting system per se because in actuality, everything under the top 1 inch of earth should be completely black.

That being said there is something you could do without reworking your whole model, I think. Appears that, in order to get your desired "effect", you have designed it such that the top tiles are having a shadow effect on tiles deeper in the earth, and the deeper or further away from the top tile they are, the stronger the shadow effect is. Further more, it looks like you are having the treetops have the same effect, and since the top layer of ground is pretty far away from the treetop, it is having a pretty strong shadow effect. Right?

## Method the First

Ok, so what to do about it? I would probably just flag tree elements as not being shadow casters. That should fix the immediate issue.

## Method the Second

The other option would be to redesign your shadow method in this way

```
if (tile has other tile directly above it){
    tile shade increase by 4
}
if (tile has other tile two spaces above it){
    tile shade increase by 3
}
if (tile has other tile three spaces above it){
    tile shade increase by 2
}
if (tile has other tile four spaces above it){
    tile shade increase by 1
}

```

What this will do is cause a penumbra effect which is how shadows really work. When something is far away, it's shadow is weaker than when it is really close. But this pseudo code I wrote will still cause an accumulative effect on a tile that has other tiles piled on it, so if you play with the numbers you'll get the same basic effect as in your current model, with the benefit of a penumbra model.

# Answer
> 0 votes
One way to do this would be to take into consideration the block types that the 'light beam' passes through - e.g. if there's a non-air block ten blocks above ground, then the light beam would note that, continue on through the next nine air blocks, then hit the ground with less (but still some) light than it would have done if the non-air block hadn't been in the way. If your light beams are currently coded to illuminate the next ten blocks as soon as they hit a non-air block, that might be the part that needs to change so that they effectively carry on until they've a) run out of steam through hitting blocks or b) go past a predefined plane that could be the bottom of the screen.

---
Tags: java, 2d, lighting
---


title: UI Bug After UI has interaction

text:
# Question
Title: UI Bug After UI has interaction
I am making a 3rd person game for pc. Space, of course, makes the player jump in game. For some reason if I interact with my menu at all and then press space it will open my menu back up. This doesn't happen if I don't interact with the UI first though. I don't know if this is a bug or what but my code does not contain anything that would take input from the keyboard in general so the space bar interacting with it doesn't make sense. Has anyone seen this issue before?

# Answer
To fix this I went into the Input Manager and deleted the alt positive button action for "Submit" as this was set to space by default. By just removing space from that the issue no longer exists.
> 0 votes

---
Tags: unity, c#
---


title: Converting ARGB surface to NV12 surface

text:
# Question
Title: Converting ARGB surface to NV12 surface
I'm trying to use NVENC to encode some frames that I'm capturing from a game. I've hooked EndScene() and I can get the data from the backbuffer, which is in ARGB format.

Unfortunately, NVENC only supports NV12 buffers ("resources") as input. I checked the SDK demo source and I've found that they create their NV12 surfaces using the fourcc code like so:

```
IDirectXVideoProcessorService * directx_services;
DXVA2CreateVideoService(d3ddev, IID_PPV_ARGS(&directx_services));
directx_services->CreateSurface(desc.Width, desc.Height, 0, (D3DFORMAT)MAKEFOURCC('N', 'V', '1', '2'), D3DPOOL_DEFAULT, 0, DXVA2_VideoProcessorRenderTarget, &NV12_surface[0], NULL);

```

This works. The problem now is that i need to convert my ARGB buffer into NV12. StretchRect() does not work, and CheckDeviceFormatConversion() returns D3DERR\_NOTAVAILABLE, so it doesn't seem like this is possible using high-level API's.

One idea I had was to copy the backbuffer to a texture surface, and then use that texture as an input to a pixel shader when doing some dummy draw operation, and then inside the shader i can do some math to do the conversion from ARGB to NV12. But then i would have NV12 formatted data inside an ARGB render target again. Would i be able to "cast" that to a NV12 buffer, or just use it as an input to my encoder even though the format technically doesn't match, but the data does?

Any ideas?

# Answer
The latest NVENC SDK (7.1) allows ARGB input directly. See here.
> 1 votes

---
Tags: directx, directx9
---


title: How to save options at the game?

text:
# Question
Title: How to save options at the game?
In my game main character can move using tap or hold finger on the screen. I wanna create at the menu options, and there button to change control type. How I can save player choose? Using Prefs?

# Answer
What input mode to use is a typical player preference. As such, it should be saved in the PlayerPrefs class. PlayerPrefs is a key/value store. It allows you to store and retrieve variables (int, float or string) under string-keys of your choice. It uses a platform-appropriate persistent storage method, so it doesn't just survive scene reloads but also closing and relaunching the whole game application.
> 1 votes

---
Tags: unity, c#
---


# Question
Title: using std::chrono::steady_clock for timing
I was wondering if it would be a good idea to use the steady\_clock class (in the C++ std libraries) for game timing. What are the pros/cons of using it as opposed to using a game library's timing mechanism?

# Answer
> 2 votes
As far as I understood std::chrono you cant be sure to get a high resolution timer with std::steady\_clock. So you might loose some accuracy on some system if the high resolution timer is not available as steady clock. I considered that too a while ago but than I read about steady clock and high resolution. I just can't find the reference at the moment.

Edit:

Here it is http://www.cplusplus.com/reference/chrono/high\_resolution\_clock/ there you can see that the high resolution clock has a is\_steady member. So for me it seems you can also get unsteady high resolution clocks. And on my system this member returned false. If you are fine with low resolution I think theres nothing against using steady\_clock.

# Answer
> 1 votes
Try this:

```
   typedef std::conditional<
       std::chrono::high_resolution_clock::is_steady,
       std::chrono::high_resolution_clock,
       std::chrono::steady_clock >::type ClockType;

```

Also note, that sometimes `steady_clock` is not steady, so include this so there are no surprises:

```
static_assert( ClockType::is_steady,
   "Clock is not monotonically-increasing (steady).");

```

Note that Steady clock is not enabled by default on GCC4.7 (and others, I'm sure), but you can enable it with a flag.

# Answer
> 0 votes
Using the game's timing library, if one is provided, has an advantage in terms of consistency. If you only interact with your own timing, this may not be important, but if you ever have to compare a time that you measured against a time reported by the game engine, it's very helpful to be using the same clocks.

If you choose to use the C++11 timers anyway, there's a choice you have to make. You have to choose between `high_resolution_clock` and `steady_clock`. There is no one-size-fits-all choice here, you have to pick the right one for your application. `high_resolution_clock` is typically very high resolution (duh) and very light weight because its job is to measure things as precisely as possible. A common implementation of it is to read the processor's instruction-count register: very fast, very high resolution. However, there's no guarantees that the rate of these ticks is very reliable. In particular, some implementations can change speed significantly if the CPU is put into a low power mode which decreases the CPU frequency. There's some odd behaviors that have shown up in cases where a laptop does some processing, then stops and waits for a few hundred milliseconds for the next bit of processing. Meanwhilem the OS drops the CPU frequency to conserve power. This slows the `high_resolution_clock` on this particular OS/platform, and the program wakes up late, missing its timing window.

`steady_clock` is guaranteed to not have this problem. However, in trade it has to be a more "heavy" clock in terms of processing work. While a `high_resolution_clock` may just read a register, a steady clock may need to make a system call to go get the "real" time.

If you're measuring very tiny amounts of time (such as profiling the cost of a block of code), then `high_resolution_clock` is the correct way to go. If you need the user to feel like your interactions are actually occurring "on time," you should pay the extra price to use `steady_clock` so that the measured time is representative of real time.

What about `system_clock` you say? You can use that too. However, one of the greats of C++ (I believe it was Herb Sutter) has stated that he believes system clock should be removed for the following reasons:

* On all existing implementations, `system_clock` is a typedef for `steady_clock` or `high_performance_clock`.
* You don't know which clock you're getting with `system_clock`, so you might as well take the extra time to figure out which clock you really wanted, and use it instead.

---
Tags: timing, c++
---


# Question
Title: Creating a planet out of an existing terrain
I am creating a game that I have created a terrain for. I really like the terrain so I am wanting to keep it but I want to have the game take place on a full planet. Avoiding paying $200 for an asset already made, how would I develop something to allow me to "tile" this terrain to make a full planet and to make it round instead of flat? I know this has to be somewhat possible with the expensive assets on the asset store that are for round terrains. I just need to figure out how and I can't find anything online that is much help.

# Answer
> 1 votes
I don't think Unity provides any default component or tool to create spherical terrains. You can create a world and a mesh procedurally, needs some coding. You can either change the transform of gameobjects to another point when you collide with them, which you can write inside OnTriggerEnter().

In your case, you could do a little hardwork and make the spherical terrain using a 3D application like Blender. Best of luck :)

---
Tags: unity, c#
---


title: Moving object beyond Bezier Curve

text:
# Question
Title: Moving object beyond Bezier Curve
I am currently developing small 2D game in Unity, in which player is using swipe to create objects paths. I already did almost everything, but I hit a wall which i cannot pass. The thing is, that when I am using Bezier Curve I have to specify all points to have a base for my curve, but I'd like my object to move further after passing end point. Look at the image.

I've created a curve based on points A, B and C. The curve is green, but it doesn't reach the screen end, so I'd like to extend it with the red line. This my code to get a point on a curve.

```
public static Vector3 GetPoint(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float t)
{
    t = Mathf.Clamp01(t);
    float oneMinusT = 1f - t;
    return
        oneMinusT * oneMinusT * oneMinusT * p0 +
        3f * oneMinusT * oneMinusT * t * p1 +
        3f * oneMinusT * t * t * p2 +
        t * t * t * p3;
}

```

I heard that passing parameter T greater than 1 should acutally do the thing, but it does not always work with my curves. Sometimes the object starts to go backwards or goes into some random direction. I would be grateful if someone could help me solve this problem. Thank you.

# Answer
You could continue the Bezier curve with another cubic curve to accomplish what you want. Basically add a new curve that starts at C and ends where the line crossing points C & B intersects the screen border. To ensure that this extended curve is C2 continuous with the original Bezier curve (i.e. is smooth in both direction and velocity), you should have the same tangent (both length & direction) at C for both curves. For the end point tangent you could use direction of C & B line and length of the start tangent.

This would be easiest to accomplish using cubic Hermite curves instead, which are controlled with end point positions and tangents. If you want to keep your original Bezier curve evaluation though, you could evaluate what the tangent for the curve at C and create Hermite curve for the extension. I think if you want to use Bezier curve also for the curve extension you could create control points at 2C-B and another at X+(B-C) where X is the intersection between the screen border and C-B line to ensure C2 continuity in addition to C and X control points.

Also another easier solution would be to simply just continue the curve to the direction of the tangent at the end of the curve until it intersects the screen border. You just need to be careful how you interpolate this line segment to ensure C2 continuity.
> 0 votes

---
Tags: unity, c#, beziers
---


# Question
Title: How to make Djikstra algorithm remember path?
I understand how dijkstra algorithm works but I don't know how I should figure out path. How can I get nodes that are on the shortest path?

# Answer
Dijkstra's algorithm operates in two passes:

1. Explore the state space (and assign a total distance value to each node) stop when target is reached
2. Browse the generated date to construct the path

You're at step 1: you reached the destination and know there's a path, but heven't extracted it yet, you're missing this second part.

If you only kept track of the 'open' nodes list, and 'closed' nodes list, that is insufficient. You can fix it in two ways:

## 1. **Assign a distance value to each node**

Classically, on a grid map, something like `double[][] distanceToGetHere`
On a Graph, you can store it in a `Map<Node, Double> distanceToGetToNode`
More simply, you can expand your Node to store it in a field like `node.setTotalDistance(double dist)`
**Once you have it**, work from the end node backwards, and find its neighbour with the lowest distance value. Store it, iterate until you get to the start node (with distance value 0, obviously).
The full node list is your path (reverse it because it goes end--\>start)
**Pro**: It's quite efficient to store the distance grid if you need to reuse the path from the start point.
**Con**: It is annoying to find which ancestor has the lowest distance.

## 2. **Remember each node's ancestor**

*This is much easier*. Whenever you uncover a neighbour B to a Node A, assaign A as B's parent: 'b.setParent(a)' Once Dijstra found the end node, just iterate `end.parent.parent.parent...` until you get to your start Node. Reverse it. Job Done.
**Pro**: It is really easy and efficient to construct the path.
**Con**: ?

Of course you can (should?) store both the distance and the ancestor in a Node (and when you wanna switch to A-Star, you'll store a heuristic in there too!)
> 1 votes

---
Tags: c++, path-finding, dijkstra
---


title: Libgdx Viewport and World Units

text:
# Question
Title: Libgdx Viewport and World Units
I want to start creating a very long project which i will work on and learn from. I've been making some basic games. Now i feel it's tine to step it up a notch.

My idéa is to create a 2.5d game such as Zelda. But i got stuck with viewport and world units. Since there is alot of viewports i can choose from and i've read what they offer. So what is the preferred viewport, dimension and world unit for a 2.5d rpg mobile/desktop game?

Thanks

# Answer
> 1 votes
Here's a tutorial on viewports: http://www.gamefromscratch.com/post/2014/12/09/LibGDX-Tutorial-Part-17-Viewports.aspx

StrechViewport would be the best as it is simple and works quite well. Some of the other viewports add padding bars to the sides, which might not make your game look good. But, you can try changing the viewports and resizing your window to see which one works best.

You specify the world width and height when initializing the viewport and the viewport scales your game accordingly.

So for a StrechViewport your code would be:

```
Viewport viewport = new StretchViewport(worldWidth, worldHeight);

```

And in your screen's resize method (or your own method) you would resize the viewport:

```
viewport.update(screenWidth, screenHeight);

```

---
Tags: libgdx
---


# Question
Title: Building a game project in C# for Unity in VS?
Say that a project needs to be created from scratch for later use in Unity, for scripts. What is the ideal way to setup this without using a template in Visual Studio?

Can this be created in C# with some simple classes and one or two game loops?

# Answer
> 1 votes
**TLDR**: Kinda but it's a lot of work for something that you will swap out in the future anyway.

I don't know that if you can get access to the unity namespaces and classes without using a template or starting a new project in unity (which essentially generates a template for you).

You could write a dummy class with the same methods that Unity uses. So a class called `MonoBehaviour` then simply list the names of the classes that you need (Start, Update, Awake, etc.) so that when you copy the code to unity you don't have to rename and adjust every method you write. Problem is that you won't be able to test this as easily.

When you want to test this you would have to create a basic game loop manually calling all the standard methods in the correct order then repeating update until your done. in a similar way as bellow:

```
public class FakeGameLoop {

    List<MonoBehaviour> scripts = new List<MonoBehaviour>();

    public void Main(string[] args)
    {
        //add all the scripts here one by one
        scripts.Add(new Thing());
        scripts.Add(new OtherScript());
        //etc, more scripts

        //initialise the scripts
        foreach (MonoBehaviour script in scripts)
        {
            script.Start();
        }

        //simulate the update cycle
        while (true)
        {
            foreach (MonoBehaviour script in scripts)
            {
                script.Update();
            }
        }
    }
}

```

The problem that you will face is that you need to implement more and more of unity the deeper you get into it and the more you want to use... If you want those scripts to talk to each other you have to make a basic version of the component system that unity has and implement the methods that you want to use.

If you want to just build systems that work around one script without needing any (or very little) unity specific stuff this will work ok as you test the script working on it's own. Once you are then done or ready you can move the code to unity and integrate it fully with other scripts

---
Tags: unity, c#, unityscript, visual-studio
---