# Question
Title: What do html5 game buyers/sponsors do with the game?
I understand there are html5 devs who make contracts with companies: they allow them to use their games for payment.

My question is how do these companies use these games to their benefit: what purposes do they have in forming these contracts and how does "buying" html5 games helps them accomplish it?

For example, if their purpose is generate money, how do they employ the html5 games for this goal?

# Answer
> 0 votes
Generally, such games are bought by dedicated browser-based game sites, which have an existing audience and a method to monetise it.

**Examples**: An ad-supported business model is very common. In addition, Miniclip sells a virtual currency for in-game items, Kongregate offers that as well as premium memberships, Armor Games does all of the above, but rather unusually also sells T-shirts and plushies.

---
Tags: html5
---


# Question
Title: When creating a game engine, how should I define the position of objects?
I'm building a custom game engine, in C++ using SDL, and I'm not sure how I should define the position of my game objects. I tried googling a bit, but I wasn't sure how to refine my search terms to get what I'm looking for.

Should I define the position (x, y) of my object to be the top left of the object, for ease of rendering? Since my game is tile based, it also makes sense to have the position of the tiles as the top left position.

Perhaps I should define it to be the center of the object, which seems to make more sense, logically? If we use `width/2` and `height/2` to calculate it, does the slightly-truncated integer for even-sized objects matter?

How do other games do this? Right now, my objects are defined by the top left corner, and it's annoying to do operations that find the center of the object.

# Answer
> 3 votes
Normally you will need three different sets of coordinates.

1. Store within your object class the top left corner as a vector, e.g. `<corner_x, corner_y>.`
2. For most tile-independent game logic, use the object's center `<center_x, center_y>`.
3. For realistic movements and application of force on object's with mass, store the object's mass center `<mass_center_x, mass_center_y>`.

You will need 1) for operation's like aligning your objects to each other, tiling or dragging with mouse in your map editor. It could be enough if you have a truly a game with solely tiles like chess.

You will need 2) for all kind of (tile independent) animations, rotational velocities and simple accelerations, collision detection and distance calculations. You might need that one if you are interested to check if your mouse pointer is hoovering over your object etc. Chance is that you need these coordinates too and they should be updated only if necessary to ease some calculations.

You will need 3) for when you apply forces for acceleration and/or your object's are able to rotate. Most likely not your cup of tea here. But if you are interested in creating a flexible game engine, keep this option viable. For example, I crated a user interface where a user can set a boundary box by dragging his mouse over an object and set optionally a mass center instead of the standard x/2, y/2.

Edit: Truncation does matter and you need to account for this by storing it as a float point precision and update the position accordingly. If you don't do this, there is a good chance that your rectangles' sizes will vary +/- 1 pixel conditional on their position on screen which can look weird. That's why for tile based game's your idea of having topleft corner as standard coordinates is a reasonable choice.

# Answer
> 0 votes
Let the developer choose. Most engines with 2d capabilities I've used allow this.

# Answer
> 0 votes
Games typically don't hardcode it either way. You have a point, which is the position of the object's origin. The object then has a graphics model/sprite and a root physics body, either of which can define a shape around that origin.

One object may decide to define both its model and body as `[-0.5,-0.5];[+0.5,+0.5]`, making the origin at the center.

Another object may decide to define its physics body as `[-0.5,0.0];[+0.5,+0.8]`, which means that the center of the body is at its "feet" (the middle of its bottom), while the sprite may be given the range `[-0.6,-0.1];[+0.6,+0.9]` which makes its sprite a little wider than the physics body in all directions.

Physics will need to know some additinal details about its center-of-mass for most "realistic" simulations, but graphics shouldn't have any reason to care at all about how the origin relates to the shape actually being drawn.

---
Tags: game-design
---


# Question
Title: How can I do something only once In Update function?
when I do something In `Update()`:

```
void Update(){
Debug.Log("Hello World");
}

```

I have this output:

```
Hello World
Hello World
.
.
.
Hello World

```

but Instead of printing manytimes I need a way that print `Hello World` once.

# Answer
> 2 votes
If you want your code to run once you can simple solve it by having a boolean that checks if your code has run before and then simply do or don't do it. (with a if-statement):

```
bool isDone = false;

void Update() {
    if (!isDone) {
        // put your code that runs once here
        isDone = true;
    }
}

```

This way, that piece of code that is in the Update() method will only be called once because of that boolean.

Let me know if this answers your question.

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


# Question
Title: How to load multiple 3D models dynamically xna
I want to load multiple 3D models `.fbx` at the same time in my map display.
I can load First Model but when I use ContentBuilder to Load another Model, I Got Error in `effect.EnableDefaultLighting ();` This my load function

```
private void loadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();

            // Default to the directory which contains our content files.
            string assemblyLocation = Assembly.GetExecutingAssembly().Location;
            string relativePath = Path.Combine(assemblyLocation, "../../../../Content");
            string contentPath = Path.GetFullPath(relativePath);
            fileDialog.InitialDirectory = contentPath;
            fileDialog.Title = "Load Model";
            fileDialog.Filter = "Model Files (*.fbx;*.x)|*.fbx;*.x|" +
                                "FBX Files (*.fbx)|*.fbx|" +
                                "X Files (*.x)|*.x|" +
                                "All Files (*.*)|*.*";
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                LoadModel(fileDialog.FileName);
            }
        }
        void LoadModel(string fileName)
        {
            Cursor = Cursors.WaitCursor;
            // Unload any existing model.
            editorDesign1.Model = null;
           // editorDesign1.CurrentModel.Model = null;
            contentManager.Unload();
            // Tell the ContentBuilder what to build.
            contentBuilder.Clear();
            contentBuilder.Add(fileName, "Model", null, "ModelProcessor");
            // Build this new model data.
            string buildError = contentBuilder.Build();
            if (string.IsNullOrEmpty(buildError))
            {
                // If the build succeeded, use the ContentManager to
                // load the temporary .xnb file that we just created.
              editorDesign1.Model = contentManager.Load<Model>("Model");
              // editorDesign1.CurrentModel.Model = contentManager.Load<Model>("Model");
            }
            else
            {
                // If the build failed, display an error message.
                MessageBox.Show(buildError, "Error");
            }

            Cursor = Cursors.Arrow;
        }

```

and this is my Draw `model function`

```
public void DrawModel()
        {
            foreach (ModelMesh mesh in Model.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.EnableDefaultLighting();
                    effect.World = Matrix.CreateTranslation(Position) * Matrix.CreateRotationX(Rotation.X) * Matrix.CreateScale(Scale) * Matrix.CreateRotationY(Rotation.Y) * Matrix.CreateRotationZ(Rotation.Z);

                    effect.View = view;
                    effect.Projection = projection;
                }

                mesh.Draw();
            }
        }

```

The problem is when I create two object from my model class and use ContentBuilder to Load another Model I get an exception `AccessViolationException was Unhandled` `Attempted to read or write protected memory. This is often an indication that other memory is corrupt`
and get another exception `NullReferenceException was unhandled`

Can anyone help me tho solve this problem?

# Answer
> 1 votes
I can find several problems, mainly with your workflow. First it looks like your editor can only show one model at a time anyway. Every time the dialog is launched the editor is cleared. You should use an array or a list to contain the models that are in the editor.

```
editorDesign1.Model = null;
...
editorDesign1.Model = contentManager.Load<Model>("Model");

```

Should become...

```
editorDesign1.Models = new List<Model>(); // or Models.Clear();
...
editorDesign1.Models.Add(contentManager.Load<Model>("Model"));

```

Also, you shouldn't clear the list upon loading if you want multiple files.

Your `AccessViolationException` is probably caused by the fact that when you build a model it saves it to the `Model` file. When you try to load another model, it also tries to write to the `Model` file which already exists and is protected, so the error is thrown.

You should either delete the file after it is loaded to memory or use unique names for the binary file.

---
Tags: xna, 3d, model-loader
---


# Question
Title: WP 8.1 XNA custom game loop (render when dirty?)
I need to know whether it's possible to create a XNA game for Windows Phone 8.1 (which I've already) using monogame with a custom game loop.

OpenGL ES has this possibility (GL\_RENDERMODE\_WHENDIRTY or sth. like that).

Is there anything like that RenderMode for XNA/MonoGame on WP 8.1

**Note:** I'm new to Windows phone game programming.

# Answer
1-Create an xaml page
2-Create a new GraphicsDevice
3-Put your own game loop
> 2 votes

# Answer
Although I may be misinterpreting your question, you are trying to make a loop that doesn't draw when it does not need to. XNA has this capability.

```
if (needsToDraw == false) {
   this.SuppressDraw();
}

```

The `SuppressDraw()` function is part of the `Game` class (you can read more at MSDN). In this case, you need to determine if the game needs to be drawn yourself. If it does not, you simply call `SuppressDraw` during the game's `Update` loop.
> 1 votes

---
Tags: xna, xna-4.0, monogame, windows-phone-8
---


title: How i can make hole in objects in unity

text:
# Question
Title: How i can make hole in objects in unity
I need to have a hole in my objects and I don't want to use terrain.

I'd like to use an object and cut them out of another object, so that there is a hole in which the player could fall into; a 'game over' would happen.

# Answer
If the road is a static object you can boolean it in 3d max and re-import, if not you'll have to use a third party plugin ( since unity it self doesn't allow complex modeling )

Something like MegaMesh would suit your purpose, also try this project, found it when searching around
> 3 votes

---
Tags: unity
---


# Question
Title: Calculating the vector to catch a falling object
I have two objects in a three dimensional world. One is a ballistic projectile: that is, it is free-falling with some known gravitational acceleration. The other is a catcher that travels with constant velocity and is not subject to gravity. I want to calculate the vector that the catcher must travel along in order to intercept and catch the falling projectile (or the position of intercept between the catcher and the projectile).

By my reckoning, the problem can be formulated into equations like this:

Intercept position = Catcher start position + Catcher velocity * Intercept time

Intercept position = Projectile start position + Projectile start velocity * time + 1/2 * Gravitational acceleration * Intercept time^2

...where all the named variables except intercept time are three-dimensional vectors. Within those equations, I know:

* The catcher and projectile start positions
* The projectile's current velocity
* The projectile's gravitational acceleration
* The magnitude of the catcher's velocity.

I don't know, and could solve the problem by finding out any one of:

* The direction of the catcher's velocity
* The intercept position
* the intercept time

...but I have really struggled to make any headway finding a solution to these equations. Can anyone help me out? Is there something missing from/incorrect about my approach here?

