# Question
Title: I want to render a texture2d on to the screen in unity, how do I do this?
So I have modified a texture in C# by removing all of its white pixels, now I want to render it on the screen in unity so that later I can use it as a terrain where I can make my sprite walk. So far, I have tried using Graphics.DrawTexture, GUI.DrawTexture, I have tried setting it equal to the main texture of a sprite, but so far, I have not been able to display it on the screen. Is there a way to do this? Basically, I want to use the following code (Processing based on Java) but in C# in Unity.

```
// Provides methods for determining solid/empty pixels, and for removing/adding solid pixels
class Terrain {
  PImage img; // the terrain image

  int destructionRes; // how wide is a static pixel

  // Constructor
  Terrain(PImage pic, int destructionRes) {
    this.destructionRes = destructionRes;

    // Copy pic over to img, replacing all pink (RGB: 255,0,255) pixels with transparent pixels
    img = createImage(pic.width, pic.height, ARGB);
    img.loadPixels();
    pic.loadPixels();
    for (int i = 0; i < img.width * img.height; i++) {
      if (red(pic.pixels[i]) == 255 && green(pic.pixels[i]) == 0 && blue(pic.pixels[i]) == 255)
        img.pixels[i] = color(0,0);
      else
        img.pixels[i] = pic.pixels[i];
    }
    img.updatePixels();
  }

  // Render terrain onto the main screen
  void draw(float x, float y) {
    image(img, x,y);
  }

  // Return the terrain's width and height
  public int width() {
    return img.width;
  }
  public int height() {
    return img.height;
  }

  // Update - apply pixels[]'s changes onto the image
  void update() {
    img.updatePixels();
  }

  // Determine if a pixel is solid based on whether or not it's transparent
  boolean isPixelSolid(int x, int y) {
    if (x > 0 && x < img.width && y > 0 && y < img.height)
      return img.pixels[x + y * img.width] != color(0,0);
    return false; // border is not solid
  }

  // Color in a pixel, making it solid
  void addPixel(color c, int x, int y) {
    if (x > 0 && x < img.width && y > 0 && y < img.height)
      img.pixels[x + y * img.width] = c;
  }
  // Make a pixel solid
  void removePixel(int x, int y) {
    if (x > 0 && x < img.width && y > 0 && y < img.height)
      img.pixels[x + y * img.width] = color(0,0);
  }
  // Get a pixel's color
  color getColor(int x, int y) {
    if (x > 0 && x < img.width && y > 0 && y < img.height)
      return img.pixels[x + y * img.width];
    return 0;
  }

  // Find a normal at a position
  float[] getNormal(int x, int y) {
    // First find all nearby solid pixels, and create a vector to the average solid pixel from (x,y)
    float avgX = 0;
    float avgY = 0;
    for (int w = -3; w <= 3; w++) {
      for (int h = -3; h <= 3; h++) {
        if (isPixelSolid(x + w, y + h)) {
          avgX -= w;
          avgY -= h;
        }
      }
    }
    float len = sqrt(avgX * avgX + avgY * avgY); // get the distance from (x,y)
    return new float[]{avgX/len, avgY/len}; // normalize the vector by dividing by that distance
  }
}

```

Basically I want to implement that code (in Processing) in C# in Unity. I want to code it so that Unity does the same thing. I only need help with displaying the Texture2D on the scene, but if the whole code I am trying to apply helps, then I am posting it here. Also, this is what I have done so far:

```
using UnityEngine;
using System.Collections;

public class ImageBring : MonoBehaviour
{
    public Texture2D Layout;
    void Start()
    {
        Texture2D Ground = new Texture2D(Layout.width,Layout.height);
        for (int x = 0; x < Layout.width; x++)
        {
            for (int y = 0; y < Layout.height; y ++)
            {
                if (Layout.GetPixel(x, y) == Color.white)
                {
                    Color color = new Color();
                    color.a = 0f;
                    Ground.SetPixel(x, y, color);

                }
                else
                {
                    Ground.SetPixel(x, y, Layout.GetPixel(x, y));
                }
            }
        }
        Ground.Apply();

    }
}

```

# Answer
Well, you are on the right track. You can do this with keep in minds something. You must have a texture with read/write permission. You can do it easily by selecting it and change its *Texture Type* to *Advance*.

Don't forget to mark check on *Read/Write Enabled*

Second thing is you must have a *Material* in your script on which you'd modify its texture so the models having that material attached will get effected.

Note that material must have a shader that supports *Transparency*. For example you can set *Unlit/Transparent*.

Now you can execute your code and apply the modified texture in that material.

Here is the code,

```
using UnityEngine;
using System.Collections;

public class ModifyTexture : MonoBehaviour
{
    public Texture2D _layout; // Your current texture
    public Material _mat; // Material attached to your Gameobject (Terrain, quad or anything else)

    void Start ()
    {
        // Your operation
        Texture2D ground = new Texture2D (_layout.width, _layout.height);
        for (int x = 0; x < _layout.width; x++) {
            for (int y = 0; y < _layout.height; y++) {
                if (_layout.GetPixel (x, y) == Color.white) {
                    Color color = new Color ();
                    color.a = 0f;
                    ground.SetPixel (x, y, color);

                } else {
                    ground.SetPixel (x, y, _layout.GetPixel (x, y));
                }
            }
        }
        ground.Apply ();

        // Applying modified texture to the material
        _mat.mainTexture = ground;
    }

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

    }
}

```

Hope this helps.
> 1 votes

---
Tags: c#, unity, processing, rendertexture
---


# Question
Title: Get pressed character in LWJGL (Ignoring modifier keys)
I have a basic text field setup in LWJGL, however pressing any modifier keys (Shift, F1-19, Page Up, etc.) inputs a space into the text field. How would I ignore those characters? Here's some code so far.

Note: `value` is a string variable

```
while (Keyboard.next()) {
    if (Keyboard.getEventKeyState()) {
        if (Keyboard.getEventKey() == Keyboard.KEY_BACK) { //Backspace
            if (value.length() > 0) {
                value = value.substring(0, value.length() - 1);
            }
        } else if (/* Character is not a modifier key*/) {
            value += Keyboard.getEventCharacter();
        }
    }
}

```

# Answer
Welp, seems a bunch of RegEx works...

```
if (Pattern.matches("[A-Za-z0-9\\s_\\+\\-\\.,!@#\\$%\\^&\\*\\(\\);\\\\/\\|<>\"'\\[\\]\\?=]", String.valueOf(Keyboard.getEventCharacter()))) {
    value += Keyboard.getEventCharacter();
}

```
> 0 votes

# Answer
You need to check for `Character.isLetterOrDigit(char)`, and if it returns false, skip it.
> 1 votes

# Answer
Add this where you add the code to the string:

```
value += String.valueOf(Keyboard.getEventCharacter());
value = value .replaceAll("[^\\w\\s\\]","");

```
> 0 votes

---
Tags: java, lwjgl, input, text, keyboard
---


# Question
Title: How can I get information from a function
Okay, so if I use this code to randomly spawn balls at the top of the screen, how do i get them to move down:

```
var max_bollar = 10;
var i = 0;
var timecounter = 0;
var bollarcounter = 0;
var spawn_delay = 200;
var min_spawn_delay = 25;
var max_spawn_delay = 500;

function spawn(i)
{
    var boll = {x: random(totalWidth), y: random(totalHeight)}
    circle( boll.x, 10, 10, "blue");
    timecounter = 0;
    bollarcounter++;
    max_spawn_delay = ( random(max_spawn_delay - min_spawn_delay ) + min_spawn_delay );
}

function update()
{
    timecounter += 1;
    if(timecounter == spawn_delay && bollarcounter < max_bollar) spawn(bollarcounter);
}

```

I want them to be falling from the top of the screen and the player has to dodge the balls falling. How do I make the balls move or rather how do I get the information of each ball? So I can Add y cordinates and stuff. (I know i need to Add a clearScreen to make the balls move)

I want to make something like this:

```
Boll.y += 10;

```

# Answer
> 1 votes
Create an array to hold all the balls:

```
var balls = [];

```

When you spawn a ball, include it on the list:

```
function spawn(i)
{
    var boll = {x: random(totalWidth), y: random(totalHeight)}
    circle( boll.x, 10, 10, "blue");
    timecounter = 0;
    bollarcounter++;
    max_spawn_delay = ( random(max_spawn_delay - min_spawn_delay ) + min_spawn_delay );

    // Include the ball on the list
    balls.push(boll);
}

```

Now is very easy to control them, just iterate the array of the balls in the `update` method and do the changes you want:

```
for (var i = 0; i < balls.length; i++) {
    balls[i].y += 5;
};

```

# Answer
> 0 votes
1. Add the balls to the list
2. in `update()` iterate over the list and update each ball's `y` position

---
Tags: javascript, game-mechanics
---


# Question
Title: GL_TEXTURE_MAX_LEVEL equivalent on DirectX
I'm trying to mix atlas and mipmapping for a kind of Minecraft editor I'm doing. Everything looks good until I reach the smaller mipmaps of the atlas texture, where obviously all the textures are mixed into one, looking horrible at the distance.

With OpenGL I'd use glTexParameteri(GL\_TEXTURE\_2D, GL\_TEXTURE\_MAX\_LEVEL, n); to avoid this problem, but I'm unable to find the DirectX equivalent. Is it possible to do this in DirectX?

Thanks in advance

# Answer
Of course, hours searching for clues, and few minutes after posting the question I find the answer :P

Most similar way to do what I want to do is MaxLOD of D3D10\_SAMPLER\_DESC:

https://msdn.microsoft.com/en-us/library/bb172415%28VS.85%29.aspx
> 1 votes

---
Tags: directx
---


# Question
Title: 2D camera perspective projection from 3D coordinates -- HOW?
I am developing a camera for a 2D game with a top-down view that has depth. It's almost a 3D camera. Basically, every object has a Z even though it is in 2D, and similarly to parallax layers their position, scale and rotation speed vary based on their Z.

I guess this would be a perspective projection.

But I am having trouble converting the objects' 3D coordinates into the 2D space of the screen so that everything has correct perspective and scale. I never learned matrices though I did dig the topic a bit today. I tried without using matrices thanks to the Wikipedia article on perspective projection but every attempt gave awkward results.

I'm using ActionScript 3 and Flash 11+ (Starling), where the screen coordinates work like this: Left-handed coordinates system illustration

**I can explain further what I did if you want to help me sort out what's wrong, or you can directly tell me how you would do it properly.** In case you prefer the former, read on.

These are images from the Wikipedia article linked above, showing the formulas I used:

The long formula is greatly simplified because I believe a normal top-down 2D camera has no X/Y/Z rotation values (**correct?**). Then it becomes d = a - c. Still, I can't get it to work.

