title: RPG Factions - Friendly/Hostile check

text:
# Question
Title: RPG Factions - Friendly/Hostile check
I'm having some trouble checking if one faction is hostile to another faction in my RPG. I'm using enums for my factions and relations but I feel like there's a better way to approach this.
Currently this is my code for the factions (copy+paste ruined format...)

```
public enum Faction {
/*
 * Position 1 = Humans
 * Position 2 = Elves
 * Position 3 = Dwarves
 * Position 4 = Orcs
 * Position 5 = Undead
 * Position 6 = Trolls
 * ....
 */

Human(Relations.Friendly/*Humans*/, Relations.Neutral/*Elves*/, Relations.Neutral/*Dwarves*/, Relations.Neutral/*Orcs*/, Relations.Hostile/*Undead*/, Relations.Hostile/*Trolls*/),
Elf(Relations.Neutral, Relations.Friendly, Relations.Neutral, Relations.Neutral, Relations.Hostile, Relations.Hostile),
Dwarf(Relations.Neutral, Relations.Neutral, Relations.Friendly, Relations.Neutral, Relations.Hostile, Relations.Hostile),
Orc(Relations.Neutral, Relations.Neutral, Relations.Neutral, Relations.Friendly, Relations.Hostile, Relations.Friendly),
Undead(Relations.Hostile, Relations.Hostile, Relations.Hostile, Relations.Hostile, Relations.Friendly, Relations.Hostile),
Troll(Relations.Hostile, Relations.Hostile, Relations.Hostile,Relations.Friendly, Relations.Hostile, Relations.Friendly);

    Faction(Relations... relation) {

    }

}

enum Relations {
    Hostile(),
    Neutral(),
    Friendly();
}

class FactionHandler {
    public boolean checkIfHostile(Faction faction1, Faction faction2) {
        //How do I check?
    }
}

```

The lazy way to do this would be to do lots of if/else statements but I want a more clean way to check.

Basically I want it to check faction1's relation with faction2, and return true if they are enemies, and false if they are friends. Feel free to entirely scrap my code if there's a better solution to this problem as this code is mainly just me experimenting.

# Answer
Build a 2D array of enum Relations, where row and column are the Factions.

You can then check using a simple array lookup:

```
public boolean checkIfHostile(Faction faction1, Faction faction2) {
    return relations[faction1.ordinal()][faction2.ordinal()] == Relations.Hostile;
}

```

Fill it in making sure `[x][y] == [y][x]` and that the diagonal `[i][i]` is Friendly or Neutral.

For example:

```
Relations[][] relations = new Relations[][]{
  { Relations.Friendly/*Humans*/, Relations.Neutral/*Elves*/, Relations.Neutral/*Dwarves*/, Relations.Neutral/*Orcs*/, Relations.Hostile/*Undead*/, Relations.Hostile/*Trolls*/},
  { Relations.Neutral,  Relations.Friendly,  ...},
  ...,
};

```