# Answer
Ultimately, the right answer to this problem proved to be "it's too hard; choose to solve a different problem instead".

What I've ended up doing is using (Distance between catcher and projectile / Catcher velocity) to find an *approximate* intercept time, then plugging that into the second of the two formulae in the question to calculate the projectile's location at that time. I then fudge the speed of the catcher to make sure that it actually arrives at that destination at the right time.

In practice, that means that the catcher does actually catch the projectile most of the time (when it would be possible for it to do so), and its "fudged" extra speed isn't too apparent in most cases.

For purists who are interested in the technically correct solution to this question, there was a clever approach suggested in this Mathematics Stack Exchange answer. I wish you better luck in resolving it into an actual solution than I had, however.
> 0 votes

# Answer
* **Constructing the formula**

Kinetic Energy on ground (catcher) is equal to Potential Energy when he is in his start position. This means that `(1/2) mv^2 = mgh >> v^2 = 2gh >> v = sqrt(2gh)`

Now that we know that v on interception is the root of gh we have to define g and h. Lets say h is your height relative to the catcher and `g = 10m/s^2`. This means that `v = sqrt(20*h)`

We also know `a = v/t` and because g is our `a, g = v/t >> t = v/g >> t = sqrt(20*h)/10`

Know we can calculate average speed of catcher: `v = x/t >> v = x/(sqrt(20*h)/10)`

The final formula of the speed of the catcher = `x / (sqrt(2g*h)/g)`

Ps: a = Acceleration, g = Gravity, h = Height, x = Distance to catcher, sqrt = Square root

\[Code is coming soon\]
> 0 votes

---
Tags: 3d, mathematics, ai, vector
---


title: Timers and performance for mobile JS

text:
# Question
Title: Timers and performance for mobile JS
I'm using the Three.js JavaScript library to do some things in WebGL, and **I wonder how the graphic aspects of timers are done on mobile.**

I was creating numbers with geometries and just replacing them when needed. This was fine on desktop (or so I think, lol). Recently, I've been playing around with mobile and the previous method is far too slow.

# Answer
Graphics timing in modern browsers, including (especially) on mobile, is done via `requestAnimationFrame()`, introduced as a result of the W3C's specs on timing control for script-based animations, replacing the older `setInterval()` approach. Both call an event handler.

`requestAnimationFrame()` (RAF) ensures far more reliable / regular timing than `setInterval()` and the like. How it works (loosely) under the hood is to let the browser know that what is currently happening in the timed event handler is an animation, and as such certain measures should be taken (by supporting browsers) to ensure this process proceeds smoothly. And to quote MSDN:

> simplifies animations by scheduling the next animation frame only when the system is ready to paint. This leads to smoother animations and less power consumption than previous animation techniques because requestAnimationFrame takes the visibility of the web application and the refresh rate of the display into account.

At least for Mozilla-based browsers and IE, RAF will typically match the display refresh rate and so generally guarantees a steady refresh period / frequency of around 60FPS, although admittedly Opera docs suggest that RAF does *not* guarantee this. In general, however, I would go with the Chrome/Firefox/IE recommendation, which is that you can rely on the rate noted above.

Under the hood, Three.js will be using RAF, or if the browser doesn't support it, will fall back to `setInterval()`.
> 1 votes

---
Tags: javascript, mobile, webgl, three.js, timing
---


# Question
Title: How to calculate height of a thought line over a known spot in 3rd person view?
Assuming a player object with third-person-view is in a **3d room** and the center of the screen has a dot - let's call it "*cursorTarget*".

All I have is the position of the player, the position 5 meters in front of it - let's call it "*spot*" - and (if necessary) the position where the *cursorTarget* touches the ground if it's below the horizon.

With that given data, is it possible to calculate the **height** of the (thought) line between player and *cursorTarget* right **above the *spot***?

I firstly thought of the intercept theorem, but I lack of knowledge of the camera height in that third-person-view.

Kind regards, Stacky

# Answer
As it turned out, there is a command to get the height of the camera above ground. It's called "positionCameraToWorld" and with that it's possible to get the spot height by applying the intercept theoreme.
Pseudo code:

```
cameraPosition = positionCameraToWorld [0, 0, 0]; //result = [x, y, z]
cameraHeight   = cameraPosition[2];

distance_cursor_camera = cursorTarget distance2D cameraPosition;
distance_cursor_spot   = cursorTarget distance2D spot;

ratio_distances = distance_cursor_camera / distance_cursor_spot;
spotHeight = cameraHeight / ratio_distances; //height of the red line in the above image

```
> 0 votes

---
Tags: 3d, mathematics, modding, linear-algebra, third-person-view
---


# Question
Title: How do I efficiently check if a point is inside a rotated rectangle?
Part for the sake of optimization, part for learning purposes, I will dare to ask: How can I most efficiently check whether a 2D point `P` is inside a 2D rotated rectangle `XYZW`, using C# or C++?

Currently, what I am doing is using a "point in triangle" algorithm found in the book *Real Time Collision Detection*, and running it twice (for the two triangles that make up the rectangle, say XYZ and XZW):

```
bool PointInTriangle(Vector2 A, Vector2 B, Vector2 C, Vector2 P)
{
 // Compute vectors
 Vector2 v0 = C - A;
 Vector2 v1 = B - A;
 Vector2 v2 = P - A;

 // Compute dot products
 float dot00 = Vector2.Dot(v0, v0);
 float dot01 = Vector2.Dot(v0, v1);
 float dot02 = Vector2.Dot(v0, v2);
 float dot11 = Vector2.Dot(v1, v1);
 float dot12 = Vector2.Dot(v1, v2);

 // Compute barycentric coordinates
 float invDenom = 1 / (dot00 * dot11 - dot01 * dot01);
 float u = (dot11 * dot02 - dot01 * dot12) * invDenom;
 float v = (dot00 * dot12 - dot01 * dot02) * invDenom;

 // Check if point is in triangle
 if(u >= 0 && v >= 0 && (u + v) < 1)
    { return true; } else { return false; }
}

bool PointInRectangle(Vector2 X, Vector2 Y, Vector2 Z, Vector2 W, Vector2 P)
{
 if(PointInTriangle(X,Y,Z,P)) return true;
 if(PointInTriangle(X,Z,W,P)) return true;
 return false;
}

```

However, I have the feeling that there might be a cleaner and faster way. Specifically, to reduce the number of math operations.

# Answer
> 4 votes
An easy and straightforward optimization would be to change the final condition in `PointInTriangle`:

```
bool PointInRectangle(Vector2 A, Vector2 B, Vector2 C, Vector2 P) {
  ...
  if(u >= 0 && v >= 0 && u <= 1 && v <= 1)
      { return true; } else { return false; }
  }
}

```

the code was pretty much `PointInRectangle` already, the condition `(u + v) < 1` was there to check if it is not in the "second" triangle of rectangle.

Alternatively, you could also do an `isLeft` (first code example on page, also greatly explained) test four times, and check that they all return results with the same sign (which one depends on whether the points were given in clockwise or counterclockwise order) for the point to be inside. This works for any other convex polygon too.

```
float isLeft( Point P0, Point P1, Point P2 )
{
    return ( (P1.x - P0.x) * (P2.y - P0.y) - (P2.x - P0.x) * (P1.y - P0.y) );
}
bool PointInRectangle(Vector2 X, Vector2 Y, Vector2 Z, Vector2 W, Vector2 P)
{
    return (isLeft(X, Y, P) > 0 && isLeft(Y, Z, P) > 0 && isLeft(Z, W, P) > 0 && isLeft(W, X, p) > 0);
}

```

# Answer
> 8 votes
**Edit:** The OPs comment has been skeptical about the efficiency of the suggested negative circular bound check to improve the algorithm in order do checks whether an arbitrary 2D point lies within a rotated and/or moving rectangle. Fiddling around a bit on my 2D game engine (OpenGL/C++), I supplement my answer by providing a performance benchmark of my algorithm against the OPs current point-in-rectangle-check algorithms (and variations).

I originally suggested to leave the algorithm in place (as it is nearly optimal), but simplify through mere game logic: (1) using a pre-processed circle around the original rectangle; (2) do a distance check and if the point lies within the given circle; (3) use the OPs or other any straightforward algorithm (I recommend the isLeft algorithm as provided in another answer). The logic behind my suggestion is that checking whether a point is within a circle is considerably more efficient than a boundary check of a rotated rectangle or any other polygon.

My initial scenario for a benchmark test is to run a large number of appearing and disappearing dots (whose position changes in every game-loop) in a constrained space that will be filled with around 20 rotating/moving squares. I have published a video (youtube link) for illustration purposes. Notice the parameters: number of randomly appearing dots, number or rectangles. I will benchmark with the following parameters:

**OFF**: Straightforward algorithm as provided by the OP without circle boundary negative checks

**ON**: Using per-processed (boundary) circles around the rectangles as a first exclusion check

**ON + Stack**: Creating circle boundaries at run-time within the loop on the stack

**ON + Square Distance**: Using square distances as a further optimization to avoid taking the more expensive square root algorithm (Pieter Geerkens).

Here is a *summary* of the various performances of different algorithms by showing the time it takes to iterate through the loop.

The x-axis shows an increased complexity by adding more dots (and thus slowing down the loop). (For example, at 1000 randomly appearing point checks in a confided space with 20 rectangles, the loop iterates and calls the algorithm 20000 times.) The y-axis shows the time it take (ms) to complete the entire loop using a high resolution performance timer. More than 20 ms would be problematic for a decent game as it would not take advantage of the high fps to interpolate a smooth animation and the game may appear thus 'rugged' at times.

**Result 1**: A pre-processed circular bound algorithm with a fast negative check within the loop improves the performance by 1900% compared to the regular algorithm (5% of the original loop time without a check). The result holds approximately proportional to the number of iterations within a loop, thus it does not matter if we check 10 or 10000 randomly appearing points. Thus, in this illustration one can increase the number of objects safely to 10k without feeling a performance loss.

**Result 2**: It has been suggested by a previous comment that the algorithm may be faster but memory intensive. However, note that storing a float for the pre-processed circle size takes merely 4 bytes. This should pose no real issue unless the O.P. plans to run simultaneously 100000+ objects. An alternative and memory efficient approach is to calculate the circle maximum size on the stack within the loop and letting it go out of scope with every iteration and thus having practically no memory usage for some unknown price of speed. Indeed, the result shows that this approach is indeed slower than using a pre-processed circle size, but it still shows a considerable performance improvement of around 1150% (i.e. 8% of the original processing time).

