title: Turn Radii and speed calculations

text:
# Question
Title: Turn Radii and speed calculations
Ok guys I'm an aspiring game designer and I'm trying to develop a racing board game using real life as a basis for my mechanics. The problem im having is I'm not very mathematically inclined I found a formula on an urban planning website but I don't really understand it. Can anyone help me?

# Answer
The clearest way to make sense of any equation is to figure out the units. In this case, it's a bit ambiguous, but you know that velocity is m/h and that radius would be some kind of distance.

`v^2` is a good assumption in this case, but it is not immediately obvious why without knowing something about the units of the denominator. Just by looking at this, it looks kind of like the well-known equation `a = (v^2)/r` which gives the acceleration `a` of an object traveling at velocity `v` in a circle of radius `r`. If you solve that equation for `r`, you get `r = (v^2)/a`, so it's a good guess that the denominator is in units of acceleration (if this is a valid formula).

If we are right so far, you can check that the units work out because we'd have `v^2` in units of `(miles^2)/(hours^2)` and `a` in units of `miles/(hours^2)`, which would give units of `miles` when divided. This is a unit of distance, so that's good. Let's keep working with that assumption for now and figure out what E and F are, and what all those magic numbers in the denominator are.

The basic assumption that this equation makes is that the car is travelling along the curve in the arc of a perfect circle, so all the acceleration is directly inward (no acceleration along the trajectory of the car). This makes the forces (accelerations) at work very simple -- you have the inward acceleration of the car and all other forces must cancel. So what force would cause the car to turn in a circle? The answer is friction!

When you turn a car's wheels, you are directing the force of friction to propel the car in a direction that is not straight ahead. If you are turning in a perfect circle, then any component of this friction force that is parallel to the motion of the car is canceled by some drag force(s) that are anti-parallel to the motion of the car, but there is no appreciable outward force to cancel the inward component of the friction force, and you get circular motion. The important thing to note here is that your formula has a "friction factor" -- which is actually just your friction force (you can look up the *kinetic* friction of tires on the road, but it's usually anywhere from 0.4 to 0.7 for wet to dry roads). In the end, you just need to note that the formula in question is using friction as the acceleration.

That's all good, but what about E and all those other random numbers? E is a factor that gives a ratio for banking of the curve. The more a curve is banked, the tighter the turn can be. Why is this? Because banking the road gives some component of the normal force (the force that is always perpendicular to the surface an object is resting on) towards the inside. In our flat situation, the normal force is perfectly canceled by gravity pulling down on the car. In the banked situation, gravity will only cancel the part of the normal force that is pointing straight up, and so the rest turns into part of our acceleration number.

Okay, that explains all the variables, but what about those numbers? Those numbers are why the units were ambiguous and we had to make assumptions earlier -- those numbers provide the units for us. I took the liberty and found the source for your image (corner radii) where they have helpfully labeled the units for us! `R` is given in feet, and `V` (as you noted) is miles per hour. `E` and `F` are unitless, as we expected. Since the denominator has to be one set of units, we can assume that all of the units are contained in the `15`, and the extra `0.01` multiplying `E` is simply a scaling factor. That means that `15` has units of (get ready for this) `squared miles per squared hour per foot`, or more clearly, `(miles^2)/((hours^2)*feet)`. How do I know this? Because the numerator (`(miles^2)/(hours^2)`) must cancel with the denominator to produce the left side, or `feet`.

So does `15` make sense? Well the force of friction is determined directly by the force of gravity, which in `feet/s` is about `32.2`. We also know that to convert `miles/hour` to `feet/s` we have a factor of `1.47`, so to convert the square values, we must square that, so we have `2.16`. `32.2/2.16 = 14.9`, so what that `15` means is actually just the acceleration due to gravity, so it does make sense!

The extra `0.01` just scales `E` because `E` is actually given as a percent (source), and must be multiplied by `0.01` to get a real ratio. It is important to note that both `E` and `F` come from the normal force acting on the car. `E` represents the direct normal force pointing inward (because the road is banked) and `F` represents the normal force converted to friction by the tires (and is just the ratio of kinetic friction between the tires and the road).
> 1 votes

# Answer
*Edit: Someone pointed out that R is in feet. Makes sense as well, and the rest stands. When in feet, the formula probably describes a **tightest** recommended curvature instead of a **comfortable** curvature. If solving from the formula the speed for this scandinavian location, it would be 30 mph or 48 km/h. The speed limit there is 40 km/h, so 48 is uncomfortable.*

---

Looks valid enough. An approximation, to provide a practical formula for solving the radius of a circle or arc - a segment of a road, and it's curvature.

If you look at this picture from a random american location you can see two measurements, both being ca 100 meters, and both being the radius of the road arc. When looking with Google, this curvature in fact seems quite common.

According to your formula (where it must be V^2, not V\*2)

radius = (V^2) / (15 * (0.01 * E + F))

and assuming

* the speed limit at that road part is 40 mph
* the friction between the tyres and surface is almost 1 (we say 1 - you must check it)
* we can ignore E

we get (40^2) / (15 * 1) which gives us 107.

Hence the conclusion would that the answer is in meters, and pretty close to the measured ca 100 meters radius (the google distance box says 196.55 m, which is the sum of both line segments, hence each of them is ca 100 meters).

You'd have to pick a number of similar cases, and see how well the formula fits reality (and ofc also check that it really is meters it outputs).

* Higher speed: Bigger radius
* Higher friction: Smaller radius
* Lower friction (eg. gravel): Bigger radius

Makes sense.
> 0 votes

---
Tags: physics, mathematics, game-design
---


title: How to efficiently move in Unity2D?

text:
# Question
Title: How to efficiently move in Unity2D?
If i want to use Physics in Unity2D what should be the most efficient way to move the object without interfering physics?

```
 1. Transform.position
 2. Rigidbody.Velocity
 3. Rigidbody.addForce
 4. Transform.translate
 5. Rigidbody.movePosition

```

Seems like there are a lot of ways and each way has a special purpose for when it should be used and when not. I just don't know that.

# Answer
Modifying the velocity will interfere with your physics if you're not sure of what you're doing. Ideally, you'd move things around by adding forces. Using `Rigidbody2D.AddForce` is the least complicated way to move objects that have a RigidBody.
> 1 votes

---
Tags: 2d, unity
---


# Question
Title: How do I change the mesh in an existing prefab in Unity?
So I made a prefab some time ago and now I want to change the mesh without changing any scripts. I have an OBJ file I want to use. Is there any way to do this? I've read the documentation but I don't seem to understand how to do it.

# Answer
> 9 votes
1. Import the mesh into Unity
2. Select the prefab you want to modify in the Project Window
3. In the Inspector, select your new mesh from the Mesh Filter component

This will update the prefab and any instances you have in any scenes.

# Answer
> 4 votes
The version by Byte56 works if the mesh is on the prefab or one of its first level child-objects. When it's deeper in the object hierarchy of the prefab, you can't expand it in the project tree. In that case:

1. Drag prefab into scene
2. Change the mesh in the MeshFilter component of the sub-object
3. Click on the main object of the prefab
4. Click "Apply" in the inspector
5. Delete prefab from scene

---
Tags: unity
---


# Question
Title: how get collision callback of two specific objects using bullet physics?
I have got problem implementing collision callback into my project. I would like to have detection between two specific objects. I have got normall collision but I want one object to stop or change color or whatever when colides with another. I wrote code from bullet wiki:

```
int numManifolds = dynamicsWorld->getDispatcher()->getNumManifolds();
    for (int i=0;i<numManifolds;i++)
    {
        btPersistentManifold* contactManifold =  dynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i);
        btCollisionObject* obA = static_cast<btCollisionObject*>(contactManifold->getBody0());
        btCollisionObject* obB = static_cast<btCollisionObject*>(contactManifold->getBody1());

        int numContacts = contactManifold->getNumContacts();
        for (int j=0;j<numContacts;j++)
        {
            btManifoldPoint& pt = contactManifold->getContactPoint(j);
            if (pt.getDistance()<0.f)
            {
                const btVector3& ptA = pt.getPositionWorldOnA();
                const btVector3& ptB = pt.getPositionWorldOnB();
                const btVector3& normalOnB = pt.m_normalWorldOnB;
                bool x = (ContactProcessedCallback)(pt,fallRigidBody,earthRigidBody);
                if(x)
                    printf("collision\n");
            }
        }
    }

```

where fallRigidBody is a dynamic body - a sphere and earthRigiBody is static body - StaticPlaneShape and sphere isn't touching earthRigidBody all the time. I have got also other objects that are colliding with sphere and it works fine. But the program detects collision all the time. It doesn't matter if the objects are or aren't colliding.

I have also added after declarations of rigid body:

```
    earthRigidBody->setCollisionFlags(earthRigidBody->getCollisionFlags() | btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);
fallRigidBody->setCollisionFlags(fallRigidBody->getCollisionFlags() | btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);

```

So can someone tell me what I am doing wrong? Maybe it is something simple?

# Answer
> 4 votes
I'm familiar with JBullet but as its the java port of the original the concept should be the same.

It seemed to me that there's always a collision with your static plane and other objects. But you need to do something only on collision of specific objects. What you need to use is the **user pointer** of the collision shape. Here's a piece of code from my own engine in java. Here GameEntity is the class I wrap my objects and CollisionListener is another class of mine which I use to implement what collision does. I also pass positions and collision normal to the listener to achive more fancy effects.

> ```
>             if (pt.getDistance() < 0.f) {
>                 Vector3f ptA = pt.getPositionWorldOnA(new Vector3f());
>                 Vector3f ptB = pt.getPositionWorldOnB(new Vector3f());
>                 Vector3f normalOnB = pt.normalWorldOnB;
>                 GameEntity thisObject = (GameEntity) (obA.getUserPointer());
>                 GameEntity thatObject = (GameEntity) (obB.getUserPointer());
>                 if(thisObject == null){
>                     return;
>                 }
>                 if (thisObject.getCollisionListener() != null) {
>                     thisObject.getCollisionListener().collided(
>                             ptA, ptB, normalOnB, thatObject);
>                 }
>                 if (thatObject.getCollisionListener() != null) {
>                     thatObject.getCollisionListener().collided(
>                             ptB, ptA, normalOnB, thisObject);
>                 }
>             }
>
> ```

# Answer
> 0 votes
**Minimal runnable example**

Two spheres falling from different heights in function of time.

Since they start at different heights, they will hit the ground at different times.

We detect the ground hit, and print out which sphere touched the ground when.

Gnuplot visualization of stdout:

See how:

* when one sphere hits the ground, the pink square collision indicator goes to `1`
* when the other sphere hits the ground, the green `X` goes to `1`

Code:

