# Question
Title: Making a cube slowly rotate 180 degress one time on a mouseclick
I am new to C# and new to Unity. I made a script that can turn a cube slowly one time after a mouse click but I feel like its probably wrong for using FixedUpdate. Is this OK or is there a better way? What is wrong with this way?

```
using UnityEngine;
using System.Collections;

public class MouseClick : MonoBehaviour {

    public float myRotationSpeed = 1.0f;
    bool flipped = false;

    //when User clicks it with mouse
    void OnMouseDown ()
    {

        if (flipped == false)
        {
        flipped = true;
        }
    }
    void FixedUpdate ()
    {

        if(flipped == true && gameObject.transform.rotation.y >=0.01)
        {

            transform.Rotate(0, myRotationSpeed * Time.deltaTime, 0);
        }
    }
}

```

# Answer
> 1 votes
You can use this script. Create a new script called TransformExtensions and paste this in it. Then just call RotateOverTime() on your transform. It takes the Vector3 rotation and float seconds. You can also call RotateTowardsOverTime() and pass in a Vector3 targetDirection and float seconds.

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

public static class TransformExtensions
{
    /// <summary>
    /// Rotates the transform to a specified rotation over a set number of seconds.
    /// For an infinite rotation, multiply the degrees by a float to adjust the speed, and set the duration to 0 seconds.
    /// Calling RotateOverTime() or RotateTowardsOverTime() will cancel any pending rotations on this transform.
    /// </summary>
    public static void RotateTowardsOverTime(this Transform transform, Vector3 degrees, float seconds)
    {
        Vector3 rotationToBeMade = degrees - transform.rotation.eulerAngles;
        if (degrees.z > 270.0F && transform.rotation.eulerAngles.z < 90.0F)
        {
            rotationToBeMade.z = -(360.0F - degrees.z + transform.rotation.eulerAngles.z);
        }
        if (transform.rotation.eulerAngles.z > 270.0F && degrees.z < 90.0F)
        {
            rotationToBeMade.z = 360.0F - transform.rotation.eulerAngles.z + degrees.z;
        }
        RotateOverTime(transform, rotationToBeMade, seconds);
    }

    /// <summary>
    /// Rotates the transform by a specified number of degrees over a set number of seconds.
    /// For an infinite rotation, multiply the degrees by a float to adjust the speed, and set the duration to 0 seconds.
    /// Calling RotateOverTime() or RotateTowardsOverTime() will cancel any pending rotations on this transform.
    /// </summary>
    public static void RotateOverTime(this Transform transform, Vector3 degrees, float seconds)
    {
        RotateOverTime[] oldRotateOverTimeComponents = transform.gameObject.GetComponents<RotateOverTime>();
        foreach (RotateOverTime oldRotateOverTimeComponent in oldRotateOverTimeComponents)
        {
            GameObject.Destroy(oldRotateOverTimeComponent);
        }

        RotateOverTime rotateOverTimeComponent = transform.gameObject.AddComponent<RotateOverTime>();
        rotateOverTimeComponent.hideFlags = HideFlags.HideInInspector;
        rotateOverTimeComponent.Degrees = degrees;
        rotateOverTimeComponent.Seconds = seconds;
    }

class RotateOverTime : MonoBehaviour
{
    public Vector3 Degrees { get; set; }
    public float Seconds { get; set; }

    private Vector3 rotationCompleted = Vector3.zero;
    private Vector3 speed;
    private Vector3 startRotation;

    void Start()
    {
        speed = GetBalancedRotationSpeeds(Degrees, Seconds);
        startRotation = transform.eulerAngles;
    }

    void FixedUpdate()
    {
        UpdateRotation();
        if (IsRotationComplete())
        {
            Destroy(this);
        }
    }

    private Vector3 GetBalancedRotationSpeeds(Vector3 degrees, float seconds)
    {
        if (seconds == 0)
        {
            seconds = 1;
        }
        float degreesWeight = (Degrees.x + Degrees.y + Degrees.z) / 3;
        float speedModifier = degreesWeight / seconds;
        float totalChangeInDegrees = Math.Abs(degrees.x) + Math.Abs(degrees.y) + Math.Abs(degrees.z);
        float xWeight = Math.Abs(degrees.x) / totalChangeInDegrees;
        float yWeight = Math.Abs(degrees.y) / totalChangeInDegrees;
        float zWeight = Math.Abs(degrees.z) / totalChangeInDegrees;
        float xSpeed = xWeight * speedModifier * 3;
        float ySpeed = yWeight * speedModifier * 3;
        float zSpeed = zWeight * speedModifier * 3;
        return new Vector3(xSpeed, ySpeed, zSpeed);
    }

    private void UpdateRotation()
    {
        rotationCompleted += Time.deltaTime * speed;
        Vector3 rotation = Quaternion.Euler(rotationCompleted + startRotation).eulerAngles;
        bool rotationIsValid = !(float.IsNaN(rotationCompleted.x) || float.IsNaN(rotationCompleted.y) || float.IsNaN(rotationCompleted.z) && float.IsNaN(startRotation.x) || float.IsNaN(startRotation.y) || float.IsNaN(startRotation.z) || float.IsNaN(rotation.x) || float.IsNaN(rotation.y) || float.IsNaN(rotation.z));
        if (!rotationIsValid)
        {
            Destroy(this);
        }
        transform.eulerAngles = rotation;
    }