**Result 3**: I further improve the result 1 algorithm by using squared distances instead of actual distances and thus taking an computationally expensive square root operation. This only sligthtly boosts the performance (2400%). (Note: I also try hash tables for pre-processed arrays for square roots approximations with a similar but slightly worse result)

**Result 4**: I further check moving/colliding the rectangles around; however, this does not change the basic results (as expected) as the logical check remains essentially the same.

**Result 5**: I vary the number of rectangles and find that the algorithm becomes even more efficient the less crowdy the space is filled (not shown in demo). The result is also somewhat expected, as the probability decreases for a point to appear within tiny space between a circle and the object's boundaries. On the other extreme, I try to increase the number of rectangles too 100 within the same confined tiny space AND vary them dynamically in size at run time at within the loop (sin(iterator)). This still performs extremely well with increase in performance by 570% (or 15% of the original loop time).

**Result 6**: I test alternative algorithms suggested on here and find a very slight but not significant difference in performance (2%). The interesting and more simple IsLeft algorithm performs very well with a boost of performance by 17% (85% of the original calculation time) but nowhere near the efficiency of a quick negative check algorithm.

My point is to first consider lean design and game logic, especially when dealing with boundaries and collision events. The OPs current algorithm is already fairly efficient and a further optimization is not as critical as optimizing the underlying concept itself. Moreover, it is good to communicate the scope and purpose of the game, as the efficiency of an algorithm critically depends on them.

I suggest to always attempt to benchmark any complex algorithm during the game design stage as merely looking at the plain code may not reveal the truth about actual run-time performance. The suggested algorithm may not be here even necessary, if, for example, one wishes to merely test if the mouse cursor lies within a rectangle or not, or, when the majority of objects are already touching. If the majority of points checks are within the rectangle, the algorithm will be less efficient. (However, then it would be possible to establish an 'inner circle' boundary as a secondary negative check.) Circle/sphere boundary checks are very useful for any decent collision detection of a large number of objects that have naturally some space in between them.

```
Rec Points  Iter    OFF     ON     ON_Stack     ON_SqrDist  Ileft Algorithm (Wondra)
            (ms)    (ms)    (ms)    (ms)        (ms)        (ms)
20  10      200     0.29    0.02    0.04        0.02        0.17
20  100     2000    2.23    0.10    0.20        0.09        1.69
20  1000    20000   24.48   1.25    1.99        1.05        16.95
20  10000   200000  243.85  12.54   19.61       10.85       160.58

```

# Answer
> 2 votes
Defining a rectangle with 4 points makes it possible to make a trapezoid. If however, you would define it by x, y, width, height and a rotation around its middle, you could just rotate the point you're checking by the inverse rotation of your rectangle (around the same origin) and then check if it's in the original rectangle.

# Answer
> 1 votes
I didn't have the time to benchmark this, but my suggestion would be to store the transformation matrix that transforms the rectangle into the axis aligned square in the x- and y-range from 0 to 1. In other words store the matrix that transforms one corner of the rectangle into (0,0) and the opposite one into (1,1).

This would of course be more expensive if the rectangle is moved a lot and collision is checked rather seldomly, but if there are a lot more checks than updates to the rectangle it would at least be faster than the original approach of testing against two triangles, as the six dot products would be replaced with one matrix multiplication.

But as always the speed of this algorithm depends a lot on the kind of checks you expect to be performed. If most of the points aren't even close to the rectangle performing a simple distance check (e.g. (point.x - firstCorner.x) \> aLargeDistance) might result in a large speedup, while it might even slow things down if almost all of the points are inside the rectangle.

EDIT: This is what my Rectangle-class would look like:

```
class Rectangle
{
public:
    Matrix3x3 _transform;

    Rectangle()
    {}

    void setCorners(Vector2 p_a, Vector2 p_b, Vector2 p_c)
    {
        // create a matrix from the two edges of the rectangle
        Vector2 edgeX = p_b - p_a;
        Vector2 edgeY = p_c - p_a;

        // and then create the inverse of that matrix because we want to
        // transform points from world coordinates into "rectangle coordinates".
        float scaling = 1/(edgeX._x*edgeY._y - edgeY._x*edgeX._y);

        _transform._columns[0]._x = scaling * edgeY._y;
        _transform._columns[0]._y = - scaling * edgeX._y;
        _transform._columns[1]._x = - scaling * edgeY._x;
        _transform._columns[1]._y = scaling * edgeX._x;

        // the third column is the translation, which also has to be transformed into "rectangle space"
        _transform._columns[2]._x = -p_a._x * _transform._columns[0]._x - p_a._y * _transform._columns[1]._x;
        _transform._columns[2]._y = -p_a._x * _transform._columns[0]._y - p_a._y * _transform._columns[1]._y;
    }

    bool isInside(Vector2 p_point)
    {
        Vector2 test = _transform.transform(p_point);
        return  (test._x>=0)
                && (test._x<=1)
                && (test._y>=0)
                && (test._y<=1);
    }
};

```

This is the full listing of my benchmark:

```
#include <cstdlib>
#include <math.h>
#include <iostream>

#include <sys/time.h>

using namespace std;

class Vector2
{
public:
    float _x;
    float _y;

    Vector2()
    :_x(0)
    ,_y(0)
    {}

    Vector2(float p_x, float p_y)
        : _x (p_x)
        , _y (p_y)
        {}

    Vector2 operator-(const Vector2& p_other) const
    {
        return Vector2(_x-p_other._x, _y-p_other._y);
    }

    Vector2 operator+(const Vector2& p_other) const
    {
        return Vector2(_x+p_other._x, _y+p_other._y);
    }

    Vector2 operator*(float p_factor) const
    {
        return Vector2(_x*p_factor, _y*p_factor);
    }

    static float Dot(Vector2 p_a, Vector2 p_b)
    {
        return (p_a._x*p_b._x + p_a._y*p_b._y);
    }
};

bool PointInTriangle(Vector2 A, Vector2 B, Vector2 C, Vector2 P)
{
 // Compute vectors
 Vector2 v0 = C - A;
 Vector2 v1 = B - A;
 Vector2 v2 = P - A;

 // Compute dot products
 float dot00 = Vector2::Dot(v0, v0);
 float dot01 = Vector2::Dot(v0, v1);
 float dot02 = Vector2::Dot(v0, v2);
 float dot11 = Vector2::Dot(v1, v1);
 float dot12 = Vector2::Dot(v1, v2);

 // Compute barycentric coordinates
 float invDenom = 1 / (dot00 * dot11 - dot01 * dot01);
 float u = (dot11 * dot02 - dot01 * dot12) * invDenom;
 float v = (dot00 * dot12 - dot01 * dot02) * invDenom;

 // Check if point is in triangle
 if(u >= 0 && v >= 0 && (u + v) < 1)
    { return true; } else { return false; }
}

bool PointInRectangle(Vector2 X, Vector2 Y, Vector2 Z, Vector2 W, Vector2 P)
{
 if(PointInTriangle(X,Y,Z,P)) return true;
 if(PointInTriangle(X,Z,W,P)) return true;
 return false;
}

class Matrix3x3
{
public:
    Vector2 _columns[3];

    Vector2 transform(Vector2 p_in)
    {
        return _columns[0] * p_in._x + _columns[1] * p_in._y + _columns[2];
    }
};

class Rectangle
{
public:
    Matrix3x3 _transform;

    Rectangle()
    {}

    void setCorners(Vector2 p_a, Vector2 p_b, Vector2 p_c)
    {
        // create a matrix from the two edges of the rectangle
        Vector2 edgeX = p_b - p_a;
        Vector2 edgeY = p_c - p_a;

        // and then create the inverse of that matrix because we want to
        // transform points from world coordinates into "rectangle coordinates".
        float scaling = 1/(edgeX._x*edgeY._y - edgeY._x*edgeX._y);

        _transform._columns[0]._x = scaling * edgeY._y;
        _transform._columns[0]._y = - scaling * edgeX._y;
        _transform._columns[1]._x = - scaling * edgeY._x;
        _transform._columns[1]._y = scaling * edgeX._x;

        // the third column is the translation, which also has to be transformed into "rectangle space"
        _transform._columns[2]._x = -p_a._x * _transform._columns[0]._x - p_a._y * _transform._columns[1]._x;
        _transform._columns[2]._y = -p_a._x * _transform._columns[0]._y - p_a._y * _transform._columns[1]._y;
    }

    bool isInside(Vector2 p_point)
    {
        Vector2 test = _transform.transform(p_point);
        return  (test._x>=0)
                && (test._x<=1)
                && (test._y>=0)
                && (test._y<=1);
    }
};

void runTest(float& outA, float& outB)
{
    Rectangle r;
    r.setCorners(Vector2(0,0.5), Vector2(0.5,1), Vector2(0.5,0));

    int numTests = 10000;

    Vector2 points[numTests];

    Vector2 cornerA[numTests];
    Vector2 cornerB[numTests];
    Vector2 cornerC[numTests];
    Vector2 cornerD[numTests];

    bool results[numTests];
    bool resultsB[numTests];

    for (int i=0; i<numTests; ++i)
    {
        points[i]._x = rand() / ((float)RAND_MAX);
        points[i]._y = rand() / ((float)RAND_MAX);

        cornerA[i]._x = rand() / ((float)RAND_MAX);
        cornerA[i]._y = rand() / ((float)RAND_MAX);

        Vector2 edgeA;
        edgeA._x = rand() / ((float)RAND_MAX);
        edgeA._y = rand() / ((float)RAND_MAX);

        Vector2 edgeB;
        edgeB._x = rand() / ((float)RAND_MAX);
        edgeB._y = rand() / ((float)RAND_MAX);

        cornerB[i] = cornerA[i] + edgeA;
        cornerC[i] = cornerA[i] + edgeB;
        cornerD[i] = cornerA[i] + edgeA + edgeB;
    }

    struct timeval start, end;

    gettimeofday(&start, NULL);
    for (int i=0; i<numTests; ++i)
    {
        r.setCorners(cornerA[i], cornerB[i], cornerC[i]);
        results[i] = r.isInside(points[i]);
    }
    gettimeofday(&end, NULL);
    float elapsed = (end.tv_sec - start.tv_sec)*1000;
    elapsed += (end.tv_usec - start.tv_usec)*0.001;
    outA += elapsed;

    gettimeofday(&start, NULL);
    for (int i=0; i<numTests; ++i)
    {
        resultsB[i] = PointInRectangle(cornerA[i], cornerB[i], cornerC[i], cornerD[i], points[i]);
    }
    gettimeofday(&end, NULL);
    elapsed = (end.tv_sec - start.tv_sec)*1000;
    elapsed += (end.tv_usec - start.tv_usec)*0.001;
    outB += elapsed;
}

/*
 *
 */
int main(int argc, char** argv)
{
    float a = 0;
    float b = 0;

    for (int i=0; i<5000; i++)
    {
        runTest(a, b);
    }

    std::cout << "Result: " << a << " / " << b << std::endl;

    return 0;
}

```