```
#include <cstdio>
#include <cstdlib>
#include <map>
#include <vector>

#include <btBulletDynamicsCommon.h>

#define PRINTF_FLOAT "%7.3f"

constexpr float gravity = -10.0f;
constexpr float timeStep = 1.0f / 60.0f;
constexpr float groundRestitution = 0.9f;
constexpr float objectRestitution = 0.9f;
constexpr int maxNPoints = 500;
constexpr float initialXs[] = {  0.0f, 5.0f };
constexpr float initialYs[] = { 10.0f, 5.0f };
constexpr size_t nObjects = sizeof(initialYs) / sizeof(*initialYs);

std::map<const btCollisionObject*,std::vector<btManifoldPoint*>> objectsCollisions;
void myTickCallback(btDynamicsWorld *dynamicsWorld, btScalar timeStep) {
    objectsCollisions.clear();
    int numManifolds = dynamicsWorld->getDispatcher()->getNumManifolds();
    for (int i = 0; i < numManifolds; i++) {
        btPersistentManifold *contactManifold = dynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i);
        auto *objA = contactManifold->getBody0();
        auto *objB = contactManifold->getBody1();
        auto& collisionsA = objectsCollisions[objA];
        auto& collisionsB = objectsCollisions[objB];
        int numContacts = contactManifold->getNumContacts();
        for (int j = 0; j < numContacts; j++) {
            btManifoldPoint& pt = contactManifold->getContactPoint(j);
            collisionsA.push_back(&pt);
            collisionsB.push_back(&pt);
        }
    }
}

int main() {
    int i, j;

    btDefaultCollisionConfiguration *collisionConfiguration
            = new btDefaultCollisionConfiguration();
    btCollisionDispatcher *dispatcher = new btCollisionDispatcher(collisionConfiguration);
    btBroadphaseInterface *overlappingPairCache = new btDbvtBroadphase();
    btSequentialImpulseConstraintSolver* solver = new btSequentialImpulseConstraintSolver;
    btDiscreteDynamicsWorld *dynamicsWorld = new btDiscreteDynamicsWorld(
            dispatcher, overlappingPairCache, solver, collisionConfiguration);
    dynamicsWorld->setGravity(btVector3(0, gravity, 0));
    dynamicsWorld->setInternalTickCallback(myTickCallback);
    btAlignedObjectArray<btCollisionShape*> collisionShapes;

    // Ground.
    {
        btTransform groundTransform;
        groundTransform.setIdentity();
        groundTransform.setOrigin(btVector3(0, 0, 0));
        btCollisionShape* groundShape;
        groundShape = new btStaticPlaneShape(btVector3(0, 1, 0), -1);
        collisionShapes.push_back(groundShape);
        btDefaultMotionState* myMotionState = new btDefaultMotionState(groundTransform);
        btRigidBody::btRigidBodyConstructionInfo rbInfo(0, myMotionState, groundShape, btVector3(0, 0, 0));
        btRigidBody* body = new btRigidBody(rbInfo);
        body->setRestitution(groundRestitution);
        dynamicsWorld->addRigidBody(body);
    }

    // Objects.
    for (size_t i = 0; i < nObjects; ++i) {
        btCollisionShape *colShape;
        colShape = new btSphereShape(btScalar(1.0));
        collisionShapes.push_back(colShape);
        btTransform startTransform;
        startTransform.setIdentity();
        startTransform.setOrigin(btVector3(initialXs[i], initialYs[i], 0));
        btVector3 localInertia(0, 0, 0);
        btScalar mass(1.0f);
        colShape->calculateLocalInertia(mass, localInertia);
        btDefaultMotionState *myMotionState = new btDefaultMotionState(startTransform);
        btRigidBody *body = new btRigidBody(btRigidBody::btRigidBodyConstructionInfo(
                mass, myMotionState, colShape, localInertia));
        body->setRestitution(objectRestitution);
        dynamicsWorld->addRigidBody(body);
    }

    // Main loop.
    std::printf("step body x y z collision2 collision1\n");
    for (i = 0; i < maxNPoints; ++i) {
        dynamicsWorld->stepSimulation(timeStep);
        for (j = dynamicsWorld->getNumCollisionObjects() - 1; j >= 0; --j) {
            btCollisionObject *obj = dynamicsWorld->getCollisionObjectArray()[j];
            btRigidBody *body = btRigidBody::upcast(obj);
            btTransform trans;
            if (body && body->getMotionState()) {
                body->getMotionState()->getWorldTransform(trans);
            } else {
                trans = obj->getWorldTransform();
            }
            btVector3 origin = trans.getOrigin();
            std::printf("%d %d " PRINTF_FLOAT " " PRINTF_FLOAT " " PRINTF_FLOAT " ",
                    i, j, origin.getX(), origin.getY(), origin.getZ());
            auto& manifoldPoints = objectsCollisions[body];
            if (manifoldPoints.empty()) {
                std::printf("0");
            } else {
                std::printf("1");
            }
            puts("");
        }
    }

    // Cleanup.
    for (i = dynamicsWorld->getNumCollisionObjects() - 1; i >= 0; --i) {
        btCollisionObject* obj = dynamicsWorld->getCollisionObjectArray()[i];
        btRigidBody* body = btRigidBody::upcast(obj);
        if (body && body->getMotionState()) {
            delete body->getMotionState();
        }
        dynamicsWorld->removeCollisionObject(obj);
        delete obj;
    }
    for (i = 0; i < collisionShapes.size(); ++i) {
        delete collisionShapes[i];
    }
    delete dynamicsWorld;
    delete solver;
    delete overlappingPairCache;
    delete dispatcher;
    delete collisionConfiguration;
    collisionShapes.clear();
}

```

Tested on Bullet 2.83, Ubuntu 15.10.

GitHub upstream: https://github.com/cirosantilli/cpp-cheat/blob/d7b70153b8f86b5864c22fbc6f7005049a93491f/bullet/which\_collision.cpp

---
Tags: collision-detection, bullet-physics
---


# Question
Title: Why I'm not getting any kind of output in SDL?
Here's the code that supposed to display the texture:

```
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, mainRaster.getOutput,null,null);
SDL_RenderPresent(renderer);

```

The code that runs the update process:

```
if(doubleBufferRegisters[0] == 0){
                doubleBufferRegisters[0] = 1;
                doubleBufferRegisters[1] = 0;
            }else{
                doubleBufferRegisters[0] = 0;
                doubleBufferRegisters[1] = 1;
            }
    SDL_LockTexture(frameBuffer[doubleBufferRegisters[0]], null, &fbData[doubleBufferRegisters[0]], &fbPitch[doubleBufferRegisters[0]]);
             1);

            for(int i ; i < layerList.length ; i++){
                layerList[i].updateRaster(fbData[doubleBufferRegisters[0]], fbPitch[doubleBufferRegisters[0]], palette);
            }
            SDL_UnlockTexture(frameBuffer[doubleBufferRegisters[0]]);
            r = false;

```

My engine uses CPU based rendering for the most part. I had to remove some of the overhead, as the engine first had to create an SDL\_Surface from the proprietary bitmap format, then an SDL\_Texture, now the palette conversion is done on the fly, enabling the use of transparencies and non-paletted graphics. However, an old problem came back after this, namely I'm getting a black screen. Even back then it was almost impossible to fix and still don't know what I did to make it work (other that trial and error with small modifications). Bypassing the "double buffering" doesn't change anything.

I'm writing my engine in D, however any help for C++ also would be helpful.

# Answer
> 0 votes
Well, it seems I had some problem with the alpha-blending algorithm I wrote in the in-line assembler, that uses MMX. While I could test that the code actually works and wrote actual data to the framebuffer, the image didn't show on the window.

Here's the assembly part to the alpha-blending:

```
asm{
            //mov       edi,dest;
            //mov       ebx,src;
            //mov       ecx,len;
            mov     EDX, alpha;

            //movzx   EAX,DL;
            movq    MM7,alphaMMXmul_const1;

            shl     EAX,16;
            add     EAX,EDX;
            mov     [alphaMMXmul_0],EAX;
            mov     [alphaMMXmul_0 + 4],EAX ;
            movq    MM6,alphaMMXmul_0; //mm6(X) = alpha (4 words)
            pxor    MM5,MM5;
            psubusw MM7,MM6; //mm7(Y) = 256 – alpha (4 words)

            //ALIGN 16
            //  MixAlphaMMX32_MainLoop:

            //movd      MM0,[EDI]; //mm0(A) = 0 0 0 0 | 0 Ra Ga Ba
            movd        MM0,dest;
            //movd      mm1,[ebx]; //mm1(B) = 0 0 0 0 | 0 Rb Gb Bb
            movd        MM1,src;

            punpcklbw   MM0,MM5; //mm0 = 0 0 0 Ra | 0 Ga 0 Ba
            punpcklbw   MM1,MM5; //mm1 = 0 0 0 Rb | 0 Gb 0 Bb
            pmullw      MM0,MM6; //mm0 = 0 Ra*X | Ga*X Ba*X
            pmullw      MM1,MM7; //mm1 = 0 Rb*Y | Gb*Y Bb*Y
            paddusw     MM0,MM1; //mm0 = 0 Ra*X+Rb*y | Ga*X+Gb*y Ba*X+Bb*Y
            psrlw       MM0,8; //mm0 = 0 0 0 Rc | 0 Gc 0 Bc
            packuswb    MM0,MM0; //mm0 = 0 0 0 0 | 0 Rc Gc Bc
            //movd      [edi],mm0;
            movd        dest,MM0;

            //dec       ecx ;

            emms        ;
        }

```

Going to use some non-scalar method until I come up with something better. The assembly code had built-in type conversion, most samples I could find on the internet even used floating point operations. Then I can focus on fixing the framerate issues either by reducing the redraw calls (by using a different framebuffer for all layers), or finding a faster way to update the framebuffer.

---
Tags: sdl
---


# Question
Title: Managing data for large number of levels in Unity?
I am making a Unity game vaguely in the vein of Candy Crush Saga for a client and am moving in circles trying to decide how to manage the data for all of their levels.

In brief, they want to divide the game into multiple regions that each have 100 levels. For example, you might go to the world map, select Teddy Bear Islands, and then go to the winding-path style level select screen similar to King's "Saga" games. My goal is to have the levels be procedurally generated, so the data for each level will consist of dozen or so parameters instead of hundreds of variables. There will only be one scene, and the levels will be built by running the parameters through an algorithm.

The game isn't a match-3, but for comparison, imagine if your level data for a match-3 was just basic parameters like the number of each type of piece and the target score, and each time you started a level it would randomly arrange pieces based on the input parameters (instead of you manually declaring the position of each piece). The data for a level will look something like:

```
int targetScore
int levelType
float difficultyModifier
int numPieceA
int numPieceB
int numPieceC
int numPieceD

```

