# Question
Title: Why are 3d projections on a 2d screen not like what the human eye sees?
Firstly, I'm sorry if this question doesn't make much sense or is poorly written - I have almost no experience with programming, and none at all with game development. I'm also not sure it's an appropriate question for gamedev stack exchange, so sorry if that's the case.

Anyway, the question is this - what are some ways of doing the vision in a fps game?

If I understand it correctly, the problem can be stated the following way - given a 3d environment given in 3d coordinates, and a camera with some direction and certain field of vision, our goal is to somehow project the environment, to a 2d screen, similar to how our eyes do it, or similar to how a camera does it.

One way to do this is the following - whatever is exactly in the direction of the camera will get displayed exactly to the middle of our 2d screen (let's presume the 2d screen is round for simplicity, with radius 1), and the rest in the field of vision will get projected linearly based on the angle. For example, if field of vision is 90 degrees (anything 45 degrees from the direction of the camera will be in the field of vision), then things 45 degrees away from the direction of the camera will get displayed to the outer circle/edge of the 2d screen, and things 22.5 degrees away will get displayed to the circle with radius 0.5. This might be similar to how a camera or our eye does it, but I'm not sure.

Now in reality, this doesn't seem to be how it's done. To give an example, if I take something like DOOM, or I think any modern fps game, and I were to stand in front of a very long wall that's of the same height everywhere, and I were looking perpendicularly towards it, the height of the wall will be the same everywhere in my 2d projection - in reality though, or a camera for example, would display the very furthest (furthest from the center of the vision) parts of the wall to be shorter in height. But, given a small enough field of vision, the difference seems negligible.

Either way, it seems like fps games don't really consider this fact, and I want to ask - why? Maybe the difference is barely noticeable, but much more power demanding? Either way, I would appreciate an explanation or information concerning how exactly the human eye or camera projects 3d environment to a 2d picture.

# Answer
If we're willing to approximate the viewer as a cyclops whose single eye has a pinhole pupil (and this turns out to be a much better approximation than it sounds like - more on that later), then I'd argue that **both projection methods you describe are correct**. *For different shapes of screen*.

---

Thinking of the problem angularly gives the correct result if the screen is a spherical dish, hemisphere, or globe centered on the viewer's eye.

As the viewer sweeps their gaze around the image (taking care to keep their pupil at the exact center of the sphere to not upset the theoretical mathematician who put them here), each degree of travel translates to a constant length across the surface of our curved screen.

Since the entire monitor's surface is the same distance from their eye, no part of the image is foreshortened or otherwise scaled/distorted from their perspective. So as the infinite wall recedes away from them, taking up an ever narrower arc of their visual field, it must also span an ever smaller height on the screen, until eventually its top and bottom lines - which had been parallel dead ahead - meet at a sharp vanishing point 90 degrees to the left. The lines have to be curved to make this work (specifically, straight lines in the rendered world will map to great circles on our screen. Groups of parallel lines will map to great circles meeting at a common pair of diametrically opposite poles, like lines of longitude)

---

Now, I don't know about you, but I don't own a spherical screen. When I play games, they're typically on a flat screen. Which means it's *not* a constant distance from my eye at every angle: as a feature recedes away to my left, so does the screen itself!

I'll spare you the equations for now, but if our monitor/viewport is exactly parallel to the wall, and we use linear perspective to draw the wall at exactly the same height on the screen all the way across, then from the viewer's perspective it will shrink in visual angle in exact proportion to the virtual wall it represents, as the two recede into the distance to the left.

The two parallel lines never need to meet at a point in this view, because even the absurdly-widescreen monitor I've drawn in the diagram above still has finite width. We'd fall off the edge of the screen long before we ever reached the vanishing point (infinitely long before, in fact!) If we did somehow have an infinitely wide flat screen, we'd see the vanishing point arise naturally - not because it's built into the projection of the world onto our screen, but because the projection of distant screen in our eye affects lines on the screen in exactly the same way any other lines in the world, including the original wall we're rendering.

Of course, if we turn our viewport (game camera) so that it's no longer parallel to the wall, then linear perspective will replace those parallel lines of the wall with ones that literally converge to a vanishing point on our screen, as we'd expect, and again the net effect of the size of the feature on screen and the distance to the screen itself will exactly match the right amount of shrinkage/foreshortening for a given angle.

---

This is because both projections work by considering where a line from the viewer's eye to each feature point on the object (the cyan lines in my diagrams above) intersects the surface of the screen, and that's where they place the image's corresponding feature point. Since these lines point directly out from the eye, they don't travel across our visual field - each one maps to precisely one point in the 2D space of our vision, no matter the depth. So as long as we draw each feature on the same "eye ray" as its original, it will be placed in the correct part of our visual field for whatever kind of screen we're intersecting with / displaying on.

To see the equivalence another way, imagine nesting these two diagrams - so the spherical screen is displaying an image of the flat screen displaying an image of the wall, or vice versa. I used the same eye rays to feature points in both cases, so they'll line up exactly, and we get the same image on the spherical screen using angular rendering whether we're trying to draw the wall itself, or the image of the wall we captured on the flat screen (if we could extend it to an infinite flat plane).

So, neither linear perspective nor this spherical/angular projection is a "more correct" way to project the scene, they just depend on our rendering intent. The spherical projection has to work a little harder to "bake in" all of the perspective shrinkage effects for every screen normal direction instead of just one normal in the linear case, though in exchange it's able to render a complete wraparound view if you're lucky enough to have hardware that can display it. :)

---

So, using linear perspective on a flat monitor is no more approximate than using spherical perspective on a spherical monitor. They're both geometrically correct for the simplified viewer we set out to model.

It's not necessary to model the roundness of the retina, the angular swivel of our gaze, or the distortion of our lenses in the image we render on the screen, because you're already viewing the screen with your angularly swiveling, lens distorting, round-retina real eyes! So all that gets applied as a "post-post effect" by our own physiology. ;)

All we need to do - in either model - is correctly plot on the screen what you'd see if your view ray continued "through" the surface of the monitor in a straight line and hit the corresponding point in the virtual world on the other side.

Now of course, having two eyes and the ability to move in space complicates this - a single image will be correct from only one viewpoint. So in non-stereoscopic games we typically choose a compromise viewpoint that's "good enough" - and the approximation of the projection comes from that choice of viewpoint, not from the perspective projection math that uses this that viewpoint as an input. Stereoscopic games for VR headsets or the 3DS have better ability to locate the player's actual eyes relative to their display and show each one a custom-tailored image, so they can get much closer.

The last detail is that our pupils aren't infinitely narrow pinholes, so we can only focus on a single focal plane at a time, and experience depth of field blurring closer and further away, in addition to lens aberration effects. This affects the sharpness of features in our visual field, but not the location of the center of their circle of confusion, so again it's not a perspective projection approximation, and the pinhole cyclops turns out to be a pretty decent approximation for figuring out where to draw stuff. XD

---

**One last note:**

There had briefly been a comment below asking about the stretching we see at the edges of the screen in some games using linear perspective. Although it's deleted now I think it raises a point worth describing in a bit more depth:

As mentioned above, both of these styles of projection are only geometrically correct when viewed from one point, where all those "eye rays" intersect.

Since most games don't do head-tracking to move this point dynamically to match your actual position (though the effect can be dramatic and extremely convincing when they do!) they tend to pick this viewpoint based more on the aesthetics of the game and the informational needs of the gameplay.

Shooters tend to push this further, since having more peripheral vision available can be a life-or-death matter in these games. So they'll choose a large field of view value for their camera - that corresponds to a hypothetical viewer whose eyeball is very close to the screen, so they have to rotate their eye further to sweep their gaze from center to edge. When viewed from this idealized close position, the extra stretching at the edges of the screen gets foreshortened by the extreme angle at which we're viewing it, and the effect is correct - like standing in the right place for an anamorphic chalk painting, the perspective of the screen and the image on it exactly compliment each other and the scene snaps into correct perspective.

But if we move back from the screen to a more comfortable play position, we're bringing more of its area into the narrow forward cone of our vision, where it's more perpendicular to our view and less foreshortened than the math was made for, and the distortion becomes more apparent.

Fortunately, our brains are pretty malleable, and players will tend to get used to even fairly significantly exaggerated FoV values when playing on a flat screen, so we tend to mainly notice the effect in stills. This does not go the same for VR though, where matching the field of view to the actual device viewing conditions is critical for maintaining player comfort, so don't push your FoVs everywhere. ;)
> 13 votes

# Answer
Your assumption is incorrect, in that things **farther** away from the viewpoint are, in fact smaller. This is called "perspective."

Given an infinitely long, perfectly flat wall normal to the view vector - that is, you're looking straight at it, perpendicular to the wall surface, and given that you could see to infinity in each direction, the wall would appear to curve, and the top and bottom would meet at a point on the left and right.

This is related to the non-linearity described by trig functions, specifically tangent. As the angle between the view vector and rendered pixel increases, the relative (world space) distance between adjacent rendered pixels increases, or, more accurately, the volume of the frustum described by the pixel bounds increases.

(TL;DR: adjacent pixels at the edges of the display contain parts of the world that are farther apart - or if you prefer, cover more area of the rendered volume - than adjacent pixels at the center of the view.)

Google "two point perspective" and sketch some stuff out for fun.

The big reason that we can't make stuff on the screen look like it would in real life is that, in most cases, we don't know how far your face is from the monitor, or in what relative position. Given that information, the screen would appear to be a window - the glass kind, like in your house / apartment / whatever - rather than a flat display.

This is one of the (few) great things about VR. Given the position / orientation data, we can render things the way they should be rendered. Stereoscopic is a gift-with-purchase.

**UPDATE**

In retrospect, I think @DMGregory's answer is more accurate, and certainly more informative. I'd delete my post, but I think the discussion-in-comments (I'm sure that'll get flagged for deletion in a few years) is useful, so I'll leave it for the time being.
> 2 votes

# Answer
Others may come with a more complete answer but the gist is:

3d computer generated images are displayed on a flat plane (your monitor), so the brains who developed the science of graphics programming came up with this technique called 'perspective projection'. This technique basically takes all the vertices that are in the viewing frustum:

(Image source)

...and 'squishes' them to make them flat on a single plane, which is the viewport. The vertices composing the objects are *projected* on the viewport in a "direct" fashion, not curved whatsoever. This is why everything looks straight.

This technique is both good enough and fast enough.

But that's not how the eyes work. What we see is not projected directly to a flat plane but directly on our retinas.
> 1 votes

# Answer
You may be interested to know that raytracing, by its nature of being more similar to the eye than your typical flat-projected computer renderer, does in fact account for the fisheye effect, which is the term you're looking for. You may not be a fish, but all creatures with (round) eyes experience it to a greater or lesser degree. For example:

Interestingly, this is often considered to be an undesirable effect in raytraced rendering. The reason is that when a human being views such a space, the visual cortex actually normalises the resultant image such that your vision does *not* at first glance (snort!) appear to have this effect... unless you examine it carefully and explicitly. This is one of several such "post-processing" effects on our vision, some of which I believe lead to a portion of the famous optical illusions we all know so well.

As others here have explained, the details of why a common present-day renderer does *not* account for the fisheye effect is based on their method of projection, which is entirely different from casting thousands or millions of rays outward in a convex semi-hemispherical arc - which leads to fisheye.
> 0 votes

---
Tags: graphics-programming, projection
---


# Question
Title: Javascript canvas rotating single sprite instead of entire context
I am trying to recreate asteroids, but I need the ship to rotate based on user input. I have w,a,s,d keys set to change the \[pos\] of the ship by 1 in the corresponding direction, but now, I need to spawn the sprite in the appropriate angle based on that, and I am running into two main issues:

1. how to correctly spawn the image over and over (right now, I can get a copy of the ship to spawn in the exact cetner of the context, rotated at one angle, ALONG with the real ship that I control. I do not know why this is.)
2. How to calculate the angle of rotation in radians based on the ship's pos.

I have included the entire ship class, but the most relevant code will be the draw method at the bottom.

```
const Utils = require('./utils.js');
const MovingObject = require('./moving_object.js');
const Bullet = require('./bullet.js');

function Ship(posOptions) {
  let options = {game: posOptions['game'], color: 'green', pos: posOptions['pos'], radius: 20, vel: [0,0], wrappable: true, type: 0}
  MovingObject.call(this, options);
  this.faceingDir = [0,0];
}

Utils.inherits(Ship, MovingObject);

Ship.prototype.relocate = function () {
  this.pos = this.game.randomPosition();
  this.vel = [0,0];
};

Ship.prototype.power = function (impulse) {
  // console.log(this.vel);
  this.vel[0] += impulse[0];
  this.vel[1] += impulse[1];
};

Ship.prototype.fireBullet = function () {
  let bulletVel = [(this.vel[0] * 4), (this.vel[1] * 5) - 10];
  let bullet = new Bullet({pos: this.pos, vel: bulletVel, game: this.game});
  this.game.bullets.push(bullet);
};

Ship.prototype.move = function () {
  if (this.isWrappable) {
    this.pos = this.game.wrap(this.pos);
  }
  this.pos[0] += this.vel[0];
  this.pos[1] += this.vel[1];
  this.vel[0] *= .98;
  this.vel[1] *= .98;
};

Ship.prototype.draw = function (ctx) {
  const img = new Image();
   img.onload = function () {
    ctx.drawImage(img, this.pos[0]-this.radius, this.pos[1]-this.radius)

  };
  img.src = 'galaga_ship.png';
  ctx.drawImage(img, this.pos[0]-this.radius, this.pos[1]-this.radius);
  var x = 800 / 2;
  var y = Math.floor(605 / 2);
  var width = img.width;
  var height = img.height;
  ctx.translate(x, y);
  ctx.rotate(10 * Math.PI / 180);
  ctx.drawImage(img, -width / 2, -height / 2, width, height);
  ctx.rotate(-10 * Math.PI / 180);
  ctx.translate(-x, -y);
};

```

# Answer
> 2 votes
1. You should load your image during initiation, *not* in the draw function. The draw function should be run over and over again, every "tick" of the game. The problem with your loading algorithm is that it takes time for the image to load, so if your draw function is called many times per second (which it should be), your game is already malfunctioning.
2. One way to applying a transformation (e.g. rotation) to only one object is like this answer, which is to implement a system that stores transformation matrices on a "stack". You will need to do research on matrix multiplication; translation, scale, and rotation matrices; and javascript stacks (*very* easy to understand; see this answer).

# Answer
> -1 votes
The problem is that you draw the image three times in your code. Put all the drawing code in img.onload and remove the extra, unwanted image drawing:

```
  const img = new Image();
  img.onload = function () {
    //ctx.drawImage(img, this.pos[0]-this.radius, this.pos[1]-this.radius)
    var x = 800 / 2;
    var y = Math.floor(605 / 2);
    var width = img.width;
    var height = img.height;
    ctx.translate(x, y);
    ctx.rotate(10 * Math.PI / 180);
    ctx.drawImage(img, -width / 2, -height / 2, width, height);
    ctx.rotate(-10 * Math.PI / 180);
    ctx.translate(-x, -y);
  };
  img.src = 'galaga_ship.png';

```

The illustrative fiddle, just in case: https://jsfiddle.net/simoroshka/ercds9cu/

---
Tags: javascript, sprites, html-canvas
---


# Question
Title: What's the performance benefit of saving all logged in characters in MMOs in regular intervals?
The majority of MMORPGS have a Worldsave system that will save all the characters once every X hours. I guess the reason is performance. So why is this better, performance wise, than saving a character on disconnection?

# Answer
This is not for performance. This is a failsafe. If the world saves every few minutes, then if something happens to the server and it shuts down everyone will only lose a few minutes' progress.

By saving on disconnect, if the server has an issue everyone will lose everything they have done since they logged on. For those on particularly long play sessions (as is common in MMOs), they will lose a significant amount of data.

They sacrifice a little performance to remove the risk of mass data loss.

Of course, you could easily store the player data on the client machines, reducing network traffic. The issue here is that it is open to hacking. Once one person works out how to cheat, they share it and everyone is doing it.

---

**EDIT:** As @Philipp pointed out, this also removes the ability to duplicate items. With a save-on-disconnect system if a transaction is made before a server crash and one person logs out before the crash, both players are rolled back to the last time they logged out, either deleting the items or duplicating them.
> 65 votes

# Answer
Early systems that saved only on disconnect tended to also save periodically while the player was active. In those systems, typically MUDs (Multi-User Dungeons), the character was maintained in memory until they were periodically dumped to a file.

This meant that if a user disconnected without "camping", they usually found themselves several rooms away and missing a bunch of loot, XP, etc, from the last time they saved. In that regards, it behaved a lot like how console RPGs play today (you have to save your game without turning off the console, or you lose everything since the last time you saved).

The system worked for its intended purpose, because characters could not interact with each other, except possibly by way of a "mail" system where they could send messages and items to each other. The chance of losing items and progressed tended to be pretty significant, but only affected one character at a time in most cases.

The worldsave feature came about because characters were eventually able to directly interact with each other, so all of the characters playing had to be in a consistent state, or item duplication and deletion could occur. This wasn't a problem in the MUD scenario, because it was difficult to abuse the system in a way that resulted in item or currency duplication, but it was incredibly easy to do in early MMO MUDs. Player A gives player B an item, player B saves and player A disconnects without saving. Instant duplication.

Worldsave is *not* a performance benefit, but designed to prevent cheating. I recall playing on systems where the worldsave event was literally announced in advance, and often hung the entire system for a minute while the server updated all of its files. While this prevented cheating, it was not very convenient for the users of these systems.

That leads us to the current state of affairs. Today, we don't use worldsave type functions. We use databases. This allows us to make sure that duplication and deletion is minimized as much as possible. The characters exist as records in a database, and each transaction between players is a literal database transaction; either the action is fully committed or it will be rolled back.

Barring unusual bugs in the system, you get the benefits of saving individual character files (quick save times) and the benefits of worldsaves (no cheating), without the drawbacks of either (losing significant progress and item duplication).

When designing a modern MMO, you would want to create stored procedures in a database, and use those procedures to perform transactions. For example, when doing a trade between two players, it might look like this:

```
start transaction;
insert into inventory (playerid, itemid) values (111, 222);
delete from inventory where playerid=111 and itemid=444;
insert into inventory (playerid, itemid) values (333, 444);
delete from inventory where playerid=333 and itemid=222;
commit;

```