The code certainly isn't beautiful, but I don't immediately see any major bugs. With that code I get results that indicate that my solution is about twice as fast if the rectangle is moved between each check. If it doesn't move then my code seems to be more than five times faster.

If you know how the code is going to be used you can even speed it up a little more by separating the transformation and the checks into the two dimensions. For example in a racing game it would probably be faster to check the coordinate first that points in the driving direction, because many obstacles will be in front or behind the car, but hardly any will be right or left of it.

---
Tags: c#, collision-detection, geometry, optimization
---


# Question
Title: Performance of instantiating many prefabs as children of one prefab in unity
Is there any performance difference between **\[instantiate multiple prefabs\]** and **\[put all prefabs under a single parent prefab and then instantiate that parent prefab\]** in scene.
Hope you understand what i want to say.

# Answer
> 0 votes
Thanks to DMGregory.
I've got an answer so I post it.
When I instantiate multiple(20000) individual prefabs(using loop 20000 times) at once in my scene,
I get (**573.73 to 463.63** Time ms and **43.81 to 30.63** Self ms)
but when I put 20 child prefabs to single parent and then instantiate parent prefab 1000 times in loop,
I get (**290.18 to 290.00** Time ms and **2.93 to 2.92** Self ms)
So, second way is better and efficient for my case.

---
Tags: unity, performance, instancing
---


# Question
Title: Possible to open Hammer directly from shortcut?
I want to open Hammer(for CS:GO) directly from windows shortcut, without the SDK-launch menu. Is this possible? I've only been able to open the SDK launcher from a shortcut.

And, is it possible to open a map directly as well? So, 1 shortcut that opens Hammer, with a specific map inside of Hammer?

If there exist a launch option for this, then I can use that!

# Answer
> 1 votes
Yup, its possible. Create a shortcut to the hammer.exe and add the -nop4 parameter. ("D:\Steam Games\SteamApps\common\Counter-Strike Global Offensive\bin\hammer.exe" -nop4)

---
Tags: steam, hammer
---


# Question
Title: glutPostRedisplay() does not update display
I am currently drawing a rectangle to the screen and would like to move it by using the arrow keys. However, when I press an arrow key the vertex data changes but the display does refresh to reflect these changes, even though I am calling `glutPostRedisplay()`. Is there something else that I must do?

My code:

```
#include <GL/glew.h>
#include <GL/freeglut.h>
#include <GL/freeglut_ext.h>
#include <iostream>
#include "Shaders.h"
using namespace std;

const int NUM_VERTICES = 6;
const GLfloat POS_Y = -0.1;
const GLfloat NEG_Y = -0.01;

struct Vertex {
    GLfloat x;
    GLfloat y;
    Vertex() : x(0), y(0) {}
    Vertex(GLfloat givenX, GLfloat givenY) : x(givenX), y(givenY) {}
};

Vertex left_paddle[NUM_VERTICES];

void init() {
    glClearColor(1.0f, 1.0f, 1.0f, 0.0f);

    left_paddle[0] = Vertex(-0.95f, 0.95f);
    left_paddle[1] = Vertex(-0.95f,  0.0f);
    left_paddle[2] = Vertex(-0.85f,  0.95f);
    left_paddle[3] = Vertex(-0.85f,  0.95f);
    left_paddle[4] = Vertex(-0.95f,  0.0f);
    left_paddle[5] = Vertex(-0.85f,  0.0f);

    GLuint vao;
    glGenVertexArrays( 1, &vao );
    glBindVertexArray( vao );

    GLuint buffer;
    glGenBuffers(1, &buffer);
    glBindBuffer(GL_ARRAY_BUFFER, buffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(left_paddle),
        NULL, GL_STATIC_DRAW);

    GLuint program = init_shaders( "vshader.glsl", "fshader.glsl" );
    glUseProgram( program );

    GLuint loc = glGetAttribLocation( program, "vPosition" );
    glEnableVertexAttribArray( loc );
    glVertexAttribPointer( loc, 2, GL_FLOAT, GL_FALSE, 0,
                           0);

    glBindVertexArray(vao);
}

void movePaddle(Vertex* array, GLfloat change) {
    for(int i = 0; i < NUM_VERTICES; i++) {
        array[i].y = array[i].y + change;
    }
    glutPostRedisplay();
}

void special( int key, int x, int y ) {
    switch ( key ) {
    case GLUT_KEY_DOWN:
        movePaddle(left_paddle, NEG_Y);
        break;
    }
}

void display() {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glDrawArrays(GL_TRIANGLES, 0, 6);
    glutSwapBuffers();
}

int main(int argc, char **argv) {

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
    glutInitWindowSize(500,500);
    glutCreateWindow("Rectangle");

    glewInit();
    init();

    glutDisplayFunc(display);
    glutSpecialFunc(special);

    glutMainLoop();
    return 0;

}

```

# Answer
> 1 votes
You need to actually update the vPosition vertex attribute in your draw function. As is, you're always redrawing with the original value you used in the init function.

Do not be fooled by the fact that OpenGL takes pointer arguments. It does not store a reference to the memory of your position vector, but rather makes a copy of it (likely into the video memory).

# Answer
> -1 votes
Add `glutIdleFunc(display);` to `main()`.

---
Tags: c++, opengl
---


title: How to fix texture edge artefacts?

text:
# Question
Title: How to fix texture edge artefacts?
This issue has been annoying me for a long time now and even after reading  lot of articles about it, I am still unable to fix the issue.

First, to my setup. I'm using LWJGL for a 2D project, rendering in immediate mode (yes, I know, FBOs, but I feel like it's too late to change it now). Textures can be scaled, rotated tinted and cropped in any way and are read from packed spritesheets that are multiples of 2 (the one in question is 512x1024 for example).

**The Problem**

Because there is no smoothing applied to the textures, scaled and rotated textures look quite ugly, showing jagged lines and black outlines. I tried improving it with using `glEnable(GL_POLYGON_SMOOTH)` (even though I know now that this is apparantly a bad practice, but I have no idea how to add multisampling to immediate mode rendering, other sites even state that multisampling is probably overkill for 2D games, which leaves me even more confused). This is what it looks like, with and without `POLYGON_SMOOTH`:

Quite clearly, there are multiple issues visible:

1. With `POLYGON_SMOOTH` disabled, there are horribly jagged lines and dark edges (that aren't there in the texture)
2. With `POLYGON_SMOOTH` enabled, the edges are no longer jagged, but the dark edges are still there and now there are those diagonal lines. After reading up on that a bit, I found out that it has something to do with how graphics cards render quads, which is as two triangles, and when smoothing is applied, this happens. To test that out, instead of drawing a single quad I draw two triangles which indeed moves the diagonal lines around.

The dark edges seem to be caused by something like like pre-multiplied alpha (according to this), but when I check the raw pixel data, it doesn't look pre-multiplied to me. A completely white texture with 0.5f alpha for example is represented as (in ARGB) `0x80FFFFFF`. So applying the "fix" (using `glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA)` instead of the default `glBlendFunc(GL_SRC, GL_ONE_MINUS_SRC_ALPHA)`suggested in the article doesn't really work, because my textures aren't premultiplied alpha, so alpha components don't work anymore (same texture, black background):

Texture without alpha:

I do use custom shaders, so I guess I probably could make alpha work in some way by passing it to the shader and then multiplying the color by it, would that fix the dark edges (which would enable me to use `GL_ONE`, the "better" blend function)? That would still leave me with the issue of the diagonal lines though, which I seem to be able to move around, but not remove.

# Answer
> 3 votes
To get rid of the jagged lines add 1 line of transparent pixels around the rectangle texture.

The issue with the dark lines is that you are most likely using black transparent pixels (color #000000). The issue is most likely to be gone if you use colored transparency instead. - Repeating the border pixels of your sprite - but simply with alpha=0

---
Tags: opengl, textures, lwjgl
---


# Question
Title: Changing the duration of motion state transitions in Animator Controller
Anyone around who is experienced with Unity animation states and the **Animation Controller**? I wonder is it possible in Unity to change the duration of time it takes between motion transitions in the Animator Controller?

To give an example let's say I have a human character that has an initial state of *Grounded* and in this state I have several motions like *idle*, *running forward/backward* and *strafe left/right*. When I now have the character in *idle* and I move left/right to go into strafe motion, the duration of the transition from *idle* to *strafe left/right* takes too long and I want it to be faster. I only want that transition between the motion states to be faster but not the actual animation itself. I think there should be a way to do this but I can't find any options for changing the duration between motions.

I'm aware that the duration between states can be changed by selecting a transition connection between states but what I'm talking about here are the motions inside a state.

# Answer
> 0 votes
You can make use of threshold to achieve this. If you place the threshold of two events close to each other then the transition will happen very quickly. But this gives rise to a new problem, i.e. the animation state in the center does not stay active for a longer time. For that we add the same animation twice and put its threshold to the desired max range

Refer to the following image

* In this set up , the value from 0 to 0.2 will be the transition from left to center.
* The value from 0.2 to 0.8 will transition between same animation hence there wont be any difference as identical animations are getting blended .
* Then from 0.8 to 1 will be transition to right.

So in this way the transition is restricted to a range of 0.2 rather than 0.5 (which is typically seen in the normal setup i.e. 0 to 0.5 to 1) . Refer to the following image.

---
Tags: unity, animation, state, mecanim, motion
---


# Question
Title: Matching collider to character mesh size in different postures
What's the optimal method in Unity to match the size of a `Capsule Collider` to the actual size of the game object it is part of?

To understand what I'm trying to do let me give an example:

I have a 3D player character with a `Capsule Collider` that is used to check collision. The character can go into various postures, e.g. crouch, prone, jump. I'm having difficulties to match the height of the collider to the height of the character when crouching or jumping because depending on the used animations the character's height is smaller by various amounts when crouched or jumping.

All I could do so far is set a multiplier for a specific posture by that the collider scales but this is very inefficient, especially when the character tries to jump onto a higher ground.

There seems to be no way of knowing the exact size of a mesh. I'm not sure if it might help to loop through all child meshes (torso, hair, etc.) in a game object and obtain their bounds through `SkinnedMeshRenderer`.

# Answer
Its best to handle collider scalling through mecanim system. Please refer to the following video. The guy adjusts the collider size according to the animation state. It covers the same problem which you are currently facing.

https://youtu.be/Xx21y9eJq1U?t=2161
> 2 votes

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


# Question
Title: Setting 4 different enemy spawn zones off screen
This is my first game, so I really appreciate all the help.

I want to create four enemy spawn zones for enemies and this areas are off screen. The enemies are coming from left, right, up and down, and their destination is a sprite on the center of the screen. And there are 4 types of enemies (only thing that changes is color).

Current code I have only makes the enemies come from the right direction into the screen. I don't really know the reason of this, I am really new to game making and some of this methods.

Relevant code I have for enemies if the following:

```
private void createEnemies() {
    listP.add(regionA);
    listP.add(regionV);
    listP.add(regionAm);
    listP.add(regionR);
    Random ran = new Random();
    int z = ran.nextInt(3 - 0 + 1) + 0;
    Sprite ship = loadSprite(100, 100, listP.get(z));
    attachChild(ship);
    Enemies enemy = new Enemies(ship);

}

 @Override
protected void onManagedUpdate(float pSecondsElapsed)   {
    listP.add(regionA);
    listP.add(regionV);
    listP.add(regionAm);
    listP.add(regionR);
    Random ran = new Random();
    int z = ran.nextInt(3 - 0 + 1) + 0;
    super.onManagedUpdate(pSecondsElapsed);
    timeEnemies +=  pSecondsElapsed;        //  Acumulates time
    if  (timeEnemies>TIME_LIMIT)    {   //  Time has completed
        timeEnemies =   0;
        Sprite spriteEnemy  =   loadsprite(GameControl.CAMARA_WIDTH+listP.get(z).getWidth(),
                (float)(Math.random()*GameControl.CAMARA_HEIGHT-listP.get(z).getHeight())   +
                        listP.get(z).getHeight(),listP.get(z));

        Enemigos newEnemy = new Enemies(spriteEnemy);
        //newEnemy.mover(0,10);
        listEnemies.add(newEenemy); //  Adds it to the scene
        attachChild(newEnemy.getEnemySprite()); //  adds to list

    }

    //  Updates enemies and checks if any has gone offscreen
    for (int    i=listEnemies.size()-1; i>=0;   i--)    {
        Enemies enemy   =   listEnemies.get(i);
        enemy.getEnemySprite().setPosition(GameControl.CAMARA_WIDTH,0); // <-- Was experimenting with this code, but doesn't really help now
        enemy.mover(-10,0);
        if  (enemy.getEnemySprite().getX()<-enemy.getEnemySprite().getWidth())  {
            detachChild(enemy.getEnemySprite());        //  Eliminates from scene
            listEnemies.remove(enemy);                                                                  //  Eliminates from the list
        }
        //  Checks collision with center sprite

        if  (spriteCenter.collidesWith(enemy.getEnemySprite())) {
            detachChild(enemy.getEmemySprite());

        }
    }
}

```

Enemies class:

```
public class Enemies {

private Sprite sprite;

public Enemies(Sprite sprite) {

    this.sprite = sprite;
}

public Sprite getEnemySprite() {
    return sprite;
}

public void setSprite(Sprite sprite) {
    this.sprite = sprite;
}

public void mover(int dx, int dy) {

    sprite.setPosition( sprite.getX()+dx, sprite.getY()+dy );
}

```

}

# Answer
> 1 votes
You only seem to be moving your enemies to the left:

```
enemy.mover(-10,0);

```

From what I can see, all of your enemies are being updated with this line of code, so they're all being moved to the left rather than moving towards their desired target. That's why the ones off the right hand side of the screen appear and the others don't.

Try changing your `enemy.mover()`method to something like this (this isn't particularly good movement code, but hopefully it will help you see where you're going wrong):

```
public void mover(int targetX, int targetY)
{
    int xPos = sprite.getX();
    int yPos = sprite.getY();
    if (xPos > targetX)
    {
        xPos--;
    }
    else if (xPos < targetX)
    {
        xPos++;
    }
    if (yPos > targetY)
    {
        yPos--; //you might need to change this to ++ depending on how the axes are set up
    }
    else if (yPos < targetY)
    {
        yPos++; //you might need to change this to -- depending on how the axes are set up
    }
    sprite.setPosition( xPos, yPos );
}

```

Then call it by passing in whatever the target is (centre of the screen in your case):

```
enemy.mover(target.getX(), target.getY());

```

The above code basically just checks to see if the enemy is either too far left or right of the target (x axis), or too far above or below the target (y axis), and if they are, moves them towards the target.

You'll probably want to change the `--`'s and `++`'s for faster movement. `+=10` and `-=10` are the equivalents for your current speed.

---
Tags: java, android, game-mechanics, andengine, android-studio
---


title: IOS/Android Game programming

text:
# Question
Title: IOS/Android Game programming
I am somewhat new to the whole game programming thing. I was wondering if I could develop a game for IOS and Android with using openGLES. if so how can I run the code on the devices and what are some good resources to continue learning from. I am only targeting mobile devices so information for PC/Mac is irrelevant to me. Thank you for your help :)

# Answer
> 0 votes
Here are some resource you can look at on how to develop in OpenGL ES. I just linked iOS tutorial. The IDE you can get is Xcode to develop the game which has a way to test it out. Sadly with iOS, you cant actually have it tested on a device but for android you may test it without it being published in their Play store.

Tutorial on how to get started

More resources

# Answer
> -1 votes
I think you would use the Android Studio for Android and Xcode for iOS. One more thing is the ShaderDesigner app (for Windows) it helps a lot on the development of shaders for you game or grphical application. I never programmed for iOS, so I don't know well what to do. But for Android, its amazing for learning from learnopengles. I think it's not complete, but if you're noob in GLES, this is good for now. After learning all they have there, you can search books in it-eboos.info

---
Tags: opengl-es
---


# Question
Title: how to set up health bar rect that depends on health?
I need some help with game math.

**What I am using:**

I am using java awt library.

**What I am trying to do:**

I am trying to build enemy health bar, which will display as an rectangle. I am display two rectangles. First one is black rectange and it will act as in base container. 2nd one is red rectangle and it will act as helath bar.

now the max size of enemy health bar will be enemy.getWidth(). I need some help with 2nd red rectangle width. how can I set up so that it dependents on enemy.getHealth() and max is enemy.getWidth.?

and enemy.getHealth() will be 4.

**Code:**

```
    g.setColor(Color.black);
    g.fillRect(enemy.getX(), enemy.getY(), enemy.getWidth(), 5);
    g.setColor(Color.red);
    g.fillRect(enemy.getX(), enemy.getY(), enemy.getHealth() * 4, 5);

```

# Answer
The width of the red rectangle should be:

```
enemyWidth * (enemyCurrentHealth / enemyMaxHealth);

```
> 1 votes

# Answer
It's simple the percentage of current health compared to max health. Something like

```
percentage =enemy.getHealth()/enemy.getWidth()
fillRect.Width(fillRect.Width()*percentage);

```

To change the color, you can have something like

```
if (percentage<=0.25)  gsetColor(Color.red);
if (percentage>0.25 && percentage<0.5)  gsetColor(Color.yellow);

```

etc.
> 0 votes

---
Tags: java
---


title: How to Sort Shoebox frames by order?

text:
# Question
Title: How to Sort Shoebox frames by order?
I ve been playing with ShoeBox lately and when trying to make a frame sheet i see that they don't appear alphabetically (frame\_1 , frame\_2 , etc). But they appear by best fitting. In Texture-Packer you can sort it by name but i cant see that option in ShoeBox.

How can i do this?
Thanks in advance

# Answer
It's not possible in ShoeBox.

Why don't you just use TexturePacker since it already does what you want?
> 1 votes

---
Tags: spritesheet
---


# Question
Title: Mixamo Models not Importing Correctly in Unity
Mixamo (now Adobe Mixamo) allows us to choose character and then animations from its website from free samples. I have done one simple animation and added the model to Unity. The animation works fine but the model is very changed once being imported, have a look here.

I am using following import settings,

Format: Fbx for Unity

Skin: With Skin

FPS: 30

Keyframe Reduction: Uniform

I tried "Fbx" format only too, but no luck.I also applied "humanoid" in rigging, but I think it is not relevant here. Since I am not good with modeling that is why I am using this service, and I have no idea how to tackle this. Once it did worked well, but unfortunately I could not remember how, so I am stuck again.

# Answer
> 2 votes
This looks like inverted normals. Is there an option for that somewhere? (In Mixamo as well as Unity). Also, check the material in Unity. It might be set to Transparent/Bumped Diffuse. Switch that to a non-transparent one

---
Tags: unity, models, importing
---


# Question
Title: Where to put the screen dimensions to make it accessible for all on screen objects?
I'm starting game development to learn a new language (SDL2, C++) and would like some opinions on the best way to handle a probably very basic problem.

I don't want my player to go off screen, so I have something like this now:

```
void Player::sanitizePosition() {
    if ( m_xpos < 0 ) {
        m_xpos = 0;
    }

    if ( m_ypos - m_height < 0 ) {
        m_ypos = m_height;
    }

    ...
}

```

For the other two sides I would need the screen dimensions. Now I'm wondering what the best way to give them to the object would be?

Global variables are bad, but a Singleton with the screen information seems like the same thing to me.

Another idea would be to have a `GameObject` base class, that has the screen dimensions as static members, which `Player` would inherit from.

Of course I could put them into the constructor of every game object, but that just screams code smell.

This is such a basic problem, I'm sure there is a consensus on how to do it.

# Answer
> 1 votes
I guess there are many feasible design approaches. For me what has worked best is that I created two classes: **GameCamera** and **GameInit**. GameInit holds all possible resolutions and is fairly technical, but passes the essential stuff, such as the best available screen resolution, monitor ratio etc. to the one and only instance of GameCamera.

Now, you may now (perhaps rightly) say: "Are you kidding me?? GameCamera, a singleton?! Nope, I dare to say there are actually few things where a singletons can be useful, and that is if you know absolutely sure that you will not need a second instance of the class and you provide an additional 'initializer' and 'updater' functions for your game objects that will collect the essential global data from the singleton(s) (and where inheritance would be rather cumbersome to implement as you just don't want your bullet to be also camera or mouse...!