I haven't worked with such a large data set (in terms of the number of levels) in Unity before and am unsure how to structure it. In a less editor-driven engine, I would probably just store all of the levels in XML files. However, since this is a Unity project I feel like I should be making an editor-based solution that will be easier for the client to work with in the future.

With an XML-driven approach, I imagine that I would have an XML for each region containing all of the 100 levels in that region, and each location on the world map would be linked to one of the XML files. When the user selected a region, it would read the levels into an array, and link each of the 100 level buttons to an array index.

For a more editor-driven approach, I might create custom editor windows where the regions and levels can be defined, and then link the region and level buttons to the data from the editor window (I haven't done much with editor windows yet and am not entirely sure how to tackle this approach). Or I could create a serializable LevelData type and a simple MonoBehavior with a public array of LevelData so that the levels could be defined on GameObjects in the inspector.

Each solution has pros and cons, and I'm stuck on what to do. Is there a conventional approach for managing such a large number of levels in Unity? Should I try one of the above approaches, or is there a better solution?

# Answer
> 4 votes
(Sorry for poor formatting - I'm on my phone)

There are a lot of valid options. If I were tasked with this, I would probably do one of two things:

Save the level data in Google Sheets and use one of the google sheets assets available on the asset store to pull it into the game either at design time or run time.

Or:

Save the level data in ScriptableObjects, probably one per region. The simplest method would be to make each scriptableobject a list of LevelData objects and create a property drawer to improve handling and editing of the leveldata objects. To make things better from there you could:

Make the list a reorderable list (undocumented but if you search it's not hard to find)

Create custom level and region editor Windows

The second option is more "Unity" and the experience you get with editor scripting will make you more effective in future projects. The first option is probably quicker. Both are perfectly valid in my opinion.

# Answer
> 1 votes
Assuming you'd like your game's levels to be edited by either a non-technical game designer or QA team, I would actually recommend none of what you suggested for the actual level editing portion. Because the parameters of these levels are relatively simple, I recommend you make the editor a part of the compiled application, not part of the Unity editor.

In my experience, streamlining the editing tools in a way, where they don't require a recompile or the use of the Unity editor, makes designers, QA teams and non-technical clients very happy. They can then see what works and what doesn't with minimal effort. The same applies when balancing.

In terms of storing this data, I personally tend to use web services during the development / testing stage. These avoid juggling files around. The web service itself is just a dumb php script, which stores whatever is submitted to it into an on-server JSON file - in your case, it will listen for a unique level ID and a list of the various parameters that build a level. When it receives these, it stores them. Note, however, that this is only a solution to be used during development and testing, do not ever use something this simple in production code - it is very exploitable.

Here is a development/testing web service I use. This one only accepts a "data" POST parameter, which is pre-computed by the game, which saves the map. Because your levels use multiple parameters, it's possible that you might prefer to store each of these parameters individually, instead of just "data". In my case, not setting the POST parameters outputs the saved data - one per line, used elsewhere in game code to print saved maps.

```
<?php
//maps.php
$data = json_decode(file_get_contents("maps.json"), true);
if(isset($_POST["levelID"]) && isset($_POST["data"]) && isset($_POST["name"]) && isset($_POST["data"])){
    $data[$_POST["levelID"]] = Array("name" => $_POST["name"], "datetime" => date("Y-m-d H:i:s"), "ip" => $_SERVER['REMOTE_ADDR'], "data" => $_POST["data"]);
    file_put_contents("maps.json", json_encode($data));
}else{
    foreach($data as $i => $d){
        print $d["data"]."\n";
    }
}
?>

```

On the Unity side, saving looks like this:

```
int LevelID; //Unique identifier of edited map (for development purposes, this can just be sufficiently large random number)
string name = ""; //Name of developer using map (can be hardcoded into shared copy), meant for accountability
string SaveString = ""; //The level-generating data you want to save. In your case, this will likely need to be reworked to multiple parameters.

string url = "http://...../maps.php";
WWWForm form = new WWWForm();
form.AddField("data", SaveString);
form.AddField("name", Settings.PlayerName);
form.AddField("levelID", LevelID.ToString());
WWW www = new WWW(url, form);

```

For the UI side of this, what I'd recommend is that you either use PlayerPrefs or a static class to transfer values between scenes. I'd create a simple "level editor" scene with the various parameters the tester/designer can manually adjust, with a "test" and "save" button. Clicking the "test" button will save the set parameters to PlayerPrefs or the static object and then load the level scene, which would generate a level from these parameters. If the designer is happy with a generated level, they can go back to the editor and hit "save". This is when the unity save script above is executed and the map saved to the server. You can, of course, add a "name" parameter to save, to make identifying levels easier down the line.

Once your maps are finished and your game is ready to ship, what I'd do is have an XML/Json file with the map data. It might be wise to create a script that takes this Json file and uses its data to generates a "hardcoded" C# script with the data, simply if you'd rather not have the end user being able to edit the file. Others have suggested alternative approaches, I'm simply listing what I'd use.

# Answer
> -1 votes
There is no conventional approach in designing a game really. You do whatever works for you. You can have full physics in your game, or you can fake it all.

Back to your question though, since the levels of a game like this are all random and also proceduraly generated, then just use one scene with a camera only. Switch from main menu to game type selection.

Then when you select a game type, you load the data for that level, sort of like a seed. You can have a single class for each game type and manage all the data in there. Then another class that handles power ups, bonuses etc.

---
Tags: unity, data-structure, levels
---


title: Player motion and combo systems

text:
# Question
Title: Player motion and combo systems
Where do you usually implement player motion when going through the state machine of a combo system?

An example, when player presses X+Y it must do an uppercut like movement (Like street fighter) where the player jumps and hits. Another example could be the Devil may cry series where you can press down+sword button and the enemy is thrown up and the player authomatically jumps to let player hit target in the air.

When creating a combo, you have 2 things to take care of. One is the media that will be played when the combo is done (sound, animation, etc...) and the other the movement of the player when doing this combo.

How do you handle the movement of the player? I have 2 posible options:

1) Include the player motion (translation, rotatio, etc...) in the animation

2) Delegate the player motion to the combo nodes while they are being linked.

First option could be the easiest but seems a bit restrictive. For example if you want to let the player do some other action while the current combo node media is playing (ej. jumping) could be tricky (Jump + hit).

Second option would need to have some many diffeernt nodes (We could use some kind of delegates here to minimize the node count(IOC)) to cover all the motion needs of every part of the combo.

What do you think. Am I thinking too much?

Cheers.

# Answer
It sounds like it greatly depends on your game and where you want to go with it, but here's my 2 cents:

I don't think you should include translation or rotation into the animations themselves. Rotation should probably be saved for orienting the character in the proper direction (in Street Fighter this is usually left or right). Baking in the animation height is problematic for several reasons. For example, if the character has a damaged-while-airborne animation, that probably needs to start playing at the correct height i.e. wherever they got damaged.

I think what you probably want to do is to use animation events during certain parts of the animation to give the script control over their physics. For example, during a somersault of an animation you might give them an upward force, or simply make them hover during a certain timeframe in the animation.
> 0 votes

---
Tags: unity, c#, animation, skeletal-animation, timing
---


title: Advice on Story Text-Based Game

text:
# Question
Title: Advice on Story Text-Based Game
I am currently in preparation on making a game. This game will be looks like Lifeline by 3 Minute Games, which is a story text-based game.

My game will have the same concept with it. Where there will be a scrollable history of conversation between player and characters in game. However, my game will has more than one conversation history. He will be able to interact with more than one character. Therefore, when the game start, it will show list of interactable characters in game, and player can choose who he will interact with when any available.

I am planning to make it with Unity. But I don't know is it possible to create some scrollable history of text, each with different content, like chat history, in Unity.

So I wanna ask your opinion, is it good to just continue with using Unity, or should I change the game engine I use? If I should change, what is the best game engine to cope with this kind of game?

Thank in advance :)

# Answer
> 2 votes
Unity can be used for your simple text based game using the UI features. It makes deploying to multiple platforms relatively easy. Although if you have no prior experience with Unity, you might want to consider something easier to use which would not overwhelm you with features.

---
Tags: unity, text-based
---


# Question
Title: Add singleton to an existing gameobject in Unity via script
I did notice that if I assign scripts that generate singleton classes (for my managers), to an empty game object, everything works fine.

Now I would like to start the scene with the empty game object, attach the main game manager singleton, and in the game manager singleton I would like to attach to it the other manager singleton classes.

Although I am not sure how you actually do so. Do you run addComponent to the main game manager, and they will be attached to the existing gameobject?

The gameobject that I use for the main gamemanager is set to not be destroyed on load; the doubt is if I should run addComponent on the scripts, or create a reference from the gamemanager script and instantiate it from there.

I did look for examples on the subject, but the only thing that I found is the reference to add a script to a game object; and I am not sure if that's actually what is supposed to be done.

# Answer
> 1 votes
A MonoBehaviour is always added to a GameObject with `AddComponent`. Unfortunately `AddComponent` will always instantiate a new object, which means that a MonoBehaviour can not be a singleton.

However, MonoBehaviours can *use* singletons. When you would like to add a singleton-component to multiple game objects, create a separate MonoBehaviour which is instantiated but then calls the singleton internally for all of its methods.

When your singleton looks like this:

```
public class MySingleton {
     private static MySingleton _instance;
     public MySingleton Instance {
        get {
             if (_instance == null) _instance = new MySingleton();
             return _instance;
        }
     }
     /* methods */
}

```

Your proxy can work like this:

```
public class MyBehaviour: MonoBehaviour {

      void Update() {
           mySingleton.Instance.Update();
      }
}

```

A simpler method to share data between instances of the same MonoBehaviour is to just declare those variables as `static`.

# Answer
> 0 votes
You can do it simply by using DontDestroyOnLoad

* Add your manager Game Object in splash screen.
* Attach all the scripts you want to it.
* In any one script call DontDestroyOnLoad in `Awake`.

`void Awake(){
 DontDestroyOnLoad(gameObject);
 }`

This game object will last through out the game.

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


# Question
Title: How to split a screen in half using LibGDX without scaling?
I am currently working on a racing game with libGDX and I need to split the screen in half for a two-players mode. (Player 1 in first half and Player 2 in second half).

I already have Camera1 that will follow Player 1's car, and Camera2 that will follow Player 2's car.

Basically, I want the first half to show Player 1's car and the second half to show Player 2's car.

I have been searching for a while online for a way to split screens with LibGDX and found how to split the screen in two with this code:

```
/*Left Half*/
Gdx.gl.glViewport( 0,0,Gdx.graphics.getWidth()/2,Gdx.graphics.getHeight() );

/*Right Half*/
Gdx.gl.glViewport(Gdx.graphics.getWidth()/2,0,Gdx.graphics.getWidth()/2,Gdx.graphics.getHeight() );

```

However, it squeezes the screen into the right half, which is not what I want.

