title: Smooth Camera Follow

text:
# Question
Title: Smooth Camera Follow
I am using a fixed static background. I have a gameobject(Current ref. image) which is moving with the help of waypoints. I have made camera to follow the Current. The camera is stuttering while moving. Can anyone help me to solve the camera stuttering and make it follow the Current smoothly?

This is my code attached to camera following the star

```
public class CameraController : MonoBehaviour {

    void Start () {
        GameObject.FindGameObjectWithTag("OptionCamera").GetComponent<Camera>().orthographicSize =
        (20.0f / Screen.width * Screen.height / 2.0f);
    }

    void LateUpdate() {
        if (GameObject.FindGameObjectWithTag ("Current") != null) {
            if (GameObject.FindGameObjectWithTag ("Current").GetComponent<CurrentController>().Greenblast == false &&
                GameObject.FindGameObjectWithTag ("Current").GetComponent<CurrentController>().Redblast == false)
            {
                Vector3 pos = GameObject.FindGameObjectWithTag ("Current").transform.position;
                transform.position = new Vector3 (transform.position.x, pos.y, transform.position.z);
            }
        }
    }
}

```

# Answer
Based on the comments above, the followed object "Current" is only moving in FixedUpdate.

By default, FixedUpdate runs 50 times per second. In-between FixedUpdates, Unity renders as many frames as it can, each time calling Update, LateUpdate, etc.

Because the rendered framerate is usually not a perfect multiple of the FixedUpdate rate, this can cause a beat frequency between the updates which is perceived as a stutter.

For example, if you're rendering at 60 fps, but the FixedUpdate is running at 50 Hz, your frames might look like this:

```
Frame         1  2  3  4  5  6  7  8  9 10 11 12
FixedUpdate   1     2  3  4  5  6     7  8  9 10

```

Sometimes two Update frames get rendered off of the same FixedUpdate state, because less than 0.02s have elapsed since the last FixedUpdate. Visually, everything hesitates a beat once every 6 frames, then runs a little fast to catch up.

The situation is reversed if you're running below 50 fps, say at 30 fps:

```
Frame         1     2     3  4     5     6
FixedUpdate   1  2  3  4  5  6  7  8  9 10

```

In this case, frames 2, 3, 5, and 6 have two FixedUpdates' worth of movement behind them, while there's only one FixedUpdate between frames 3 & 4, causing the apparent motion to slow down for one frame in every 5.

This is usually resolved using **interpolation**.

If you're moving your object using velocities on a Rigidbody, you can tell Unity to handle this for you by setting its Interpolation mode to either:

* interpolate (smooth, at the cost of 1 physics frame of latency) or
* extrapolate (maximum responsiveness, but may overshoot & correct due to mis-prediction)

Automagically, the movement of this object will now appear continuous, no matter your framerate.

You can also implement this yourself by adding a separate visual object that follows the (invisible) Current object in Update or LateUpdate, using Time.deltaTime as a blend weight to interpolate or extrapolate its position smoothly.

Or, if keeping the gameplay in FixedUpdate isn't important in this case (say, you're running at a locked framerate, or this is a non-interactive sequence in the game) you can change the object itself to move in Update so it changes its position with every rendered frame. (The reason this is usually avoided is that, if your framerate is variable, you can get inconsistent results from gameplay in Update, causing hard-to-track-down bugs that depend on precise timings)

For more insight on why the updates are split this way and how you can interpolate the visible game state between frames, check out this article on fixed timesteps.
> 5 votes

# Answer
You can use Vector3.Lerp(transform.position, WAYPOINT POS, Time.deltaTime) for smooth movement from one point to another.
> 2 votes

# Answer
The only possibility based on your snippet would be all the collection iterations it has to do each line to find stuff. If you have a lot of objects to hunt through, maybe that could influence performance to cause the stutter although I doubt it.

Have you profiled the code to see if it's a garbage collection issue somewhere other than this snippet?

Are you sure it's the camera and not the star(current) that is stuttering?

To speed up your snippet there, you can try something like this so it only has to find stuff once per call:

```
//in LateUpdate
GameObject go = GameObject.FindGameObjectWithTag("current");
If(go != null)
{
  CurrentController cc = go.GetComponent<CurrentController>();
  if(!cc.RedBlast && !cc.GreenBlast)
    {
      transform.position.Y = go.transform.position.Y;
    }
}

```
> 0 votes

# Answer
From what you have posted I have a few pointers:

* There are some Follow scripts you can try to tinker with in the standard assets: \**Standard Assets\Utility\** and \**Standard Assets\2D\**
* You shouldn't have Find functions inside Update() loops as it might slow down your game. Here is how your code can include that:

(not the solution just an improvement)

```
public class CameraController : MonoBehaviour{

private GameObject target;

void Start ()
{
GameObject.FindGameObjectWithTag("OptionCamera").GetComponent<Camera>().orthographicSize = (20.0f / Screen.width * Screen.height / 2.0f);
target = GameObject.FindGameObjectWithTag ("Current");

 }

 void LateUpdate()
 {
     if (target != null) {
         if(target.GetComponent<CurrentController>().Greenblast == false &&
            target.GetComponent<CurrentController>().Redblast == false)
         {
             Vector3 pos = target.transform.position;
             transform.position = new Vector3 (transform.position.x, pos.y, transform.position.z);
         }
     }
 }
 void UpdateTarget(GameObject target) {
     this.target = target;
 }
 }

```
> 0 votes

---
Tags: unity, camera, movement
---


title: Fading in and fading out animations

text:
# Question
Title: Fading in and fading out animations
This is how I'm creating my player. Is there any way to start fading in and fading out for an amount of time when I get hit?

```
private Texture tex = Game.res.getTexture("player");

public Player(Body body) {
   TextureRegion[] sprites = new TextureRegion[1];
   sprites[0] = new TextureRegion(tex, 0, 0, 70, 96);
   sprites[1] = new TextureRegion(tex, 69, 193, 68, 93);
   animation.setFrames(sprites, 1 / 6f);
}

```

# Answer
The solution suggested by Sebastian would work, but you'll end up with a lot of code just for a "fade out/fade in" animation.

Libgdx has built-in functionnalities for that in Scene2D, you should use them. (Actions, Stage, Actor) That would make your code as simple as that :

```
 myPlayer.addAction(Actions.sequence(Actions.fadeOut(0.15f), Actions.fadeIn(0.15f));

```

Where myPlayer is an instance of an object extending the Actor class.
> 2 votes

# Answer
Why not set the alpha value of the sprites directly via `sprite.setAlpha(float)`? Of course you would have to call that by your rendering method and calculate the amount of alpha alteration using `deltaTime`.

https://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/graphics/g2d/Sprite.html#setAlpha-float-
> 1 votes

---
Tags: libgdx, textures, animation, sprites
---


# Question
Title: How to bounce the player away after attack by enemies?
I creating a 2d platform game. I would like to bounce the player away after hit by the enemy, so the user get another feedback beside the sound effect.

How can I achieve my wish?

Use the following code for my enemy attack:

```
public float timeBetweenAttacks = 0.5f;     // The time in seconds between each attack.
    public int attackDamage = 25;               // The amount of health taken away per attack.

    Animator anim;                              // Reference to the animator component.
    GameObject player;                          // Reference to the player GameObject.
    PlayerHealth playerHealth;                  // Reference to the player's health.

    bool playerInRange;                         // Whether player is within the trigger collider and can be attacked.
    float timer;                                // Timer for counting up to the next attack.

    void Awake () {
        // Setting up the references.
        player = GameObject.FindGameObjectWithTag ("Player");
        playerHealth = player.GetComponent <PlayerHealth> ();
        //enemyHealth = GetComponent<EnemyHealth>();
        anim = GetComponent <Animator> ();
    }

    void OnCollisionEnter2D (Collision2D other) {
        // If the entering collider is the player...
        if(other.gameObject == player) {
            // ... the player is in range.
            playerInRange = true;
        }

    }

    void OnCollisionExit2D(Collision2D other) {
        // If the exiting collider is the player...
        if(other.gameObject == player) {
            // ... the player is no longer in range.
            playerInRange = false;
        }
    }

    void Update () {
        // Add the time since Update was last called to the timer.
        timer += Time.deltaTime;

        // If the timer exceeds the time between attacks, the player is in range and this enemy is alive...
        if(timer >= timeBetweenAttacks && playerInRange) {
            // ... attack.
            Attack ();
        }

        // If the player has zero or less health...
        if(playerHealth.currentHealth <= 0) {
            // ... tell the animator the player is dead.
            anim.SetTrigger ("PlayerDead");
        }

    }

    void Attack () {
        // Reset the timer.
        timer = 0f;

        // If the player has health to lose...
        if(playerHealth.currentHealth > 0) {
            // ... damage the player.
            playerHealth.TakeDamage (attackDamage);
        }
    }

```

The enemies do have a `box collider 2D`, and the script you can see above. Player has also a box and circle `collider 2d`, a `rigid body2D` and a player health script:

```
public int startingHealth = 100;                            // The amount of health the player starts the game with.
    public int currentHealth;                                   // The current health the player has.
    public Slider healthSlider;                                 // Reference to the UI's health bar.
    public Image damageImage;                                   // Reference to an image to flash on the screen on being hurt.
    public AudioClip hurtClip;
    private AudioSource source;
    public float flashSpeed = 5f;                               // The speed the damageImage will fade at.
    public Color flashColour = new Color(1f, 0f, 0f, 0.1f);     // The colour the damageImage is set to, to flash.

    public float internalStrength = 1000;
    public int externalStrength = 1000;

    Animator anim;                                              // Reference to the Animator component.
    PlayerMovement playerMovement;                              // Reference to the player's movement.

    bool isDead;                                                // Whether the player is dead.
    bool damaged;                                               // True when the player gets damaged.

    void Awake () {
        // Setting up the references.
        anim = GetComponent <Animator> ();
        source = GetComponent <AudioSource> ();
        playerMovement = GetComponent <PlayerMovement> ();

        // Set the initial health of the player.
        currentHealth = startingHealth;
    }

    void Update () {
        //internalStrength -= Time.deltaTime;
        //externalStrength = Mathf.RoundToInt(internalStrength) + Random.Range(-100, 100);

        // If the player has just been damaged...
        if(damaged) {
            // ... set the colour of the damageImage to the flash colour.
            damageImage.color = flashColour;

        }
        // Otherwise...
        else {
            // ... transition the colour back to clear.
            damageImage.color = Color.Lerp (damageImage.color, Color.clear, flashSpeed * Time.deltaTime);
        }

        // Reset the damaged flag.
        damaged = false;

    }

    public void TakeDamage (int amount) {
        // Set the damaged flag so the screen will flash.
        damaged = true;

        // Reduce the current health by the damage amount.
        currentHealth -= amount;

        // Set the health bar's value to the current health.
        healthSlider.value = currentHealth;

        // Play the hurt sound effect.
        source.PlayOneShot (hurtClip);

        // If the player has lost all it's health and the death flag hasn't been set yet...
        if(currentHealth <= 0 && !isDead) {
            // ... it should die.
            Death ();
        }
    }

    void Death () {
        // Set the death flag so this function won't be called again.
        isDead = true;

        // Tell the animator that the player is dead.
        anim.SetTrigger ("Die");

        // Set the audiosource to play the death clip and play it (this will stop the hurt sound from playing).

        // Turn off the movement and shooting scripts.
        playerMovement.enabled = false;
    }

```

