# Question
Title: Extending the camera vs CameraHelper class vs camera field
I am following an eBook called "Learning Libgdx Game Development"

In it, the author implements a `CameraHelper` class that implements `Zoom`, target-following behaviour, and probably some other things along the way.

Can I do this just by extending the camera class, or using composition?

Approaching it like this seems like a clearer code to me:

```
public class Camera extends OrthographicCamera {
    GameObject target;
    boolean followTarget;

    Camera(float viewWidth, float viewHeight){
        super(viewWidth, viewHeight);
    }

    public void setTarget(GameObject target) {
        this.target = target;
    }

    public GameObject getTarget() {
        return target;
    }

    @Override
    public void update(){
        if(followTarget && target != null){
            this.position.x = target.position.x;
            this.position.y = target.position.y;
        }
        update(true);
    }
}

```

Any problems with this that I can expect?

# Answer
> 1 votes
Yes, you can. I don't see any extra problems. It is OOP way.

* Camera extends OrthographicCamera -\> Camera IS OrthographicCamera
* CameraHelper isn't Camera it Helps to work with camera. This is like lib with commonly used stuff. For example if camera doesn't follow player (no need), you don't use/call method from CameraHelper class.

---
Tags: java, libgdx, camera, software-engineering
---


title: How to reset position of my player?

text:
# Question
Title: How to reset position of my player?
Link: https://academo.org/demos/rotation-about-point/

```
    private bool isTiming = false;
    private float timeTillKeyIsPressed = 0;

    float time = 1;
    float time2 = 4;

    void Update()
    {
       if (isTiming)
        {
           if (timeTillKeyIsPressed <= time)  //0<=1 1<=1
            {
                if (time2 != 0) //4!=0 4!=1 4!=2 4!=3 4!=4
                {
                    time2 -= Time.deltaTime;

                    float angle = 360;   // reset here but not work properly

                    rb.transform.Rotate(Vector3.forward * angle * Time.deltaTime / time);

            }
        }
    }

    public void Rotate(float angle)
    {
        float d = angle * Time.deltaTime;

        int movement = GetMovement();

        rb.transform.Rotate(Vector3.forward * d * (float)movement * speed);

    }

  public int GetMovement()
  {
        if (Input.touchCount > 0)                              //mobile     //how many count touch
        {
            Touch touch = Input.GetTouch(0);

            float num = (float)(Screen.width / 2);

            var touchres = touch.position.x;
            //DebugPanel.Log("touchres", "touchres:" + touchres);

            var res = touchres > num;
            //DebugPanel.Log("res", "res" + res);

            if (res)//TRUE(Right)
            {

                return -1;
            }
            else//FALSE(Left)
            {

                return 1;
            }
        }
        else
        {
            return (int)Input.GetAxisRaw("Horizontal") * -1;     //pc
            //return 0;
        }
    }

```

```
  void OnTriggerEnter2D(Collider2D other)  //here my obstacle touch my player
    {
        foreach (Transform child in transform)
        {
            if (child.tag == "point")
            {
                isTiming = true;
            }
        }
    }

```

Image:

when I m playing the game:

I want the:

Player Image:

I want the when my player touches my obstacle then I want to reset the position of my player?

# Answer
> 0 votes
Create a new script Call it any thing you want, I named it "ReseatingPlayer" and then past the following code into it:

```
    public static ReseatingPlayer instance;
    [SerializeField] private Transform playersParent;
    [SerializeField] private Transform redPlayer;
    [SerializeField] private Transform bluePlayer;

    [Space(10)]
    [SerializeField] private float redPlayerStartX;
    [SerializeField] private float bluePlayerStartX;

    private Vector3 playersParentStartPosition;

    private void Start()
    {
        instance = this;
        playersParentStartPosition = playersParent.position;
    }

    public void ResetPlayers(float delay)
    {
        Invoke("ResetPlayersPositions", delay);
    }

    public void ResetPlayersPositions()
    {
        redPlayer.localPosition = new Vector3(redPlayerStartX, 0, 0);
        bluePlayer.localPosition = new Vector3(bluePlayerStartX, 0, 0);
        playersParent.position = playersParentStartPosition;
    }

```

Now attach the script to players parent assign the values to it like I did:

**redPlayerStartX**: assign red player start X position to it.

**bluePlayerStartX**: assign blue player start X position to it.

**How to re seat player:** if you want delay this do it like: 4 means that re seat player after 4 secs.

```
 ReseatingPlayer.instance.ResetPlayers(4);

```

if you don't want any delay:

```
ReseatingPlayer.instance.ResetPlayersPositions();

```

I hope this will do the job.

---
Tags: unity, rotation
---


title: Disposing objects when changing screens

text:
# Question
Title: Disposing objects when changing screens
I'm making my first game with LibGDX and Box2D, and I've realized that the memory used increases when I change screens. It starts from 150MB and progressively reaches 850. How should I deal with this? It does not seem to be a memory leak, memory is constant throughout the level, and I'm using an AssetManager to dispose everything needed.

The problem is when switching screens, since objects remain in memory. What is the best practice in this case? Should I have a method in each class that sets every object to `null` before the screen is disposed? Another problem might be that I have a static class for all my constants (this was the method proposed in the Udacity course), could this be an issue?

Another idea described here is initializing all screens in the beginning and using them throughout the game. Though I'm not sure this could be done in my game now. Is this good practice?

I tried profiling a bit although it's the first time, here are some results. The sudden 'hops' are when switching screens.

# Answer
> 0 votes
Setting objects to null might not guarantee proper disposal. Usually an asset manager has some kind of reference counter for every used asset. It is better to use dispose instead of setting to null and waiting until the destructor call happens via garbage collector. It is better because the dispose happens instant and you have better control when memory is freed and stuttering can occur on large disposals. Understand that if you dispose the asset manager clears cpu and gpu memory for e.g. a texture. Initializing all screens is only a good idea if your game size is very small and you want achieve faster level switching. Otherwise it is a bad practice because you waste system resources for content that isn't even consumed by the player. The general rule is to only allocate as much as absolutely required and as less as possible. That's the whole point of loading screens. Less memory allocated = able to support older hardware = bigger playerbase.

# Answer
> 0 votes
Possible memory leak. LibGDX uses native Box2D. To use it, they wrote Java wrapper, because of that, the objects that are created by the native methods need manual disposal.

```
    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = shape;
    fixtureDef.density = 1f;
    Fixture fixture = body.createFixture(fixtureDef);
    shape.dispose(); // You need to dispose Shape manually...

```

Also do not forget to dispose the world.

```
@Override
public void dispose() {
    //dispose other stuff
    world.dispose();
}

```

Also, if more detailed profiling is not possible, comment some part and check it again ....

---
Tags: libgdx, box2d, memory
---


# Question
Title: Quick way to approximate a truncated gaussian distribution?
I'm doing some procgen stuff and I need a truncated gaussian distribution. Basically, I need a way to get the same thing as this:

```
import random
def truncated_gaussian(mean, deviation, min, max):
    while True:
        val = random.gauss(mean, deviation)
        if min < val < max: return val

```

except without so much wasted effort. It looks like this is a pretty complicated thing to do *properly*, but I don't need statistics-grade perfect randomness, just a video-game-grade approximation.

Anyone know a trick to make this work?

# Answer
When all else fails, cheat. You could either generate 10,000 (or 1,000,000 or whatever) Gaussian randoms at startup, or put them in a resource and load them at start up, then generate one random offset into the list and start reading them as needed. Then it would be as fast as a look-up.
> 2 votes

---
Tags: mathematics, procedural-generation, random, statistics
---


title: How to loop color list SpriteRenderer

text:
# Question
Title: How to loop color list SpriteRenderer
I can already make one for (int) normally, but I'm trying to create a sprite renderer loop using (i ++ / i--) sorry, I do not know the names for this condition but it's showing a mountain of errors

```
public List<Color> Sprit;

public void Previous(){
for(int i = 0; i Sprit.Count; i++)
{
    Sprit[i].GetComponent<SpriteRenderer>().color = Sprit;
}
public void Next(){
for(int i = 0; i< Sprit.Count; i--)
{
    Sprit[i].GetComponent<SpriteRenderer>().color = Sprit;
}

```

# Answer
While your question asks for help with loops, it looks as though actually all you want to do is select the next or previous colour in a list, and apply that to a list of re-determined colours.

To do that we must declare the list of colours, the index for those colours, and the SpriteRenderer.

We then increment or decrement the index, based on the selection, and then change the Colour in the SpriteRenderer accordingly. It doesn't require looping.

```
public List<Color> coloursList = new List<Color>(); // Fill this list in the editor with colour values
public int colour = 0; // The colour to start from
private SpriteRenderer sR; /* The sprite renderer itself. Attach this script
to the gameobject you want to change the colour of */

private void Start(){
sR = gameObject.GetComponent<SpriteRenderer>(); // Get the sprite renderer
}

public void Previous(){
colour--;
if(colour < 0){colour = coloursList.Count - 1;}
sR.color = coloursList[colour];
}

public void Next(){
colour++;
if(colour >= coloursList.Count){colour = 0;}
sR.color = coloursList[colour];
}

```
> 0 votes

# Answer
For the sake of giving this old question a more complete answer:

It looks like you really want two separate collections:

* A collection of renderers whose colours you want to change
* A collection of colours to change them to

We can do this with two arrays (or lists, if you need to add/remove items dynamically):

```
public class SpriteColorChanger : MonoBehaviour {

    public SpriteRenderer[] spriteRenderers;

    // I give this a default value so the script is well-behaved,
    // even if we forget to populate the color array in the inspector.
    public Color[] colors = new Color[]{ new Color(1, 1, 1, 1) };

    int _currentColorIndex;

    void UpdateAllRenderers() {
        var currentColor = colors[_currentColorIndex];

        foreach(var renderer in spriteRenderers)
            renderer.color = currentColor;
    }

    void NextColor() {
        // The % operator, "modulo", will wrap the index around,
        // so if we go past the end of our array, we restart at 0.
        _currentColorIndex = (_currentColorIndex + 1) % colors.Length;

        UpdateAllRenderers();
    }

    void PreviousColor() {
        // (-1 % length = -1), but we want to wrap around to (length - 1),
        // so we add instead of subtracting, to wrap below zero correctly.
        _currentColorIndex = (_currentColorIndex - 1 + colors.Length) % colors.Length;

        UpdateAllRenderers();
    }

    void Start() {
        UpdateAllRenderers();
    }
}

```
> 0 votes

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