Is there a way to split the screen without squeezing it?

# Answer
I would suggest having a look at this page and using a viewport to manage both cameras. Since you don't want scaling a ScreenViewport would be the way to go.

https://github.com/libgdx/libgdx/wiki/Viewports

```
// These would be the cameras you have set up which are following the players
Camera playerOneCamera;
Camera playerTwoCamera;

ScreenViewport playerOneViewport = new ScreenViewport(playerOneCamera);
ScreenViewport playerTwoViewport = new ScreenViewport(playerTwoCamera);

```

Each time the window is resized you would update both viewports with new dimensions and offsets. To split the screen vertically you would do the following:

```
public void resize(int width, int height){
    playerOneViewport.update(width / 2, height);
    playerTwoViewport.update(width / 2, height);
    playerTwoViewport.setScreenX(width / 2);
}

```

Then each draw call you perform two renderings, one using the first cameras projection and another using the second cameras projection.

```
public void render(){
    // Set batch to use first players camera
    batch.setProjectionMatrix(playerOneCamera.combined);
    batch.begin();
    // Render what is required
    batch.end();

    // Set batch to use second players camera
    batch.setProjectionMatrix(playerTwoCamera.combined);
    batch.begin();
    // Render what is required
    batch.end();
}

```
> 2 votes

---
Tags: libgdx, box2d, screen, viewport, racing
---


title: OnPointerClick not being called

text:
# Question
Title: OnPointerClick not being called
I implemented the IPointerClickHandler in a script that runs on multiple GameObjects in my scene. I'm definitely missing something since the implementation is not being called at all. The objects are not UI elements. Here is the implementation of the interface :

```
 public void OnPointerClick(PointerEventData eventData)
 {
      Debug.Log("clicked on " + eventData.selectedObject.name);
 }

```

Can I even use the EventSystem with normal GameObjects? If I can how do I do it.

What i tried: Adding a BoxCollider2D to the object, using the event trigger component on the object calling a public method.

Edit: I was missing a raycaster on the main camera.

# Answer
> 0 votes
Turns out i was simply missing a RayCaster component attached to my main camera. In my case I had to use the Physics 2D Raycaster.

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


# Question
Title: How to make text have a fixed position in world space and be overlayed in screen space at the same time?
I'm trying to make text have a fixed position in world space and be overlayed in screen space at the same time.

I have text in canvas with "Screen Space - Overlay" which covers my text located in canvas (world space).

What should I do?

# Answer
You're going to need a custom shader for your World Space UI objects that has it's Render Order to Overlay and has ZTest turned off. Also your World Space ui does not have to be a child of a screen overlay canvas( that's not how it works)

This is a copy of the Default UI shader with the necessary changes. Should do the trick. Just make a material with this shader, and apply it to everything you want drawn over the top of geometry in your WorldSpace UI.

```
Shader "UI/Default_OverlayNoZTest"
 {
     Properties
     {
         [PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {}
         _Color ("Tint", Color) = (1,1,1,1)

         _StencilComp ("Stencil Comparison", Float) = 8
         _Stencil ("Stencil ID", Float) = 0
         _StencilOp ("Stencil Operation", Float) = 0
         _StencilWriteMask ("Stencil Write Mask", Float) = 255
         _StencilReadMask ("Stencil Read Mask", Float) = 255

         _ColorMask ("Color Mask", Float) = 15
     }

     SubShader
     {
         Tags
         {
             "Queue"="Overlay"
             "IgnoreProjector"="True"
             "RenderType"="Transparent"
             "PreviewType"="Plane"
             "CanUseSpriteAtlas"="True"
         }

         Stencil
         {
             Ref [_Stencil]
             Comp [_StencilComp]
             Pass [_StencilOp]
             ReadMask [_StencilReadMask]
             WriteMask [_StencilWriteMask]
         }

         Cull Off
         Lighting Off
         ZWrite Off
         ZTest Off
         Blend SrcAlpha OneMinusSrcAlpha
         ColorMask [_ColorMask]

         Pass
         {
         CGPROGRAM
             #pragma vertex vert
             #pragma fragment frag
             #include "UnityCG.cginc"

             struct appdata_t
             {
                 float4 vertex   : POSITION;
                 float4 color    : COLOR;
                 float2 texcoord : TEXCOORD0;
             };

             struct v2f
             {
                 float4 vertex   : SV_POSITION;
                 fixed4 color    : COLOR;
                 half2 texcoord  : TEXCOORD0;
             };

             fixed4 _Color;

             v2f vert(appdata_t IN)
             {
                 v2f OUT;
                 OUT.vertex = mul(UNITY_MATRIX_MVP, IN.vertex);
                 OUT.texcoord = IN.texcoord;
 #ifdef UNITY_HALF_TEXEL_OFFSET
                 OUT.vertex.xy += (_ScreenParams.zw-1.0)*float2(-1,1);
 #endif
                 OUT.color = IN.color * _Color;
                 return OUT;
             }

             sampler2D _MainTex;

             fixed4 frag(v2f IN) : SV_Target
             {
                 half4 color = tex2D(_MainTex, IN.texcoord) * IN.color;
                 clip (color.a - 0.01);
                 return color;
             }
         ENDCG
         }
     }
 }

```

credit goes to http://answers.unity3d.com/questions/878667/world-space-canvas-on-top-of-everything.html

Edit: Ok so I managed to replicate what the OP wants using my shader and a screen-space camera canvas. Here is a screenshot:

The red square is a world canvas image that has a material with the shader. The button is a screenspace camera button with the same material. Both canvases are set to the UI layer. The world space canvas has its sorting order set to 1 and the camera canvas order in layer is 0. Now both the world space canvas and the camera one are over all other geometry and the world canvas is on top of everything.
> 1 votes

# Answer
A world-space canvas is rendered as a 3d plane-mesh in the game-world, which means it is overlapped by other 3d objects. But to solve this problem you don't need a custom shader. You can do it with multiple cameras with different culling masks.

When you have multiple cameras in your scene, each camera will be rendered separately. The culling mask decides what will be rendered by the camera. Then the output of all the cameras get drawn on top of each other in order of their "Depth" value.

* Click on "Layers -\> Edit Layers" and create a new user layer "Over".
* Assign that layer to the world-space canvas.
* Make sure everything else has the "Default" layer assigned to it.
* Create a second camera which is identical to the first. Make sure it also maintains the same position, rotation and other settings so both cameras always show the exact same view frustum.
* On the first camera (the "default"-camera) set:
    + Clear Flags: "Skybox" / "Solid color" (whatever you want to be the background)
    + Culling mask: "Default"
    + Depth: 0
* On the second camera (the "over" camera) set:
    + Clear Flags: "Depth Only"
    + Culling mask: "Over"
    + Depth: 1
> 0 votes

---
Tags: unity
---


# Question
Title: Checking if point is inside the mesh via raycasting - where to cast rays?
I need to voxelize triangle meshes which involves testing if a point is located inside or outside the given mesh. I have just implemented a basic algo based on raycasting and checking the number of ray-mesh intersections (by intersecting the ray with each triangle).

I select a position which lies outside the mesh: I add a small offset to the mesh's bounding box. Then I cast a ray from the point being tested to the position calculated above.

1) How to find the position which definitely lies inside or outside the mesh? What are good values for the 'offset' which is added to the mesh's bounds? (Currently, I'm using offset = vec3(1,1,1).)

2) The method is very slow. For example, voxelizing "cow.ply" (17412 vertices, 5804 triangles) on a 128^3 grid takes almost 5 minutes on a 3 GHz CPU! What is a good acceleration strategy? (I plan to add a uniform grid where each cell keeps indices to intersecting triangles.)

# Answer
> 2 votes
A lot of calculations can be simplified by turning this into a 2D problem, and you can do that by casting your ray along a single axis -- x, y, or z.

For a given V = { Vx, Vy, Vz }, if we cast our ray along the z axis, we're effectively just checking which triangles intersect the 2D point V2 = { Vx, Vy } (projected into 2D by removing the z component). From there, find the z value for the point of intersection of V with each triangle. Count the number of triangles whose z-point of intersection is greater than Vz (we're effectively doing a ray trace in the positive z direction). If it's even, V is outside the mesh; if it's odd, it's inside the mesh (assuming the mesh is closed).

This leads to the main optimization: **Rasterise the triangles into a 2D grid.**

That is, you'll want to pre-calculate which triangles intersect which 2D { x, y } points in your grid, and with what z value, because that way you're only calculating triangle intersections for 128^2 points instead of 128^3 points. This can be done by rasterising the triangles to a 2D 128^2 grid, but keeping a list of intersecting triangles or z points of intersection for each point in the grid. The 2D grid could be anything from a 2D array of arrays to something more space-efficient, but I think that's beyond the scope of this question.

---
Tags: voxels, raycasting, mesh
---


# Question
Title: Handling accelerate in different devices
I am adding tilt controls to my game. The sensor values I get are different in different android devices which results in random behavior.

Anyone knows how can I tackle this situation?

I tried normalizing acceleration but it is still the same.

# Answer
> 0 votes
I think Jons correct. I don't know what you mean about low pass filter.

One way is to deal in local range values for your game. Like a range of 0-1. 0 is no tilt, 1 is max tilt. Your game always expects 0-1. Then your calibration create values to convert the device values into your to your local range.

So for example, your redmi extent is 0.4.

1.0 / 0.4 == 2.5. You then multiply your redmi device values by 2.5 to get the 0 -\> 1 range.

for your Mi 1.0 / 0.9 == 1.11. You then multiply your Mi device values by 1.11 to get the 0 -\> 1 range.

# Answer
> 0 votes
I use this and it seems to work on different devices. The motion of putting the phone down gives me a value for the delta x of -0.5041921 on a samsung galaxy and a -0.5021868 on a Nexus 5.

```
using UnityEngine;
using UnityEngine.UI;
public class GyroController : MonoBehaviour {
 //   public Text x, y, z;
    public Dice dice;
    public GameManager gameManger;
    public float lowPassKernelWidhtInSeconds;
    private float acceleromerUpdateInterval;
    private float lowPAssFilterFactor;
    private Vector3 lowPassValue;

    private Vector3 phoneAcc, phoneDeltaAcc;
    // Use this for initialization
    void Start () {
        Input.gyro.enabled = true;
        acceleromerUpdateInterval = 1.0f / 60.0f;
        lowPAssFilterFactor = acceleromerUpdateInterval / lowPassKernelWidhtInSeconds;
        lowPassValue = Vector3.zero;
    }

    // Update is called once per frame
    void Update () {
       //x.text ="X: " + Input.gyro.userAcceleration.x;
       //y.text ="Y: " + Input.gyro.userAcceleration.y;
       //z.text ="Z: " + Input.gyro.userAcceleration.z;
    }
    void FixedUpdate()
    {
        phoneAcc = Input.acceleration;
        phoneDeltaAcc = phoneAcc - LowPassFilter(phoneAcc);

        if(Mathf.Abs(phoneDeltaAcc.x)>=.5)
        {
            dice.RollDice();
            dice.StartSetPlayerRoll(gameManger.activePlayer);
        }

    }
    private Vector3 LowPassFilter( Vector3 newSample)
    {
        lowPassValue = Vector3.Lerp(lowPassValue, newSample, lowPAssFilterFactor);
        return lowPassValue;
    }

}

```