    private bool IsRotationComplete()
    {
        bool xRotationIsComplete = Math.Abs(rotationCompleted.x) >= Math.Abs(Degrees.x);
        bool yRotationIsComplete = Math.Abs(rotationCompleted.y) >= Math.Abs(Degrees.y);
        bool zRotationIsComplete = Math.Abs(rotationCompleted.z) >= Math.Abs(Degrees.z);
        return xRotationIsComplete && yRotationIsComplete && zRotationIsComplete && Seconds != 0;
    }
}

```

# Answer
> 0 votes
I think Update() is better in this case. Try to change your code like below:

```
public float myRotationSpeed = 1.0f;
bool flipped = false;
 Vector3 targetDir;

void OnMouseDown ()
{

    if (flipped == false)
    {
    flipped = true;
    targetDir = -1 * transform.forward;
    }
}
void Update ()
{

    if(flipped == true )
    {
        float angle = Vector3.Angle(targetDir, forward);
        if (angle > 0.01F) //stop condition
        {
         transform.Rotate(Vector3.up * myRotationSpeed * Time.deltaTime, Space.World);
        } else {
         flipped = false;
        }
    }

}

```

---
Tags: unity, transformation, rotate
---


# Question
Title: How common are game engine bugs, and can I claim damages for them?
Are game engine bugs (in popular ones like Unreal and Unity, not some unknown ones) common? I know engines like Unreal, Source and Unity3D are well tested and maintained, but, for example, is there any threat like: I create a game, the engine programming is fine, so is everything I do, but I get a bug in the game because of a bug in the engine?

And as most of you guys here are game developers, has any one had such an experience? Also, can I take legal action on the creators of that engine incase I am under loss because of their bug?

# Answer
It can be assumed that all non-trivial software contains bugs.

* Unreal Engine 4 has a bugtracker here.
* Unity has a bugtracker here.

If you browse these sites you can see the many known issues with these engines.

---

The licensing agreements for these engines (and most software generally) will contain clauses similar to this:

> No Warranty.
>
> THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND. UNITY AND ITS LICENSORS DISCLAIM ALL WARRANTIES AND CONDITIONS, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT, AND ANY WARRANTIES AND CONDITIONS ARISING OUT OF COURSE OF DEALING OR USAGE OF TRADE. NO ADVICE OR INFORMATION, WHETHER ORAL OR WRITTEN, OBTAINED FROM UNITY OR ELSEWHERE WILL CREATE ANY WARRANTY OR CONDITION NOT EXPRESSLY STATED IN THIS AGREEMENT.

These No Warranty / "as is" clauses are intended to reduce any liability brought against the software developers/publishers.
> 19 votes

# Answer
I'm fairly certain that no, you cannot take legal action against the creators of software because of a bug. I'm not even sure how you get this idea, and what specifically you would sue them for.

There are known bugs (as Kelly said), and probably also unknown ones, but you have to think about the likelyhood of you even encountering these bugs, and even then you can probably work around that. In addition to that, Unreal has released their source code, so you can fix it yourself if you really have to.

The bigger question is: reliable enough compared to what? Writing an engine on your own? Unless you are The Chosen One, your homemade stuff will most likely have far more and/or serious bugs than something that has been used and tested not only longer, but by several orders of magnitude more people.
> 8 votes

# Answer
Hmm, you raised an actually interesting point there, but what do you actually mean by the term **legal action**? That does matter a lot in this case. And another thing, the creators of those engines aren't forcing you to use their engines. So it won't be possible that you can take an action on them.

The only thing that you are able to do is to report a bug to them, and ask them for a possible solution that you can take in regarding that bug. Given that you mentioned engines like UE4 and Unity, it is really unlikely (I'm not a user of those engines) that you encounter a bug that nobody has spotted before, considered the fact that there are a lot of successful titles that use those engines.

Even if you have spotted such an error or bug, the workflow is that you report the bug to them in their bug trackers. Most successful engines do have a large communities often, so it is guaranteed to be fixed unless the bug you are thinking of is not a bug actually, but is the intended behaviour.

So the conclusion is, it is mostly certain that you are not eligible to take an action on the creators of those engines.
> 0 votes

---
Tags: legal
---


# Question
Title: How do I go about selecting minimum GPU requirements for a video game a couple years out from release?
How does one go about determining a good minimum GPU requirement for a game that development is starting on, that will be published in approximately 2 years?

On one hand, you want as many people as possible to be able to play it, but on the other hand, you want the capabilities to be as high as possible for a better experience. The higher the DX/GL API you can use also means some things will be much better optimized.

My current idea is basically to identify what GPUs of the past have done, over a two year period, and identify the best one at the moment that will more than likely be hitting the bargain bin at the expected release date.

# Answer
Usually from my experiences, the minimum target hardware at release should be around the mid-range hardware from the point you start developing your game.

NOTE: Dont use that as an excuse for not optimizing. If your code is shitty but you say "yeah but it runs on a Titan which i set as my minimum Hardware" thats not how it works.

Try to optimize for current mid-range hardware, while testing and developing you will be able to get a feeling on if it works on lower end hardware or if the user will need something better in order to flawlessly play the game.

You can not 100% aim for your target hardware because you might really want to have one specific visual feel and you cant quite optimize it to run good on the hardware you had in mind, so this will have to be tested out at the point of release again.
> 1 votes

---
Tags: gpu
---


# Question
Title: Obstacles work in Unity Editor but not in the build
As the title states my code works in editor view but not when I Build it.

I need to dynamically place and remove Obstacles in a NavMesh.

Can anyone give some insight why this happens?

# Answer
try and have a look at this: http://docs.unity3d.com/Manual/class-NavMeshObstacle.html you could make a prefab of the Obstacle you want to place, load it with (GameObject)Resources.Load("Obstacle") and then spawn it where you want.

To give you a more in-depth answer you should be able to post the section of your code that handles obstacles, until that, this is the solution I would use for that problem.
> 1 votes

# Answer
Well, it seems Unity4 had a general problem with placing obstacles in a Navmesh. I have swapped to Unity5 which works as intended.
> 0 votes

---
Tags: unity, path-finding
---


# Question
Title: How can I split up a large model into an octree codewise?
For collision detection, I am attempting to split up a large model into an octree.

If we take this black thing thing to be the ship (104,000 vertices):

Then I would like to split up the faces

I could easily split them up, but the problem is one of location. For example, if we take the bottom left chunk, how can I know that the projectile (in this case, a cannonball) is at that specific chunk?

And also how can I define the areas of the chunks in the first place? And for that matter, I need them to rotate with the ship as well!

I'm hopelessly lost as of how to do this, and so I'm hoping someone can help me out.

# Answer
> 1 votes
first you transform the cannon ball into the coordinate space of the ship.

Then you act as *if you want to add the ball's model* to the octree and step down through the nodes. If the ball straddles a boundary line then go through both sides.

Once you get into a leaf not then there is the bucket with faces to test with.

---
Tags: opengl, java, collision-detection, lwjgl, octree
---


# Question
Title: Position and rotate a 2D point array into a 3D world
I have a set of 2D points (defining a flat 2D 'connect the dots' shape). I want to calculate the 3D positions for these 2D points at a specific 3D position and rotation.

For example, say I have five 2D points forming the shape of a 2D hexagon. I want to place this hexagon shape at a specific location in my 3D world, at a specific rotation. I need to calculate new 3D coordinates for each of the 2D points.

If it matters, the 2D points will center around (0,0).

What magic formula do I need to do to accomplish this translation? Is there a built in method (in Unity) to do this?

Each point will be perpendicular to the rotation angle/direction, so will I need to calculate the cross product? Then somehow use this to remap each 2D point?

I should have paid more attention to this in school, all those years ago (I can't even remember if I actually learned this before!).

Any help will be appreciated. Thanks.

Here's some basic code to illustrate:

```
Vector3 position;     // Where in 3D to place the 2D shape
Quaternion rotation;  // What 3D rotation to apply to the 2D shape.  Should be a Vector3?
Vector2[] shapeIn;    // List of 2D points defining shape
Vector3[] shapeOut;   // List of updated 3D points at its new position and rotation

shapeOut = new Vector3[shapeIn.Length];

for (int p=0; p<shapeIn.Length; p++) {
    shapeOut[p] = MagicFormula(shapeIn[p]);
}

```

# Answer
> 1 votes
You don't need anything special to do this. You can "up-convert" a Vector2 to a Vector3 with z = 0 by writing:

```
(Vector3)shapeIn[p];

```

This will give you your shape in 3D, oriented in the XY plane (vertically, facing the default camera position you'd get for a new scene). (0, 0) in the source shape will map to (0, 0, 0) in the scene.

You can now use all the regular tricks you'd use to orient a 3D object.

To rotate it, you just need to multiply each point by a Quaternion representing the orientation you want. You could copy this from another object whose orientation you've manipulated in the scene to the angle you want:

```
shapeRotation = myReferenceObject.transform.rotation;

```

Or you could construct it using convenience functions like Quaternion.AngleAxis(angle, axis) or Quaternion.Euler(x, y, z)

To translate it, just add an offset Vector3 (which represents the coordinates of the worldspace point you want to map the source shape's (0, 0) to)

Putting it all together:

```
 shapeOut[p] = (shapeRotation * (Vector3)shapeIn[p]) + shapeOffset;

```

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


# Question
Title: How to make inventory pause screens in Gamemaker?
I'm making a game in Game Maker, and I want to know how to make it so you can pause into an inventory screen and then go back to the same position you were in (also the same room) after you press a back button. It would also be great if all the dead enemies were dead and the alive ones were at the same position also.

# Answer
To go into an inventory screen, you can create a new room which you can customize to your liking.

To have all of the instances of your room "freeze", use the **instance\_deactivate\_all()** method.

To "unfreeze" all of the instances in your room, use the **instance\_activate\_all()** method.

If we break up your code and look at the individual parts, it should resemble the below:

1. In Key Press event, go to your inventory room.
2. In Room Exit event of original room, freeze all instances.
3. Code your Inventory room as you see fit.
4. In Key Press event, go back to original room.
5. In Room Enter event of original room, unfreeze all instances.
> 2 votes

---
Tags: game-maker
---


title: database structure for rpg items

text:
# Question
Title: database structure for rpg items
I am currently developing a multiplayer html5 game, and the game has rpg elements (levels, items and such)

I just started working on the database side of things, and now I have a mongodb server setup with a basic user table (email, nickname, password hash and salt etc)

Now, each user should aquire items, and I am wondering should each user get his own collection in the db, or should there be a single collection that stores all the items, and has a email field that links the item to a user?

# Answer
> 1 votes
One may miss a very important detail: you're using Mongo. It's not an RDBMS, it's a document-oriented DB and it should be used differently.

Namely, where a relational DB would use a foreign key (a reference, in fact) and rely on joins with indexes, you can embed entries right into your users' documents, RDBMS are terrible at doing so. A tradeoff, yeah. I personally think it's a better choice, read on and see if you agree.

Of course, that implies that once copied from the game-wide colection, the player's item is no longer linked to its "prototype item". Thus, should the prototype change, changes to it won't propagate to its copies (unless you explicitly spend time doing that). That, in turn, makes each copy self-contained. You mentioned upgrading certain items -- piece of cake, just increment a field on an object in player's inventory and there you have it. All other items like this one are not affected.

By using SQL-style data structure (a table with all items, a join table items-players) you'd end up with a ridiculous amount of lookups on Mongo's side, so the database in this case may quickly become a performance bottleneck. If that looks better suited for your needs (i. e. if you plan a lot of many-to-many relations), consider switching to PostgreSQL, it has some highly unusual datatypes for a relational DB (hstores, arrays) that may help.

# Answer
> 0 votes
It depends on what your items are like. Many games will just have a table of item types, and then the character record will list how many items of which types that character has. Only if you have unique items (special unique artifacts, or customizable items) might you want/need separate tables with records for each actual item, with links back to the owner, and perhaps not even then, though there might be reasons to do it that way depending on your game design.

Given the detail you added in the comment here, I'd suggest a table of characters, a table of item types, and then a table of actual items, with a column for the item type id, a column for the owner id (I would use an integer ID not an email string), and then you can add columns to that table if you end up having properties for specific items (for enhancements, damage to the item, special conditions, etc).

There can be a bit of a performance tradeoff in terms of looking the information up in the database, but probably you will write your code so you only look up the info from the database rarely, and keep local copies in memory when you are frequently re-using the information during play.

# Answer
> 0 votes
Usually, in a database, you'd make a table of all the items in your game, make a table of all your players, and make another table, the Inventory table, that stores entries consisting of Player ID, Item ID, and Item Quantity. If you were using another structure to hold your data I'd probably be inclined to tell you to give each player their own separate inventory so you don't have to try to find items at the bottom of a long array (or something) but databases are kinda designed for querying so it wouldn't make a lot of sense to use a database like you'd use an OO class.

---
Tags: databases
---


# Question
Title: DirectX 11 - Get the world matrix of my camera
I'm relatively new to the world of 3D games programming and I am not sure if I am understanding some key concepts correctly.

Right now I have created a sphere that is 2.0f in radius which surround the camera to act as a sky box ( I disabled culling to ensure that it did not block structutes in my world, and then turned culling back on once it was drawn ), its position is currently relative to the world, which is a problem.

The problem is that when I walk over terrain my camera exits the 2.0f sphere causing me to see the default black colored sky, in order to solve this I think I need to move the sphere relative to the cameras world matrix.

I currently have this function, which takes in the master WVP matrices with an output parameter for the cameras world matrix:

```
void Camera::GetWorldMatrix(D3DXMATRIX w, D3DXMATRIX v, D3DXMATRIX p,
                            D3DXMATRIX& camWorld)
{
    // How can I determine the cameras world matrix here?
}

```

How I get the cameras world matrix relative to the master world matrix?

# Answer
Just move the skybox with the view. Just the translation of the view though. You wouldn't want the skybox to rotate and scale with your view. I suggest looking at this http://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices/ to understand matrices better. From what I've found this has a very simple explanation of them. To get an idea of what a transform matrix looks like (which the paper doesn't describe as much):

This picture should help. When multiplied together you produce a transformation matrix. I usually keep the properties of my camera elsewhere. In some data structure that holds things like FOV, nearZ, farZ, position, etc.

In code I suggest something like this (Psuedocode):

```
D3DXMATRIX T = D3DXMatrixTranslation(eyePos.x, eyePos.y, eyePos.z);
D3DMATRIX WVP = D3DXMatrixMultiply(T, camera->GetView() * camera->GetProj());

// Then skipping some rendering code I fed the WVP to the shader where it then (in HLSL)
// did this for every vertex in the skybox
vout.PosH = mul(float4(vin.PosL, 1.0f), gWorldViewProj).xyww;
vout.PosL = vin.PosL;

```

gWorldViewProj is WVP it's just in the shader and named differently.

getView and GetProj return D3DXMATRIX view and proj matrices
> 1 votes

---
Tags: directx, directx11
---


# Question
Title: DirectX 11 vertex shader incorrectly sending <0, 0, 0> normal vector to pixel shader
I'm following the Rastertek tutorials. I'm unable to get diffuse lighting working from http://www.rastertek.com/dx11tut06.html.

I think the NaNs in the following screenshots is just from stuff getting optimized out. I have found that I can run the same vertex and pixel shader frame through Visual Studio's Graphics Analyzer and sometimes get different values. 9/10 the values below are what's shown.

The vertex shader looks like its filling out the normal vector. It found the normal to be \<0, -1, 0\>, but I don't know if that's right.

The pixel shader is apparently getting a \<0, 0, 0\> vector.

Here's the vertex shader code. I skipped around Rastertek tutorials, which definitely is hurting now that I missed this 'basic' lighting problem.

```
cbuffer MatrixBuffer
{
    matrix worldMatrix;
    matrix viewMatrix;
    matrix projectionMatrix;
};

struct VertexInputType
{
    float4 position : POSITION;
    float2 tex : TEXCOORD0;
    float3 normal : NORMAL;
};

struct PixelInputType
{
    float4 position : SV_POSITION;
    float2 tex : TEXCOORD0;
    float3 normal : NORMAL;
};

PixelInputType LightVertexShader(VertexInputType input)
{
    PixelInputType output;

    // Change the position vector to be 4 units for proper matrix calculations.
    input.position.w = 1.0f;

    // Calculate the position of the vertex against the world, view, and projection matrices.
    output.position = mul(input.position, worldMatrix);
    output.position = mul(output.position, viewMatrix);
    output.position = mul(output.position, projectionMatrix);

    // Store the texture coordinates for the pixel shader.
    output.tex = input.tex;

    // Calculate the normal vector against the world matrix only.
    output.normal = mul(input.normal, (float3x3)worldMatrix);

    // Normalize the normal vector.
    output.normal = normalize(output.normal);

    return output;
}

```

And the pixel shader.

```
Texture2D shaderTexture;
SamplerState SampleType;

cbuffer LightBuffer
{
    float4 ambientColor;
    float4 diffuseColor;
    float3 lightDirection;
    float padding;
};

struct PixelInputType
{
    float4 position : SV_POSITION;
    float2 tex : TEXCOORD0;
    float3 normal : NORMAL;
};

float4 LightPixelShader(PixelInputType input) : SV_TARGET
{
    float4 textureColor;
    float3 lightDir;
    float lightIntensity;
    float4 color;

    textureColor = shaderTexture.Sample(SampleType, input.tex);

    // Set the default output color to the ambient light value for all pixels.
    color = ambientColor;

    // Invert the light direction for calculations.
    lightDir = -lightDirection;

    // Calculate the amount of light on this pixel.
    lightIntensity = saturate(dot(input.normal, lightDir));

    if(lightIntensity > 0.0f)
    {
        // Determine the final diffuse color based on the diffuse color and the amount of light intensity.
        color += (diffuseColor * lightIntensity);
    }

    // Saturate the final light color.
    color = saturate(color);

    // Multiply the texture pixel and the final diffuse color to get the final pixel color result.
    color = color * textureColor;

    return color;
}

```

Here are the hardcoded vertices for the triangle.

```
vertices[0].position = DirectX::XMFLOAT3(-1.0f, -1.0f, 0.0f);  // Bottom left.
vertices[0].texture = DirectX::XMFLOAT2(0.0f, 1.0f);
vertices[0].normal = DirectX::XMFLOAT3(0.0f, 0.0f, -1.0f);

vertices[1].position = DirectX::XMFLOAT3(0.0f, 1.0f, 0.0f);  // Top middle.
vertices[1].texture = DirectX::XMFLOAT2(0.5f, 0.0f);
vertices[1].normal = DirectX::XMFLOAT3(0.0f, 0.0f, -1.0f);

vertices[2].position = DirectX::XMFLOAT3(1.0f, -1.0f, 0.0f);  // Bottom right.
vertices[2].texture = DirectX::XMFLOAT2(1.0f, 1.0f);
vertices[2].normal = DirectX::XMFLOAT3(0.0f, 0.0f, -1.0f);

```

If there's some other piece of code you think is relevant let me know. I just didn't want to overload this post with code.

**Edit 3/17/2015** Here is the input layout.

```
HRESULT result; // FAILED(result) checks have been omitted.
ID3D10Blob* errorMessage = 0;
ID3D10Blob* vertexShaderBuffer = 0;
ID3D10Blob* pixelShaderBuffer = 0;
D3D11_INPUT_ELEMENT_DESC polygonLayout[3];
unsigned int numElements;
D3D11_BUFFER_DESC matrixBufferDesc;
D3D11_SAMPLER_DESC samplerDesc;
D3D11_BUFFER_DESC lightBufferDesc;

result = D3DCompileFromFile(vsFilename, NULL, NULL, "LightVertexShader", "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS | D3DCOMPILE_DEBUG, 0, &vertexShaderBuffer, &errorMessage);
result = D3DCompileFromFile(psFilename, NULL, NULL, "LightPixelShader", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS | D3DCOMPILE_DEBUG, 0, &pixelShaderBuffer, &errorMessage);
result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &mVertexShader);
result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &mPixelShader);

