# Question
Title: Rotate a plane defined by its normal and its distance
First apologies for the amount of pictures, it's a bit hard trying to explain my problem without pictures. Hope I've provided all the relevant code. If you feel you want to know about how I am doing something else, please tell me and I will include it.

I've been trying to work around rotating a plane in 3D space, but I keep hitting dead ends. The following is the situation:

I have a physics engine where I simulate a moving sphere inside a cube. To make things simpler, I have only drawn the top and bottom plane and moved the sphere vertically. I have defined my two planes as follows:

```
CollisionPlane* p = new CollisionPlane(glm::vec3(0.0, 1.0, 0.0), -5.0);
CollisionPlane* p2 = new CollisionPlane(glm::vec3(0.0, -1.0, 0.0), -5.0);

```

Where the `vec3` defines the normal of the plane, and the second parameter defines the distance of the plane from the normal. The reason I defined their distance as `-5` is because I have scaled the the model that represents my two planes by `10` on all axis, so now the distance from the origin is `5` to top and bottom, if that makes any sense.

To give you some reference, I am creating my two planes as two line loops, and I have a model which models those two line loop, like the following:

```
top plane:
std::shared_ptr<Mesh> f1 = std::make_shared<Mesh>(GL_LINE_LOOP);
std::vector<Vertex> verts = { Vertex(glm::vec3(0.5, 0.5, 0.5)), Vertex(glm::vec3(0.5, 0.5, -0.5)), Vertex(glm::vec3(-0.5, 0.5, -0.5)), Vertex(glm::vec3(-0.5, 0.5, 0.5)) };
f1->BufferVertices(verts);

bottom plane:
std::shared_ptr<Mesh> f2 = std::make_shared<Mesh>(GL_LINE_LOOP);
std::vector<Vertex> verts2 = { Vertex(glm::vec3(0.5, -0.5, 0.5)), Vertex(glm::vec3(0.5, -0.5, -0.5)), Vertex(glm::vec3(-0.5, -0.5, -0.5)), Vertex(glm::vec3(-0.5, -0.5, 0.5)) };
f2->BufferVertices(verts2);

std::shared_ptr<Model> faceModel = std::make_shared<Model>(std::vector<std::shared_ptr<Mesh>> {f1, f2 });

```

And like I said I scale the model by `10`.

Now I have a sphere that moves up and down, and collides with each face, and the collision response is implemented as well.

The problem I am facing is when I try to rotate my planes. It seems to work fine when I rotate around the Z-axis, but when I rotate around the X axis it doesn't seem to work. The following shows the result of rotating around Z:

However If I try to rotate around X, the ball penetrates the bottom plane, as if the collisionplane has moved down:

The following is the code I've tried to rotate the normals and the planes:

```
for (int i = 0; i < m_entities.size(); ++i)
    {
        glm::mat3 normalMatrix = glm::mat3_cast(glm::angleAxis(glm::radians(6.0f), glm::vec3(0.0, 0.0, 1.0)));

        CollisionPlane* p = (CollisionPlane*)m_entities[i]->GetCollisionVolume();
        glm::vec3 normalDivLength = p->GetNormal() / glm::length(p->GetNormal());
        glm::vec3 pointOnPlane = normalDivLength * p->GetDistance();
        glm::vec3 newNormal = normalMatrix * normalDivLength;

        glm::vec3 newPointOnPlane = newNormal * (normalMatrix * (pointOnPlane - glm::vec3(0.0)) + glm::vec3(0.0));

        p->SetNormal(newNormal);
        float newDistance = newPointOnPlane.x + newPointOnPlane.y + newPointOnPlane.z;
        p->SetDistance(newDistance);
    }

```

I've done the same thing for rotating around X, except changed the `glm::vec3(0.0, 0.0, 1.0)` to `glm::vec3(1.0, 0.0, 0.0)`

m\_entites are basically my physics entities that hold the different collision shapes (spheres planes etc). I based my code on the answer here Rotating plane with normal and distance

I can't seem to figure at all why it works when I rotate around Z, but not when I rotate around X. Am I missing something crucial?

# Answer
You have at least one error. This is incorrect:

```
float newDistance = newPointOnPlane.x + newPointOnPlane.y + newPointOnPlane.z

```

It should instead be:

```
float newDistance = glm::dot(newPointOnPlane, newNormal);

```

Because the "distance" of a plane is the distance along the normal to the plane origin, which is given by the dot product between the normal and the plane origin.

EDIT: Also:

```
 glm::vec3 newPointOnPlane = newNormal * (normalMatrix * (pointOnPlane - glm::vec3(0.0)) + glm::vec3(0.0));

```

Is equivalent to:

```
glm::vec3 newPointOnPlane = newNormal * (normalMatrix * (pointOnPlane));

```

And further, it should just be:

```
glm::vec3 newPointOnPlane = normalMatrix * pointOnPlane;

```

Which is equivalent to:

```
glm::vec3 newPointOnPlane = newNormal * p->GetDistance();

```

Which means:

```
float newDistance = p->GetDistance();

```

Therefore, this is the correct code (you only have to rotate the normals!):

```
    glm::vec3 normalDivLength = p->GetNormal() / glm::length(p->GetNormal());
    glm::vec3 newNormal = normalMatrix * normalDivLength;

    p->SetNormal(newNormal);

```

EDIT 2: Now, you need to rotate and translate the models so they align with the planes:

```
rotation = normalMatrix;
translation = newNormal * p->GetDistance();

```

Your meshes should both have exactly the same data:

```
std::shared_ptr<Mesh> f1 = std::make_shared<Mesh>(GL_LINE_LOOP);
std::vector<Vertex> verts = { Vertex(glm::vec3(-0.5, -0.5, 0.0)),   Vertex(glm::vec3(-0.5, 0.5, 0.0)), Vertex(glm::vec3(0.5, 0.5, 0.0)), Vertex(glm::vec3(0.5, -0.5, 0.0)) };
f1->BufferVertices(verts);
f2 = f1;

```
> 1 votes

---
Tags: opengl, collision-detection, physics, rotation, normals
---


# Question
Title: DirectX RenderTargetTexture bound to both RTV and SRV
After following the 22th tutorial of Rastertek. I and some others on the internet have had an error. Despite following the tutorial to the letter. However, the answers to this error message have been a bit diffuse. So for future reference and if anyone else founds this thread. Lets once and for all, settle this!

When debugging we get this error message:

*ID3D11DeviceContext::OMSetRenderTargets: Resource being set to OM RenderTarget slot 0 is still bound on input!*

*ID3D11DeviceContext::OMSetRenderTargets\[AndUnorderedAccessViews\]: Forcing PS shader resource slot 0 to NULL.*

So, here is some code;

```
   HRESULT Application::RenderToTexture()
    {
        HRESULT hr = S_OK;

        //Set render target to render to the texture inside mRenderTexture
//Inside this func we see this: _deviceContext->OMSetRenderTargets(1, &this->mRenderTargetView, _depthStencilView);
        this->mRenderTexture.SetRenderTarget(this->mDirectX.GetDeviceContext(), this->mDirectX.GetDepthStencilView());
        //clear it
        this->mRenderTexture.ClearRenderTarget(this->mDirectX.GetDeviceContext(), this->mDirectX.GetDepthStencilView(), 0.0f, 0.0f, 1.0f, 1.0f);

        // Render the scene now and it will draw to the render to texture instead of the back buffer.
        hr = RenderScene(); //Using the render target
        if(FAILED(hr))
            return hr;

        // Reset the render target back to the original back buffer and not the render to texture anymore.
        this->mDirectX.SetBackBufferRenderTarget();

        return hr;
    }

```

We need to take a look inside RenderTextureClass (mRenderTexture). It is focused on these membervariables.

```
class RenderTextureClass
{
private:
    ID3D11Texture2D*            mRenderTargetTexture; //This is the root of the issue
    ID3D11RenderTargetView*     mRenderTargetView;
    ID3D11ShaderResourceView*   mShaderResourceView;

```

If we are to understand the answers of others. They say that the RenderTargetView AND the ShaderResourceView is used both at the same time and is then unable to work properly.

Init function;

