# Question
Title: Voxel (Marching Cubes) Terrain Creation / Terrain Editing
im working on a voxel based game in unity. the terrain(sphere--\>planet) should be out of voxels and at first i built a minecraft like voxel plugin for unity. this means that i had a sphere out of cubes, but as you can imagine, a sphere out of cubes just doesn't look good :P (i made a level array which stored the material at \[x,y,z\]. --\> so when "1" stands for stone, it means that level\[x,y,z\] = 1; was stone. but then i decided to use the marching cubes algorithm for my voxel planet. so i learned the marching cubes algorithm and i realised that now i must have a density function, and not a level array with material information.

my density function looks like this:

x * x + y * y + z * z - rad - (noise.FractalNoise3D (x, y, z, oct, frec, amp) * scale);

The noise is made by a simplex noise generator script. so far so good. i get a good sphere rendered with a little bit of noise. but when i try to edit the sphere (terrain editing) i run into problems.

i made a function which gets the collision coordinates(x,y,z) of the mouse and the sphere, and changes the density in the level array at these coordinates.:

void dig(){ Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit;

```
    if (Physics.Raycast (ray, out hit)) {
        Debug.Log ("Dig...");
        Debug.DrawLine(ray.origin,ray.origin+( ray.direction*hit.distance), Color.green,2);
        editTerrain(hit);
    }
}

void editTerrain(RaycastHit hit){
    int xEn = (int) hit.point.x;
    int yEn = (int) hit.point.y;
    int zEn = (int) hit.point.z;

    level [xEn, yEn, zEn] += 1000;

    mesh = MarchingCubes.CreateMesh (level);
    mesh.uv = new Vector2[mesh.vertices.Length];
    mesh.RecalculateNormals ();
    GetComponent<MeshFilter> ().mesh = mesh;
    GetComponent<MeshCollider>().sharedMesh=mesh;
}

```

my problems/questions now:

-is the density function alone enough for my level array? did i understand terrain creation right so far?

-when i try to edit the terrain (add something to the density at levelArray\[x,y,z\], it just flats the surface, but doesn't dig holes.

-when i want to add materials to my voxel planet (stone, dirt, sand, etc...), can i make another array, which holds the material data at \[x,y,z\]? are there better possibilities?

-i also realised that when i turn my sphere in the unity editor, my colission detecten gets displaced. like when i want to edit the top of the sphere, the bottom of the sphere gets changed...

-btw...i know i didn't apply chunks to my voxel planet yet...this comes later...

i hope anybody can help me because i don't know what to do.

# Answer
> 2 votes
marching cubes deals with voxel densities between -1 and 1 and alters the geometry of each cube based on its own density compared to the densities around it. this mean that it can actually put faces(triangles) within sections of space that contain less than zero density. In such cases trying to change the value at that section (using a FloorToInt function or whatever) with be like setting zero to zero. it's easy to deal with with simple cubes, but when you get into marching cubes and dual contouring you need to start working with normals and/or ray direction.

If your code thinks it has hit something but when you run a check it's actually hit a zero (or -1 in marching cubes) weight cube you need to tell it to keep looking to find what it was supposed to have hit.

you can mess with the target setting of marching cubes. you can also treat space in 27s instead of 1s by treating the hit point as the center and looping through -1 to +1 in x,y,z and setting them all to -1. This will make certain there is clear hole where you are digging. Otherwise the surfaces around it might all blend together and never reveal the next level down in your digging.

---
Tags: unity, terrain, voxels, sphere, marching-cubes
---


title: Java-script map/array "undefined"

text:
# Question
Title: Java-script map/array "undefined"
Hi when I call the the function below in the chrome console it tells me "Type error cannot read property '2' of undefined" why?.

defining the map:

```
var map = {
FALL:[
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [3, 0, 0, 2, 0, 0, 0, 3, 0, 0, 3]
    ],
}

```

Function:

```
    for (i = 0; i < 4; i++) {
    console.log(map.FALL[pmx-i]
    [pmy-1]);
    if(map.FALL[pmx-i][pmy-1] > 0){
        return true;
        break;
    }

```

by the way pmx = 1 pmy=3

# Answer
In the third iteration of the loop, `pmx-i` is equal to -1, `map.FALL[-1]` is undefined and `undefined[pmy-1]` is an error since you can't access an index of undefined.
> 1 votes

---
Tags: collision-detection, javascript, html5
---


title: Perspective projection?

text:
# Question
Title: Perspective projection?
I am trying to write an elite like game and I kind of understand the maths behind it but it would be really helpful if someone could explain it.

# Answer
> 0 votes
This link explains it way better than most could in a short answer here: http://www.tomdalling.com/blog/modern-opengl/explaining-homogenous-coordinates-and-projective-geometry/

In summary: 4x4 matrices are used in graphics so that homogeneous coordinates (which are 4d) can be used.

This is important because it allows for both perspective and translation.

W is the fourth component of the vectors and can be seen as the distance between the projector and the surface that is being projected on.

To convert a 4d homogeneous vector to a 3d vector, you literally just divide X,Y and Z by the W component.

A neat side effect of this is that a vector with a W component of zero is a point at infinity in homogeneous coordinates. This is why you sometimes see vectors described with a 0 in the W vector component, while points have a 1 in the W component. This is most often seen when talking about point lights vs directional lights. Directional lights are essentially point lights that are infinitely far away.

Also, to help understand how dividing X,Y,Z by W does projection, converting 3d coordinates to 2d screen coordinates can be done in a similar manner. To convert from (X,Y,Z) to (X',Y') you just do this:

X' = X/Z
Y' = Y/Z

The fourth component (W) of the homogeneous coordinates performs the same role, to map 4d points in homogeneous coordinates to a 3d point that can then be converted to 2d and put on the screen.

---
Tags: 3d, mathematics, graphics
---


# Question
Title: Disable/Remove Warning about a not bound Render Target View
So to render into my shadow map depthstencil buffer i only bind a DepthStencilView to the Output Merger. Like this

```
    m_pContext->OMSetRenderTargets(0,0, m_pShadowMapDV);
    m_pContext->ClearDepthStencilView(m_pShadowMapDV, D3D11_CLEAR_DEPTH, 1.0f, 0);

```

Now this works fine and my shadow-map also produces the desired result. What bothers me though is the constant warnings in the debug-window. Is there a way or trick to disable that warning?

```
D3D11 WARNING: ID3D11DeviceContext::DrawIndexed: The Pixel Shader expects a Render Target View bound to slot 0, but none is bound. This is OK, as writes of an unbound Render Target View are discarded. It is also possible the developer knows the data will not be used anyway. This is only a problem if the developer actually intended to bind a Render Target View here. [ EXECUTION WARNING #3146081: DEVICE_DRAW_RENDERTARGETVIEW_NOT_SET]

```

This might be a pretty dumb question, but after googling a lot i still came up empty. Only i a lot of people who are not doing this on purpose.

**EDIT:** Maybe the question can be asked in another way:

Is there a way to define an empty PixelShader? If i define the return value as void it notifies me, that i have to at least return the 4 pixel colors. If i don't give it any Semantics it does not work either.

# Answer
You can suppresses messages from the debug layer:

```
#include <wrl/client.h>
using Microsoft::WRL::ComPtr;

#ifndef NDEBUG
    ComPtr<ID3D11Debug> d3dDebug;
    hr = m_d3dDevice.As(&d3dDebug);
    if (SUCCEEDED(hr))
    {
        ComPtr<ID3D11InfoQueue> d3dInfoQueue;
        hr = d3dDebug.As(&d3dInfoQueue);
        if (SUCCEEDED(hr))
        {
            D3D11_MESSAGE_ID hide [] =
            {
                D3D11_MESSAGE_ID_SETPRIVATEDATA_CHANGINGPARAMS,
                // TODO: Add more message IDs here as needed
            };
            D3D11_INFO_QUEUE_FILTER filter;
            memset(&filter, 0, sizeof(filter));
            filter.DenyList.NumIDs = _countof(hide);
            filter.DenyList.pIDList = hide;
            d3dInfoQueue->AddStorageFilterEntries(&filter);
        }
    }
#endif

```

See Direct3D SDK Debug Layer Tricks.
> 4 votes

# Answer
If you don't need the pixel shader (eg: you don't write to depth manually in there or don't use discard), you can just set the Pixel Shader stage to null.

Depth stencil will still be written to, and your warning message will disappear.

so just doing

```
deviceContext->PSSetShader(NULL,NULL,0);

```

Will do the trick.

It (should) also be faster since you don't even call the pixel shader at all.
> 6 votes

---
Tags: directx, directx11, shadow-mapping
---


# Question
Title: Reading filename(image) to a string using corona
Is there a way to get the filename from image and read it to a string using corona? I can't find any help regarding this issue.

In example, if I had:

```
local movieTitle = display.newImage("pulpfiction.png")

```

How could I print the image name(pulpfiction.png) or store it in a string?

# Answer
According to the documentation, the `newImage` function produces a `DisplayObject`; looking at the services offered by that object, **there is no way to fetch *where* it came from**, or how it's been built, which is, IMHO, reasonable.

Now you did not mention what you were trying to ultimately achieve, so it is hard to give you an alternative that would be perfect for your situation; but generally, when you *know* you'll need this information again after loading the image, one could go the other way around and store the name associated with the DisplayObject built. Perhaps in an associative array.
> 0 votes

---
Tags: corona-sdk
---


title: Move towards view direction opengl?

text:
# Question
Title: Move towards view direction opengl?
I'm trying to get the basics of 3d with opengl 2.0(I know, I know, it's deprecated etc, etc. It's just for the sake of prototyping). I'm trying to get a cube on the screen which you can move around. I have rendered the cube, and I can navigate the "world"(black background with the colored cube). However, when I try to rotate the camera, and then move, the camera moves independently of the camera's direction. For example, I rotate 90 degrees to the left, then I press "w" and it looks like I'm strafing to the right. I use sdl2 to get keyboard input, and when the user presses a key, I increase deltaX, deltaY, deltaZ, rotationX and rotationY accordingly(that's right, no rotation around the z axis).

And the rendering occurs as follows:

```
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    // Apply transformations
    glRotatef(rx, 1, 0, 0);
    glRotatef(ry, 0, 1, 0);
    glTranslatef(dx, dy, dz);

    // Draw each face with a different color
    glColor3f(1.0, 1.0, 0.0);
    glDrawArrays(GL_QUADS, 0, 4);
    glColor3f(1.0, 0.3, 0.4);
    glDrawArrays(GL_QUADS, 4, 4);
    glColor3f(0.0, 1.0, 0.5);
    glDrawArrays(GL_QUADS, 8, 4);
    glColor3f(1.0, 1.0, 1.0);
    glDrawArrays(GL_QUADS, 12, 4);
    glColor3f(0.3, 0.8, 0.0);
    glDrawArrays(GL_QUADS, 16, 4);
    glColor3f(0.0, 0.0, 1.0);
    glDrawArrays(GL_QUADS, 20, 4);

```

How can I do this?

EDIT: forgot to add, I would like to do this without glu. I don't like linking against a lot of libraries, especially when it's only to get a few functions.

EDIT2: I got forward movement to work using trigonometry like this:

```
case SDLK_w:
    posZ += (float)cos(rotY * M_PI / 180); // I use rotY * PI/180 to convert rotY to radians
    posX -= (float)sin(rotY * M_PI / 180);
    break;
case SDLK_s:
    posZ -= (float)cos(rotY * M_PI / 180);
    posX += (float)sin(rotY * M_PI / 180);

```

And now the only thing to add is strafing, which I thought would be something like this

```
case SDLK_a:
    posX += (float)sin(rotY * M_PI / 180) + (float)cos(rotY * M_PI / 180);
    posZ += (float)sin(rotY * M_PI / 180);
    break;
case SDLK_d:
    posX -= (float)sin(rotY * M_PI / 180) + (float)cos(rotY * M_PI / 180);
    posZ -= (float)sin(rotY * M_PI /180);
    break;

```

But it doesn't work, if you strafe when looking down the x axis, you move backwards in the z axis(wtf?)

Thanks!

EDIT3: Never mind, solved it by doing

```
case SDLK_a:
    posX += (float)cos(rotY * M_PI / 180);
    posZ += (float)sin(rotY * M_PI / 180);
    break;
case SDLK_d:
    posX -= (float)cos(rotY * M_PI / 180);
    posZ -= (float)sin(rotY * M_PI /180);
    break;

```

I don't know if this is the best way to do it, but it works. Thanks everyone for helping me!

# Answer
> 2 votes
Now I would first suggest you use GLM, but you're using C (according to your tag) so probably not. The best math I suggest in that case is continual use of the sine and cosine functions.

My examples will require math.h

You will want to first store your camera's position (if you haven't already)

```
float horizontal = cos(pitch) * GetCameraForwardSpeed();
float x += cos(yaw) * horizontal;
float z -= sin(yaw) * horizontal;
float y += sin(pitch) * GetCameraYSpeed();
//if you wanted strafing, you need this
x -= sin(yaw) * GetCameraStrafeSpeed();
z += cos(yaw) * GetCameraStrafeSpeed();

```

If you are storing degree, you should use a function like this:

```
float ToRadians(float degree)
{
 const double PI_CONST = 3.14159265358979323846;
 return degree * PI_CONST/180;
}

```

and replace yaw and pitch with that.

You will probably want to apply a View and Projection matrix to the position of the other objects, but that is way too much to put as an answer, so I suggest reverse engineering the math in GLM's perspective and translate functions and searching through the examples on the use of these functions.

Note: I have stated a few advanced methods of getting the answer

# Answer
> 1 votes
You typically need to keep track of at least three vectors to be able to easily move a camera around a scene. You need a vector representing the direction you are facing (0,0,-1), one representing upwards (0,1,0) and one vector representing camera position.

After rotating the lookat vector you can then translate your position in the direction of the vector.

Afterwards you can easily construct the ModelView matrix using the three vectors.

See this tutorial to learn more. It may be slightly out of date in some regards but it is still very useful for beginners

---
Tags: opengl, mathematics, c
---


# Question
Title: QuadTree-based pathfinding for a volume body
I want to make a game where a player follows a mouse pointer. The game is not tile-based. I use quadtree for a collision detection and everything works fine. But now I want to develop a player pathfinding algorithm. I.e. when a user clicks somewhere the player should find the most expected way to go there and follows it. And I stuck with situations like on the picture:

Player is not just a dot. He has got specified size (2D volume). If I use centres of the quadtree regions as a path trajectory, then this tunnel looks impassable. But when I control the player directly from the keyboard, he of course, is able to pass through this place.

How can I make quadtree-based pathfinding works for such situations? Or should I use another technique to solve this problem maybe?

# Answer
> 3 votes
I'm doing research in autonomous navigation for robotics, and this is a familiar problem. The real world analogy is you have two vehicles (a robotic motorcycle and a robotic tank) that have to decide on going through a narrow alleyway or not. Dimensions and positions are known by whatever means (radar, LIDAR, maps, GPS, etc)--how do you program such a decision?

Since either vehicle (and, in your case, the NPC that is walking around) are of "fixed" size for an orientation, here are the constraints:

1. In general, vehicles travel along a particular axis of their own.
2. We don't want to spend an inordinate amount of time doing orientation calculations.
3. Software is dumb--it thinks in terms of point positions rather than whole body.
4. The widest dimension (fender-to-fender plus whatever junk is hanging out there) of that movement axis is known.

So the approach is this:

1. Adding a buffer zone to obstacles is common practice--make it 1/2 of your vehicle width.
2. Use a "resolution" for your pathfinding that is proportional to your buffer.

The first part of the approach takes care of the collision part--the "point" of the vehicle/NPC is the same, but every potential collision object is buffered out so that your robotic motorcycle is not running into other cars (handlebars) or the tank is not taking out the corners of buildings.

The second part is an engineering/computation choice. If the space you want to go through is at least a little bit wider than the NPC, then you'll have to keep subdividing your quadtree down to match that buffer--and the algorithm can find a path through that's not occupied by either buffered obstacle.

If you're trying for an exact fit (space matches width of vehicle/NPC), then you're at an edge case that you'll either have to account for or call as a loser (no passage). As the resolution of your calculations (how small you're going to go down to) gets finer, the running time goes way up.

OTOH, the advantage of this approach is that the same process can account for a motorcycle-sized vehicle (which would add about a foot or so buffer) and a tank (8 feet or more), and would work in either case: The motorcycle goes through the alleyway, and the tank goes around the block.

Implementation details are specific to your setup, but I hope this helps get you started.

---
Tags: 2d, path-finding, quadtree
---


title: Libgdx Platform collision problem

text:
# Question
Title: Libgdx Platform collision problem
I am trying to come up with a collision function where all the cases are made.

1. If the player (Who's hit box is a circle) collides with a platform (hit box is a rectangle) from the right the platform will push the player back.
2. If the player collides with the platform for the top the player will stand on the platform.
3. If the platform is to the left of the player the player cant move to the left.

I am not asking how to tell if they are colliding or not but which side of the platform they are collide with where each platform is it's own object.

Can someone help me make this function?

# Answer
Since you seem to be just starting out, I'll give you the simplest approach.

First, define rectangles for all of your game objects (including your player) which will serve as their collision bounds. Once you've done that you will need a method that tests for collision between 2 rectangles (if you used the LibGdx rectangles then you can simply call their `overlaps()` method). This method would look like so:

```
public boolean overlaps (Rectangle r) {
    return x < r.x + r.width && x + width > r.x && y < r.y + r.height && y + height > r.y;
}

```

Then you would iterate through all of your kinetic objects and test them against each other and all the static objects to see if they are colliding (make sure to make this test efficient because you might have many bodies and it's worthless to test objects not remotely close to each other) and react accordingly.

If you want to know which sides collided, you can use a line intersection test (one of the links below explains that) or you could check the objects' velocities to see which direction they had been moving in, which would tell you which side they touched on.

Having the platforms push the player, you could just give the player some velocity and make them *stunned* (i.e. the user can't control them) until they have been pushed all the way, but these effects are each very specific and would make this question (and my answer) too broad (i.e. answers too many questions). Ask those more specific questions separately after you have tested out your own ideas using my answer and the links below.

Check out these links for more in-depth explanations and/or more complex approaches:

1. https://developer.mozilla.org/en-US/docs/Games/Techniques/2D\_collision\_detection
2. http://devmag.org.za/2009/04/13/basic-collision-detection-in-2d-part-1/
3. https://katyscode.wordpress.com/2013/01/18/2d-platform-games-collision-detection-for-dummies/
> 0 votes

---
Tags: collision-detection, libgdx
---


# Question
Title: Unable to get object to rotate to looked position?
I'm trying to get an object to smoothly rotate towards a clicked point in my terrain.

However, my code only yields jittery movements in the other direction.

Any help will be greatly appreciated.

```
using UnityEngine;
using System.Collections;

public class Movement : MonoBehaviour {

    public float rotationSpeed = 5.0f;

    private Quaternion _lookRotation;
    private Vector3 _direction;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit))
            {
                if (hit.collider.tag == "Ground")
                {

                    Vector3 looker = new Vector3(hit.point.x, hit.point.y, 0); //get x and y point from ray cast.

                    _direction = (looker - transform.position).normalized;

                    _lookRotation = Quaternion.LookRotation(_direction);

                    transform.rotation = Quaternion.Slerp(transform.rotation, _lookRotation, Time.deltaTime * rotationSpeed);

                }
            }
          }

    }
}

```

# Answer
> 1 votes
```
Vector3 targetDirection;
float rotationSpeed;

void Start() {
    targetDirection = this.transform.forward;
}

void Update() {
    if (Input.GetMouseButtonDown(0))
    {
        RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out hit))
        {
            if (hit.collider.tag == "Ground")
            {
                Vector3 looker = new Vector3(hit.point.x, hit.point.y, hit.point.z); //get x and y point from ray cast.
                targetDirection = (looker - transform.position).normalized;
            }
        }
    }

    this.transform.forward = Vector3.Lerp(this.transform.forward, targetDirection, Time.deltaTime * rotationSpeed);
}

```

This will cause the Object this script is attached to to constantly rotate towards the TargetDirection. Upon MouseClick you will update TargetDirection with the new point of interest and the GameObject will rotate as needed to face it. This is assuming "transform.forward" points along the correct axis of your Mesh to represent its forward as well in your game. If not just change that line of code to suit your model.

---
Tags: c#, unity, vector, scripting
---


title: Getting curved-based zooming speed?

text:
# Question
Title: Getting curved-based zooming speed?
I am able to get a fairly smooth zooming function going on in my project.

However I'm hoping to achieve a non-linear function.

I've tried using the smoothstep function but it doesn't feel smooth (Could have been an improper implementation of mine).

If anyone can provide any suggestions, that will be greatly appreciated.

An example of what I'm trying to achieve is that of the spectator camera, where it zooms in/out, in Dota2.

```
using UnityEngine;
using System.Collections;

public class Pan : MonoBehaviour {

    public float zoomSpeed = 20f;
    public float smoothTime = 0.3f;

    private float refSpeed = 0.0f;

    void Update () {

    if(Input.touchCount == 1)
        {
            panUpdate();
        }

    if(Input.touchCount == 2)
        {
            zoomUpdate();
        }

    }

    void panUpdate()
    {

    }

    void zoomUpdate()
    {

        // Store both touches.
        Touch touchZero = Input.GetTouch(0);
        Touch touchOne = Input.GetTouch(1);

        // Find the position in the previous frame of each touch.
        Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
        Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition;

        // Find the magnitude of the vector (the distance) between the touches in each frame.
        float prevTouchDeltaMag = (touchZeroPrevPos - touchOnePrevPos).magnitude;
        float touchDeltaMag = (touchZero.position - touchOne.position).magnitude;

        // Find the difference in the distances between each frame.
        float deltaMagnitudeDiff = prevTouchDeltaMag - touchDeltaMag;

//        float into = GetComponent<Camera>().fieldOfView + deltaMagnitudeDiff; //* ZoomSpeed

       // float smoothDiff = Mathf.SmoothDamp(GetComponent<Camera>().fieldOfView, deltaMagnitudeDiff, ref zoomSpeed, smoothTime);

        // Otherwise change the field of view based on the change in distance between the touches.
        GetComponent<Camera>().fieldOfView = Mathf.SmoothDamp(GetComponent<Camera>().fieldOfView, GetComponent<Camera>().fieldOfView += deltaMagnitudeDiff * zoomSpeed, ref refSpeed, smoothTime);

        // Clamp the field of view to make sure it's between 0 and 180.
        GetComponent<Camera>().fieldOfView = Mathf.Clamp(GetComponent<Camera>().fieldOfView, 59.9f, 119.9f);

    }
}

```

# Answer
```
float targetFieldOfView;
Camera currentCamera;

void Start() {
currentCamera = GetComponent<Camera>();
targetFieldOfView = currentCamera.fieldOfView;

}

void Update() {
    AdjustZoom();

}

void AdjustZoom() {
    if(Input.touchCount == 2)
    {
        Touch touchZero = Input.GetTouch(0);
        Touch touchOne = Input.GetTouch(1);
        targetFieldOfView = (touchZero.position - touchOne.position).magnitude;
    }
    currentCamera.fieldOfView = Mathf.Lerp(currentCamera.fieldOfView, targetFieldOfView, Time.deltaTime * zoomSpeed);
}

```

Something like that will give you a nice zoom that starts off fast and slows down near the end. You can add an additional line in Update to check if currentCamera.fieldOfView is within a certain small amount of targetFieldOfView and skip calling AdjustZoom() if you want.

```
if(Mathf.Abs(currentCamera.fieldOfView - targetFieldOfView) > 0.01f)
    AdjustZoom()

```
> 0 votes

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


# Question
Title: Working but flawed bullet spread (vector math)
I'm trying to implement random bullet spread into my game, and I've managed something that works, but is consistently flawed.
The spread doesn't vary depending on the distance the mouse is from the player, it does however vary depending on the combined mouse position, aka top left is the maximum amount of spread (20 degrees I think, as I have my GetSpread( ) return 10) and top right is no spread at all.

```
void Player::StartShooting( float mouse_x, float mouse_y )
{
    for( unsigned int i = 0; i < activeFirearm.bullet.size( ); i++ )
    {
        if( activeFirearm.bullet[i].GetActive( ) == false )
        {
            activeFirearm.bullet[i].SetOrigin( GetPosition( ).x + GetHitbox( ).x / 2,
                                               GetPosition( ).y + GetHitbox( ).y / 2 );
            sf::Vector2f projEndNorm = vectorNormal( { mouse_x - activeFirearm.bullet[i].GetOrigin( ).x,
                                                       mouse_y - activeFirearm.bullet[i].GetOrigin( ).y } );
            float ratio = tan( activeFirearm.GetSpread( ) * 3.141592 / 180 );
            float random = static_cast<float>( randomNumberGenerator( static_cast< int >( ratio * -100000 ),
                                                                      static_cast< int >( ratio * 100000 ) ) ) / 100000.f;

            //projEndNorm.x += random;
            //projEndNorm.y += random;
            projEndNorm = vectorNormal( { projEndNorm.x + random,
                                          projEndNorm.y - random } );
            if( projEndNorm.x == 0 &&
                projEndNorm.y == 0 )
            {
                if( mouse_x < GetPosition( ).x + GetHitbox( ).x / 2 &&
                    mouse_y == GetPosition( ).y + GetHitbox( ).y / 2 )
                {
                    projEndNorm.x = -0.999f;
                    projEndNorm.y = -0.001f;
                }
                else if( mouse_x > GetPosition( ).x + GetHitbox( ).x / 2 &&
                         mouse_y == GetPosition( ).y + GetHitbox( ).y / 2 )
                {
                    projEndNorm.x = 0.999f;
                    projEndNorm.y = 0.001f;
                }
                else if( mouse_x == GetPosition( ).x + GetHitbox( ).x / 2 &&
                         mouse_y < GetPosition( ).y + GetHitbox( ).y / 2 )
                {
                    projEndNorm.x = -0.001f;
                    projEndNorm.y = -0.999f;
                }
                else if( mouse_x == GetPosition( ).x + GetHitbox( ).x / 2 &&
                         mouse_y > GetPosition( ).y + GetHitbox( ).y / 2 )
                {
                    projEndNorm.x = 0.001f;
                    projEndNorm.y = 0.999f;
                }
            }
            activeFirearm.bullet[i].SetPosition( activeFirearm.bullet[i].GetOrigin( ) + projEndNorm );
            activeFirearm.bullet[i].SetVelocity( vectorNormal( activeFirearm.bullet[i].GetPosition( ) - activeFirearm.bullet[i].GetOrigin( ) ).x * activeFirearm.GetInitialVelocity( ),
                                                 vectorNormal( activeFirearm.bullet[i].GetPosition( ) - activeFirearm.bullet[i].GetOrigin( ) ).y * activeFirearm.GetInitialVelocity( ) );
            activeFirearm.bullet[i].SetActive( true );
            activeFirearm.bullet[i].SetStep( 0 );
            break;
        }
    }
}

```

I'm not sure what I should do to make it work.

# Answer
First thing you should do is to refactor your code, to have a clear view about what's being done. So get out of thee loop the values that won't change, and cache any re-used value.

Below is some pseudo-code that should get you in the right direction.

The principle is : get the aimAngle, the angle between player and target (mouse).
Then randomly pick an angle aimAngle +- the spread.
Then build the vector having weaponSpeed as norm and this random angle as direction.

There's just a little trick here, to avoid numerical issues,( causing almost random direction ) , that is to re-use the last valid aimAngle in case the mouse is too near from the player ( making atan useless with too small y/x figures ).

```
void Player::StartShooting( float mouse_x, float mouse_y )
{
    // compute the start point of all bullets once
    var startPoint = GetPosition( ) + GetHitbox( ) / 2;
    // compute player to mouse distance
    var distance = ... you guess
    var aimAngle = 0;
    if (distance < minDistance ) {
        // if the mouse is too close from the player, the angle cannot be accurate.
        // lastAimAngle is a class property init. to zero.
        aimAngle = lastAimAngle;
    } else {
        // get angle
        aimAngle = atan2 ( delta y , delta x) ;
        lastAimAngle = angle
    }
    // retrieve weapon data
    var weaponSpread = activeFirearm.GetSpread( ) * 3.141592 / 180;
    var bulletVelocity = activeFirearm.GetInitialVelocity( );
    //
    var bullets = activeFirearm.bullet ;
    for( unsigned int i = 0; i < bullets.size( ); i++ )
    {
        var bullet = activeFirearm.bullet[i];
        if( bullet.GetActive( ) == true ) continue;
        // pick a random angle between aimAngle - weaponSpread and  aimAngle + weaponSpread
        var bulletAngle = aimAngle + weaponSpread * ( random() - 0.5 ) ;
        var speedVector = { bulletVelocity * cos ( bulletAngle ) ,
                                         bulletVelocity * sin ( bulletAngle )  } ;
        // setup the  bullet
        bullet.SetOrigin( startPoint );
        bullet.SetPosition( startPoint );
        bullet.SetVelocity( speedVector );
        bullet.SetActive( true );
        bullet.SetStep( 0 );
        break;
    }
}

```
> 0 votes

---
Tags: c++, 2d, vector, sfml
---


# Question
Title: Prime31 Plugin Error : "Plugin 'P31RestKit.dll' is used from several locations"
I got the following error, when i tried to install "Prime31: MicrosoftAds\_2015-04-22" plugin in Unity 5

* Plugins colliding with each other
* Plugin 'P31RestKit.dll' is used from several locations: Assets/Plugins/P31RestKit.dll would be copied to /P31RestKit.dll, Assets/Plugins/WSA/P31RestKit.dll would be copied to /P31RestKit.dll .Please fix plugin settings and try again.

Thank you

# Answer
> 0 votes
The error is saying that you have 2 DLLs called P31RestKit in your project, one at "Assets/Plugins/P31RestKit.dll" and one at "Assets/Plugins/WSA/P31RestKit.dll".

The process for dealing with plugins for Windows Unviersal has changed in Unity 5 from Unity 4. (It actually seems to change with every update and patch fix!). In Unity 5 you have to specify which platforms each dll will be used on.

To do this select each dll in the Project window and change their settings. For the dll in the standard plugins folder just deselect the WSAPlayer. For the dll in the WSA folder set the platform just to WSAPlayer. In additon also tick the box that says 'Don't process" and in the Placeholder drop down, navigate to "Assets/Plugins/P31RestKit.dll".

That should sort you out. It is worth pointing out that Prime31 is (maybe already has) dropped support for the Windows Universal apps platform. This is partly due to various issues with the Unity/Windows Universal/Plugins combination, which as I said is a bit of a nightmare at the moment.

For reference the plugin vendor's documentation on this is here The advice is slightly out of date though and for Unity 4 I believe.

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


# Question
Title: Are there any benefits for using the CPU instead of the GPU?
I've been researching processors and graphics cards, and I discovered that GPUs are way faster than CPUs. I read in this one article, a 2-year-old Nvidia GPU outperformed a 3.2GHz Core I7 Intel processor by 14 times in certain circumstances. If GPUs are that fast, why don't developers use them for every function in a game? Is it possible for GPUs to do anything other than graphics?

# Answer
"I've read that F1 cars are faster than those we drive on the streets... why people don't use F1 cars then?" Well... The answer to this question is simple: F1 cars can't break or turn as fast as most cars do (the slowest car could beat an F1 in that case). The case of GPUs is very similar, they are good at following a straight line of processing, but they are not so good when it comes to choosing different processing paths.

A program executed in te GPU makes sense when it must be executed many times in parallel, for instance when you have to blend all the pixels from Texture A with pixels from Texture B and put them all in Texture C. This task, when executed in a CPU, would be processed as something like this:

```
for( int i =0; i< nPixelCount; i++ )
     TexC[i] = TexA[i] + TexB[i];

```

But this is slow when you have to process a lot of pixels, so the GPU instead of using the code above, it just uses the next one:

```
     TexC[i] = TexA[i] + TexB[i];

```

and then it populates all the cores with this program (essentially copying the program to the core), assigning a value for `i` for each. Then is where it comes the magic from the GPU and make all cores execute the program *at the same time*, making a lot of operations much faster than the linear CPU program could do.

This way of working is ok when you have to process in the same way a very lot of small inputs, but is really bad when you have to make a program that may have conditional branching. So now let's see what the CPU does when it comes to some condition check:

* 1: Execute the program until the first logical operation
* 2: Evaluate
* 3: Continue executing from the memory address result of the comparison (as with a JNZ asm instruction)

This is very fast for the CPU as setting an index, but for the GPU to do the same, it's a lot more complicated. Because the power from the GPU comes from executing the same instruction at the same time (they are SIMD cores), they must be synchronized to be able to take advantage of the chip architecture. Having to prepare the GPU to deal with branches implies more or less:

* 1: Make a version of the program that follows only branch A, populate this code in all cores.
* 2: Execute the program until the first logical operation
* 3: Evaluate all elements
* 4: Continue processing all elements that follow the branch A, enqueue all processes that chose path B (for which there is no program in the core!). Now all those cores which chose path B, will be IDLE!!--the worst case being a single core executing and every other core just waiting.
* 5: Once all As are finished processing, activate the branch B version of the program (by copying it from the memory buffers to some small core memory).
* 6: Execute branch B.
* 7: If required, blend/merge both results.

This method may vary based on a lot of things (ie. some **very small** branches are able to run without the need of this distinction) but now you can already see why branching would be an issue. The GPU caches are very small you can't simply execute a program from the VRAM in a linear way, it has to copy small blocks of instructions to the cores to be executed and if you have branches enough your GPU will be mostly stalled than executing any code, which makes no sense when it comes when executing a program that only follows one branch, as most programs do--even if running in multiple threads. Compared to the F1 example, this would be like having to open braking parachutes in every corner, then get out of the car to pack them back inside the car until the next corner you want to turn again or find a red semaphore (the next corner most likely).

Then of course there is the problem of other architectures being so good at the task of logical operations, far cheaper and more reliable, standarized, better known, power-efficient, etc. Newer videocards are hardly compatible with older ones without software emulation, they use different asm instructions between them even being from the same manufacturer, and that for the time being most computer applications do not require this type of parallel architecture, and even if if they need it them, they can use through standard apis such as OpenCL as mentioned by eBusiness, or through the graphics apis. Probably in some decades we will have GPUs that can replace CPUs but I don't think it will happen any time soon.

I recommend the documentation from the AMD APP which explains a lot on their GPU architecture and I also saw about the NVIDIA ones in the CUDA manuals, which helped me a lot on understanding this. I still don't understand some things and I may be mistaken, probably someone who knows more can either confirm or deny my statements, which would be great for us all.
> 53 votes

# Answer
GPUs are very good a parallel tasks. Which is great... if you're running a parallel tasks.

Games are about the *least* parallelizable kind of application. Think about the main game loop. The AI (let's assume the player is handled as a special-case of the AI) needs to respond to collisions detected by the physics. Therefore, it must run afterwards. Or at the very least, the physics needs to call AI routines within the boundary of the physics system (which is generally not a good idea for many reasons). Graphics can't run until physics has run, because physics is what updates the position of objects. Of course, AI needs to run before rendering as well, since AI can spawn new objects. Sounds need to run after AI and player controls

In general, games can thread themselves in very few ways. Graphics can be spun off in a thread; the game loop can shove a bunch of data at the graphics thread and say: render this. It can do some basic interpolation, so that the main game loop doesn't have to be in sync with the graphics. Sound is another thread; the game loop says "play this", and it is played.

After that, it all starts to get painful. If you have complex pathing algorithms (such as for RTS's), you can thread those. It may take a few frames for the algorithms to complete, but they'll be concurrent at least. Beyond that, it's pretty hard.

So you're looking at 4 threads: game, graphics, sound, and possibly long-term AI processing. That's not much. And that's not *nearly* enough for GPUs, which can have literally hundreds of threads in flight at once. That's what gives GPUs their performance: being able to utilize all of those threads at once. And games simply can't do that.

Now, perhaps you might be able to go "wide" for some operations. AIs, for instance, are usually independent of one another. So you could process several dozen AIs at once. Right up until you actually need to make them dependent on each other. Then you're in trouble. Physics objects are similarly independent... unless there's a constraint between them and/or they collide with something. Then they become very dependent.

Plus, there's the fact that the GPU simply doesn't have access to user input, which as I understand is kind of important to games. So that would have to be provided. It also doesn't have direct file access or any real method of talking to the OS; so again, there would have to be some kind of way to provide this. Oh, and all that sound processing? GPUs don't emit sounds. So those have to go back to the CPU and then out to the sound chip.

Oh, and coding for GPUs is terrible. It's hard to get right, and what is "right" for one GPU architecture can be very, *very* wrong for another. And that's not even just switching from AMD to NVIDIA; that could be switching from a GeForce 250 to a GeForce 450. That's a change in the basic architecture. And it could easily make your code not run well. C++ and even C aren't allowed; the best you get is OpenCL, which is sort of like C but without some of the niceties. Like *recursion*. That's right: no recursion on GPUs.

Debugging? Oh I hope you don't like your IDE's debugging features, because those certainly won't be available. Even if you're using GDB, kiss that goodbye. You'll have to resort to `printf` debugging... wait, there's no `printf` on GPUs. So you'll have to write to memory locations and have your CPU stub program read them back.

That's right: *manual* debugging. Good luck with that.

Also, those helpful libraries you use in C/C++? Or perhaps you're more of a .NET guy, using XNA and so forth. Or whatever. It doesn't matter, since you can't use *any* of them on the GPU. You must code everything from scratch. And if you have an already existing codebase, tough: time to rewrite all of that code.

So yeah. It's horrible to actually do for any complex kind of game. And it wouldn't even work, because games just aren't parallel enough for it to help.
> 32 votes

# Answer
**Why** is not so easy to answer -- it's important to note that GPUs are specialized processors which are not really intended for generalized use like a regular CPU. Because of this specialization, it's not surprising that a GPU can outperform a CPU for the things it was specifically designed (and optimized) for, but that doesn't necessarily mean it can replace the full functionality and performance of a generalized CPU.

I suspect that developers don't do this for a variety of reasons, including:

* They want the graphics to be as fast and highest quality possible, and using valuable GPU resources could interfere with this.
* GPU-specific code may have to be written, and this will likely introduce additional complexity to the overall programming of the game (or application) at hand.
* A GPU normally doesn't have access to resources like network cards, keyboards, mice, and joysticks, so it's not possible for it to handle every aspect of the game anyway.

In answer to the second part of your question: **Yes, there are other uses.** For example, projects like SETI@Home (and probably other BOINC projects) are using GPUs (such as those by nVidia) for high-speed complex calculations:

Run SETI@home on your NVIDIA GPU
http://setiathome.berkeley.edu/cuda.php

(*I like your question because it poses an interesting idea.*)
> 21 votes

# Answer
CPUs are more flexible, it's generally easier to program them, they can run single threads a lot faster.

While modern GPUs can be programmed to solve pretty much any task they only gain a speed advantage when they can utilize their parallel architecture. This is usually the case with highly repetitive "simple" tasks. A lot of the code we write is branching too unpredictably to run efficiently on a GPU.

On top of all this you could end up spending a lot of time optimizing the code for different graphics chips. While OpenCL is available to make the same code run across a lot of different graphics chips you'll trade some of the speed advantage for this luxury.

From a game programmer perspective, we'd generally also want our game to run on computers with lesser graphics cards. Some of the integrated chips don't have the required programmability, but if they do they are so slow that they won't beat the processor by a very big margin, even for the kind of jobs they ought to be good at. And of course if you did tap into a low end GPU for a game you would take dearly needed processing power from the graphics rendering.

Indeed the prospects are great, but when you are making a game rather than cracking passwords the practical issues in most cases outweigh the benefits.
> 18 votes

# Answer
GPU are very difficult to program. You should search howto to sort a list on a GPU. Many thesis have search to do it.

Use a CPU with one thread is easy, use multi-threads is more difficult, use many computers with parallel library as PVM or MPI is hard and use a gpu is the hardest.
> 6 votes

# Answer
Other than what Randolf Richardson answered there are some certain functionalities that GPU processors can't handle by themselves. For example, some of the graphics memory management commands are processed by the CPU since the GPU can't handle them.

And there is one other big reason, the GPU is designed for multithreaded calculations. This means GPU makers can easily add cores whenever they want to increase the computational power. But there are many tasks that can't be divided in smaller problems like computing the n'th number in the Fibonacci series. In these situations the CPU is much faster since it is more optimized for single-threaded tasks.
> 4 votes

# Answer
There are a lot of answers suggesting that GPUs are only faster because they handle tasks in parallel. This is overstating the issue a little. GPUs can be more efficient for other reasons, such as being able to have more restrictive memory access, not having to support as many data types, being able to have a more efficient instruction set, etc. Early GPUs could still only draw 1 pixel at a time, but it was the fact that they could do 1 every cycle that was important.

The real difference is because they are 2 different types of machine that are customised to perform well on different categories of task which *seem* similar but are actually quite different. It's like comparing an aeroplane to a car. The aeroplane has a much higher top speed but has more restrictions on how it can be used. On the occasions where you can make the same journey with either kind, the aeroplane seems superior.
> 4 votes

# Answer
Developers *do* use GPUs for all the functions they're good at. They use CPUs for all the functions they're good at. What makes you think they don't?

GPUs are good at tasks that can be massively paralellized and require massive amounts of computation with either low memory requirements or high temporal correlation with only small amounts of decision making. This includes rendering images, physics simulations (particles, collision, cloth, water, reflection) and so on. So this is precisely what modern games use the GPU for.

CPUs are good at tasks that do not parallelize well and require massive amounts of decision making. They can tolerate high memory requirements even with only moderate temporal correlation. This includes artificial intelligence, user interface, disk and network I/O, and so on. So this is precisely what modern games use the CPU for.
> 3 votes

# Answer
Readback is another reason I can think of to occasionally prefer the CPU. Not in terms of bandwidth (as GPU-\>CPU bandwidth is not so much an issue on modern hardware) but in terms of stalling the pipeline. If you need to fetch back results from a computation and do something interesting or useful with them, using the GPU is not a wise choice (in the general case - there will be special cases where it can remain appropriate) as reading back will always require the GPU to stop whatever it is doing, flush all pending commands, and wait for the readback to complete. This can kill performance to the extent that it not only wipes out the benefit of using the GPU, but may actually be considerably slower.
> 1 votes

# Answer
This is an old thread, but this recently published paper may answer this question. This paper, published in ACM Computing Surveys 2015 shows that each of CPUs and GPUs have their unique advantages and hence, this paper makes a case for moving away from "CPU vs GPU debate" to "CPU-GPU collaborative computing" paradigm.

A Survey of CPU-GPU Heterogeneous Computing Techniques
> 0 votes

---
Tags: gpu, process, gpgpu
---


# Question
Title: Sending an object from one point to another
I am working on a simple game in Java and am stuck for now with getting an object to be directed from its current position to a certain point, all at a fixed speed. My problem is that whenever I activate the movement, the object seems to shoot off into a random direction, sometimes towards my target, sometimes away, really any direction it seems, but nothing consistent.

This is what I'm working with:

```
    else if (key == KeyEvent.VK_SPACE)
    {
        double deltaY = 100 - p.getY();
        double deltaX = 100 - p.getX();
        double angle = Math.atan2(deltaY, deltaX) * 180 / Math.PI;
        System.out.println(angle);
        double dx = (double) (Math.cos(angle) * 3);
        double dy = (double) (Math.sin(angle) * 3);
        p.setVelX(dx);
        p.setVelY(dy);
    }

```

Here is my SetVel functions as well as the tick method.

```
public void tick()
{
    x+=velX;
    y+=velY;

    if(x <= 0)
        x = 0;
    if(x >= 640)
        x = 640;
    if(y < 0)
        y = 0;
    if(y >= 480)
        y = 480;
}

public void setVelX(double velX)
{
    this.velX = velX;
}

public void setVelY(double velY)
{
    this.velY = velY;
}

```

Using the system outs, and positioning my object at 90 degree angles relative to my target I am getting 90 and 180 degrees, so I don't think its a problem with that.

# Answer
> 1 votes
Your issue seems to be coming from the fact that you are using **degrees** to calculate your rotation instead of **radians**.

Here would be a way to fix your issue:

```
else if (key == KeyEvent.VK_SPACE)
{
    double deltaX = p.getDestX() - p.getX();
    double deltaY = p.getDestY() - p.getY();

    double angleRad = Math.atan2(deltaY, deltaX);
    double angleDeg = angleRad * 180 / Math.PI;
    System.out.println(angleDeg);
    double dx = (double) (Math.cos(angleRad) * p.getMaxVel());
    double dy = (double) (Math.sin(angleRad) * p.getMaxVel());
    p.setVelX(dx);
    p.setVelY(dy);
}

```

and here would be another way to achieve it:

```
else if (key == KeyEvent.VK_SPACE)
{
    double deltaX = p.getDestX() - p.getX();
    double deltaY = p.getDestY() - p.getY();

    double angleRad = Math.atan2(deltaY, deltaX);
    double angleDeg = angleRad * 180 / Math.PI;
    System.out.println(angleDeg);

    double len = Math.sqrt( deltaX * deltaX + deltaY * deltaY );
    double unitX = deltaX / len;
    double unitY = deltaY / len;

    double dx = unitX * p.getMaxVel());
    double dy = unitY * p.getMaxVel());
    p.setVelX(dx);
    p.setVelY(dy);
}

```

---
Tags: java
---


# Question
Title: Getting unit to complete rotation before moving?
I've been trying to get a unit in my project to move in a fashion similiar to that of modern MOBA games.

However, I am faced with the issue of the unit moving before the rotation is completed and the unit moving along the Y-axis.

I have tried using a cooroutine to allow the rotation to completed first, but to no avail. Any help would be greatly appreciated.

```
using UnityEngine;
using System.Collections;

public class Move : MonoBehaviour {

    public float smooth;
    public float speed;

    private float z;
    private float x;
    private Vector3 targetPosition;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

        if (Input.GetKeyDown(KeyCode.Mouse0))
        {

            speed = 1;
            smooth = 20;

            RaycastHit hit;

            //var playerPlane = new Plane(Vector3.up, transform.position);
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            //double hitdist = 0.0;

            if (Physics.Raycast(ray, out hit))
            {
                targetPosition = hit.point;

                x = hit.point.x;
                z = hit.point.z;
                //var targetRotation = Quaternion.LookRotation(targetPoint    - transform.position);
                //transform.rotation = targetRotation;
            }
        }

        StartCoroutine(Turn(x,z));

        //transform.position = Vector3.RotateTowards(transform.position, targetPosition, speed*Time.deltaTime, 0.0f);
        transform.position = Vector3.MoveTowards(transform.position, targetPosition, Time.deltaTime * smooth);
    }

    IEnumerator Turn(float _x, float _z)
    {
        Vector3 turn = new Vector3 (_x, 0, _z);
        transform.Rotate(turn, speed);
        yield return null;
    }
}

```

# Answer
There are two options here.

1. Moving the unit at the end of the coroutine (and maybe changing the name of the coroutine)
2. Creating a second coroutine that waits for the first one to finish before executing

Now I'll illustrate the examples

```
// 1st option
IEnumerator Turn(float _x, float _z)
{
    Vector3 turn = new Vector3 (_x, 0, _z);
    transform.Rotate(turn, speed);
    yield return null;
    // now move
    transform.position = Vector3.MoveTowards(transform.position, targetPosition, Time.deltaTime * smooth);
}

```

Let's work out a second option with some code you commented, but I think it's a better approach

```
// Move function is the coroutine to be called to trigger movement
IEnumerator Move(Vector3 targetPosition)
{
    // we want to rotate first
    yield return Turn(Vector3 targetPosition);
    // then translate
    transform.position = Vector3.MoveTowards(transform.position, targetPosition, Time.deltaTime * smooth);
}

IEnumerator Turn(Vector3 targetPosition)
{
    Quaternion srcRotation = transform.rotation;
    Quaternion dstRotation = Quaternion.LookRotation(targetPosition);
    float percent = 0.1f;
    while (percent <= 1.0f)
    {
        Quaternion newRotation = Quaternion.Lerp(srcRotation, dstRotation, percent);
        transform.rotation = newRotation;
        percent += .01f;
        yield return null;
    }
}

```

Using Lerp gives us smoothing and then you can change the values according to your own rotation speed, movement speed, etc.
> 2 votes

# Answer
No need for the coroutine, just don't update the position until the rotation has been completed:

```
if(turnComplete){
    transform.position = Vector3.MoveTowards(transform.position, targetPosition, Time.deltaTime * smooth);
}

```

Getting whether the turn is completed means checking how much more the unit needs to turn. If the remaining angle is small enough then `turnComplete=true;`
> 1 votes

---
Tags: c#, unity, scripting, transformation, quaternion
---


# Question
Title: Algorithm for a smooth weather transitions in game weather system
I've been slowly learning c++ and building up a codebase intending to create a simple first person role playing game.

I've coded a time management tool to track time elapsed in game, an inventory and container system, and some other bits. I have been considering a basic system to change the weather in game.

I haven't actually done code towards it yet but the simplest weather solution (not including rendering) would be a very very crude state system.

```
enum WEATHER_TYPES { FINE, CLOUDY, RAINY, STORM }
int min_duration = 2;   // 2 hours
int max_duration = 5;   // 5 hours

int current_duration;
if(current_duration >= min_duration && current_duration < max_duration) {
    float r = my_rand_range_float(0.f,1.f);
    if(r <= 0.25 )
        changeWeather();

```

That is obviously a really rough approximation and it would result in very harsh changes in the weather. It could instantly go from FINE to STORM which is very unrealistic.

I don't want a system where it models the weather based on realistic parameters. I am happy with a relatively simple randomly changing system to begin with. (Although it is worth noting that my timemanager class is tracking seasons as well as generating temperatures for the days)

I am thinking along the lines of having a WeatherManager class to keep track of the current weather state and decide when to transition between them. Each "Weather Type" would become it's own class that can be updated when it is in use. Each weather class would have a "starting" state where it would be possible to transition into the next weather state from the previous.

For example if changing from FINE to RAINY then during the "starting" state of the RAINY weather it would slowly build up the cloud layers, start the rain particle system with a small number of particles and build up to the desired number. The idea is to provide a bit of a build up.

It would also need to be able to do the reverse in the case of changing from RAINY to FINE.

I don't really know how others have implemented weather systems in game. Am I on the right track in my thinking in this regards and can anyone point me towards some resources to learn about implementing weather systems for a game?

# Answer
One way to go is to model Weather as Random Process using Hidden Markov Model(HMM). For full explanation of it, check Hidden Markov Model - Wikipedia

This will solve the following problem: I'm in state A. From state A, which is the next state i should go into.In other words, if you are in Cloudy State, where should you go next:Remain in Cloudy state or go into Rainy or Fine state. This will not tell you when transition should happen. For that, you could simply use some random variable to indicate duration of each state.

Shortly, HMM is set of states and transitions between states based on probability theory(this is of course crude explanation and mathematicians will be angry if they see this). You could have state for all weather types, i.e. *FINE\_STATE*, *CLOUDY\_STATE*, *STORM\_STATE*, and *RAINY\_STATE*, and define set of transition between them and assign probabilities on them that would look something like this:
Sum of probabilities of outgoing paths from every state must be 1 as you see.

HMM is a way more general than this, but it does good job. You can use State Design Pattern with this and implement HMM as weighted digraph. For explanation of State Pattern, check
State Pattern - Wikipedia.

As Alan already said, "cross-fading" is nice feature to have, and you could easily combine it with HMM using State Pattern.

Here is the code that corresponds to theory said above(please note that for simplicity i did not accounted duration of the state, and "cross-fading"):

```

//Header files .h
class Graph
{
public:
    //If nodes "from" and "to" does not exist, they will be added
    //Complexity: O(1) average, O(n) worst case
    void addEdge(string from, string to, float probability)
    {
        mAdj[from].push_back(pair<string, float>(to, probability));
    }
    //Return adjencent nodes to vertex "from"
    //Complexity: O(1) average, O(n) worst case
    list<pair<string, float>> operator[](string from) { return mAdj[from]; }
private:
    unordered_map<string, list<pair<string, float>>> mAdj;
};

class State
{
public:
    //Complexity:O(n) where n is total number of weather states
    State* getNextState(Graph hmm);
    virtual string toString() = 0;
    static State* createState(string state); //Create State object from string argument
};

class FineState : public State
{
public:
    string toString() { return "fine"; }
};
class CloudyState : public State
{
public:
    string toString() { return "cloudy"; }
};
class RainyState : public State
{
public:
    string toString() { return "rainy"; }
};
class StormState : public State
{
public:
    string toString() { return "storm"; }
};

class WeatherManager
{
public:
    WeatherManager() : mCurrentState(0) {}
    ~WeatherManager() { if(mCurrentState) delete mCurrentState; }
    //Add weather states and transition between "from" -> "to" based on probability
    //Complexity: Same as Graph::addEdge()
    void addWeather(string from, string to, float probability)
    {
        mHMM.addEdge(from, to, probability);
    }
    //Calculate weather state for next frame
    //Complexity: Same as State::getNextState()
    //Please note that current implementation of weather system does not account duration of state
    //i.e. Each state have duration of 1 frame
    void changeWeather()
    {
        if (mCurrentState)
        {
            State* pState = mCurrentState->getNextState(mHMM);
            delete mCurrentState;
            mCurrentState = pState;
        }
    }
    void setState(string state)
    {
        if (mCurrentState) delete mCurrentState;
        mCurrentState = State::createState(state);
    }
    void printState()
    {
        cout << mCurrentState->toString() << endl;
    }
private:
    Graph mHMM;
    State* mCurrentState;
};

//Source files .cpp
State* State::getNextState(Graph hmm)
{
    string thisState = toString();
    //Get number in [0, 1] interval.
    //Use some advanced random generator if you need Normal Distribution
    float r = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
    float sum = .0f;
    for (auto it : hmm[thisState])
    {
        float prob = it.second;
        if (sum <= r && r < (sum + prob))
            return State::createState(it.first);
        sum += prob;
    }
    return nullptr;
}

State* State::createState(string state)
{
    if (state == "fine")
        return new FineState();
    else if (state == "cloudy")
        return new CloudyState();
    else if (state == "rainy")
        return new RainyState();
    else if (state == "storm")
        return new StormState();
    return nullptr;
}

int main() {
    srand(static_cast<unsigned>(time(nullptr)));
    WeatherManager mgr;
    mgr.addWeather("fine", "fine", 0.2f);
    mgr.addWeather("fine", "cloudy", 0.8f);
    mgr.addWeather("cloudy", "cloudy", 0.3f);
    mgr.addWeather("cloudy", "fine", 0.1f);
    mgr.addWeather("cloudy", "rainy", 0.2f);
    mgr.addWeather("cloudy", "storm", 0.7f);
    mgr.addWeather("rainy", "rainy", 0.4f);
    mgr.addWeather("rainy", "cloudy", 0.4f);
    mgr.addWeather("rainy", "storm", 0.2f);
    mgr.addWeather("storm", "storm", 0.1f);
    mgr.addWeather("storm", "cloudy", 0.1f);
    mgr.addWeather("storm", "rainy", 0.8f);
    mgr.setState("fine");

    for (unsigned i = 0; i < 10; i++)
    {
        mgr.printState();
        mgr.changeWeather();
    }

    return 0;
}

```

You can expand concrete states (i.e. `FineState`) classes to add duration among the other things, and just use another `State*` variable for "cross-fading" LERP(Linear Interpolation) to save previous state.
> 7 votes

# Answer
You could also think about "crossfading" from one weather state to the next when they switch. Basically the weighting of the old state will go from 1.0 to 0.0 over time while the new state goes from 0.0 to 1.0 over the same amount of time. This is used of course in audio to switch from one audio track to another but its also used in skeletal animation programming to switch from one animation to another, and other places as well. Its a good way to handle state transitions in general.
> 1 votes

---
Tags: c++, algorithm, game-mechanics
---


title: Stop Camera up movement

text:
# Question
Title: Stop Camera up movement
I am developing 3D game , the main camera is child of player.

When player jumps camera too gets move up with player as its child of player.Is there anyway to stop this behavior?

The only thing I can guess is to make camera separate gameobject and let it follow player

**EDIT** After applying @Everless Drop 41's script, here is what main problem arises

# Answer
You need to have the camera follow the player, but you will want an offset so the player is still seen

I have a script that makes this fairly easy and can be used on other things too.

# CameraFollow.cs

```
using UnityEngine;
using System.Collections;

public class CameraFollow : MonoBehaviour
{

    public Transform target;

    public bool X, Y, Z;

    public float XOffset, YOffset, ZOffset;

    void Update()
    {
        transform.position = new Vector3(
            (X ? target.position.x + XOffset : transform.position.x),
            (Y ? target.position.y + YOffset : transform.position.y),
            (Z ? target.position.z + ZOffset : transform.position.z));
        //Use of conditional operator
    }

}

```

## How to use the script

---

1. In the unity project create a new script:

2. Name that script `CameraFollow.cs` This could be different but make sure to change the class name if you don't use CameraFollow.cs

3. Double click the script to open in your editor (Probably MonoDevelop) and paste my code, be sure to name the class correctly if you used a different filename

4. Add the script to the camera object. In the hierarchy click on the camera, then click on on `Add Component` then search for the name of the script (CameraFollow.cs), press enter when the follow script is highlighted

5. Set the target, in your case the player. Either click on the circle and select the player from the window that pops up or drag the player object into the target parameter.

6. Adjust the values to suit you

* X - Follow on the X axis
    * Y - Same as X but on Y axis
    * Z - Same as X but on Z axis
    * X Offset - Amount to offset this position compared to target position on the X axis
    * Y Offset - Same as X offset but on Y axis
    * Z Offset - Same as X offset but on Z axis
> 4 votes

---
Tags: unity
---


# Question
Title: problem loading Collada DAE model using Assimp in OepnGL 4.4
I am loading a model in my OpenGL application using Assimp library like this :

```
bool CGameObject::LoadModelFromFile(char* sZFilePath)
{
std::string fn = sZFilePath;
std::string td = "\\";
std::string mfn = _getcwd(NULL, 0) + td + fn;
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(mfn,
    aiProcess_CalcTangentSpace      |
    aiProcess_Triangulate           |
    aiProcess_JoinIdenticalVertices |
    aiProcess_SortByPType);

if (!scene) {
    return false;
}

const int iVertexTotalSize = sizeof(aiVector3D) * 2 + sizeof(aiVector2D);
int iTotalVertices = 0;

for(UINT i = 0; i < scene->mNumMeshes; i++) {
    aiMesh* mesh = scene->mMeshes[i];
    int iMeshFaces = mesh->mNumFaces;
    for (UINT f = 0; f <iMeshFaces; f++) {
        const aiFace* face = &mesh->mFaces[f];
        for (UINT k = 0; k < 3; k++) {
            aiVector3D pos = mesh->mVertices[face->mIndices[k]];
            Model.vertices.push_back(pos.x);
            Model.vertices.push_back(pos.y);
            Model.vertices.push_back(pos.z);
        }
    }
}

// VAO
glGenVertexArrays(1, &m_vao);
glBindVertexArray(m_vao);

// VBO
glGenBuffers(1, &m_vbo);
glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
glBufferData(GL_ARRAY_BUFFER, this->Model.vertices.size() * sizeof(GLfloat), &this->Model.vertices[0], GL_STATIC_DRAW);
glVertexAttribPointer((GLuint)0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(0);

// unbind buffers
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);

// return success when everything is loaded
return true;
}

```

and then render it like this :

```
for (GameObject::iterator i = GameObjects.begin(); i != GameObjects.end(); ++i)
{
    CGameObject* pObj = *i;
    glUniformMatrix4fv(MatrixID, 1, GL_FALSE, GetMVPMatrix(pObj->position));

    glBindVertexArray(pObj->m_vao);
    glVertexAttrib3f((GLuint)1, 1.0, 0.0, 0.0); // set constant color attribute
    glDrawArrays(GL_TRIANGLES, 0, pObj->Model.vertices.size());

}
.
.
.

// function used to set MVP matrix
GLfloat* GetMVPMatrix(glm::vec3 position)
{
glm::mat4 Model = glm::translate(mat4(1.0), position);
glm::mat4 MVP3 = Projection * View * Model;
return &MVP3[0][0];
}

```

I created and exported my model using **Blender**. if I use **OBJ** format then it is rendered correctly :

but with **DAE** format it is like this :

My model has 5 meshes and debugging in Visual Studio shows that all 5 meshes are loaded.

Loading the **DAE** file in assimp\_viewer shows the model file has been exported correctly :

Where am i doing it wrong ?

# Answer
As Stephen said in the comments there is transformation data that you are missing. This data is not stored in `aiMesh`, but in `aiNode`. Instead of iterating over `scene->mMeshes` iterate recursively over `scene->mRootNode` and it's `mChildren`. Then you iterate over `node->mMeshes` and use them as the index of `scene->mMeshes[index]`. Lastly, you need to apply `node->mTransformation` to each vertex before adding them to the container.

For example (not tested, probably has some minor mistakes.)

Replacing the main for loop:

```
LoadModelFromNode(scene, scene->mRootNode, aiMatrix4x4());

```

Where `LoadModelFromNode(aiScene* scene, aiNode* node, aiMatrix4x4 transformation)` is something like:

```
// accumulate from parent transformation.
transformation *= node->mTransformation;

for(UINT i = 0; i < node->mNumMeshes; ++i) {
    aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
    for (UINT f = 0; f < mesh->mNumFaces; ++f) {
        const aiFace* face = &mesh->mFaces[f];
        for (UINT k = 0; k < 3; ++k) {
            aiVector3D pos = mesh->mVertices[face->mIndices[k]] * transformation;
            Model.vertices.push_back(pos.x);
            Model.vertices.push_back(pos.y);
            Model.vertices.push_back(pos.z);
        }
    }
}
for(int i = 0; i < node->mNumChildren; ++i){
    LoadModelFromNode(scene, node->mChildren[i], transformation);
}

```
> 1 votes

# Answer
Your problem and a possible solution is supplied by chipgw.

But there is an alternate solution, which is an importer flag, which will pre-transform everything for you.

So you can simply add this flag to your importer: `aiProcess_PreTransformVertices`.

But note that this has a huge negative: It drops all animations.(Although the node tree is kept)
> 1 votes

---
Tags: opengl, windows, assimp
---


title: Map coordinates system

text:
# Question
Title: Map coordinates system
I am planning to implement in my game a very big map. I won't be showing all map at once but rather only a selected part of it. Additionally, I would need to connect hexes into bigger pieces (provinces) and show them altogether.

I was thinking of using a hex map. Can you recommend any manual relating to working on coordinates on hex map? I am looking for a good way to store the hex positions on map so that I can easily find nearby hexes and do not have to load all the map at once.

Maybe you may also recommend some reliable alternatives to hex maps?

I am limited to 2D.

# Answer
If you are interested in doing a hex map you should definitely check out this http://www.redblobgames.com/grids/hexagons/

It coves few different methods of storing hex grids as well as basic operations like distance, fov, rotation and many more. It also describes how to do mapping from screen coordinates to hex coordinates and vice versa.
> 1 votes

# Answer
All three uniform 2D grids can be stored in a rectangular grid, you just have to scale and shear it to fit the one you're aiming for.

To know what regions you need to load just transform the viewport extents to the data's coordinate system.
> 5 votes

---
Tags: tilemap, maps, hexagonal-grid
---


# Question
Title: What is the difference between a game object being disabled and it made inactive?
I am looking over a script that has a particular function called to disable the script and mark a list for re-structuring:

```
void Disable()
{
    gameObject.SetActive(false);
    isEnumerated = false;
}

```

What I am trying to determine is whether it would be better to simply have the code in the OnDisable() function:

```
void OnDisable()
{
    isEnumerated = false;
}

```

I found that OnDisable() calls whenever the game object is "disabled" or "inactive", but I am a bit confused on the exact difference between the two. Documentation I have found that references both is only specific in that they are two different cases, where places that offer definition appear to use the two words synonymously.

# Answer
As far as I can tell, when an object is disabled it is "turned off" from the current scene: it doesn't perform behaviors, code, event or interactions with other instances. The only exception is responding to scripts that "enable" back disabled object. So, a disabled object is like it isn't there but there's a reference to it somewhere in order to enable it for use. This can be a better solution than having an object flagged as not active (in a naive way) but still existing and having its own CPU calculations, because you can enable objects as soon as you actually need them.

An inactive object is something similar to a disabled object, though it can still responds to global functions (you can find inactive objects, but not disabled ones) and so on.
> 1 votes

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


# Question
Title: How do I trigger OnSelect() via the ISelectHandler in my class?
I'm trying to figure out how I can make a custom UI element identify when it has been selected or deselected. Classes such as `Selectable` inherit from the `ISelectHandler` and `IDeselectHandler` and their methods `OnSelect()` and `OnDeselect()` are called whenever I click inside the `Selectable` element and click outside of it.

From my understanding, inheriting from the appropriate handler interface and implementing it's required method will allow your class to handle events from the `EventSystem`. As an example if I have:

```
public class TestSelectable
    : MaskableGraphic,
    ISelectHandler,
    IDeselectHandler,
    IPointerEnterHandler,
    IPointerExitHandler
{

    public void OnSelect(BaseEventData eventData)
    {
        Debug.Log("Selected");
    }

    public void OnDeselect(BaseEventData eventData)
    {
        Debug.Log("De-Selected");
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        Debug.Log("Pointer Enter");

    }

    public void OnPointerExit(PointerEventData eventData)
    {
        Debug.Log("Pointer Exit");

    }

```

When the mouse enters and exits the element the `OnPointerEnter()` and `OnPointerExit()` methods are sucessfully called. However selecting/De-selecting the element does not cause the `OnSelect()` or `OnDeselect()` methods to be called. Though if you look in `InputField.cs` *(which inherits from `Selectable`)*, the `OnSelect()` method does successfully get called when the input field is selected. I'm trying to replicate this within my own element without having to inherit from `Selectable`, and since Unity's event system is publicly accessible this should be possible.

Are there other requirements that will enable those events to fire and call my methods?

# Answer
> 3 votes
I managed to figure this out. You need to manually tell the `EventSystem` that the object has been selected. On a method such as `OnPointerDown()` you need to call the `EventSystem.current.SetSelectedGameObject()` method and pass in the event data and your gameobject.

```
public class SelectableText
    : MonoBehaviour,
    IEventSystemHandler,
    ISelectHandler,
    IDeselectHandler,
    IPointerDownHandler,
    IUpdateSelectedHandler
{

    public void OnPointerDown(PointerEventData eventData)
    {
        if (eventData.button != PointerEventData.InputButton.Left)
            return;

        // Selection tracking
        EventSystem.current.SetSelectedGameObject(gameObject, eventData);
    }

    public void OnSelect(BaseEventData eventData)
    {
        //base.OnSelect(eventData);
        UnityEngine.Debug.Log("Selected");
        isFocused = true;
    }

    public void OnDeselect(BaseEventData eventData)
    {
        //base.OnDeselect(eventData);
        UnityEngine.Debug.Log("De-Selected");
        isFocused = false;
    }

```

If you have inherited from `ISelectHandler` and `IDeselectHandler` the `OnSelect()` method will be called, and if you click off of your UI element onto the background or another UI element the `OnDeselect()` method will be called.

# Answer
> 2 votes
Ran into the same situation myself recently and try as I might I never got the event to fire off. I'm guessing *Selectable* does some kind of initialization with the Event System, maybe adding the game object to a list of selectable objects or maybe checking the Input Position versus the graphic the control contains etc...

But you can get around this simply by adding the Selectable script to the game object your TestSelectable script is attached to. Once you do that then you will begin recieving OnSelect() and OnDeselect(). You can automate this by adding the line: \[RequireComponent (typeof (Selectable))\] at the top of your script, leaving you free to still derive from MaskableGraphic.

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


# Question
Title: How to I Create My own 3d modals in unity5?
How to I Create My own 3D modals in unity 5? Actually,I don't know how to create a 3d modals in unity 5.If anyone is know, PLZ tell me...!

# Answer
Currently, Unity3d has no built-in 3d modeling tool. However, it can import models made with other editors in a large variety of formats. You can use almost every common 3d modeling program to create 3d models and then import them into Unity.

For software recommendations regarding 3d modeling programs, please ask on https://softwarerecs.stackexchange.com
> 0 votes

---
Tags: unity, 3d, models
---


# Question
Title: What is the name of the phenomenom where faces get stretched to the middle of the screen?
I'm trying to make my own 3D view in java without the use of any imported libraries. It has been going really well for me except for the fact that if I'm positioned in a certain way some of my edges get stretched to the middle of the screen. a reference image:

The gun render's completely fine in the front part, but when I'm looking at it from this angle it looks like some of my edges get stretched to my viewto point. I want to google information on what other people have done to fix it, but I have no idea what this phenomenom is named.

I'm not looking for an answer on how to fix it, but on the name of the phenomenom because I'm trying to learn as much as possible by myself.

I'm pretty sure this is a wellknown problem and I just can't remember the name of it.

# Answer
I've *never* seen a specific term regularly used to describe this artifact. "Stretching to infinity" (as in the object gets stretched to infinity) is probably the most common phrase I've heard used to describe the problem.

One of the most common causes of this problem is bad or uninitialized data in a vertex or index buffer, usually caused by a failure to compute the correct size of a vertex or index buffer, or the correct number of elements being rendered based on the primitive topology.
> 1 votes

---
Tags: terminology
---


# Question
Title: Making a border around a translucent shape in LibGdx
The recommended method for making a border around a shape using LibGdx is to draw a larger version of the shape to serve as the border, then draw the shape over the larger image.

```
shapeRenderer.setColor(borderColor);
shapeRenderer.circle(x, y, radius + borderWidth);
shapeRenderer.setColor(shapeColor);
shapeRenderer.circle(x, y, radius);

```

This works well most of the time, but if you want `shapeColor` to have any opacity less than 1, it fails. The problem is that you can see the `borderColor` through the shape, and the colors are blended.

Is there anyway to fix this issue?

# Answer
One thing you could try is to draw the border as a line with a thickness first, then draw the inner part of the circle as a filled shape;

```
shapeRenderer.begin(ShapeType.Line)
Gdx.gl10.glLineWidht(borderWidth);
shapeRenderer.setColor(borderColor);
shapeRenderer.circle(x, y, radius + borderWidth);
shapeRenderer.end();

shapeRenderer.begin(ShapeType.Filled)
shapeRenderer.setColor(shapeColor);
shapeRenderer.circle(x, y, radius);
shapeRenderer.end();

```

You might have to query for the capabilities for the line width using `glGet` and asking for 'GL\_ALIASED\_LINE\_WIDTH\_RANGE' and 'GL\_SMOOTH\_LINE\_WIDTH\_RANGE' (opengl reference), and it will possibly make the drawing device dependent.

If that does not work, you could try render to texture first, using a frame buffer with no blending, then draw that buffer (with blending) to screen;

```
// Position and size of circle, and border
float circleX = 100;
float circleY = 100;

float radius=100;
float border=10;

// Total size of the buffer
int size = (int)((radius+border)*2);

// Create the buffer and get a region to it
FrameBuffer buffer = new FrameBuffer(Format.RGBA8888, size, size, false);
TextureRegion region = new TextureRegion(buffer.getColorBufferTexture());
region.flip(false, true);

// Begin the buffer, any draw calls made after this affect the buffer, not the "screen"
buffer.begin();
ShapeRenderer renderer = new ShapeRenderer();
renderer.begin(ShapeType.Filled);
// Draw border, centered on buffer
renderer.setColor(new Color(1, 0, 0, 1.0f)
renderer.circle(size / 2, size / 2, radius + border);

// Draw center, centered on buffer
renderer.setColor(new Color(1, 1, 1, 0.5f)
renderer.circle(size / 2, size / 2, radius);

renderer.end(); // shapes done
buffer.end(); // buffer done

// Now render the buffer onto the "screen"
SpriteBatch batch = new SpriteBatch();
batch.begin();
// Move to the buffer offset representing the circle's position
batch.draw(region, circleX - size, circleY - size);
batch.end();

```

Obviously, in the example above, try to new up the `buffer`, `region`, and `renderer` outside of your render method so that you don't pay the performance penalty of doing that every time.
> 3 votes

---
Tags: libgdx
---


title: 8 ball pool scratch card effect logic

text:
# Question
Title: 8 ball pool scratch card effect logic
how to replicate this type of scratch card effect in Unity3D considering its for mobile.

https://youtu.be/6wLWu1BefXs

Two cases 1. Clear part of screen where user touches. 2. How to trigger rewards after certain amount of image get reveal?

# Answer
> 3 votes
Create a Texture2d and assign it to the Mask component then use SetPixel to set the alpha of pixels beneath the players finger to 0.

SetPixel

1) Use EventTrigger Component to track OnPointerDown and OnDrag on your scratch card.

2) Interpolate pixels at touch location based on touch position and screen size of Scratch Card.

3) Set pixels in Mask Texture to alpha = 0 where touched.

4) Apply changes to Texture2d.

---
Tags: unity
---


# Question
Title: Unable to stop navmeshagent for rotation before moving
I'm trying to get the NavMeshAgent to rotate before calculating a path and proceed walking.

I stumbled upon a thread that said this can be done by manually rotating the object first.

However, I am still stumped as to how to do this as my unit either a)refuses to move or b)moves, but does not stop to rotate.

