# Question
Title: How can I manually draw a Sprite in Unity?
I'm creating a simple workaround on the unsupported prefab-on-prefab.

I've thus created this simple class:

```
[ExecuteInEditMode]
public class PrefabLinker : MonoBehaviour
{
    public GameObject prefab;

    private GameObject spawn;

    void Awake ()
    {
        #if UNITY_EDITOR
        if (!EditorApplication.isPlaying)
            return;
        #endif

        spawn=(GameObject)Instantiate(prefab);
        spawn.transform.parent=transform.parent;
        spawn.transform.localPosition=transform.localPosition;
    }

    #if UNITY_EDITOR
    void Update ()
    {
        if (EditorApplication.isPlaying)
            return;

        // Manually draw the Sprite

    }
    #endif
}

```

However I've no clue on **how to manually draw the Sprite**, without adding it to the scene. Obviously I can't add it to the scene like I do when I play it, because otherwise the spawn would be saved in the prefab, polluting it and creating a mess.

I'm hesitant to add the spawn to the scene "somewhere else" and updating its position, because I'd like to prevent the level designers from mistakenly move this spawn instead of the PrefabLinker object.

*This only needs to work with 2D stuff. I've found this link which I* guess *does something similar to my needs, but I've no idea how to fix it to work with sprites (and doesn't work out of the box).*

# Answer
Still no clue on how to draw the Sprite, so I've just managed to Instance the prefabs in a auto-cleaning way.

PrefabLinker.cs:

```
#if UNITY_EDITOR
using UnityEditor;
#endif
using UnityEngine;
using System.Collections;

[ExecuteInEditMode]
public class PrefabLinker : MonoBehaviour
{
    public GameObject prefab;

    private GameObject spawn;
    private static Trash trash;

    void Awake ()
    {
        if (trash==null)
        {
            trash=(Trash)GameObject.FindObjectOfType(typeof(Trash));
        }
    }
    void Start ()
    {
        // NOTA: facendolo nella OnEnable non funziona (Unity buggato)
        spawn.transform.position=transform.position;
    }
    void OnEnable ()
    {
        spawn=(GameObject)Instantiate(prefab);
        spawn.transform.parent=trash.transform;
        LinkBack lb=(LinkBack)spawn.AddComponent("LinkBack");
        lb.originalObject=this;
    }
    void OnDisable ()
    {
        DestroyImmediate(spawn);
    }

    #if UNITY_EDITOR
    void Update ()
    {
        if (EditorApplication.isPlaying)
            return;

        spawn.transform.position=transform.position;
    }
    #endif
}

```

LinkBack.cs:

```
using UnityEngine;
using System.Collections;

[ExecuteInEditMode]
public class LinkBack : MonoBehaviour
{
    public PrefabLinker originalObject;
}

```

Trash.cs:

```
using UnityEngine;
using System.Collections;

// todo. volendo pulire automaticamente (non strettamente necessario se gli elementi stessi provvedono)

[ExecuteInEditMode]
public class Trash : MonoBehaviour
{
}

```
> 1 votes

# Answer
Ok, some crazy code coming through

```
public struct Record
{
    public Mesh mesh;
    public Matrix4x4 matrix;
    public List<Material> materials;
    public MaterialPropertyBlock propertyBlock;
}

foreach (SpriteRenderer spriteRenderer in source.GetComponentsInChildren(typeof(SpriteRenderer), true))
{
    Sprite sprite = spriteRenderer.sprite;
    if (sprite == null)
    {
        continue;
    }

    Mesh mesh = new Mesh();

    var bounds = sprite.bounds;
    mesh.vertices = new Vector3[]{
        new Vector3(bounds.min.x,bounds.min.y),
        new Vector3(bounds.min.x,bounds.max.y),
        new Vector3(bounds.max.x,bounds.max.y),
        new Vector3(bounds.max.x,bounds.min.y),
    };

    mesh.triangles = new int[]{
        0,1,2,
        2,3,0
    };

    Vector2 textureCoordsFix = new Vector2(
        1.0f / (float)(sprite.texture.width),
        1.0f / (float)(sprite.texture.height)
        );

    Vector2 _00 = new Vector2(sprite.rect.x, sprite.rect.yMax);
    Vector2 _01 = new Vector2(sprite.rect.x, sprite.rect.y);
    Vector2 _11 = new Vector2(sprite.rect.xMax, sprite.rect.y);
    Vector2 _10 = new Vector2(sprite.rect.xMax, sprite.rect.yMax);

    _00.Scale(textureCoordsFix);
    _01.Scale(textureCoordsFix);
    _11.Scale(textureCoordsFix);
    _10.Scale(textureCoordsFix);

    mesh.uv = new Vector2[]{
        _00,
        _01,
        _11,
        _10
    };

    mesh.colors = new Color[]{
        Color.white,
        Color.white,
        Color.white,
        Color.white
    };

    //Important part, MaterialPropertyBlock is a part of unity sprite pipeline
    MaterialPropertyBlock block = new MaterialPropertyBlock();
    spriteRenderer.GetPropertyBlock(block);

    records.Add(new Record()
    {
        mesh = mesh,
        matrix = baseMat * spriteRenderer.transform.localToWorldMatrix,
        materials = new List<Material>(spriteRenderer.sharedMaterials),
        propertyBlock = block
    });
}

```

Then somewhere in drawcall

```
Matrix4x4 mat = transform.localToWorldMatrix;
foreach (Record record in records)
{
    for (int i = 0; i < record.materials.Count; i++)
    {
        Graphics.DrawMesh(record.mesh, mat * record.matrix, record.materials[i], gameObject.layer, null, i, record.propertyBlock);
    }
}

```

Works pretty fine for me, but still feels kludgy
> 0 votes

---
Tags: unity
---


title: What does glMultiDraw* do?

text:
# Question
Title: What does glMultiDraw* do?
I'm having trouble understanding exactly what glMultiDraw\* does, and when it should be used.

Is it to be used if I have one VBO with multiple objects in it or do I use it with many VBO's?

It would be great if someone could give a real example of how to use this is a VAO/VBO as all the stuff I've found on google just explain what the function does rather that how to use it practically.

# Answer
As per the documentation for `glMultiDrawArrays` and its sister `glMultiDrawElements`, these functions behave exactly the same as their `glDraw*` counterparts, except that they can specify more than one object. This means you bind all the same objects and use all the same state as with a `glDraw*` command.

The practical upshot of this is that yes, you can have one VBO with multiple objects in it, and render all of them with one API call.

I will direct you to this page for a more thorough discussion.

See also pages 34 (3.3) and 349 (4.5) of the OpenGL standards.
> 7 votes

# Answer
Take this code:

```
for (int i = 0; i < numarrays; i++)
    glDrawArrays (GL_TRIANGLE_FAN, arrayfirsts[i], arraycounts[i]);

```

Multi-draw allows this to be executed with a single draw call:

```
glMultiDrawArrays (GL_TRIANGLE_FAN, arrayfirsts, arraycounts, numarrays);

```

In *theory* this can give you better performance: by having only a single draw call, the driver need (again, *in theory*) only perform setup and validation once rather than once per draw call.

It's actually got nothing to do with VBOs explicitly, because it dates to GL 1.4; i.e *before* VBOs were added to OpenGL. Instead it provides you with a method of batching multiple draw calls to a single draw call, which is something that all GPU vendors recommend.

I made a point of emphasising "in theory" above, because in practice it's performance is going to depend on how the driver implements it. Some drivers may implement it entirely in software, and just treat it as a loop of individual glDrawArrays calls. Others may be able to take a faster path with it. OpenGL makes no promises either way.
> 5 votes

---
Tags: opengl
---


# Question
Title: How does interpolation actually work to smooth out an object's movement?
I've asked a few similar questions over the past 8 months or so with no real joy, so I am going make the question more general.

I have an Android game which is OpenGL ES 2.0. within it I have the following Game Loop:

**My loop works on a fixed time step principle (dt = 1 / ticksPerSecond**)

```
loops=0;

    while(System.currentTimeMillis() > nextGameTick && loops < maxFrameskip){

        updateLogic(dt);
        nextGameTick+=skipTicks;
        timeCorrection += (1000d/ticksPerSecond) % 1;
        nextGameTick+=timeCorrection;
        timeCorrection %=1;
        loops++;

    }

    render();

```

My intergration works like this:

```
sprite.posX+=sprite.xVel*dt;
sprite.posXDrawAt=sprite.posX*width;

```

Now, everything works pretty much as I would like. I can specify that I would like an object to move across a certain distance (screen width say) in 2.5 seconds and it will do just that. Also because of the frame skipping that I allow in my game loop, I can do this on pretty much any device and it will always take 2.5 seconds.

**Problem**

However, the problem is that when a render frame skips, the graphic stutter. It's extremely annoying. If I remove the ability to skip frames, then everything is smooth as you like, but will run at different speeds on different devices. So it's not an option.

I'm still not sure why the frame skips, but I would like to point out that this is **Nothing to do with poor performance**, I've taken the code right back to 1 tiny sprite and no logic (apart from the logic required to move the sprite) and I still get skipped frames. And this is on a Google Nexus 10 tablet (and as mentioned above, I need frame skipping to keep the speed consistent across devices anyway).

So, the only other option I have is to use interpolation (or extrapolation), I've read every article there is out there but none have really helped me to understand how it works and all of my attempted implementations have failed.

Using one method I was able to get things moving smoothly but it was unworkable because it messed up my collision. I can foresee the same issue with any similar method because the interpolation is passed to (and acted upon within) the rendering method - at render time. So if Collision corrects position (character now standing right next to wall), then the renderer can alter it's position and draw it *in* the wall.

So I'm really confused. People have said that you should **never** alter an object's position from within the rendering method, but all of the examples online show this.

So I'm asking for a push in the right direction, **please do not link to the popular game loop articles (deWitters, Fix your timestep, etc) as I've read these multiple times**. I'm **not** asking anyone to write my code for me. Just explain please in simple terms how Interpolation actually works with some examples. I will then go and try to integrate any ideas into my code and will ask more specific questions if need-be further down the line. (I'm sure this is a problem many people struggle with).