```
HRESULT RenderTextureClass::Initialize(ID3D11Device* _device, XMFLOAT2 _textureSize)
{
    HRESULT hr = S_OK;

    //Setup RenderTargetTexture
    D3D11_TEXTURE2D_DESC textureDesc;
    ZeroMemory(&textureDesc, sizeof(textureDesc));

    textureDesc.Width               = _textureSize.x;
    textureDesc.Height              = _textureSize.y;
    textureDesc.MipLevels           = 1;
    textureDesc.ArraySize           = 1;
    textureDesc.Format              = DXGI_FORMAT_R32G32B32A32_FLOAT;
    textureDesc.SampleDesc.Count    = 1;
    textureDesc.SampleDesc.Quality  = 0;
    textureDesc.Usage               = D3D11_USAGE_DEFAULT;
    textureDesc.BindFlags           = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
    textureDesc.CPUAccessFlags      = 0;
    textureDesc.MiscFlags           = 0;

    hr = _device->CreateTexture2D(&textureDesc, NULL, &this->mRenderTargetTexture);
    if(FAILED(hr))
        return hr;

    //Setup RenderTargetView
    D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc;
    renderTargetViewDesc.Format             = textureDesc.Format;
    renderTargetViewDesc.ViewDimension      = D3D11_RTV_DIMENSION_TEXTURE2D;
    renderTargetViewDesc.Texture2D.MipSlice = 0;

    hr = _device->CreateRenderTargetView(this->mRenderTargetTexture, &renderTargetViewDesc, &this->mRenderTargetView);
    if(FAILED(hr))
        return hr;

    //Setup Shader resourceview
    D3D11_SHADER_RESOURCE_VIEW_DESC shaderResourceViewDesc;
    shaderResourceViewDesc.Format                       = textureDesc.Format;
    shaderResourceViewDesc.ViewDimension                = D3D11_SRV_DIMENSION_TEXTURE2D;
    shaderResourceViewDesc.Texture2D.MostDetailedMip    = 0;
    shaderResourceViewDesc.Texture2D.MipLevels          = 1;

    hr = _device->CreateShaderResourceView(this->mRenderTargetTexture, &shaderResourceViewDesc, &this->mShaderResourceView);
    if(FAILED(hr))
        return hr;

    return hr;
}

```

So to the question. How do we correct this in the most reasonable manner without breaking everything?

# Answer
You can't have the same texture bound as both an input and an output at the same time. The solution is to explicitly clear one binding before applying the new binding.

In the DirectX Tool Kit tutorial for post-processing:

```
m_d3dContext->OMSetRenderTargets(1, m_rt1RT.GetAddressOf(), nullptr);
// Draw using m_sceneSRV

m_d3dContext->OMSetRenderTargets(1, m_rt2RT.GetAddressOf(), nullptr);
// Draw using m_rt1SRV

ID3D11ShaderResourceView* null[] = { nullptr, nullptr };
m_d3dContext->PSSetShaderResources(0, 2, null);

m_d3dContext->OMSetRenderTargets(1, m_rt1RT.GetAddressOf(), nullptr);
// Draw using m_rt2SRV

m_d3dContext->OMSetRenderTargets(1, m_renderTargetView.GetAddressOf(), nullptr);
// Draw using m_rt1SRV

m_d3dContext->PSSetShaderResources(0, 2, null);

```

To avoid the same warning.
> 3 votes

---
Tags: c++, directx, rendertargets
---


# Question
Title: Creating a unit selection box in Unity (2D)
I've been trying to get my head around how to create a selection box for a selected unit in a 2D top-down type game. When you click on a unit, a small box would appear around that unit based on some sort of box-size.

I do not know/understand how to either calculate the size that box needs to be, draw the box (have an object under the game object that is sized appropriately with the selection box texture?) or how to make the selection box adjust it's size/shape like in this gif: http://i.imgur.com/xY7XW6C.gif

I don't expect anyone here to hand feed me what I need to use, but some idea of how to go about doing this in Unity (starting from the smallest, and most simple thing, like just making the box) would be very much appreciated.

Thanks!

# Answer
> 2 votes
I have done something like this just today. The key idea here is to use the new Unity UI and a world space canvas. Here are the general steps needed to make this work:

1. Create a new canvas, set it to world space. (The size should not matter, but I have only started using the new UI system recently, so I am not 100% sure of that. It works with a size of 0 though.)
2. Create an UI image as a child of the canvas. Make sure that its source image is set to 'Background' (i.e. the background image coming with Unity's new UI. If this is not listed, first create a UI panel. That should add that texture). Now set the image type to 'sliced', uncheck 'Fill Center' and set the color to whatever color you need. You should store this image as a prefab, let's call it 'Selection Box'.
3. Whenever a unit is created, create a new selection box in the world space canvas and set it to be inactive. Store a reference to this selection box in the unit. (Okay, this is the most straightforward approach to this, but associating each unit with its own box may be wasteful. You can do this any other way, just make sure to have a Selection Box available when the unit is selected.)
4. For as long as the unit is selected, set its selection box to be enabled. Update the size of the selection box by getting the RectTransform component and setting the 'sizeDelta' value. I myself am using the 'bounds' field of a Collider2D to get the extents of the rotated sprite, but you can also use the 'bounds' field of the SpriteRenderer.

Good Luck!

# Answer
> 2 votes
Make the texture that you want and attach it to the game object you want it to appear on, size it and everything so it looks how you want. Then uncheck its renderer.

Then in the code for the game object add

```
public GameObject selectionBox;

```

and then drag and drop the box onto the area in the script of the parent so you have a reference to it.

Then in your code for the parent just enable or disable it through code using the reference.

This is essentially the same as Justin Markwell's answer except his doesn't use a direct reference. That will be fine if the selection box is the only sprite renderer, but if you have multiple it might not select the correct one.

# Answer
> 1 votes
Make a texture like this in Paint or Photoshop or something. you can turn this into a sprite and add it as a child of your unit, size it and uncheck spriterenderer then prefab the unit and then add something like this to a OnSelected or OnMouseDown event.

```
SelectedUnit.gameObject.GetComponentInChildren<SpriteRenderer>().enabled=true;

```

there is a bunch of ways to accomplish but this is a very simple way hope it helps

note that the image is just a shape with a transparent center

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


# Question
Title: WebGL (three.js) - rendering object behind camera far plane
I need to have one object that is always visible/rendered (a lens flare, to be exact). I don't want to set the camera far plane to the maximum possible distance between camera and the sun (performance reasons). Are there any tricks to this? Is this even possible? I could obviously play math and update flare's position so it's always no further than a camera far plane at the correct angle but I also want it to change size depending on the distance as well.

If there are some solutions to such a problem I would be very thankful for answers on how it can be done in three.js.

# Answer
> 2 votes
Lens flare is always in front of any thing rendered so you may as well just disable the depth test when you draw it as the last thing.

A sun/skybox can be drawn first with depth writing disabled.

Changing the size is as easy as doing the perspective divide in the vertex shader explicitly and clamping the Z to -1,1. Or instead of putting the far plane at your sun, put the sun at the far plane.

---
Tags: camera, webgl, three.js
---


title: Discrete movements in Phaser

text:
# Question
Title: Discrete movements in Phaser
What is the best approach to let a Phaser.Sprite do discrete movements?

It should continue moving along all possible values, but at the end of a move it must end up on a certain position which will have the following property: **position.x % SOME\_FIXED\_VALUE = 0** and **position.y % SOME\_FIXED\_VALUE = 0**

# Answer
There are many ways to skin this cat, but the easiest may be to **create a doppelganger sprite, constrained to the discrete coordinate space**. That is, make your actual sprite invisible, and set a second sprite that follows the main sprite with discrete movement.

* Make your main sprite invisible: set `Phaser.Sprite.visible` to `false`
* Create a second sprite
* Make the second sprite follow the main sprite in one of your `update` functions:
* From simple integer division, we know that `round(x / y) * y % y == 0`, so set the sprite's coordinates accordingly. Use whatever rounding function is appropriate.

i.e.

```
sprite.x = Math.round(x / SOME_FIXED_VALUE) * SOME_FIXED_VALUE
sprite.y = Math.round(y / SOME_FIXED_VALUE) * SOME_FIXED_VALUE

```

Sample:

http://jsfiddle.net/bwsgdn0v/

I've kept the main sprite visible so you can see what's going on, as you move the main sprite with the mouse. Sprites from http://opengameart.org/content/squares

I consider this approach easiest as you don't have to hack away at any physics routines or override anything, and it plays well with any existing physics code you may use.
> 1 votes

---
Tags: phaser
---


title: 2D graphics - why use spritesheets?

text:
# Question
Title: 2D graphics - why use spritesheets?
I have seen many examples of how to render sprites from a spritesheet but I havent grasped why it is the most common way of dealing with sprites in 2d games.

I have started out with 2d sprite rendering in the few demo applications I've made by dealing with each animation frame for any given sprite type as its own texture - and this collection of textures is stored in a dictionary. This seems to work for me, and suits my workflow pretty well, as I tend to make my animations as gif/mng files and then extract the frames to individual pngs.

Is there a noticeable performance advantage to rendering from a single sheet rather than from individual textures? With modern hardware that is capable of drawing millions of polygons to the screen a hundred times a second, does it even matter for my 2d games which just deal with a few dozen 50x100px rectangles?

The implementation details of loading a texture into graphics memory and displaying it in XNA seems pretty abstracted. All I know is that textures are bound to the graphics device when they are loaded, then during the game loop, the textures get rendered in batches. So it's not clear to me whether my choice affects performance.

I suspect that there are some very good reasons most 2d game developers seem to be using them, I just don't understand why.

# Answer
A strong argument for using spritesheets is that the number of available textures on a graphic card can be limited. Therefore your graphics library would constantly have to remove texture and re-allocate textures on the GPU. It's much more efficient to just allocate a large texture once.

Also consider that texture sizes are usually power of 2. So if you have a 50x100px Sprite, you'll allocate textures with the size 64x128px or in the worse case 128x128px. That's just wasting graphics memory. Better pack all the sprites into a 1024x1024px texture, which would allow 20x10 sprites and you'll only lose 24 pixels horizontally and vertically. Sometimes even sprites of different sizes are combined into one huge sprite-sheet to use the texture as efficient as possible.

**Addendum:** A very important reason to use sprite-sheets is to reduce the amount of draw-calls on your GPU, which can have a notable impact on performance. This has been stated in other answers and I'm adding this for the sake of completeness so that this gets some more visibility.
> 73 votes

# Answer
I'd say the arguement to use would be the ability to render multiple things in a single draw call. Take for example font rendering, without a spritesheet you'd need to render each character with a separate texture swap followed by a draw call. Throw them into a spritesheet and you can render entire sentences with a single draw call (the difference characters in the font being picked out by just specifying the different UV's for the corners). This is a much more efficient way of rendering when a very real overhead of rendering stuff on a lot of platforms is in making too many API calls.

It can also help save space, but it depends on what your packing into the spritesheet in the first place.
> 37 votes

# Answer
Each draw call has a certain amount of overhead. By using sprite sheets you can batch the drawing of things that aren't using the same frame of an animation (or more generally, everything that's on the same material) greatly enhancing performance. This may not matter too much for modern PCs depending on your game, but it definitely matters on, say, the iPhone.
> 12 votes

# Answer
In addition to performance considerations, sprite sheets can be handy when creating the art; each character can be in its own sheet, and you can see all the frames just by scrolling around. It helps me keep a consistent look across all the frames.

Additionally, I code in AS3, and each image file requires a separate embed instruction. I'd rather have a single embed of an entire spritesheet than 24 embeds for all the frames, even if I'm using a separate resource class.
> 7 votes

# Answer
Another reason so use spritesheets with XNA is that with Xbox360 development there's a known issue with slow deploy/load times in relation to the number of files you have in your project. So combining lots of small image files into a single image file will help combat that issue.
> 7 votes

# Answer
I'm not going to mention memory/GPU here, since there's enough answers like that.

Instead, it can clear up your art as you work on it - and after. Instead of having to flick through 10 images to see the walk cycle, you can see all the frames in one go. If you wanted to distribute this, you've only got 1 file to deal with instead of 10.

And then it's also cleaner (from a organizing point of view) to have character.png and enemy.png over characterwalk01 through to characterwalk10, then characterattack01 to characterattack05, and it goes on.
> 5 votes

# Answer
The graphics memory does not have a bloat up **memory management** like file systems on disks; the oposite is the case: it is kept **simple and fast**.

One such simple and fast memory mangement might be like having only one single giant 4096x4096 sprite that is cut in multiple smaller sprites by halfing its width and/or height. (There exists a similar 1-dimensional memory-managing technique, but I forgot the name.) Eventually, Defragmentation has to be performed.

To skip such memory management at **run-time**, developers fill single large sprites with multiple smaller sprites automatically at **compile-time** or even while in the desing-process of the graphics.
> 4 votes

# Answer
Also don't forget the I/O operations it might save you during initialization. If you are loading from a CD drive, each file is an extra I/O call, and might take some time to seek (modern HDD's are about 15 ms per file, CD's maybe 50-100ms?). This can save you a lot of initialization time as only one file has to be fetched. It also allows your OS to cache these I/O operations, in case your application is doing something else (like waiting for GPU).
> 3 votes

# Answer
Other than being more performance efficient, I find it simply easier. It requires a little extra work to make sure your images are always within their bounds when creating the art, but it's a lot easier being able to see all the images you're dealing with at the moment.

It's also easier to code, in my opinion. I simply have an array of objects like:

```
sheet = {
    img: (the actual image),
    rects: [
        {x:0, y:0, w:32, h:32},
        {x:32, y:0, w:32, h:32},
        {x:64, y:0, w:32, h:32}
    ]
};

sheets.push(sheet);

```

Then for each item I give it two values, sheet and rect. The sheet would be the index in the array of objects, and the rect would be the index in that sheet's rects array.
> 0 votes

---
Tags: xna, 2d, graphics-programming
---


title: Accelerometer bike game rotation help

text:
# Question
Title: Accelerometer bike game rotation help
Hi I've been making a game for the last few months and not sure what to do.

It's a 2d bike game and I want the rotation done with accelerometer, at the moment To test on computer I've set the rotation up as if left is hit transform.rotate to the left but because gravity my bike will not stay doing a wheelie.

Is there another way to do this can I just set up that the rotation of the bike is equal to the screen rotation? Or do I need the bike to stay in the air first and then when rotated right it goes right ect?

Really not sure and have been stuck on this for a month noob to unity too thanks

# Answer
> 2 votes
The way I've handled issues like this in the past is to keep track of a "desired angle/orientation", and then each FixedUpdate I apply a torque to nudge the object toward that orientation.

You might implement this with a negative feedback control system, or error-controlled regulation, where as the bike deviates further from the goal, you apply greater and greater corrections to push it back. Here's one way this might look:

(in 2D)

```
// This controls the maximum torque ever applied.
// without this, a bike far from the desired angle can be twisted too violently.
public float maxTorque;

// This controls how quickly the correction ramps-up as the bike drifts from the target.
// Higher values will keep it locked tighter, but it also might appear to jerk or vibrate.
public float rotationStiffness;

// This member variable will track the desired orientation of the bike.
// Let's keep it in the range 0 to 360 degrees, to match rigidbody2D.rotation
float desiredRotation;

void FixedUpdate()
{
   // Find the angular correction needed to get back to the desired rotation.
   float correction = desiredRotation - rigidbody2D.rotation;

   // Wrap the angular correction
   // (We'd rather turn 170 degrees counter-clockwise than 190 degrees clockwise)
   if(Mathf.abs(error) > 180f)
       correction -= Mathf.sign(correction) * 360f;

   // Calculate a scaled torque based on the correction & public parameters.
   float torque = Mathf.clamp(correction * rotationStiffness, -maxTorque, maxTorque);

   rigidbody2D.AddTorque(torque);
}

```

This is a bit different if you're using 3D physics, since a rotation is more than a single number. You could extract the rotation angle and do the same thing, but here's a similar method using vectors:

```
// Keep maxTorque & rotationStiffness as before.

// This member variable will track the desired orientation of the bike.
// This time we're storing it as a direction we want the bike's "forward" to point.
Vector3 desiredForward;

void FixedUpdate()
{
   // You might need to flip the order of transform.forward & desiredForward here.
   // It's easy to get mixed up with left-vs-right-handed coordinates, so this is a guess.
   Vector3 torque = rotationStiffness * Vector3.Cross(transform.forward, desiredForward);

   // If your body's rotation is not constrained on the other two axes,
   // you may want to project this torque onto the pivot axis to avoid wobble.

   // Ensure our maximum torque is respected.
   if (torque.sqrMagnitude > maxTorque * maxTorque)
       torque *= maxTorque/torque.magnitude;

   rigidbody.AddTorque(torque);
}

```

# Answer
> 1 votes
take a look at Elastomania. I guess this is the game you want to replicate. there are some people with unbelievable skill at this game, check youtube :)

Anyway you need to take a look at inertia tensor tool. its a matrix that characterizes the solid's inertia parameters. http://en.wikipedia.org/wiki/Moment\_of\_inertia

In your case there are many terms that simplify because you are in 2D. Also you are not required to realistically calculate the second area moment http://en.wikipedia.org/wiki/Second\_moment\_of\_area, this is done from geometry by integrating units of surface multiplied by their mass density. You can just estimate some value and create a small physics integrator that will do the simulation in time. Your problem is 1D for the rotation because you have only one axis to care about. But you need also to solve contacts at the same time. It means you will need to apply forces at contact points, those forces are evaluated by the collision intersector, it will give you a list of impulses that correspond to the force you need to apply to avoid penetration.
If you add all forces you get a "net force" http://en.wikipedia.org/wiki/Net\_force and for the torque you need to go through a little cross product and sum the result http://en.wikipedia.org/wiki/Torque. This will give you the "net torque" at some point you define as being the rotation center. I suppose it could be any point in fact. Just don't forget to add the gravity force from the gravity center (usually geometrical center) of your bike and also sum in into the net torque.