Below is the code I've attempted.

```
void Update() {

    RaycastHit hit;
    if (Input.GetMouseButtonDown(0))
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out hit) && hit.collider.tag == "Ground")
        {
            targetPosition = hit.point;
        }
    }

    if (transform.rotation != _lookRotation) //check if unit is in line with direction of hit.point
    {
        agent.Stop(); //stops the navmeshagent from moving.

        _direction = (targetPosition - transform.position).normalized;
        _lookRotation = Quaternion.LookRotation(_direction);

        transform.rotation = Quaternion.RotateTowards(transform.rotation, _lookRotation, Time.deltaTime * speed);

    } //perform rotation
    else //else, if already in line, set path and walk.
    {

        agent.SetDestination(targetPosition);

    }

```

# Answer
1.) You need to update \_lookRotation when the mouse is clicked or it never changes so your agent will never look at a new location.

Simple Coroutine Example:

```
IEnumerator RotateAgent(Quaternion currentRotation, Quaternion targetRotation) {

    IsRotating = true;
    while(current rotation != targetRotation) {
        transform.rotation = Quaternion.RotateTowards(currentRotation, targetRotation, RotationSpeed * Time.deltaTime);

        yield return 1;
    }
    IsRotating = false;
}

```

Then on Mouse Click:

```
StartCoroutine(RotateAgent(transform.rotation, _lookRotation);

```