// Setup the layout of data that goes into the shader.
// This setup needs to match the VertexType structure in the model and in the shader.
polygonLayout[0].SemanticName = "POSITION";
polygonLayout[0].SemanticIndex = 0;
polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
polygonLayout[0].InputSlot = 0;
polygonLayout[0].AlignedByteOffset = 0;
polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[0].InstanceDataStepRate = 0;

polygonLayout[1].SemanticName = "TEXCOORD";
polygonLayout[1].SemanticIndex = 0;
polygonLayout[1].Format = DXGI_FORMAT_R32G32B32_FLOAT;
polygonLayout[1].InputSlot = 0;
polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[1].InstanceDataStepRate = 0;

polygonLayout[2].SemanticName = "NORMAL";
polygonLayout[2].SemanticIndex = 0;
polygonLayout[2].Format = DXGI_FORMAT_R32G32B32_FLOAT;
polygonLayout[2].InputSlot = 0;
polygonLayout[2].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
polygonLayout[2].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[2].InstanceDataStepRate = 0;

numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]);

result = device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &mLayout);

vertexShaderBuffer->Release();
vertexShaderBuffer = 0;

pixelShaderBuffer->Release();
pixelShaderBuffer = 0;

samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.MipLODBias = 0.0f;
samplerDesc.MaxAnisotropy = 1;
samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
samplerDesc.BorderColor[0] = 0;
samplerDesc.BorderColor[1] = 0;
samplerDesc.BorderColor[2] = 0;
samplerDesc.BorderColor[3] = 0;
samplerDesc.MinLOD = 0;
samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;

result = device->CreateSamplerState(&samplerDesc, &mSampleState);
if (FAILED(result))
{
    return false;
}

// Setup the description of the dynamic matrix const buffer that is in the vertex shader.
matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType);
matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
matrixBufferDesc.MiscFlags = 0;
matrixBufferDesc.StructureByteStride = 0;

result = device->CreateBuffer(&matrixBufferDesc, NULL, &mMatrixBuffer);
if (FAILED(result))
{
    return false;
}

lightBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
lightBufferDesc.ByteWidth = sizeof(LightBufferType);
lightBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
lightBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
lightBufferDesc.MiscFlags = 0;
lightBufferDesc.StructureByteStride = 0;

result = device->CreateBuffer(&lightBufferDesc, NULL, &mLightBuffer);

```

Struct that is given to the vertex shader.

```
struct VertexType
{
    DirectX::XMFLOAT3 position;
    DirectX::XMFLOAT2 texture;
    DirectX::XMFLOAT3 normal;
};

```

Setting the shader parameters.

```
HRESULT result;
D3D11_MAPPED_SUBRESOURCE mappedResource;
MatrixBufferType* dataPtr;
LightBufferType* dataPtr2;
unsigned int bufferNumber;

// Lock the const buffer so it can be written to.
result = deviceContext->Map(mMatrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if (FAILED(result))
{
    return false;
}

dataPtr = (MatrixBufferType*)mappedResource.pData;

dataPtr->world = DirectX::XMMatrixTranspose(worldMatrix);
dataPtr->view = DirectX::XMMatrixTranspose(viewMatrix);
dataPtr->projection = DirectX::XMMatrixTranspose(projectionMatrix);

// Unlock.
deviceContext->Unmap(mMatrixBuffer, 0);

bufferNumber = 0;

deviceContext->VSSetConstantBuffers(bufferNumber, 1, &mMatrixBuffer);

deviceContext->PSSetShaderResources(0, 1, &texture);

result = deviceContext->Map(mLightBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if (FAILED(result))
{
    return false;
}

dataPtr2 = (LightBufferType*)mappedResource.pData;

dataPtr2->ambientColor = ambientColor;
dataPtr2->diffuseColor = diffuseColor;
dataPtr2->lightDirection = lightDirection;
dataPtr2->padding = 0.0f;

deviceContext->Unmap(mLightBuffer, 0);

bufferNumber = 0;

deviceContext->PSSetConstantBuffers(bufferNumber, 1, &mLightBuffer);

```

# Answer
My lighting problem was caused by two things.

1.) My input layout's TEXCOORD was set to DXGI\_FORMAT\_R32G32B32\_FLOAT instead of DXGI\_FORMAT\_R32G32\_FLOAT. I suspect that this was behind the weird debug output I was seeing from my shaders, but I'm not sure.

and 2.) My light was facing down the negative z axis, instead of the positive z axis.

Either of these fixes alone had no effect visually, but together fixed the diffuse lighting!
> 0 votes

---
Tags: 3d, shaders, directx, directx11
---


# Question
Title: How can I refactor an enum so that it is still available in the inspector?
I am trying to use an enum so that it is available in the inspector. This code works:

```
public ArmorTypeEnum ArmorType;
public enum ArmorTypeEnum { Light, Medium, Heavy };

```

How can refactor it into a single line?

How can I make `ArmorTypeEnum` private while keeping `ArmorType` public?

# Answer
> 2 votes
You can't make your enum anything other than public if you want `ArmorType` to be public too. See Restrictions on Using Accessibility Levels (C# Reference).

If you don't want to use an enum, and just want a selection in the inspector, you can use a property drawer to show a selection of strings in the inspector.

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


# Question
Title: Should I ask my artist to make Sprites in full resolution or can I scale them up?
I'm started with Unity development and my artist asked me what size she should make the sprites for the game.

They are all pixel art and she didn't know if she should make them on Photoshop on a small resolution, do them already on the iOS resolution 1920x1080 or even if she should use a vector program and then rasterize them.

How is this normally done?

# Answer
> 9 votes
Pixel art generally responds extremely bad to any scaling. Just a small size adjustment will make pixel art appear either blurry or distorted, depending on what scaling algorithm your engine uses. For that reason it is important to make sure that the graphics are designed in exactly the resolution in which they appear in the finished game.

Here is a pixel-art sprite from one of my projects, interpolated with linear interpolation and nearest neighbor interpolation. As you can see only the original size looks well:

When stepless scalability of graphics is important for your game concept, you should consider to use vector-based graphics instead of pixel-art. Just keep in mind that the hardware requirements can become a lot higher when the vector graphics are not specifically designed to be fast to render. When your artist comes from a general visual design background with not much game development experience they might not know what they need to do and avoid to ensure this (it also depends on the platform and technology you use. Different vector graphic rasterizers have different strengths and weaknesses).

Another option when you want scaling is to go for a retro-look, design very low resolution sprites and upscale them with nearest neighbor. Nearest neighbor preserves the "blockyness" which is usually undesirable, but preserves the aesthetics of 90s style pixel art on high-DPI screens. This usually only works when you upscale by a large amount. When you downscale, most other algorithms are preferable to nearest neighbor, even on pixel art. Here is a very small sprite from the first Final Fantasy game upscaled a lot with nearest neighbor interpolation:

As you can see the retro aesthetics are preserved, and the image quality doesn't suffer even with a very uneven zoom factor. But this **only** works because the original sprite is so tiny and the zoom level is so high. Also, this look is not appropriate for every game.

# Answer
> 2 votes
Make them the size they would normally be. Don't try to make them big and scale them down later. That way there will be less time loading the images (Not that it's all that long.) Less data stored as well. Make sure that when you are scaling them up to draw them to the screen, you don't use a any sort of filter. Anotherwords... Use no mipmapping. Ie point sampling. (It looks bad in 3d but not with 2d pixel art.)

Graphics API's usually have a flag to set mipmapping. For Unity: http://answers.unity3d.com/questions/22491/how-do-i-turn-off-mip-mapping.html

# Answer
> 1 votes
Vector images are useful since they would work with any resolution, and you can even use them directly in the game, letting OpenGL/DirectX rasterize it only when they are rendered to the frame buffer.

But since you specifically mentioned pixel art it doesn't sound like you would get the right look with vector graphics, in that case you want to be careful about resizing them (as the other answers have mentioned).

In pixel art a lot of the style comes from each pixel having importance, so shrinking the image would rarely give good results. Increasing their size also has pitfalls, although there are some algorithms that have been made specifically for pixel art (they are often used with emulators of older systems).

If the art looks good as vector graphics then that is a good choice, specifically because it lets you postpone the decision about precise size of things until a later date, thus making it easy to resize things if you realize that a certain character should be taller or shorter. If not then your artist will have to make the sprites in the proper size to begin with for the best results.

# Answer
> 1 votes
If you can only afford to have one set of sprites drawn (i.e. your artist time/effort is limited) then get them to do the largest resolution. It's far easier to make hi-res sprites look okay when scaled down than it is to make low-res sprites look okay when scaling up.

Neither approach is better than having sets of sprites tailored for your target resolution, but that can be expensive to have developed. If you have a wide range of target resolutions you may still want to have two or more sets of sprites made up, so that if you do have to do scaling that you don't have to go too far. 50% is probably a reasonable limit, any more than that and they'll look very muddy once scaled. But if you have small and large versions then you can scale whichever one is nearest to the target resolution.

In all cases, do your scaling offline using the best filters you can, even if those filters are too expensive to do at runtime. Storage for your assets is generally cheap, and you don't want to be burning performance on scaling and filtering at runtime. You'd have to have a very, very large sprite-set to be worrying about the storage footprint of your app more than how it performs. You want to keep your sprite sets separate as well, so that you're only ever loading the data the game needs, not loading a larger version and scaling down, or loading multiple sets and then picking one of them.

# Answer
> 0 votes
Depends on what look you're going for. Usually you'd design for your target platform and then scale/rework art assets for secondary platforms. Make it look nice for the largest chunk of your players, essentially.

---
Tags: unity, graphics, sprites, spritesheet
---


# Question
Title: Learning To Use C# In Both VisualStudio And Unity's Monodevelop Frameworks
I apologize if this has been asked and answered, but I can't find it. I know the framework is different in `MonoDevelop` and `Visual Studio 2010 Express`. For instance, if I want to use `Write.Line`, I need to change the code to `Debug.Log`. Is there a source for crossover syntax? I found this but it doesn't seem to answer the question.

```
namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            string name;

            Console.WriteLine("Hello, what is your name?");
            name = Console.ReadLine();
            Console.WriteLine("Your name is  " + name);
            Console.ReadLine();
        }
    }
}