# Question
Title: OnTriggerExit2D called multiple times when two triggers touch
I have two GameObjects tagged "Point", each with a Collider 2D set to `Is Trigger`.

I have another GameObject, "pencil", which also has a Collider2D set to `Is Trigger`

I want to move the pencil the first point to the start drawing a line, and then stop drawing when it hits the second point.

My problem is that when the pencil hits a point, it calls `OnTriggerExit2D` multiple times. How can I only detect first contact with the point?

Pencil script:

```
private void OnTriggerExit2D(Collider2D collision)
{
    if (!collision.isTrigger)
    {
        if (collision.gameObject.tag == "Point")
        {
            writing = !writing;
        }
    }
}

```

# Answer
It looks like your Pecil needs some memory, so it can disregard repeated contacts with the same collider multiple times in a row.

This is related to the idea of "debouncing" a switch - the input to our systems, especially when they come from players or physics - can be messy. The mouse cursor might hover just at the border of a zone for several frames, alternately entering and exiting. So we often need to make our trigger responses "sticky", by remembering we've been activated, and requiring a larger action to deactivate/reset, something called hysteresis.

```
Collider2D _lastPointTouched;

void OnTriggerExit2D(Collider2D other)
{
    // Disregard collisions with anything but our points.
    if(other.gameObject.CompareTag("Point") == false)
        return;

    // Disregard repeated visits to the same point.
    if(other == _lastPointTouched)
        return;

    // Toggle our writing state, and remember this point for future events.
    writing = !writing;
    _lastPointTouched = other;
}

```

If you want, you can clear this memory if a condition is met (like the mouse button/touch is released, or the pencil gets far enough away, or if a certain amount of time passes) to allow starting a new line at this point when the player does so deliberately, without accidentally triggering it from a brushing contact.
> 1 votes

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


# Question
Title: how to calculate resulting velocity and angular velocity rocket has on center of mass
The issue i am having is that i can't seem to figure out how to apply force from a rocket to a bodies center of mass.

\*Edit This is in 2D

e.g. Let's call the body 'ship'

the 'ship' is 1000 (relative unit) and the center of mass is normalized at \[0,0\] (origin)

the 'ship' has two rockets (lets say for thrust vectoring), one at \[-2,-4\] (left) and one at \[2,-4\] (right) relative to the center of mass, and that both had nozzles pointed down (90 degree angle counterclockwise from x)

if the left rocket were to fire at say 500 (relative unit), what formula could i use to find the resulting force and angular force on the center of mass?

if it helps, the language is a superset of javascript (custom preparser similar to typescript), and i'm using a custom physics engine that only accepts force on center of mass as an array e.g. \[force x, force y, force angular\]. I tried to recycle my collision detection algorithm but it was like jamming a square into a circle shaped hole.