If there is something unclear or whatever, ask me! Look out for some advice.

# Answer
> 1 votes
you can try Rigidbody2D.AddForce to the palyer rigidbody, using force mode : Impulse ("This mode is useful for applying forces that happen instantly, such as forces from explosions or collisions").

Put tha addforce into your TakeDamage()

# Answer
> 0 votes
You could use RigidBody2D.AddForce(Vector3) to make knockback or you could have and animation of the player being bounced.

---
Tags: unity, 2d
---


# Question
Title: How to make a 2d shooter game interesting?
Im asking what can i implement in a online multiplayer 2d shooter to make it more interesting the idea i have(i know how to make it) doesn't seem so fun what can i add to a lastman standing 2d shooter game that is not to hard to make in java? I know how to make multiplayer games online.

# Answer
1. Most games are interesting if you can play them with friends.
2. Start simple, go complex. You can make the simplest possible game, and test if your friends like it. I bet they will give you more suggestions.
3. KISS principle: keep is simple, stupid (check TeeWorlds for an example). It is much harder to make simple (to play) games, rather than complex and unintuitive games.
4. Make it easy to mod/extend your game (not MC-style). Make it possible for your friends add new features/levels/enemies/etc. to the game using a ***simple*** editor.
5. Make it an MMO (more players-\>more fun). The only downside is that it need to be *over*-performant, so it can handle \>400 players.
6. Add more game-modes, so everyone can play it as xe likes. Maybe most of them can come as mods/plugins.
7. Make it a web/HTML5 game. Some people are particularly against downloading any kind of executable content, be it .JAR, .EXE, or whatever. Plus, if you make it a web game, it might be easier to get people check it out. (Counter-example, Minecraft is played by millions, but it is not on the web...)
> 1 votes

---
Tags: game-design, multiplayer, online
---


# Question
Title: Save the screenshot of the scene locally in unity
I have a unity project which contain a button in the scene. I have loaded a terrain also into the scene. When I run the project, the terrain and the button will be shown. When I click on the button, a screenshot should be taken saved to the device.

How can I do that in unity?

# Answer
> 2 votes
http://docs.unity3d.com/ScriptReference/Application.CaptureScreenshot.html

You can use this method to capture the screen buffer at normal or scaled sizes. Give it a file path to save to, and it'll be saved there. Put this in your button press/click event( can't tell if you mean an in game button, or UI )

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


# Question
Title: What is the movement represented by this sprite animation?
Fire Emblem 7 is a sprite based game with some interesting sprite art aesthetics. For example, see this sheet of one of the main characters, Lyn:

On the last frames of the critical hit, the artist used some kind of slash effect to represent the entire motion of the sword in a single frame. It looks really appealing on video. I have two questions:

1. What is this effect called?
2. How or why did the artist arrive at that result? For example, why are those "spikes" where they are, and why is the "end" of the line fatter?

# Answer
It looks like it's supposed to represent a motion blur or at least achieve a similar effect: to convey the feeling of movement and speed as the sword is swung in a arc. In 3D we sometimes go for similar effects with geometry or particle-effect based "trails" behind slashes.

It looks the way it does for a variety of reasons, many of them due to the stylistic choices of the artist (that is, because it looks cool). There are some technical consideration to keep in mind, like what the perspective of the sprite is (and how it might foreshorten the sword during its arc), and the direction of travel (the "spikes" can help suggest that by guiding the eye). But generally things like this are designed to for visual oomph more than anything else, and tend to be exaggerated as they are only on-screen for a very limited number of frames; the exaggeration combined with human persistence of vision leads to the desired illustration of power and/or speed.
> 3 votes

# Answer
Ah yeah. Fire Emblem, a great game indeed.
If you take a really close look to the critic attack of Lyn you will actually got it. The first slash is going from down-right to up-left.
That will be the first slashing image starting from the left of the sheet combined with the second. So, we can say that the second slashing image is a continuation of the first one, and that makes a single large blow.
That's why the end of the line in the first image is fat headed, so the second image can be placed parcially on top of it. Same thing happens with the third and fourth images, (from up-rigth to down-left), they both are a single great blow.
After the enemy get's hitted, she then returns to his place, and that's the last slashing image.
Reasons for making a first blow in two images could be a couple, I think. One of them is to make the eye believe that the blow really last a while so, it gives an impression that Lyn traveled a long trail around the enemy in pretty high speed.
She is really fast, so she cannot be seen! D:
The other reason is that the width and eight of every image that represents the blows were not enough, so they had to make it in two pieces, probably, because some systems work better in power of 2 images, say 64x64, if you take a look to the second and fourth images, that are the continuations, they have the same width and height, and the fourth one Its like is not finished, but it doesn't matter, because, where is placed on the screen, it make's it look like it continues. And about the spikes, I'm not an artist, but I think it resembles where the end of the sword is pointing, notice that, spikes are when she draws the sword from the cover, and at the end of the blow, when she hit's, giving some impression of colition or friction. And the middle clean part is where the sword takes more speed.
> 1 votes

---
Tags: animation, sprites, art
---


# Question
Title: Can you trilinear sample a non volume texture?
Let's say that i have a regular 2d texture (not a volume texture). Is it possible to do trilinear texture sampling of that texture even though it isn't a volume texture in opengl or directx?

Specifically, if i had a 2x4 texture laid out like below where **A** through **H** are pixels:

**A B**
**C D**
**E F**
**G H**

What I'd like to get is a trilinear sample being the result of linearly interpolating the bilinear sampling of (**A**,**B**,**C**,**D**) and (**E**,**F**,**G**,**H**).

I know i could take two bilinear texture samples and lerp them to get what I want, but is there a hardware supported way to do this?

# Answer
> 0 votes
No, it is not possible, unless you read the involved pixels into a pixel shader, and then do the interpolation in the shader program manually.

---
Tags: opengl, directx, graphics, graphics-programming
---


# Question
Title: How can I build a game in Unity with minimum/no use of the visual editor?
I'd like to write a game completely in C#. In my search for an engine, I found Unity3D, but all the tutorials and documentation are speaking about a visual editor and the Unity IDE in which you click and point around to create scenes and scripts.

I don't want to do that. I prefer full code coverage over designers abstracting things away from me. I'd like to only write pure C# code from scratch or if required the Unity scripts as an addition. I couldn't find any explanation or documentation about doing so; how can I build a game using Unity and making minimum (or no) use of the visual editor?

# Answer
> 31 votes
I am a complete beginner in Unity, but this is how I do it at the moment, and it reduces the editor usage to minimum:

In editor, I only have three objects: An empty GameObject called "main", a camera, and a light. And this is only because so far I only work with a single camera and a single light, so it was faster this way. Later I will probably remove them, and only the "main" will remain.

In "Assets/MyScripts" I have a class "Main", which is added to the "main" GameObject as a behavior. Which means that when the program starts, the "Main" class in instantiated and its method is called. The "Main" class is like this:

```
using UnityEngine;

public class Main : MonoBehaviour
{

    void Start ()
    {
        // initialize the game
    }

    void Update ()
    {
        // update physics
    }

}

```

In the game I dynamically build the environment like this:

```
GameObject floor = GameObject.CreatePrimitive (PrimitiveType.Cube);
floor.renderer.material.color = RandomGreen ();

```

But this is because so far I am only making a prototype. Later I will want to replace the cubes with some nice things edited in Blender. Which will require making them in Blender, and importing them to Units as "prefabs". Then, I will similarly instantiate the "prefabs" from the C# code.

If you want to make an object react to events, such as collisions with other objects, you can instantiate the object and add them dynamically a behavior class, which is a C# class derived from MonoBehavior. For example, if you want to have a car, you make a car prefab, and write a "CarBehavior" class for its behavior in the game.

This way you can reduce the interaction with the editor to a minimum, although probably not completely to zero. Now it depends on whether this is an acceptable solution for you.

# Answer
> 9 votes
When working with Unity you have to do some work within Unity's editor; that's simply how Unity works.

However the *vast* majority of what you'd be doing as a programmer doesn't happen within Unity's editor; the script files are external text files written in an external IDE, and as a programmer you only use Unity's editor for linking which scripts to run and then hitting Play to actually run the game. That's not unlike linking in classes in the project settings, and then hitting Run within your IDE.

Most other game development tools that have a central visual editor are also saddled with limited and inflexible scripting support, but Unity doesn't suffer that disadvantage. Although everything created for Unity ultimately goes through the visual editor, this core interface involves a lot of linking projects to custom code that runs in Unity's game engine. Experienced programmers, don't dismiss this development environment, mistaking it for some click together game creator with limited programming capability!

(also, it sounds like the book I'm currently writing would be a great resource for you, since it's targeted at experienced programmers)

# Answer
> 7 votes
I believe what you are looking for is the Futile Framework for Unity.

Basically, you can then do all your programming using scripts without having to "drag and drop" stuff or mess with the visual editor much. All you need is a single GameObject in your Scene which will be the container for your entire game. You then do everything procedurally as you would with a non-visual editor.

Disclaimer: While Futile is very code centric, it is inevitable that you will have to mess with the Unity editor in some fashion. But this is very much reduced with Futile.

# Answer
> 2 votes
I would like to add to all the good answers here, especially @jhocking 's answer:

Almost everything I have found in Unity has a plain text counterpart in the projects folder tree. I have directly edited prefabs and other gameObjects without opening Unity, and those changes were successfully found by other devs upon commit.

While I didnt know as much about the Futile Framework until today, it looks to be a really awesome way to get at everything.