```

For instance, where would I find a resource to translate this code to MonoDevelop? I know Unity doesn't use static void, namespace, Console.ReadLine();, etc. Thanks for the help!

# Answer
> 5 votes
The C# language is not changed between MonoDevelop and Visual Studio. You'd have access to `Console` if you included `using System;` in your MonoBehavior script, it just won't do what you expect because the Unity editor isn't a console application.

There's no direct conversion between the two because they are not replacements for each other. They may have similar functionality, but the `Debug` class is not a replacement for the `Console` class.

Instead of looking for a guide to convert between the two (which doesn't exist), look for the functions you want to perform in Unity.

# Answer
> 0 votes
This occurrs because, unlike a normal C# program, Unity does not have a Main() function. Instead, you should do the following.

* Start a new Unity Project
* Add a new empty GameObject to the scene
* Add a new script
* Double-click on the script and it will open in MonoDevelop.

Unity will generate a script with the following code:

```
class ScriptNameHere
{
    void Start()
    {

    }
    void Update()
    {
    }
}

```

This is where you will put all user-written code.

It's still C# but code written with Unity can only use .NET 3.5, so anything added from .NET 4.0 onwards won't work, but basic code like this should be fine.

Instead of using `Console.WriteLine()` and `Console.ReadLine()` you will need to read up on topics such as how to create a GUI in unity, how to render a text box, and how to process input, but to output to the Unity console you will use this code:

```
Debug.Log("Hello World");

```

# Answer
> 0 votes
There is no direct conversion, as others have stated, unity is not a console application, so writting and reading from something that is not there is not going to work.

This means you need to do all the heavy lifting yourself. The methodology here is going to be a great deal different than working with consoles, because Unity is handling all of the user inputs.

To accomplish this (or, one way to skin this cat---), I personally would recommend using an Update function (a function that you can write, that is automatically called once per frame on any monobehavior). Additionally, I would use Unity's Input class to listen for key strokes.

And this is what that might look like:

```
using UnityEngine;
using System.Collections;

public class sample : MonoBehaviour {

//Location where the name is stored while it is being typed.
private string name="";

//The different 'stages' in which we are interacting with the player.
private enum Stage{
    SayHello,
    WaitingForInput,
    SayName,
    Complete
}
//The current 'stage' right now. When this starts, it starts by saying hello
private Stage currentStage = Stage.SayHello;

//Every frame this is run. We need to keep track of the users input over many frames.
void Update () {

    //Check which stage we are currently in.
    switch (currentStage) {

        //If we are in the sayHello Stage
        case Stage.SayHello:
            Debug.Log("Hello, what is your name?");
            //Change to Wait for Input Stage. This is done after sayhello is run one time.
            currentStage = Stage.WaitingForInput;
            break;

        //If we are in the waiting for input stage
        case Stage.WaitingForInput:
            //If the user has hit any keys on the keyboard this frame
            if(Input.inputString.Length>0){
                //if any of those keys are the return button
                if(Input.inputString.Contains("\r")){
                    //you are done waiting for input, now you can process to say their name
                    currentStage = Stage.SayName;
                }else{//otherwise
                    //add the input from this frame into the name variable for later use.
                    name += Input.inputString;
                }
            }
            break;

        //If we are in the sayname stage
        case Stage.SayName:
            //Say the name
            Debug.Log("Your name is "+name);
            //Change to a complete stage (a stage that does litterally nothing and is missing from this switch).
            currentStage = Stage.Complete;
            break;
    }
}
}

```

So if you just take all that and put it in a c# script in unity, and attach it to any game object, that should do close to what you are looking for.

Your question is one of those questions that seems like it should be really simple, but unfortunately Unity and console applications are very different in many respects. Keep working at it, and in no time you will get the hang of it!

Hope that helps and good luck!

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


# Question
Title: Is there a javascript physics engine that does not require canvas?
I just need a really simple and small physics engine for squares or circles that moves images using javascript. For the project that I am working on, I can't use canvas, so I will be moving the images via the dom. If I understand it correctly, Box2D and PhysicsJS both require the canvas (or at least in my testing that seemed to be the case). I don't really want to make my own, because I bet there is something out there that already does this.

So, is there a javascript physics engine that does not require canvas?

# Answer
> 7 votes
A physics engine being tied to a particular renderer shows horrible separation of concerns and really shouldn't happen.

In fact, it doesn't. Box2D-js *can* visualise the simulation with a canvas, but is in no way required to do so. It is possible to extract the information you want and drive some other visualisation with it. PhysicsJS has a custom renderer tutorial, as does Matter.js.

Here's a list of a bunch more suitable engines.

---
Tags: physics, javascript
---


# Question
Title: OrthographicCamera and viewport not giving expected effect
I recently asked a question about this area that I think was too broad, so I will try a new approach.

I have the following code I am experimenting with:

```
        batch = new SpriteBatch();
        texture = new Texture(Gdx.files.internal("bg_test.png"));

        sprite = new Sprite(texture);
        sprite.setSize(GAME_WORLD_WIDTH, GAME_WORLD_HEIGHT);

        myGameWidth = Gdx.graphics.getWidth();
        myGameHeight = Gdx.graphics.getHeight();

        float aspectRatio = (float)myGameHeight / (float) myGameWidth;

        cam = new OrthographicCamera();
        viewport = new StretchViewport(GAME_WORLD_WIDTH * aspectRatio, GAME_WORLD_HEIGHT * aspectRatio, cam);
        viewport.apply();
        cam.position.set(GAME_WORLD_WIDTH / 2, GAME_WORLD_HEIGHT / 2, 0);

```

Now I thought `StretchViewport` was supposed to stretch the image across whatever screen you tried, however I get this result in desktop when I try with `config.height=800`, `config.width=400`:

Now if I change the following line:

```
viewport = new StretchViewport(GAME_WORLD_WIDTH * aspectRatio, GAME_WORLD_HEIGHT * aspectRatio, cam);

```

to:

```
viewport = new StretchViewport(GAME_WORLD_WIDTH, GAME_WORLD_HEIGHT, cam);

```

(I remove aspect ratio) This makes the image fill the screen the way I thought StretchViewport should, but I dont want to ignore the aspect ratio.

What makes it even weirder is that this only happens when I run desktop `heigt>width`(portrait), if I change it to the opposite `width>height`(landscape) then the image fills the screen too much, so the edges of the image go outside the screen :S

Am I missing something here? Is my aspectRatio wrong? I want to make sure my games will scale nicely across devices before I really get started with libgdx, right now all different viewports show me the same result with this padding.

I really can't figure this out, I get the behaviour (stretch) I want when I dont use aspectratio, but everywhere I read it tells me to use aspectratio. I really just wanna solve this so I can start with the fun stuff ^^

# Answer
First your use of the aspect ratio is nonsense. The aspect ratio is the relation of width to height.

So if you have

```
float aspectRatio = (float)myGameHeight / (float) myGameWidth;

```

This means that the the following is true:

```
myGameHeight == aspectRatio * myGameWidth

```

If you want to preserve the aspect ratio of the screen you need to do the following:

```
viewport = new StretchViewport(GAME_WORLD_WIDTH, GAME_WORLD_WIDTH * aspectRatio, cam);

```

Note the that only `GAME_WORLD_WIDTH` is used. (If height is the desired size you want to preserve, do the inverse.)
> 2 votes

---
Tags: java, libgdx, camera, viewport
---


# Question
Title: How can I convert OBJ data into CSS3D transformations?
I want to convert the data in a 3D `.obj` file (vertices, normals, faces) to CSS3D (width, height, rotateX,Y,Z and/or similar transforms). I found a bunch of formulae and what-not, but 3D isn't my forte, so I don't know which I should use.

*Essentially*: How can I get the X/Y/Z-rotation of a 4-point plane from it's matrix of x,y,z coordinates?

---

For example, here are 2 simple planes in `.obj` format:

```
g plane1
# simple along along Z axis
v  0.0  0.0  0.0
v  0.0  0.0  1.0
v  0.0  1.0  1.0
v  0.0  1.0  0.0