**edit**

Some additional information - variables used in game loop.

```
private long nextGameTick = System.currentTimeMillis();
//loop counter
private int loops;
//Amount of frames that we will allow app to skip before logic is affected
private final int maxFrameskip = 5;
//Game updates per second
final int ticksPerSecond = 60;
//Amount of time each update should take
private final int skipTicks = (1000 / ticksPerSecond);
float dt = 1f/ticksPerSecond;
private double timeCorrection;

```

# Answer
> 5 votes
There are two things crucial to get motion appearing smooth, the first is obviously that what you render needs to match the expected state at the time at which the frame is presented to the user, the second is that you need to present frames to the user at a relatively fixed interval. Presenting a frame at T+10ms, then another at T+30ms, then another at T+40ms, will appear to the user to be juddering, even if what is actually shown for those times is correct according to the simulation.

Your main loop seems to lack any gating mechanism to make sure that you only render at regular intervals. So sometimes you might do 3 updates between renders, sometimes you might do 4. Basically your loop will render as often as possible, as soon as you've simulated enough time to push the simulation state in front of the current time, you'll then render that state. But any variability in how long it takes to update or render, and the interval between frames will vary as well. You've got a fixed timestep for your simulation, but a variable timestep for your rendering.

What you probably need is a wait just before your render, that ensures that you only ever start rendering at the start of a render interval. Ideally that should be adaptive: if you've taken too long to update / render and the start of the interval has already passed, you should render immediately, but also increase the interval length, until you can consistently render and update and still get to the next render before the interval has finished. If you have plenty of time to spare, then you can slowly reduce the interval (i.e. increase the frame rate) to render faster again.

But, and here's the kicker, if you don't render the frame immediately after detecting that the simulation state has been updated to "now", then you introduce temporal aliasing. The frame being presented to the user is being presented at slightly the wrong time, and that in itself will feel like a stutter.

This is the reason for the "partial timestep" you'll see mentioned in the articles you've read. It's in there for a good reason, and that's because unless you fix your physics timestep to some fixed integral multiple of your fixed rendering timestep, you simply cannot present the frames at the right time. You end up either presenting them too early, or too late. The only way to get a fixed rendering rate and still present something that's physically correct, is to accept that at the time the rendering interval comes around, you will most likely be mid-way between two of your fixed physics timesteps. But that doesn't mean that the objects are modified during rendering, just that the rendering has to temporarily establish where the objects are so that it can render them somewhere in between where they were before and where they are after the update. That's important - never change the world state for rendering, only updates should change the world state.

So to put it into a pseudocode loop, I think you need something more like:

```
InitialiseWorldState();

previousTime = currentTime = 0.0;
renderInterval = 1.0 / 60.0; //A nice high starting interval

subFrameProportion = 1.0; //100% currentFrame, 0% previousFrame

while (true)
{
    frameStart = ActualTime();

    //Render the world state as if it was some proportion
    // between previousTime and currentTime
    // E.g. if subFrameProportion is 0.5, previousTime is 0.1 and
    // currentTime is 0.2, then we actually want to render the state
    // as it would be at time 0.15. We'd do that by interpolating
    // between movingObject.previousPosition and movingObject.currentPosition
    // with a lerp parameter of 0.5
    Render(subFrameProportion);

    //Check we've not taken too long and missed our render interval
    frameTime = ActualTime() - frameStart;
    if (frameTime > renderInterval)
    {
        renderInterval = frameTime * 1.2f; //Give us a more reasonable render interval that we actually have a chance of hitting
    }

    expectedFrameEnd = frameStart + renderInterval;

    //Loop until it's time to render the next frame
    while (ActualTime() < expectedFrameEnd)
    {
        //step the simulation forward until it has moved just beyond the frame end
        if (previousTime < expectedFrameEnd) &&
            currentTime >= expectedFrameEnd)
        {
            previousTime = currentTime;

            Update();
            currentTime += fixedTimeStep;

            //After the update, all objects will be in the position they should be for
            // currentTime, **but** they also need to remember where they were before,
            // so that the rendering can draw them somewhere between previousTime and
            //  currentTime

            //Check again we've not taken too long and missed our render interval
            frameTime = ActualTime() - frameStart;
            if (frameTime > renderInterval)
            {
                renderInterval = frameTime * 1.2f; //Give us a more reasonable render interval that we actually have a chance of hitting
                expectedFrameEnd = frameStart + renderInterval
            }
        }
        else
        {
            //We've brought the simulation to just after the next time
            // we expect to render, so we just want to wait.
            // Ideally sleep or spin in a tight loop while waiting.
            timeTillFrameEnd = expectedFrameEnd - ActualTime();
            sleep(timeTillFrameEnd);
        }
    }

    //How far between update timesteps (i.e. previousTime and currentTime)
    // will we be at the end of the frame when we start the next render?
    subFrameProportion = (expectedFrameEnd - previousTime) / (currentTime - previousTime);
}

```

For this to work all objects being updated need to preserve the knowledge of where they were before and where they are now, so that the rendering can use it's knowledge of where the object is.

```
class MovingObject
{
    Vector velocity;
    Vector previousPosition;
    Vector currentPosition;

    Initialise(startPosition, startVelocity)
    {
        currentPosition = startPosition; // position at time 0
        velocity = startVelocity;
        //ignore previousPosition because we should never render before time 0
    }

    Update()
    {
        previousPosition = currentPosition;
        currentPosition += velocity * fixedTimeStep;
    }

    Render(subFrameProportion)
    {
        Vector actualPosition =
            Lerp(previousPosition, currentPosition, subFrameProportion);
        RenderAt(actualPosition);
    }
}

```

And let's lay out a timeline in milliseconds, saying rendering takes 3ms to complete, updating takes 1ms, your update time-step is fixed to 5ms, and your render timestep starts (and remains) at 16ms \[60Hz\].

```
0   1   2   3   4   5   6   7   8   9   10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33
R0          U5  U10 U15 U20 W16                                 R16         U25 U30 U35 W32                                 R32

```
1. First we initialise at time 0 (so currentTime = 0)
2. We render with a proportion of 1.0 (100% currentTime), which will draw the world at time 0
3. When that finishes, actual time is 3, and we don't expect the frame to end till 16, so we need to run some updates
4. T+3: We update from 0 to 5 (so afterwards currentTime = 5, previousTime = 0)
5. T+4: still before the frame end, so we update from 5 to 10
6. T+5: still before the frame end, so we update from 10 to 15
7. T+6: still before the frame end, so we update from 15 to 20
8. T+7: still before the frame end, but currentTime is just beyond the frame end. We don't want to simulate any further because to do so would push us beyond the time we next want to render. Instead we wait quietly for the next render interval (16)
9. T+16:It's time to render again. previousTime is 15, currentTime is 20. So if we want to render at T+16, we are 1ms of the way through the 5ms long timestep. So we are 20% of the way through the frame (proportion = 0.2). When we render, we draw objects 20% of the way between their previous position and their current position.
10. Loop back to 3. and continue indefinitely.

There's another nuance here about simulating too far ahead of time, meaning the user's inputs might be ignored even though they happened before the frame was actually rendered, but don't worry about that until you're confident that the loop is simulating smoothly.

# Answer
> 3 votes
What everyone has been telling you is correct. Never update your sprite's simulation position in your render logic.

Think of it like this, your sprite has 2 positions; where the simulation says he is as of the last simulation update, and where the sprite is rendered. They are two completely different coordinates.

The sprite is rendered at his extrapolated position. The extrapolated position is calculated each render frame, used to render the sprite, then thrown away. That's all there is to it.

Other than that, you seem to have a good understanding. Hope this helps.

---
Tags: android, interpolation, lerp, extrapolation
---


# Question
Title: Why are gaming graphics not as beautiful as animated movies?
I remember watching the Tomb Raider pre-rendered trailer, and wished those graphics could be in the game itself.

Why there is such a big difference between the trailer and the actual game? I understand the game is a completely different concept, it has different pipeline, it has to go through different kinds of player interactions etc. I want to know what it is about games that makes rendering them so difficult compared to animated films.

So far I know that making a game and an animated movie share some basic workload, e.g. making 3d models, rendering them (only in-game it happens live). Animated movies render for a long time and we only see pre-rendered scenes. That's all I know so I hope you'll answer from that perspective!

What about animated movies rendering for hours and hours makes them so beautiful while in-game live rendering is less beautiful (from a general point of view)?

# Answer
> 107 votes
You already mentioned one of the central points: *Time*.

In the process behind rendering a high fidelity animation, multiple different approaches and algorithms are used (all usually combined under the term "Global Illumination"), with Ray-Tracing being one of the most common ones (others include for example Radiosity and Ambient Occlusion).

Ray-Tracing involves simulating a (usually high) number of light rays going through the scene and calculating their paths, their reflections and refractions when they hit objects with different materials. Different materials in return then have different physical properties that result in specific reactions for the rays (the amount of light that bounces from one objects for example is higher for a shiny objects compared to a glossy one).

Another point is *Physics*: Simulating thousands of hair strains in a physically correct way is time-consuming. This is why in older games, hairs are often approximated with a very rough mesh that is then textured to give the impression of hair, perhaps with some additional moving objects to make it look a bit more realistic.

Also to be considered: *Memory & Bandwidth*. The higher the quality of a texture applied to an object in a scene should be, the more memory you need to load and use it in a game. But not only does the system need to have enough memory to hold the data, but this data also needs to be transferred around which uses up the available bandwidth. Since memory and bandwidth are limited, there is a maximum what can be achieved.