---
Tags: unity, rotation, rotate
---


title: SceneGraph understanding

text:
# Question
Title: SceneGraph understanding
So far i can understand that it is a tree data structure consisting of multiple nodes.

If i draw an entity in world without any scenegraph, e.g. I have an object "Aircraft" which inherit from object "Entity"... so far so good i guess.

But what if i use scenegraph? if i draw an entity in world with scenegraph, i still have an object "Aircraft" which inherit from object "Entity" but now my object Entity inherit from a object "Node"? what is the diference? i still move my aircraft as the same without a scenegraph? or do i need to move node instead of aircraft?

# Answer
You're confusing Entity Heirarchy with Scene Heirarchy from what I can tell.

It Works something like like this:

```
class Scene
{
   Collection<Entity> Objects;
}

class Entity {
     Collection<Entity> Objects;
}

class Bullet : Entity { }

class Aircraft : Entity {
   void Shoot() {
       Objects.Add(new Bullet())
   }
}

```

then in game code ....

```
CurrentScene = new Scene();

CurrentScene.Objects.Add(new Aircraft());

```

Not the best example I admit, but I think it covers the idea based on your explanation of the problem.

I took this a step further when Iwas building engine code and had something like:

```
interface IEntityContainer
{
    Collection<Entity>
}

class Scene : IEntityContainer { ... }
class Entity : IEntityContainer { ... }

```
> 2 votes

# Answer
To elaborate on what Wardy said, there are some really important object attributes that are integrally related to this tree structure and could not be expressed as easily if the objects were merely stored as a "scene list". For example, take position and scale. Normally moving an object will also move the children. This is because each object stores its scale as an offset from a parent. It's very convenient, and it would not be as straightforward if objects were stored in a different way. Scale is similar--if an object is marked as scale=50%, all its children will be also.

The king of attributes is whether an object is active--should it be updated? Should it be rendered? So if you set a character inactive, his skeleton, his guns, his hair, etc., will all become inactive. (This isn't true for all game engines.) But an intelligent game engine can assume that if an object (the character) is disabled, the child objects underneath have no need of continuing logic. The hair doesn't need to blow in the breeze. And because of this tree structure, you don't need to update the attributes of all the children. The way Unity expresses this is having two ways to look at object activity: "activeSelf", and "activeInHierarchy". The former is the "active" bit, and the latter is whether it's *really* active (based on its own state, and the state of its parent object).

(I meant to post this as a comment, but I accidentally typed too much because the text box didn't tell me to stop! Well, I was typing in the wrong text box. ;-) )
> 1 votes

---
Tags: scene-graph
---


# Question
Title: SDL & OpenGL - Artifacts when multisampling
Im trying to render a model with anialiasing using OpenGL and SDL, but when I do I get strange artifacts.

When I render with antialiasing disabled everything looks fine.

When antialiasing is enabled I get white dots in edges of the model.

I'm using a Nvidia Geforce 320M graphics card and enabling the display as well as the multisampling with this code

```
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
glEnable(GL_MULTISAMPLE);

```

This is the fragment shader:

```
#version 330

#define MAX_NUM_LIGHTS 4

in vec3 normal0;
in vec3 pos;

out vec4 FragColor;

struct LightSource
{
    vec4 position;
    vec4 ambientColor;
    vec4 diffuseColor;
    vec4 specularColor;

    // attenuation parameters
    float attConstant;
    float attLinear;
    float attQuadratic;
};

struct Material
{
    vec4 ambientColor;
    vec4 diffuseColor;
    vec4 specularColor;
    float shininess;
};

uniform LightSource light[MAX_NUM_LIGHTS];
uniform Material material;
uniform vec3 viewPos;
uniform int numOfLights;

// function declarations
vec4 calcDirLight(LightSource light, Material material, vec3 normal, vec3 viewDirection);
vec4 calcPointLight(LightSource light, Material material, vec3 normal, vec3 fragPos, vec3 viewDirection);

void main()
{
    vec3 viewDirection = normalize( viewPos - pos );
    vec4 result = vec4(0.0f);

    // Loop over all lights
    for(int i = 0; i < numOfLights; i++)
    {
        // Directional light
        if( light[i].position.w == 0.0f )
        {
            result += calcDirLight( light[i], material, normal0, viewDirection);
        }
        // Point light
        else if ( light[i].position.w == 1.0f )
        {
            result += calcPointLight( light[i], material, normal0, pos, viewDirection);
        }
    }

    FragColor = result;
}

vec4 calcDirLight(LightSource light, Material material, vec3 normal, vec3 viewDirection)
{
    // Properties
    vec3 lightDirection = normalize( vec3(light.position) );
    vec3 reflectDirection = reflect( -lightDirection, normal);

    // Ambient component
    vec4 ambientComponent = light.ambientColor * material.ambientColor;

    // Diffuse component
    float diffuseReflection = clamp(dot(normal,lightDirection), 0.0, 1.0);
    vec4 diffuseComponent = diffuseReflection * light.diffuseColor * material.diffuseColor;

    // Specular component
    float specularReflection = pow( max( dot( viewDirection,reflectDirection ), 0.0 ), material.shininess );
    vec4 specularComponent = specularReflection * light.specularColor * material.specularColor;

    return ( ambientComponent + diffuseComponent + specularComponent);
}

vec4  calcPointLight(LightSource light, Material material, vec3 normal, vec3 fragPos, vec3 viewDirection)
{
    // Properties
    vec3 lightDirection = normalize( vec3(light.position) - fragPos );
    vec3 reflectDirection = reflect( -lightDirection, normal);
    float distance = length( vec3(light.position) - fragPos );
    float attenuation = 1.0f / ( light.attConstant + (light.attLinear * distance) + (light.attQuadratic * (distance * distance)) );

    // Ambient component
    vec4 ambientComponent = light.ambientColor * material.ambientColor * attenuation;

    // Diffuse component
    float diffuseReflection = clamp(dot(normal,lightDirection), 0.0, 1.0);
    vec4 diffuseComponent = diffuseReflection * light.diffuseColor * material.diffuseColor * attenuation;

    // Specular component
    float specularReflection = pow( max( dot( viewDirection,reflectDirection ), 0.0 ), material.shininess );
    vec4 specularComponent = specularReflection * light.specularColor * material.specularColor * attenuation;

    return ( ambientComponent + diffuseComponent + specularComponent);
}

```

Can anyone point me in the direction of what might be the problem?

# Answer
> 2 votes
As pointed out to me, normalizing normals in the vertex shader and then passing them to the fragment shader doesn't ensure they are normalized after being passed. By only passing the normals in the vertex shader and then normalizing them in the fragment shader the problem was fixed.

Another way to fix the error is centroid attribute interpolation between the vertex and fragment shader. This might only be considered a quick-fix however, since the real issue was not normalizing the normals in the fragment shader.

---
Tags: opengl, sdl
---


title: GUI.Box z-index for mouseover

text:
# Question
Title: GUI.Box z-index for mouseover
So I am drawing an inventory with slots like so:

```
private void DrawItemSlotAndAttachActions(Item currentItem, Rect slotRectangle, Event e, int itemSlotPosition)
    {
    if (!(currentItem is EmptyItem))
        {

            GUI.depth = 0;
            GUI.DrawTexture(slotRectangle, currentItem.Icon);
            if (slotRectangle.Contains(e.mousePosition))
            {
                _tooltip = currentItem.CreateTooltip();
                _showTooltip = true;

                DragAndDropItem(e, itemSlotPosition);
                UseConsumable(e, currentItem);
            }
        }
        else
        {
            DropItemOnEmptySlot(slotRectangle, e, itemSlotPosition);
        }
    }

    public void OnGUI()
    {
        _tooltip = ""; //reset every time...can this be done better?
        GUI.skin = Skin;

        DrawItemSlotAndAttachActions(.....);
        ShowTooltip();
    }

    private void ShowTooltip()
    {
        if (_showTooltip)
        {
            GUI.Box(new Rect(Event.current.mousePosition.x, Event.current.mousePosition.y, 200, 150), _tooltip,
                Skin.GetStyle("Tooltip"));
        }
    }

    private void HideToolTipWhenEmpty()
    {
        if (string.IsNullOrEmpty(_tooltip))
            _showTooltip = false;
    }

```

In here I have the problem that when I hoven over an item, all the boxes that are drawn **after** are on top of my tooltip Box.

How can I make sure that the box is drawn **on top** of all the rest?

Screenshot:

As you can see, it is still behind the rest of the buttons.

# Answer
> 1 votes
Look into GUI.depth

The sorting depth of the currently executing GUI behavior. It's the equivalent of CSS's `z-index`.

Set this to determine ordering when you have different scripts running simultaneously. GUI elements drawn with lower depth values will appear on top of elements with higher values (ie, you can think of the depth as "distance" from the camera).

Your box should have the **lowest** `depth` value.

```
// slots
GUI.depth = 0;
GUI.DrawTexture(...);

// box; to be rendered on top of the slots
GUI.depth = -1;
GUI.DrawTexture(...);

```

---
Tags: unity, depth
---


title: Unity: Make camera center of screen

text:
# Question
Title: Unity: Make camera center of screen
Here is my camera setting:

With this setting, when I run, game is not center of screen:

Please tell me how to fix this.

thanks :)

# Answer
> 5 votes
Your Camera is static, which is OK in your case. In order to make it display what you want, you just need to tweak it's position.

The screen size for this specific project is 7 x 7. For the camera to show it properly you need to set it's position to middle. And that's 3.5 x 3.5.

Update Main Camera's position to **3.5 X** and **3.5 Y**.

Position in the tutorial where the Camera position is set: http://youtu.be/7NYXBUWmFvU?t=3m

# Answer
> 1 votes
In most games you will want to make the camera follow the player. A good way to do this is to make the camera a sub-object of the player. You can do this in the hierarchy window by dragging the `Main Camera` game object onto the player object, so it is listed below it with a slight indentation. That way the transformation coordinates of your camera object will always be relative to the player, not to the world origin.

Alternatively, when you would like the camera to be in fixed position instead, set the x- and y-position of your camera to half the x- and y- size of your scene.

---
Tags: unity
---


title: Why are Texture2d arrays so expensive?

text:
# Question
Title: Why are Texture2d arrays so expensive?
I'm building a 2d engine in C# and I have several static sprites that have multiple color variations. Ok, easy enough, I create the Texture2D images at start time, then stuff them into an array, and use an array index at draw time.

This caused a surprising performance hit for me.

I made a quick simple test app where it draws the same 32x32 texture 1,000 times. The baseline call takes 1.0001ms

```
spriteBatch.Draw(testTexture1, new Vector2(100, 100), null, Color.White, 0, new Vector2(16, 16), 1f, SpriteEffects.None, 1);

```

But this version, takes 11.0011ms!

```
spriteBatch.Draw(testTextureArray[i], new Vector2(80, 80), null, Color.White, 0, new Vector2(16, 16), 1f, SpriteEffects.None, 1);

```

Ten fold longer! Same performance with a List.

Why is this and is there anything I could use instead of an array?

# Answer
If your `testTextureArray[i]` is pointing to the same texture, you should have the same performance, but if not, then you are just hitting a design restriction of SpriteBatch.

Most implems of SpriteBatch I'm aware of (at least, XNA, SharpDX, Paradox, DirectXTk... though, don't know for sure about MonoGame...) are trying to batch draws with the same consecutive texture (see for example here, DirectXtk the C++ equivalent of SpriteBatch is assuming the same here \- look at method `void SpriteBatch::Impl::FlushBatch()`). If you switch between textures, the code path is much slower so this is not recommended to use SpriteBatch in this way.

