# Question
Title: DirectX Performance Issue: Rendering to texture
Brief introduction: I'm programming a game and, till now, I've runned it on my desktop. This morning I decided to try it on my laptop (a i3-4005u with a gt920m) to see cpu/gpu usage and, with my surprise, it couldn't even reach 60 fps... then I discovered that it didn't use the nvidia gpu but the intel's integrated one. I looked a bit on Google and found the problem: https://stackoverflow.com/questions/10535950/forcing-nvidia-gpu-programmatically-in-optimus-laptops.

The usage of the GPU (the Nvidia one now) was still to high for such the game I'm making (kind of 2D platform). Trying it on my desktop (gtx 780) I discovered that it uses even 50% of its power (MSI Afterburner).

A screenshot:

To generate the light map I use a render-to-texture and here is the problem: rendering the lights uses all the power (profiled with visual studio). The only difference between rendering the lights and the background is the active RenderTargetView and the only different between the default back buffer and the light map RTV is the format so I changed it:

```
textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; //it was DXGI_FORMAT_R32G32B32A32_FLOAT

```

After that the gpu usage dropped to 3-4% (and the game looks the same). Now I'm wondering why things changed. Can you help me?

Still now rendering the lights is the most expensive things and I can't understand why (the shader is simpler than the sprites' one. I can post the code if you want, but is a basic "load data from texture and output")

The first draw call is for lights, then there is the background's one. I really can't understand what's going on.

P.S I also found that using a borderless window instead of the fullscreen mode by default adds a 10% of usage on the gpu, while fullscreen mode uses all the cpu power (100% of usage). Can you help me again understanding why?

# Answer
> 2 votes
The answer to the first part is easy, R32G32B32A32\_FLOAT is a massively expensive format to use for GPUs. It uses 128 bits per pixel compared to R8G8B8A8\_UNORM which uses only 32. So by changing it you've quartered the amount of memory bandwidth required which will have a large positive effect on older GPUs.

Why fullscreen is slower could be several things. Is it definitely running in the same resolution? Are you using the same swapchain settings? Is vsync enabled? We really need a before & after GPU profile to get a better idea.

# Answer
> 0 votes
For the second part of the question I found the problem which causes the high time for the lights' draw call: I wasn't properly clearing the ShaderResourceView slot (actually I was doing it wrong) where the light map was bound, so when I set it as RendertargetView it took time to unbound it. Now everything's ok. Need just to call

```
ID3D11ShaderResourceView* null = 0;

_graphic->context()->PSSetShaderResources(_slot, 1, &null); //with _slot 1 and not 0... :)

```

Now draw time is about 140ns, nearly like background.

---
Tags: c++, directx11, performance, gpu, rendertargets
---


# Question
Title: After creating DirectX11 Device, enumerating the DXGI Adapters seems to produce invalid results
**EDIT: This is part of an upgrade from DirectX10 to DX11.**

When I create a DirectX 11 device with D3D11CreateDevice(), it chooses a video adapter for me. I access this object like so:

```
// removed HRESULT checks for brevity- normally I print errors on failed hr

IDXGIDevice1*  pDXGIDevice = NULL;
HRESULT hr = mpDXDevice->QueryInterface( &pDXGIDevice );

IDXGIAdapter* pAdapter = NULL;
pDXGIDevice->GetAdapter( &pAdapter );

// save pAdapter

```

However, later, when I enumerate the adapters, this adapter is not on the list:

```
IDXGIDevice*  pDXGIDevice = NULL;
HRESULT hr = mpDXDevice->QueryInterface( &pDXGIDevice );

IDXGIAdapter* pAdapter;
hr = pDXGIDevice->GetParent(__uuidof(IDXGIAdapter), (void **)&pAdapter);

// so far so good: pAdapter matches my current adapter I saved from above

IDXGIFactory* pFactory;
pAdapter->GetParent(__uuidof(IDXGIFactory), (void **)&pFactory);

UINT i = 0;
while( SUCCEEDED( hr ) && hr != DXGI_ERROR_NOT_FOUND )
{
    IDXGIAdapter* padapter;
    hr = pFactory->EnumAdapters1( i, &padapter );

    // none of these padapters matches the current adapter!!
    i++;
}

```

After this section, I have a list of the enumerated adapters. My current adapter is not in the list! Instead there is a DIFFERENT adapter with the same name as my current one.

Most importantly (this is the part I actually need) if I call D3D11CreateDevice() with this enumerated (different) adapter specified, I get E\_INVALIDARG.

What am I doing wrong to generate these alternative, invalid adapters?

# Answer
Ok I got it. Sorry for the misleading question but the major problem turned out to be creating a D3D Device with a supplied adapter. The point about the enumerated adapters being "different" was wrong on my part.

Per the documentation on D3D11CreateDevice:

> If you set the pAdapter parameter to a non-NULL value, you must also set the DriverType parameter to the D3D\_DRIVER\_TYPE\_UNKNOWN value. If you set the pAdapter parameter to a non-NULL value and the DriverType parameter to the D3D\_DRIVER\_TYPE\_HARDWARE value, D3D11CreateDevice returns an HRESULT of E\_INVALIDARG.

Setting the driver type to unknown fixed this problem!
> 0 votes

---
Tags: c++, directx11
---


# Question
Title: Should I use the X-Y-plane when using an orthographic projection in OpenGL?
I'm currently at a loss rendering a tile-based 3D map with an orthographic projection in OpenGL. Imagine any isometric 3D game (using actual geometry instead of sprites).

Internally, the tiles of my map have `x` and `y` coordinates (for `column` and `row` position within the map respectively). The tile with `x=0` and `y=0` is the one in the "top left", the one with `y=0` and `x=1` the one to the right of the first tile and so on.