(I didn't fill in the whole table for readability, just keep going where the ... are)
> 5 votes

# Answer
While your solution works if you extends the `Faction` to hold the `Relations` it has the problem of each relation being specified twice. First you specify that the relation from `Humans` to `Elfs` is neutral, and then you also specify that the relation from `Elfs` to `Humans` is also neutral, this leads room for a problem where the relations are different depending on the point of view (unless that's what you're going for, it would mean some interesting game mechanics).

One way to fix this in the way you've implemented this is check both relations and return the "*worst*" one;

```
public enum Faction {
    /*
     * Position 1 = Humans
     * Position 2 = Elves
     * Position 3 = Dwarves
     * Position 4 = Orcs
     * Position 5 = Undead
     * Position 6 = Trolls
     * ....
     */

    Human(Relations.Friendly/*Humans*/, Relations.Neutral/*Elves*/, Relations.Neutral/*Dwarves*/, Relations.Neutral/*Orcs*/, Relations.Hostile/*Undead*/, Relations.Hostile/*Trolls*/),
    Elf(Relations.Neutral, Relations.Friendly, Relations.Neutral, Relations.Neutral, Relations.Hostile, Relations.Hostile),
    Dwarf(Relations.Neutral, Relations.Neutral, Relations.Friendly, Relations.Neutral, Relations.Hostile, Relations.Hostile),
    Orc(Relations.Neutral, Relations.Neutral, Relations.Neutral, Relations.Friendly, Relations.Hostile, Relations.Friendly),
    Undead(Relations.Hostile, Relations.Hostile, Relations.Hostile, Relations.Hostile, Relations.Friendly, Relations.Hostile),
    Troll(Relations.Hostile, Relations.Hostile, Relations.Hostile,Relations.Friendly, Relations.Hostile, Relations.Friendly);

    public final Relations[] relations;

    Faction(Relations... relations) {
        this.relations = relations;
    }
}

public enum Relations {
    Hostile,
    Neutral,
    Friendly
}

public class FactionHandler {
    public Relations getRelations(Faction faction1, Faction faction2) {
        Relations relations1to2 = faction1.relations[faction2.ordinal()];
        Relations relations2to1 = faction2.relations[faction1.ordinal()];
        return relations1to2.ordinal() < relations2to1.ordinal() ? relations1to2 : relations2to1;
    }

    public boolean checkIfHostile(Faction faction1, Faction faction2) {
        return getRelations(faction1, faction2) == Relations.Hostile;
    }
}

```

If you want to avoid having that problem, and if you relations can change during the game you might want to store the `Relations` in a `Map` keyed on the `Faction`,`Faction` pair. A simplified version of this (without error handling for you forgetting to set a `Relation` for a specific pair) could look like this;

public enum Faction { Humans, Elves, Dwarves, Orcs, Undead, Trolls }

```
public enum Relations {
    Hostile,
    Neutral,
    Friendly
}

public class FactionPair {
    private final Faction factionA;
    private final Faction factionB;

    public FactionPair(Faction factionA, Faction factionB) {
        // This makes sure that if you do
        //   new FactionPair(Humans, Orcs)
        // or
        //   new FactionPair(Orcs, Humans)
        // they both end up the same.
        this.factionA = factionA.ordinal() < factionB.ordinal() ? factionA : factionB;
        this.factionB = factionA.ordinal() < factionB.ordinal() ? factionB : factionA;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof FactionPair) {
            FactionPair other = (FactionPair)obj;
            return other.factionA.equals(factionA) && other.factionB.equals(factionB);
        }
        else
            return false;
    }

    @Override
    public int hashCode() {
        return factionA.hashCode() ^ factionB.hashCode();
    }
}

public class FactionHandler {
    private final Map<FactionPair, Relations> map = new HashMap<FactionPair, Relations>();

    public void setRelations(Faction factionA, Faction factionB, Relations relations) {
        map.put(new FactionPair(factionA, factionB), relations);
    }

    public void isHostile(Faction factionA, Faction factionB) {
        return map.get(new FactionPair(factionA, factionB));
    }
}

```

You would then set your relations like this;

```
FactionHandler factionHandler = new FactionHandler();
factionHandler.setRelations(Faction.Humans, Factions.Orcs, Relations.Hostile);

bool areOrsHostileTowardsHumans = factionHandler.isHostile(Factions.Orcs, Factions.Humans);

```
> 0 votes

---
Tags: java, game-mechanics, rpg
---


# Question
Title: Is it necessary to set a stage as an input processor when creating a touchpad?
I mean, I've been searching it, they always use set a stage as an input processor after they had added the `Touchpad`to the `Stage` because it extends from `Actor` indireclty(it extends from `Widget` that extends from `Actor`), just like this:

```
myStage.addActor(myTouchpad);
Gdx.input.setInputProcessor(myStage);

```

Is there any other way to set the input processor when creating a touchpad?

# Answer
> 1 votes
You can also create a class that extends InputProcessor.

Then add add it as the Gdx InputProcessor.

```
Gdx.input.setInputProcessor(MyInputProcessor);

```

More information on the LibGDX wiki: Event handling.

---
Tags: java, android, libgdx
---


# Question
Title: How to implement own UI widget in libGDX?
I want to implement my own widget, here is an image:

what I want to get. Instead of numbers there will be some names, but I think it doesn't matter. I'm pretty new in libGDX, so could you please briefly describe me plan, how can I do something like this (if there will be some code, it would be awesome)? I tried to google it, but didn't find something relevant.

Thanks in advance!

# Answer
> 1 votes
```
 shapeRenderer.begin(ShapeType.Line);
 shapeRenderer.setColor(1, 1, 0, 1);
 shapeRenderer.line(x, y, x2, y2);
 shapeRenderer.rect(x, y, width, height);
 shapeRenderer.circle(x, y, radius);
 shapeRenderer.end();

```

Here is an example for the shapeRenderer class. I think that tree is a dynamic, a background image wouldn't work.

So you need to come up with an object oriented design or use a recursive function to draw it. How do you store your data? Without further information, supplying you with code is impossible.

Also did you get that image in libgdx, and are you asking to only write words instead of numbers? If that's the case use bitmap font. To use bitmap font look at the first link.

Here are some links to help you.

https://github.com/libgdx/libgdx/wiki/Gdx-freetype

https://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/graphics/glutils/ShapeRenderer.html

# Answer
> 0 votes
People might hate me for this (Not the most optimized idea, but still easy):

You can create an image without the numbers/names, just the lines, load it as background image, then write your text (Doesn´t matter if numbers or letters) in the desired position.

```
yourGame.font.draw(yourBatch, yourString, x, y);

```

(Take into account the resolution of the image if you want your app to work on different devices)

---
Tags: libgdx, gui
---


# Question
Title: Collision works except for when coming from right side
I am trying to make a bomberman clone. I'm having problems with the collision on the walls that is not on the sides of the map (see image). When I come from the right (going left), the red square (player) goes through the wall but when I come from other sides (up, left, down) the collision works well and the player does not go through. The collision on the side walls works well also even when I come from the right and going left.

I am using Tiled and LibGDX and here is the code:

```
private void checkCollision(float delta) {
    //player.getVelocity().scl(delta);
    Vector2 position = player.getPosition();

    // just to see if it overlaps because this is the location of the
    // rectangle when getTiles is called when player moves left as shown in the image
    Rectangle rect = new Rectangle(128, 128, 64, 64);
    if(player.getRectangle().overlaps(rect)) {
        System.err.println("overlap");
    }

    if(player.isMovingRight()) {
        Array<Rectangle> tiles = getTiles((int)(position.x/TILE_SIZE + 1), (int)(position.y/TILE_SIZE - 1),
                (int)(position.x/TILE_SIZE + 1), (int)(position.y/TILE_SIZE + 1));
        for (Rectangle tile : tiles) {

            if(player.getRectangle().overlaps(tile)) {
                System.out.println("overlap right");
                player.setPosition(tile.x - player.getWidth() , player.getPosition().y);
            }
        }
    }
    if(player.isMovingLeft()) {
        Array<Rectangle> tiles = getTiles((int)(position.x/TILE_SIZE - 1), (int)(position.y/TILE_SIZE - 1),
                (int)(position.x/TILE_SIZE - 1),  (int)(position.y/TILE_SIZE + 1));
        for (Rectangle tile : tiles) {

            if(player.getRectangle().overlaps(tile)) {
                System.out.println("overlap left"); // this doesn't show
                player.setPosition(tile.x + tile.width, player.getPosition().y);
            }
        }
    }

    if(player.isMovingUp()) {
        Array<Rectangle> tiles = getTiles((int)(position.x/TILE_SIZE - 1), (int)(position.y/TILE_SIZE - 1),
                (int)(position.x/TILE_SIZE + 1), (int)(position.y/TILE_SIZE));
        for (Rectangle tile : tiles) {

            if(player.getRectangle().overlaps(tile)) {
                System.out.println("overlap up");
                player.setPosition(player.getPosition().x, tile.y + tile.height);
            }
        }
    }
    if(player.isMovingDown()) {
        Array<Rectangle> tiles = getTiles((int)(position.x/TILE_SIZE - 1), (int)(position.y/TILE_SIZE + 1),
                (int)(position.x/TILE_SIZE + 1), (int)(position.y/TILE_SIZE + 1));
        for (Rectangle tile : tiles) {

            if(player.getRectangle().overlaps(tile)) {
                System.out.println("overlap down");
                player.setPosition(player.getPosition().x, tile.y - player.getHeight());
            }
        }
    }

    //player.getVelocity().scl(1/delta);

}

private Array<Rectangle> getTiles(int startX, int startY, int endX, int endY) {
    TiledMapTileLayer layer = (TiledMapTileLayer)level.getMap().getLayers().get(1);
    Array<Rectangle> rectangles = new Array<Rectangle>();
    for (int x = startX; x <= endX; x++) {
        for (int y = startY; y <= endY; y++) {
            Cell cell = layer.getCell(x, y);
            if(cell != null) {
                Rectangle rect = new Rectangle(x*TILE_SIZE, y*TILE_SIZE, TILE_SIZE, TILE_SIZE);
                rectangles.add(rect);
            }
        }
    }
    return rectangles;
}

```

# Answer
> 2 votes
The glitch is in your `isMovingLeft` method. You are giving in `getTiles` same `X` value in `start` and `end`. That is why it is creating no geometrical area.

So change do change in `player.isMovingLeft()` check, 3rd parameter of `getTiles` from `(int)(position.x/TILE_SIZE - 1)` to `(int)(position.x/TILE_SIZE + 1)`.

By this it will create an area of your tile size.

# Answer
> 0 votes
1. Check if there is a collision.
2. Find the direction of the collision.
3. Move the player to the opposite side.

Forget about checking which direction the player is moving. get rid of `if(player.isMovingLeft())` and others.

After finding collision, compare the positions of the tile and the player to find the direction of the collision. Then move player in the other direction. If you are using `speed*timeElapsed` to move the player normally, use it again when moving in the other direction from the collision.

In order to find the direction of the collision:

```
if (player.width/2 + tile.width/2 < Math.abs(player.x - tile.x)) {
    // collsion  from left or right
    if (player.x > tile.x) {
        player.setPosition(tile.x + player.width/2 + tile.width/2, player.y)
    }
    else {
        player.setPosition(tile.x - player.width/2 - tile.width/2, player.y)
    }
}

```

You can use this to find if there is a collision too.

**NOTE:** Always move player in the opposite side or reposition the pleyer, don't block movement.

---
Tags: collision-detection, libgdx, collision-resolution
---


# Question
Title: save a particular area of the scene as screenshot in unity
I need to save a particular part of the scene as screenshot. I have done a sample to show the particular part of the scene.

When I click on the rectangular area the selected area will being shown on the screen on a texture (marked in red rectangle):

But when I save, the whole scene is getting saved but not the selected part:

Here is code:

```
Texture2D screencap;
Texture2D border;
bool shot=false;
public string path;

void Start () {
     screencap=new Texture2D(300,200,TextureFormat.RGB24,false);
     border=new Texture2D(2,2,TextureFormat.ARGB32,false);
     border.Apply();
}

// Update is called once per frame
void Update () {
    if(Input.GetKeyUp(KeyCode.Mouse0))
    {
        StartCoroutine("Capture");
    }

}
string fileName(int width, int height)
{
    return string.Format("screen_{0}x{1}_{2}.png",
                         width, height,
                         System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"));
}

void OnGUI()
{
    GUI.DrawTexture(new Rect(200,100,300,2),border,ScaleMode.StretchToFill);
    GUI.DrawTexture(new Rect(200,300,300,2),border,ScaleMode.StretchToFill);
    GUI.DrawTexture(new Rect(195,100,2,200),border,ScaleMode.StretchToFill);
    GUI.DrawTexture(new Rect(500,100,2,201),border,ScaleMode.StretchToFill);

    if(shot)
    {
        GUI.DrawTexture(new Rect(50,10,60,40),screencap,ScaleMode.StretchToFill);
        //Application.CaptureScreenshot(myFolderLocation+myFilename);
    }
}

IEnumerator Capture()
{
    yield return new WaitForEndOfFrame();
    screencap.ReadPixels(new Rect(198,98,298,198),0,0);
    screencap.Apply();
    shot=true;

    byte[] bytes=border.EncodeToPNG();
    string filename=fileName(Convert.ToInt32(screencap.width), Convert.ToInt32(screencap.height));
    Application.CaptureScreenshot("D:"+filename);
}

```

How can I save only the particular part in unity,can anybody please help me out.

# Answer
Your

```
Application.CaptureScreenshot("D:"+filename);

```

saves the whole shene on file, you need to save the texture2d to file

Follow the example:

```
 import System.IO;

  function SaveTextureToFile( texture: Texture2D,fileName)
  {
     var bytes=texture.EncodeToPNG();
     var file = new File.Open(Application.dataPath + "/"+fileName,FileMode.Create);
     var binary= new BinaryWriter(file);
     binary.Write(bytes);
     file.Close();
  }

```

Call it using:

```
      SaveTextureToFile( screencap,"picture.png");

```

EDIT: a variation of SaveTextureToFile can be:

```
     function SaveTextureToFile(  Texture2D texture ,string fileName)
      {
        byte[] bytes = texture.EncodeToPNG();
         File.WriteAllBytes(filename, bytes);
}

```
> 2 votes

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


title: Unity 3D C# - Shifting beetween worlds?

text:
# Question
Title: Unity 3D C# - Shifting beetween worlds?
Let's say I want to replicate Planeshifting from Legacy of Kain: Soul Reaver in Unity.

There are 2 realms: Spectral realm and Material realm.

The Spectral realm is based on the Material realm, only has the geometry distorted and certain objects fade out/become non-interactive.

In Soul Reaver, it is used as means to go to areas where you normally wouldn't be able to in Material (distorting geometry), to use other powers (such as going through grates).

My question is: Is it even possible at all to implement this in Unity 3D? (I would need the Scene(level) or the objects to have 2 states somehow that I could switch beetween/distort to real-time.)

# Answer
Absolutely, there are several approaches you could use.

* You could use one scene for each. This would involve some duplication of work potentially, but you could build each scene from prefabs to minimize that.

This will cause there to be some load time when you switch from one realm to another, though you may be able to eliminate that with `LoadSceneAsync()`.
* You could tag all objects from each realm with a tag for that realm, and use `GameObject.SetActive(bool active)` to flip all the objects from one realm off and the objects from another realm back on.

Again this would mean two versions of everything would have to be built, but depending on how warped they are that might be the easiest way to do it. This would make flipping between realms relatively instant.
* Progamatically distort the objects in the scene when you switch between realms. This may be the best approach if the degree of distortion is not extreme.

Tag each gameobject that will need to be modified, use `FindGameObjectsWithTag(string tagname)` to get a list of all those objects, iterate over them and make the necessary changes. You can easily swap shaders/textures or even meshes on each game object as you flip between one mode and another.

This may introduce a slight pause in the gameplay depending on how much manipulation has to be done to each game object. You could easily disguise that with some sort of transition effect.
> 3 votes

# Answer
This is kind of an extension to @jackmott's answer, similar his suggestions, but different.

Instead of using `GameObject.SetActive()` to flip the states of everything in the scene, I would instead suggest using shaders, material flags, and your own method that flags objects as being visible or invisible depending on the current render state. (This is also slightly related to point 3, doing it programatically, as well).

The benefits are that you only need to create your scene once, and objects that are only visible in one "realm" are cleverly not-rendered when the player isn't *in* that realm.

Take a look at `Camera#SetReplacementShader()`. In forcing the main camera to use a different shader to render every object in the scene, you can change between the material realm (objects use their own shaders) and the spectral realm (objects are rendered using a custom `SpectralShader` that you will need to create) which will do the color shifting, blurring, and vertex distortion.

Can't find my screenshot at the moment (on the wrong computer), but I've got something similar set up for my own project right now. It lets me draw outlines of enemies through walls (if the player has that ability active), not draw enemies that are invisible (but they will get outlines!), or draw them as unlit blobs (visible through walls). I use the last one for things like notification icons, e.g. a red `!` that hovers over an objective point.

Which state is active depends on which camera is currently rendering, what attribute flags it has, and the enemy being rendered. I had to do a little hacking to get this to work, but I have an event notification system that fires off an event during `OnPreRender` (this only happens on the object the Camera is attached to, not for every object *being* rendered!) to notify every object about to be rendered the detail specifics of the render being performed (can the player see through walls, is the camera a remove-viewing device, and so on). Objects that should be invisible turn their renderer off, objects that should turn it back on, and a couple other flags get flipped via `Material#SetOverrideTag`.

Shader pass tags are super important when dealing with SetOverrideShader: When the replaced shader runs, it looks at the original shader's tags. If the replaced shader has the same tag with the same value, the pass runs. See Rendering with Replaced Shaders.

This will be a very hard avenue to pursue, but it will also be the one that will have the best looking result with the most flexibility and least amount of effort spent in level creation. And almost certainly the method employed by Legacy of Kain. The hardest part will be creating the custom shader. My own, for my three or four simple effects, is hundreds of lines long (the outline pass alone is 165!)
> 2 votes

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


title: How to spawn Chunks in Libgdx?

text:
# Question
Title: How to spawn Chunks in Libgdx?
I'm currently working on a 2D platforming game with an infinite map.

I did my research and I discovered that I can use chunks. Based on my understanding chunks is about spawning terrain at the right time and then removing them when not needed.

My idea was to pool a body then add it to an array list so that I can use a static body and remove it any time without any problems.

But then I realized that Pooling is not applicable to bodies.

How can I spawn chunks, without creating a new body every single time and then remove it when not needed?

# Answer
I would suggest changing position of already created chunks.

For example:

```
if(exampleChunk.getX()-exampleChunk.getWidth()<0){
    exampleChunk.setX(Gdx.graphics.getWidth());
}else{
    exampleChunk.setX(exampleChunk.getX()-(200*delta);  //delta being the render(float delta) value.
}

```

Simply use this code for every chunk every time you update the state of your game.

I find it pretty easy, and you won´t need to dispose or create any chunks.

Hope it helps, tell me if you have any question.

**EDIT:** This is just an **example**, you can also update Y value, or whatever changes you want to make, I think it is simple enough to understand it, even with my poor english.
> 0 votes

---
Tags: java, libgdx, box2d, object-pools
---


# Question
Title: What are the document grid settings in inkscape for making an isometric tilemap for tiled?
I am using inkscape to create a isometric tilemap. What settings do I need on the grid in document properties in inkscape to make it match up to a 64 x 32 grid in tiled?

# Answer
As the link that Sidar comment alluded to, **in the document properties you have the set both of the angles on the grid to 26.56 degrees.** This will give you a size ratio where the height is half the size of the width.

From there, as long as all the other numbers are in pixel units and set to a value that is in the base 2 set (2, 4, 8, 16, 32, 64, etc...) you should be able to get set up a grid that matches you're requirements.
> 1 votes

---
Tags: tiles, isometric, tiled
---


title: Shadows in Android using Unity 5

text:
# Question
Title: Shadows in Android using Unity 5
The point lights in my scene cast shadows when it's in the editor mode but the light passes through walls in the build or play mode.
I checked the quality settings and set it to hard and soft shadows for all quality settings but that didn't fix it.
It does work when I increase the quality when I build it for Standalone but not when I build for Android.
I've removed the dx11 option in the PC/Mac Standalone settings.
I've changed both forward and deferred rendering options.
I'm testing it on a Moto G 1st Gen \[XT 1033\].

# Answer
> 1 votes
My camera was too far from the scene. Cranked up the shadow distance in the quality settings and it works fine now.

---
Tags: unity
---


# Question
Title: Unity UI Text Font Size changes with the screen resolution Problem
I am working on a project and now I have a problem . The problem is the font size. The font size is OK inside the Unity but it is really small when I play the game on a real Android device .

My Canvas has 2 text (a and b) and 1 image .

I created an empty game object to hold that text.

Here is the code attached to empty game object :-

```
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class Text_Script : MonoBehaviour
{

public Text My_Text_1 ;
public Text My_Text_2 ;

// Use this for initialization
void Start ()
{
    My_Text_1.text = "Hello";
    My_Text_2.text = "World";
}

// Update is called once per frame
void Update ()
{

}
}

```

Here are the images :-

Inside Unity

Inside a Android Device (here I uploaded the image from BlueStacks , I didn't use my mobile)

So why this is happening ?

I tried this :-

```
function Start()
{
     var myText = GetComponent(GUIText);
     // 50 is the fontsize you want to use
     myText.fontSize = Mathf.Min(screen.height,screen.width)/50;
}

```

but I don't know where to put and on which object should I put those code And I am using Unity 5 and that code is for Unity 4.x .

I don't want to scale the font for a large size as explained in YouTube video (I don't think this is a good method)

So is there any ways to change the font size according to the screen size and resolution .

Please help me

Thanks:)