(Note: this SQL, isn't written in a practical way and is only meant to be an example).

In this way, if there's a crash before the commit, the system rolls back to a state where player 111 and player 333 still have the original items, while after the commit, the trade is completed. There's no opportunity for duplication, because the characters are saved at the same time, as guaranteed by the database.
> 5 votes

---
Tags: networking, mmo, databases
---


# Question
Title: How can i press the key, show the text and choose if i want to take the item?
It's working fine right now, showing the text and then press the key and it takes the item but, i want something like resident evil, the text is not showing until you press acction button. How can i do that?

**The key script:**

```
var TheKey : GameObject;
private var playerNextToKey = false;
//var showMessage : boolean = false;
//var nearKey : boolean = false;
 var hasCollided : boolean = false;
 var labelText : String = "";

 function OnGUI()
     {
         if (hasCollided ==true)
     {
          GUI.Box(Rect(140,Screen.height-50,Screen.width-300,120),(labelText));
     }
 }

function Update ()
{
    if (Input.GetKeyDown(KeyCode.E) && playerNextToKey == true)
    {
    TheKey.active = false;

    }
}

function OnTriggerEnter (theCollider : Collider)
{
    if (theCollider.tag == "Player")
    {
        //nearKey = true;
        playerNextToKey = true;
        hasCollided = true;
        labelText = "¿Vas a coger la llave?";

    }
}

function OnTriggerExit (theCollider : Collider)
{
    if (theCollider.tag == "Player")
    {
        //nearKey = false;
        playerNextToKey = false;
        hasCollided = false;

    }
}

```

# Answer
So the conditions under which the dialog is supposed to pop up are:

1. The player-character is inside the trigger-area AND
2. The player holds down the `E` key AND
3. The dialog is not already open

Condition 1 can be checked by implementing the other two conditions in the `OnTriggerStay` event. This function is called during each game-tick where the object is inside a trigger-collider.

You already figured out how to check the second condition (`Input.GetKeyDown(KeyCode.E)`)

The third condition can be solved with a boolean flag.

The whole code for OnTriggerStay would look something like this:

```
var dialogOpen : boolean = false;

function OnTriggerStay (theCollider : Collider)
{
    if (theCollider.tag == "Player" && Input.GetKeyDown(KeyCode.E) && !dialogOpen )
    {
         ... your code to make the dialog window appear...

         dialogOpen = true;
    }
}

```

The next thing you might want to implement is to disable all other player input controls if `dialogOpen == true`, so the player is forced to interact with the dialog window and can not just walk away from it.

Then you should implement the logic behind the dialog itself. Both accepting and rejecting should hide the dialog and set `dialogOpen = false` so the player can continue playing and pick up another item.
> 1 votes

---
Tags: unity, javascript, unityscript
---


title: Continuously Fire like machine gun

text:
# Question
Title: Continuously Fire like machine gun
I made the game space shooter and i want the space fire continuously (auto fire) without click the button. \[ This are the code i always click on space bar and its fire but i want its fire continuously (auto fire). if (Input.GetKeyDown (KeyCode.Space) && isEnemyWeapon == false) { Fire (); } \] and i want only player fire continuously not enemy. In my case enemy also fire continuously like laser after taking some times..

Weapon.cs

```
using UnityEngine;
using System.Collections;

public class Weapon : MonoBehaviour {

    public Transform laserPrefab ;
    public bool isEnemyWeapon = false;
    public float shootDelay = 0.0f;
    private float waitToShoot;

    void Start () {
        waitToShoot = 0f;
    }

    void Update () {

        if (waitToShoot > 0) {
         waitToShoot = Time.deltaTime;

        }

    if (Input.GetKeyDown (KeyCode.Space) && isEnemyWeapon == false) {
          Fire ();
    }

        if (isEnemyWeapon == true && EnemyAttack == false) {
            waitToShoot = shootDelay;
            var shootLaser = Instantiate (laserPrefab) as Transform;
            Vector2 pos = shootLaser.transform.position;
            pos.x = transform.position.x ;
            pos.y = transform.position.y - 0.3f;
            shootLaser.transform.position = pos;
            SoundHelper.instanceSound.EnemyLaserSound();

        }
    }

    public void Fire()
    {
        var shootLaser = Instantiate(laserPrefab) as Transform;
        Vector2 pos = shootLaser.transform.position;
        pos.x = transform.position.x;
        pos.y = transform.position.y + 0.5f;
        shootLaser.transform.position = pos;
        SoundHelper.instanceSound.PlayerLaserSound();

    }

public bool EnemyAttack
    {
         get
        {
         return waitToShoot <= 0f;
        }
    }
}

```

# Answer
Here's the code which should work for you:

```
bool firingContinously = false; // is firing right now
float nextFire = 0; // when the next bullet fires
float fireDelay = 100; // 100 milliseconds between each bullet, you can change that

void Update(){
    if(firingContinously && !isEnemyWeapon)
    {
        if(Time.time * 1000 > nextFire){
            nextFire = (Time.time * 1000) + fireDelay; // delay the next fire by the fireDelay
            Fire();
        }
    }
}

```

In order to fire continously, you change `firingContinously` to `true`, and to stop - you change it to `false`.

I didn't test it. Copy the `Update()` method contents into your `Update()` method and these `3 variables` somewhere to your class so it looks like:

```
using UnityEngine;
using System.Collections;

public class Weapon : MonoBehaviour {

    public Transform laserPrefab ;
    public bool isEnemyWeapon = false;
    public float shootDelay = 0.0f;
    private float waitToShoot;

    public bool firingContinously = false;
    float nextFire = 0;
    float fireDelay = 100; // 100 milliseconds between each bullet

    void Start () {
        waitToShoot = 0f;
    }

    void Update () {

        if(firingContinously && !isEnemyWeapon)
        {
            if(Time.time * 1000 > nextFire){
                nextFire = (Time.time * 1000) + fireDelay;
                Fire();
            }
        }

        if (waitToShoot > 0) {
         waitToShoot = Time.deltaTime;

        }

        if (Input.GetKeyDown (KeyCode.Space) && isEnemyWeapon == false) {
              Fire ();
        }

        if (isEnemyWeapon == true && EnemyAttack == false) {
            waitToShoot = shootDelay;
            var shootLaser = Instantiate (laserPrefab) as Transform;
            Vector2 pos = shootLaser.transform.position;
            pos.x = transform.position.x ;
            pos.y = transform.position.y - 0.3f;
            shootLaser.transform.position = pos;
            SoundHelper.instanceSound.EnemyLaserSound();

        }
    }

    public void Fire()
    {
        var shootLaser = Instantiate(laserPrefab) as Transform;
        Vector2 pos = shootLaser.transform.position;
        pos.x = transform.position.x;
        pos.y = transform.position.y + 0.5f;
        shootLaser.transform.position = pos;
        SoundHelper.instanceSound.PlayerLaserSound();

    }

public bool EnemyAttack
    {
         get
        {
         return waitToShoot <= 0f;
        }
    }
}

```
> 0 votes

# Answer
First, you should not have one class for both your enemy weapon and your player weapon. Create a separate class for each of them. And having a base class could be a good idea too :

```
using UnityEngine;
using System.Collections;

public abstract class Weapon : MonoBehaviour {

    public Transform laserPrefab ;
    public float shootDelay = 0.1f;
    protected float nextFireTime;

    public abstract bool CanShoot
    {
        get;
    }

    void Start ()
    {
        nextFireTime = Time.time;
    }

    void Update ()
    {
        if ( CanShoot )
        {
            Fire ();
        }
    }

    public virtual void Fire()
    {
        nextFireTime = Time.time + shootDelay;
    }
}

```

---

```
using UnityEngine;
using System.Collections;

public class PlayerWeapon : Weapon {

    public override bool CanShoot
    {
        get { return Input.GetKey(KeyCode.Space) && Time.time >= nextFireTime  ; }
    }

    public override void Fire()
    {
        base.Fire();
        var shootLaser = Instantiate(laserPrefab) as Transform;
        Vector2 pos = shootLaser.transform.position;
        pos.x = transform.position.x;
        pos.y = transform.position.y + 0.5f;
        shootLaser.transform.position = pos;
        SoundHelper.instanceSound.PlayerLaserSound();
    }
}

```

---

```
using UnityEngine;
using System.Collections;

public class EnemyWeapon : Weapon {

    public override bool CanShoot
    {
        get { return Time.time >= nextFireTime ; }
    }

    public override void Fire()
    {
        base.Fire();
        var shootLaser = Instantiate (laserPrefab) as Transform;
        Vector2 pos = shootLaser.transform.position;
        pos.x = transform.position.x ;
        pos.y = transform.position.y - 0.3f;
        shootLaser.transform.position = pos;
        SoundHelper.instanceSound.EnemyLaserSound();
    }
}

```
> 0 votes

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


# Question
Title: Game engine tool generating game entities
I'm writing a game engine with an editor that allows you to create individual components like sprites, fonts, and particles. Then you're able to combine these individual components into what I call an "Entity", to create something more complex and whole.

Currently you can only construct an Entity through code. You derive a new class off of an `Entity` interface and its derived members are the components you wish it to have (sprites, texts, etc). You can then implement whatever new logic this Entity is supposed to do.

I want to be able to create these entities in my editor, so you're able to simply read a file at run time that loads in all the required components and initializes them to specified values.

* I can auto generate the c++ derived `Entity` class file, then deal with either auto importing it into the code project (or relying on the user to do so). I can directly generate the specified initialization code in the constructor. Makes for easiest access to components when implementing custom logic, and can ensure components' memory is contiguous for better cache.
* Or simply have the `Entity` base class read the file and stores all its required components in a std::vector. Initializing the components will require a robust, hefty function for parsing the file and applying the specified values. Accessing the components when implementing your logic will also be a pain, either remembering their indices, or using string names in a map (bleh).

I like the first auto generating solution better, but I'm afraid of the maintenance and upkeeping it may require. Also I can't just keep overwriting their class source file so I'll need them to separate their custom logic in another source file. Would want a clean way to do that, and possibly a clean way to auto import the source code into the project (The tool knows the source directory, and I guess I could put the whole declaration/definition in a header file).

Any insight on which implementation? Have you ever auto generated C++ code before and regretted it? Or is there an entirely better way?

# Answer
> 1 votes
> I like the first auto generating solution better, but I'm afraid of the maintenance and upkeeping it may require. Also I can't just keep overwriting their class source file so I'll need them to separate their custom logic in another source file. Would want a clean way to do that, and possibly a clean way to auto import the source code into the project (The tool knows the source directory, and I guess I could put the whole declaration/definition in a header file).

As @Quentin points out, several AAA game engines basically allow you to load .dll / .so files in their editors at runtime to expose custom objects.

The one aspect you need to consider is precisely how you intend to expose the metadata for your objects to the engine and editor.

One game engine I know uses a custom pre-processing step that essentially reads the compile units and translates macros into injectable code and then passes the final pre-processed compilation unit to the compiler.

In another engine, they use a special method the engine calls to build a hierarchical representation of the class, its methods, and properties so that the editor knows what is publicly exposed and can be changed but also what can be manipulated via other objects through scripts, etc.

After having used both approaches, I actually prefer the latter approach. It has one less overall step during compilation, less tools maintenance, while being just as easy to maintain code wise as the former.

---
Tags: c++, architecture, entity-system, tools
---


# Question
Title: Help developing a scoring system for a tech tree based game
I'm working on a tech tree based project in which the player would select "advancements" to effect several measurement stats, or "basic stats". I have a working excel model that will calculate the "scores" for these basic stats based on advancements selected, but I'd eventually like to use these measurement stats that I have to calculate higher level measurements like population or total production power.

For example in the case of calculating "Population", I'd like to take the (current pop + (current pop. * fertility rate)) - death rate. Fertility rate would be calculated based on the "basic stats" of "health" and "food supply", and death rate on metrics like "health" and "squalor".

I'm not really sure how to use these measurements though... If health and food supply both start at 0 and increased by 5 over the course of a few turns, how should I use these scores in a meaningful way to do what I'm trying to do in the case of fertility rate? Fertility rate should be expressed as a certain percentage of total pop. but I'm not sure how to get there from two scores of 5. I don't think this will be a simple process, but I feel like I'm missing some basic concepts to put this into place. Is there a name for this kind of scoring system?

Any ideas would be appreciated! Thanks.

# Answer
For your Population example, you are probably looking for a 'population model'. If you have interacting species, try something like the 'predator-prey' mathematical model:

(Wikipedia)

I believe a simpler model like the 'Logistic growth equation' (also see link on population models) is a simplification of these equations.
> 1 votes

# Answer
A general technique for taking several numbers and producing a single number from them when you don't know the precise relationship between them is a weighted sum.

Basically you select floating point weights for each score then multiply the current value of each state by its weight and sum that up to get your result.

So for your example you could use this formula:

```
fertility_rate = health * HEALTH_WEIGHT + food * FOOD_WEIGHT + squalor * SQUALOR_WEIGHT;

```

where HEALTH\_WEIGHT, FOOD\_WEIGHT and SQUALOR\_WEIGHT are constants that you can tweak to get the effect you want.
> 1 votes

---
Tags: game-design, game-mechanics
---


title: How to securely submit a score?

text:
# Question
Title: How to securely submit a score?
We have an app with several mini-games in it and in each a highscore can be achieved. The score gets submitted by requesting an endpoint and passing the score as a json in the body. How can we be sure that the client is sending us the correct score? Our current solutions:

* we're using wss, so man in the middle should be not possible
* the client can access the endpoint only after authenticating with his device (over gamesparks)
* at least on Android we're obfuscating the code
* we're saving each score in two different variables and comparing them before sending one of them

Is there anything more we can do to secure the game? It seems to be quite effective to just submit the player interactions and calculate the scores server-side, but that seems - because of our several completely different games - to complicated in our case. What is about creating a hash of the score and comparing it on the server?

# Answer
Ultimately you can't, unless you execute all game mechanics on your server. The app runs on the user's device. Any code running on the user's device is under their control. The best you could try which might buy you a few days of cheater-free competition is using cryptographic signatures.

1. Generate an RSA keypair
2. Add a private key to the app
3. Sign each score update with that private key
4. Use the public key to verify the signature on the server

This will work until a hacker extracts your private key from your app. Then they can build their own app to submit fake scores.
> 1 votes

# Answer
One way might be to detect abnormal increments in score. For example, if you know the max score attainable per time-step is 15, then the score cannot increment more than 15 per time-step. This can be done locally, and on server-side periodically via interpolation (since it's expensive to send messages every time-step).
> 0 votes

# Answer
Maybe instead of sending a score, you can send an action to the server, then the server will calculate the new score and resend it to the client, with this approach you can make some statistics like how much time is taking for a player to complete a task and make some averages
> 0 votes

---
Tags: security, leaderboards, websocket, anti-cheat
---


# Question
Title: How can I parse different types of objects from JSON?
I'm trying to save the player's inventory as a JSON data but I'm having a problem. I have a class `Sword` which extends an abstract class `Weapon` which extends another abstract class called `Item`. This is what JSON file looks like with the Sword and Armor objects in it:

```
[
    {
        "category": {
            "type": "Weapon",
            "subtype": "Sword"
        },
        "id": 0,
        "value": 1,
        "name": "Wooden Sword",
        "description": "Sword made out of wood",
        "slug": "wooden_sword",
        "stats": {
            "wear": 100,
            "damage": 5
        }
    },
    {
        "category": {
            "type": "Armor",
            "subtype": "Helmet"
        },
        "id": 1337,
        "value": 1,
        "name": "Steel Helmet",
        "description": "Whatever...",
        "slug": "steel_helmet",
        "stats": {
            "wear": 100,
            "defence": 5,
            "vitality": 3,
            "dexterity": -1
        }
    }
]

```

How can I parse these objects into their respective C# objects, putting the first entry into a `Sword` object and the second one into a `Helmet` object. There will be other types of objects in there too, so it's not limited on these two.

# Answer
> 1 votes
Directly converting these objects using JSONUtil won't work in this case.

What you could do instead is parse it into an intermediate data-structure first. Create a `struct` which directly mimics the structure of that JSON code (with a `category` variable which is another struct with the fields `type` and `subtype`).

You can then use the data in that structure to instantiate the actual objects of the correct types.

---
Tags: unity, savegame, data, json
---


# Question
Title: Why is my sprite moving 90 degrees to the right?
I have a sprite which i'm trying to move towards the top of the screen with the left and right buttons adjusting the heading.

However when my `heading = 0;` my sprite moves off to the right.

Here's what im using to adjust my heading:

```
function calcHeading() {
        if (heading>360 ) {
            heading = 0;
        } else if (rightPressed) {
            heading++
        } else if (leftPressed) {
            heading--
        }

        if (heading<0) {
            heading = 359;
        }
}

```

Heres what im using to adjust my x and y positions:

```
    function adjustBoatPos() {
    boatDX = Math.cos(heading * (Math.PI / 180));
    boatDY = Math.sin(heading * (Math.PI / 180));

    boatPosX = boatPosX + boatDX;
    boatPosY = boatPosY + boatDY;
}

```

I can fix this by rotating my sprite in the function that draws it like this:

```
function drawBoat() {
    drawImageRot(boat, boatPosX-(boatWidth/2), boatPosY-(boatHeight/2), boatWidth, boatHeight, heading+90);
}

```

however this "solution" makes the heading variable incorrect(when moving up it is 270)

How can i make my sprite move towards the top of the screen when the `heading = 0`?

I'm using pure JavaScript and a `<canvas>` element.

```
var canvas = document.getElementById("game-window"); //store a reference to the canvas element
 var ctx = canvas.getContext('2d'); // create a variable to store the 2d rendering context
 var canvasWidth = 256; //set the canvas width...
 var canvasHeight = 256; //... and height

 var boat = new Image(); //create new image element for boat
 var boatWidth = 16; //define the sprites width...
 var boatHeight = 16; //... and height
 boat.src = 'https://github.com/Synj24/expert-potato/blob/master/crappy-placeholder.png?raw=true'; //set souce of boat image

 var map =  new Image(); //create a new image element for the map
 var mapWidth = 768; //define the maps width...
 var mapHeight = 768; //... and height
 map.src = 'https://github.com/Synj24/expert-potato/blob/master/crappy-placeholder-map.png?raw=true' //set source of the map image

 var rightPressed = false;
 var leftPressed = false;

 var heading = 0;
 var vHeading = 0.01;

 var boatPosX = canvasWidth/2;
 var boatPosY = canvasHeight/2;
 var boatDX = 0;
 var boatDY = 0;

 document.addEventListener("keydown", keyDownHandler, false);
 document.addEventListener("keyup", keyUpHandler, false);

 function keyDownHandler(e) {
     if(e.keyCode == 39) {
         rightPressed = true;
     }
     else if(e.keyCode == 37) {
         leftPressed = true;
     }
 }
 function keyUpHandler(e) {
     if(e.keyCode == 39) {
         rightPressed = false;
     }
     else if(e.keyCode == 37) {
         leftPressed = false;
     }
 }

 function adjustBoatPos() {
  boatDX = Math.cos(heading * (Math.PI / 180));
  boatDY = Math.sin(heading * (Math.PI / 180));

  boatPosX = boatPosX + boatDX;
  boatPosY = boatPosY + boatDY;
 }

 function calcHeading() {
   if (heading>360 ) {
    heading = 0;
   } else if (rightPressed) {
    heading++
   } else if (leftPressed) {
    heading--
   }

   if (heading<0) {
    heading = 359;
   }
 }

 function debugText(x,y) {
  ctx.fillStyle = "grey";
  ctx.fillRect(x, y+17, 80, 100);
  ctx.font = "bold 16px Arial";
  ctx.fillStyle = "#FB5167";
  ctx.fillText("  X:"+Math.round(boatPosX * 100) / 100, x+2, (y+25) +8);
  ctx.fillStyle = "#FBE551";
  ctx.fillText("  Y:"+Math.round(boatPosY * 100) / 100, x+2, (y+25) +24);
  ctx.fillStyle = "#FB9051";
  ctx.fillText("dX:"+Math.round(boatDX * 100) / 100, x+2, (y+25) +40);
  ctx.fillStyle = "#FB51BC";
  ctx.fillText("dY:"+Math.round(boatDY * 100) / 100, x+2, (y+25) +56);
  ctx.fillStyle = "#BCFB51";
  ctx.fillText("  H:"+heading, x+2, (y+25) +72);
  ctx.fillStyle = "#9051FB";
  ctx.fillText("vH:"+vHeading, x+2, (y+25) +88);
 }

 function drawImageRot(img,x,y,width,height,deg){
     var rad = deg * Math.PI / 180; //Convert degrees to radian
     ctx.translate(x + width / 2, y + height / 2); //Set the origin to the center of the image
     ctx.rotate(rad); //Rotate the canvas around the origin
     ctx.drawImage(img,width / 2 * (-1),height / 2 * (-1),width,height); //draw the image
     ctx.rotate(rad * ( -1 ) );
     ctx.translate((x + width / 2) * (-1), (y + height / 2) * (-1)); //reset the canvas
 }

 function drawBoat() {
  drawImageRot(boat, boatPosX-(boatWidth/2), boatPosY-(boatHeight/2), boatWidth, boatHeight, heading);
 }

 function drawMap() {
  ctx.drawImage(map, (mapWidth/3-canvasWidth*2), (mapHeight/3-canvasHeight*2));//draw the map
 }

 function draw() {
  ctx.clearRect(0 ,0, canvasWidth, canvasHeight); //clear the canvas
  drawMap();
  calcHeading();
  adjustBoatPos();
  drawBoat();
  debugText(0, canvasHeight/2);
 }
 setInterval(draw, 10);
```

```
<canvas id="game-window" width="256px" height="256px"></canvas>
```

# Answer
Your boat goes left when heading is `0` because *cos( 0 )* is `1` which is the delta you give to your `boatPosX`.

Since your boat image is draw pointing upwards this makes it point the wrong way as a zero rotation for the image is **up**, whilst a zero heading for the velocity is **right**.

You can either re-draw the image so that it points right or subtract `90` from the `heading` before doing the `cos` and `sin` operations;

```
boatDX = Math.cos((heading - 90) * (Math.PI / 180));
boatDY = Math.sin((heading - 90) * (Math.PI / 180));

```

You can try the last solution at JSFiddle.
> 0 votes

---
Tags: javascript, rotation, trigonometry
---


# Question
Title: Profiling unity games on Android devices
I would like to profile our Unity mobile game on Android devices in a way similar to profiling Unity games on iOS with Instruments.

I am aware of how to do this using Unity's profiler, I would however like to use a third party profiler for the following reasons:

* to validate Unity's profiling data
* to have more visibility into how the app is running, including Unity's functions, etc.
* the largest lag spikes cause unity's profiler to run out of samples. I'm however very interested in precisely these spikes
* I'd like to have profile data for longer periods than unity records for
* I'd like to do analysis over time (not just detailed data for each frame, but also aggregated over a time span)

Essentially I'd like as much visibility as possible to make Android on-device profiling as comprehensive as possible. As close to Instruments on iOS as possible.

So far I've tried with DDMS, but could only get visibility into Andoid OS functions and seeminly nothing in the actual apk - at least nothing I recognised. I tried with mono2x and il2cpp, with all debug features that I'm aware of in build and player settings enabled.

The game is developed with Unity 5,4 with Mono2x.

All help is appreciated. I've listed my intents above, so even if profiling on device is not possible in this way on Andoid, alternate solutions to the listed intents are still very appreciated. Thanks!

# Answer
> 1 votes
In the Android developer options portion of android settings, there are several options for profiling the gpu and cpu. The gpu-profiling option displays the gpu usage as colorful vertical bars on the screen, while the cpu-profiling option displays horizontal bars corresponding to each process on the system. There is a "record in adb shell dumpsys gfxinfo" option for gpu profiling, but I never used it, so I don't know if it records the data the way you want.

---
Tags: unity, android, profiling
---


# Question
Title: Why should I not use MySQL for a browser based game?
I keep reading on here that I shouldn't use MySQL for game development/play on the Internet, a browser game. I understand MySQL wasn't made necessarily for that and for big relational needs. Ok. But what do I use then? I am on a shared hosting, Unix/Linux platform. What do I use to store my "stats" or other game necessities, level information, player information, etc.

# Answer
> 12 votes
## Of Course You Can Use MySQL

Let's get this out of the way: lots of successful games and their related companies use MySQL. Riot Games (League of Legends) does, Big Fish Games has a small case-study done by Oracle about their use and optimization of MySQL, an Oracle Principle Infrastructure Architect has a slideshow of a talk they give on using MySQL for high popularity social games (one uses 1000+ dedicated servers), ad infinitum.

It's an industry standard, it's free, it's tremendously scalable, support is available all over the place...its a great system.

## ...But Use It Correctly

The best, bleeding-edgiest database system on earth won't save you from, say, deciding to store all the textures for a FPS game as a BLOB in the database and trying to load/unload them in real time across a server connection. You're gonna have a bad time.

RDBMS are for Storing information in an intelligent, structured way, where it is assumed that there will be Relationships between the various pools of data. There are Players, and they'll have Highscores, and they'll have Account Information, and there will be Logins, and (hopefully) Transactions and Purchases, and so forth, and that's exactly what things like MySQL was designed to handle.

The rest of the stuff really depends on the game. Graphics? It's usually just plain easier to use a regular file folder structure. Live updates of exact player xyz location as in an MMO? Probably not something to use the database for, but only if something better than using fopen is an option (which usually isn't available in shared hosting environments). But what 'zone' a player is in? Sure, why not!

The same rules apply to games as they do anywhere else - don't ask for more than you really need (avoid SELECT * without a conditional, unless that's what you really wanted), and expect to get cozy with query analyzers and profilers if things start getting sluggish.