Since in OpenGL, the coordinate system is so that the X-Z-plane is the "ground" plane, I create the model matrix for each tile by using the tile's `y` coordinate for the matrix' (or position vector's) `z` component. I then set up an orthographic "camera" by using `glm::ortho()`.

This seems to work fine at first, but I quickly ran into clipping issues when trying to render larger parts of the map. I assume this is due to the fact that the orthographic projection clips on `z`. A quick and dirty attempt of having the map in the X-Y-plane confirmed this, as I didn't have clipping issues then.

**Now, I'm not sure what's the best approach here?**

* Change the code so the tiles are being layed out in the X-Y plane? In that case, it seems as if I would have to remember to rotate every single object around x accordingly, which seems wrong.
* Do I need to set up the orthographic projection manually to use Y as the clipping plane? Is that even possible? I think OpenGL always uses z for clipping, right?
* Some other approach? I think I'm lost in coordinates and matrices, really.

I assume this is a common problem with a well-known solution, so I'm hoping to learn about that before I go ahead, change a lot and then learn I did it the wrong way...

# Answer
> 2 votes
### Yes, you can choose any coordinate system for your world. Choose one you like the most.

### No, you don't need to rotate each object, you can just modify your projection matrix accordingly.

How to do that is explained below, but first I need to make some things clean.

---

> in OpenGL, the coordinate system is so that the X-Z-plane is the "ground" plane

This is not true. XZ plane being ground is a widely-used convention, but OpenGL does not enforce it in any way.

There is such thing as a window plane, which is XY, and you can't change it. But it is completely unrelated to the issue.

> A quick and dirty attempt of having the map in the X-Y-plane confirmed this, as I didn't have clipping issues then.

You seem to have done something wrong. It should work completely same. Simply saying, the clippling is done in "window space" (not a proper term), so it does not matter in which coordinate system you have your world, only camera settings matter.

Also, you should know that stricly saying all 3 axes are clipped. You can see Z clipping when objects dissappear in the distance or when you get too close too them, but you can't really see X and Y clipping, because it happens right where your window frame is.

---

Now, about your matrices.

To swap the axes you need to multiply your projection matrix by

```
1  0  0  0
0  0  1  0
0 -1  0  0
0  0  0  1

```

if you want world Z to become camera Y and world Y to become camera -Z.

Or by

```
1  0  0  0
0  0 -1  0
0  1  0  0
0  0  0  1

```

for `Z -> -Y` and `Y -> Z`.

Just try both to see which works better.

---
Tags: opengl, tiles, glm, clipping
---


# Question
Title: SerializeField and Range(0, 1) in Unity3D
I want know What is the Use Of \[SerializeField\] and \[Range(0,1)\] in Unity3D.

# Answer
> 2 votes
`[SerializeField]` and `[Range(x,y)]` are both attributes, which can offer powerful utility to your script. If you are ever unsure of an attribute (or even if you are just curious) you should have a read through the references provided by the Attributes section, in the Unity API contents. You may find *other* attributes you did not know about that make your life a lot easier.

`[SerializeField]` tells Unity that you want to serialise that field, which in turn, forces it to display in the inspector. You might say "why would I need that? They already display in the inspector", and in most cases, you would be correct. This attribute is sparingly used, most commonly to display `private` variables in the inspector. There are some restrictions, for instance, you can not serialize a `static` field or a `Dictionary`. You can read more about the limitations (and work arounds) at the API reference.

`[Range(x,y)]` tells Unity that you want to restrict that field to a particular range of numbers, `x` and `y`. As such, it is only compatible with `float` and `int` variables. When you use this attribute, the variable will be displayed in the inspector as a *slide bar* that enforces the provided constraint, as opposed to the default input field you are probably use to. You can even tell it if you want the scroll bar to *count up* or *count down*. You can read more about the application at the API reference.

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


# Question
Title: "High" Quality Pixel Art Games (varying the scale factor)
Currently I'm developing a pixel art game and I was looking through the different styles to see which one would be the best for my game. The classic style is to draw all sprites/textures at a 1x scale offscreen to an image and then when you render the frame, scale the image up some amount to fit the window. The smaller the textures, the more pixelated the graphics look.

However, I also saw games like Realm of the Mad God, and I was wondering how they do their drawing. The game is mostly pixelated, with some exceptions. Most notable are the high quality shadows, high quality text and the very thin black outlines on all the sprites. I was wondering how this can be achieved. The only thing I can think of is the scale everything separately (game elements x3, outlines x1, shadows x1, etc...) so you can mix pixelated elements with high quality textures. Is this the right approach? What would this look like in LibGDX and game development in general?

Realm of the Mad God example.

One last thing, if anyone knows, could you tell me which of these two styles Terraria uses, and if its the first style, what the "base" scale is? (resolution of the game screen at 1x scale)

# Answer
This is very simple - you just have your textures made out of e.g. 8x8 pixels blocks and use 1px outlines and smooth shadows.
> 0 votes

---
Tags: art, pixel-art
---


# Question
Title: How can I make a character Blink effect in Unity?
I am making a game where I am making a health script where I have made a blueprint of what needs to be done. I'm trying a blinking effect after the character is hurt.

Can someone help me make a blink effect in Unity for JS?

# Answer
I use a Coroutine to bounce the alpha of the SpriteRenderer back and forth between two values. Unfortunately, this is C#, but is should be really easy to port to javascript.

```
///Renderer is your sprite's SpriteRenderer
///minAlpha is the lower bound that the alpha will "bounce" between
///maxAlpha is the upper bound that the alpha will "bounce" between
///interval is how long each "bounce" takes
///duration is how long the flashing lasts
public static IEnumerator FlashSprite(SpriteRenderer renderer, float minAlpha, float maxAlpha, float interval, float duration)
{
    Color colorNow = renderer.color;
    Color minColor = new Color(renderer.color.r, renderer.color.g, renderer.color.b, minAlpha);
    Color maxColor = new Color(renderer.color.r, renderer.color.g, renderer.color.b, maxAlpha);

    float currentInterval = 0;
    while(duration > 0)
    {
        float tColor = currentInterval / interval;
        renderer.color = Color.Lerp(minColor, maxColor, tColor);

        currentInterval += Time.deltaTime;
        if(currentInterval >= interval)
        {
            Color temp = minColor;
            minColor = maxColor;
            maxColor = temp;
            currentInterval = currentInterval - interval;
        }
        duration -= Time.deltaTime;
        yield return null;
    }

    renderer.color = colorNow;
}

```

You call it like this

```
StartCoroutine(FlashSprite(renderer, .7f, 1f,2, 3)

```
> 1 votes

---
Tags: unity, shaders, javascript
---


# Question
Title: Twin stick shooter turning and animation using Vector3.Angle() in Unity
I am trying to smoothly transition between running, strafing, and running backwards by calculating the angle between the left thumb stick (move) and the right thumb stick (rotate).

It is my understanding that `Vector3.Angle()` calculates angles to the left as negative and angles to the right as positive. This doesn't seem to be working for me. I am able to use `Vector3.Angle ()` make my character do the following actions:

```
if(-25 <= angle <= 25) // then run forward

if(25 < angle < 155) //then strafe left

if(-25 > angle > -155) //then strafe right

if(-155 < angle > 155) //then run backwards

```

Why is `Vector3.Angle()` behaving like this?

# Answer
You understanding of `Vector3.Angle()` is not correct. It always tries to give a positive angle. Quoting Unity Docs:

> The angle returned is always the non reflex angle between the two vectors - ie the smaller of the two possible angles between them and never greater than 180 degrees.

`Vector3.Angle()` has no concept of "to the right" or "to the left". It can't, anyway, because it would need a reference vector for that. You need a normal vector around which you can calculate this angle if you want to differentiate directions in angles with the sign of the angle. Here are two solutions for you:

If you have game objects that track the directions of the two thumb sticks, and if the y Euler angle of each game object represent the angle of the stick:

```
Transform stick1Transform;
Transform stick2Transform;

float angle1 = stick1Transform.localEulerAngles.y;
float angle2 = stick2Transform.localEulerAngles.y;

// get them to the same mod 360
while(angle1 - angle2 > 180) angle2 += 360;
while(angle2 - angle1 > 180) angle1 += 360;

// use this as the angle that you mentioned in your question
float angle = angle1 - angle2;

```

If you want something more general (your "up" vector may change), this would be another approach. You need to supply the up vector that is perpendicular to the two thumb stick vectors here.

```
Vector3 normal = Vector3.up; // you supply this. if vectors are in x-z, leave it like this.

// THIS is the formula that gives you angles with signs.
// Vector3.Angle() can not do that because it does not accept
// a normal vector around which positive and negative are defined
float angle = Mathf.Atan2(
    Vector3.Dot(Vector3.Cross(stick1Vector, stick2Vector), normal),
    Vector3.Dot(stick1Vector, stick2Vector)) * Mathf.Rad2Deg;

```

Hope that helps.
> 1 votes

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


# Question
Title: Disadvantages of using a singular scene in Unity
In my previous experience with Unity, I have had an organized level structure where each level instance was easily separated into a different scene.

For my current project, it would be much more natural to avoid such transitions, and instead disable or remove `GameObject` instances far from the player's position, and of course loading them in when necessary.

It strikes me that this must be how titles like Gone Home & Firewatch must have been made, and while my game won't be *huge* in scope, it will be bigger than those ("distance" wise).

Basically, I don't want to get halfway down this road and realize I've made a terrible mistake, so any input is appreciated. Are there disadvantages to using a singular scene in Unity?

# Answer
A few disadvantages that spring to mind for me:

**1.** Loading up the level in the editor will probably take a good while. As well as negotiating to that one fern you want to change.

**2.** You have to setup the streaming of the level seamlessly (i.e loading in the level as the player uncovers new areas, and unloading the ones no longer needed). You're giving the illusion of one constantly loaded world and breaking that with some spontaneous mountain creation up the player's nose is almost worse than having a loading screen.

**3.** The world size limit is mighty deceiving. As you breach further and further distances the little devils start to rear their ugly bug heads. One of these is floating point drift. With a physics engine or any other persistent calculations this can lead to some unpleasant jittering. ( Unless it's an open world horror game, then it'll be *spooky* shivering. )
> 2 votes

---
Tags: unity
---


title: Transition the scale of a sprite

text:
# Question
Title: Transition the scale of a sprite
I'm new to LibGDX but I am making a menu with some basic animation, I would like to start with a sprite scaled up and then it would transition to the normal size.

Is it possible with LibGDX or do I have to use a third party library?

# Answer
Take a look at Actions, I'd say they're what you need: https://github.com/libgdx/libgdx/wiki/Scene2d#actions
> 1 votes

# Answer
I don't know LibGDX or if it has a built in animation library, but you can be certain that it does give you the ability to scale a sprite.

All you have to do is use a function of the desired graph shape to pick the size you'll render the button on each frame. For example, a linear interpolation for the scaling values will produce a perfectly smooth(err, linear) growing or shrinking effect. Periodic functions are a special class of function which repeat. Sine(sin) is such a function. You can use this to produce a continuous animation.

However, I will suggest that you only use this scaling temporarily. This is an animation that will always look the same; take the time to have an animation made in a proper animation tool and simply change sprites each frame. This approach can be combined with the math above.
> 0 votes

---
Tags: libgdx, animation, sprites
---


# Question
Title: Moving a continue condition into the for loop produced something NOT logically equivalent?
I'm setting up a hex grid. The column/row system I use puts 0, 0 as the top left corner, and increasing columns (x) moves to the right but also vertically upwards. So columns run straight up and down, but rows run to the right but slanted upwards a bit.

This code...

```
for (j = 0; j < bd*2-1; j += 1) // bd is "board dimension", in my case 9
{
  for (i = 0; i < bd*2-1 and i < j+bd; i += 1)
  {
    if (i <= j-bd)
      continue;

    scr_ini_hex(i, j, bxo + i*hs, byo + j*hh - i*vs); // bxo and byo are arbitrary board x/y origins where the first cell is drawn, hs, hh, and vs are the gaps between cells in horizontal and vertical directions.
  }
}

```

produced this:

which is exactly what I want, a large hexagon with 9 smaller hexagons on each side.

So I thought I would be sophisticated and move that continue condition into the for loop. I wrote this...

```
for (j = 0; j < bd*2-1; j += 1)
{
  for (i = 0; i < bd*2-1 and i < j+bd and i > j-bd; i += 1) // added "i > j-bd", basically migrated the condition into this inner loop
  {
    //if (i <= j-bd)
      //continue;

    scr_ini_hex(i, j, bxo + i*hs, byo + j*hh - i*vs);
  }
}

```

and it produced this:

What went wrong here? I thought they were logically equivalent (except negating the condition, because the continue code was like a do until, but the for condition is like a do while).

# Answer
The difference is that continue only skips forward one step and the condition ends the whole loop.

To me it seems like the issue is, that you try to fit both the starting point and the end point into the loop-condition. When you should set the different starting point in the loop-initialization:

```
for (j = 0; j < bd*2-1; j += 1)
{
    for(i = max(0,j-bd);i < bd*2-1 and i < j+bd; i++)
    {
        scr_ini_hex(i, j, bxo + i*hs, byo + j*hh - i*vs);
    }
}

```
> 2 votes

# Answer
The condition part of the `for`-loop tells the loop when to stop looping. This is different from the `continue` statement that just skips the rest of the current step and moves on to the next.

Consider the following loop;

```
for(i = 0; i < 10; i += 1) {
    if (i % 2 == 0)
        continue;  // Skip even indices

    // Do stuff
}

```

If you were to extract the condition for the `continue` and place it as part of the `for`-loop you'd get

```
for(i = 0; i < 10 && !(i % 2 == 0); i += 1) {

    // Do stuff only on odd ones
}

```

But that means that the loop will exit as soon as it sees an even number, this is not what the `continue` statement does.
> 3 votes

---
Tags: logic, hexagonal-grid
---


title: Handling touch input with Event Trigger

text:
# Question
Title: Handling touch input with Event Trigger
I wrote a simple script to control my 'Player' object:

```
using UnityEngine;
 using System.Collections;

 public class PlayerMovement : MonoBehaviour {

     public float jumpVelocity = 10;

     private Transform groundCheck;
     private Animator anim;
     private Rigidbody2D rigidbody2D;
     private bool grounded;
     private Physics2D gravity;

     [SerializeField] private LayerMask whatIsGround;

     const float groundedRadius = .2f;

     void Awake () {

         // Setting up references.
         groundCheck = transform.Find("GroundCheck");
         anim = GetComponent<Animator>();
         rigidbody2D = GetComponent<Rigidbody2D>();

     }

     // Use it for Graphic & Input
     void Update () {

     }

     //Physics and ground check
     void FixedUpdate () {

         grounded = false;

         Collider2D[] colliders = Physics2D.OverlapCircleAll(groundCheck.position, groundedRadius, whatIsGround);
         for (int i = 0; i < colliders.Length; i++)
         {
             if (colliders[i].gameObject != gameObject)
                 grounded = true;
         }

     }

     //Jump function
     public void Jump () {

         if (grounded)
             rigidbody2D.velocity = jumpVelocity * Vector2.up;
     }

     //Gliding function
     public void GlideON () {

         rigidbody2D.gravityScale = 1;
         Debug.Log ("Graviti is on");
     }

     public void GlideOFF () {

         rigidbody2D.gravityScale = 0;
         Debug.Log ("Graviti is off");

         if (!grounded) {
             rigidbody2D.velocity = ( -jumpVelocity / 10 ) * Vector2.up;
         }
     }

 }

```

To operate touch screen I used GUI function like this:

**What I want to achieve:**

* One click - Player jump
* Hold button - Player starts glide.
* Player can not glide when he's grounded.
* It does not matter whether I start from 'PointerClick' or 'PointerDown'. If player is grounded the first action should be 'Jump' always.
* If we start with 'PointerDown', Player should jump and after reaching the maximum height he starts glide.
* If we start with 'PointerClick' Player should jump.
* If Player is not grounded and we want to start glide - we have to touch screen and hold it.

**Where is the problem:**

* When I start with 'PointerDown', my Player begins infinite jump until 'PointerUp'.

I would be grateful for your help and suggestions.

# Answer
One of the best solutions for managing behaviour like this is the **state pattern**. The problem with simply adding a bool for "can jump" is it can quickly turn into a mess as you add more and more behaviours and mechanics and more and more different combinations of what the player can and can't be doing. You're swinging down to bug central!

The state pattern resolves this by neatly keeping all the relevant information **in** the state it concerns. The first thing you'd do to achieve this is make a separate class for each state that extends an abstract base class (interface is probably better but I haven't done one in c# for a long while so I'm sticking to what I know):

```
public abstract class PlayerState
{
   public virtual void handleInput( ref PlayerMovement player);
   public virtual void update( ref PlayerMovement player);
}

```

and then each of your states would provide a special override for the special fun it gets up to:

```
public class PlayerStateJumping : PlayerState
{
   [SerializeField] private LayerMask whatIsGround;

   private Transform groundCheck;
   private Physics2D gravity;

   private float jumpVelocity;
   private float groundedRadius;

   public PlayerStateJumping()
   {
      groundedRadius = .2f;
      groundCheck = transform.Find("GroundCheck");
      player.setRigidBody2D(jumpVelocity * Vector2.up);
      // Perform other necessary setup here
   }

   public override void handleInput(PlayerMovement player)
   {
      if ( Input.getButtonDown("Glide") )
      {
         player.setState( new PlayerStateGliding() );
      }
   }

   public override void update(PlayerMovement player)
   {

     Collider2D[] colliders = Physics2D.OverlapCircleAll(groundCheck.position, groundedRadius, whatIsGround);
     for (int i = 0; i < colliders.Length; i++)
     {
         if (colliders[i].gameObject != gameObject)
         {
             player.setState(new PlayerStateIdle());
         }
     }

   }
}

```

Now you can't jump again in the jump state, you can only move to the glide state or return to idle when you reach the ground. All the information specific to jumping is kept isolated as it shouldn't be tangling up the rest of the states.

**Note** This is just an example of what makes up the state pattern. This isn't perfect code you can just copy in (since you have a lot of different variables getting set up all over the place and I probably goofed it up somewhere Unity-wise.)

It would then free up the PlayerMovement To have a much more elegant class with no chance of confusion:

```
public class PlayerMovement : Monobehaviour
{
    private Animator anim;
    private Rigidbody2D rigidbody2D;

    private PlayerState currentState;

    void Awake()
    {
      anim = GetComponent<Animator>();
      rigidbody2D = GetComponent<Rigidbody2D>();
      currentState = PlayerStateIdle();
    }

    void Update()
    {

    }

    void FixedUpdate()
    {
       currentState.Update();
    }

    void setState( ref PlayerState playerState )
    {
       this.currentState = playerState;
    }

}

```

This stops PlayerMovement getting dogpiled with a bunch of bools and nonsense that will end up being a bug breeding ground. Each state only knows what it needs to know and the transitions out are very explicit. Essentially this is a model of a Finite State Machine.

If you wanted to add functionality not related to player movement (e.g being able to shoot at an enemy) to stop the doubling up of states you'd probably make a PlayerShooting class and have a state in there as well.
> 1 votes

# Answer
You could remedy to this by adding another bool `canJump` :

```
public void Jump () {
       if(canJump) {
         if (grounded)
             rigidbody2D.velocity = jumpVelocity * Vector2.up;
       canJump = false;
    }
 }

```

So when you are clicking, the Jump() method will run the jumping loop one time.After this code, you will need to set the `canJump` boolean to true once he hits the ground again.

EDIT : By the way, using Event handlers isn't the most effective way you could use to handle Android/iOs touch events. You can simply add code to your script using Input.GetTouch which offers not just 2 phases (Down, Up) but 4-(5) phases of "Touching".
> 0 votes

---
Tags: c#, unity, android, ios, movement
---


# Question
Title: How to resolve collision when both of the intersecting bodies were moving?
Suppose there are two quadrilaterals A and B. A is stationary but B is moving. They collided. Now B is inside A.

To check if they are intersecting I can use 2d separating axis theorem (SAT). To push B out of A so that they are not intersecting anymore, I can again use SAT to get the Minimum Translation Vector(MTV) and project B out of A using it.

My problem is, what should I do when both A and B were moving, and then they collided? I can't project A out of B or B out of A alone since both of them were moving. How should I separate them?

# Answer
If you seperate along the Minimum Translation Vector, you could be getting some very jerky behaviour.

I think you should do your projection backwards along the movement path, which lead to the collision.

Then you can resolve your collision physics (change of movement direction ...) and move the object that collided the rest of it's new movement for the partial timestep still missing.

If you do that, then 2 moving objects is straightforward:

You subtract their velocity vectors and calculate how far you would have to move the first of the two backwards along this combined velocity to avoid the collision. Then you calculate the timelength that represents and actually move both of them backwards along their orginal velocities.

**edit for clarity:**

For two moving object if the first moves with a velocity of *v1* and the second with *v2*, then resolve the collision hypothetically with a velocity of *v=v1-v2* (vector valued) for the first object and 0 for the second objects velocity. You get a negative timestep *dt*, which you would have to move the first obeject backwards. Multiply this timestep with the actual velocities, *v1* and *v2*, to move both object backwards.
> 2 votes

# Answer
Not completely sure if this answer is 100% correct, but i can't comment yet :/

First a question, is it completely necesary to have objects get inside another object and then pushing it out?

What i mean is, maybe you can avoid movement in a certain direction in case there is "going to be" a collision.

im not sure how modern engines handle collisions, but what if when you detect a collision you instance a collision handler, who knows both colliders and can correct the positionning of both?
> 1 votes

---
Tags: collision-detection, separating-axis-theorem
---


# Question
Title: Scaling a rotated rectangle in a given direction
I'm facing an issue when trying to scale a rotated rectangle in a given direction.

In my context, the width and height of the rectangle are based on the texture size multiplied by a scale factor (one for X-horizontal and another for Y-vertical).

Basically, if a texture width is 100 and the scale-X factor is "2" the calculated width is 200, which is the double. The same goes for the height.

Right now, if I want to scale the rectangle to the left, I'm applying a scale value and at the same time I'm modifying the X position to compensate the increased scale factor (to keep the right side of the rectangle in the same position).

If there is no rotation applied, this method works nicely, but things complicate when I rotate the rectangle (in the following example 45º):

From what I'm understanding, this time I have to compensate the Y position as well because of the slope BUT I can't figure out the correct relation to apply an acceptable value.

Any ideas? Thanks!

# Answer
Naturally, right after posting this I've reminded myself of a way to solve this issue using the following parametric equations to calculate the correct compensation for each axis when the rectangle is rotated:

```
var x = difX * Math.cos(direction);
var y = difY * Math.sin(direction);

```

Another problem appeared if the rotation was between 180º and 360º, as the mouse X and Y offsets should have an inverted value. For this case I've simply inverted the X and Y whenever the normalized rotation value was between those values:

```
 var normDirection = direction % MathHelper.PI2;
 if (Math.abs(normDirection) > MathHelper.PIo2 && Math.abs(normDirection) < MathHelper.PI + MathHelper.PIo2) {
    difX *= -1;
    difY *= -1;
 }

```

Also, to calculate the correct direction of the selected point which is to be dragged/positioned, I added the result of a arctangent calculation which gives the correct direction based on the mouse offset direction vector:

```
direction += Math.atan2(difY, difX);

```

Currently I'm only having some difficulties in the corner cases (top left for instance) which for some reason are getting a different slope value compared to the mouse movement vector (currently investigating the reason and will update this answer when I have some good news).

In any case, if someone has a better understanding of the problem, I'm open to more suggestions! Thanks..
> 1 votes

# Answer
If dragging the handle is restricted in alignment with the resulting change, then you just have to move the center half of the way the square handle moved.

**edit:** added a picture
> 1 votes

# Answer
I would recommend constructing an axis aligned bounding box (AABB) around the rotated shape and checking the difference between before the shape was scaled, and then after. The delta between the previous left and the new left offset will tell you exactly how much you need to offset to compensate. This can also be applied to the top offset in the same way. Hope this helps.
> 0 votes

---
Tags: mathematics, transformation, linear-algebra, scale
---


# Question
Title: Finite State Machines for Enemies (AI vs. Entity States)
Finite State Machines are a great tool for simplifying a system where an Entity has many states it can be in with different conditions that determine what state to transition to. This works well for representing a Player in a platformer, because the state machine can keep track of what state the Player is in based off of user input. This state machine would largely be based around animation states (running, jumping, attacking, etc...)

However, although this makes sense for handling Entity states and keeping track of animations, what about AI states? FSMs also provide a great framework for handling how enemies behave when interacting with the Player. My question is, what is the relationship between this FSM and the FSM that handles general entity states?

For example, in general, an enemy can be running, attacking, idling, jumping, falling, crouching, etc... In terms of AI, the enemy could be following, attacking, running away, patrolling, etc... As you can see, these states are mostly different with some overlap. I want to know how to handle these two different FSMs in code.

**Questions**:

1. Should I keep these FSMs separate and update the states separately or should I somehow combine them into one FSM?
2. If I keep the FSMs separate, how can I can I handle interdependence (behavior in the AI might change if suddenly the Enemy walked off a cliff and is now falling)?

# Answer
1. I think that you should keep each individual "state" separate. For instance, if you have an enemy that will chase after the player if it sees the player, it will start following and running. If you had an enemy that only tails the player, it will start following, but not running. The code might look like this in pseudocode:

```
class enemy{
private:
    bool running;
    bool pursuing;
    running = false;
    pursuing = false;

public:
    class chaser{
        void detectPlayer(){
            if (enemy can see player) then {
                pursuing = true;
                running = true;
            }
        }

    class tail{
        void detectPlayer(){
            if (enemy can see player) then {
                pursuing = true;
            }
        }
    }
}

```
2. You would have to code the interdependencies into various functions. You can either do an event based function that updates all the relevant states whenever an enemy falls off of a cliff (which is what I have above) or you can have it be part of his general update method that updates all his states.
> 1 votes

---
Tags: architecture, ai, behavior, fsm
---


# Question
Title: Is there any less expensive way to achieve this lighting effect?
I'm creating a game that is similar to Tibia on its projection:

But I want it, under the hoods, to be 3D, and extremely dynamic - meshes generated on the fly, statues exploding and turning into smoke monsters, things like that. For that, I've created a renderer that isn't geometry based, but atom based - it takes a compact buffer of positions and colors and renders it to screen. It works extremely well and is quite fast. There is only one problem, lighting. To achieve realistic lighting, I must, for each atom on the screen, emit a ray that traces a volume, sampling among the way. If it hits something before the light, that space isn't lit. This is the end result:

I love that effect, but, on my machine with a low-end GPU, it can stand millions of atoms, but only 2 lights max. That is not enough, I'd need 16 lights at least. Each light requires dozens of samplings for each atom on scene, it is prohibitively expensive. Without global lighting, the ambient becomes flat and boring.

Is there any creative way to achieve the same effect, albeit less expensive?

# Answer
> 1 votes
The best thing you can do is to calculate all the lighting data you can beforehand and store that in the game. If none of the lights move themselves, then you have a much easier problem, as you only have to account for the entities or other moving objects. Instead of storing the floor as just one specific grey, you can use a shader function.

Another thing you can do is cull as many calculations as you can. Instead of lighting across the entire area, only do it until the light no longer has a noticeable effect the point. For instance, if a light has a brightness of one unit at one centimeter away from the source, you can stop considering it after a meter, as it will only add 0.0001 at most to the brightness of the pixel.

Finally, Coburn's suggestion in the comments is great, and you should probably use that article.

**Addendum:** One thing that you can do is instead of sampling each atom dozens of times is realize that light obeys an inverse square law. The formula for light on a plane is 1/(height of the light^2+distance on the ground^2), which is just a combination of the Inverse Square Law and the Pythagorean Theorem. You can then use that formula to add the amount of light to an atom that you would expect from that light. You will have to calculate ambient light beforehand. Finally, whenever a light "path" hits something, you would temporarily stop the algorithm from adding light to atoms until you reach a point where the light can shine over the object. This should take out the dozens of samples for every single atom. This basic idea, plus the earlier ideas, should significantly reduce computation time.

---
Tags: 3d, shaders, rendering, glsl, lighting
---


# Question
Title: How should I make a jump-timing game's character static on screen?
I decided to learn Pygame and try to make a simple game inspired by Google's T-rex jump game. However, I stumbled upon a problem that I can not seem to figure out: How can I implement a scroller/camera that can keep up with my character and platform?

Now it just disappears off the screen. I have made it so the platform moves to the right with the same speed as the character. Here is a GIF of what it looks like at the moment:

Is this the best way to do it for a game like this where speed of the character is always constant or is there a better way that will make adding obstacles in the future more easy?

# Answer
You're overthinking it. For the dinosaur game, you need 2 sprites (don't worry about the pterodactyl or different sized cactuses yet):