And only do Agent.SetDestination if IsRotating = false;
> 1 votes

---
Tags: unity, vector, scripting, quaternion, navmesh
---


# Question
Title: Efficient modification of Texture2D at runtime for a 2D painting game in Unity3D
I have spent some time looking for different solutions to be implemented in a mobile painting game I'm creating. At this time, everything is working but I have some serious performance problems on large screens and slow devices because I massively use setPixel / setPixels and apply on Texture2D.

I have come across 2 ways to speed things up:

1) Tile the image in small chunks, every chunk would be a Texture2D, and just upload (calling Texture2D.Apply()) the modified chunks.

2) Another trick I could apply on top of the tiling solution is to catch changes in an array and write them down to the needed Texture2D chunk and apply it every X miliseconds if modified.

I would like to know what other optimizations I could apply to this subject. Perhaps I should throw setPixel away and go with another more efficient way?

Cheers.

# Answer
A major bottleneck here is syncing the CPU & GPU to shuttle the texture back and forth - to the CPU for modification with SetPixels(), and to the GPU for display.

Also, the CPU is typically working on just one pixel at a time, while the GPU can churn through them in huge batches.

So, we can often greatly improve performance by keeping the texture work on the GPU side, using RenderTextures, Graphics.Blit, and the like. That lets the graphics hardware do what it was designed for, and it's very fast at it.