g plane2
# plane rotated 90 degrees along Y-axis
v  0.0  0.0  0.0
v  0.0  1.0  0.0
v  1.0  1.0  0.0
v  1.0  0.0  0.0

f  1 2 3 4
f  5 6 7 8

```

I'd like to convert it into CSS:

```
#plane1 {
    width: X;
    height: Y;
    transform: rotateX(Xdeg) rotateY(Ydeg) rotateZ(Zdeg) translateZ(Zpx)
}

#plane2 {
    width: X;
    height: Y;
    transform: rotateX(Xdeg) rotateY(Ydeg) rotateZ(Zdeg) translateZ(Zpx)
}

/* Or equivalent, like using transform: matrix3d() */

```

# Answer
> 1 votes
It is not that hard if you think about if for a while. Now the following assumes that you have perfect rectangles as faces in the OBJ. (I honestly don't know how to do arbitrary polygons.)

I think you can build a orhtonormal R3 matrix from the values in the OBJ.

You have 4 vertices:

```
v  0.0  0.0  0.0
v  0.0  0.0  1.0
v  0.0  1.0  1.0
v  0.0  1.0  0.0

```

You can create two perpendicular vectors:

```
 a = v[1] - v[0]
 b = v[3] - v[0]

```

Now you are just missing the normal, which you can get from a and b:

```
 n = cross(u, v)

```

After normalizing everything you should be able to defined the following rotation matrix:

```
 m_rot = mat3(a, b, n)

```

The "upper left corner" should be the position of the face. (It may be the center; I am not sure.) This can then be used to create a transformation matrix:

```
#<planeN> {
    // a, b not normalized
    width: length(a);
    height: length(b);
    // a, b & n normalized
    transform: matrix3d(a.x, b.x, n.x, v[0].n,
                        a.y, b.y, n.y, v[0].y,
                        a.z, b.z, n.z, v[0].z,
                          0,   0,   0,      1);
}

```

Please note that I am not sure about the column order of the CSS3 matrix3d directive, it may be inverted.

---
Tags: 3d, matrix, transformation, obj, css
---


# Question
Title: How to enable IntelliSense for Unity scripts in Visual Studio?
I am using Visual Studio 2013 pro and Unity 4.6.

Whenever I write scripts (javascript or c#) for anything and open it up in Visual Studio, I don't get IntelliSense.

How to fix this issue?

# Answer
> 3 votes
The reason that this occurs is because Visual Studio can't find the dll files for Unity without opening a specialized solution file. This file can be created using UnityVS, which can be found as "Visual Studio Tools for Unity" in the Visual Studio gallery. After installing this (make sure you have Unity closed when you do), open Unity, and a new tab will be present called "Visual Studio Tools". Click this, and click the button that says "Generate solution file" or similar, depending on the version of Unity and UnityVS that you are using.

Thanks to @IcyDefiance in chat, I can now say that UnityVS definitely does not support UnityScript or Boo, as said on their website. This is since version 1.9.x was released.

> **C# only:** C# being the predominant language in the Unity ecosystem - the new Sample Assets are in C#, the Unity documentation will default to C# - we removed our basic support for UnityScript and Boo to better focus on the C# experience. As a result, VSTU solutions are now C# only and are much faster to load.

---
Tags: unity, unityscript, visual-studio
---


title: 2D water shader in SFML

text:
# Question
Title: 2D water shader in SFML
I want to implement the algorithm for a 2D water surface described here and here.

Before somebody finds out, beats me up and deletes this, I'm gonna say it myself. I posted this question over at stackoverflow too. I know cross posting is a terrible thing, but I just found this Game Development Q&A site. My question is closely connected to game development, because I want to use the effect in a game. Also I use SFML, which is a library mostly used for developing games. I think there are more GLSL and graphics experts here, so maybe somebody is able to help me. Again please excuse this.

So some background information: I am using SFML and C++. I want to recreate the effect described in the articles above. But instead of using two int arrays and calculating on the CPU I would like to use SFML's `sf::RenderTexture`'s (FBO's basically) and a GLSL shader to run everything on the GPU.

I've made some good progress so far. I was able to set up 3 `sf::RenderTextures` and ping-pong between them correctly (because other than int array you can't read and write to the same `sf::RenderTexture` at the same time). I was also able to adapt the algorithm for the height field creation form being in the range -32.767 to 32.767 to the range 0 to 1 (or to be more precise -0.5 to 0.5 for the calculation). Also adding new ripples works to some extend. So up to this point you can actually see a little of waves going on.

Here comes my problem now: The waves disappear really, really fast and I don't even apply any damping yet. According to the algorithm the ripples are not stopping if there is no damping applied. It's even the other way around. If I apply "amplification" the waves look close to what you would expect them to look like (but they still disappear without any damping applied to them). My first thought was that this is, because I use float's in range 0 - 1 instead of integers, but I only see this being a problem if multiplication is used, but I only use addition and subtraction.

Another idea that a user at stackoverflow suggested was, that I was sampling the texels edges and not their centre, giving me interpolated values and thus creating the unexpected damping, but this turned out to be false as well.

Here is my SFML C++ code :

```
#include <SFML/Graphics.hpp>
#include <iostream>

int main()
{
    sf::RenderWindow window(sf::VideoMode(1000, 1000), "SFML works!");
    window.setFramerateLimit(12);

    sf::RenderTexture buffers[3];
    buffers[0].create(500, 500);
    buffers[1].create(500, 500);
    buffers[2].create(500, 500);
    sf::RenderTexture* firstBuffer = buffers;
    sf::RenderTexture* secondBuffer = &buffers[1];
    sf::RenderTexture* finalBuffer = &buffers[2];

    firstBuffer->clear(sf::Color(128, 128, 128));
    secondBuffer->clear(sf::Color(128, 128, 128));
    finalBuffer->clear(sf::Color(128, 128, 128));

    sf::Shader waterHeightmapShader;
    waterHeightmapShader.loadFromFile("waterHeightmapShader.glsl", sf::Shader::Fragment);

    sf::Sprite spritefirst;
    spritefirst.setPosition(0, 0);
    spritefirst.setTexture(firstBuffer->getTexture());

    sf::Sprite spritesecond;
    spritesecond.setPosition(500, 0);
    spritesecond.setTexture(secondBuffer->getTexture());

    sf::Sprite spritefinal;
    spritefinal.setPosition(0, 500);
    spritefinal.setTexture(finalBuffer->getTexture());

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if(event.type == sf::Event::Closed)
                window.close();

            if(event.type == sf::Event::KeyReleased && event.key.code == sf::Keyboard::Escape)
                window.close();
        }

        waterHeightmapShader.setParameter("mousePosition", sf::Vector2f(-1.f, -1.f));
        // if mouse button is pressed add new ripples
        if(sf::Mouse::isButtonPressed(sf::Mouse::Left))
        {
            sf::Vector2i mousePosition = sf::Mouse::getPosition(window);
            if(mousePosition.x < 500 && mousePosition.y < 500)
            {
                sf::Vector2f mouse(mousePosition);

                mouse.x /= 500.f;
                mouse.y /= 500.f;

                mouse.y = 1 - mouse.y;

                std::cout << mouse.x << " " << mouse.y << std::endl;

                waterHeightmapShader.setParameter("mousePosition", mouse);
            }
        }

        waterHeightmapShader.setParameter("textureTwoFramesAgo", firstBuffer->getTexture());
        waterHeightmapShader.setParameter("textureOneFrameAgo", secondBuffer->getTexture());

        // create the heightmap
        secondBuffer->display();
        finalBuffer->clear(sf::Color(128, 128, 128));
        finalBuffer->draw(sf::Sprite(secondBuffer->getTexture()), &waterHeightmapShader);
        finalBuffer->display();

        spritefirst.setTexture(firstBuffer->getTexture());
        spritesecond.setTexture(secondBuffer->getTexture());
        spritefinal.setTexture(finalBuffer->getTexture());

        window.clear();
        window.draw(spritefirst);
        window.draw(spritesecond);
        window.draw(spritefinal);
        window.display();

        // swap the buffers around, first becomes second, second becomes third and third becomes first
        sf::RenderTexture* swapper = firstBuffer;
        firstBuffer = secondBuffer;
        secondBuffer = finalBuffer;
        finalBuffer = swapper;
    }

    return 0;
}

```

And here is my GLSL shader code :

```
uniform sampler2D textureTwoFramesAgo;
uniform sampler2D textureOneFrameAgo;
uniform vec2 mousePosition;

const float textureSize = 500.0;
const float pixelSize = 1.0 / textureSize;

void main()
{
    // pixels position
    vec2 position = gl_TexCoord[0].st;

    vec4 finalColor = ((texture2D(textureOneFrameAgo, vec2(position.x - pixelSize, position.y)) +
                        texture2D(textureOneFrameAgo, vec2(position.x + pixelSize, position.y)) +
                        texture2D(textureOneFrameAgo, vec2(position.x, position.y + pixelSize)) +
                        texture2D(textureOneFrameAgo, vec2(position.x, position.y - pixelSize)) - 2.0) / 2) -
                       (texture2D(textureTwoFramesAgo, position) - 0.5);

    // damping
//    finalColor.rgb *= 1.9;  // <---- uncomment this for the "amplifiction" ie. to see the waves better
    finalColor.rgb += 0.5;

    // add new ripples
    if(mousePosition.x > 0.0)
    {
        if(distance(position, mousePosition) < pixelSize * 5.0)
        {
            finalColor = vec4(0.9, 0.9, 0.9, 1.0);
        }
    }

    gl_FragColor = finalColor;

}