As suggested by @Shiro, SpriteBatch is usually more efficient if you have packed all your sprites in a sprite sheet and use this same texture in your whole batch between Begin/End.
> 1 votes

---
Tags: c#, textures, monogame
---


# Question
Title: Unity 4.6: why Image object doesn't stretch all sides of canvas
I insert a canvas, after that, I insert an image at center. Then, I want to stretch this image over this canvas, so I choose last option as below:

But the image doesn't stretch to fit the canvas, as you see: (in fact, image object doesn't change anything)

Please tell me how to make this image stretches over the canvas.

thanks :)

# Answer
> 3 votes
As the top notification says, in order to achieve the desired effect, you need to hold down **ALT** and **SHIFT** when clicking the stretch icon.

More info: http://docs.unity3d.com/Manual/class-RectTransform.html
Video: http://unity3d.com/learn/tutorials/modules/beginner/ui/rect-transform

---
Tags: unity
---


# Question
Title: Generate islands/continents with simplex noise
Managed to get something like this using a simplexnoise port i made from the original javacode to php:

Used some tips from other post:

Understanding Perlin Noise

basically, lowered the frequency to get more flat terrain.

Now, how could i foce the map to be a huge Pangea? If i manualy set for example, if (x \< 5) set height = 0 (water), when i normalize all the map to 0...1 the value 0 get higher (as my simplexnoise function returns -1 1). If i force it to -9999, does not work either.

Has to me something elegant to sneak into the height generation code to make the borderline squares, water.

With MDP algorithm i could seed the sides of the map to -500 for example and then pretty coast would be made, but with simplex/perlin does not seem the case as i can not enter pre-seeded cells with artificial heights.

Any tips?

# Answer
> 3 votes
Maybe I'm not seeing the whole picture, but can't you just the apply the border (by setting those values to 0 / water) **after** normalizing?

And I suppose you're normalizing correctly e.g: `[0,1] = ([-1,1] + 1) * 0.5`

Some aditional ideas... last time I generated something like this, I used probabilities and a random number generator.

I simply choose the center of my island, and a maximum radius. Then for each pixel, there was a probability of it being land or water based on its distance from the center and the maximum radius. At the end I also applied a few post processing passes, to detect oceans and remove inner lakes, etc.

Maybe you could keep your current simplex noise approach, but afterwards do a similar post-process on your map in order to make it more "continent-like".

This could consist of going through every pixel, and depending on a random probability convert some of them back to water (by setting the value to 0) e.g. 100% chance of water at the border and decrease to 0% about 20 pixels in). This way it would still look kinda organic.

You could then apply a second pass to remove small islands or something, if you wanted.

