# Question
Title: Adapting tilemap algorithm to support isometric tilemap
I'm using Phaser to build an isometric game. The framework doesn't have support for isometric tilemaps yet, so I'm starting to write a PR for it to support.

What I currently have, loading an isometric tilemap on the current `Phaser.Tilemap` object, is this:

As you can see, the tiles are wrongly positioned because of the simple 2D tile positioning approach the framework currently uses.

The class that actually makes the parsing of the JSON map and converts it into a tilemap is Phaser.TilemapParser, specifically at line 185.

What I need is some help on where to start adapting this parser – or any other part of the code – in order for it to support isometric tilemaps.

I don't know exactly where to start extending this parser – or even writing a new parser just for isometric tilemaps. Also, I know the calculations are different for positioning isometric tiles, and I want to know too where that change should go here, as I didn't find that either.

# Answer
> 8 votes
You don't need to change the parser, just the renderer.
The tiles will be at the 'same' place, except the projection is different.
The good news is that the good context 2d can do isometric just by setting the right isometric transform.
Once you set it, just draw in a regular way (including drawImage), and all will be drawn in the isometric way !!! magic !!!

So what i suggest you do with phaser to draw the tiles :
-save context.
-set transform to an isometric one.
-draw tiles with regular phaser code.
-restore context.

This image was made just with setTransform + drawImage of random small tile bitmap on a context2D :

**How does isometric coordinates work ?**
The 'regular' coordinate system is the cartesian coordinates.
It needs a center **O**, and two unit perpendicular vectors Ux and Uy.
The fact that they are unit vectors means they have a length of 1. It allows such a system not to change distances after translation.
The fact that they are perpendicular allows such a system not to change distances after a rotation.
If you have x and y of a point, you get the points with

```
P(x,y) = x * Ux + y * Uy.
with Ux = (1,0) and Uy = (0,1).

```

Now for isometric projection we just release one constraint : Ux and Uy do not have to be perpendicular. So distances will change after a rotation.
But since they are still unit vectors, distances are kept after a translation ( iso - metric == same - distances ).
Since Ux and Uy, are unit vectors, we can write them as

```
 Ux = (cos A1, sin A1)
 Uy = (cos A2, sin A2).

```

A1 and A2 will be the relative angle between Ux / Uy and the horizontal line :

By changing A1 and A2, you change the axes directions, and you can give the look that you want to your projection.
Obviously, if A1 == A2, both axes are the same and you'll see nothing.
A1 = PI / 6 and A2 = 9 * PI / 10 seems (subjectively) a good starting point for the angles.

to compute where is a (x, y) point, the formula is the same as cartesian : P = x*Ux + y*Uy.

To convert from cartesian to isometric, the transform matrix is :

```
  (in regular mathematical notation)
  M =  [ cosA1 sinA1 translateX
         cosA2 sinA2 translateY
          0     0        1       ] ;

  or (in webgl column-by-column notation )
  Mgl = [ [ cosA1       cosA2     0 ]
          [ sinA1       sinA2     0 ]
          [ translateX translateY 1 ]  ]

```

below i also compute the reverse of the transform matrix to be able to get world coordinates from mouse coordinates.

Notice that i introduced a scale, and also that i allow to change the x aspect ratio if you want to have non-square tiles.

if you want to play with the fiddle it's here (move by pressing mouse).

(version corresponding to the code below) http://jsfiddle.net/gamealchemist/zF2w8/4/