* Dino

The dino doesn't move left/right - he stays in the same spot on the screen, and pressing space only makes him jump up - gravity makes him fall down. The "ground" is just the y coordinate where you make him stop. Draw a line there using pygame.draw.line()

* Cactus

A cactus spawns with an x position \> screen\_width, and its x\_velocity is \< 0. That will make it look like it moves across the screen from right to left. When a cactus has an x\_pos \< 0, you delete it.

That's it. There's no need for a camera or moving platforms, etc. The illusion is that the dino is running, but really it's just the cactuses. The illusion is improved with some small clouds that move at a slightly slower speed than the cactus does.
> 2 votes

# Answer
I've never used Pygame but it appears as though your moving the terrain away from the camera. Maybe not the best way of wording it, but you should just move the terrain to the left keeping the T-rex in a constant spot in the X axis, then when you just you simply move it in the Y-axis when jumping while still moving the terrain to the left (at a constant speed or one that increases over time). that way it appears as though there is movement in the T-rex while in reality the ground is just moving under it.
> 0 votes

---
Tags: camera, python, platformer, pygame
---


# Question
Title: Proper way to calculate x and y components of two 2D vectors
I'm having some issues on resolving this with the current set of Vector2 methods. Could you help me to define a universal solution? The idea is to move a spaceship to another point using only relative to (A) lateral and forward movements.

