# Question
Title: Transform point while keeping other points offset
I have the following situation: I've got a box with its center of mass transform matrix that I'm obtaining from physics simulation, i.e. it keeps changing with time. I've also got two points (actually two transformation matrices) which are static (the simulation doesn't calculate them, neither do I want it to) that I want to 'keep in sync' with the original state (t=0 in the picture).

Any ideas how do I calculate the other two matrices when the center of mass changes, while keeping their original offsets satisfied?

I'm using jBullet for physics.

# Answer
As long as the transformation applied to the center of mass is only composed of rotation and translation (given that it comes from a physics simulation that should be true), that same transformation applied to your two non-simulated points will put them in the same relative position at `t = 0.25` as they were in at `t = 0`.

Most physics engines provide a way for you to get the world transform of a given body's center of mass, either in matrix form or as separate translation and rotation components. For jBullet, that would be the `getCenterOfMassTransform` function.

Construct two `Transform` objects for both of your non-simulated points in their original position. Then use the `mul` method of `Transform` to multiply your non-simulated point transforms by the rigid body's transformation to bring your non-simulated points into the same relative orientation and position as the new center of mass.
> 0 votes

---
Tags: mathematics, matrix, transformation
---


title: How to use touchDown?

text:
# Question
Title: How to use touchDown?
How to use Screen and touchDown?

...

```
    playButton.addListener(new ClickListener(){
        @Override
        public void clicked(InputEvent event, float x, float y) {
            ((Game)Gdx.app.getApplicationListener()).setScreen(new MyScreen());
        }
    });

```

...

```
public class MyScreen extends Stage implements Screen {

    public MyScreen() {
        super( new StretchViewport(320.0f, 240.0f, new OrthographicCamera()) );
    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(1, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        super.act(delta);
        super.draw();
    }

    @Override
    public void show() {
        Gdx.input.setInputProcessor(this);
    }

    @Override
    public void resize(int width, int height) {
        getViewport().update(width, height, true);
    }

    @Override public void hide() {}
    @Override public void pause() {}
    @Override public void resume() {}

    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        Gdx.app.log("MyScreen","touchDown");
        return super.touchDown(screenX, screenY, pointer, button);
    }
}

```

result - empty

why `touchDown` does not fire ?

# Answer
> 1 votes
You've extended Stage and you use it's `touchDown()` method. What you should do is to implement `InputProcessor` to this class and implement it's methods (including `touchDown()`). Also, don't extend the stage that early. Build some apps with a '`Stage` object'.

Here's how your code should look like:

```
public class MyScreen implements Screen, InputProcessor {

    private Stage stage;
    public MyScreen() {

        stage = new Stage();
        // add some actors to the stage if necessery
    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(1, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        super.act(delta);
        super.draw();

        stage.act(delta);
        stage.draw();
    }

    @Override
    public void show() {
        // Your class now becomes the InputProcessor (it will receive events)
        Gdx.input.setInputProcessor(this);
    }

    @Override
    public void resize(int width, int height) {
       getViewport().update(width, height, true);
    }

    // Now you override a method from the inputProcessor, not the stage (and now it will work).
    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        System.out.println("Hello, this is touchdown!")
        return false;
    }

    @Override public void hide() {}
    @Override public void pause() {}
    @Override public void resume() {}

    @Override
    public boolean keyTyped(char character) {
        return false;
    }

    @Override
    public boolean touchUp(int screenX, int screenY, int pointer, int button)
        return false;
    }

    @Override
    public boolean touchDragged(int screenX, int screenY, int pointer) {
        return false;
    }

    @Override
    public boolean mouseMoved(int screenX, int screenY) {
        return false;
    }

    @Override
    public boolean scrolled(int amount) {
        return false;
    }

}

```

**Additional info:**

`Stage` has it's own InputSystem (it extends `InputAdapter`) and also has these methods from `InputProcessor` (like touchdown, clicked etc) BUT! to make this work stage must `act()` because in the `act()` method it takes the inputs from the pool and process them. (you have to simply update the stage calling `act(delta);`).

Technically, what you've done would work, cause you've just created a Stage by creating a MyScreen object (your class extends Stage). You'd just have to call `act(delta);` in `render()` method :)

---
Tags: libgdx
---


title: 2d Tile Movement and Camera

text:
# Question
Title: 2d Tile Movement and Camera
Let's imagine we have a 60x60 grid (where a Tile is 64x64px). Within the viewport there should be 10 tiles. The player object is 32x32px.

To have smooth movement, I have to take delta time in consideration; and do something like:

```
this.player.x += 5 * dt;

```

To calculate viewports:

```
vX = parseInt(this.player.x); - Math.floor(0.5 * 10);
  if (vX < 0) vX = 0;
  if (vX+10 > 40) vX = 60 - 10;

  vY = parseInt(this.player.y); - Math.floor(0.5 * 10);
  if (vY < 0) vY = 0;
  if (vY+10 > 40) vY = 60 - 10;

```

And to render position of player:

```
this.context.rect((this.player.x - vX) * 64, (this.player.y - vY) * 64, 32, 32);

```

However I cannot get the math right.

How can I determine which tiles that should be rendered based on Canvas coordinates, in context to where the Player "actually" is on the tile grid. Basically I want to achieve this: https://stackoverflow.com/questions/11464550/html5-creating-a-viewport-for-canvas

But with smooth movement (and not jumping to one tile at a time).

# Answer
So I've answered your question by creating this repo on GitHub. You can play the game here. Use cursor

**Edit:It had a bug, fixed it. Thank GOD! Added code explanation below**

So the game works like this

* We initialize the game:
    + We set event listeners for controls
    + We load all assets into the game
    + And when all the assets are loaded we start creating the world
* Create the world using the dimensions given & number of tiles specified.
* After the world is created a sprite is created and the game's loop started.
* In the loop:
    + update() and draw() the sprite
        - The update() checks for input and updates sprite `pos.x` and `pos.y` accordingly.
        - The draw() draws the sprite's image onto the player canvas.
    + We then clear the viewport's canvas (This is where the world is drawn. Think of the world as a static background. Anything that moves will have to be drawn on another canvas.) and draw the part of the world canvas that we want.
    + Lastly, we call the loop again.

This is the whole process. Remember that the world canvas is just a background, so any sprite or game element that does't move (e.g. castle walls) should be drawn here (of course adding them as sprite. So that you can, for example, check collisions with the wall).

## How the viewport and character are drawn

We draw the character using two different coordinate objects

* In the first we use the `pos2` object. We use this to draw the character onto the player canvas which is a canvas that tricks the player into thinking that the character is actually in the world and yet he is actually being drawn over the viewport. The player canvas is over the viewport canvas (using css to do that). This object is only used to draw the character not move it around the world. The character is drawn on the center of the player canvas until he reaches near the edge of the world canvas. At this point, we will use the character's world canvas coordinates to draw onto the player canvas.
* The `pos` object holds the character's world coordinates. You can use these for collision checking and movement around the world.

Remember that we don't draw onto the world canvas. This canvas is drawn only once. Drawing of movable sprites (e.g. enemies) should be done either on an enemy canvas, player canvas, or on the viewport canvas (Creating an enemy canvas is the best idea).

## Here's all the code. Use the above explanation to understand it.

