# Question
Title: Collision between a sphere and a mesh(height-map)
I am trying to implement a method that detects the collision between a sphere and a mesh and reflects the vector of speed. I have a method, that detects a collision between a sphere and a triangle and returns the time to this collision using the speed of the sphere.

```
// Detects whether the triangle contains the point.
// v1, v2, v3 - triangle; n - normal; p - point
template < class T >
bool TrisContainsPoint( const Vertex3D< T > &v1,
                        const Vertex3D< T > &v2,
                        const Vertex3D< T > &v3,
                        const Vertex3D< T > &n,
                        const Vertex3D< T > &p )
{
  if( n.MixedProduct( v2 - v1, p - v1 ) <= 0 )
    return false;
  if( n.MixedProduct( v3 - v2, p - v2 ) <= 0 )
    return false;
  if( n.MixedProduct( v1 - v3, p - v3 ) <= 0 )
    return false;
  return true;
};

// Returns the nearist point to p from a-b segment.
template < class T >
Vertex3D< T > ClosestPointToSegment( const Vertex3D< T > &p, const Vertex3D< T > &a, const Vertex3D< T > &b )
{
  Vertex3D< T > c = p - a;
  Vertex3D< T > w = b - a;
  T d = w.Length();
  if ( fabs( d ) < Plane3D< T >::EPS )
    return a;
  w /= d;
  const Vertex3D< T > v = w;
  T t = v & c;
  if ( t < 0.0f )
    return a;
  else if ( t > d )
    return b;
  return a + t * v;
};

// Finds the nearist point to p from the sides of the triangle. Return the smallest distance.
template < class T >
T ClosestPointToTris( const Vertex3D< T > &v1, const Vertex3D< T > &v2,
                      const Vertex3D< T > &v3, const Vertex3D< T > &p,
                      Vertex3D< T > *res )
{
  *res = ClosestPointToSegment( p, v1, v2 );
  T bestDist = p.DistanceToSqr( *res );

  Vertex3D< T > pt = ClosestPointToSegment( p, v1, v3 );
  T dist = p.DistanceToSqr( pt );
  if ( dist < bestDist )
  {
    bestDist = dist;
    *res = pt;
  };
  pt = ClosestPointToSegment( p, v2, v3 );
  dist = p.DistanceToSqr( pt );
  if ( dist < bestDist )
  {
    bestDist = dist;
    *res = pt;
  };

  return (T) sqrt( bestDist );
}

// Returns true if the ray intersects the sphere.
template < class T >
bool IntersectSphereByRay( const Vertex3D< T > &center, T radius,
                           const Vertex3D< T > &org, const Vertex3D< T > &dir,
                           T *time )
{
  Vertex3D< T > q = center - org;
  T c = q & q;             // squared length
  Vertex3D< T > nDir = dir;
  T l = dir.Length();
  if ( fabs( l ) < Plane3D< T >::EPS )
    return false;
  nDir /= l;
  T v = q & nDir;
  T d = radius * radius - (c - v * v);
  if ( d < 0.0f )
    return false;
  *time = (T)(v - sqrt( d )) / l;
  return true;
};

// Detects the collision of the sphere and the triangle.
// time - time to collision(can be negative); normal - normal from the triangle to the center of the sphere; ...
template < class T >
bool IntersectTrisBySphere( const Vertex3D< T > &v1, const Vertex3D< T > &v2, const Vertex3D< T > &v3,
                            const Vertex3D< T > &center, T radius, const Vertex3D< T > &speed,
                            T *time, Vertex3D< T > *normal )
{
  Plane3D< T > plane( v1, v2, v3 );
  Vertex3D< T > pt = center - plane.n * radius;
  if ( !plane.IntersectByRay( pt, speed, time ) )
    return false;
  Vertex3D< T > planePt = pt + (*time) * speed;
  *normal = plane.n;
  // Is the point inside the triangle or not?
  if ( !TrisContainsPoint( v1, v2, v3, plane.n, planePt ) )
  {
    // Finds the nearest point in the triangle
    Vertex3D< T > trisPt;
    ClosestPointToTris( v1, v2, v3, planePt, &trisPt );
    if ( !IntersectSphereByRay( center, radius, trisPt, -speed, time ) )
      return false;
    *normal = center - (trisPt - (*time) * speed);
    normal->Normalize();
  };
  return true;
};

```

For each triangle below the sphere i use the following "algorithm" (every render):

1) Call `IntersectTrisBySphere` method with the speed of the sphere and the inverse speed of the sphere. Find the time to the collision for each case.

2) If the time with normal speed \<= 0 (intersects the triangle) and the time with inverse speed \< 0, then I reflect the vector of speed.

Like this:

```
float k = normal.x*xSpeed+normal.y*ySpeed+normal.z*zSpeed;
xSpeed = koef * (xSpeed + normal.x * k *-2.0f);
ySpeed = koef * (ySpeed + normal.y * k *-2.0f);
zSpeed = koef * (zSpeed + normal.z * k *-2.0f);

```

This trick with 'inverse speed' is for avoiding the situations when the sphere moves from the triangle (time will be negative), but doesn't intersect it.

So, I am not sure what to do with multiple collision. I mean, my algorithm works fine(not sure:) ) when the sphere intersects only one triangle, but when I use it for several collisions (one by one), it doesn't work.

What should I do? Maybe I have a mistake somewhere else, I don't know. I have spent a lot of time for debuging, but it still doesn't work.