Maybe you could explain what numbers I should put in a(xyz), c(xyz), theta(xyz), and particularly, e(xyz)? I don't quite get how e is different than c in my case. c.z is also an issue to me. If the Z of the camera's target object is 0, should the camera's Z be something like -600? ( = focal length of 600) Whatever I do, it's wrong.

I only got it to work when I used arbitrary calculations that "looked" right, like most cameras with parallax layers seem to do, but that's fake! If I want objects to travel between Z layers I might as well do it right.

# Answer
Those formulas look crazy. Perspective projection just means dividing each object's XY position and size by its Z distance from the camera. Then you scale the resulting values to get the desired field of view. This is assuming the camera is located at the origin and the Z axis points into the screen, so do this after any camera rotation/translation has been applied.

I'm not sure how helpful this will be to you, but you might want to look at the projection matrix formula shown on this page from the Direct3D API documentation. In D3D and similar APIs, perspective projection is done by multiplying a point like \[x, y, z, 1\] by this matrix, then dividing the result by its fourth component (see What does the graphics card do with the fourth element of a vector?). Again, this is done after any camera rotation/translation are applied.
> 2 votes

# Answer
Although you state that you want perspective projection, I would first try orthographic, since it is surprisingly simple and might just give you the type of effect you're looking for.

For this to work, you just need to keep track of the center of the object (`x`,`y`, and `z`) and the distance from the camera to the near clipping plane. Then to translate those 3D coordinates into 2D space your need the following formula:

```
f(z, v) = v/(v+z)
* Where f is the size ratio to the original sprite aka size factor
    and v is the distance to the near clipping plane (trial and error value)
    and z is the distance from the near clipping plane to the object

// Example:

Assuming you have a sprite that is 2.5x1.8 units in size and 10 units away
   from the camera, and that the near clipping plane is 5 units from the camera.

depthFactor = 5/(5+10) = 0.3

renderHeight = actualHeight * depthFactor = 1.8 * 0.3 = 0.54
renderWidth  = actualWidth * depthFactor = 2.5 * 0.3 = 0.75

```

This function will give your the correct factor to scale the images by, then you can just rotate and render them in the correct coordinates, starting with the object with the highest `z` to the lowest.

A neat fact about that result, **it also works for the speed of an object.** For example, a parallax background will work with that same factor value. In theory, you could create a whole sets of artwork that is proportional to each other and use that one function to scale the size and speed of every object.

### EDIT:

Here is a quick demo that gives you a good idea of how it functions. Use the mouse to move and the scroll wheel to change the depth.

*Demo courtesy of @Stick and @JimmyBoh.*
> 0 votes

# Answer
I see this is a fairly old question but I wanted to add something to the discussion.

If I am wrong in my approach, feel free to correct me, but this has worked out well for me so far.

It looks like the previous suggestions do not take the horizon point into account, which is part of what may be missing from previous answers. The suggested changes involving the scale factor are correct inasmuch as determining how large your objects should appear:

```
drawn_x = obj.x * scale_factor
drawn_y = obj.y * scale_factor

```

However, if you're looking for a way to draw relative to a horizon, might I suggest a modification; wherein the offset is calculated, then added to the drawn\_ values of x and y.

The following pseudocode as an example:

```
horizon_x = screen_width / 2 //or wherever you've placed it
horizon_y = screen_height / 2 //again, wherever else is fine
scaleinverse = 1.0 - scale_factor //the inverse of your scale_factor

drawn_x = (obj.x * scale_factor) + (horizon_x * scaleinverse)
drawn_y = (obj.y * scale_factor) + (horizon_y * scaleinverse)

```

By ADDING `(horizon_x OR horizon_y * scaleinverse)` to your calculations, you determine the perspective's 'offset' for the object, such that it appears to move towards the vanishing point or horizon, or whatever you wish to call it.

http://jsfiddle.net/wRSLb/16/ is an example I've modified based off of a previous answer. I think I updated the fiddle instead of forking it :( I apologize for that! I left several comments which hopefully clearly outline what I did and why.

One thing I have noted with doing it in this way is that IF you decide to use 3D objects, it does sort of force you to determine an appropriate amount of "depth" for the screen. If for example your screen has screen\_width, screen\_height, and screen\_depth as instance variables, if the depth is less than `(screen_width + screen_height) / 1.5` then you will see some odd distortions towards points which are extremely far away from the vanishing point. Especially if objects are rotated/rotating AND they are far from the horizon, this will really become apparent. However, if you're simply using 2D sprites and scaling them in relation to a given vanishing point, this will give you both perspective as well as a parallax effect wherein the further an object is from the observer, the slower it appears to travel (even though its own speed constant need not change).
> 0 votes

# Answer
```
x = ((X - xFocus) / (Z / depthScale)) + xFocus
y = ((Y - yFocus) / (Z / depthScale)) + yFocus

```

The point is at (X, Y, Z) The focus is the vanishing point (xFocus, yFocus) The depthScale is how much to zoom in. Usually the average of the width and height of your screen.
> 0 votes

---
Tags: 2d, 3d, camera, projection, perspective
---


title: OpenGL GLSL vector of sampler2D

text:
# Question
Title: OpenGL GLSL vector of sampler2D
If im trying to create an obj. file loader in c++ and draw it with opengl i need to use multiple textures in the fragment shader.I know i can just use:

```
`uniform sampler2D Texture1`
`uniform sampler2D Texture2`
`uniform sampler2D Texture3`
`uniform sampler2D Texture4`

```

But i think there must be an elegant way to do it.Like a vector of samplers or something.Im asking this because i dont want to declare `n` textures in my fragment shader and type `n` if's where i test which texture i should use for the current fragment.It just looks ugly.

# Answer
> 0 votes
There is, 3d textures. It is the same as a 2d, except it has layers of textures on top if each other. You sample it with `texture3d(Sampler2d sampler, vec3 texture coord)` You still need zo create these, but you only load 1 uniform integer.

To bind a 3d texture, you bind the GL\_TEXTURE\_3D instead of a texture\_2d

---
Tags: opengl, c++, shaders
---


title: Set input relative to map rotation?

text:
# Question
Title: Set input relative to map rotation?
I'm trying to figure out how I can make the input which looks like this :

```
    // Checks if player is pressing movement keys, if is applies force to specified direction
    if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A))
    {
        //rigid.AddForce(new Vector2(-speed * Time.deltaTime, 0));
        rigid.AddRelativeForce(Vector2.left);
    }

    if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D))
    {
        //rigid.AddForce(new Vector2(speed * Time.deltaTime, 0));
        rigid.AddRelativeForce(Vector2.right);
    }

    if (Input.GetKey(KeyCode.UpArrow) && groundCheck.isGrounded == false || Input.GetKey(KeyCode.W) && groundCheck.isGrounded == false || Input.GetKey(KeyCode.Space) && groundCheck.isGrounded == false)
    {
        groundCheck.isGrounded = false;
        //rigid.AddRelativeForce(new Vector2(0, jumpPower));
        rigid.velocity = new Vector2(rigid.velocity.x, jumpPower);
    }

```

Always move according to the maps rotation.

So, even if the map were to rotate the player doesn't get inverted inputs (player is children of map, so it rotates too) :

Right now A is always to left, according to the players position, but if the player would rotate 90 degrees the input would be wrong, Left would be up/down, but I want it to still be left.

---

Here's a picture example : (Sorry for the horrible painting, I blame mouse :\> )

---

I do want the physics in the world to not change when I rotate the world.

So if the player is rotated 90 degrees it should fall to the side instead of down. :D

# Answer
The key is knowing current world rotation, you need to maintain it as you rotate e.g.:

```
double worldRotation;

void rotateWorldLeft()
{
   worldRotation = (worldRotation + 90) % 360;
}

```

then, when moving the character, just Rotate the `Vector2`s along e.g.:

```
if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A))
{
    rigid.AddRelativeForce(Vector2.left.Rotate(worldRotation));
}

```

Alternatively, if you have only few and known in advance possible rotations, you could use lookup table coupled with enum and modulus:

```
Enum Direction { Up = 0, Left, Bottom, Right }

Vector2[] Directions = { Vector2.up, Vector2.left, -Vector2.up, Vector2.right };

Direction worldOrientation; /*again keep it up-to date*/
...
if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A))
{
   rigid.AddRelativeForce(Directions[((int)Direction.Left + (int)worldOrientation) % Directions.Length]);
}

```

*note: the first solution should be preferred, casting enum to int is not the best practice - I am mentioning this only should you prefer avoid vector math completely*
> 0 votes

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


# Question
Title: Rigidbody AddForce() skipping/teleporting
I'm surprised that this issue is nowhere to be found on these forums... Well at least when I searched. So, on my setup I have created a cube and applied a Rigidbody to the object with the following C# script:

```
using UnityEngine;
using System.Collections;

public class Movement : MonoBehaviour {
    Rigidbody movement;
    float distToGround;
    bool doubleJump=false;
    void Start() {
        movement = GetComponent<Rigidbody>();//Initialize movement as their rigidbody
        distToGround = GetComponent<Collider>().bounds.extents.y;//Get the distance from the user to the ground
    }
    void Update() {

        /*If they aren't moving the horizontal or vertical axes, cancel out their velocity.*/
        if(Input.GetAxis("Horizontal")==0&&isGrounded()) movement.velocity = new Vector3(0, movement.velocity.y, movement.velocity.z);
        if(Input.GetAxis("Vertical")==0&&isGrounded()) movement.velocity = new Vector3(movement.velocity.x, movement.velocity.y, 0);

        /*Horizontal Movement*/
        if(Input.GetAxis("Horizontal")>0) movement.velocity = new Vector3(5, movement.velocity.y, movement.velocity.z);
        if(Input.GetAxis("Horizontal")<0) movement.velocity = new Vector3(-5, movement.velocity.y, movement.velocity.z);

        /*Vertical Movement*/
        if(Input.GetAxis("Vertical")>0) movement.velocity = new Vector3(movement.velocity.x, movement.velocity.y, 5);
        if(Input.GetAxis("Vertical")<0) movement.velocity = new Vector3(movement.velocity.x, movement.velocity.y, -5);

        /*Jumping and Falling*/
        if(Input.GetButtonDown("Jump")&&isGrounded()) Jump();//For jumping
        if(!isGrounded()) {//If they are in the air
            Gravity();//They're free... free falling!
            if(Input.GetButtonDown("Jump")&&doubleJump) {//If they jumped once
                if(Input.GetAxis("Horizontal")==0&&Input.GetAxis("Vertical")==0) {//And they aren't moving
                    Jump(); doubleJump=false;//Double Jump
                }
                else if(Input.GetAxis("Horizontal")>0) {//Otherwise, if they're trying to dodge right...
                    movement.AddForce(10, 0, 0, ForceMode.Impulse); doubleJump=false;//Dodge Right!
                    print("Dodged!");
                }
            }
        }
        if(isGrounded()) doubleJump=true;//Reset Double Jump bool
    }

    void Gravity() {
        movement.AddForce(movement.velocity.x, -20, movement.velocity.z);//Simply push them down consistently
    }
    void Jump() {
        movement.velocity = Vector3.zero;
        movement.velocity = new Vector3(movement.velocity.x, 15, movement.velocity.z);//Simply push them up consistently
    }
    bool isGrounded() {
        return Physics.Raycast(transform.position, -Vector3.up, distToGround + 0.1f);//returns whether or not the object is grounded
    }
}

```