---
Tags: unity, android, accelerometer
---


title: How to "mark" a track/ road?

text:
# Question
Title: How to "mark" a track/ road?
I'm developing a simple racing game, using Unity. I've created a road simply applying a texture (asphalt) to a terrain . Is it possible (and how to do) to mark that roard with an invisible marker to identifiy that as a road (so i can make appears bonus, or others similar things) ? Which is the approach used in a racing game to accomplish that task ? Please, don't tell me "buy a Roads assets" because i want to understand the basics, the main concept.

Thanks

# Answer
> 0 votes
Usually when you want to have "Zones" in unity, you use game objects with Colliders with `isTrigger` activated.

There are two strategies you can use here. Either you surround the track with colliders to detect when the vehicle leaves the road (`OnTriggerEnter`) or you place colliders on the road and detect if the vehicle is still on the road (`OnTriggerStay`).

When you use the latter method, keep in mind that when you create your road from multiple colliders then it is possible that a vehicle triggers multiple `OnTriggerStay` events in the same frame. To handle this problem I would recommend you to have the `OnTriggerStay` method of the road colliders set a flag on the vehicle which is then retrieved in the update-method of the car.

```
public class RoadMarker : MonoBehavior
{
      void OnTriggerStay(Collider other) {
          Vehicle vehicle = other.GetComponent<Vehicle>();
          if (vehicle != null) {
               vehicle.isOnRoad = true;
          }
      }
}

public class Vehicle : MonoBehavior
{
      public bool isOnRoad;

      void Update() {
          if (isOnRoad) {
              // do what you want to do when vehicle is on the road
          } else {
              // do what you want to do when vehicle is not on the road
          }
          isOnRoad = false; // to be changed by RoadMarker... or not
      }
}

```

Regarding placing object on the road: You could make each RoadMarker responsible for handling object spawns within its collider.

---
Tags: unity, racing
---


title: 2D infinite grid data structure

text:
# Question
Title: 2D infinite grid data structure
I'm currently developing a game, and I'm in a process of experimenting with various data structures to support my game model and simulation.

Here are some of the requirements:

* Grid structure where every node will have exactly 4 neighbors, if revealed.
* Infinite structure(max\_int), with ability to dynamically add nodes
* Ability to find all neighbors of a specific node
* Ability to find all outer empty spots around existing nodes ( basically outline around graph)
* Pathfinding

This is an example of how it should look. Red node will be starting point. Depending on a player's direction of movement, other nodes will be revealed and inserted into a graph. Also there is no restriction to movement between nodes as long as they are neighbors.

Current structure looks like this:

* Node - containing \[x,y\] position in grid and data pointer, custom hash function for only \[x,y\]
* Grid - set containing all nodes.

Now, in my testing, with the structure above, the bottleneck for 250x250 grid is finding neighbors, which takes a lot of time. BFS and DFS traversing is also slow due to the process of finding neighbors.

What are your suggestions for this kind of data structure ?

**Edit 1:**

Here are some of the ideas i was thinking about. Btw already using hash\_set(unordered\_set) for storing nodes. Maybe i should switch to unordered\_map, that way i could directly search by providing only \[x,y\]

Node could keep pointers to all neighbors like a cache, when adding new nodes, i could update old nodes with new neighbors, this way node will have direct access to neighbors.

As suggested, by using small chunks, i could possibly waste memory, because in worst case scenario only one node could be explored in a single chunk.

I was definitely thinking about quad-tree, this way i could use it in two different aspects(model searching/updating and rendering).

# Answer
> 1 votes
You could use a hashtable with a key which consists of both the x-coordinate and y-coordinate. Finding the tile at a specific coordinate is then a constant-time operation.

When you want to cache the "outline", you could store it in another hashtable. Whenever a node is added, follow this algorithm:

* the new node is removed from the "outline" hashtable
* for each neighbor of the new node:
    + when the neighbor is not in the main hashtable (aka is filled) add it to the "outline" hasthtable.

When the constant-time lookup speed in the hashtable is still a bottleneck during route-finding, you could also have each node maintain references to its four neighbors. Whenever you add a new node, get the neighbors from the hashtable and set up the references from new node to neighbors and from neighbors to new node.

---
Tags: c++, algorithm, data-structure
---


title: Minecraft: Players Held Item Type

text:
# Question
Title: Minecraft: Players Held Item Type
How can I check if a players held item is of a specific item type - for example an axe. (can be iron axe, gold axe, wooden axe, etc.)?

Or do I have to do multiple if statements to have this done?

```
@EventHandler(priority= EventPriority.HIGH)
    public void onInteract(PlayerInteractEvent event){
        Player p = event.getPlayer();
        ItemStack heldItem = p.getInventory().getItemInMainHand();

        if(heldItem.getType() == Material.DIAMOND_AXE){ //I dont want to do multiple if statements for multiple type of Axes
            //...
        } //other if statement for Material.WOODEN_AXE etc.
    }

```

# Answer
> 1 votes
The cleanest method would be to check if `m.toString()` contains the `"_AXE"` string in it. Same with swords (`"_SWORD"`), and every tool.

# Answer
> 0 votes
I ended up using this

```
if (
            //Axe
                m == Material.DIAMOND_AXE
                        || m == Material.GOLD_AXE
                        || m == Material.IRON_AXE
                        || m == Material.STONE_AXE
                        || m == Material.WOOD_AXE

                        //Pickaxe
                        || m == Material.DIAMOND_PICKAXE
                        || m == Material.GOLD_PICKAXE
                        || m == Material.IRON_PICKAXE
                        || m == Material.STONE_PICKAXE
                        || m == Material.WOOD_PICKAXE

                        //Hoe
                        || m == Material.DIAMOND_HOE
                        || m == Material.GOLD_HOE
                        || m == Material.IRON_HOE
                        || m == Material.STONE_HOE
                        || m == Material.WOOD_HOE

                        //Spade
                        || m == Material.DIAMOND_SPADE
                        || m == Material.GOLD_SPADE
                        || m == Material.IRON_SPADE
                        || m == Material.STONE_SPADE
                        || m == Material.WOOD_SPADE

                        //Sword
                        || m == Material.DIAMOND_SWORD
                        || m == Material.GOLD_SWORD
                        || m == Material.IRON_SWORD
                        || m == Material.STONE_SWORD
                        || m == Material.WOOD_SWORD
                ) {

            //...
        }

```

But I guess theres cleaner code somewhere out there..

# Answer
> -1 votes
I think you can use this:

```
if(heldItem.getItem() instanceof ItemAxe){
//do something
}

```

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


# Question
Title: Obtain jump vector given time, distance and gravity
I tried for several days to solve my problem , but in the end I just gave up and I decided to ask , since the solution is beyond my knowledge

I'm writing a 2d top-down game, in order to simulate the heigth of an object i use a third axis (the image below make a better idea) , and i stucked while writing an AI for an enemy

This enemy, which is located over an A point, must jump over a B point, and the duration of the jump must be T seconds, my problem is how to find the velocity to apply in order to obtain the jump that i want

The image may be not clear but the 'height' axis is the z, while the x and the y are the standard axis of a cartesian diagram

This is the part of the code of the enemy where the jump start, then where forces are computed:

```
var p1 = new Point(this.xCenter(), this.yCenter());
var p2 = new Point(this.target.xCenter(), this.target.yCenter());
var direction = Math.atan2(p1.y - p2.y, p1.x - p2.x);

var time = 0.3;             //Jump time

var g = gravity;            //Gravity

var distance = distanceBeetweenTwoPoints(p1, p2);       //Distance

var xForce = (-(Math.cos(direction)) * ???;

var yForce = (-(Math.sin(direction)) * ???;

var zForce = ???;

this.xSpeed = xForce;
this.ySpeed = yForce;
this.zSpeed = zForce;

```

I obtain the direction in radians, if the enemy has simply to walk towards the point b this works

The following method is called in order to start the jump, then every frame the movement of the enemy is updated with this:

```
updateMove(delta){
  this.x += this.xSpeed * delta;
  this.y += this.ySpeed * delta;
  this.z += this.zSpeed * delta;
  if (this.z > 0) this.zSpeed -= gravity * delta; //Gravity has global scope
  if (this.z < 0) { //When floor is touched again
    this.z = 0;
    this.zSpeed = 0;
  }

```

I omit several parts of code, for example the part where i stop the forces where floor is again touched

So the main question are:

* how to get the z (height) force to apply at the jump in order to make it last T seconds?
* how to get the x and y forces needed to move to point b in T seconds?

This answer isn't my case since it describes in a different context of 2D, my jump should affect 3 axis

# Answer
You can try some some physic's projectile motion:

From the horizontal displacement the maximum distance of projectile:

```
d = v0 *  t * cos(theta)

```

where d is ab distance , v0 = start velocity, t= time , theta= trow angle (usualy Pi/4 for max trow distance)

so

```
v0 = d /(  t * cos(theta) )

```

then you can get the x y and z component of V0 using theta and the ab vector.
> 0 votes

---
Tags: physics, jumping
---


# Question
Title: Finer collision detection with multi-path Polygon2DCollider from Tiled2Unity
I'm in the process of incorporating Tiled2Unity prefabs into my code. Their exporter creates a collision object (shown below) that amalgamates the collider of each tile into a single Polygon Collider 2D made up of multiple "subcollider" paths, shown below as green polygons.

What I'm trying to do is to adapt my old corner detection code to work with the new collider, but when OnTriggerStay2D(Collider2D other) is triggered, I'm not provided with the specific path I've collided with. In the picture, each green polygon is a path, and together they make up the Collider2D (other) provided in the argument.

Is there any way to find out which path I've collided with, without looping through each of the 1000ish points every time I want to detect a nearby corner? So far I am only able to discover via events that I've collided somewhere in the ENTIRE collection of green polygonal paths.

Thanks!

# Answer
When you have a collision, do a CircleCast (or BoxCast, depending on the shape of the collider of the colliding object) from the center of the colliding object with a size equal to its own collider, a distance of 0 and a layerMask setting which only covers the polygon collider.

The resulting RaycastHit2d object will tell you the closest point of the polygon collider.

It doesn't tell you the edge you collided with, but it tells you its surface normal. Now that you know the orientation you can check one unit left and right of the collision point if these points are also inside the PolygonCollider (PolygonCollider.OverlapPoint). When they are not, you are at a corner.
> 0 votes