# Answer
> 1 votes
GUIText is one of Unity's legacy GUI elements, pre-4.6, so this might feel outdated, but still works.

Define your base resolution height. Say you're working with a base height of 500 pixels:

```
var uiBaseScreenHeight:float = 500;

```

Now, what happens if the Android device's screen height is, say, 1500 pixels, which is 3x larger? You'd want to increase the font size:

```
// Dynamically determine the UI scale to use
var uiScale:float = Screen.height / uiBaseScreenHeight; // eg 1500 / 500 = 3

// Set the base font size
var baseFontSize:int = 16;

// Set the scaled font size
var scaledFontSize:int = Mathf.RoundToInt(baseFontSize * uiScale);

// Apply the scaled font size to the GUIText element
myText.fontSize = scaledFontSize;

```

And if you start working with GUITextures, you can adjust the `pixelInset.width` and `pixelInset.height` properties similarly by multiplying base widths and heights against `uiScale`.

---

C# example:

```
public float uiBaseScreenHeight = 500f;

private int GetScaledFontSize (int baseFontSize) {
    float uiScale = Screen.height / uiBaseScreenHeight;
    int scaledFontSize = Mathf.RoundToInt(baseFontSize * uiScale);
    return scaledFontSize;
}

void Start () {
    My_Text_1.fontSize = GetScaledFontSize(16);
}

```

---

The other method, is to use Unity's new UI Canvas and elements instead. Right-click in your Hierarchy and choose UI \> Text. This will create a Canvas with a UI.Text element. Check the Canvas' CanvasScaler component and play around with it; make it use "Scale With Screen Size" and choose your base resolution.

---
Tags: unity, gui, fonts
---


# Question
Title: How to make a bar showing the "percentage" of a maximum
so Im making a game and I need a 'bar' to show how much time has passed in ms (dont worry about the time 'mechanics' I only work with the correct numbers). So lets say that the bar is 128px wide and that I want the timer (the time passed since start in ms) to be displayed within that bar properly, so that e.g. if the time passed is half way of the maximum, then the bar should be half full. Could anyone please tell me the formula because I cant remember/find it.

(btw. all variables needed are the curTime, maxTime and the progress of the bar/the max bar width)

# Answer
> 10 votes
You do it with math.

```
private static const int maxBarWidth = 128;

//...

float ratio = (float)curTime / maxTime;
float barProgressInPixels = ratio * maxBarWidth;

```

Unless you're looking at figuring out how to *render* this information to the screen.

---
Tags: java, mathematics
---


# Question
Title: My rigid body controller stuck in middle of screen (unity)
Still working on my Star Fox clone and am changing up the camera a bit.

**The problem I keep having is my Ship gets locked in the middle of the screen and can't move while its parent (spinMe) is still moving.**

I'm working with rigidbody-ception here I have a rigidbody with in a rigidbody. Both of them move up, down, left, and right.These two are called ***spinMe*** and ***Ship***.

In this version the player is able to move until they reach the end of the screen.

What I'd like to do is have the camera move slightly as well to help ***Ship*** cover more of a bases and help with perception. *Star Fox did this as well.*

So ***spinMe*** pulls ***Ship*** around with it but for some reason that keeps ***Ship*** from moving independently while being moved around by ***spinMe***. Only when ***spinMe*** can't move any further ***Ship*** will move.

So I guess I would like to know is why can't I get my ***Ship*** to move at the same time as ***spinMe***.

**So this is the main chunk of the code for spinMe**

```
    Vector3 movementy = transform.TransformDirection(Vector3.up * Input.GetAxis("Vertical") * turnSpeed);
    Vector3 newPos = transform.position + movementy;
    Vector3 offset = newPos - Midpoint.position;
    transform.position = Midpoint.position + Vector3.ClampMagnitude(offset, radius);

    Vector3 movementx = transform.TransformDirection(Vector3.right * Input.GetAxis("Horizontal") * turnSpeed);
    Vector3 newPosx = transform.position + movementx;
    Vector3 offsetx = newPosx - Midpoint.position;
    transform.position = Midpoint.position + Vector3.ClampMagnitude(offsetx, radius);

```

**And this is the movement for Ship**

```
Vector3 pos = Camera.main.WorldToViewportPoint(transform.position);
    pos.x = Mathf.Clamp01(pos.x);
    pos.y = Mathf.Clamp01(pos.y);
    transform.position = Camera.main.ViewportToWorldPoint(pos);
   Vector3 moveDirection = new Vector3(turnSpeed * Input.GetAxis("Horizontal"),
                                       turnSpeed * Input.GetAxis("Vertical"), 0);
   moveDirection = transform.TransformDirection(moveDirection);
   rb.MovePosition(transform.position + moveDirection);

```

I've tried this a variety of different ways and I believe this is my best chance of getting this working.

# Answer
I did it okay what I did was I put spinMe within another object and moving that one around. I believe the whole problem had to do with the fact that spinMe is an animated object. this was a relatively simple fix as it turns out.
> 0 votes

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


# Question
Title: Painter algorithm vs. 3D rendering with Z-buffer when drawing 2D Sprites
I'm currently developing a tile base engine. I want it to look like your average old school tilebased RPG like Zelda - Link to the past (orthographic projection, squared tile texture, textures overlapping each other, alpha channels, etc.). The twist is that the world is internally 3d meaning that every tile has an elevation and entities are moving in a 3d space. Reason for this is beyond the scope of this question but I'm struggling on comparing the follow two ideas for the rendering. I'm using OpenGL with libGDX in Java but wouldn't mind writing my own code to interface OpenGL. That's also why I didn't tag it.

**A screenshot of "Zelda - Link to the past" in case you don't know what it looks like.**

# Painter algorithm

Disable Z-Buffer and use painter algorithm to draw from back to front in the appropriate order with some overdraw and a lot of texture rebinding. I know a texture atlas can minimize the texture rebinding but the engine is supposed to act more like a sandbox so I don't want to rely too heavily on assumptions like a efficient texture atlas that I might not have all the time.

**Pro:** Easy to implement and very straight forward.

**Con:** I've no idea how big the impact will be since almost every sprite will cause a texture rebinding. And I don't know how to predict the performance costs of that many texture bind calls.

---

# Full blown 3D

Rotate the camera 45 degrees up around the x axis with an orthographic projection matrix. Then use the 3d information from the game world to draw the tile textures with billboarding at the real position in the worlds 3d space. Same for entities and such. This way I can gather all sprites and then render them sorted by their texture which means one texture bind per texture and reduced overdraw due to usage of the Z-buffer

**Pro:** I can use a freecam to debug render problems. I assume it's significantly faster that the painter algorithm.

**Con:** Some sprites might share the same place which could lead to Z-fighting. I'm thinking about how to use multiple layers on a tile. For instance you may have a bridge tile with a railing where the railing is always overlapping an entity on the bridge but the floor of it is always overlapped by the entity. So I would have to add a little offset to different layers in the 3d space. I'm not really sure how that would work out and to be honest had a hard time figuring out how old games did it so maybe I'm overthinking it.

---

I guess I have a very rough idea of how each method will work out but I don't know how much the texture rebinding (or sorting and preparing the sprites for the 3d approach) is affecting the performance and while it's easy to find information regarding large 3D scenes I found it difficult to get information about 2D scenes with way less polygons.I hope this question is not too much a subject of personal preference. I know that *Premature optimization is the root of all evil* but due to how the decision is affecting almost the entire rendering process I don't want to make the wrong call.

I deliberately didn't mention any OpenGL functions mainly because I've mostly used the libGDX API which hides the function calls behind it's wrappers but generally I know how the internals work and just got into the internals and how the OpenGL API works. I don't think specific OpenGL calls do matter for the question but feel free to use them for your answer I'll just look them up.

# Answer
One downside to Z-buffering vs sorting not mentioned by the other answers can and most likely will happen when using Z-buffering with images whose pixels are not fully transparent or fully opaque. Alpha-blending said pixels correctly *is dependent on the order they are drawn*. Say you have a half-transparent green square and a half transparent red square in the same location, with the green square having a z value closer to the view (so overlapping, with green square being on top). If you draw the red square first, and then the green square second, blending will be done correctly as the green square with a closer z value gets drawn on top of the red square further away. But, if you draw in the reverse order, the red square *will not get drawn at all* since the its z value is further than the z value of the green square previously drawn! So instead of the nice blending you got before, you now only get the green square. In fact, this same issue can occur if you have a fully transparent pixel that you do not discard (so it does not write to the depth buffer). So in this case, you would need to sort the images by their z to ensure the proper blending is done.
> 2 votes

# Answer
Use Z-buffering. You can test this out, but in principle for your application you should end up *with no Z-fighting!*.

(In either approach, you need to keep track of which things you *want* in front of other things; attaching a Z value per tile is straightforward. This answer is really just striking one of your "cons" for z-buffer.)

Z fighting happens because the Z interpolation of two surfaces has minute errors where sometimes it's a little high and sometimes it's a little low.