To make things work, you gotta be careful though. I use in all my other classes two essential functions: Simplified that's `InitAllGlobalData()` which is called only once after all classes have been initialized, and `UpdateData()` which is naturally placed in the GameLoop.

`InitAllGlobalData()` instantiates all the static global data for your object. In this function, you will instantiate your member data by copying all the essential stuff from GameCamera, e.g. `{myScreenSize=Ref.ScreenSize}` etc. The advantage is that, (1) if you break my rule and dare to create a second instance of GameCamera, you could exceptionally help yourself by calling again the function or its overloaded instance `InitAllGlobalData(GameCamera &Ref)` where you only update the new camera stuff, without worrying that somewhere in line 14291 in your collision algorithm of your 12th .cpp file there is the need to find again the edge of the universe; (2) all access to this singleton and other global data is clean and tidy in that one function and thus easy to find/modify if you ever revisit your code.

The other, `bool UpdateData()` copies all member data that is dynamic, such as, Zoom, Scroll etc. They get updated in the Gameloop, although GameCamera may return prematurely if there is nothing to update. Hence, your collision objects that bounce around access dynamic members of GameCamera through a pointer call in UpdateData() and update their own member data through that.

For example, GameCamera holds stuff like Zoom(), ScrollEdge() etc., so the bullet's object own private member myZoom is updated when needed within `UpdateData() {MyZoom=GameCamera->GetCurrentZoomLevel();)`. Note that there is no other call to GameCamera anywhere in my class, except by the power of those two functions--tame your singletons!

However, I felt this is also not an ideal design when dealing with different resolutions on different computers when we have to deal with static "HUD" (head-up-design) objects like radars, message screen, messages etc.

I thus added secondary screen-percentage units as a member function of GameCamera (going from 0 to 100) for positioning of HUDs. For example, I want a radar always to be on the top right corner (=90,90) and no matter the resolution of the screen. Now since the screen is probably more wide than high, x units are automatically adjusted by this ratio, but not the radar size (10 units) as it would appear stretched. Naturally, in my `DisplayScreen` class, I have the aforementioned `InitAllGlobalData()` function that initalizes through that the necessary members, but no `UpdateData()`, as I do not need anything dynamic like Scroll, Zoom etc. from GameCamera.

This ensured me that I have the same design and same game feel, no matter the prevailing screen resolution etc. I have faced no issues so far in terms game design (currently 35k lines code) and can reuse my code in other projects, as I just refurbish my UpdateData() and InitAllGlobalData() functions. But, to be honest with you, I have not plunged into networking yet, and Update() may need some additional thoughts when coming to synchronizing at runtime, but I will update this post once I get to that stage.

# Answer
> 0 votes
This is the approach I usually go with.

C# Example

```
class Scene
{
    public int Width;
    public int Height;
    public List<GameObject> Objects;

    /* TODO: Initialize the collection. */

    public void AddObject(GameObject gameObject)
    {
        this.Objects.Add(gameObject);
        gameObject.Scene = this;
    }

    public void RemoveObject(GameObject gameObject)
    {
        this.Objects.Remove(gameObject);
        gameObject.Scene = null;
    }
}

abstract class GameObject
{
    public Scene Scene;
}

```

This is a good OOP approach and allows you to have multiple Scenes with different dimensions should that ever be needed. It also allows you to do generic sanitizing in the Scene itself rather than having to implement it on each GameObject.

---
Tags: collision-detection, architecture
---


# Question
Title: Read custom content in MONO-GAME in a cross-platform way
using **Mono-Game**,

* i have some custom content files in some binary format (**not .xnb**)
* in run-time i need to read the content of those files.
* i prefer to get a stream, but if something will give me a filled byte\[\] or something, that's also fine..
* this must be **cross-platform** as much as possible and work on PC \ Mobile \ consoles \ web \ what-ever-mono-game-offers

;

my efforts so far :

* **ContentManager.Load()** does not read custom formats
* subclassing ContentManager, and overriding **OpenStream(string assetName)** did not help - it expects the file i give it to end with **.xnb**
* renaming all files to "**.xnb**" just for this is not possible for me, because some other proccess reads thease files and expects them the way they are
* **TitleContainer.OpenStream()** seems to read files from the file system, but im not sure how they will be packed when building for mobile devices for example.

(i know that in **unity**: for android, content is simply copied to a folder on the device, but on iphone all content is packed to a binary package.. so reading from the file-system will not work)

(i dont have an iphone\ipad to test this on)
* the simple "**File.ReadAllBytes()**" is no good for the same reason

;

My questions are :

1. am i right about TitleContainer's cross-platform limitation ?
2. what can i do ?

thanks.

# Answer
I recommend creating a custom Content project for each unique format. I recommend this blog as a starting point: http://dylanwilson.net/creating-custom-content-importers-for-the-monogame-pipeline Also take a look at the answer to this question: MonoGame 3.4 Content Pipeline Extension missing reference

A custom Content project will enable you to create your own .xnb format files. A custom Content project makes using your unique file formats equally simple as using out-of-the-box supported formats such as .png and .mp3 .

In your list of requirements you state that an external program needs the files as well. If this is because the external program is a tool you use to create/modify these assets, then it is no problem. Simply point the Content project to the source file and the Content pipeline will convert it to a .xnb content file when you build your project.

If you want the external program to be able to access the files when your game is already build then you really don't have another option than leave the files as-is. However I'm not sure how that would work for mobile, as I believe all mobile installs are in a container and are generally not able to access files from other packages.

`TitleContainer.OpenStream()` allows you to read from the filesystem. If your package includes the files, I would expect the method to be able to read it. After all, as you state, Unity would copy the content to a folder as well. So if you set the properties of the files to be included in your build step, you should be able to read it.
> 1 votes

---
Tags: xna, monogame, mobile, cross-platform, xna-content-pipeline
---


# Question
Title: "Squeezing" a game object based on distance to another game object
I am trying to "squeeze" a gameObject. When distance starts to be 6.98, execute this code: "The smaller the distance between gameObject1 and gameObject2, the thinner and longer this gameObject is". Somehow, this code has no effect. Why?

```
public Transform gameObject1;
public Transform gameObject2;

void Update ()
{
    float distance_squeeze = Vector3.Distance(gameObject1.position,
                                              gameObject2.position);
    if(distance_squeeze < 6.98F)
    {
        transform.localScale = new Vector3(-distance_squeeze, distance_squeeze, 1);
    }
}

```

# Answer
> 2 votes
If I understand question correctly, you wish to reduce width(*x* scale) so that total area of object is maintained. In order to do that, when setting *x* scale you need to set *y* scale to `1/x`.
Second part is finding the *x* scale. Please note that it is *relative* to object width:

```
float original_width = 6.98f; //no magic constants, this will pay off in long run
void Update ()
{
  float distance_squeeze = Vector3.Distance(gameObject1.position, gameObject2.position);
  //note: you probably wanted to subtract gameObject2's witdth/2 here - you probably wanted distance from edge, not center
  float scale_x = distance_squeeze / original_width; //relative
  scale_x = Mathf.Min(scale_x, 1.0f); //do no stretch, equivalent to if(<6.98f)
  transform.localScale = new Vector3(scale_x, 1.0f / scale_x, 1.0f);
}

```

*note: this assumes default scale 1.0f, for details see chat linked in comments.*

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


title: Isometric Mouse Camera Panning

text:
# Question
Title: Isometric Mouse Camera Panning
I am building an isometric game environemnt and i want to be able to pan the camera around the map by holding the right mouse button, can someone talk me through the logic for this please, i have made an attempt and tried a number ways. I can get the camera to move correctly the first time but when i click and hold the second time the camera resets itself, thanks in advance for any help

```
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class CameraMovementTest extends JPanel{

private Timer timer;
private int DELAY = 10;
private  CustomMouseListener mouseListener;
private int positionX = 0, positionY = 0;

public CameraMovementTest() {

    mouseListener  = new CustomMouseListener();
    this.addMouseListener(mouseListener);
    this.addMouseMotionListener(mouseListener);
    this.setSize(500,500);
    this.setVisible(true);

    //Swing Timer
    timer = new Timer(DELAY, new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent arg0) {
            update();
            repaint();
            validate();
        }
    });
    timer.start();
}

private void update() {
    if(mouseListener!=null){
        positionX = mouseListener.getX();
        positionY = mouseListener.getY();
    }
}

@Override
public void paint(Graphics g) {
    super.paint(g);
    g.fillRect( positionX,  positionY, 300,300);
}

public class CustomMouseListener implements MouseListener, MouseMotionListener {
    private int positionX = 0, positionY = 0;
    private int mouseClickX, mouseClickY;

    @Override
    public void mousePressed(MouseEvent evt) {

        if(SwingUtilities.isRightMouseButton(evt)) {

            mouseClickX = evt.getX();
            mouseClickY = evt.getY();
        }
    }
    @Override
    public void mouseDragged(MouseEvent evt) {
        if(SwingUtilities.isRightMouseButton(evt)) {
            positionX = mouseClickX - evt.getX();
            positionY = mouseClickY - evt.getY();
        }
    }
    @Override
    public void mouseMoved(MouseEvent arg0) {}
    @Override
    public void mouseClicked(MouseEvent arg0) { }
    @Override
    public void mouseEntered(MouseEvent arg0) { }
    @Override
    public void mouseExited(MouseEvent arg0) {}

    @Override
    public void mouseReleased(MouseEvent arg0) {}
    public int getX(){
        return positionX;
    }
    public int getY(){
        return positionY;
    }
}

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            JFrame f = new JFrame();
            f.setVisible(true);
            f.setSize(new Dimension(500,500));
            f.setContentPane(new CameraMovementTest());
        }
    });
}

```

}

# Answer
> 0 votes
```
@Override
public void mouseDragged(MouseEvent evt) {
    if(SwingUtilities.isRightMouseButton(evt)) {
        positionX = mouseClickX - evt.getX();
        positionY = mouseClickY - evt.getY();
    }
}

```

You're setting the position to the difference between the initial mousedown and the actual position. In this case, what you get is the expected result. What you rather should do is calculate the delta between the actual and the last mouse position and add this delta to the position:

```
@Override
public void mousePressed(MouseEvent evt) {

    if(SwingUtilities.isRightMouseButton(evt)) {
        mouseClickX = evt.getX();
        mouseClickY = evt.getY();
    }
}
@Override
public void mouseDragged(MouseEvent evt) {
    if(SwingUtilities.isRightMouseButton(evt)) {
        int deltaX = mouseClickX - evt.getX();
        int deltaY = mouseClickY - evt.getY();
        mouseClickX = evt.getX();
        mouseClickY = evt.getY();
        positionX += deltaX;
        positionY += deltaY;
    }
}

```