The exact steps will depend on the kind of painting program you want to make, and how much you'd like to do in-scene or in code.

One common approach is to set up a camera looking at a copy of your current canvas texture, rendering to another texture. Anything you put between the canvas and that camera will get composited into the new texture every frame. You can use a coloured sprite that represents the shape of your brush, or an image stamp, setting its position in Update() so that it gets drawn in the right place each frame.

You can ping-pong the two RenderTextures (one for reading the current canvas, one for writing the new one) each time you add a segment of brush stroke or stamp to your image.

(Note that you'll want any UI or preview graphics to be added by a second camera, to ensure they don't get baked into the canvas image)

For more specialized image operations, I'd recommend asking a new question with specifics of the effect that you want to achieve.
> 3 votes

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


title: Changing animation speed at runtime

text:
# Question
Title: Changing animation speed at runtime
Is there a way in Unity to change the animation speed of an animation managed by an animator controller (Mecanim)?

I'd like to do that at runtime so that I can speedup and slow down an animation based on conditions in code.

# Answer
You can change the Speed of the Animator itself, which may be adequate for what you are trying to do:

http://docs.unity3d.com/ScriptReference/Animator-speed.html

However, if you need to adjust each animation individually, you will need to use the AnimationState object instead.

http://docs.unity3d.com/ScriptReference/AnimationState-speed.html
> 4 votes