But for your 2d, flat tiles, the Z values for all vertices of the tile will be the same. The interpolation will be perfect, and will give the same value for the entire triangle, and be the same for the whole tile. So for any two tiles, one of them will be visibly in front of the other.

If it matters which, be sure to give them different Z values, or manipulate the draw order appropriately for the depth function used.

---

Addendum -- I'm not sure I grok, but you mentioned something about "rotate the camera 45 degrees"... if you're trying for an ortho projection, you may want to implement something like

```
transformedP.xy = p.xy + orthoAmt * vec2(p.z, p.z);
transformedP.z = p.z;

```

So, very specifically, not "full 3d", to guarantee perfectly flat (z-constant) polys.
> 1 votes

# Answer
Since the entire world is 3d, and orthographic, a simple "cheat" could be made to avoid all z buffering problems, and maximize efficiency over the painterly algorithm.

First, for every tile in the game, give it a height. This shows where is over relative to the objects directly above and below it. For example, a bust over grass. The grass, on the bottom, would have a height of 0. The bush would have a height of 1. This means that the bust is above the grass, and will be rendered on top of it.

If you want move objects, just keep stacking the height. Lets say you want to add berries on the bush. Then make the berries a height of 2. While on another area the berries have a height of 1, and the bush has a height of 2. On that once, the bush is above the berries. Always, until you say otherwise.

Now, for each possible *type* of object in the game, assign a very small, unique value between 0 and 1, exclusive. Which means ALL berries have a uuid of 0.1, and ALL bushes have a uuid of 0.15, and so on. The actual values don't really matter, as long as it's always different. (Note, REALLY close together values may still cause issues. Like 0.1 and 0.0999999.) Do this for every tile, entity, and sprite in the game.

When you assign an object's height, always add this number. After doing this, the bush example above would look more like:

```
Grass Tile = 0.1  (Uuid of 0.1, height of 0)
Bush = 1.2        (Uuid of 0.2, height of 1)
Berries = 2.3     (Uuid of 0.3, height of 2)
Player = 3.4      (Uuid of 0.4, height of 3)

```

Now, your problem is solved. Z-Fighting will not occur between two objects of the same texture, as it will always be the same texture on both sides, so nothing flickers.)

The whole uuid system can be erased if you can confirm that no two tiles can share the same x, y, and z. If none do, then get rid of the system above.

Now, for best performance, render all solids first, then all transparents. Make sure to do as little texture switching as possible. Meaning render all grass tiles in one go, then all sand, then all bushes, then all berries.

Skip any textures not currently on screen.

Good luck!
> 1 votes

---
Tags: opengl, rendering
---


# Question
Title: Looking for a clever way to differentiate objects
I have a lot of cubes in my game (2d squares) and I decided to add some skins to them. However the colors that they have don't really make them look appealing.

For example, I have this sprite:

Here is how the squares look with that particular sprite:

As you can see, they don't really look that great with all these bright colors.

Is there any way that I can make this look better, but for the users to still be able to differentiate between the different cubes?

# Answer
> 6 votes
You can use:

* Colours (what you did already)
* Add 'tags' (like a label that has been stuck to it) at different positions
* Add letters or numbers as decals
* Add different images
* Instead of having only box crates, you could add steel crates, rock blocks
* Different shapes
* You could make them slightly *move!* Like Fat Albert's gang, you could give each type of cube it's own way to move (e.g. one rotates every 2 seconds, one performs a half rotation each second, one half-rotate and comes back, one pulses like a beating heart, one fades like a ghost, etc...)
* With the lore of your game, give them names, personalities and visuals and make them act as such (e.g. instead of *Green Cube*, call it Hope, make it move softly and give it a look of a soft and comforting joy, and instead of *Red Cube*, call it Rage, make it pulse violently like a pounding fist, while giving it the look of something angry, like your worst grade school teacher).