(You might need to fix the direction by replacing the `+=` with `-=`)

---
Tags: camera, movement, isometric, mouse
---


# Question
Title: Is there a random command for Boolean variables in Unity C#
Can you randomly choose a Boolean's value in Unity C#. I tried random.range, but it only works with floats. Here is an example of what I'm trying to do:

```
Boolean = (random boolean value command)(false, true);
if(Boolean = true){
    Debug.Log("It's true!")
} else{
    Debug.Log("It's false!")
}

```

Any ideas?

# Answer
SanSolo answer is good and he get my +1.

Using unity Random.value here is a one line command:

```
bool Boolean  = (Random.value > 0.5f);

```
> 17 votes

# Answer
Random.Range will return an integer if both min and max are integers. `Random.Range(0,2)` will return either one or zero. You could use it like this:

```
Boolean boolValue = (Random.Range(0, 2) == 0);
if(boolValue == true){
    Debug.Log("It's true!");
} else{
    Debug.Log("It's false!");
}

```
> 7 votes

---
Tags: unity, c#, random, boolean
---


# Question
Title: How can I stop players from cheating on puzzle levels by finding solutions on the web?
In a level based, puzzle-like, game, how can we prevent the gamers to be searching on the Internet for solutions to a specific level? I'd like to let players fairly compare their scores.

I've thought about adding some randomness to the levels, but that has the downside of losing control over how hard the level is, and how it feels.

Are there specific strategies to solve this issue?

# Answer
> 48 votes
People reading about a game in the net is a problem for all games, not just level-based puzzle ones. For instance a simple search can give you detailed walkthrough/cheatsheet/solutions/guides to any game you can think of. Even games like Fifa or LoL that obviously has no definite solution in the first place. But that being said you can more or less control people checking for online material. Here are the few tricks I've seen being used:

1. As you said adding some random elements to your levels. And it really depends on your game how it can be achieved. For example a game about guessing numbers can choose a random number each run, and give different hints about that hint, while maintaining the general idea of how to solve that puzzle. Another option is to have multiple variations of each level having minor but critical differences, and ask player to solve one of them each time. Obviously it's the best if each player has a single set of levels persistent through his own play meaning a single player shouldn't see two different variations of same level. The list continues and you can think of your own solutions, but this really is the hard answer.
2. Some games offer solution guides themselves, either online or in-game. This will reduce the change of players looking online for solutions, or others offering detailed walkthroughs. An example of this would be "machinarium" in which you could play a short minigame and get the solution to each chapter. You also can purposely miss some few details in the solutions you provide, this will kinda force people to solve the puzzles themselves, while discouraging them from looking online.
3. Perfecting your difficultly curve. Most people don't want to use online guides, They only ask for help if they are forced to. Since playing puzzle games in more about proving yourself you can do it. By perfecting your difficulty curve you can decrease the chance of people getting frustrated with puzzles and thus, reducing the chance of them seeking solutions from other sources.

All that being said, people will cheat, whether you like it or not. But using these methods you can only reduce the number of times they cheat and that's the best you can hope for.

# Answer
> 11 votes
If a player cheats, it's likely either because they're frustrated with a particular puzzle (and want to continue progressing) or they're disinterested in a particular puzzle and just want to get it over with. Either case may be indicative of a problem with the particular puzzle's design.

It helps a lot if your mechanics allow for more than one solution to the same puzzle. A good example of how this can play out in a positive way is the game SpaceChem, made by Zachtronics. There are actually two separate score metrics (often with competing requirements, meaning that optimizing one requires reducing the other.) Because there are so many different solutions to each puzzle, copying a solution off the internet really doesn't impact much (just changes the histogram slightly for how many players achieve each score.) Of course, some of the puzzles in the game are fiendishly difficult, so maybe it's best that players *can* cheat if they want to.

On a side note, the bigger issue in the above is validating that the solution is actually a real solution to the puzzle and not just a faked set of score data. The developer has a dev post on this where he describes a server-side validator that checks each solution against a model of the game logic prior to accepting the reported score. This might actually be of more concern for you (if you want to allow score comparisons) than whether players can duplicate eachother's solutions.

# Answer
> 7 votes
Possibly not the answer you might seek. However that problem does seem like a non-issue. You are searching for a technical solution to a social problem - an endeavour which is often bound to fail.

However what should matter more is that your customers, your players, are happy: If someone chooses to seek for a solution guide in the web, that's what s/he needs for happyness that moment - also those websites are free advertizement for your game. Thus if one chooses to search for a solution, it's a willfull decision which makes him happy. Other players may willfully choose to not search for it - and are happy about that, too. Thus comparisons of the speed in which fixed level-based games are played-through inevitably can be cheated or skewed by players finding solutions prior to actually playing it.

Further, disallowing this by scrambled levels won't necessarily make you customers more happy.

If you want to allow a universal comparison you have to go for really randomized levels - but then the scores of course are also not directly comparable as one random set might turn out easier than another. Of course you can still increase a difficulty during different levels by adding further elements which constrain solutions and as such will pose a greater challenge than available in lower levels

# Answer
> 2 votes
2 parts to my answer: one actually addressing the question and one suggesting the question needs questioned.

**Potential Solution**

One idea that springs to mind is holding regular 'blind level contests'.

The general premise is that you have a separate score board only for these contests where by once a month the newest contest level is made available and players update their game to install it. Scores for this level can then only be submitted for N amount of time after the update, say 30 min - 1 hr depending how complex the game is.

You could take this a step further and have multiple level releases throughout the day, some sort of aggregated scoring at the end.

It goes without saying this depends greatly on the business model of the game and whether it will have regular updates / releases or whether it is meant to be fairly static as in released and forgotten about. However this style of contents should allow your core players who will care about how they compare to others to take part and find out.

---

**Philosophical note**

Is looking up the solution online really cheating?

If I want to be the best at something, say Mario Kart, then I'm going to do all the research I can to find out everything I can about the game so that I am the best. If I put in the effort to find out the shortest routes, the quickest characters, the best items and so on and use this knowledge to beat all others then why am I a cheat just because I didn't work it out myself?

To take it back to your game consider Portal, a level based puzzle game. If I want to be the fastest at it then it is just common sense to see what the current fastest player is doing and try an improve on it. I wouldn't say this is cheating.

You see further standing on the shoulders of giants after all.

# Answer
> 1 votes
One way to reduce the effect of the solution's availability on the score is to count time spent on each level and use it when calculating the score.

Examples:

* remove `X` points every second
* add bonuses: create time intervals, e.g. if the player finish the level between 0 and 1 minute, (s)he win `Y` points, and less points between 1 and 2 minutes, etc.

With these method, a player with the solution will be able to get an high score only if (s)he's quick, so the score is not based on the solution only, skills and quickness of action are needed too.

# Answer
> 0 votes
A potential solution to this would be to anonymize the levels and swap out the order, so they can't say "Level 10", or "The final encounter", they'd only be able to provide screenshots.

Of course with that solution, eventually the community would sort out their own nicknames for levels based on anything they could.

You could try doing something like a hint system, so that instead of getting frustrated they could get a hint from in-game at the right time, knowing that it won't be giving away too much and that they'd feel good for not cheating. You could even disable the hints for extra points.

# Answer
> 0 votes
My advice would be to randomly generate your levels, but take some sort of special measures so that each level is an appropriate difficulty.

For example, suppose you can create an algorithm for estimating how hard a particular random level will be for a human to solve.

Further, suppose that the player will play ten puzzles.

Whenever the game loads, generate ten puzzles, and then sort them using score from the hardness estimating algorithm, so that the player gets the easiest puzzle first, and so on.

Alternatively, there may be a way to control the puzzle difficulty when randomly generating it. For example, for mazes, some generators have a user selectable "branch factor" which controls how likely a corridor is to split.

# Answer
> 0 votes
This is a problem that don't realy have a solution. If people want to cheat it they will! It as simple as that.

Why people cheat level? There is a couple of reasons. First the level might be too hard for them or versu the previous one. It might just be something they can't concieve correctly how to solve, what ever.

There is a simple solution that can benefit you and your players, **just let them skip it**. Why cheat it when you can simply skip the too hard puzzle and come back at it later without blocking your progress in the game?

Why it benefit both of you? The player can obviously keep playing and you get a direct feedback about that particular puzzle. If X% of the player skip the level Y you can see that a majority of people find that puzzle too hard. If they just cheat it you would never know this. This let you adjust the difficulty of your game based on the feedback users give you while they benefit from their actions. Win-win!

# Answer
> -1 votes
You could make the puzzle appear random by tying it to the machine's MAC address or similar piece of data. That way, you can control the difficulty, but unless/until someone figures out both what the key is, and the algorithm, it will be impossible to go online to get the solution.

# Answer
> -1 votes
I felt compelled to write something. I do online riddles all time, have written them, and care very deeply for the development of intriguing riddles. I have to say that the accepted answers to this as mostly garbage. In my findings, numerous people cheat--it's just the human condition. People get stuck and it's a test of their own honor. At least 50% and probably close to 90% cheat at some point in the completion of riddles. There is a significant difference in asking for a hint and there exists sites of just riddle solutions.

Unfortunately I don't wish to be incredibly explicit here because part of beating cheaters is being sneaky about what it is you are doing to nab them. My general suggestion is--cheaters give up really easily and are lazy, change the answers (the methods of solving are usually elaborate--keep those the same). Also, charge a very small but some kind of fee/donation to play. The first x levels can be free, just at some point make sure your audience is the audience you want. (i.e. free of cheaters) Perhaps even tie this to a user account and log what they guess as answers so when they guess answers that make absolutely no sense (but match a list of answers from before) now you know who cheated. When people have skin in the game they feel less likely to cheat and cheaters want a free lunch--if it stops being free now they're not only feeling bad for not being able to solve it, they also have no interest in paying for something they get no value out of anyway. That's the best suggestion I can give that requires the least effort.

In short, adding some processes to capture cheaters and ridicule them is a good strategy.

I will never understand the need to cheat at a game, especially riddles because the entire thing is a journey--there is no time limit, everyone solves it differently, and the entire 'game' and fun is the process of moving logically (or illogically as the case may be) to the solution. I had a friend that would literally buy a new game and immediately cheat at everything...so a lot of what has been said as other answers here just don't fit the psyche I see and have to deal with when designing stuff like this.