Everything works fine in this code except for the code that allows them to dodge mid-air. Whenever I perform a jump successfully and jump again without pressing an arrow key, it double jumps as expected.
Whenever I dodge right, I noticed that the object seemed to "teleport" or "skip" in the direction a bit instead of actually applying the force. The more force I apply, the more it skips.
Why is my code executing it in this way? Is it a glitch with Rigidbody or is it a problem with my code that I'm not realizing?

# Answer
> 4 votes
This might be the correct expected behaviour for the code you've written. Let's run through some math.

I'll assume for the moment that you're using Unity's default FixedUpdate rate of 50 Hz and that your character has a mass of 1.

If I press right on my stick (on the ground), my character gets an x velocity of **5 m/s**.

If I do this in the air, then since the Gravity method applies lateral forces too (contrary to the comment which only mentions "downward" force) then they get a bonus of `velocity.x * Time.fixedDeltaTime/movement.mass`, for a net x velocity of **5.1 m/s**.

If I dodge, then we also apply an impulse of 10 newton seconds, which divided by our mass instantaneously raises the x velocity to **15.1 m/s**, almost triple our normal speed, for *one step*. The very next frame, because `doubleJump == false`, we don't run the dodge code again, so the velocity gets stomped back to 5.1 by the preceding lines.

```
Moment                   x Travel since previous frame
----------------------------------------------------
On ground stationary                  0
Start pressing right                  0.1
Jump                                  0.102
Dodge                                 0.302
Frame after dodging                   0.102

```

So, we have one frame where we jump triple our normal frame-to-frame distance, before resuming our typical speed. If we apply more force, or use a character with less mass, this jump gets bigger, but without any change in x velocity in the subsequent frame. That sounds consistent with your description of teleporting to the right.

The reason it looks like it's not applying the force is that you are overwriting this dodge velocity in the very next frame. In fact, you're doing that in `Update()` which will sometimes get called multiple times between physics steps, so there's the possibility you might get no dodge at all!

You need to be very judicious about when to set an object's velocity versus applying an incremental change \- it's very easy to break expected physics this way.

So, recommendations to get more predictable, intuitive movement:

* keep your physics manipulation in FixedUpdate, so you don't accidentally double-up or skip physics effects depending on the framerate.
* Use `AddForce` in its various flavours, rather than directly setting velocity.

---
Tags: unity, rigidbody
---


# Question
Title: Libgdx AtlasTmxMapLoader with multiple tilsets
I am working on a Libgdx game which loads Tiled maps. The current map I am working on makes use of two tilesets, one for shadow/light and another for terrain and buildings. The general process I do, that has been working fine, is that I receive the sprite sheet from the artist, design the maps, then take the spritesheet file and split it using ImageMagick. From there I take the split images and create an optimized png and atlas file with TexturePacker.

However, this is the first map I have made that makes use of multiple tilesets. The issue I am having is when loading the map with AtlasTmxMapLoader it relies on a single atlas file property in the map. I tried to merge my 2 images into a single atlas/texture (keeping the same names/indexes) but it only seems to render by first tileset tiles.

Perhaps I am missing something simple. What is the correct way to handle multiple tilesets (how exactly should my atlas file be setup)?

# Answer
So after reading more into how .tmx files are read I was able to fix my problem.

Here is how to properly do it when working with multiple tilesets and re-packing your spritesheets in TexturePacker. First, cut up the tileset images using a utility like ImageMagick and make sure they are indexed (specified by an underscore and number in the filename). You can do this with the crop command in ImageMagick like so:

`convert.exe "shrine_tileset.png" -crop 16x16 "shrine_tileset_%02d.png"`

Second, re-pack all tiles from all tilesets into a single atlas in TexturePacker. If it works correctly you will see the name of each tileset in the atlas file with an associated index based on the tile id. For example:

```
 shrine_tileset
  rotate: false
  xy: 382, 122
  size: 16, 16
  orig: 16, 16
  offset: 0, 0
  index: 703

```

Finally (and this is the part I could not figure out), make sure each tileset's tile indexes start from the "firstgid" value in the .tmx file. For example, my second tilesheet starts from 2049, as their are 2048 tiles in the first sheet. This should be denoted at the top of the .tmx file for each tileset.

```
<tileset firstgid="2049" source="shadow_light.tsx"/>

```

So when cutting up the tiles for my tileset "shadow\_light", I would start them from index 2048, one less than the gid, EX: "shadow\_light\_2048.png".

Hopefully this helps someone!
> 2 votes

---
Tags: libgdx, texture-atlas
---


title: Javascript 2D game tile textures

text:
# Question
Title: Javascript 2D game tile textures
I am using a texture atlas for my tiles. Of course I need to get the sub-images to draw them on the canvas as separate tiles. Right now I can think of two ways to implement this.

1. Divide the texture atlas into separate `Image` instances. Then draw them onto the canvas accordingly.
2. Use a single image, and just draw part of it by adding extra parameters to `CanvasRenderingContext2D`'s method \`drawImage.

I'm not sure which is better. My thoughts were that the first option would be more manageable and flexible, since each tile is separated. What would be better? What are the ups and downs of each?

# Answer
The ups of the "storing texture in atlas" would be, that you can assign textures dinamically. E.g. you hve your dungeon brick tile on the 0;0 coordinates on your image. If ypu put the 0 id on the array where the tile goes, then instead of harcoding it in, you can just do

texX = (i * texSize) % imageWidth

texY = Math.floor(i * texSize / image.width) * texSize

i is the id of the tile, texX and texY are the x and y positions, texSize is 1 textures width.

So for example, you have your texture at (5; 3), and it has 8 textures across, then you set it's id to 29.
> 0 votes

---
Tags: javascript
---


title: Align UI element to gameObject in 2D

text:
# Question
Title: Align UI element to gameObject in 2D
I have a 2d game where I want to display UI element perfectly aligned to specific gameObjects.

I have an ortographic camera and I used to `Camera.main.WorldToScreenPoint()` function giving it the gameobject position modified, for instance, by +1 on X component to get the UI element on its perfect right.

My problem is that the element is not on the gameObject's perfect right, but sensibly above. See this schema:

Expectation:

G -\> UI element

Reality:

---\> UI element
G

I tried also to use the `WorldToViewportPoint()` but it's not giving the desired result.
So, I think this is the right way to go but I can't guess what I'm missing.
Any clue?

**EDIT**:
After a little bit more observations it seemed that the UI element alignment depends somehow on it's distance from the center of the screen (of the camera viewport I guess), so that if the gameObject is below half height the UI element y position won't be on the perfect right but slightly below it and if above half heigth will be slightly above the perfect right. Same for x coordinate. Is there a way I could control this?

# Answer
Setting the render mode of the canvas to world space allows you to manipulate the UIElement as if it was a normal gameobject instead of overlaying it onto the screen.

This allows the position, scale etc to be set directly and the position of the camera to have no effect on it.
> 1 votes

---
Tags: unity, unityscript
---


# Question
Title: In Unity, how can I modify the shape of a sprite?
I am new to Unity and programming in general, however, I wanted to know how to change a sprite's shape. I want to do this while the game is running, so I was thinking about removing a set of pixels given some condition after an event has happened and then adjusting the collider around the object. However, I don't know how to do this. I have searched in YouTube and Google but so far I have not found anything that is useful to me.
My first thoughts were to make the pixels in a sprite's texture transparent given a condition, and I was able to achieve this, but when the time came to translate the texture into the shape of the sprite I failed miserably. Then I thought about using meshes, but I think that meshes might be too hard on the engine and cause some slowdown. I want to make a digging game where I can dig through many different objects and those are my ideas thus far. If you think there are better ways or know of a place where I can learn or, ideally, were willing to give me some coding techniques in C# for achieving the above, I would be very grateful.

# Answer
> Then I thought about using meshes, but I think that meshes might be too hard on the engine and cause some slowdown.

Let me check my clock...yes, it is 2016, having 1 mesh shouldn't slow down anything.

What you need here is a tile based terrain (e.g. terraria) with marching squares. Marching squares is an algorithm, wich is made to smooth out 2d tile based terrain.
> 2 votes

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


# Question
Title: How would I handle collision to all instances of one object? (C# and monogame)
What I'm saying is, let's say I have a list. That list contains all the tiles in the game. I use this to update them all, draw them all, etc.

```
for (var i = 0; i < Tiles.Count; i++)
{
     Tiles[i].Update(gameTime);
}

```

But how can I handle collision from each side of the tile, each side of the player for all tiles, but instead have each tile have its own individual set of collision codes? Because if I have the player box intersect the tile box, it counts as ALL of the tiles..

# Answer
Assuming you store each tiles x, y, width and height in the class, you could provide a method which makes a rectangle and then returns it, and then check if that intersects with the rectangle of the player.

```
for (var i = 0; i < Tiles.Count; i++)
       {
            Tiles[i].Update(gameTime);
            if (Tiles[i].getRectangle().intersect(Player.getRectangle()))
            {
                //get more details and resolve collision
            }
       }

```

The getRectangle method would just consist of

```
public Rectangle getRectangle() {
    return new Rectangle(x, y, width, height);
}

```
> 1 votes

---
Tags: c#, monogame, platformer
---


# Question
Title: Sampling in the Compute Shader not working
I'm trying to sample a image in the compute shader.

My code is

```
    [numthreads(1, N, 1)]
void VertBlurCS(int3 groupThreadID : SV_GroupThreadID,
                int3 dispatchThreadID : SV_DispatchThreadID)
{

    float4 test = gDiffuseMap.SampleLevel(samAnisotropic,0,0);
    gOutput[dispatchThreadID.xy] = test;
}

```

I'm getting one solid color.

What is wrong with my code?

# Answer
> 3 votes
You are sampling from the same location on the texture for every output, therefore the output is a single colour.

See the documentation for SampleLevel

A fix would look something like this:

`float2 uv = float2(dispatchThreadID.xy) / float2(textureWidthHeight);
float4 test = gDiffuseMap.SampleLevel( samAnisotropic, uv, 0 );`

---
Tags: directx11, hlsl
---


# Question
Title: Game Object is Instantiating on same position
I am working on a small project . But now I have come across a problem . The problem is the prefab is instantiating on the same position .

I want to instantiate a box end to end . The basic set up is as follows : -

Image 3 :- Please see the comment below

Box game object has a parent empty object (Start\_point) , and a child empty object (end point) . Those marks the Start and End of that game object .

The game a empty game object (Tile\_Gen) which has a C# script as follows :-

```
using UnityEngine;
using System.Collections;

public class Tile_Gen : MonoBehaviour
{

   public GameObject G_O_01 ;

   public GameObject Current_Tile ;

   public Vector3 Start_Position_Of_Path ;

// Use this for initialization
void Start ()
{
    Start_Position_Of_Path = Current_Tile.transform.GetChild(0).transform.GetChild(0).position;
    Instantiate(Current_Tile , Start_Position_Of_Path , Quaternion.identity);

}

// Update is called once per frame
void Update ()
{
    Path_Generator ();
}

public void Path_Generator()
{
    Instantiate(G_O_01 , Start_Position_Of_Path , Quaternion.identity);
// End of tile position = start tile position
    Start_Position_Of_Path = G_O_01.transform.GetChild(0).transform.GetChild(0).position;
    print (Start_Position_Of_Path);
}
}

```

Here G\_O\_01 is Start\_point prefab , Current\_Tile is Start\_point .

But this is not instantiating as I wanted . This instantiates all the object at one place .

But I want something like one behind the another , like this :-

Image 4 :- Please see the comments below

So Please help me to figure it out .

Regards NB :)