This last idea really comes down to "*Why do I have different coloured cubes?*" If there is no reason, there is no reason to have different coloured cubes and differentiate them, as this could confuse some players. If you want to have different coloured cubes, find a game-design reason to have different coloured (or whatever you'd like to change their look for).

Once you find that reason, this will help you define the cube personalities, and then expand on them, and then further expand on your game's background story.

If your game does not have a story/background, this could be a nice reason to develop one (some players like to follow through the story of the game, sometimes more than to play the game *per se*), and if you already have one, try to make the colour/personalities complement it.

---

*Keep in mind that your players will want to play the game, not be bothered by the story: make sure they know there is one and give them access to it if they want to live it, but don't force them to have to go through it in order to play.*

---
Tags: unity, game-design, sprites
---


title: Reusable component design

text:
# Question
Title: Reusable component design
I'm working on an engine for my game (in C++). I've done the graphics related stuff and I've started working on UI (user interface). When I was working on buttons I've realized that hardcoding every kind of button would not be possible (or would be too many classes) as I have buttons with only labels, with colored backgrounds, with texture backgrounds and so on...

So I think what I need are Components. I just build the button I want:

```
UIButton* btn = new UIButton();
btn->AddRenderComponent(new DrawRectComponent(...));
btn->AddRenderComponent(new DrawStringComponent(...));
btn->AddLogicComponent(new SendEventOnClickComponent(...));

```

My problem is that I don't know how to tell the component objects what fields should they use from the UI elements? For example position and size (which could change dinamically). Should I use references for example?

Also it would be good if I could not only use this in the UI, but a similar component system could be used in other parts of the engine (at entities for example).

# Answer
Let's see if I can understand your question here:

* You want to create some UI elements (such as your `UIButton`);
* All of the components that are passed to it (eg.: `RenderComponent`) should be able to access the UI object's properties.

Is this it? Because if that's the case, then you can do use the following logic:

* Each of the UI elements should have fields for `position`, `sizeX` and `sizeY` for example;
* With that in mind, you can create a *super class* that represents an UI element, and have all your elements inherit from that class;
* In that very same *super class*, you can already leave declarations for possible components you want to add, and those methods declared already as well (eg.: `AddRenderComponent`);
* In each one of the subclasses (eg.: `UIButton`), since you say the size and position aren't always the same, these variables should be controlled within the UI component;
* That is good, because then you decouple code from the outside of the elements themselves. By doing that, each button will have different characteristics (like random animations that you might want to apply to the buttons, or have them move around the screen);
* It's also good because then you can just access the object's position and size through its instance. Like that, you can have all buttons as dynamic as you want, and independent from one another;
* As for the components, since they're "coupled" to the UI element, they can use all of the information from the element as they want - that can be achieved in passing the needed information in the methods:

```
void UIButton::AddRenderComponent(T renderComponent) {
  renderComponent.elementSize = this->size; //size passing example
  // Add your render component to the element here
}

```

With the above, your elements will have their properties set for themselves, with the possibility for the outside to access them, as well as keep your components with the needed knowledge.

Hope that helps you!
> 2 votes

# Answer
What you should do is have a local *relative* field in the subcomponents, for instance the size and position could be floats in the range of **\[0,1\]** and then you figure out the absolute size, position and everything else of a subcomponent by multiplying the elements values with the components values when rendering.
> 0 votes

---
Tags: c++, component-based
---


title: libgdx-using more than one class

text:
# Question
Title: libgdx-using more than one class
Hi i am very new to programming and in this community,so im recently studying on how to develop games with libgdx and all the tutorials only have one class and do all the things in that class,but is it possible to use more than one class?(ex:individual class for player, mobs , etc) thanks!

# Answer
> 1 votes
Short answer; **Yes**, it is possible to use more than one class when doing **libGDX** development.

But don't worry about it, asking if *X* is possible isn't always that useful, I think you'll have more luck with asking questions on this site if you instead try to implement something and when you hit a problem you ask specifically about that.

Just asking if multiple classes is possible doesn't necessarily give you a relevant answer as the question doesn't constrain the context enough and is also opinion based (as to where and how multiple classes should be used in **libGDX**).

If you want to look at a game that has a more complex implementation, have a look at Super Jumper.

---
Tags: libgdx
---


# Question
Title: Why does rotating my quad appear to move it farther away?
I have created a 3x3 matrix class which is then passed over to OpenGL Vertex Shader for transform my Quad. I have been trying to rotate my Quad around Z-Axis. Rotation is working but the Quad getting further away from the screen. Below are my Matrix and Vertex Shader source:

Matrix3x3.cpp

```
#include "matrix3x3.h"
#include "vector2d.h"
#include <cmath>

Matrix3x3::Matrix3x3()
{
    matrix[0][0] = 1.0f;
    matrix[0][1] = 0.0f;
    matrix[0][2] = 0.0f;

    matrix[1][0] = 0.0f;
    matrix[1][1] = 1.0f;
    matrix[1][2] = 0.0f;

    matrix[2][0] = 0.0f;
    matrix[2][1] = 0.0f;
    matrix[2][2] = 1.0f;
}

void Matrix3x3::setIdentity()
{
    matrix[0][0] = 1.0f;
    matrix[0][1] = 0.0f;
    matrix[0][2] = 0.0f;

    matrix[1][0] = 0.0f;
    matrix[1][1] = 1.0f;
    matrix[1][2] = 0.0f;

    matrix[2][0] = 0.0f;
    matrix[2][1] = 0.0f;
    matrix[2][2] = 1.0f;
}

void Matrix3x3::translate(float tx, float ty, float tz)
{
    float tmpMatrix[3][3];

    tmpMatrix[0][0] = 1.0f;
    tmpMatrix[0][1] = 0.0f;
    tmpMatrix[0][2] = 0.0f;

    tmpMatrix[1][0] = 0.0f;
    tmpMatrix[1][1] = 1.0f;
    tmpMatrix[1][2] = 0.0f;

    tmpMatrix[2][0] = tx;
    tmpMatrix[2][1] = ty;
    tmpMatrix[2][2] = tz;

    mutliply(tmpMatrix);
}

void Matrix3x3::rotate(float angle)
{
    float tmpMatrix[3][3];

    const float radian = 3.141593f / 180 ;//(angle * 3.141592653589793 )/ 180.0;// (2 * PI) / (360.0 / cos(angle));

    float cs = cos(radian * angle);
    float sn = sin(radian * angle);

    tmpMatrix[0][0] = cs;
    tmpMatrix[0][1] = sn;
    tmpMatrix[0][2] = 0.0f;

    tmpMatrix[1][0] = -sn;
    tmpMatrix[1][1] = cs;
    tmpMatrix[1][2] = 0.0f;

    tmpMatrix[2][0] = 0.0f;
    tmpMatrix[2][1] = 0.0f;
    tmpMatrix[2][2] = 1.0f;

    mutliply(tmpMatrix);
}

void Matrix3x3::scale(float sx,float sy)
{
    float tmpMatrix[3][3];

    tmpMatrix[0][0] = sx;
    tmpMatrix[0][1] = 0.0f;
    tmpMatrix[0][2] = 0.0f;

    tmpMatrix[1][0] = 0.0f;
    tmpMatrix[1][1] = sy;
    tmpMatrix[1][2] = 0.0f;

    tmpMatrix[2][0] = 0.0f;
    tmpMatrix[2][1] = 0.0f;
    tmpMatrix[2][2] = 1.0f;

    mutliply(tmpMatrix);
}

void Matrix3x3::transform(vector2d& vec)
{
    /*float tx = vec.x * matrix[0][0] + vec.y * matrix[3] + vec.w * matrix[6];
    float ty = vec.x * matrix[1] + vec.y * matrix[4] + vec.w * matrix[7];
    float tw = vec.x * matrix[2] + vec.y * matrix[5] + vec.w * matrix[8];

    vec.x = tx;
    vec.y = ty;
    vec.w = tw;*/
}

void Matrix3x3::mutliply(const float(&matrixb)[3][3])
{
    /*matrix[0] = (matrix[0] * matrixb[0]) + (matrix[1] * matrixb[3]) + (matrix[2] * matrixb[6]);
    matrix[1] = (matrix[0] * matrixb[1]) + (matrix[1] * matrixb[4]) + (matrix[2] * matrixb[7]);
    matrix[2] = (matrix[0] * matrixb[2]) + (matrix[1] * matrixb[5]) + (matrix[2] * matrixb[8]);

    matrix[3] = (matrix[3] * matrixb[0]) + (matrix[4] * matrixb[3]) + (matrix[5] * matrixb[6]);
    matrix[4] = (matrix[3] * matrixb[1]) + (matrix[4] * matrixb[4]) + (matrix[5] * matrixb[7]);
    matrix[5] = (matrix[3] * matrixb[2]) + (matrix[4] * matrixb[5]) + (matrix[5] * matrixb[8]);

    matrix[6] = (matrix[6] * matrixb[0]) + (matrix[7] * matrixb[3]) + (matrix[8] * matrixb[6]);
    matrix[7] = (matrix[6] * matrixb[1]) + (matrix[7] * matrixb[4]) + (matrix[8] * matrixb[7]);
    matrix[8] = (matrix[6] * matrixb[2]) + (matrix[7] * matrixb[5]) + (matrix[8] * matrixb[8]);*/

    for (int x = 0; x<3; ++x)
        for (int y = 0; y<3; ++y)
        {
            float sum = 0;
            for (int z = 0; z<3; ++z)
                sum += matrix[x][z] * matrixb[z][y];

            matrix[x][y] = sum;
        }
}

ostream& operator<<(ostream& os,Matrix3x3& matrix)
{
    os << matrix.matrix[0][0] << " " << matrix.matrix[0][1] << " " << matrix.matrix[0][2] << std::endl;
    os << matrix.matrix[1][0] << " " << matrix.matrix[1][1] << " " << matrix.matrix[1][2] << std::endl;
    os << matrix.matrix[2][0] << " " << matrix.matrix[2][1] << " " << matrix.matrix[2][2] << std::endl;

    return os;
}

float* Matrix3x3::getPtr()
{
    return &matrix[0][0];
}

```

vertex\_shader.glsl

```
#version 330 core

layout (location = 0) in vec3 position;

uniform mat3 transform;

void main()
{
    gl_Position = vec4(transform  * vec3(position.x,position.y,0.0) , 1.0);
}

```

This is where i am using my matrix in the Quad class:

```
void Quad::rotate(float angle2)
{

    glUseProgram(shader->getProgramId());
    this->transformMatrix->rotate(angle);

    shader->setUniformMatrix3("transform", this->transformMatrix->getPtr());
}

```

I have also tried to debug my GLSL shader to check the gl\_Position . But its shows that my Z-Axis is always zero and W component is always 1. No idea why its getting away from my screen.

# Answer
> 2 votes
The quad is getting further away due to rounding errors in the cumulative matrix operations (it's actually getting scaled down).

You must either normalize the matrix or use a rotation angle variable and recreate the rotation matrix from that variable on every frame.

For the translation you must use `vec3(position.x, position.y, 1.0)` so that your last row becomes the translation.

Setting it to 0.0 multiplies the whole matrix row by 0.0 which nullifies your translation.

Because

```
transform  * vec3(position.x, position.y, 0.0)

```

is the same as

```
transform[0] * position.x + transform[1] * position.y + transform[2] * 0.0

```

# Answer
> 1 votes
After spending whole day i finally found out whats the issue actually. Its really silly of me that its got overlooked at the very first place. So here is the problem :

```
matrix[1][1] = (matrix[1][0] * matrixb[0][1]) + (matrix[1][1] * matrixb[1][1]) + (matrix[1][2] * matrixb[2][1]);

```

Here i am setting matrix\[1\]\[1\] to a new value. But in the next line i need to multiply the matrix\[1\]\[1\] which need the old value

```
 matrix[1][2] = (matrix[1][0] * matrixb[0][2]) + (matrix[1][1] * matrixb[1][2]) + (matrix[1][2] * matrixb[2][2]);

```

So now what i did is i am multiplying the matrix using temporaries again and copy the values over the root matrix.

```
void Matrix3x3::mutliply(const float(&matrixb)[3][3])
{
    float tmat[3][3];

    tmat[0][0] = (matrix[0][0] * matrixb[0][0]) + (matrix[0][1] * matrixb[1][0]) + (matrix[0][2] * matrixb[2][0]);
    tmat[0][1] = (matrix[0][0] * matrixb[0][1]) + (matrix[0][1] * matrixb[1][1]) + (matrix[0][2] * matrixb[2][1]);
    tmat[0][2] = (matrix[0][0] * matrixb[0][2]) + (matrix[0][1] * matrixb[1][2]) + (matrix[0][2] * matrixb[2][2]);

    tmat[1][0] = (matrix[1][0] * matrixb[0][0]) + (matrix[1][1] * matrixb[1][0]) + (matrix[1][2] * matrixb[2][0]);
    tmat[1][1] = (matrix[1][0] * matrixb[0][1]) + (matrix[1][1] * matrixb[1][1]) + (matrix[1][2] * matrixb[2][1]);
    tmat[1][2] = (matrix[1][0] * matrixb[0][2]) + (matrix[1][1] * matrixb[1][2]) + (matrix[1][2] * matrixb[2][2]);

    tmat[2][0] = (matrix[2][0] * matrixb[0][0]) + (matrix[2][1] * matrixb[1][0]) + (matrix[2][2] * matrixb[2][0]);
    tmat[2][1] = (matrix[2][0] * matrixb[0][1]) + (matrix[2][1] * matrixb[1][1]) + (matrix[2][2] * matrixb[2][1]);
    tmat[2][2] = (matrix[2][0] * matrixb[0][2]) + (matrix[2][1] * matrixb[1][2]) + (matrix[2][2] * matrixb[2][2]);

    for (int i = 0; i < 3; ++i)
    {
        for (int j = 0; j < 3; ++j)
            matrix[i][j] = tmat[i][j];
    }
}

```

Now all is working great. Only thing i need to do now is to find a way to optimize my matrix class.

---
Tags: opengl, glsl
---


# Question
Title: What is the Basic Game Screen/Scene Life Cycle?
**Question**

What is the standard or basic game screen/scene life cycle used in most games?

**What is Screen/Scene?**

The term screen or scene refers to the current displayed entity holder where game entities or objects are placed. I personally call it scene because the term screen for me is the hardware screen, but I have read that others call it screen as denoted by Screen Manager classes (I call it Scene Manager).

**Understanding Scene Management and Game Scene Life Cycle**

Here is my current understanding of a simple scene management and game scene life cycle:

Assuming, we have 4 screens/scenes in a basic game:

1. **Splash Scene** \- used to display the company logo, the game logo and loading of most of the game resources used by the menu scene and loading scene.
2. **Menu Scene** \- used to display menus and buttons, referred to as the "main menu" and the gateway to other scenes especially the game scene (sometimes there are settings scene, help scene and about scene).
3. **Loading Scene** \- used to display a progress bar or anything related that indicates the loading and unloading of the game scene.
4. **Game Scene** \- used to display the game logic and implementation of the game itself.

> **start application** ---(load splash scene contents)---\> **splash scene** ---(load menu scene and loading scene contents and unload splash scene contents)---\> **menu scene ("start game" pressed)** ---\> **loading scene** ---(load game scene contents)---\> **game scene ("return to main menu" pressed)** ---\> **loading scene** ---(unload game scene contents)---\> **menu scene**

1. Start Application
2. Load Splash Scene Contents
3. Show Splash Scene
4. Load Menu Scene and Loading Scene Contents
5. Hide Splash Scene
6. Show Menu Scene
7. Unload Splash Scene Contents
8. "Start Game" Button Pressed
9. Hide Menu Scene
10. Show Loading Scene
11. Load Game Scene Contents
12. Hide Loading Scene
13. Show Game Scene
14. THE GAME IMPLEMENTATION
15. "Return to Main Menu" Button Pressed
16. Hide Game Scene
17. Show Loading Scene
18. Unload Game Scene Contents
19. Hide Loading Scene
20. Show Menu Scene

Is this the right way to do it in most cases? I know that the screen/scene life cycle varies depending on the game you are creating. I just want to know if this is the right way to do it or am I doing things the wrong way?

# Answer
The nomenclature here is definitely odd.

I at first thought you were talking about something lower level (like the scenegraph or screen manager for organizing logic flow and/or rendering). I then realized you are talking about what I would refer to as game state.

Scenes are a popular term for it now with Unity, so I could see why you would call it that, although you could have the entire lifecycle of your game in one scene. This can be helpful to remove or reduce loading times.

So terminology aside. This is really all up to personal preference and the scenario you wish to achieve. I would definitely consider what you described as a very classic game state model.

You can obviously feel free to break this mold and try to eliminate loading screens or hard transitions between the game world and the user interface.
> 4 votes

# Answer
Mostly right, but you're missing the in-game overlay menu, which has most of the main menu functionality, such as changing sound, controls, and graphics. The existence of that menu means the "return to Main Menu" becomes "Quit to Main Menu".

"Hide" - "unload" - "delete" order can also be simplified by simply telling a scene to hide itself now, and start to asynchronously unload its contents and delete itself - that's one command instead of 3.
> 0 votes

---
Tags: loading, resource-management, scene, screen-management
---


# Question
Title: How to access a variable from another C# script in Unity
I am working on a simple game project, and have a problem. The problem is accessing the variable from one script to another.

For example :-

I have 2 Scenes (Game Scene and Game Over Scene), Game Scene has a Player Game Object , who has a int Variable Score.

```
using UnityEngine;
using System.Collections;

public class Game_Scene_Script : MonoBehaviour
{
     private int Score ;

     // Use this for initialization
     void Start ()
     {
          Score = 0 ;
     }

     // Update is called once per frame
     void Update ()
     {
          // Let us assume some one played the game
          // And Now the Score is 207
          Score = 207 ;
     }
}

```

Now I want to access that int Variable Score in Game Over Scene which a Game Object.

So how can I access that int Variable from that script?

I searched for, but couldn't find any proper answer I wanted. Even-though some answers are in JavaScript , some are in Unity 4.x etc.

# Answer
# You can't, it's private.

Now, that's not the end of things, as I suspect that wasn't really your question.

Firstly, you need a reference to this script. Which you can get from a reference to the game object this script is attached to. `GameObject.Find()` works sometimes, I don't recommend it, but none the less, once you have the GameObject reference...

```
Game_Scene_Script sceneScript = gameObj.GetComponent<Game_Scene_Script>();
int score = sceneScript.GetScore();

```

Of course, that still means you need to either make the Score public *or* provide an accessor function, `GetScore()`.

```
public int GetScore() {
    return Score;
}

```
> 2 votes

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


# Question
Title: Am I allowed to release an app I developed with Xcode on windows?
I want to develop an app for the iOS app store, but don't want to invest in a mac since they start very expensive. So I considered running Xcode via VMware using OSX Lion on my windows 7 computer. Would it be legal for me to create and sell an app if it was created on windows? Is Apple fine with it? *Selling it on Cydia or other jailbreak stores are not an option.*

# Answer
> 8 votes
It is against the Apple and Mac OS terms of agreement to install Mac OS on anything aside from an Apple authorized machine. You are in breach of your user agreement by doing even that. So app-store stuff aside - you are in legal hot water.

However! Pushing that aside, I'd like to note at least one game has been published with a similar method as the one you have developed. If you see this article you can read about it.

The paragraph I want to quote is:

> "And one final thing to know about releasing to the app store when you make your app on a PC: you REQUIRE a mac to upload the binary to apple.
>
> ITunes Connect used to allow you to upload through http, but no longer. There is a binary uploader program in the iOS SDK that checks and uploads your binary to apple. That uploader program only works on a mac. So while you can build and test the entire app on a PC, you need a mac for 10 minutes to upload your final binary. I’ve seen someone suggest just going to an apple store and using a demo mac to upload. In my case I already had the mac mini, so it wasn’t terribly inconvenient, but it was a real surprise."

They developed on the PC but uploaded on a Mac Mini. But apparently others have uploaded via just a demo computer and done well.

# Answer
> 1 votes
Even though legal advice should not be given here, it is a clean case as was noted earlier: you are not legally allowed to run OS X on non-Apple hardware.

However, to the question can you submit apps to AppStore the answer is yes. You can run OS X in a VM, develop there, send the apps to Apple and everything will be fine. Either Apple doesn't send any information about the machine (just the serial number would be enough to show it's not Apple HW), or they don't care.

So legal issues aside, you don't need a *Mac* to develop and submit, you just need *OS X* to do that. How you get it and run it is in your hands and there are no known cases where Apple would've not allowed an app that had been developed or submitted via OS X in a VM.

And, of course, if you happen to have Apple HW but prefer to run Windows/Linux on it, the legality of running OS X in a VM there is a bit greyer matter. You are running OS X on Apple HW in that case.

# Answer
> 0 votes
Can't run OSX in a VM. You don't need a new Mac though. Just buy some crappy used MacBook off eBay. That's what I did. I only use it to git pull, and then build in Xcode. Works great.

---
Tags: ios, legal, windows, xcode
---


title: Code vs. Configuration in Unity

text:
# Question
Title: Code vs. Configuration in Unity
I know a thing or two about Unity at this point, but I've still lots of subjective, best practice questions, Such as: How do you decide what values are obtained via Start/Awake initialization, and which values are explicitly serialized into the scene? In my current project, game objects and behaviors reference each other in a complex graph. Initially, I did this on Start(), programmatically, with lots of raycasts and GetComponent\<\>() and such. Now though, I just declared stuff public (violating encapsulation?), to simply serialize this information to the scene once generated by an Editor script... Which is more correct? Should my methodology be that anything that *can* be serialized *should* be serialized? Or is it better to write more initialization code which conveys some explanation why the values are what they are?

# Answer
> 1 votes
You're right that this is subjective. You can load your initialization data from literally anywhere. So in my mind, asking about what method you should use is not answerable by anyone other than yourself.

So regarding how you might make that decision, there are a few things to consider.

1. You mentioned encapsulation. I think this is not a concept that should be applied to initialization. The thing about configuring the system is that you are doing the part of programming that can't be abstracted in the academically ideal, OO-software way of doing things. Whether you're embedding it inside a dedicated unity script, reading an external text file, or designing some sort of convoluted dependency injection container, it's important to remember what you're trying to accomplish. That something is: the ugly part of the system. The coupling, the dependencies, the code that ought not be within a well-designed class. You *need* some of that code to make a working system of any type, especially games. But it probably won't be pristine under any circumstances.
2. Serializability: should you be able to move this data outside the code. I would contend that yes, you should. Many reasons. However, as a stop-gap, implementing the data inside a single unity script is not a bad tactic, as long as you can easily update it and/or transition away from it.
3. Explanation: should you have to describe the configuration as you write it. Ideally, no, because configuration data ought not be too complicated to speak for itself. Is that the case? Perhaps you should reconsider what is configurable and what is not. If the configuration is susceptible to error, then those errors ought to be caught by the thing loading the configuration. So that might be a better place to explain the cause of the errors. Or to efficiently report errors back to the configuration author, to inform them of their mistake.
4. What unity callback should run it. I am not a unity expert, but I would doubt that there is an objectively correct answer to this. My intuition is that it does not matter. You should design your unity app to run some sort of startup logic that loads the data, and from there bootstrap itself into a system that runs the game using that data without worrying where it came from. In other words, show a main loading screen that figures it out. Then transition out of that loading screen into your actual game.

---
Tags: unity, state, scene-graph, serialization, initialization
---


title: How Can I Find a Shape on 2D Array?

text:
# Question
Title: How Can I Find a Shape on 2D Array?
For the code in my test project, I want to find `2D[,]` array shape on the `char[][] list`. I created an actual map with '`char[][]`' array. So, how can I find a `tileChar`'s shape on the `worldChar` array?

How to do this in Java, C#, JavaScript, pseudo-code, algorithm or etc.?

For Example;

```
List<string> mainShape = GetRandomShape().Split('#').ToList();
char[][] tileChar = mainShape .Select(a => a.ToArray()).ToArray();
char[][] worldChar = GenerateRandomWorld();

```

Example Image:

'\*' -\> NOT NULL

'-' -\> NULL

# Answer
The solution below utilizes boolean values as opposed to chars as I found them easier to utilize for this solution, but it can easily be modified to support char instead.

The easiest way to perform this test in my mind is to loop through each possible origin point in the world that the shape can possibly fit at. Then, at each of those origin points, loop through each set of indexes in the shape array, testing if the shape matches (for the purposes of this function; if shape\[x,y\] is false or if shape\[x,y\] is true AND world\[x,y\] is true) the world at that point. If the shape matches at that point, continue on to check the other points in the shape, otherwise break the loop so that you can start the check at the next origin point.

```
public static bool doesShapeExistInWorld(bool[,] shape, bool[,] world)
{
    int shapeWidth = shape.GetLength(0);
    int shapeHeight = shape.GetLength(1);
    int worldWidth = world.GetLength(0);
    int worldHeight = world.GetLength(1);
    if (shapeWidth <= worldWidth && shapeHeight <= worldHeight)
    {
        //Enumerate through each possible origin position for shape
        for (int startY = 0; startY < worldHeight - shapeHeight; startY++)
        {
            for (int startX = 0; startX < worldWidth - shapeWidth; startX++)
            {
                //At each origin, test all points in shape against world
                bool shapeExists = true;
                for (int shapeY = 0; shapeY < shapeHeight; shapeY++)
                {
                    for (int shapeX = 0; shapeX < shapeWidth; shapeX++)
                    {
                        shapeExists = !shape[shapeX,shapeY] || (shape[shapeX,shapeY] && world[startX + shapeX,startY + shapeY]);
                        if (!shapeExists)
                        {
                            break;
                        }
                    }
                    if (!shapeExists)
                    {
                        break;
                    }
                }
                if (shapeExists)
                {
                    return true;
                }
            }
        }
    }
    return false;
}

```

I should probably be the first to point out that the above is likely not as optimized as possible, but at least gives a rough starting point.
> 0 votes

---
Tags: c#, java, javascript, game-mechanics
---


# Question
Title: Is my Lua form/scene loading setup efficient?
At the moment, I'm working on a small game project using LUA and the love2d framework. Using this framework, I've made my own assets (i.e. button images, form images, etc), and using these assets I've been able to make a functional application, but not yet a game. In my project, I plan on having several scenes, and I'm not quite sure whether my method for scene management/switching is efficient/safe to use (safe, as in minimal bugs). So the process I'm using is as follows:

```
if scene_selector.active_scene == "splash" then
    if sceneSplash.loaded == false then
        sceneSplash.link.load()
        sceneSplash.link.update(dt)
        sceneSplash.link.draw()
        sceneSplash.loaded = true
    else
        sceneSplash.link.update(dt)
    end
elseif scene_selector.active_scene == "menu" then
    if sceneMainmenu.loaded == false then
        sceneMainmenu.link.load()
        sceneMainmenu.link.update(dt)
        sceneMainmenu.link.draw()
        sceneMainmenu.loaded = true
    else
        sceneMainmenu.link.update(dt)
    end
end

```

where scene\_selector is a link to the follow file:

```
    -- Misc Vars
    active_scene = "splash"
    version = nil

    -- Resources
    cre = nil
    xp = nil

    -- End Vars

    -- Global Script Indicator
    calls = {}
    calls.active_scene = active_scene
    calls.version = version
    return calls

```

and sceneSplash/sceneMainMenu are links to lua files which act as the scenes. Each file manages its own updates, which are passed through by the `main.lua` \- found by the love.update and love.draw functions which are passed through to the forms relevant load/update/draw functions. I'm aiming at using about 10 forms, 3 variable files and 2 misc function files (file management/encryption/IO operations/logging/etc).

So the **TL;DR** version is - is it efficient/safe (safe in terms of minimal bugs) to pass through draw and update functions from main.lua to other lua script files?

So far, the process works without any bugs, even when I go back to a previously accessed 'scene', so I assume the process will work 'safely' when I'm using more scenes.

# Answer
> 0 votes
To answer your question, it's perfectly safe and common to let other functions (in potentially other files) update or draw parts their responsible for (or everything if you'd like that). The important thing to keep in mind is that drawing things to the screen outside of the `love.draw()` function, or functions called from that one, will have no effect, because the screen is cleared before `love.draw()` is invoked in your `main.lua` script.