I currently use all the drag-and-drop stuff instead of going script-based, but that will have to change since my goal will have procedurally generated levels and bad guys.

My two cents says basically get the few objects you need in Unity, then rely on scripts in an external editor. You can do nearly everything in plain text.

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


title: Retro Racing Renderer

text:
# Question
Title: Retro Racing Renderer
While I have a lot of experience with coding SW&HW 3D rasterizers across multiple platforms and eras, I never got to coding a 2D renderer for a non-polygonal racing game with multiple rolling hills (with correct perspective and occlusion). Say, something like a Lotus from 1990.

Of course, the roadside props and cars are all sprites, but I'm curious as to how the road, especially with rolling hills is done. My uneducated guess is that it's composed from separate horizontal lines (that have the terrain and road texels), which are simply stacked above each other with zero horizontal offset (for the straight road) and once you approach the curve, the horizontal offset for the given scanline is taken from a look-up table (for a given curve). Given enough RAM we could have a lot of different curves. Or perhaps if the curve equation is simple (not some Bezier stuff), then it could be even calculated at run-time (integer / fixed-point, of course). This should supply the illusion of curved road.

Now, for the single rolling hills, we would probably merely introduce a vertical offset to our road scanlines, so this could give an illusion of going up/down the rolling hills, as all scanlines would move up/down on the screen.

What I don't quite understand is how the multiple rolling hills with a perspective are done, especially if they are overlapping correctly. This is probably hard to visualize, but imagine there is a second hill in the distance, and you are climbing up the hill in front of it. While climbing up, you can see it in the distance, and when you get to the top of the hill, the valley between two hills appears. With polygonal gfx, this is super easy and you don't even think about it - the valley is just back-face culled polygons, so it's obvious they did not get rendered when climbing up the first hill. Meaning - the valley is transformed, clipped and discarded thanks to back-face culling.

But how would you do that with the 2D horizontal scanlines ? Perhaps using SW Z-Buffering on each scanline ? One idea could be that you separate the scanlines for the hill up and the hill down - e.g. you only start rendering those scanlines when you get to the top of the hill- but I doubt it would work flawlessly.

I suspect, as with everything in game coding, once you start prototyping it, a solution would simply be reached by multiple iterations/prototypes. I'm in the middle of some other project now, so I don't want to distract myself with another project, hence this question.

EDIT: StackOverflow supplied few links, right before I submitted the question, and one of the threads contained this link: http://www.extentofthejam.com/pseudo/ It explains in a great amount of detail various techniques for this type of rendering. I am in the middle of it right now. From what I can see, the early games did actually use the FOV projection! That explains why their 'feeling' of perspective was so exact, as you can't really hack it properly (especially for a 3D-trained eye).

# Answer
> 2 votes
The idea for the rolling hills is as follows: you use the painters algorithm to draw your road; so basically it means you start at some distance in front of the the car and work your way back to the car. I'll try to explain the process with some ACII art :-)

Consider this as a hill profile (seen from the side):

```
        __
___    /
   \__/
0123456789

```

The car is at 0. You start by section 9 and work backwards to 0.

For each segment you draw keep track of the vertical position of the segment on the screen. Section 9 is a flat section in the distance and will be drawn as a triangle let's say screenY 100-102. We keep track of the 102, it is the screenY coordinate of the nearest part of the road section you're drawing.

```
9   /\  screeny=102

```

Section 8 is flat, so your perspective calculation that section would end up at scanlines 102-104.

```
9   /\
8  /  \ screeny=104

```

Now come the tricky bits. The road goes down in sections 7 and 6. For both sections perspective calculations will make the scanlines go down further, it's just a bit steeper. So after drawing section 6: we're at, let's say, scanline 110. Next bit comes up.

```
9     /\
8    /__\
7   |    |
6   |____|
5  /      \
4 /        \ screeny=200

```

It becomes iteresting at section 3: this is where the hill goes back up (remember we're working back to front; from the car's perspective this section goes DOWN and therefore is hidden from view). For this section the calculated vertical position is actually ABOVE the scanline we're at. Thus it is culled and not drawn. We still however keep track of the scanline that results from the perspective calculation.

```
9     /\
8    /__\
7   |    |
6   |____|
5  /      \
4 /        \ 3 is not drawn but screeny=180

```

Now at section 2 the road is flat again and should appear. The perspective calculation should come up with a screenY below the previous one, thus the section is drawn on the screen.

```
9       /\
8      /__\
7     |    |
6     |____|
5  __/______\__   4 is drawn over by section 2,
2 /            \   due to painters algorithm
1/              \

```

Keep in mind that the roadside objects are also drawn using the painter's algorithm, the screenY you kept recording should help you clip the sprites at the right point for objects that are just behind the apex of an hill.

Hope this helps :-)

Check the javascript code by Jake Gordon, he explains a lot of the math that is going on here: http://codeincomplete.com/posts/2012/6/22/javascript\_racer/

# Answer
> 0 votes
To close out this question, like I mentioned in my edit, the Stackoverflow supplied the link with detailed description of the algorithm and a link to site with javascript examples, that fully answered my query.

---
Tags: 2d, racing, rasterization
---


# Question
Title: Card/Tile Game, loops dont update element0 of playerHand properly
**The Problem**

I am dealing from another class and into a player's Tray(A class with a List of Tiles and an array of bools to show that a slot in the tray is full). When dealing into the player's tray, I update the list and bool array after each tile. The first element of the bool array never gets filled, and I think its a logic error with my loops. *I am looking for suggestions about how to make sure that the first element of the bool array gets populated after updating each tile.*

The image shows what happens to the bool array in the inspector when one tile is dealt. The second part of the image is when the second card is dealt.

**BackGround**

In Unity 2D: I have a *Tile* class, *PlayerTileTray* class, *PlayerTileTrayManager* class and a *TileManager* class.

*TileManager* creates a List and adds elements to the list, setting the *Tile* variables. *TileManager* has a Deal Method with an OnTileSent(Tile sentTile) event that sends the top tile as a parameter.

*PlayerTileTrayManager* listens to the event using the OnTileSent Method. *PlayerTileTrayManager*'s job is to take that tileSent and place it in one of several \_trays in a PlaceTileInFirstEmptySlotOfTrays method. I am currently using an array of trays called \_tray\[\].

If an next element of the \_tray array is null, I Instantiate a gameObject Prefab representing the tray and add a *PlayerTileTray* instance to the prefab as \_tray\[trayIndex\].

The *PlayerTileTray* has an array of bools,slotFull\[\], to show whether a slot is full. In the *PlayerTileTrayManager*: I loop through \_tray and then slots of that tray to call the UpdateTrayWithTile method of *PlayerTileTray* UpdateTrayWiltTile adds the tile to a List in \_tray, then trys to update the \_tray bool variables emptyTray, fullTray and slotFull\[\].

**The main problem I am having** I am currently using a nested for loop. I have tried do while loops. The first bool element slotFull\[0\] never gets set to true despite how I try to make it true. When the first tile is dealt, slotFull\[0\] stays false. When the second tile is dealt both slotFull\[0\] and slotFull are true;

The results of everything else is achieved or will be if I can fix the first element of slotFull updating properly..

**TileManager.cs**

```
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;

public class TileManager :MonoBehaviour
{
    //For testing
    private int _topTile = 0;
    private List<Tile> _fullStackTiles = new List<Tile>();
    private static int _stockTileCount = 16;
    private static int _numberOfTileSets = 4;

    public int tilesToDeal = 1;
    public static Dictionary <string,Tile> stockTiles = new Dictionary <string,Tile>();
    public static List<Tile> shuffledTiles = new List<Tile>() ;
    public static int maxTiles = _numberOfTileSets * _stockTileCount;

    / **Singleton Stuff and Delegate,Event and Publisher Method removed for Brevity */
    void Awake(){
        _instance = this;  //  <--Singleton
    }
    void Start(){
        AssignTiles ();
        createFullStackWithSetOf(_numberOfTileSets);
        shuffledTiles = _fullStackTiles;

        //Shuffle is located in MyExtensions
        shuffledTiles.Shuffle();
    }
    void AssignTiles(){/* Method Contents removed for Brevity */ }

    void createFullStackWithSetOf(int numSets){
        //Create a stack of tiles with _numOfTileSets of stockTiles
        foreach(KeyValuePair<string,Tile> t in stockTiles){
            for(int i = 0; i < numSets; i++)
                _fullStackTiles.Add(t.Value);
        }
    }
    public void Deal(int numIilesToDeal){
        for(int i = 0; i < numIilesToDeal; i++){
            //TileSend method is near the beginning of this script in the Delegate #region
            //TileSend (shuffledTiles[_topTile]);
            OnTileSent(shuffledTiles[_topTile]);
            shuffledTiles.RemoveAt(_topTile);

            //create node for instantiated tile
            //insert tile into Node
        }
    }
}

```

**PlayerTileTrayManager**

```
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class PlayerTileTrayManager : MonoBehaviour {

    private static int _maxNumberOfTrays = TileManager.maxTiles / PlayerTileTray.trayMax;
    private List<Tile> _playerTiles = new List<Tile>();
    private GameObject _tilePrefab;
    private PlayerTileTray[] _tray = new PlayerTileTray[8];

    public Tile tileFromDraw;
    public GameObject TrayPrefab;
    List <GameObject> _trayObject  = new List<GameObject>();

    void OnEnable(){
        TileManager.Instance.TileSent += OnTileSent;
    }
    void OnDisable(){
        TileManager.Instance.TileSent -= OnTileSent;
    }

    void OnTileSent(object source, Tile tileSent){
        _playerTiles.Add (tileSent);
        PlaceTileInFirstEmptySlotOfTrays (tileSent);

        GameObject go = PrefabMap.Instance.GetValueByKey(tileSent.tileName);
        Instantiate (go,Vector3.zero,Quaternion.identity);

        //move _tilePrefab to childLocation
    }
    void PlaceTileInFirstEmptySlotOfTrays(Tile placeTile)
    {
        for(int trayIndex = 0;trayIndex < _maxNumberOfTrays;trayIndex++){
            //for(int slotIndex = 0; slotIndex < PlayerTileTray.trayMax; slotIndex ++)
            int slotIndex = 0;
            do{
                if(_tray[trayIndex] == null)
                {
                    _trayObject.Add (Instantiate (TrayPrefab, Vector3.zero, Quaternion.identity) as GameObject);
                    _tray[trayIndex] = _trayObject[trayIndex].GetComponent<PlayerTileTray>();
                }
                if (!_tray[trayIndex].fullTray)
                {
                    if(!_tray[trayIndex].fullSlot[slotIndex])
                    {
                        _tray[trayIndex].UpdateTrayWithTile(placeTile);
                        Debug.Log (placeTile.tileName + "was placed in the " + trayIndex + " trayIndex iteration and in the " +
                                   slotIndex + " slotIndex iteration.");
                        return;
                    }
                }
                slotIndex++;
            }while(slotIndex < PlayerTileTray.trayMax);
        }
    }
    public void showHand(){/* Not relevant to the Question*/    }
    //CycleTrays
}

```