---
Tags: unity, c#, collision-detection
---


# Question
Title: What is the state of the art in procedural character animations?
I'm a programmer and I'm interested in programmatic character animation — walking or running, bipedal or many-legged: what is the state of the art today?

I heard about NaturalMotion's Euphoria system and Ubisoft's IK Rig, and they look amazing. Where can I find more info about similar algorithms?

# Answer
IK Rig looks very cool, and from what I can find, it's all in the name. It's about using Inverse Kinematics, prescribing the bare minimum number of elements for describing an animation -- feet, pelvis, wrists, shoulders, neck-base and head. Everything in between is constrained according to artistic factors and calculated in-engine, or baked to a new, more fully-defined animation.

Based on slides downloaded from the description of one of their videos (see description, but be warned: 1.2 GB and not much information):

> **IK Rig Definition**
>
> ● Active bones – full body IK
>
> ● Twist bones, small bones, secondary bones, collider, pivot, prop nodes – added and constrained directly in engine

This is accompanied by a picture of their IK rig's active bones -- feet, pelvis, wrists, shoulders, neck-base and head.

Another of their videos contains a more informative set of slides in its description (0.8 GB). It describes 3 steps:

1. Convert Source -- Mocap or other animation is converted into "IK chain proxy format".
2. Adjust -- Behaviours are changed/constrained according to the desires of the artist applying these animations to the character.
3. Apply to target -- These are then animated at runtime or saved as a more traditional animation.

With all this info, if I were you, I'd learn about Inverse Kinematics -- I've never done it before, but I'd probably Google "Inverse Kinematics" for more information on that specifically.
> 2 votes

---
Tags: procedural-generation, skeletal-animation
---


title: libgdx sprite placement

text:
# Question
Title: libgdx sprite placement
Im making a soccer game where you basically have to shoot the ball to the goal and the ball goes to where you touch the screen. Im having an issue with the ball though, when the ball spawns on the player it goes directly to the top left corner of the screen, without even touching the screen. This might be really easy but I cant seem to find the solution

Here's the code:

**Ball class**

```
public void shootToward(float targetX, float targetY) {

    velocity.set(targetX - position.x, targetY - position.y);
}

public void update(float deltaTime) {

    position.add(velocity.x * deltaTime, velocity.y * deltaTime);
    velocity.scl(1 - (1f * deltaTime));
}

```

**Game class**

```
public void create () {

    cam = new OrthographicCamera();
    cam.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    batch = new SpriteBatch();
    batch.setProjectionMatrix(cam.combined);

    player = new Sprite(player1);
    player.setX(MathUtils.random(Gdx.graphics.getWidth()));
    player.setY(MathUtils.random(Gdx.graphics.getHeight() / 2));

    b.position.set(player.getX(), player.getY());

}

public void render () {
    Gdx.gl.glClearColor(255, 255, 255, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    b.update(Gdx.graphics.getDeltaTime());

    batch.begin();
    batch.draw(bg, 0, 0);
    batch.draw(goal1, Gdx.graphics.getWidth()/4-20, Gdx.graphics.getHeight() - 180, 420, 130);
    if (!Gdx.input.isTouched()) {
        batch.draw(bs, b.position.x, b.position.y);
        b.shootToward(Gdx.input.getX(), Gdx.graphics.getHeight() - Gdx.input.getY());
    }
    player.draw(batch);
    batch.end();
}

```

Thanks in advance.

# Answer
> 0 votes
My guess is that you have a stray `!` in your code. Remove the `!` in:

```
if (!Gdx.input.isTouched()) {

```

This is making it so `shootToward()` is being called when the player is not touching the screen.

---
Tags: android, libgdx, sprites
---


title: Line Collision In Pygame?

text:
# Question
Title: Line Collision In Pygame?
I am working on a game(a platformer) that is physics and momentum based. I want to make it so that the player(a single dot) can bounce off of the lines with correct physics, but to do that, I need to know which line it is touching. Knowing if it is touching a line or not is simple. I just have to check for a white dot where the player is. The problem is that I cannot find out which line the player is touching. I thought of making a ton of rects along each line and testing for the player, but that would cause too much lag. Does anyone have any ideas? :/

# Answer
> 0 votes
I figured it out. Since lines can be seen as equations, you can detect if the player(or whatever)'s rise is equal(or similar) to the rise of the line. To convert a line to a segment, just make pygame check to see if the player is colliding with a rect that's two corners are the start and end points of the line. Make sure the rect has a positive side though, or `.colliderect`.

Here is how I calculated it: First, I took checked if the player(or whatever) was in range of the line. (using the previously mentioned method) Then I calculated the rise of the line by dividing the Y length by the X length. I did the same thing for the player, but finding the length of a line from the line's starting point to the player. Next I subtracted the line rise from the player rise. Then I found the absolute of that. If the absolute value(the difference in the rises of the lines) was less than a specific number(based on the width of the line), it was considered a collision. I used `0.1` for a 1 pixel wide line.

It is recommended that you check for each pixel the player moves to see if it is colliding.

# Answer
> 0 votes
You could do it as you did above (get the distance to the line and if it's less than some number, they are colliding), or you could see if the player's position is a point on the line. If so, they are colliding. The downside of doing it this way is you have to do intra-frame collision checking (ie if the players speed is 2 pixels, you could miss an intersection with a line 1 pixel wide), IE project the player's path for the next frame as a line segment, and if that line segment intersect a line, the player will intersect with the line within the next frame, so go to that point in time and calculate the collision and how far the players moves afterwards but before the next frame.

As I understand your method the "less than" will cover the situation where a player goes past a line (since the distance will be negative), but that's assuming you cover distance with respect to the orientation of the line (eg lines at the top of the screen are "upside-down" and lines at the bottom are "right-side up;" therefore, being above the top line and below the bottom line will be a "negative distance."

Of course, this is all moot if the player will only ever move one pixel at a time. :)

---
Tags: python, pygame
---


# Question
Title: Shader only rendering 1/4th of the screen
I've asked the same question on SO here and they suggested I should ask here instead.

---

I'm currently trying to create a gaussian blur shader, and while I've successfully created the blur effect my shader only renders the lower right quarter of my screen like the image shows: And just to make it clear; it has NOT re-scaled the image, it just doesn't render the rest of it.

Here's my shader code with comments of my thoughts:

## Vertex (horizontal, vertical almost identical. See below)

```
#version 400

in vec2 a_texCoord0; //My tex coords

out vec2 blurTextureCoords[11]; //Sample 11px (i.e, 5 right 5 left of center)

uniform float u_width; //Width of the screen. Used to calculate pixel size

void main(void){
    gl_Position = vec4(a_texCoord0, 0.0, 1.0);
    vec2 centerTexCoords = a_texCoord0 * 0.5 + 0.5; //Maybe this is somehow wrong?
    float pixelSize = 1.0 / u_width; //This is kind of interesting, because my shader sometimes tells me that "no uniform value was found with name 'u_width', but it still seems to work as if I change the values manually (ex. set it to 1920) it still looks normal.

    for(int i=-5; i<=5; i++) {
        blurTextureCoords[i+5] = centerTexCoords + vec2(pixelSize * i, 0.0); //I also thought that it might be because I multiply a float with an integer, but if I do float(i) instead of just i it still looks the same.
    }

}

```

## Fragment

```
#version 400
#ifdef GL_ES
precision mediump float;
#endif

in vec2 blurTextureCoords[11];

out vec4 out_colour;

uniform sampler2D u_texture;

void main(void){
    //The actual bluring
    out_colour = vec4(0.0);
    out_colour += texture(u_texture, blurTextureCoords[0]) * 0.0093;
    out_colour += texture(u_texture, blurTextureCoords[1]) * 0.028002;
    out_colour += texture(u_texture, blurTextureCoords[2]) * 0.065984;
    out_colour += texture(u_texture, blurTextureCoords[3]) * 0.121703;
    out_colour += texture(u_texture, blurTextureCoords[4]) * 0.175713;
    out_colour += texture(u_texture, blurTextureCoords[5]) * 0.198596;
    out_colour += texture(u_texture, blurTextureCoords[6]) * 0.175713;
    out_colour += texture(u_texture, blurTextureCoords[7]) * 0.121703;
    out_colour += texture(u_texture, blurTextureCoords[8]) * 0.065984;
    out_colour += texture(u_texture, blurTextureCoords[9]) * 0.028002;
    out_colour += texture(u_texture, blurTextureCoords[10]) * 0.0093;
}

```

## Additional code

Creating a shader:

```
//I also have one for the vertical shader, it's almost exactly the same.
horizontalShader = new ShaderProgram(
    Gdx.files.internal("graphics/shaders/post-processing/blur/horizontalBlur.vert"),
    Gdx.files.internal("graphics/shaders/post-processing/blur/blur.frag"));
horizontalShader.pedantic = false;
horizontalShader.begin();
horizontalShader.setUniformf("u_width", Gdx.graphics.getWidth());
horizontalShader.end();

if (horizontalShader.getLog().length() != 0) {
    System.out.println("Horizontal shader! \n" + horizontalShader.getLog());
}

```

Rendering to FBO then to screen:

```
// Horozontal blur
horizontalFBO.begin();
spriteBatch.begin();
spriteBatch.setShader(horizontalShader);
background_image.draw(spriteBatch);
spriteBatch.end();
horizontalFBO.end();

// Vertical blur
verticalFBO.begin();
spriteBatch.begin();
spriteBatch.setShader(verticalShader);
spriteBatch.draw(horizontalFBO.getColorBufferTexture(), 0, 0);
spriteBatch.end();
verticalFBO.end();

// Normal FBO (screen)
spriteBatch.begin();
spriteBatch.setShader(null);
spriteBatch.draw(verticalFBO.getColorBufferTexture(), 0, 0);
spriteBatch.end();

```

## Additional info

I use two FBOs, but it seems that those are not the root of the problem, as the problem still persists if I just render directly to the screen using these shaders.

I have two vertex shaders, one for the horizontal and one for the vertical blur. The only difference is the uniform name `u_width` becomes `u_height` and the `blurTextureCoords[i+5] = centerTexCoords + vec2(pixelSize * i, 0.0);` becomes `blurTextureCoords[i+5] = centerTexCoords + vec2(0.0, pixelSize * i);`

# Answer
> 1 votes
The screen coords go from {-1,-1} to {1,1} but you are most likely feeding it {0,0} to {1,1} - hence the fact that only one-quarter of the screen gets rendered.

So just to be clear - point {0,0} is not the top-left (or bottom-left, depending on your co-ordinate system) point; it's the center.

This also explains the texture coord tranformation that you are querying:

> vec2 centerTexCoords = a\_texCoord0 * 0.5 + 0.5; //Maybe this is somehow wrong?