```

Please remember that this is all just about the height field creation. There is no shading of the water or a background texture yet.

I have done a lot of research, but I can't find anything that helps me, I am really stuck now! So does anybody know why the waves disappear by them self without damping?

# Answer
Why would you consider the wave disappearing unexpected?

The shader averages/spreads differences in the heightmap. All it does is basically damping. Each iteration it will flatten out the waves, making them a little less high and a little wider.

To have a more realistic wave-propagation you might want to try to use 2 textures.

Use one for heights, and one for velocities, and spread (see advection, wave-propagation) their values just like you would with only the heightmap. In this case an additional step is needed to update velocities based on height-differences (gravity). A high pixel flows towards a low pixel, with means the velocity at and/or between those to will increase a little per timestep.

A good term to search the interwebs for would be "shallow water equations". Especially Stam's method might interest you, as it is well suited for fast but visually appealing results. See: http://www.gamasutra.com/view/feature/1549/practical\_fluid\_dynamics\_part\_1.php
> 1 votes

---
Tags: c++, shaders, glsl, sfml, graphic-effects
---


# Question
Title: How to raycast against a physx cloth mesh?
I'm using the PhysX 3.3 SDK in a application and mostly everything is working fine. However, I'm trying to develop a feature that would allow users to click on various actors in the scene and modify their properties.

My approach so far has been to use the PhysX raycast to query the scene and use RaycastHit to return a pointer to the actor. This works fine for rigid bodies, but for cloth actors, the hit is invariably null.

This suggests that PhysX can't raycast against cloth objects, but other than my tests, I haven't seen anything in the docs (or on the interwebs) that say this definitively.

Any thoughts?

# Answer
As i cannot comment yet, as an answer:

Raycast against the bounding-box, not the actual cloth itself. This may not be perfect, but it's fast. The drawback would be the clicks slightly besides the cloth would be considered a hit. Which is most probably neglectable unless those clicks have critical consequences. (Think sniper-shots in a game.)

More complex and much slower could be to check the click against rendered buffer. Render each cloth as full white to a black background from the same perspective the clicking user sees it from and check if click position falls on white or black pixel. Wouldn't recommend that though.
> 2 votes

---
Tags: c++, raycasting, physx
---


# Question
Title: Fast(er(est)) fullscreen/scene collision detection technique ("selection buffer")
My vertex format has a float4 Flags element used to pass miscellaneous data to shaders. Each mouse-collidable object that is rendered has a unique ObjectID that is written to an ObjectID-rendertarget which can be CPU-sampled to index the hovered object. The remaining render targets are geometry/lighting data.

I've found this has advantages:

1. I set (Flags.x = ObjectID) upon object creation so the vertex buffer only needs an initial upload and updates only when new ObjectID's (that will be rendered) are created. Everything else is per-object/instance. Essentially, "no" overhead added by using a Flags component for ObjectID.
2. I'm semi-certain that, since I have to render everything anyway, outputting one additional color to one additional rendertarget is already cheaper than ANY clever bounding/container collision testing algorithm. Currently, I copy the entire ObjectID-rendertarget back to the CPU, but even that could be further optimized.
3. The depth buffer (that I'm using anyway) automatically ensures that the pixel I sample is the ObjectID of the top-most, visible, mouse-collidable, object. I don't have to check if the mouse position/ray is within the bounds of anything, intersects with anything, visibilities, nothing. All of that is already sorted out by rendering the scene properly.
4. Rendering the interface components first and reusing the ObjectID depth-buffer to render the world, reduces the fill-volume for the 3D scene; drastically, if a lot of interface is visible.

I've found only one disadvantage:

1. Since I render the interface first, if the camera has moved (the world hasn't been rendered yet), the WorldCoordinate available during Update() is incorrect. If the camera hasn't changed, the coordinate is correct. Immediately after rendering to the geometry buffers, but before any cursor-dependent shaders are invoked, I update the CPU-buffer and WorldCoordinate. The CPU-buffer is only updated when necessary and, at most, once per-frame. The "second sample" is during the following Update() and just re-reads the (wrong if the camera has moved) value from the byte array. Still, no significant overhead and this is basically just a slight annoyance because I'm just debugging the value anyway. Currently, when the WorldCoordinate is usefully-used (during render), it is correct.

Overall, I've got pixel-perfect, anything-on-the-screen, mouse-collision detection, with zero\* *additional* overhead beyond standard rendering.
\*Minimal and/or approximately-fixed, regardless of screen/scene complexity

**Why is this method not popular and/or tutorialized?**
-I assume most new-ish games post-process geometry buffers but I found nothing similar to this and just worked my way through the issues as they came up. To me, it appears as though I've got collision detection working for all of the objects/classes that I haven't even written yet. All of the "tech" involved here is obvious and easy, so I feel like I must be missing something; a future problem that I can't think of yet.

-Comments/critiques of the "algorithm" are welcome. Best answers would point out critical flaw(s) and, for bonus points, work-arounds.

-If this has been done before, is there an accepted best-practice? Links to similars would be ok.

# Answer
> 3 votes
Well, it's not new and it's a proper method. I think a common term for this "color picking", at least that's what i call it.

As long as you are fine with picking only one object at a time, and that object being the one on top, there are no critical shortcomings. Even multi-select clicks are possible to a certain extend by mixing/adding colors/ids.

However, consider how often a user actually clicks versus the amount of processing. You will in one way or another have to write a full screen of extra values each frame, even if the user isn't clicking at all. How many clickable objects do you actually have to consider *when* the user is clicking? Even a screen cluttered full of symbols might be faster to traverse when a click is happening then the accumulated time/power spend on copying something each frame you probably won't use even every 50th frame.

---
Tags: collision-detection, deferred-rendering
---


# Question
Title: How does glRotate affect the axes of the global coordinate system?
I am currently playing around with 3D transformations applied on a 2D context in LWJGL, to later be implemented in my game. So I managed to set up LWJGL well enough (scaling, translating, scaling and even more translating) to be able to use the "default" 2D-coordinate system again after I switched to glPerspective instead of glOrtho (otherwise you wouldn't be able to see the effect).

This works perfectly well and I can obscure and transform any 2D-object I desire. However, there is a problem with rendering images. In order to see the effect in more detail, any piece of geometry has to be cut down and rendered multiple times in smaller parts at different heights, the height is calculated with a function using x and y as parameters. With no rotation, this also works for images.

But when I try to do the same for images with rotation it doesn't work at first, obviously (if that's not so obvious: I take the current rendering coordinates as parameters for the z-function, which are of course incorrect in a rotation-transformed matrix). Therefore I changed the rendering function to also take rotation into account properly - and - doesn't work: The image still acts as though the function was applied to a non-rotated object, while the image itself is rendered with rotation. Looks weird, creates seams and is totally not what I intended.

I double- and triple-checked the values that are used as height, but my manual rotation transformations seem to be correct. The top left corner acts like the top bottom order if rotated around the center with 45 degrees for example, which is exactly where it will be in the final rendered version.

This is the code I use to render each part of the image; for debugging purposes I made the texture quad size (the size of the image parts its being split it into for said effect) to be exactly the image size, so just one quad per image at the moment. ZHandler is the class that calculates the z coordinate for a given x and y coordinate, absX and absY are the final coordinates at which it will be displayed.

```
GL.glTexCoord2f(curTexOffX, curTexOffY);
GL.glVertex3f(curX, curY, ZHandler.getZ(absX, absY));

GL.glTexCoord2f(curTexOffX, curTexOffY + curTexHeight);
GL.glVertex3f(curX, curY + parHeight, ZHandler.getZ(absX, absEndY));

GL.glTexCoord2f(curTexOffX + curTexWidth, curTexOffY + curTexHeight);
GL.glVertex3f(curX + parWidth, curY + parHeight, ZHandler.getZ(absEndX, absEndY));

GL.glTexCoord2f(curTexOffX + curTexWidth, curTexOffY);
GL.glVertex3f(curX + parWidth, curY, ZHandler.getZ(absEndX, absY));

```

It looks basically like this:

The white and gray area are background quads that are rendered to show what the function looks like, brighter areas are closer to you and darker ones further away. Obviously, this awesome duck image isn't tilted the way it should be, being exactly offset by the rotation it should have (what?).

When we look at the debug output however, it seems exactly like it should be:

```
0 400.0 550.0 0.60619825 //top left (all in un-rotated state)
1 400.0 250.0 0.60619825 //top right
2 700.0 250.0 -0.504535  //bottom right
3 700.0 550.0 -0.504535  //bottom left

```

It's in the format *corner absX absY z*, so the last two corners (originally bottom left and right, now thanks to -90 degrees of rotation, top right and bottom right) should be further away and the first two (originally top left and right, now bottom left and top left) should be closer to the camera. But. They. Aren't.

I suspect it must have something to do with the way glRotate works, so here is how it is called for rotated texture rendering:

```
//rotate around image's rotation center
GL.glTranslatef(centerX, centerY, 0.0f);
GL.glRotatef(angle, 0.0f, 0.0f, 1.0f);
GL.glTranslatef(-centerX, -centerY, 0.0f);

//draw texture...

//undo rotation
GL.glTranslatef(centerX, centerY, 0.0f);
GL.glRotatef(-angle, 0.0f, 0.0f, 1.0f);
GL.glTranslatef(-centerX, -centerY, 0.0f);

```

Maybe the z-Axis is affected in some ways I don't know of so that my calls are weirdly rotated. It also happens to any other rotation, it is just the most obvious for 90 degrees.

As of writing this, I am totally aware of the rubber-duck-debugging irony here. The holy duck clearly deserves better than being rendered wrongly, so I am asking for any hints, help or advice that could point me in the right direction to solve this problem.

**Edit**

I tried adding glPushMatrix and glPopMatrix to surround the rendering code, nothing changed. I already back-translate after the translation and undo all the transformations / rotations.

Also, @concept3d requested the set-up code for camera and projection matrix, so here it is:

```
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60, WIDTH / HEIGHT, 0.001f, 1000.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0, 0, -cameraDistance);
glScalef(1f / (WIDTH / 2.0f), 1f / -(HEIGHT / 2.0f), 1f);

```

I also calculate the actual and the rendered ratio to translate and scale it back to the "normal" orthographic system I used previously, so I can still use all the same coordinates. But on this, it is important to note that it works perfectly well for everything not-rotated, so there is no problem with the setup of the z-coordinates there.

**Edit**

As requested, the implementation of ZHandler.getZ:

```
return (float) (sin((x - 100) / 150 + t)) / 1.5f;

```

**Edit**

To clarify what I suspect is wrong, here is the rendered output with a rotation of +90, applied to the exact same configuration.

As seen, the same (wrong) effect applies, the image is tilted in the wrong direction even though the outputed debug values (same respective corners as in previous debug output) are correct:

```
0 700.0 250.0 -0.504535
1 700.0 550.0 -0.504535
2 400.0 550.0 0.60619825
3 400.0 250.0 0.60619825

```

**Edit**

Also, I now added the z-Values I render the different parts of the images at, which should further clarify what I am talking about. **The passed z-Values don't match the rendered scene.**

**Edit**

As requested, the code on how I calculate the rendered position based on the actual position. It's basically just rotation around a fixed point but here it is:

```
if (angle != 0.0f)
{
    absX -= centerX + drawPos.x;
    absY -= centerY + drawPos.y;

    buffer.set(centerX + drawPos.x + (absX * cos - absY * sin), centerY + drawPos.y + (absX * sin + absY * cos));

    absX = buffer.x;
    absY = buffer.y;
}

```

But I have to add that the calculated absolute values seem to be correct, as seen in the previous debug outputs :)

**Edit**

Here is how it (correctly) looks like with 0 rotation:

And here is how the final version looks like, also correct so far, with an un-rotated image and an texture quadrant size of 8.

# Answer
So with your provided problem image, the problem is that the top side of the quad is being affected, while the right side is supposed to have the majority of the effect? Is that correct? If that's the case then the problem is that your passing the wrong values to your ZHandler.getz function.

Your code, from what I'm seeing, is:

```
glTransform
glBegin
    ...
    glVertex(x, y, ZHandler.getz(x,y))
glEnd
glUntransform

```

What happens to your vertices with that is:

```
float z = ZHandler.getz(x, y); // your function happens here
glVertex(x, y, z) = {
    transformPoint(x, y, z); // your rotation happens here
    addVertex(x,y,z);
}