# Answer
You'r approach is rather strange, but stick with it an learn it's faults / strengths because creating it your way is a great way to learn. Below is the same concept just cleaned up a bit. Remember that in your setup, the box object has to be offset so the left side of the box is at the same position as its parent. This can be done with sprites setting the pivot to the right side, or by offsetting the childs transform.

```
using UnityEngine;

public class Spawner : MonoBehaviour
{

    public GameObject Prefab;

    private GameObject _previousTile;
    private Vector3 _nextStartPosition;

    void Update()
    {
        PathGenerator();
    }

    private void PathGenerator()
    {
        _previousTile = Instantiate(Prefab, GetNextStartPosition(), Quaternion.identity) as GameObject;
    }

    private Vector3 GetNextStartPosition()
    {
        if(_previousTile == null)
            return Vector3.zero;

        var BoxObject = _previousTile.transform.GetChild(0);
        if(BoxObject == null)
            return Vector3.zero;

        var endOfLastTile = BoxObject.GetChild(0);
        if(endOfLastTile == null)
            return  Vector3.zero;

        return endOfLastTile.position;
    }
}

```
> 1 votes

# Answer
This is because you Instantiate them in the same position:

```
Instantiate(G_O_01 , Start_Position_Of_Path , Quaternion.identity);
Start_Position_Of_Path = G_O_01.transform.GetChild(0).transform.GetChild(0).position;

```

You could try something like this in your Start ():

```
float n = 5.0f;
Vector3 dist = ((endPoint - startPoint)/n);
for( int i = 0; i <= n; i++ ) {
    Instantiate(G_O_01 , startPoint + dist*i , Quaternion.identity);
}

```

This code will Instantiate n+1 G\_O\_01 objects on straight line between endPoint and startPoint ( including both points ).

Edit:

Why your code spawns them in one position?

In short. You place object in position `Start_Position_Of_Path`. Then you set `Start_Position_Of_Path` to this object's position ( which is of course equal to `Start_Position_Of_Path` ), and spawn next object in `Start_Position_Of_Path`, etc. etc.
> 0 votes

# Answer
Here you are giving same point every time. Second bad practice is you are calling your generator method in `Update`.

Well, if you want to spawn platforms in linear path then you adopt ambiguous way. You made an empty `parent`, then `child` (platform) then then again child `gameObject` for End Point. It would bevery confusing because of global and localPositions.

Here is a simpler way to achieve your goal.

* Delete `parent` and `child` and make prefab of only box.

Now what your script do,

```
using UnityEngine;
using System.Collections;

public class Tile_Gen : MonoBehaviour
{

   public GameObject G_O_01 ;

   GameObject _lastTile;
   float _tileGap = 0;

    // Use this for initialization
    void Start ()
    {
        _lastTile = Instantiate(G_O_01) as GameObject;
        _tileGap = _lastTile.transform.localScale.x/2.0f;

        // Creating 20 tiles
        for (int i = 0; i < 20; i++)
            Path_Generator ();
    }

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

    }

    // A general method, whenever you call it, it will spawn tile next to previous one.

    public void Path_Generator()
    {
        _lastTile = Instantiate(G_O_01 , new Vector3(_lastTile.transform.position.x + _tileGap ,_lastTile.transform.position.y,_lastTile.transform.position.z) , Quaternion.identity) as GameObject;
    }

}

```

Now set you block in editor to very start (at very left) then make prefab or apply changes. After that drop your `GameObject` to this script. **Because** this script is spawning tiles from left to right.

Hope this helps.
> 0 votes

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


# Question
Title: How do I control texture appearance based on game play events?
In an FPS I am developing, I am procedurally altering the appearance of textures based on game play events, and would like to know if the way I have implemented this was a good idea.

Right now, on each frame, I am grabbing a pointer to the uncompressed image and writing to it using `memset`. It's pretty straightforward if I want to have game play events affect the texture's appearance, because all I have to do is tie whatever attribute I like from any game object into the function writing the image data. For example, using this I could get the player's x,y position and draw an x directly to a map texture as the player moves around.

Is there a better way to implement this functionality in general?

My first thought would be to use shaders instead, but I haven't been able to find anyone doing anything like this and I know almost nothing about shaders. I feel like I could be missing something obvious to someone.

I am trying to keep this question as engine-independent as possible, but if relevant, I am using Source Engine procedural materials.

# Answer
Modifying textures on the CPU is usually very, very slow. What you'd prefer to do is use Render to Texture- you use data from your program in a shader to render to something that is not the screen (render target).

Taking your minimap example, drawing an X on the player is as simple as sending the map background texture, X texture, and the player position to the shader, and blending those two based on the player pos (anything outside where you mark the X is the minimap texture, anything inside is the X, alpha blended on top the map, if i understand the idea). Any parameters that you send to your function that changes the texture with `memset` you now send as a constant buffer to your shader.

This also works for other types of textures (like ones you map on say, a model, like a soldier) as you can render to texture the original texture with the additional things and then send the new texture as the one you map on the model.

I'm no expert on Source but this seems useful : https://developer.valvesoftware.com/wiki/Adding\_a\_Dynamic\_Scope
> 1 votes

---
Tags: textures, procedural-generation, source-engine
---


# Question
Title: Libgdx, Gradle, android package naming problem
I'm upgrading my libgdx project to make use of all the new Gradle stuff.

However I changed the package namespace from the default generated by gdx-setup but that hasn't worked: when I debug to my phone Gradle is still trying to launch the default activity using the old namespace, hence it fails. But I can't figure out where Gradle is getting this from - I've searched the entire folder tree for the offending old namespace string and can't find it anywhere.

Details:

So gdx-setup generated the android project with namespace "com.wibble.mygame.android"

To match the namespace of my already-published game, I edited that to "com.wibble.mygame\_a". I did this in the Android.manifest and the source code. Also noticed that the android build.gradle file has a line that generates the am start command so corrected that as well.

But when I debug with my connected Android device, it tries to launch the app with a command like:

```
am start -n "com.wibble.mygame.android/com.wibble.mygame_a.AndroidLauncher"
   -a android.intent.action.MAIN -c android.intent.category.LAUNCHER

```

the old namespace is still there but I can't figure out where its getting it from because I can't find any mention of 'mygame.android' anywhere in the whole project tree. Is there some cache of stuff hidden somewhere that I need to delete?

# Answer
Clearing out the IntelliJ project and files and re-importing from the gradle.build solved the problem. IntelliJ must have been caching something somewhere.
> 0 votes

---
Tags: libgdx, gradle
---


title: Change screen from main menu to game

text:
# Question
Title: Change screen from main menu to game
I'd like to know how I can change the screen from the Main Menu to the Game itself but im having quite the trouble and I would appreciate the help. What I want to do is when I press *btn.Play* it changes the screen from the main menu to the game.

Here's the code I got (sorry it's long):

Game:

```
@Override
public void create(){

    batch = new SpriteBatch();

    Up = new Texture("left.png");

    cam = new OrthographicCamera();
    cam.setToOrtho(false,1280,720);

    //creates the square in the middle of the screen
    square = new Rectangle();
    square.x = 630;
    square.y = 720 / 2 - 32 /2;
    square.width = 32;
    square.height = 32;

    //code
}

//code

public void render() {

    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    cam.update();

    batch.setProjectionMatrix(cam.combined);
    batch.begin();
    batch.draw(Up, square.x, square.y);
    //code
    batch.end();
}

```

Screens (used to display the first screen) :

```
public class Screens extends com.badlogic.gdx.Game {

//creates the timing on the splash screen

@Override
public void create() {

    startTime = TimeUtils.millis();

    //sets the next screen as the splash screen
    setScreen( new SplashScreen(this));
}

@Override
public void render(){

    super.render();
    rendCount++;
}

@Override
public void dispose(){

    endTime = TimeUtils.millis();
}

```

SplashScreen:

```
public class SplashScreen implements Screen  {

public SplashScreen(Game g) {

    myGame = g;

    cam = new OrthographicCamera();
    cam.setToOrtho(false, 1280, 720);
}

@Override
public void show() {

    //image of the splash screen
    splashTexture = new Texture("splash.jpg");

    //timer starts
    timeStart = TimeUtils.millis();
}

@Override
public void render(float delta) {

    SpriteBatch batch = new SpriteBatch();

    //draws the image on screen
    batch.setProjectionMatrix(cam.combined);
    batch.begin();
    batch.draw(splashTexture, 0, 0);
    batch.end();
    rendCounter++;

    // if the timer is higher than 5 secs goes to the main screen
    if(TimeUtils.millis() > (timeStart+5000)) {
        myGame.setScreen(new MainScreen());
    }

}

@Override
public void dispose(){

    splashTexture.dispose();

}

```

Main Menu:

```
public class MainScreen implements Screen{

private SpriteBatch batch;
private OrthographicCamera cam;
private Stage stage;
private TextButton btnPlay, btnExit;
private BitmapFont font;
private Skin skin;
private TextureAtlas atlas;

public MainScreen() {

    cam = new OrthographicCamera();
    cam.setToOrtho(false, 1280,720);
    batch = new SpriteBatch();

}

@Override
public void show() {

    // creates the pack for the buttons, its skin, the font used on the buttons, and the stage(screen)

    atlas = new TextureAtlas("buttons.pack");
    skin = new Skin();
    skin.addRegions(atlas);
    font = new BitmapFont(Gdx.files.internal("font.fnt"), false);

    stage = new Stage();
    stage.clear();
    Gdx.input.setInputProcessor(stage);

    // sets the style of the buttons

    TextButton.TextButtonStyle style = new TextButton.TextButtonStyle();
    style.up = skin.getDrawable("btn_up");
    style.down = skin.getDrawable("btn_down");

    // sets the font of the buttons

    style.font = font;

    //creates the play button with the text, its position and the size

    btnPlay = new TextButton("Play", style);
    btnPlay.setSize(350, 150);
    btnPlay.setPosition(450, 400);

        btnPlay.addListener(new InputListener() {

            public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {

                return true;
            }

            public void touchUp(InputEvent event, float x, float y, int pointer, int button) {

                new Game()
                dispose();

            }
        });

    btnExit = new TextButton("Exit", style);
    btnExit.setSize(350,150);
    btnExit.setPosition(450, 150);

    btnExit.addListener(new InputListener() {

        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {

            return true;
        }

        public void touchUp(InputEvent event, float x, float y, int pointer, int button) {

            Gdx.app.exit();
            dispose();

        }
    });

    stage.addActor(btnPlay);
    stage.addActor(btnExit);

}

@Override
public void render(float delta) {

    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    Gdx.gl.glClearColor(0, 0, 0, 1);

    batch.setProjectionMatrix(cam.combined);

    stage.act();

    batch.begin();
    stage.draw();
    batch.end();

}

@Override
public void dispose() {
    batch.dispose();
    stage.dispose();
    atlas.dispose();
    skin.dispose();
    font.dispose();

}

```

# Answer
> 2 votes
One way of doing this that's quite easy is to let there be a single class that extends `Game`, that launches the first `Screen` (this is pretty much what you have).

What you also need to do though is to pass a reference to that `Game` to all your `Screen`s so that they can call `setScreen` themselves when they want to go to another screen.

In a somewhat simplified example the root would the the `Game` class, in your code this is `Screens`;

```
package com.androidstudiosandbox;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;

public class MyAndroidStudioSandboxGame extends Game {
  @Override
    public void create () {
        setScreen(new SplashScreen(this));
    }

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

```

As you can see, this calls `setScreen` in the `create` passing an instance to the `SplashScreen`;

```
package com.androidstudiosandbox;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.utils.TimeUtils;

public class SplashScreen implements Screen {

    private Game game;
    private long showTime;

    public SplashScreen(Game game) {
        this.game = game;
    }

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

        if (TimeUtils.timeSinceMillis(showTime) > 2000) {
            game.setScreen(new MenuScreen(game));
        }
    }

    @Override
    public void show() {
        showTime = TimeUtils.millis();
    }

    @Override
    public void resize(int width, int height) { }

    @Override
    public void pause() { }

    @Override
    public void resume() { }

    @Override
    public void hide() { }

    @Override
    public void dispose() { }
}

```

As the `SplashScreen` has a reference to the initial `Game` instance, it can call `game.setScreen` when the time has elapsed and pass a new instance of a `MenuScreen` that also gets the `Game` instance passed;

```
package com.androidstudiosandbox;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Button;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;

public class MenuScreen implements Screen {

    private final Stage stage;

    public MenuScreen(final Game game) {

        stage = new Stage();
        Gdx.input.setInputProcessor(stage);

        TextButton button = new TextButton("My button", some_skin);
        button.addListener(new ClickListener(){
            @Override
            public void clicked(InputEvent event, float x, float y) {
                game.setScreen(new GameScreen(game));
            }
        });

        stage.addActor(button);
    }

    @Override
    public void show() { }

    @Override
    public void render(float delta) {
        stage.act(delta);

        Gdx.gl.glClearColor(1, 1, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        stage.draw();
    }

    @Override
    public void resize(int width, int height) { }

    @Override
    public void pause() { }

    @Override
    public void resume() { }

    @Override
    public void hide() { }

    @Override
    public void dispose() { }
}

```

The `MenuScreen` sets up a `Stage` and a `TextButton` and wires up the click handler of the button to call `setScreen` when the button is pressed. Note that the `game` argument to the constructor needs to be `final` here as the click handler is a seperate class.

package com.androidstudiosandbox;

```
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.utils.TimeUtils;

public class GameScreen implements Screen {
    private Game game;

    public GameScreen(Game game) {
        this.game = game; // Store this to call game.setScreen(new MenuScreen(game)) to return to the menu
    }

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

        // Do game logic and rendering
    }

    @Override
    public void show() { }

    @Override
    public void resize(int width, int height) { }

    @Override
    public void pause() { }

    @Override
    public void resume() { }

    @Override
    public void hide() { }

    @Override
    public void dispose() { }
}

```