---
Tags: unity, animation, mecanim
---


# Question
Title: Health bar - calculating health bar's position from percentage
I'm making a simple health bar in Unity 3D. Health bar UI is made from images. I'm having a problem with setting bar's position based on health percentage. Here's a script part:

```
    percentHealth = (currentHealth / maxHealth) * 100; //get's health percentage.

    HealthBarHealth.transform.localPosition = new Vector3(healthBarCurrentX, 0); //moves health bar

```

I want healthBarCurrentX to be calculated from these values:

percentHealth - percentage calculated from max health and current. healthBarMaxX = 0f - health bar's position at 100% health. healthBarMinX = -273.5f - bar's position at 0% health.

So when health is 50%, currentX is at -136.65, etc.

# Answer
> 1 votes
Use Mathf.Lerp() to interpolate between the value you want at 0% and the value you want at 100%.

Mathf.Lerp

```
healthBarCurrentX = Mathf.Lerp(healthBarMinX, healthBarMaxX, currentHealth / maxHealth);

```

# Answer
> 0 votes
You could have a black bar, with a green bar painted on top of it. Just change length of the bar on top, and it should work well.

```
blackbarlength = 100;
percentHealth = (currentHealth / maxHealth) * 100;
greenbarlength =  percenthealth;

```

# Answer
> 0 votes
Why not use Slider component of uGUI? Its very easy,flexible and resolution independent.Check in, https://unity3d.com/learn/tutorials/projects/survival-shooter/player-health

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