```
/* General stuffs */
var can_vPort = document.getElementById('viewport'),
  /* Viewport canvas */
  can_pCanvas = document.getElementById('player'),
  /* Player canvas */
  grid = {
    'width': 60,
    'height': 60
  },
  /* This is in tiles not in pixels */
  tile = {
    'width': 64,
    'height': 64
  },

  viewPort = {
    'width': 640,
    'height': 640
  },
  /* Create world canvas */
  can_world = createElement('canvas', {
    'width': 3840,
    'height': 3840
  }),
  cursor = { /* Arrow keys */
    'rightPressed': false,
    'leftPressed': false,
    'downPressed': false,
    'upPressed': false
  },
  img = {}, /* This is where all images are saved */
  sprites = {}; /* This is where all sprites are placed */

var ctx_vPort = can_vPort.getContext('2d'),
  /* Viewport canvas context */
  ctx_pCanvas = can_pCanvas.getContext('2d'),
  /* Player canvas context */
  ctx_world = can_world.getContext('2d'); /* World canvas context */

function init(key, assets) {
  /* Begin handling key presses */
  document.onkeydown = keyDownHandler;
  document.onkeyup = keyUpHandler;

  /* Load assets. This is very simple, to save time. */
  for (var i = 0, len = assets.length; i < len; i++) {
    var image = new Image();
    if (i !== len - 1) { /* If this isn't the last iteration */
      var str = key[i];
      image.onload = function() {
        // console.log(str)
        img[str] = this;
      };
    } else { /* Now if this is the last iteration */
      var str2 = key[i];
      image.onload = function() {
        img[str2] = this; /* Add the image as a property to img */
        createWorld(grid.width, grid.height, tile.width, tile.height);
      };
    }
    image.src = assets[i];
  }
}

function createWorld(_numTileWidth, _numTileHeight, _tWidth, _tHeight) {
  /* Following for loop makes the world canvas */
  for (var i = 0, len = _numTileHeight; i < len; i++) {
    for (var k = 0, len2 = _numTileWidth; k < len2; k++) {
      var x = k * _tWidth,
        y = i * _tHeight,
        image = img['tile']; /*getImg('tile') ==> Don't know why this failed, but in the interest of time */
      ctx_world.drawImage(image, x, y, _tWidth, _tHeight);
    }
  }
  /* Here we add the sprite, 'player' */
  addSprite('player');

  /* The game starts here */
  requestAnimationFrame(loop); /* Start the game after world is drawn */
}

function loop() {
  /* Do game stuff here */

  sprites['player'].update(); /* Update player sprite position */
  sprites['player'].draw(); /* Draw player at new/old position. I didn't optimize */

  ctx_vPort.clearRect(0, 0, can_vPort.width, can_vPort.height); /* Clear viewport canvas */
  ctx_vPort.drawImage(can_world, (sprites.player.pos.x < 320 || sprites.player.pos.x > can_world.width - 320) ? 0 : (sprites['player'].pos.x + (sprites['player'].width / 2) - 320), (sprites.player.pos.y < 320 || sprites.player.pos.y > can_world.height - 320) ? 0 : (sprites['player'].pos.y + (sprites['player'].height / 2) - 320), 640, 640, 0, 0, 640, 640); /* This is the 'viewport' itself btw. Just read it ou loud, helps when you want to understand what's going on */
  requestAnimationFrame(loop); /* Loop!!!! */
}

function keyDownHandler(event) { /* Handler for keyup events */
  event.preventDefault();
  if (event.keyCode == 39) {
    cursor.rightPressed = true;
  } else if (event.keyCode == 37) {
    cursor.leftPressed = true;
  }
  if (event.keyCode == 40) {
    cursor.downPressed = true;
  } else if (event.keyCode == 38) {
    cursor.upPressed = true;
  }
}

function keyUpHandler(event) { /* Handler for keydown events */
  event.preventDefault();
  if (event.keyCode == 39) {
    cursor.rightPressed = false;
  } else if (event.keyCode == 37) {
    cursor.leftPressed = false;
  }
  if (event.keyCode == 40) {
    cursor.downPressed = false;
  } else if (event.keyCode == 38) {
    cursor.upPressed = false;
  }
}

function createElement(ele, attrObj) {
  /* Create the new Element */
  var element = document.createElement(ele);

  /* Do the following only if attrObj exists */
  if (attrObj) {
    /* Loop through attrObj's properties to set the element's attributes */
    for (var i in attrObj) {
      element.setAttribute(i, attrObj[i]);
      /* attrObj's format:
          {
              'attribute name': "Attribute's value"
          }
      */
    }
  }

  /* Return the new element */
  return element;
}

function Sprite(key) {

  /* Position of sprite in world */
  this.pos = {
    'x': can_world.width / 2,
    'y': can_world.height / 2
  };

  this.pos2 = { /* Sprite's position in player canvas */
    'x': can_pCanvas.width / 2,
    'y': can_pCanvas.height / 2
  };

  this.speed = { /* Speed of sprite */
    'x': 5,
    'y': 5
  };

  /* Use a helper function that returns an object with x and y as it's properties for the above */

  /* Image reference for sprite. */
  this.img = img[key]; /* The image for sprite */
  this.width = this.img.width; /* Width of sprite image */
  this.height = this.img.height; /* Height of sprite image */

  this.draw = function() {
    ctx_pCanvas.clearRect(0, 0, can_pCanvas.width, can_pCanvas.height); /* Clear the whole player canvas (a canvas used to draw the character only */
    /* This makes sure that the camera stops when the character is near the edge of the screen */
    if (this.pos.x < 320) {
      this.pos2.x = this.pos.x;
    } else if (this.pos.x > can_world.width - 320) {
      this.pos2.x = 640 - (can_world.width - this.pos.x);
    } else {
      this.pos2.x = can_pCanvas.width / 2;
    }

    if (this.pos.y < 320) {
      this.pos2.y = this.pos.y;
    } else if (this.pos.y > can_world.height - 320) {
      this.pos2.y = 640 - (can_world.height - this.pos.y);
    } else {
      this.pos2.y = can_pCanvas.height / 2;
    }

    ctx_pCanvas.drawImage(this.img, this.pos2.x, this.pos2.y); /* Draw the character using it's secondary position */
    // console.log(this.pos2.x, this.pos2.y)
  };

  this.update = function() {
    /* Here we check to see if any buttons where pressed and if our character is in the world */
    if (cursor.rightPressed && this.pos.x < can_world.width - this.width) {
      this.pos.x += this.speed.x;
    } else if (cursor.leftPressed && this.pos.x >= 0) {
      this.pos.x -= this.speed.x;
    }
    if (cursor.downPressed && this.pos.y < can_world.height - this.height) {
      this.pos.y += this.speed.y;
    } else if (cursor.upPressed && this.pos.y >= 0) {
      this.pos.y -= this.speed.y;
    }
  };
}

function addSprite(key) {
  sprites[key] = new Sprite(key); /* Add the sprite using the key as a reference*/
}

// document.body.appendChild(can_world); Don't uncomment this. Unless you want to see the whole world as it's rendering

/* The magic begins here */
init(['tile', 'player'], ['tile.png', 'player.png']);

```

If you run the game you'll see a black box (32x32px) in a world filled with 64x64px tiles. And yes, it's a grid of 60x60 tiles. The game runs quick (For me at least) and movement is smooth. Play it here. Use arrows for controls.

I hope this will be helpful to you, peace!

Check the link in my comment below, some really good ideas
> 2 votes

---
Tags: 2d, camera, html-canvas
---


# Question
Title: How to make space invaders destructible scenery and conform it to a shape?
We all like the bases that can be destroyed by chunks being split out,

I originally implemented it by making a rectangle filled with individual squares (2x2 pixel size CANVAS rects) that would collision detect with any bullets (On^2 very inefficient). I am now trying to make the base into a shape instead of a boring rectangle. I also want to perform collections of nearby squares when one is hit so that chunks can be taken of the base, instead of just the part that was hit. (easy to do with a rectangular array)

Is a 2 dimensianal arry still the best way to acheive this? Is there a way to create this array by somehow performing image analysis of a PNG to populate this array? Transparent parts would hold no base item at that \[i\]\[j\].

# Answer
I believe your image holds a clue as to how this could be done in a more efficient way.

Note how the damage on both of those objects results in the same pixels being destroyed.

To achieve a similar effect you could create the objects using a series of overlapping images, mapping a small collision area to each.
> 2 votes

# Answer
You can convert a section of a canvas to an array of color values with `var data = context.GetImageData(x, y, width, height)`. The return value is an object with the fields `width`, `height` and `data`. `data` is an array with four entries per pixel (integer values for red, green, blue and alpha).

You can scan that array, manipulate it and then write it back to the canvas with `context.PutImageData(data, x, y)`.

Note that these methods only work when the canvas is not "tainted by cross-origin data" (contains images loaded from a different domain).

Also note that both methods require to transfer data between GPU RAM and System RAM, which is not very performance-friendly. So you should avoid doing it more often than necessary.
> 1 votes

# Answer
Checkout this post on tuts+ it shows you how to use bitmap images for this.

As in, by using the bitmap image as a mask. So you could have a bitmap image representing the arrays that are destructible. In the above tutorial there's even debris.

You could also checkout this jsfiddle
> 1 votes

---
Tags: collision-detection, html-canvas, terrain
---


# Question
Title: Why do I need an "object reference" to access UnityEngine.Transform.Translate?
Why am I getting this error?

> error CS0120: An object reference is required to access non-static member 'UnityEngine.Transform.Translate(UnityEngine.Vector3)'

---

This is my code:

```
using UnityEngine;
using System.Collections;

public class vectr : MonoBehaviour
{
    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.UpArrow))
        {
            Transform.Translate(Vector3.Forward * variable * Time, deltaTime);
        }
        if (Input.GetKey(KeyCode.DownArrow))
        {
            Transform.Translate(Vector3.Backward * variable * Time, deltaTime);
        }
        if (Input.GetKey(KeyCode.RightArrow))
        {
            Transform.Rotate(Vector3.Right * variable * Time, deltaTime);
        }
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            Transform.Rotate(Vector3.Left * variable * Time, deltaTime);
        }
    }
}

```

# Answer
### Type vs Instance

Consider the following code:

```
float myFloat = 5f;
Transform myTransform = gameObject.transform;

```

You would say that the value of `myFloat` was 5; you *would not* say that the value of `float` was 5. Why is that? `myFloat` is the name I have given to the *instance* of `float` that I then set to `5`. `float` is the *type* I am using, `myFloat` is a reference to the *instance* of that type.

In the same way, `UnityEngine.Transform` is a *type*. It is a structure, *like* a `float` but with greater complexity. If we reference `UnityEngine.Transform`, we reference the *type*, but we do not reference any particular *instance* of that type. We can access `static` fields and methods, but that is about it.

When used in the above example, you need an *object reference* to tell us *what* transform you mean to reference. In this case, I think it is safe to assume that you mean to reference the transform of the game object holding that particular script, which brings us to the next comparison.

---

### `Transform` vs `transform`

In case you have not noticed, so far, you have a `UnityEngine.Transform` and a `UnityEngine.GameObject.transform`. Given that we usually have `using UnityEngine` at the top of our code, we usually reference these as `Transform` and `GameObject.transform`.

`Transform` represents a common component; one that is present on just about every game object. As a result, the `GameObject` class already has a field that references its specific `Transform` component. The *instance* of the `Transform` *type* you want to be referencing, when you intend to move that object.

```
void Update()
{
    if (Input.GetKey(KeyCode.UpArrow))
    {
        transform.Translate(Vector3.Forward * variable * Time, deltaTime);
    }
    if (Input.GetKey(KeyCode.DownArrow))
    {
        transform.Translate(Vector3.Backward * variable * Time, deltaTime);
    }
    if (Input.GetKey(KeyCode.RightArrow))
    {
        transform.Rotate(Vector3.Right * variable * Time, deltaTime);
    }
    if (Input.GetKey(KeyCode.LeftArrow))
    {
        transform.Rotate(Vector3.Left * variable * Time, deltaTime);
    }
}

```

---

### What do we do if we do not immediately have a local reference?

This is not *usually* the case. With *other* components, you are required to create a reference to them, first. This would look something like this:

```
Transform transform;
Rigidbody rigidbody;

void Start()
{
    transform = GetComponent<Transform>();
    rigidbody = GetComponent<Rigidbody>();
}

void Update()
{
    if(rigidbody != null)
    {
        // this object did have a rigidbody; we can reference it here,
        // without risk of a null reference exception. Most non-transform
        // components should be treated in this manner. You should also
        // note that objects may have a RectTransform, not a Transform.
    }
}

```

---

### Further Observation

* You will notice that the *type* keyword starts with a capital letter, while the *reference* name does not. You can see this, especially, the above example. This is common practice, and providing you follow it, gives you a good hint at whether the name points to a *type* or an *instance reference*. `Transform` is the type, `transform` is the object reference.
* You will also notice that most compilers colour the *type* keyword. In the above examples, `Transform` should colour in light or dark blue. This is the same default colour as *Visual Basic* and *MonoDevelop*, to of the most popular compilers for Unity. Colour coding usually implies a specific *keyword*, and will never point to a specific instance, such as the instance of object you intend to reference.
> 1 votes

# Answer
Try this:

```
void Update() {
if (Input.GetKey(KeyCode.UpArrow))
{
    transform.Translate(Vector3.Forward * variable * Time, deltaTime);
}

```