---

Given two points A(1,-1) and B(2,-3): \- A has a known angle with the y axis: alpha \- How to calculate the x-dist and y-dist relative distances in order to move A to B?

# Answer
Use the dot product to find how far along the normal a vector is

```
float Y_dist = Vector2.Dot(B - A, thatBigArrow.normalized);

```

And the rotated vector for the other direction:

```
// calculate rotated vector by 90 degrees: (y, -x)
Vector2 x_direction = new Vector2(thatBigArrow.y, -thatBigArrow.x);

float X_dist = Vector2.Dot(B - A, x_direction.normalized);

```
> 0 votes

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


# Question
Title: Smoothness & performance issues of new game
I've written the basics of a new game which just includes a game loop that can update and render basic game objects so far.

I want to ensure that what I've written so far is as good as it can be and provides me with the best & most flexible foundation to build a game on top of. Really don't want to discover something fundamental later which causes a massive re-write.

Even though the game is running at a very decent frame rate the game objects are not moving entirely smoothly. I'm seeing stuttering and what looks like skipped frames, especially when the game objects bounce off the walls.

I'm not sure if this is a problem with my game loop or how I'm updating the game objects, or something else?!

If I increase the number of game objects from 5 to 100 the performance does not seem to change so I don't think it's a processing issue.

The project is only small at the moment - https://github.com/arrwhidev/java2d

# Answer
I looked at your code, and there's one big performance issue that can lower your expected FPS.

It's that you are drawing to an image, which you then draw onto your `BufferStrategy`. Even though it's the same image object every render, this image is not going to be cached in VRAM because you keep changing it on every frame update. This means all your Java 2D calls against it are CPU bound. If you instead draw to your `BufferStrategy` graphics object then your Java 2D calls are translated for some hardware accelerated pipeline (most likely translated into OpenGL calls).

Using images is ok, just use them for static textures. An image should be cached in VRAM rather fast if you do not modify it (and of course also use it).

So change your code roughly to enable the following:

```
if (shouldRender) {
   frames++;
   render(bs.getDrawGraphics()); // render directly to the bufferstrategy
}

```
> 0 votes

---
Tags: java, performance, game-loop, frame-rate
---


# Question
Title: How to only detect Actor and not background
I'm making a game where I have buttons on a stage, but the background also acts as a "button". But when I press on one of the existing actors on the stage, it also registers a click in the background in addition to the click on the button. How can I fix this?

Inside constructor

```
button = new ImageButton(getDrawable(new Texture("PlayUp.jpg"))); //only using one image atm
button.setSize(150, 134);
button.setPosition(camera.position.x, camera.position.y);
stage = new Stage(viewport);
        Gdx.input.setInputProcessor(stage);
        stage.addListener(new ClickListener(){
            @Override
            public void clicked(InputEvent event, float x, float y) {
                System.out.println("Background touched");

            }
        });
        button.addListener(new InputListener() {
            @Override
            public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
                return true;
            }

            @Override
            public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
                System.out.println("Button touched");
            }
        });
        stage.addActor(button);

```

part of render() method

```
@Override
    public void render(float delta) {
        Gdx.gl.glClearColor(1, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    tapCatch.batch.setProjectionMatrix(camera.combined);
    tapCatch.batch.begin();

    stage.act(delta);
    stage.draw();

    tapCatch.batch.end();

}

```

# Answer
> 1 votes
It the click-handler for the background, make sure you filter out the `InputEvent`s that are already handled:

```
Gdx.input.setInputProcessor(stage);
stage.addListener(new ClickListener(){
    @Override
    public void clicked(InputEvent event, float x, float y) {
        if (!event.isHandled()) {
            System.out.println("Background touched");
        }
    }
});

```

This will allow you to only care about events that are not already handled by a previous click-handler, like your `Button` for example.

---
Tags: libgdx, touch
---


# Question
Title: How do I show the position and rotation lines of the camera, while having other game objects selected?
When I select the Camera object, I see the border-lines, the near clipping plane and the camera preview. I would like to see all of these things when I select another game object.

In other words, I would like to still see the lines from the position and rotation of the main camera, but while having another object.

I know it somehow works with a custom inspector, I also found some solutions which seemed close ("how to create an editor screenview" and "show camera preview"), but I couldn't get them to work.

How do I show the position and rotation lines of the camera, while having other game objects selected?

# Answer
I don't know of a way to force the camera preview picture-in-picture overlay to always display. My best recommendation for that part would be to set that camera to render to the display, and then use the Game Window as your camera preview. You can arrange your workspace tabs so you can see both the scene view and game at the same time.

Duplicating the frustum cage you see in the scene when the camera is selected is fairly straightforward. Attach this script to each camera you want to see this way:

```
[RequireComponent(typeof(Camera))]
public class AlwaysCameraGizmo : MonoBehaviour {

    public Color color = Color.white;

    Camera _camera;
    static Vector3[] _frustumPoints = new Vector3[8];

    void OnDrawGizmos()
    {
        if (_camera == null)
            _camera = GetComponent<Camera>();

        Gizmos.color = color;

        _frustumPoints[0] = _camera.ViewportToWorldPoint(new Vector3(0, 0, _camera.nearClipPlane));
        _frustumPoints[1] = _camera.ViewportToWorldPoint(new Vector3(1, 0, _camera.nearClipPlane));
        _frustumPoints[2] = _camera.ViewportToWorldPoint(new Vector3(1, 1, _camera.nearClipPlane));
        _frustumPoints[3] = _camera.ViewportToWorldPoint(new Vector3(0, 1, _camera.nearClipPlane));

        _frustumPoints[4] = _camera.ViewportToWorldPoint(new Vector3(0, 0, _camera.farClipPlane));
        _frustumPoints[5] = _camera.ViewportToWorldPoint(new Vector3(1, 0, _camera.farClipPlane));
        _frustumPoints[6] = _camera.ViewportToWorldPoint(new Vector3(1, 1, _camera.farClipPlane));
        _frustumPoints[7] = _camera.ViewportToWorldPoint(new Vector3(0, 1, _camera.farClipPlane));

        // Near
        Gizmos.DrawLine(_frustumPoints[0], _frustumPoints[1]);
        Gizmos.DrawLine(_frustumPoints[1], _frustumPoints[2]);
        Gizmos.DrawLine(_frustumPoints[2], _frustumPoints[3]);
        Gizmos.DrawLine(_frustumPoints[3], _frustumPoints[0]);

        // Far
        Gizmos.DrawLine(_frustumPoints[4], _frustumPoints[5]);
        Gizmos.DrawLine(_frustumPoints[5], _frustumPoints[6]);
        Gizmos.DrawLine(_frustumPoints[6], _frustumPoints[7]);
        Gizmos.DrawLine(_frustumPoints[7], _frustumPoints[4]);

        // Between
        Gizmos.DrawLine(_frustumPoints[0], _frustumPoints[4]);
        Gizmos.DrawLine(_frustumPoints[1], _frustumPoints[5]);
        Gizmos.DrawLine(_frustumPoints[2], _frustumPoints[6]);
        Gizmos.DrawLine(_frustumPoints[3], _frustumPoints[7]);
    }
}

```