Now, as to your question about efficiency; all function calls have a *minimal* overhead. Calling functions from `love.update()` or `love.draw()` does not produce any extra overhead when compared to any other function call in Lua.

# Answer
> 0 votes
I'm also "playing" with love2d.

You can spare a bounch of if .. elseif if you use a generic scene like this :

```
if currentScene.loaded == false then
    currentScene.link.load()
currentScene.link.update(dt)
    currentScene.link.draw()
    currentScene.loaded = true
else
    currentScene.link.update(dt)
end

```

changing scene :

```
currentScene.unload() --if you need to releas resurces.. invoce gc .. ecc
currentScene= sceneMainmenu
currentScene.loaded = false

```

---
Tags: lua, love2d
---


# Question
Title: Tile-based collision problem with corners
I am currently making a tile based collision system. But I encountered a big problem I can't seem to figure out.

Use the image bellow for reference.

Gray lines represent the border between tiles. White square is void and grey square is a wall. Purple is a collision box and red lines represent the collision tested.

Fig 1. is the way I'm currently testing for collisions. I test for the tiles adjacent to the box.

Fig 2. is my problem. If the box slightly enters a tile in a corner, the collision will not be tested. I see you coming and tell me to test for diagonal collisions. See Fig3.

Fig 3. If I test for diagonal collisions, then if the box slides along a wall, it will hit the diagonal tile and completely stop (green line)

So I'm not really sure what to do at this point. I tried to look for 2D based tile collision detection and resolution, but nothing I found could solve my problem.