(latest version : http://jsfiddle.net/gamealchemist/zF2w8/ )

```
//  Parameters
//

// center of the display on screen
var displayCenterX = 1*canvas.width / 3;
var displayCenterY = 2 * canvas.height / 3;

// angle of the x axis. Should be in [0, PI/2]
var angleX = Math.PI / 6;
// angle of the y axis. Should be in [PI/2, PI[
var angleY = 2.8;

// scale for the tiles
var scale = 120.0;
// relative scale for the x of the tile. use it to stretch tiles.
var relScaleX = 1;

// ----------------------------------------
//     Transforms
// ----------------------------------------
var transfMatrix = [Math.cos(angleX), Math.sin(angleX),
Math.cos(angleY), Math.sin(angleY)];
var _norm = relScaleX + 1;
relScaleX /= _norm;
transfMatrix[0] *= scale * relScaleX;
transfMatrix[1] *= scale  * relScaleX;
transfMatrix[2] *= scale / _norm;
transfMatrix[3] *= scale / _norm;
// matrix reverse
var determinant = transfMatrix[0] * transfMatrix[3] - transfMatrix[2] * transfMatrix[1];
var transfMatrixRev = [transfMatrix[3], -transfMatrix[1], -transfMatrix[2], transfMatrix[0]];
transfMatrixRev[0] /= determinant;
transfMatrixRev[1] /= determinant;
transfMatrixRev[2] /= determinant;
transfMatrixRev[3] /= determinant;

// use with :
c.setTransform(transfMatrix[0],transfMatrix[1],
                 transfMatrix[2],transfMatrix[3],
                   displayCenterX, displayCenterY);

```

.

```
 // regular 3x3 transform matrix in webGL format :
 var mat3 = [ transfMatrix[0],transfMatrix[2], 0,
             transfMatrix[1],transfMatrix[3], 0,
             displayCenterX, displayCenterY, 1
           ] ;

```

( for the fun, the pseudo-3D version : http://jsfiddle.net/gamealchemist/zF2w8/5/ )

---
Tags: javascript, tilemap, isometric, phaser
---


# Question
Title: Why is my C# array in unity not working?
I'm creating a 2D brick breaking game in unity 4.3. I want all of my bricks to be different colours for each game, so I've created a C# script to assign random colours to each brick when the game starts, about every half-second to "Make it look cooler." However, when I run my game I get the following error:

```
NullReferenceException: Object reference not set to an instance of an object
BlockInitialiser+<blockColour>c__Iterator0.MoveNext () (at Assets/Scripts   /BlockInitialiser.cs:16)
UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator)
BlockInitialiser:Start() (at Assets/Scripts/BlockInitialiser.cs:9)

```

Here is my code:

```
using UnityEngine;
using System.Collections;

public class BlockInitialiser : MonoBehaviour {
    GameObject[] blocks;
    // Use this for initialization
    void Start ()
    {
        StartCoroutine (blockColour ());
                blocks = GameObject.FindGameObjectsWithTag ("Brick");
        blocks = new GameObject[40];
    }

    IEnumerator blockColour()
    {
        foreach (GameObject block in blocks)
            block.renderer.material.color = new Color(Random.value,Random.value,Random.value);
        yield return new WaitForSeconds (0.5F);
    }

```

PS I'm a noob both with C# and Unity, so this is probably a really easy fix, but despite reading through loads of other questions, I just can't get it right. Thanks in advance, guys.

# Answer
Change this:

```
StartCoroutine(blockColour());
blocks = GameObject.FindGameObjectsWithTag("Brick");
blocks = new GameObject[40];

```

To this:

```
blocks = GameObject.FindGameObjectsWithTag("Brick");
StartCoroutine(blockColour());

```
> 1 votes

# Answer
You start your coroutine, which accesses the blocks array, BEFORE you fill it with GameObjects.
> 2 votes

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


# Question
Title: How can I render something like the swirling clouds of Jupiter?
The effect should be as similar as possible to this, though it does not need to be at planetary scale.

I was thinking that it could be done offline via particles, perhaps by directing their motion in some way. Then rendering the frames to a texture and playing these back in a loop for real-time rendering?

But I wonder if there is some other real-time way... maybe mesh patches shaped like swirls can be moved around, after being textured carefully, to imitate the motion of swirls of gaseous matter?

# Answer
I think you shouldn't use particles for performance reasons. They can indeed give spiral feel, but it's hard to efficiently let particles affect each others' movement. In other words, efficient particle systems usually have no interaction between particles.

In the below photo, it seems more like the clouds are being affected by the nearby environment.

Instead of particles, you could use 2D fluid or smoke simulation, which resolves the problem of interaction with advection of quantities inside the fluid and pressure constraints. An implementation of 2D smoke is detailed in Mark Harris' Fast Fluid Dynamics Simulation on the GPU. There's also this other answer with a brief explanation of fluid dynamics, with other references.
> 2 votes

# Answer
You could use a particle engine or even a fluid dynamics engine, but that will be quite complicated to set up. When you do it in real-time, you will likely run into performance problems. When you precalculate a few seconds long movie sequence from a simulation, you will have problems to get it to loop seamlessly.

But you could reach an almost as good effect by multiple bitmaps.

Start with a static bitmap as a background. Then representing each of the moving bands of clouds with a series of a repeating, tiling bitmaps. Have all these bands scroll horizontally with different speeds. When you let the borders of these bands fade to transparency and let them overlap each other, it should look almost like that.
> 2 votes

# Answer
How about combining techniques. Start with an image (painting, reference, etc.), and modify it to give you initial conditions for a 2D fluid simulation. Run the fluid simulation from these initial conditions for a while and then use the resulting velocity field to advect the source image.
> 0 votes

---
Tags: textures, particles, planet, fluid-dynamics
---


title: JBox2D bodies don't collide?

text:
# Question
Title: JBox2D bodies don't collide?
I have two objects. A dynamic player and a static ground object.

It was working for a while until I did some refactoring and suddenly my play falls right through my ground object.

Is there anything obviously wrong with the following? I have no idea what might be wrong so if you have experienced this before, enlighten me!

Here's the initialization code of the objects:

(pixelsPerMeter is 10)

```
    int pixelsPerMeter = Game.instance.pixelsPerMeter;

    //create body def
    BodyDef boxDef = new BodyDef();
    boxDef.position.set(0, 0);
    boxDef.type = BodyType.DYNAMIC;

    //create shape
    PolygonShape boxShape = new PolygonShape();
    boxShape.setAsBox(this.size.width / pixelsPerMeter, this.size.height / pixelsPerMeter);

    //create body
    body = Game.instance.world.createBody(boxDef);

    //finally create the fixture
    FixtureDef boxFixture = new FixtureDef();
    boxFixture.density = 1;
    boxFixture.shape = boxShape;

    //add the fixture to the box? :\
    body.createFixture(boxFixture);

```

This is done twice, one for the player and once for the ground object.

The player's body type is set to BodyType.DYNAMIC while the ground is STATIC.

And of course the ground is below the body, and gravity is set to 9.8f.

# Answer
> 1 votes
Turns out, there was two problems. One was I set the size property of my entity after instantiating but did not update the Body size.

The other issue is I didn't realize box2d positions was centered for each body.

---
Tags: java, collision-detection, jbox2d
---


title: glGenVertexArrays causes crash

text:
# Question
Title: glGenVertexArrays causes crash
My code keeps crashing at runtime, I have done some creative debugging and determined that it was the glGenVertexArrays that was causing the crash, I've looked around and come across some answers that told me to enable experimental mode in GLEW but that didn't work, as far as I can tell my graphics card supports it, my opengl version is 3.1. I'm using freeGLUT and GLEW

here's the code, the line in question is 45 http://hastebin.com/rekizejuza.cpp

```
std::cout << "made it here\r\n";
glGenVertexArrays(1, &meshID);
std::cout << "not here here\r\n";
glBindVertexArray(meshID);

```

# Answer
> 9 votes
A common reason for null pointer dereferences on calls to newer OpenGL functions is that they are provided by an extension wrangler library like GLEW through function pointers that are dynamically loaded at runtime.

In order for them to be initialized, you need to run the initialization function of GLEW.

The correct place to call `glewInit()` is after you've gotten an OpenGL context and have made it current, but before you use any of the extension function pointers it exposes.

# Answer
> 2 votes
You mentioned to be using GLEW. If so, the `glGenVertexArrays` symbol should be just a plain global variable of type function pointer. To know if it is available, you can just test it for null:

```
if (glGenVertexArrays == NULL)
{
    // chances are you don't have this feature...
}

```

If it is null, then either you have a problem with GLEW or the feature is likely not supported in your system.

In case you don't have VAOs, you can still render pretty much in the same way. Just remove the VAO calls and remember to always reset the vertex format before drawing. I.e.: `glVertexAttribPointer`.

Also, Make sure you have the most recent GL diver. It might help.

---
Tags: opengl, c++, glut, mingw, glew
---


# Question
Title: How to control which polygons get rendered first in a batch (e.g. to draw leaves)?
Sorting transparent objects is a well-known problem. If you send a bunch of transparent polygons (e. g. leaves and branches on a tree) into the GPU and render them with alpha blending enabled, the GPU will sort the polygons randomly.

But what I noticed is that although they get sorted randomly, the order of rendering is always the same. If it wasn't the leaves would flicker as their colors change, depending on which layer they are on.

How can I control which polygons get rendered when? Maybe their order depends on the index buffer?

\[EDIT\] To clarify things: I know that different Draw() calls execute precisely in the order they were issued. I am trying to figure out how to manipulate the polygon order inside a single Draw() call. If a tree has a hundred polygons it is a waste do draw evey single one separately and a pain in the artists'... behind. So what I need is to influence the order of rendering for a bunch of polygons in a single pair vertex and index buffers.

Yes and I am working with XNA 4.0.

# Answer
> 3 votes
Your premise is incorrect.

If you send a bunch of transparent polygons (or anything else) to the GPU to be rendered, the GPU will draw them in precisely the order you defined them -- it will not sort them at all.

The way you control which polygons get rendered first is to send them to the GPU first; either by putting them first in the index buffer (if you're using one), or by putting them earlier in the vertex buffer (if you're using one), or putting them in an earlier draw operation.

# Answer
> 1 votes
The order in which they are drawn is deterministic. The GPU will not randomly decide which polygon to draw. The order is controlled by the order you supply the draw calls in and the order of the indices in the index buffer.

Often you will want to manually sort your polygons and then send them as a batch to the GPU. I do not know which framework you're using so unfortunately I cannot give you any more tips there. But I usually add a parameter to my draw calls that I later use to sort them. Though I've never had to sort individual polygons in a model before.

You can also separate the model into two. One with the entire tree excluding the leaves, and one with only the leaves and then draw them separately. The extra benefit of this is that you can use a different shader for the leaves. For example you can use this to tint the leaves depending on seasons.

---
Tags: transparency, sorting
---


title: jQuery - div border around map area

text:
# Question
Title: jQuery - div border around map area
Let's say I have this map:

```
<map name="diffmap1" id="diffmap1" class="myMap">
<area shape="poly" coords="152,347,253,292,264,307,167,358" class="diff diff1">
<area shape="poly" coords="93,244,164,215,171,233,97,264" class="diff diff2">
</map>

```

and javascript:

```
$('.diff').click(function(e){
//code here
});

```

How can I make when I click on one one 'diff' to make a div with border appear around that 'diff'?

It has to calculate the position automatically, like the margin-top, margin-left and size based on the coordonates.

Any thoughts?

# Answer
> 0 votes
You can get the coordinates of your ".diff" with offset.

```
$(".diff").click(function(e)) {
    var offset = $(this).offset();
    var width = $(this).width();
    var height= $(this).height();
    // use offset.left and offset.top
    $(body).append("<div style=\"position:absolute;left:"+offset.left+";top:"+offset.top+";width:"+width+";height:"+height+";border:5px solid red\"></div>");
});

```

the generated div should be like (border red 5px) :

```
<div style="position:absolute;left:15px;top:20px;width:40px;height:100px;border:5px solid red"></div>

```

---
Tags: jquery
---


# Question
Title: Providing texture coordinates and using indexed drawing at the same time
Please consider the following vertex structure

```
struct vertex {
    vec3 posL, normalL;
};

```

Using this vertex layout, we can provide the vertex data in an interleaved way, i.e. (posL,normalL),(posL',normalL'),... This works pretty fine in combination with indexed drawing via glDrawElements().

However, if we add texture coordinates to our vertex structure, i.e. consider

```
struct vertex
{
    vec3 posL, normalL;
    vec2 tex;
};

```

things get more complicated. Since one and the same vertex (meaning it's position) may participate in a variety of different faces with varying texture coordinates, I wondered how one would provide such vertex data to the vertex buffer.

One solution would be to quit storing the data interleaved and provide it a linear way, i.e. (posL,posL',...),(normalL,normalL',...),(tex,tex',...) where each tuple has the same length. Doing so, we would hold related things together (i.e. the k-th element of each tuple forms exactly one input the vertex shader sees).

But we would push much more data to the pipeline than necessary. So, what's the "ideal" solution to this problem? If one suggests to use different buffers, how does the vertex shader know, that texture coordinate `tex` at position `i` in Buffer 2 corresponds to the tuple `(posL,normalL`) at position `j` in Buffer 1?

# Answer
There is not ideal way of doing it, this is a common problem with meshes. To solve this there, are two different approaches: Considering that you have a vertex that has to be used with two different textures coordinates here is how you can approach the problem:

1:Duplicate the vertex and assign to each one the different texture coordinates. As a result you will have two vertices with exactly the same position but two different texture coordinates. How you store the vertex data is not really relevant at this point (interleaved or not). There is no way i know right now (someone correct me if i'm wrong) to be able to represent an indexed vertex buffer in order to share vertex position and different texture coordinates.

2:Separate the geometry in multiple parts and draw it with two (or multiple) draw calls but this has a couple of drawbacks. First need to create extra code to be able to share the vertex position, second you need to make multiple draw calls and this hurts performance especially on mobile devices.

I think the first approach is the industry standard because in the end the extra memory used is not much of a problem. One way to overcome the memory usage is to use streaming and it's much easier to use that (not to mention that you can significantly increase the amount of geometry) instead of the second approach in which adds a lot of code complexity.
> 2 votes

---
Tags: opengl, glsl, index-buffer, vertex-buffer
---


# Question
Title: How do I deal with different "types" of entities in Entity-Component-System model?
I have **CollisionSystem** which basically iterates through the array of **PhysicsComponent** and checks if there was some collision between two entities. But where should interaction code go? And how should I deal with different types of entities? (pseudocode below)

```
// in collision system
for(e1 in all entities) {
    for(e2 in all entities) {
        if(e1 == e2) continue;
        if(e1 collides with e2) {
            handleCollision(e1, e2);
        }
    }
}

...
// probably in collision system too?
void handleCollision(Entity* e1, Entity* e2) {
    if(e1 has DamageComponent) {
        if(e2 has HealthComponent) {
            e2->HealthComponent->
            reduceHP(e1->DamageComponent->damageAmount);
    //but what if some entities show "Hurt" animation or
    // do some other stuff specific for that type of entity?
        }
    }
    ... // other types of entities
}

```

What is bad is that this **handleCollision** code will have lots of if-else conditions as more and more types of entities emerge and the code will be hard to maintain. How can I deal with this?

# Answer
There are many, many ways to approach this, depending on the needs of your game and what you want the API surfaces to look like. This is also not a problem that really has anything to do with entity systems. A physics API should maintain a list of physics object (often "rigid bodies"), detect, and resolve the collisions between them. The API can be a "system" in the common component-based parlance, or not. A physics object can be a physics component or not. It doesn't matter: the solution is the same.

You don't want the physics code itself to know anything about the interactions between specific objects, beyond the fact that they collided (and perhaps some metadata about the collision). Instead, design your physics API to support the *notification* of a collision to interested parties, who can subscribe to events on the physics API if needed. You can implement this behavior with the observer pattern. Thus you delegate the processing of the interaction elsewhere.

In whatever higher-level code deals with the interaction now (typically something more at the "game" level), you can employ techniques such as double-dispatch to resolve interactions between two runtime component types (normal dynamic dispatch in C++ and most languages is done only on a single parameter, the `this` pointer; double-dispatch is a way to perform dynamic dispatch on two parameter types, which is all you have varying in the case of two objects interacting).

Back in the physics system itself, you can avoid the n-squared problem of checking every rigid body against every *other* rigid body using spatial partitioning techniques. By dividing up your simulation space into distinct regions (for example using quad-trees or oct-trees, or even simple separation-of-axis approaches) reduces the problem space for detecting collisions by immediately discarding large numbers of objects that cannot possibly collide.
> 6 votes

# Answer
Personally, I'd do something like this:

```
// in collision system
for(e1 in all entities) {
    for(e2 in all entities) {
        if(e1 == e2) continue;
        if(e1 collides with e2) {
            e1.sendMessage(COLLISION, e2);
            e2.sendMessage(COLLISION, e1);
        }
    }
}

//on the component that needs to handle a collision
void DamageComponent::handleMessage(MessageType msg, Entity* e) {
    if (msg == COLLISION) {
        if(e has HealthComponent) {
            e2.sendMessage(reduceHp, damageAmount);
        }
    }
}

void AnimationComponent::handleMessage(MessageType msg, Entity* e) {
    if (msg == COLLISION) {
        //...
    }
}

```

This requires a sendMessage method on the Entity class that sends on the message and parameter to each component that makes up the Entity. The Entity parameter on the handleMessage method should really be a void\* so you can pass anything in.
> 0 votes

# Answer
I actually found a pretty good website recently that helped me.

http://afloatingpoint.blogspot.com/

This lets you test for derivations and whatnot. Personally I would detatch my physics code so that the component is simply a pointer to some data and that the index of that data can easily be indexed.

You could go GameComponent-\>PhysicsComponent (abstract)-\>BoxCollider ... etc. Then you just need to go with

```
         Entity->GetComponent<PhysicsComponent>()

```

to get the collider, or if you want a specific one you can check to see if you have

```
         Entity->GetComponent<BoxCollider>()

```

Also on your physics code you don't want to recheck specific pairings so your for loop could be different for a nice speed up. Also it is unlikely you want your callbacks to happen RIGHT when the collision happens. Maybe but I'd let my physics code finish up first so you don't destroy the cache and that way if you raycast or whatever all the colliders are resituated where they need to be.

```
    /*
        Want a continuous block of colliders for processing.
        Makes processing much faster.
    */
    vector<AABB> m_aabbColliders;
    vector<AABBCollider*> m_aabbComponents;

    Queue<Collision> m_collisionQueue;

    Collision collision;
    //No comparison necessary because when i is zero it evaluates as false
    for(auto i = m_aabbColliders.size();i;--i)
    {
       //No need to check i or greater then i because all collisions
       //combinations in that part of the list have been checked.
       //Since j will never equal i we can ignore having the if(j == i) clause here.
       for(auto j = i - 1;j < 0;--j)
       {
         //Physics Code
          if(Physics::AABBvAABBCollision(m_aabbColliders[i],m_aabbColliders[j],&collision))
          {
              collision.first = m_aabbComponents[i];
              collision.second  m_aabbComponents[j];
               m_CollisionQueue.push_back(collision);
          }
       }
    }

    //Let the physics engine deal with collisions before you take call backs.
    //To resituate collided objects.

    //Collisions are DONE now deal with callbacks to pass that info to
    //Entities that need to know.
    Message collisionMessage;
    for(auto i = m_collisionQueue.size();i;--i)
    {
       collisionMessage = Message(m_collisionQueue.pop());
       collisionMessage.asCollision().first->SendMessage(MessageType::Collision,collisionMessage);
       //Maybe swap first and second here depending on
       //if you want your engine to have the collision message
       //have first be itself always or something.
       collisionMessage.asCollision().second->SendMessage(MessageType::Collision,collisionMessage);
    }

 //DamageComponent Code

 void DamageComponent::RecieveMessage(MessageType type,const Message& msg)
 {
  switch(type)
  {
     case MessageType::Collision:
         Message dmg = Message(dmg_amount);
         msg.asCollision().second->SendMessage(MessageType::DealtDamage,dmg);
         break;
  }
}

void HealthComponent::RecieveMessage(MessageType type,const Message& msg)
{
    switch(type)
    {
      case MessageType::DealtDamage:
        this->ChangeHealth(-msg.asInt());
        break;
    }
}

void HealthComponent::ChangeHealth(int amount)
{
   if(m_health != m_maxHealth && m_health + amount >= m_maxHealth)
   {
      m_health = m_maxHealth;
      SendMessage(MessageType::HealthFilled);
   }
   else
   {
      m_health += amount;
      if(m_health > m_maxHealth) m_health = m_maxHealth;
   }

   if(m_health <= 0)
   {
      Message msg = Message(playerComponent);
      SendMessage(MessageType::PlayerDeath,msg);
   }
}

//On the Player script you can have it recieve the event then remove itself from   queues and setup respawn and all that other stuff.

```

As you can see this can get really interconnected but still be completely encapsulated in individual components.
> 0 votes

---
Tags: entity-system
---


# Question
Title: Why aren't ModLoader's decompiled files showing up?
I want to start making a Minecraft 1.6.4 mod, but have this trouble with ModLoader:

I've run the `decompile.bat` batch file, but when opening the `eclipse` folder, the `bin` folder is empty. The batch file ran fine with no errors, and `/src/minecraft/net/minecraft` contains many decompiled java files, but no modloader files like `BaseMod.java`.

If I open this folder with Eclipse, the package explorer menu stays empty.

What's happening here?

# Answer
The MCP decompiler should give you a warning saying that the jar is modded and may behave in ways that were unexpected, this is not just one of those errors you ignore and brush off, it is there for a reason. MCP only contains mappings for the obfuscated minecraft code, and when you throw extra files into the mix (such as modloader) it tends to behave erratically. I would suggest using an easier and more capable alternative, the Minecraft Forge project. It's easy to use and they now have an automated build and update system, making it more convenient than ever, I myself have made a few tutorials on how to get the forge workspace up and running here. that being said, if you still want to continue using ModLoader, here are some debugging tips to make sure that you decompile correctly.

* Make sure the jar you provide MCP with is modded
* Make sure that the version of ModLoader is correct for that minecraft version
* Make sure you import the project into eclipse instead of just adding the files, to ensure you are seeing all of the decompiled project.

Happy Modding!
> 1 votes

# Answer
Your question is phrased unclearly, but I think this is what you mean:

"I have the correct files in Eclipse that are decompiled, but they dont show up!!!".

This is because Eclipse does not just show any random file in the directory. You must add the classes in. If you add a class that already exists (e.g. your decompiled modloader code), then it will automatically use the class file already there.

I do not have as much experience with ModLoader. I program minecraft server plugins, not minecraft client mods, but I hope that this has helped.
> 1 votes

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


title: Set Position of multiple bodies

text:
# Question
Title: Set Position of multiple bodies
I have a character composed of five bodies which are tied together by a lot of joints. On of them is the overall chassis, to which all forces and impulses are applied to move the whole Character.

All in all that works very fine, except one thing: I need to set the Position of the Character so that it get Beamed from one place to the other in one single frame.

Unfortunately I cannot get this to work. I tried the following code, without any success…

```
playerbodies.forEach(function (bd) {
    bd.SetLinearVelocity(new b2.Vec2());
    var t = bd.GetTransform();
    t.p.x -= 10;
    bd.SetTransform(t, bd.GetAngle());
});

```

How can I make that happen?

# Answer
> 0 votes
As suggested in the comments… The answer is quiet simple and the right code is:

```
1| playerbodies.forEach(function (bd) {
2|     bd.SetLinearVelocity(new b2.Vec2());
3|     var t = bd.GetTransform();
4|     t.p.x -= 10;
5|     bd.SetTransform(t.p, bd.GetAngle());
6| });

```

whereby line 6 is corrected with `t.p`.

Since Javascript is not typesafe this mistake totally broke the simulation of the bodies, instead of throwing an error.

---
Tags: box2d
---


# Question
Title: What does Unity's "Speed of Sound"-option do?
I've been reading Unity's manual on the `AudioManager`'s properties. *Speed of Sound* is the only undocumented option. What is it for?

# Answer
> 6 votes
It looks like this value is a measure of the *physical speed of sound*, and likely plays a part in the result of the simulation of the Doppler effect (if enabled).

The value shown in the screenshot in the documentation is 347, which is very close to the actual speed of sound (343 meters-per-second at sea level).

It doesn't appear to have anything to do with the observed *playback speed* of the sound.

---
Tags: unity, audio, configuration
---


# Question
Title: Why is my cursor not working if I add a scaling matrix?
After moving the camera to any direction, my cursor isn't getting drawn on the correct position. For example: I move my camera to the right, after that I click on the screen, but the cursor isn't getting drawn on the place I clicked. It's drawn somewhere else on the screen. Why is the cursor not getting drawn on the place I clicked?

I need to scale the screen because I want to support different resolutions in a MonoGame project(see my other question): How can I use a camera matrix with different resolutions?

I scale like this:

**UPDATE:** I added the code that I'm using to get the cursor position, and the code that I'm using to draw the cursor. In addition, I use now Matrix.Invert(scaleMatrix * camera.GetMatrix())), but it doesn't work. The cursor is still drawn on the wrong position.

```
//In my Player class, I get the position of the click(Tap)
//The Playerposition is the center of the camera

public void Update(GameTime gameTime)
{
  while (TouchPanel.IsGestureAvailable)
  {
    GestureSample gs = TouchPanel.ReadGesture();
    switch (gs.GestureType)
    {
        case GestureType.HorizontalDrag:
          Playerposition += new Vector2(gs.Delta.X / game1.scaleX, gs.Delta.Y / game1.scaleY);
        break;
        case GestureType.VerticalDrag:
          Playerposition += new Vector2(gs.Delta.X / game1.scaleX, gs.Delta.Y / game1.scaleY);
        break;
        case GestureType.Tap:
          game1.CursorPosition = new Rectangle((int)(gs.Position.X / game1.scaleX), (int)(gs.Position.Y / game1.scaleY), 10, 10);
          game1.Clicked = true;
        break;
    }
  }
}

  //In Game1:
  public const int VirtualScreenWidth = 800;
  public const int VirtualScreenHeight = 480;
  public float scaleX, scaleY;
  private Vector3 _screenScale;

  protected override void LoadContent()
  {
    scaleX = (float)GraphicsDevice.Viewport.Width / (float)VirtualScreenWidth;
    scaleY = (float)GraphicsDevice.Viewport.Height / (float)VirtualScreenHeight;
    _screenScale = new Vector3(scaleX, scaleY, 1.0f);
  }

  protected override void Update(GameTime gameTime)
  {
   player.Update(gameTime);
   //Updating the camera position:
   Newcameraposition = new Vector2(player.Playerposition.X - (float)VirtualScreenWidth / 2, player.Playerposition.Y - (float)VirtualScreenHeight / 2);

   camera.Update(gameTime, Newcameraposition);

   InvertCursorPos = Vector2.Transform(new Vector2(CursorPosition.X, CursorPosition.Y), Matrix.Invert(scaleMatrix * camera.GetMatrix()));

   //Calculate the cursor position
   if (Clicked == true)
   {
     CursorPosition = new Rectangle((int)(InvertCursorPos.X + Newcameraposition.X), (int)(InvertCursorPos.Y + Newcameraposition.Y), 10, 10);
     Clicked = false;
   }

   base.Update(gameTime);
  }

  // Drawing
  protected override void Draw(GameTime gameTime)
  {
  GraphicsDevice.Clear(Color.CornflowerBlue);
  var scaleMatrix = Matrix.CreateScale(_screenScale);
  spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.AnisotropicClamp, DepthStencilState.None, RasterizerState.CullNone, null, scaleMatrix * camera.GetMatrix());
    //Drawing the cursor
    spriteBatch.Draw(CursorSprite, CursorPosition, null, Color.White, 0, Vector2.Zero, SpriteEffects.None, 1);
  spriteBatch.End();

```

# Answer
You most likely need to convert your screen coordinates into your game world coordinates.

```
Vector2 pos = new Vector2(Mouse.GetState().X, Mouse.GetState().Y);
pos = Vector2.Transform(pos, Matrix.Invert(camera.GetMatrix()));

```

Line 1 gets the current mouse position

Line 2 converts the current mouse position, into your world coordinates, based on the camera transformation matrix you are using to draw.
> 0 votes

---
Tags: xna, c#, monogame
---


title: What are easing functions?

text:
# Question
Title: What are easing functions?
I found this cool website for game development and it has a list of easing functions:

Although the site contains a description of what they're for, it goes over my head. What are easing functions and what are they used for?

## Update

I found a better example of the functions themselves from Phaser.io's source code. These functions are much simpler than the answers here would suggest. They only take one parameter, `k`. As part of the answer, I'd like to know how to use these.

# Answer
> 13 votes
Easing functions are used for interpolation, typically (but not necessarily) in animation / kinematic motion. Linear interpolation (lerp) is something you may have heard of. Let's say you lerp a smiley face from one corner of the screen to another (much as per your image). This means the smiley will move at a steady velocity from point A to point B. If you were to apply this to movement of a limb, it would look very robotic and unnatural -- the actuators / servos that robots use, perform this way. Obviously, human limbs move in a very different way. And most motion that you will see in nature will have interesting motion curves, rather than the steady, unchanging velocity seen in linear interpolation.

Enter easing. Easing motion means the velocity is *not* constant. What this achieves is to look more realistic. Watch people, watch different animals, watch plants bending in the wind, or even how falling rain changes direction on a gusty day. Watch the velocity of a ball as you throw it up in the air and in comes back down again. Watch the motion of a guitar string as you pluck it. Each of these types of motion has a different curve describing velocity.

I suggest you play with GreenSock's GSAP online to get a feel for what the different types of easing curves produce in terms of motion. It's one of those things where it takes time and practice to map a particular named curve to the sort of motion you imagine you want. But once you have grasped the basics, you'll have a lot of fun.

P.S. As I said, easing is not only used for animation. It may be used for sound panning, for effecting skeletal motion at the logical / model level, or anything else you can think of that might need specific smooth variation over time.

# Answer
> 8 votes
An easing function lets you interpolate values from one value to another over a given interval using something called an "easing function". These are functions that are designed to take a value and at any given point in the interval, output the value at a certain point in time.

This can be best explained by taking a look at a code snippet:

```
// simple linear tweening - no easing, no acceleration

Math.linearTween = function (t, b, c, d) {
    return c*t/d + b;
};

```

> @t is the current time (or position) of the tween. This can be seconds or frames, steps, seconds, ms, whatever – as long as the unit is the same as is used for the total time
>
> @b is the beginning value of the property.
>
> @c is the change between the beginning and destination value of the property.
>
> @d is the total time of the tween.

Thanks, http://upshots.org/actionscript/jsas-understanding-easing

This is the definition of a linear easing function. Graphing this over time in terms of 't' we get a mere linear graph.

**Okay, cool. What can we use them, for?**

Any time you have a start and finish in mind and want to animate them, you can use a "tween" or "easing function".

For example, here's a GIF I just took of Angry Birds:

Notice the menu sliding out to the point in the screen, but it stops slowly? This is due to an easing function that eases into place. You can see those all over the web. If this was a linear ease, it would be the same throughout.

**Music?**

Sure! If we take the value of our current soundtrack value and interpolate it between that and 0 over a total t of say, 1 second then our volume will slowly fade out over a period of one second.

**Bounding Objects**

There are also functions that allow for bouncing (see: http://easings.net/#easeOutBounce) which can produce effects like this on a sprite without any physics systems:

You can find more information on the web by searching for tweening.

# Answer
> 2 votes
Easing functions serve to change a value during a time period, from a starting number to an end number.

You use that value to animate a property of an object in your game, such as position, rotation, scale, changing colors and other properties that use a value.

The different easing functions determine the "feel" of the animation, or how the value changes over time.

On the website you posted, the graph shows the value changing over time from a start to an end, so it doesn't mean the object you are animating will follow the path of the ball in the graph.

---
Tags: game-design, easing
---


# Question
Title: Mixing interpolation with extrapolation in multiplayer game
I am creating a multiplayer drag racing game and have difficulties mixing extrapolation and interpolation. To save network bandwidth i am getting information from the opponent only on his button press, which is:

```
car->speed = newSpeed;
car->distanceReached = newDistance;
car->currentForce = newForce;

```

And i extrapolate the rest until the next update from opponent. On player update, extrapolation kicks in:

```
//Find new acceleration, frictionForce and mass being constants.
car->acceleration = (car->currentForce - car->frictionForce) / car->mass;

//Calculate new velocity.
car->speed += car->acceleration * dTime;

//Reduce force.
car->currentForce -= car->friction * dTime;
if(car->currentForce < 0)
    car->currentForce = 0;

//Update distance reached
car->distanceReached += car->speed;

```

So we got update from opponent - car starts moving until force is equal 0. This seems to be working fine. What is not - when update is received in the middle of extrapolation, i am setting new position directly as seen before and car jumps to adjust to the "real" position. So the question is - how to incorporate interpolation in this situation for car not to jump and not to ruin already running extrapolation?

# Answer
First of all, make sure you using fixed timestep, instead of variable one. Also adding an extra field of sending time to your messages will probably make things easier, since that way you can tell when the message arrived how many frames is the local game ahead of message sending time.
> 1 votes

---
Tags: mathematics, multiplayer, game-mechanics, physics, movement
---


# Question
Title: XNA Diffuse Shader Issue. Edge lighting problem. Image Attached
As you can see in this image the diffuse shading is working correctly in some places but in other places such as the the bottom of the sphere you can see the squares/triangles of the mesh.

Any idea what would be causing this? Let me know if you need anymore information related to code. I can upload my normals calculations and shader effect if required.

EDIT: Here's a link to the shader I'm using http://pastebin.com/gymVc7CP

Link to normals calculations: http://pastebin.com/KnMGdzHP

Seems to be an issue with edge lighting. Can't seem to see where I'm going wrong with the normals calculations though.

# Answer
> 1 votes
I don't see any obvious issue in the code you've provided.

One thing that could go wrong is the order of the indices for some faces, which would lead to normals pointing backward on them (as Joseph Mansfield hinted in comments).

Check your index buffer: are you building up all faces in the same order, either clockwise or anti-clockwise? If not then what you see is perfectly normal. The order of the vertices matter, it defines in which direction the face is oriented.

---
Tags: xna, shaders, lighting, shadows, normals
---


# Question
Title: How do I detect when an HTML 5 game has ended?
I'd like to embed HTML5 games in a website, but I need to be able to detect when the game has ended so I can run some of my own JavaScript.

Looking at the output of some game engines (Construct 2, for example) reveals a nightmare of code that I couldn't hope to tweak so that it fires off an event when done.

How can I detect when a game has ended?

# Answer
Unless the game or framework offers some sort of API that let's the webpage check on its state, there no easy way to do this. Technically, the game is always "running" even if the player is just sitting in the menu, which is why you would need the game to tell your webpage when the player has completed the level.
> 4 votes

# Answer
I don't see why this is necessarily that difficult to approach. It depends what triggers a "Game Over," but take for example some 2D collision based game, where you loose when you fall out of bounds. You'd have a simple `isInBounds()` function or something that you could check when running the main which might lead to some `gameOver()` function when to is false. From there you could reference any of your own javascript you want to.

A really good example of all of this can be found here. It gives a broader tutorial on creating a whole game, but it has a section that deals specifically with a 'gameOver()\` event.

If this doesn't answer your question, please tell me.
> 1 votes

---
Tags: javascript, html5
---


title: AddComponent using a variable

text:
# Question
Title: AddComponent using a variable
I want to add a Component to a GameObject using an existing instance of the Component class.

Let's say I have the class `Foo`:

```
public class Foo : MonoBehaviour {
    int id {get; set;}
    string name {get; set;}
    //and other many variables
}

```

In another class I already have an instance of `Foo` with all variables setup.

What I want to do is attach the existing instance of `Foo` to a `GameObject`, instead to attach it and then setup all the variables.

Something like that, it is just an example, of course it give errors:

```
GameObject go;      //Existing GameObject
Foo foo;            //Existing instance of Foo with variables setup.

go.AddComponent(foo);

```

Instead of doing:

```
GameObject go;      //Existing GameObject
Foo foo;            //Existing instance of Foo with variables setup.

go.AddComponent("Foo");

Foo myComponent = go.GetComponent<Foo>();
myComponent.id = foo.id;
myComponent.name = foo.name;
//and so on

```

Is there a way to do that?

# Answer
> 1 votes
I don't know of a way to add the existing component. However, it is possible to make it easier to duplicate the existing component into the new one:

```
Foo newFoo = go.AddComponent(foo.GetType());
foreach (FieldInfo fi in foo.GetType().GetFields())
{
  fi.SetValue(newFoo, fi.GetValue(foo));
}

```

This uses reflection to copy the fields of the old component to the fields of the new component. Do note that `GetFields()` only returns fields marked as `public`. You can get everything but private fields using binding flags.

Remember to update the reference at the end if you want to use `foo` to reference `go`'s `Foo` component:

```
foo = newFoo;

```

Alternatively, I'm not sure how you're creating the `foo` component in the first place, but I'd pass in the game object you want to attach.

```
public static Foo CreateFoo(ref GameObject go) {
    Foo foo = go.AddComponent<Foo>();
    //Setup foo
    return foo;
}

```

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


# Question
Title: Can I prevent diagonal movement from exploring more of the map?
In a tile-grid where movement in any of 8 directions takes exactly the same amount of turns (chess-board style rules), can I prevent diagonal movement from showing more new tiles than orthogonal movement?

For example: You are the red box in the image below. The green cells are presently visible to you (square field of view). You can move a distance of one tile in any of the eight directions.

If you move *north-east*, you will explore 13 new tiles (shown in blue). If you instead move *south*, you will only explore 7 new tiles (shown in purple).

How can I make traveling in each direction equally favorable for exploration?

# Answer
> 67 votes
Dungeons and Dragons 3.5 (pen-and-paper RPG) has a solution used for both movement and grid-based radius calculations: diagonal movement costs 1.5 what orthogonal costs. Since the diagonal of a unit square is approximately 1.414, 1.5 is pretty close.

Because D&D 3.5 only supports integer movement, the way this is actually calculated is that orthogonal movement costs "one square." Your first diagonal movement also only costs "one square," but the second diagonal costs "two squares." You alternate one and two squares for each diagonal move. Implementing this movement rule within your game will handle several problems with diagonal movement.

As this diagram shows, this movement rule creates a reasonable approximation of circles and also is not off by more than 1 when compared to the true distance (when within 15 units of the start).

If your vision/exploration radius is also calculated in this way, diagonal movement and diagonal discoveries will be about as close or far as orthogonal ones.

# Answer
> 66 votes
You need to change the shape of the field of view.

So that when you move in any direction, the same number of new squares become visible.

Here is one possibility:

# Answer
> 27 votes
To have diagonal and orthogonal movement reveal approximately the same area, you need *two* things (each of which, alone, has already been suggested in another answer or comment):

1. **Approximately circular view range**:

On its own, this won't give exactly the same revealed area for both types of movement. For example, in the image above, orthogonal movement reveals 9 squares, while diagonal movement reveals 13. It's still better than the 13 / 7 ratio for the square view area in your example, though.

In fact, as the view radius grows, the ratio of revealed areas per diagonal / orthogonal step tends to √2 ≈ 1.414 for a circular area, while the same ratio for a square view area tends to 2.
2. **Slower diagonal movement**:

In real life, walking diagonally across a square field takes longer than walking along one of the sides. In fact, it takes about √2 ≈ 1.414 times longer. If you want movement in your game to feel realistic, you should make that happen in your game, too.

In practice, 3/2 = 1.5 is a pretty good approximation of √2. Thus, you can just make each orthogonal step take two time units, and make each diagonal step take three. With the example view area above, this yields 9/2 = 4.5 revealed squares per time unit for orthogonal movement, and 13/3 = 4.33 revealed squares per time unit for diagonal movement. Pretty close, eh?

Alternatively, if you want to stick to "1 step = 1 time unit" for orthogonal movement, you can use something like the D&D system Dane suggested and make every second diagonal step consume an extra turn. (If you do that, though, you do need to give every unit an explicit counter of how many diagonal steps they've taken; otherwise you may end up with exploits like, say, a *E, NE, E, NE, ...* movement sequence allowing a player to explore faster than intended.)

# Answer
> 11 votes
Since you are using a grid and know which direction the user is proceeding there is nothing constraining you from adapting the prior answer and using a different fields of view depending on the direction.

For example you could extended the field to include the corners when you travel in cardinal directions and shrink it down two squares on each end in your diagonal cases so that each uncovers 9 squares.

Another alternative depending on how your lighting works would be to use a better circle approximation with antialiasing, to partially reveal some of the squares.

# Answer
> 7 votes
How about, rather than having a fixed viewing range, have the player's visibility area depend upon what direction the player was facing, as well as perhaps the direction the player faced in the last few turns (a player who was moving north might be able to immediately take a step south, but might take a few turns to get maximum viewing distance in that direction). A player who heads north out of a narrow corridor into a large room and continues traveling north would have limited visibility east and west, and probably should. When the player stops moving, one could have the system automatically "explore" unseen areas that are within the player's present sight radius, but while the player is actively moving the field-of-view should be more confined.

# Answer
> 3 votes
As an alternative to a more complex field of view (which as discussed above adds its own problems because of the constraints of a grid-based layout) you could try to emulate the effect of movement in a game that isn't based on a discreet grid. Where free movement is possible a diagonal move of one unit would be exactly that, not the ~1.41 units of movement seen with a square grid.

While you can't force single unit movement without losing your descreet grid (which would change your game design pretty significantly) perhaps you could keep track of the extra movement taken and drop moves later: track the extra 0.41s and once they total more then 1.00 have that unit skip a move. Or the other way around: consider diagonal to be normal, add up the 0.41s for each horizontal or vertical move, and give extra move credit once that is greater than 1 (or 1.41 for a diagonal move).

You would need to be careful how you present this to your players in a way that makes it look both smooth and fair. In a multi-human-player scenario such changes could become something the players take advantage of strategically - this may be a problem, or there may be a natural way to mix this in with the game mechanic (perhaps allow the players to store a small amount of "unused move credit" that they can use to react quickly at a later time and have the extra 0.41s of move feed into (or take out from) that pool.

This would work best if player control entities moved move than one unit each turn. For example three movement points might be used as three horzontal moves, or two diagonal ones with 0.16 left in the pool for later. Once that hits 1.00 the player gets a "free" hor/very move and at 1.41 a free diagonal one. You could cap the extra at 1.5 for force it to be used or lost at that point to stop the player keeping this stored energy for ages or letting it build up.

Obviously this is a complication to your game rules that may be completely undesirable, and it would be impractical for a non-computerised game, but if you could make it work within your game's existing rules it would limit the exploration difference between movement directions without needing to abandon the grid format.

# Answer
> 2 votes
You could make the player move two spaces if they move up, down, left or right, and only one diagonally. It wouldn't completely even it out, but it would be much closer.

---
Tags: movement, grid, line-of-sight
---


# Question
Title: How to rotate an image around its own center in AndEngine?
I'm beginner in Android programming with Andengine framework. And my question:

How to rotate an image around its own center in AndEngine?

I use Body and AnimatedSprite.

**Update**

This is my code:

```
        final AnimatedSprite face;
        final Body body;
        face = new AnimatedSprite(pX, pY, this.mCircleFaceTextureRegion,
                this.getVertexBufferObjectManager());
        body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face,
                BodyType.DynamicBody, FIXTURE_DEF);
        face.setUserData(body);
        face.animate(200);
        face.applyTorque(100);
        face.setUserData("monster");
        this.mScene.registerTouchArea(face);
        this.mScene.attachChild(face);
        this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face,
                body, true, true));

```

And here in the **ContactListener** when have a collision with other object.

```
private ContactListener createContactListener() {
        ContactListener contactListener = null;
        contactListener = new ContactListener() {
            @Override
            public void beginContact(Contact contact) {
                try {
                    Fixture x1 = null;
                    Fixture x2 = null;
                    x1 = contact.getFixtureA();
                    x2 = contact.getFixtureB();
                    if (x2.getBody().getUserData().equals("player")
                            && x1.getBody().getUserData().equals("monster")) {
                        x1.getBody().setFixedRotation(true);
                        hitsound.play();
                        mEngine.vibrate(100);
                        Log.i("CONTACT", "BETWEEN PLAYER AND MONSTER!");
                    }
                } catch (Exception e) {
                    Log.d("ErrorMessage", e.getMessage());
                }
            }
            @Override
            public void preSolve(Contact contact, Manifold oldManifold) {
            }
            @Override
            public void postSolve(Contact contact, ContactImpulse impulse) {
            }
            @Override
            public void endContact(Contact contact) {
            }
        };
        return contactListener;
    }

```

I have set `x1.getBody().setFixedRotation(true);`. But position of this object isn't kept. What is wrong with my code?

# Answer
Without physics you can use `setRotation` and also register rotation entity modifier to make it rotate from its current to the desired angle. When you add physics, you should no longer directly rotate an object around it's center, you should to use forces and impulses to give the body a spin. In your case:

```
body.applyTorque(force);

```

This won't work if you set fixed rotation to true. You can use the following to set the rotation directly.

```
body.setTransform(positionVector, rotation);

```

However if you set the fixed rotation to true, you can still use the entity modifier:

```
face.registerEntityModifier(new RotationModifier(timeInSeconds, fromAngle, toAngle));

```

---

When solving collisions, you have to use the if both ways, because it is not guaranteed player will be `x2`. If you want to stop the object from moving and rotating, simply call

```
body.setLinearVelocity(0);
body.setAngularVelocity(0);

```

But you should do this in `endContact()`. Also you might want to call

```
body.setActive(false);

```

It will remove the body from simulation. It should keep its position and rotation. It would no longer collide with anything.
> 0 votes

---
Tags: sprites, box2d, andengine, body
---


# Question
Title: Unity3d - zooming with orthogonal camera like in Google maps
I am implementing 2d orthogonal zoom.

As far as I know - in Unity3d there are no translations like in OpenGL. Taking this into consideration, I work with :

* camera size
* camera position (center)
* real world mouse position

I have no issues implementing simple zoom in/ zoom out operations, combined with camera position changes ( drag'n'drop )

But I have some issues calculating camera zoom shift in this case :

* camera size = (4,4)
* camera position = (0,0)
* real world mouse position = (1,0)

A double zoom in (2x) is applied, as a result -

* camera size = (2,2)
* camera position = (0.5,0)
* real world mouse position = (1,0)

User shifts real mouse position to (1.5,0) and applies a double zoom out ( 0.5 ). In this case :

* camera size is again (4,4)
* camera position = ???????
* real world mouse position = (1.5,0)

What should be the camera shift so the mouse doesn't visually move ? What is the formula for calculation in this case ?

Thank you in advance.

P.S. Any suggestion regarding current method of handling zoom are welcome

**Update**

So - I resolved this issue with Blue's help. The basic idea about shifting is right. The main reason it didn't work was incorrect zoom factor.

Example :

Initial camera size is 5. User zooms in by 1, camera size is now 4 ( it displays less content on the same 'screen'). User changes mouse position and zooms out by 1. Camera size is 5 again, but the amount of zoom is actually different :

* initially the change was 20% ( 1/5 )
* in the second time, the change was 25% ( 1/4 )

My fault was that, when zooming out, I tried to restore position by 20%, not 25%.

# Answer
In this case you need the difference between your camera center and your real world mouse point. You can then apply your scale factor to this and offset your camera to make it "zoom" on the mouse position.

Semi-pseudo code:

```
float scaleFactor;
Vector2 mousePosition;
Vector2 cameraCenter;

Vector2 offset = (mousePosition - cameraCenter) / scaleFactor;
cameraCenter += offset;

```

If you are scaling a percentage this would be relative to the current zoom level. so it would be 0.2, then 0.16 and so on. This makes the mouse pointer be the focus point no matter the scale factor.
> 1 votes

---
Tags: unity
---


# Question
Title: How can I implement a third-person camera in an SC2 map?
I want to try creating a custom Starcraft 2 map with a third-person camera following a unit. A few custom maps with this feature exist already, so I know it's possible.

How do I do this? Do I need a custom mods file, or can everything be done in the map file?

# Answer
The information provided below is from http://www.staredit.net/starcraft2/Third\_Person\_Camera where you can find out more stuff like WASD triggers and multiple camera options, but the basics for the 3rd person setup is here:

## Setting up the Camera Object

Underneath the "Create Camera" Button, you will see a white box with the value "Camera 001" in it, right click it and hit "Modify Properties". Set the values to the following (Name - Sub - Value - (Description)):

* Angle - Field Of View - 27.996 - (How wide the view is. This will be a 28 degrees view from the left of the screen to the right) Angle - Roll - 0.0 - (How far to roll the camera from the left to right. Think barrel rolls.)
* Depth of Field - Amount - 0.0 - (Unknown, feel free to update the wiki article if you know any information about this value)
* Depth of Field - Depth - 8.0 - (How far the camera sees)
* Depth of Field - End - 8.0 - (The end position of the view from the point of the camera)
* Depth of Field - Start - 0.0 - (The start position of the view from the point of the camera)
* Distance - 4 - (How far the literal camera is from the actual location of the camera. Setting this to 0 results in a FPS (First Person Shooter), around 4 with be a TPS (Third Person Shooter))
* Distance - Far Clip - 300.0 - (The distance from which nothing will be rendered. If anything is farther than this from the camera, it WILL NOT RENDER)
* Distance - Near Clip - .1 - (The distance when nothing will be rendered. If anything is closer than this from the camera, it WILL NOT RENDER)
* Distance - Shadow Clip - 75.0 - (Assuming the distance after which shadows will not be rendered)
* Target - Pitch - 12 - (Pitch of the camera. Pitch is the looking up/down movement)
* Target - X - (Doesn't matter, this will change every frame of the game)
* Target - Y - (Doesn't matter, this will change every frame of the game)
* Target - Yaw - 180 - (Yaw of the camera. Think left to right movement that isn't barrel rolls)
* Target - Z Offset - 1 - (How far the camera is off the ground)

The main value we need here is the Distance - 4. Setting this to 4 will create a third person camera (Although with units other than a marine, you may need to edit this). 0 will create a first person camera. The same goes for the Target - Z Offset - 1. A taller unit will need a higher value to raise the camera up some.

## Global Variables

A few global variables are needed, the names and types of which are indicated below (Name - Type - Value - (Description)):

* FaceOffset\[8\] - Real - 0.0 - (Where each player's respective units is facing)
* Speed - Real - 0.03 - (The speed at which a unit moves)
* Units\[8\] - Unit - \[EMPTY\] - (Stores each player's respective units)
* PlayerA\[8\] - Real - 0 - (Stores is the players A key is down)
* PlayerS\[8\] - Real - 0 - (Stores is the players S key is down)
* PlayerD\[8\] - Real - 0 - (Stores is the players D key is down)
* PlayerW\[8\] - Real - 0 - (Stores is the players W key is down)

## Set Up Camera Trigger

```
Set Up Camera
   Events
       Timer - Every 0.0 seconds of Game Time
   Local Variables
       Yaw = 0.0 <Real>
       CameraFocus = No Point <Point>
       Counter = 0 <Integer>
   Conditions
   Actions
       General - For each integer Counter from 1 to 8 with increment 1, do (Actions)
           Actions
               General - If (Conditions) then do (Actions) else do (Actions)
                   If
                       (Controller of player Counter) == User
                       (Status of player Counter) == Playing
                   Then
                       Camera - Apply Camera 001 for player Counter over 0.0 seconds with Existing Velocity% initial velocity, 10% deceleration, and Don't Include Target
                       Camera - Lock camera mouse relative mode On for player Counter
                       Camera - Turn camera mouse rotation On for player Counter
                       Camera - Turn camera height smoothing Off for player Counter
                       Camera - Turn camera height displacement On for player Counter
                   Else

```

## Camera Update Trigger:

```
Camera Update
   Events
       Timer - Every 0.0 seconds of Game Time
   Local Variables
       Yaw = 0.0 <Real>
       CameraFocus = No Point <Point>
       Counter = 0 <Integer>
   Conditions
   Actions
       General - For each integer Counter from 1 to 8 with increment 1, do (Actions)
           Actions
               General - If (Conditions) then do (Actions) else do (Actions)
                   If
                       (Controller of player Counter) == User
                       (Status of player Counter) == Playing
                   Then
                       Variable - Set Yaw = (Current camera yaw of player Counter)
                       Variable - Set CameraFocus = ((Position of Units[Counter]) offset by 0.0 towards (Yaw + 90.0) degrees)
                       Unit - Make Units[Counter] face (Yaw + FaceOffset[Counter]) over 0.0 seconds
                       Camera - Set the camera bounds for (Player group(Counter)) to (Region((X of CameraFocus), (Y of CameraFocus), ((X of CameraFocus) + 0.01), ((Y of CameraFocus) + 0.01))) (Do Not adjust the minimap)
                   Else

```
> 1 votes

---
Tags: modding, starcraft-2, third-person-view
---


# Question
Title: jQuery - calculate map polygon Width and Height
Let's say I have this map:

```
<map name="diffmap1" id="diffmap1" class="myMap">
<area shape="poly" coords="152,347,253,292,264,307,167,358" class="diff diff1">
<area shape="poly" coords="93,244,164,215,171,233,97,264" class="diff diff2">
</map>

```

and jquery:

```
$('.diff').click(function(e){
//code here
});

```

How can I calculate the maximum height and width of each polygon?

LE: https://www.dropbox.com/s/erplo5fwtp284oh/qwe.jpg

# Answer
I feel like I'm helping you a lot these time ;-)

So you have this :

```
<area shape="poly" coords="152,347,253,292,264,307,167,358" class="diff diff1">

```

and you know that coords are like "x1,y1,x2,y2\[...\]" so you must put every x in one array and every y in another array. Then, process =)

```
var x = [];
var y = [];
// string value of the attribute coord :
var coord = $(".diff1").attr('coord');
// split it in some int values
var values = coord.split(',');
var length = values.length;
// fill in your X and Y arrays
for (var i = 0; i < length; i++) {
    // push in x and increase i by 1.
    x.push(values[i++]);
    // push in y
    y.push(values[i]);
}

// get the min & max X values :
var minX = Math.min.apply(null, x),
maxX = Math.max.apply(null, x);

// get the min & max Y values :
var minY = Math.min.apply(null, y),
maxY = Math.max.apply(null, y);

// Here is your result :
var width = maxX - minX;
var height = maxY - minY;

```

Your devoted servant,

Apolo

---

**NOTE** : in my code I use the selector ".diff1", you have to do the same with ".diff2" to have values of your other polygon.
> 1 votes

---
Tags: jquery
---


title: 2d OnMouse(anything) Not working

text:
# Question
Title: 2d OnMouse(anything) Not working
So I want to be able to click on these targets and have them destroy themselves. Right now I have many OnMouse functions all just trying to print something for testing. For whatever reason it doesn't fire. I'm sure theres something simple I'm missing. Anyones help is greatly appreciated. Here is a picture of Unity itself and the code.

```
using UnityEngine;
using System.Collections;

public class TargetLogic : MonoBehaviour
{

    // Use this for initialization
    void Start ()
    {

    }

    // Update is called once per frame
    void Update ()
    {
        //print("ok");
    }

    void OnMouseDown()
    {
        print("Works");
    }
    void OnMouseEnter()
    {
        print("Enter");
    }
    void OnMouseUp()
    {
        print("up");
    }
    void OnMouseOver()
    {
        print("Over");
    }
}

```

I also Have tried with a 2d Rigidbody as shown here

# Answer
> 0 votes
I see nothing wrong with your first setup, the only thing that may interfere could be another object over (in Z space) your target, with a collider attached to it.

The first collider in Z space is the one that get's the mouse events.

So try to disable everything except the MainCamera, the Light and your target, if it is working then there is something that overlaps your target, and this object is getting the mouse events.

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


# Question
Title: Most efficient way of brighten and darken sprites with OpenGL > 2.0
So I have been shading (brighten/darken +adding color) my sprites by using *glTexEnvf* with *GL\_MODULATE* and *GL\_ADD* and a vertex color. I only had to rebind the batch every time I needed to change from modulate to add and vice versa. it was not perfect but worked well enough.

However libGDX **1.0** dropped support for OpenGL1.1 and the only way I see is to use shaders. I want to stay up to date and therefore want to update. I am new to shaders but I found some code that works to brighten a sprite. However as far as I understood I need to rebind the batch *every time* I want another value for my brightness =\> batch binding on every sprite I render. That is not very performant.

* Is there a way to change values between the bindings? (I don't think it's possible because shaders get compiled afaik).
* Or do you have another idea how to archive this effect with openGL2.0 (like I did before)?
* Or is rebinding every sprite the most efficient way with OpenGL2.0?

# Answer
> 3 votes
Make a vertex attribute "vec4 Color", and multiply the color you get from the texture sampler with the Color vertex attribute.

```
vec4 color = texture2D(TextureSampler, TexCoord) * Color;

```

Supply white and the brightness will remain unchanged, supply black and the sprite will become black, supply something brighter than white the sprite will become brighter. (Brighter than white would be 2.0, 2.0, 2.0, 1.0)

As a added bonus you can also colorize the sprite this way, supply pure red and it will become (dark) red. And you can draw them half-transparent too by changing the 4. parameter, the alpha channel.

If you don't need that just multiply by a single float instead of a vec4.

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


title: Constant 2D Bullet movement in a shmup

text:
# Question
Title: Constant 2D Bullet movement in a shmup
I've been following the pixelnest tutorial to make a 2D shmup (http://pixelnest.io/tutorials/2d-game-unity/player-and-enemies/).

While working on this I've experimented with increasing the firing rate to get a continuous stream of bullets, and I've noticed that bullets are more spaced apart if the ship is moved backwards, and they get clumped up when the ship is moved forwards. Is there a way to maintain constant distance between bullets no matter the movement of the player?

Should I even care? I get the feeling that if the player moves backwards then the firing rate is essentially slower (at least until they reach the edge of the screen) and vice versa if you move forwards.

# Answer
> 16 votes
It is classical Doppler effect, which is quite normal thing. If you move backwards, then the distance between bullets is `normal_distance_caused_by_firerate - ship_backward_distance_passed`, instaead of just `normal_distance_caused_by_firerate` if ship stands still.

If you increase the bullets speed, then this effect would be harder to notice, because the distance would be bigger by itself, compared to the ship speed.

You could increase the firerate if ship's moving back, and decrease it when it's moving forward, but this isn't normal behavior, and it could look weird. It would be also cheating on game logic.

To sum up, you should leave it as it is, or decrease ship speed / increase bullet speed to decrease the visual difference in distance between bullets while moving forward/backward.

# Answer
> 1 votes
Add the ship's velocity to the bullet velocity when they are created.

When moving backwards, the bullets will be slowed down. When moving forward, they'll be sped up. However this will have the effect of making the bullets move horizontally when the ship does - experiment with having the bullets be affected by only the y-velocity.

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


# Question
Title: my movement is working good on keyboard but on android its not
So basically here is what my movement is like for keys:

key down

```
 if (keycode == Keys.LEFT) {
                mishi.getAcceleration().x = -13;
            }

```

key up

```
if (keycode == Keys.LEFT) {
            mishi.getAcceleration().x = 0;
            mishi.getVelocity().x = 0;
            mishi.setRotation(0);
        }

```

touch down

```
            if (x >= 0 && x < 1 && y > 5 && y < 8) {
                mishi.getAcceleration().x = -13;
            }

```

touch up

```
if (x >= 0 && x < 1 && y > 5 && y < 8) {
            mishi.getAcceleration().x = 0;
            mishi.getVelocity().x = 0;
            mishi.setRotation(0);
        }

```

So its basically the same thing, however, on android when I move around my player doesn't stop he just keeps going. Its hard to explain but it just feels and looks wrong, you have to touch around to get it to work properly but its unplayable. I think it has to do with the fact that I am moving with 2 touches but not sure how to handle it. I tried adding 2 input processes and combining them but it produced the same results.

I saw some code online using a map to hold in the pointers but I am not sure how to utilize those pointers in this scenario where 2 keys being pressed are both for movement and they need to be combined so that I can move up/right or down/left diagonally.

# Answer
> 1 votes
I am not incredibly familiar with mobile interface processing but my understanding of your question is that you want the user to be pressing both up and left at the same time on the device? This seems to be a little counter intuitive, while on a computer it is natural to press two keys at a time but for a mobile device you would only want to press once.

My suggestion would be to have a single input from the device and depending on the angle of that press from the origin of the directional pad (or however the user determines where to press) and conclude from there whether they are intending to go left, up, or both.

Lastly, if you think your input is being processed twice and you aren't moving how you expect then that could very well be the case but it would most likely have to do with your code.

EDIT: Also you may want to take a look over at this question: https://gamedev.stackexchange.com/a/35594/40821

---
Tags: java, android, libgdx, movement, touch
---


# Question
Title: Adding Components (classes) to unordered_map in Entity? (Possible typeid as key issue)
I've got a little test put together that has a couple simple Components that are supposed to be added to an Entity, but the addComponent function isn't working; I think it's got something to do with typeid/component class inheritance, but I'm not sure. It seems to add a single entry to the map of type Component, but nothing else. Any help is much appreciated, thanks!

```
#include <iostream>
#include <unordered_map>
#include <typeinfo>

using namespace std;

//----------------------------------------------------------------------

//the base component
class Component {
    public:
    Component() {cout<<"new Component created\n";}
};

//----------------------------------------------------------------------

//a "thing" component
class Thing : public Component {
    public:
    Thing() {cout<<"new Thing created\n";}
};

//----------------------------------------------------------------------

//a "what" component
class What : public Component {
    public:
    What() {cout<<"new What created\n";}
};

//----------------------------------------------------------------------

class Entity {
    public:
    void addComponent(Component* c);
    template <typename T> T* getComponent();
    int componentCount();

    private:
    unordered_map<const type_info *, Component *> components;
};

//----------------------------------------------------------------------

void Entity::addComponent(Component* c) {
    components[&typeid(*c)] = c;
}

//----------------------------------------------------------------------

template <typename T>
T* Entity::getComponent() {
    if(components.count(&typeid(T)) != 0) {
        return static_cast<T*>(components[&typeid(T)]);
    } else {
        return nullptr;
    }
}

//----------------------------------------------------------------------

int Entity::componentCount() {
    return components.size();
}

//----------------------------------------------------------------------

int main(int argc, char* argv[]) {
    Entity e;

    e.addComponent(new What());
    e.addComponent(new Thing());

    cout<<e.componentCount()<<endl;

    return 0;
}

```

# Answer
`typeid` can only see the derived type of an object if you have virtual methods. Otherwise it can only see the static type of an object. Since your base class almost certainly *needs* a virtual destructor, that's the easiest thing to change in your example.

```
class Component {
  public:
  Component() {cout<<"new Component created\n";}
  virtual ~Component() = default;
};

```
> 1 votes

---
Tags: c++, component-based, entity-component
---


title: XNA C# Mario Collide

text:
# Question
Title: XNA C# Mario Collide
I'm trying to make Mario so im trying to do the collision part but whenever I do the side collision it bounces back too far. I want to make it so that it only stops Mario not bounces him back.

```
        public void MarioBrickCollide()
    {
        for (int collide = 0; collide < brick.Length; collide++)
        {
            if (Mariovec.Y <= brickvec[collide].Y && Mariovec.Y + Mario.Height + 3 > brickvec[collide].Y && Mariovec.X + Mario.Width > brickvec[collide].X && Mariovec.X < brickvec[collide].X + brick[collide].Width)
            {
                Mariovel.Y = 0;
                brickHitTop = true;
            }
            if (Mariovec.X + Mario.Width >= brickvec[0].X && Mariovec.X < brickvec[0].X + brick[0].Width && Mariovec.Y + Mario.Height > brickvec[0].Y && Mariovec.Y < brickvec[0].Y)
            {
                Mariovec.X = brickvec[collide].X - Mario.Width;
            }
        }
    }

```

What can I do to make the collisions work?

# Answer
> 1 votes
Formatted your code so I can read it:

```
public void MarioBrickCollide() {
   for (int collide = 0; collide < brick.Length; collide++) {
      if (Mariovec.Y <= brickvec[collide].Y
         && Mariovec.Y + Mario.Height + 3 > brickvec[collide].Y
         && Mariovec.X + Mario.Width > brickvec[collide].X
         && Mariovec.X < brickvec[collide].X + brick[collide].Width
      ) {
         Mariovel.Y = 0;
         brickHitTop = true;
      }

      if (Mariovec.X + Mario.Width >= brickvec[0].X
         && Mariovec.X < brickvec[0].X + brick[0].Width
         && Mariovec.Y + Mario.Height > brickvec[0].Y
         && Mariovec.Y < brickvec[0].Y
      )
         Mariovec.X = brickvec[collide].X - Mario.Width;
    }
}

```

should the `0` indexes in the second `if` statement actually be `collide` instead?

---
Tags: c#, xna
---


# Question
Title: Multiple keypresses causing wierd results in SDL
I have been building a pong clone. I've been using a mixture of peoples different code to understand the way they structure their games as well as reading on game patterns. Currently I've gotten to draw a paddle on the screen and the player can move it with the keyboard no problem.

The issue comes when a player presses a button that is not 'Up' or 'Down'. For instance when the player holds the 'Up' key the paddle travels upwards, but if they simultaneously hold the 'Right' key it causes the paddle to fly downwards at a much greater speed.

My keyboard checking code is:

```
void GameLoop::Input(SDL_Event &ev)
{
    if (ev.type == SDL_KEYDOWN)
    {
        if (ev.key.keysym.scancode == SDL_SCANCODE_DOWN)
        {
            player1->IsMoving(true);
            player1->velocity = 10;
        }
        if (ev.key.keysym.scancode == SDL_SCANCODE_UP)
        {
            player1->IsMoving(true);
            player1->velocity = -10;
        }

    }

    else if (ev.type == SDL_KEYUP)
    {
        if (ev.key.keysym.scancode == SDL_SCANCODE_DOWN)
        {
            player1->IsMoving(false);
            player1->velocity = 0;
        }
        if (ev.key.keysym.scancode == SDL_SCANCODE_UP)
        {
            player1->IsMoving(false);
            player1->velocity = 0;
        }
    }
}

```

The GameLoop is ran within loop that is configured to run at 60FPS. You can see this in this code block here:

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

    //Initialise the app and SDL
    App app(SDL_INIT_VIDEO);
    GameLoop game;

    double lastTime = 0.0, currentTime;

    SDL_Event e;

    while (app.isRunning())
    {
        if (SDL_PollEvent(&e))
        {
            if (e.type == SDL_QUIT)
            {
                app.exit();
            }
        }

        currentTime = SDL_GetTicks() / 1000.0;
        if (currentTime >= lastTime + 0.01666667)
        {
            game.Input(e);
            game.Update();
            game.Render();

            lastTime = currentTime;
        }

    }

    return 0;
}

```

This is the paddles update code:

```
void Paddle::Update()
{
    if(moving == true)
    {
        rect.y += velocity;
        velocity = 50;
    }

    X = rect.x;
    Y = rect.y;
}

```

I'm unsure of what is causing the paddle to behave so strangely. Any insight given into this problem or even just the way I've approached this problem would be appreciated.

# Answer
> 0 votes
My guess is that your problem resides in the fact that you are not utilizing your delta time when updating your position.

```
if(moving == true)
{
    rect.y += velocity * delta;
    velocity = 50;
}

```

I am also not sure why you are setting the velocity to 50 here, whereas, in your Input function, you are setting it to -10 or 10.

---
Tags: sdl, input, keyboard
---


title: what is the ducking ability?

text:
# Question
Title: what is the ducking ability?
In my game framework I have this property:

```
canDuck : Boolean = true
Determines whether or not the hero's ducking ability is enabled.

```

What does it mean ?

regards

# Answer
> 8 votes
Ducking ability could be:

* Ability to turn into a duck, for a disguise or for duck related beak attacks.
* Ability to swim like a duck, enabling escape across water.
* Ability to quack like a duck, stunning the hero's enemies.
* Ability to lay eggs like a duck, perhaps with treasure inside.
* Ability to talk to ducks for duck related conversation, or command them to defend the hero.
* Ability to crouch or duck down (not related to ducks), to get under low things or steady aim.

But seriously it's likely the last one. To be sure you can search for references to `canDuck` and see how it's used in your framework.

# Answer
> 7 votes
Crouching, ducking -- the ability for the character to go from a standing position to a hunched-up position.

---
Tags: 2d, game-design, physics
---


# Question
Title: How can I implement platformer pathfinding?
I've gone through A\* pathfinding but could find anything on this. What I'm looking for is pathfinding for something kind of like a super smash bros level with different platforms. Can anyone point me in the right direction?

# Answer
This entirely depends on the nature of the game's platforms. Can you jump through them from below? Can you drop down through them while standing? Can you pass through them while falling without landing? Can an NPC jump/glide/accelerate in a specific direction mid-air?

These are all questions you should be asking when implementing your pathfinding algorithm.

All in all, A\* is pretty much applicable to all pathfinding. It's a very, very abstract algorithm, and all it requires is some sort of system of points or nodes in one form or another (polygonal vertices/edges/faces all work great for representing these) with some way to determine the "cost" of moving from one node to the next.

Given that the platforms will likely be flat surfaces, with no third dimension of movement, you could easily use a system of points that define the borders of each platform (left and right), and treat everything between those points as "walkable." From there, you just need to get your NPC to the goal location (which is decided by the AI behavior more than the pathfinding algorithm).

If you want to define AI behavior to be, say, "melee" aggressive, you'll likely want them to get as close to the player (or enemy, if the NPC is friendly) as possible, so they can attack them.

If you want to define AI behavior to be "ranged," you will likely want to find a position where the NPC is "safe" (distanced) but has a clear shot at the target.

The most efficient way for an NPC to detect these sorts of "hot spots" for target finding would be to pre-program them into the node map, itself.

For example, many NPCs in modern games know how to take cover behind obstacles, in combat. This is generally not because the AI is taught how to detect if an obstacle has a large enough bounding box to be used as cover, but rather because there is a pre-defined node (or, in fancier implementations, a polygon covering an area that is "acceptable to take cover at") told them that they should go there, and they likely detected that the player had too clear a shot at them (either by raycasting to the player's line of sight, or by the player's relative position with respect to the current position of the NPC).

AI behavior is full of quick little hacks like this that can all combine to make a fully functional, believable NPC.
> 3 votes

# Answer
I would have placed invisible object that when the NPC collide they change direction. You will get pretty far with that.
> 0 votes

---
Tags: path-finding, platformer
---


# Question
Title: How to get and change a mesh-renderer component in unity?
I've been making a simple brick-breaker game using unity 4.3 (In C#). I'm currently trying to make the blocks, which are stored in an array, all start with random colour properties. The colours are working correctly, but I want the blocks to start invisible, and then be assigned the various colours. I have researched, and found similar questions on changing the mesh-renderer component, but, as yet, they haven't worked. Here is my code:

EDIT: To put it simply: how do you make objects invisible, test if they are invisble or not and make them visble again.

```
using UnityEngine;
using System.Collections;

public class BlockInitialiser : MonoBehaviour {
    GameObject[] blocks;
    // Use this for initialization
    void Start ()
    {
        blocks = GameObject.FindGameObjectsWithTag ("Brick");
        StartCoroutine (blockColour ());
    }

    IEnumerator blockColour()
    {
        foreach (GameObject block in blocks)
                {
                        block.renderer.material.color = new Color (Random.value, Random.value, Random.value);
                        yield return new WaitForSeconds (0.1F);
                }
    }

```

Thanks in advance, guys.

# Answer
> 2 votes
The easiest way is to enable/disable the renderer.

Just go block.renderer.enabled = false; to turn it off, and = true; to turn it back on. You can check block.renderer.enabled to see if it's on or off.

Disabling the renderer also has the benefit of speeding up rendering.

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


# Question
Title: Retrieving JSON return value from function and parsing in Construct 2
I would like to know how to parse a JSON object and parse each value into either an array, or something that I can use to set values of several global variables in my project file. I want to avoid editing the Javascript file itself, so please try to provide an approach that can be done in Construct itself rather than an external way.

**Code sample**

```
 axonify.game = {
  gameData: function() {
    data = {
      name: 'Block Mania',
      timeLimit: 30,
      addedTimePerQuestion: 0,
      addedTimePerCorrectQuestion: 15,
      questionCount: questionCount
    };
    return data;
  },

```

# Answer
The manual is pretty explicit about this.

> Any external files can also be imported to your project via the Project Bar. This is useful for including any other resources your project might need, such as videos, additional images, JSON data, XML data, text data, documents, or other general files you might want to let the user download.
>
> For ideas on uses for project files and possible workflows, see the tutorial Using project files in Construct 2.

That link within the manual does indeed point to useful method to utilize this feature (it explains later that json may be used in place of xml):

> **Loading XML data**
> If you want to read an XML file stored with the project, import the XML file as a project file. Then you can use the AJAX object's Request project file action to download the file, and then load the result in to the XML object. The events below show how this can be done.

The further along in the article, the section **Making level editors** explains how this loading can be utilized to insert data that is edited separately from the project, allowing Construct2 games to be data-driven.
> 1 votes

---
Tags: javascript, construct-2
---


# Question
Title: Is it possible to use Unity components individually outside of the Unity Studio?
Such as physics, rendering or math libraries/objects. I would like create a project which would benefit from a few game engine related things but rather than use a mixture of separate libraries I thought a unified solution would be less hassle in the long run.

I'd like to build it using Visual Studio and utilize Unity components or would Unity studio be suitable to build this non-game application which ultimately would almost be like a 3d level editor.

# Answer
Most of the core bits of Unity are built into the executable itself and aren't even written in C# (the core of Unity is written in C++ and exposed to a C# runtime via Mono). The core Unity libraries cannot be used outside of Unity in any way.

Whatever you're trying to build can almost certainly be built inside of Unity itself, and easier than doing it outside the editor. If you really want to use Visual Studio, you can use VS to author .cs files for Unity and this is even supported by Unity (or was, at least). There are commercial plugins to make this use of VS easier, too.

If you'd rather build with Visual Studio and not use Unity's editor at all, you will need to find a different set of helper libraries. Unity is simply not a reusable set of free libraries; it's a complete unified product.
> 3 votes

---
Tags: unity, level-design
---


# Question
Title: Why does my character move up forever when he jumps with this code?
I've been doing some stupid stuff in Slick2D+LWJGL and I've run into a problem. I press the UP arrow and my character continues to go up until I let go :/ Here's the code:

```
if (inp.isKeyDown(Input.KEY_UP) && !jumping) {
    jumping = true;
    velY=-0.4f;
} else {
    jumping = false;
    velY=0.2f;
}

```

No idea what's happening :/ Help?

# Answer
> 2 votes
Presumably this code is called once every frame. What is likely happening is that while you hold down the up arrow, you are constantly toggling the state of `jumping`, which means you take the positive branch of the `if` every *even* frame and the negative branch every *odd* frame.

That also means you constantly toggle the velocity between `-0.4` and `0.2`. Every frame you presumably process that velocity and offset the player by it; however, because your upwards velocity exceeds your downwards velocity, you'll have a net upwards movement.

For example:

* On frame 0 you starting hold up. That sets your velocity to -0.4 (and `jumping` to `true`) and then you add that velocity to the player's position, giving you a delta in of Y of -0.4.
* The next frame you are still holding up, but `jumping` is now true, so you take the negative branch, setting velocity to 0.2 and jumping to `false`. When you apply velocity to position, you have a net delta of `-0.4 + 0.2 = -0.2`.
* Now, the third frame you are still holding up but `jumping` is now false, so you take the positive branch, set velocity to -0.4 and jumping to true. When you apply velocity to position you have a net delta of `-0.2 - 0.4 = -0.6`.

That's why your player always moves up.

To fix this, you could restructure the condition as follows:

```
if (inp.isKeyDown(Input.KEY_UP)) {
  if (!jumping) {
    jumping = true;
    velY=-0.4f;
  }
} else {
  jumping = false;
  velY=0.2f;
}

```

This means that if the up key is held, you start jumping if you have not already. If the up key is *not* held, you cancel the jump.

---
Tags: java, lwjgl, slick
---


# Question
Title: Unity: Instantiate an object respecting the prefab's default rotation
Simple question, I hope.

I've built a variety of prefabs for an isometric shooter game (hazards, enemies, health indicator bars, popup texts, shots, explosions). All of these prefabs were constructed with default rotations appropriate for the gameplay.

My problem is that Instantiate() will overwrite the default rotation of the prefab with whatever is specified as the rotation parameter. So I'm left with hard-coded rotations in my Instantiate() calls to get things oriented correctly in the X-Z plane. (0,180,0) and (90,0,0) are common ones. I'd much prefer to Instantiate prefab gameObjects consistently with "no change to their default rotation," but I'm not sure how to accomplish this.

Thanks for the help, Mike.

# Answer
The easiest way to achieve this, is to nest GameObjects you use as prefab. For example, if you want your prefab to be rotated (90,180,0), then put it in additional, empty GameObject. This GameObject will be not rotated after Instantiate (it will have (0,0,0) rotation), but inside of it you will have your old prefab, rotated as you wish it to be rotated.

So, this is how your current stucture looks:
`YourCurrentPrefab (90,180,0)`, which after Instantiation would have lost rotation: `YourCurrentPrefab (0,0,0)`

Instead, you should came up with structure like this:
`YourNewPrefabRoot (empty GO) (0,0,0)
 - YourWholeOldPrefabAsAChild (90,180,0)`,
which after Instantiation will actually remain the same, because the root already has a default rotation, and all your content is facing correct global direction anyway.

This workaround will require some work, to add additional empty root for each of your existing prefabs, however you can write a script to make this work for you. If you want to do so, take a look at PrefabUtility class, which has some helpful functions when it comes to work on prefabs.
> 0 votes

---
Tags: unity
---