# Answer
> -3 votes
You can make the puzzle search resistant by avoiding key words associated with the puzzle. You can practice disinformation by posting fake solutions to the puzzle in all the usual places so anyone looking for the solution finds a flawed solution and wastes their time till they give up without ever finding. Basically you create a haystack of fake solutions to bury the valid user posted solution so finding the real solution online is a harder puzzle than figuring out the game problem solution.

---
Tags: puzzle, anti-cheat
---


# Question
Title: Make gameObject “stick” to another gameObject after it has collided with it?
Currently, I am using the following code to make objects stick to other gameObjects.

```
rb = GetComponent<Rigidbody>();
rb.isKinematic = true;
gameObject.transform.SetParent (col.gameObject.transform);

```

It works perfectly, but it causes many other problems... For example, after colliding, it can no longer detect collisions... Is there an alternative to this code (which makes a gameObject stick to another one after collision)?

# Answer
Instead of parenting it to the other object you can do the following:

1. Give it a member variable of type GameObject, initialized to `null`.
2. When it collides with another object, assign the object it collided with to that variable.
3. On every frame, if the variable is not `null`, update the position relative to the other object's position.

This way you also avoid problems you might get when the other object already has child objects you do stuff with in your code.

**Edit:**

Code Example:

```
// The class where you make your collision check
public class YourClass : Monobehaviour {

    // add this to your class fields
    private GameObject collidedObject = null;

    void Update()
    {
        collidedObject = theOtherObject; // do collision check, replace with collided object
        if (collidedObject != null)
        {
            Vector3 offset = new Vector3(0, 0, 1); // replace with your desired offset vector
            transform.position = collidedObject.transform.position + offset;
        }

        // rest of your Update method
    }

    // rest of your class
}

```

Be advised that this is not tested code, but it should be enough to illustrate the solution.
> 1 votes

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


title: World, view, projection matrix?

text:
# Question
Title: World, view, projection matrix?
What does multiplying an object in local space with a WVP(world,view,projection) matrix do? My book says "local space to homogeneous clip space"

Luna, Frank D. (2012-05-21). Introduction to 3D Game Programming with DirectX 11 (Kindle Location 5444). Mercury Learning and Information. Kindle Edition.

# Answer
The world matrix translates the coordinates of your vertices from model space to world space. This transformation includes the position of the object in the world as well as its orientation and potentially scale.

The view matrix translates those vertices from world space to camera/view space. This means the transformed coordinates are in relation to the camera/point of view.

The projection matrix finally translates those coordinates from camera/view space to projection space. Projection space coordinates specify where the vertex is located on your display/monitor as well as containing depth information (i.e. How far away from the camera the point is). This coordinate space is the "homogeneous clip space", because all the x/y components of all visible points are in the range \[-1,1\]. Depth (z component) lies in \[0, 1\].

If you premultiply those matrices you get a world-view-projection matrix and can do all those steps in one single matrix multiplication. Note that it actually makes sense to premultiply view and projection Matrix, as those usually don't change in the timeframe of one frame. You'll save calculations this way if there are a lot of objects needing to be rendered. Also you only have to send 2 different matrices to you GPU instead of 3 (World Matrix is different for every object you'll render, but it could also make sense to include the world matrix in your premultiplication when meshes have a lot of vertices).

Look here for further reference.
> 9 votes

---
Tags: directx11
---


# Question
Title: Choosing random array indexes in Unity C#
I want to change a string by randomly choosing an index in an array, using the random.range command in unity. Bare in mind that I'm using strings here, not floats or integers. Here is a code **example**(not the real thing. I'm just coming up with this by example, but it still has the same meaning. I may make a few typo errors as a result):

```
public string ChangingString = ("");
public string[]ExampleArray = new string [2];

void Start () {
    ExampleArray[0] = ("String1");
    ExampleArray[1] = ("String2");
}
void OnGUI () {
    if(GUI.Button(new Rect(10,10,100,24), "Randomize text")){
        ChangingString = (code to choose random string using the ExampleArray);
    }
    GUI.Label(new Rect(10,30,100,20), ChangingString);
}

```

EXTRA NOTE: I'M NEW TO USING ARRAYS.

# Answer
```
string randomString = ExampleArray[Random.Range(0, ExampleArray.Length)];

```
> 1 votes

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


# Question
Title: Keeping an object constrained to a 2d radius based off of the camera
A few weeks back I posted a question about keeping an object on the screen. What I would like to do now is clamping an object around a 2d radius based on the camera.

I'm need this for a reticule for this on rail shooter I've been making. (like that of starfox)

Here is the current code I am using :

```
        Vector3 movementx = transform.TransformDirection(Vector3.right * Input.GetAxis("Mouse X") * aimSpeed);
        Vector3 newPosx = transform.position + movementx;
        Vector3 offsetx = newPosx - centerPt.position;
        transform.position = centerPt.position + Vector3.ClampMagnitude(offsetx, radius);
// the same for the y axis

```

The problem with this set up is that I'm restricting it around 3-dimensional objects base off their locations in the world. (this is restricting the players movement towards the edges not letting the player to move the reticule to the side)

So this is what I've tried:

```
   Vector3 screenPosition = Camera.main.WorldToScreenPoint(transform.position);
   Vector3 shipOnScreen = Camera.main.WorldToScreenPoint(Ship.position);

        Vector3 movementx = transform.TransformDirection(Vector3.right * Input.GetAxis("Mouse X") * aimSpeed);
        Vector3 newPosx = screenPosition + movementx;
        Vector3 offsetx = newPosx - shipOnScreen;
        transform.position = shipOnScreen + Vector3.ClampMagnitude(offsetx, radius);
// the same for the y axis

```

This just seems to send the empty (which the ship is pointing at) off some where else in the world I cant even tell if I'm moving it or if its just moving with the parent object. (I've tried different variations with this moving the screenPosition swapping it with the transforms position in world space to no avail)

My guess is that its not converting 2d space to 3d space when I try to clamp a 3d object within that radius.

I would like to keep my reticule at an empty point on the screen and not replace it with the cursor.

Edit:

Okay i have now thought up a new system that still needs some work. Having an empty object next to the reticule. With this I cut out the need for a 2d radius but I need this object object follow the ship on on the screen with taking in account the perception of the camera.

I have taken a measure of the height and width of the camera. Its not too exact but it should do.

So i guess I would like to know how the coordinate system on the camera is set up. like where is (0, 0)

update:

Okay I've found a way to do this but it took a quite a bit of math on my part and a bit of estimation on my behalf.

The way I've set it up is that I moving the pivot the same way I'm moving the ship only I'm multiplying it times the proportion of distance the ship can move side to side vs the distance the pivot can move side to side. I still have not built in an equation that will allow me to move the point farther back with more accuracy but this is a good temporary fix and if i really have to move it I'll i do the math again. but I would still like to have the equation of the rate of change. I'm not that brilliant at related rates. If you want to see my math I noted it down.

but if i can have an equation out of this it would work perfectly while changing

> ship distance (constant) (61.6209, 27.5131)
>
> first measure distance : 100
>
> point A distance (320.5, 143.1)
>
> 5.20115872075484 y-multiplier
>
> 5.200473802917458 x-multiplier
>
> so the multiplier at 100
>
> 5.2
>
> distance : 50
>
> point B distance (192.0436, 85.74551)
>
> 3.11633 y-multiplier
>
> 3.11633 x-multiplier
>
> so the multiplier at 100
>
> 3.11633
>
> Rate of change (5.2-3.1165)/(100-50) = ROC
>
> ROC = 0.04166934
>
> mt = 0.042
>
> y = No idea
>
> x = distances from ship
>
> =0.042

Oh in case your wondering how i got my measurements I measured the distance manually with points.

# Answer
> 1 votes
It sounds like you've done a lot of math in 3D space to try and support this feature, taking into account the position of the ship and the camera, etc. But unless I'm missing something, I think there's an easier way.

This should work whether you want the game to be in first-person or third-person view.

1. Add two empty Game Objects to your player object along the line of fire (in front of the ship), one farther away than the other.

2. Make two reticle objects that look however you like. Make them children of the main camera.
3. Place these reticles anywhere on the X and Y axes, but keep their positions on the Z axis right in front of the main camera, exactly at the near clipping plane.
4. On the main camera or the Game Controller, write a Reticles Manager script. This script should watch the two empty game objects you placed in front of the ship and use Camera.WorldToScreenPoint to obtain their screen positions relative to the main camera. Once it has those positions, the Reticles Manager should move your two reticles to those two X and Y positions (keep the Z fixed at the near clipping plane).

In short, what you're doing is moving around some reticles right in front of your camera to overlap invisible objects you put in the player's line of fire.

If you don't want to have the reticles sitting in front of your main camera at the near clipping plane, which is usually pretty close, you can consider these options:

* Put the reticles on their own layer. Make use of a second camera that renders only the reticles, while the main camera renders everything but.
* Have the reticles live in the UI system.

Good luck!

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


title: Game Loop and Animation states/frames

text:
# Question
Title: Game Loop and Animation states/frames
I just wanna be straighforward. I read a dozen of articles talking about game loop, components, modules, structures, time control, etc...

But, in the end I'm still somewhat confused of how animation actually takes place in the game flow...

Explicitly: Each time the render() assumes command It may render (say) a player sprite (in 2D game). The player "animations" would be expanded in a spritesheet (?) and player object may hold it's state and frame. Say "running" frame 'n'. So the render will render that sprite.

Is that it?

If so, how should I control the actual frame when using a time based game loop (for fps control)?

How do I sinc that with the update variables (x and y position) of the player itself. That will mean that the character will "slide" until next frame (in a walking sequence)...?

Comments, pseudo-codes and maybe a link to a more deep-in article concerning these issue is appreciated... ;)

Thx,

# Answer
Both approaches are viable:

You can make the animation state part of the game state and control it such that it updates in the defined manner. It then can influence also what can happen. In that case the render has to check the animation state and select a different sprite based on the outcome. How you sync that with any movement depends on how you want it synced. For instance OpenTTD has such animation states for several of its base graphics - the relative positions of the sprites towards their 'parents' are in those cases also part of the animation sequence, as such it's synced to lateral movements.

Alternatively you can decouple an animation from the game state and simply pick a new sprite and draw the next state ever draw call or every other (whatever you want). That makes sense for animations where exact control is not important (for instance smoke or water waves maybe). It frees you of some complexity in the game state and allows for easier implementation of parallel threading in a way that you can de-couple processing the game state and drawing the game.
> 1 votes

---
Tags: animation, game-loop
---