# Answer
> 1 votes
Well, I am pretty sure that the problem is in the anchor point, that you use to control the position of the collision box. To get the results you want, I would recommend considering the 4 corners as anchor points, simultaneously, just like a plane, so, in your code, the collision listener must be fired whenever any point between the corners touches the wall. You can consider the corners as A, B, C, D, and any point between them as a collision bound.

---
Tags: collision-detection, tiles, collision-resolution
---


title: Problem finding correct value for Yaw

text:
# Question
Title: Problem finding correct value for Yaw
I use an Arduino and a 9dof sensor ( gyroscope, accelerometer and magnetometer ) and i'm trying to use the pitch, roll and yaw that the sensor gives me to rotate an object in unity.

I managed to correctly compute pitch and roll ( the z and x axis in unity ) from the accelerometer but it seems that I can't get the Yaw right. By that I mean that when I rotate my sensor pitch or roll it rotates my Yaw too in a weird way.

---

*Code in the arduino to get the heading*

```
void getHeading(void)
{
  heading=180*atan2(Mxyz[0],Mxyz[1])/PI;
  if(heading <0) heading +=360;
}

void getTiltHeading(void)
{
  //float pitch = asin(-Axyz[0]);
  //float roll = asin(Axyz[1]/cos(pitch));
  float pitch = atan( Axyz[0] / sqrt( Axyz[1] * Axyz[1] + Axyz[2] * Axyz[2] ) );
  float roll = atan( Axyz[1] / sqrt(Axyz[0] * Axyz[0] + Axyz[2] * Axyz[2]));

  float xh = Mxyz[0] * cos(pitch) + Mxyz[2] * sin(pitch);
  float yh = Mxyz[0] * sin(roll) * sin(pitch) + Mxyz[1] * cos(roll) - Mxyz[2] * sin(roll) * cos(pitch);
  float zh = -Mxyz[0] * cos(roll) * sin(pitch) + Mxyz[1] * sin(roll) + Mxyz[2] * cos(roll) * cos(pitch);
  tiltheading = 180 * atan2(yh, xh)/PI;
  if(yh<0)    tiltheading +=360;
}

```

*Pitch and roll*

```
    float _Pitch  = (float)(180 / Math.PI * Math.Atan( m_ResultX / Math.Sqrt( m_ResultY * m_ResultY + m_ResultZ * m_ResultZ ) ) );
    float _Roll = (float)(180 / Math.PI * Math.Atan(m_ResultY / Math.Sqrt(m_ResultX * m_ResultX + m_ResultZ * m_ResultZ)));
    float _Yaw = (float)(m_TiltHeadingResult);

```

Don't hesitate to ask for details.

# Answer
The name for this problem is Sensor Fusion, because we're taking readings from multiple sensors, each in some way incomplete or inaccurate, and combining them into a more reliable measure.

---

There are available libraries which help with performing sensor fusion - the RTIMULib for Android seemed to solve OP's problem some years ago, though it appears to no longer be maintained.

---

In the past, I've had good results using a **Complementary Filter** for this task, which is effectively a weighted average. It's not state of the art, but it's straightforward to implement and tune.

The filter retains some internal state frame to frame, which is a representation of the current estimated orientation of the device in space. You can use a world-to-local quaternion for this, but I'll describe it using two vectors:

* **localUp** is a vector in the device's local coordinate frame pointing in the estimated direction of world up (0, 1, 0). (So if the device is upside-down, localUp points toward (0, -1, 0))
* **localNorth** is a vector in the device's local coordinate frame pointing in the direction of world "forward" (0, 0, 1)

Each time we get new sensor data, we integrate it into our estimated orientation. The first step is to build an estimate of how much the device has rotated, according to each sensor, as a vector of radian rotation angles about each axis:

```
Vector3 gyroAngles = gyroscope.rotationalVelocity * dT;
Vector3 accelAngles = Vector3.Cross(localUp, accelerometer.sensedUp - localUp);
Vector3 magnetoAngles = Vector3.Cross(localNorth, magnetometer.sensedNorth - localNorth);

```

A few notes:

* this assumes `gyroscope.rotationalVelocity` is in radians per second, and that `dT` is the number of seconds elapsed since the last integration step (which may differ from your frame's deltaTime if you're running this filter on a separate thread to get more frequent sensor updates)
* `sensedUp` is a calculated value, applying some type of low-pass filter to the accelerometer readings to minimize noise. Ideally, this calculation should discount readings in which the magnitude differs substantially from 1G, as this indicates it's picking up device motion rather than gravity direction)
* `sensedNorth` is a calculated value, low-pass filtered and compensated for magnetometer biases. If you tumble your device around, your sensedNorth readings should ideally trace out a unit sphere centered at the origin. Magnetometer mis-calibration can have a huge impact on the accuracy of the tracking. You may also need to compensate for magnetic inclination (where I am, for instance, the magnetic field points closer to vertical than horizontal)

Now that we have each sensor's estimated rotation from the current orientation, we use a weighted average to combine them into an `angularDelta` vector.

You generally want to give the gyroscope a very high weight (in the ballpark of 90-99%) to make the filter respond immediately to quick movements, while the remaining weight helps rein-in drift from accumulating.

If you detect that the device is accelerating (accelerometer magnitude differing from 1G), you can drop the weighting of the `accelAngles` since they're not trustworthy in motion.

Once we have our averaged `angularDelta`, we use it to derive new estimates for our local Up and North:

```
Vector3 estimatedUp = localUp + Vector3.Cross(angularDelta, localUp);
Vector3 estimatedNorth = localNorth + Vector3.Cross(angularDelta, localNorth);

```

These will in general not be perpendicular or unit length, so we apply a quick error correction before using them to update our orientation state:

```
float error = Vector3.Dot(estimatedUp, estimatedNorth) * 0.5f;

localUp = Vector3.normalize(estimatedUp – error * estimatedNorth);
localNorth = Vector3.normalize(estimatedNorth – error * estimatedUp);

```

Now we're done. For ease of use, we can convert our orientation estimate into a quaternion:

```
Quaternion worldToLocal = Quaternion.LookRotation(localNorth, localUp);
Quaternion localToWorld = Quaternion.Inverse(worldToLocal);

```

One neat trick is that this filter even works for devices with no magnetometer. We just fake a constant magnetometer reading of (0, 0, 1) and assign the magnetometer a very low weight (\<0.1%), keeping our estimated yaw from drifting uncontrollably.
> 2 votes

---
Tags: unity, rotation, motion-control, sensor-fusion
---


# Question
Title: How to pause and unpause the Particular action of a sprite?
My game has a sprite representing a character. When the character picks up an item, the sprite should stop moving for a period of time.

I use CCbezier to make the sprite move, like this:

```
sprite->runaction(x)

```

Now I want the sprite to stop its current action (moving) and later resume it. I can make the sprite stop by using:

```
sprite->stopaction(x)

```

but if I do that, I can't resume the movement. How can I do that?

# Answer
> 1 votes
You could try this:

```
[yourSprite pauseSchedulerAndActions]

```

and to resume

```
[yourSprite resumeSchedulerAndActions]

```

Source: SO thread

If that shouldn't work, another option might be:

```
//pause
[sprite.actionManager pauseTarget:sprite];

//resume
[sprite.actionManager resumeTarget:sprite];

```

# Answer
> 1 votes
Yes, cocos2d-x has a built in way to do this. If you want to pause everything the character is doing you can simply use:

```
  _character->pause();

  _character->resume();

  _scheduler->pauseTarget(_character);

 _scheduler->resumeTarget(_character);

```
* NOTE: this also pauses any actions being performed on the character. If you want to continue the actions, but just pause the animation, do this instead:
* \_scheduler is declared in the Node class, so all classes that inherit from it have access to it

.

---
Tags: cocos2d-iphone, cocos2d, cocos2d-x
---


# Question
Title: Huge performance difference when using drawImage with IMG vs CANVAS
I put together a couple of simple tests that render an image to a canvas. One renders from an IMG, while the other renders from an offscreen CANVAS. You can see the code and results here: http://jsperf.com/canvas-rendering/2

In most browsers rendering from an image is much faster than rendering from a canvas, except in Chrome, where the situation is reversed. Can anyone explain the reason for the differences? After all, we are rendering the same pixel data to the same destination.

# Answer
> 10 votes
OK, I figured it out. Almost. It's actually quite obvious, and I feel a bit dumb for not noticing this right away. When you call `drawImage(src, 0, 0)` without specifying width/height it draws the entire src region, which in this case is much larger (the canvas is 320x420 versus the img at 185x70). So in the canvas case the browser is doing much more work, which explains the slower performance. I' still puzzled by Chrome's *higher* score with the larger src.

```
dest.drawImage(src, x, y) // bad
dest.drawImage(src, x, y, w, h, destX, destY, w, h) // good

```

I've posted an updated version which uses the same regions, and the differences are much closer. http://jsperf.com/canvas-rendering/5

I still can't explain why there is a difference, but it's now small enough that I don't really care.

# Answer
> 4 votes
Chrome is likely to use hardware acceleration.

Create a canvas 240x240 and run your experiment in Chrome then create a canvas 300x300 and do it again. The larger canvas I expect to be faster due to the fact hardware acceleration kicks in after 256x256 and chrome uses software when the sizes are less.

Also it worth pointing out that -webkit-transform:translateZ(0) turns off hardware acceleration.

I haven't tested any of the above; I only know this due to the fact one of the chrome engineers commented on a bug I reported in chrome when you cross the hardware and software threshold by dynamically resizing the canvas from larger to smaller than the 256x256 boundary or vice-versa. The solution to this bug was to turn off acceleration using the translateZ as mentioned above.

In my case, I simply did not allow users to resize less than 256x256.

# Answer
> 1 votes
Sometimes images might be loaded to GPU memory and canvas in host memory. In that case when you draw from image to canvas the image data has to be copied first to host memory and then to canvas.