This transformation maps position coords of {-1,-1 ... 1,1} to texture coords of {0,0 ... 1,1}, and is therefore correct.

---
Tags: opengl, libgdx, shaders, glsl
---


# Question
Title: How can I get width and height of grouped objects in Unity3D
Is it possible to get height and width of grouped objects like this?

I tried boxcollider2d.bounds and renderer.bounds. Each shapes in the group has collider component.

Is it possible?

# Answer
> 1 votes
Grab all the `.bounds` properties of all the items, and figure out what the maximum and minimum values are.

# Answer
> 1 votes
To get the bounds of a group of objects, you need to get the bounds of each object in the group. For each axis, you compare the maximum and minimum bounds of each object. The maximum of the local maximums is the global maximum, the minimum of the local minimums is the global minimum.

i.e.

```
 Global_X_Max = Max(item1.bounds.max.x, item2.bounds.max.x,...)
 Global_X_Min = Min(item1.bounds.min.x, item2.bounds.min.x,...)

```

Create new bounds using the 3 min values and 3 max values.

One way of implementing this is to use `Bounds.Encapsulate`, as Chris mentioned.

1. Create a new bounds instance
2. For each object, add their minimum and maximum bounds to the new bounds with `Bounds.Encapsulate`.
3. The resulting bounds object will contain all objects and their bounds. Retrieve the minimum and maximum from the new bounds object.

Even with 100+ items, this comparison is not too intensive if you're only updating it occasionally.

---
Tags: unity
---


title: Sprite Animation Problem For Enemy

text:
# Question
Title: Sprite Animation Problem For Enemy
I have a problem regarding the attack animation for the enemy. The problem is that the attack animation sprite stops at the first index.It doesn't play the animation.It stops at the first index. Why? Any suggestions.

Here is the code(It's in the step event)

```
if(distance_to_object(player)<10){

    hspeed = 0;
    vspeed =0;
    enemy.x=enemy.x;
    enemy.y=enemy.y;

    if(sprite_index == enemy_left){
        sprite_index=enemy_left_attack1;
    }

    if(sprite_index == enemy_right){
        sprite_index=enemy_right_attack1;
    }

     if(sprite_index == enemy_up){
        sprite_index=enemy_up_attack1;
    }

     if(sprite_index == enemy_down){
        sprite_index=enemy_down_attack1;
    }
}

```

# Answer
Try setting `image_speed` after changing your sprite.

Like such:

```
if(sprite_index == enemy_up){
  sprite_index = enemy_up_attack1;
  image_speed = some_number_that_looks_good_to_you;
}

```

... or right before last bracket (`distance > 10` end bracket) to do it in one line instead of 4 lines...

hope it helps.
> 0 votes

---
Tags: game-maker
---


# Question
Title: Script no longer working now that it is attached to a child object. Why is this?
So I decided I wanted to make this script part of a separate swap-able weapon so I made a child and put the script there. Before the script worked fine but now it won't work. The script works as follows: if the left mouse button is pressed send a ray cast out forward, if it hits something matching the condition (a tag check, and distance check) parent it to the player, and if the right click button is pressed than un-parent it.

The code:

```
public class PhysGun : MonoBehaviour
{
    public GameObject Player;
    private bool isPlayerHolding;
    private GameObject RayCastHitObject;

    // Update is called once per frame
    void Update()
    {
        Vector3 fwd = transform.forward;

        Ray ray = new Ray(transform.position, transform.forward);
        RaycastHit hit;

        if (Input.GetMouseButton(0) && Physics.Raycast(ray, out hit, 10f) && hit.collider.gameObject.CompareTag("Pickable"))
        {
            Debug.Log("Press detected");
            isPlayerHolding = true;
            hit.transform.SetParent(Player.transform);
            Debug.Log("We hit: " + hit.transform.name);
            hit.rigidbody.constraints = RigidbodyConstraints.FreezeAll;
            MoveScrollWheel();
        }
        if (Input.GetMouseButton(1) && Physics.Raycast(ray, out hit, 10f))
        {
            hit.transform.parent = null;
            isPlayerHolding = false;
            hit.rigidbody.constraints = RigidbodyConstraints.None;
        }
        if (isPlayerHolding != false)
        {
            MoveScrollWheel();
        }
    }

        void MoveScrollWheel ()
        {
            if (Input.GetAxis("Mouse ScrollWheel") > 0f) // forward
            {
                Debug.Log("Mouse wheel up");
            }
            else if (Input.GetAxis("Mouse ScrollWheel") < 0f) // backwards
            {
                Debug.Log("Mouse wheel down");
            }
    }
}

```

What is wrong with my setup?

To clarify a few things...

* It's not working - By this mean it does not parent the object to the player like it should.
* Steps I've taken to resolve the issue (some are already above)...
* Remove tag check requirement - this causes a weird issue no matter where I am it always parents the terrain to the player and causes the player fall through it.
* Manually attach the player GameObject to the script.
* Detach the child (and make it a sibling) and put in front to see if it works that way (it doesn't).
* The raycast is **hits something** without the tag check (in this case the terrain as described above) but that is totally the wrong thing.
* No error messages appear in the console or anywhere.
* As per request here is a demonstration of the issue.

# Answer
> 0 votes
Well I finally figured out the issue with some help from here and Reddit. Basically I was trying to send the raycast from the model's (the child) forward and that was the wrong forward.

So I changed the third (2nd) line of code in the update statement to `Ray ray = new Ray(Player.transform.position, Player.transform.forward);`. This basically makes it so that the ray will originate from the players forward facing position rather than whatever the model's (child) forward is.

Long story short I used the Player's forward position and it worked brilliantly.

# Answer
> 2 votes
A Couple things to check:

1) Transform.forward may not be the direction you actually want to shoot the ray. For example if this is a first-person game, the direction the PhysGun is facing (transform.forward) may be totally different than where the *camera* is looking, and in that case you would probably want to shoot the ray from the camera.

2) Have you tried using RaycastAll to get more than just one hit? Perhaps you are raycasting in the correct direction, but the first result is undesirable.

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


# Question
Title: Failed to understand how to use glm::unProject (OpenGL 4.3)
Situation: I use OpenGL 4.3, FreeGLUT 3.0, and GLM library.

Let say i have a simple 2D object (a ball) and it moves accordingly to the simple equations:

x = x\_0 + v\_0 * t * cosf(alpha);

y = y\_0 + v\_0 * t * sinf(alpha) - 0.5 * g * t * t;

So i can be sure what are x and y in every time step.

My GLUT mouse callback is:

```
void onMouse(int button, int state, int mx, int my) {
    if (state != GLUT_DOWN)
        return;
    view = glm::lookAt(glm::vec3(0.0, 0.0, 10.0), glm::vec3(0.0, 0.0, 0.0), glm::vec3(0, 1, 0);
    projection = glm::perspective(45.0f, 1.0f*640 / 480, 0.1f, 10.0f);
    glm::vec4 viewport = glm::vec4(0, 0, 640, 480);
    glm::vec3 wincoord = glm::vec3(mx, 480 - my, 0.0f);
    glm::vec3 objcoord = glm::unProject(wincoord, view, projection, viewport);
}

```

So, when the ball moves and i click on it, i suppose to get (objcoord.x, objcoord.y) very close to the center of the ball (x,y).

Coordinates of the ball itself (x,y) are calculated correctly. But when i click on the ball, (objcoord.x, objcoord.y) are not even close to the (x,y). I always get very small values like (0.0012, 0.099) wherever i click on the screen. I feel that it might be due to some Z (depth) issues, but i don't have enough knowledge here and ask for help now.

# Answer
> -1 votes
try using something \>= your near (i.e. \>= 0.1) for your window\_z instead of 0?

```
glm::vec3 wincoord = glm::vec3(mx, 480 - my, /**/0.1f/**/);

```

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


title: VSync / real 30FPS on Android

text:
# Question
Title: VSync / real 30FPS on Android
I'm working on a game which can't run at Full speed on some devices. On Tegra2, with many optimizations, performance is near 40 fps. The framerate is stable but animations aren't smooth enough, so i need a vsync.
With 2.3 Android SDK, we can use EGL library natively. So i try to use eglSwapInterval but no success. In this GDC Paper, it seems that Tegra2 can do it.

Ps: Thread.sleep() to force a constant FPS is not an acceptable solution

# Answer
According to this thread on some opengl es benchmark, most devices' drivers simply ignore the eglSwapInterval, but tegra2 should have vsync enabled by default (and eglSwapInterval can be used to disable it).

Perhaps the vsync rate on your device is such that your stuttering comes from sometimes hitting, sometimes missing the frame time? Have you tried if *disabling* vsync will actually improve matters?
> 2 votes

# Answer
Published a sample doing 30FPS using choreographer API. https://github.com/googlesamples/android-ndk/tree/master/choreographer-30fps Does that work for you?
> 0 votes

---
Tags: android, vsync
---


title: Normals showing unexpected results

text:
# Question
Title: Normals showing unexpected results
I am making a game in c++ with opengl and glm and was working on my terrain when this happend :

as it appears it is renderering just the way i planned it, but my question was, how do i make it appear so that the their are not as many shadows? i have no idea of how i can fix this.

Here is the normal code:

```
        glm::vec3 calculateNormal(int x, int z) {
            float heightL = getHeight(x - 1, z);
            float heightR = getHeight(x + 1, z);
            float heightD = getHeight(x, z - 1);
            float heightU = getHeight(x, z + 1);
            glm::vec3 normal(heightL - heightR, 2.0f, heightD - heightU);
            glm::vec3 result = glm::normalize(normal);
            return result;
        }

```

and here is the terrain normal generation code

```
for (int i = 0; i < vertex_count; i++) {
                for (int j = 0; j < vertex_count; j++) {

                    float height = getHeight(j, i);

                    vert[vertexPointer * 3] = (float)j / ((float)vertex_count - 1) * size;
                    vert[vertexPointer * 3 + 1] = height;
                    vert[vertexPointer * 3 + 2] = (float)i / ((float)vertex_count - 1) * size;

                    glm::vec3 normal = calculateNormal(j, i);

                    norm[vertexPointer * 3] = normal.x;
                    norm[vertexPointer * 3 + 1] = normal.y;
                    norm[vertexPointer * 3 + 2] = normal.z;
                    ...

```

here is the terrain generation code