The actual game play is then handled by the `GameScreen`, this class also takes a reference to `Game` so that the player can return to the `MenuScreen` again (that part I've left out though).

---
Tags: android, libgdx, menu
---


# Question
Title: Creating actor comprising multiple other actors - controlling where pieces are drawn
I am making my custom actor class, made up of 3 actors (one`ProgressBar`, one `Label` and one `TextButton`), because I will be using this many times, so it's not a good idea to create 3 of those actors separately when I can create one that can contain them. So I am making my class:

```
public class MyActor extends Actor {
ProgressBar bar;
Label nameLabel;
TextButton button;
public MyActor(String name, Skin skin, float progress){
    nameLabel = new Label(name, skin);
    button = new TextButton("Buy", skin);
    bar = new ProgressBar(0f,5f,progress,false,skin);
}

@Override
public void act(float delta) {
    super.act(delta);
    bar.setBounds(getX(), getTop()-getHeight() / 3f, getWidth(), getHeight() / 3f);
    nameLabel.setBounds(getX(), getY()+getHeight() / 3f, getWidth(), getHeight() / 3f);
    button.setBounds(getX(), getY(), getWidth(), getHeight() / 3f);
}

@Override
public void draw(Batch batch, float parentAlpha) {
    super.draw(batch, parentAlpha);
    bar.draw(batch, parentAlpha);
    nameLabel.draw(batch, parentAlpha);
    button.draw(batch,parentAlpha);
}

}

```

So in my game, I add my actor to the Stage using a table:

```
Table table = new Table();
table.debug();
MyActor actor = new MyActor("whatever",mySkin,1f);
table.add(actor).size(myWidth,myHeight);

```

The actor is drawn in the correct place (I know because of the debug lines), but the 3 actor are drawn at the 0,0 coordinates. What am I doing wrong? Do I need to override another method?

# Answer
> 1 votes
**From the comments:** the solution seems to be to make `MyActor` extend `Group`, then add the constituent actors to that group.

---

**Original answer:**

It looks like your problem could be that your `MyActor` class does not report it's width and height to the parent `Actor`. Just because you have an `Actor` that has some other `Actor`s as members doesn't mean the "*parent*" `Actor` will know how tall and wide it should be to accommodate all of them.

By querying the preferred size of the child `Actor`s you can return more sensible values by overriding `getHeight` and `getWidth`;

```
public class MyActor extends Actor {
    Label nameLabel;
    TextButton button;
    ProgressBar bar;

    public MyActor(String name, Skin skin, float progress){
        nameLabel = new Label(name, skin);
        button = new TextButton("Buy", skin);
        bar = new ProgressBar(0f, 5f, progress, false, skin);
    }

    @Override
    public void act(float delta) {
        super.act(delta);

        button.setBounds(getX(), getY(), getWidth(), button.getPrefHeight());
        nameLabel.setBounds(getX(), button.getTop(), getWidth(), nameLabel.getPrefHeight());
        bar.setBounds(getX(), nameLabel.getTop(), getWidth(), nameLabel.getPrefHeight());
    }

    @Override
    public float getWidth() {
        return Math.max(bar.getPrefWidth(), Math.max(nameLabel.getPrefWidth(), button.getPrefWidth()));
    }

    @Override
    public float getHeight() {
        return nameLabel.getPrefHeight() + button.getPrefHeight() + bar.getPrefHeight();
    }

    @Override
    public void draw(Batch batch, float parentAlpha) {
        super.draw(batch, parentAlpha);
        nameLabel.draw(batch, parentAlpha);
        bar.draw(batch, parentAlpha);
        button.draw(batch,parentAlpha);
    }
}

```

I also changed the layout logic to consider the preferred size of the children, instead of saying that each should be a third of the whole in height, for example.

Also, if your `table` is the root table, I think you want to set it to fill the parent;

```
Table table = new Table();
table.setFillParent(true);

```

---
Tags: libgdx, transformation, scene2d
---


title: Can someone explain this function?

text:
# Question
Title: Can someone explain this function?
How does the spawn function work?

```
var max_bollar = 15;
var i = 0;
var timecounter = 0;
var bollarcounter = 0;
var spawn_delay = 5;
var min_spawn_delay = 25;
var max_spawn_delay = 500;
var balls = [];

function spawn(i)
{
    var boll = {x: random(totalWidth), y: 0};
    circle(boll.x, 0, 10, "blue");
    timecounter = 0;
    bollarcounter++;
    max_spawn_delay = (random(max_spawn_delay - min_spawn_delay) + min_spawn_delay);
    balls.push(boll);
}

function update()
{
    fill("black");
    timecounter += 1;
    if(timecounter == spawn_delay && bollarcounter < max_bollar)
    {
         spawn(bollarcounter);
    }
    for (var i = 0; i < balls.length; i++) {
        balls[i].y += 10;
        circle(balls[i].x, balls[i].y, 10, "blue");
    }
}

```

So what i don't get is the

```
spawn(bollarcounter);

```

If i have understod functions right the i in

```
function spawn(i)

```

should be replaysed with the bollarcounter but there is no i in the spawn function so why when i want to spawn the balls use

```
spawn(bollarcounter);

```

?

# Answer
> 4 votes
Since we are unsure what the game or rendering library is, I have commented the code to tell what I think it does. It appears to make rain drops.

```
var max_bollar = 15; // Lots of setup - should be explanatory. Skip to update()
var i = 0;
var timecounter = 0;
var bollarcounter = 0;
var spawn_delay = 5;
var min_spawn_delay = 25;
var max_spawn_delay = 500;
var balls = [];

function spawn(i)
{
    var boll = {x: random(totalWidth), y: 0}; // spawns boll at y:0 and randomly along the x
    circle(boll.x, 0, 10, "blue"); // draws boll at coords, 10 radius/diameter filled blue
    timecounter = 0; // resets time counter (should be in update)
    bollarcounter++; // increases boll count
    max_spawn_delay = (random(max_spawn_delay - min_spawn_delay) + min_spawn_delay); // makes random delay between min and max delay - OVERWRITING the max delay value
    balls.push(boll); // adds boll to balls list
}

function update()
{
    fill("black"); // Fills canvas with black
    timecounter += 1; // Increments tick counter
    if(timecounter == spawn_delay && bollarcounter < max_bollar)
    // If we have less that 15 boll and tick counter is at 5 - run the below
    {
         spawn(bollarcounter); // spawn boll
         // SHOULD reset time counter to 0, else we will never spawn another
    }
    for (var i = 0; i < balls.length; i++) {
        // iterates through the bolls
        balls[i].y += 10; // moves the currently selected boll 10 (px down)
        circle(balls[i].x, balls[i].y, 10, "blue"); // redraws boll with 10 radius/diameter and colored blue
    }
}

```

---
Tags: javascript
---


# Question
Title: Get Particular Object's collision status via C# script
My current scripts creates and modifys the location of various prefab objects as they go along the screen. One of the things I want to find out about the active object is whether it has collided with another object, and if so, to destroy itself. The problem is that every example I've found to date has no way to access the object itself to get this information.

```
        if (Random.value > 0.9)
    {
        var bomberInstance = GameObject.Find("bomber");

        var newBombObject = Instantiate(Resources.Load("_prefabs/bomb"), new Vector3(bomberInstance.transform.position.x, bomberInstance.transform.position.y, bomberInstance.transform.position.z), Quaternion.identity) as GameObject;

        bombArray.Add(newBombObject);
    }

    foreach (GameObject bomb in bombArray)
    {

        //get bomb objects collision status here.

        var newBombYAxisPosition = bomb.transform.position.y - .1f;

        bomb.transform.position = new Vector3(bomb.transform.position.x, newBombYAxisPosition, bomb.transform.position.z);

    }

```

As you can see, the examples you find online don't exactly fit very well for what I need. Do objects in unity store this information, and if so how can it be accessed? And if not, is there another way to access this information?

# Answer
> 2 votes
If I get you right, one way would be to add a script to your Bomb Prefab that implements the OnTriggerEnter and OnTriggerExit method.
There should also be a collider attached, the collider should be marked as trigger. If it is a mesh collider, make sure it is also convex, otherwise the OnTriggerEnter/Exit methods will not be called.
In OnTriggerEnter/Exit you should count the collisions:

BombScript.cs (attached to the bomb GameObject):

```
int collisions = 0;
public bool HasCollisions {
  get { return collisions > 0; }
}

void OnTriggerEnter(Collider other) {
  //Check other collider here. Checks can be like type, or layer. If it is the check you want, increment collisions.
  collisions++;
}

void OnTriggerEnter(Collider other) {
  //Check other collider here. Checks can be like type, or layer If it is the check you want, decrement collisions.
  collisions--;
}

```

You then can get the script of the Bomb and check the Collisions property. If it is true, delete the Bomb and do whatever you want: foreach (GameObject bomb in bombArray) {

```
    //get bomb objects collision status here.
    BombScript bs = bomb.GetComponent<BombScript>();
    if(bs.HasCollisions)
    {
        //Do stuff here...
    }
    var newBombYAxisPosition = bomb.transform.position.y - .1f;

```

Since you modify the position of the bomb via the transform, you might also need a Rigidbody component which is set to `isKinematic`. You can find more information about colliders here: http://docs.unity3d.com/Manual/CollidersOverview.html

# Answer
> 0 votes
Assuming you have a collider on each object involved in the collision, access the other GameObject through the collider. This is what I typically do:

```
void OnCollisionEnter(Collision collision) {
    MyOtherScript other = collision.collider.GetComponent<MyScript>();

    //We know it is the right kind of object by whether is
    //has a certain script attached
    if(other && other.CheckSomeCondition()) {
        Destroy(gameObject); //self-destruct
    }
}

```

This is assuming that the object your checking for has a script called MyOtherScript attached, containing a method called CheckSomeCondition().

---
Tags: unity, c#, collision-detection
---


# Question
Title: Annoying snag when moving with dx and dy JAVA
I am currently using a keyAdapter with detectors and when I move I change the value of dx and dy respectively. However if I move left then right or up then down quickly, the sprite won't move in the direction I last input. Does anyone know a fix?

Detector method:

```
@Override
public void keyPressed(KeyEvent e) {

    int key = e.getKeyCode();

    if (key == KeyEvent.VK_LEFT) {
        dx = -1;
    }

    if (key == KeyEvent.VK_RIGHT) {
        dx = 1;
    }

    if (key == KeyEvent.VK_UP) {
        dy = -1;
    }

    if (key == KeyEvent.VK_DOWN) {
        dy = 1;
    }
}

@Override
public void keyReleased(KeyEvent e) {

    int key = e.getKeyCode();

    if (key == KeyEvent.VK_LEFT) {
        dx = 0;
    }

    if (key == KeyEvent.VK_RIGHT) {
        dx = 0;
    }

    if (key == KeyEvent.VK_UP) {
        dy = 0;
    }

    if (key == KeyEvent.VK_DOWN) {
        dy = 0;
    }
}

```

Move method:

```
public void move(){
    worldX+=dx;
    worldY+=dy;
}

```

# Answer
Alternatively, you could decouple the button push and the delta move. In the key events, you can always set the button state

```
if (key == KeyEvent.VK_LEFT) {
    leftPressed = true/false; // depending on press/release
}
...

```

Then later set deltas in the move method or a controls handler method (this will stop x movement if both left and right are pressed -1 and +1 to the delta):

```
public void move(){
  dx = 0;
  dy = 0;

  if (leftPressed) {
    dx -= 1;
  }
  if (rightPressed) {
    dx += 1;
  }
  ...

  worldX+=dx;
  worldY+=dy;
}

```
> 1 votes

# Answer
guessing keyreleased come after changing direction, try :

```
if (key == KeyEvent.VK_LEFT) {
    if (dx==-1)
    dx = 0;
}

if (key == KeyEvent.VK_RIGHT) {
    if (dx==1)
    dx = 0;
}

if (key == KeyEvent.VK_UP) {
    if (dy==-1)
    dy = 0;
}

if (key == KeyEvent.VK_DOWN) {
   if (dy==1)
    dy = 0;
}

```
> 0 votes

---
Tags: java, movement
---


# Question
Title: How do I properly combine the colors of different lights?
Let's say I have 4 light colors:

```
(0.6,0.0,0.0), (0.0,0.6,0.0), (0.1,0.1,0.1), (0.1,0.1,0.1)

```

And now I want to combine them properly. I can't add them together, because if I add for example 3rd color and 4th color I will receive `(0.2,0.2,0.2)`, while I would expect it to be `(0.1,0.1,0.1)`. So what is the way to mix colors together and receive **final light color?**

I tried something like this (Pseudo-code example for color 3 and 4):

```
color3 - color4 = (0.0,0.0,0.0)
finalColor = subtraction result (0.0,0.0,0.0) + color3

```

But sometimes it doesn't work.

# Answer
> 3 votes
Your question makes it clear what you don't want, i.e. a combination of a color like `(0.1,0.1,0.1)` with itself to result in pure addition, giving `(0.2,0.2,0.2)`, when you would expect it to result to stay the same `(0.1,0.1,0.1)`. However, you never made it clear what you want in other cases, such as when combining your first color, `(0.6,0.0,0.0)` with your second color `(0.0,0.6,0.0)`. I guess that in this case you are expecting the result to be a pure plain addition, giving `(0.6,0.6,0.0)`.

Here are the visual representations of the 4 colors you gave as example in the second line of your question:

So, here it is a visualization of what you get when purely adding `(0.6,0.0,0.0)` and `(0.0,0.6,0.0)`, which is equal to `(0.6,0.6,0.0)`:

Now, when summing two lights of the same color, like `(0.1,0.1,0.1)` plus `(0.1,0.1,0.1)`, as @amitp has accuratelly pointed out in the comments, there is no reason why you should expect that two hlights overlapping would NOT result in a brighter version of that original color. Thus, this is what you got, i.e. `(0.2,0.2,0.2)`:

In other words, that is perfectly correct and "realistic": two lights of different color result in a brighter light of composed color, while two lights of the same color result in a brighter light of that original color.

That only works well because of something that @Draco18s correctly pointed out in her/his answer: any values above 1 (i.e. 255) will be clamped to 1 (i.e. 255). It means, in a rough and imprecise way to put it, that when a light color is in its brightest RGB version, then of course the overlap of two such lights just cannot result in any brigther versions of themselves. Thus, summing `(1,0,0)` with itself still results in `(1,0,0)`, which looks like the following:

So, to sum up, there is nothing wrong there that you need fixing. However, maybe what you are looking for is something that is not exaclty what one can see in the picture you posted in your question. For instance, think of the averaging of two colors instead of their addition (I mean, literally the sum of the two colors divided by 2).

The average of `(0.6,0.0,0.0)` and `(0.0,0.6,0.0)` is `(0.3,0.3,0.0)`. Which looks like the following:

Now, in that case, the averaging combination of the colors results in a new color that looks similar to both the original colors. Instead of red and green resulting in yellow, now you have red and green resulting in something that *looks*, in a perception sense of the word, like a mix of the red and green. However, the downside is that due to the nature of the average, it also looks a bit darker than the original two colors that compose the third. Therefore, this may or may not work for your particular situation, depending on what you prefer.

But of course, in this case, averaging `(0.1,0.1,0.1)` with itself will now result in `(0.1,0.1,0.1)`:

Whether averaging or pure addition (or any other formula) works best for you, it is you who can decide. However, within the RGB color space alone, you can't easily get the result of averaging for `(0.1,0.1,0.1)` plus `(0.1,0.1,0.1)` AND the result of pure addition between `(0.6,0.0,0.0)` and `(0.0,0.6,0.0)`. Unless you just hard code `if-else` exceptions, passing different formulas for each types of cases. But of course, that wouldn't keep consistency, would probably look less natural or could result in pretty unpredictable results.

PS: For a fairly detailed explanation on color mixing and related discussions, see Manipulating colors in .NET - Part 1.

# Answer
> 4 votes
Define "properly." There are multiple ways of blending color. Additive blending works as you describe, `0.1 + 0.1 = 0.2` because we don't care if this value goes over 1 (as the values are clamped \[0-1\]). If you want to account for High Dynamic Range color, then you have to perform an additional step: rescaling.

HDR works by saving the *largest* value produced across the standard render (letting per-pixel values exceed 1), then dividing *every* pixel by that value, or some value close to it, so that the whitest whites stay white, the darkest black stay black, and everything else in between scales. This is how our eyes work, and why going into a dark room you can't see (until your eyes adjust) only to have the sun dazzle you when you come out again.

---
Tags: lighting, color
---


# Question
Title: Google leaderboards, up to a maximum of 70?
I see in the doc that the limit for the number of leaderboards on Google Play Services is 70. However, I am able to create more than 70 leaderboards and they are all working when I test my app. Is this limit still up to date? Does this mean that if I publish my game some of the leaderboards will be deactivated or something?

Thank you in advance if you know the answer. I just want to make sure of what I can expect for when I publish my game.

# Answer
Since the documentation says the limit is 70, you should rely on the limit being 70. That's about as official as you can get, in the general case.

To do otherwise is to rely on undocumented behavior that may only work during development or local testing -- such things are typical, for example you may be able to create more than 70 for testing purposes or over the lifetime of your application but can only have 70 active on the live services at a time. This facilitates debugging or retiring older leaderboards in favor of newer ones, et cetera.

Trying to have more will likely result in the extras being disabled, or possibly prevent your app from being available until the issue is corrected.
> 6 votes

# Answer
One of my friends experience the same. They got truncated once the app was uploaded to the google play.
> 5 votes

# Answer
Will they be deactivated?

# Yes.

The 70 leaderboard limit is part of the store specification, so more than seventy are allowed for testing on a local environment, which I have found myself, and from testimony of a few friends. The documentation refers to Game Services, so the limit will be enforced upon publishing
> 3 votes

---
Tags: leaderboards, google-play-services
---


title: Detect collision from a particular side

text:
# Question
Title: Detect collision from a particular side
I'm making a platform sidescrolling game. All I want to do is to detect if my character is on the floor:

```
function OnCollisionStay (col : Collision){
    if(col.gameObject.tag == "Floor"){
        onFloor = true;
    } else {onFloor = false;}
}
function OnCollisionExit (col : Collision){
    onFloor = false;
}

```

But I know this isn't the accurate way. If I hit a cube with a "floor" tag, in the air (no matter if with the character's feet or head) I would be able to jump.

Is there a way to use the same box collision to detect if I'm touching something from a specific side?

# Answer
You don't have to have only one collider on your character; you can have multiple colliders to perform different checks!

I would suggest creating a separate collider that is located on your character's feet. You could also have a collider for the top of your head, or maybe your front or back so you know when you bump into a wall...

Another way would be, when you collide with something, use Physics.Raycast or Physics.RaycastAll to check for points just below your feet, to see if you're standing on ground or not.

If you really wanted to only use one collider, within your collision functions, you could check the `col.contacts` points to see if the collision occurred above or below the mid point of your collider.
> 6 votes

# Answer
You can check the col.normal, well that's how I do this. For example if the x value is 1, I know the collision is on the bottom of my collider. (that's an example, I don't recall the values of the normals)
> 0 votes

# Answer
Note that if you're using a Character Controller, you should use `isGrounded` to check for collisions with the ground:

From the docs:

> Was the CharacterController touching the ground during the last move?

```
void Update() {
    CharacterController controller = GetComponent<CharacterController>();
    if (controller.isGrounded)
        print("We are grounded");
}

```

And it sounds like you should be, since it's best suited for characters such as those you'd use in a platformer. The wording of the docs suggests this is precalculated during each Move operation, so you should look at this before adding extra colliders/triggers.
> 0 votes

# Answer
Add this code to your player. Make a transform child object that is in the feet of the player. This code will determine weather the feet transform overlaps on ground.That means if player is grounded.

```
  public Transform theGround; //  A empty transform on the feet of the player.
  public LayerMask groundLayer; // Determines the ground.
  float groundRadius; //radius of the overlap circle to ground
  bool isGrounded;
    private void FixedUpdate()
    {
        isGrounded = false;
        Collider2D[] col = Physics2D.OverlapCircleAll(theGround.position, groundRadius, groundLayer);
        for (int i = 0; i < col.Length; i++)
        {
            if (col[i].gameObject != gameObject)
                isGrounded = true;
        }

    }

```
> -1 votes

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


title: Screen point to world space conversion

text:
# Question
Title: Screen point to world space conversion
I have a 3D cube that can be rotated with the mouse to show any side of the sphere.I want to be able to click a point on the cube and draw a circle around that point at a fixed height(so i dont need depth information), however i run into a problem where i cant translate the screen coridiantes to the worldspace coordinates. What i have attempted:

* get mouse click `position(x,y)`
* normalise the screen position(-1 to 1)
* create a vector with the z coordinate as 1
* multiply the vector by (inverseProjection x inverseView)

However, this does not give me the world coordinates as i would have expected. Where am i going wrong?

The depth information is not needed form this, i only need to map the mouse click point (x,y) to the world point (x,y,z) where z is fixed.

```
DirectX::XMMATRIX projection = projectionmatrix();
DirectX::XMMATRIX view = viewmatrix();

DirectX::XMMATRIX invProjectionView = DirectX::XMMatrixInverse(&DirectX::XMMatrixDeterminant(view *  projection), (view *  projection));
//invViewProjection = invView * invProjection;

float x = (((2.0f * mouseX) / _viewport.Width) - 1);
float y = -(((2.0f * mouseY) / _viewport.Height) - 1);

DirectX::XMVECTOR mousePosition = DirectX::XMVectorSet(x, y, 1.0f, 0.0f);

mouseInWorldSpace = DirectX::XMVector3Transform(mousePosition, invProjectionView);

```

Edit: The fixed axis is the y-axis, the z and x axis are the changing axis

Edit: I have revised the question after realising my mistakes in the initial question.

The x, y, and z are positioned as shown above. I want to be able to click the cube surface and drwaw the shape at a point with a fixed y-offset from the click point.

I am not able to draw a plane on the surface of the cube due to the nature in which the cube is generated hence the need for the screen to world coords.

# Answer
> 1 votes
Ok so this is my solution:

since the troube was broght about by the missing z coordinate, it check for intersection with the plane and store the z-coordinate. i then use this same coordinate when unprojecting using the code above and it seems to work fine. Thanks for the help

# Answer
> 1 votes
Not 100% sure of what you are trying to draw where, but neither Z=0 nor Z=1 correspond to the location of the cube in world space. Both points, however, do define the ray shown below in red. You can run an intersection test between that ray and the cube's BoundingBox to determine the exact world coordinate of collision. "Depth", which you claim to not need, is actually the calculated length of the collision vector. The Z of your cursor position comes directly from it.

```
CollisionPoint = RayStart + (RayDirection * CollisionDistance);

```

If you project CollisionPoint to screen-space, the resulting Z value will approximately match the value that is written to the depth buffer, if one is in use, and enabled.

If my assumptions are correct, you would draw your "3D circle" centered at
World(24.15, FixedHeight, 50).

---
Tags: directx11
---


title: Upgrade system for tower defence?

text:
# Question
Title: Upgrade system for tower defence?
What is the best way to create a rather dynamic upgrade system for a tower defence game? I thought of two possibilities:

* Create enums for stats and math operation (latter could be just a char as well), and use the following function:

```
Upgrade (Stat, Value, Operation);

```

Like:

```
Upgrade (STAT_HEALTH, 2, OP_MULT);

```

would double health.
* (Using an entity system with each one having an ID) Every tower, and its possible upgrades, are different entities, so:

```
Upgrade(int id);

```

would upgrade the entity to entity of ID id. This one doesn't look very good for me, as it looks like a waste of memory. This also makes me think of a system using a tree of stats nodes to define their dependencies, but I'm not sure what to do exactly.

Just started learning about JSON so the information needed would be available through it.

# Answer
> 2 votes
This depends on a few factors:

* Do you *actually* need to worry about memory? Unless you're dealing with a top-of-the-line 3D tower defense game, I doubt it's an issue you should be worried about.
* By "dynamic", you clearly mean that upgrades can change their value. Do you also mean that upgrades can combine to form others (ex: *+5 Attack* and *+3 Explosiveness* could be upgraded to *+10 Splash*)? If they are this dynamic, I would recommend using your second system, an entity system, because you'd have more flexibility. If not, I'd lean towards an enum-based system.
* Will different upgrade types be similar or drastically different? If you have upgrades varying from "Randomly grants a boost nearby towers!" to *+2 Attack*, you should probably use an entity system. With enums, you don't have as much room to work with these differences.

When it comes down to it, it's really a matter of **simplicity v. flexibility**. Which of these you choose should be determined by the scope/complexity of your game.

---
Tags: tower-defense
---


title: passing a class type as a parameter

text:
# Question
Title: passing a class type as a parameter
I have a setup in my game engine where I can add behavours to game objects. All behaviours are based on the class `AbstractBehaviour`. To easily get access to behaviours from a game object, I am trying to mimic unity's `getComponentOfType<type>()`.

Now for the question: how can I pass a class type as a parameter to my `GetBehaviourOfType()` function?

What I am trying to achieve in code:

```
AbstractBehaviour* GameObject::GetBehaviourOfType(typeid type)
{
    for (int i = 0; i < _behaviours->size(); i++)
    {
        if (dynamic_cast<type>(_behaviours[i]) != NULL)
        {
            return _behaviours[i];
        }
    }
}

```

Where `_behaviours` is a vector of abstract behaviours.

# Answer
> 4 votes
C++ differs a lot from C# in that it is a much more static language. There is very little support for Runtime Type Inference in C++, so in general I'd avoid going that route and just design my code in a very strongly typed fashion, avoiding abstract types, within reason.

If you must go that way, your best bet would probably be using a template, however, it will still be a compile-time thing only, you can't really pass a type as a normal function parameter.

```
template<class T>
AbstractBehaviour* GetBehaviourOfType()
{
    for (int i = 0; i < _behaviours->size(); i++)
    {
        if (dynamic_cast<T*>(_behaviours[i]) != nullptr)
        {
            return _behaviours[i];
        }
    }
    return nullptr;
}

// auto behaviour = gameObj.GetBehaviourOfType<PlayerBehaviour>();

```

If you really need the dynamic/runtime variant, then take a look at something like `std::type_info`. You might be able to come up with a non-trivial solution using it.

# Answer
> 1 votes
You can use a hash table for behaviors and access the elements by their `typeid`:

```
typedef std::unordered_map<const std::type_info*, AbstractBehaviour*> BehaviourHashTable;

// ...

template<typename T>
T* GetBehaviourOfType(void)
{
    if (_behaviours.count(&typeid(T)) != 0){
        return static_cast<T*>(_behaviours[&typeid(T)]);
    }

    return nullptr;
}

```

This is much faster than using `dynamic_cast`.

Example (where RunBehaviour is a sub-class):

```
AbstractBehaviour* run = GetBehaviorOfType<RunBehaviour>();

```

Insert into the table with:

```
_behaviours[&typeid(*behaviour)] = behaviour;

```

---
Tags: c++
---


# Question
Title: How to create a material with variable color
I'm new to Unity and trying to create a Carrom game. Since all the White and Black pieces, Queen basically have the same material and physical properties and texture except for their color, I'm trying to create a single material that I could assign to all 3 types of objects but could then set the material color per object type. Can this be achieved in Unity (I'm using 5.3.2)?

# Answer
`MaterialPropertyBlock` probably what you are looking for. Just make sure to create the block *once* and cache it, to save on garbage collection.

I'd create one `MaterialPropertyBlock` per piece color (so a red and a black, with the material by itself being white), cache them, and apply the block to each piece as needed.
> 5 votes

# Answer
In a simple case you can change the main albedo color of the material of an object by assigning a different Color to

```
gameobject.renderer.material.color

```

Note that some advanced materials have multiple color properties which serve different purposes. In that case `Material.color` might not be the color you actually want to change and you have to use the `material.SetColor(propertyName, color)` method.

Also, in some cases a renderer can use more than one material. In that case `renderer.material` will be the first material. When that is not the one you want to change, you can find the other materials in the `renderer.materials` array.

By the way: Changing the color of the material of an object at runtime causes an entirely new material to be created. So when you have a large number of colored objects in your game but only a small number of different colors, it might be far more efficient to have a small number of different materials and assign these to the objects (as in Hamaz Hasan's answer) or use a MaterialPropertyBlock (as in the answer by Draco18s).
> 2 votes

# Answer
Actually normally people get benefit and consider it as a feature of Unity. For example, in Carrom you'd probably have to have 3 colors (Black, White and Red). What you have to do is to create 3 Materials for the above colors and apply at all 3 types of object. So from that you can change a single color from material and all the objects would change their color having this material attached.

Although you can set same physical properties to all the objects.
> 0 votes

---
Tags: unity, materials
---


# Question
Title: MonoGame-based animation system fails to change animation
We have a problem with the animation. The problem is that it won't play the right animation. We are using a spritesheet with 4 frames: idle, movement and so on. Here's the code we are using:

```
class Animator : Component, IUpdateable
{
    private SpriteRenderer spriteRenderer;
    private int currentindex;
    private float timeElasped;
    private float fps;
    private Rectangle[] rectangles;
    private string animationName;
    private Dictionary<string, Animation> animations;

    public Animator(GameObject gameObject) : base(gameObject)
    {
        animations = new Dictionary<string, Animation>();
        fps = 5;
        spriteRenderer = (SpriteRenderer)gameObject.GetComponent("SpriteRenderer");
    }

    public void Update()
    {
        timeElasped += GameWorld.Instance.deltaTime;
        currentindex = (int)(timeElasped * fps);

        if (currentindex > rectangles.Length - 1)
        {
            GameGetGameObject.OnAnimationDone(animationName);
            timeElasped = 0;
            currentindex = 0;

        }

        spriteRenderer.Rectangle = rectangles[currentindex];
    }

    public void CreateAnimation(string name, Animation animation)
    {
        animations.Add(name, animation);
    }

    public void PlayAnimation(string animationName)
    {
        if (this.animationName != animationName)
        {
            this.rectangles = animations[animationName].GetRectangle;
            this.spriteRenderer.Rectangle = rectangles[0];
            this.spriteRenderer.Offset = animations[animationName].GetOffSet;
            this.animationName = animationName;
            this.fps = animations[animationName].GetFps;

            timeElasped = 0;
            currentindex = 0;
        }
    }
}

```

That's part of the animation code. Next is the player class that uses the animation code.

```
class Player : Component, IUpdateable, ILoadable, IAnimateable
{
    private float speed = 50;

    public Player(GameObject gameObject) : base(gameObject)
    {

    }

    public Animator Animator
    {
        get { return (Animator)GameGetGameObject.GetComponent("Animator"); }
    }

    public void Update()
    {
        Move();

    }

    public void Move()
    {
        Vector2 translation = Vector2.Zero;
        KeyboardState KeyState = Keyboard.GetState();

        if (KeyState.IsKeyDown(Keys.W))
        {
            translation += new Vector2(0, -1);

            Animator.PlayAnimation("MovingZero");
            Animator.PlayAnimation("MovingOne");
            Animator.PlayAnimation("MovingTwo");

        }

        if (KeyState.IsKeyDown(Keys.S))
        {

            translation += new Vector2(0, 1);
            Animator.PlayAnimation("MovingZero");
            Animator.PlayAnimation("MovingOne");
            Animator.PlayAnimation("MovingTwo");

        }

        if (KeyState.IsKeyDown(Keys.A))
        {

            translation += new Vector2(-1, 0);

            Animator.PlayAnimation("MovingZero");
            Animator.PlayAnimation("MovingOne");
            Animator.PlayAnimation("MovingTwo");

        }

        if (KeyState.IsKeyDown(Keys.D))
        {

            translation += new Vector2(1, 0);

            Animator.PlayAnimation("MovingZero");
            Animator.PlayAnimation("MovingOne");
            Animator.PlayAnimation("MovingTwo");

        }

       Animator.PlayAnimation("MovingZero");
        GameGetGameObject.GetTransform().Translate(translation * GameWorld.Instance.deltaTime * speed);

    }

    public void CreateAnimations()
    {
        Animator.CreateAnimation("Idle",new Animation(4,0,0,42,32,4,Vector2.Zero));
        Animator.CreateAnimation("MovingZero", new Animation(4, 0, 1, 42, 32, 4, Vector2.Zero));
        Animator.CreateAnimation("MovingOne", new Animation(4, 0, 2, 42, 32, 4, Vector2.Zero));
        Animator.CreateAnimation("MovingTwo", new Animation(4, 0, 3, 42, 32, 4, Vector2.Zero));

    }

    public void LoadContent(ContentManager Content)
    {
        CreateAnimations();
        Animator.PlayAnimation("Idle");
    }

    public void OnAnimationDone(string animationName)
    {
    }
}

```

We are using the component-pattern. This is our animation component:

```
class Animation : Component
{
    private float Fps;
    private Vector2 Offset;
    private Rectangle[] rectangles;
    public float GetFps { get; set; }
    public Vector2 GetOffSet { get; set; }

    public Rectangle[] GetRectangle
    {
       get { return rectangles; }
       set { rectangles = value; }
    }

    public Animation(int frames, int yPos,int xStratFrame, int width, int height, float fps, Vector2 offset)
    {
        rectangles = new Rectangle[frames];
        Offset = offset;

        Fps = fps;

        for (int i = 0; i < frames; i++)
        {
            rectangles[i] = new Rectangle((i + xStratFrame) * width,yPos,width,height);
        }
    }
}

```

And finally the code for the sprite renderer:

```
class SpriteRenderer : Component, ILoadable, IDrawable
{
    private GameObject gameObject;
    public Texture2D sprite;
    private string spriteName;
    private float layerDepth;
    public Vector2 Offset { get; set; }
    public Rectangle Rectangle { get; set; }

    public SpriteRenderer(GameObject gameObject, string spriteName, float layerDepth)
    {
        this.gameObject = gameObject;
        this.spriteName = spriteName;
        this.layerDepth = layerDepth;
    }

    public void Update()
    {
        Update();

    }

    public void LoadContent(ContentManager content)
    {
        this.sprite = content.Load<Texture2D>(spriteName);
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(sprite, gameObject.GetTransform().GetPosition(), Rectangle, Color.White);
    }
}

```

Basically the player can move and it plays a part of the animation but not all of it. How do I fix the animation playback?

# Answer
you reset the animation each time

```
    }

   Animator.PlayAnimation("MovingZero");
    GameGetGameObject.GetTransform().Translate(translation * GameWorld.Instance.deltaTime * speed);

}

```

and

```
        Animator.PlayAnimation("MovingZero");
        Animator.PlayAnimation("MovingOne");
        Animator.PlayAnimation("MovingTwo");

```

won't work. you have to wait to finish the animation first or all statements will be called first, then the last will be rendered

monogame have 2 loops, the draw and update loop. you need a counter that counts the frames, each frame you have to increment it and check which frame now should be rendered.
> 1 votes

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


# Question
Title: transfer 3d model processing from Xna to Android?
I developed an XNA scenario in a desktop application and I need to make the same scenario in an Android app so I need to process data on the desktop computer and just display it in Android app using socket programming. For now, I can just transfer text from my desktop app to the android app, but how can I transfer a 3D model from XNA to Android? The model format is FBX.

# Answer
> 1 votes
FBX is a common interchange format, so ideally just need to find a library or framework on Android that supports loading them. Alternatively, convert the FBX files to some other format that your Android framework or libraries can load.

If you don't current have any investment into a particular API on Android, and

* you want to just load the FBX files directly: search Google for "Android FBX loading API" or similar terms, evaluate the features of the resulting technologies against the rest of your needs, and choose one.
* you want to convert the FBX files to something else: first choose the 3D graphics framework you're going to use on Android, then search Google for tools for converting FBX files to any of the formats supporting by your chosen 3D graphics framework's import pipeline.

---
Tags: xna, android
---


# Question
Title: How to use objects with different attribute values in Swift?
I think this is a really basic question and to make it easier to understand what I do not understand, I use the following scenario.

**Scenario:** I have two or more ships in my game. They should have different attributes like name, hitpoints and score. I want shoot at them and get score points for it.

**My approach:** I extended SKSpriteNode to get my own `ship class`. And when I fire a bullet collision detection will tell me when it hits.

```
import SpriteKit
class ship: SKSpriteNode {
        var hitpoints: Int = nil?
        var score: Int = nil?

    func createPhysicsBody(){
        self.physicsBody = SKPhysicsBody(circleOfRadius: self.size.width / 2)
        self.physicsBody?.dynamic = true
            ...
    }
}

func didBeginContact(contact: SKPhysicsContact){
    switch(contact.bodyA.categoryBitMask + contact.bodyB.categoryBitMask){
        case shipCategory + bulletCategory:
            contactShipBullet(contact.bodyA, bodyB: contact.bodyB)
            break;
        default:
            break;
    }
}

```

**Problem:** Swifts collision detection returns physicsBody objects and their parent is the game scene. So I do not know the SKSpriteNode of this physicsBody nor ship's hitpoints (to decrease it by 1) or score.

**Thought:** At the end I am not sure if my approach is a good one. What should be the best way to give objects on screen attributes and how can I get/change those attributes after a collision is detected by the physics engine?

# Answer
Might be a bit late, but I did this same thing recently. The simplest method for me was to give each SKSpriteNode object a unique name, and parse the sprite's name from the description property:

`sprite.physicsBody?.description`
> 2 votes

---
Tags: collision-detection, gameobject, swift
---