# Question
Title: putting a delay between animation looping
I've got a player swinging a sword, this animation is controlled by a state machine. However, I don't want the player to be continuously swinging the sword when he's attacking -- I want him to swing once, wait a bit, then swing again. The animation in the animator controller has a speed variable I can control, but this merely makes each swing slower or faster -- I want the swing speed to be the same, just have a pause before the animation loops again. How should I do it?

# Answer
> 2 votes
When you accept the character input, you can verify if a certain delay has passed, before you allow the input to be submitted again.

```
float Delay = 3f;

void Update()
{
    Delay -= Time.deltaTime;

    if (Delay <= 0 && Input.GetKey(Keys.Attack))
    {
       Attack();
       Delay = 3f;
    }
}

```

# Answer
> 0 votes
You should use programming if unity does not have the option. For unreal engine 4, there is an animation delay but programming is the best choice.

It should be like loop animation1 and wait for the seconds you want.

# Answer
> 0 votes
Another option is to add idle frames to the attack animation strip to fit the timing that you want, but it's less efficient than passing a delay as Jon suggests.

Alternatively if you are using the AnimationState object, you can impose delays between transitions between the looping of the attack state.

---
Tags: unity
---


title: AR / VR Software Engineering

text:
# Question
Title: AR / VR Software Engineering
What is the primary difference between Augmented Reality and Virtual Reality software engineering?