## Is MySQL the Only/Best Option

No, and of course not/maybe. It's a great system, it works. I dislike SQL, yet ORM tools make it invisible and I like some of them a lot. NoSQL solutions abound, and they have their unique strengths and weaknesses, too.

MySQL is like a chef's knife - it can get the job done. Sometimes you'd be better off with a paring knife or a cleaver, but lets face it - sometimes you just want to whack something with a reasonable-sized knife and get on with your day.

# Answer
> 2 votes
I personally find MySQL is ok to use for browser games but it depends on the **type of game**. I can't stress that enough!!!

For storing basic player information yes its perfectly fine.. just don't use `mysql_*` as it is no longer supported for the future.

Other things however:

For example, is your game turned based, think like civilization franchise, this using mySQL is easily doable and i see no downside if you plan your tables correctly. Same for any games that use timers rather than "real time" updates.

However im not so sure it's wise if you plan to use MYSQL to store a user's location which updates in `real time` for other users to see the person on a map. This needs to sync with other players constantly for every player in the given area.

Continuously updating user locations and selecting user's locations from the database like that would basically be like DDosing your server to the point it overloads and lags / crashes.

For live real time syncing between players you want to look into websockets. You don't want to store the user's exact positions but a "rough" position then let websockets fine tune in that area where the user is precisely.