This just manually renders the bounding frame of the camera's frustum each time the Unity editor repaints its gizmos. You can customize the colour to keep track of multiple cameras in a scene.
> 1 votes

---
Tags: unity, camera
---


# Question
Title: Transform luminosity (Watt) to be usable in shader
I'm studying the color and the Luminosity of Stars. I'm trying to figure how to transform information of Luminosity i perceive at a given distance to something usable into a shader. For instance , Given the Radius and temperature of a star, with inversed square law on Distance(meters) i obtain the perceived luminosity of a star in Watt (brut force, without any scattering). For sample, the luminosity I obtain for the Sun ON Earth is about 1361W and a RGB color about

```
w=1361
r=255 g=245 b=242

```

Astronomical and physics are quite OK, but how to transform this values into usable shader formulas or values? best practices ? samples ?

I guess i will simply take the aboves value as Light reference an normalize the intensity(1361) to be 1 on each rgb componemt value. I' ll keep you posted.

# Answer
One formula that you can play around with is the inverse square law for light fall-off at a given distance. In a virtualisation the inverse square law can often give a light that just seems a bit too bright and keen.

A *brighter* way to work out the fall-off in light intensity is this watering down of the formula:

```
NewIntensity = Original Intensity
               ------------------------------
               K1 + K2Distance + K2Distance^2

```

where K1, K2, and K3 are constants we can attune to give the best results. This tends to give a better looking model.
> 1 votes

---
Tags: shaders, lighting, fragment-shader
---


title: Selecting unit if ray intersects

text:
# Question
Title: Selecting unit if ray intersects
Again some problems with my RTS base:

I have worked on the script that should select the unit, if its clicked. In this case, I check if the raycast hit's the object and checks, if it has a selectable child, which is basically a projector for a circle on the ground. This should be toggled on.

You can see, how the clored ray intersects with the unit but it doesn't show the expected debug message.

Here's my full code that handles the mouse interactions:

```
using UnityEngine;
using System.Collections;

public class Mouse : MonoBehaviour {

    RaycastHit hit;

    public static GameObject CurrentUnit;

    private static Vector3 mouseDownPoint;

    void Awake()
    {
        mouseDownPoint = Vector3.zero;
    }

    public GameObject Target;

    private float raycastLength = 1000; // Mathf.Infinity;
    void Update () {

        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if(Physics.Raycast(ray, out hit, raycastLength)) {
            if (Input.GetMouseButton(1))
            {
                mouseDownPoint = hit.point;
            }
            if (hit.collider.name == "Terrain")
            {
                if (Input.GetMouseButton(1)) // wenn rechtslick -> ziel instanziieren
                {
                    GameObject TargetObj = Instantiate(Target, hit.point, Quaternion.identity) as GameObject;
                    TargetObj.name = "Target Instance";
                }
                else if (Input.GetMouseButtonUp(0) && CheckLeftClick(mouseDownPoint))

                    DeselectIfSelected();
                //Terrain click end
            }
            else {
                if (Input.GetMouseButtonUp(0) && CheckLeftClick(mouseDownPoint))
                {
                    //does the ray hit a unit with selection child?
                    if (hit.collider.transform.FindChild("Selection"))
                    {
                        //unit found
                        Debug.Log("Unit found");

                        if (CurrentUnit != hit.collider.gameObject)
                        {
                            //enable the selection child
                            GameObject SelectedObj = hit.collider.transform.FindChild("Selection").gameObject;
                            SelectedObj.SetActive(true);
                            if (CurrentUnit != null)
                                CurrentUnit.transform.FindChild("Selection").gameObject.SetActive(false);
                            //replace selection
                            CurrentUnit = hit.collider.gameObject;

                        }
                    } else
                    {
                        //if not a unit
                        DeselectIfSelected();
                    }
                }
            }
            } else {
                if(Input.GetMouseButtonUp(0) && CheckLeftClick(mouseDownPoint))
                {
                    DeselectIfSelected();
                }
            }

        Debug.DrawRay(ray.origin, ray.direction * raycastLength, Color.yellow); // ray to position

    }

    #region Helper

    //check, if mouse is clicked

    public bool CheckLeftClick(Vector3 hitPoint)
    {
        float clickZone = 0.8f;
        if (
         (mouseDownPoint.x < hitPoint.x + clickZone && mouseDownPoint.x > hitPoint.x - clickZone) &&
         (mouseDownPoint.y < hitPoint.y + clickZone && mouseDownPoint.y > hitPoint.y - clickZone) &&
         (mouseDownPoint.z < hitPoint.z + clickZone && mouseDownPoint.z > hitPoint.z - clickZone))
            return true;
            else return false;
    }

    public static void DeselectIfSelected()
    {
        if (CurrentUnit != null) {
            CurrentUnit.transform.FindChild("Selection").gameObject.SetActive(false);
            CurrentUnit = null;
        }
    }
    #endregion

}

```

I'd be very happy, if someone could help with that problem

# Answer
you have "Selection" GO disabled by default, do you have any script that enables it? also make sure it has Collider.
> 1 votes

---
Tags: unity
---


# Question
Title: Missing Reference: Unity should clone object before destroying
For a small RTS Project, I'm working on the pointer. I want a pyramid as a marker on the terrain, that indicates the selected position, sinks into the ground and disappears. For the next interaction there should be another object that can be animated and so on.

Here's my C# code:

**This handles the click event on the terrain:**

```
using UnityEngine;
using System.Collections;

public class MousePoint : MonoBehaviour {

    RaycastHit hit;
    public GameObject Target;
    private float raycastLength = 500;

    void Update () {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if(Physics.Raycast(ray, out hit, raycastLength)) {
            Debug.Log(hit.collider.name);

            if(hit.collider.name == "Terrain") {

                if (Input.GetMouseButton(1)) {
                    GameObject TargetObj = Instantiate(Target, hit.point,
                            Quaternion.identity) as GameObject;
                    TargetObj.name = "Target Instance";
                }
            }
        }
        Debug.DrawRay(ray.origin, ray.direction * raycastLength, Color.yellow);
    }
}

```

**This should destroy the pointer object:**

```
using UnityEngine;
using System.Collections;

public class DestroyParentGameObject : MonoBehaviour {

    void DestroyParent () {
        Destroy(this.gameObject.transform.parent.gameObject);
    }
}

```

In my hierarchy, I have a `Terrain`, a `Camera`, a `SpotLight` and a `GameObject` "`Target`" with the child "`Pointer`". The target should be cloned.

At the end of the sink animation, I call `DestoryParent()` from The script above. Unfortunately, it deletes the first existing object, and returns this error:

> MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
>
> Your script should either check if it is null or you should not destroy the object.
>
> UnityEngine.Object.Internal\_InstantiateSingle (UnityEngine.Object data, Vector3 pos, Quaternion rot) (at C:/buildslave/unity/build/artifacts/generated/common/runtime/UnityEngineObjectBindings.gen.cs:63)
>
> UnityEngine.Object.Instantiate (UnityEngine.Object original, Vector3 position, Quaternion rotation) (at C:/buildslave/unity/build/Runtime/Export/UnityEngineObject.cs:80)
>
> MousePoint.Update () (at Assets/scripts/MousePoint.cs:18)

The cloned object is a prefab with an empty `Object`, with a `Cylinder` as the child. The short code is bound to this cylinder; a placeholder for the arrow, later. The large code is appended to a global empty object that handles all world scripts

You can see what happens via my screen recording. Does somebody has an Idea how to solve this?

# Answer
> 1 votes
here you go, i made some edits to your code:

```
using UnityEngine;
using System.Collections;

public class MousePoint : MonoBehaviour {

RaycastHit hit;
public GameObject Target;
private float raycastLength = 500.0f;

void FixedUpdate () {
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

    if(Physics.Raycast(ray, out hit, raycastLength)) {
        Debug.Log(hit.collider.name);

        if(hit.collider.name == "Terrain") {

            if (Input.GetMouseButton(1)) {
                GameObject TargetObj = Instantiate(Target, hit.point,
                        Quaternion.identity) as GameObject;
                   //transform.name
                TargetObj.transform.name = "Target_Instance";
            }
        }
    }
    Debug.DrawRay(ray.origin, ray.direction * raycastLength, Color.yellow);
}
}

```

and second code:

as i understand this code is attached to gameObejct yo uwant do destroy, so..

```
  void DestroyParent () {
     if(transform.parent.gameObject){
     Destroy(transform.parent.gameObject);
  }

```

}

---
Tags: c#, unity, game-mechanics, mouse
---


# Question
Title: How hard is it to edit an xml based database in a Unity3D game?
I want to make an **item database in xml** for my game.

I was thinking about **encrypting** it, but I don't know how hard is it to edit the database.

I want my database to be moddable, but hard to screw up for average users.