# Answer
The main difference in concept is also the main difference from a software engineering perspective: AR needs a view of the real world, VR does not. Thus AR has the challenge of overlaying graphics onto a live view, while VR has the challenge of completely replacing the environment around the viewer.
> 2 votes

---
Tags: virtual-reality, augmented-reality
---


title: CS:GO workshop awp skin scrambles

text:
# Question
Title: CS:GO workshop awp skin scrambles
I was starting make my awp skin, but I was wondering that my skin at CS:GO looks bit different than on photoshop. So I came here for help. I will show just a test skin (fully red).

First I was save my skin with photoshop to .tga format (32 bits/pixel). Then importing to VTF editor, but not changing any of these settings, they are default. After that I checked only "No Level Of Detail", "No Mipmap" and "SRGB".

Opening CS:GO and workshop, awp is not fully red, there is some scrambles.

I hope for solution. :)

# Answer
> 1 votes
From the looks of it, you have some other texture layer that's adding "wear and tear" to your model (for example the corners of the ammo cartridge). You should poke around for decals or other layers being applied to the model.

I'd be particularly interested in the slider at the bottom:

---
Tags: textures, modding
---


# Question
Title: Is quadrilinear texture sampling hardware supported?
If you have a volume texture with mipmaps, GL\_LINEAR\_MIPMAP\_LINEAR texture sampling will perform quadrilinear texture sampling.