Websockets is not hugely supported however, although the major players Firefox, Chrome and IE support them sufficiently.... the use of websockets can be looked into with node.js. Which is javascript but for server side.

Linking that with client side HTML5 canvas features would be the way to go.

See here for a working example and the code is freely available to look at BrowserQuest and its source code

TL;DR - it totally depends on what your game will be.....

# Answer
> 0 votes
MYSQL is a very good tool to use due to is capability of handling lot of data storage, most especially when you're developing an internet base football manager game, it will be capable of holding your various team data.thus this will take allot of query coding......but you know the says, Persistence leads to achievement!.

---
Tags: mysql
---


# Question
Title: How do you chase a changing value with ease in and ease out
Assume you have a target that changes. Example:

```
// on average every 1000 frames, move the target
if (random(1000) == 0) {
    // pick a value between 0 and 999
    target = random(1000);
}

```

Now, I want to chase that value with both ease in and ease out. With just ease out a common solution is this

```
const kApproachFudge = 0.03;
value += (target - value) * kApproachFudge;

```

That only gives ease out though. Another might be to use a kind of `arrive` behavior with acceleration and deceleration but that seems like overkill and is often fiddly meaning if your deceleration is not fast enough you'll overshoot the target. If you max speed is too high you might also overshoot the target. For example

```
function main()
{
  g_a = new Arriver();

  g_canvas = document.getElementById("canvas");
  g_ctx = g_canvas.getContext("2d");

  var then = getTime();
  function mainLoop()
  {
    var now = getTime();
    var elapsedTime = Math.min(0.1, now - then);
    then = now;
    resizeCanvas();
    update(elapsedTime, g_ctx);

    requestId = requestAnimFrame(mainLoop, g_canvas);
  }
  mainLoop();
}

function update(elapsedTime, ctx)
{
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

    g_a.update(elapsedTime);
    if ((g_a.distToTarget < 1 && g_a.velocity.length() < 5) ||
        randInt(200) == 0)
    {
       g_a.setTarget(
         randInt(ctx.canvas.width - 100) + 50,
         randInt(ctx.canvas.height - 100) + 50);
    }
    drawCircle(ctx, g_a.target.x, g_a.target.y, 10, "#00ff00");
    drawCircle(ctx, g_a.value.x, g_a.value.y, 10, "#ff80ff");
    drawLine(ctx,
         g_a.value.x, g_a.value.y,
         g_a.value.x + g_a.velocity.x * 1, g_a.value.y + g_a.velocity.y * 1,
         "black");
    drawLine(ctx,
         g_a.value.x, g_a.value.y,
         g_a.value.x + g_a.acceleration.x * 1, g_a.value.y + g_a.acceleration.y * 1,
         "red");
}

function getTime()
{
  return(new Date()).getTime() * 0.001;
}

// return int from 0 to range - 1
function randInt(range)
{
  return Math.floor(Math.random() * range);
}

function drawLine(ctx, x1, y1, x2, y2, color)
{
  ctx.beginPath();
  ctx.strokeStyle = color;
  ctx.moveTo(x1, y1);
  ctx.lineTo(x2, y2);
  ctx.stroke();
}

function drawCircle(ctx, x, y, radius, color)
{
  ctx.fillStyle = color;
  ctx.beginPath();
  ctx.arc(x, y, radius, 0, Math.PI * 2, false);
  ctx.fill();
}

function drawCircleLine(ctx, x, y, radius, color)
{
  ctx.strokeStyle = color;
  ctx.beginPath();
  ctx.arc(x, y, radius, 0, Math.PI * 2, false);
  ctx.stroke();
}

function resizeCanvas()
{
  if (g_canvas.width != g_canvas.clientWidth ||
      g_canvas.height != g_canvas.clientHeight)
  {
    g_canvas.width = g_canvas.clientWidth;
    g_canvas.height = g_canvas.clientHeight;
  }
}

function Vec2(x, y) {
  this.set(x, y);
}

Vec2.prototype.set = function(x, y)
{
  this.x = x;
  this.y = y;
  return this;
};

Vec2.prototype.copy = function(b)
{
  this.x = b.x;
  this.y = b.y;
  return this;
};

Vec2.prototype.add = function(b, dest)
{
  dest = dest || this;
  dest.x = this.x + b.x;
  dest.y = this.y + b.y;
  return this;
};

Vec2.prototype.addScaled = function(b, scale, dest)
{
  dest = dest || this;
  dest.x = this.x + b.x * scale;
  dest.y = this.y + b.y * scale;
  return this;
};

Vec2.prototype.subtract = function(b, dest)
{
  dest = dest || this;
  dest.x = this.x - b.x;
  dest.y = this.y - b.y;
  return this;
};

Vec2.prototype.scale = function(b, dest)
{
  dest = dest || this;
  dest.x = this.x * b;
  dest.y = this.y * b;
  return this;
};

Vec2.prototype.truncate = function(max, dest)
{
  dest = dest || this;
  var length = this.length();
  if (length > max)
  {
    this.scale(max / length, dest);
  }
  return this;
};

Vec2.prototype.lengthSq = function() {
  return this.x * this.x + this.y * this.y;
};

Vec2.prototype.length = function() {
  return Math.sqrt(this.lengthSq());
};

Vec2.prototype.normalize = function(dest) {
  dest = dest || this;
  var length = this.length();
  if (length > 0.000001)
  {
    dest.x /= length;
    dest.y /= length;
  }
  return this;
};

function Arriver()
{
  this.value = new Vec2(0,0);
  this.target = new Vec2(0,0);
  this.velocity = new Vec2(0,0);
  this.maxSpeed = 150;
  this.deceleration = 0.6;
  this.zero = new Vec2(0,0);
  this.tempDelta = new Vec2(0,0);
  this.force = new Vec2(0, 0);
  this.acceleration = new Vec2(0,0);
  this.mass = 1;
  this.distToTarget = 0;
};

Arriver.prototype.setValue = function(x, y) {
  this.value.set(x, y);
}

Arriver.prototype.setTarget = function(x, y) {
  this.target.set(x, y);
  this.target.subtract(this.value, this.tempDelta);
  this.distToTarget = this.tempDelta.length();
}

Arriver.prototype.calcDesiredForce_ = function(elapsedTime) {
  this.target.subtract(this.value, this.tempDelta);

  this.distToTarget = this.tempDelta.length();
  if (this.distToTarget <= 0)
  {
    return this.zero;
  }

  var speed = this.distToTarget / this.deceleration;
  speed = Math.min(speed, this.maxSpeed);

  this.tempDelta.scale(speed / this.distToTarget);
  this.tempDelta.subtract(this.velocity);

  return this.tempDelta;
};

Arriver.prototype.update = function(elapsedTime) {
  this.force.copy(this.calcDesiredForce_());
  this.force.scale(1 / this.mass, this.acceleration);
  this.velocity.addScaled(this.acceleration, elapsedTime);
  this.velocity.truncate(this.maxSpeed);
  this.value.addScaled(this.velocity, elapsedTime);
};

// shim layer with setTimeout fallback
window.requestAnimFrame = (function(){
  return window.requestAnimationFrame  ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame    ||
    window.oRequestAnimationFrame      ||
    window.msRequestAnimationFrame     ||
    function( callback ){
      window.setTimeout(callback, 1000 / 60);
  };
})();

main();
```