**(~I don't want kids to make the game unplayable, then unable to fix it)**

Should I encrypt the database? Or will it just annoy the "modders", while the average players wouldn't find the database even when it isn't encrypted?

**TL;DR How hard is it to get a raw xml file from a standalone build?**

# Answer
> I want to make an item database in xml for my game.

Good idea.

> I was thinking about encrypting it, but I don't know how hard is it to edit the database.

Encryption is an advanced topic. And it can be really easy to screw things up.

> I want my database to be moddable, but hard to screw up for average users.

Moddable = Editable = Not secure. You choose.

> (~I don't want kids to make the game unplayable, then unable to fix it)

Instead of preventing the edit, offer an option in-game to fix the xml file (Rebuild, load from backup, etc.). This would be easier for you and modders. And players can safely mess around without fearing to break the game.

> Should I encrypt the database? Or will it just annoy the "modders", while the average players wouldn't find the database even when it isn't encrypted?

It will just annoy the modders. Most of your players won't even open the folder the xml file is stored.

> TL;DR How hard is it to get a raw xml file from a standalone build?

It is not hard, but it takes some time to implement and polish the code. Take a look at this unify wiki article about serializing to XML file and deserializing back.
> 4 votes

---
Tags: unity
---


# Question
Title: Why does this transparent shader cause objects' z-sorting to be backwards?
I am making a Klondike Solitaire game, with the intent of later expanding it to encompass other solitaire games and allow deck customization. As part of this, the playing card meshes I am creating programatically are mostly opaque, but require non-alphatest transparency in order to draw the pips (rank/suit icons) correctly.

The problem is this:

The z-sorting of the cards is the exact opposite of what it's supposed to be. I know that transparency is the problem because the z-sorting works properly when it's disabled (the `#pragma alpha:fade` in the shader is removed):

...which obviously breaks how the cards' material is being rendered.

This is the shader I have:

```
Shader "Custom/Card" {
    Properties {
        _CardAtlasTex ("Card Atlas", 2D) = "white" {} // card atlas texture
        _ColorUVZone ("Colour UV Zone", Vector) = (0,0,0,0) // texture zone inside which the pips are, and so the suit colour should be used
    }
    SubShader {
        Tags { "RenderType"="Opaque" "Queue"="Geometry" }
        LOD 200

        CGPROGRAM
        #pragma surface surf Lambert vertex:vert alpha:fade

        sampler2D _CardAtlasTex;
        float4 _ColorUVZone;

        struct Input {
            float2 uv_CardAtlasTex;
            float3 vertexColor;
        };

        void vert (inout appdata_full v, out Input o) { // http://answers.unity3d.com/questions/923726/unity-5-standard-shader-support-for-vertex-colors.html
            UNITY_INITIALIZE_OUTPUT(Input,o);
            o.vertexColor = v.color;
        }

        void surf (Input IN, inout SurfaceOutput o) {
            half4 card = tex2D (_CardAtlasTex, IN.uv_CardAtlasTex);
            o.Albedo = card;
            o.Alpha = 1; // make it opaque to start with

            // if this is a pip, colourize it
            if (IN.uv_CardAtlasTex.x >= _ColorUVZone.x && IN.uv_CardAtlasTex.y >= _ColorUVZone.y && IN.uv_CardAtlasTex.x <= _ColorUVZone.z && IN.uv_CardAtlasTex.y <= _ColorUVZone.w) {
                o.Albedo *= IN.vertexColor; // colourized
                o.Alpha = card.a; // transparented
            }
        }
        ENDCG
    }
    FallBack "Diffuse"
}

```

Things I have tried:

* Changing the subshader's `RenderType` to things like `Transparent` or `TransparentCutout`, or removing it entirely. No effect.
* Changing the subshader's `Queue` to things like `Transparent` or `AlphaTest`, or removing it entirely. No effect.
* Adding a `ZWrite On` (just before the `LOD 200`). Does nothing because the generated code forces `ZWrite Off` due to having `#pragma alpha:fade` (as far as I can tell), and putting the line after the pragma in hopes of re-overwriting it is a syntax error.

From #3, I'm guessing that if I can somehow force `ZWrite On` despite the `alpha:fade`, it should work as expected. But chances are there's something else I'm missing that could work.

Other notes:

* The problem is very consistent: the back-most cards are always drawn front-most, no matter what the shuffle is or whether the lower cards are ahead or behind.
* There is no alternative to using full transparency; pips can be any colour against any background. (The face card designs don't use transparency.)
* All cards use the same material, which uses a single texture atlas.

# Answer
After doing some tests, it looks like this may be a bug in a recent version of Unity.

When you create a new material, under the hood its `Custom Render Queue` property defaults to -1, meaning "use whatever queue is specified in the shader file," as we would expect.

But as soon as we change the material's shader to use a custom one (I've now tried this with newly-created Surface and Unlit shaders), Unity sets the `Custom Render Queue` to 2000, meaning "ignore what the shader says and always render this in the opaque geometry queue"

That seems blatantly wrong, so I expect they'll fix that. In the meantime, as Toomai discovered in the comments above, we can fix this by...

1. Switch the Inspector to Debug mode by opening the hamburger menu (≡) in the top-right corner and selecting "Debug"

2. Replace the 2000 in the `Custom Render Queue` field with -1 instead

Your shader's queue settings should now be respected again.
> 3 votes

---
Tags: unity, shaders
---


# Question
Title: is there a way to check if a point is inside circle, other than distance between points?
Is there a way to check if a point is inside circle, other than distance between points? I am struggling with floating point precision problems. Is there some method to do the same test, but with more precision? The usual method uses square root...

# Answer
There's no real way around using the distance. There's always *some* error margin you have to accept and I don't think it will get any better using some more complex algorithm.

You can skip the square root though:

```
is_inside = (delta_x * delta_x + delta_y * delta_y) < (radius * radius)

```

If this isn't precise enough for you, you can try multiplying all values by 100 first (or whatever you need to make them bigger than 1), but I think your problem is really somewhere else.
> 1 votes

---
Tags: geometry
---


# Question
Title: Having a problem with referencing Farseer into my Monogame project
I am trying to load in the Farseer Physics Engine into my current Monogame project and whenever doing so, the Farseer solution will load in correctly but then when I try and reference it, it gives me an error:

I cannot find any information or anyone else that had this issue so if anyone has any tips or solutions on how to include or reference this project then I would appreciate it greatly.

# Answer
Don't use the latest version of mongame. Delete and reinstall the previous version. I think it is 3.4.
> -1 votes

---
Tags: c#, physics, monogame
---


# Question
Title: Managing Discrete Character Animation States
I'm creating a 2D game in which each possible direction of movement for the player, (Up, Down, Left, Right), has its own distinct animation, i.e., they aren't rotations of each other. Currently I am using a FSM design to manage this, but its getting messy already, and I know it will only get worse.

For example: (in Lua)

```
StateComponent = {
    states = {
        walking_left = {set_animation("walking_left")},
        walking_right = {set_animation("walking_right")},
        ...
    }
},

```

Now say I want to add attacking, the collection of states then becomes:

```
StateComponent = {
    states = {
        walking_left = {set_animation("walking_left")},
        walking_right = {set_animation("walking_right")},
        ...

        attacking_left = {...},
        attacking_right = {...},
        ...
    }
},

```

Okay, but now what about opening up a chest from each different side... This quickly becomes very complex. I read about a using a Behavior Tree, but it doesn't seem to support the discrete division of states necessary for having a different animation for walking/attacking/etc in each cardinal direction. What kind of design would be elegant and scalable for this problem? Or how else might I represent these states?

# Answer
> 1 votes
Since you asked to expand on my first part, here it is.

Currently, under `states` you save all your states, regardless of the relation between them, but we can clearly see that you can group them up to make it more organized.

So, this:

```
StateComponent = {
    states = {
        walking_left = {set_animation("walking_left")},
        walking_right = {set_animation("walking_right")},
        ...

        attacking_left = {...},
        attacking_right = {...},
        ...
    }
},

```

Becomes this:

```
StateComponent = {
    states = {
        walking = {
             left = {set_animation("walking_left")},
             right = {set_animation("walking_right")},
        },
        ...

        attacking = {
            left = { ... },
            right = { ...},
        }
        ....
    }
},

```

And then you would save two states in your code: `state type` and `state direction` (maybe word it a bit differently).

And then, you'd set the state by `stats[type][direction]` or something like that

---
Tags: animation, game-mechanics, state, fsm
---


# Question
Title: Accessing soft keyboard on Android via Monogame
I have a game built in Monogame targeting the Android and iOS platforms. I need to develop a login form for the game. I've begun to roll out my own UI components (text inputs, buttons, so forth), as I've read that there are no commonly used libraries for this purpose.

Now, I'm looking to access on the soft keyboard (for Android at the moment) but can't seem to get it working.

I've looked into the GamerServices module, but I'm pretty sure this only applies to Windows OSes.

I'm trying to implement what looks like the C# wrapper to the Android API. While debugging this code in Visual Studio 2015, the ShowKeyboard function executes without error, but the onscreen keyboard in the emulator doesn't appear.

I've added the following functions to my Android Activity class generated by Monogame, then access these functions when appropriate in-game. The code executes, but alas no keyboard.

```
    public static void ShowKeyboard()
    {
        var pView = KeyboardConfig.game.Services.GetService<View>();
        var inputMethodManager = KeyboardConfig.Application.GetSystemService(Context.InputMethodService) as InputMethodManager;
        inputMethodManager.ShowSoftInput(pView, ShowFlags.Forced);
        inputMethodManager.ToggleSoftInput(ShowFlags.Forced, HideSoftInputFlags.ImplicitOnly);
    }

    public static void HideKeyboard()
    {
        InputMethodManager inputMethodManager = KeyboardConfig.Application.GetSystemService(Context.InputMethodService) as InputMethodManager;
        inputMethodManager.HideSoftInputFromWindow(KeyboardConfig.pView.WindowToken, HideSoftInputFlags.None);
    }

```

# Answer
Instead of rolling out my own toolset for taking input, I push the users out to a non-Monogame Activity to take input and pass the results back. Works pretty well, even if the user experience is a little jagged.

I'll have to reimplement the forms for any other platforms I intend to support - but that was already a problem.

```
    // go to authentication screen
    private void launchPlatformAuthentication()
    {
        #if __ANDROID__
            var intent = new Intent(Android.App.Application.Context, typeof(ActivityAuth));
            intent.SetFlags(ActivityFlags.NewTask);
            Activity1.ActivityConfig.Application.StartActivityForResult(intent, 0);
        #endif
    }

```
> 1 votes

---
Tags: c#, android, monogame, input
---


# Question
Title: Trying to leave a trail of particle effects with a Particle system attached to an Object Unity C#
I have a particle system attached to my game object, which starts to emit particles when I press down the "W" key and stops when I release it. The particle system works fine, but when I rotate the object, the particles rotate with the object. I would like to have the particles leave behind a trail of the path of the object.

Script below:

```
public class Motor : MonoBehaviour {

public ParticleSystem EngineLeft;
public ParticleSystem EngineRight;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    if (Input.GetKey(KeyCode.W))    {
        transform.Translate(Vector3.forward * Time.deltaTime * Speed);
    }

    if (Input.GetKeyDown (KeyCode.W)) {
        EngineRight.Play ();
        EngineLeft.Play ();
    }

    if (Input.GetKeyUp (KeyCode.W)) {
        EngineRight.Stop ();
        EngineLeft.Stop ();
    }

```

# Answer
> 4 votes
Set the "Simulation Space" setting of the particle system from "Local" to "World". That way the position and rotation of the particle system (or its parents) will only affect newly spawned particles and not those already spawned.

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


# Question
Title: How to automatically generate (creative) names for stuff?
How can I get large number (100-1000-10 000) of names, that are at most average hard to spell for things like places, weapons (and NPCs).

Have a look at TES4 Oblivion or TES% Skyrim.

http://www.uesp.net/wiki/Oblivion:Places

Yes, I understand, that they have paid army of designers for years.

My questions is how this people are creating those names? Is there some hints for this, like should have at least/most this amount of letters or maybe let's create three sets of words - beginnings, middle and endings, and then take one random word from each?

Can it be automatized? Do they check, if created name means anything in any language?

This question is meant as extension for other questions like this, especially: Name generation

Above question was about NPC names, I am looking for something generic, especially for places and artifact names.

I am aware of Markov chains, but even after automatic generation, I would need a way to check, if this "sounds" good and if it means anything in nay language.

As much as second thing can be probably automatized, that first one not really.

Is there any full solution? Do we know, what kind of solution does Oblivion/Skyrim use? Most important part of this question is automatizing part.

# Answer
In one game I used this technique to generate names for procedurally generated NPCs. They are not *true* Markov chains, but follow a similar idea:

* Take a bunch of real-world names for the entities (cities, countries, male people, female people...) you want to name. When your game is inspired by a specific culture and you want to emulate the naming style in your game, you might want to do this with names from that cultural circle.
* Separate them into syllables and create three lists: Start syllables, middle syllables and end syllables.
* To generate a name, concatenate a random syllable from the start list, 0-4 syllables from the middle-list and one syllable from the end-list.

I tested this by having the algorithm generate a list of 100 names. Here is a sample from my "male NPC name" generator. It will sometimes generate names which sound like a real word in some language (you can spot some English words in the list), but considering that there are literally *thousands* of languages in the world, this can hardly be avoided (not even by real authors). It's also not as much of a problem as you would think, because people named like things isn't that uncommon in the real world.

When I make up a name for something myself, I usually enter it into Google and see if something comes up. This also helps to not accidentally steal a name from someone else. But this is not an option for bulk generation.
> 8 votes

# Answer
Markov chains provide fully qualified new names if fed with the right input in my experience. I adapted the code of this generator for my needs and it works like a charm.

Regarding TES, as this world is finite and has a fixed number of places, NPCs etc. every name can be made up by hand or randomly generated and then checked manually. I do not know how they do it, but the definitely do not face the problems of randomly generated names. Much more interesting is how it is done in No Man's Sky as they need new generated names every few minutes. That's closer to the problem you are facing I suppose.
> 5 votes

---
Tags: procedural-generation
---


# Question
Title: Restrict render in Blender is not working
I click "Restrict renderability", so that everything except the item I want to export is grayed out. However, it still exports lights and everything when I import it into Unity.

How can I fix this?

# Answer
> 3 votes
The render visibility option only affects what is visible when blender renders a final image, it isn't used when exporting objects.

If you give unity your blend file, it can do the export/import for you and shouldn't import lights and cameras, see the unity manual for the full list.

If you are exporting manually, you should find options to control what is exported, the fbx exporter has an option that lets you turn off the export of cameras and lights, while the obj exporter can be set to export only selected objects.

\- fbx options

\- obj options

---
Tags: unity, blender
---


# Question
Title: UE4 C++ Variables in my custom class change for no reason after a while
I've made a class extending UObject to store player stats, and provide some static utility functions and variables. It gets instantiated in my PlayerController:

```
APuzzleProjectPlayerController::APuzzleProjectPlayerController() {
    playerStats = NewObject<UPlayerStats>();
    playerStats->setStrenght(4);
    playerStats->setSpeed(1);
    playerStats->setStamina(1);
}

```

Everything compiles fine and the game logic works perfectly except for the fact that after a while (1 or 2 minutes of gaming) the non-static private variables change their value.

In the following code I've added some Dummy variables just to make sure that nothing was accessing/changing them during execution. They are only accessed by GEngine-\>AddOnScreenDebugMessage to show their value.

```
UCLASS()
class PUZZLEPROJECT_API UPlayerStats : public UObject
{
    GENERATED_BODY()

    // Stats Const
    static const uint8 MIN_STAT_VALUE = 1;
    static const uint8 MAX_STAT_VALUE = 7;

    // Stamina Pool Const
    static const uint8 BASE_STAMINA_POOL = 199;
    static const uint8 STAMINA_POOL_STEP = 8;
    static const uint8 STAMINA_RECOVERY_VALUE = 3;

    // Stats
    uint8 strenght = 1; // Becomes 221
    uint8 speed = 1; // Becomes 221
    uint8 stamina = 1; // Becomes 221
    uint8 staminaPool = BASE_STAMINA_POOL; // Updated by a function, still unconsistent after a while since stamina dependent

    // These are never modified by my code, but get modified after a while like the Stats variables
    uint8 dummyA = 3; // Becomes 221
    const uint8 dummyB = 4; // Becomes 221
    int dummyC = 5; // Becomes -572662307
    const int dummyD = 6; // Becomes -572662307

    public:
    enum SpeedSteps {WALK, RUN, SPRINT};
    static const float TIMER_PRECISION;
    static const uint8 MIN_STAMINA_POOL = 0;
    static const uint8 MAX_STAMINA_POOL = 255;
    static const float DELTATIME_STAMINA_RECOVERY;
    static const float DELTATIME_STAMINA_LOSS;
    static const uint8 STAMINA_RUN_LOSS = 2;
    static const uint8 STAMINA_SPRINT_LOSS = 32;

    UPlayerStats();
    uint8 getStrenght();
    uint8 getSpeed();
    uint8 getStamina();
    uint8 getStaminaPool();
    static uint8 getStaminaDelta(SpeedSteps speedStep, bool isIdle);
    void setStrenght(uint8 value);
    void setSpeed(uint8 value);
    void setStamina(uint8 value);
};

```

Now, I'm a bit rusty with C++ (I work as Java & PL/SQL programmer), but I really don't know what's wrong here. The variables in the other three classes I have (default third person game mode, character and custom player controller) don't seem to be affected by the same issue.

Thanks for any suggestion you might have.

# Answer
> 2 votes
Sounds like your data is being overwritten by 0xDD, 221 is the decimal representation of 0xDD, and -572662307 is the signed integer representation of 0xDDDDDDDD.

Objects created by NewObject take place in garbage collection. I think you don't have any other references to your playerstats that the garbage collector is aware of so it's deleted, leaving you with some dangling pointers. Use UPROPERTY() to make it see a reference.

See also: https://wiki.unrealengine.com/Garbage\_Collection\_%26\_Dynamic\_Memory\_Allocation for more detail.

# Answer
> 0 votes
Make sure all member variables that point to instances of `UPlayerStats` are decorated with the `UPROPERTY` macro:

```
UPROPERTY()
UPlayerStats* playerStats;

```

This includes the variable you are assigning to in the `NewObject` call in your sample code.

Unreal implements a garbage collector, and that collector cannot "see" member variables that are not not marked with `UPROPERTY`, so it's likely your object is being garbage collected after a few frames.

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


# Question
Title: Unity3D, How do I press one key and then cant press another key while the one is pressed?
I am making a horror game, and I want to press a key to look up while I am idle, that i've done but if I press the W key it stands in idle but floating forward. How can I disable the W key while I press the F key to look up ? Everything works fine I can press F and the LookUp Animation is being played and if KeyUp on F the Animation goes back to Idle. My problem is if I am in LookUp Animation when I press F, I can also press W to go forward but its floating not walking. I want to deactivate this function so I can just press F when I am Idle.

Thanks for help.

my Script:

---

```
public float speed = 10f;
public Rigidbody rgb;
public Animator anim;
bool walk = false;

// Use this for initialization
void Start ()
{
    rgb.GetComponent<Rigidbody> ();
    anim = GetComponent<Animator> ();
}

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

    float move = Input.GetAxis ("Vertical");
    anim.SetFloat ("Speed", move);

    if (Input.GetKey (KeyCode.W) | walk == true)
    {
        rgb.transform.position -= new Vector3(0, 0, 1) * speed * Time.deltaTime;
        Debug.Log("Walking");
    }
    else
    {
        walk = false;
        Debug.Log("Idle");
    }

    if (Input.GetKey (KeyCode.F))
    {
        anim.SetBool("LookUpIdle", true);
        rgb.transform.position = transform.position;
    }
    else
    {
        anim.SetBool("LookUpIdle", false);
    }

}

```

}

# Answer
Mind enclosing your walk code in if clause to check wether the F key is held down. Also be sure to check the keyDown and keyUp events for triggering LookUp.

```
void Update()
{
    float move = Input.GetAxis ("Vertical");
    anim.SetFloat ("Speed", move);
    if(!Input.GetKey(KeyCode.F))//Add this line to perform movement only if the F key isn't pressed
    {
        if (Input.GetKey (KeyCode.W) | walk == true)
        {
            rgb.transform.position -= new Vector3(0, 0, 1) * speed * Time.deltaTime;
            Debug.Log("Walking");
        }
        else
        {
            walk = false;
            Debug.Log("Idle");
        }
    }

    if (Input.GetKeyDown (KeyCode.F))
    {
        anim.SetBool("LookUpIdle", true);
        rgb.transform.position = transform.position;
    }
    else if (Input.GetKeyUp (KeyCode.F))
    {
        anim.SetBool("LookUpIdle", false);
    }
}

```
> 1 votes

---
Tags: unity, c#, animation, logic
---


# Question
Title: Pointer deleted by object manager on next frame
I have a class named GameManager, which job is to manage GameObject allocation and deallocations. The thing is, every GameObject can interact with each other, so there's a possibility that a pointer to another GameObject in a GameObject's script becomes deleted by manager the next frame. (Something like a missile, the missile's target may be already destroyed by another object)

I can't use shared pointer because there are times where a GameObject should be removed, but can't be removed because a GameObject won't release. What is a good design pattern to tackle this problem? Or should GameObject check for null each time?

# Answer
There are two facets to this issue:

First, you may want to defer destruction until the end of the frame (or at least until some time after you know all your inter-object interactions will have been resolved). This is fairly straightforward: when you "destroy" an object, put that object into a "pending kill" set and at the end of the frame, iterate the set, actually destroying every object and then emptying the set.

Second is the issue of outstanding references to dead objects from live ones. This is a much larger design issue for object lifetime and there's a lot of ways you can handle it. You need to decide certain things about how your objects will function to choose a solution.

* Does a reference to an object never need to keep that object alive?
* Does a reference to an object always need to keep that object alive?
* Does a reference to an object *sometimes* need to keep an object alive? Under what conditions, and are those conditions determined at compile time or at run time?
* Or you simply need to be able to tell if a referenced object *has been* destroyed and consequently prevent accessing it?

(When I say "keep alive" I mean doing so simply by virtue of the reference existing. Whether or not you can request destruction of that object via that reference is another thing altogether.)

If a reference never needs to keep an object alive, you are in the ideal world. This probably means that reference is the only reference to the object, though, and the containing objects entirely controls its lifetime. If you are extremely rigid about the way your objects are created and destroyed you can make this work (always ensuring objects which have non-lifetime-preserving references are destroyed before the things they reference are, in and inside-out fashion), but it takes discipline.

If a reference must always keep an object alive, a reference-counting approach is potentially what you want to look at. You will also want to include some way of making non-counting references (so called "weak pointers," like C++'s `std::weak_ptr`) to break cycles or otherwise create non-counting references. You can also look into solutions involving garbage collection, although in some languages (like C++) this would be quite an intensive option. It's possible though (Unreal does it).

If a reference *sometimes* needs to keep an object alive and those conditions are determined at compile time, a reference-counting approach can still be used, you just choose a weak reference for this instance. If the conditions are determined at compile time, you'd have to use a more complex reference counting approach where a reference can switch from counting to non-counting, and I'd argue this is a sign you need to make your ownership policies more rigid instead.

If a reference simply needs to be able to *determine* if a thing is destroyed, you're probably in the second-best scenario. This is where you should try to be, in my opinion (reference counting makes overall determinism related to destruction harder to reason about). There are various *handle-based* solutions to object management that can work here. The crux of this approach is to keep all your objects in one place along with some metadata that includes a "salt" value, and hand out handles which reference those objects. The handle holds a pointer or index that refers to the actual object, and a salt value of its own. Whenever you actually delete an object, you increment the salt for that object's slot in the object storage. That way allows handles to test their salt against the current salt in storage and if they differ, the handle refers to a dead object.

There are various structures that can be used to implement this, such as innumerable variations on a slot map or related data structures like `plf::colony` (which can be conceptually adapted to support salted handles instead of iterators or bare pointers).
> 2 votes

---
Tags: c++, design-patterns
---


title: Scene2D Actor walking animation?

text:
# Question
Title: Scene2D Actor walking animation?
I used to extend my Player/Entity class with Sprite, that way I could create a walking animation using SetRegion and super(stilldown.getKeyFrame(0));

I've recently started porting everything over to Scene2D and I use Actors now. I do not know how to use this way of animation anymore, does anybody have a guess how I could do this?

```
        animationtime += delta;
    if(dir == Direction.DOWN){
        setRegion(velocity.y == 0 ? stilldown.getKeyFrame(animationtime) : walking.getKeyFrame(animationtime));
    }else if (dir == Direction.UP){
        setRegion(velocity.y == 0 ? stillup.getKeyFrame(animationtime) : walkingup.getKeyFrame(animationtime));
    }else if (dir == Direction.RIGHT){
        setRegion(velocity.x == 0 ? stillright.getKeyFrame(animationtime) : walkingright.getKeyFrame(animationtime));
    }else if (dir == Direction.LEFT){
        setRegion(velocity.x == 0 ? stillleft.getKeyFrame(animationtime) : walkingleft.getKeyFrame(animationtime));
    }

```

This is how I'd initialise the animation

```
    playeratlas = new TextureAtlas("overworld/player/playersheet.pack");

    Animation walking;
    Animation walkingup;
    Animation walkingright;
    Animation walkingleft;

    Animation stilldown;
    Animation stillup;
    Animation stillright;
    Animation stillleft;

    walking = new Animation(1 / 4f, playeratlas.findRegions("walkingdown"));
    walkingup = new Animation(1 / 4f, playeratlas.findRegions("walkingup"));
    walkingright = new Animation(1 / 4f, playeratlas.findRegions("walkingright"));
    walkingleft = new Animation(1 / 4f, playeratlas.findRegions("walkingleft"));

    stilldown = new Animation(1 / 4f, playeratlas.findRegions("stilldown"));
    stillup = new Animation(1 / 4f, playeratlas.findRegions("stillup"));
    stillright = new Animation(1 / 4f, playeratlas.findRegions("stillright"));
    stillleft = new Animation(1 / 4f, playeratlas.findRegions("stillleft"));

    walking.setPlayMode(Animation.PlayMode.LOOP);
    walkingup.setPlayMode(Animation.PlayMode.LOOP);
    walkingright.setPlayMode(Animation.PlayMode.LOOP);
    walkingleft.setPlayMode(Animation.PlayMode.LOOP);

    stilldown.setPlayMode(Animation.PlayMode.LOOP);
    stillup.setPlayMode(Animation.PlayMode.LOOP);
    stillright.setPlayMode(Animation.PlayMode.LOOP);
    stillleft.setPlayMode(Animation.PlayMode.LOOP);

```

For now I only use a static image for my Actor

```
Sprite text = new Sprite(new Texture(Gdx.files.internal("overworld/player/placeholder.png")));

```

Now I draw it like this

```
public void draw(Batch batch, float ParentAlpha){
    text.draw(batch);
}

```

I would greatly appreciate help, I'm new to Scene2D and I can't find much on it.

# Answer
> 1 votes
If I understand correctly, your are wondering how to draw from the animation when using an Actor. It is very similar to how you were doing it before.

The getKeyFrame() method in the Animation class returns a TextureRegion so, rather than passing this to setRegion(), you have to draw it yourself. Don't worry, its pretty simple:

```
public void draw(Batch batch, float ParentAlpha){
    TextureRegion currentFrame = currentAnimation.getKeyFrame(animationtime);
    batch.draw(currentFrame, x, y, width, height);
}

```

It is probably worth looking into the Batch class to see all of the overloads of draw(), you can add other parameters such as rotation and scaling.

The best place to update your animation time variable is by overriding the Actor's act() method

```
@Override
public void act(float deltaTime)
{
    super.act(deltaTime);
    animationTime += deltaTime;
}

```

make sure that you are calling act on your stage in the render loop, otherwise, the Actor's act wont be called.

# Answer
> 1 votes
```
// Take your **animation** created for your sprite batch and call this:
public class AnimatedActor extends Image
{
  private float stateTime = 0;
  Animation animation;
  public AnimatedActor(Animation animation) {
    super(animation.getKeyFrame(0));
    this.animation = animation;
  }
  @Override
  public void act(float delta)
  {
 ((TextureRegionDrawable)getDrawable()).setRegion(animation.getKeyFrame(stateTime+=delta, true));
    super.act(delta);
  }
}
/* Render with:
    // if you change direction you will need logic for myAnimatedActor.remove and stage.addActor(myAnimatedActor);
    animationFrames = walkSheetArray[moveDirection];
    animation = new Animation(1f / 5f, animationFrames);
    myAnimatedActor = new AnimatedActor(animation);
    // stage.addActor(myAnimatedActor);
    myAnimatedActor.setPosition(posX, posY);
    stage.act(Gdx.graphics.getDeltaTime());
    stage.draw();
*/

```

---
Tags: libgdx, animation, sprites, scene2d
---


# Question
Title: What image resoluiton for sprites in 2D mobile game?
I am an experienced iOS developer, however I have never worked on games before. We are planning to make a mobile game using Unity 3D.

Our graphics designer needs to know what resolution should he design our sprites in? I know that we will have to use different sizes for the different screen resolutions, but my question is:

**What is the largest resolution we will need the sprites to be in, considering future-proofness?**

OR

**Shall we go with vector graphics?**

We are targeting tablets as well!

# Answer
If cost and time-wise `svg` is the same to you (and your graphic designer) as a raster sprite, then you should go with `svg`.

`Svg` is not necessarily easy to use in Unity natively nor is it supported out of the box. If you want to do this, Unity Answers recommends these:

But, if it's in `svg` you can always rescale them and export them to whatever size you need as raster later when you do decide on a resolution.

If you're worried about the added implications of making an `svg` (cost, time, etc) and want to just go with raster you need to consider the resolution and dpi of your target devices. If you don't have target devices yet, you should probably do a trade study. This might entail:

1. Taking the most popular phones on the market
2. Noting their resolutions
3. Comparing your assets scale in the game with how much of the resolution they will take up
4. Multiply by two to ensure that you have crisp assets when rendered in the game.

This is kind of a cost, time and quality trade-off and is project specific which is something you need to decide on. There is no one right answer but many rule of thumbs that will help you decide.
> 1 votes

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


title: Array empty while performing a for-loop

text:
# Question
Title: Array empty while performing a for-loop
I'm working on a massive selection via a 2D rectangle in my RTS project. For this, I Interate over an array of units, that are within the camera screen.

But somehow, in the loop, the n-th item does seem to contain nothing. If I call `Debug.Log(UnitsOnScreen[0].ToString());` before the loop, I get this in the console:

> Unit\_1(UnityEngine.GameObject) UnityEngine.Debug:Log(Object)

Which basically indicates, that the array does contain something. But in the loop it doesn't even perform `Debug.Log("Test");`

Any Ideas how I can get rid of this problem?

```
 void LateUpdate()
    {
        UnitsInDrag.Clear();
        if ((UserIsDragging || FinishedDragOnFrame) && UnitsOnScreen.Count > 0){
            Debug.Log(UnitsOnScreen[0].ToString()); // returns something
            for (int i = 0; i > UnitsOnScreen.Count; i++)            {
                Debug.Log("Test"); // no output
                //error somewhere over here
                Debug.Log(UnitsOnScreen[i].ToString());
                GameObject UnitObj = UnitsOnScreen[i] as GameObject;
                Unit UnitScript = UnitObj.GetComponent<Unit>();
                GameObject SelectedObj = UnitObj.transform.FindChild("Selection").gameObject;
                if (!UnitAlreadyInDraggedUnits(UnitObj))
                {
                    if (UnitInsideDrag(UnitScript.ScreenPos))
                    {
                        SelectedObj.SetActive(true);
                        UnitsInDrag.Add(UnitObj);
                    }
                    else
                    {
                        if (!UnitAlreadyInDraggedUnits(UnitObj))
                            SelectedObj.SetActive(false);
                    }
                }
            }
        }
        if (FinishedDragOnFrame)
        {
            FinishedDragOnFrame = false;
            PutDraggedInSelectedUnits();
        }
    }

```

# Answer
I'm sure you by

```
for (int i = 0; i > UnitsOnScreen.Count; i++)

```

meant

```
for (int i = 0; i < UnitsOnScreen.Count; i++)

```
> 3 votes

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


# Question
Title: Unity2D: The name `EventSystems' does not exist in the current context
I am having a problem with errors that "The name `EventSystems` does not exist in the current context". I made sure that I added `using UnityEngine.EventSystems`, so I'm a bit dumbfounded. Anyway, this is my code:

```
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;  // As you can see, its "using" correctly.

public class PlayerMovement : MonoBehaviour {

    public GameObject currentSelectedGameObject;

    void Update () {
        if (Input.GetMouseButtonDown (0)) {
            if (!EventSystems.EventSystem.currentSelectedGameObject ()) {
                Vector3 mousePosition = Input.mousePosition;
                mousePosition.z = 10; // distance from the camera
                target = Camera.main.ScreenToWorldPoint (mousePosition);
                target.z = transform.position.z;
            }
        }

    transform.position =
            Vector3.MoveTowards (transform.position, target, speed * Time.fixedDeltaTime);
}

```

# Answer
When you are "`using`" something, your effectively telling your compiler 'I'm already looking in this directory of libraries'.

When you tell it `using EventSystems`, you can no longer use `EventSystems`, because your already using `EventSystems`. If that makes sense.

Write your `if` statement without the initial `EventSystems`.

```
if (!EventSystem.currentSelectedGameObject ()) {
    Vector3 mousePosition = Input.mousePosition;
    mousePosition.z = 10; // distance from the camera
    target = Camera.main.ScreenToWorldPoint (mousePosition);
    target.z = transform.position.z;
}

```

Alternatively, get rid of `using EventSystems`. It is a pretty early topic you should be familiar, with as a programmer, so you may want to read more at Microsoft's C# Programming Guide to get a better understanding of it.
> 1 votes

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