Is that implemented in hardware like bilinear texture sampling is? Or does the driver just do two trilinear texture samples and interpolate those results for you?

Is trilinear sampling even supported by hardware?

# Answer
Alfonse Reinheart's post in this thread (#8) should shed some light. When you boil it down, the answer is "there's no such thing." Quadrilinear sampling is simply the term used for applying a linear sampling (GL\_LINEAR\_MIPMAP\_LINEAR in OpenGL) to a 3D texture.

You can almost argue the answer is "yes" since linear is at the hardware level and it's simply applying several passes of linear to the texture; but strictly speaking, no.
> 2 votes

---
Tags: textures, graphics, graphics-programming, hardware, hardware-acceleration
---


title: Aspect ratios for sprites in Unity3d

text:
# Question
Title: Aspect ratios for sprites in Unity3d
I'm using Unity3D version 5.0.

I'm wondering what the best way to deal with changing resolutions in Unity is. In Swift I can just use the @x2/@x3 in order for it to pick the correct sprite for it to use. Is there a similar mechanism in Unity?

Thanks

# Answer
I would read this and this for some helpful tips.

The short answer is no, but Unity has some very convenient and efficient tools to handle scaling images. So ideally you should choose the highest resolution you wish to support, and let the engine scale it from there. I'm not 100% on this, but I think I read somewhere that when you build the project for export, Unity's optimizer will pre-generate scaled images for use in the final product.
> 1 votes

---
Tags: unity, sprites, ios, resolution
---


# Question
Title: Is it dramatically more efficient to have less BoxCollider2D's (for raycasting/custom physics)?
I have a temporary tile system for my platformer where I simply duplicate the same tiny box sprite with a `BoxCollider2D`on it over and over again. Like I said this is a temporary procedure for design testing before I choose something for practical, I don't need it to be the most efficient.

That being said, I'm curious: when using `BoxCollider2D`'s **and detecting them with a custom ray-cast script** is it much less efficient than having a few larger colliders? How much less efficient?

Please back up answers with explanations of source code if possible.

# Answer
There are some optimizations under the hood that prevent the engine from iterating over the total set of colliders every time it checks: layer filtering, active/inactive flags.

That said, the fewer items in the list of collidable objects that the collision checker has to go through, the faster the processing will be. It's a simple numbers game. It takes less time to check 4 edges of one box than it does to check 4 edges of 500 boxes.

In effect tho, no there will not be a significant speed improvement. There will however be a mild memory consumption improvement (fewer boxes to store).
> 1 votes

---
Tags: unity, physics
---