Just for reference, using probabilities generates shapes such as this (of course this is in a much lower resolution that yours because it's tile based, not pixel based):

**Edit**

Even if you don't want to use probabilities (which are just there to give a little extra bit of variation) you'll still need to work with a *radius* and combine it with your perlin noise in order to get something that looks like an island.

The very least you need to do is take your perlin noise, and apply a radial filter to it so that pixels closer to the border become water. Using a radius will be better for sure than your idea of doing for instance "x \< 5 becomes water".

And another thing you could do is ignore the height values in your perlin noise for now. Set a thresold and let the result decide *only* where there's land and where there's water, nothing else.

You can add mountains as a second pass (e.g by measuring the distance from the coast on each pixel). Then add some lakes, rivers, different biomes in separate passes. Your perlin noise doesn't need to provide all the information at once.

I just found an old link I used before when I worked with this:

http://www-cs-students.stanford.edu/~amitp/game-programming/polygon-map-generation/

I'm sure you'll enjoy it.

# Answer
> 0 votes
I think you're making the mistake of thinking that you can produce this with a single perlin function.

Depending on the result you are trying to achieve you have 2 options:

1. reduce the frequency on that perlin (might be good enough for you)
2. do it the pro way ...

**The pro way**

I found the reality is waaaay more complex for "realistic" planets.

It seems the best results are achievable through using a stack of noise functions in a tree like fashion.

Typical example might be something like this: http://libnoise.sourceforge.net/tutorials/tutorial8.html

I built a basic tool to try this out for my own use.

I good start point might be to try perhaps a module stack like this ...

billow \> scale \> clamp = result

That should get you "island like output" with a binary result for a given x,y which you can then feed in to other modules to get the desired final value. Playing with the frequency settings on your billow should then allow you to adjust the size of the islands up to the point of generating continents.

What to do with the basic map:

I took the result of that and fed it in to a select module to determine if I should pull from an ocean module (outputs very low values) or a continent module (outputs from sea level up values, with region a region module for things like plains, mountains, ect).

My model isn't as complex as the version they have on the libnoise site but gets reasonable results in under a minute for a reasonably large planet on a single thread on my cpu.

I'm still improving my generator stack and also threading the generation in to chunks to improve the performance.

Using the gpu is another option, not sure if there's a library available for that though so you might need to code a perlin lib for your gpu yourself if that's the route you want to go down.

---
Tags: algorithm, maps, heightmap, perlin-noise
---


# Question
Title: Remove previous scenes from memory in Unity 3d
I'm making a game in unity3d which I optimized as much as I can.

I've made different levels in each scene.

After a few scenes the game starts to lag on mobile devices. And works smoothly if application is restarted and game is continued from last scene .

How can I clear previously loaded scene in Unity3d or overcome the problem I mentioned above ?

# Answer
By default, when loading a scene, everything in the previous scene is **destroyed**.

However, some resources might remain loaded. Try use Resources.UnloadUnusedAssets.

In order to prevent a GameObject from being destroyed when a new scene is loaded, you can call DontDestroyOnLoad. Make sure that your code doesn't abuse this functionality.
> 1 votes

---
Tags: unity
---


# Question
Title: How to synchronize damage with attack animation in a RTS game?
I have been working on a RTS game in unity and did damage deal through code and a timer but it does not fit with the animations quet well. The damage is dealt in the beginning of the animation and about 4 attacks it fits perfectly and after more 4 attacks the damage is dealt delayed after the animation.

My big question is if hitboxes would be a good answer to solve this problem or is it to preformance heavy?

# Answer
I think the approach you are probably looking for is to trigger damage based on some event, which is keyed to a particular time or frame in the animation. I'm not sure exactly how you can set this up in your case as I'm not familiar with the specific tools etc. but the general concept would be:

1. For each attack animation, define at which frame / time offset the damage is applied.
2. Watch for this event happening in code, or check each frame after starting the animation to test if the specified time has past.
3. When the event is triggered or the time past you can then apply the damage. At this point you should know everything you need to such as: The unit attacking (hence it's damage and stats), the unit being attacked (hence the appropriate target and it's defenses etc) so you can apply the damage appropriately.

Some advantages of an approach like this are:

* You can pick the damage event time to coincide with the the sword swing, or the muzzle flash etc. This signifies the "active" or "hit" portion of the animation so you can tweak it to make it look right. Potentially you can also manage DoT attacks, or attacks which persist for multiple frames in a similar way by recording a time period that the attack is active, though you then need more complex code to handle how multiple hits to the same unit are processed.
* It's a fairly light system and should not need much overhead (in code or cycles). If your units are already capable of attacking each other then you already have all the targeting information, and presumably the damage calculation setup. All you need to incorporate is the timing aspect, which should be driven from the animation.
* It's data driven (either via the animation, or easy to make so via your game files), so should be easy to tweak / change over time as you iterate on your units. This also helps for modding etc.

Having written a hitbox system myself from scratch, I'd say that it's almost certainly overkill for a game like you have described, certainly as a first iteration. There is a lot more overhead in terms of code (and performance) to manage life-cycle of hit/hurtboxes and checking for their intersections.

They do give good results, and can be fairly straightforwards if you limit the hitbox shapes permitted to rectangles, but I'd start simple and work up as you need it.
> 2 votes

# Answer
I can see several issues:

1. You should probably deal the damage at the *end* of the animation. That way, if the damage causes the opponent to die, the animation is done and doesn't keep waving the sword over a dead body. If you can, break your animation up into several steps and deal the damage in several smaller increments, and just stop dishing out damage once the opponent has died.
2. The secret behind animation timing is to self-correct while animations are playing and equate animations with actual time stamps. I'd expect Unity to do that for you already. What one usually does is decide on a frame rate (e.g. 24fps) and a start time, and then to periodically (e.g. from a timer or a display link callback, vertical blanking interrupt or whatever your platform offers) call your drawing code. The drawing code now doesn't draw the *next* frame, but rather, based on the difference between the start time and the current time, draws the frame that is scheduled to be drawn right now:

```
currentFrame = (currentTimeSeconds -animationStartTimeSeconds) / framesPerSecond

```

This means that on a slow machine, gameplay will still have the same speed, though you may get dropped frames.

The advantage of this is that you can now use the same mechanism to schedule when how much damage is dealt and when the animation should end. If your timers drift, you just run them a little more often, and they will draw the right frame even if they skip one frame.
> 0 votes

---
Tags: unity, 3d, animation, rts
---


# Question
Title: Changing the texture filtering methodology within the same SpriteBatch Begin/End pair
How would I go about using changing the texture filtering method being used within the same SpriteBatch Begin/End pairing?

I have this code so far.

```
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null, null);

spriteBatch.Draw(PixelArtTexture, new Vector2(x, y), null, Color.White, 0f, Vector2.Zero, new Vector2(8, 8), SpriteEffects.None, 0f);

spriteBatch.End ();

```

This draws a pixel art texture using point filtering, however I want to draw another texture using linear filtering, so how would I do that?

# Answer
> 1 votes
So long as the `SpriteSortMode` is `SpriteSortMode.Immediate` you can make alterations to graphics device in between draw calls which allows you to change the `ScissorRectangle`, `RasterizerState`, `SamplerStates`, ect...

Of course you lose the performance optimization from the batching; however, it is sometimes worth it if the alternative is creating many begin/end pairs.

For Example

```
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, null, null, null);
spriteBatch.Draw(PixelArtTexture, new Vector2(x, y), null, Color.White, 0f, Vector2.Zero, new Vector2(8, 8), SpriteEffects.None, 0f);

//Changing the SamplerState
GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;
spriteBatch.Draw(PixelArtTexture, new Vector2(x, y), null, Color.White, 0f, Vector2.Zero, new Vector2(8, 8), SpriteEffects.None, 0f);

spriteBatch.End();

```

The first Draw call would use `SamplerState.PointClamp` and the second draw call would use `SamplerState.LinearWrap`.

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


# Question
Title: maps in a multiplayer diablo clone - unity3d
I'm messing around with unity3d free, trying to figure out if i can get away with using its readymade graphic engine. I have some problems figuring out how maps should be implemented/handled

(the graphics are 3d, like diablo, but essentialy game is only X/Y movement)

Case 1. Model a "3d" map within Unity scenes, then model a 2d version of it for serverside calculations (line of sight, positioning, movement and spawning of objects). How to keep them in sync the easiest? Are there any tools for this purpose?

Case 2. Feed a tile based map to Unity client, making it render it from small pieces (tiles). Essentialy use the 2d server version to render the pretty 3d client version. Is that possible at all within unity?

I would love to be able to generate terrain randomly, so solving case two would be most beneficial...

Probably both my cases are a good deal off the "correct" approach, so please give me some hints on the industry standards ;-)

# Answer
> 1 votes
Case 1: unity has built in networking code to handle this in full 3d if need be.

Case 2: there are likely a ton of solutions to this already on the unity store for cheap or free.

Personally if i was building diablo I would do something like this:

When kicking off a new game my custom server would pick a random "seed" value. Any clients that join the game would be sent this seed value.

Using the seed value I would use a 2d perlin / simplex noise based generator to build the tiles / chunks of the map that are in view and generate more as needed.

All clients would then be able to gen the same map and not need to have map data sent from server.

I would then add unities built in networking scripting to any moveable object I choose to add to my game so all clients in the same area see the same behaviour from them.

Seems like a pretty standard unity game to me.

---
Tags: unity, maps, mmo, server
---


title: Export Spriter animations to Unity

text:
# Question
Title: Export Spriter animations to Unity
I want to use bone animations in my 2D game for Unity (5.0 beta). I am trying Spriter. Apparently, it has no official Unity support. There was some guy, back in 2014, who posted a plugin to convert Spriter files to Unity prefabs here: http://brashmonkey.com/forum/index.php?/topic/3365-spriter-for-unity-43-updated-integrated/.

However, the plugin does not seem to work (perhaps it is because I am using 5.0 beta).

There are deprecated lines, like

```
AnimationUtility.SetAnimationType(animClip, ModelImporterAnimationType.Generic);

```

Or

```
 UnityEditor.Animations.AnimatorController.AddAnimationClipToController(controller, animationClip);

```

If you remove them, of course it won't be able to properly export your files.