```
html, body {
  width: 100%;
  height: 100%;
  border: 0px;
  padding: 0px;
  margin: 0px;
  font-family: sans-serif;
  overflow: hidden;
}
canvas {
  width: 100%;
  height: 100%;
}
#legend {
  position: absolute;
  left: 1em;
  top: 1em;
  z-index: 2;
}
```

```
<canvas id="canvas" width="1024" height="1024"></canvas>
<pre id="legend">
---[ legend ]---
pink:  vehicle
green: target
black: velocity
red:   acceleration
</pre>
```

I can sit there and just max force and max velocity and mass and deceleration but then it's so damn fiddley. If I want it to go faster I have to first adjust max vel, then maybe I have to adjust max force to it started quicker but then it will over shoot the target and I have to adjust other factors. I have to imagine this is a solved problem.

Is there a simple algorithm that ALWAYS gives good results?

note: I'm not looking for an ease in / ease out function between 2 fixed values. I have that in my toolbox and there are several answers here as well. There's probably an answer for this too but I didn't find it.

---

The answers claimed to be duplicate \** DO NOT ANSWER THIS QUESTION \**

Those answers assume a known starting distance to target and pick the 1/2 way mark as the spot to start slowing but if the target is moving *there is no 1/2 way spot*. Since you'll be recalculating every frame you'll always be a 0% of the way to target from your current position

# Answer
> 1 votes
You should have a look at the animations functions in jQuery. I use them to get the math right in my own easing functions.

Here is an example of them in action... http://jqueryui.com/demos/effect/easing.html

I should add that each of these returns a value used like this..

currentValue = startValue + easeFunction(x, t, b, c, d) * (endValue - startValue)

```
 // jQuery Ease Functions
 x = 0 - 1 as float of completion
 t = elapsed time in ms
 b = 0
 c = 1
 d = duration in ms

    easeInQuad: function (x, t, b, c, d) {
        return c*(t/=d)*t + b;
    },
    easeOutQuad: function (x, t, b, c, d) {
        return -c *(t/=d)*(t-2) + b;
    },
    easeInOutQuad: function (x, t, b, c, d) {
        if ((t/=d/2) < 1) return c/2*t*t + b;
        return -c/2 * ((--t)*(t-2) - 1) + b;
    },
    easeInCubic: function (x, t, b, c, d) {
        return c*(t/=d)*t*t + b;
    },
    easeOutCubic: function (x, t, b, c, d) {
        return c*((t=t/d-1)*t*t + 1) + b;
    },
    easeInOutCubic: function (x, t, b, c, d) {
        if ((t/=d/2) < 1) return c/2*t*t*t + b;
        return c/2*((t-=2)*t*t + 2) + b;
    },
    easeInQuart: function (x, t, b, c, d) {
        return c*(t/=d)*t*t*t + b;
    },
    easeOutQuart: function (x, t, b, c, d) {
        return -c * ((t=t/d-1)*t*t*t - 1) + b;
    },
    easeInOutQuart: function (x, t, b, c, d) {
        if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
        return -c/2 * ((t-=2)*t*t*t - 2) + b;
    },
    easeInQuint: function (x, t, b, c, d) {
        return c*(t/=d)*t*t*t*t + b;
    },
    easeOutQuint: function (x, t, b, c, d) {
        return c*((t=t/d-1)*t*t*t*t + 1) + b;
    },
    easeInOutQuint: function (x, t, b, c, d) {
        if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
        return c/2*((t-=2)*t*t*t*t + 2) + b;
    },
    easeInSine: function (x, t, b, c, d) {
        return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
    },
    easeOutSine: function (x, t, b, c, d) {
        return c * Math.sin(t/d * (Math.PI/2)) + b;
    },
    easeInOutSine: function (x, t, b, c, d) {
        return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
    },
    easeInExpo: function (x, t, b, c, d) {
        return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
    },
    easeOutExpo: function (x, t, b, c, d) {
        return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
    },
    easeInOutExpo: function (x, t, b, c, d) {
        if (t==0) return b;
        if (t==d) return b+c;
        if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
        return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
    },

```

# Answer
> 1 votes
I think your behaviorally-based approach is right on the money - and I'm not sure that overshooting your target is the problem that you're making it out to be. What you're describing is essentially a 1d steering behavior, and overshoot is an inevitable element of that behavior. Think of it this way: suppose you started at x=0 and you're after a current target of target\_x=1000, with your cur\_x=800 when a new target is chosen 'behind you' at target\_x=700. You presumably wouldn't want your 'chase' to stop on a dime and flip velocity instantaneously, because that would be an implausible acceleration and a discontinuous velocity — basically, a 'kink' in your curve. Instead, you'd keep incrementing cur\_x a little until you were able to change your velocity to the point of starting to decrement it towards target\_x. The same behavior should be true if target\_x=750, or if target\_x=799 — and it stands to reason by 'continuity of behavior' that it should still be true if target\_x is just ahead of you, say target\_x=850.

As far as the specifics on either end of the curve, I think the best way to handle 'ease out' from a stopped position would be your suggested approach of putting a limit on acceleration; for symmetry purposes, then, you'd probably want your ease-in to be symmetric, with just enough lookahead to know when it should start decelerating in order to hit the target position 'on the nose'. Alternately, if you don't care about precisely hitting your target when it ultimately 'holds still', you could use an exponentially damped approach where you have a target velocity v given by v=dx/dt = C\*|x\_target-x| (with C the constant controlling the damping behavior) and you clamp your acceleration attempting to reach that target velocity; this will give asymmetric ease-in and ease-out (since ease-out from a stop will be quadratic, but ease-in to a stop will be exponential) but makes the updates slightly easier since there's no real lookahead involved.

# Answer
> 1 votes
Daniel Shiffman described your desired behavior in chapter 6 of his book The Nature of Code. That link leads directly to a live example of the behaviour. All code snippets are in Java.

Basically, you keep track of a velocity. Then calculate a desired velocity which points towards the target but has a magnitude equal to the maximum speed. Then you calculate a steering vector which is equal to your desired velocity minus your actual velocity. Then you add steering to your velocity.

To slow down and stop at the target, your set a threshold radius around your target. When your object is within this radius, you set your desired velocity depending on how close you are to the target.

Please read the chapter for a proper explanation with diagrams, code snippets and live examples.

I implemented this technique today to animate the motion of the camera following the player. This is really easy to implement and looks really nice. It does take some fiddling to get working though. Trying to get the perfect values of the constants took me about an hour but my camera moves really nicely now.

I don't think there is one perfect solution that doesn't require fiddling with constants because everyone's desired behaviour is different.

---
Tags: animation, ai
---


# Question
Title: Build a convex hull from a given mesh in Bullet
According to this tutorial, a convex hull is the most accurate shape one can build from a mesh? I have two questions regarding this:

1. How do I build a convex hull from a given, complex mesh in Bullet?
2. Should this be done offline? How do most people do this? (that is, create a collision shape from a mesh in games)

# Answer
> 4 votes
You can do it using `btConvexHullShape`, calling the `addPoint` method. But that's usually not what you want. You should manually make a much much simpler collision mesh in your 3D modeling tool. Collision meshes don't have to be detailed. Use only a few triangles.