I've searched since last night and can't seem to find a formula to do this (atleast not one I can understand, I can't understand complex math notations).

Any and all help is greatly appreciated.

TL;DR
I need a formula that gives the resulting force and angular force from a offset rocket on center of mass where the result looks like:

\[force x , force y , force angular\]

the center of mass is normalized to origin,

and takes the variables:
rocket offset (\[x,y\]),
rocket angle (in degrees to center of mass),
force of rocket (in relative units)

# Answer
First we'll want to convert to world coordinates:

```
nozzleAngleWorld = nozzleAngleLocal + shipAngleWorld;
// Note here: nozzleAngleLocal is the angle your nozzle is *facing*/thrusting
// in your local coordinates, NOT the angle of the line from the center of mass through the nozzle.

forceWorld = new Vector2(
             cos(nozzleAngleWorld) * rocketForce,
             sin(nozzleAngleWorld) * rocketForce);

```

Then we can compute the worldspace offset of the point of force application from the center of mass of your ship. One way to do that is to store a "right" and "forward" unit vector for your ship's current orientation, but you can also do this with a matrix transform or trig.

```
rocketOffsetWorld = ship.right * (rocketOffsetLocal.x - shipCenterOfMassLocal.x)
                  + ship.forward * (rocketOffsetLocal.y - shipCenterOfMassLocal.y);

```

The angular force on your ship is called a "torque", and it can be computed with a simple cross product:

```
torque = cross(rocketOffset, forceWorld);

```

Where the 2D version of the cross product gives us a scalar value:

```
function cross(a, b) {
    return a.x * b.y - a.y * b.x;
}

```
> 2 votes

---
Tags: 2d, physics, javascript
---


# Question
Title: how to generate mipmap, and check if done properly?
i am implementing Mipmapping for my texture for the first time.

i have 2 questions

1. HOW TO CHECK IF MIPMAP IS DONE PROPERLY ?
2. HOW TO SET MIPMAP FOR TEXTURE FROM FILE ?

**First** one. i implemented texture in application.

```
ID3D11Texture2D* TEX;
D3D11_TEXTURE2D_DESC DESC;
DESC.ArraySize = 1;
DESC.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
DESC.CPUAccessFlags = 0;
DESC.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
DESC.Width = 256;
DESC.Height = 256;
DESC.MipLevels = 9;
DESC.MiscFlags = D3D11_RESOURCE_MISC_GENERATE_MIPS;
DESC.SampleDesc.Count = 1;
DESC.SampleDesc.Quality = 0;
DESC.Usage = D3D11_USAGE_DEFAULT;
r_assert(graphic->Device()->CreateTexture2D(&DESC, nullptr, &TEX));
ID3D11ShaderResourceView* TEXV;
D3D11_SHADER_RESOURCE_VIEW_DESC TEXVDESC;
TEXVDESC.Format = DESC.Format;
TEXVDESC.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
TEXVDESC.Texture2D.MipLevels = -1;
TEXVDESC.Texture2D.MostDetailedMip = 0;
r_assert(graphic->Device()->CreateShaderResourceView(TEX, &TEXVDESC, &TEXV));
graphic->DContext()->GenerateMips(TEXV);
D3D11_TEXTURE2D_DESC desc;
TEX->GetDesc(&desc);

```

not sure, but i think i generate Mipmap for `TEX` and i just want to know the ways how to check/debug if mipmap actually done well.

---

**Second**. i am also using `DirectX::CreateWICTextureFromFileEx` to create texture from file.

```
resource=nullptr;
newSRV=nullptr;

r_assert(
    DirectX::CreateWICTextureFromFileEx(
        graphic->Device(),
        (L"Data\\Texture\\" + fileName).c_str(),
        0,
        D3D11_USAGE_DEFAULT,
        D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE,
        0,
        D3D11_RESOURCE_MISC_GENERATE_MIPS,
        DirectX::WIC_LOADER_DEFAULT,
        &resource,
        &newSRV)
);
graphic->DContext()->GenerateMips(newSRV);
ID3D11Texture2D* tex = nullptr;
r_assert(
    resource->QueryInterface(IID_ID3D11Texture2D, (void**)&tex)
);
D3D11_TEXTURE2D_DESC desc;
tex->GetDesc(&desc);

```

and i checked `desc.MipLevels` is 1, which means there is no mipmapping. so wonder how to generate mipmap when using WIC function?

any advice would be appreciated^

# Answer
My solution.

So my approach is

1. i prepare image that i want to render with mipmap effect in file
2. create resource of that image(i used `CreateWICTextureFromFile`)
3. create an empty texture with mipmap setting.
4. read data from image and store in cpu
5. copy that data into texture with mipmapsetting
6. `DeviceContext->GenerateMaps`

```
ID3D11Texture2D* image = TextureMgr::Instance()->GetTexture("grass.jpg"); // it is just my custom function that read texture from file and return resource of it.

ID3D11Texture2D* tex = nullptr; // FIRST generate mipmap texture________________________________
D3D11_TEXTURE2D_DESC texDesc;
image->GetDesc(&texDesc);
texDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
texDesc.CPUAccessFlags = 0;
texDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
texDesc.MipLevels = 7;
texDesc.MiscFlags = D3D11_RESOURCE_MISC_GENERATE_MIPS;
texDesc.Usage = D3D11_USAGE_DEFAULT;
r_assert(device->CreateTexture2D(&texDesc, nullptr, &tex));

ID3D11Texture2D* stagTex; // create Staging texture_____________________________________
D3D11_TEXTURE2D_DESC stagDesc;
image->GetDesc(&stagDesc);
stagDesc.ArraySize = 1;
stagDesc.BindFlags = 0;
stagDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
stagDesc.MipLevels = 1;
stagDesc.MiscFlags = 0;
stagDesc.Usage = D3D11_USAGE_STAGING;
r_assert(device->CreateTexture2D(&stagDesc, nullptr, &stagTex));

// read from image_________________________________________________________________________
graphic->DContext()->CopyResource(stagTex, image);
D3D11_MAPPED_SUBRESOURCE mapped;
r_assert(graphic->DContext()->Map(stagTex, 0, D3D11_MAP_READ, 0, &mapped));
UINT* arr = new UINT[(mapped.RowPitch/(float)sizeof(UINT)) * stagDesc.Height];
ZeroMemory(arr, mapped.RowPitch*stagDesc.Height);
CopyMemory(arr, mapped.pData, mapped.RowPitch*stagDesc.Height);
graphic->DContext()->Unmap(stagTex, 0);

// copy image data into mipmap texture_______________________________________________________________
graphic->DContext()->UpdateSubresource(tex, 0, &CD3D11_BOX(0, 0, 0, stagDesc.Width, stagDesc.Height, 1), arr, mapped.RowPitch, mapped.DepthPitch);

// create SRV of mipmap texture______________________________________________________________
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
srvDesc.Format = texDesc.Format;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MipLevels = texDesc.MipLevels;
srvDesc.Texture2D.MostDetailedMip = 0;
r_assert(device->CreateShaderResourceView(tex, &srvDesc, &srv));
graphic->DContext()->GenerateMips(srv);

```

now you can use this final `srv` with mipmap setting.

Good luck
> 1 votes

# Answer
One way is capturing a frame with a graphics debugger, such as RenderDoc, Nsight, Visual Studio graphics debugger or something else, search for your texture in the resources window (different names with different programs of course), and see if there are any mip levels. You can also view any specific mip level.

An other way is to sample the texture in a shader with SampleLevel(), where you provide the mip level as the last argument to the funcion, and output the texture to the screen, so you will see if there are any mips. If there is only one mip level set for the texture, it will always return mip0. If there are multiple mip levels, but you didn't generate mip levels, then mips greater than zero will return black. If everything is correct, mips greater than zero will return a lower resoution texture.

Also, if you enable the debug layer and call GenerateMips(), and there are no error messages, it's safe bet that mip levels are generated fine.

Second question: I only used CreatWICTexture function a long time ago, but I remember that you could provide the device context as one of the arguments, and then it would generate mip levels. (but the interface might have changed by then)

Good luck!
> 1 votes

---
Tags: textures, directx, debugging, mipmaps
---


title: Tile based smooth snake movement

text:
# Question
Title: Tile based smooth snake movement
while making my own Snake implementation I decided to use delta time for smoothing movement on screen. The problem is that before Snake was moving fixed amount of pixels every frame, but now when mulitplying snakeSpeed by timeStep it's no longer aligned to the grid. How can I fix it?

Main game function:

```
void Run()
{
    while (!gameOver)
    {
        Time = (float)al_get_time() * 1000.0;
        timeStep = Time - lastFrameTime;

        Input();

        if (draw && al_is_event_queue_empty(eventQueue))
        {
            al_clear_to_color(al_map_rgb(255, 255, 255));

            UpdateSnake(&snake, timeStep, direction);
            Draw();
            Logic();

            al_flip_display();
            draw = false;
        }
    }
}

```

UpdateSnake() function (for now it's only one element moving):

```
void UpdateSnake(Snake *snake, float timeStep, Position direction)
{
    snake->animationTime += timeStep;

    float f = snake->animationTime * snakeSpeed;

    if (f >= 1.0f)
    {
        snake->animationTime = 0.0f;
        f = 1.0f;
    }

    snake->animationOrigin.x = ((int)snake->position.x / BOARD_CELL) * BOARD_CELL;
    snake->animationOrigin.y = ((int)snake->position.y / BOARD_CELL) * BOARD_CELL;

    if (direction.x == 1)
    {
        snake->animationDestination.x = snake->animationOrigin.x + BOARD_CELL;
        snake->animationDestination.y = snake->animationOrigin.y;
    }

    if (direction.x == -1)
    {
        snake->animationDestination.x = snake->animationOrigin.x - BOARD_CELL;
        snake->animationDestination.y = snake->animationOrigin.y;
    }

    if (direction.y == 1)
    {
        snake->animationDestination.x = snake->animationOrigin.x;
        snake->animationDestination.y = snake->animationOrigin.y + BOARD_CELL;
    }

    if (direction.y == -1)
    {
        snake->animationDestination.x = snake->animationOrigin.x;
        snake->animationDestination.y = snake->animationOrigin.y - BOARD_CELL;
    }

    snake->position.x = Lerp(snake->animationOrigin.x, snake->animationDestination.x, f);
    snake->position.y = Lerp(snake->animationOrigin.y, snake->animationDestination.y, f);

}

```

# Answer
Variable timestep is imprecise due to the floating point arithmetics, so by constant accumulation you add up the errors as well.

To avoid this, you can define start and the end points and with the use of linear interpolation you will achieve smooth transition between them.

Here's the code solution. It requires you to extend your `snake` class with few elements:

`float anim_time;` \- how much time passed since the animation start

`Position anim_origin;` \- position of the previous cell

`Position anim_dest;` \- position of the destination cell

```
float lerp(float a, float b, float f)
{
    return a + f * (b - a);
}

void UpdateSnake(Snake *snake, float timeStep)
{
    snake->anim_time += timeStep;

    float f = min(anim_time*snakeSpeed, 1.0f);//min clamps interpolation factor to (-inf; 1]
    snake->position.x = lerp(snake->anim_origin.x, snake->anim_dest.x, f);
    snake->position.y = lerp(snake->anim_origin.y, snake->anim_dest.y, f);
}

```

Note that you will have to reset `anim_time` to zero and calculate start and destination points every time you move to the next cell.

Also, instead of `snake->anim_time += timeStep;` you can store animation start time and use `snake->anim_time = current_time - anim_time_start;`
> 2 votes

---
Tags: movement, grid, timestep, allegro, snake
---


# Question
Title: How to process particle effect between UI?
I'm developing a game with Unity3D. I found that particle effects would penetrate upper hierarchy UI. Can I show the effect when the UI's sibling index bigger then effect's and hide the effect when the UI's sibling index smaller then effect's?

Here is an illustration:

# Answer
To achieve this sort of effect:

1. You need to change your caves "Render Mode" to "Screen space - Camera".

You might have did it already as you are using particles but still to ensure you change the canvas "render mode".

2. Now Change "Order in layer" to 0 for particles system.

3. Add a component "Canvas" to the UI which you want to show up on the particles. In your case add "Canavs" to "drop\_down\_list\_root".
4. Now check the "Overriding sorting" and change "Order in layer" to some thing higher then particle's "Order layer" like:

And that's it. I hope this will resolve the issue you have.
> 3 votes

---
Tags: unity, effect
---


title: Websocket : Is wss faster than ws?

text:
# Question
Title: Websocket : Is wss faster than ws?
I am developing a small game where latency matters and I have been reading this article https://samrueby.com/2015/01/26/why-is-https-faster-than-http/ and it claims that Https is faster than Http. I know that in HTTP connection is opened to transfer a single file/text/image and closes whereas in websocket connection stays open once handshake is done. I wanna know if data transfer speed can have some boost with secure connection in case of websocket.

Thank you.

# Answer
Websockets isn't HTTP, even though the handshake is compatible. It doesn't rely on SPDY (by default, I get into this later), nor can it use HTTP2, so anything mentioned by the article doesn't apply here.

However, there's a flag for chrome, which enables websockets over SPDY (`--enable-websocket-over-spdy`), but since Chrome is going to remove SPDY support in a future release and most browsers don't have this, I wouldn't count on it.

Use WSS, when you need security, not for speed
> 1 votes

---
Tags: websocket
---


title: how to use preferences in libgdx

text:
# Question
Title: how to use preferences in libgdx
I am trying to save a username for game in preferences (first time user enters the game, registration screen shows up, and after that whenever user enters the game, username is automatically synchronized).

i tried the following `// in create() method of game class
 userPreferences = Gdx.app.getPreferences("userPrefs");`

then, in my registration stage

`enter.addListener(new ClickListener() {
 @Override
 public void clicked(InputEvent event, float x, float y) {
 super.clicked(event, x, y);
 user.username = usernameField.getText();
 PanBallGame.getGameInstance().userPreferences.putString("username", user.username);
 user.requestPath = "/addUser";
 new RequestObserver(user);
 }
 });`

but this doesn't save the username in preferences. Can anyone explain how to get this work ? Thank you .

# Answer
You are missing flush command after put command.

```
public class GameManager {
  private static final String RESULT_BEST = "BEST_RESULT";
  public String userID;
  private Preferences PREFS;
  public static final GameManager INSTANCE = new GameManager();
  int result;
  //...
  private GameManager() {
    PREFS = Gdx.app.getPreferences(GameManager.class.getSimpleName());
    userID = "XXXX";
  }

  public void setBestResult(int result) {
    PREFS.putInteger(RESULT_BEST, result);
    PREFS.flush();  //THIS IS MISSING
  }

 public int getBestResult() {
    return PREFS.getInteger(RESULT_BEST, 0);
 }

```

}
> 0 votes

---
Tags: libgdx
---


# Question
Title: I want to test the Animator component of a gameobject using nunit, but I am having issues
I made a Blender 3D model with animations. Then I used the Animator Controller, and attached it to the model. The Animator Controller has a few Boolean parameter variables like `isWaving`, `isDoing`, and `isIdle` and more variables like that. If, say, a non-idle action is true, then the animation of my model transitions to the next one. I am into test-driven development, but I have never done it with Unity.

---

I tried writing the following code to test my project:

```
[SetUp]
public void SetUp()
{
    Crystal = GameObject.FindGameObjectWithTag("CrystalModel");
    CrystalScript = Crystal.GetComponent<CrystalChanPlayer>();
    CrystalAnimator = Crystal.GetComponent<Animator>(); // unity game animator
}

[Test]
public void ifSetAnimationIstodoThenToDoAnimationIsPlayed()
{
    CrystalScript.setAnimationStrategy("todo"); // set strategy
    CrystalScript.playAnimation(); // sets todo boolean to true and idle to false

    // first debug output
    Debug.LogError("todo is " + CrystalAnimator.GetBool("isDoing") +
        " idle is " + CrystalAnimator.GetBool("isIdle"));

    //second output
    Debug.LogError("current state is " +
        CrystalAnimator.GetCurrentAnimatorStateInfo(0).IsName("idle"));

    Assert.True(CrystalAnimator.GetCurrentAnimatorStateInfo(0).IsName("todoAnimation"));
}

```

I received the following output:

> "todo is true and idle is false"
> "true"

---

I think this is because Unity isn't really running, and my Animator doesn't get to update based on the variable changes. The first output assures me that `todo` is set to `true` and `idle` is `false`, hence the Animator should transition that animation to the `todoAnimation`. Yet, I can't seem to show that, in my tests.

Is there any way to test the Animator class? Are there any design patterns I can use?

# Answer
I'm testing my animators by always using `animator.Update(0.1f)` to make them pass from states to states.

You should try this after your following triggers.

```
CrystalScript.setAnimationStrategy("todo"); // set strategy
CrystalScript.playAnimation(); // sets todo boolean to true and idle to false
CrystalScript.Update(0.1f);

```

Some times I also manually call Awake()/Start() on my scripts, as you said, unity is not running at this time so you have to mock the sequencing manually.

Let me know it does any good.
> 1 votes

---
Tags: unity, c#, visual-studio, unit-testing, test-driven-development
---


# Question
Title: How can I rotate pixel art sprites without the aesthetics getting ruined?
I'm right now in front of a huge "Game Design" question. I'm making a pixel-art-ish game and using bilinear interpolation could solve lots of animation-issues. On the other hand, its not a "pixel-game" anymore.

If I use Bilinear Interpolation the animation works but it looks "hybrid-ish" and the artstyle gets lost. Either I mess up my animations or I mess up the artstyle. I cant have both it seems.

Is there any other way to solve this?

# Answer
Automatic rotation of pixel art by other angles than 90° usually goes wrong. If you want to maintain the pixel-art aesthetics you usually won't get around redrawing your art in each angle.

If you use a faux-retro look where your sprites are actually in a far higher resolution than they look, you can sometimes get away with upscaling them by an integer factor without interpolation in your graphic editor and then rotating them in *linear* interpolation at runtime. To avoid your sprites from getting blurred while in original orientation, always ensure that the drawing position is rounded to the nearest integer (some graphic engines/frameworks/libraries allow you to draw sprites on floating-point coordinates which often results in blurring). But that's usually still just a lazy substitute which doesn't reach the quality you can reach with manual work.

Here is an example of a sprite in the original size, upscaled by factor 3 without interpolation and then rotated by 30° with linear interpolation:
> 17 votes

# Answer
Have a look at RotSprite.

> RotSprite is a scaling and rotation algorithm for sprites developed by Xenowhirl. It produces far fewer artifacts than nearest-neighbor rotation algorithms, and like EPX, it does not introduce new colors into the image (unlike most interpolation systems).

> The algorithm first scales the image to 8 times its original size with a modified Scale2× algorithm which treats similar (rather than identical) pixels as matches. It then calculates what rotation offset to use by favoring sampled points which are not boundary pixels. Next, the rotated image is created with a nearest-neighbor scaling and rotation algorithm that simultaneously shrinks the big image back to its original size and rotates the image. Finally, overlooked single-pixel details are restored if the corresponding pixel in the source image is different and the destination pixel has three identical neighbors.

You can either implement this algorithm yourself as part of your game's drawing code, or use it to create rotated assets beforehand. The pixel art tool Aseprite has integrated RotSprite as part of its sprite editor.

Also, have a look at this Unity forums thread on how to use RotSprite in Unity, as well as more general information about RotSprite.
> 20 votes

# Answer
top left of page is a option: auto-select: group & layer. choose layer option then rotate. thats the way no one tells you.
> -4 votes

---
Tags: 2d, rotation, pixel-art
---


# Question
Title: Animating object, setting isKinematic=false, and then letting physics take over
I'm trying to create a "tree felling" effect, where the tree trunk falls over after being cut down by the player. I've used one prefab which contains my tree stump and tree trunk as children.

In its default state, my tree trunk as a rigidbody with `isKinematic=true`. When the player cuts down the tree, I begin an animation on the trunk which "tips it over". On the last frame, it sets `isKinematic=false` \- at this point it should "fall over" because physicals/gravity is in control and the center of mass is definitely over its base.

However, the animation seems to be preventing it, like it's still "controlling" the transform.

* Adding a transition from the "fell" state to an "exit" state just resets the position/rotation.
* Setting the animator to "animate physics" kind of works, but the tree just flies away, probably colliding with the stump or something.
* Disabling the animator after the animation kind of works, but this also causes the tree to go flying with some crazy physics.
* When left alone, `OnCollisionEnter` is called on the tree for colliding with my ground, yet the gameobject *appears* to still be stuck at 45 degrees and never touched the ground. It seems like the rigibody/collider is *not* where the mesh/transform is?

Animating the object and then turning off isKinematic should work, it's been recommended to me on reddit and is the accepted answer on this question, so I'm not sure what could be wrong.

Edit: I can ease the physics problems by telling the trunk to ignore it's own stump (`Physics.IgnoreCollision(Trunk.transform, Stump.transform);`), but the base of the tree still "jumps" away from the stump, rather than "continue tipping over". I'm not sure what else could be at play.

# Answer
A sudden jump in the physics behaviour can often occur if the tree's collider is intersecting with anything else the moment you switch off isKinematic (forcing the physics engine to apply a large impulse to move it out of this overlap), or if the tree has some accumulated velocity or angular velocity stored up that wasn't able to manifest previously because it was kinematic.

Can you double-check for penetration in the area the frame before you switch over, and forcefully zero-out the velocity and angular velocity?

Adding more mass or damping can also help smooth out small bumps.
> 0 votes

# Answer
what i understand from you question is, you sometimes need to control you objects by physics and sometimes by animation and translation. an object only can be controlled by one of them.

an standard way that works for characters is to make a **parent** object with **colliders** and **rigidbody** and a a child with **model** and **animator**. so everytime you want to make your scripted scenes, you just turn of the behaviour and make parent Object rigidbody to kinematic and after that you can bring it back to simple behaviour.
> 0 votes

---
Tags: unity
---


# Question
Title: How can I open source my Unity project when I use third party assets?
I know you are not allowed to open source a Unity project that contains asset store items that are either paid or under the default license. I am just wondering if there's any way to make my git repository public without getting into trouble.

Would it be possible to compile all third party assets into binary and keep the rest of the project text only? Would this solve the redistribution problem of third party assets while still keeping my own code and assets open source?

I know about just adding a list of required assets, but I'm looking for a better approach: a way to just download the repository, import it and it just works. If this is at all possible please share your solutions.

# Answer
> 2 votes
Yes, you can open source your own code and your own assets independently of any third party assets that your project may need or may not need. However, the whole project cannot be made open source that way, only part of it. You cannot include the third party assets that are under a restrictive license.

In order to do that, I would recommend you to just leave them out of the Git repository. Either modify the .gitignore file to exclude the third party assets from the Git but keeping them locally, or put them in a Git submodule, which you do not publish (that would give you the advantage of being able to version them), or do just not add them to the Git repository.

It should be explained somewhere in your project that certain assets are required for the project to run, but are not included in the repository. It's as simple as that.

For binary distributions, it would depend on how you package a Unity app. However, without the third party assets your project will not work right out of the box, unless these assets are made optional. Maybe that could be accomplished easily? Try to make the usage of these assets optional, maybe with some kind of fallback assets if they are not existing. But even without replacements, as long as the building process doesn't fail and the app doesn't crash without the optional assets, this would be a very comfortable solution for others to share and remix your project.

# Answer
> 1 votes
I also came to that question and came to a solution to ask for publishing permission from asset owners before I publish the whole project.

I asked one asset owner to publish *part* of their paid package (a set of icons, but I used only few of them). They allowed me to do so.

# Answer
> 1 votes
That way you are still distributing the bought assets outside an actual game and quite explictly allowing people to reuse them which will be against most of the asset's licenses.

What you can instead do is find assets under a license where you can redistribute them outside a game, you can inquire with the author/owner of the assets for special permission, or create your own placeholder assets that work and license them out permissively.

# Answer
> 1 votes
if your package depends on commercial asset or packages or... it cant be a open source project. you can exclude your dependencies and after that, publish you project and give info that this project depends on these packages or dependencies but as people have to pay for those packages, so your project can not considered free or open source.

---
Tags: unity, legal, open-source
---


# Question
Title: Public domain piece found on You Tube but recorded by someone else
I want to use a public domain piece found on YouTube but it was recorded in midi form by someone else. I only want sections of it, not the whole thing. Do I need permission?

# Answer
> 3 votes
Yes, you need permission. Only the pattern of notes themselves is in the public domain.

Any arrangement, performance, or recording of the piece is its own creative work - and this recording sounds like it was made somewhat recently, so it would not yet have entered public domain itself. To use it in your game or other work, you would need a licence from the party who owns the rights to that particular recording.

If you recorded your own performance of the piece however, you would not need an additional licence if the source material is in the public domain. (If using electronic samples in your performance, be sure you have the licence to use those in this manner, of course)

---
Tags: audio, copyright
---


# Question
Title: Can Event Triggers be used on Non-UI objects?
Is there any way to use UI-Based event triggers on Non-UI objects?

Example : on any UI object, you add an `EventTrigger` component, set the event, and then set the actions for the event. Its easy, and clean, to make UI do various actions on things like mouse enter / exit, drag, etc.

For non UI objects (a cube, for example) these kind of things are mostly done through scripts with raycast code. Its not impossible, but I find it messier, harder to organize, and less flexible then the `EventTrigger` approach.

I'm working on a turn based strategy type game. Much of the game mechanics is based around mouse movement and clicking. I tried just adding an on-click event to a cube, but it didn't do anything.

Is this scenario just plain not supported?

# Answer
> 3 votes
You can do this if you add a Physics Raycaster component to your camera. Just make sure you have colliders on the same GameObjects that have the EventTriggers you want to be clickable.

You also have the option to do this with 2D physics using a Physics 2D Raycaster.

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


# Question
Title: Full screen shader causes performance hit
I basically want to have a shader run that can do something like toon shading, or grayscale the whole screen, or radial lighting.

To do this, I create a new bitmap each time the display resizes that is the size of the screen. I then use this as my drawing buffer.

I realized this creates quite a performance hit. Especially on my laptop. Is there a way to do something like this without such a performance hit?

The framework I'm using is Allegro5. This is my current implementation:

```
void GraphicsContext::flipDisplay()
{
    if(!m_backBuffer)
    {
        al_flip_display();
    }
    else
    {

        setTargetToBackbuffer();
        if(m_shader)
        {
            m_shader->use();
            m_shader->setSampler(m_backBuffer,"tex");
        }
        drawSprite(m_backBuffer,0,0,0);
        if(m_shader)
        {
            m_shader->stop();
        }

        al_flip_display();
        clear();
        setTargetToBuffer();

    }

}

```

This way all drawing gets drawn to my bitmap, then that bitmap is blitted to the backbuffer.

I tried using single buffering display but it did not help.

Any advice for fullscreen effects? I have a game I play on my laptop that uses fullscreen film grain and it does not lag. I wonder what they do.

I know that the default shader I set gets ran through every bitmap, but I do not think I can do lighting effects this way since I cannot know which pixel on the screen I'm on.

# Answer
> 1 votes
The solution to single buffer is fine, but it should not be reallocated every time the display size changes. Make a buffer the max texture size or sufficiently large enough to cover all possible screen sizes. Then make a sub bitmap of the large buffer texture that you use for drawing. This can then be drawn to screen using your shader.

FYI, allegro 5 can set / tell you what type of display mechanism is in use, whether it is double buffer, page flipping, or triple buffer behind the scenes.

---
Tags: c++, shaders, glsl, hlsl, allegro
---


title: How to get LineRenderer coordinates?

text:
# Question
Title: How to get LineRenderer coordinates?
I am trying to get the coordinates or positions that are generated at the time I draw with linerenderer, but it gives me an error.

This may be a rookie mistake and I am not using the Linerenderer's methods well. I would be very grateful for your help.

---

LineRenderer.GetPosition index out of bounds! UnityEngine.LineRenderer:GetPosition(Int32) sendData\_Figura:Trazo(Int32) (at Assets/sendData\_Figura.cs:115) sendData\_Figura:Update() (at Assets/sendData\_Figura.cs:93)

---

```
public LineRenderer  line;
public static int contadorTrazo = 0;

void Update(){
    Trazo();
}

void Trazo() {
    line = line.GetComponent<LineRenderer>();
    Debug.Log("Trazo : "+line.GetPosition(contadorTrazo));
    contadorTrazo++;
}

```

# Answer
First, this line does nothing of use:

```
line = line.GetComponent<LineRenderer>();

```

`line` already points to your `LineRenderer`. You don't need to say "assign line to continue being itself" ;)

Second: your problem is just that you're continuing past the end of the line.

> LineRenderer.GetPosition index out of bounds!

This means yo tried to access, say, point number 5 in a line that contains only 4 points. There's no sensible answer Unity can give you here, so it throws an error to tell you to correct your question.

You need to either stop incrementing `contadorTrazo` when you reach the last point in the line, or wrap back around to the beginning / bounce back / whatever behaviour is appropriate for your application:

```
void Trazo() {

    if(contadorTrazo < line.positionCount) {
        Debug.Log("Trazo : "+line.GetPosition(contadorTrazo));
        contadorTrazo++;
    } else {
        // What do you want to do at the end of the line?
        // Maybe restart at zero?
        contatorTrazo = 0;
    }
}

```
> 0 votes

---
Tags: unity, c#, line-renderer
---


# Question
Title: Rotating UI element using touch for mobile - Unity 2D
I want to create the above object that will rotate on z-axis following the direction of a finger. Like a dial. I have written the following code and attached it to that element:

```
private float rotationRate = 3.0f;

    void Update()
    {
        // get the user touch input
        foreach (Touch touch in Input.touches)
        {
            Debug.Log("Touching at: " + touch.position);

            if (touch.phase == TouchPhase.Began)
            {
                Debug.Log("Touch phase began at: " + touch.position);
            }
            else if (touch.phase == TouchPhase.Moved)
            {
                Debug.Log("Touch phase Moved");
                transform.Rotate(touch.deltaPosition.y * rotationRate,
                                 -touch.deltaPosition.x * rotationRate, 0, Space.World);
            }
            else if (touch.phase == TouchPhase.Ended)
            {
                Debug.Log("Touch phase Ended");
            }
        }
    }

```

But the element does not move at all. Any ideas?

EDIT:

Here is a gif for better understanding:

# Answer
I used this Script and it did rotate the sprite but not like the GIF you have posted so i mad a little bit of changes and it worked fine also the value of "rotationRate" was way to high so reduced it to "0.4f" but is totally up to you what do you like, Any way here is you updated script:

```
[SerializeField, Range(0, 3)] private float rotationRate = 0.4f;

    void Update()
    {
        foreach (Touch touch in Input.touches)
        {
            Debug.Log("Touching at: " + touch.position);

            if (touch.phase == TouchPhase.Began)
            {
                Debug.Log("Touch phase began at: " + touch.position);
            }
            else if (touch.phase == TouchPhase.Moved)
            {
                Debug.Log("Touch phase Moved");
                transform.Rotate(0, 0, -touch.deltaPosition.x * rotationRate, Space.World);
            }
            else if (touch.phase == TouchPhase.Ended)
            {
                Debug.Log("Touch phase Ended");
            }
        }
    }

```
> 1 votes

---
Tags: unity, c#, 2d
---


# Question
Title: How do make a box collider align with a line renderer continuously?
I am having the issue of aligning my `BoxCollider2D` with my `linerenderer`.

I am trying to have a laser shoot using:
`Physics2D.Linecast(startingPoint.transform.position, maxEndPoint.transform.position);`

This works fine and the line is always shooting in the right direction and angle when I rotate the object. But, when I am drawing a box collider, the box doesn't align at the correct position.

Firstly, the boxcollider is attached as a child component of the line renderer.

I am using this code to get the size of the collider, which seems to work fine.

```
float lineLength = Vector3.Distance(lazer.GetPosition(1), lazer.GetPosition(0));

```

This code is for aligning the collider with the line renderer. I know I am supposed to get the midpoint, because that's how you control the location of the box collider, but I need to know the math to always make it align.

```
    lazerCollider.offset = new Vector3(0, ourHitPos.y - startingPoint.transform.position.y, 0) / 2;
    lazerCollider.size = new Vector3(lazerWidth, lineLength, 0);

```

I know right now I am only using the Y coordinate... I just need to know the math to make this work.

# Answer
To me its looks like every thing is working fine. But the child which is holding the box "BoxCollider2D" is off the center So you need to take one more step to find the the mid point of the laser and then assign it to the child which holds "BoxCollider2D".

Formula for finding mid point is:

---

* (vector1 + vector2)/2

vector 1, is start point of the laser.

vector 2, is end point of the laser.

or vice versa

---

So when you expend the formula it will become like:

* (((X1,+X2)/2) , ((Y1,+Y2)/2) , ((Z1,+Z2)/2))
> 0 votes

---
Tags: unity, box2d, geometry, line-renderer
---


# Question
Title: Multiplayer VR art gallery using different headsets
I'm creating a VR art gallery using Unity3D (like a VR Museum Views with more freedom) and would like to have an environment where 1 or more users can gather together, communicate and move around (similar concept to SecondLife except in this case would be first-person view (by default) with only one room/location and users would be in VR).

From a user perspctive, the initial screen would be a door and the user would have a mini-map and a menu, turned to him/herself, with specific actions.

Once inside of the gallery, the users would be able to see others, "walk" or "teleport" to different locations

and see the canvas

The overall environment is rather simple so I've decided to get feedback from potencial users. Turns out the majority doesn't want to be alone in such environment. So, I've considered adding multiplayer (one of the users could even be guiding the others, which is interesting).

Now, multiplayer makes more sense when we can more inclusive. That's where the problem starts. In this specific case, inclusive is being defined as the possibility of users to be able to be present in the environment using *at least one* of the following devices

* Android Phone (Cardboard)
* Oculus GO
* Samsung Gear VR
* Google Daydream
* Oculus Rift
* HTC Vive

I've done some research and couldn't find someone doing it or a way to do it (considering all of the requirements). If that's possible to do, how can i do it?

One thing I found was that if I didn't want the users to move around and just be watching the gallery like watching a webinar / presentation in different devices, I could use VR Sync (they basically synchronize video playback on multiple VR devices).

So, at the moment I can either have the environment with just one user at a time and develop the environment for all the different headsets or use VR Sync.

# Answer
your question is Too General. so i have to give a General answer too. VR is just an input/output system that takes Head Position with Gyroscope and ... and returns resulting view with head mounted screens.

unity basically work for all supported headsets. you just have to change your goal platform to VR to change camera to VR camera. that is all.

what you are looking for is a realTime multiplayer System that players can send they own position and rotation and receive others. realTime Multiplayer or online is based on UDP for real-time and faster connection. unity has many solution for this like photon as easy approach or latest one that has much more freedom and responsiblity to work with. i give you link below:

https://github.com/Unity-Technologies/multiplayer/blob/master/com.unity.transport/Documentation~/TableOfContents.md
> 1 votes

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


# Question
Title: Adding force to a 3d object in a 2d scene
I have a 3d game object placed in a 2d scene (top-down view) in Unity. I want to add force to the object to move it in the direction it's facing. I attached a RigidBody2D component to it and when I use the AddForce() method, it's not working as I want it to i.e. it's moving on only one plane x or y but not in the facing direction. Please help me. Edit :- The game is my version of Asteroids. The ship is 3d and the asteroids are 2d. The scene is in 2d. I fixed the 'y' and 'z' rotation of the ship. Now how do I add force to the ship in the direction its facing ? The Update method -

void Update() {

```
    float rotationInput = Input.GetAxis ("Rotate");
    if (rotationInput != 0) {
        float rotationAmount = RotateDegreesPerSecond * Time.deltaTime;
        if (rotationInput < 0) {
            rotationAmount *= -1;
        }
        ship.transform.Rotate (Vector3.down, rotationAmount);
    }
    Vector3 currentRotation = ship.transform.eulerAngles;
    currentRotation.x *= Mathf.Deg2Rad;
    thrustDirection = new Vector3 (Mathf.Sin(currentRotation.x) * -1, Mathf.Cos(currentRotation.x), Mathf.Cos(currentRotation.x));

```

}

The FixedUpdate method -

void FixedUpdate() {

```
    if (Input.GetAxis ("Thrust") > 0) {
        print (thrustDirection);
        ship.AddRelativeForce (ThrustForce * thrustDirection, ForceMode.Force);
    }

}

```

Thanks in advance.

# Answer
> 1 votes
You should probably have look at the space shooter tutorial : https://unity3d.com/fr/learn/tutorials/s/space-shooter-tutorial

If i'm remembering it correctly they are using Unity RigidBody (not the 2d one) and they are freezing the y axis. You should probably look at "Moving the player" section

# Answer
> 1 votes
mostly its type of your camera that makes your game 2d or 3d. RigidBody2d as in the name, only can move the object in (X,y) space and z is locked.

you cant use RigidBody2d and RigidBody in same simulation as they can not interact with each other and work differently as Rigidbody2d is made with **Box2d** engine and rigidBody is wrapper of **Physx** engine.

# Answer
> -1 votes
It is a 3D gameObject. 2D Rigidbody component can be added on it but will not work on it. Use a 3D Rigidbody component and add force only in the X-Z plane.

---
Tags: unity, c#, 3d
---


# Question
Title: How can I make my score Increase Every Level?
I m implementing a simple score system. everything works fine but when I leave the game and then the last score fetch using debugging but score text not updated??

ex:

Level1:100

Level2:200

Level3:300

Level4:400

every level to increase my score 100??

```
//firstscenes.cs //this is my first scene script and when I press the Play button then my game start
void Awake()
{
   PlayerPrefs.GetInt("score", playerscore.Score);
   print(PlayerPrefs.GetInt("score", playerscore.Score));

   player.Instance.scoretext.text = PlayerPrefs.GetInt("score").ToString();
   print(player.Instance.scoretext.text);
}

```

```
playerscore.cs

public static class playerscore
{
    public static int Score = 0;
}

```

player.cs

```
private void Awake()
{
            //get the last score
            PlayerPrefs.GetInt("score", playerscore.Score);
            print(PlayerPrefs.GetInt("score", playerscore.Score));
            //get the last score text
            scoretext.text = PlayerPrefs.GetInt("score").ToString();
            print(scoretext.text);

            //set the score when score going to one scene to another scene
            PlayerPrefs.SetInt("score", playerscore.Score);
            scoretext.text = ("" + playerscore.Score);
            PlayerPrefs.SetInt("score", playerscore.Score);
   }

void OnCollisionEnter2D(Collision2D col)
{
   if (col.gameObject.tag == "roadfinishline") //ex:Level1 player collide with roadfinishline then score=100, Level2 player collide with roadfinishline then score=200,Level3 player collide with roadfinishline then score=300
   {
                playerscore.Score += 100;
                PlayerPrefs.SetInt("score", playerscore.Score);    //scoreadd=100
                scoretext.text = ("" + playerscore.Score);
                Debug.Log("scoreadd:" + playerscore.Score);
   }
}

```

last score and last score text fetch successfully but score text not updated. see my debugging

ref:

# Answer
> 0 votes
in unity all behaviours and function classes derive from **monoBehaviour** but data can be an static class.

```
public static PlayerData
{
public static int Score=0;
}

```

then in you monobehaviour:

```
     void Awake()
        {
        PlayerData.Score+=100;
        PlayerPrefs.SetInt("score", PlayerData.Score);
        scoretext.text = ("" + PlayerData.Score);
        PlayerPrefs.SetInt("score", PlayerData.Score);
        }

```

so you can work with shared data in all scenes.

---
Tags: unity
---


# Question
Title: How does one first draft a linear visual novel plot?
I’m making a linear visual novel with partial interactivity that allows the player to influence small portions of the story, but I just want to know how one goes about drafting something like that. The interactivity feature allows you to build a relationship with some characters, this is what can change different parts of the story. Thing is that I have several other characters whose growth I would like to cover, but don’t know how.

# Answer
> 3 votes
When I read your question I see two different goals. 1 you want to make a rich and deep story, and 2 you want to include some slight interactivity elements to help build some of the characters relationships with the player. As such I think you should approach the two goals separately.

1. Here I would first write a full story with your characters. As the player is playing a limited role in how the story plays out just writing the plot and the interactions can help you define how each of the characters act and interact. In addition to this it can help to make a “Lore Bible” or a document where you record all sorts of information about the different characters. Their birthdays, what they like to eat and drink, who was their prom date, and various other life events. This can help keep your characters consistent and real.
2. You want to add some limited interactivity with the player. There are lots of ways to do this whether it just be keeping a bunch of boolean values that the player ticks off as the go through the story or by keeping various “relationship scores” on how much the player has interacted. To get this done you can create your own system in Java or C, or you could use a system in existence. Personally I’m a fan of Twine.

I should also note that this seems to be a good question for the writing stack exchange.

---
Tags: visual-novel
---


# Question
Title: Updating transform position after root motion
I have an animation of a character climbing with root motion in it (i.e. the character moves generally upwards for a couple of units during the animation). It is intended as a one shot, not a loop. The skeleton is fairly standard hips \> spine 1, hips \> right leg, hips \> left leg etc. The root is the hips and the pivot is between the soles of the feet.

I know its generally best to make in-place animations without root motion but scripting the upward movement using Vector3.Lerp etc looks unrealistic (in reality when rock climbing for example the upward motion will come in perdiodic bursts as the knees are first bent, then extended, rather than a constant movement upwards), so I want to keep the root motion in the animation.

Problem is when the animation has finished Unity still considers the transform pivot to be in its original location, before the skeleton climbed up two units. Is there any way to instruct Unity that the new transform position is where the characters feet have ended up after the animation has finished?

I figure I could parent the hips to an empty which moves the charaters around normally, detatch the empty before the root motion climb, move it by the same amount the hips moved then re-attach but is there a less hacky way? Some kind of `transform.returnToOriginalOffset` method perhaps?

# Answer
**UPDATE**

You are right my original explanation is a bit too light in details. In details, in the root motion the Body Transform and Orientation are stored in the Animation Clip, so when the animation ends you can write a piece of code that gets the new info and translate the transform position to your desired location, just make sure you take in consideration the offset, might move it to the center of the character, if that happens easy fix, you can calculate that as well and move it.

some more info can be found in this link

https://docs.unity3d.com/Manual/ScriptingRootMotion.html
> 1 votes

---
Tags: unity, animation, scripting
---


# Question
Title: How can I spread my texture evenly across a cylinder in Unreal Engine 4?
How can I spread my texture evenly across a cylinder in Unreal Engine 4?

Specifically, in the image below, I would like have texture on cylinder (on the left) match the one on the box (on the right). I need a many sides because I want the cylinder to be very smooth.

# Answer
> 1 votes
generally the texture needs to match the UV you created for it, but if you have a generic object (which looks like is your case) the best bet is to use triplanar material projection, in short is a 3d mapping of a texture, rather than a 2d mapping.

here few links

https://external-preview.redd.it/Llj2OT\_QDUjam24PDd0pBauqBDUym4acCiqwRcnPsJI.gif?format=mp4&s=e282639bae4fb0ca5808c819436863bcef83ac99

https://forums.unrealengine.com/community/community-content-tools-and-tutorials/7147-tutorial-triplanar-material

---
Tags: textures, unreal-4
---


# Question
Title: Game runs in UE4Editor but not standalone
I have just completed these instructions to build and run UE4Editor for Linux.

I created a new C++ project and in the editor I hit the Launch button and after a while it compiled and ran successfully.

If I close down UE4Editor and `cd` to `MyTestProject/Binaries/Linux/` there is a `MyTestProject` executable, but if I try to run that from the shell I get

```
error while loading shared libraries: libApexCommonPROFILE.so: cannot open shared object file: No such file or directory

```

How do I set up the program so that it can be run standalone, not from within the editor?

# Answer
your game needs to be packaged in order to launch on its own, this way all the libraries and files are copied together.

You can do this by clicking on "File" than select "Package Game", select the platform you want to build for, in your case Linux, and select the output location.

After this the game will appear in the location you specified.

P.S. don't forget to assign to your new fancy game a cool icon in Settings, Platform -\> Linux ;)
> 0 votes

---
Tags: unreal-4, unreal, linux
---


# Question
Title: How to make a texture appear the same way in a cube?
**My problem seems so simple, that before asking the question here I did a search on google and this site:**

But nothing seemed to be related to my problem.

**I imported this image.png:**

**I created a material and added the image to it:**

**But I did not get the expected result in the game (I wish this yellow line were under that pink arrow that I drew):**

**Innocently I thought the solution was obvious, so I added another image.png and added it to the material:**

**To my surprise, the result was worse, the yellow line did not even appear:**

I realized this happens because the floor of my game is a "stretched" cube, so the image I added is appearing correctly on one of its faces, not just the one I want.

**I'd like to know how to make it look the same on all faces, or some value that I can change so that it appears correctly on the face I want.**

---

**EDIT 1 (attempt using rotator)**

I put the input time to see if any value would be compatible with what I want, but none is.

**I tried with both texture images, but both presented the same behavior:**

See that spinning looks like the shaft rotates around the top left of the floor.

For some moments the yellow line will disappear.

# Answer
You might want to play around with texture coordinate (UVs) scaling and flipping.

Right now, the face pointing upwards is just showing a part of the unfolded cube texture. If you adjust the scale you should be able to show the image on every face of the cube.

TextureCoordinate Expressions shows that `UTiling` and `VTiling` can be used for scaling the texture. Use `Un Mirror U` and/or `Un Mirror V` for flipping the texture.

Maybe you will need some texture offset as well, which can be achieved with the Panner Expression. *Note, the order when combining both expressions makes a difference.*
> 2 votes

# Answer
your coordinates are incorrect, the texture might be to big or too small, to verify that make a checker pattern texture apply it as an overlay to the original texture.

In game re import the image and apply it to the mesh again, after that create a texture coordinates in the material and two number input parameter (x, y), multiply the two, than connect the result into the texture sample input parameter.

This way once compiled the material you can create an instance and modify only the x and y parameters till the tiling is good

**UPDATE**

Checker textures are any type of texture that allows you to verify your tiling/uv scales, the most standards comes in two flavors, gradient pattern with indexes or black and white.

When applied to your mesh you can use them to see how big or small the boxes are or how many cells appears. After that you can use your UV tiling property in the Material to adjust till the image is displayed properly or within the wanted range.

If now the values are matching your preferences, you can keep the UV tiling values but replace back the texture with the original one you wanted to display and if all is ok the image should display properly.

You can still fix the parameters afterwards, now you just have a baseline to start from

**P.S.**

Uneal Engine also has the Z axes usually rotated by 90 degrees when importing meshes from Maya(not sure other packages like blender), if still not the right direction, rotate the mesh by -90 in the z axes and should help
> 2 votes

---
Tags: textures, unreal-4, materials, blueprints
---


# Question
Title: Reading and writing components from multiple systems in ECS
As a learning exercise, I'm building my own ECS. I've got a situation where two separate systems want to query and possibly update a `Transform` component - input handling and collision detection.

Given that each system operates in isolation, as if it were running in its own private thread, I'm effectively doing a concurrent update, but don't really want to block. I'm also concerned that one system might update the transform and then the next system is operating on different data.

Are these valid concern, or are the periods between updates so small that this is negligible and not worth worrying about? If valid, what are some other possible options for solving?

# Answer
> 0 votes
As i understand it, you dont use seperate threads, they just work as if they were seperate threads, correct?

If you had seperate threads for systems, you would still need to watch out for locks on data. In this case, the input handling is either writing (just set the acceleration vector) or reading and writing (changing the velocity vector). In this case, another system should neither read nor write on those data, as it could read data that are in the state of change. That could lead to unintended consequences.

In a concurrent ECS, you still need to think of the order of systems to call. Rendering your character in an jump or fall animation, while clearly still on the ground would be an obviously bad idea. Collision detection before moving could result in the player stuck in a wall.
On top of that, some systems are get called more often than others. If your game is set to 60 fps for rendering, that does not mean that some other systems like player input are also working only 60 times per second.

So, what you should think of is what in what order are your systems called? If you detect the collisions first, but then override your movement with the input, that would be useless.
Second, what does your input handler write in the transform component? If it is a new velocity vector then that vector will get used in the collision detection (and in case of a collisiion changed). if Input Handler gets called more often than the collision detection, you collision detection might not work.

So in short, if you call your systems concurrently (start a system after the system before finished) there should not be a problem, if your data is organized correctly and systems get called the correct amount of times in relation to other dependent systems.

---
Tags: entity-component-system
---


title: Draco encoder lossless, is it possible?

text:
# Question
Title: Draco encoder lossless, is it possible?
I'm trying to use the draco library in a Unity project. I've a lot of obj files with models of a person in different positions. When I encode these models with the `draco_encoder` command I obtain a lossy conversion, and a lot of parts of my original models get lost.

I tried to play around the parameters `-qp` and `-cl` in order to change the quantization and the compression level, but also with `qp` at its maximum and `cl` to its minimum some parts get lost.

In this image the left model is the original one. The right model is the one converted with `draco_encoder` by using `cl` 0 and `qp` 21. As you can see some parts are missing.

Do you have any suggestion on how can I obtain a lossless (as lossless as possible) conversion?

# Answer
> 0 votes
The documentation for encoding states:

> A value of 0 for the quantization parameter will not perform any quantization on the specified attribute. Any value other than 0 will quantize the input values for the specified attribute to that number of bits.
> ...
> In general, the more you quantize your attributes the better compression rate you will get. It is up to your project to decide how much deviation it will tolerate. In general, most projects can set quantization values of about 14 without any noticeable difference in quality.

That is the key section to note because quantization:

> is a lossy compression technique achieved by compressing a range of values to a single quantum value. When the number of discrete symbols in a given stream is reduced, the stream becomes more compressible.

In your example, you're using a `qp` factor of 21; the docs say quality begins to change noticeably at around a `qp` of 14, so it's not surprising that you're seeing errors. If you want to reduce the lossiness, you need to reduce your `qp` value. Theoretically, a `qp` of 0 would give you lossless compression. You may need to increase the compression level `cl` to compensate.

That being said, most lossy compression techniques need to discard *some* data in order to achieve any compression at all. It's possible that reducing the `qp` to zero will prevent compression errors, but increase the over size of the data set once encoded.

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


# Question
Title: Replicate GetKey & GetKeyDown like a UI button
I'm trying to make a UI Button works like the key presses Unity Input methods, but I can't realize on my own how to make this. I tried using the button event and eventTrigger but it doesn't work like it suppose GetKey and Getkeydown works. Any ideas? thanks in advanced.

# Answer
> 0 votes
you need **OnClick** and **EventTrigger** events including **OnPOinterEnter** and **OnPointerExit**.

for GetKeyDown() just use OnClick(). you can set it in inspector or just add your event like link below:

https://docs.unity3d.com/530/Documentation/ScriptReference/UI.Button-onClick.html

if You look for **GetKey** you have to define a bool Variable. and make it True on **OnPOinterEnter** and make it false on **OnPointerExit**

just assign KeyDown and KeyUp methods to these events.

```
  Bool KeyIsDown;

void keyDown(){KeyIsDown=true;}
void keyUp(){KeyIsDown=false;}
    void Update()
    {
    if(KeyIsDown)
    {
    // everything like GetKey()
    }
    }

```

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


# Question
Title: Slick2D noClassDefFoundError for StateBasedGame
I'm trying to write a 2D game using slick2D, and I thought I set everything up correctly, but I'm getting this error:

```
Error: Could not find or load main class javagame.Main_Game
Caused by: java.lang.NoClassDefFoundError: org/newdawn/slick/state/StateBasedGame

```

My `Main_Game` class is the class with my main function and it extends `StateBasedGame`. I can't find this error or how to fix it when I try to search for it.

# Answer
> 2 votes
I had the same error, but I fixed it because when I imported the lwjgl.jar and slick.jar, I imported them into the "Modulepath". If its the same for you (assuming you're using eclipse), go to where you added your libraries (Properties\>java Build Path\>Libraries) and make sure you added you libraries to the "Classpath" rather than the "Modulepath".

Hope this helps.

---
Tags: slick
---


# Question
Title: Why particle effect alway rendered after UI though they have same sorting layer and same sorting order?
Why particle effect alway rendered after UI though they have same sorting layer and same sorting order?
I searched a lot of information about it,every one said that both of effect and UI are controlled by sorting order and sorting layer.If UI's sorting layer is same to effects' and sorting order is bigger then effects', then UI will render after effect and the result is that UI cover effect.
But what they will do if they have the same sorting layer and the same sorting order?I found that effect alway cover UI in this case.I think this is because effect render after UI. But why?
There are some pictures below:
Hope anyone could answer me.Thanks.

# Answer
> 0 votes
After your question I was curious about why particles system always render in front of the UI when both UI and Particles system are having same sorting layer and sorting order.

So I find out some thing interesting:

**Project Hierarchy:** same project hierarchy is used for both situations.

**Situation # 1: Canvas (Render Mode : Screen space overlay):**

**screen shot:**

**Frame debugger:**

So from frame debugger its clear that if **Canvas render mode is Screen space overlay** the all of the **scene objects are rendered before canvas.**

---

---

**Situation # 2: Canvas (Render Mode : Screen space Camera):**

**screen shot:**

**Frame debugger:**

So frame debugger making things clear that canvas is rendered prier then particles if **Canvas render mode is Screen space camera**.

---

---

**Summery:** As for both of the Canvas and Particles sorting layer was "Default" and sorting Order was "0".

But in **screen space camera** particles was rendered after canvas so we see prticels in front of the UI.

while in case of the **screen space overlay** UI was rendered after Particles , so we saw canvas in front of the Particles.

Which means Unity do change rendering order for in different situation. I hope this will clear your confusion.

---
Tags: unity, gui, effect
---


# Question
Title: Count the number of on-screen pixels occupied by an object
I need to find the number of pixels an object occupies on screen. How do I do that using DirectX?

# Answer
Apart from rendering the scene to a separate frameBuffer with a certain color, then counting those pixels after the render, you can't really do much.

You could theoretically take every face, transform their vertices to screen space and check which pixels they intersect, but then you would essentially do the same as the first method, just slower.
> 1 votes

# Answer
As Bálint noted:

> You could theoretically take every face, transform their vertices to screen space and check which pixels they intersect, but then you would essentially do the same as the first method, just slower.

This would be slow. However, if you're willing, you could settle for the approximate answer.

Just take every non-back-facing triangle in your object and transform it to screen space. Then, measure the area of each triangle (and perhaps round this number). This gives inaccurate numbers, especially if your object is concave and in an orientation where non-back-facing triangles can overlap. It's much faster than testing individual pixels though.
> 0 votes

# Answer
Raycasting can do this. Cast a ray from the eye position through the viewing frustum for each pixel. Count the rays that intersect that object. This won't give correct numbers if you're using transparent textures or materials though. Good luck.
> 0 votes

---
Tags: directx, scene
---


# Question
Title: Using logic gates for Sprite Collision Detection - humor an old fart please
Im an old coder who came back so to speak, learning Java I know what I want but I cannot find anyone asking it anywhere so here goes...

Im writing a basic tank game to code for practice but as is always the case my personal ambitions out pace my abilities.

Ive been reading up on the various methods used for collision detection using rectangles and point testing around the sprite for collisions but it all seems a little hap hazard and processor heavy to me.

I was thinking maybe a method would work by which I could logically compare two sprites -

So maybe I have a tank(me) and I come to a tile which is meant to be wall. OK so I can compare the square from an array and look up what type of tile is there and prevent movement in that direction, but again Im not happy with this because its not accurate enough. I mean what happens if I want that wall shootable, where it goes through several stages of destruction before its turned into a fully traversable square, it may have a few bits un-destroyed and I want to be able to detect even this.

So how about if I created a tank mask, black and white and grab the square the tank is entering and logically AND it with the tank sprite, creating zero unless a pixel appears in both locations, in which case it hit something.

Is this clear enough?

Do you think this would work and which coding direction do you recommend, Im still new to the syntax but as you can see I know what I want....I think!

# Answer
I would not do this the way you describe. How many pixels will you test in the event there is no collision (the probable case)? All of them! Instead define a polygonal outline for your tank and whichever objects exist on the map. Then, you can test each point of the tank polygon against each edge of the obstacle polygon and determine if there is a collision. Look up point/plane collision testing. This will be tremendously faster than your proposed method. Good luck!
> 1 votes

---
Tags: java, collision-detection, logic
---


# Question
Title: How to make Unity sprite animation not lerp?
I set sprite animation at key1 and key2.

at Key1 :

```
Position.x = 0

```

at Key2 :

```
Position.x = 1

```

I want it not lerping. i mean i want it appear at posX 0 and posX 1. not between 0~1.

what should i do?

# Answer
> 4 votes
You have to rightclick on the animation curve and set both `tangents` to `broken` and `constant`.

See the documentation here: https://docs.unity3d.com/Manual/EditingCurves.html

---
Tags: unity, animation, sprites
---


# Question
Title: Unity) How can i loop animation 'n' times?
I usually use

```
currentAnimatorStateInfo.normalizedTime > n

```

but is there any better way for this?

I want my animation loop n times and invoke call back.

# Answer
> 2 votes
blue region is your callback or event. just make an script and set it to object uses this animation. when you select that event, inspector shows field you can enter name of you function. remember script should be attached to that object. you can use an counter in you code to cound how many times this event is called.

---
Tags: unity, animation
---


title: Unity prefab object limitations

text:
# Question
Title: Unity prefab object limitations
TLDR: What are limitations on how many objects a single prefab can handle safely? keeping in mind that I could potentially have almost a 100 of these

I am busy creating a system to essentially load the game world in chunks as the player moves. This means that every single object in the world will be streamed into the game through script when needed(still designed in the editor, impossible otherwise) The problem I am having is with methods to store and load objects.

I have looked at everything I could think of or get information on. After researching all the methods I found, I started thinking that prefabs is the best solution since it can live anywhere in the project(unlike streaming assets folder, which is also not recommended for many assets, let alone every single asset). Creating Game Objects at runtime is not as easy once GO's get complex with components and settings, also I assume the performance hit from creating GO's this way is worse than using an existing prefab.

So my question is if prefabs can handle massive amounts of objects(lets say 1000) safely? testing this is hard because i would have a prefab(or a few) for each tile that gets loaded.

# Answer
Prefabs are just a useful way of storing gameobjects that are going to be repeated. As a result you can have just as many prefabs as gameobjects, in other words as many as you need.

There is, of course, a computational limitation. If each prefab is running its own complex AI and has a complicated hit box and your spawning 1000s it could cause a real problem for even beefy computers. In most cases though just having a system that spawns many prefabs as background tiles to make up the floor of a 2d world or the like would not be any problem.

With that said creating that many gameobjects is a very inefficient way of handeling processing power. I would look into meshes and mesh chunks as an alternate solution if you run into any computational issues
> 1 votes

---
Tags: unity, streaming
---


# Question
Title: Update DXGI swapchain sample count without recreating swapchain in full-screen mode
I'm implementing the ability to tweak graphics settings in my application at runtime (resolution, refresh rate, v-sync, multisampling).
It is possible to update the resolution, format and refresh rate using **IDXGISwapChain::ResizeTarget** and **IDXGISwapChain::ResizeBuffers**. However, I cannot find any way to update the swapchain's sampling(count and quality) in the same way. The only option I have is to go to windowed mode using **IDXGISwapChain::SetFullscreenState**, then release the swapchain, recreate the swapchain with a new **DXGI\_SWAP\_CHAIN\_DESC**, and then go back to fullscreen again. *(Didn't mention releasing and recreating back buffer and depth stencil since it is a must do)*.
I am willing to stay at full-screen mode before and after the settings are applied.

# Answer
> 2 votes
I had a look through my own code to look into answering this question. And someone more qualified may have a more accurate answer. To answer your question about sample and quality, unfortunately no, you cant and also tearing down the associated z buffer etc as well. You are correct in releasing swapchain and creating. BUT, there is an alternative.

What you are asking about, count and quality I will assume is about the MsAA you would like to run with. From my experience, and I was in the same position you are in, doing this to the SWAPCHAIN Buffer wasn't the way to go. I instead use the swapchain buffer only to present the final rendered frame and control refreshrate, format and resolution of actual visual frame on the monitor. That means, that I have a separate class that manages the actual render target where all my drawing is done and use ResolveSubResource to take my MsAA buffer to a single sample result (which is what your swap buffer will be). That allows for decoupling of the management of the underlying sample count from the refreshrate etc, those attributes that inherently dont change the structure of your swapchain buffer from those that do.

You still will need to dispose your backbuffer and the z buffer, plus any other structures that are associated to your render target, but you can now change your AA sampling almost instantaneously. What this also means is, that you segregate your games internal resolution away from the resolution of the monitor. This is also handy if you want to say lower the internal resolution of your game while still displaying at the native res of the monitor for example.

Hope this helps.

For completeness, I've added my game and resolution management into it. If it fires up (hope it does), go to settings-\>graphic Settings and you can see what options I have employed through the suggestions above.

insanesoftware.com.au/Strafe\_Latest\_Build.rar

---
Tags: directx11, antialiasing, settings, multisampling, dxgi
---


# Question
Title: Draw textured circle / 2D shape in SceneKit
I have the following code to create a circle Path and a SCNShape from this path. orbit\_gradient.png is a horizontal 1px high image that represents a gradient.

```
let material = SCNMaterial()
material.isDoubleSided = true
material.lightingModel = .constant
material.diffuse.contents = UIImage(named: "art.scnassets/orbit_gradient.png")

let shapePath = Path.circle(radius: radius, segments: 512)

let orbitShape = SCNShape(shapePath)
orbitShape.materials = [material]
self.orbitNode.geometry = orbitShape

```

The problem I have is that when applying the texture to this geometry I'm just left with a white circle. If I set the diffuse to be UIColor.red it displays as red. What I want to accomplish is a stroked circle that appears to gradually fade, creating a rotating trail effect.

# Answer
> 1 votes
Got there in the end by using SCNGeometrySource and SCNGeometryElement.

1. Generate vertices
2. Generate texture coordinates
3. Generate indices
4. Set material (my horizontal, 1px tall gradient)

I made a gist of a class I made incase it's useful to anyone else.

https://gist.github.com/kemalenver/79523e5606f62c5958fcf5e9bedc48a5

---
Tags: textures, materials, scenekit
---


# Question
Title: Changing a sprite and adding a new background layer
I followed a tutorial to make a Flappy Bird clone. At the end he gives you a premade game so everything works correctly, from jumping to going through pipes, etc.

I want to change the aesthetics though with sprites I made myself. I don't want to change any gameplay, just the sprites. This is easy for the bird, I just selected the asset I wanted and it changed in the scene and game. Easy.

Now, I want to add a building background layer to the back to go along with clouds, stars, and other background elements, and use the parallaxer to make them move. This doesn't work, however. It doesn't show up in the scene or the game when pressing play.

Next I want to make the pipes use a different sprite. So I changed the pipe sprite in the Unity menu to what I wanted, but when I hit play, it's still just pipes.

This is the tutorial project in question and it's free to DL and use, so I shouldn't be having this issue with changing its sprites. Can anyone please talk me through how to get these elements working?

Here is a screenshot of how I've tried making my changes:

# Answer
> 1 votes
Make sure you change the sprite on the Prefab and not on an instance of the prefab in the scene. The prefab is named `Pipe.prefab`. Then save and run the project.

If you want to see the sprite and edit the collider it is best to use the prefab editing mode.

> Entering and exiting Prefab Mode
>
> There are many ways to begin editing a Prefab in Prefab Mode, including:
>
> ```
> Double-clicking it in the Project window
> Using the arrow button next to the Prefab in the Hierarchy window
> Clicking the “Open” button in the Inspector
> window of a Prefab Asset
>
> ```

See the docs for more information.

---
Tags: unity, sprites
---


# Question
Title: GLSL: gl_ModelViewMatrixTranspose vs. gl_ModelViewMatrix
What is the difference between doing these two operations? Don't the first transform the vector from model space to view space? Then what does the second operation do?

gl\_ModelViewMatrix * vec4(vector, 0.0)

gl\_ModelViewMatrixTranspose * vec4(vector, 0.0)

# Answer
> 0 votes
Transpose of a matrix is the same as inverting the matrix, as long as the matrix is orthogonal.

So if your gl\_ModelView matrix transforms from model space to view space, then the transpose (inverse) of that matrix will transform from view space to model space.

---
Tags: glsl, matrix
---


# Question
Title: Unreal crashes on build: unable to connect to the swarm
I am having trouble with Unreal engine 4. 22

After clicking on build, it CRASHES and says "unable to connect to the swarm"

How can I fix this?

# Answer
> 1 votes
Swarm is part of the Unreal Engine which, when building lighting, connects to other computers running Swarm to use their spare processing capacity to reduce the amount of time it takes to build your level lighting.

You should have a copy of SwarmAgent.exe in you Program Files\Epic Games\UE\_4.22\Engine\Binaries\DotNET

If you don't (and there have been reports that Windows Defender has been removing it recently), you either need to disable Windows Defender, go into your Unreal Engine Launcher, use the drop down and choose "Verify" or, if you have an earlier version of Unreal Engine on your computer, you can copy the SwarmAgent.exe from that engine version to your 4.22 DotNET folder.

---
Tags: unreal-4, build-process
---


# Question
Title: How To Resolve Collision Before it Occurs
I have 2 objects, A and B, in a 2 dimensional space. If I know A is trying to move by vector M (that is to add vector M to the positional vector of A), and that A will collide with B after A moves, what math would be used to scale back the M's x and y components such that M will no longer collide, whilst still allowing M to make A slide along B should x or y be cut back? (eg. if A is on the left of B, moves with vector (1f,1f), cant move 1 right, but can move 1 up and does so).

# Answer
Try vector projection as illustrated here

Vector projection formula:

$$ (\vec{a}\cdot\hat{\vec{b}})\times\hat{\vec{b}} $$

where `b` with a hat means norm of the vector

$$ \hat{\vec{b}} = \frac{\vec{b}}{\left\\|\vec{b}\right\\|} $$

You can represent side of object B and velocity of object A as vectors and use vector projection to remove any velocity directed at object B allowing A to slide across it.
> 1 votes

# Answer
I would rather be able to comment, since you are missing a lot of information, but since I cannot I will post a possible solution.

Using circle/circle collision detection:

Before each move, add M temporarily to A's position. Then calculate the distance between A's new position and B. If that distance is less than the radius of A's bounding circle added to the radius of B's bounding circle, then you need to scale back M, by the difference plus some constant value (if you don't add this constant value, then the two objects will collide, but just barely touch).

Your bounding circles can be arbitrary also, since you are trying to avoid collisions. You can make them much larger than the objects themselves.

Hope this helps!
> 0 votes

---
Tags: java, collision-detection, collision-resolution
---


# Question
Title: How to connect Google Domain to AWS ELB url
I have recently uploaded a server with node js in my AWS environment and added a HTTPS listener in my load balancer. Also generated a certificate using ACM(AWS certificate manager) for my google domain and added it in HTTPS Listener. Added .ebextensions folder to upgrade Websocket in Proxy server. I have no Idea how can I connect my domain to my beanstalk app which url is something like "myapp.region.elasticbeanstalk.com" so that I can connect as "**wss**://MyGoogleDomain.com". Can you guys help me? I am new to this.

# Answer
Steps to host your domain on AWS EC2 :

* Create a hosted zone in route53
* Create record set with Alias name(your beanstalk URL)
* In your domain hosted zone you will get some Nameservers
* Copy those one by one and paste them google domain settings

You should be able to connect now. :)

Caution : Route53 charges some fraction of money every month even if you are on free tier
> 0 votes

---
Tags: node.js, websocket
---


# Question
Title: why child class can access object while parent can't
I have Block class which is the parent and StandardBlock the child , the prefab block have StandardBlock script attached to it, and according to my small knowledge in inheriting I though this would work

```
public class Block : MonoBehaviour
{
HUD HUDscript;
// Start is called before the first frame update
void Start()
{
    HUDscript = GameObject.FindWithTag("Canvas").GetComponent<HUD>();
}
public void OnCollisionEnter2D(Collision2D col)
{
    HUDscript.addPoints();
    Destroy(gameObject);
}
}

```

and child class

```
public class StandardBlock : Block
 {

      // some code
}

```

but this is the error that i got

NullReferenceException: Object reference not set to an instance of an object Block.OnCollisionEnter2D (UnityEngine.Collision2D col) (at Assets/Scripts/Gameplay/Block.cs:24)

while writing `OnCollisionEnter2D` in the child class worked fine

# Answer
> 1 votes
Since I used a start method too in the child class I should have written it that way

```
override protected void Start()
{
    //some code
    base.Start();
}

```

and in the parent class

```
virtual protected void Start()
{
    HUDscript = GameObject.FindWithTag("Canvas").GetComponent<HUD>();

}

```

so now the child can implement both methods

Thanks to @DMGregory

---
Tags: unity, collision-detection, inheritance
---


# Question
Title: How to use the Object parameter in UInputComponent.BindAction?
What is the purpose of the Object parameter here?

```
UInputComponent.BindAction(..., UserClass* Object, ...)

```

What information should I pass here?

# Answer
> 1 votes
The full signature is:

```
template<class UserClass>
FInputActionBinding & BindAction
(
    const FName ActionName,
    const EInputEvent KeyEvent,
    UserClass * Object,
    typename FInputActionHandlerSignature::TUObjectMethodDelegate< UserClass >::FMethodPtr Func
)

```

This shows that `UserClass` is a template parameters and that `TUObjectMethodDelegate` uses that parameter as well. `TUObjectMethodDelegate`looks to be a helper to encapsulate member functions of the template parameter type.

This means that Object is the instance object on which the passed delegate is invoked.

Which is a long winded way of saying it's unreal's typesafe alternative to a `void* userData` parameter commonly found in callback frameworks.

---
Tags: c++, unreal
---