So my question is: is there a reasonable to use Spriter animations in Unity? I know I could just export to a spritesheet, but I was hoping to use bones for super fluid animations (I have several characters so I don't really want to make lots of spritesheets). Or perhaps there is a better bone-based solution for 2D animation in Unity?

# Answer
This is one of the problems with early adoption - third party extensions may not catch up right away.

The way I see it, you have two options:

1. Use Unity 4.x until an extension becomes available for 5.
2. Update the extension's code yourself.

If your heart is set on using Unity 5, then you'll have to take care of these issues on a case by case basis. I suspect that static methods such as `AnimationUtility.SetAnimationType` have been moved to the applicable object, ie `AnimationClip`, in order to align with OOP principles. However, I don't have the Unity 5 beta to check, and it seems the documentation hasn't been updated for 5 yet.

**Update:** According to this, Spriter2Unity has been updated to be compatible with Unity 5.
> 1 votes

---
Tags: unity
---


# Question
Title: How should I choose between Vec3 and Vec4?
I find myself torn between using Vec3's vs Vec4's for representing position, directions, etc in my non-gpu code. I see the obvious benefit of using Vec3s for stuff like data in buffers, to more tightly pack mesh data, reducing memory used.

The primary motivation for switching from Vec3 to Vec4 is to reduce the tedius conversions back and forth. For example the math library I am using (GLM) only lets mat4's multiply with vec4's.

I realise it dosn't make sense to have a fourth component in say a direction vector, and to make the distinction between say a position and a direction vector becomes more important.

It's not a big issue, but nonetheless I am curious is there any significant pros or cons between using vec3's or vec4's? What makes the most sense to other users?

# Answer
> 2 votes
Use the smallest type that makes sense.

3-components vectors are smaller, but may involve "overhead" when converted to 4-component vectors for some operations. 4-component vectors, on the other hand, are larger and thus have some space "overhead."

In most cases "overhead" in either case is *negligible*. However, the additional storage taken up by a 4-component vector is not negotiable. It's always there; the additional conversion required of a 3-component vector can be deferred or amortized in a lot of cases, and doesn't happen constantly (or if it does, then you've found a scenario where you should be using the larger type). Plus, it is far more likely to be optimized into a complete non-issue.

So you should evaluate the context in which you are going to use the types, and pick the type that will achieve the most optimal storage/runtime overhead for the majority of the use cases, *and* which also represents the data in the most accurate fashion for the use cases involved.

If you don't need four components, don't store four components. Wait until that is a demonstrated *problem* before worrying about it further.

---
Tags: c++, directx
---


# Question
Title: How do I draw a line from a set of points in unity to use as terrain in a 2D game?
I'm trying to make a 2D game in unity. My terrain is randomly generated and what I'm trying to do is make a bunch of points with different x coordinates and then draw a line through them to use as my ground/terrain.

Originally I wanted to make a polygon out of the points by specifying two additional vertices which would basically be the camera bounds and fill the whole thing in, but I'm not sure that's feasible, so I'll settle for just having a line as a platform.

How would I go about doing this?

# Answer
> 0 votes
I see two different solutions in your case:

1. The easy one: take a look at LineRenderer
2. The "hard" one: build your own mesh

---
Tags: unity
---


# Question
Title: How to deal with events in a game with multiple players, in Unity?
As I'm developing our game I have asked myself a couple times "When we have more than 1 player, how will I ensure events from player A do not crossover to player B?"

As an example, lets say player A clicks on a unit. This publishes an event with data on the click location, the type of object it is, and the player that clicked. This can be received by lets say a selection manager script that just keeps track of what is currently selected for that player.

The problem now, is that this event is received by every player. Every player will receive this event and try and select that object, and perform various tasks along the way.

Is there a method of programming in unity to ensure that an event is only subscribed to by classes that have the same player component referenced (only the appropriate players methods will be added to the invocation list of delegates under the player)? Or will I just need to create a check at the subscribers to these events to only accept the event data if it's the same player?

ie.

```
if ( RClickEventArgs.Player.GetInstanceID() == player.GetInstanceID()) {}

```

Edit: For clarity. Here is an example event.

```
public delegate void RightClickHandler(string clickType, RClickEventArgs e);
public static event RightClickHandler RightClickEvent;
private void RightClick()
{
    if(Input.GetMouseButtonDown(1))
    {
        if (userInput.isMouseOnScreen && !EventSystem.current.IsPointerOverGameObject())
        {
            GameObject hitObject = inputValidations.FindHitObject();
            Vector3 hitPoint = inputValidations.FindHitPoint();
            hitPoint.z = -1;

            if (hitObject && hitPoint != ResourceManager.InvalidPosition && hitObject.name != "Ground")
            {
                RightClickEvent("Object", new RClickEventArgs(hitObject, hitPoint, player));
            }
            else if (hitObject.name == "Ground")
            {
                RightClickEvent("Ground", new RClickEventArgs(hitPoint, player));
            }
        }
    }
}

```

When an object is clicked an event is published with relevant info on what was clicked. There are subscribers to this event using "MouseClickEvents += YourMethodNameHere;". This works as intended. However, since two players will have the same scripts as components this creates an issue where the 2nd player's scripts also add themselves to the invocation list of player 1's delegates, and vice versa (as far as I know, I don't know how to check what is in the invocation lists). So each player receives their own events, and the events of the other player.

If I have a fundamental misunderstanding of a concept here, please let me know.

# Answer
I don't what your code architecture looks like, but you will have to make this check at some point.

The simplest way to do this, imho, is to be sure that the local player only receive his own events, so, be sure to make him register to only his event.

You say that, at click, you know who has clicked. Why don't you just send the event to this specific player. If the, let's say, `click_event` object contains a `player` object, you just have to use it to only warn the specific player.

```
click_event.player.OnClickEvent(click_event);

```

**EDIT**

After your edit, it's now clearer.

You will have to check the sender in your callback method. Note that you often want to actually "display" other players actions. In RTS you sometimes want to show who is selecting what or who is clicking on what, even if you don't want to call the action code, only the UI code.

So if `OnRightClickEvent` has subscribed to `RightClickEvent` you would have something like :

```
void OnRightClickEvent(GameObject hit_obj, Player player)
{
   // SHOW ACTION UI
   // ... like mouse movement and click on the hit_obj ...
   // ... show hit_obj UI FX ...

   // HANDLE CLICK CODE ONLY FOR THE GOOD PLAYER
   if ( player == local_player )
   {
       // ... do what you want to do ...
   }
 }

```
> 1 votes

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


# Question
Title: AndEngine Scoreloop - java.lang.IllegalStateException: you are not calling from the main thread context
I am a very novice android developer but also created a game using andEngine successfully. Now I want to integrate Scoreloop and everything is fine with Leaderboard view and TOS view, except I am having hard time submitting scores from a game scene. I implemented OnScoreSubmitObserver in the main BaseGameActivity (GameActivity). I used the following line inside the onCreateEngineOptions method:

```
ScoreloopManagerSingleton.get().setOnScoreSubmitObserver(this);

```

I also declared the override method perfectly inside GameActivity as mentioned in the scoreloop tutorial:

```
@Override
public void onScoreSubmit(int status, Exception error) {
    // TODO Auto-generated method stub
    //Calls the ShowResultOverlayActivity. Make sure you have modified the
    //AndroidManifest.xml to reference this overlay class.
    startActivity(new Intent(this, ShowResultOverlayActivity.class));
}

```

Now I want to submit score from inside a scene using the following line:

```
ScoreloopManagerSingleton.get().onGamePlayEnded(score, null);

```

But this shows the following error:

```
java.lang.IllegalStateException: you are not calling from the main thread context

```

I also tried implementing OnScoreSubmitObserver on the scene class and tried calling each line mentioned above inside the scene class using "activity" instead of "this", as "activity" is an instance of the GameActivity. but it also shows the same error. Please help.

# Answer
Create a Runnable object that executes the update to Scoreloop, then run that object from whatever thread you like with `runOnUIThread`. This will always ensure the code runs on the same thread.

Your runnable would look something like:

```
public class ScoreLoopUpdater implements Runnable {
  private float score;
  public ScoreLoopUpdater (Float _score) {
    this.score = _score;
  }

  public void run() {
    ScoreloopManagerSingleton.get().onGamePlayEnded(score, null);
  }
}

```

So using it would look like:

```
ScoreLoopUpdater scoreLoopUpdater = new ScoreLoopUpdater(finalScore);
Activity.runOnUiThread(scoreLoopUpdater);

```

If the UI thread doesn't work, you can try the same on the "main" thread:

```
Handler mainHandler = new Handler(context.getMainLooper());

mainHandler.post(scoreLoopUpdater);

```
> 2 votes

# Answer
The runOnUiThread solution doesn't work for me, because I call it when game resume, my workaround solution is to use TimerHandler:

```
    @Override
protected void onResume() {
    super.onResume();
    final TimerHandler getTimerHandler = new TimerHandler(0.5f, new ITimerCallback() {
        @Override
        public void onTimePassed(final TimerHandler pTimerHandler) {
            if (!AccountUtils.checkSession()) {
                ResourceManager.getInstance().getCurrentScene().alert("Session timeout！", new IParamCallback() {
                    @Override
                    public void onCallback(final Object param) {
                        finish();
                    }
                });
            }
        }
    });
    getEngine().registerUpdateHandler(getTimerHandler);
}

```
> 0 votes

---
Tags: android, andengine, leaderboards
---


# Question
Title: Confused with how I should organize my code in a 2D game using OpenGL
I've just now started learning OpenGL and I'm getting very overwhelmed and confused with some things. I don't want to permaturely optimize things, but I also don't make decisions about things I still don't fully understand.

Question 1: I know that immediate mode compared to the use of VBOs in OpenGL is primitive and slow, but how much does it really matter for a 2D game, unless I start rendering tens of thousands sprites? At which point does it really justify the hassle of having to go through all that tedious process of the modern OpenGL? (I know modern OpenGL is a better practice, I am just legitimately curious!)

Question 2: I'm making a 2D game, it is going to implement particles, a few sprites, raycasted shadows and some blending tricks. My question is, do I keep one VAO and VBO for each Sprite, or do I create all the sprites in one single VBO / VAO? If so, how do I do that, how should my code be structured? I'm very confused as to how I should batch the draw calls.

Question 3: Is it significantly expensive to swap shaders? How do I handle multiple shaders? I thought about categorizing the objects and join the ones that have the same shader together for drawing, so I don't have to switch shaders as much, but I wasn't sure if it was worth the hassle.

# Answer
### Question 1:

As always, it depends, and on many factors. Not only it depends on how much stuff you're drawing, but also on the particular video card, drivers and OS.

In general, the old way of doing things (immediate mode and fixed pipeline) will probably be fast enough for your needs.

However, you should probably consider doing things the modern way (vertex buffers and shaders). Not only you will find it's not a hassle at all, and the "tedious process" is just a different way of doing things, but you'll also find that the modern way of doing things makes more sense, and will probably help you organize your code much easier.

### Question 2:

Each one of those options makes sense, and has different advantages and disadvantages. For what you want to do, probably either will work fine, so you should probably do what makes more sense to you.

Usually, updating VBOs takes time, so you should probably not share VBOs between things that change a lot (like particles or shadows) and things that don't (GUI and static parts of the map). However, switching between VBOs also takes time, so you shouldn't go overkill and have one VBO per object. There are thousands of ways to organize your code, and none is perfect, so you should probably do what makes the most sense to you.

### Question 3

Switching shaders is not such a big deal. As long as you're not compiling them on each frame, you can have hundreds of different shaders and switch them as you switch objects.

In my experience, switching shaders is pretty similar to switching textures or VBOs. Once again, do what makes the most sense to you, and only optimize when you find **and measure** bottlenecks.

You'll be surprised how fast modern video cards are, so for the type of game you're describing, you'll most likely have no performance problems, unless you do something extremely wrong, and maybe not even then.

You should usually prefer writing code in the way that makes most sense to you first, and worry about optimizations later.
> 3 votes

---
Tags: opengl, 2d, vbo, vao
---


# Question
Title: Get normal dependent on collisions position
As I hask ask here I'm working on how my objects can move over the terrain and other objects. My proposal and also an idea in the answers was to calculate the rotation from the object with the normals from other objects around (under and in front) the moving object.

My main problem for that is how I can get the normal from an object at a special position. Let's take the ramp on the road from the old example. It depends from which side my car comes. If it comes from front it can drive along the ramp but if it comes from back it moves against the wall. Of course there are other normals if I come from the other side. All my objects have these variables:

```
float vertices[];
float normals[];
short drawOrder[];

float[] modelMatrix;
AABBox boundingBox;

```

So you see I can allways get the vertices, normals and the position. I can also test if the object collides with another object with the bounding box (axis aligned) but I have no idea how I can get the normal where the collision happens but that is the important thing for the rotation of the car. Do you have any ideas or are there usual way how to do this?

# Answer
To put it simply - winding order. Winding order is the way you define which side of a triangle is the front and which side is the back. For example, OpenGL's default winding order is counter-clockwise, which means the triangle on the left is pointed out of the screen and the triangle on the right is pointed into the screen. If you had back-face culling turned on you would not be able to see the right-hand triangle.

```
1       1
|\      |\
| \     | \
|  \    |  \
2---3   3---2

```

This works together with the non-commutative property of the vector cross product

```
a × b = -(b × a)

```

to ensure that when you calculate the normal of a triangle it points in the right direction. To use the triangle example from above, if you always calculate your normal vector as follows, the normal will always point out from the front of the triangle (towards you for the left triangle, away for the right). Note that to obtain a unit normal, which is desirable for lighting and collision, you also need to normalize the vector.

```
n = (p2 - p1) × (p3 - p1)

```

Since the vector cross product is conventionally right-handed, you can verify the normal direction yourself using this method with your right hand:

1. Point your index finger in the direction of the left-hand operand `a`
2. Point your middle finger in the direction of the right-hand operand `b`
3. Your thumb is now pointing in the direction of the vector obtained with the cross product `a × b`

Notice how if you switch the operands your thumb ends up in the opposite direction.

---

So how does this relate to collision detection?

To ensure that you always obtain a collision normal that will point away from the surface, only detect collisions from the front side. If, like in your example, you want to be able to collide with both sides of an object, put two collision surfaces, one flipped, on top of each other. Again, refer back to the two triangles and how the winding order defines which side is the front. If you layer the two triangles, now you have a double-sided triangle with a different normal (the exact opposite!) on each side. Since you only detect collisions with the "front" of a surface you always obtain the correct normal.

Respecting winding order is how convex hull algorithms are still able to determine which is the "outside" despite not being given that information explicitly. The Quickhull algorithm uses tetrahedra that are eventually used to build a triangle mesh, and if the winding order is maintained properly from the start all the normals will be facing in the correct direction.
> 7 votes

---
Tags: collision-detection, movement
---


# Question
Title: Collision detection between axis-aligned bounding box and bitmap (pixel perfect) terrain
Working on a Worms-type game, I have my objects in bounding boxes and they sit on the pixel terrain.

Currently I am able to successfully do the collision detection for objects when they enter the game by checking the middle-bottom pixel of the bounding box, if it is solid, reduce the x and y velocity to 0, other wise keep moving down at a value of gravity.

The trouble comes in when I start to move the "player sprites" as they can walk into walls and I'm not sure how to approach how to detect collision if moving into pixels, and finally how to resolve these collisions.

I need to be able to detect solid walls I cannot pass, and gradient hills where the player should "walk up".

Could you help point me in a way to do this or how it has been done in the past?

# Answer
Let's say your "worm" is 100 pixels high, and his bottom edge is at 0 height. As you walk to the side, you'll find collisions (you know how to check if there's a collision, so I'm not going over that). If the pixel you're colliding with is LOWER than y + (h/4), where y is the height of the bottom edge (in this case 0), and h is the height of your worm (in this case 100), just let your worm keep walking, and adjust his height accordingly. If the colliding pixel is HIGHER than that value, stop you worm's movement.
> 1 votes

---
Tags: java, 2d, android, collision-detection, collision-resolution
---


# Question
Title: How do I show a small sprite being dragged by touch?
In my mobile game, users drag shapes across the screen. Think of it as a classic Lines game, where you drag a dot on the field, or a chess game where you drag and drop pieces.

The problem is that the player's finger totally covers the sprite, making dragging confusing.

Is there a common practice to solve this?

---

My best try so far was to move the sprite to be offset from the finger when the dragging starts, then move along with the finger in the offset position until dropped.

The problem with this approach is that users might be left- or right-handed. If I offset the sprite to the top-left of the finger, dragging with the left hand covers the sprite again.

# Answer
> 2 votes
If you move elements smaller than your finger, there's something wrong with your game design.

I see several solutions to this:

* Make your elements bigger so you can see that you hold and where you put them, possibly enabling a Zoom gesture.
* Use another method of move, like a two tap movement mode, you tap from and to positions.
* Constraint your moves on one axis. User can move his finger on the whole screen with the element fixed on its own axis, so there's always a way his finger doesn't cover the element.
* Create another element for precise positioning, like a arrow, a cross or a thin line that appears when you start to drag an element.

For the right/left hand problem, people don't change their hand often, what's done most of the time is create a setting to enable or disable left handed mode, so your offset is applied on the right side instead of the left side.

# Answer
> 1 votes
I would suggest zooming in your game screen so that the pieces are slightly larger, it's extremely frustrating when a game has a bunch of tiny pieces that are hard to see and hard to drag. However, if you don't want to do that, there's a common approach that can be used so that the item can still be seen as it is being dragged. So to Crazyrems list of suggestions I would add this:

* Try programming the item/element to move slightly slower than the user's finger *at all times*. So as the user drags it, have it drag behind just a little bit. That way the user can still see where it's going, but selecting the item doesn't have to be difficult and/or confusing.

This is a slightly different suggestion then what you say you're doing. The item should drag slightly behind the finger *in all directions at all times*, rather than to a certain position to the left or right of your finger. That way, it doesn't matter if you're a lefty or righty, but rather which way you're dragging the item.

---
Tags: animation, mobile, touch, user-experience
---