Games often cheat a bit by only using the high-resolution textures for near objects, and use lower resolution images for the far away objects (term: MipMapping) thus reducing the needed bandwidth since less texels need to be fetched which in return increases the performance (see section about MipMapping in Apple's OpenGLES Programming Guide).

Similarly, games also often use different meshes for objects depending how far away they are with far away objects being less detailed (term: LoD = Level of Detail).

*Conclusion:* In real-time graphics (such as games and simulations), this detailed and complex rendering process will of course not work to produce fluid/smooth scenes. You need at least 20 rendered frames per second to achieve that fluid animation/movement effect for the human eye. On the other side, rendering a single frame (!) in an animation movie can easily take up anything from a few hours to multiple days depending on many factors such as the number of used rays in Ray-Tracing or the number of samples for Ambient Occlusion (see these Pixar page 1 / Pixar page 2 for screenshots of 16 vs. 256 samples) as well as the desired movie resolution (more pixels = more information to be calculated). Also see this article about the process behind Pixar's *Monsters University* animation movie, giving some interesting insights and also mentioning 29 hours render time per frame.

In general: The higher the fidelity / realism that is to be achieved, the more iterations / bounces / samples are usually needed which in return then requires more resources (both time and/or computation power / memory). To visualize the difference see the resulting render based on the number of bounces for the refraction calculation in this example: Diamond Bounces from Keyshot

But of course, the quality in real-time applications increases all the time for two reasons:

1. Stronger hardware: As the (gaming) computers get better (= more \[parallel\] computing power, higher data transmission between computer components, more and faster memory, etc.), the visual fidelity increases as well, because more time-consuming computations actually become feasible in a real-time system.
2. More clever methods/formulas are developed and implemented that are able to create rather photo-realistic effects without needing raytracing. This often involves approximations and sometimes pre-calculated data. Some examples:

# Answer
> 44 votes
Besides the time factor, it's worth noting that in a movie, the artist has complete control over what the viewer will and won't look at.

In your typical movie scene, the camera won't spend much time pointed at the ceiling, or pointed into a dark corner of the room, or aimed at someone's ankle, so the polygon and texturing budget for those elements will be fairly low.

If the entire scene takes place from one vantage point, the virtual set (like a real film set) doesn't need to include the parts that are behind the camera. In most games, the player is free to look anywhere at any time. That means the quality budget can be focused on what's actually seen. (Some third-person games, e.g. the God Of War series, use a restricted camera; their visuals tend to be notably better than those of more free-camera games.)

# Answer
> 12 votes
> What about animated movies rendering for hours and hours makes them so beautiful while in-game live rendering is less beautiful (from a general point of view)?

You're assuming that the difference is simply in the render -- in an animated movie, there's also a chance for editing after the fact. They might have effects composited in that would have been difficult to have achieved in the original engine, or they may tweak things a little bit (eg, remove or repeat every 10th frame to speed up / slow down the animation).

If you get a chance, dig up one of the 'Roughnecks: The Starship Trooper Chronicles' DVDs, as they have commentary tracks by the editor & animators about tricks that they had to do when they started falling behind their delivery schedule -- things like recycling shots but flipping the axis so it wasn't as obvious, color corrections, masking off things they didn't like, adding in explosions, etc.

# Answer
> 10 votes
You kind of answered your own question already. Animated movies generally usually have a higher level of detail which causes a long render time for each individual frame.

Games on the other hand don't have quite as much detail in them, because the scene has to be rendered 30 or more times per second. That's also why developers try to reuse as much assets (textures, models, etc.) as possible, because rendering the same object in two positions is a lot faster than if everything would be unique. They also have to watch out not to use too many polygons in their models, and instead try to achieve an impression of depth by using lighting, textures, bump mapping and other techniques.

Movies don't have that problem; they make the scene the way they want and use as many and as detailed textures, models and geometry as they need to to achieve the scene they're looking for.

One might argue though that games are catching up. If you look at some of the best looking games in recent times, they're not as far away from movie quality as they used to be. Of course you'll always be able to cram more detail into a pre-rendered scene than a game, but I think the difference will not be as noticeable in a few years time.

# Answer
> 8 votes
Adding to the other great answers that were already posted, it is worth noting that in order to achieve the fast processing times that games need, game developers need to bake many of their visual effects as simple textures. This means that great care must be taken in avoiding effect that won't bake well.

One important effect that's hard to bake for video games is Subsurface Scattering (SSS). Unfortunately, this effect is really important in generating realistic-looking human skin. That's why many "realistic" video game characters come out looking plastic.

One way developers avoid this issue is by deliberately making the characters brightly colored to detract from the plastic look, or by adding a lot of shadows and textural details to the face (like beards etc.) to break up the otherwise large, continuous sections of skin.

# Answer
> 8 votes
The other answers cover the raw graphics issues in good detail, but don't mention an important part of the realism of games vs. movies and trailers: **the animations and camera movements**.

In a movie or trailer, each movement of people and cameras can be carefully coordinated to show just the right emotion for the moment, and they never need to be repeated. In video games, the game must be able to react instantly to the player's movements, and must reuse a small pool of stock animations in order to fill the unlimited hours of game time that can be possible.

Examples of this from the trailer in question are when the therapist nods and gives a "not bad" smile, and when Lara grips the armrest, jiggles her leg, or looks on the cavern in awe. These small things (or the lack of them, and the "plastic" characters involved) affect the perceived realism far more than minor graphics improvements.

Unlike the other graphics differences, this is not a problem that can potentially be solved by throwing more computing power at it: it's a fundamental difference between a world that's scripted and a world that responds to your every action. In this particular regard, I expect that the realism of today's trailers will exceed all gameplay for the foreseeable future.

# Answer
> 6 votes
To answer one of the questions the OP asked in a comment:

> "So who should be the main culprit? Polygon level or ray tracing?"

This question is more difficult than it looks. I think a good rule of thumb is the following equation (which I made up by the way):

```
number of calculations = {polygons} * {light sources} * {effects}

```

Basically, this means that for models with relatively few special materials (i.e. no mirror, subsurf, etc.), the computation time will be large determined by the number of poligons. This is usually the case for very simple video game graphics.

In practice, however, in newer high-end games and especially movies, **the culprit is "usually" ray tracing.** Why? Well for two reasons. I'll give the mathy reason first, and then my opinion of the real reason at the end.

**Mathy reason:**

*Update: This mathy explanation may not be completely accurate. Please see CrazyCasta's explanation in the comments for more details.*

Suppose you have 1000 polygons and 3 light sources. The smallest number of ray traces you need to perform is 3\*1000.

If we over simplify the situation and assume that 1 ray trace = 1 calculation (a gross underestimate) then we will need 3000 calculations.

But now lets suppose you want have reflections too.

The default settings for reflections in the freeware program Blender are:

```
max reflections  = 2
ray length limit = None
...

```

For these settings we can guesstimate that, in the best case scenario, this super-simple reflection will *double* the computational cost of your model.

But like I said before, this example is very-oversimplified, and you can find a great many effects (besides the ones I mentioned already) that will shoot your rendering time through the roof.

Case and point: try to render reflections with `gloss=1` (the default in Blender), then turn the gloss down to 0.01 and compare the two rendering times. You'll find that the one with 0.01 gloss will be much slower, but the model complexity hadn't been changed at all.

**My qualitative but more realistic reason:**

Increasing the mesh complexity will only improve the model quality to a point. After going past a couple million faces, there really isn't a whole lot that adding more faces will do. I'll even go so far as that say that if you use smoothing, you'll be able to get away with just a couple hundred faces for most general purposes.

But the things that almost always make a difference are the lighting, material effects, and ray tracing. That's why movies will tend to use a great number of these in an attempt to approximate the beautiful complexities of the real world.

A great way to get a feel for all this stuff is to look at the cast list at the end of the latest Disney feature-length animations. You'll probably be surprised by just how many lighting and texture people they have.

# Answer
> 4 votes
It's worth adding that movie animation usually does a good deal of visual trickery to make perceived motion more fluid.

Animators may, for instance, use traditional hand-animation techniques which are not typically used in realtime rendering, such as smears, multiples or warping to produce more fluid-looking motion despite the lower framerate which movies are (were at any rate, until recently) displayed at. The use of smears and multiples in particular are complicated by the use of meshes - you need to produce mesh deformations for that sort of mesh distortion, and I don't believe I've seen that done in any 3d video games.

Frames with fast-moving objects passing through them may be rendered at a different framerate and then combined again to produce motion blur through the scene. Motion blur is a fairly common technique in realtime 3d graphics these days. The effect is usually not of the high quality that an animation house with dozens of processors at their disposal will obtain (see the "time" answers above) largely due to the fact that faking motion blur really well requires multiple post processing steps per layer, and a large number of intermediate frames to be really fluid.

Doing this sort of visual trickery to enhance the perceived quality with realtime graphics effectively requires limiting the output framerate to rates well below the maximum available, background-rendering intermediate frames, then doing compositing to produce the final frame. There are probably multiple schools of thought on whether the slight gains in visual fidelity for using techniques like this is worth the loss of frame budget, particularly if it's going to be extremely hard to get right.

To address one aspect of your question:

> What about animated movies rendering for hours and hours makes them so beautiful while in-game live rendering is less beautiful (from a general point of view)?

Artisanry, chiefly. The realtime artists aren't afforded the chance to fine-tune each frame or create one-off gimmicks to improve the overall look of a scene, or reaction, not only because of time constraints (both in development and in rendering) but also because of practical constraints. As noted in the interactivity comment, the player is probably not going to do exactly the same thing every time, but the movie will play the same each time.

This means that the video game artist has a very different set of priorities where it concerns model quality and final render quality than the film artist. Both require enormous amounts of skill, but each demand different techniques. I expect these techniques to increasingly converge as consumer level rendering hardware continues to progress and further mathematical genius continues to emerge at your SIGGRAPHs and your GDCs.

# Answer
> 3 votes
A single animated movie could take many years to render on a single beast of a machine. Since it is pre-rendered it does not matter how much costly effects like light bounces, shadows, etc we add to the scene. These movies usually get rendered by render farms where thousands of PC's are linked together working on the same job.

The reason we cannot achieve the same quality for real time is simply because the machine needs to render the current frame in about 16ms to achieve a FPS of 60. A single frame for a animated movie could take hours to render on a single PC.

In a game, besides the graphics, a ton of other stuff is going on. Each frame there are tons of calculations. Simply said, an animated movie does not need to calculate the damage taken by the player from a rocket launcher, you just animate the gibs and the polygons will render.

Luckily there are some genius people walking around on this planet. Apart from better PC's that can render more polygons and larger textures there are some ingenious inventions made like normal maps that can animate light/shadow on a flat polygon very cheaply, making a boring 3D object look extraordinary detailed.

Some of these expensive effects that make movies have that extra flare.

* Light bounces. In real life light bounces until it is completely absorbed by the surfaces it bounced on. For each light source calculations have to be made. Try to hold a colored object next to a piece of white paper, you will see the color bleed on to the paper.
* Games have harsh limitations on the amount of polygons used, prerender movies do not have these limitations, it just takes longer to render. Back to light bouncing, if we have more polygons then there are more light calculations for even better visuals but at the expense of exponential growing cost.
* Texture size, graphic cards can only hold a certain amount of data in them and switching this data is expensive. A common 1024x1024 texture including all the shader maps could easily take up a couple percentages of you 1GB GFX card. When the card needs to switch data this goes at a cost. Obviously we don't care so much for this when prerendering a movie. Also, in a movie we just need high resolution textures where the camera gets near, for a game we want this for each object the player can get close to.
* Pathfinding is very demanding on the CPU. Pathfinding algorithms, for example, make enemies find routes towards you or make your player walk a path when you click somewhere. These pathfinding can be costly, when there are 10000 way-points (which is just each square meter on a 100m x 100m map) then it is possible we need to traverse all these way-points many times on a single frame. There are many ways to make this cheaper depending on needs but the fact is we do not need this for prerendered scenes.

Simpy put, we need to come up with "cheap" tricks to make a game look good. But the human eye is hard to fool.

---
Tags: animation, rendering
---


title: Libgdx with Scala: Overwrite listener

text:
# Question
Title: Libgdx with Scala: Overwrite listener
I try to learn Scala the fun way, with a little libgdx project.

Now I'm somewhat stuck:

```
val go = new TextButton("Go", style)
go.addListener(new ClickListener()
{
   override def isPressed() : Boolean =
   {
     Predef.println("isPressed!)
     true
   }
}

```

This doesn't work, sadly. Not sure why. I tried returning a "java.lang.Boolean" but the compiler doesn't allow for that, saying these would be incompatible types.

On the other hand, the "void"-method of keyTyped works like a charm:

```
textField.setTextFieldListener(new TextFieldListener()
{
  override def keyTyped(textField: TextField, key: Char)
  {
    textFieldInput = textField.getText()
    Predef.println(textFieldInput) // TODO remove
  }
});

```

Here when I type something it gets printed to the console.

Any ideas?

That's probably not really related to game-development, still I wasn't sure if another forum would've been a safer bet.

# Answer
> 1 votes
Are you sure this is not working?

I tried to reproduce and it's working just fine. (\*)

You wrote that the TextFieldListener is just working fine, so I assume you've set the InputProcessor to the stage, right?

Just in case you did not and did some black magic (or rather for others who might face a similar error):

```
Gdx.input.setInputProcessor(stage)

```

(\*) I don't know what you try to achieve of course, but: Maybe you rather want "clicked" and "enter" instead?

If this wasn't helpful, please tell me what exactly you want to do. Oh, and sorry, I would've posted this as a comment, but I'm not allowed to, yet -.-

---
Tags: libgdx
---


# Question
Title: Only affect pixels in buffer with alpha 0
I'm working on a transition effect where I have a texture and simply draw that as a pattern to my buffer. Here is a demo, use "e" to start the effect again. This looks fine but it won't work if the texture has pixels with alpha 0 \< x \< 1.

This is the texture I used in my demo ( zoomed ):

As you can see the edges are rough and full on opaque. If I do use a texture with softer edges the pixels with alpha will just smear the black away. How can I achieve the effect of pixels in my texture with an alpha of 0 \< x 1 to only affect pixels with alpha 0 in my buffer?

# Answer
> 0 votes
( If it's more appropriate to remove this thread please let me know)

When the problem occurred I changed to hard edges and only worked with that. Meanwhile I changed my drawing logic and the fix went unnoticed:

The problem was that I didn't have the right blending modes applied, these should work. ( names might be slightly different in OpenGL) This is done in Kha and Haxe:

```
//before rendering fading **in** blend modes :
g2.setBlendingMode(BlendingOperation.DestinationAlpha, BlendingOperation.SourceAlpha);
//bedore rendering fading **out** blend modes :
g2.setBlendingMode(BlendingOperation.SourceAlpha, BlendingOperation.DestinationAlpha);

```

If someone has some pointers, that would be appreciated.

---
Tags: opengl, glsl, alpha-blending
---


# Question
Title: What does "~" in front of a function name inside a class mean?
I added a class using the 'add class' item in Visual Studio Express and it generated two functions in the .cpp file with the same names. But the second has the `~` character in front of it.

What does it mean?

# Answer
> 1 votes
One without `~` in front of the name is a constructor and one with `~` in front of it's name is a destructor.

This however only applies if the function name matches exactly the class name. Otherwise it would not represent a constructor or destructor and the character `~` would most likely result in a syntax error.

Check this tutorial on constructors and destructors.

# Answer
> 1 votes
C++ has the concept of constructors and destructors.

A constructor is a method that is executed once a class instance is created. It is named with the same name as the class, but with no return type. The constructor is usually where you initialize member variables of a class.

A destructor, as the name implies, is executed once a class instance is destroyed. It is the place to do any non-automatic cleanup, such as closing files, database connections, etc. A destructor is also named with the same name as the class, no return type, but with a tilde `~` at the beginning. You don't need to define a destructor for every class. It can be omitted if no manual cleanup is required.

See this example, and test it here, to get a better grasp of it:

```
#include <iostream>

class MyClass {

public:

    // Constructor declaration
    MyClass()
    {
        std::cout << "on MyClass constructor" << std::endl;
    }

    // Destructor declaration
    ~MyClass()
    {
        std::cout << "on MyClass destructor" << std::endl;
    }
};

int main()
{
    MyClass myClassInstance;
}

```

---
Tags: c++, visual-studio
---


title: Calculating distance travelled

text:
# Question
Title: Calculating distance travelled
I am working on a road fighter kind of game. The game has its tracks moving to give the effect of car movement. The car accelerates and decelerates as expected with certain keys pressed. But How do I give the notion of distance travelled by the car and how to calculate it?

For some reference, here's how the movement of tracks is sped to simulate acceleration and deceleration:

```
void Update ()
        {
        if (Input.GetKey(KeyCode.F))
        {
            if(speed<=35f)
            {
            speed = speed + 3f* Time.smoothDeltaTime;

            }

        }
        if (Input.GetKeyUp(KeyCode.F))
        {

                speed = speed - 7f * Time.smoothDeltaTime;

        }

        if(Input.GetKeyDown(KeyCode.S))
          {
            speed = speed - speed/2;
        }
        this.transform.Translate (Vector3.right * Time.smoothDeltaTime * speed);

        }

```

# Answer
> 2 votes
Simple: just keep track of the distance traveled by keeping track of the changed time and current speed. Make sure that if your speed is in kilometers per hour that you multiply by time in hours.

If we assume `Time.smoothDeltaTime` is in seconds:

```
timeInHours = (Time.smoothDeltaTime / 60) / 60;
totalDistance += speed * timeInHours;

```

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


# Question
Title: how does an SM5 shader handle loops and if statements? (HLSL/CG)
How does an SM5 compilation handle loops and if-else statements, are branching execution routines unwound and if so, to what degree?

Is it only Direct Compute that can optimize branching code?

searchwords: dx11, shadermodel5,

# Answer
There are two ways if-branching is handled in SM5: predication and dynamic branching. Both of these mechanisms give the same result but have different performance characteristics.

Predication means that the if-statement sets a predication bit on GPU based on the if-condition and every instruction within the non-taken if-branch is effectively turned into a nop-instruction, i.e. GPU checks this bit for each instruction and skips the execution of instructions within the non-taken if-branch at the rate of one instruction/cycle. Because many "normal" instructions (mul, add, etc.) are executed at the full rate of one cycle/instruction anyway this doesn't necessarily result in much of a performance improvement. Some instructions are more expensive though such as texture fetch, transcendental instructions (exp, sin/cos, etc.), double precision math, etc. that are executed at lower-than-full-rate and thus predication can result in some performance improvements, but it depends on GPU architecture what kind of improvements you can get.

Dynamic branching is the mechanism that result in true branching in the execution. There is some overhead for this type of branching though (somewhere around 5 cycles/branch but this depends on the GPU architecture) so it's preferable to use dynamic branching only if you potentially skip larger chunk of code. Also because GPU's execute shader code for several pixels (or more generally "threads") at once in lock-step called warps(NVIDIA)/wavefronts(AMD), branching divergence within a wavefront causes both if-branches be executed for all pixels for the wavefront (with predication). So only if all pixels in a wavefront (around 64 pixels/wave but depends on GPU) take the same branch you can see performance improvements over predication. To enable dynamic branching for given if-statement you need to precede the if-statement with \[branch\] attribute in HLSL. For more details check: http://msdn.microsoft.com/en-us/library/windows/desktop/bb509610(v=vs.85).aspx

For and while loops can be unrolled or they can use real dynamic looping. There are some attributes in HLSL how this can be controlled as show here (same for both for and while loops): http://msdn.microsoft.com/en-us/library/windows/desktop/bb509602(v=vs.85).aspx. Similarly to if-branching dynamic looping adds some overhead and has branch divergence issues.
> 2 votes

---
Tags: directx11
---


# Question
Title: How can I calculate the visible area of my camera in world space and take zoom into account?
I am trying to get the bounds from an orthographic camera in Unity which take into account the current orthographic size (zoom).

I thought that I could use the *cameraToWorldMatrix* to transform the camera pixel rectangle into world coordinates.

```
var m = camera.cameraToWorldMatrix;

var bL = m.MultiplyPoint(new Vector3(camera.pixelRect.xMin, camera.pixelRect.yMin));
var uL = m.MultiplyPoint(new Vector3(camera.pixelRect.xMin, camera.pixelRect.yMax));
var uR = m.MultiplyPoint(new Vector3(camera.pixelRect.xMax, camera.pixelRect.yMax));

var rect = new Rect(uL.x, uL.y, Math.Abs(uR.x - uL.x), Math.Abs(bL.y - uL.y));

```

However, this does not take into account the orthographic size (zoom).

Multiplying the *cameraToWorldMatrix* with the camera's *projectionMatrix* property does not give me the correct results either.

Is there a sensible way that this can be solved?

# Answer
Turns out that the answer is more simple than I originally thought.

```
        // Calculate orthographic camera bounds
        float height = 2f * camera.orthographicSize;
        float width = height * camera.aspect;

```
> 6 votes

---
Tags: unity, camera
---


# Question
Title: How do I rotate and flip 2D sprites stored in a 1D array of pixels?
I am using a 1D array of pixels for rendering in 2D in java. I am interested in rotation (in radians) and mirroring across the x and y axes. The desired result looks something like this:

```
Public void render(Sprite sprite, int x, int y, double rotation, boolean xFlip, boolean yFlip) {}

```

I am not using any libraries for the current project. The information that I have gleaned is that I must somehow multiply the points of my pixels with a transformation matrix. I am familiar with matrices (outside of a programming context) and am ok with rigorous mathematics.

**How do I rotate and flip 2D sprites with a 1D array of pixels?**

**EDIT** The sprite class is almost exclusively a wrapped array of pixel data. In my `Screen` class:

```
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
int[] pixels  = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();

```

and then

```
g.drawImage(image, 0, 0, getWidth(), getHeight(), null);

```

# Answer
> 0 votes
I'll try to give a two-fold answer: On the one hand, giving a bit of source code as a MCVE. On the other hand, I'll quickly try to point out why implementing this on your own is a bad idea.

I'll start with the latter.

## Why you should not implement it this way

You mentioned in the comments

> I was always under the impression that this was a more efficient system (more work means it's better, right? ;))

## ***NO!***

(It's a pity that I can't emphasize this more...)

The best way to do image- and sprite rendering and manipulation is to do it in the way that it was *intended* to be done, by the developers of the respective API. And if these developers did it right, this implies the *least* work: The easiest way should be the right way.

In this particular case: If you want to draw images (sprites) *efficiently*, you really should use the built-in mechanisms. Store the sprite data as a `BufferedImage`, and draw the sprites using the corresponding methods of the `Graphics2D` class, utilizing an `AffineTransform` to transform the images. This allows the underlying library (Swing/AWT) to use hardware support for drawing, and you'll not even *remotely* achieve a similar performance when you are doing all this manually in software...

(Of course, when using the intended API functionality, there still are some "tricks" to squeeze out the last bit of performance, but this is a different story than the fundamental decision between hardware- and software rendering...)

---

This recommendation finds its limitations in the (rare) cases where one needs the image data in a format that is "not directly accessible" with the vanilla API. For example, when you have a `BufferedImage` and want to modify individual pixels, this *can* be done with the `BufferedImage#setRGB(x,y,rgb)` method. But if you have to do this often, then there may be better options.

I'd really recommend you to read the question Java single Array best choice for accessing pixels for manipulation?. I wrote an elaborate answer pointing out the caveats when trying to access the raw pixel data.

---

## If you *still* wanted to implement it this way...

The question itself touches a very general (and broad) topic. Namely the topic of Texture Mapping. (As such, this usually refers to mapping a **3D** polygon to **2D**, but the techniques that are employed there are basically the same as for a 2D-\>2D mapping).

The fact that you are using 1D arrays for the pixels is only a minor (and actually rather unimportant) artifact. For the mapping techniques it does not matter whether a (pseudocode) method like `int rgb = readPixel(x,y)` or `writePixel(x,y,rgb)` internally accesses a 1D array or a 2D array (or a `BufferedImage`).

---

So the question can be boiled down to: How to paint an image that was transformed with some (affine) transformation?

You're not the first one who tries this ;-) And summarizing 50 years of research in one answer is not possible. You may start with reading this (PDF file) with a Survey of Texture Mapping.

It starts with a first, rough classification of the possible approaches:

* For each pixel of the image, you can compute its position on the screen
* For each pixel on the screen, you can compute which pixel of the image has to be painted there

These approaches are implemented here in a dummy example.

## But...

...this is not how it is done "properly" (see the notes below). It's just to have some code showing the idea:

```
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferInt;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class PixelImageTest
{
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI()
    {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final PixelImagePanel pixelImagePanel = new PixelImagePanel();
        f.getContentPane().add(pixelImagePanel);

        BufferedImage image = loadImage("Julia01.jpg");
        final int w = image.getWidth();
        final int h = image.getHeight();
        final int pixels[] = PixelImages.getPixels(image);

        Timer t = new Timer(20, new ActionListener()
        {
            private double angleRad = 0;
            @Override
            public void actionPerformed(ActionEvent e)
            {
                AffineTransform at = new AffineTransform();
                at.concatenate(AffineTransform.getTranslateInstance(400,400));
                at.concatenate(AffineTransform.getRotateInstance(angleRad));
                angleRad += 0.05;
                pixelImagePanel.clear();
                //pixelImagePanel.drawImageTextureScanning(pixels, w, h, at);
                pixelImagePanel.drawImageScreenScanning(pixels, w, h, at);
            }
        });
        t.start();

        f.setSize(800,800);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    private static BufferedImage loadImage(String fileName)
    {
        try
        {
            return convertToARGB(ImageIO.read(new File(fileName)));
        }
        catch (IOException e)
        {
            e.printStackTrace();
            return null;
        }
    }

    private static BufferedImage convertToARGB(BufferedImage image)
    {
        BufferedImage result = new BufferedImage(
            image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics g = result.getGraphics();
        g.drawImage(image, 0, 0, null);
        g.dispose();
        return result;
    }
}

class PixelImagePanel extends JPanel
{
    private BufferedImage canvasImage;
    private int canvasPixels[];

    void clear()
    {
        validateCanvas();
        Arrays.fill(canvasPixels, 0);
    }

    // For each pixel of the image, compute its location
    // on the screen when transformed with the given AT
    void drawImageTextureScanning(
        int pixels[], int w, int h, AffineTransform at)
    {
        Point p = new Point(0,0);
        for (int x=0; x<w; x++)
        {
            for (int y=0; y<h; y++)
            {
                p.x = x;
                p.y = y;
                at.transform(p, p);
                int index = x+y*w;
                int rgb = pixels[index];
                setPixel(p.x, p.y, rgb);
            }
        }
        repaint();
    }

    // For each pixel on the screen, compute which pixel
    // of the image is placed there with the given AT
    void drawImageScreenScanning(
        int pixels[], int w, int h, AffineTransform at)
    {
        Point p = new Point(0,0);
        AffineTransform ati = at;
        try
        {
            ati = at.createInverse();
        }
        catch (NoninvertibleTransformException e)
        {
            e.printStackTrace();
        }

        int sw = getWidth();
        int sh = getHeight();
        for (int x=0; x<sw; x++)
        {
            for (int y=0; y<sh; y++)
            {
                p.x = x;
                p.y = y;
                ati.transform(p, p);
                if (p.x < 0 || p.x >= w || p.y < 0 || p.y >= h)
                {
                    continue;
                }
                int index = p.x+p.y*w;
                int rgb = pixels[index];
                setPixel(x, y, rgb);
            }
        }
        repaint();
    }

    private void setPixel(int x, int y, int rgb)
    {
        if (getWidth() <= 0 || getHeight() <= 0)
        {
            return;
        }
        validateCanvas();
        int index = x+y*getWidth();
        canvasPixels[index] = rgb;
    }

    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        validateCanvas();
        g.drawImage(canvasImage, 0, 0, this);
    }

    private void validateCanvas()
    {
        if (getWidth() <= 0 || getHeight() <= 0)
        {
            return;
        }
        if (canvasImage == null ||
            canvasImage.getWidth() != getWidth() ||
            canvasImage.getHeight() != getHeight())
        {
            canvasImage = new BufferedImage(
                getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
            canvasPixels = PixelImages.getPixels(canvasImage);
        }
    }
}

class PixelImages
{
    public static int[] getPixels(BufferedImage image)
    {
        WritableRaster writableRaster = image.getRaster();
        DataBuffer dataBuffer = writableRaster.getDataBuffer();
        if (!(dataBuffer instanceof DataBufferInt))
        {
            throw new IllegalArgumentException("Image must be TYPE_INT...");
        }
        DataBufferInt dataBufferInt = (DataBufferInt)dataBuffer;
        return dataBufferInt.getData();
    }
}

```

It has two methods for painting an image (consisting of a 1D array of pixels) into the "canvas" (which is also a 1D array of pixels):

* `drawImageTextureScanning`: For each image pixel, this computes the the position on the screen where the pixel has to be placed
* `drawImageScreenScanning`: For each screen pixel, this computes the image pixel that has to be placed there

Both approaches are horribly inefficient, because each pixel location is transformed individually. For a more efficient implementation, one would have to use more sophisticated algorithms. One common approach is to use an algorithm that is similar to the Bresenham line algorithm to efficiently compute the "next" pixel that has to be painted.

---

To emphasize this once more: If you want to draw and handle sprites *efficiently*, then use the built-in infrastructure of `BufferedImage`. Preferably *managed* images of type `TYPE_INT_ARGB` or `TYPE_INT_RGB` \- see my answer to the linked question, particularly the section about "Implementation Details" (no fear, it's not as technical as it may sound...).

---
Tags: java, 2d, graphics, matrix, transformation
---


# Question
Title: Building a chunk w/ blocks: making ramps. How to detect if blocks are making "stairs" (like in a mountain) and should be turned into ramps?
My question is quite simple, but the answer may be not.

I am studying and making a voxel engine, generating block vertices around its center position with TriangleList primitive at C#/XNA.

The problem is that I don't want that my game make those ugly "stairs" of cubes in mountains or hills. I want that the cube turns into a ramp when needed (when it has no connection with blocks at some sides, for example: no connection at top and east, then it turns into a ramp from west top to east bottom).

Another example that already exists may be found at SimCity 2000 maps. Edges become ramps, in many types, depending of how the squares of the terrain grid are modeled. Even corners between two directions of ramps become a new type of ramp, with two triangles.

I don't know how to detect that in a easy way, like, do I have to test each side and then check between the sides detected for selecting the type of ramp to create?... Or what should I test first, and then select the way of placing the vertices?

Thanks for any answer. And sorry for my English, if something is wrong.

# Answer
> 2 votes
As far as I know, there's no existing algorithm for this, you'll just have to create one. You're already on the right track. For each cube, check the surrounding cubes to see if converting the current cube is reasonable.

For example, say we're looking at cube #5 on a hill side. (green is solid, while is air).

This image will represent the X axis. You'd perform this test for the Z axis as well. Basically, we can simplify the check to:

```
if(isSolid(x-1, y, z) && !isSolid(x+1, y, z))
    ConvertToRamp(x, y, z, RampDirection.TopWest);
else if (!isSolid(x-1, y, z) && isSolid(x+1, y, z))
    ConvertToRamp(x, y, z, RampDirection.TopEast);

```

In this case, we'll trigger the second option, because 4 (x-1) is not solid, and 6 (x+1) is solid. This will convert 5 into a ramp with its top toward the East (top in the X plus direction), as shown with the red line.

The same check can be performed for the z axis. Then you'll find that you have a case where a ramp is valid in two directions. You can either choose a direction to make the ramp, or create some kind of dual direction ramp.

So what about performance? Running this check on every cube might get crazy when generating terrain. There's a few things you can do:

* Only check surface level cubes. Don't worry about making ramps underground.
* Don't perform this test on cubes that are air.
    + Or only perform it on cubes that are air with solid cubes below them. This would add new ramps to your existing blocky terrain.
* Store a byte for each cube that describes if its neighbors are solid or not (for example, a 1 for solid and 0 for air). Then you can do a quick bit check to test if a cube should be a ramp. This sort of offsets the performance hit to another stage of world generation, but it's likely a stage the user is either expecting (loading screen) or they're not watching and waiting for it to happen (chunk generation out of view).

# Answer
> 1 votes
I guess what you're looking for is the Marching Cubes algorithm or some variation of it.

Basically, you do exactly what you described: Look at the surroundings and then pick an actual "piece" that fits in.

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


# Question
Title: How to approach players beeing overlapped by high isometric tiles?
I'm making a browser game wich is based on PHP, MySQL and Javascript. It has an isometric world where the player can move and see other players/NPCs. But if a tile in the foreground is so high that it overlaps the tile behind it (e.g. a building or a group of trees, etc.), how to approach players beeing overlapped as well? I don't wan't players to be able to "hide" behind high tiles so that the characters of other players or the own character is not visible.

I thought about involving transparency by "making a sandwich" with a tile layer at the bottom, then the player and then the same tile layer on top, but slightly transparent. But when I tried it, the player looked like some king of ghost floating around and it was not clear where the player stands exactly.

Other games (like Age of Empires) managed this by displaying overlapped characters as an outline but this is really complicated/CPU-intensive using PHP, as far as I know.

I have no idea on how to approach this problem. Any ideas?

# Answer
I don't think displaying an outline of your character will be CPU intensive (unless you have thousands of players to display).

You just need to have 2 sets of images for your characters: 1 with only the outline (O sprite) and one with the rest of the character (C sprite).

If you're having high tiles, you probably already draw them in the correct order (using z-order, the tiles in the background first, and the ones in the foreground last).

You just have to draw the C sprite in the correct z-order (which means it may be hidden by a high tile in front of it), and the O sprite after you have drawn all the tiles (which means it will always be visible).

You mention doing this in PHP; I take it that you're working in a turn based game, and you're generating an image on the server every time something changes.

While it's not critical, you may consider rendering the scene in Javascript on the client side; that will greatly reduce the bandwidth used by your game (each tile is only sent once) and displaying an isometric world in Javascript is not that difficult.
> 1 votes

---
Tags: javascript, maps, isometric, php, browser
---


# Question
Title: Graphic/Animation tools and workflow for iPhone/iOS game development
I've got some experience producing Flash games, and for all Flash's faults I find the designer/developer workflow pretty decent.

I can set up a template FLA with placeholder movieclips and code to that independently of a designer/animator doing their thing. When it comes time for integration, I can either compile their animations into my project by using a SWC or by loading SWF's at runtime.

I've had a quick look, but I can't see any tools that offer a similar workflow for iOS game development. Could anyone producing iOS games shed any light on how they're handling designer/animator/developer workflow?

# Answer
> 4 votes
Unity for iPhone is the most complete pipeline and toolset I've found. It is natively a 3D engine, but can be made to do 2D as well. For 2D, I've paired Unity with SpriteManager2 which is an excellent third party tool and library.

A warning, however - it is still unclear if Unity projects will be allowed on the iPhone in the future due to Apple's new terms of service. Unity is working hard to ensure that it will be OK, but who knows with Apple's track record.

There is also Unity for Android coming later this year so if you build a game for iPhone and Unity gets banned by Apple, you could still put it on Android.

# Answer
> 1 votes
We have had quite a bit of success using Unity3D's iPhone Engine. Unity has a similar workflow to Flash and we have found that all members of the team make the transition fairly well.

You might want to check out Unity for Flash Developers

# Answer
> 0 votes
I was in your same situation. As a 2D guy I really have a deep fear of huge IDE with unlimited options for the 3D world (Maya, 3DStudio). Lately I ended up coding with frameworks (Cocos2D, SpriteKit).

But in your case, I highly recommend you to take a look into SpriteBuilder. It's the most Flash alike for iOS 2D game development right now. You will find it really easy and familiar out of the box.

---
Tags: iphone
---


# Question
Title: How can I simulate a magnet that attracts a ball in a 2D enviroment?
I am making a top-down game where you have to move a ball from point A to point B. You are attracting the ball using magnets that are standing still. The ball needs to get pulled by multiple magnets.

How can I make this happen?

# Answer
> 4 votes
Magnets are kinda hard to simulate, but if you are looking solely for the effect of pulling and pushing objects you can use coulomb's law and simulate an electric field.

Basically there are some points in the plane with an electric charge, which is either positive or negative. Since you are not aiming to do a physics simulation and for a game you are only interested in the final results, you can assume the ball has '+1' coulomb charge. With this assumption, all the points with negative charge will pull the ball, and those with positive charge will push it.

The total force applied to ball will be equal to sum all forces from each of those electric charges.

```
totalForce = Vec2(0,0);
foreach(charge in electricCharges)
{
    Vec2 distance = charge.position - ball.position;
    Vec2 unitDistance = distance / distance.length();
    Vec2 chargeForce = unitDistance * (charge.signedMagnitude / (4 * Math.Pi * Coulomb_Constant * distance.squareLength());
    totalForce += chargeForce;
}

```

You can also simplify above equation by assuming charge of the ball is `4 * Math.Pi * Coulomb_Constant`. this will only scale your the values you need to assign to each static charge.

From this point you just need to update the ball velocity and position according to force applied.

---
Tags: xna, physics
---


title: Multi-colored text and kerning

text:
# Question
Title: Multi-colored text and kerning
Drawing multi-colored text or highlighted text in XNA/MonoGame is pretty annoying, and the standard way I've seen to do it is to just to make multiple SpriteBatch.DrawString calls, and place them using the x-coordinates given by SpriteFont.MeasureString. This is fine if you're highlighting whole words or blocks of text, but if you only want to highlight select letters inside of a word, you get a kerning nightmare:

Sometimes this looks alright, but not consistently and I can't think or find a good way to space out the letters properly.

Therefore, I would like to know if there's either a better way to draw highlighted text like this in XNA/MonoGame, or a way to pull kerning data out of a font so I can space the letters properly or some other fancy way to do it using masks or whatnot.

Thanks in advance!

# Answer
What I do is ignore the built in SpriteFont's in MonoGame and roll my own. If you use a tool like BMFont to generate the texture, writing a basic font renderer is pretty easy.

First you'll need to grab a BmFont XML Serializer so that you can load the font file into C#. You can find one on pastebin here. http://pastebin.com/x3Z2mDC6

Then you'll need to write a basic font renderer. Here's one I've used before:

```
public class FontRenderer
{
    public FontRenderer (FontFile fontFile, Texture2D fontTexture)
    {
        _fontFile = fontFile;
        _texture = fontTexture;
        _characterMap = new Dictionary<char, FontChar>();

        foreach(var fontCharacter in _fontFile.Chars)
        {
            char c = (char)fontCharacter.ID;
            _characterMap.Add(c, fontCharacter);
        }
    }

    private Dictionary<char, FontChar> _characterMap;
    private FontFile _fontFile;
    private Texture2D _texture;
    public void DrawText(SpriteBatch spriteBatch, int x, int y, string text)
    {
        int dx = x;
        int dy = y;
        foreach(char c in text)
        {
            FontChar fc;
            if(_characterMap.TryGetValue(c, out fc))
            {
                var sourceRectangle = new Rectangle(fc.X, fc.Y, fc.Width, fc.Height);
                var position = new Vector2(dx + fc.XOffset, dy + fc.YOffset);

                spriteBatch.Draw(_texture, position, sourceRectangle, Color.White);
                dx += fc.XAdvance;
            }
        }
    }
}

```

Obviously you'll also need to make some changes to allow each letter to be a different color. Once you've got the basic framework in place that should be pretty easy.

I have a more complete tutorial on my blog here:

http://www.craftworkgames.com/blog/tutorial-bmfont-rendering-with-monogame/
> 3 votes

# Answer
The font format for XNA/MonoGame still *stores* the required info for kerning - obviously it needs it to draw text itself! You just need to get at it and use it from your own code.

**In MonoGame you can *directly* access the gylph data** (see this source file). The `Gylph` structure contains the kerning information you need to layout your text correctly.

(MonoGame is open source, so this was correct at time of writing, and may change.)

If you look at `DrawInto` and `MeasureString` in MonoGame, you can figure out what is actually being done with the kerning data. It should be reasonably straightforward to reuse/reference that for your own string drawing.

If you use XNA, the same data is available. Use ILSpy and reflection to get access to it. The kerning information in is simply ABC data returned from `GetCharABCWidths` in the win32 API (it's the same data for both XNA and MonoGame, but stored slightly differently).
> 1 votes

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


# Question
Title: Implementig State-driven agents in an Entity-Component-System
A state-driven agent is an agent that performs an action based on its current state. The logic can be implemented through the use of a D-FSM that changes state depending on the Agent's "perception" and "stimuli" and perform actions on entering, being in, and exiting a state.

I'm trying to implement this type of design in a Entity-Component-System (ECS) architecture.

My first thought was to implement an "FSM" component containing a current\_state and a rulebook, a System that updates the FSM component current\_state depending on its rulebook and a System that implements the actions of an Entity ( and modify its components accordingly ) depending on the state of the FSM component.

I'm not sure this is a correct ECS implementation and that it can cleanly represent the enter\_state/exit\_state -\> perform an action behaviour.

So, how should SDA be implemented in a ECS architecture?

# Answer
> 2 votes
The approach I have taken in the past was to separate the behavior and the AI aspects into two systems much as you described. On the behavior side, you have a series of predefined aspects that can be chained together into a behavior tree like patrol, attack, threat detection, etc. The behavior tree describes how these behaviors interact, which has priority, etc. The benefit to separating the behavior in this way is you can create a series of several behavior tree patterns per level and simply reuse the pattern across multiple AI entities. This saves on memory budget and makes it much easier to make a change to a behavior tree and have that change reflect across multiple entities with ease.

On the opposite side when I create an AIController, I must give the AIController a behavior tree. The behavior tree is much like a PlayerController's keyboard/mouse. The behavior tree is updated each logical tick and it emits events that the controller is responsible for keeping track of, translating into generalized commands and dispatching the commands to the entity.

As I pointed out, this works in much the same way as keyboard/mouse's input being interpreted by a PlayerController, translated into generalized game commands, and dispatched to the entity.

# Answer
> 0 votes
Assuming that there are only going to be a small number of FSM classes (one for movement, one for AI, etc.) then I would make each state a component (or part of a component). For example, if an entity has Walking, Climbing, Melee and Ranged components, in these components will be encoded the Walking, Climbing, Patrolling, and Attacking states of two different FSMs. Although you will have to have a separate place for each entity to actually keep track of which states it's in, such as an additional AI component, this will make it relatively simple to extend the mixin philosophy to your FSMs.

---
Tags: ai, entity-system, component-based, entity-component
---


# Question
Title: 2D Terrain generation with controlled variations
Well, I'm trying to create a simple endless runner and -this may sound repetitive- I'm searching for ways to generate the terrain. The game will only have 3 types of ground tiles, ascending, descending and plain, and it should look (somewhat) like this:

So, what I want to say is that the terrain can only vary 1 unit of height.

I first thought of perlin noise, but I haven't found any information about restricting height variations. I've also thought about choosing randomly between the three posible tiles, but I still want that "natural randomness" that perlin noise can produce (very high hills, deep valleys, etc)

Any idea on how to procede?

Thanks! And please excuse my english.

# Answer
> 1 votes
You can still use Perlin noise. You simply need to constrain the random value to three values. Depending on how you're generating the noise, you'll get a value between -1 and 1, or 0 and 1. Whatever you have, just divide it by three, and place your tiles based on that.

```
float range = Perlin.max - Perlin.min
float value = Perlin.GetValue(xCoord)

if(value < range * (1/3))
   placeDecending()
else if (value < range * (2/3))
   placeFlat()
else
   placeAccending()

```

Essentially you're just taking the range of random values you can get from Perlin noise, and splitting them into three categories:

* Less than 1/3
* Between 1/3 and 2/3
* Greater than 2/3

This gives you the benefit of gradient noise, while also constraining the output to three tile types.

# Answer
> 0 votes
You can also set a target height to move towards, with smaller target height variations in between. Then you can have a sort of rolling hills effect where stuff still gets generally higher or lower as desired.

This is a great use case for recursion where you can tweak the parameters of each step to get different spacings.

---
Tags: procedural-generation, terrain, perlin-noise
---


title: Entity Component System Coupling

text:
# Question
Title: Entity Component System Coupling
Lately I've been working on a small personal project which is basically an Entity Component System framework with autoupdated Systems.

While I have a pretty good idea on the way the framework should work, because of lack of experience I am having trouble with actually keeping everything decoupled.

Some details on the framework:

Each entity is defined by it's components.

Systems are responsible for the actually modifying the entities by changing their components.

In order to improve locality of reference, instead of keeping each component in the appropriate entity, all components are stored in homogenous vectors and each entity keeps a list of indices to each vector.

Since each System modifies specific components, it should keep a list only of the entities with the corresponding components. This 'registration' to the Systems happens whenever a component is added or removed from an entity.

How I dealt with all of this until now was to have a ComponentManager, an EntityManager and a SystemManager. These classes however have very tight coupling with each other. The EntitManager needs to have access to the ComponentManager in order to handle the size of the the index lists and the mapping of each component type to them. It also needs access to actually add the components in the appropriate vector. Another coupling is between the EntityManager and the SystemManager. Whenever an entity is created, it needs to be added to the list of the appropriate Systems.

A general event bus would appear to help but I am not sure how to implement it without making it global.

How do I improve this design by removing coupling while still maintaining the system's functionality?

# Answer
> 2 votes
Class coupling can occur when you have classes that work collaboratively to provide functionality that the classes alone couldn't otherwise.

One way to avoid coupling is to abstract the coupling away into a layer above the classes in question. For example, remember that the classes you are talking about are part of a larger system called the Game Object System. You could easily have a `ObjectManager` class that brings the classes you describe together which 1) exposes a public API and 2) takes on the burden of some of the coupling needs you want to avoid.

The first benefit allows you to freely alter the internal class interactions between `EntityManager`, `ComponentManager`, and `SystemsManager` without impacting the external code. The second allows this `ObjectManager` to implement methods such as `ActivateEntity()` that internally manages the interactions between classes like `EntityManager` and `SystemsManager` for a specific use case.

Another means to decouple the three classes is to leverage the observer pattern where appropriate. For example, an `EntityManagerListener` class could expose some callback methods that the `SystemsManager` implements by subclassing the listener. During startup, the `SystemsManager` registers as a listener to the `EntityManager` and now when the entity manager fires specific events, the `SystemsManager` and any other class of interest can be informed without any coupling. Similarly the `ComponentManager` could implement something similar to adjust it's internals based on things that happen with the `EntityManager`. None of this requires an event bus, just one class maintaining a vector of listeners and iterating them during specific cases where event notifications are to be done.

But if you find yourself where the inner workings of one class require a considerable amount of information from another class, then perhaps the relationships you've built are too granular and perhaps should be refactored into a single class.

# Answer
> 1 votes
Interfaces are probably the answer. Your `ComponentManager`, `EntityManager`, and `SystemManager` do not really need each other, they only need each other's *types*. But an object doesn't have to be a type definition. It can be merely an implementation of a type by fulfilling an interface. Your objects can serve their current roles, but they still can be removed and replaced at will. This can be done via injection, or any number of other constructor-type patterns you want to implement.

Sometimes systems need each other; it's unavoidable. Make each of these items an implementation of a type (by interface), rather than a definition of a type, and they will be as decoupled as is possible.

And if you desperately want to avoid globals, there is always the infamous Singleton (also a constructor pattern).

---
Tags: c++, entity-system, component-based, design-patterns
---


title: Align SpriteText position

text:
# Question
Title: Align SpriteText position
i have this function which aligns text.

```
static function AlignTxt(obj : GameObject, txtAnchor : SpriteText.Anchor_Pos,
txtAlign : SpriteText.Alignment_Type)
{
obj.GetComponent(SpriteText).SetAnchor(txtAnchor);
obj.GetComponent(SpriteText).SetAlignment(txtAlign);
}

```

The above function is called from this function..

```
txtlib.AlignTxt(powerTxt, SpriteText.Anchor_Pos.Middle_Left, SpriteText.Alignment_Type.Center);

```

But i get this error on AlignTxt Function :

The name 'SpriteText.Anchor\_Pos' does not denote a valid type ('not found'). The name 'SpriteText.Alignment\_Type' does not denote a valid type ('not found').

Can you please help me to solve the error..Thanks..

# Answer
You get those errors because those types (`SpriteText.Anchor_Pos` and `SpriteText.Alignment_Type`) don't exist.

The correct types are `TextAnchor` and `TextAlignment`.

```
static function AlignTxt(obj : GameObject, txtAnchor : TextAnchor,
  txtAlign : TextAlignment)
  {
    obj.GetComponent(SpriteText).anchor = TextAnchor.txtAnchor;
    obj.GetComponent(SpriteText).alignment = TextAlignment.txtAlign;
}

```
> 0 votes

---
Tags: 2d, unity, javascript, unityscript
---


title: Collision bug with gravity in slick2D

text:
# Question
Title: Collision bug with gravity in slick2D
I have fixed some of the previous problem. The collision when running into a corner(a wall on two sides) however is still not working. When the player runs into a corner he just falls down and out of the map. Not sure what is happening.

manageWallCollision Method:

```
@Override
public void manageWallCollision(Scene currScene) {
    for(int i = 0; i < currScene.getMapManager().getWalls().size(); i++){
        MapTile currTile = currScene.getMapManager().getWalls().get(i);

        if(currTile.isCollidable()){
            if(this.getBounds().intersects(currTile.getBounds())){
                //down
                if(vy > 0 && y2 > currTile.getY() && y2 < currTile.getY2()&& y < currTile.getY() && y < currTile.getY2() ){
                    setY((currTile.getY() - getHEIGHT()) - 7);
                    break;
                }
                //up
                else if(vy < 0 && y < currTile.getY2() && y > currTile.getY() && y2 > currTile.getY2() && y2 > currTile.getY()){
                    setY(currTile.getY2() + 7);
                    break;
                }
                //right
                else if(vx > 0 && x2 > currTile.getX() && x2 < currTile.getX2() && x < currTile.getX() && x < currTile.getX2() ){
                    setX((currTile.getX() - getHEIGHT()) - 7);
                    break;
                }
                //left
                else if(vx < 0 && x < currTile.getX2() && x > currTile.getX() && x2 > currTile.getX2() && x2 > currTile.getX()){
                    setX(currTile.getX2() + 7);
                    break;
                }
                break;

            }
        }
    }
}

```

If you need any more code or info just ask. Any help is appreciated.

bump

# Answer
It looks like your character is entering a tile and then you're setting it just outside of it. If that "just outside" part is actually the border then it's still intersecting and will react the next turn as well. Additionally if you don't also reset their velocity when they hit the barrier, they'll bump it again on the next loop.

On a side note: you don't need all of the "this." portions in your code. The way Java scope works you can't get any scope confusion for anything that's not the same name as a passed in parameter.
> 1 votes

---
Tags: java, collision-detection, slick
---


title: Persistence of Random

text:
# Question
Title: Persistence of Random
Sorry if this is such a simple thing, but for some reason I can't get my head around it.

Imagine you have a world, that you have "seeded" with a value. You base all your randomisations off this value - perhaps you made mountains, monsters, or any other such thing.

Then the user saves her game, and then picks up where she left off a few days later.

We can store the seed we started with easily enough. But, it will reset to the beginning. What I would actually like is to "start off where we left off". Therefore, with persistence, do I need to be storing the iterations that we applied on said random number generator? When loading the saved game, do we go through the iterations to arrive at the place we should be?

An alternate would be to initialise a world using a random seed, and then throw it away when we save, so that any subsequent *load*, has a new random number generator.

Thoughts and ideas welcome :)

**Edit**

To reiterate from the comment I made below, my first thought was to wrap all access to the `Random` class, and track the number of iterations. This could be saved alongside the seed. When loading, one would re-initialise the class, and then loop through the iterations (effectively throwing away the result) to arrive at the point you'd have been at originally.

Also, added c# tag.

# Answer
The *correct* way to do this is to implement your own random number generator, such as the Mersene Twister. The reason you should implement your own is this:

**The output of `Random` is not guaranteed to be the same between different invocations of your program!**

(Even though it *should* be the same when running on the identical versions of the .NET Framework.)

When you implement your own, you simply need to serialize the *current* state of your random number generator (assuming your goal is to have the "generated in the future" sequence of numbers match). Note that the `Random` class in C# is serializable, should you wish to risk using it.

If you want to get the same sequence of random numbers, from the start, then simply store the initial seed (again, on your own implementation is safer).
> 3 votes

# Answer
If the players cannot modify the world, you may be able to just save your seed, and rebuild the world later.

If they can modify the world, it will be very tricky to rebuild the world (especially if their modifications depends of the RNG at the moment they take the action).

If your world is highly procedural (you generate a lot of data) and modifiable you may try to save both the seed and a "delta" of the differences between the generated world and the "actual" world.

One way to do that (not the most efficient but it should work) would be:

* Save the seed
* Recreate the original world in another part of your memory (from the creation seed)
* Iterate through your world objects/actors/etc and if they have changed, store the new value

Re-loading will be almost the same:

* Read the seed
* Recreate the original world
* Read all modified objects and overwrite their "original" version

Depending of the specific details of your game, you can probably optimize this further.

Just a bit of warning: If your procedural process is using floating numbers AND you want the saved games to be useable on another computer than the one which saved it, it will likely not work the way you're expecting it unless you take extra precautions (see this article about the issue if you plan to do it: http://gafferongames.com/networking-for-game-programmers/floating-point-determinism/)
> 0 votes

# Answer
You could reseed the terrain generation per chunk dependent on both the global seed and the coordinates of where you are generating.

Enemy RNG can be independent from this global seed.
> 0 votes

---
Tags: c#, random
---


# Question
Title: CSS Sprite position updates slow due to addition of 'px'?
I'm moving fewer than 10 `position: absolute` elements around the screen. An enormous amount of CPU time (profiled in Chrome as `(program)` i.e. native code) is used where I do the following:

```
style.left = monster.x + 'px';
style.top  = monster.y + 'px';

```

... where `style` belongs to the DOM element representing the monster in question.

This is a string concatenation cost since as soon as I remove that `+ 'px'`, the problem disappears. Of course, then absolute positioning doesn't work onscreen since the `px` is required by the browser.

I'm running this logic via `requestAnimationFrame` which runs about 60FPS... am currently amending such that position updates only occur every 2-3 frames as this will certainly help. Am also modifying so that only when the numeric value *changes*, is the style property set anew, rather than setting the style property on every active frame.

Even so, is this how CSS sprite updates are done? Is it always this slow? The only alternatives I can see are to use canvas (usually also slow, for different reasons) or WebGL. I'd prefer CSS for simplicity.

# Answer
I doubt the string concatenation is the culprit here, but you could always use the `transform` CSS property, which is supported in almost every recent browser.

Since most CSS transforms also use `px` values (for example: `translate`), you should use raw matrix coordinates.

So to offset an element by say `x: 10px, y: 20px` you would use:

```
transform: matrix(1, 0, 0, 1, 10, 20)

```

But since you're dealing with CSS properties, there's always going to be a string (the property value) that will be interpreted by the browser at some point. So I'm not sure if that's going to speed up things considerably.

Internally you could work with matrices as arrays, say:

```
var transformMatrix = [1, 0, 0, 1, 10, 20];

```

Then when it comes to rendering, assign it like so:

```
style.transform = "matrix(" + transformMatrix.join() + ")";

```

But as I mentioned previously, there's no way to avoid string concatenation/conversion at some point if you're dealing with CSS properties. Another thing to note is that the `transform` property requires a vendor-prefix in some browsers.

Libraries like jQuery will automatically generate the prefix for you, if you're not using such a library, you should consider these vendor-prefixes: `-moz-`, `-ms-`, `-webkit-`, `-o-`. A CSS declaration would then look like this:

```
.myElement {
    -moz-transform: matrix(1, 0, 0, 1, 10, 20);
    -ms-transform: matrix(1, 0, 0, 1, 10, 20);
    -webkit-transform: matrix(1, 0, 0, 1, 10, 20);
    -o-transform: matrix(1, 0, 0, 1, 10, 20);
    transform: matrix(1, 0, 0, 1, 10, 20);
}

```

Which translates to the following JavaScript code:

```
style.MozTransform =
style.msTransform =
style.WebkitTransform =
style.OTransform =
style.transform = 'matrix(1, 0, 0, 1, 10, 20)';

```

But instead of doing that, you better figure out the required prefix of the browser beforehand and then just use the property that is supported by the browser. Here's a short explanation how to figure out vendor prefixes using JS.
> 2 votes

---
Tags: javascript, html5, performance, optimization
---


title: Responsive GUI with Unity and C# script

text:
# Question
Title: Responsive GUI with Unity and C# script
I'm working on my character menu for an RPG in Unity. I have my menu set up with different buttons for different categories. All is well, except when I re-size my screen, my layout is sized incorrectly. I need my GUI to respond to my screen size. Is there any information or a tutorial I can read?

# Answer
> 1 votes
I'm disturbing an old thread but I feel it's worth it. You can use the all new unity 4.6 with a great UI system. The anchors is the magic word you should look for. Setting the anchors of the UI elements to their corners will make them responsive. It is as simple as that.

# Answer
> 1 votes
I resolved my issue. I accomplished this by creating a ratio based on target screen sizes and actual screen sizes. This ratio is then applied to static value coordinates.

---
Tags: unity, gui, menu
---


# Question
Title: How to make it two seconds for Time.time?
```
var targetscript : Diamond;
var red : Color;
var orange : Color;

function Start () {
    gameObject.camera.backgroundColor = red;
}

function Update () {
    if (targetscript.score > 4) {
        gameObject.camera.backgroundColor = Color.Lerp(red, orange, Time.time);
    }
}

```

So right now, if the score is larger than 4 then it would change the camera background color to orange with lerp. But its too quick. I read on the internet that Time.time is 1 second. What is the alternative way but for 2 or 3 seconds? I tried this : http://answers.unity3d.com/questions/328891/controlling-duration-of-colorlerp-in-seconds.html I tried the code for the voted answer but it didn't work. It still lerps through quickly. Does anyone have any ideas? Thanks

# Answer
> 1 votes
You seem to misunderstand `Lerp`. The last parameter is the blend-factor (not time) and should be a value from `0 - 1`. In your case, a blend-factor of `0` results in red and `1` results in orange.

You can just plug in `Time.time`, but this value will get truncated to `1` as soon as it's bigger than `1`... and that point will be reached 1 second into your game. Doesn't sound like the thing you want to do.

So what you should do is have a "start-time" and a desired duration. Example:

```
var duration:float = 3; // duration of 3 seconds
var startTime:float = -1;

```

Then you need to assign the `startTime` as soon as your color-change starts and use it to calculate the time that has passed. Example:

```
function Update () {
    if (targetscript.score > 4) {
        if(startTime < 0){
            startTime = Time.time;
        }
        gameObject.camera.backgroundColor =
            Color.Lerp(red, orange, (Time.time - startTime) / duration);
    }
}

```

---
Tags: unity, color, unityscript
---