**PlayerTileTray.cs**

```
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class PlayerTileTray :MonoBehaviour{

    public static int trayMax = 8;

    public bool[] fullSlot;
    public bool fullTray;
    public bool emptyTray;

    public Tile tileFromTrayManager;
    public List<Tile> tilesInTray = new List<Tile>();

    public PlayerTileTray(){
        fullSlot = new bool[trayMax];
        fullTray = false;
        emptyTray = true;
    }
    void Start(){
        for(int i = 0; i < trayMax; i++)
            fullSlot[i] = false;
    }
    public void UpdateTrayWithTile(Tile tileToTray){
        tilesInTray.Add (tileToTray);
        for (int i = 0; i < tilesInTray.Count; i++)
            fullSlot[i] = true;
        if(tilesInTray.Count >= 0)
            emptyTray = false;
        if(tilesInTray.Count >= 8)
            fullTray = true;
    }
}

```

# Answer
In the PlayerTileTray, I initaized my Boolean array in Start(). I changed this to Awake and code worked as expected.
> 1 votes

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


# Question
Title: How can I approximate an "opening fan"-transformation?
Is there a way to—with matrices—transform something as if opening the image on a Japanese folding fan?

Image from Wikimedia Commons.

I'm at a loss of what to call it, so pointers towards avenues of research would be greatly appreciated. If it isn't possible with matrices, alternate methods would also be good.

If that is not possible either, a way to approximate the perspective tool in most graphics manipulation programs would be nice also.

# Answer
> 1 votes
Use trig to sample it into a triangle strip.

As for texturing: a rectangular image UV-mapped to the triangle strip might work, with projective interpolation.

---
Tags: mathematics, graphics, matrix, graphics-programming, scale
---


# Question
Title: TypeError: this.scale.setScreenSize is not a function
Game work with the old version 2.0.6. But they get this error after switching to 2.4.2

```
TypeError: this.scale.setScreenSize is not a function

```

any Idea how to solve this ?

# Answer
> 6 votes
I found this in the changelog:

```
Deprecated [...] ScaleManager.setScreenSize (see updateLayout)

```

Try replacing your call to setScreenSize with updateLayout -- that worked for me.

---
Tags: phaser
---


# Question
Title: Blur effect on background to make the forground more clear unity
I'm making a game in unity and I'm trying to add a background blur effect to my game to make things a bit more clear.

Here is an example of what I am looking to do:

I'm trying to get the background blurriness and cloudy effect, but I have no idea how to go about getting a similar effect. It looks like a blur + cloudiness of some sort, but I've tried blurring my background objects and it just looks terrible.

Here is what I currently have:

I'm using Unity, it's all 2D sprites so I don't think I can use shaders, which is the only solution I could find people talking about, and have no idea how to proceed. Any help would be appreciated, Thanks.

Edit: Even knowing the terms I could use to search for a solution would help as I'm not quite sure what it is called.

# Answer
Shaders are what you need to use to make this happen, if you don't want to use pre-blurred art.

Basically what you'd do is render each layer to it's own texture every frame, then blur each layer the amount that it should be blurred, then combine all the layers into a single image, which is the output image you see on the screen.

For blurring, you are probably going to be best off using a 2 pass gaussian blur, where the first pass is X axis, and the second pass is Y axis. Doing it in two one dimensional passes is way more efficient than doing a single two dimensional pass.

Here's a good looking tutorial on writing shaders in unity: https://cgcookie.com/unity/cgc-courses/noob-to-pro-shader-writing-for-unity-4-beginner/

Hope that helps!
> 2 votes

# Answer
A convincing blur is really expensive on mobile. However if this is on desktop, and you want a dynamic blur, here's something I've written:

Gaussian Blur

Here is what it looks like:
> 1 votes

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


# Question
Title: Cube bounces back with rigidbody and script in Unity
I have Unity 4.6.1 and I added a cube with a moving script and a rigidbody. The script is:

```
#pragma strict

var speed : float = 10.0;

function Update () {

    // Is the user pressing left or right (or "A" & "D") on the keyboard
    var horMovement = Input.GetAxis("Horizontal");
    // Is the user Pressing up or down (or "W" & "S") on te keyboard
    var forwardMovement = Input.GetAxis("Vertical");

    if (horMovement) {
        transform.Translate(transform.right * horMovement * Time.deltaTime * speed);
    }

    if (forwardMovement) {
        transform.Translate(transform.forward * forwardMovement * Time.deltaTime * speed);
    }
}

```

And the rigidbody freezes position Y and freezes rotation X, Y, and Z. How do I stop it from bouncing back?

# Answer
Use physics instead to move your object like rigidbody.AddForce(Vector3). Using physics will solve your problem with bouncing.
> 1 votes

---
Tags: unity, movement
---


# Question
Title: FPS using mouse to move rather than keys
Hi I am developing a First person game but would like to use the mouse to move on a click to move as opposed to the keys. I also need to disable Y movement and restrict the x movement to 180. What ever values I enter into the input manager, it seems to be ignoring them as I still have both x and y when I run the game.

I dabbled with the standard unity FPS but is seems very jagged on movement and from what I can see being a new user, their doesn't seem to be a way to restrict y movement. Can someone help with this or suggest a good tutorial on this type of movement. Thanks

# Answer
> 1 votes
You can use: *transform.Translate(Input.GetAxis("Mouse Y"), 0, Input.GetAxis("Mouse X"));*

Or if you want to use physics: *rigidbody.AddForce(Input.GetAxis("Mouse Y"), 0, Input.GetAxis("Mouse X"));*

# Answer
> 0 votes
Go to the code and find the input.Axis function and add two if statements. ~If greater than 180 =180. And the same for 0. I would recommend using global variables for the limits so you can change them in the future in the editor.

---
Tags: unity
---


# Question
Title: Circle Collision Resolution and Angular Momentum
I have a 2D engine working pretty well that involves rectangles and circles. I just reworked parts of the collision detection/response system for better handling of angular speed/momentum.

The collision response algorithm I'm using is described here: http://www.myphysicslab.com/collision.html (the complicated "j = ..." equations towards the bottom of the page under "Physics of Collision for Rigid Bodies in 2 Dimensions").

Everything's working great, but I'm wondering about circles. No matter how another another rectangle or circle hits a circle, it's impossible for the circle to gain angular speed through a collision, **since the collision normal vector is always perpendicular to surface of the circle**.

This makes sense to me mathematically, but it goes against my real-life intuition. For example, in the picture below, if I poke a ball on the side with a rectangle (tangentially, not towards the middle of the ball), I expect the ball to start spinning (counter-clockwise in this case).

Why isn't this happening for me? Do I need some kind of non-instantaneous collision (deformation maybe?) to experience this effect? If so, is there a way to "fake" it? (Realistically! I don't want to mess up the realistic linear/angular momentums and energies of my system!) Thanks in advance for the help!!

# Answer
> 3 votes
You need a tensor for a generic solution. but the "specialized" solution here is that you have a a spin only if you have friction in your contact. otherwise of course the contact forces will purely be directed to the center of the circle and never cause spin. if you have friction, your forces will start to deviate within the realms of the friction cone, which is then, not-anymore-center directed. This contact force will work against the inertia of your circle that applies at the center of mass. Both forces create a couple, which is a torque. this torque is determined is classical analytic mechanics using a cross product of the force vector and the lever vector.

From memory, the reduction of force in a point (to find a **net force** (or resultant) will give you a 2-components force, a force and a torque, directly. You "just" have to create a segment vector that links the center of mass to your contact point (subtract points `A-B=BA`) and then cross-product it with your contact force, you get the torque component. This is the "lever effect". You can see that the more orthogonal the force gets, the greater the torque, or the farther away the contact is, the greater the torque. The 1st component is just a copy of the linear force.

You can treat your contact as an impulse if it is supposed to happen in only one simulation frame. Also you can consider about 2 possibilities for the colliding stick:
\- infinitely heavy (because handled by some infinitely powerful virtual hand ?)
\- or free, like the circle, and then the amount of energy transmitted in the circle will have to be determined by "momentum" repartition `p=m*v` (momentum="quantity of movement").
link for this here: http://www.physlink.com/Education/AskExperts/ae462.cfm

> F = m * v/t

For you it means diving by your simulation dt because the contact is instantaneous, and this creates the impulse.

The rotation will not happen directly as a result of the torque you calculate, there is the equivalent in rotation to the linear inertia, which is called angular inertia.
linear inertia is given by the mass, simply. This is natural to understand why because that's what happen with movement forumlas (from Netwon's `f=ma`).
The mass is resisting the force applied to give birth to an acceleration.
In rotation, it is the same, the **moment of inertia**, is resisting the torque to create a spin.
One can find the moment of inertia by integrating the elements of surface over the shape (called second moment of mass), which for special shapes you can find pre-calculated on internet. for example for your circle you could say it's a cylinder and use `1/2 mr2`.

And the final touch is given by `torque = I * alpha` which is `f=ma` written in rotation form, so you know the torque because you calculated it using the cross product afore-mentioned, you know `I` because it is `1/2 mass radius squared` and so you know alpha: (`alpha = t/I`) which is the angular acceleration, so then you just have to integrate over time to get the angular speed and finally angle after a second integration. (using Euler, Verlet, or Runge kutta, whatever).