```

So that means your Z function gets calculated, and then the whole thing gets rotated. It sounds like you want that the other way around. Correct? To do that, you would need to create your own glRotate/glTranslate/glScale alternative. Not using the OpenGL provided functions, and using your own, you could transform your vertices first, then apply your function, and then pass the already-transformed vertices to OpenGL.

As a much faster, likely easier, possibly daunting, alternative, using GLSL 1.2 (Since you are, or seem to be, using OpenGL 2.1), you could move your ZHandle.getz function into a vertex-shader and calculate it there, then apply the transformation matrices.
> 2 votes

# Answer
Thanks to @WolfgangSkyler for his answer (and also @Byte56 for his generous bounty), the problem was resolved yesterday by following your advice. This would not fit into a comment and I want to share further information about how the issue was resolved, but - of course - I will not un-accept WolfgangSkylers answer, just add to it. So now, as promised, what exactly was wrong?

Well, in the question I stated (and repeated multiple times in the comments - sorry ;)) that I double- and triplechecked the z-Values I pass and that they are correct. Turns out they weren't. The issue was that I confused counter-clockwise counting with clockwise counting - everywhere else in my code (be it hitboxes or any other polygon I need to set up in any way) I set it up clockwise. Already see the flaw? Except in this piece of code, where I - for whatever reason - had decided to rotate counter-clockwise for a change (yeah..).

After re-reading Wolfgang Skyler in an attempt to find the solution to my problem I noticed that indeed I messed up the z-Value part - meaning that LWJGL was correct. Furthermore, I found out that my logical assumptions to calculate the transformed and rotated absolute values didn't make any sense: I had assumed that one min- and max value for x and y would suffice, because I always tested it with x\*90 degrees of rotation (which is the one case where it would work).

```
0 400.0 550.0 0.60619825 //top left (all in un-rotated state)
1 400.0 250.0 0.60619825 //top right
2 700.0 250.0 -0.504535  //bottom right
3 700.0 550.0 -0.504535  //bottom left

```

Here you can see the values in the order I *thought* they had. Looking at those, nothing seems off. However, if we correctly assign each corner a value in the same direction as I draw them, this is the real output:

```
0 400.0 550.0 0.60619825 //top left (all in un-rotated state)
1 400.0 250.0 0.60619825 //bottom left
2 700.0 250.0 -0.504535  //bottom right
3 700.0 550.0 -0.504535  //top right

```

And from there on, it is obvious that the values are wrong and it is rendered exactly in the way I call it - incorrectly. I then took the same code but just rotated each corner individually (= 8 values/4xy-pairs instead of 4/2). And it works :)
> 1 votes

---
Tags: opengl, rotation, lwjgl
---


# Question
Title: Player position on second player connection
I'm having some trouble trying to run my game for the multiplayer part. I'm creating a 2D game. I have followed this tutorial : http://www.paladinstudios.com/2013/07/10/how-to-create-an-online-multiplayer-game-with-unity/ and I've implemented it. As the tutorial says, I have a network view pointing to a script, containing my OnSerializingNetworkView and his interpolation and predilection stuff. It's working very fine, the movement is fluid and it's very good. The problem is when a second player join the game and my first player have already moved, since I'm instantiating the player using Network.Instantiate(prefab, Vector2.zero, ...) the player spawn in the middle of the map and then slowly move to his normal position. I've tried other things such as not using a script but putting the transform in the network view, when the second player spawn, the first one is at the correct position but the mouvements aren't the same and aren't that fluid.

Anyone have any idea on how to deal with this problem ?

Thanks!

# Answer
> 1 votes
According to your tutorial the fluid movement issue should be dealt with the smooth movement paragraph, which state the following:

```
private float lastSynchronizationTime = 0f;
private float syncDelay = 0f;
private float syncTime = 0f;
private Vector3 syncStartPosition = Vector3.zero;
private Vector3 syncEndPosition = Vector3.zero;

void OnSerializeNetworkView(BitStream stream, NetworkMessageInfo info)
{
    Vector3 syncPosition = Vector3.zero;
    if (stream.isWriting)
    {
        syncPosition = rigidbody.position;
        stream.Serialize(ref syncPosition);
    }
    else
    {
        stream.Serialize(ref syncPosition);

        syncTime = 0f;
        syncDelay = Time.time - lastSynchronizationTime;
        lastSynchronizationTime = Time.time;

        syncStartPosition = rigidbody.position;
        syncEndPosition = syncPosition;
    }
}

```

and

```
void Update()
{
    if (networkView.isMine)
    {
        InputMovement();
    }
    else
    {
        SyncedMovement();
    }
}

private void SyncedMovement()
{
    syncTime += Time.deltaTime;
    rigidbody.position = Vector3.Lerp(syncStartPosition, syncEndPosition, syncTime / syncDelay);
}

```

I once did the same tutorial and the problem was solved as I understood that part.

In a few words you have to Lerp between your client pos and real position on the server.

Hope this could helo you.

**EDIT**: by the way after trying the stuff in this tutorial I tried different ways to implement networking for my game. I tried the PhotonServer from exitgames which has a very complete api to handle bot cloud and autoritative server. And then I tried and chosen uLink from MuchDifferent, which has built in unity compatibility and fit my needs to the best.

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


# Question
Title: Creating a curve path for gameObject which reacts to Triggers
I am trying to create a path for a gameObject which will bounce off other gameObjects if it hits them. Can I get an idea on how I could possibly get this curve path set up.

Stuck on ideas. I don't want to use ITween and I can't simply define the entire path via ITween either. I need to account for whether it hit another gameObject and cause it to carry on the path or just fall through.

Attached the image below for clarification. I need the circle(purple) gameObject to bounce along the white path provided the rectangle(green) gameObject is in place to cause a Trigger and let the path carry on or the circle gameObject just simply falls through.

There is only 1 green gameObject at any point of time which moves to one of the 3 possible positions. Placed 2 just for clarification.

# Answer
> 1 votes
If the only deviation from the path is falling through you could make the object follow a parabolic function, check it at a certain point and if your green thing is there then send the object back along the same parabola. You can use something like this graph calculator to find the right curve.

```
y = -(a*x)*(x - contact)

```

If you modify 'a' in the equation above you can modify the height of the parabola while still hitting the x axis at 'contact'. a = 2 will be taller while a = 0.5 will be shorter.

---
Tags: unity
---


title: Rogue Door Connection logic

text:
# Question
Title: Rogue Door Connection logic
I'm having a bit of trouble developing code to figure out which doors connect in Rogue which is written in c. Not the actual path making. I just dont understand how they link to each other.

If rooms have 2 doors each then, while not the cleanest solution, I can connect the first rooms door1 to the second rooms door2 and continue that pattern, finally going around in a loop.

However, say there are 3 doors for one room, then that would break because one door wouldnt connect to anything. The same thing goes for a one door room.

Any help would be appreciated and links to examples would help too.

Thanks

EDIT

I'm not really generating paths right now, its more of the player teleporting to another door. If it were paths then of course it could intersect which takes care of the paths.

# Answer
> 5 votes
Imagine dots are doors and lines are corridors. This is how you can have three doors connected:

There is no reason why you can't link a door to more than one other door. You can have corridors merge at some point.

But oldskool roguelikes didn't even do this; they simply connected random pairs of rooms with corridors, and if they happen to cross into a room, *boom*, open a door here. This is the reverse process of what you're thinking. You can easily see how, since each corridor creates exactly two doors, this never produces a third door, so the problem never appears.

But why limit yourself to these methods? There is a wealth of possibilities on the PCG wiki. Maze generation alone is a well-studied field and has numerous algorithms.

# Answer
> 2 votes
Here is another way to connect rooms with three doors:

1. Make sure the amount of doors in your level is even.
2. Put all your rooms in the *not-door'd* set
3. Pick two rooms from the *not-door'd* set
4. Connect them through one of their doors
5. If those rooms still have a door that has no corridor, put them in a *partially-door'd* set
6. While the *not-door'd* set is not empty, pick one room from the *partially-door'd* set and one from the *not-door'd* and repeat from step 4, otherwise, proceed to next step
7. While the *partially-door'd* set is not empty, pick two rooms from the *partially-door'd* and repeat from step 4, otherwise, your done

This should work for rooms with any number of doors; all the rooms should be connected to the labyrinth, but some could be connected to themselves. And you might have issues if you have more than one room that has only one door :P

---
Tags: game-design, c, roguelikes
---


# Question
Title: OpenGL why point's size stay the same while zooming/unzooming
i'm currently working on a game engine for a college's project. While implementing some debug tools I came across a little problem. When i'm drawing point on the ModelView Matrix the point's thickness doesn't stay at scale with the other objects.

This is how I draw a point

```
    public static void DrawPoint(Vector3 p1,float size,Color color)
    {
        GL.Disable(EnableCap.Texture2D);
        GL.PointSize(size);
        GL.Begin(BeginMode.Points);
        GL.Color3(color);
        GL.Vertex3(p1.X, p1.Y, p1.Z);
        GL.End();
    });

```

This is my drawing loop

```
          protected sealed override void OnRenderFrame(FrameEventArgs e)
    {
        base.OnRenderFrame(e);

        GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
        GL.MatrixMode(MatrixMode.Modelview);
        GL.LoadMatrix(ref _Camera.CameraMatrix);
        GL.PushMatrix();

        RenderGame(); //<-- Where I render world object

        GL.Clear(ClearBufferMask.DepthBufferBit);
        GL.LoadIdentity();
        GL.MatrixMode(MatrixMode.Projection);
        GL.PushMatrix();
        GL.LoadIdentity();
        GL.Ortho(0, Width, 0, Height, -1, 1);
        GL.MatrixMode(MatrixMode.Modelview);

        DrawHUD(); //<-- Where I render UI

        GL.MatrixMode(MatrixMode.Projection);
        GL.PopMatrix();
        GL.MatrixMode(MatrixMode.Modelview);

        GL.PopMatrix();
        SwapBuffers();
    }

