# Question
Title: Float array not connecting with OpenGL Shader
I first tried using a float\[\]\[\] to get the height of a particular area but OpenGL didn't want to and it was much simpler to just use a flat multi-dimensional array instead. However, that array is not working now. I checked the math for how I was adding the floats and they were correct - I added them in the TerrainShader class with the same forumla as below (\[x * MAX\_X + y\] AKA x * 128 + y) but the result is still the same as before with the double array.

```
#version 400 core

in vec2 pass_textureCoordinates;
in vec3 surfaceNormal;
in vec3 toLightVector;
in vec3 toCameraVector;
in vec3 coordinates;

out vec4 out_Color;

uniform sampler2D backgroundTexture;
uniform sampler2D sandTexture;
uniform sampler2D stoneTexture;

uniform vec3 lightColour;

uniform float biomeMap[128 * 128 + 128];

void main(void) {

    vec4 textureColour = texture(backgroundTexture, pass_textureCoordinates);

    float c = biomeMap[int(pass_textureCoordinates.x * 128 + pass_textureCoordinates.y)];

    if(c < 110)
        textureColour = texture(sandTexture, pass_textureCoordinates);
    else if(c < 150)
        textureColour = texture(stoneTexture, pass_textureCoordinates);

    vec3 unitNormal = normalize(surfaceNormal);
    vec3 unitLightVector = normalize(toLightVector);

    float nDot = dot(unitNormal, unitLightVector);
    float brightness = max(nDot, 0.1);

    vec3 diffuse = brightness * lightColour;

    out_Color = vec4(diffuse,1.0) * textureColour;

}

```

The above is my terrainFragmentShader and below is the TerrainShader class.

```
public class TerrainShader extends ShaderProgram {

    private static final String VERTEX_FILE = "src/shaders/terrainVertexShader.txt";
    private static final String FRAGMENT_FILE = "src/shaders/terrainFragmentShader.txt";

    private int location_transformationMatrix;
    private int location_projectionMatrix;
    private int location_viewMatrix;
    private int location_lightPosition;
    private int location_lightColour;
    private int location_plane;

    private int location_backgroundTexture;
    private int location_sandTexture;
    private int location_stoneTexture;

    private int location_biomeMap[];

    public TerrainShader() {
        super(VERTEX_FILE, FRAGMENT_FILE);
    }

    @Override
    protected void bindAttributes() {
        super.bindAttribute(0, "position");
        super.bindAttribute(1, "textureCoordinates");
        super.bindAttribute(2, "normal");
    }

    @Override
    protected void getAllUniformLocations() {
        location_transformationMatrix = super.getUniformLocation("transformationMatrix");
        location_projectionMatrix = super.getUniformLocation("projectionMatrix");
        location_viewMatrix = super.getUniformLocation("viewMatrix");
        location_lightPosition = super.getUniformLocation("lightPosition");
        location_lightColour = super.getUniformLocation("lightColour");
        location_plane = super.getUniformLocation("plane");

        location_backgroundTexture = super.getUniformLocation("backgroundTexture");
        location_sandTexture = super.getUniformLocation("sandTexture");
        location_stoneTexture = super.getUniformLocation("stoneTexture");

        location_biomeMap = new int[Terrain.VERTEX_COUNT * Terrain.VERTEX_COUNT + Terrain.VERTEX_COUNT];
        for(int i = 0; i < location_biomeMap.length; i++) {
            location_biomeMap[i] = super.getUniformLocation("biomeMap[" + i + "]");
        }
    }

    public void loadClipPlane(Vector4f plane) {
        super.loadVector(location_plane, plane);
    }

    public void connectTextures() {
        super.loadInt(location_backgroundTexture, 0);
        super.loadInt(location_sandTexture, 1);
        super.loadInt(location_stoneTexture, 2);
    }

    public void loadTransformationMatrix(Matrix4f matrix) {
        super.loadMatrix(location_transformationMatrix, matrix);
    }

    public void loadLight(Light light) {
        super.loadVector(location_lightPosition, light.getPosition());
        super.loadVector(location_lightColour, light.getColour());
    }

    public void loadViewMatrix(Player camera) {
        Matrix4f viewMatrix = Maths.createViewMatrix(camera);
        super.loadMatrix(location_viewMatrix, viewMatrix);
    }

    public void loadProjectionMatrix(Matrix4f projection) {
        super.loadMatrix(location_projectionMatrix, projection);
    }

    public void loadBiomes(float[][] biomeMap) {
        for(int x = 0; x < Terrain.VERTEX_COUNT; x++) {
            for(int y = 0; y < Terrain.VERTEX_COUNT; y++) {
                super.loadFloat(location_biomeMap[x * Terrain.VERTEX_COUNT + y], biomeMap[x][y] * 128 + 127);
            }
        }
    }
}

```

From what I can tell, the code completely crashes when it tries to get a float our of `biomeMap`. No errors appears, however it is like a `return` is called and no color is loaded for the terrain - making it blank as if it were invisible. Why is it doing this and how can I fix it?

# Answer
There is a limit how many uniforms you can have. You can query the exact amount using glGetIntegerv with `GL_MAX_XXX_UNIFORM_COMPONENTS` where XXX is the shader stage name. This limit is quite generous, but it is still guaranteed **just 1024** in OpenGL 3.0+.
Even if there was no other error in your code and your machine had limit high enough to accommodate 128\*129 slots, it might not work on other machines due to said limitations. In addition, you should always check for shader linking/compilation errors using glGetShaderiv/glGetShaderInfoLog.
An alternative to your implementation using uniform float array could be, for example, textures which should be big enough to accomodate the array on any device.
> 1 votes

---
Tags: opengl, java, lwjgl
---


# Question
Title: LWJGL 3 how to convert screen coordinate to world coordinate?
I'm trying to convert screen coordinate to world coordinate on mouse click event. For LWJGL 3 there's not GLU utility class is available whereas LWJGL 2 has.

I'm using JOML math classes and wrote following code, but its returning wrong world coordinate, I'm doing something wrong and couldn't figure out.

On program init, I get viewProjMatrix and viewport:

```
viewProjMatrixUniform = glGetUniformLocation(this.program, "viewProjMatrix");
IntBuffer viewportBuffer = BufferUtils.createIntBuffer(4);
int[] viewport = new int[4];
glGetIntegerv(GL_VIEWPORT, viewportBuffer);
viewportBuffer.get(viewport);

```

On render loop, I calculate viewProjMatrix:

```
viewProjMatrix
    .setPerspective((float) Math.toRadians(30), (float) width / height, 0.01f, 500.0f) // define min and max planes
    .lookAt(eye_x, eye_y, eye_z,
            eye_x, eye_y, 0.0f,
            0.0f, 2.0f, 0.0f);
glUniformMatrix4fv(viewProjMatrixUniform, false, viewProjMatrix.get(matrixBuffer));

```

I convert screen coordinate to world coordinate with following code:

```
DoubleBuffer mouseXBuffer = BufferUtils.createDoubleBuffer(1);
DoubleBuffer mouseYBuffer = BufferUtils.createDoubleBuffer(1);
glfwGetCursorPos(window, mouseXBuffer, mouseYBuffer);
double x = mouseXBuffer.get(0);
double y = mouseYBuffer.get(0);
System.out.println("clicked at: " + x + " - " + y);

Vector3f v3f = new Vector3f();
viewProjMatrix.unproject((float)x, (float)y, 0f, viewport, v3f);
System.out.println("world coordinate: " + v3f.x + " - " + v3f.y);

```

Here's the full source code: https://gist.github.com/digz6666/48bb433c83801ea4b82fa194f05b4f02

# Answer
> 3 votes
There are to steps to converting cursor coordinates to world coordinates: 1) Convert the mouse coords to a direction. 2) Perform something like a raycast to find to world coordinate.

**Step 1**: First you will need to convert mouse coords to a direction. This is a simple illustration of how you could do this:

(Source: http://antongerdelan.net/opengl/raycasting.html)

I also recommend taking a look at this tutorial: https://m.youtube.com/watch?list=PLRIWtICgwaX0u7Rf9zkZhLoLuZVfUksDP&v=DLKN0jExRIM. You should be able to use the math classes with LWJGL 3, so you shouldn't have a problem.

**Step 2**: This part is the hardest out of the two, if you don't already have some sort of physics engine up and running that supports raycasting. If you don't have one available, then it shouldn't be that difficult if you know what you are doing. Try searching online for tutorials. I really like video tutorials, so I recommend spending some time one YouTube. There are a lot of tutorials over there that are really good.

---
Tags: opengl, java, lwjgl, lwjgl3
---


title: Rotation ascending into infinity?

text:
# Question
Title: Rotation ascending into infinity?
I'm creating a rotation for my sun to move, however it quickly extends to Infinity before going into NaN. I thought that taking advantage of the Matrix4f would make this much easier but it does as previously stated. Ideally should have the `sun` rotate around the `sunCenter`. Why is it doing this and how would I fix it?

```
private Vector3f getSunPosition() {
    double rotation = (time / DAY_LENGTH) * 360;
    Matrix4f matrix = new Matrix4f();

    Vector3f pos = sun.getPosition();
    matrix.m03 = pos.x;
    matrix.m13 = pos.y;
    matrix.m23 = pos.z;

    Matrix4f.rotate((float) Math.toRadians(rotation), sunCenter, matrix, matrix);

    return new Vector3f(matrix.m03, matrix.m13, matrix.m23);
}

```

I had it print out the Vector3f and rotation. The rotation looks a bit odd at first, however I can fix that another time.

```
Vector3f[1.0, 1.0, 1.0] 0.0
Vector3f[288375.56, 0.18377686, 287549.88] 79.41000366210938
Vector3f[1.96323607E11, -125296.0, 1.96323607E11] 158.82000732421875
Vector3f[1.05730567E17, 0.0, 1.05730567E17] 238.23001098632812
Vector3f[5.5935644E22, 0.0, 5.5935644E22] 240.02999877929688
Vector3f[2.9050322E28, 0.0, 2.9050322E28] 241.8300018310547
Vector3f[1.4801178E34, 0.0, 1.4801178E34] 243.6300048828125
Vector3f[Infinity, 0.0, Infinity] 243.8400115966797
Vector3f[Infinity, NaN, Infinity] 244.04998779296875
Vector3f[NaN, NaN, NaN] 244.25999450683594
Vector3f[NaN, NaN, NaN] 244.41000366210938
Vector3f[NaN, NaN, NaN] 244.55999755859375

```

# Answer
> 2 votes
Instead of rotating the sun position based on its current position, generate the sun position based on the parameter of time. That way you don't have repeated multiplications of the same value, and it will be easier for you to understand. I'm not familiar with the framework you're using but you might be able to just do something like this:

```
// Convert units of time to radians (one complete rotation per DAY_LENGTH)
const float time2radians = 2 * PI / DAY_LENGTH;
// Size of the sky in game units.
const float skyRadius = 999;

// Assume that the sky is rotating around the z axis, and the sun sits
//on the XZ plane. Assume that the world center is (0, 0, 0). Create a
// 3x3 matrix, multiply it by a unit vector to get a direction. Multiply
// The direction by the distance to the sun to get sun position.
vec3 getSun(float time) {
    return skyRadius * (Matrix3f.createRotationZ(time * time2radians)
                     * vec3(0, 0, 1));
}

```

---
Tags: opengl, 3d, rotation
---


# Question
Title: Make a bullet shape around model in libgdx
How do I make a btBoxShape around a Model or ModelInstance in Libgdx? This is my code:

```
modelInstance.calculateBoundingBox(boundingBox);
collisionShape = new btBoxShape(boundingBox.getDimensions(tempVector3).scl(.5f));

```

This works and creates a box of the right size but it is offset from the model. I cant figure out how to make it around the model and not offset.

# Answer
You have to use a `btMotionState` to synchronize model and bullet transforms. You use it like this (example taken from LibGDX wiki):

```
// Create your own implementation
public class MyMotionState extends btMotionState {
    Matrix4 transform;

    @Override
    public void getWorldTransform (Matrix4 worldTrans) {
        worldTrans.set(transform);
    }

    @Override
    public void setWorldTransform (Matrix4 worldTrans) {
        transform.set(worldTrans);
    }
}

// Then attach it to your body
btRigidBody body = ...;
ModelInstance instance = ...;
MyMotionState motionState = new MyMotionState();
motionState.transform = instance.transform;
body.setMotionState(motionState);

```

The wiki is a very good place to get information about how to use the wrapper. You should also check out Xoppa's blog on the subject as he goes into more in-depth solutions.
> 0 votes

# Answer
You are setting it to offset with scaling dimensions with 0.5f . Try not to scale it or just create new vector3 at {0,0,0} .

```
collisionShape = new btBoxShape(boundingBox.getDimensions(tempVector3));

```
> 0 votes

---
Tags: java, collision-detection, libgdx, models, bullet-physics
---


title: Raycast not hitting a collider

text:
# Question
Title: Raycast not hitting a collider
I have the following simple raycast from a capsule on a cube:

```
bool hit = Physics.Raycast
(transform.position, Vector3.down,
jumpSettings.groundJumpDistanceCheck,
jumpSettings.layerMask);

print(hit);

```

When my `layerMask` is 8 (terrain), I have set my layer on my cube and my `groundJumpDistanceCheck` is 2. Then my `hit` is ***false***.

When my `groundJumpDistanceCheck` is set to Infinity. Then my `hit` is still ***false***.

However when I remove the distance parameter:

```
bool hit = Physics.Raycast
(transform.position, Vector3.down,
/* jumpSettings.groundJumpDistanceCheck, */
jumpSettings.layerMask);

print(hit);

```

Then `hit` returns ***true***. This is odd for me, as far as I know when you exclude the distance parameter it's supposed to be Infinity by default. But when I explicitly give Infinity as the distance, it returns ***false***.

I have also used the following code in an attempt to debug my issue, using the desired distance `2f`

```
Debug.DrawRay(transform.position,
Vector3.down * jumpSettings.groundJumpDistanceCheck, Color.red, 60f);

```

As you can see, the ray does intercept the cube.

I need the reycast to return true with a distance of `2f`.

# Answer
So after doing some more research. I realized that the layermask param was **excluding** layers. This is what it should be:

```
bool hit = Physics.Raycast
(transform.position, Vector3.down,
jumpSettings.groundJumpDistanceCheck,
1 << jumpSettings.layerMask);

print(hit);

```
> 1 votes

---
Tags: unity, physics, mathematics, raycasting
---


title: Selecting objects

text:
# Question
Title: Selecting objects
I'm having some conceptual difficulties understanding an efficient and clean way to implement multiple object selection behaviour in game. Think of an RTS in which you can select different kinds of units and do different things with them. My preliminary thoughts are that maybe I should create an interface ISelectable and implement it on each of my units and buildings. Basically, I'm pretty sure I should avoid creating a bunch of bools like marineIsSelected, medicIsSelected, yetAnotherUnitIsSelected, etc., and setting them to true when I click on the appropriate colliders. But, I've also never used interfaces and don't really know what that would look like or if it would be any simpler.

Suppose I just have a blank project with 3 different kinds of objects which I want to be selectable in it. When I select Object A, I want to be able to then click somewhere and have that object move to that location. When I select Object B, I want similar behaviour to occur. When I select object C, I don't want to be able to move it, but build other objects from it (for example). Are interfaces what I'm looking for? Is there another way that's simpler and that I'm overlooking? I want to avoid using a bunch of conditional logic where I can since there will be lots of different kinds of objects.

# Answer
> 0 votes
There is always more than one way to solve a software architectre problem. But this is how I would approach the problem:

Create different MonoBehaviours for different features. Have a behaviour `Unit` which you add to all units, no matter what side they are on and if the player can select them or not. This should handle the main combat mechanics and store the unit stats (which you might want to manage with `ScriptableObject` assets, by the way, but that's a completely different topic). Have another behaviour `Selectable` which just does that: handling the user selecting and unselecting the unit and handling the gizmos which appear when a unit is selected.

When it's a unit the player can control, add a behaviour `Commandable`. This behaviour handles things which are common to everything the player can control, like set up the UI Hud for showing the unit status (drawing the data from the `Unit` component).

For everything more specific, add additional behaviours.

When a unit can receive move orders, add a behaviour `MoveCommandable`. When such an object is selected, have it listen to click mouse events and make it move around. When it can attack, also give it a behaviour `AttackCommandable` which processes attack click commands. When it is a building which can build units, give it a `UnitFactoryCommandable`. Each of these behaviours should also communicate with the general `Commandable` component by telling it what icons the player sees in their UI Hud regarding the actions the unit can perform.

---
Tags: unity, rts
---


# Question
Title: Gdx.input.setInputProcessor(stage) doesn't work
I have an image and I want to make clickable this image. I have already done this a lot of times, but this time doesn't work. Probably because the image is from a class which extends Image:

```
public class BitmapFontGenerale extends Image
{

BitmapFont bitmapFont;
String scritta;
private float x;
private float y;

public BitmapFontGenerale(BitmapFont bitmapFont1, String string, float scale)
{
    bitmapFont = bitmapFont1;
    bitmapFont.setColor(Color.BLACK);
    bitmapFont.getData().setScale(scale);
    scritta = string;
}

@Override
public void draw(Batch batch, float parentAlpha)
{
    bitmapFont.draw(batch,scritta,x,y);
}

public void setX(float x)
{
    this.x = x;
}

public void setY(float y)
{
    this.y = y;
}

public float getX()
{
    return x;
}

public float getY()
{
    return y;
}

}

```

This is the code which I used to set the input:

```
image.addListener(new ClickListener()
{
    @Override
    public void clicked (InputEvent event, float x, float y)
    {
       Gdx.app.log("CLICKED ", "CLICKED");
    }
});
stage.add(image);
Gdx.input.setInputProcessor(stage);

```

This code works if image is from Image class and not if it's from a class which extends Image. Note: I need to extend Image class. What's the problem?

# Answer
You must set size in constructor. If width and height equals 0, no clicks will be detected
> 1 votes

---
Tags: libgdx, input
---


# Question
Title: Relative quaternion rotation (delta rotation) produces unstable results
Use case: I have a `currentRotation` quaternion and a `targetRotation` quaternion and need to calculate the relative rotation between them - as in: what rotation do I need to apply to transform an object with `currentRotation` so that it has `targetRotation`.

Common solutions say that the delta rotation can be calculated by `qDelta = qFrom.inverse() * qTo`, which I use as well and works fine for **most** cases.

However, I am often running into issues for some specific rotations - Codepen Example here (I'm using three.js and coffeescript).

---

While a relative rotation around the z-axis works fine:

```
qFrom = (new THREE.Quaternion()).setFromAxisAngle new THREE.Vector3(0, 0, 1), 2 * (Math.PI / 6)
qTo = (new THREE.Quaternion()).setFromAxisAngle new THREE.Vector3(0, 0, 1), 5 * (Math.PI / 6)
qExp = (new THREE.Quaternion()).setFromAxisAngle new THREE.Vector3(0, 0, 1), 3 * (Math.PI / 6)
qDelta = calculateRelativeRotation(qFrom, qTo)
qResult = qDelta.clone().multiply(qFrom)

```

*Sane case results (delta): expected x: 0.0°, y: 0.0°, z: 90.0°, got x: 0.0°, y: 0.0°, z: 90.0°*

*Sane case results (result): expected x: 0.0°, y: 0.0°, z: 150.0°, got x: 0.0°, y: 0.0°, z: 150.0°*

... a more complicated rotation does not work out - the combination of `qFrom` and `qDelta` does not result in the expected `qTo` rotation:

```
eFrom = new THREE.Euler(0, 170 * dToR, 10 * dToR, 'XYZ')
eTo = new THREE.Euler(0, 170 * dToR, -10 * dToR, 'XYZ')
eExp = new THREE.Euler(0, 0, -20 * dToR, 'XYZ')

```

*Problematic case results (delta): expected x: 0.0°, y: 0.0°, z: -20.0°, got x: 0.0°, y: 0.0°, z: -20.0°*

*Problematic case results (result): expected x: -180.0°, y: 10.0°, z: 170.0°, got x: 176.5°, y: 9.4°, z: -149.7°*

*expected result quaternion (qTo): {'\_x':-0.086,'\_y':0.992,'\_z':-0.007,'\_w':0.086}* *

*actual result quaternion: {'\_x':0.257,'\_y':0.962,'\_z':-0.007,'\_w':0.086}*

---

Inverting the calculated delta rotations helps for some cases, but doesn't cover all cases.

What am I missing?

# Answer
> 3 votes
Thanks to Neal on Mathematics Stackexchange I found out that my code to calculate relative rotations was indeed in the wrong order (I took it from Unity Anwers which seems *not* to be the correct way to do it within three.js) - with the tricky part being that it worked out most times. So, the correct solution to calculate a relative rotation is

**qDelta = qTo * qFrom.inverse()**

---
Tags: mathematics, rotation, quaternion, three.js
---


title: How to blend multiple normal maps?

text:
# Question
Title: How to blend multiple normal maps?
I want to achieve a distortion effect which distorts the full screen. For that I spawn a couple of images with normal maps. I render their normal map part on some camera facing quads onto a rendertarget which is cleared with the color (127,127,255,255). This color means that there is no distortion whatsoever. Then I want to render some images like this one onto it:
If I draw one somewhere on the screen, then it looks correct because it blends in seamlessly with the background (which is the same color that appears on the edges of this image). If I draw another one on top of it then it will no longer be a seamless transition. For this I created a blendstate in directX 11 that keeps the maximum of two colors, so it is now a seamless transition, but this way, the colors lower than 127 (0.5f normalized) will not contribute. I am not making a simulation and the effect looks quite convincing and nice for a game, but in my spare time I am thinking how I could achieve a nicer or a more correct effect with a blend state, maybe averaging the colors somehow? I I did it with a shader, I would add the colors and then I would normalize them, but I need to combine arbitrary number of images onto a rendertarget. This is my blend state now which blends them seamlessly but not correctly:

```
    D3D11_BLEND_DESC bd;
    bd.RenderTarget[0].BlendEnable=true;
    bd.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
    bd.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
    bd.RenderTarget[0].BlendOp = D3D11_BLEND_OP_MAX;
    bd.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
    bd.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
    bd.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_MAX;
    bd.RenderTarget[0].RenderTargetWriteMask = 0x0f;

```

Is there any way of improving upon this?
(PS. I considered rendering each one with a separate shader incementally on top of each other but that would consume a lot of render targets which is unacceptable)

# Answer
> 0 votes
I am doing this by first remapping the normal map to the range \[-1,1\], then blending them onto a signed normalized 32 bit render target (DXGI\_FORMAT\_R8G8B8A8\_SNORM). The additive blend state I am using is of course like this:

```
BlendOp: ADD
SRCBlend: SRC_ALPHA
DSTBlend: ONE

```

The signed render target is first cleared to ZERO of course.

# Answer
> 2 votes
Have a look at Reoriented Normal Mapping, it will allow you to blend several normal maps on top of each other and give the intuitively expected result. The main idea is to transform the the normal to blend to the local space of the surface your blending on, or in this scenario, the normal mapped space of the surface.

---
Tags: directx11, blending
---


# Question
Title: Const returning C++ method can't be bound with LuaBridge
I have a method with this signature:

```
const std::string GameObject::GetName()

```

And then I try to bind it with this line:

```
...
.addFunction("getName", &GameObject::GetName)
...

```

When I try to compile, this error comes up:

```
Error C2440 '=': cannot convert from
'const std::basic_string<char,std::char_traits<char>,std::allocator<char>> *'
to
'void *'

```

The error comes from here:

```
\include\luabridge\detail\Userdata.h, line: 354

```

Here is a snippet from the `Userdata.h`

```
  inline T* getObject ()
  {
    // If this fails to compile it means you forgot to provide
    // a Container specialization for your container!
    //
    return reinterpret_cast <T*> (&m_storage [0]);
  }

private:
  /**
    Used for placement construction.
  */
  UserdataValue ()
  {
    m_p = getObject(); //Line 354
  }

```

I can use const, and const & std::string as parameters, in those cases there are no errors.

Why does this error occur? How could I fix this?

Thanks in advance!

# Answer
Sounds like a bug in LuaBridge, so you should report it.

As for fixing your project, just remove the `const`, it doesn't make sense anyway since you're returning a value.
> 3 votes

---
Tags: c++, lua
---


# Question
Title: Need help understanding VkCommandBuffer and VkCommandPool
I'm creating my first Vulkan project and I'm at the point where I need to send commands to the GPU. Now I need help understanding how and when commands are being executed and what sort of commands can be sent. I have a working example of where I clear the screen using the following.

Creating the Buffer

```
VkCommandBufferAllocateInfo commandBufferAllocateInfo{};
commandBufferAllocateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
commandBufferAllocateInfo.commandPool = engine.pipeline.command_pool;
commandBufferAllocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
commandBufferAllocateInfo.commandBufferCount = 1;

VkCommandBuffer commandBuffer = VK_NULL_HANDLE;

vkAllocateCommandBuffers(
    engine.device.instance,
    &commandBufferAllocateInfo,
    &commandBuffer
);

```

Clearing the screen

```
VkCommandBufferBeginInfo commandBufferBeginInfo{};
commandBufferBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
commandBufferBeginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;

engine.ErrorCheck(vkBeginCommandBuffer(
    commandBuffer,
    &commandBufferBeginInfo
));

VkRect2D renderArea{};
renderArea.offset.x = 0;
renderArea.offset.y = 0;
renderArea.extent = window->GetVulkanSurfaceSize();

std::array<VkClearValue, 2> clearValues{};
// Depth stencil
clearValues[0].depthStencil.depth = 0.0f;
clearValues[0].depthStencil.stencil = 0;
// Color
clearValues[1].color.float32[0] = 0.0f;
clearValues[1].color.float32[1] = 0.0f;
clearValues[1].color.float32[2] = 1.0f;
clearValues[1].color.float32[3] = 0.0f;

VkRenderPassBeginInfo renderPassBeingInfo{};
renderPassBeingInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
renderPassBeingInfo.renderPass = engine.window.renderPass;
renderPassBeingInfo.framebuffer = engine.window.framebuffers[engine.window.activeSwapchainImageId]; // Get current frame buffer
renderPassBeingInfo.renderArea = renderArea;
renderPassBeingInfo.clearValueCount = clearValues.size();
renderPassBeingInfo.pClearValues = clearValues.data();

vkCmdBeginRenderPass(
    commandBuffer,
    &renderPassBeingInfo,
    VK_SUBPASS_CONTENTS_INLINE
);

```

I'm finding it difficult to understand. I see that when you define a CommandBuffer you point to the pool that it will be submitted to, then when you execute the command it gets added to the queue to be processed asynchronously with the logic that is happening CPU side? I'm not sure if that is right.

Also, can the command buffer be used for other commands? and if so, what commands and how would I find example usage of them.

And what is a command pool in the scheme of things that is happening?

# Answer
> 2 votes
CommandPool are objects used to manage the allocation of CommandBuffers, and CommandBuffer is used to store the commands.

---

You almost got the mechanic of a CommandBuffer right.

A command buffer doesn't point to the pool; in fact, a CommandPool allocates the memory for CommandBuffers. The pool isn't the place where a command will be submitted; the place we actually want to submit them is the Queue. We must provide the Queue pointers of all CommandBuffer objects, to be submitted in the struct `VkSubmitInfo`, and submit them using `VkSubmitQueue`. After that, the commands in the queue will be taken, and executed.

If you have time, check out some tutorials on Vulkan-Tutorial. It explains everything you need, including the type of commands CommandBuffer stores.

# Answer
> 0 votes
The command buffer only starts executing after you submit the buffer to a queue.

All `vkCmd*` functions will add a command to a command buffer. Every such command is annotated in the spec with where they are allowed to be used (primary command buffer, inside or outside a renderpass) and which queues capabilities it needs.

---
Tags: c++, vulkan
---


# Question
Title: In Maya- how can I merge mulitple primitive cubes together into one parent item? (And is this actually needed for using in unity etc)?
Im trying to make some 3d models in Maya and then put them into Unity as characters which I can give rigidbody to etc. (Im new to Unity and 3d modelling software, but i have a small amount of programming experience in LWJGL, LibGDX and XNA).

I'm focusing on making some assets out of blocks. To give a kind of 2.5D feel to a platform game.

I have made the following image but as you'll see its just a bunch of cubes. I think i need this to be turned into a single piece (but im not sure if 100% necessary or not). Of course, I will be adding animation to this by way of moving the blocks about for different frames of animation.

As I said, im very new to this so I may be doing things completely wrong.

Heres the image:

What i need is to be able to refer to this as one piece with its own transform position, scale etc that I can adjust. Currently if I select it all and try to change the scale it only changes on of the cubes scale even when all are selected.

Also once I've created this and want to add it to my game in unity, will each cube get a rigidbody when i add it or will the whole item get it as standard?

Thanks for any help

# Answer
What I was taught to do in Maya was to first remove faces that are inside of the model. These are unnecessary and up the poly count for unused faces. You can do this by selecting faces with the RMB and using delete on the desired faces.

You'll next want merge based off edges or off vertices.

Use the RMB again and choose vertices or edges, select all the ones you wish to merge, go to edit mesh, and hit merge.

You have to do them bit by bit because if you try to merge them all at once they'll merge onto an average point and ruin the model. You can alter how close they merge together by changing the threshold.

Try this video for assistance as well. You know it works when there's only one vertex and not two. You can also tell that by selecting a single vertex (that you intended to merge to) and dragging it around. If they've properly merged you won't be able to drag a vertex and have it separate into two, and it should move the whole side, and there won't be gaps in the edges (if you drag it away you won't suddenly see inside the model).

Notes based off some comments you made:

* There won't be a parenting structure that you can see changed like Unity has.
* When you import it into Unity, Unity *should* see it as a complete model, granted it's *actually* a complete model. If none of the pieces are connected, they won't be in Unity.
* It's good to do this as you go but it's not necessary.
* I was actually taught to build based off one item. So start with a cube and just build from there, so that you're not doing this cut and merge etc. This basically involves adding vertices to the cube and pulling them out to grow the original cube into the model you want.
> 1 votes

---
Tags: 3d, 3d-meshes, maya, rigid-body-dynamics, 3d-modeling
---


# Question
Title: Cardboard VR Mode rendering black in Unity
I've searched around and seen this problem is quite common, but none of the fixes I've read have resolved the issue: If VR Mode is enabled in the GvrViewerMain prefab, the scene will render as just a black screen.

I've set the Graphics API to OpenGLES2, I've disabled Multithreaded Rendering, I've disabled direct render, yet this continues to be an issue.

This happens both within unity itself and if it is built and run to my phone. Has anybody encountered this problem/do you know of any further steps to take to resolve the issue?

# Answer
Using `VR mode enabled = true` , try `Distortion Correction (Unity or Native)`
> 1 votes

# Answer
Add a camera into gvrviewermain, it solved the problem.
> -3 votes

---
Tags: unity, virtual-reality
---


# Question
Title: What's a proper way to change colors of a sprite on the fly in libGDX?
I have found a great tutorial series on creating a simple 2D side scroller, Super Mario Brothers, in this case, and I believe I can adapt it fairly well to create a Megaman clone(something I am quite familiar with so that I can focus on learning the code and not necessarily the mechanics).

What has been challenging me is how to swap colors on Megaman when the chosen weapon is changed. I've found a few options, but I am unsure which one is viable.

1. Having each color as a separate sprite sheet
    * PRO:
        + simplest implementation I believe
    * CON:
        + increased footprint size of overall app
2. Converting the texture to a Pixmap, changing the colors I want, convert back to a texture and render as normal?
    * PRO:
        + no increase in app size
    * CON:
        + Is this done on reach render cycle or can I change it once and forget about it until a new weapon change?
3. Shaders
    * PRO:
        + ??
    * CON:
        + From what I am reading, it sounds like they can only change on color at a time? Do I use 2 shaders?
        + They can only be applied wholly to the render and not per sprite?

Thanks.

# Answer
It seems that doing the pixmap conversion would be your best bet. Especially if your thinking of using alot of colors. Once you convert it back to a texture the colors are retained so you wouldnt need to continuously swap colors during your runtime. If you wanted to, you could even load separate textures for each color before the game starts to save processing time. Shaders could work, but as you said, it would be applied to everything on the screen. But if you were to use some shaders, they could change two colors through frame buffers and such, it would just be really heavy on your game.

Overall, you should go with your pixmap idea. Good luck with your code :)
> 1 votes

# Answer
Another option is to create a black and white or grayscale version of the character spritesheet and then tint it using SpriteBatch.setColor() before rendering the character, based on the appropriate color for the currently equipped weapon.

This option doesn't increase the overall size (like option 1) or memory/cpu usage (like option 2) of the app, and is significantly less complex than option 3 for someone who is learning.

Just make sure you setColor() back to Color.WHITE after drawing the player sprite or everything drawn after that will also be tinted.

Regarding the shader option, it is possible to apply a shader to just a single sprite (sort of), but it would involve rendering the player sprite to an offscreen FrameBufferObject while applying the tinting shader and then compositing that back onto the main scene.
> 1 votes

# Answer
To achieve this behaviour, you should definitely use a specific shader. If you apply the shader to your sprite batch before drawing your sprite and set it back to null, it will just apply to your sprite and not to the entire screen.

You can drive the colours using a few uniforms depending on the power the user have enabled.

See this question for more details:

https://stackoverflow.com/questions/24099103/libgdx-changing-sprite-color-while-hurt

you basically need the same thing with some colour swapping in your shader.
> 1 votes

# Answer
To color your sprite simply use the `Sprite#setColor(color)` method. This will tint your sprite with the selected color. Make sure to have the parts of your sprite that you want to be colored to be *completely white*. That way the blending will tint them with 100% of the new color.
> 0 votes

---
Tags: java, libgdx, sprites
---


title: Roblox script: Can't get "IntValue"?

text:
# Question
Title: Roblox script: Can't get "IntValue"?
I am new to Roblox scripting (Lua apparently) and was fiddling with a function that is called when one Part (dubbed the "Sender") is touched by another Part, which is actually a tool with a Part called "Handle" inside of it, and a third Part nested inside that. I have also added an IntValue to the latter to be read upon touching.

The object tree looks like this:

```
__Apple (Tool)
  L_Handle (Part)
    L_TouchInterest
    L_Value (IntValue)
    L_Apple (Part)
    L_Handle-to-Part Strong Joint

```

The function is called alright, and the part with the name "Handle" is correctly identified, but I cannot for the world get a hold of the IntValue using the following code:

```
function onTouch(hit)
    print("Sender touched by "..hit.Name)
    local val = hit:FindFirstChild("IntValue", true)
    if val == not nil then
        print("Found IntValue: "..val.Name)
        if val.Name == "Cash" then
            --Get Money For Apple
            print("Players: "..game.Players.LocalPlayer.Name)
            game.Players.LocalPlayer.leaderstats.Money.value = game.Players.LocalPlayer.leaderstats.Money.value + val.value
        end
    else
        print("IntValue Not Found!")
    end
    hit:Destroy()
end
script.Parent.Touched:connect(onTouch)

```

In other words: It keeps on logging "IntValue Not Found"! I have changed the name of the IntValue to "Value" and back to "IntValue" to no avail. I have been adding clones of it to several different layers of the composite object, but no results.

Any help is greatly appreciated!

BTW The object is a Tool, because the player is supposed to be able to pick it up and place it on the "Sender".

# Answer
> 2 votes
I think your misunderstanding is based around what `val == not nil` means. The expression `not nil` evaluates to `true`, so the if-statement is really saying—

```
if val == true then

```

That only evaluates to `true` when `val` is *exactly* the Boolean value `true`. For example, `'true' == true` is `false`.

As your answer indicates you've discovered, when you change the predicate to just—

```
if val then

```

—you will find that any values other than `false` and `nil` are "truthy" and will pass the `if`-statement. This is explained by the Lua manual in §3.3.4:

> The condition expression of a control structure can return any value. Both **false** and **nil** are considered false. All values different from **nil** and **false** are considered true (in particular, the number 0 and the empty string are also true).

---

If you find yourself using Lua a lot, I highly recommend reading through the rest of the Reference Manual too. It's exceptionally clearly written.

# Answer
> 0 votes
I figured out the answer myself, although I do not fully understand why, it does stem from my inexperience with Lua. I was trying to transfer my habits from other programming languages.

This line:

```
if val == not nil then

```

Needs to be changed to:

```
if val then

```

And now it works!

Apparently what is returned by the FindFirstChild() method is a Boolean?

---
Tags: lua, roblox
---


# Question
Title: How to manage changing Z-Index in an Entity-Component-System?
If got an Entity Component System based game-project (like classic zelda).

* The Player as well as Enemys are Entities with sprite- and tranform-components.
* The Weapons are also Entities with sprite- and tranform-components.
* The player and the Enemies can pickup weapons.
* Weapons got an ParentComponent so they will be rendered realtive to the Carrier-Entity.
* There is a script/system for that.
* No everytime an player/enemy walks upwards, the weapon must rendered BEHIND/under the carrier for the illution, that the player walks to the top of the screen.
* I will do this by switching the Z-Index of the transform-component of the carrier with the one of the weapon.
* Unfortunately, the rendering system is a Sorted-Iterating-System which holds a sorted list of all entities with Sprite-Components so everytime Im changing the Z-Index of an Entity, I have to force the re-sortening of the list.
* This works but sorting an entire list in java almost every gamellop-update sounds very bad.

Is this really a good idea or should I try something else? BTW: In practice, Im using libGdx with Ashley as the ECS.

# Answer
I'm going to agree with @Sidar in the comments- this probably isn't an issue, and I don't see a better implementation given the libraries you're using.

If you look at the Ashley/libGDX implementation, the SortedIteratingSystem ultimately uses TimSort each time you resort it. While TimSort has a big-O of O(n log n), when working on a nearly-sorted array it typically does even better than that.

The only other way to handle this would be to create your own equivalent to SpriteBatch that allows you to pass an actual z coordinate when you render the plane your sprite is painted on. If you want to stay true to the spirit of ECS systems, you should keep your current system, and then if you find that this z-index sorting causes a noticeable issue in your game, create a separate replacement system with your custom spritebatch.
> 1 votes

---
Tags: libgdx, entity-system, game-loop, sorting
---


title: Alternatives to raycasts in unity?

text:
# Question
Title: Alternatives to raycasts in unity?
I have an ai car script. The car needs to be able to slow down and or stop if it gets too close to another car. Right now I'm using 3 raycasts like so:

```
if (Physics.Raycast(lRay, out lHit, rs.forwardCollisionRayLength, rs.rayLayerMask) || Physics.Raycast(rRay, out rHit, rs.forwardCollisionRayLength, rs.rayLayerMask) || (Physics.Raycast(mRay, out mHit, rs.forwardCollisionRayLength, rs.rayLayerMask)))
{
    //some code...
}

```

However this is really long and inconvenient because it's a pain to figure out which raycast actually had the hit. And then there's other cases where multiple raycasts hit the same car, which point do I use, or if different raycasts hit different cars...Anyway, you can see that this is not ideal.

Also, depending on the size of an object, it could go between the raycasts. In the image below, the blue box is ok because its wider than the width between the raycasts, thus two of the raycasts find it. But on the other side, the green pole is too small, so the car can't see it and drives on.

I also need to get the distance between the hit.point and the car so that I know how much the car needs to slow down so that there's a reasonable distance between the two cars at all times.

I could use something like `Physics.OverlapBox` or `Physics.CheckBox` but then I can't get the distance between the closest point of the car, only the center of it. This is bad because some cars are longer than others - I need the distance between the nearest point of the car.

Also, keep performance in mind, I could solve the problem of objects going in between raycasts by adding more, but that will drain performance hugely, mainly because I have up to about 40 cars running at a time.

**TL;DR: What are some alternatives for a raycast that can also give me the distance to the closest point?**

# Answer
I asked a question here similar to this. The answer I posted there also solved this problem.

This is the code I used:

```
Collider[] cols = Physics.OverlapBox(position, scale, rotation, layerMask);
Vector3 bestPoint = Vector3.zero;
float closestSqrDistance = Mathf.Infinity;

for (int i = 0; i < cols.Length; i++)
{
    Vector3 pos = cols[i].ClosestPointOnBounds(centerPosition);
    Vector3 direction = pos - centerPosition;
    float sqrDist = direction.sqrMagnitude;

    if (sqrDist < closestSqrDistance)
    {
        closestSqrDistance = sqrDist;
        bestPoint = pos;
    }
}

```

In short, it gets all of the colliders intersecting a box, loops through all of them to find the closest point out of all the colliders and then calculates the distance based on that.
> 0 votes

# Answer
There are other types of casts. Sounds like you might get some use out of Physics.BoxCast. Like the RayCast, BoxCast will return hit data that you can use to get all the same information as you would from a RayCast.

Also available, SphereCast or CapsuleCast. See the documentation for details.
> 3 votes

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


title: Oblique Projection in Directx?

text:
# Question
Title: Oblique Projection in Directx?
Making a 3d scene in my game(stereographic double projection). I was looking for a Direct X version of a LH or RH Matrix for oblique projection. Does directx have a function or will I have to make my own?

# Answer
> 2 votes
DirectXMath doesn't have a function for computing stereo projection matrices in the standard library.

There is code for creating a stereo projection (right-handed) in the Windows 8.1 Store app Direct3D stereoscopic 3D sample in the `Stereo3DMatrixHelper.h/.cpp` files.

There is also a prototype of a stereo projection helper with additional controls which you can find on the DirectXMath GitHub as Stereo3DMatrixHelper.h / .cpp

---
Tags: directx
---


title: How can I make an object "solid"?

text:
# Question
Title: How can I make an object "solid"?
In Valve's software Hammer (Counter-Strike Global Offensive SDK Hammer software, for reference), I have created several props that I plan to have players jump on. However, players pass right through this prop.

How can I make it so that a prop is solid, and so that players can't walk right through the prop? Also, the prop is a static prop.

# Answer
I downloaded Hammer to try this out. Looks like this is how you do it:

1. With the Selection tool active, double click the object you want to make solid.
2. Set its class to `prop_static`
3. Select Collisions from the property list
4. To the right of the property list, change the value in the drop down from `Not Solid` to either `Use Bounding Box` or `Use VPhysics`

(The image numbers are actually -1 from the steps listed, oops)
> 4 votes

# Answer
Idk if this is helpful but changing it to prop\_physics\_multiplayer might be useful
> -3 votes

---
Tags: valve, hammer
---


# Question
Title: Set custom Yaw Pitch and Roll in Three.js
So I have the following struct in C++, it gets updates with the values of an program that uses a camera in spectator mode:

```
struct SCameraInfo
{
    Utils::Vector3 Position;
    float Matrix[3][3];
    float FieldOfView;
};

```

I'm sending these values through websockets to an HTML5 app running on my iPhone. I want to set these values in a **Free Camera mode** of a Three.js scene but don't know how to do it. As far I can tell I know the Position, View Matrix and Fov, but not sure of how to apply them to the three.js camera.

The problem is that I don't know which methods call or how to apply the lookAt for example.

This is a kind of yaw pitch and roll camera and not Quaternion based.

Here is and example of the values:

```
position 2721.35 -390.34 107.15
view mat 0.47 -0.67 0.57
view mat 0.82 0.57 0.00
view mat -0.33 0.47 0.82
FOV      0.10

```

I've been searching for the most easiest example but all of them seem to use Quaternions.

# Answer
> 1 votes
I think that: How to convert a 3x3 rotation matrix into 4x4 matrix may help you on getting a 4X4 matrix.

"to convert a 3x3 matrix to a 4x4, you simply copy in the values for the 3x3 upper left block, like so:"

```
[ a11  a12  a13 ]
[ a21  a22  a23 ]
[ a31  a32  a33 ]

```

That 3x3 becomes this 4x4

```
[ a11  a12  a13  0 ]
[ a21  a22  a23  0 ]
[ a31  a32  a33  0 ]
[   0    0    0  1 ]

```

Then you can use setRotationFromMatrix ( m )

considering that Camera is a subclass of Object3D and that `m` is a 4X4 matrix

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


title: Merging box colliders for optimization

text:
# Question
Title: Merging box colliders for optimization
Look at the picture.

The figure on the left shows the individual box colliders in green.

The yellow boxes on the right are the results of the optimization of the original box colliders.

What is the algorithm that makes this possible?

# Answer
Sure you can.

Assuming you have a list of `BoxCollider` that need to be combined, you can access each of their `bounds` properties, which consist of the boxes' `center` and `extents`. With this two information in mind, you can easily calculate the minimum and maximum x, y, and z coordinates of the boxes.

The combined `BoxCollider` will have these two corners:  and . From upper and lower corners, you can calculate the center and extents of the combined `BoxCollider`.

All you need to do later is remove or disable initial `BoxCollider`s in your list.
> 2 votes

---
Tags: unity, algorithm, collider
---


# Question
Title: Why am I having these errors, when opening my Unity project in Ubuntu?
I'm experiencing some trouble with the Linux build of Unity. I suspect that my Nvidia driver is producing this error, but I'm really not sure. I have an Nvidia GTX 860M, and until 2 days ago, I was able to use Unity without any problems. I have not touched my computer in those 2 days. My operating system is Ubuntu 14.04.

This is the error that I get in my editor log:

> ATTENTION: default value of option force\_s3tc\_enable overridden by environment. \[1010/122616:ERROR:gpu\_channel\_host.cc(148)\] GpuChannelHost::CreateViewCommandB$ \[1010/122616:ERROR:webgraphicscontext3d\_command\_buffer\_impl.cc(256)\] Failed to $ \[1010/122616:ERROR:gpu\_channel\_host.cc(148)\] GpuChannelHost::CreateViewCommandB$ \[1010/122616:ERROR:webgraphicscontext3d\_command\_buffer\_impl.cc(256)\] Failed to $ \[1010/122616:ERROR:gpu\_channel\_host.cc(148)\] GpuChannelHost::CreateViewCommandB$ \[1010/122616:ERROR:webgraphicscontext3d\_command\_buffer\_impl.cc(256)\] Failed to $ \[1010/122616:ERROR:gpu\_channel\_host.cc(148)\] GpuChannelHost::CreateViewCommandB$ \[1010/122616:ERROR:webgraphicscontext3d\_command\_buffer\_impl.cc(256)\] Failed to $ ATTENTION: default value of option force\_s3tc\_enable overridden by environment. /home/MyUser/Unity3d/Age UpdateMenuTitleForLanguage: 10 Receiving unhandled NULL exception Launching bug reporter

Why am I having these errors, when opening my Unity project in Ubuntu?

# Answer
While only a broad explanation for future users, Unity does not actually currently support Linux or Ubuntu. Looking at the system requirements page, Linux is not listed as a supported platform; furthermore, it is not listed as an available platform in the archive for previous builds.

> ## System Requirements for Unity 5.6
>
> ### For development
>
> **OS:** Windows 7 SP1+, 8, 10; Mac OS X 10.8+.
> <sub>\- Official Unity system requirements page</sub>

---

As far as I was aware, there *is* a version of Unity available for Linux and Ubunutu; however, they are not *officially* supported. I have previously found versions on the official website, but even in these cases, the developers acknowledged that said versions were buggy. I can not find these versions, now; perhaps I have missed them, perhaps they have been taken down.
> 0 votes

# Answer
As one of the answers did mention, Linux is ***not officially supported***.
We get those releases just because Unity development team is kind enough to give us at least something. Imagine an endless number of distributions and libraries and kernels they have to support if they announce it - that's like digging your own grave.
Your best bet is to get latest release, Unity 2017 as of recently
(https://forum.unity3d.com/threads/unity-on-linux-release-notes-and-known-issues.350256/)
And do try latest Ubuntu, since big chances are Unity team is using it. Just to prove that Unity is actually doing *some* work on Linux releases, refer to the state of Unreal Engine. Unreal does not even provide releases for Linux. The only way is to build it from source and see that it's basically unusable: graphical artifacts, 100% cpu load and silky-smooth 10 fps.
> 0 votes

---
Tags: unity, linux
---


title: Gyroscope inaccuracy

text:
# Question
Title: Gyroscope inaccuracy
I have this code which is **rotating my camera object based on Gyro** it is working fine

```
public void CalibrateYAngle()
    {
        calibrationYAngle = appliedGyroYAngle - initialYAngle; // Offsets the y angle in case it wasn't 0 at edit time.
    }

    void ApplyGyroRotation()
    {
        transform.rotation = Input.gyro.attitude; //
        transform.Rotate(0f, 0f, 180f, Space.Self); // Swap "handedness" of quaternion from gyro.
        transform.Rotate(90f, 180f, 0f, Space.World); // Rotate to make sense as a camera pointing out the back of your device.
        appliedGyroYAngle = transform.eulerAngles.y; // Save the angle around y axis for use in calibration.
    }
 public void Update() {

            ApplyGyroRotation();
            ApplyCalibration();

    }

```

but sometime my camera start to rotate slowly slowly automatically. It slowly rotate left or right but sometime not always. What I am doing wrong? due to inaccurate sensors values?

# Answer
> 1 votes
This is a known problem with low-cost gyroscopes mounted in phones and it's called `drift`. Try to put your phone on a desk and read gyro values for some time. Even when you don't move your phone the readings will probably change in time.

There's no direct solution for this, you can't make it more precise but one of the workarounds is to use other physical sensors to help to 'fix' the gyro readings. Unfortunately there are many different sensors used in different phones so it may be very hard to find some reliable solution.

For some quick and dirty test I'd try to limit the minimal rotation per time span or frame:

* Remember orientation from the last frame.
* If current orientation differs more than some threshold - apply it.
* If current orientation differs less than some threshold - remember it as a last frame orientation.
* Let us know if it helped :).

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


title: How can I make a Soft Outline Shader?

text:
# Question
Title: How can I make a Soft Outline Shader?
Most Outline Shaders or Tutorials found online, are Shaders which are sharp edge-outlines. Like here:

Even though a lot of games are already using soft outlines like here:

with a nice gradienty- blurry effect.

Creating a Outline is basically easy (as described here: http://wiki.unity3d.com/index.php/Silhouette-Outlined\_Diffuse)

Also ive seen that wanted effect in 2D: https://www.assetstore.unity3d.com/en/#!/content/84126

But how do they do it in 3D?

Ive found a useful step-by-step guide here: (https://willweissman.wordpress.com/tutorials/shaders/unity-shaderlab-object-outlines/) . But the first step is already not working. (rendering the 3d object in as pure white to a rendertexture).

# Answer
> 1 votes
Sooo after keeping myself busy finding all my mistakes about the tutorial ive made in this: https://willweissman.wordpress.com/tutorials/shaders/unity-shaderlab-object-outlines/)

I would like to provide a very simple solution- where you dont even have to understand shaders at all.

1. Create a new Camera Gameobject which only Renders things you want in a **RenderTexture**. That Rendertexture will later have the Outline. (Set the Culling Mask to a new "Outline" layer. Set the Layer of the Objects you want the outline for to the same layer.)  Also create a new RenderTexture and put it inside "TargetTexture" of your camera.
2. Put this script inside that camera gameobject

```
public class OutlineEffect : MonoBehaviour
{
    public bool Gauss;

    public Material WhiteMaker;
    public Material PostOutline;
    public Material GaussianBlur;

    private Camera cam;

    void Start()
    {
        cam = GetComponent<Camera>();
    }

    void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        RenderTexture TempRT = new RenderTexture(cam.pixelWidth, cam.pixelHeight, 24);
        RenderTexture whiteRT = new RenderTexture(TempRT.width, TempRT.height, TempRT.depth);

        Graphics.Blit(source, whiteRT, WhiteMaker);
        if (Gauss)
        {
            Graphics.Blit(whiteRT, TempRT, PostOutline);
            Graphics.Blit(TempRT, destination, GaussianBlur);
        }
        else
        {
            Graphics.Blit(whiteRT, destination, PostOutline);
        }
    }
}

```
3. put these shaders inside a material with the same name and put those materials inside that script in step 2.

**WHITEMAKER SHADER**

```
Shader "WhiteMaker" {
    Properties
    {
        _MainTex("Main Texture 1", 2D) = "white" {}
    }

    SubShader
    {
        Tags{ "Queue" = "Transparent" }
        Pass
        {
            Blend SrcAlpha OneMinusSrcAlpha
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            sampler2D _MainTex;
            half _SampleTime;

            v2f_img vert(appdata_base v)
            {
                v2f_img o;
                o.pos = UnityObjectToClipPos(v.vertex);
                o.uv = v.texcoord.xy;
                return o;
            }
            float4 frag(v2f_img i) : COLOR
            {
                // Surface
                float4 main = tex2D(_MainTex, i.uv);
                if (main.a == 0)
                {
                    return float4(0, 0, 0, 0);
                }
                else
                {

                    return float4(1, 1, 1, 1);
                }
                return main;
            }
                ENDCG
            }
    }
}

```

**POST OUTLINE SHADER**

```
// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with

'UnityObjectToClipPos(*)'

Shader "Custom/Post Outline"
{
    Properties
    {
        _MainTex("Main Texture",2D) = "black"{}
    _SceneTex("Scene Texture",2D) = "black"{}
    }
        SubShader
    {
        Pass
    {
        CGPROGRAM

        sampler2D _MainTex;
    float4 _MainTex_ST;

    //<SamplerName>_TexelSize is a float2 that says how much screen space a texel occupies.
    float2 _MainTex_TexelSize;

#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
    struct appdata
    {
        float4 pos : POSITION;
        float2 uv : TEXCOORD0;
    };

    struct v2f
    {
        float4 pos : SV_POSITION;
        float2 uv : TEXCOORD0;
    };

    v2f vert(appdata v)
    {
        v2f o;
        o.pos = UnityObjectToClipPos(v.pos);
        o.uv = o.pos.xy / 2 + 0.5;
        return o;
    }

    half frag(v2f i) : COLOR
    {
        //arbitrary number of iterations for now
        int NumberOfIterations = 20;

    //split texel size into smaller words
    float TX_x = _MainTex_TexelSize.x;

    //and a final intensity that increments based on surrounding intensities.
    float ColorIntensityInRadius;

    //for every iteration we need to do horizontally
    for (int k = 0; k<NumberOfIterations; k += 1)
    {
        //increase our output color by the pixels in the area
        ColorIntensityInRadius += tex2D(
            _MainTex,
            i.uv.xy + float2
            (
            (k - NumberOfIterations / 2)*TX_x,
                0
                )
        ).r / NumberOfIterations;
    }

    //output some intensity of teal
    return ColorIntensityInRadius;
    }

        ENDCG

    }
        //end pass

        GrabPass{}

        Pass
    {
        CGPROGRAM

        sampler2D _MainTex;
    sampler2D _SceneTex;

    float4 _MainTex_ST;

    //we need to declare a sampler2D by the name of "_GrabTexture" that Unity can write to during GrabPass{}
    sampler2D _GrabTexture;

    //<SamplerName>_TexelSize is a float2 that says how much screen space a texel occupies.
    float2 _GrabTexture_TexelSize;

    #pragma vertex vert
    #pragma fragment frag
    #include "UnityCG.cginc"
    struct appdata
    {
        float4 pos : POSITION;
        float2 uv : TEXCOORD0;
    };

    struct v2f
    {
        float4 pos : SV_POSITION;
        float2 uv : TEXCOORD0;
    };

    v2f vert(appdata v)
    {
        v2f o;

        //Despite the fact that we are only drawing a quad to the screen, Unity requires us to multiply vertices by our MVP matrix, presumably to keep things working when inexperienced people try copying code from other shaders.
        o.pos = UnityObjectToClipPos(v.pos);

        //Also, we need to fix the UVs to match our screen space coordinates. There is a Unity define for this that should normally be used.
            o.uv = o.pos.xy / 2 + 0.5;
        o.uv = TRANSFORM_TEX(v.uv, _MainTex);

        return o;
    }

    half4 frag(v2f i) : COLOR
    {
        //arbitrary number of iterations for now
        int NumberOfIterations = 20;

    //split texel size into smaller words
    float TX_y = _GrabTexture_TexelSize.y;

    //and a final intensity that increments based on surrounding intensities.
    half ColorIntensityInRadius = 0;

    //if something already exists underneath the fragment (in the original texture), discard the fragment.
    if (tex2D(_MainTex,i.uv.xy).r>0)
    {
        discard;
        return tex2D(_SceneTex,float2(i.uv.x,1 - i.uv.y));
    }

    //for every iteration we need to do vertically
    for (int j = 0; j<NumberOfIterations; j += 1)
    {
        //increase our output color by the pixels in the area
        ColorIntensityInRadius += tex2D(
            _GrabTexture,
            float2(i.uv.x,1 - i.uv.y) + float2
            (
                0,
                (j - NumberOfIterations / 2)*TX_y
                )
        ).r / NumberOfIterations;
    }

    //this is alpha blending, but we can't use HW blending unless we make a third pass, so this is probably cheaper.
    half4 outcolor = ColorIntensityInRadius*half4(0,1,1,1) * 2 + (1 - ColorIntensityInRadius)*tex2D(_SceneTex,float2(i.uv.x,1 - i.uv.y));
    return outcolor;
    }

        ENDCG

    }
        //end pass
    }
        //end subshader
}
//end shader
^
[POST OUTLINE SHADER ENDS HERE]

```

**GAUSSIAN BLUR SHADER**

```
Shader "Blur"
{
    Properties
    {
        _MainTex("Base (RGB)", 2D) = "white" { }
    }

    SubShader
    {
        ZTest Always Cull Off ZWrite Off Fog{ Mode Off }

        Pass
        {
            CGPROGRAM

            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            sampler2D _MainTex;
            float4 _MainTex_TexelSize;
            float step_w;
            float step_h;

            struct v2f
            {
                float4  pos : SV_POSITION;
                float2  uv : TEXCOORD0;
            };

            float4 _MainTex_ST;
            float4 _MainTex_ST_TexelSize;

            v2f vert(appdata_base v)
            {
                v2f o;
                o.pos = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
                return o;
            }

            fixed4 frag(v2f i) : COLOR
            {
                step_w = _MainTex_TexelSize.x;
                step_h = _MainTex_TexelSize.y;

                float2 offset[25] =
                {
                    float2(-step_w*2.0, -step_h*2.0), float2(-step_w, -step_h*2.0),  float2(0.0, -step_h*2.0), float2(step_w, -step_h*2.0), float2(step_w*2.0, -step_h*2.0),
                    float2(-step_w*2.0, -step_h),     float2(-step_w, -step_h),      float2(0.0, -step_h),     float2(step_w, -step_h),     float2(step_w*2.0, -step_h),
                    float2(-step_w*2.0, 0.0),         float2(-step_w, 0.0),          float2(0.0, 0.0),         float2(step_w, 0.0),         float2(step_w*2.0, 0.0),
                    float2(-step_w*2.0, step_h),      float2(-step_w, step_h),       float2(0.0, step_h),      float2(step_w, step_h),      float2(step_w*2.0, step_h),
                    float2(-step_w*2.0, step_h*2.0),  float2(-step_w, step_h*2.0),   float2(0.0, step_h*2.0),  float2(step_w, step_h * 20),   float2(step_w*2.0, step_h*2.0)
                };

                float kernel[25] =
                {

                    0.003765,    0.015019,    0.023792,    0.015019,    0.003765,
                    0.015019,    0.059912,    0.094907,    0.059912,    0.015019,
                    0.023792,    0.094907,    0.150342,    0.094907,    0.023792,
                    0.015019,    0.059912,    0.094907,    0.059912,    0.015019,
                    0.003765,    0.015019,    0.023792,    0.015019,    0.003765
                };

                float4 sum = float4(0.0, 0.0, 0.0, 0.0);

                for (int j = 0; j < 25; j++)
                {
                    float4 tmp = tex2D(_MainTex, i.uv + offset[j]);
                    sum += tmp * kernel[j];
                }

                return sum;
            }

        ENDCG //Shader End
        }

    }

}

```
4. create a new "raw image" inside a UI canvas. Put the Rendertexture inside that Rawimage. And set the Camera Height and Width as the image Height and Width.
5. Its done! You can check the "Gauss" bool true or false- depends on which you prefer. Also you can change the color of the raw image

---
Tags: unity, shaders, outline
---


# Question
Title: Designing RPG player classes, and the trend to avoid a Priest or Cleric RPG class
From my experience, RPG classes ("hero" or "villain" types) are often divided into four categories: 1. Mage 2. Priest 3. Rogue 4. Warrior

However, there are quite a few popular RPGs that ignore the Priest or Cleric "base" character class entirely. Two game series of note: The Elder Scrolls (Skyrim), and Dragon Age.

Is there a specific reason why this is so? Perhaps the background story makes allowing players to be a Cleric difficult; for example, if there is a large amount of NPCs in the game that have the adventure class of Cleric, and making that class available to players would be detrimental to the story of the game.

I've pondered this quandary myself when working on developing my own video RPG; should the character class options be sub-categorized with the aforementioned base classes? Or perhaps even more difficult of a question to answer, should a video RPG include some kind of Deity system?

The RPG approach to "gods" is difficult for me, particularly because I've have somewhat of a spiritual perspective on real life, I'm not sure how to reconcile my choices with game design to my choices regarding spirituality.

Any helpful responses will be greatly appreciated!

# Answer
> From my experience, RPG classes ("hero" or "villain" types) are often divided into four categories: 1. Mage 2. Priest 3. Rogue 4. Warrior

These broad classifications derive ultimately from Dungeons & Dragons and the way it developed its class systems.

Broadly speaking, a "Warrior" is someone who deals combat damage based on items (swords, bows, etc). As such, they either have weapons with no ammunition (most melee weapons) or weapons with relatively large quantities of ammunition (quivers tend to hold 25+ arrows). This means that their damage is fundamentally reliable, but it does usually require that they carry around certain items (namely, weapons).

A "Mage" under such classification is distinguished by having the ability to do lots of damage, either to single targets or large groups. Alternatively, they can inhibit the ability of enemy characters to attack effectively or make them vulnerable. The primary issue here is one of "ammunition"; they can have big effects, but they can only do them a more limited number of times relative to other classes.

A "Rogue" is... less well defined. The modern Rogue-like classes have evolved into being specialized fighters: they can deal lots of damage, but only in special circumstances (sneak attacks). Older Rogues had sneak attacks, but their primary class features were out of combat: unlocking chests/doors, climbing walls, information gathering, etc.

A "Priest" in this classification is a class based on healing/buffing the party. While they can deal damage, they can generally not do so as well or as reliably as "Warriors", and rarely can achieve the battle-changing effects of "Mages". Their first duty is to keep everyone alive.

Which is why RPGs that don't involve a fairly large party of characters generally don't have pure-"Priest" classes. If you have 5 characters in an encounter, it's reasonable to have one character primarily or solely dedicated to keeping everyone alive. If you only have 2 characters, it's much more difficult to take half of the group's firepower away just to keep the other half alive.

In such games, you will generally find healing powers scattered among other classes. Fighter/Healers, Wizard/Healer, etc. Alternatively, there just won't be any character-specific healing at all; there is only item-based healing that anyone can use, or automatic healing out-of-combat or whatever.

This is why MMOs tend to be the kinds of RPGs that frequently provide a dedicated healer class. Or at least, a class that is mostly about healing.

> Or perhaps even more difficult of a question to answer, should a video RPG include some kind of Deity system?

Character classes are, from a pure gameplay standpoint, are just a set of rules. You can provide any kind of storyline justification for it.

Priests as a *religious* concept became associated with healing in RPGs thanks to D&D. D&D is ultimately based on the mythology and folklore of Western Europe (as partially interpreted by fantasy authors like Tolkien). Wizards are a thing because they're a part of various such tales. Clerics are a part of that; in religious mythology, there are many tales of religious people healing the sick or even raising the dead.

But that's all just the in-world *justification* for the in-game abilities (or you could say that the myths inspired the gameplay. But the gameplay is the gameplay that it is). So that doesn't have to be your game's concept and justification for healing.

Your game may need the function of a healer class. But such a class doesn't need actual deities involved to justify healing abilities.
> 2 votes

# Answer
Trying to answer the seemingly various questions, not just "why have and what are priests/clerics".

**tl:dr** There's no *should* and *must* when you're designing your own game. Do what sounds fun to you, make something you're passionate about. Sure take ideas or good practice from other games, but unless you're working on someone else's game, there's no need to be a cookie cutter.

---

> From my experience, RPG classes ("hero" or "villain" types) are often divided into four categories: 1. Mage 2. Priest 3. Rogue 4. Warrior

While this is true, it's not an end all be all standard to follow and you're allowed to make your game however you want, there's no *rule* that says, you *need* categories X, Y and Z, with classes 1, 2, 3 and sub-classes Alpha, Beta, Omega.

> However, there are quite a few popular RPGs that ignore the Priest or Cleric "base" character class entirely. Two game series of note: The Elder Scrolls (Skyrim), and Dragon Age.

That's because some RPGs don't have set class systems. Those single player RPGs tend to offer a range of abilities, skills and other features that allow you to "be the character you want to be". In Skyrim there's not a "Priest or Cleric" but you can most certainly spec into restoration.

Something like a WoW has set classes that you play as because it's a part of the game. You need Tanks, Healers, DPS classes to have an overall successful raid or large scale game-play, but again, this is just a trend, it doesn't mean it's the only way to make an RPG.

> Is there a specific reason why this is so? Perhaps the background story makes allowing players to be a Cleric difficult; for example, if there is a large amount of NPCs in the game that have the adventure class of Cleric, and making that class available to players would be detrimental to the story of the game.

It really has nothing to do with backstory and it's more about the freedom to play how you want to play (especially in single player). RPGs are about *role playing*. Being allowed to be what you want and do what you want is an enormous part of their appeal.

The games like MMORPGs or D&D as was mentioned, have these common classes because they make sense, they're familiar and a bit of a standard.

> I've pondered this quandary myself when working on developing my own video RPG; should the character class options be sub-categorized with the aforementioned base classes? Or perhaps even more difficult of a question to answer, should a video RPG include some kind of Deity system?

You *can* make sub-classes sure, but you don't *have* to. As I've continued to mention, there's no requirement for what you do in *your* game. Some trends might be expected, but at the end of the day they aren't required.

In a Medieval RPG someone would expect a sword, or a bow. If you give them a laser gun and say you're a sniper class, that makes no sense. Things should make sense, and those are the types of trends (sensible choices and successful game designs) you should be aiming to follow.

> The RPG approach to "gods" is difficult for me, particularly because I've have somewhat of a spiritual perspective on real life, I'm not sure how to reconcile my choices with game design to my choices regarding spirituality.

If it's difficult for you, don't do it. You're allowed to make a game about God classes or Diety characters, but again, if this is *your* game, you're making the decisions. Go make an RPG about mice fighting back against the Owl overlords if that's what you're passionate about.

If your concern is that a priest is too close to your faith/spirituality, then add healing abilities (if those are needed) to a different character. Name it cleric, wizard, bard, or alchemist or any of the other suggested or common names.

It's so much easier to make something when your heart is in it, "is difficult for me" screams do something else, which isn't a bad thing.
> 2 votes

# Answer
The archetypical "Priest" or "Cleric" class as interpreted by most RPG games is a support class. They usually can not win a battle on their own. They rather support other characters in winning battles. This means they are only interesting and useful if part of a larger group.

The TES series, though, focuses mostly on the one player-character. Sure, the player can have *one* follower and *one* summoned creature, but these are usually not much more than a talkative pack-mule and a way of distracting enemies. The character which is expected to actually get stuff done is still the player-character. Playing a supporting class simply doesn't work in such a game.

But if you decide to interpret the priest-class in your game in a way which makes it more interesting to play solo, or make the player a part of a large group of NPCs and manage to design supporting gameplay in an interesting manner, then there is no reason to not let the player play one.
> 0 votes

---
Tags: game-design, rpg
---


# Question
Title: MovingPlatform - move position1 to position2 then wait for 3 sec
I have one PlatformManager (Script Attached)

One is Position-1

One is Position-2

One is MovingPlatform

I want. MovingPlatform move Position-1 to Position-2 then wait for 5 Sec

then MovingPlatform move Position-2 to Position-1 then wait for 5 Sec

**Here is code for PlatformManager & its working fine without Wait**

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

public class MovingPlatform : MonoBehaviour
{
    public Transform movingPlatform;
    public Transform position1;
    public Transform position2;
    public Vector3 newPosition;
    public string currentState;
    public float smooth;
    public float resetTime;

    private void Start()
    {
        ChangeTarget();
    }

    private void FixedUpdate()
    {
        movingPlatform.position = Vector3.Lerp(movingPlatform.position, newPosition, smooth * Time.deltaTime);
    }

    void ChangeTarget()
    {
        if (currentState == "Moving To Position 1")
        {
            currentState = "Moving To Position 2";
            newPosition = position2.position;
        }
        else if (currentState == "Moving To Position 2")
        {
            currentState = "Moving To Position 1";
            newPosition = position1.position;
        }
        else if (currentState == "")
        {
            currentState = "Moving To Position 2";
            newPosition = position2.position;
        }
        Invoke("ChangeTarget", resetTime);
    }
}

```

**I have tried this code but MovingPlatform didnt Wait**

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

public class TestMovingPlatform : MonoBehaviour
{
    public Transform movingPlatform;
    public Transform position1;
    public Transform position2;
    public Vector3 newPosition;
    public string currentState;
    public float smooth;
    public float resetTime;

    IEnumerator Start()
    {
        while (true)
        {
            yield return StartCoroutine(ChangeTarget());
            yield return new WaitForSeconds(3.0f);
        }
    }

    private void FixedUpdate()
    {
        movingPlatform.position = Vector3.Lerp(movingPlatform.position, newPosition, smooth * Time.deltaTime);
    }

    IEnumerator ChangeTarget()
    {
        if (currentState == "Moving To Position 1")
        {
            currentState = "Moving To Position 2";
            newPosition = position2.position;
        }
        else if (currentState == "Moving To Position 2")
        {
            currentState = "Moving To Position 1";
            newPosition = position1.position;
        }
        else if (currentState == "")
        {
            currentState = "Moving To Position 2";
            newPosition = position2.position;
        }
        Invoke("ChangeTarget", resetTime);
        yield return null;
    }
}

```

**Also i tried This but not success**

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

public class TestMovingPlatform : MonoBehaviour
{
    public Transform movingPlatform;
    public Transform position1;
    public Transform position2;
    public Transform position3;
    public Vector3 newPosition;
    public string currentState;
    public float smooth;
    public float resetTime;

    IEnumerator Start()
    {
        while (true)
        {
            yield return StartCoroutine(ChangeTarget());
        }
    }

    private void FixedUpdate()
    {
        movingPlatform.position = Vector3.Lerp(movingPlatform.position, newPosition, smooth * Time.deltaTime);
    }

    IEnumerator ChangeTarget()
    {
        if (currentState == "Moving To Position 1")
        {
            currentState = "Moving To Position 2";
            newPosition = position2.position;
            yield return new WaitForSeconds(3);
        }
        else if (currentState == "Moving To Position 2")
        {
            currentState = "Moving To Position 1";
            newPosition = position1.position;
            yield return new WaitForSeconds(3);
        }
        else if (currentState == "")
        {
            currentState = "Moving To Position 2";
            newPosition = position2.position;
            yield return new WaitForSeconds(3);
        }
        Invoke("ChangeTarget", resetTime);
        yield return null;
    }
}

```

Here i attached Screenshot of Hirerchy & Inspector

Also i tried other different MovingPlatform Scripts but MovingPlatform's movement is jerky when player ride on it.

Only this script. MovingPlatform's movement is smooth when Player ride on it. So, I used this string script.

Anyone idea how to solve this?

# Answer
> -1 votes
Call your co routine only once instead

```
 void Start()
{
    StartCoroutine(ChangeTarget());
 }

private void FixedUpdate()
{
    movingPlatform.position = Vector3.Lerp(movingPlatform.position, newPosition, smooth * Time.deltaTime);
}
IEnumerator ChangeTarget()
    {
        if (currentState == "Moving To Position 1")
        {
            currentState = "Moving To Position 2";
            newPosition = position2.position;
            yield return new WaitForSeconds(3);
        }
        else if (currentState == "Moving To Position 2")
        {
            currentState = "Moving To Position 1";
            newPosition = position1.position;
            yield return new WaitForSeconds(3);
        }
        else if (currentState == "")
        {
            currentState = "Moving To Position 2";
            newPosition = position2.position;
            yield return new WaitForSeconds(3);
        }
        yield return null;
      StopCoroutine(ChangeTarget());
     StartCoroutine(ChangeTarget());

    }

```

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


# Question
Title: Unity rotating camera around specific Vector
I'm making a game in which the player controlls a ball. (Wow, such originality^^) It's a 3rd person game so the camera is slightly above and behind it. The ball is being controlled via WASD. Now the tricky part is, I want this to work totally independent from the worldaxis so or example even upside down. So in my PlayerControllerScript I have an array of three vectors which represent the new X,Y and Z axis of my ball. The X axis always points in the direction the sphere is moving. The Y axis is calculated by the forces influencing the body. So if the gforces on the body are strong enough, for example while rolling along a craterslope, my Y axis is going to be horizontal. The Z axis is always orthogonal to the firs two.

So much for the explanation. So the camera is always being offset according to those new axis' and then pointed in direction of the gameobject using this line:

T.rotation = Quaternion.LookRotation (TargetTrans.position - T.position);

T being the Camera's transform. I don't really understand this line but it works. My problem is, that this makes the camera always parallel to the horizon, but I want the camera to tilt with the objects movement. So when I'm rolling in circles on a craterslope it should not be parallel to the horizon but to the slope. I tried to Rotate the Transform of the camera around the calculated X axis like so:

T.Rotate(PlayerScript.Orientation\[0\] , Vector3.Angle(Vector3.ProjectOnPlane( Physics.gravity,PlayerScript.Orientation\[0\]) ,OtherScript.Orientation\[1\]) );

Notice that I'm taking the angle between my calculated Y axis and the gravity beeing projected onto the YZ Plane of y calculated orientation. Like this I avoid unwanted tilting, for example when moving straight up the crater slope away from the center. However this line doesn't change anything visually. What's wrong? It's not because the rotation is changed right afterwards with the first command I gave, because the Rotate command comes after it.

I'm starting to realize rotation is a lot more complicated than I thought and eventhough this has to be a very common problem in for all peple who develop games with planes, I couldn't find anything. :(

Help me please... Thanks in advance.

I also realize how hard this even is to explain so let me know if something is not clear.

# Answer
> 0 votes
You're going to laugh at how easy this is. ;)

You know this line?

```
T.rotation = Quaternion.LookRotation (TargetTrans.position - T.position);

```

Add your ball's vertical axis as a second parameter:

```
T.rotation = Quaternion.LookRotation (
                TargetTrans.position - T.position,
                OtherScript.Orientation[1]);

```

(You might need to negate that second parameter if your vertical axis points down toward the ball's ground plane, rather than up & away)

How this works:

1. `TargetTrans.position - T.position` is a vector pointing from your camera to the object.
2. `Quaternion.LookRotation` constructs a rotation that rotates the forward axis to point in the direction of that first argument. So that gets the camera looking in the direction toward the ball.
3. The second direction is optional, and it's used to give a hint for where the local "up" vector of the rotating object should point. By default/if omitted, it uses `Vector3.up = (0, 1, 0)`, which is what keeps the camera oriented level vs the horizon. But if you provide your own up vector, it will try to roll the object around the look direction to keep its local up aligned with the second direction you provide.

One last little note is that, for working in Unity, you'll likely have an easier time if you adopt Unity's coordinate system conventions. There Z represents "forward" (see eg. `Vector3.forward`) and X represents "right", so it's flipped relative to the axis naming you described for your ball. Keeping one consistent coordinate convention will help avoid mistakes and bugs.

---
Tags: unity, rotation
---


# Question
Title: How do I change windows commands to android commands?
I created a game and would like to test it on android, but it does not respond to any touch on the screen, I think it's because I have to adapt the game code for android. Click =\> Touch

I developed it and tested it with the selected target (windows):

I was able to put it to run on an android virtual machine, but it does not respond to any commands:

How could he do that?

How to adapt the function =\> `if (point_in_rectangle(window_mouse_get_x(),window_mouse_get_y(),60,250,104,313)) && config==false` for example? For something that works for android.

I hope I have been clear. What I want exactly is to turn all game mouse clicks into screen touches.

Sorry for any translation error and thank you already

# Answer
> 1 votes
I found the solution. The code I posted in the question works for the application on windows, to make it work for android is just modifying it as follows:

`if (point_in_rectangle(window_mouse_get_x(),window_mouse_get_y(),60,250,104,313)) && config==false` \<= becomes =\> `if device_mouse_x(0)>=60 && device_mouse_y(0)>=250 && device_mouse_x(0)<=104 && device_mouse_y(0)<=313{`

Link =\> https://docs.yoyogames.com/source/dadiospice/002\_reference/mouse,%20keyboard%20and%20other%20controls/device%20input/index.html

---
Tags: android, game-maker
---


title: Three.js recover camera values

text:
# Question
Title: Three.js recover camera values
When I start the script, camera has starting values. When I will move it and click button to set up startign values it is never same. What values I missed?

The best way, I suppose, it is to look at the example: http://jsfiddle.net/VsWb9/6652/

I used console.log for debbuging camera values.

HTML:

```
<button id="buttonTest">
TEST
</button>
 Please, move cube before click!
<div id="wrapper">

</div>

```

JS:

```
var camera, scene, renderer, geometry, material, mesh;

init();
animate();

function init() {
        window.wrapper = document.getElementById('wrapper');
    var buttonTest = document.getElementById('buttonTest');
    buttonTest.addEventListener('click', function() {
        test();
    });

    scene = new THREE.Scene();

    camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 10000);
    camera.position.z = 500;
    scene.add(camera);

    geometry = new THREE.CubeGeometry(200, 200, 200);
    material = new THREE.MeshNormalMaterial();

    mesh = new THREE.Mesh(geometry, material);
    scene.add(mesh);

    renderer = new THREE.WebGLRenderer({
        preserveDrawingBuffer: true
    });
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.setClearColor(new THREE.Color("hsl(193, 50%, 57%)"));

    wrapper.appendChild(renderer.domElement);

        controls = new THREE.TrackballControls(camera, renderer.domElement);
    controls.rotateSpeed = 4.0;
    controls.zoomSpeed = 1.2;
    controls.panSpeed = 0.1;
    controls.noZoom = false;
    controls.noPan = false;
    controls.staticMoving = true;
    controls.dynamicDampingFactor = 0.3;
    controls.keys = [ 65, 83, 68 ];
    controls.addEventListener( 'change', render );

     console.log('camera_default: '+camera.position.x+', '+camera.position.y+', '+camera.position.z);
    console.log('quaternion_default: '+camera.quaternion.x+', '+
            camera.quaternion.y+', '+camera.quaternion.z+', '+camera.quaternion.w);
}

function animate() {

    requestAnimationFrame(animate);
    controls.update();
    render();

}

function render() {
        camera.lookAt(scene.position);
    renderer.render(scene, camera);
}

function test() {
        // lines below shows actual settings
    console.log('camera_now: '+camera.position.x+', '+camera.position.y+', '+camera.position.z);
    console.log('quaternion_now: '+camera.quaternion.x+', '+
            camera.quaternion.y+', '+camera.quaternion.z+', '+camera.quaternion.w);

    window.setTimeout(function() {
        // this is recovering camera values like
        // it was on the sart of script
        // it is not enought, what I missed?
        camera.position.x = 0;
        camera.position.y = 0;
        camera.position.z = 500;
        camera.quaternion.x = 0.0;
            camera.quaternion.y = 0.0;
            camera.quaternion.z = 0.0;
            camera.quaternion.w = 1.0;

        console.log('camera_recover_default: '+camera.position.x+', '+camera.position.y+', '+camera.position.z);
        console.log('quaternion_recover_default: '+camera.quaternion.x+', '+
            camera.quaternion.y+', '+camera.quaternion.z+', '+camera.quaternion.w);
        },1500);
}

```

# Answer
Example solution using *reset()*, *updateProjectionMatrix()* and *update()* methods:

```
controls.reset();
camera.position.x = 13.5;
camera.position.y = 0;
camera.position.z = -165;
camera.updateProjectionMatrix();
controls.update();

```
> 0 votes

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


title: MMO Player Position Update

text:
# Question
Title: MMO Player Position Update
I have been looking at the development of MMO games for a while and have got stuck up on one thing. Player Movement. If we have an area with 10 players, each player needs to be able to see the orientation and position of other players. But when players start moving I need to update the ten players locations simultaneously. If I were to use an MYSQL database it would be slow and laggy to send coordinates and get coordinates from the database everytime a player moved. What would be the professional and proper (more efficient) way of doing this?

# Answer
> 1 votes
You wouldn't store the positions of any currently ingame-players in a MySQL database. Databases are for data at rest, not for data in use. You would use a database to persist the state of player-characters when they go offline and retrieve it again when they come online again. Data in use (anything which is relevant for current gameplay) should be in the game-server's memory for fast access.

---
Tags: movement, mmo, server, synchronization
---


# Question
Title: LibGDX - Camera and viewport initialization in show()?
I'm reading the book LibGDX game development by example and the author tends to follow a pattern like

```
 public class MyGame extends Game {
      @Override
      public void create() {
          setScreen(new GameScreen(this));
      }
      ...
 }

 public class GameScreen extends ScreenAdapter {
     private Viewport viewport;
     private Camera camera;
     private final MyGame myGame;

     // code omitted for brevity

     public GameScreen(MyGame myGame) {
         this.myGame = myGame;
     }

     @Override
     public void show() {
         camera = new OrthographicCamera();
         camera.position.set(WORLD_WIDTH / 2, WORLD_HEIGHT / 2, 0);
         camera.update();
         viewport = new FitViewport(WORLD_WIDTH, WORLD_HEIGHT, camera);
         ...
     }

```

It seems to me that creating a new camera and viewport in the show() method is not correct, as it would create new objects every time the screen becomes active (eg when the game has multiple screen and the user can switch between them). So my questions:

* Am I correct in my reasoning? Should the camera and the viewport be created in the GameScreen class constructor?
* Would it be possible/advisable to have just a single camera and viewport shared by all screens?

# Answer
## TL;DR

Create viewports separate from your screens and simply supply them as parameters wherever needed (i.e. your point 2).

---

There is no "correct" way to do it design wise per-se but if we go a bit deeper and start to think about garbage collection (GC) this is not good design at all. Realistically you should probably have 2 viewports:

1. Game: Used to render your game.
2. UI: Used to render your UI separate from your game.

These should be initialized separate from your screens and then passed into your screens as parameters of some form (`new GameScreen(uiViepwort, gameViepwort)`). This means that you limit GC by only creating these once during the entire lifecycle of your game.

If you for some reason need separate viewports / cameras per screen you should create it in the constructor for the same reason mentioned above.

You *should* however update the state of these objects in the `show()` method - *not* in the constructor - to ensure that the state is updated every time you show the screen to the user.

## But then why put it in the show method in the first place?

The reason I used to do this was just a misunderstanding of the framework. As you may (or may not) know you have to put all initialization logic into or after your `create()` method of your game. To understand why let's say you decided to create 2 viewports and pass them into your screens as parameters. You might do something like this:

```
public class MyGame extends Game {
    /*Game is a constant size*/
    private final Viepwort game = new FitViewport(1920, 1080);
    /*UI stretches to fill the screen*/
    private final Viepwort ui = new StretchViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());

    @Overrite
    public void create() {
        setScreen(new GameScreen(this, game, ui));
    }
}

```

This will crash the game. Can you spot the bug? We are using `Gdx.graphics` before it is initialized! `Gdx.graphics` is initialized just before `create()` is called, but the viewports are created before that! Things like this just led me to assume that I should initialize all variables in the `show()` method as well, even though I don't have to.

## Slight pet peeve

Please don't do this:

```
camera = new OrthographicCamera();
camera.position.set(WORLD_WIDTH / 2, WORLD_HEIGHT / 2, 0);
camera.update();
viewport = new FitViewport(WORLD_WIDTH, WORLD_HEIGHT, camera);

```

This is equivalent to doing this:

```
viewport = new FitViewport(WORLD_WIDTH, WORLD_HEIGHT);
viewport.apply(true); // true = center camera

```

Viewport creates its own camera, you don't have to create one yourself unless you're going to use a camera that isn't `OrthographicCamera`.
> 1 votes

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


# Question
Title: What is a bank payment gateway concept upon publishing a game app?
I was asking a local bank about the possibility of transferring money to my account there upon publishing a paid app on play store. The reply was that they have their own payment gateway that deducts a percentage of the profits besides monthly and yearly charges.

My first question is what exactly is a payment gateway? (The information written on google about this is very confusing and very broad that after hours of research I still do not know what exactly is the benefit of a gateway.)

My second question is do all banks around the world impose this "gateway"deduction?

I always thought that money is transferred directly from google to the concerned developer's bank account without the concept of gateway. Please correct me if am wrong.

Thank you!

# Answer
Usually when you take payments online you forward the user to a page on another site to handle the payment.

That site is the payment gateway. They expect compensation for handling the actual transaction usually in terms of a percentage of the amount or a recurring fee.

Using a gateway like that involves setting up tokens during transactions and letting that site verify the transaction to your server directly,etc. It's fiddly but less likely to go horribly wrong (as in leaking users' account information getting sued and losing your business over it) than trying to handle those things yourself.
> 0 votes

---
Tags: publishing
---


# Question
Title: how to disable enum if bool is not true in inspector unity
I want to enable an `enum` when a `bool` value is true through the inspector and disable it when the value is `false`. Please see the relevant code below:

```
public bool hasWeapon;

[System.Serializable]
public enum WeaponType {HandGun, Sword, ShotGun, Spear, BowAndArrow};

public WeaponType weaponType;

```

From the above code `weaponType` should only appear in the inspector if `hasWeapon` is `true`.

How can this be done?

# Answer
You have to create your own inspector script where you manually draw the layout of the inspector for the type you're interested in. With custom inspector scripts you can display the information you want and need depending on any value of your object.

Plenty of tutorials on it :https://unity3d.com/learn/tutorials/topics/interface-essentials/building-custom-inspector
> 1 votes

---
Tags: unity
---


# Question
Title: Variable value in inspector is not updating automatically?
Something weird is happening when I change a variable value in script and hit play the var value doesn't update I have to reset the script in inspector. Is this normal? Aren't the values suppose to update when we hit play?

*The Simple Code I used to test this:*

```
var a:int=0;

function Start () {
print(a);
}

```

# Answer
> 1 votes
The editor serializes the value for what you've set in the inspector prior to changing it in code. It doesn't matter if you change the value of `a` in script. The editor only cares about the serialized values, after the object is created.

When you hit play it takes the value you've set in the inspector.

# Answer
> -1 votes
I found a very simple solution: initializing the variables inside the `Start()` function.

Like such:

```
var a:int=0;

function Start () {
    a = 0;
    print(a);
}

```

---
Tags: unity, unityscript
---