P.S. Sorry for my english :(

# Answer
> 0 votes
You probably should avoid sphere to intersect multiple triangles.

Since you can determine time to collision for a sphere and triangle, therefore, when you detect case of multiplie collision just choose shortest time and advance your simulation for this time instead of fixed timestep. Thus you can be sure you always will deal with single collision.

---
Tags: opengl, collision-detection, physics, collision-resolution, physics-engine
---


# Question
Title: How do I make my character jump in every direction?
My character can only jump when he is grounded, but he can only grounded in one direction I want him to jump in every direction, can anyone help?

**CAN JUMP :**

**CAN'T JUMP :**

Code:

```
 using UnityEngine;
using System.Collections;

public class Player: MonoBehaviour {

public float maxspeed = 10f;
bool facingRight = true;

Animator anim;

bool grounded = false;
public Transform groundCheck;
float groundRadius = 0.2f;
public LayerMask whatIsGround;
public Vector2 jumpDirection = new Vector2(0f, 0f);
public float jumpFocre = 500f;

bool doubleJump = false;

void Start ()
{
    anim = GetComponent<Animator> ();
}

void FixedUpdate () {
    grounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround);
    anim.SetBool ("Ground", grounded);

    if (grounded)
        doubleJump = false;

    float move = Input.GetAxis ("Horizontal");
    anim.SetFloat ("Speed", Mathf.Abs (move));

    GetComponent<Rigidbody2D>().velocity = new Vector2(move * maxspeed, GetComponent<Rigidbody2D>().velocity.y);
}
void Update()
{
    if((!doubleJump) && Input.GetKeyDown ("up"))
    {
        anim.SetBool("Ground", false);
        float move = Input.GetAxis ("Horizontal");
        jumpDirection.x = move;
        GetComponent<Rigidbody2D>().AddForce(jumpDirection.normalized * jumpFocre);

        if(!doubleJump && !grounded)
            doubleJump = true;
    }

}

void Flip()
{
    facingRight = !facingRight;
    Vector3 theScale = transform.localScale;
    theScale.x *= -1;
    transform.localScale = theScale;
}
}

```

# Answer
Your `groundCheck` `Transform` is a child of the player and rotates around the player when the player spins.

The `groundCheck`'s primary function is to provide a position to use when calling `OverlapCircle()`.

This means it could be replaced as follows:

```
public Vector3 groundCheckOffset = new Vector3(0f, -1f, 0f); // one unit down
// ...
grounded = Physics2D.OverlapCircle(transform.position + groundCheckOffset, groundRadius, whatIsGround);

```

This will allow a ground check that travels with, but does not rotate around, the player.

Note that the actual value of `groundCheckOffset` will need to be modified to suit the size of your player.
> 2 votes

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


# Question
Title: How to make a joystick follow the touch around a starting point using atan2?
I would like to move a joystick, and be able to go beyond the limit of the circle, and the joystick should follow the angle from the touch (the touch is moving), but it should stay on the circle. It should not go beyond the circle.

I calculate the angle with atan2, then place the joystick at a specific radius from a starting point.

The problem is that the values are positive only, so the joystick only stays in the top right quarter : when the touch goes down, the joystick goes until y=0, then it goes up, whereas the touch is still going down.

Would you know how to fix this? The joystick should follow the same angle as the touch, around a starting point :

Here is the code :

```
func moveJoystick(touch:CGPoint){
    let invY : Float = Float(self.view!.frame.size.height) - Float(touch.y)
    let dy : Float = Float( fabs( invY - Float(startPosFrontJoystick.y) ) )
    let dx : Float = Float ( fabs( touch.x - startPosFrontJoystick.x ) )

    //find angle when more than limit of radius //** HERE **
    let radWhenBeyondLimit = atan2(dy, dx)
    let newX : Float = cos(radWhenBeyondLimit)
    let newY : Float = sin(radWhenBeyondLimit)

    //place front joystick on circle
    let yPos : Float = Float(newY) * radiusForFront + Float(startPosFrontJoystick.y)
    let xPos : Float = Float(newX) * radiusForFront + Float(startPosFrontJoystick.x)
    frontJoystick.position = CGPoint( x:CGFloat(xPos), y:CGFloat(yPos) )
}

```

Thanks

# Answer
> 3 votes
You're only getting angles in the top-right quadrant because you're taking the absolute value of dy & dx. The sign information is important for determining what quadrant atan2 should return.

What I'd recommend instead is using vector normalization, rather than trigonometry.

```
dx = touch.x - startPosFrontJoystick.x;
dy = invY - startPosFrontJoystick.y;

squaredMagnitude = dx * dx + dy * dy;

if(squaredMagnitude > radiusForFront * radiusForFront)
{
    scale = radiusForFront/sqrt(squaredMagnitude);
    dx *= scale;
    dy *= scale;
}

xPos = startPosFrontJoystick.x + dx;
yPos = startPosFrontJoystick.y + dy;

```

For touches that are inside the radius, this puts the joystick at the touch location. For touches beyond the radius, this puts the joystick at the edge of the circle defined by that radius, in the same direction as the touch.

---
Tags: mathematics, ios, trigonometry
---


title: Non equi-probable random function

text:
# Question
Title: Non equi-probable random function
I was trying to find or make a function which is not equi-probable, meaning some values are less probable than others. Apparently what I want has something to deal with http://en.wikipedia.org/wiki/Normal\_distribution and Gaussian Distributions.

The math and algorithmics involved in such a function seemed a little complex, and I was not sure if they were really necessary.

My goal is to make better loot more rare to get (the player can generate an infinite amount of loot events), but since I want the loot quality to be expressed with a single value, I need a function that returns values \> 0.9 very rarely but will return value \> 0.1 much more often.

I tried `log((100*random())^(0.01*random()))` ('^' meaning exponent, so '\**' to be precise) in python, I got results that seems pretty satisfying, but I'm really suspicious that I can can trust those results.

Is there some type of standard function that already do what I'm looking for ? Do you think this formula is somehow reliable ?

I don't want to have "loot tables" because they're integral values, and it would require more tweaking, and I don't intend to have special items that are much more powerful than lower tier items.

Here are the results, with 10000 picks:

```
('0.003', 1514, '15%', '####################')
('0.006', 1323, '13%', '#################')
('0.010', 1269, '12%', '################')
('0.014', 1169, '11%', '###############')
('0.022', 1187, '11%', '###############')
('0.027', 1089, '10%', '##############')
('0.028', 964, '9%', '############')
('0.034', 760, '7%', '##########')
('0.037', 496, '4%', '######')
('0.043', 228, '2%', '###')

```

# Answer
Here is my gaussian distrib. in 0..1 in c# With reference Note: r is the Random class istance.

```
   private double  nextGaussian(double mean,double variance ) {
        // http://stackoverflow.com/questions/218060/random-gaussian-variables
        //with mean = 0.5 and variance = 0.5 we get uniform distribution over [0..1]
        double u1 = r.NextDouble(); //these are uniform(0,1) random doubles
        double u2 = r.NextDouble();
        double randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) *
                     Math.Sin(2.0 * Math.PI * u2); //random normal(0,1)
        double randNormal =
                     mean + variance * randStdNormal; //random normal(mean,stdDev^2)
        return randNormal;
    }

```
> 1 votes

# Answer
I don't understand phython but a simple but not very flexible solution is to use annidated if like this one:

```
float ProbDensityFunction ()
{
    value = random();
    if (value > .1)
        value = random();
            else if (value > .2)
                value = random();
                    ...
                     else if (random()>.9)
                        value = random();

    return value;
}

```

In this way you have a probability density function where low values have the most chance to be selected.. the drowback is that is not flexible but you can change the values of conditions or increase/decrease the number of "if" to obtain the desired function.
> 0 votes

# Answer
How about a trivial power function? Take a random number in the 0 to 1 interval, raise it to the power "needed". This is easy to calculate and different selections of exponent will give you the loot-rarity you want.
> -1 votes

---
Tags: mathematics, probability
---


title: Unity3d - move 3d object in an AR scene

text:
# Question
Title: Unity3d - move 3d object in an AR scene
I have an AR scene that has one AR camera, an image target and a 3D object as below.

I want to move the AR object to the position of the mouse click. I have tried taking the `Input.mouseposition` (screen position), converting it using `ScreenToWorldPosition` and moving the 3D object to this position. The object is moved, but not to the mouse click position.

How can I move the object to the position of the mouse click? My code is as follows:

```
Camera cam;
Vector3 target = new Vector3(0.0f, 10f,0.5f);
// Use this for initialization
void Start () {
if (cam == null)
    cam = Camera.main;
}
void Update()
{
    if (Input.GetMouseButtonDown(0)) {
        Debug.Log("MouseDown");

        Vector3 mousePos = Input.mousePosition;
        mousePos = cam.ScreenToWorldPoint(mousePos);
        GameObject.Find("Car1").gameObject.transform.position = mousePos;
    }
}

```

**EDIT 1**

To move 3d object with mouse, I tried this code. But it don't move the position of mouse click. enter link description here

**EDIT 2**

If I add a plane to scene, I can move to the position of mouse click **only** on the plane. The code is taken from here. But the plane prevents to show AR camera view. The screenshot is below:

**EDIT 3**

I add box collider and rigidbody to 3d object. Screenshot is below :

I used below code :

```
if (Input.GetMouseButtonDown(0)) {
            Debug.Log("mouseDown = " + Input.mousePosition.x + " " + Input.mousePosition.y + " " + Input.mousePosition.z);

        RaycastHit hit;
        var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out hit))
        {
            if (hit.rigidbody != null)
                GameObject.Find("Car1").gameObject.transform.position = hit.point;
            else
                Debug.Log("Rigidbody is null");
        }

```

When mouse clicked, 3d object isn't moved the position of mouse click.

# Answer
The mouse is in the screen coordinates. The screen is two dimensional. And you are trying to convert the 2d screen coordinates to 3d world coordinates. You need to specify the desired `z` position to the mouse position vector (you can think of it as the distance from the camera):

```
var mousePos = Input.mousePosition;
mousePos.z = 10f;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
GameObject.Find("Car1").gameObject.transform.position = mousePos;

```

The other problem is that you need to know the desired `z` position to specify it. This is not that difficult for 2d graphics in Unity, because `z` of an object is most likely constant (because 2d worlds are `xy`) and you could just set it from the previous objects position:

```
var mousePos = Input.mousePosition;
mousePos.z = 10f;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
var transform = GameObject.Find("Car1").gameObject.transform;
mousePos.z = transform.position.z;
transform.position = mousePos;

```

But it might be a problem in 3d. One of the options is to raycast from mouse position and take the point of the hit as the target position:

```
RaycastHit hit;
var ray = Camera.main.ScreenPointToRay(Input.mousePos);
if (Physics.Raycast(ray, out hit))
{
    if (hit.rigidbody != null)
        GameObject.Find("Car1").gameObject.transform.position = hit.point;
}

```

This technique, of course, requires 3d colliders in the scene that could be hit by the raycast. And, possibly, you might need to calculate an offset from the hit point, so the character will not move into collider.
> 1 votes

---
Tags: unity, 3d, movement, mouse
---


# Question
Title: How to detect and prevent abuse (botting) of online game API?
I have been ocassionally working on a game idea in my free time. The gameplay and content renders it to be implemented as a online multiplayer game built with well established web technologies. You should know that it falls into the strategy and simulation genre. That means: No running around with characters or similar but only atomic actions (regarding client-server communication) like "build thing A on location X".

At one point I realized there is a huge problem: having a browser based front end relying on a REST API back end makes it a more than excellent target for bots. While automation is desireable for business it is poison to a game which is about fun. I experienced it first hand in a browser game in the past were the most successful players were bots which subdued everybody.

From my current point of view I do not see any possibility to protect against bots when building a multiplayer online game based on a REST API. Exception: Making it open source so everybody can host his own instance for private groups or even just oneself (to not get annoyed by jerks with bots).

Is there any way to differenciate between an honest player who just set an alarm for the next possible action and a bot automatically taking every chance on appearance of it? Besides such show stoppers like captchas. If not, I would think about another technology stack which makes it at least much harder to mess with client-server communication (proprietary encrypted binary protocol in a native code client).

**Edit**: Thank you, your answers are inspiring but also made me realize that specific countermeasures cannot be made by going further into details of the game. However, that would be too much for a question on Stack Exchange. So I just want to point out the most important points:

* Players are exploring, developing and managing whenever they want to. Their businesses still run fine when they are offline (it is a peaceful game, no weapons involved). Only expansion and progress need the players action. Those actions are limited by:
* *time* is one of the key resources (like in EVE Online skill training). All processes in game require it. There is no point in being online 24/7. The average player should be successful already with spending not more than an hour every day in one or two sessions (*roughly*, the concept is still in development).

# Answer
> 50 votes
If people want to bot, I don't think you can really stop them.

You can of course implement many measures that make botting more or less of a pain. But you can only do so much before your codebase turns into a gigantic mess that's hell to maintain, error prone, and annoys legitimate users. Meanwhile the botters will always find a way to defeat your countermeasures:

* There's more of them than you
* They have more free time on their hands (you have to split time between actual development and bot proofing, they can hack their bot code all day long)
* As you create outlandish, challenging safeguards the bot authors will be further encouraged because it's fun to break your bot protection
* If there is a black market of people commercially profiting from bots, the harder you make it to write a bot the more valuable working bots become, so you incentivize botting

You will basically be trapped in an arms race with the botters, and based on logic along the lines of the above points, as well as my experience with such games, you will not be able to keep up.

Some game developers employ extremely aggressive anti-cheating measures: For instance, Steam will scan memory and the file system to look for hacks, and offenders can be punished by losing accounts worth hundreds of dollars. Yet there are still bots and other hacks for Steam games, and some of them even work half the time. Unlike them, you have an API that's wide open to the user, and no control over the users computer. It's an uphill battle from the start.

The problem you are trying to solve is essentially a Turing test: Except it is a very easy Turing test, because you cannot cheat by requiring hard AI problems like language. No matter how many heuristics you create, it would be trivial for a botter to add a little randomness to the bot's action to have it mimic almost exactly a human. It wouldn't even be very hard to have the bot watch you play for a bit, and learn how to time actions exactly like you. Then when you ban the bot, the botter posts a huge rant on the forum about how he's just a dedicated player (and maybe he *is* actually a false positive) and your core audience of hardcore players will rise up in arms against you.

## Make the game too fun to bot

The main reason someone uses a bot is because there is a part of the game they want to skip. If they enjoyed the game and found it fun, they wouldn't have the bot play it, they'd play it themselves.

But if the game is so boring, why play it at all? Presumably, some parts of the game are boring and mandatory to get to parts that are fun. For instance, in MMOs everyone loves going up a level, but nobody wants to kill 42,324 dire undead poison rats to get the XP. So they let the bot grind and drop in to play the fun part.

This is not a criticism of you or your game, but clearly at least some players find some parts of your game tedious. You should see if you can reduce these tedious parts, and look into adding more difficult, meaningful decisions: Bots aren't good at deep strategy or lateral thinking compared to human intelligence, and besides humans enjoy making difficult game decisions.

From your description, I get the impression that this is a browser game similar to Travian, where there is a build queue with a single best build order and certain "maintenance" (such as keeping farming raids going) tasks that must be done. You say there is no conflict, but in any MMO drama and petty politics is inevitable (IMO it's the main attraction) so I'm sure your players find ways to butt heads. With these sorts of games, a lot of the tedium comes from these "maintenance" tasks - what players really want to do is make alliances and play the diplomacy game with rival clans, the maintenance then becomes a sort of tax where you have to wake up to an alarm at odd hours to be allowed to get into that fun diplomatic part. So cut out the tedium: Automate boring things yourself (but maybe imperfectly to keep it interesting), so that players can focus on the parts they like.

This approach may not always work, unfortunately. Not all players have the same tolerance to tedium or the same concept of fun. You could have a prominent mechanic that 99% of your players enjoy, but the 1% find boring. What if the 1% then start writing bots, ruining the fun for the 99%? But ultimately, it is a matter of degree. You can never remove botting completely, but you can minimize the damage.

## Undercut botters

A lot of the really negative effects of bots come from bot authors commercializing their work. If this is the case for you, you could simply compete with the bots. Many real-time based online games already have premium features that allow time-skipping and automation (such as extended build queues). These amount to a developer-sanctioned official bot. If you have these, and price them appropriately, players will buy your premium instead of buying bots. The good news is, you are in charge of the API, so you always have a strong advantage at developing quality automation for your own game, so this time it's a losing battle for botters.

This will not eliminate amateur botters, or people who feel that your premium is not good value for the money, so again the effectiveness of this approach depends on the situation.

## Manually look for them

As I said above, what you are doing is essentially a Turing test. Since interaction with humans is famously considered a difficult Turing test challenge, you can try to leverage that.

Manually inspect top-level players and see if you find anything suspicious. You might even be able to get away with occasionally probe them in ways restricted only to your imagination, to see if you can trick the bot into doing something it wouldn't do.

While it is hard to write an algorithm that will detect bots reliably, it isn't so hard for a human to learn how to spot them. I think a lot of browser games use this strategy, and it can be pretty effective. The disadvantage is that either you need to do a lot of boring work all the time, or you need to pay game masters to do regular bot patrol.

# Answer
> 24 votes
The best and only effective defense against bots is to design your game in a way that players don't feel the need to automatize in the first place. When your players automatize simple tasks which do not actually require skill, it is a sign that your user interface is lacking and they are substituting an UI feature they are missing.

* Does your game include repetitive tasks where the player performs the same action over and over again to grind?

Make these aspects of your game less repetitive and more interesting to play and re-play.
* Does your game require players to perform actions at times inconvenient for them, like in the middle of the night or when they are at work?

Allow them to queue orders (like "build X1, then X2, then X3, starting each as soon as the resources are available") or schedule actions at specific times in advance (build X at 3:22 AM).
* Does your game require players to act on events within a very short timespan?

Allow them to configure the game in a way that these actions are triggered automatically

+ when building X gets destroyed, rebuild it immediately.
    + When someone offers resource X for less than Y money, immediately buy up to Z units.
    + Auto-sell all resource X when stock exceeds Y units, but not for less than Z money per unit.

Monitor your community. When you notice that they automate anything else, steal the idea and add the option to automatize it to the core game.

# Answer
> 23 votes
### Don't make your game so vulnerable to johnny-on-the-spot effort

First, make sure that players who only play your game for twenty minutes or an hour a day in a single sitting aren't at a huge disadvantage to players who leave it open at work and play 16 hours a day.

This may require a change in your game mechanics - for instance a move allotment that fills up when you aren't playing and allows players to execute many quick moves when they can play, rather than a mechanism that requires constant tending.

This will disincentivize bot makers because they can keep up with the game, and they have no pressing need to make an automaton that performs actions for them.

### Require server info for each action, and make the server responses slower

When a player plays the game, they request a page which present them with the UI they interact with to make their move. You can insert elements, such as invisible form elements, that verify they actually requested the page first. A random number which your server stores along with the user's ID and what page they last requested. When an action comes in, the server verifies that this user has returned the same random number, and is performing an action on the page they were last seen on. This not only means the bot has to make two API calls for every action, but that regular users can't open multiple pages and execute sequential fast actions (if this is a problem with your design).

The two API calls gives you a way to slow bots down later on. Eventually you'll see suspicious patterns, and you'll be able to pick up on them. When your server detects a suspicious pattern, it can delay the API response in the first call by a second - which will annoy users, but will really slow down bots. Further, if the second request comes back "too quickly" (whatever that means for your game) then you can reject it, or reload the page with some in-game error or reason for requesting a re-submission. "You can't build that quickly. Please take your time." for instance.

Listen to your users and you'll find what they are ok with, and what annoys them.

### Make the moves and actions require thought

IF the game is a simple button clicker, then you can't do much about bots. Consider re-designing your game so that the game itself performs a captcha-like test.

Not knowing anything about the game, I can't suggest much. If it involves choosing where to place a building, design the interface so the user can choose anywhere, even though there are obvious placements that wouldn't work. Or perhaps the user has to match the orientation up correctly for the placement to be successful. If it involves choosing an action, include a longer list of actions, some of which would make no sense in a given situation.

### Include random very simple bot checks

Add an occasional dialog, "Are you sure?" for instance. Change the question and wording frequently and use it as a spot check for bots.

### Change the API

Change the API frequently, forcing them to actually parse the webpage for the correct variables and how they are returned to the webserver. If you develop your interface using a template, replace the template with code that uses a salted hash or random variable generator for each variable name. Then start using javascript to encode the responses, and change that encoding frequently. You can probably write software that does all this for you, and either have everything random all the time, or just do a static template that you change occasionally.

# Answer
> 13 votes
You can't stop them. But you can make their lifes miserable, as they have to spend lots of time writing their bots, and updating them. You have to use whatever you have to verify if user is valid.

* Check for request headers, and reject requests with invalid values. Either set custom headeror check for existing like user-agent. Sure it's easy to overcome, but it's even easier to check. If botwriter is unexperienced it might take him a while to think about it! Your task is to force as many of them to give up right?
* You probably have some sort of hash signature or something in your requests, which is generated on client side with some function. Well, then keep changing it! Make it as separate non-cacheable script, and change it at random intervals. Make few of thems, or edit on fly, by adding random salt to hashing process. While it's again, easy to overcome, this will force them to keep eye on your function. They might also need some sort of constant deployment pipeline to keep users updated. Else, their bots will start sending incorrectly hashed requests. You can even ban users who are doing it too often. Valid users will move around your client anyway, so they will refetch hashing function every now and then. Just remember to update server side too (script based backend will really help here).
* Keep track of resource usage efficiency. If they are spend instantly, after something become affordable, or if new raids are always send within 1-2 seconds from last one, 24/7, then you are dealing with some hardcore player or a bot. You request captcha from such person, and force logout him. If he keeps making requests after being logged out (poorly written bots!) then it's a bot. If he attempts to login multiple time without success, then he's probably a bot. If it takes him few hours to relog, then he might be a bot (bot might request human assistance at this point, and owner might be sleeping).
* IP. This one might eliminate bot-selling. If someone writes a bot with $$$ in mind, they might not want to share source. They will sell bot time instead. If they are greedy, they might use single machine, with single/few ips. That means alot of users will start sharing IP. This is risky, because the same case is for people who are sharing a network. You will have to check if any of previous checks is successfull on certain IP, and decide manually if it's legit user group, or an army of bots.

# Answer
> 8 votes
In general, distinguishing between bots and humans fully automatically is hard, some form of human-assisted decision process works best.

What I would do: define some heuristics that hint the user is probably a bot - doing a lot of actions, doing stuff 24/7, ... Then if these heuristics get over a certain threshold, do an invasive check.

You can manually scan the players activity and see if it seems OK. Or you do a captcha the next time the user is online. Or (even stronger) just send him a chat message where you explain that you suspect he is a bot and want him to respond with something human-like to prove he is not a bot (how was your day? What is your favorite movie? ... - you can have a bunch of those). If he does not respond at all, he is probably a bot. If he responds, you manually check the answers for human-likeness and ban robots. If your heuristics are reasonable, only a small minority of users will be questioned and the amount of responses to scan will be small. And if you keep the set of questions private and changing, there is no way the robots can be prepared, unless someone invents SkyNet.

# Answer
> 8 votes
Embrace the botter. You've built a restful API, perfect for a coder to experiment with automation of your game. Design your gameplay so that the bot doesn't gain an advantage over a human player due to being automated - eliminate the advantages of speed of execution etc that a machine has; design your game so the bot provides the same revenue as a human player, if possible - or at least provides a richer environment to attract more human players.

The question is, why are people creating bots for your game, and will they pay money for the privilege?

# Answer
> 4 votes
I don't neccessarily disagree with the soft-science answers but **there *are* technical things you can do** to detect botters and some things that just make life harder for them.

* Grade accounts by how much you suspect they're using a bot. This will feed into several other techniques and protect legitimate users from your wrath.
* Rotating the session cookie key. This ensures the bot preserves its cookies but also makes it much harder for a botter to share cookies between browser and bot (which is really handy while developing and testing).
* Rate-limit certain actions. Work out the quickest *you* could actually do something, and monitor how quickly these bots are doing it. Might also be worth keeping a running log and working out standard deviations. Even if somebody is only doing something every 10 seconds, if they're doing it *exactly* every 10 seconds they're probably a bot. Modify their rating and log them out.
* Make login more difficult on accounts you suspect could be a bot. CAPTCHAs and questions and other unavoidable things make things much harder for a would-be botter to automatically script things.
* Monitor mouse/page movement. This is fairly simple with javascript these days but bots won't organically have any mouse movement. If you aren't getting any between "clicks", they might be mobile or they might be a bot. Investigate. It's a lot of data to log though... So you might want to reserve this for accounts that have already triggered previous steps.
* Build tools to link accounts by behaviour, IP, action sequences, action cadence. If you're going to ban people, make sure you have the tools to manually verify their wrongdoing.
* Rotate out URL schema, CSRF variables, etc and do it often. It's a big step and probably requires more up-front work than it's ever going to be worth but at the very least, any accounts that suddenly just stop working (or keep hammering the old URLs and sending the old variable names - log it!) need their bot index level increasing.

# Answer
> 3 votes
Create a separate bot only server. Create a leaderboard and celebrate the winners. Look at the data this generates. Ban users from normal severs whose behaviour profile looks like that of a bot.

# Answer
> 3 votes
Have you considered making bots an integral part of the game? It's hard for bots to ruin the game for everyone else if everyone is encouraged to create them. Add support for scripting and all of a sudden the dynamics of the game changes from manual resource management strategies to bot design strategies.

# Answer
> 2 votes
Whatever you do, remember to NOT make it more annoying for the real player! A lot of the responses I've seen (slower page results, not allowing multiple pages open to facilitate faster input, etc) would also prevent legitimate players from doing things fast, which will just needlessly frustrate them.

imho the easiest approach may be to apply social engineering to the problem: 1) add an explicit NO-BOT clause to your TOS, and add that detecting bot activity will remove the player from the high-score list (or have the label "cheater" attached, so people aren't as frustrated with them; if you go that route, allow people to hide cheater records).

2) check for bot-like behavior (e.g. regularly timed pings to the server, or close-to-perfect timing for many hours in a row), and if so then put the account into "bot mode" - display occasional captchas and whatnot. if these are ignored but the player keeps actively playing the game, mark the player as "bot" and exclude him from the rankings. if they're addressed, mark him as "power player" and take him off the bot list.

this way the vast majority of players are never affected, the hardcore gamers are affected for a short duration, and the bots don't "ruin the game" for anyone else.

---
Tags: multiplayer, security, online, bot
---


# Question
Title: Improving performance for flocking behavior?
I have a game that I am trying to make. It is a twin-stick shooter that I want to design to have a LOT (Up to 500) of enemies on the screen. The game's base design comes from that of Geometry Wars, and serves as a learning experience.

A bit about my setup: i7 quad-core CPU @ 3.5GHz, 8GB of RAM, and Intel 4000 integrated graphics. While these aren't the best specs, they are now more and more common, so this is my target system.

There is an invisible plane that acts as the playing field. I built a NavigationMesh from this plane, and sample random points from that to spawn my enemies. The enemies use DetourCrowd to implement the flocking behavior. On my moderately-powerful machine, I can get around 150 enemies before I begin to experience drastic performance drops. Accounting for other potential issues, I made my enemies invisible, so only the agents are used, and still the performance drops significantly from 150-200 enemies on my machine. It is bad enough that this difference of 50 enemies drops my framerate from a solid 60 fps to \<1 fps.

I decided to instead try using Bullet physics instead. I have the linear/angular factors setup to make Bullet act on a 2D plane. All of my enemies now use a Sphere for collision, have a mass of 1 unit, and no friction. They are not affected by gravity or external forces, but instead I set a fixed impulse at the beginning of each physics step. Additionally, the collision mask is setup so that the enemies only collide with each other. Around 350-400 enemies, I begin to see performance issues. They're not nearly as severe as the performance issues that I see with DetourCrowd, however they do come with an additional downside.

I use a small sphere set as a Trigger for firing off bullets. I handle the collision events to destroy the enemies. With the DetourCrowd method, this caused no noticeable performance drop. However with the Bullet approach, it causes a much more significant performance drop.

Overall, I can comfortably use ~120-150 enemies with the DetourCrowd approach, and ~200 enemies with the Bullet approach.

Are there any solutions that would give a much cheaper flock behavior for this game? I prefer solutions targeting 2D under the assumption that it will be cheaper than a solution targeting 3D.

# Answer
> 1 votes
Intel released an crowd collision avoidance algorithm and sample code a few years ago that's designed to solve this problem. It's parallelizable, and you may be able to adapt the algorithm to work with your entities.

---
Tags: c++, bullet-physics, urho3d
---


# Question
Title: What's the most recommended transmission format using websockets for a MMORPG?
(**note**: I'm not asking for the supported formats in the RFC, but the format I should develop to send/receive the messages, say, in the Application layer).

(**note 2**: Please help me retagging this post to reference internet, communication, client-server messages).

I am developing a game. Right now it is just a concept of a multiplayer game, tile-mapped, with role-playing characters.

The big problem here? It will be online-massive. My concerns are about lag and transmission. The front-end will be pure ActionScript3. The connection will be done with **websockets**.

Certain actions will be really quick like: walk, grab (item) and perhaps hit (attack) or execute another type of quick action (e.g. use a small, quick, item).

Considering that websockets are not plain sockets, and this is my first online game, my question is about the protocol to use.

Right now, I marshall the messages in the following format (this is just an example, since I did not develop the actual commands yet):

```
client ---> {'code': 'walk', 'kwargs': {'direction': 'left'}} ---> server
server ---> {'code': 'walk.ok', 'kwargs': {}} ---> client

```

As you can see, it is JSON format, sent via websockets. The processing backend is Tornado with Python 2.7. I developed a library to marshal and unmarshal these messages.

Assuming that, as an expected peak (with so much luck), I will have 1000 players mostly walking... will I have performance issues with this protocol I defined? Actually, I'm asking about

I want to avoid lag as much as possible, considering websocket transmission.

What format is more adecquate and performant for MMORPG games client-server communication for these really-quick actions? Actually I never developed one of these games and I'm concerned about the performance.

# Answer
> 2 votes
With all respect: Don't worry about it... yet.

By all means, keep in mind that eventually, to run at scale with as few servers as possible, you *may* need to use a binary format.

You will *probably* benefit from omitting duplicate data; there's no need for sending "Still moving at velocity 1.0, no change there!" hundreds of times a second.

You will certainly need to resolve issues relating to timing of nodes with different ping times, lost and found connections, sanity-synchs from time to time, and many other things.

Switching from JSON to binary, if and when the time comes, will involve swapping out one well-defined part of your code. (Or possibly keeping both, and checking if the first character of a message is '{' to decide which flavor.)

In the early stages, having text-based easy-to-read messages will be more valuable. It will ease your debugging, and you can use ready-made solutions to get on with it. Done!

Because... You have hundreds of hours of more interesting problems to solve before worrying about 1000 low-bandwidth players.

(On the other hand, if you're not actually writing a game, and just want to learn about data compression for networking, that would change your priorities.)

---
Tags: mmo, lag
---


# Question
Title: How do you get a multiplayer-only game to reach critical mass?
Say you have a multiplayer-only game in which players are randomly paired head-to-head against a random online player...

How do get such a beast off the ground?

You need enough players online at all times such that any random player game request will be paired with someone else's request.

Chicken and egg ... You need players to play but without players to play no players will play!

How do I reformulate the problem to make this work?

This happened to me a while back and I haven't come up with anything useful since. https://github.com/fictorial/Rock-Paper-Scissors-World-Masters-iOS

# Answer
> 7 votes
You, the rest of your team and maybe friends should play the game a lot in the beginning, always making sure there is a player online.

If it's a game with no involvement between the players that make them do choises, record people's games and play them back to the next player. E.g:

You vs. Player A, record player a

Player B comes a long later, play back player A's game against him and record player B.

This seems much more realistic than bots, and they actually will play against other profiles.

# Answer
> 3 votes
That is the million dollar question :)

I assume your funds are limited.

I suggest:

1. get as many of your friends, family and former enemies to play - beg if you have to
2. advertise a little (on something like google ads, or facebook) to get some new players. target your adds very specifically. spend a few dollars per day at least.

2a On google, target by keywords to get players that you think will like your game

2b on facebook, target players who have liked or have interest in similar games - ie, if they like that game, they must like my game

1. spend the time to go on forums and groups of players that will like your game on tell them about it, nicely, don't spam
2. add social interaction to the game and, mostly importantly, give people benefits, or something they want, in order to reward them for sharing your game on facebook, twitter etc More on this here http://www.gamasutra.com/blogs/GregBala/20120322/167136/How\_little\_changes\_made\_a\_big\_difference\__case\_study\_in\_one\_aspect\_of\_game\_design.php

# Answer
> 2 votes
The answer is simple and hard at the same time: **Make a good game that people want to play, and talk about it.** If they do, they will come and they will advertise it for you; if not, then they won't and no (sustainable) amount of effort will bring them back.

If your game is not free to play (subscription or up-front payment), then you might need a kind of demo/trial phase to let people experience the game for themselves.

Either way, involving the potential players has never hurt a game. Talk to them via social media. If your game is still in development, give them teaser material, like (parts of) new artwork, if applicable, or just your thoughts on game design, or technical problems that popped up (don't let it get too dry though).

People are always happy to try something new, especially if it's free, and if you tickle them in the right way in that early phase and keep up the quality, then this problem will solve itself.

# Answer
> 1 votes
In your case I would say if there is no one to match, just put some AI against the player. The player won't be able to tell the difference.

# Answer
> 0 votes
Especially for paid games, a single-player mode is beneficial since your players will always have the opportunity for bang when they open up your game. If a player can't find an online match, he can play the single-player mode for a bit then try again later, maintaining your player base.

Another strategy is to promote players bringing their friends. This can be done with rewards (i.e. recommendation promos) or, the better method in my opinion, implied cooperation. If your game has a multiplayer mode that requires your players to cooperate and trust each other, players would have a very great motive to invite their friends who they already trust.

---
Tags: multiplayer, matchmaking
---


title: unity animation not starting

text:
# Question
Title: unity animation not starting
I have written the following code:

```
public class TargetAnimation : MonoBehaviour {
    Animation anim;
    public AnimationClip Open;
    // Use this for initialization
    void Start () {
        anim = GetComponent<Animation>();
        anim.AddClip (Open, "Open");
        anim.Play ("Open");

    }
}

```

I have the following script and animation settings:

I have put the animation type in legacy and the generation as store in root (Depricated) as suggested elsewhere, this did not work. The animation works in the import/annimations view. The origenal comes from blender. And all f this is in unity 5.

# Answer
> -1 votes
the animation needs to be not in legacy (1) but in (2) as per being played.

when you select the animation and look the inspector, put it in debug mode (the little icon top right of the inspector) and in type write "2" without quotes.

check out this link. It shows your opposite problem but it demonstrate how to enable debug mode.

---
Tags: unity, animation, blender
---


# Question
Title: How does Unity's Entity-Component System Work In Practice?
On the surface Entity-Component seems like a good way to program games. Everything is a game object and those game objects are made up of components. The attraction is components are very flexible, just requiring you to "add" them to a game object to inherit it's functionality.

So, obviously a good example might be a platform the character has to jump on. Maybe this thing has a collider, a moving component, maybe a rotating component, or maybe even a rigid "RotatingAndMovingPlatformComponent". Okay, that sounds great, just add all these components to the game object and that's it, you have this extra functionality. However, I find that this level of complexity is where it's usefulness ends.

Try this with menus, complex character movement with multiple states, abstract ideas like game modes or game state, and your flexibility and modularity are destroyed. Menus involve a lot of specifics, complex character movement often involves many states meaning either communication between these components is needed or there must be a controlling component made just for this type of character. On top of this, some components will need to rely on game state in some way.

I see very little benefit to programming this way over ordinary inheritance. The lack of object structures at compile time makes doing a lot of things very difficult and unreliable.

I feel the best and easiest way of going about things would be using larger components with more dependencies. I don't see this as a problem ( more like unreal 4's architecture ), but then I wonder what's the point in the Entity-Component architecture.

# Answer
I will risk and post almost-opinion based answer. What Unity is missing is decopled "system" element. It would be much nicer to have "Component-Entity-System" instead of current "Component-Entity". That is because of the problems you mentioned.

The problem of communication you have mentioned can by solved by adding System. Unity Component, holds both, data and logic, so either you build massive Component that does alot of stuff and knows alot. This kind of monolith, can be dropped in another game, but you can reuse part of it. You can also try and break it, by building lots of small components, but you will end up with tons of tiny components exchanging events, messages and stuff. You can "reuse" them, but they won't work alone.

This is where System comes in. System is just a logic. It will tell your game manager "I can make your tree fly, but I need tree to have \[wings, physics\]". Game manager will then, search for entities with wings and physics, and give it to system. System will then do whatever it has to do to make your tree fly. Wings and physics are components. But different that Unity ones, they will just hold data, like how wide are the wings, or how fast will object fall (it's a flying tree, it will fall fast!). Now, all your components can be reused, as they don't know about anything else than some weird data they hold. They have no meaning, unless some System is interested. But it's System job to read and use the data. System doesn't need to know who has which component, and doesn't need to know about other system. Now you have Components and Systems ready to copy-paste anywhere!

Now how to translate it to Unity? You can write your custom manager, where components are systems, and all they do is logic (and system states if required, like in Menu system you might want to know shorthand which button clicked most recently). Your GameObject is your Entity. What about Models? Well you are using c# or JavaScript, just use normal Class/Object for this, that's why you will need custom manager. To handle non-unity models.

Second option is to split Components into Models and Systems. Component can query GameObject and whole Scene for other GameObjects with certain components. Designate one GameObject as your System Manager. This GO will hold only components who can do stuff. Other Entities in scene, will have components with pure data.

Please note, this is only theory (of adding Systems to Unity), and it might not result in effective architecture for your game.

About inheritance. Easiest way to see the difference is to use both patterns to describe object. Let's describe "Car" in standard class hierarchy. Car will Inherit from wheels so it can move around, thus, car is a wheel. Now in Component Entity. This Object has wheels, and doors, so it's a car!

Few links to articles, about Component-Entity. First one describes Unity like Component-Entity, second one adds Systems.

http://gameprogrammingpatterns.com/component.html

http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/

http://python-utilities.readthedocs.org/en/latest/ebs.html
> 8 votes

# Answer
This doesn't directly answer the question but, from the sounds of it your question and the information you're wanting seem to differ a little (at least to me). So this "outlook" might help connect them.

Abstractions commonly lead to generalizations so you can prepare for future unknowns. This is what Unity does since it knows barely anything about the type of game you're going to make until you start providing that information to it (i.e. game code). The more complex your abstractions (most likely) the more generalized they are.

**Generalization** is a great thing, it allows you to reuse code between games (with little to no changes), and make adjustments when design details change. However with generalization comes the long told saying **Too much of anything is a bad thing**. Over-generalization can lead to difficult and tedious implementations to do something simple.

An example:

Let's say you're a game-development company. You like TBS games and plan on only ever making TBS games. Would it make sense when designing and programming your game-state management system to generalize for future potential of RTS games, when you know you're only ever going to make TBS games? No, it doesn't you can cross that bridge **if** it comes.

Now don't confuse over-generalizing being bad with "don't generalize" because we gain quite a bit of flexibility when doing so. You may know exactly what this game you're making needs 100% (chances are you don't and they'll change), but for sake of the argument lets pretend you do. Well, do you know what the next TBS game you're going to do needs? No, chances are it'll be mechanically different in some way (so that people aren't bored of it before you make it). So you still need some generalization and abstraction just not to the degree that unity does since you know more.

**TLDR;**

Too much and too little of generalization can be a bad thing (for begginners and single-game developers it is much better to under-generalize). The more you know the less you need to generalize.
> 5 votes

---
Tags: unity, architecture, entity-component
---


# Question
Title: How to use polymorphism with the Unity editor
For example:

```
[System.Serializable]
public class A
{
    [SerializeField]
    public int x;
}
public class TestA : MonoBehaviour
{
    [SerializeField]
    public A a = new A();
}

[System.Serializable]
public class B : A
{
    [SerializeField]
    public int y;
}
public class TestB : TestA
{
    // Not legal, I know. Considering Unity forbids the use of constructors in
    // monobehaviour classes, I have no idea how I'd do this.
    a = new B();
}

```

Given that this MonoBehaviour class "TestA" exposes an "A" object, I'd like to override this default value so that when a MonoBehaviour of type "TestB" is attach to a game object in the editor, an object of type "B" is exposed.

Perhaps I'm better off looking into creating custom property drawers, but I'm wondering if there is a way to do this with the default editor.

# Answer
There are some problems with your approach.

**Unity doesn't support serialization of polymorphic custom classes** not derived from ScriptableObject or MonoBehaviour.

In other words, it doesn't matter where and how you initialized `a` field, if `B` if an instance of `A` it will be sliced of (or won't be serialized at all I don't remember exactly I need to check).

Similar to this answer.

A clarification:

```
a = new B();

```

This is legal. You don't instantiate certain classes using constructors (such as `MonoBehaviours`) becasue those are resources allocated in the **unmanaged C++** side of the engine. `MonoBehaviour` are just `C# wrappers` for the relative components. For everything whose lifetime and ownership is just managed by `mono runtime`, than you can use constructors.
> 2 votes

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


# Question
Title: Java libgdx Game Screens and rendering tile map
I'm working on a 2D tiled game with Java and libGDX. I'm having problems implementing gamescreens. I'm trying to set the screen to gameScreen and start rendering tiles, but I'm getting a nullpointer exception on my camera and my renderer.

I think what's happening is that it's calling the render method before the create method for some reason. The create method is where the camera and renderer are set up.

This is my entry point, `gameClass`

```
package com.psillicoder.farmGame;
import com.badlogic.gdx.Game;

public class gameClass extends Game {
    gameScreen gameScreen;

    public static final String TITLE="Farm Game";
    public static final int WIDTH=800,HEIGHT=600;

    @Override
    public void create() {
        gameScreen = new gameScreen(this);
        setScreen(gamaeScreen);
    }

    @Override
    public void render () {
        super.render();
    }
}

```

This is my `gameScreen` class:

```
package com.psillicoder.farmGame;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;

public class gameScreen implements Screen {
    gameClass game;

    private OrthographicCamera camera;
    private OrthogonalTiledMapRenderer renderer;
    private TiledMap map;

    SpriteBatch batch;

    float unitScale = 1/16f;

    public gameScreen(gameClass game) {
        this.game = game;
    }

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

        camera.update();
        renderer.setView(camera);
        renderer.render();

        batch.begin();

        batch.end();
    }

    @Override
    public void resize(int width, int height) {
    }

    @Override
    public void show() {

        TiledMap map = new TmxMapLoader().load("tdmap1.tmx");
        OrthogonalTiledMapRenderer renderer = new OrthogonalTiledMapRenderer(map,unitScale);

        OrthographicCamera camera = new OrthographicCamera();

        camera.setToOrtho(false,40,40);
        renderer.setView(camera);
        camera.update();

        batch = new SpriteBatch();
    }

    @Override
    public void hide() {
        dispose();
    }

    @Override
    public void pause() {
    }

    @Override
    public void resume() {
    }

    @Override
    public void dispose() {
        System.out.println("Disposed");
        batch.dispose();
        renderer.dispose();
    }
}

```

# Answer
The constructor of your `gameScreen` class does not initialize the `camera` and `renderer` fields, what you're initializing in the `show` method are method-local variables with the same names. That's why they're `null` when you're in the `render` method.

Try changing

```
OrthogonalTiledMapRenderer renderer = new OrthogonalTiledMapRenderer(map,unitScale);
OrthographicCamera camera = new OrthographicCamera();

```

to

```
renderer = new OrthogonalTiledMapRenderer(map,unitScale);
camera = new OrthographicCamera();

```

in the `show` method.
> 2 votes

# Answer
```
@Override
public void create() {
    gameScreen = new gameScreen(this);
    setScreen(gamaeScreen);
}

```

Is the setScreen(gamaeScreen) a typo (gamaeScreen) ???
> 0 votes

---
Tags: java, libgdx, tiled
---


# Question
Title: Unity 3D - Rotating an object in relation to its velocity
I am currently trying out Unity 3D and I've run into a problem. The problem is I have a car that moves along a road and then when it reaches a corner I would like it to turn the corner and have the model rotate based on its current velocity.

Here is the code I have for moving the object forward:

```
_velocity += (_velocity * Time.deltaTime) + (_acceleration / 2f) * Time.deltaTime * 2f;
_velocity = Mathf.Clamp(_velocity, 0f, MaxVelocity);
Vector3 position = this.transform.position;
position += -this.transform.forward * _velocity * Time.deltaTime;
this.transform.position = position;

```

The variables are declared as class members:

```
private const float MaxVelocity = 10;
private float _velocity;
private float _acceleration;

```

This appears to work OK for moving forward. If I applied a rotation it may look OK for a certain velocity, but if the velocity changes, then the rotation seems to quick or to slow.

What I would like (but completely failing at accomplish) is when it comes time to turn, then I would look at the velocity and calculate a smooth rotation so when an object performs a turn it will always end up at the same point regardless of how quick it approaches the corner.

I have tried a number of options, over countless hours, but I'm not having any luck!

Any ideas?

**UPDATE #1**:

Below is a half-way solution I got, but for now I will add it here and leave the question open for a bit in case someone can provide a better approach.

From what I worked out a LERP rotation from the current direction to the new direction did the trick (kind of!). So, I created a behaviour called `VehicleController` and in the `Awake` method I added this:

```
_target = this.transform.rotation * Quaternion.Euler(0f, 90f, 0f);

```

This gave me the target rotation relative to my current rotation, i.e. my rotation would have to equal `_target` for me to be facing in the desired direction. I then added the following to the `FixedUpdate` method:

```
//  Rotate
if(_doTurn)
{
    this.transform.rotation = Quaternion.Lerp(this.transform.rotation, _target, Time.fixedDeltaTime * _velocity);
}

```

This performed the actual rotation. The key part was setting the third parameter `Time.fixedDeltaTime * _velocity`. This meant that my rotation speed matched my velocity.

My final `FixedUpdate` method looked like this:

```
//  Forward
_velocity += (_velocity * Time.deltaTime) + (_acceleration / 2f) * Time.fixedDeltaTime * 2f;
_velocity = Mathf.Clamp(_velocity, 0f, MaxVelocity);
Vector3 position = this.transform.position;
position += -this.transform.forward * _velocity * Time.fixedDeltaTime;
this.transform.position = position;

//  Rotate
if(_doTurn)
{
    this.transform.rotation = Quaternion.Lerp(this.transform.rotation, _target, Time.fixedDeltaTime * _velocity);
}

```

In this sample I had a `BoxCollider` that triggered the turn, so in the `OnTriggerEnter` method I simply set `_doTurn` to `true`.

Now there are a few things with this:

1. After the turn I had to fix the positioning and rotation a little. The values were off by about .2, but I couldn't really notice any oddness to care.
2. This approach gives a quick snap change in direction which wasn't what I was really after. Ideally I wanted a situation where the turn would be gradual at a certain angle and end in the same point. But, to be honest, it looks OK and that gets me moving on for now! :)

With regards to #1 I think I had to fix some of the position/rotation values because I was using a `BoxCollider` to trigger the turn so there may be better approaches.

# Answer
> 1 votes
The easiest way to rotate an object to face the direction of its velocity is to represent the rotation as a vector. Unity's physics does this internally, but unfortunately won't let you access any of these variables. Instead, you can simply apply Torque which will do everything for you (it's not good to use a physics engine and apply physics yourself).

First, get the the rotation you want.

```
Vector3 DesiredRotation = Quaternion.LookRotation(rigidbody.Velocity).EulerAngles;

```

Then find the rotation you need to rotate to get there:

```
Vector3 RotationSteering = DesiredRotation - rigidbody.rotation;

```

Normalize RotationSteering so you can get more control over the degree of the rotation:

```
RotationSteering.Normalize();

```

Multiply Rotation steering by whatever amount you wish to rotate at.

```
RotationSteering *= 30;

```

Apply the force then $$$:

```
rigidbody.AddTorque (RotationSteering);

```

I'm not sure how Unity handles Torque but that's the physics way. If you want complete control, you could set the rotation manually, but this leads to a lot of awkward things. You'll also have to change the rotational velocity for realistic collisions. Just stick to le standard (albeit flawed) wheel and don't reinvent it. You'll have many less headaches.

---
Tags: unity, 3d, unityscript
---


# Question
Title: What are diegetic, non-diegetic, spatial and meta user interfaces?
Could anyone please explain to me the differences between "diegetic," "non-diegetic," "spatial," and "meta" user interfaces in terms of how they are represented in games and game development?

# Answer
> 8 votes
There is an excellent article over at gamasutra which explains it all, but I'll go over what each mean

## Non-Diegetic

In terms of game UI, Non-Diegetic is what you would normally associate a typical game UI, an overlay on top of the game. They have the freedom to be completly removed from the games fiction. Non-Diegetic UIs can represent health and ammo or be a hotbar like in World of Warcraft. Non-Diegetic UIs are normally represented two dimensionally.

## Diegetic

On the flip side you have Diegetic, which exist in a game world instead of being overlaid onto the game, very much being part of the games fiction. For example a player could press a button to make their character look at their watch to check the time.

## Meta

Meta UIs are like Non-Diegtic UIs, the difference is that Meta UIs have some way of staying the fiction of the game. A great example is Call of Duty; There is no health bar, but when you are low on health the screen would be overlay with blood to show that you are damaged. Meta UIs are normally represented two dimensionally.

## Spatial

Spatial UIs are again like Non-Diegetic and Meta UIs, but the main difference is that Spatial UIs exist three dimensionally. An example of this is a glowing trail that appears on the floor that the player can follow.

# Answer
> 5 votes
I'm not sure what "spatial" or "meta" mean, but diegetic and non-diegetic are actually terms that originated with film music and mean essentially the same thing in the context of game UI. Diegetic means it's part of the scene, whereas non-diegetic means it's not part of the scene. So a diegetic UI is interface elements that are in the game scene (think the ammo display on Halo guns) whereas non-diegetic UI is buttons that aren't part of the game world (ie. the majority of game interfaces).

---
Tags: interface, terminology
---


# Question
Title: Proper way to divide a 2D climbing animation in Unity3D
I've got a 2D character that's going to climb up a 2D tile to his left or right and I've got a climbing animation consisting of three parts essentially:

* Animation for the character going from walking onto the ground -\> climbing on the wall
* The actual climbing animation when on the wall
* A "climbing over the top" animation for where the character pulls himself over the top of the wall and onto the ledge above.

What is the smoothest way to handle this in Unity? Do I need three separate animation clips for each of the steps, or can I do it with one and simply loop the middle section of the clip?

For example, my initial thought would be to have one clip for the entire animation and do the following:

1. play the first few "climbing onto the wall" frames when climbing onto the wall
2. loop the actual climbing animation while the character is on the wall and isn't ready to climb over the top
3. transition to the final few frames when the character is ready to pull himself over the top

Is this easily doable in Unity? Or is there an easier way to do this that I'm not thinking about? This seems a bit contrived and decently complicated so that's why I'm wondering.

# Answer
> 0 votes
From my experience recently in doing a few 3D animations, I found it very simple to just split up the animation into 3 separate clips. That way I felt that it was quite intuitive and easy when creating transitions between each animation clip in each stage of the overall animation. You also have a great deal more control over the animation transitions using this method.

If you split the animation up then just ensure that when you import the animations that you check the Loop animation check box in the Animations tab for the middle climbing animation clip and you should be good to go.

You can then also use State Machine Behaviours to drive any additional actions like playing sounds or effects etc during each clip.

I'm sure you could also perform some complex looping logic as you allude to, however that seems unnecessarily complicated and error prone in my opinion.

---
Tags: c#, unity, 2d, animation
---


# Question
Title: Broadcast message to Parent Gameobject and Siblings in Unity
I wish to broadcast a message from one object to it's parent and it's siblings. I am aware that unity does not support broadcasting a message to all other game objects but is there a way to broadcast to parent and siblings?

I am using Unity 5.

# Answer
> 2 votes
First off, are you aware of the command BroadcastMessage? It's not quite what you are asking for, but it's close and it happens to be named the exact terms you used. That command sends a message to all *children*, not siblings, but that means it will message all siblings if you use that command *on the parent.* So write something like: transform.parent.BroadcastMessage("FunctionName");

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


# Question
Title: Is there a way to drain durability from an item instead of a sword, for instance?
I am modding Minecraft 1.8 using Eclipse with Forge, and I just wondered, is there a way to drain durability from a battery, for instance, instead of a piece of armor when hit. I have tried things like getting an item from the player's inventory and attempting to reduce its durability, so that would be a possibility, however, I was unable to find a way to do so?

# Answer
You can use the field `inventory` in the player class to help you. Using the method `player.inventory.hasItemStack(ItemStack);` to test if it contains the battery item. An example:

```
@Override
public boolean onLeftClickEntity(ItemStack stack, EntityPlayer player,
        Entity entity) {
  if (player.inventory.hasItemStack(Items.battery)) {
    //Do something to it
    return false;
  } else {
    return true;
  }
}

```
> 2 votes

---
Tags: minecraft-modding, modding
---


# Question
Title: What size should I scale my sprites to before importing them to Unity?
I'm developing a game with an 8bit look. I want to target iOS and Android devices.

The real resolution for my backgrounds is 108 x 192.

Should I should put them in that same resolution and scale them in Unity using FilterMode / or s there a way to make the camera use nearest neighbor?

Or should I resize all my sprites before importing to something bigger? And if so to what size? 1920 x 1080?

# Answer
I think you have to weigh the cost / benefit of loading larger assets into your project verses dealing with scaled game objects within a scene. Personally I keep my assets at actual size, smaller the better and throw them into a sprite sheet, and scale them up within the editor. FilterMode Point is so crunchy works just fine for me! and from everything I have experienced the performance hit from scaled game objects is negligible.

The best thing you can do is actually take a look at `Static Batching` here: http://docs.unity3d.com/Manual/DrawCallBatching.html which would have much more potential for improved performance.

Overall targeting a phone, I would want to keep my assets as small as possible.
> 0 votes

---
Tags: unity, sprites
---


# Question
Title: Unity UI Input Field suddenly malfunctioned
I'm using Unity 5.0.1f1, and my UI Input Fields are not working as they are supposed to.

I have an Input Field that is placed in a Panel and inside a Canvas. It has a Text component in which I can set text that the Input Field will display. When I change value of this Text component, the changes are not reflected on the Input Field, it seems to be reset to the value of Input Field (Script) \ Text of the Input Field.

If I enter Play mode, I can input text normally but when I build and run on my Android phone, I cannot input anything.

Has anyone encountered this problem? How can I solve this?

# Answer
> 1 votes
The children of the InputField GameObject are modified as needs be by the scripts that make the InputField work (you'll notice a input caret child appears at runtime too and as you say the text attribute of the child is overwritten).

If you need to set a default value for the text there is a field in the inspector of the InputField Component on the parent InputField GameObject; underneath the "navigation" attributes, there is a reference to the "Text Component" of the child and a field which says "Text", add your text here.

I'm not an android developer so I've no idea how to fix the second part of the problem.

---
Tags: unity
---


title: Should UI be part of the game-loop?

text:
# Question
Title: Should UI be part of the game-loop?
I can't really find a good answer to this anywhere, I have never worked on games in a proffessional environment and I am wondering; *Do these games render their UI in the main game-loop?*

That is, do they render loading-screen, menu-screen, text-dialogs with running text, ingame UI (direction arrows for example) in the main game loop? that is the same game-loop they use to update and render the actual game-play, meaning only one activity is used, and the game-loop runs from the moment the app starts until it exits.

I'm having a hard time making my menu because I want to animate the buttons, but when I have the menu in my main game-loop and I for example press the "start game"-button, the game starts right away before the buttons animation is played (supposed to shrink), is this just done adding like a timer for delay or something like that (like in example below)? Feels so ugly.

Ugly pseudo code:

```
if(startButton gets pressed){
start button animation;
start 1 second timer;
timer finished -> start game;
}

```

EDIT: I'm building my game for ios and Android using LibGdx Java, but I guess this question is universal so that might not be relevent.

# Answer
> 4 votes
Yes, generally, games are a single main loop.

Games in Java may have a separate main loop for each menu/screen/mode due to Java's idioms, but that of course does not solve your animation wait problem.

For things like the problem you are running into, consider using events. e.g., when your animation system finishes playing an animation, it can send out an event indicating that the animation is done. The menu UI listens for this event and only transitions to the game state at that moment. That lets the animation play, plus it means that the animation can be changed (i.e. get a new duration) and the UI will properly adjust how long it waits before moving into the game state.

If events don't work well for you in this case, you could also just poll the animation state. Something like:

```
class MenuState {
  _startAnimation = null;

  void Update() {
    if(IsPressed(StartButton))
      _startAnimation = PlayStartAnimation();

    if(_startAnimation && _startAnimation->IsFinished())
      EnterGameState();
  }
}

```

That gives you (in this case) most of the advantages of the event systems. Most games will end up using a mixture of events and polling (depending on situation), so familiarizing yourself with both approaches is a good idea.

---
Tags: java, game-design, rendering, game-loop, mobile
---


title: Resize sprite to match camera width?

text:
# Question
Title: Resize sprite to match camera width?
I'm trying to resize my small background sprite to match the screen width of the user's device.

This is what I'm trying

```
// Use this for initialization
void Start () {
    // Set filterMode
    SpriteRenderer sr = (SpriteRenderer) GetComponent("Renderer");
    sr.sprite.texture.filterMode = FilterMode.Point;

    // Get scaling
    float multiplier = Camera.main.rect.width / sr.sprite.bounds.size.x;

    // Scale
    transform.localScale = localScale * multiplier;
}

```

It seems there is a problem with the measure I get from the Camera width, I also tried Screen.width but it seems it returns the value in pixels.

# Answer
> 4 votes
This functions should scale the sprite proportionally so it fits the camera width:

```
void fitCameraWidth() {
    SpriteRenderer sr = (SpriteRenderer)GetComponent ("Renderer");
    if (sr == null)
        return;

    // Set filterMode
    sr.sprite.texture.filterMode = FilterMode.Point;

    // Get stuff
    double width = sr.sprite.bounds.size.x;
    Debug.Log ("width: " + width);
    double worldScreenHeight = Camera.main.orthographicSize * 2.0;
    double worldScreenWidth = worldScreenHeight / Screen.height * Screen.width;

    // Resize
    transform.localScale = new Vector2 (1, 1) * (float)(worldScreenWidth / width);
}

```

If what you want to do if resize to fit the camera height (if your game is played in landscape this is probably what you would want):

```
void fitCameraHeight() {
    SpriteRenderer sr = (SpriteRenderer)GetComponent ("Renderer");
    if (sr == null)
        return;

    // Set filterMode
    sr.sprite.texture.filterMode = FilterMode.Point;

    // Get stuff
    double width = sr.sprite.bounds.size.x;
    double worldScreenHeight = Camera.main.orthographicSize * 2.0;

    // Resize
    transform.localScale = new Vector2 (1, 1) * (float)(worldScreenHeight / height);
}

```

---
Tags: unity, sprites, scale
---


# Question
Title: In RecastNavigation, how can I make an agent idle after reaching its destination?
*This question is specifically about dealing with the Recast Navigation library.*

I have added an agent with `addAgent` and set its target with `requestMoveTarget`. When agent reaches its destination, it stops, but when being pushed out of the way (by another agent) it will try to return back to its target. Instead, want it to stop and become idle, so that when other agent walking by push it aside and it wont return back.

I have tried calling `resetMoveTarget` upon `agent.npos` being close to `agent.targetPos` (as if agent has reached its destination), but that seems to break the inner logic of the crowd simulation - the agent would just keep walking in old direction, never stopping.

How do I properly tell an agent to stop and become idle (yet pushable) in RecastNavigation?

# Answer
> 2 votes
A fix was made upstream related to your solution that resets the desired velocity in `resetMoveTarget`.

```
bool dtCrowd::resetMoveTarget(const int idx)
 {
    if (idx < 0 || idx >= m_maxAgents)
        return false;

    dtCrowdAgent* ag = &m_agents[idx];

    // Initialize request.
    ag->targetRef = 0;
    dtVset(ag->targetPos, 0,0,0);
    dtVset(ag->dvel, 0,0,0); // <<-- This line added
    ag->targetPathqRef = DT_PATHQ_INVALID;
    ag->targetReplan = false;
    ag->targetState = DT_CROWDAGENT_TARGET_NONE;

    return true;
 }

```

# Answer
> 0 votes
I am not sure but my guess would be to call "requestMoveVelocity" with zero-vector as well on that agent. Give it a try.

# Answer
> 0 votes
**Note:** This solution appears to be superfluous, but I'm leaving it in case the issue re-appears.

After a lot of decoding, trial and error I took `dtCrowd.resetMoveTarget` as a base and found a way to modify it:

```
procedure TKMTerrainNavigation.AgentTargetClear(aIdx: Integer);
var
  ag: PdtCrowdAgent;
begin
  ag := fRecastCrowd.getAgent(aIdx);

  ag.targetRef := 0;
  dtVset(@ag.targetPos[0], 0, 0, 0);
  ag.targetPathqRef := DT_PATHQ_INVALID;
  ag.targetReplan := False;
  ag.targetState := DT_CROWDAGENT_TARGET_NONE;

  // Reset desired velocity
  dtVset(@ag.dvel[0], 0, 0, 0);

  // Reset agents corridor so that agent won't try to walk back to his last corner
  ag.ncorners := 0;
end;

```

P.S. Above code is in Delphi, but it should work just as well in C++.

Recast Navigation author commented:

> Instead of resetting the corners, you should reset the corridor to agents current position and first polygon.
>
> Setting target position to agents current position is generally preferred, than setting it to 0,0,0. But you're resetting everything else too, I think it is fine.

---
Tags: steering-behaviors
---


# Question
Title: How do I create a server for an existing game I don't have the source for?
I was wondering if it is possible to create a dedicated game server for a game that already exists and you don't have access to. For example, a game on Steam that only allows multiplayer through hosting a game with your running client. A client can host a server but only while the hoster is also playing the game.

The question being, is it possible to write a server from scratch that can replace the game client host with a dedicated server that does not require a player hosting it? If so, how?

# Answer
Can you? Yes.

You would need to capture all the packets sent from a client, and the return packets expected from the server. This is a super long and tedious process to decipher packets, if encrypted packets, you need to decrypt.

You would then need to write the entire server logic to interface with your newly understood packets.

The process usually evolves getting the client to accept a login into your custom server and going from there, step by step, figuring out what packets need to be exchanged to keep the client going barebones.

This is how private servers are made for AAA games.

Some sample tools might consist of https://www.wireshark.org/ to monitor network activity.
> 1 votes

---
Tags: networking, multiplayer, modding
---


# Question
Title: Implementing a delay timer into triggered method
I have a shoot method that is used as a mouseDown() Trigger on my player. I am wanting to introduce a delayTimer but am unsure of how to do this within the method due to the trigger.

```
public void Shoot(){
    if (BulletsManager.bullets > 0 && facingRight == true) {
        playShotgunSound();
        Instantiate (Bullet, firePoint2.position, firePoint2.rotation);
        BulletsManager.SubtractPoints (bulletsToSubtract);
        facingLeft = false;
        facingRight = true;
    }

        if (BulletsManager.bullets > 0 && facingLeft == true) {
        playShotgunSound();
        Instantiate (Enemy, firePoint2.position, firePoint2.rotation);
        BulletsManager.SubtractPoints (bulletsToSubtract);
        facingLeft = true;
        facingRight = false;
    }
}

```

Could anybody advise as to how I'd implement it within this code?

# Answer
> 0 votes
I found it was best to set up a Coroutine and calling each separate Coroutine within each if statement. The reason for this is a Coroutine allowed me to utilise

```
yield return new WaitForSeconds (shotDelay);

```

For more info reference: http://docs.unity3d.com/ScriptReference/Coroutine.html

# Answer
> 0 votes
Without a bit more clarification, it sounds like using invoke to delay the execution of a method might be what you need. Check out this script reference for Unity: http://docs.unity3d.com/ScriptReference/MonoBehaviour.Invoke.html

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


title: Move Sprite in direction of rotation

text:
# Question
Title: Move Sprite in direction of rotation
I have the following code.

```
void Update () {

        if (Input.GetAxis("Vertical")!=0)
        {
            GetComponent<Rigidbody2D>().AddForce(-transform.right);
        }

        if(Input.GetAxis("Horizontal")>0)
        {
            GetComponent<Rigidbody2D>().transform.Rotate(Vector3.forward * rotationSpeed);
        }

        if (Input.GetAxis("Horizontal") < 0)
        {
            GetComponent<Rigidbody2D>().transform.Rotate(Vector3.forward * rotationSpeed*-1);
        }
    }

```

This obviously moves my sprite in an asteroids fashion. What I really want is the sprite to track the direction it is facing (ie like a car) so as you rotate the sprite it continues its movement in the direction it is facing rather than the initial direction the force was applied.

# Answer
> 2 votes
When you rotate the transform object, rotate the velocity vector by the same amount.

---
Tags: unity, sprites
---


title: SFML game loop and FPS problems

text:
# Question
Title: SFML game loop and FPS problems
I've been building an SFML engine and I've been very confused on the FPS, frame independent movement and game loop.

My particular problem is that I have a variable set to 60 for the frame limit but changing this value doesn't seem to change the frame limit. I used the built in SFML window function to set a limit and it seems to work.

Am I doing something wrong with this loop?

```
while (mWindow.isOpen())
{
    time=renderClock.getElapsedTime();
    float fFps=1000000/time.asMicroseconds();
    std::stringstream s;
    s<<fFps<<" fps";
    fps.setString(s.str());
    renderClock.restart();

    const sf::Int64 frameTime = 1000000/FRAMES_PER_SECOND;
    sf::Clock c;
    sf::Time t=c.getElapsedTime();
    sf::Int64 nextFrameTime=t.asMicroseconds()+frameTime;

    int loops = 0;
    while( t.asMicroseconds() < nextFrameTime && loops < MAX_FRAMESKIP)
    {
        processEvents();
        updateTime=updateClock.restart().asMilliseconds();
        update(updateTime);
        t=c.getElapsedTime();
        loops++;
    }

    render();
}

```

Here's a link to my full code: https://github.com/csharpest94/SFML/blob/master/src/Game.cpp

# Answer
This might not be a solution to problem , but as far as I know main game loop should not be limited using `sf::Window::setFramerateLimit(unsigned int limit)`. Only game logic, AI, physics should be limited, events should be processed without any limitation as not to create input lag.

I would suggest:

```
sf::Clock clock;
sf::Time accumulator = sf::Time::Zero;
sf::Time ups = sf::seconds(1.f / 60.f);

while (windows.isOpen())
{
    ProcessEvents();

    while (accumulator > ups)
    {
        accumulator -= ups;
        UpdateLogic();
        //AI();
        //Physics();
    }

    Render();
    accumulator += clock.restart();
}

```

Smooth movement can be easily implemented because logic runs at 60 updates per second, so if you want for instance sprite to move about 100px you need to divide this by 60 or in example above multiply with `ups` variable:

`//pseudo code
sprite.move(100 * ups);` So every update your sprite will move for the same distance.

With this approach comes the danger that if you're not limiting game loop, your CPU will be working at high load, even if it's unnecessary. Unfortunately way to prevent this situation requires more complex game loops. Of course you can limit your render analogously and set it to be running at for example 100 frames per second, however that is not the best idea since there might be some issues if render can't keep up with fps - whole loop will be blocked.

I suggest you take a look at diagrams and descriptions in this article: http://entropyinteractive.com/2011/02/game-engine-design-the-game-loop/

About your problem, you can try implementing fixed time step loop I mentioned above with limiting main loop through `sf::Window::setFramerateLimit(unsigned int limit)`.
> 0 votes

# Answer
Why not just use the sf::Window::setFramerateLimit(unsigned int limit) method? That should be a lot more straightforward and it works flawlessly for me.

EDIT:Just read you used it before. Gonna tell you something. Basic of rule of programmers. If it works, don't fix it.
> 0 votes

# Answer
Your issue here is not that you are not using `sf::Window::setFramerateLimit(unsigned int limit)`, but that you are only actually calculating your `frameTime` variable once, as it is really a constant.

All that you have to do is change:

`const sf::Int64 frameTime = 1000000/FRAMES_PER_SECOND;`

to:

`sf::Int64 frameTime = 1000000/FRAMES_PER_SECOND;`

and that should fix the issue since the `frameTime` will now be calculated once every loop.
> 0 votes

---
Tags: sfml, frame-rate
---


# Question
Title: In XNA, how do I access a model's dimensions with code?
I'm trying to rotate a model around some axes, but this rotates it around the world origin. I understand that I need to translate the object relative to its own size before rotating it, but I don't know by how much.

I've done it by trial and error until now. How can I automatically read a model's width, height and position?

# Answer
There are a couple ways.

This way shows how you can do it at runtime by grabbing out all the vertices to build the BoundingBox around the model.

The first answer on this page is super old but the basic idea applies to use a custom processor for your model in the content pipeline so you can compute the BoundingBox and store it in the Tag property of the model.

Generally it's better to do it in the content pipeline and store the data with the model that way your users don't have to wait for those redundant calculations each time they boot the game, but either approach should work.
> 3 votes

---
Tags: xna, rotation, models
---


title: Legacy GUI - run OnGUI only once

text:
# Question
Title: Legacy GUI - run OnGUI only once
I remember something about onGui being able to be run multiple times per frame, and I also seem to recall that you can check 'which state' the onGUI is being run in, so that you can do all of the intense logic in just the part that gets run once.

Does anybody know what I am talking about --- I can't seem to remember what it was called and it is making googling it a daunting task. Thanks!

# Answer
> 1 votes
http://docs.unity3d.com/ScriptReference/Event.html

> "For each event OnGUI is called in the scripts; so OnGUI is potentially called multiple times per frame. Event.current corresponds to "current" event inside OnGUI call."

If you use the Event.current, and look for a given event type in the ongui, then you can have it run once per frame. Namely, looking for the 'repaint' event.

So something like:

```
void OnGUI(){
    if(Event.current.type != EventType.Repaint) return;
    //otherwise if currently painting the gui
    //do all this stuff
}

```

---
Tags: unity, gui, state
---


# Question
Title: Unity3d - deploy game to android device off site
I am using Unity3d to develop my game and my friend with android device wanted to test it. I am natively IOS developer and have no knowledge of deploying Android platform. What do I need other than Unity3d? The scenario here is that I have to send to my friend who is not developer to install and test on his device via internet. We used to have TestFlight App but that is history now.

# Answer
Well, here is the minimum you need:

* You have to install android sdk and set path to it in Unity preferences
* You have to switch target platform to android and set settings you need in Player Settings (like supported android versions etc.)
* Click "build" in Build Settings - if everything is fine you'll get an .apk file that you can send to your friend

But again, you might run into some problems. It depends of your project and your code. For example, if you have some plugin code that works only for iOS (using `[DllImport]` attribute) you might have to turn it off or rewrite for android (using `AndroidJavaClass`, for example). You might also be using some features that are not supported on android.

There might be some other problems, but there is no answer which ones - you should try it and find them out by yourself.

Also, you can test your .apk on android simulator before sending to anyone else (in this case install android studio or eclipse to make it a little more comfortable).
> 1 votes

# Answer
It sounds like you are talking about what is required to deploy to test devices. Luckily, it is significantly easier on Android than it is on iOS. Your tester will have to enable the installation of non-market on their Android device, after which they can just click on a link for an APK and download/install it through their phone's browser. To enable non-market executables, direct them to go to Settings, then Application Settings, and then to enable Unknown Sources. This will allow them to install non-market executables. If this is not suitable for your purposes, you can also go into the Android Marketplace portal and create your application, and from there you can add testers to your app. They should then be able to search and install it through the Android marketplace, but it will not be visible for users who are not in your app profile until after it has been officially released.
> 1 votes

---
Tags: unity, android
---


title: Send a prefab over network in Unity

text:
# Question
Title: Send a prefab over network in Unity
I want to instantiate an object on only the server and one client. This means Network.Instantiate is out of the question and I have to instantiate it manually. Since Network.Instantiate takes a prefab, there must be some way of identifying a prefab over a network( you can't send a reference in an rpc. ) How can I do this? Drag and dropping the prefab from the inspector is also not an option, since the component with this reference is on the server only( the client doesn't have a local reference. )

# Answer
It turns out Resources.FindObjectsOfTypeAll where T is GameObject, returns all game objects "resources" in the project. In other words this gets all your prefabs. They do not have to be in a "Resources" folder.

Using this list I can now search them by some sort of ID( either assigned by me, or Unity ), then send that ID over the network and find the prefab from that locally.

The problem with this is that the prefab has to be "loaded" on both machines. It's reasonable to believe that if a prefab is loaded on the server, it should be loaded in the client. As long as there is some reference to the prefab in a script( through the inspector, direct or indirect ) or the prefab is explicitly loaded using Resources.Load, it will be able to be found this way.

Also, assets are always loaded in the editor. Don't be fooled by this. It does not mean the asset will be loaded in a build.
> 0 votes

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


# Question
Title: How to write a script for circular motion?
Сan any body explain me the script for the tangential motion,so that when i cut the rope circle should move tangentially:

# Answer
First, let's define a few terms to make this simpler. Rope Vector: This is the vector from the ball's position to the anchor point (i.e. the rope). I am assuming it is not normalized. Ball Position: The center position of the ball, and the point from which the Rope Vector originates. Anchor Position: The other end of the rope, the point you are swinging around. Up Vector: A vector that points in the direction of "up". If you're in 3D, and the balls are moving along X and Y, your Up Vector will be {0,0,1} (a Z component of 1).

Since you have the Rope Vector, you just need to generate the vector that is perpendicular to your Rope Vector. The most straightforward way would be to figure out what direction you consider "up", and then take a cross-product of your rope vector and your up vector. You're not clear whether you are in 2D or 3D, so I am assuming 3D, but the math works the same either way (although you can remove components and make it simpler for the 2D case, its not important). The cross product will give you a vector perpendicular to the 2 vectors passed in. The order of the terms in the cross product will determine which direction the output points. You can now take your output vector and normalize it (divide each term of the vector by the vector's total length). This vector can be scaled by the current speed of the ball, and added to the Ball Position, which would give you a velocity vector in the perpendicular direction.

I've glossed over a few points, but this is a general solution to your problem. I can certainly elaborate if you specific questions. If you are doing all of this in 2D, you can convert them to 3D (just add a Z coordinate of 0 to each term), have an up vector of {0,0,1} and do the math. You'll see a bunch of terms cancel out because of the 0's, but you'll end up with a result that doesn't have a Z component, only X and Y.
> 1 votes

---
Tags: unityscript
---