Transform is the name of the class and transform gives you the instance to the Transform of your object. Using 'transform' lets you access the transform component of your gameobject to which the script is attached to. Hope that helps :)
> 3 votes

---
Tags: unity
---


# Question
Title: Sprites in Object Pool spawning and updating, but not rendering
So I've been trying to draw sprites onto the world canvas. These sprites are held in a Group (aka object pool. They are meant to be bullets). They update properly, even go off bounds, but they never render!

The code below creates the engine, then after places a sprite onto the screen. This sprite will then 'shoot' out other sprites (That's where the issue is).

Engine:

```
var NE = (function() {
/* Public Variables */
var t = this;
this.images = {}; /* This is where all the loaded images are saved */
this.sprites = []; /* This is where are sprites are saved */
this.groups = []; /* This is where the groups are saved */
this.anim = ''; /* This is the main animation loop. Uses requestanimationframe to animate rooms */
this.canStart = false; /* Can the game start? Should be set to true when loading finishes */
this.rooms = {}; /* This is where all the rooms are saved. */
this.display = ''; /* Display canvas */
this.world = ''; /* This is the reference to the world canvas on which all the currrent running room's objects will live. */

var toBeLoaded = 0,
    /* Total number of images that need loading */
    isLoaded = 0,
    /* Images that have loaded */
    perLoadedDec = 0,
    /* Percentageloaded in decimal form */
    iDontDoAnything; /* Self explanatory, doesn't do anything */

this.Group = function(numEle, key, layer /*, obj*/ ) {
    /* Make sure theres an object value */
    /*if (obj === undefined) {
        obj = Sprite;
    }*/
    this.children = [];
    this.reloadTime = 0;
    this.isReload = false;
    /* Create array children with length numEle. The objects used will be obj */
    this.init = function() {
        for (var i = 0; i < numEle; i++) {
            this.children[i] = t.sprites[t.sprites.push(t.addSprite(key, 100, 100, false)) - 1];
            // this.chilldren[i].groupName =
        }
    };

    /* Create a getFirstAlive() that checks for the first 'alive' element in the children[] and returns it */
    this.getFirstAlive = function() {
        var l = this.children.length;
        for (var i = 0; i < l; i++) {
            if (this.children[i].alive) {
                console.log(this.children[i])
                return this.children[i];
            }
        }
    };

    this.getFirstDead = function() {
        var l = this.children.length;
        for (var i = 0; i < l; i++) {
            if (!this.children[i].alive) {
                return this.children[i];
                break;
            }
            if (i >= l - 1) {
                console.log('There are no more sprites');
                if (!this.isReload) {
                    // this.setAllAliveAfter();
                    // this.isReload = true;
                }
            }
        }
    };

    /* Create setAllAliveAfter(ms) which will set all children elements to alive after specified ms value. If none is given it happens immediately */
    this.setAllAliveAfter = function(ms) {
        var l = this.children.length;
        var ms = ms || this.reloadTime;
        console.log('Starting reloading')
        for (var i = 0; i < l; i++) {
            if (this.children.alive) {
                break;
            } else {
                if (i >= l - 1) {
                    setTimeout(function() {
                        for (var i = 0; i < l; i++) {
                            this.children[i].alive = true;
                            if (i >= l - 1) {
                                console.log("done reseting")
                                this.isReload = false;
                            }
                        }
                        console.log('reloaded!')
                    }, ms); /* END SetTimeout */
                } /* END if */
            } /* END else */
        } /* END forLoop */
    };

    /* Set attribute for all objects in group */
    // debugger;
    this.setAttr = function(attr, value) {
        for (var i = 0; i < this.children.length; i++) {
            this.children[i][attr] = value;
        }
    };

    t.groups.push(this);
    this.groupLength = (t.groups.length - 1 > 0) ? t.groups.length - 1 : 0;
    console.log(t.groups[this.groupLength]);
    return t.groups[this.groupLength];
}

this.Sprite = function(layer, key, x, y, isAlive) {
    /* Sprite Class */
    var spr = this;
    this.pos = t.Point(x, y);
    this.mass = 1;
    this.force = t.Vector();
    this.velocity = t.Vector();
    this.acceleration = t.Vector(this.force.x / this.mass, this.force.y / this.mass);
    // this.baseSpeed = t.Vector(170, 170);
    this.layer = layer || t.world; /* The layer onto which to draw this sprite */
    this.canvas = this.layer.canvas; /* The layer's canvas */
    this.ctx = this.layer.ctx; /* The layer canvas' drawing context */
    this.img = new Image(); /* The sprite's main image */
    this.img.src = t.images[key].src;
    this.group = undefined; /* This is the group to which this sprite controls */
    this.rotImg = undefined; /* The rotated version of the main image. To be used when rotating towards mouse/Vector */
    this.doIRotate = undefined;
    this.rotAngleRad = undefined; /* This is the angle between mouse and sprite */
    this.isClickable = false; /* Whether the sprite is clickable */
    this.acceptsClickEv = false; /* Whether the sprite accepts mouse click events or not*/
    this.mouse = t.Point();
    this.alive = isAlive || false; /* Whether the sprite should be drawn onto the world */
    this.checkOutOfBounds = false; /* Check if the out of bounds */
    this.killOutOfBounds = false; /* If out of bounds then kill the sprite */

    this.init = function() {
        /* Create the drawer canvas */
        // debugger
        this.drawer = undefined;
        this.cW = 0;
        this.cH = 0;
        this.imgW = this.img.width;
        this.imgH = this.img.height;
        // console.log('canvas width ' + this.cW + '. canvas height ' + this.cH + '. image width ' + this.imgW + '. image height ' + this.imgH + '.');
        /* Find dimensions for canvas */
        this.cW = (Math.sqrt(sqr(this.imgW / 2) + sqr(this.imgH / 2))) * 2;
        // console.log(this.cW + ' is hypotemus');
        this.cH = this.cW;
        this.imgOnDrawerX = 0 - (this.imgW / 2);
        this.imgOnDrawerY = 0 - (this.imgH / 2);
        // console.log('canvas width ' + this.cW + '. canvas height ' + this.cH)
        this.drawer = t.createCanvas(this.cW, this.cH, '0');
        this.drawer.ctx.translate(this.cW / 2, this.cH / 2);
        if (this.alive) {
            t.renderCanvas(this.drawer, this.img, this.imgOnDrawerX, this.imgOnDrawerY);
            t.renderWorld(this.drawer.canvas, this.pos.x, this.pos.y);
        }
        /* END Create the drawer canvas */

        /* Event Listeners */
        this.handleClick = function(m) {
            if (this.doIRotate) {
                this.setMouseToPointAngle(m);
                this.rotationInit(this.drawer);
            }
            this.customHandleClick(m);
        };
        this.handleSpriteClicked = function(m) {
            /* Handle collision between mouse and sprite */
        }
    };
    this.kill = function() {
        /* This will remove sprite from world canvas */
        if (this.alive) {
            this.alive = false;
            this.pos.x = 0;
            this.pos.y = 0;
            this.velocity = t.Vector(0, 0);
            this.acceleration = t.Vector(0, 0);
        }

    };
    this.outOfBounds = function() {
        if (this.checkOutOfBounds) {
            var x = this.pos.x,
                y = this.pos.y,
                cW = this.canvas.width,
                cH = this.canvas.height;
            if (x < 0 || y < 0 || x > cW || y > cH) {
                if (this.killOutOfBounds) {
                    this.kill();
                    console.log('Yay killed!')
                }
                return true;
            } else {
                return false;
            }
        }
    }
    this.render = function(a) {
        /* This will place sprite onto x,y position and then draw it */
        if (!this.outOfBounds()) {
            this.alive ? renderWorld(this.drawer.canvas, this.pos.x, this.pos.y) : 'a';
            // console.log(this.alive)
        }
        // console.log('Rendering!!' + this.group)
    }
    this.update = function(dt) {
        /* This is the update function */

        this.velocity.x += this.acceleration.x * dt;
        this.velocity.y += this.acceleration.y * dt;
        this.pos.x += this.velocity.x * dt;
        this.pos.y += this.velocity.y * dt;
        this.outOfBounds();

    };
    this.reset = function(x, y) {
        /* Bring a sprite back to life. Set alive to true */
        this.alive = true;
        this.pos.x = x;
        this.pos.y = y;
        console.log('Ive been reset!!')
    };

    if (this.alive) {
        this.init();
        this.render();
    } else {
        this.init();
    }
    t.sprites.push(this);
    return t.sprites[t.sprites.length - 1];
}
this.Sprite = Sprite;

function Room(obj) {
    this.create = obj.create;
    this.update = obj.update;
    return this;
}

this.mainGame = function(room) {
    var lastUpdate;
    room.create();
    var l = this.sprites.length;

    function loop() {
        stats.begin();
        var now = window.Date.now();

        if (lastUpdate) {
            var elapsed = (now - lastUpdate) / 1000;
            lastUpdate = now;

            // Update all game objects here.
            room.update();
            for (var i = 0; i < l; i++) {
                if (this.sprites[i].alive) {
                    this.sprites[i].update(elapsed);
                }
            }
            // ...and render them somehow.
            t.render();
        } else {
            // Skip first frame, so elapsed is not 0.
            lastUpdate = now;
        }
        stats.end();
        // This makes the `loop` function run 60 frames per second (or slower, depends on monitor's refresh rate).
        t.anim = window.requestAnimationFrame(loop);
    }
    loop();
};

this.renderCanvas = function(layer, img, x, y) {
    var canvas = layer.canvas,
        ctx = layer.canvas.getContext('2d');

    /* Draw image onto the canvas at position (x,y) */
    ctx.drawImage(img, x, y);
};
this.renderWorld = function(img, x, y) {
    renderCanvas(this.world, img, x, y);
};
this.clearCanvas = function(layer) {
    var c = layer.canvas,
        cx = layer.ctx; /* Get the canvas and context of the layer onto which we draw onto */
    cx.clearRect(0, 0, c.width, c.height); /* Clear the layer */
};
this.clearWorldCanvas = function() {
    clearCanvas(this.world);
};
this.render = function() {
    /* Render all the layers now */
    clearWorldCanvas();
    var l = this.sprites.length;
    for (var i = 0; i < l; i++) {
        this.sprites[i].render();
    }
};
this.addSprite = function( /*layer,*/ imgKey, x, y, isAlive) {
    return spr = new this.Sprite(this.world, imgKey, x, y, isAlive);
    // return spr;
};
this.addGroup = function(numEle, key, layer) {
    var grp = new this.Group(numEle, key, layer);
    grp.init();
    return grp;
};
/* ./Public Functions */

return this;
})();

```

main.js:

```
/* Thank YOU GOD for this code and may YOU Bless it
Col 3:23 "Whatever you do, work at it with all your heart, as working for the LORD, not for human masters" */

// All rights reserved by Kitanga Nday
var keyArray = [
    'box'
],
srcArray = [
    'img/box.png'
];

NE.init('displayCanvas', 700, 400, keyArray, srcArray);
NE.addRoom('room', {
    create: function() {
    var t = this;
    // debugger;
    this.spr = NE.addSprite('box', 10, 10, true);
    this.spr.doIRotate = true;
    this.spr.acceptsClickEv = true;
    this.bulletPool = NE.addGroup(40, 'box', NE.world);
    console.log(this.bulletPool);
    this.bulletPool.setAttr('checkOutOfBounds', true);
    this.bulletPool.setAttr('killOutOfBounds', true);
    this.bulletPool.setAttr('alive', false);
    this.bulletPool.reloadTime = 2000;
    this.spr.group = this.bulletPool;
    this.spr.customHandleClick = function(ev) {
        /* Take first alive element from bulletpool and reset on this sprite ==> spr. */
        var bullet = this.group.getFirstDead();
        // console.log(this.group);
        bullet.reset(this.pos.x + 20, this.pos.y + 20);
        bullet.applyImpulse(NE.Vector(10, 10));
        /* Give a speed relative to the normalized vector of mouse position. */

    }
},
update: function() {
    // this.spr.velocity = {x:0,y:0};
}
});
NE.startRoom('room');

```

The html code:

```
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Blank</title>
<meta name="description" content="Game" />
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1" />
<link rel="stylesheet" href="main.css" />
</head>
<body>
<div id="displayCanvas"></div>
<script src="NDAY13ngine.js"></script>
<script src="main.js"></script>
</body>
</html>

```

# Answer
The issue was in the sprite's `init` function.

Aparently, I started the drawing functions only if the sprite was alive. Since my sprite's image was drawn on a canvas, and fed to the main canvas, there was no image to draw.

To fix it, I had to set all children in the sprite to dead (aka `this.alive = false`).

```
if (this.alive)
{
    t.renderCanvas(this.drawer, this.img, this.imgOnDrawerX, this.imgOnDrawerY);
    t.renderWorld(this.drawer.canvas, this.pos.x, this.pos.y);
}

```
> 0 votes

---
Tags: javascript, html
---


# Question
Title: How to access the component of a child object inside another child object using a tag?
As the question above, I need to access the collider component of a child object that is inside its parent object which is also a child to its parent object. I tried this line of code below but it only detects the first child object in a hierarchy. Since I have the same name for each child, I need to access all of them using a tag instead. Any help would be appreciated

```
GameObject.FindGameObjectWithTag("Level").transform.GetChild(1).gameObject.transform.Find("Platform").gameObject.GetComponent<BoxCollider2D>().enabled = false;

```

# Answer
> 0 votes
Silly me, I just have to use this code at Start() instead since I'm searching the child objects with tag. Problem solved.

```
foreach (GameObject gameObject in GameObject.FindGameObjectsWithTag("Platform"))
    {
        gameObject.GetComponent<BoxCollider2D>().enabled = false;
    }

```

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


# Question
Title: Unity - Where should downloaded level data be stored?
I've been looking around and it appears suggestions are only to store data to UserPrefs, or PersistentDataPath.

I intend to have map files streamed to the client on demand, and saved for reuse. UserPrefs seems inappropriate for large blobs. PersistentDataPath is per computer user, thus duplicating data and space usage. I believe Program Files has access restrictions too.

What are the current best practices for storing runtime data that meet the following criteria?

* Is shared across user accounts to avoid wasting disk space.
* Doesn't require elevated permissions.
* Doesn't annoy the user (such as data being placed in My Documents).
* Can be modified at any time.

# Answer
I don't think placing game related files in `My Documents/My Games/` annoys users, it's pretty much standard to put it there so why don't you do it? Each user can have it's own save games, skins and mods this way and it's easy accessible/mod-able.

However, for larger assets you do want to consider to share them amongst user accounts. I think you have two options:

* `Users/Public/` isn't tied to a specific account and can be used for this.
* Store it locally like in a `Data/Maps` folder within your main game folder.

Apart from that, I think map data should in most cases not be all that large. Maps should just be a bunch of numbers like ID's and positions so unless it are huge dynamic worlds it won't really matter to have duplicates on rare occasions stored on the same HD.
> 4 votes

# Answer
I reccomend you use regular System.IO with the System.IO.Environment class. You can store to Local Appdata. The Environment class provides functions like the SpecialFolder enum or the GetFolderPath method to get the place to store data. This actually works pretty well as it gets the correct AppData folder for each operating system(on Windows it is Appdata/Local). You can then create your own folder in there for your game(if it doesn't already exist), You can store anything you need there: Settings, Levels, Scores, etc.
> 0 votes

# Answer
Upon much research, I've decided ProgramData is the best place. It's made for common data between users for a program (as opposed to the per-user AppData). I'll save per-user to AppData, and saves to %USER%/Saved Games.

I should have mentioned that these files aren't necessary to keep around, they're more of a cache. I shouldn't have mentioned 'My documents', as that's not shared between users at all anyway. I don't consider game data to be a document.

Unfortunately, it's a semi-protected directory where you can't modify a file that was created by another user.

Mono 2, which Unity uses, doesn't implement the appropriate classes for modifying permissions. I've had to resort to PInvoke/Native plugins.

I know the maps won't be large, but I'm not going to use that as an excuse for not doing things properly. Users/Public just seems like abuse.

Edit: You could do it without permissions, using a cyclic system. User1 saves to "A.txt", if the file needs changing, and User2 logs in next, User2 saves to "B.txt". When User1 logs back in, "A.txt" could be deleted, etc.
> 0 votes

---
Tags: unity, data, file, path
---


title: Pathfinding in non-quantized space?

text:
# Question
Title: Pathfinding in non-quantized space?
Pretty much whenever anyone thinks about pathfinding, they think about algorithms like A\* and DFS - graph search algorithms, which also just so happen to work as pathfinding algorithms when you quantize the space you're pathing in into a graph.

What if that's not an option, though? Are there efficient pathfinding algorithms that work in space that hasn't been split in to chunks? The "left hand rule" is one example; walk forward and when you hit a wall, turn left - but there's plenty of situations where that won't ever find the target. Are there others like that?

# Answer
Typically you would generate a visibility graph and perform pathfinding on that. Refer to this excellent page on map representations by amitp.

Given an open space with polygonal obstacles, the shortest path between any two points is either:

* directly from start to finish, or
* touches the boundaries of at least one of these obstacles

So if you generate a visibility graph, made up of the edges of all these obstacles and connected together based on visibility, any shortest path can be found using that graph. It looks something like this:

See how the shortest path touches some edges and corners, and the shortest path is completely within the visibility graph. This is a result that can be proven but it's pretty intuitive anyway.
> 6 votes

# Answer
As you suggest: Discrete (quantized) approaches like BFS, DFS, Dijkstra, A\* etc. are typically used with traditional graphs, which form a discrete space.

For continuous (non-quantized) spaces, hill climbing suits better. Continuous (top) vs discrete:

That is, you can take a floating point space like this:

...and move intelligently across it, i.e. perform pathfinding, without needing individual quanta, i.e. nodes or cells. Note that the wireframe shown here exists only to indicate continuous values at that point as defined by `f`, not any kind of *discrete topology*. That is, there are infinite values available between every pair of grid lines (i.e. it is a real space).

We can see an example of hill climbing here:

The algorithm is a simple one: find the closest point where the value is higher than the current point, and go there. This is simple enough in a static environment such a set of walls or mountains on a 2D plane.

But how does this relate to, say, seeking an enemy agent in a game? Agents can release/diffuse a scent on every update that creates a "hill" around them that follows them around, and allows others to seek them in that space. You can learn more about this by looking into collaborative diffusion.

**Alternative**

You can use classification, or "step" / quantise a continuous space (in 2 or 3 dimensions, this is but a 1D example):

```
float continuous = ...; //some floating point value in range 0..1 with precision down to n decimal places
int numSteps = 5; //some arbitrary integer value
int steppedInt = continuous * numSteps;
float steppedFloat = steppedInt / numSteps; //will be e.g. 0.0, 0.2, 0.4, 0.6, or 0.8

```

...Then operate on it using traditional discrete algorithms like A\*.
> 2 votes

---
Tags: algorithm, path-finding
---


# Question
Title: Libgdx game crashes on some devices without any Errors / Logs
I'm making a similar game to the talking tom game where a character is animated on the screen and talks back.

I have about 100 transparent PNGs for each animation. There are 10 Animations. Each PNG has been compressed to the max, max file size is 30KB.

I've been having issues with memory management before ( fixed it ), but this is what I've tried before :

* **Loading all PNGs into the assets manager on splashscreen :** Takes too long to load, crashes at the end of the loading, no errors, no log.
* **Packing all the PNGs into atlas files :** Each PNG is 480\*800, so I get about 5 pages of 2048\*2048 atlas files for each. Takes too much time to load in the Assets manager, and same as before, crashes with no errors.
    + **I can't make the PNGs smaller in dimensions**, please don't suggest that.
    + **I don't want to use GIFs or Videos for the animations**.

What has worked for me is using a timer, no assets manager, and just loading whatever frame I need. It's working great on the 3 Android phones I have at my house + Friends, but they're all modern Samsung & Nexus devices. I've also tested on a few emulators, and it's working just fine.

I published the game a few days ago, and I'm getting some reviews about the game crashing right away, and since there is no errors or log to be reported, I'm not sure how to reproduce the issue or debug it.

Here's the code of my Actor that takes care of the animation :

public class AnimActor extends Actor {

```
private SpriteBatch batch;
private TextureAtlas textureAtlas;
private Sprite sprite;
private int currentFrame = 1;
private int TotalFrames ;
FileHandle[] filesxx;
String currentFolder;
Boolean currentLoop;
float stateTime;
TalkerGame Game;
AssetManager assets_manager;
String[] fileList;
TextureRegion tex1;
Texture tex = null;
Timer Timerx = null;
Timer.Task TheTask = null;
public AnimActor(TalkerGame talkerGame, AssetManager manager)
{
    Game = talkerGame;
    assets_manager = manager;
    batch = new SpriteBatch();
    sprite = new Sprite();

    float scale = (float)( (float)Gdx.graphics.getWidth() / (float) (480));

    sprite.setPosition(0, 0);
    sprite.setBounds(0,0,(float)Gdx.graphics.getWidth() ,(float)Gdx.graphics.getHeight() );
//    sprite.setScale(scale);
}

public void PlayAnimation(String FolderName,Boolean loop)
{

    currentLoop = loop;
    currentFolder = FolderName;
    currentFrame = 1;
    //String[] fileList = new String[0];
    ArrayList<String> FileListArray = new ArrayList<String>();
    final String Path = FolderName + "/";

     filesxx = Gdx.files.internal(Path).list();
    for (FileHandle file : filesxx) {
        // do something interesting here
        if( !file.name().contentEquals("icon.png") && file.name().contains(".png") )
        {
            FileListArray.add(file.name());

        }
    }

    Collections.sort
            (FileListArray, String.CASE_INSENSITIVE_ORDER);
    fileList = FileListArray.toArray(new String[0]);

    // Get all files in Folder

    TotalFrames = fileList.length-1;

    if(TheTask != null)
    {
        TheTask.cancel();
    }
   TheTask = new Timer.Task() {
        @Override
        public void run() {
            currentFrame++;
            if ((currentFrame > TotalFrames) && (currentLoop == false))
            {
                // Play Idle
                PlayAnimation("idle", true);

                currentLoop = true;
                currentFolder = "idle";

                // Stop Music if was playing
                Game.StopMusic();
                // Start/Restart Recording
                Game.StartInterfaceRecord();
            }
            if ((currentFrame > TotalFrames) && (currentLoop == true))
            {
                currentFrame = 1;
            }

           /* if ((currentFrame > TotalFrames))
            {
                currentFrame = 1;
            }*/
            sprite.setRegion(getNextRegion(currentFrame));
        }
    };

    if(Timerx != null)
    {
        Timerx.stop();
        Timerx.clear();
    }
    Timerx = new Timer();
    Timerx.schedule(TheTask, 0, 1 / 30.0f );

}

public TextureRegion getNextRegion(int CurrentFramex)
{
   // System.gc();

    String file_name = fileList[CurrentFramex]; //  String.valueOf(CurrentFramex)+".png";
    if(tex!=null)
    {
      //  Game.aInterface.Log("Disposing Texture");
        tex.dispose();
    }
    String num = "0";
    if(CurrentFramex <10)
    {
        num = "00";
    }
   // System.gc();
    FileHandle file = Gdx.files.internal(currentFolder+"/"+file_name);
        tex = new Texture(file);
        TextureRegion tex1= new TextureRegion(tex);
    return tex1;
}
@Override
public void draw(Batch batch, float parentAlpha) {
    // TODO Auto-generated method stub
    sprite.draw(batch);

}

@Override
public void act(float delta) {
    // TODO Auto-generated method stub
    super.act(delta);

}

public String getCurrentFrameFile()
{
    return currentFolder+"/"+fileList[currentFrame];
}

public void dispose(){
    batch.dispose();
    sprite.getTexture().dispose();
}

```

}

Thanks

# Answer
*As I can see, you probably think that if your image takes 30kb on disk it will allocate 30kb of RAM - **it won't!***

Classic 32 bit PNG file (with transparency) has 4 values - R (255 combinations), G (also 255), B (255) and A - alpha (also 255 combinations). It's for one single pixel.

255 is one byte so one single pixel takes 4 bytes of RAM.

*Now let's calculate:*

You have 5 2048x2048 images - each of them is loaded to the memory. one image 2048 * 2048 gives you 4,194,304 (4 million) pixels, each pixel takes 4 bytes of memory so we have to multiply by 4 which gives: 4,194,304 * 4 = 16777216 (nearly 16 million bytes). Let's convert it to megabytes:

16777216 bytes = 16 MB of ram - this is still one atlas!

You have 5 images = 16MB * 5 = 80MB of RAM

Now let's assume that you have other .png images, so you've already allocated 100 mbytes of RAM.

Now, GDX allocates some memory on itself (without any assets) so you have ~120 mbytes of RAM allocated.

Do you get it? :D

You've already allocated at least 120 MB of RAM. Android device can't stand this much. For example:

Hearthstone game uses ~54 MB of RAM (on Galaxy S5 and J7) and they have all of these cards graphics, particle effects etc. 100 mbs of RAM for a normal device these day is MAX.

There's only one solution for you: .png compression to .etc1. It will remove transparency from your images, but instead of 120 mbytes of ram you'll end with 30mb allocated.

Read here: https://github.com/libgdx/libgdx/wiki/Texture-Compression

**Use transparent PNGs only when you really need them - transparent.equals(death).**

ps. Remember. If you make your image non-transparent it won't make your compression. You have to use the LibGDX guide and use a tool like ImageMagick to convert your images to .etc format and then load them normally to an app.
> 3 votes

---
Tags: android, libgdx, memory-efficiency
---


# Question
Title: DirectXTK C++ : How do you use the Spritebatch.Draw() function with overloaded for RECT?
I am trying to make use of the DirectXTK's SpriteBatch for the C++ version on github. Which is heavily based on the one for XNA. However I can't seem to get the darned thing to work properly.

I have no idea how to fill in the data for RECT. And the closes thing I have found was in SimpleMath::Rectangle.

SimpleMath::Rectangle appears to have a number of overloads to accommodate RECT, however using it as an argument apparently results in visual studios giving a really vague error. Something about their being no overloads to support it.

# Answer
RECT is the classic Win32 rectangle structure documented on See MSDN

```
typedef struct _RECT {
  LONG left;
  LONG top;
  LONG right;
  LONG bottom;
} RECT, *PRECT;

```

It provides the left,top corner and the right,bottom corner pixel location.

`Rectangle` should be able to convert to `RECT` implicitly, but only if you have `using DirectX::SimpleMath;` to pull it into the namespace.

I cover using RECT for `SpriteBatch` in the sprites tutorial.
> 1 votes

---
Tags: xna, c++, directx
---


# Question
Title: What kind of algorithm can be used to have a random selection of question, just like in a quiz game?
We were trying to create a mobile game using Unity 5, and we don't have any idea for what kind of algorithm we're going to use.

Our game is like a logic quiz game, and we want the questions to be randomly picked for the users, in order to enhance their thinking.

What kind of algorithm can be used to have a random selection of question, just like in a quiz game, using Unity 5?

# Answer
> -1 votes
It's quite a big question.

**Short answer.** Assign every question a random number, sort the question list, take the top 5.

**Long answer.** Do as above, remove questions from the list that have been asked in the last N days to stop repeats

**Longer answer.** Ascertain if the question was good or not (Wheel of fortune asks for a thumbs up / down) and feed this into the ranking selection so popular questions are more likely to be asked.

---
Tags: unity, random
---


# Question
Title: GameMaker: how to let the game run as fast as it is able to?
I am making a game/simulator where I want the game to, upon command, run as fast as the computer can handle, that is to say, if the game can run at 60 fps, don't run at 30 fps.

What should I do to make the game do that and would this even make sense?

(Note: when I looked at the built-in variable `fps`, I often see the value to be higher than the room speed I set, so I thought that maybe I can allow the game to run faster than the room speed initially set.)

# Answer
No, Game Maker runs at a fixed timestep.

`fps` will show how many steps the computer is able to handle up to the room's speed. `fps_real` is measured in CPU cycles.

What you want to have is a semi fixed timestep, which Game Maker doesn't support. (You know how much the variables needs to be changed per second, but don't care how many times your loop runs in a second)

Reference: fps and fps\_real
> 1 votes

---
Tags: game-maker
---


title: No LWJGL in java.library.path

text:
# Question
Title: No LWJGL in java.library.path
Okay, so I know I need to set the path to the native files. I can do this in Eclipse, by going to the VM arguments and using -Djava.library.path=, but when I export, it says that the VM arguments aren't kept after exporting, but it can be set in the console while running it. I am running Mac OS X. How do I set that using Terminal?

# Answer
> 2 votes
It should be exactly the same, just provide -Djava.library.path="your\_path" to java when you run it:

```
java -Djava.library.path="your_path" -classpath "your_classpath" your.main.Class

```

# Answer
> 0 votes
I just wrote a nifty way to solve this problem, without needing to define the library beforehand. Which is more useful when you actually deploy your game. Basically it goes like this:

1. Detect OS and architecture
2. Copy LWJGL native binaries from inside your .jar file to game directory
3. Dynamically set library path for Java to the natives folder in your game directory
4. Continue with the rest of your game loading

This needs to happen first thing. So at the beginning of your `main` function goes:

```
loadNatives(getPlatform());

```

Then you have your `getPlatform()` function (**step 1** from above), you can get the OS details like so:

```
String OS_Arch = System.getProperty("os.arch").toLowerCase();
String OS_Name = System.getProperty("os.name").toLowerCase();

```

Use those to return an enum that defines your OS and architecture, i.e. `Win_X86`.

Then you load your natives that are packaged in your .jar file (**step 2** from above). Depending on the OS and architecture you'll load certain files from the LWJGL native binaries. For example `Win_X86` would be something like:

```
String path = Main.class.getProtectionDomain().getCodeSource().getLocation().getPath();
copyFileFromJar("/assets/native/windows/jinput-raw.dll",
  path + "/native/jinput-raw.dll");
copyFileFromJar("/assets/native/windows/jinput-dx8.dll",
  path + "/native/jinput-dx8.dll");
copyFileFromJar("/assets/native/windows/lwjgl.dll",
  path + "/native/lwjgl64.dll");
copyFileFromJar("/assets/native/windows/OpenAL32.dll",
  path + "/native/OpenAL32.dll");

```

Where `copyFileFromJar()` just makes an input stream and an output stream, then streams until it can stream no more. The input stream is from the native file in your .jar and the output is the destination file (which probably needs to be created first!)

Finally, tell Java about this new library resource (**Step 3** from above):

```
System.setProperty("java.library.path", path + "native/");
Field fieldSysPath = ClassLoader.class.getDeclaredField("sys_paths");
fieldSysPath.setAccessible(true);
fieldSysPath.set(null, null);

```

# Answer
> 0 votes
Use this class to load Natives from anywhere in your system.

```
import java.lang.reflect.Field;
import java.util.Arrays;

public class NativeLoader
{
 public static void loadNatives(String nativepath)
 {
     try
     {

     Field natives=ClassLoader.class.getDeclaredField("sys_paths");

      natives.setAccessible(true);

      String paths[]=(String[])natives.get(null);

      for(int i=0;i<paths.length;i++)
      {
        if(paths[i].equalsIgnoreCase(nativepath))
        {
          return;
        }
      }

      String newpaths[]=Arrays.copyOf(paths,paths.length+1);

      newpaths[newpaths.length-1]=nativepath;

      natives.set(null,newpaths);
     }
     catch(Exception e)
     {
      e.printStackTrace();
     }
 }
}

```

This method should be called as the first method in your main method.

Works in JDK 1.7 and 1.8 so far.

---
Tags: java, console, lwjgl
---


# Question
Title: Communication between Photon Cloud game and web server
I am creating a multiplayer game using Photon Cloud (Photon Unity Network). For storage of player data (profile, inventory, achievments) I use web server (asp.net mvc & sql server). How to organize the communication between the game client and the web server? I see two ways:

1. Use WWW class and send requests direct to web server:

```
var www = new WWW("http://mygame.com/api/user.get?id=1");
// Each time creates a new connection to the web server

```
2. Use Photon Cloud Webhooks and send requests through Photon servers:

```
PhotonNetwork.WebRpc("user.get?id=1");
// Photon Servers play a Proxy or Relay role between client and web server

```

http://doc.photonengine.com/en/realtime/current/reference/webrpc

Which way do you recommend? The first way is simple but each time creates a new connection to the web server. The second way use one persistent connection between client and Photon server but there is a delay between connecting the Photon server to the web server.

# Answer
You can find a list of advantages of the use of Photon's WebRPCs (compared to direct client to web server HTTP requests) at this link.

I think that if you don't need any of those then you shouldn't use it and you can find better alternatives than Unity's WWW.
> 0 votes

---
Tags: unity, networking, multiplayer, unity-networking, photon
---


# Question
Title: Unity3D Get collision without having Rigidbody
I am trying to detect a collision between 2 objects, each one of them has a `Collider` component. In the script I have the method `OnCollisionEnter(Collision other)` where I want to check if the collided object is the same as a pre-defined variable, but when they collide, nothing gets called.

If I try to attach a Rigidbody to one of the objects, it works, but that makes the Rigidbody object behaves weird, like going up and down, and changing its rotation.

Is there a way to check for collision without having a Rigidbody attached? Or if not, how can I make the object with Rigidbody not moving weirdly, and rotating?

# Answer
**Rigidbody.isKinematic**

If isKinematic is enabled, Forces, collisions or joints will not affect the rigidbody anymore. The rigidbody will be under full control of animation or script control by changing transform.position. Kinematic bodies also affect the motion of other rigidbodies through collisions or joints.

You can toggle this on/off in the **Inspector**, or in code

```
GetComponent<Rigidbody>().isKinematic = true;

```

Caution: having Colliders without a Rigidbody is never a good idea unless the object in question is static. If an object without a Rigidbody moves, it's Collider will not move with it!
> 6 votes

# Answer
Moving an object without a rigidbody or a character controller is also not optimized and will slow your game down, you can check Is Kinematic if you don't want forces acting on it and it will still be more optimized
> 1 votes

# Answer
An ad-hoc solution to this problem is to work with Triggers (eg OnTriggerEnter2D) and restrict Rigidbody constraints. So even if the collision occurs, it will not have an effect to the physics if the appropriate rotations and/or positions are "freezed"

if for example you want the object to move only along the 'X' axis and rotate on the 'Y' axis. You would do:

```
rigidbody.constraints = RigidbodyConstraints.FreezeRotationX |
RigidbodyConstraints.FreezeRotationZ | RigidbodyConstraints.FreezePositionY |
RigidbodyConstraints.FreezePositionZ;

```

Otherwise you can work with the intersection of the bounds:

```
var bounds1 = gameObject1.renderer.bounds;
var bounds2 = gameObject2.renderer.bounds;

if (bounds1.Intersects(bounds2))
{
    // do something
}

```

the problem with that is that it has to be placed in a coRoutine or inside the Update() method.

Hope it helps!
> 1 votes

---
Tags: unity, collision-detection, 3d
---


# Question
Title: How can I get UI element over which pointer is in Unity3D?
I can detect if mouse is hovering any UI element by `EventSystem.current.IsPointerOverGameObject()`.

But how do I know which `GameObjest` it is exactly?

I have tried:

```
    if (EventSystem.current.IsPointerOverGameObject())
        foreach (GameObject go in new PointerEventData(EventSystem.current).hovered)
            print(go.name);

```

But in every moment `new PointerEventData(EventSystem.current).hovered` is empty whether I hover or not.

I can see required info using `print(EventSystem.current);`:

```
<b>Selected:</b>

<b>Pointer Input Module of type: </b>UnityEngine.EventSystems.StandaloneInputModule
<B>Pointer:</b> -1
<b>Position</b>: (746.0, 535.0)
<b>delta</b>: (60.0, -44.0)
<b>eligibleForClick</b>: False
<b>pointerEnter</b>: cursorInfoText (UnityEngine.GameObject)
<b>pointerPress</b>:
<b>lastPointerPress</b>:
<b>pointerDrag</b>:
<b>Use Drag Threshold</b>: True
<b>Current Rayast:</b>
Name: cursorInfoText (UnityEngine.GameObject)
module: Name: Canvas (UnityEngine.GameObject)
eventCamera:
sortOrderPriority: 0
renderOrderPriority: 0
module camera: null
distance: 0
index: 0
depth: 1
worldNormal: (0.0, 0.0, 0.0)
worldPosition: (0.0, 0.0, 0.0)
screenPosition: (746.0, 535.0)
module.sortOrderPriority: 0
module.renderOrderPriority: 0
sortingLayer: 0
sortingOrder: 0
<b>Press Rayast:</b>

<B>Pointer:</b> -2
<b>Position</b>: (746.0, 535.0)
<b>delta</b>: (60.0, -44.0)
<b>eligibleForClick</b>: False
<b>pointerEnter</b>: cursorInfoText (UnityEngine.GameObject)
<b>pointerPress</b>:
<b>lastPointerPress</b>:
<b>pointerDrag</b>:
<b>Use Drag Threshold</b>: True
<b>Current Rayast:</b>
Name: cursorInfoText (UnityEngine.GameObject)
module: Name: Canvas (UnityEngine.GameObject)
eventCamera:
sortOrderPriority: 0
renderOrderPriority: 0
module camera: null
distance: 0
index: 0
depth: 1
worldNormal: (0.0, 0.0, 0.0)
worldPosition: (0.0, 0.0, 0.0)
screenPosition: (746.0, 535.0)
module.sortOrderPriority: 0
module.renderOrderPriority: 0
sortingLayer: 0
sortingOrder: 0
<b>Press Rayast:</b>

<B>Pointer:</b> -3
<b>Position</b>: (746.0, 535.0)
<b>delta</b>: (60.0, -44.0)
<b>eligibleForClick</b>: False
<b>pointerEnter</b>: cursorInfoText (UnityEngine.GameObject)
<b>pointerPress</b>:
<b>lastPointerPress</b>:
<b>pointerDrag</b>:
<b>Use Drag Threshold</b>: True
<b>Current Rayast:</b>
Name: cursorInfoText (UnityEngine.GameObject)
module: Name: Canvas (UnityEngine.GameObject)
eventCamera:
sortOrderPriority: 0
renderOrderPriority: 0
module camera: null
distance: 0
index: 0
depth: 1
worldNormal: (0.0, 0.0, 0.0)
worldPosition: (0.0, 0.0, 0.0)
screenPosition: (746.0, 535.0)
module.sortOrderPriority: 0
module.renderOrderPriority: 0
sortingLayer: 0
sortingOrder: 0
<b>Press Rayast:</b>

```

By the way why are there 3 pointers (-1, -2, -3) and what does this mean? I've read somewhere in docs, `pointer -1` is left mouse button, but I click nothing, so this is weird.

I can see `<b>pointerEnter</b>: cursorInfoText (UnityEngine.GameObject)` and `Name: cursorInfoText (UnityEngine.GameObject)` which is what I need. But how do I extract this info? I have tried `print(new PointerEventData(EventSystem.current).pointerEnter);`, but it is `Null` doesn't matter I enter or hover. And I see no other appropriate methods or properties in docs, although I can see that info is stored. I've tried `EventSystem.current.currentSelectedGameObject` too and it always returns `Null` as well. What have I missed?

My goal is to detect if mouse is hovering UI element with some conditions (ignore small amount of UI elements (likely by tag) and don't ignore the rest (most of elements)), so I have to get `GameObject` itself. And if mouse doesn't hover UI element (except those few), script does unrelated to UI stuff. But do not ignore if it hovers one of those few and one of the rest at the same time.

# Answer
> 3 votes
Unity 4.6 UI doesn't really like those OnMouse events, so we can't use OnMouseOver() for example. (Those are just for Colliders or GUIElements.) Instead, we use Pointer properties from Selectable under EventSystem. You can add the following script on your Canvas, or individually on UI transforms, or just attach EventListeners to them.

```
using UnityEngine;
using UnityEngine.EventSystems; //required for Event data

public class MouseOver : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler {

    GameObject currentHover;

    public void OnPointerEnter(PointerEventData eventData) {
        if (eventData.pointerCurrentRaycast.gameObject != null) {
            Debug.Log("Mouse Over: " + eventData.pointerCurrentRaycast.gameObject.name);
            currentHover = eventData.pointerCurrentRaycast.gameObject;
        }
    }

    public void OnPointerExit(PointerEventData eventData) {
        currentHover = null;
    }

    void Update() {
        if (currentHover)
            Debug.Log(currentHover.name + " @ " + Input.mousePosition);
    }
}

```

# Answer
> 1 votes
Sorry, I'm late. I answer in case you haven't found a solution yet.

There are several solutions to detect the GameObject the pointer is over, I think that the best is the use of EventTrigger. Usage is quite simple, your script will be something similar:

```
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour {
     OnMouseOver(string str) {
          Debug.Log(str);
    }

```

}

Now select the GameObject you want detect, Inspector, Add Component and search for EventTrigger, then Add New Event Type and Pointer Enter. Now drag and drop the GameObject that you've applied the script in the apposite field, in the menu search function OnMouseOver and type a string that allows you to recognize the object on which the mouse is on. You can repeat the process with Pointer Exit, obviously using a different string. Now whenever your mouse is over the GameObject, the function OnMouseOver will be executed.

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


# Question
Title: How can I use collision lines to implement line-of-sight in GameMaker?
I am making a GameMaker game that involves the enemies having line of sight so that they don't target the player through a wall. I have this code that uses collision line to detect whether there is a wall between the enemy and the player, then sets `CanSee` to 1 if true.

```
if collision_line(x, y, obj_parent.x, obj_parent.y, obj_wall_parent, false, true)
    global.CanSee = 1;

```

However, this code does not ever affect the value of `CanSee`. Am I using this code wrong?

Edit: Here is my room setup. The walls all have `obj_wall_parent`as their parent.

Here are some of the objects:

# Answer
```
if collision_line(x, y, obj_parent.x, obj_parent.y, obj_wall_parent, false, true)
    global.CanSee = 1;

```

> However, this code does not ever affect the value of CanSee. Am I using this code wrong?

Yes, and this is a common error. Check the GameMaker documentation for the function collision\_line and you can see it returns:

> Returns: Instance id or noone

At the moment your code assumes a true/false response, but since collision\_line doesn't return true/false, this won't work correctly.

I would recommend changing your code to:

```
if (collision_line(x, y, obj_parent.x, obj_parent.y, obj_wall_parent, false, true) != noone)
global.CanSee = 1;

```

This will set global.CanSee to 1, when the collision line function returns the id of an object. Remember you'll need to reset the variable this is no longer the case.

Happy coding!
> 1 votes

---
Tags: game-maker
---


# Question
Title: Is there a term of art for the collection of non-gameplay screens or pages
Is there a term of art for the collection of non-gameplay screens or pages in a game. I am thinking of screens such as:

* title screen
* options menu (key bindings, volume, graphics quality)
* credits screen
* hi-score table (maybe extradiegetic?)
* help page
* etc

These are all 'meta-screens', in that they help the player manage the gameplay experience, but are outside the gameplay space.

The term I am looking for should not include screens for extradiegetic elements, such as inventory management, character dialog boxes, hint screens etc. as these are all related to, or control gameplay state.

# Answer
> 1 votes
Not really (or at least if there is a technical term I've never heard it in common use, but maybe somebody who wanders in from the UX StackExchange site can educate me).

I've heard them informally referred to with a variety of terms, primarily:

* non-gameplay screens
* shell or shell screens
* menu screens

---
Tags: terminology, menu, screen-management
---


# Question
Title: Parent variable inheritance methods Unity3D/C#
I'm creating a system where there is a base "Hero" class and each hero inherits from that with their own stats and abilities. What I'm wondering is, how could I call a variable from one of the child scripts in the parent script (something like maxMP = MP) or call a function in a parent class that is specified in each child class (in the parent update is alarms() in the child classes alarms() is specified to do something.)

Is this possible at all? Or not?

Thanks.

# Answer
I suppose you can use reflection to achieve the setting of stats, as long as Unity3D allows it. I should warn you however reflection is relatively slow so you should look at your design before implementing reflection. The method calling is simple, make the base Hero class's Alarms() virtual and override it in the children classes.

The output of the following for instance is

Hero's MP is 40/100

Hero's MP is 40/400

Wizard's Alert!

```
class Program
{
    static void Main()
    {
        BaseHero hero = new Wizard() {MaxMp = 100, Mp = 40};
        Console.WriteLine("Hero's MP is {0}/{1}", ((Wizard) hero).Mp,
                                                    ((Wizard) hero).MaxMp);
        hero.SetStat("MaxMp",400);
        Console.WriteLine("Hero's MP is {0}/{1}", ((Wizard)hero).Mp,
                                                    ((Wizard)hero).MaxMp);
        hero.TriggerAlert();
    }
}

class BaseHero
{
    public void TriggerAlert()
    {
        Alert();
    }

    //This will only fire if the child classes do not override,
    //or if the child class calls base.Alert()
    protected virtual void Alert()
    {
        Console.WriteLine("Base Alert!");
    }

    //Reflection to set fields, requires the name of the field and the value
    public void SetStat<T>(string statName,T value)
    {
        FieldInfo field = GetType().GetField(statName);
        field.SetValue(this, value);
    }
}

class Wizard:BaseHero
{
    public int Mp = 0;
    public int MaxMp = 0;

    protected override void Alert()
    {
        Console.WriteLine("Wizard's Alert!");
        //Uncomment this line to have both the Wizard's alert and the base hero's alert fire
        //base.Alert();
    }
}

```
> 1 votes

# Answer
if you think about it a different way, your Stats and Abilities data could be components on the Hero & Wizard objects, which you would then access with:

```
myHero.GetComponent<StatsComponent>().GetMp();

```

then you're simplifying your hierarchy and preferring composition over inheritance.

Hero.TriggerAlert() could access a component directly or use the SendMessage() functionality built into Unity game objects.
> 0 votes

# Answer
If there are properties or methods in your child class that requires usage from your parent class, then you should probably recompose your class design and consolidate that functionality upward. Unless there is a fault with the parent class method that prevents a child class method from doing something different and/or unique. In that case, read below.

For your follow on question, which seems to be "How do I have a common function in my parent class that is common to all subclasses, yet have each child class have a different implementation?", I may have a solution. You could use one public method that calls a virtual method in your parent class, that will be inherited by all of your child classes. The virtual method could then be overriden safely by all of your parent classes and have a slightly different implementation or effect, but still be used by calling the parent class public method. For example,

```
public class ParentObject
{
    public void Run()
    {
        ImplementationRun()
    {

    // Stub virtual method to be overriden in child classes
    protected virtual void ImplementationRun()
    {
    }
}

public class ChildObject : ParentObject
{

    protected override void ImplementationRun()
    {
        // Child Class specific implementation here
    }
}

```

This way you could still utilize your child class methods in the virtual function, that will execute in the parent class method, rather than contort the parent class method to suit a child class specific instance.
> 0 votes

# Answer
One very straightforward way that wasn't mentioned is simply sending messages.

```
using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    void ApplyDamage(float damage) {
        print(damage);
    }
    void Example() {
        gameObject.SendMessage("ApplyDamage", 5.0F);
    }
}

```

Messaging basically gets a game object and calls a function in every MonoBehaviour in that game object ( ApplyDamage in the example above ).

This is a very good approach if you're aiming for clearer abstraction, but do keep in mind that it is not designed for hundreds of calls per second. Updating mana values should be fine, though.

For something more performant ( if you happen to need it ) - you should check the Observer Pattern ( It's actually built in the C# language ). The Unity team also has a tutorial for how to build a Messaging System ( same functionality different name ).
> 0 votes

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


# Question
Title: Should I Have a Ridiculously Easy First Level?
I am making a game based on a grid and filling in certain squares with certain colors according to some rules. It is level-based, and the difficulty of a level is determined by the size of the grid and how many colors you have to fill in. Should the first level be ridiculously easy to allow players to get used to the UI?

# Answer
Here is a really good example from the creator of Super Mario. He explains that the first level was designed to introduce the player to the base concepts of the game. It's a very good video. https://youtu.be/zRGRJRUWafY There is actually quite a bit of psychology in the design of the first level.

You should also look at Classical Conditioning, aka "Pavlovian Conditioning". https://en.m.wikipedia.org/wiki/Classical\_conditioning Essentially, you allow the player to discover what "feels good" and "feels bad". In the video, when the player hits a block they receive a coin. This is a reward; they now know that hitting those blocks gives rewards, so they would like to try it again. And inversely, falling into a hole or into water(if applicable to your game), will result in death, which naturally is a bad thing, thus they now know that they should refrain from doing it again.
> 1 votes

# Answer
Usually you should.

The purpose of the first level(s) is to make the player familiar with the controls, UI and most basic game mechanics. The first challenge for the player to beat should be how to control the game, then to understand the game, and then to actually play it competently. It's great when you can mark each of these steps with a success milestone in form of a complete level.

For further research I recommend the video *Tutorials 101 by Extra Credits*.

However, keep in mind that game design is more of an art than a science. There are no absolute rules in game development. Sometimes you need to muddle this progression for the sake of immersion and storytelling. And sometimes it can be refreshing for the player to get pushed out of their comfort zone and challenge them from the first second on.
> 1 votes

# Answer
Not really.

It's highly recommended to have ridiculously easy ( and few ) mechanics in the first level. Make the first few player mechanics easy ( introduced in the first level ) to understand and learn - this generally allows a broader range of people to play.

You can make it challenging, though. As long as the overall mechanics are simple - you can make players work to actually win.

All endless games embrace this concept ( Threes, 2048, Flappy Bird, Temple Rush and so on ). It's vital to make the game rules easy to understand ( especially at the start of the game ), but that by now way means you should have a trivial game/level to play.
> 0 votes

# Answer
I personally don't think it should be "ridiculously" easy because if it is too easy then it would give the impression to the player that the whole game lacks any challenge.

I think it would be best to have a slightly more simple introduction to the game's mechanics so the user finds it easy to pick up the controls, just make sure they can easily pick up how to play and that they will learn how to play, but it should have a little challenge (not too much, but a little) to engage the player more.
> 0 votes

---
Tags: game-design, ui-design, levels, tutorials
---


# Question
Title: Unity : Android Button : Select (Highlight) by touch, before clicking
I have a multiplatform game with dozens of buttons in many menus.

I used the animated buttons setup to have a normal state and highlight state. Highlight will most of the time resize the button with a nice anim AS WELL as make a dedicated text box appear with extra information. So far so good. Everything works perfectly on PC.

However, as I am testing my build on android, I cannot find how to access the "highlight" state since touching the screen = click and it execute the on click () associated.

What I need is a way to select a button when it is first touched, since selected = highlight (somewhat) then if it is touched (clicked) a second time while selected then to do the on click ( ) function.

I have a few theory on how to do it, but it would require recreating every of my 80 or so buttons as well as changing everything from using the Unity GUI system to make my own C# version which would take weeks.

I am also trying a few other way to achieve the same thing. One of which is using the "button.select()" to select the button on its first click. That works. problem is I cannot seem to write a way to do: "if (thisbutton.IsSelected == true)" that just refuses to work.

# Answer
Should anyone every come here looking for an answer to something similar, here is what i eventually managed to do :

I created a special button script that could either call the function directly if running on PC, or, if on a touchscreen it would select the button first based on its name, and if it was already selected, it would call the function.

```
using UnityEngine.UI;

(...)

public void CallButton (string OriginalName)
//the function called when the button is clicked, the string is the name of the button itself in Unity
    {
    #if UNITY_STANDALONE || UNITY_WEBPLAYER  || UNITY_WEBGL
        ButtonFunction(); //IF on pc, call the function directly
    #elif UNITY_IOS || UNITY_ANDROID || UNITY_WP8 || UNITY_IPHONE
    if (Static.ButtonSelectedName == OriginalName)
    {
        ButtonFunction(); //if on touch, and button is already selected, call function.
    }
    else
    {
        Static.ButtonSelectedName = OriginalName; //update static STRING with the name of this button
        Button thisButton = GameObject.Find(OriginalName).GetComponent();
        thisButton.Select (); //Select (highlight) the button.
    }
    #endif
    }

void ButtonFunction ()
{
//anything that your button actually needs to be doing
}

```

This works on every single button in my project and enabled them to get selected with the first touch, then executed on the 2nd if its already selected. Hope it can help someone one day! :)
> 0 votes

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


title: 3D sphere generation

text:
# Question
Title: 3D sphere generation
I have found a 3D sphere in a closed-source game engine that I really like the look of and would like to have something similar in my own 3D engine.

This is how the sphere looks like when it is created in the game engine, at program/game start:

At program start, a function named CreateSphere is called and the user has the option to choose a 3D position and a radius of the sphere. That's all I know about the function since the engine is closed source.

Anyone have any idea of how this sphere might be generated programmatically? I have checked other posts/sites discussing spheres but none of them has the look of the sphere in the image.

Edit: removed some unnecessary information to get to the point of what I need help with.

# Answer
I created sphere before. My way is, generated all longitude points according to the latitude points. Then, store these points in longitude order for drawing longitude lines, store these points in latitude order for drawing latitude lines. So actually all the points will be use two times.

This is the way i created all the points first.

```
    for(var latNumber = 0; latNumber <= latitudeBands; latNumber ++)
    {
    var theta2 = latNumber * Math.PI / latitudeBands;
    var sinTheta = Math.sin(theta2);
    var cosTheta = Math.cos(theta2);
    for(var longNumber = 0; longNumber <= longitudeBands; longNumber ++)
    {
        var phi2 = longNumber * 2 * Math.PI / longitudeBands;
        var sinPhi = Math.sin(phi2);
        var cosPhi = Math.cos(phi2);
        var x = cosPhi * sinTheta;
        var y = cosTheta;
        var z = sinPhi * sinTheta;

        var points=vec4(radiusSphere * x,radiusSphere * y,radiusSphere * z,1);
        vertexPositionData.push(points);

    }
}

```

Then i store all the latitude points and all the longitude points.

```
for(var latNumber = 0; latNumber < latitudeBands; latNumber ++)
{
    for(var longNumber = 0; longNumber <= longitudeBands; longNumber ++)
    {

        pointsArray.push(vertexPositionData[(latNumber*(longitudeBands+1))+longNumber]);
        colorsArray.push(sphereColor);
    }
}

 for(var latNumber = 0; latNumber < latitudeBands; latNumber ++)
{
    for(var longNumber = 0; longNumber <= longitudeBands; longNumber ++)
    {
        pointsArray.push(vertexPositionData[(longNumber*(latitudeBands+1))+latNumber]);
        colorsArray.push(sphereColor);
    }
}

```

Then i connect all the latitude points into circle. same as longitude points.

```
   for(var i=0; i<=latitudeBands; i++)
    gl.drawArrays( gl.LINE_STRIP, i*(longitudeBands+1),longitudeBands+1);

offset = latitudeBands*(longitudeBands+1);

for(var j=0; j<=longitudeBands; j++)
    gl.drawArrays( gl.LINE_STRIP, j*(latitudeBands+1)+offset,latitudeBands+1);

```

This is not a best way to draw shpere. but it can successfully draw sphere.

This is the picture i have.
> 2 votes

---
Tags: opengl, 3d, sphere
---


# Question
Title: Managing animations for object state transitions
I'm looking for an optimized way to handle simple state transitions on my game objects. By "simple" I mean not more than 1-2 actions per object, and most algorithms are linear.

For example, I have an UI element that implements a switch (like a light switch) and it has two states - "up" (lights turned on) and "down" (lights turned off). Let's say I want to make it so that I can switch the switch from one state to another, and update its presentation in a smooth way using linear interpolation (move the foreground sprite up or down).

The question is if I should always check if the object should update its state (every frame), or should I add/remove this object from the update loop on demand, or is there any other (better) way of handling this situation?

Currently I have it implemented the following way: my object has a boolean variable called `animated` and in my `onframe` loop I have the following code:

```
if (this.animated)
    /* calculate new positions for the sprite */
else
    /* do nothing */`

```

And it would appear to me that this kind of code is not very well optimized. How to handle this kind of things better?

# Answer
Here is a simple, popular way of doing animation:

1. Define the starting state and end state for your object. This will vary depending on whether you want to move the object, rotate it, etc. An example would be to store the position of the object at the current state, and for the final/target/end state.
2. Then you subtract the coordinate values from each other
3. ... and multiply them by the magic variable `f` (in a lot of examples its referred to as f). `f` is a fraction between 0 and 1 that controls how far the animation is, or how what percentage of it has completed in other words.
4. Then you add the result from step 3 to the starting state.

Here is a crude psuedocode example for doing 2D translation animation:

```
State 1 [0,0]  State 2 [10,0]

f = (1 / anim_duration) * time_since_start_of_anim
current_x = state1_x + (f * (state2_x - state_x))
current_y = state1_y + (f * (state2_y - state_y))

```

The animation is finished if `f = 1`

Why this is a good approach:

* It is very easy to implement interpolation (like ease-in animation) by getting the value of `f` under some function
* It is very versatile and adaptable, making it easy to implement on a large number of objects
> 1 votes

---
Tags: animation, software-engineering
---


# Question
Title: What system could I use to identify my entities, when sending data over network or storing them in file?
I have a game engine using an entity-component system (ECS). I serialize the data contained in the ECS by having a system that registers serializers for different component types. I want to create networking,= using authoritative peer-to-peer, where I still have a server, but it acts only as the traffic center, and does not run the game logic. The idea is that specific entities are synchronized across client instances.

However, there is a problem with this. While I can easily serialize my data, I don't know how to synchronize it over a network, or load it from a file. The problem lies in how my system communicates; how do I tell which entity is which, on the other end? How do I let the receiving side know which entity the sent data was meant for?

My entity ids are currently generated as sequential numbers, but it feels very unreliable to use them, as there could be a time when the numbers are not synchronized. For example, one might create a decal entity sooner, or the order in which they are created could be different. This also makes seeded random GUIDs unusable.

What system could I use to identify my entities, when sending data over network or storing them in file?

# Answer
I dont think i know enough details, because im afraid i dont understand the situation correctly. However, if i understand it you are trying to sync entity IDs over network so multiple games on different computers would have same entity IDs.

Since you are dealing with networking you must have a server and it should be the server's job handling the IDs. So for example when an entity is created the client should send a request for new id to server(would also have to send the type and initializing component data) and server would then send the id, type and serialized component data to all the clients except the first one which would only get the id, so that they would all get to know about the new entity(this would apply for bullets for example when the player shoots a bullet the bullet would be created on player's computer and so on ).

It would be different regarding the world. AI, map generation, etc. should work on the server. Any kind of world entity would be created on server because all the clients must have the same world experience.

Regarding the file reading / writing of the component data it should again be the server's job doing so. This means that for example when the server would start it would read the files and initialize the components and then the clients would send requests for intialization data that the server read from files. Each client would confirm that they recieved the data and when they would all confirm server would start the game and so on.

All in all make sure that server controls the IDs and be careful with situations like coop mechanics where the server would actually be one of the clients so then that one client doesnt need to run a seperate server program but rather just open a server within the game and use it for its own game as well(it would simply share its game data with other clients and would recieve events from other clients).

I made up the exaples stated above on spot and i do not know if those are best solutions and i do know they are not accurate and they are not complete. However, i wanted to support the idea with examples, so it really depends on you how you will actually implement this idea, if you ever will that is.

I hope i didnt misunderstand the problem or that i didnt forget anything important regarding it and i hope i helped. I wish you the best of luck with the engine :)

**EDIT** I totally missed the point here with this answer(for some reason i totally missed the p2p part).

As you have p2p you want to sync IDs every time an entity is created / removed. When entity is created for example just sync the new ID and data. Now with this approach you would have to do that for every entity and it could hit the performace dramatically. You dont want to sync every entity out there, so what you could do is that you logically divide entities into sync and non-sync entites and have those groups generate seperate IDs for their own entities. You could also approach this by still having all the entities with same ID generation and just create a hash table for sync entities. There are probably some better ideas, since I just made these up on spot, but this should give you an idea to think about. The latter is imo better since you dont have to optimize the core of your ECS but you can just add the hash table elsewhere(p2p network module or sth), it is also better regarding the performance.

When saving to files you should just save the hash table as well and you are done.

I hope I helped this time and that I didnt miss the point again. Again, good luck :)
> 1 votes

---
Tags: architecture, entity-system
---


# Question
Title: Use Mathf.PingPong() from current position
I am trying to use Mathf.PingPong() from the current x, y and z coordinates and let it move along the x axis however now it moves too far and too fast. I know how I can speed down but what about the distance?

```
       transform.position = new Vector3(transform.position.x + Mathf.PingPong(Time.time * speed, 1), transform.position.y, transform.position.z);

```

# Answer
> 1 votes
The second parameter of PingPong is the length, so you can adjust that to your desired distance.

```
transform.position += new Vector3(transform.position.x + Mathf.PingPong(Time.time * speed, length), transform.position.y, transform.position.z);

```

Also another way to write this would be:

```
transform.position += Vector3.Right * Mathf.PingPong(Time.time * speed, length);

```

Also: I noticed you're adding it on to the current position, but PingPong never returns less than zero so your object won't move back and forth if that's what you were intending (?) if so you could subtract half the length from the result of PingPong first: `transform.position = new Vector3(transform.position.x + (Mathf.PingPong(Time.time * speed, length)-0.5*length), transform.position.y, transform.position.z);`

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