I noticed that kind of behaviour with Chrome, when I was writing project which loads over 100M pixel images and then reads parts of them to small 256x256 canvas ( http://elhigu.github.io/canvas-image-tiles/).

In that project if I drew directly from image tag to canvas in Chrome, memory always jumped to ~1.5GB when drawing started and then when drawing ended memory was freed again, even that 250 megapixel source image was shown all the time in the page.

I fixed the problem by writing image once to big canvas (same size with image) and then drawing smaller canvas from there (I also threw image away after converting it to canvas).

# Answer
> 0 votes
Can't explain the differences, but I'd disagree with

> And the fact that at least one major browser has the opposite performance characteristic means we need to implement two code paths in our renderers. - alekop

If you look at the results on the js.pref the differences in chrome are fairly subtle. I'd stick with just rendering from an image when possible.

# Answer
> 0 votes
The image's size is 185\*70 but we create a canvas with size, I think this will waste some performance, so I set the offscreen canvas's size same as the image. And the difference is closer.

```
var g_offscreenCanvas = createCanvas(185, 70);

```

http://jsperf.com/canvas-rendering/60

---
Tags: html-canvas
---


# Question
Title: How should I handle quaternion types, in my game engine?
I've recently been coding a quaternion class, for my game engine, and have run into a problem. Firstly, should I be using unit quaternions for my engine? Secondly, should I have the functions automatically normalise the quaternion, or should I leave it to the user?

What are the benefits and detriments for each of the possible options?

# Answer
> 3 votes
If your goal is to have quaternion that expresses rotations, and if you want to do operations with them (for eg. rotation composition by multiplying quaternions or convertion a quaternion to a rotation matrix), they must be unit quaternions, otherwise you may have unexpected results.

Quaternion normalization is a relatively costly operation involving squares and division and then should be avoided whenever possible to save CPU cycles.

Thanksfully, multiplication, for example as it is the most common quaternion operation, results in a unit quaternion when operands are unit quaternions themselves.

I would then recommend to let the user manually call normalization on a quaternion when he knows that the operation may have changed its length.

Hope it helps.

---
Tags: quaternion
---


title: Counter-clockwise angle limit

text:
# Question
Title: Counter-clockwise angle limit
I'd like to limit rotation of an object, so I've written following snippet:

```
if (targetRotation < constraintMin) {
    targetRotation = constraintMin;
} else if (targetRotation > constraintMax) {
    targetRotation = constraintMax;
}

```

It works fine when moving in clockwise direction (big chunk starting right of blue lines), however nothing I've tried works work counterclockwise (smaller chunk between blue lines) because of `Math.PI` -\> `-Math.PI` jump.

Here's working outer angle constraint between -3 and 3. However I'd like to make one between 3 and -3, but cannot think of how to do that.

```
const SPEED = 0.05;
let div = document.querySelector('div');
let targetRotation = Math.PI - 0.1;
let rotation = 0;

const CONSTRAINT_MIN = -3;
const CONSTRAINT_MAX = 3;

function rotate(dt) {
  let deltaRotation = (targetRotation - rotation) % (Math.PI * 2);

  let constraintDiffMin = ((CONSTRAINT_MIN - deltaRotation) + Math.PI * 4) % (Math.PI * 2);
  let constraintDiffMax = ((CONSTRAINT_MAX - deltaRotation) + Math.PI * 4) % (Math.PI * 2);

  //This works for outer angle
  if (deltaRotation < CONSTRAINT_MIN) {
    deltaRotation = CONSTRAINT_MIN;
  } else if (deltaRotation > CONSTRAINT_MAX) {
    deltaRotation = CONSTRAINT_MAX;
  }

  //But how to make it constraint inner angle between MAX and MIN?

  if (Math.abs(deltaRotation) > Math.PI) {
    deltaRotation -= 2 * Math.PI * (deltaRotation / Math.abs(deltaRotation));
  }

  rotation += deltaRotation * SPEED;
  div.style.transform = 'rotate(' + rotation + 'rad)';

  requestAnimationFrame(rotate);
}

document.addEventListener('mousemove', function(e) {
  targetRotation = Math.atan2(e.y - 100, e.x - 100);
}, false);

requestAnimationFrame(rotate);
```

```
div {
  width: 100px;
  height: 30px;
  background: linear-gradient(45deg, #BADA55, red);
  transform: rotate(0);
  margin: 85px 50px 0;
}
```

```
<div>
</div>
```

How can I resolve this?

# Answer
> 1 votes
Although circles are continuous, it's easy to get confused if we forget that a circle is a poor representation of angles.

Your code treats this calculation as distinguishing between two sections, "inside" and "outside", but that doesn't really represent the values.

If you "unroll" the circle to see the angles as more of a number line, you get something like this:

Now you can directly see why "outside" is a strange concept to compute with a single if-then. (Not to say it can't be done, it's just less intuitive.)

In your specific case, with these hard-coded MIN/MAX values, it may be easiest to first compute if the angle is between them (what you call the 'big chunk'/'clockwise direction'). Then, if you want to invert that calculation, do so.

```
// 'inner' being the little wedge in your example
// set this to false if you want to constrain to the bigger chunk
let constrainToInner = true;

// first figure out where it is
let angleIsBetween = true;
if (deltaRotation < CONSTRAINT_MIN || deltaRotation > CONSTRAINT_MAX) {
  angleIsBetween = false;
}

// now decide if it needs to be clamped to one of the CONSTRAINT_???s
if( angleIsBetween === constrainToInner ){
  // then let's clamp by setting it equal to the nearest constraint
  let distanceToMin = Math.abs(deltaRotation-CONSTRAINT_MIN);
  let distanceToMax = Math.abs(deltaRotation-CONSTRAINT_MAX);

  if(distanceToMin < distanceToMax){
    deltaRotation = CONSTRAINT_MIN;
  }
  else{
    deltaRotation = CONSTRAINT_MAX;
  }
}

```

I tested this in C#, though in degrees instead of radians. It should work fine either way.

# Answer
> 1 votes
Instead of limiting it on a circle define a range of motion , for example -30 to +30 degrees. The define the center of the motion on your circle. For example 180 degrees.

Now you can limit the range of motion by keeping the angle between those values.

Simply add the center value to the angle and you're done.

In your example the big arc could be like range -160 to +160 degrees, center 0 degrees. The small arc would be -20 to +20, center 180 degrees.

(Degrees and radians are ofcourse the same in concept but values degrees is easier for examples).

# Answer
> 0 votes
I had exactly the same problem and used this to constrain the rotation of my object to a positive maximum and negative minimum. Maybe this helps.

```
public float RealClamp(float angle, float min, float max)
{
    if (angle > max && angle < 360 - min) {
        if (angle > 180) {
            angle = 360 - min;
        } else {
            angle = max;
        }
    }

    return angle;
}

RealClamp(constrainedAngle, 36, 36)

```

---
Tags: 2d, trigonometry
---


title: Slick2d fullscreen with black bars

text:
# Question
Title: Slick2d fullscreen with black bars
NOTE: I am moving this question here from Stack Overflow because I feel it belongs better on this forum. I am deleting the original question from Stack Overflow.

I'm working on a game in Slick2D and I want to have some versatility with the resolutions I can use for fullscreen. Is there a way to make the game's fullscreen add black bars around the game instead of stretching the game to whatever resolution the graphics card can support for fullscreen? I'm not terribly familiar with openGL so if the only way to fix that requires openGL, I would appreciate some detailed explanation on how to implement the code. Currently I'm using the

```
arg0.setDisplayMode(X_resolution, Y_resolution, true); //arg0 is my AppGameContainer

```

method. But it means I have to stretch my game to one of the compatible resolutions.

# Answer
Just call the render function and draw a filling black rectangle on your screen.

```
public void render(GameContainer arg0, Graphics arg1) throws SlickException {

    arg1.setColor(Color.black);
    arg1.fillRect   (   0.0f,
                        0.0f,
                        gameCon.getWidth(),
                        gameCon.getHeight()
                     );

}

```

Then all you need to do is set up a clipping area for the rest you're rendering:

```
g.setWorldClip((int) x, (int) y, (int) width, (int) height);

```

That way anything outside that area won't be rendered. Voilà!
> 0 votes

---
Tags: opengl, java, slick
---


title: Cocos2d Sprite 3D position

text:
# Question
Title: Cocos2d Sprite 3D position
When I set a position3D for a Sprite in cocos2dx, it render two times the same sprite, i took a screenshot:

I set the position3D because i want to use the Z position the give an effect of distance, but its rendering these two sprites in the lower left corner, how can I fix that?

Here is my code in .h:

```
cocos2d::Sprite* mySprite;
cocos2d::Sprite* mySprite2;
cocos2d::Camera* camera;

```

Here i my code in cpp:

```
bool HelloWorld::init()
{

if ( !Layer::init() )
{
    return false;
}

auto s = Director::getInstance()->getWinSize();
camera = Camera::createPerspective(60, (GLfloat)s.width / s.height, 1, 100);

camera->setRotation3D(Vec3(0, 0, 0));

this->addChild(camera);
mySprite2 = Sprite::create("idle1.png");
mySprite2->setPosition3D(Vec3(5, 0, -41));
mySprite2->getTexture()->setAliasTexParameters();

this->addChild(mySprite2, 2);

mySprite = Sprite::create("idle1.png");
mySprite->setPosition3D(Vec3(-5, 0, -81));
mySprite->getTexture()->setAliasTexParameters();

this->addChild(mySprite, 0);
}

```

# Answer
> 1 votes
You have to set the camera user to something other than DEFAULT because the DEFAULT camera is used for things like UI, Menus and is rendered last.

```
// Camera
auto s = Director::getInstance()->getWinSize();
auto camera = Camera::createPerspective(60, (GLfloat) s.width / s.height, 1, 1000);

// set parameters for camera
camera->setPosition3D(Vec3(0, 400, 400));
camera->lookAt(Vec3(0, 0, 0), Vec3(0, 1, 0));
camera->setCameraFlag(CameraFlag::USER1);
this->addChild(camera); //add camera to the scene

```

So when you create a new camera the deafult camera is set to DEFAULT, and the new camera is also set to DEFAULT initially. So set it to USER1.

---
Tags: c++, 2d, graphics, software-engineering, cocos2d-x
---


# Question
Title: Problem in if statement comparing GameObject name
I am trying to get the name of the game object. for that i used

```
    Debug.Log (gameObject.transform.ToString());

```

in start. My gameObject name is "PowerupItem\_0" and "PowerupItem\_1". in console it displayed the gameObject name correctly. then i tried to execute the statement. so i used

```
    if (gameObject.transform.ToString () == "PowerupItem_0") {
        Debug.Log ("PI_0");
    } else if (gameObject.transform.ToString () == "PowerupItem_1") {
        Debug.Log ("PI_1");
    } else
        Debug.Log ("Oth");

```

for this coding in console it displayed a message as "oth". i am not understanding why its not printing "PI\_0" and "PI\_1". anybody please help

# Answer
> 4 votes
`gameObject.transform.ToString()` gives you with `transform` type. Means `(UnityEngine.Transform)` is also included in `string`. You can get `GameObject's` name simply by calling `gameObject.name`.

# Answer
> 0 votes
Like Hamza Hasan said the `(UnityEngine.Transform)` is also a part of the returned string. Of course you could get the name of the GameObject with `gameObject.name`, but why don't you create a "Powerup\_Item" class with a property "Name"? That would be the better solution in my opinion.

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


# Question
Title: How do I implement a flashlight in SDL2?
I'm a beginner trying to implement a flashlight in SDL2, but can't figure out a good way to do it.

I've found a way to manipulate the background's color; changed it to dark and back to its normal colors, but this isn't the whole solution.

My main goal is a flashlight that follows the player around the map.

I thought about per-pixel drawing, but I think it will result in poor performance. Drawing a black pixel for every pixel on screen, then changing back the to the normal color to all of the pixels surrounding the player.

How do I do this correctly?(BTW, I'm using a 'SDL\_Renderer', not 'SDL\_Surface', i realized this can be a problem when dealing with pixels.)

# Answer
> 1 votes
For a very simple effect just load an alpha image with a white circle in the center and otherwise all black into an `SDL_Texture` and render it centered to your character. Anything inside the white circle will stay visible while the rest will become black.

You could also make the texture animated creating a "candlelight" effect. You could also scale the texture for stronger/weaker lighting. You can create a smooth transition with making the alpha in the image be a radial gradient. You don't even have to make it an image file, it could be generated on init into a `SDL_Surface` then converted to an `SDL_Texture`. just make sure you use the alpha value correctly.

# Answer
> 0 votes
You can use per-pixel drawing in precalc stage of your engine, and then use glTexImage2d to move the data to GPU, and then rest of the rendering primitives can be done quickly in every frame.

So for flashlight, you'd just draw a filled circle first, then negate the bitmap.

---
Tags: c++, lighting, graphic-effects, sdl2
---