```
float getNoise(int x, int z) {
            int seed = x + z + (std::rand() % (0 - 15));
            return seed * 2.0f - 1.0f;
        }

        float generateheight(int x, int z) {
            return getIntoplatedNoise(x/16.0f, z/ 16.0f);
        }

        float getSmoothNoise(int x, int z) {
            float corners = (getNoise(x - 1, z - 1) + getNoise(x + 1, z - 1) + getNoise(x - 1, z + 1) + getNoise(x + 1, z + 1)) / 16.0f;
            float sides = (getNoise(x - 1, z) + getNoise(x + 1, z) + getNoise(x, z - 1) + getNoise(x, z + 1)) / 8.0f;
            float center = getNoise(x, z) / 4.0f;
            return corners + sides + center;

        }

        float getIntoplatedNoise(float x, float z) {
            int intX = (int)x;
            int intZ = (int)z;
            float fracX = x - intX;
            float fracZ = z - intZ;

            float v1 = getSmoothNoise(intX, intZ);
            float v2 = getSmoothNoise(intX + 1, intZ);
            float v3 = getSmoothNoise(intX, intZ + 1);
            float v4 = getSmoothNoise(intX + 1, intZ + 1);

            float i1 = interplate(v1, v2, fracX);
            float i2 = interplate(v3, v4, fracX);
            return interplate(i1, i2, fracZ);
        }

        float interplate(float a, float b, float blend) {
            double theta = blend * M_PI;
            float f = ((float) 1.0f - cos(theta)) * 0.5f;
            return a * (1.0f - f) + b * f;
        }

        float getHeight(int x, int z) {
            return generateheight(x, z);
        }

```

Thank you very much for you time

# Answer
It seems each time you call getHeight(x,z) you get different results, regardless of whether the (x,z) is the same or not, so the generated normals don't match the terrain surface.

Normals will match the actual terrain if you compute them from the generated terrain, and not from what getHeight returns. **However**, it makes sense to also fix getHeight so it always returns the same value for the same input point. As a tip, take a look at Perlin Noise.

https://en.wikipedia.org/wiki/Perlin\_noise
> 1 votes

---
Tags: opengl, c++, terrain, glfw, glew
---


# Question
Title: Does multiple downsampling have a benefit?
So i came across this site and you can see these lines on the first and second paragraph:

> For a crude but easy effect, draw the bright portions of the scene (eg, light sources) into an FBO, then **downsample it using GL\_LINEAR minification several times**. For the final render, simply combine the original scene with the downsampled FBO's.
>
> In the following example, the original scene is 128 x 128 and is **downsampled 3 times**. This requires *4 framebuffer objects*. The original scene is shown in the upper-left and the final rendering in the upper-right.

Is there any reason i should downsample multiple times (128 -\> 64 -\> 32 -\> 16) rather than downsample it once (128 -\> 16)?

If you scroll down more, they even downsample it like 9 times. (128 -\> ... -\> 16 -\> 128 -\> ... -\> 16 -\> and so on). Why not do it like (128 -\> 16 -\> 128 -\> 16 -\> and so on)?

# Answer
There are two main benefits:

First, if you downsample by more than a factor of two, some pixels in the original image will have no impact on the result image. Using `GL_LINEAR`, each destination pixel will only sample from at most 4 pixels from the source image; the other pixels simply get discarded. By downsampling by a factor of two, you ensure that each pixel from the source image has kept an equal effect on the next layer down.

Second, the algorithms discussed on that site require every one of the framebuffer objects; they're actually all required, even if there wasn't a good reason for downsampling in this way. You can't skip the 64x64 or the 32x32 images, because those images are used as part of constructing the gaussian-blurred result image.

Finally, if you read the article you'll see that it isn't advocating downsampling images 9 times; it downsamples just three times, and then does several operations on those downsampled images. The images you're looking at are just showing the state of those same 3 downsampled images after each step of the process, not showing separate downsampling events.
> 23 votes

---
Tags: opengl, graphics, bloom
---


# Question
Title: How to create a linear plateform between two points?
I have a set of 2D coordinates. Their positions are regular on the X axis, but unpredictable on the Y axis:

I would like to create slim platform between each point in order tu use it as ground for my game, expecting a result like this:

I'm working with Box2D, so I thought about create boxes like this:

```
float x1, y1, x2, y2; // Coordinates between two points
float centerX, centerY;
float differenceX, differenceY;
float width;
b2BodyDef bodyDef;
b2Body* body;
b2PolygonShape shape;

centerX = (x1 + x2) / 2.0;
centerY = (y1 + y2) / 2.0;
differenceX = x2 - x1;
differenceY = y2 - y1;
width = sqrtf(differenceX * differenceX + differenceY * differenceY);
height = 10.0f

bodyDef.position.Set(centerX, centerY);
bodyDef.angle = -M_PI / 4.0f * width / height
body = world.CreateBody(&bodyDef);
shape.SetAsBox(width, 10.0f);
body->CreateFixture(&box, 0.0f);

```

But the wrong part of this code seems to be on angle. I cannot find the correct rotation between two points from their coordinates.

Is there a correct math formula to find it?
Or am I simply wrong to use rectangular boxes to trace it, and should I use something else? Like a `b2PolygonShape`?

# Answer
> 1 votes
Do not use boxes for this kind of terrain. There are numerous problems that arise with using boxes, namely "catching" of objects on the intersections between the boxes.

Box2D provides Edge Shape (line) primitives as well as a Chain Shape that far better suites your purpose.

From the linked manual:

```
// This a chain shape with isolated vertices
b2Vec2 vs[4];
vs[0].Set(1.7f, 0.0f);
vs[1].Set(1.0f, 0.25f);
vs[2].Set(0.0f, 0.0f);
vs[3].Set(-1.7f, 0.4f);
b2ChainShape chain;
chain.CreateChain(vs, 4);

```

For your terrain, you'd just generate the array of points and then create the Chain Shape.

Pay attention as well to the *ghost vertices* feature which is necessary to correctly use multiple distinct Chain Shapes that adjoin each other without generating similar collision problems to the box solution.

# Answer
> 0 votes
You can compute the angle with the arctangent function atan2 (from math.h)

float angle = atan2(differenceY, differenceX);

---
Tags: c++, box2d, rotation
---


# Question
Title: Different Screen Sizes and Camera in Unity
Now I know that no matter what the screen size is the camera will keep its height, so no worries about that. My question is, is there a way to manipulate the camera, either its orthographic size, or its viewport rect width, height, x or y so that the camera will fit perfectly on different screen resolutions. I know this a perfect solution for supporting different screens problem but how do other games do that? I mean I took some games from google play like bunny skater, or stick hero, those games look the same on Huawei P6 which has 1280x720 resoltuion, on Prestigio Multipad 4 which has 1024x768 and on HP Slate 7 which has 1024 x 600 resultion, now my question is how do they do that? I think the closest solution to this is to manipulate viewport rect of the camera, I'm saying this because I found a script that does so but it leaves black bars on top and bottom, the game looks the same on every device though but as I said it leaves black bars on top and bottom, so is there a solution on how to do this?

# Answer
When making games, I typically support resolutions between 5:4 to 16:9. The best way I found to ensure maximum object coverage on the screen is to optimize for 3:2 and then adjust the camera's view along the axis that minimizes the amount of extra space. So if the game is in landscape mode and is being played on a 5:4 device, the width would remain static and the height would adjust, if it's being played on a 16:9 device, then the height would remain static and the width would adjust.

Here's a picture display of how it works in practice.

A 3:2 display will have the best experience, a device which is taller than 3:2 (going towards 5:4) will have some extra view at the top or bottom, a device which is wider than 3:2 (going towards 16:9) will have some extra view at the left and right edges.

The content of this view will however only contain an extra bit of background, it should not contain anything important or interesting.

The issue with relying on Unity's "constant height" default behaviour is that the amount of overlap between the two extremes of common resolutions: 5:4 and 16:9 is huge. Meaning you can't position anything in the yellow area of the image above or the purple area of the image below, because it will simply not be shown on devices with the other (in images smaller) resolution. This also messes up things like the rule of thirds and makes scene composition essentially impossible.
> 2 votes

# Answer
Usually for portrait games you need to set camera as fixed height , that is how it already works in Unity. And for landscape games like side scrollers you need to use fixed width. You need to write some additional code to achieve this functionality.

You can find the explanation in the following tutorial at 37 mins

Unite 2014 - 2D Best Practices In Unity
> 0 votes

# Answer
What you are asking, in the Web Design world is known as "responsive design". essentially the game positions elements relatively, instead of absolutely.

This means the positions are "skewed" with the viewport size. A good example of this might be to say:

```
column1_x = (Screen.width / 4) * 1;
column2_x = (Screen.width / 4) * 2;
column3_x = (Screen.width / 4) * 3;
column4_x = (Screen.width / 4) * 4;

```

This would give you screen column coordinates to work with. (HTML5 Web pages utilize typically a 12 column layout, but that is a bit excessive for a game)

the next question you have about manipulation of the camera, comes from unity's scripting API. You can find a range of functions and properties for the camera at: http://docs.unity3d.com/ScriptReference/Camera.html
> 0 votes

---
Tags: unity, camera, screen
---


# Question
Title: How can I Debug.Draw different shapes in unity?
I want draw new shapes in Sence for example I want `Debug.DrawSphere` can I Debug.DrawCollider? Is possible that I Debug.DrawSphereCast

# Answer
You could use unity's Gizmos to draw cubes and spheres. Script Reference.

```
void OnDrawGizmos()
{
    Gizmos.color = Color.red;
    Gizmos.DrawSphere(this.transform.position, 1);
}

```
> 2 votes

---
Tags: unity, debugging
---


# Question
Title: Increase speed with each enemy destroyed?
I need some help with coding this idea: "For each Target destroyed, increase the Gunner's speed by (speed variable)". The idea is that the Gunner is automatically moving, and I want it to become more frantic with each target hit.

Here's the relevant code I have so far:

```
   using UnityEngine;
   using System.Collections;
   using System.Collections.Generic;

    void Update () {
            Gunner_Move ();
    }

    //gives me the error "Assets/_Scripts/MovementPathScript.cs(60,83): error CS0200: Property or indexer `System.Array.Length' cannot be assigned to (it is read only)"
    void Gunner_Move(){
            if (GameObject.FindGameObjectsWithTag ("BulletProgressionObject").Length -= 1)
                Gunner_SpeedIncrease ();
    }

```

void Gunner\_SpeedIncrease(){ //behavior that I'm not sure how to make }

```
    //for the bullets colliding with target's parent object
        void OnTriggerEnter(Collider other){
            if (other.gameObject.CompareTag ("BulletProgressionObject"))
                Destroy (other.gameObject);

```

I think it's a foreach loop, but the issue I'm having is properly implementing it. Any suggestions or referrals would be greatly appreciated.

# Answer
> 3 votes
Rather than calling `GameObject.FindGameObjectsWithTag` every frame, you could just call `Gunner_SpeedIncrease()` within `OnTriggerEnter` when the trigger/collision happens.

```
void OnTriggerEnter(Collider other) {
    if (other.gameObject.CompareTag ("BulletProgressionObject")) {
        Destroy (other.gameObject);
        Gunner_SpeedIncrease ();
    }
}

```

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