```

All points are drawn in the RenderGame method

My question is am I doing something wrong when I draw points, because it is the only shape that doesn't behave correctly. Or maybe it's just something I don't understand from openGL side. I'll put images of the problem soon.

# Answer
> 2 votes
The *point* you draw is really a spot of the *size* you put on the **screen**. It has no *volume*.

From opengl wiki:

> Points are rasterized as screen-aligned squares of a given window-space size.

If you want to draw a *point* that changes size as you zoom in and out, you could

1. Draw a point like you do but change the *size* as you zoom in and out (more complex because it's harder to determine the size you should have your point).
2. Draw a sphere or a cube, this will have a volume and will change size correctly as you zoom in and zoom out.

---
Tags: c#, opengl, opentk
---


title: Rotate object around fixed axis

text:
# Question
Title: Rotate object around fixed axis
I am trying to let the user of my app rotate a 3D object drawn in the center of the screen by dragging their finger on screen. A horizontal movement on screen means rotation around a fixed Y axis, and a vertical movement means rotation around the X axis. The problem I am having is that if I just allow rotation around one axis the object rotates fine, but as soon as I introduce a second rotation the object doesn't rotate as expected.

Here is a picture of what is happening:

The blue axis represents my fixed axis. Picture the screen having this fixed blue axis. This is what I want the object to rotate in relation to. What is happening is in red.

Here's what I know:

1. The first rotation around Y (0, 1, 0) causes the model to move from the blue space (call this space A) into another space (call this space B)
2. Trying to rotate again using the vector (1, 0, 0) rotates around the x axis in space B NOT in space A which is not what I mean to do.

Here's what I tried, given what I (think) I know (leaving out the W coord for brevity):

1. First rotate around Y (0, 1, 0) using a Quaternion.
2. Convert the rotation Y Quaternion to a Matrix.
3. Multiply the Y rotation matrix by my fixed axis x Vector (1, 0, 0) to get the X axis in relation to the new space.
4. Rotate around this new X Vector using a Quaternion.

Here's the code:

```
private float[] rotationMatrix() {

    final float[] xAxis = {1f, 0f, 0f, 1f};
    final float[] yAxis = {0f, 1f, 0f, 1f};
    float[] rotationY = Quaternion.fromAxisAngle(yAxis, -angleX).toMatrix();

    // multiply x axis by rotationY to put it in object space
    float[] xAxisObjectSpace = new float[4];
    multiplyMV(xAxisObjectSpace, 0, rotationY, 0, xAxis, 0);

    float[] rotationX = Quaternion.fromAxisAngle(xAxisObjectSpace, -angleY).toMatrix();

    float[] rotationMatrix = new float[16];
    multiplyMM(rotationMatrix, 0, rotationY, 0, rotationX, 0);
    return rotationMatrix;
  }

```

This isn't working how I expect. The rotation seems to work, but at some point horizontal movement doesn't rotate about the Y axis, it appears to rotate about the Z axis.

I'm not sure if my understanding is wrong, or if something else is causing a problem. I have some other transformations I'm doing to the object besides rotation. I move the object to the center before applying rotation. I rotate it using the matrix returned from my function above, then I translate it -2 in the Z direction so I can see the object. I don't think this is messing up my rotations, but here's the code for that anyways:

```
private float[] getMvpMatrix() {
    // translates the object to where we can see it
    final float[] translationMatrix = new float[16];
    setIdentityM(translationMatrix, 0);
    translateM(translationMatrix, 0, translationMatrix, 0, 0f, 0f, -2);

    float[] rotationMatrix = rotationMatrix();

    // centers the object
    final float[] centeringMatrix = new float[16];
    setIdentityM(centeringMatrix, 0);
    float moveX = (extents.max[0] + extents.min[0]) / 2f;
    float moveY = (extents.max[1] + extents.min[1]) / 2f;
    float moveZ = (extents.max[2] + extents.min[2]) / 2f;
    translateM(centeringMatrix, 0, //
      -moveX, //
      -moveY, //
      -moveZ //
    );

    // apply the translations/rotations
    final float[] modelMatrix = new float[16];
    multiplyMM(modelMatrix, 0, translationMatrix, 0, rotationMatrix, 0);
    multiplyMM(modelMatrix, 0, modelMatrix, 0, centeringMatrix, 0);

    final float[] mvpMatrix = new float[16];
    multiplyMM(mvpMatrix, 0, projectionMatrix, 0, modelMatrix, 0);
    return mvpMatrix;
  }

```

I've been stuck on this for a few days. Help is much appreciated.

==================================================================

UPDATE:

Getting this to work in Unity is straightforward. Here's some code that rotates a cube centered at the origin:

```
public class CubeController : MonoBehaviour {

    Vector3 xAxis = new Vector3 (1f, 0f, 0f);
    Vector3 yAxis = new Vector3 (0f, 1f, 0f);

    // Update is called once per frame
    void FixedUpdate () {
        float horizontal = Input.GetAxis ("Horizontal");
        float vertical = Input.GetAxis ("Vertical");

        transform.Rotate (xAxis, vertical, Space.World);
        transform.Rotate (yAxis, -horizontal, Space.World);
    }
}

```

The part that makes the rotations behave as I'm expecting is the `Space.World` parameter to the `Rotate` function on the transform.

If I could use Unity I would, unfortunately I have to code this behavior myself.

# Answer
I was able to get the rotations expected by rotating an accumulated rotation matrix.

```
setIdentityM(currentRotation, 0);
rotateM(currentRotation, 0, angleY, 0, 1, 0);
rotateM(currentRotation, 0, angleX, 1, 0, 0);

// Multiply the current rotation by the accumulated rotation,
// and then set the accumulated rotation to the result.
multiplyMM(temporaryMatrix, 0, currentRotation, 0, accumulatedRotation, 0);
arraycopy(temporaryMatrix, 0, accumulatedRotation, 0, 16);

```
> 3 votes

# Answer
The problem your having is called gimble lock. I think what your looking to do is called arcball rotation. The math for arcball can be abit complicated.

A simpler way of doing it is finding a 2d vector perpendicular to the 2d swipe on screen.

Take the vector and project it onto the camera near plane to get a 3d vector in world space. Screen space to World space.

Then create a quaternion with this vector and multiply it to gameobject. Probably with some slurp or lerp transition.

Edit:

Unity Example: In the unity example, the internal state of the gameobjects rotation is a quaternion not a matrix. The transform.rotation method generates a quaternion based on the vector and angle provided and multiplys that quaternion with the gameobjects rotation quaternion. It only generates the rotation matrix for rendering or physics at a later point. Quaternions are additive and avoid gimble lock.

Your Code Should look something like this:

```
private float[] rotationMatrix() {

    final float[] xAxis = {1f, 0f, 0f, 1f};
    final float[] yAxis = {0f, 1f, 0f, 1f};

    Quaternion qY = Quaternion.fromAxisAngle(yAxis, angleX);
    Quaternion qX = Quaternion.fromAxisAngle(xAxis, -angleY);

    return (qX * qY).getMatrix(); // should probably represent the gameobjects rotation as a quaternion(not a matrix) and multiply all 3 quaternions before generating the matrix.
  }

```

ArcBall Rotation Opengl Tutorial
> 3 votes

# Answer
Your image corresponds with your rotationMatrix code, by rotating the x axis with your previous y rotation you get the local x axis, when you then rotate the object around that you would get the result that you show in your image. To have the rotation be logical from a users point of view you would want to rotate the object using the world coordinate axis instead.

If you want your user to be able to spin your object many times it would make sense to store your rotation in a quaternion instead of a matrix, over time multiple spins (and floating point inaccuracies) will cause the matrix to look less and less like a rotation matrix, the same happens in a quaternion of course, but just normalizing the quaternion brings it back to a good rotation.

Simply use the identity quaternion as the initial value, and each time the user swipes the screen you rotate your quaternion with the `Quaternion.fromAxisAngle(yAxis, -angleX)` code. Always using (1,0,0,1) for x rotations and (0,1,0,1) for y rotations.

```
static final float[] xAxis = {1f, 0f, 0f, 1f};
static final float[] yAxis = {0f, 1f, 0f, 1f};

private void rotateObject(float angleX, float angleY) {
  Quaternion rotationY = Quaternion.fromAxisAngle(yAxis, -angleX);
  Quaternion rotationX = Quaternion.fromAxisAngle(xAxis, -angleY);

  myRotation = myRotation.rotate(rotationY).rotate(rotationX).normalize();
}
private float[] rotationMatrix() {
  return myRotation.toMatrix();
}

```

Since you didn't mention the language or any specific framework the methods on Quaternion may be called something differently of course, and normalize isn't necessary to call that often, but since the rotation comes from a user swiping the screen they won't slow things down much and that way there is no chance of the Quaternion slipping away from a unit quaternion.
> 1 votes

---
Tags: opengl, rotation, matrix
---


title: Subdived objects in different shapes

text:
# Question
Title: Subdived objects in different shapes
Currently I'm working on an Android OpenGL 3D game and now I want to implement a collision detection. For this I want to use oriented bounding boxes but here is my problem. For a normal oriented bounding box I have to store the middle and then the length into every dimension. Now let's say I have a tree and of course my character can walk under the treetop but not into the tree trunk. I tried to sketch up the different bounding boxes here:

```
Tree as two rectangels                         Normal bounding box

-----------------------                   ------------------------------
|                     |                   |                            |
-----------------------                   |                            |
        |     |                           |                            |
        |     |                           |                            |
        |     |                           |                            |
        |     |                           |             x              |
        |     |                           |                            |
        |     |                           |                            |
        |     |                           |                            |
        |     |                           |                            |
        |     |                           |                            |
        -------                           ------------------------------

```

If you think about the collision detection in the first sketch you can walk under the treetop because the border of the tree is subdivided into different shapes and the outline of a tree is still visible. In the second picture you can't tell something about the outline of the object because you only have one big box around the whole object so you can't walk under the treetop. You see the first method is much better then the second method for my plan.

Now my question: Do you have any ideas how I can subdivide my objects into different shapes? Maybe even in triangles, circles and so on. Is there an algorithm for this or do I have to do it by myself?

# Answer
> 1 votes
From my experience, the subdivision is made manually: you produce a 3d model for the graphics, and you compose another one made out of boxes, spheres, capsules and cylinders for your physics engine because it is generally what it understands well.

So yeah, **basically, you have to make these yourself**.

Unless you need *very basic* physics simulation, **I would strongly advise you to try and use a readily available physics engine for your target language and platform.** Physics simulation is one of the most complex things to manage in a game, and you'd probably like to spend your time on not recoding such a thing.

# Answer
> 0 votes
I agree with Alex, but more to the point, I don't think you'll find a silver bullet approach to make collision approximation models.

You will need to let your editor pick from a list of optional methods or generate one from scratch. After a tree model and material have been made, creating another cylinder and sphere mesh for collisions should be negligible effort.

---
Tags: collision-detection, bounding-boxes
---


# Question
Title: How are CSS and WebGL coordinates related?
I'd like to build a simple framework which rendering combines web page DOM elements with WebGL, such that they're manipulable in the same coordinate space.

How does the plain CSS coordinate system relate to the one used by WebGL? How can I make sure the two line up (e.g. have a div and a WebGL quad transformed the same way)? Can I expect CSS3D transform coordinates to correspond to WebGL?

# Answer
> 2 votes
They are not. Webgl coordinates refers to the positions of pixels in a canvas element and CSS describes the position of any HTML element in a page. You have to do math to apply the correct transformation if you wish align them. The default coordinate space for webgl is -1 being on one side of canvas and +1 on the other side (assuming viewport is same as whole canvas), with -1,-1 being the bottom left corner of canvas and +1,+1 being the top right.

You just need to find a transformation that maps the left side of canvas (x-position) to -1 in webgl and right side of canvas (x+width) to +1 in webgl and same for Y. Also in webgl the Y coordinate goes upwards from bottom of screen where as in HTML its 0 at top of screen.

---
Tags: opengl, html5, coordinates, webgl, css
---