A good way to create an accurate representation is to use a compound shape (`btCompoundShape`) made of convex shapes since working with concave shapes directly is cumbersome. Here I explain how to export *.bullet* files from Blender which can then be imported in Bullet using `btBulletWorldImporter` http://xissburg.com/post/export-bullet-from-blender/

---
Tags: physics, bullet-physics
---


# Question
Title: How to hide fbx files for commercial release
I see that all commercial games I've played never expose their fbx files - usually, they archive the fbx files into PAK file or BIN file. For example, Torchlight 2 use OGRE3D for their Graphic Engine, and at the loading screen, they un-pack the PAK file. How do they do that?

# Answer
> 0 votes
Commercial games usually don't use .fbx as their runtime format. They have converters that convert .fbx into their engine's own format because then they don't have to ship an .fbx reader that's huge/complex/not supported on all platforms.

---
Tags: models, fbx, resource-management, 3d-modeling
---


# Question
Title: How to integrate admob ads in Unity 5.6.2f1
I made the game space shooter. But i don't know how to integrate admob ads in Unity. I downloaded Google Admob ads Plugin for unity. But where i write the code don't know and how to implement it!!

# Answer
There is no short answer to your long question, please study one of guide given below.

**Ads Implementation in Unity Using AdMob**

**ADMob for Unity By Google**

**Unity-Admob Github**

**Unity Forums Thread On AdMob**
> 1 votes

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


# Question
Title: Baked GI artifacts with Blender and Unity
I've created a very simple model in blender, exported it as FBX and imported in Unity. When I generate light maps on unity I got these strange artifacts (check the images attached here). I've verified the normals and they seems to be correct, the model has been exported with rotation and scale set to 0... any idea where those artifacts are coming from?

# Answer
Hello I was able to fix this issue. Actually the problem was related to the UVs. For this model I had some overlapping UVS and since I haven't selected the option to generate UV lightmap from Unity the final lightmaps were a mess.

You have three options to fix this issue:

1) Avoid overlapping UVs

2) Create a new UV channel from your 3d editor annd be sure that those UVs don't overlap. unity will automatically pick the second channel for the lightmap and uses the first channel for texture etc.. (I'm not sure about that but this is what I'm reading... I can't find it in the documentation though, please confirm that in case!)

3) With the model selected in unity go to the inspector and select "Generate lightmap UVs" unity will generate a new uv set for lightmap for you (this solution for me doesn't work really well... I choosed option 1.
> 0 votes

---
Tags: unity, blender, fbx
---


# Question
Title: Isometric Tile-Based Pixel Game Code Structure
I'm starting to hit some tricky bits in my Java project.

So far, I have drawn the following isometric tile:

And written some Java code to display it as a map:

I do this by looping over an array of tiles and drawing them on a JPanel. I have also implemented layers so that I can draw objects on top of the ground, etc. So far I have set up some basic classes such as Tile and Level but I'm starting to hit some real complexities.

My question is, with such a project, should I be drawing everything in a normal 2d perspective and rotating them? Or is drawing them isometrically and overlapping them the correct approach?

Is anyone aware of any resources that I can follow that take a similar approach to myself? I've had a Google but everyone seems to take a different approach.

# Answer
**2D** It *is* normal for 2D games to have these drawn and ordered / overlapped by code (loop), using e.g. the painter's algorithm. However, there are special conditions for constructing complex isometric terrain in 2D and you should look around at other Q&A on this site by typing `[isometric]` (tag) into the search bar at top right of this page. You want to get this right from the start, or it can be a headache.

**3D** Full 3D not only enables an isometric perspective, but any other that you might like as well. Of course, full 3D is *much* more work, since (at least) you will then be building 3D models for everything.

**Hybrid** Between pure 2D and full 3D approaches, there are some midway solutions: You can for example go for 3D terrain with fixed camera declination, allowing you to rotate around the up axis, but have the characters and items on the ground be billboarded images that they look the same from any camera angle. This greatly reduces the amount of work you need to do.

P.S. We do not list resources here, but you are welcome to take this information and use it to research your problems further. Google is your eternal friend.
> 4 votes

---
Tags: java, isometric, pixel-art
---


title: Circles within circle (PUBG safe zone)

text:
# Question
Title: Circles within circle (PUBG safe zone)
I'm attempting to do something that resembles the safe zone in PUBG (PLAYERUNKNOWN'S BATTLEGROUNDS), a circular area on the map that shrinks over time.

On map screen:

```
draw circle at rand X Y, 300 pixels wide

```

After say 5 minutes, I want to edit the X, Y and WIDTH of the circle so the new, smaller circle sits at a random position inside the old one.

# Answer
If the first circle is at `(x1, y1)` with a radius of `r1` and the second circle is to have a radius `r2` (that is smaller than `r1`) then the second circle needs to be **somewhere within** a circle that has its center at `(x1, y1)` and have a radius that is equal `r1 - r2` (I'll call this difference `delta`).

Then, using the circle equation, `(x-a)*(x-a)+(y-b)*(y-b)=r*r` and (for simplicity) assuming a center at `(0, 0)` we get that `x*x-y*y=r*r`. That is to say if we know that the second circle is at `x2` (which we know is in the range `[0, delta]`), then the only valid values for `y2` are in the range `[0, sqrt(delta*delta - x*x)]`

This, in turn means that if you randomly select a valid value for `x2`, you can solve for `y2`.

```
    Circle last = circles.get(circles.size() - 1);
    float newRadius = 0.8f * last.r; // Next circle is 80% of last
    float delta = last.r - newRadius;

    float x = (rnd.nextFloat() * delta) * (rnd.nextBoolean() ? 1.0f : -1.0f);
    float maxY = (float)Math.sqrt(delta*delta - x*x);

    float y = rnd.nextFloat() * maxY *  (rnd.nextBoolean() ? 1.0f : -1.0f);
    circles.add(new Circle(last.x+x, last.y+y, newRadius));

```

Note that I do a `rnd.nextBoolean()` because the range is actually not the radius but the diameter (`2 * delta`) but I want it around zero.

A full working java example here;

```
package com.bornander.circles;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Random;

import javax.swing.JFrame;

public class Program extends JFrame {

private static Random rnd = new Random();

private static class Circle {
    public float x;
    public float y;
    public float r;
    public Circle(float x, float y, float r) {
        this.x = x;
        this.y = y;
        this.r = r;
    }
}

private Color[] colors = new Color[] {
        Color.RED,
        Color.BLUE,
        Color.BLACK,
        Color.WHITE,
        Color.MAGENTA,
        Color.WHITE
};

private ArrayList<Circle> circles = new ArrayList<Circle>();

public Program() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(800, 600);
    setVisible(true);
    circles.add(new Circle(400, 300, 200));
    addMouseListener(new MouseListener() {

        @Override
        public void mouseClicked(MouseEvent arg0) {
            addCircle();
        }

        @Override
        public void mouseEntered(MouseEvent arg0) { }

        @Override
        public void mouseExited(MouseEvent arg0) { }

        @Override
        public void mousePressed(MouseEvent arg0) { }

        @Override
        public void mouseReleased(MouseEvent arg0) { }
    });
}

private void addCircle() {
    Circle last = circles.get(circles.size() - 1);
    float newRadius = 0.8f * last.r; // Next circle is 80% of last
    float delta = last.r - newRadius;

    float x = (rnd.nextFloat() * delta) * (rnd.nextBoolean() ? 1.0f : -1.0f);
    float maxY = (float)Math.sqrt(delta*delta - x*x);

    float y = rnd.nextFloat() * maxY *  (rnd.nextBoolean() ? 1.0f : -1.0f);
    circles.add(new Circle(last.x+x, last.y+y, newRadius));

    repaint();
}

@Override
public void paint(Graphics graphics) {
    Graphics2D g = (Graphics2D)graphics;
    g.setColor(Color.GREEN);
    g.fillRect(0, 0, getWidth(), getHeight());

    int index = 0;
    for(Circle circle : circles) {
        g.setColor(colors[(index++) % colors.length]);
        int x = (int)(circle.x - circle.r);
        int y = (int)(circle.y - circle.r);
        int d = (int)(2 * circle.r);
        g.fillOval(x, y, d, d);
    }
}

public static void main(String[] args) {

    Program program = new Program();

}

}

```

Just keep clicking to add new circles. This example generates a new circle that has an 80% radius of the previous one.
> 3 votes

---
Tags: geometry, random
---


# Question
Title: LibGDX how to remove PointLight that is attached a destroyed Body
I have this code:

```
@Override
public void beginContact(Contact contact) {
    fa = contact.getFixtureA();
    fb = contact.getFixtureB();

    if (fa == null || fb == null) return;
    if (fa.getUserData() == null || fb.getUserData() == null) return;

    final Body toRemove = contact.getFixtureA().getBody().getType() == BodyDef.BodyType.StaticBody ?
            contact.getFixtureA().getBody() :
            contact.getFixtureB().getBody();
    Gdx.app.postRunnable(new Runnable() {
        @Override
        public void run () {
            world.destroyBody(toRemove);
        }
    });

}

```

It removes the FA body, but this body have a pointlight attached. I want to remove this PointLight attached. I have no idea how to do this :/.

# Answer
> 0 votes
If you keep a list of all your `Light`s, then when you come to destroy the `Body` `toRemove` you can first iterate over that list and see if there are any `Light`s that are associated with that `Body`.

```
public class SomeClass {

  private List<Light> lights;

  ...

@Override
public void beginContact(Contact contact) {
  fa = contact.getFixtureA();
  fb = contact.getFixtureB();

  if (fa == null || fb == null) return;
  if (fa.getUserData() == null || fb.getUserData() == null) return;

  final Body toRemove = contact.getFixtureA().getBody().getType() ==     BodyDef.BodyType.StaticBody ?
    contact.getFixtureA().getBody() :
    contact.getFixtureB().getBody();
  Gdx.app.postRunnable(new Runnable() {
        @Override
        public void run () {
            Light light = null;
            for(Light l : lights) {
              if(l.getBody() == toRemove)
                light = l;
            }
            if (light != null) {
              light.remove();
              lights.remove(light);
            }
            world.destroyBody(toRemove);
        }
    });
}

}

```

---
Tags: libgdx
---


title: Move body to mouse click and stop

text:
# Question
Title: Move body to mouse click and stop
I'm trying to have a body move to the player touch and stop once he reaches the destination. I have the player boxed in to prevent him to move out of bounds, I can somewhat do that with translate but with collision, it doesn't work properly, is there a better solution for this?

# Answer
> 2 votes
Once you have the destination determined, it can be done in two popular ways:

* Tweening. That is the most simple way of transforming an object to a destination in exact N seconds with the ease algorithm of your choice. Most tween engines has path feature to allow you to put checkpoints on their way, so you can take a longer path.
* Physics. You can control your player navigation code to help it reach to the destination and continue to control or apply force (in case there is a friction). Finally, once arrived (collided), remove all forces/controls.

If your scene is complicated and your player has to make decisions on the road, then AI is your friend.

# Answer
> 1 votes
First, you need to define a bounding box around your player. This is what actually collides with the outside. To try to calculate collisions with every pixel of your character, your CPU would put you in the realm of terrible FPS. Since you are programming in Java, I would recommend looking into the java.awt.Rectangle class. You can simply define one rectangle as your "out of bounds box" and one rectangle around your player, and use outOfBoundsRectangle.contains(playerRectangle) to check if the player is in bounds.

**What if your bounds isn't a simple rectangle?**

The "contains method can also apply to single points. Just if your player's bounding box contains any points in your out of bounds shape.

**What if that is taking too long/too much processing power**

If you have a lot of points in your out of bounds shape, the above method will be too tedious. You can try dividing up a larger shape into smaller rectangles that can be checked for collisions.

The best way for working with a complicated boundary is by making it into a java.awt.geom.Path2D - a class that defines a set of points with lines between them. Using methods in this class, you can check for intersections between the path and your player's bounding box. You could also create a bounding path for your player for more complicated collisions.

Edit: I'm not sure whether you are writing code for 2D or 3D. What I gave you above only works in two dimensions. For three dimensions, I believe libgdx has a BoundingBox class that works in a similar way to what I described above. It can also replace the Rectangle class if you define the BoundingBox as only having two dimensions. The BoundingBox is defined by two "Vector3"s, another libgdx class that just stores a 3D vector. Again, you can make this 2D by setting one of the vector dimensions to 0.

As for clicking and having your player move to that point, that should be done by frames in your update method. I'd recommend looking at this site for some easing equations, but a linear equation will work fine for a basic game:

Some easing equations

---
Tags: libgdx, box2d
---


title: Price for Unity on Android and iPhone?

text:
# Question
Title: Price for Unity on Android and iPhone?
I was looking at the Unity site, and I was a bit confused with the pricing. It says it's free, but for iOS/iOS Pro or Android/Android Pro. I need to shell out $400 minimum each. So if I want to develop with Unity for Android and iPhone, I need $800 to do this? (not saying that it's a lot of money, actually seems reasonable, just wondering)