Edit: About the concern of contact point being infinitely small and not capable of having friction: this is unrelated to the cinematic study, we can perfectly sanely infer that friction exists without any more justification. If in need for justification then you can imagine sticking a needle on a glass panel, this doesn't slip perfectly, it slips but has some amount of friction.
Also if you accept imagining that molecules can intertwine even a micro contact will be enough to get forces laterally transmitted. This especially happens easily on cold materials. (cold = less movement, thus more opportunities to fall in holes. imagine a rotating fan, if you push on it you can't go through, but if it is off, you just have to stick your finger in between the wings)

ODE creates temporary linkage in case of contacts, in this case it would create a ball joint during the simulation dt.

nice sum up here of linear / rotational parallels:
http://hyperphysics.phy-astr.gsu.edu/hbase/mi.html

---
Tags: physics, collision-resolution
---


title: Drawing Farseer Fixtures

text:
# Question
Title: Drawing Farseer Fixtures
Is there any way how to draw a `Polygon` / `Fixture` from Farseer Physics with XNA?
As I deform these polygons at runtime I can't take any texture from my Content folder, the texture must be generated at runtime too.

# Answer
You can draw the polygons easily, if you attach the DebugView from farseer, in your physics simulation.

If this is not what you want, you will need to write your own renderer, which is not going to be a trivial task.

You could also extend the DebugView from the Farseer library, seeing as it is open source.
> 1 votes

---
Tags: xna, c#, rendering, farseer-physics-engine
---


# Question
Title: Drawing/adding shape objects with the mouse on html canvas
I've started with the canvas paint tutorial from link which worked fine with a few problems that can be fixed later. I've been checking a lot of posts on drawing shapes on the canvas but they all use draw functions in a gameloop or intervals but I do not want to use `draw();` in an interval or gameloop for now, I just need to update the content on userinput.

I am trying to create a drawing software that paints objects instead of just bitmaps. I've been debugging for a while now and can't find the problem: I have problems accessing the objects in the `pointsArr[];` array. I was only able to add rectangles to the screen by using `contextVar.strokeRect(50,50,50,50);` directly with the `mouseDownVar`so far.

Yes I know that the addFilledCircleFunc creats rectangles, for now I just want everything to work properly.

```
// to do:
// add gameloop and draw with gameloop?
// stroke line in resize  fix
// collission check + detection objects
// functions to draw detection objects
// implement resize?

// Varibale declration
var canvasVar = document.getElementById('canvasHtmlElement');
var contextVar = canvasVar.getContext('2d');
var pointRadiusVar = 10;
var mouseButtonHeld = false;
var pointsArrPosition = 0;

//Arrays
var pointsArr = [];

// Varibale declration end

//canvas setup
canvasVar.width = window.innerWidth;
canvasVar.height = window.innerHeight;

//canvas setup end

//resize fix
window.onresize = function(){
    var tempImageVar = contextVar.getImageData(0,0, canvasVar.width, canvasVar.height);
    canvasVar.width = window.innerWidth;
    canvasVar.height = window.innerHeight;
    contextVar.putImageData(tempImageVar, 0,0);
}
//resize fix end

contextVar.lineWidth = pointRadiusVar * 2; // Line Width

//functions

// Objects

 function pointObject () {
 this.x = 0;
 this.y = 0;
 this.w = 10; // default width and height?
 this.h = 10;
 this.fill = '#444444';
 this.stroke=stroke||"skyblue";
 this.strokewidth=strokewidth||2;
 }

function addFilledCircleFunc(x, y, w, h, fill){
var filledCircle = new pointObject;
    filledCircle.x = x;
    filledCircle.y = y;
    filledCircle.w = w;
    filledCircle.h = h;
    filledCircle.fill = fill;
    pointsArr.push(filledCircle);
}

//Objects end

// create circle on mouse clicked point while mousebutton is held
var addPointToCanvasVar = function (e) {
    if(mouseButtonHeld){
        addFilledCircleFunc(e.clientX, e.clientY, 10, 10, '#444444');

        /* // old drawing code
         contextVar.lineTo(e.clientX, e.clientY);
         contextVar.stroke();
         contextVar.beginPath();
         contextVar.arc(e.clientX, e.clientY, pointRadiusVar, 0, Math.PI * 2);
         contextVar.fill();
         contextVar.beginPath();
         contextVar.moveTo(e.clientX, e.clientY);
         */
    }
};

// MAKE SURE that lines work when drawn over the edge of the canvas
/*
 function clearPathIfMouseCursorLeavesCanvasFunc(e){
 //contextVar.beginPath(); // clears the path so buttonpresses dont connect the line
 //mouseButtonHeld = false;
 }
 */
// end

// mouse Up/Down Switch
var mouseDownVar = function(e){
    alert("mouseDown");
    //contextVar.strokeRect(e.clientX, e.clientY,50,50);
    draw();
    mouseButtonHeld = true;
    addPointToCanvasVar(e); // add point on first click, not just when mousebutton is held
}

var mouseUpVar = function(){
    //alert("mouseUp");
    mouseButtonHeld = false;
    contextVar.beginPath(); // clears the path so buttonpresses dont connect the line
}

// mouse Up/Down Switch end

//functions end

//listeners

canvasVar.addEventListener('mousemove', addPointToCanvasVar);
canvasVar.addEventListener('mouseup', mouseUpVar);
canvasVar.addEventListener('mousedown', mouseDownVar);
//canvasVar.addEventListener ('mouseout', clearPathIfMouseCursorLeavesCanvasFunc);

//listeners end

//draw function

function draw(){
    alert('drawing');
    contextVar.strokeRect(pointsArr[pointsArrPosition].x,pointsArr[pointsArrPosition].y,pointsArr[pointsArrPosition].w,pointsArr[pointsArrPosition].h);
    pointsArrPosition++;
}

//draw function end

```

# Answer
I wasen't able to get the array working so I bypassed it and got it working by adding `contextVar.strokeRect(filledCircle.x,filledCircle.y,filledCircle.w,filledCircle.h);` to the `addFilledCircleFunc`.

```
// to do:
// add gameloop and draw with gameloop?
// stroke line in resize  fix
// collission check + detection objects
// functions to draw detection objects
// implement resize?

// Varibale declration
var canvasVar = document.getElementById('canvasHtmlElement');
var contextVar = canvasVar.getContext('2d');
var pointRadiusVar = 10;
var mouseButtonHeld = false;
var pointsArrPosition = 0;

//Arrays
var pointsArr = [];

// Varibale declration end

//canvas setup
canvasVar.width = window.innerWidth;
canvasVar.height = window.innerHeight;

//canvas setup end

//resize fix
window.onresize = function(){
    var tempImageVar = contextVar.getImageData(0,0, canvasVar.width, canvasVar.height);
    canvasVar.width = window.innerWidth;
    canvasVar.height = window.innerHeight;
    contextVar.putImageData(tempImageVar, 0,0);
}
//resize fix end

contextVar.lineWidth = pointRadiusVar * 2; // Line Width

//functions

// Objects

 function pointObject () {

 this.x = 0;
 this.y = 0;
 this.w = 10; // default width and height?
 this.h = 10;
 this.fill = '#444444';
     /*
 this.stroke=stroke||"skyblue";
 this.strokewidth=strokewidth||2;
 */

 }

function addFilledCircleFunc(x, y, w, h, fill){
    //alert('works2');
var filledCircle = new pointObject;
    filledCircle.x = x;
    filledCircle.y = y;
    filledCircle.w = w;
    filledCircle.h = h;
    filledCircle.fill = fill;
    //pointsArr.push(filledCircle);

    contextVar.strokeRect(filledCircle.x,filledCircle.y,filledCircle.w,filledCircle.h);
    contextVar.fill(fill);
    //alert('works');
}

//Objects end

// create circle on mouse clicked point while mousebutton is held
var addPointToCanvasVar = function (e) {
    if(mouseButtonHeld){
        //alert('addpointfunc');
        addFilledCircleFunc(e.clientX, e.clientY, 10, 10, '#121212');

        /* // old drawing code
         contextVar.lineTo(e.clientX, e.clientY);
         contextVar.stroke();
         contextVar.beginPath();
         contextVar.arc(e.clientX, e.clientY, pointRadiusVar, 0, Math.PI * 2);
         contextVar.fill();
         contextVar.beginPath();
         contextVar.moveTo(e.clientX, e.clientY);
         */
    }
};

// MAKE SURE that lines work when drawn over the edge of the canvas
/*
 function clearPathIfMouseCursorLeavesCanvasFunc(e){
 //contextVar.beginPath(); // clears the path so buttonpresses dont connect the line
 //mouseButtonHeld = false;
 }
 */
// end

// mouse Up/Down Switch
var mouseDownVar = function(e){
    //alert("mouseDown");
    //contextVar.strokeRect(e.clientX, e.clientY,50,50);
    addPointToCanvasVar(e); // add point on first click, not just when mousebutton is held
    mouseButtonHeld = true;

}

var mouseUpVar = function(){
    //alert("mouseUp");
    mouseButtonHeld = false;
    contextVar.beginPath(); // clears the path so buttonpresses dont connect the line
}

// mouse Up/Down Switch end

//functions end

//listeners

canvasVar.addEventListener('mousemove', addPointToCanvasVar);
canvasVar.addEventListener('mouseup', mouseUpVar);
canvasVar.addEventListener('mousedown', mouseDownVar);
//canvasVar.addEventListener ('mouseout', clearPathIfMouseCursorLeavesCanvasFunc);

//listeners end

//draw function

function draw(x,y,w,h){
    alert('drawing');
    contextVar.strokeRect(x,y,w,h);
}

/*
function draw(){
    alert('drawing');
    contextVar.strokeRect(pointsArr[pointsArrPosition.x] = x,pointsArr[pointsArrPosition.y] = y,pointsArr[pointsArrPosition.w] = w,pointsArr[pointsArrPosition.h] = h);
    pointsArrPosition++;
} */

//draw function end

```
> 1 votes

---
Tags: javascript, html5, html-canvas
---


# Question
Title: Firing attack and take_damage events on entity attacking?
I have an `Entity` class with health, armor, and damage. I want my entities to raise some kind of `take_damage` and `attack` events whenever they attack or take damage. Here's my current implementation:

```
class Entity:

   """Base class for all entities."""

    def __init__(self, name, health, armor=0, damage=0):
        """Initializes a new entity."""
        self.name = name
        self.base_health = health
        self.base_armor = armor
        self.base_damage = damage
        self.events = event_dict('take_damage', 'die', 'attack', 'kill')

    def take_damage(self, damage, attacker=None):
        """Takes damage from a source."""
        final_damage = damage * (self.armor / (100 + self.armor))
        self.base_health -= final_damage
        self.events['take_damage'].fire(
            attacker=attacker,
            victim=self,
            damage=final_damage,
            raw_damage=damage
        )
        if self.base_health <= 0:
            self.events['die'].fire(
                attacker=attacker,
                victim=self
            )
        return final_damage

    def attack(self, victim):
        """Attacks a victim."""
        final_damage = victim.take_damage(self.damage)
        self.events['attack'].fire(
            attacker=self,
            victim=victim,
            damage=final_damage,
            raw_damage=self.damage
        )
        if not victim.alive:
            self.events['kill'].fire(
                attacker=self,
                victim=victim
            )

    @property
    def health(self):
        """Getter for entity's health."""
        return self.base_health

    @property
    def armor(self):
        """Getter for entity's armor."""
        return self.base_armor

    @property
    def alive(self):
        """Getter for entity's alive state."""
        return self.base_health <= 0

    @property
    def damage(self):
        """Getter for entity's damage."""
        return self.base_damage

```

First of all, I'm really new to game developing, so any improvements would be nice. The problem I'm having is that I'm "forced" to return a value from the `take_damage()` method, in order to include the actual damage in `attack()`'s event arguments. Would there be any fix for this?

# Answer
Here is a suggestion:

```
def compute_final_damage(self, raw_damage):
    """Apply armor to the damage"""
    return raw_damage * (self.armor / (100 + self.armor))

def take_damage(self, damage, attacker=None):
    """Takes damage from a source."""
    final_damage = self.compute_final_damage(damage)
    self.base_health -= final_damage
    self.events['take_damage'].fire(
        attacker=attacker,
        victim=self,
        damage=final_damage,
        raw_damage=damage
    )
    if self.base_health <= 0:
        self.events['die'].fire(
            attacker=attacker,
            victim=self
        )

def attack(self, victim):
    """Attacks a victim."""
    final_damage = victim.compute_final_damage(self.damage)
    victim.take_damage(self.damage)
    self.events['attack'].fire(
        attacker=self,
        victim=victim,
        damage=final_damage,
        raw_damage=self.damage
    )
    if not victim.alive:
        self.events['kill'].fire(
            attacker=self,
            victim=victim
        )

```

You delegate the computation of the `final_damage` to a third method, which will be called by both `take_damage` and `attack` methods. It's unfortunate you have to call the same method twice, I don't really see any other options with your current architecture.
> 1 votes

# Answer
> The events are there for items and spells; if an item wants to interfere with the attack (say, deal 10% extra damage), it simply listens to the entity's attack event with a function \[...\]

Now that it's clear what you use the event for, here's a different suggestion architecture-wise:

**Items listen for the `take_damage` event. If the item's owner is the damage dealer, enqueue the special effect via your function.**

That helps keeping events distinct: the `take_damage` event is pretty similar to the `attack` event *in its use.* It is meant to signify something else, though.

* Use `take_damage` to notify "the world" about all the details of being damaged.
* Use `attack` to notify "the world" that X attacks Y, maybe with details about the weapon, but without final damage info. Raw damage is okay if it cannot be obtained easily.

Use both events for example to log what is happening:

> * *X* attacks *Y* with Broadsword! (`attack` event)
> * *Y* takes 123 damage! (`take_damage` event)
> * *Y* is badly hurt. (imaginary `status_change` event, based on taking damage so that leftover HP is \<10%)

Subscribe to the attack event in a fighting coordinator object. Let it react to an attack by letting the receiver taking the actual damage.

This decouples the damage dealer from the victim further. You could also let the coordinator decide if an attack is an actual hit, or if the ground is muddy and the dealer should miss, or whatever circumstances *not themselves being part of the damage dealer* affect an attack.
> 0 votes

---
Tags: python, entity-system, rpg
---


# Question
Title: May I distribute a game engine that is based on textbook examples?
I have purchased several game programming books to start my journey as a game developer. One of them teaches its readers by building a game engine's parts in each chapter until finally you have a complete working game engine. It's bare-bones, but still a game engine.

What exactly am I allowed to do with this engine, as far as releasing an indie game of my own? Is it copyright infringement if I attempt to use the game engine from the book even with my little changes and adjustments?

# Answer
> 2 votes
Book contents usually fall under the copyright of the author. Software developed based on the source code from the book (no matter how much or little you change) is a derived work, meaning you need the permission of the copyright holder.

However, it is usually not in the interest of a textbook author to sue people for following their advice.

Some books have a section somewhere explaining the copyright terms of the code printed in the book. If your book has no such section, I would recommend you to contact the author and ask them to clarify the copyright situation.

---
Tags: copyright, licensing
---


title: Monogame fails to load Effect

text:
# Question
Title: Monogame fails to load Effect
I'm currently porting an old XNA game over to MonoGame and everything (including custom shaders) build fine.

However when i try to load the xnb file using `content.Load<Effect>("BaseDraw");` I receive the following error:

```
An unhandled exception of type 'SharpDX.SharpDXException' occurred in SharpDX.dll

Additional information: HRESULT: [0x80070057], Module: [General],
    ApiCode: [E_INVALIDARG/Invalid Arguments], Message: The parameter is incorrect.

```

I even tried building the shaders with 2MGFX.exe and loading it manually but that throws the same error.

I have no idea what to so any help would be appreciated!

# Answer
> 3 votes
Figured I had the shader versions too high (`vs_5_0`/`ps_5_0`) lowering them to their `4_0` variant fixed the error.

---
Tags: shaders, monogame, graphic-effects
---


# Question
Title: Will reseting a scene instead of reloading it improve performance?
I made a 2D infinite runner. My game was approved for iOS and now pending release. However, on Android, performance is a nightmare. So I'm tweaking to optimize performance. As it stands now, there is game scene and game over scene. On game over scene, there is "Play Again" button that reloads the game scene. Now, if instead of having separate scene, if i handle the play again in same scene, will it be better than reloading the scene? What i could do is, have initial speed, position etc stored in array for example and when play again is clicked, set all gameobjects to the initial values. Will the performance be better with this? since gameobjects are now not getting destroyed and reloaded?

# Answer
It depends what "performance" you are attempting to optimize. "Performance" is an umbrella term that could be referring to many things. Like, if your load times are too long, then sure *not* loading will eliminate that wait. But if you mean how fast the game is running during gameplay, then no this makes no difference.

Or rather, it certainly won't make the game run *faster*. It's possible for your game to run *slower* after making this change, because now you aren't cleaning up everything in the scene and filling up memory. Of course, then your *real* problem is that you have lots of extra objects filling up your memory, and the memory wipe from loading the scene was covering up this issue.
> 2 votes

# Answer
I believe it is better to reload the scene using SceneManager.LoadScene() as this will require less code than positioning everything all over again. However it might depend a little on your scene, things like checkpoints and high scores.
> 1 votes

---
Tags: unity
---


# Question
Title: Detecting possible moves in a swap-match game
I've been coming up with ideas for how I would go about programming a Bejeweled-like minigame. After some deep thought, I've managed to figure out how to detect matches (including special bonus cases like 4 in a row, 5 in a row, intersections...) without any real issue.

However, one major issue I'm struggling with is this: how do I detect *possible* moves, and influence the dispensing of new tiles in light of them?

Specifically, I need to be able to:

* Detect that there are no moves possible on the board

A legal move consists swapping two adjacent tiles in order to create a match of at least three in a row.

* Ensure that there are no moves on the starting board layout

This could be a simple case of "generate a board, check if there are any matches, try again until there aren't" but this seems messy.

* Ensure that there is at least one valid move on the starting board

Again, can be achieved by generating boards until true, but anything with more finesse than brute force would be nice.

* Optionally (based on game mode) ensure that tiles fall such that there is always at least one valid move on the board.

Once again, brute force simply says "pick some tiles to drop in, check there's a valid move, if there isn't then drop some different ones in until there is".

Ultimately almost all of these can be done through brute force, but I'm sure there must be a better way. At the core, however, I really need help with figuring out how to detect potential moves on the board...

# Answer
Even though I think your best bet is to brute force it, I have a suggestion for another way to get this done. Keep in mind that this is purely speculative, I have not tried it.

Considering that each turn looks like this:

1. Player swaps two gems, forming a match
2. The matched gems are removed from the board, revealing a gap
3. The gems above the gap fall to fill it, revealing another gap on the top
4. Gem appear from the top to fill the top gap
5. IF there are new matches on the board GOTO 2

I think that it is possible to work in reverse to create a board where specific matches are possible:

1. Generate a board where there are no current matches
2. Pick a match "signature" (eg 3-in-a-row)
3. Pick a random space for that match
4. Move all gems above that space upwards to create a gap for that match
5. Place gems from a single color into that gap
6. Swap one of the newly placed gems so that there is no current match
7. GOTO 2

By taking care to not accidentaly create more matches than the ones you insert and by adding variety with combos and different signatures, you can create a level for someone to play.

**Pros:**

* Level can be customized based on difficulty factors
* Levels are always solvable

**Cons:**

* You need to know in advance the number of steps/moves to generate
* There will always be only one possible move

In short, by brute forcing it, you create levels with a wide possibility space while by designing it from the finish to start, you create levels with a linear progression.
> 1 votes

---
Tags: game-mechanics
---


# Question
Title: How should data about past interactions be stored?
I have been developing a text-based rpg in C++, using sqlite as my database.

When it comes to interactions that change the world around the player in some permanent fashion I have been unable to find a satisfactory method of storing them.

**Example**

The player kills a character then if they return to the same area I do a check in my "game\_data" table for "character\_x\_is\_dead" and if the character is dead then the player sees the body on the floor, if they are alive then the player can talk to them.

Is there a better way to handle this type of thing without having to impose conditions on an area that are checked and then the correct output is picked from a list of possibilities? (I'm just thinking about how as the game gets bigger and the player does more things this table is just going to grow more and more with potentially a lot of the contents becoming no longer needed)

**Edit - clarification about "list of interactions"**

By this phrase I mean any interactions that may alter how the player is allowed to interact with an area, hopefully these examples might make it clearer:

1. The first time the player talks with the innkeeper at the starting town they get given some money - when they talk to the innkeeper the next time, the money adding event should not fire again.
2. After the player has gone through a dungeon, any chests they open should still be empty if they come back later.
3. If the player helps a character then the next time they talk to the character they give one of their positive responses instead of their standard ones.

# Answer
Probably the cleanest way of doing this is just to explicitly store your entities as classes:

```
class Entity
{
   Room location;
   bool isDead;
   ...
   etc.
}

```

And just store a flat list of all your entities in the world.

```
List<Entity> entities;

```

You can also store, for each room, a list of entities that are currently in the room:

```
class Room
{
   List<Entity> entities;
}

```

Then, your check simply becomes:

```
foreach(Entity entity in room.entities)
{
   if(entity.isDead)
   {
        // Do something
   }
}

```

In order to prevent entities from building up, you may want to delete them under certain conditions.
> 3 votes

# Answer
I assume that you're asking because file sizes would be too large to make copies of your SQLite file for each "new game", so I don't believe you have any alternative. Otherwise I'd say just copy that original game state and alter it directly.

You may consider the idea of firing a sort of OnLoad() event whenever a new area is visited. It could check the time of death on each enemy found in that area and "expire" them away from your data file before you finally display that area to the user.

It might be a bit tricky, but you could even have another thread combing for expirable changes in your gamestate whenever your main thread is not actively trying to access the file. You'd want to think of a clever of indexing "expirable" state changes however.
> 1 votes

# Answer
You have two initial options: to hard-code the conditions or to use scripts.

Hard-coding is quick and great for prototypes, but it allows 0 flexibility. I expect your game to out-grow this very quickly.

Using a script takes more time to get started because you need a script file parser first. Apart from proven scripting languages like LUA, you can devise your own simple instructions.

With scripting in place, I can think of two ways to store state of the game world:

1. introduce simple flags
2. put all interaction events into an event store and check for occurences of kinds of events in the script; the series of events is a log of what the player has done (with which you could play back all interactions in the game; not the movements, of course)

The event store approach will work well with a SQLite database, if one `.sqlite` file equals a save game.

Flags are simpler, though. Savegames need to be a list of flags only.

## Using state Flags

Flags work like this: you create a `flags` array of *N* integers. This array contains all game states.

Your script may trigger setting `flags[107] = 3` through something like `SETFLAG 107, 3` in a dialogue to signify that some NPC has revealed a detail. Conditional dialogues are possible checking the flags for a value in the scripts: `IF 107 > 2 ... ENDIF`

Chests on your map can be populated using map launch scripts: `IF 222 = 0` fill with items and close; `ELSE` make it empty.

Flags are very low-tech and easily work for most kinds of RPGs. They're not convenient to manage, because the numbers won't tell what they're about. You have to keep track of them in spreadsheets.

### Example

I got most of this flags-related stuff from Jeff Hangartner aka Tsugumo and FrozenEmu from old QuickBasic times.

The simple scripts I devised 15 years ago with their help look like this:

```
checkflag,5,ST,1,a
kollide,21,39,1
end
tag,a
kollide,21,39,0
end

```

Which in pseudo-code means:

```
if flag[5] < 1
  goto A
else
  add_collision_block(21, 39)
  exit
endif

A:
remove_collision_block(21, 39)
exit

```
> 1 votes

# Answer
tl;dr

You have rooms, you need "keep an eye on them" by saving them and their contents (NPCs / items) to your sqlite. Each room has entities that can be in different states, you need possibly a simple `Enum` to save those states, the one row per entity can "remember" that entities state for you.

Elaborate answer:

You are mixing two things together. One is the state of the world, places, NPC's and items. The other is the player's activity. Normally, you wouldn't be storing player activity, and instead storing the state of the game world and all entities (places / NPC's / items) inhabiting it.

The reason being, that some changes occur due to other things. For instance, time passes by and the forest becomes dark as the night draws near (unrelated to player actions).

Each room / place needs to be aware of its state and its inhabitants. It should also have some sort of template (with blanks) that gets filled by function calls to the NPCs and items in that room.

For instance:

### Some Room:

Template text:

You are in a `<insert room.description(room.current_state)>`. There is a `<insert entity.description(entity.current_state)>`, in the `<insert entity.description(positional_state)>`.

Obviously the template needs to be more elaborate than this (possibly). The idea is that you need to maintain a `Table` or during play a `Vector` of `Room`s where each `Room` knows:

1. Which room indices it is connected to.
2. How to describe itself in it's state.
3. What entities are inside.
4. It's own description's template needs "blanks" inthat get filled with useful information about the entities inside it.

If there are very few states an entity can be in (dead or alive, there or gone), then it is likely that you can define a simple Enum to contain the state of the entity. Then you create a `switch` that returns the correct string description for each state. If the states are more complex then you may need to use a more sophisticated funtion.
> 0 votes

# Answer
How about using Set Theory to model your data as relations (this is easy with any relational database, or any language/library support for sets and tuples):

Imagine a relation `killed_by(a, b)` where `a` and `b` are both members of the set of all living things. `character_x_is_dead` when there exists any solution to `killed_by(?, b)`. You could store this on disk or in memory as a set of tuples `(a, b)`. A set is simply a list with no duplicates; there are lots of ways to search sets quickly.

A chest has a relation `contains(a, b)` where `a` is a member of the set of all chests (or all things that can contain anything -- the player's inventory can contain things too!) and `b` is a member of the set of all items (or the ID that represents it). You similarly store this on disk or in memory as a list of tuples.
> 0 votes

---
Tags: c++, rpg, data
---


# Question
Title: Stop player following cameras cameras direction
Okay I'm not going to go to much into it but this is what I need my script to do. The way I have my controller set up is that the camera looks to the side of the player a little bit. I use this for aiming attacks, bullets and what not. The problem is that it follow the camera when it looks up causing my character to slightly jump ever time I aim and look up. So i want the player to move with the camera while ignoring its y axis. and i need my character to jump so i cant just make the players y movement = 0.

Here's the code I've been using:

`transform.position += Time.deltaTime * cameraMain.forward * Input.GetAxis("Vertical") * speedWilAim;`

and I am trying to avoid separating the mouse look script into x and y pivots but if there is no alternative I will do that.

# Answer
> 1 votes
Okay I went ahead and separated my mouse look function which I used to rotate my camera rig, into the X and Y axis and placed them on two different objects. The one with the x axis was used to dictate how what direction my character moves.

---
Tags: unity, c#, camera, movement
---


title: Lag compensation in rocket game context

text:
# Question
Title: Lag compensation in rocket game context
I have read a lot of papers recently to understand the lag compensation concept recently. They were all about the same context: shooter game where bullets move in infinite velocity.

The most important thing is checking what was in the crosshair when the client created the fire command. If another player was there at that time, then s/he's damaged. That is done by checking the world state at that time by finding a snapshot and executing commands until the fire command.

How about firing a rocket? That is slow (not to mention other differences: ignition time and area damage). That means, I cannot **only** check what was on the crosshair of the client at the command creation time.

If I go back and check the world state at that time (with same method above), it wouldn't be enough. I would still need to do the simulation for the next snapshots until the most recent one (server's present).

That would mean, if I have a time step of 15ms (tick rate = 66) and I want to discard a command if it is older than 1.5 seconds, I need to keep the most recent 100 (1500/15) snapshots of the world. And every time a delayed command comes, I have to re-simulate the world from that command's timestamp to present - including reprocessing the commands with timestamps after that one.

This sounds too much work on the CPU to me. Is this the same in the first scenario (infinite speed bullet)?

What about lag compensation for movement commands? Would that be different?

Or did I misunderstand something / many things?

# Answer
> 1 votes
You are finding the cross hair to set the origin and orientation of the rocket. Then let the server track the rocket from there and inform the clients if anything affects the trajectory from what the clients logic can accurately estimate. Then inform the clients if/when it explodes.

This might not mean that clients see it from *exactly* where it is, but ultimately the effect should be unnoticable. Especially if the launcher makes a cloud of smoke before the server tells the client, milliseconds later, where it has officially acknowledged the rocket to be.

In otherwords, don't retroact rockets. Spawn it and forget it. Just like you won't go back in time to undo a death that occurred 5ms before the victim touches a health pack.

---
Tags: networking, lag
---


title: My GUI stopped working?

text:
# Question
Title: My GUI stopped working?
Okay I bought this asset online so I would like not to show the whole script. The problem is this asset stopped working when I updated from unity 5.0 to 5.1.2. The script is for a controller GUI interface but it seems to be giving me an error :

> NullReferenceException: Object reference not set to an instance of an object UnityEngine.UI.Selectable.Select ()

on this line of code :

```
selectedOject.GetComponent<Button> ().Select ();

```

so there is a null reference and its no longer recognizing the child objects as buttons is what I'm assuming

if you want to have a better look at his set up he has a short video On youtube : HERE

I would like to continue to use this script and continue updating Unity.

# Answer
> 0 votes
Okay I was way off turns out the problem had nothing to do with the update at all. Apparently I deleted the event system that ran with this. So its working again

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


# Question
Title: QuadTree Checking Collision With Different Levels of Nodes
I am making a QuadTree for a 2D Platformer. Researched on it and I managed to make a pretty good one where each node stores its 4 SubNode and there's a MAX\_OBJECTS for each Node and MAX\_LEVELS which represents the amount of Levels my Tree has, with 0 being the root.

So, I get my object and I try to store it into the Deepest Node possible. If I can't, then I'll store it in the Parent Node instead.

Then when I check for Collision, I'll see which Nodes have Possible Collisions with my Object, get the Objects in those Nodes and add it to a List of my Collision Checks.

My problem is this Checking for Collision. I am quite confused. For example, I have an ObjectA at Level 1 Node and it will collide with objects within its node. I have another ObjectB at Level 0 (Root Node) and it overlaps ObjectA's node so there is a possible Collision.

This is where it gets tricky, just from the paragraph above, I can see that Objects in the Parent Node have a chance to to collide with the Objects in the SubNode. So when I check for the Possible Collisions, do I check the Parent Nodes + SubNodes of my Object's Node...I'm not really sure as to how you choose which node to check.

There will be Nodes of Different Levels won't there? An Object of Level 1 can have Collision Checks with Level 0, Level 2, Level 5...etc(or is this wrong). It's hard to grasp what the criteria is of checking a specific node...To put it simply, a Tree has so many different Levels...

For all I know, there might be an ObjectA(x,y) at Level 0 and ObjectB(x,y) at Level5. Completely same coordinates, but different node levels. If I were to check Collisions for ObjectC(x,y) at Level 0, I'd put ObjectA in the List cause same Node, but what about ObjectB whose in a different Level, but same coords.

So just from the above theory/explanation or whatever you may call it. Can I conclude that the Nodes I check for Collisions should include Nodes from Root til the Node My Object is in + the SubNodes of Node my Object is in.

You might ask why not just store it in the same Level, well I heard from others that it's better if I store those overlapping ones at the parent node and it'd be good if I limit the amount of objects per node. So if the level is full, I need to send it up.

I'm sorry if this might be an easy question, it's just that I've pondered on this for 6 days now but I still can't figure it out. Please help! This is my last hope!

# Answer
> 1 votes
The answer is yes, of course.

You test object b against all L1 nodes in the root because that's where it is. If a node is hit, add it's objects to the short phase (object to object tests) list. Then recursively repeat the process against those child nodes which were hit. Do this until you determined to hit or miss all leaf nodes.

---
Tags: collision-detection, collision-resolution, quadtree, tree
---


# Question
Title: What framework do you reference for external dll's to work with Unity/Mono?
So I want to compile an extensions dll for a unity game because I feel I'll end up reusing these extensions in other games/projects too - and I want to learn about external dependencies with Unity. :)

Anyway. I've found some posts that say to reference .NET 2.0, however, when selecting a framework in project settings, I get a list of Unity frameworks that I think were added to VS by either UnityVS(VSUnity?) or Unity 5.

I'm unsure which to select for an external DLL. :/

**edit:** I also thought the current Unity (v5) supported Mono up to the equivalent of .NET 3.5?

A related question. Whichever framework I end up selecting, will I be able to reference "UnityEngine" in said project?

# Answer
> 1 votes
If your DLL is free-standing. IE. does not need to reference Unity, then you should be fine with either framework as long as it is supported on your target platforms. Otherwise you will need to use one of the Unity frameworks.

Unity does not support the NET 4.0+ frameworks though, so you are limited to 3.5 or lower.

---
Tags: unity, visual-studio
---


title: How to measure packet latency?

text:
# Question
Title: How to measure packet latency?
In the context of lag compensation, one needs to know when the command is instantiated on the client (this can be named as "command execution time" as well). AFAIK, there can be 2 methods for this:

1. Client sends a timestamp with the command.
2. Client doesn't send any timestamps, but server does a smart thing to calculate the command's instantiation time.

About #1:

* Is this safe in terms of cheating?

About #2:

According to Valve's paper, command execution time is as following:

> Command Execution Time = Current Server Time - Packet Latency - Client View Interpolation

This means, server must know the packet latency.

Another paper from Valve confirms this and says:

> Before executing a player's current user command, the server:
>
> 1. Computes a fairly accurate latency for the player
> 2. ...

* How can the server compute "fairly accurate latency for the player"?

Most naive and easiest approach would be sending pings regularly (less frequent than game commands and updates though) to find out an average of the latency and use it. Busy network traffic, latency fluctuation and naiveness of this method makes me feel there must be a more elegant way.

EDIT: Would UDP vs TCP change anything in this context?

# Answer
> 1 votes
Your intuition about #1 is correct: don't trust client timestamps. Even without cheating, timestamps can be wildly wrong.

Best approach is to ping, and divide the ping time by two. The lag may be asymmetric, but there's no way to verify that from the server. If you already have a persistent connection (TCP), that channel is fine. For just a ping, a no-setup UDP is probably better.

A client can "cheat" making a ping time appear longer than the actual latency, if server=initiated. (If client-initiated, it could lie about the result to the server.) So be careful about revealing "the future" to a client, while trying to compensate, if that can affect the game.

Yes, latency will vary by "network weather", and you can smooth over time and perhaps discard outliers.

---
Tags: networking, lag, latency
---


title: Keeping Android device awake

text:
# Question
Title: Keeping Android device awake
I currently program a game in which the user don't need to interact with the screen. Is there any way to keep the screen awake?

# Answer
One option is to use a wake lock. Example from the docs:

```
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
wl.acquire();

// screen and CPU will stay awake during this section

wl.release();

```

I've got this answer from this stack overflow post. For detailed information go there.
> 3 votes

---
Tags: android, libgdx, gui, touch, user-experience
---


title: Porting a SFML game to the browser?

text:
# Question
Title: Porting a SFML game to the browser?
I've been messing around with SFML, it's my first experience with C++ and I'm enjoying it. But I'm wondering how to publish my game onto anything other than a native platform. Noting that this is my first time dealing with porting and C++, could anyone explain this to me as if I'm 5?

Thanks in advance.

# Answer
Here is a list of all known SFML bindings. I work now for a few years with SFML but I've never heard about something like a web binding for browsers. If you are new to SFML and c++ you can probably look a bit arround and search for the best language/graphic libary which fit perfectly in your needs.
> 1 votes

---
Tags: c++, sfml, browser-based-games, porting, browser
---


title: How to add tiles randomly?

text:
# Question
Title: How to add tiles randomly?
I made a set of 10 different "ocean" tiles, all interchangeable with one another, and I'd like to randomly attach these 10 different tiles together in different combinations over a large rectangular area -- what would be the best way to do so? I've thought of just adding each sprite into a script and then calling a for/foreach loop to add it into my world but that seems extremely expensive since I'd be adding over 1000 sprites. I don't want to reduce the number of sprites I have to add, I'm just seeing if there's a typical way people do this sort of thing.

# Answer
> 1 votes
Another common technique is to pre-render your tiles (at runtime) into a large texture, or a set of large textures. This way, you can draw large swaths of the screen with a single draw call, at the cost of increased texture memory usage.

# Answer
> 0 votes
My answer is just based on imagination, no experience here.

this is for the case where you don't have to render all the ocean in one unique time (or maybe it would, its up to you)

Maybe you might want to make "false random generated" area. Let's say you want to display 20 by 20 tiles each time you render. let's say you have 1000 tiles total.

You could make a 20 by 20 generated content (matrix or whatever you implement) that repeat itself over the ocean.

Just make sure the repeatition is not obvious, and I think there won't be troubles.

# Answer
> 0 votes
A really great technique for tiled graphics that doesn't look tiled is called Wang tiling.

Basically, you design your tiles to have edge types and make it so if two tiles have the same edge type, they will look seamless if you put them next to each other, regardless of what else is going on in the tile

It looks great and also lends itself well to random generation / random placement.

To fill in a grid, you put down one tile in the upper left, then randomly select the neighbors from the tiles that have compatible edges. Rinse and repeat for those neighbors and on, until the grid is full. You can also do this procedurally so you don't actually need to store a map of what tiles go where - you define it mathematically!

Check this out for more info: http://blog.demofox.org/2014/08/13/wang-tiling/

Note that there's a link on that page to a Shadertoy pixel shader implementation that uses this to efficiently tile an infinite world.

# Answer
> 0 votes
Yet another way to do tiles graphics, but to hide the fact that its tiled is to use texture multisampling.

This is traditionally more useful for terrain, but might work for water as well.

The basic idea is that every pixel is some blend between multiple textures, and that the contribution from each texture varies based on some rule. Common rules include height of the vertex (to blend between rock, grass and snow for instance) but it could also be based on random numbers.

The reason this works well is because the images overlap and change per pixel not per tile, so makes tiling patterns much harder to detect.

Here's a link with more info: http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series4/Multitexturing.php

# Answer
> 0 votes
You could generate a random number(eg.integer) and then use switch to check cases for how many numbers you want, to randomize numbers use Random.Range(float max, float min).

# Answer
> 0 votes
This is a little late, but...

This is an example from c++, written by me, but you could probably take it and write it out in unity.

You could take a random number using the rand() or any other random function. Then take that number, and as you place down each tile upon the map, use that number to determine what type of ocean tile it is going to be.

```
for(placingOceanTilesDownX) {
    for(placingOceanTilesDownY) {
        int randOceanTile = rand() % 4; // 0 - 3 different types

        if(randOceanTile == 0)
            oceanTileMap[x][y] = 0;

        if(randOceanTile == 1)
            oceanTileMap[x][y] = 1;

        if(randOceanTile == 2)
            oceanTileMap[x][y] = 2;

        if(randOceanTile == 3)
            oceanTileMap[x][y] = 3;

        ...
        ...
    }
}

```

Or something like it.

Hope this helps.

---
Tags: unity
---


title: Vibration on Android

text:
# Question
Title: Vibration on Android
How to change duration of vibration on Android(Unity3D)?

For example:

```
public void Jump()
{
    if (grounded)
    {
        rb2d.velocity = new Vector2(rb2d.velocity.x, jumpPower);
        Handheld.Vibrate();
    }
}

```

This code makes a vibration in one second long.

# Answer
> 2 votes
You can download a plugin in asset store to regulate vibration. here's a link: https://www.assetstore.unity3d.com/en/#!/content/10982 or you can check this one it's FREE: https://www.assetstore.unity3d.com/en/#!/content/16648

---
Tags: unity, android
---


title: ETC1 Performance Problem Android

text:
# Question
Title: ETC1 Performance Problem Android
I wanted to support etc1, because it shoul improve the performance and loading times, but somehow its worse than using normal png files.

I'm using Mali compression tool with seperate RBG pkm texture and Alpha pkm texture. I'm using a GLSL shader to deal with the alpha problem ofc ETC1. With the shader the performance is really bad. but even without the shader, just working with the RGB pkm file (where transparency is black) the performance is equal to png. does anyone know what the problem might be?

# Answer
I could say that using ETC1 or any other compression will surely improve your memory usage but will NOT improve your CPU/GPU usage. See uncompressed file formats can be used without any additional processing whereas compressed ones must be decompressed (processing impact) first. If you would reuse (and not load up every time) those textures would act just as any others (inside memory they are all raw in RGBA form).

FPS could be improved by reducing work on your GPU (like reducing rendered polygon count, using less/more simple shaders, using less draw calls (most important)). But changing the way your textures are stored will have impact only on: build size (storage), GPU/CPU load on decompression. I may be wrong in some cases, but compression is used mainly for reducing memory footprint and has nothing (very little) to do with your fps.

And remember kids: Early optimization is root to all evil!

Edit 1: Also bear in mind that using any kind of compression method does not come free. The space saved is not magic! You will lose quality. More space you save - more distorted images you will have. It is a general rule to not use any kind of compression for UI elements if they must be pixel-perfect or contain text.
> 2 votes

# Answer
The answer to your question rather depends on what the bottleneck is in your renderer.

If your system is *bandwidth limited* because of, say, many texture reads, then texture compression should help but, as you point out, ETC1 is opaque-only and so to emulate transparency, you need to set up a second texture with R=G=B\*=A\* and then copy one of the channels back to A in a shader.

If, OTOH, your system is *shader limited*, which may be the case here, the extra instructions will possibly make things worse.

You probably already know this but no rendering hardware (that I know of) reads PNG files, and these so are typically converted to 32bpp (or 16bpp) RGBA.

Other possible options would be to

1. identify if the hardware supports a different compressed texture format that includes alpha, eg. DXTC/S3TC or PVRTC or
2. identify all the textures (or portions of textures if you have atlases) where alpha==255 and explicitly handle them as opaque. This will give additional rendering speed benefits anyway.
> 0 votes

---
Tags: android
---