# Answer
At the time of this posting, the basic iPhone and Android licenses will cost a total of $800 along with the free version of Unity. For future reference, here are the Shop and License Comparisons:

Shop

License Comparisons
> 8 votes

# Answer
Yes, the engine is free for Win/Mac/Web. But if you want to release on Android/iPhone you have to buy some extra license. But I agree with you. It is a bit confusing, because on the download page it says "Free Full Version for Windows with Unity Pro and Android." They don't mention that it is a 30 day trial. At least, that was the case some time ago...
> 5 votes

# Answer
There are certain restrictions in regards to commercialization of products that apply to the free version of Unity. I believe you are allowed to profit up to $50,000 for a product produced by Unity before you need to purchase additional licensing.

It is pretty steep to purchase Unity Pro and the additional add-ons if you are just starting out and your on a shoe string budget. There are also some student licensing options to consider. The student pricing is for annual licenses and they only cut the *current* prices down by half, which if you are planning to be developing in Unity for longer than two years it is not really worth it.

Best solution is to download Unity and get your game up and running to near perfection, then download the free trial and spend the next month perfecting your game on your platform of choice. When you have completed your test deploy and your trial runs out, your best bet is to decide whether to bite the bullet and purchase the license. If you decide to try your luck then you can try to recoup your investment by selling your application (400+ friends at 99 cents should do the trick), but there is lots of competition on the app stores.
> 2 votes

# Answer
Since May 2013, the basic license to publish for Android and iOS is Free. This was a move to remove the costs of the basic license similar to the move that made basic Unity License free of charge for PC, Mac and the Web in 2009. See https://thenextweb.com/insider/2013/05/21/unity-makes-its-android-and-ios-video-game-publishing-tools-free-to-small-and-independent-developers/

However, depending on your needs you can check license upgrades.
> 1 votes

---
Tags: android, unity, ios, costs
---


title: Unable to Set-Up unity remote?

text:
# Question
Title: Unable to Set-Up unity remote?
I have installed Android Studio and set the path in unity. And I am able to build apks with no problem. But when I try to test in unity remote unity gives an warning as

> Set-up Android SDK path to make Android remote work

I don't know what is happening. If Android SDK path is not set then how am I able build the apks.

I tried to solutions like *enabling usb debugging mode **,** running unity editor first then opening Unity Remote **,** installing Google USB driver component of Android SDK* but none of them worked for me.

# Answer
> 1 votes
You set-up the path in external tools unity preferences ?

---
Tags: unity, android-studio
---


# Question
Title: Why does my Unity/Android game get a small amount of lag when not being touched for some time?
I have made a 3d version of space invaders. I made all the assets myself in Blender. I feel that it's a very basic game and my Galaxy Note 3 test device should handle it no problem. (Although it's a few years old now so perhaps some kind of shader issue or something that my phone not updated enough for ?)

There are 55 enemies all with one mesh each. There's the flying saucer model and the player model.

Then there's a plane for a background, and 4 defensive meshes (although I've tested without these and the result is the same).

Basically, it all runs superbly (I have turned down much of the lighting and graphics quality etc, but have left basic shadows in). However I notice that if the player just lets the phone sit there in game without touching it, there is very slight (but noticeable) frame lag.

All the enemies have a very short animation which moves its arms a small amount.

I could post the code but its massively unorganized and really quite an embarrassment (HAHA!). Also I'm not sure what parts are relevant so it would be a huge post.

Is there any known issues that can cause the lag only when not being touched? As I feel like some of my old projects might have had this happening too but they've been deleted now unfortunately so I can't really dabble with it.

It works smooth as silk in the Unity Editor Android 'emulator' and as I say, if I actually play the game on my phone it's smooth too.

# Answer
Most likely the phone goes into power saving mode and reduces CPU/GPU speed when there is no user interaction for a while.

This is at the OS level.

There may be a setting on your phone to disable this behaviour but your battery life will suffer as a result.
> 1 votes

# Answer
You can have a look at the Screen.sleepTimeout property and initialize it to:

```
 Screen.sleepTimeout = SleepTimeout.NeverSleep;

```

Documentation link: https://docs.unity3d.com/ScriptReference/Screen-sleepTimeout.html
> 1 votes

---
Tags: unity, android, performance
---


# Question
Title: Unity Ads or Google Ads wich one is better?
I don't know if i can ask this here, but i have a doubt about wich ad advertiser is better, a friend said unity and other said google... I want to know in general wich one is better? If there's one wich is better than both let me know. If i can't ask this here let me know and i delete this question :D thanks

# Answer
I would suggest using Google ads as the ad revenue is higher and you will start to tell thus as you get more impressions. It is also rather easy to set up and has a nice UI. You also have better flexibility in how ads are placed and there is more demand for Google advertising. You should use Adobe to set it up.
> 2 votes

---
Tags: unity, advertisements
---


# Question
Title: How to reduce the size occupied by my video animations?
I have a mobile game but my build size is currently 4gb. Furthermore, it crashes on open and I suspect it has something to do with the huge build size.

In my project are 10 animations made of a series of images, each one using around 250-300 images. Each one is quite large as the animation takes up most of the screen so they are high resolution. What can I do to reduce the build size?

I have tried converting it into a video file and using the raw image component to display it as a movie texture, however, it seems unity doesn't support videos with alpha channels, and the alpha channel is critical to my animation.

I thought about combining them into a single image, but lets be real, if each image is more than 1080p, then combining 250 - 300 images into a single file will be massive.

So what can I do to reduce the size of the animations?

# Answer
> 1 votes
For starters, Unity has a page regarding reducing build size that I assume you've encountered before -- to my knowledge, its suggestions for reducing texture size are the only real useful and simple ones out there. The main build size reducer I've found that it doesn't directly mention is ensuring all textures are Power-of-Twos. I assume, however, that you've done this; it appears Unity 2017 by default now automatically converts textures to PoT formats, but more importantly your file size would be even bigger with that many animations. A simple test had a 2048x2048 file take 2.7MB of space, while the same file scaled to 2049x2049 takes a whopping 16MB! If this was your problem, with ~3000 images your filesize would likely be far higher than 4GB.

From a quick google search, this thread on the unity forums seems to suggest that imported videos do, in fact, support alpha channels when in the right codec. Unity also has section in the documentation confirming this. I've never actually used video clips in Unity so I can't offer much more advice in that department, but it seems as though that strategy should work -- the file size may still end up being quite large, however.

If you can't go the video route, in terms of actually fixing this issue, unfortunately, I don't believe there's much you can do if you need to keep every frame of animation and also maintain the same texture resolution. You could try reducing resolution in-unity with the Max Size option on the imported texture, or you could try cutting out any unnecessary frames of animation, and see how much those operations impact how the animation plays. Lastly, without knowing what the animations are, this advice may be useless, but you could hypothetically split the animations up into layers, with static backgrounds and much smaller animated sprites for the moving characters/objects, with their positions (and maybe even rotations and scale) adjusted with Unity's built-in animation system.

---
Tags: unity, animation, image, video
---