title: Camera moving down

text:
# Question
Title: Camera moving down
I'm working on Unity and I have already set how to smoothly move up camera when player get on higher position. But if player is on position which is below on camera, then you lost " life ". I need a way to show score and highscore but on way that when you lost " life ", camera is moving down.

For better explanation you can see how look like lost " life " on Doodle Jump game. youtu.be/wjofzwaC\_Oo?t=18m30s , did you catch how he lost life and how camera move? I need that move ;)

This is my code which I used to move camera higher during game and it's attached to MainCamera.

```
void Update ()
    {
        playerHeightY = player.position.y;

        if (playerHeightY > platCheck)
        {
            PlatformManager ();
        }
        float currentCameraHeight = transform.position.y;
        float newHeightOfCamera = Mathf.Lerp (currentCameraHeight, playerHeightY, Time.deltaTime * 100f);

        if (playerHeightY > currentCameraHeight)
        {
            transform.position = new Vector3 (transform.position.x, newHeightOfCamera, transform.position.z);
        }

        else
        {
            if (playerHeightY<(currentCameraHeight-5f))
                {
                   SceneManager.LoadScene("Scena1");
                }
        }

```

Thanks :)

# Answer
I'm assuming your code `if (playerHeightY<(currentCameraHeight-5f))` is a check to see if the player has fallen off the screen, below the view of the camera. In this case, you do not want to hard code in `5f` because you may later want the change the size of your camera viewport.

Instead, change the entire inside of your `else` statement to the following:

```
Camera cameraComp = this.GetComponent<Camera>();
Plane[] planes = GeometryUtility.CalculateFrustumPlanes(cameraComp);
if (!(GeometryUtility.TestPlanesAABB(planes, player.collider.bounds)))
{
    // handle death
}

```

This checks to see if the bounding box of the player is within the view of the camera. If the player is NOT in view of the camera, we handle the death. A note: this will also kill the player if he moves off the left or right of the screen. If you just want death off the bottom of the screen, you need to check if the player has fallen towards the bottom frustum plane. Comment on this answer if you would like help with that.

Now, onto your question, it's actually a lot easier than you think. If you want camera movement exactly like Doodle Jump, all you need to do is set the camera to interpolate to one screen length lower than the bottom of your camera's view INSTEAD of to the player's height:

```
bool died = false; // PUT THIS OUTSIDE OF YOUR UPDATE FUNCTION

...

else
{
    Camera cameraComp = this.GetComponent<Camera>();
    Plane[] planes = GeometryUtility.CalculateFrustumPlanes(cameraComp);
    if (!(GeometryUtility.TestPlanesAABB(planes, player.collider.bounds)))
    {

        float currentCameraHeight = transform.position.y;

        if (!died)
            float finalCameraHeight = currentCameraHeight - (currentCameraHeight - playerHeightY);

        float newHeightOfCamera = Mathf.Lerp (currentCameraHeight, finalCameraHeight, Time.deltaTime * 200f);

        transform.position = new Vector3(transform.position.x, newHeightOfCamera, transform.position.z);
        died = true;
    }
}

```

This finds the distance from the current camera height to the fallen player, then moves the camera down far enough to where the player is falling from the top of the screen like doodle jump.

This should work and yes I know the code is really ugly but I'm at work right now so I didn't want to post any solutions that may not work because I can't test. Comment on this if something doesn't work and I'll try to help.
> 0 votes

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


title: AABB Collision Problems in SFML

text:
# Question
Title: AABB Collision Problems in SFML
I have a problem with AABB collision.

I am making a top down rougelike in SFML and my collision algorithm does't quite work properly.

HERE IS A GIF OF THE PROBLEM.

It mostly works, except for when you're against the corner of the block and hold the direction towards the block for a second. For some reason, after about a second, the player is clipped through the block to the adjacent side.

I think the problem is caused when, for example, the `x` axis needs to be resolved as the player is approaching the object from the left, but the `y` penetration ends up being more than the `x` and thus the collision is resolved incorrectly.

This is my collision code:

```
sf::FloatRect collisionRect;
std::vector<Entity*> activeEntities;
for each (Entity* e in entities)
    if (e->otype == Dynamic)
        activeEntities.push_back(e);
for each (Entity* dynamicEntity in activeEntities)
{
    for each (Entity* target in entities)
    {
        if (dynamicEntity->sprite.getGlobalBounds().intersects(target->sprite.getGlobalBounds(), collisionRect) && dynamicEntity != target)
        {
            dynamicEntity->velocity = sf::Vector2f(0, 0);
            if (collisionRect.width > collisionRect.height)
            {
                if (collisionRect.contains(collisionRect.left, dynamicEntity->sprite.getPosition().y))
                    dynamicEntity->sprite.setPosition(dynamicEntity->sprite.getPosition().x, dynamicEntity->sprite.getPosition().y + collisionRect.height);
                else
                    dynamicEntity->sprite.setPosition(dynamicEntity->sprite.getPosition().x, dynamicEntity->sprite.getPosition().y - collisionRect.height);
            }
            else if (collisionRect.height > collisionRect.width)
            {
                if (collisionRect.contains(dynamicEntity->sprite.getPosition().x + dynamicEntity->sprite.getGlobalBounds().width - 1.f, collisionRect.top + 1.f ))
                    dynamicEntity->sprite.setPosition(dynamicEntity->sprite.getPosition().x - collisionRect.width, dynamicEntity->sprite.getPosition().y);
                else
                    dynamicEntity->sprite.setPosition(dynamicEntity->sprite.getPosition().x + collisionRect.width, dynamicEntity->sprite.getPosition().y);
            }
        }
    }
}

```

**EDIT:** I have tried making only one call to getPosition() getSprite() etc., and that only makes it glitchier.

**EDIT2:** I made a gfy of the problem. Sorry for the low res.

# Answer
> 1 votes
This is actually a pretty common problem. You are correct in your guess that it evaluates the y collision first since your physics or what not push you vertically into the block quicker than your horizontal movement.

Currently you evaluate the **greater** collision first. You shouldn't do this. Instead, evaluate the lesser of the two collisions first. i.e. if you jump into a wall and your jump speed is faster than your horizontal movement speed, it will evaluate the horizontal collision with the wall first instead of the the vertical jump.

I'll be honest, I didn't bother to read all your code as this issue is so common. Feel free to comment if my answer doesn't work for your specific needs and I'll do a better job reading.

**EDIT:** So I took a look at your code and it seems like you do the following:

1) Check for the intersections of the AABB's and store that collision rectangle in `collisionRect`.

2) Set velocity equal to zero.

3) Check if the width of the bounding box is greater than the height. This essentially checks if the collision is a y-axis collision.

4) If it is a y-axis collision, check to see if `collisionRect`contains the top of the sprite. This essentially checks if a collision has occurred at the top of the sprite.

5) If a collision has occurred at the top of the sprite, then set the sprite's position to the top of the `collisionRect` (put it on top of the thing you collided with).

And then repeat steps 3, 4, and 5 with an x-axis collision and right and left instead of top and bottom.

**EDIT:** So as crazy as this sounds, I believe that your bug occurs when `collisionRect` is exactly a square (when the height is equal to the width). This would cause the freezing since your code doesn't account for this situation. It would also make sense that it would evaluate the y-axis collision first simply because that if your first check (the if-statement). Off the top of my head you have two options if this is the case: evaluate either the x or the y collision first before the other, or see if velocity is greater in the x or y direction and resolve that collision first (since that's the direction you're moving in). Obviously the second solution would require you not set velocity equal to zero before the checks. I would suggest setting velocity to zero *inside* to if and else if statements.

---
Tags: c++, collision-detection, collision-resolution, sfml
---


title: Zoom Camera from C# in Unity

text:
# Question
Title: Zoom Camera from C# in Unity
I am creating endless running game. I want to zoom camera when player dies to the player. I have tried using camera.FieldOfView, but it does not work. Is there another way to zoom In camera to the object when particular condition becomes true. Thanks in advance.

# Answer
> 4 votes
As I said the trick you can use is to just activate Smooth Camera Follow when your player dies. You can take the script for `Smooth Follow` from this answer.

Now,

* Attach it to camera.
* Play and properly configure it, as you want.
* Disable the script.
* Enable it when your player dies.

**Note:** This is for 3D environment, as you are trying to change FOV of camera, which is applicable in perspective view. If you are developing a 2D game then let me know.

**Update:** As you already have camera follow script for your 2D game, just change the `Camera.main.orthographicSize`.

```
Camera.main.orthographicSize = 1;

```

You can also make a coroutine for some smooth effect

```
IEnumerator ZoomIn ()
    {
        while (Camera.main.orthographicSize > 1) {
            yield return new WaitForSeconds (0.01f);
            Camera.main.orthographicSize -= 0.1f;
        }
    }

```

Just call `StartCoroutine ("ZoomIn");` once when your player dies.

---
Tags: unity, camera
---


# Question
Title: Smooth Scene transitions with SceneManager and additive scene in Unity
I'm trying to work with the new SceneManager class with Unity, I'd like to have smooth transitions between scenes. Currently I suppose that the only way to do those transitions is to manually implement them on the scene objects leveraging on the fact that scenes can be loaded additively.

In pseudo code I image something like:

```
for gameObject in previousSceneGameObjects
    gameObject.animateSceneExit()
endFor

for gameObject in nextSceneGameObjects
    gameObject.animateSceneEnter()
endFor

```

I feel that there is something I'm missing :P which is the best approach that you'd suggest? Is it my approach valid?

# Answer
Your `animateAppear` term indicates that you want fade-in, fade-out effect. Correct me if I am wrong, for that,

Just a tricky suggestion :)

I think you can achieve this by placing a black or white sprite above all. fade it in when you are exiting from scene, and in next scene you can do the same in opposite way when entering into another scene. No need to use additive scene.
> 1 votes

---
Tags: unity, architecture, scenemanager
---


# Question
Title: Calculate total area of a composition of images
I'm trying to calculate the total area of a game object composed of several images. For each image, I know:

* Width, Height
* X, Y
* Rotation
* ScaleX, ScaleY
* OriginX, OriginY

Where OriginX/Y are floats in the range \[0, 1\] indicating the relative point inside the image. Also, this is the center of the rotation and the location where the image is placed regarding the X/Y coodrinates.

I have this algorithm which works fine without taking the rotation into account.

```
float left = float.MaxValue;
float right = float.MinValue;
float bottom = float.MaxValue;
float top = float.MinValue;

foreach (Image i in images)
{
    float w = i.Width * i.ScaleX;
    float h = i.Height * i.ScaleY;

    float l = i.X - i.OriginX * w;
    float r = l + w;
    float b = i.Y - i.OriginY * h;
    float t = b + h;

    left = Math.Min(left, l);
    right = Math.Max(right, r);
    bottom = Math.Min(bottom, b);
    top = Math.Max(top, t);
}

float totalW = right - left;
float totalH = top - bottom;

```

What do I have to do to take rotation into account?

I know how to calculate the area of the rotated rectangle but don't know how to take the pivot point into account.

Also, I know this can be achieved easily by using transform matrices but this is going to be a part of a standalone library with no dependencies (including a math library with matrices).

---

**EDIT**

My goal is to compute the axis-aligned bounding box of the whole composition.

# Answer
A rotation around a pivot point is performed by translating the geometry so that the pivot coincides with the origin, rotating, and translating the same amount back.

This holds whether you use matrices or just write out the operations, that is:

```
x' = oX + cos(theta) * (x - oX) - sin(theta) * (y - oY)
y' = oY + sin(theta) * (x - oX) + cos(theta) * (y - oY)

```

is the literal expansion of `v' = T(pivot) * R(theta) * T(-pivot) * v`:

```
     | 1  0  oX |   | +cos(theta)  -sin(theta)  0 |   | 1  0  -oX |   | x |
v' = | 0  1  oY | * | +sin(theta)  +cos(theta)  0 | * | 0  1  -oY | * | y |
     | 0  0  1  |   | 0            0            1 |   | 0  0  1   |   | 1 |

```

Depending on if your scale applies around the pivot point or the world origin, you either scale before the rotation, or scale your input vector. I'm going to assume you scale around the pivot point:

```
x' = oX + cos(theta) * sX * (x - oX) - sin(theta) * sY * (y - oY)
y' = oY + sin(theta) * sX * (x - oX) + cos(theta) * sY * (y - oY)

```

which is the literal expansion of `v' = T(pivot) * R(theta) * S * T(-pivot) * v`:

```
     | 1  0  oX |   | +cos(theta)  -sin(theta)  0 |   | sX 0  0 |   | 1  0  -oX |   | x |
v' = | 0  1  oY | * | +sin(theta)  +cos(theta)  0 | * | 0  sY 0 | * | 0  1  -oY | * | y |
     | 0  0  1  |   | 0            0            1 |   | 0  0  1 |   | 0  0  1   |   | 1 |

```

As your goal is to compute the axis-aligned bounding box of the extents of all the components in the composite shape, compute all the corner points and take the min/max of X and Y.
> 1 votes

# Answer
Are they overlapping? Otherwise the total area is simply the sum of all images areas, where each image's area is equal to the respective w\*h. Rotation doesn't affect area.
> 1 votes

---
Tags: algorithm, geometry
---


# Question
Title: Player keeps bumping when walking over to another sprite
So, my problem is that my play when he walks over to another sprite he will stop.

I fixed that by adding a physics material with 0 density and 0 friction to the player

and adding a circle collider instead of a box collider to the player.

---

However now I have another problem where my character keeps bumping when it enters another sprite.

The sprites are at the exact same height, the objects are just as big and the colliders have the exact size.

I would like to get a fix for this problem, which still allows me to use `Rigidbody2D.AddForce` for movement.

---

**Video of my problem :**

Video :\>

---

**How to recreate the problem :**

Make a sprite, add a `Circle Collider 2D` to it and a `Rigidbody2D`.

That will be the player.

Next, make some platforms and add a `Box Collider 2D`

Now, if you let your player walk over the platforms it will (or should..) start bumping.

# Answer
> 2 votes
Short answer: Don't build a 2D jump and run using a physics engine. I worked on such a project and we were mostly fighting the physics engine.

Long answer: Have less, bigger colliders. We built our levels using tiled. We placed sprites and colliders seperately so one block of floor got only one, big collider. It still has issues at ramps, when falling on the edge of a platform, and so on. There were lots of raycasts and custom forces involved and it was not pretty.

You could also try and merge the colliders / create them on the fly from the sprites, though this is probably more complex.

---
Tags: unity, physics
---


# Question
Title: HumanIK Z axis Up in Maya for Unreal Engine
I am pretty stumped! I want to use HumanIK in Maya to throw together some prototype animations for my game that is being developed in Unreal Engine 4.7

The issue is that Unreal requires Z axis to be UP and this results in HumanIK Skellies to end up on their backs in Maya when Created.

Is there a way to Configure HumanIK to use Z axis as Up?

Or is there another way around this? I see plenty articles on studios using HumanIK for Unreal so I must be missing something really silly in regards to this issue!

Any help will or suggestions would be greatly appreciated!

# Answer
I figured our that on export you can switch the axis on export to work with the target engine allowing you to use HumanIK for unreal :D/
> 1 votes

---
Tags: maya, unreal-4
---


# Question
Title: Adding a small slide when player releases left/right key
The aim is for the player object to slow down and stop instead of just stopping dead. The following codes works ok when the player is not jumping, but gets stuck in an object if the player is in the air when they do it.

Left key released event:

```
if hsp = 0 exit;

hspeed = -3;
friction = 0.20;

if obj_Player.hspeed = 0
{
hspeed = 0;
}

```

Right key released event:

```
if hsp = 0 exit;

hspeed = +3;
friction = 0.20;

if obj_Player.hspeed = 0
{
hspeed = 0;
}

```

Horizontal collision code for interest:

```
if (place_meeting(x+hsp,y,obj_bound))
{
while(!place_meeting(x+sign(hsp),y,obj_bound))
{
    x += sign(hsp);
}
hsp = 0;
}

x += hsp;

```

# Answer
> 1 votes
So, the way I've implemented similar movement controls in the past is I assign the player to have an x and a y, as well as an xSpeed and ySpeed. X Speed is always constant while the player is holding down left or right, then slowly goes down to zero when they release. Then, instead of directly incrementing player x, you use x speed.

Doing this for both x and y should fix this problem, though if that's not the problem, more context would be appreciated.

# Answer
> 0 votes
Lets break this down into a few cases while only considering movement in a single horizontal direct ion.

Case 1, the user presses and holds the horizontal movement key. In this case our movement is taken by adding the vector V to the objects position.

Case 2, the user releases the horizontal movement key. In this case our movement varies with respect to time since the key has been released. This means we need to parameterize our velocity vector V by time.

Lets modify V by V * F(x), where F(x) = sin(x). Now let x be a real number between 0 and pi/2. Now suppose we want the player to slow down over the course of 1s, so t is a real number between 0 and 1. Then x = pi/2 * t.

Psuedo code for this might be something like this...

```
func Update:
  if (t > 0)
    player_vels.push_back(V * sin(pi/2 * t))
    t -= deltaT

func UserInput:
  if (horiz_key_press)
    player_vels.push_back(V)
    t = 0
  else if (horiz_key_release)
    t = 1

```

This is an example, not guarenteed to be most efficient. I encourage you to think over this.

# Answer
> 0 votes
The best way to implement this would be through utilizing acceleration, which is linked to the controls, as opposed to using methods on button release. On every update loop, apply friction, then acceleration, then cap the speed. Assuming the user is holding down a movement key, acceleration should cancel out the friction and keep the user at maximum speed, but if the user releases the movement key, friction will apply every update until the character comes to a stop.

Example code:

```
update()
{
    acceleration = getAccelFromButtonsPressed()
    velocity = velocity - friction
    velocity = velocity + acceleration
    if (velocity > maxSpeed)
    {
        velocity = maxSpeed
    }
    position = position + velocity
}

```

---
Tags: 2d, collision-detection, platformer, game-maker
---


# Question
Title: How to create realism similar to scenes rendered in Vray?
I am tasked to make a game which requires very realistic interior scenes. Unity's bedroom demo(http://blogs.unity3d.com/2015/11/10/bedroom-demo-archviz-with-ssrr/) really caught my eye. See I know how to code but I am not good at modelling in 3DS. I see some amazing images only generated in 3DS using vray. But those are static images and the moment the same models are imported into Unity, they end up looking unrealistic. But somehow in the demo, Unity managed to create a very realistic looking scene. So here are my questions :

Guys this is a really long question and might not be clear. So sorry, tried to describe it the best I can. Appreciate any answer, tips or advice. Thanks guys

# Answer
> 3 votes
You can't have the realism provided by ray casting engines (e.g. vray) without a ray casting. You can only get very close to it.

Ray casting is a **simulation**, xou simulate how lightrays bounce off from objects. Hardware rendering is not a simulation. You can get close to it, but most of the times, it requires you to re-render the scene multiple times in different position, for exampls shadow mapping.

---
Tags: rendering, unity, lighting, 3dsmax
---


title: How do I use Libgdx viewport for UI?

text:
# Question
Title: How do I use Libgdx viewport for UI?
I am using LibGDX to make a game for Android and I am using 2 `Viewports`. One for UI and one for the actual game content. My problem is I can't find a good way to scale my UI using a `Viewport`.

This is a picture of my UI using a `FitViewport`:

As you can see it adds space on the top and bottom to fit the screen, but I want my pause button to stay on the top of the screen. I tried using a `StretchViewport` and that worked well for the pause button, but then the joysticks were no longer circle because they were distorted.

Is there a way to make a `StretchViewport` that only stretches the middle? (since nothing will be in the middle I don't care about that. Should I make a custom `Viewport`? And if so, how would I go about that? Thank you for any help!

# Answer
What I ended up doing was having one `Viewport` that was an `ExtendsViewport` for just the joysticks. Then I added the pause button to the screen without using a table and manually set its size to a fraction of the physical screen resolution.

This isn't a great solution because it required another `Stage` that didn't use a `Viewport` and since I had another `Stage` I had to use an `InputMultiplexor`. Please let me know if you find a better solution that uses only one `Stage`.
> 1 votes

# Answer
I currently use a ScreenViewport on the GUI scene2d Stage, and set the size of the UI elements as inches, then just multiply it by `Gdx.graphics.getPpix()`.

This should make the UI elements consistent in size across devices, no matter the size or density of the screen.

Your GUI stage should only contain a table as well, to position the elements correctly.

Hope it helps!
> 0 votes

---
Tags: libgdx, gui, viewport
---


title: Unity 5 Command not being sent

text:
# Question
Title: Unity 5 Command not being sent
I have a client server build in Unity 5. I want to send a command from the client to the server with a GUI button click, this is for testing purposes. So on my client all I want is to click a button and then have the server display a message on its console window. Reading through http://docs.unity3d.com/Manual/UNetActions.html this seems to require a player object. With the demo I am trying to create there is no player. So I created an empty game object and called it player and assigned it a player script:

```
public class Player : NetworkBehaviour {

void Update ()
{   //receive message from camera follow script to run command from client to server
    if (isServer)
        return;

    if (GameObject.Find("Main Camera").GetComponent<CameraFollow>().sendCommand)
    {
        CmdTurnOnNetworkTransformOnServer ();
    }
}

[Command]
void CmdTurnOnNetworkTransformOnServer()
{
    UnityEngine.Debug.Log ("Received");
}
}

```

This script checks if a boolean is true on another script (the script that contains the GUI button that when clicked sets the bool to true). if it is true then I would like the server to display "Received" on the console in the editor. However I get the error "Trying to send command for non-local player." From what I can see I am following the above link properly to just display a simple message. I realise there is another route with http://docs.unity3d.com/Manual/UNetMessages.html however I would like to see if I can get a command working instead.

Full Error: Trying to send command for non-local player. UnityEngine.Networking.NetworkBehaviour:SendCommandInternal(NetworkWriter, Int32, String) Player:CallCmdTurnOnNetworkTransformOnServer() Player:Update() (at Assets/Player.cs:37)

How come I am getting this error?

This error appears in the client console window

# Answer
Reading through http://docs.unity3d.com/Manual/UNetActions.html a player object is required. This player object should be a prefab and fill the space beside player prefab under spawn info within the network manager script in the editor. I created an invisible player object, so it may aswell not be there, but for the purposes of sending a command it should be. This avoids the error of sending a command for a non-local player.
> 0 votes

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


# Question
Title: Generate random numbers without repetitions
How to generate Random numbers without repeating any numbers in the given target like(1-5000) there should be no reparation and I should be able to get 5000 randomized numbers. I should be able to run the randomized as many times as the user wants,How to do with C#

For Sample Target is (1-10) No of times to run =2

First run: 5,4,6,8,3,1,2,0,7,10

second run 6,3,5,8,4,2,0,1,10,7

Like this I should be able to get the results as many times as I run..

# Answer
As others have pointed out, what you're looking for is effectively a shuffled deck of cards. Every card (in this case, a unique number) is present exactly once, in a randomized order. By drawing cards from the deck one at a time, you create a psuedorandom number string with no repeats.

(Obviously, once you've exhausted the deck, you'll need to either reuse it or reshuffle it to generate the next number)

A fast way to do this is with a Fisher-Yates shuffle, also commonly called a Knuth Shuffle:

```
// Prepare a deck of sequential numbers from min to max:

int count = max - min + 1
int[] deck = new int[count];

for(int i = 0; i < count; i++)
{
   deck[i] = min + i;
}

// Shuffle it:

for(int i = count - 1; i > 1; i--)
{
    // Pick an entry no later in the deck, or i itself.
    int j = Random.Range(0, i + 1);

    // Swap the order of the two entries.
    int swap = deck[i];
    deck[i] = deck[j];
    deck[j] = swap;
}

// Now deck[] contains all numbers from min to max
// in a random order with no duplicates.

```

This can also be combined into one pass:

```
int count = max - min + 1;
int[] deck = new int[count];

for(int i = 0; i < count; i++)
{
    int j = Random.Range(0, i + 1);

    deck[i] = deck[j];
    deck[j] = min + i;
}

```

One neat trick is that you don't even have to shuffle all at once for this. You can randomize as you go, at a constant cost per card drawn:

```
[System.Serializable]
public class Deck<T> {
    [SerializeField]
    T[] deck;

    // Tracks a partition between the deck & discard pile.
    // All entries at i < remaining are in the undrawn deck,
    // remaining <= i < deck.Length are in the discard pile.
    int remaining = 0;

    public T Draw() {
        // If we ran out of cards, shuffle the discards to make a new deck.
        if(remaining == 0)
            remaining = deck.Length;

        // Pick a card at random from the remaining deck.
        int chosenIndex = Random.Range(0, remaining);
        T chosenItem = deck[chosenIndex];

        // Remove the card from the remaining deck and place it at the
        // top of the growing discard pile.
        remaining--;
        deck[chosenIndex] = deck[remaining];
        deck[remaining] = chosenItem;

        return chosenItem;
    }
}

```
> 11 votes

# Answer
You can achieve this by creating a list of numbers, populate it with your range, pick it and remove it. Simple cycle :)

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

public class AnyClass : MonoBehaviour
{
    // Your original list. Can be use to reset your list
    List<int> _originalList = new List<int> ();
    // List which will be used
    List<int> _numbersToGenerate = new List<int> ();

    void Start()
    {
        // For 0 - 9

        // Initializing original range. You can reset list by this
        for (int i = 0; i < 10; i++)
            _originalList.Add (i);

        // Assigning list to _numbersToGenerate list
        _numbersToGenerate = _originalList;

        // Getting unique numbers
        for (int i = 0; i < 10; i++)
        {
            int index = Random.Range (0, _numbersToGenerate.Count);
            int nextNumber = _numbersToGenerate [index];

            print ("Next Number: " + nextNumber.ToString ());

            // On DMGregory's advise for optimization. Replacing selected index with the last index
            SwapElements (ref _numbersToGenerate, index, _numbersToGenerate.Count - 1);

            _numbersToGenerate.RemoveAt (_numbersToGenerate.Count - 1);
        }

        // Reset it again
        _numbersToGenerate = _originalList;
    }

    void SwapElements (ref List<int> list, int index1, int index2)
    {
        int tmp = list [index1];
        list [index1] = list [index2];
        list [index2] = tmp;
    }
}

```
> 5 votes

# Answer
The usual approach to this scenario is to build a collection and then shuffle the contents, much like a deck of playing cards. The Fisher-Yates shuffle is a simple and effective algorithm that suits our purpose well.

Here is a minimal implementation:

```
using System.Collections.Generic;

public class Deck<T>
{
    private int index;
    private List<T> values;

    public bool isEmpty
    {
        get { return index == values.Count; }
    }

    public Deck(IEnumerable<T> seedValues)
    {
        values = new List<T>(seedValues);
        Reshuffle();
    }

    public T Draw()
    {
        T next = values[index];
        index++;
        return next;
    }

    public void Reshuffle()
    {
        index = 0;
        Shuffle();
    }

    private void Shuffle()
    {
        // Durstenfeld's version of Fisher–Yates shuffle
        System.Random random = new System.Random();
        for (int i = values.Count - 1; i >= 1; i--)
        {
            int j = random.Next(0, i);
            T temp = values[j];
            values[j] = values[i];
            values[i] = temp;
        }
    }
}

```

That can be used like so:

```
int count = 5;
var numberPool = new List<int>(count);
for (int i = 0; i < count; i++)
{
    numberPool.Add(i);
}

Deck<int> deck = new Deck<int>(numberPool);

Debug.Log("Deal 1");
while (!deck.isEmpty)
{
    Debug.Log(deck.Draw());
}

Debug.Log("Deal 2");
deck.Reshuffle();
while (!deck.isEmpty)
{
    Debug.Log(deck.Draw());
}

```
> 1 votes

# Answer
An alternative to a List, could be a Hashset, which provides a much more efficient solution.

```
// Container to store our random values
HashSet<int> RandomNumbers = new HashSet<int>();

// Function to generate a range of unique random values
private void CreateRandomNumbers(int low, int high, int amount)
{
    int count = 0;

    while (count != amount)
    {
        int value = Random.Range (low, high);
        if (!RandomNumbers.Contains (value)) {
            RandomNumbers.Add (value);
            count++
        }
    }
}

// Output our Random Numbers
private void Print()
{
    foreach (int value in RandomNumbers)
        Debug.Log (value.ToString ());
}

```
> 0 votes

# Answer
This creates an unsorted list of numbers in a range, randomized them, and then iterates through them.

```
int count = 5000;
int[] randomNumbers = new int[count];
for(int i = 1; i <= count; i++)
{
    randomNumbers[i] = i;
}
randomNumbers = randomNumbers.OrderBy(a => (new Random()).Next());
foreach(int randomNumber in randomNumbers)
{
     //use randomNumber
}

```
> 0 votes

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


# Question
Title: Is there any way to bring animation into unity without a rig/bones?
I am developing for mobile and to make the game run on lower spec mobiles, I was only going to import bones/rig for the main character. There are other humanoid characters in the scene which do move about and are rigged already in my 3d app but since they wont be controlled in anyway by the player in the game, I just wanted to bake and import their animations alone without the bones. I know unity can handle blendshapes but I am more comfortable with rigs and also cos these characters are already rigged properly.

# Answer
No. Your 3D model MUST have bones of some kind in order to tell the game engine how it should move. Bones also include optional scripts, ik chains, etc., in order to tell it how to move around. Think of it in real life - without bones your body could not move at all. Same concept here. :D
> 2 votes

---
Tags: unity, animation, skeletal-animation, rigging
---


title: Python: Programming a game GUI

text:
# Question
Title: Python: Programming a game GUI
I'm looking for some suggestion on books or tutorials to make a game GUI with inventory management, map , stats... in python, as this is the only language I know a bit of so far. I want to design it to feel like a modern game GUI, have taken a look at tkinter, but the resulting GUI/UI looks very "old". Im not going to make a game or something, but just want to make the GUI for excitement and learning.

My idea is to make images in Gimp or something similar. "Plot" the image like I would do to a point or curve in matplotlib, but with another library and define areas of the images as buttons that I can interact with with mouse and keyboard. I am fully aware that the aforementioned idea may be very bad, but I hope that it gives and idea of what I want to achieve.

# Answer
> 0 votes
If you want some help/suggestions, it would be a good idea to give more details.

Is this a 2D Game, a 3D Game? What Game Engine are you using, or What graphics library are you using?

tkinter is a desktop GUI toolkit. These are generally not used for games. For games you generally want to render the images and ui elements with a library specifically meant for games/your engine or directly through your graphics library.

Most of the time, the UI is added through a special set of classes/calls in the game engine you are using.

If you are not using a game engine generally it works like this.

First you draw your scene, the main game render. Then, if your game is 3D, you switch to a 2D rendering context on top of the 3D and then draw your ui much like you would any other game object.

If you need suggestions for python game engines to start with, I know of a couple that seem fairly popular. ( I have never used them myself though. ) Their sites should have starter tutorials to walk you through things such as making a simple game and UI.

2D: pyGame: http://www.pygame.org/ 3D: Panda3d: https://www.panda3d.org/

---
Tags: gui, python
---


# Question
Title: Maya Rigging - Shoulder joint attached to head?
I'm fairly new to modeling and rigging in Maya; so my question is: in the image below how can I unbind the rigs head from the shoulder pivot? I've searched online for why this occurs and I can only guess that it's due to bad Joint placement?

# Answer
It depends on the bind method. Go into the ANIMATION menu set and select SKIN \> BIND SKIN \[options box\] - and tell me which bind method you have selected.

I can then tell you how to weight your skin! :D

By the way, your joint placement is fine.
> 1 votes

# Answer
I would also like to add as an alternative -

You could simply use HUMANiK. Google that and youll get lots of helpful resources. It requires you deleting your old skeleton/bones, though. In the end, it is simpler to work with which is why I wanted to make you known to HumanIk. It may be right up your alley! Good luck, friend! :D
> 0 votes

---
Tags: animation, assets, maya, rigging
---


# Question
Title: How to get a pixel color from a specific sprite on touch (unity)?
I have a 2 layers of a different sprites. How can i get a pixel color from lower sprite?

I know how to get touch and world coordinates, but i have no idea what to do next.

```
Touch touch0 = Input.GetTouch(0); // screen touch coordinates
Vector2 playerPick = GetComponent<Camera>().ScreenToWorldPoint(touch0.position); // world coordinate

```

# Answer
I sample image data for my color picker utility. Raycasting will effectively return all objects that were clicked on, regardless if they appear underneath another one.

So first, you need to extract the image color data.

```
Color[] Data;
SpriteRenderer SpriteRenderer;

public int Width { get { return SpriteRenderer.sprite.texture.width; } }
public int Height { get { return SpriteRenderer.sprite.texture.height; }

void Awake()
{
    // Get renderer you want to probe
    SpriteRenderer = GetComponent<SpriteRenderer> ();

    // extract color data
    Data = SpriteRenderer.sprite.texture.GetPixels();
}

```

Then on Touch or MouseDown, you would determine if the click is inside of your image (via a collider and raycast) and then determine what pixel you clicked on inside of your image:

```
if (Input.GetMouseButton (0)) {

    // Get Mouse position - convert to world position
    Vector3 screenPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    screenPos = new Vector2(screenPos.x, screenPos.y);

    // Check if we clicked on our object
    RaycastHit2D[] ray = Physics2D.RaycastAll(screenPos, Vector2.zero, 0.01f);
    for (int i = 0; i < ray.Length; i++)
    {
        // You will want to tag the image you want to lookup
        if (ray[i].collider.tag == "TAGNAME")
        {
            // Set click position to the gameobject area
            screenPos -= ray[i].collider.gameObject.transform.position;
            int x = (int)(screenPos.x * Width);
            int y = (int)(screenPos.y * Height) + Height;

            // Get color data
            if (x > 0 && x < Width && y > 0 && y < Height)
            {
                Color = Data[y * Width + x];
            }
            break;
        }
    }
}

```

My picker is opened sourced, so if you want to further investigate this, check out https://github.com/jongallant/UnityColorPicker
> 3 votes

---
Tags: unity, 2d, color, pixel
---


# Question
Title: What tile storage method is best for tile-based game?
I am making a simple tile based game. The tiles are Ground and Wall. The entities (dynamic objects) are Box and Player. I am storing tiles as 2d array of enum variables and both Box and Player has own class that extends abstract Entity. Box are saved as list. While doing my level editor I have faced with several problems like check if tile already has some entity in it, is tile solid or soft and so on. What approach is better: to store tiles like entities (each tile in own object that contains it's own position and possibly contains link to an entity and objects are saved as list) or like 2d array and always cycle through it to make some check?

# Answer
There is never *one* best method. Only the method which works best for you and your game.

But most tile-oriented game engines I know use a 2d array of integer values for each static map layer where each entry represents the tile-type at a given tile-coordinate pair. When your tiles have more properties than can be expressed with a single ID value, this 2d array can also hold a whole structure or object per tile with all the relevant information. This can also include a reference to the mobile object which occupies it (or the list of occupying entities if your game mechanics require that) .

If tiles do not manage their occupants, then mobile objects are usually stored in a simple list which is ordered by the desired drawing order. If you have a very (very!) large number of mobile objects, you might instead use a BSP tree so you can quickly get all objects on a point or in an area.
> 3 votes

---
Tags: storage, tiles
---


# Question
Title: how to get rid of blurred and overlaping 3d shapes in javafx
I actually wanted to build a 2x2 rubiks cube. As the Box class in javafx doesn't provide the feature of building a cube with different colours on different faces, I chose to build the cubes using RectangleBuilder to build rectangles with different colours and then applied transformations to build the cubes. But while testing the code I saw that the entire display was coming in a broken manner with the edges overlapping as shown in the picture. Here is my source code:

```
package helloworld;

import javafx.scene.transform.Rotate;
import javafx.scene.PerspectiveCamera;
import javafx.scene.transform.Translate;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.SceneAntialiasing;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.RectangleBuilder;
import javafx.scene.transform.Rotate;
import javafx.util.Duration;

    public class NewFXMain1 extends Application {

    public class Cube extends Group {
    final Rotate rx = new Rotate(0,Rotate.X_AXIS);
    final Rotate ry = new Rotate(0,Rotate.Y_AXIS);
    final Rotate rz = new Rotate(0,Rotate.Z_AXIS);
    public Cube(double size, Color back,Color bottom,Color right,Color left,Color top,Color front, double shade) {
        getTransforms().addAll(rz, ry, rx);
        getChildren().addAll(
            RectangleBuilder.create() // back face
                .width(size).height(size)
                .fill(back.deriveColor(0.0, 1.0, (1 - 0.5*shade), 1.0))
                .translateX(-0.5*size)
                .translateY(-0.5*size)
                .translateZ(0.5*size)
                    .smooth(true)
                    .stroke(Color.BLACK)
                .build(),
            RectangleBuilder.create() // bottom face
                .width(size).height(size)
                .fill(bottom.deriveColor(0.0, 1.0, (1 - 0.4*shade), 1.0))
                .translateX(-0.5*size)
                .translateY(0)
                .rotationAxis(Rotate.X_AXIS)
                .rotate(90)
                    .smooth(true)
                    .stroke(Color.BLACK)
                .build(),
            RectangleBuilder.create() // right face
                .width(size).height(size)
                .fill(right.deriveColor(0.0, 1.0, (1 - 0.3*shade), 1.0))
                .translateX(-1*size)
                .translateY(-0.5*size)
                .rotationAxis(Rotate.Y_AXIS)
                .rotate(90)
                    .smooth(true)
                    .stroke(Color.BLACK)
                .build(),
            RectangleBuilder.create() // left face
                .width(size).height(size)
                .fill(left.deriveColor(0.0, 1.0, (1 - 0.2*shade), 1.0))
                .translateX(0)
                .translateY(-0.5*size)
                .rotationAxis(Rotate.Y_AXIS)
                .rotate(90)
                    .smooth(true)
                    .stroke(Color.BLACK)
                .build(),
            RectangleBuilder.create() // top face
                .width(size).height(size)
                .fill(top.deriveColor(0.0, 1.0, (1 - 0.1*shade), 1.0))
                .translateX(-0.5*size)
                .translateY(-1*size)
                .rotationAxis(Rotate.X_AXIS)
                .rotate(90)
                    .smooth(true)
                    .stroke(Color.BLACK)
                .build(),
            RectangleBuilder.create() // front face
                .width(size).height(size)
                .fill(front)
                .translateX(-0.5*size)
                .translateY(-0.5*size)
                .translateZ(-0.5*size)
                    .smooth(true)
                    .stroke(Color.BLACK)
                .build()
        );
    }
    }

    PerspectiveCamera camera = new PerspectiveCamera(true);
    @Override public void start(Stage primaryStage) throws Exception {

    Group root = new Group();
    Scene scene=new Scene(root,600,600,true);

    camera.setNearClip(0.00001);
    camera.setFarClip(10000000.0);

    camera.getTransforms().addAll (
            new Rotate(0, Rotate.Y_AXIS),
            new Rotate(0, Rotate.X_AXIS),

            new Translate(0, 0, -1000));
    scene.setCamera(camera);
    Cube c1 = new Cube(50,Color.BLUE.darker(),Color.BLUE.darker(),Color.ORANGE.darker(),Color.BLUE.darker(),Color.BLUE.darker(),Color.RED.darker(),1);
     c1.setTranslateX(100);

    Cube c2 = new Cube(50,Color.GREEN.darker(),Color.GREEN.darker(),Color.GREEN.darker(),Color.YELLOW.darker(),Color.BLUE.darker(),Color.RED.darker(),1);
    c2.setTranslateX(50);

    Cube c3 = new Cube(50,Color.CYAN.brighter(),Color.GREEN.darker(),Color.GREEN.darker(),Color.YELLOW.darker(),Color.BLUE.darker(),Color.RED.darker(),1);
    c3.setTranslateX(50);
    c3.setTranslateZ(50);

    Cube c4 = new Cube(50,Color.CYAN.brighter(),Color.GREEN.darker(),Color.ORANGE.darker(),Color.YELLOW.darker(),Color.BLUE.darker(),Color.RED.darker(),1);
    c4.setTranslateX(100);
    c4.setTranslateZ(50);

    Cube c5 = new Cube(50,Color.BLUE.darker(),Color.GREEN.darker(),Color.ORANGE.darker(),Color.BLUE.darker(),Color.BLUE.darker(),Color.RED.darker(),1);
     c5.setTranslateX(100);
     c5.setTranslateY(50);

    Cube c6 = new Cube(50,Color.GREEN.darker(),Color.GREEN.darker(),Color.GREEN.darker(),Color.YELLOW.darker(),Color.BLUE.darker(),Color.RED.darker(),1);
    c6.setTranslateX(50);
    c6.setTranslateY(50);

    Cube c7 = new Cube(50,Color.CYAN.brighter(),Color.GREEN.darker(),Color.GREEN.darker(),Color.YELLOW.darker(),Color.BLUE.darker(),Color.RED.darker(),1);
    c7.setTranslateX(50);
    c7.setTranslateZ(50);
    c7.setTranslateY(50);

    Cube c8 = new Cube(50,Color.CYAN.brighter(),Color.GREEN.darker(),Color.ORANGE.darker(),Color.YELLOW.darker(),Color.BLUE.darker(),Color.RED.darker(),1);
    c8.setTranslateX(100);
    c8.setTranslateZ(50);
    c8.setTranslateY(50);
    handleMouse(scene,root);
    Group k=new Group(c1,c2,c3,c4,c5,c6,c7,c8);
    root.getChildren().addAll(k);
    primaryStage.setScene(scene);
    primaryStage.show();
    }
    public static void main(String[] args) { launch(args); }
    private static final double CONTROL_MULTIPLIER = 0.1;
    private static final double SHIFT_MULTIPLIER = 10.0;
    private static final double MOUSE_SPEED = 0.1;
  private static final double ROTATION_SPEED = 2.0;
  double mousePosX,mousePosY,mouseOldX,mouseOldY,mouseDeltaX,mouseDeltaY;
  private void handleMouse(Scene scene, final Node root) {

    scene.setOnMousePressed(new EventHandler<MouseEvent>() {
        @Override public void handle(MouseEvent me) {
             mousePosX = me.getSceneX();
             mousePosY = me.getSceneY();
             mouseOldX = me.getSceneX();
             mouseOldY = me.getSceneY();
        }
    });
    scene.setOnMouseDragged(new EventHandler<MouseEvent>() {
        @Override public void handle(MouseEvent me) {
            mouseOldX = mousePosX;
            mouseOldY = mousePosY;
            mousePosX = me.getSceneX();
            mousePosY = me.getSceneY();
            mouseDeltaX = (mousePosX - mouseOldX);
            mouseDeltaY = (mousePosY - mouseOldY);

           double modifier = 1.0;

           if (me.isControlDown()) {
                modifier = CONTROL_MULTIPLIER;
            }
            if (me.isShiftDown()) {
                modifier = SHIFT_MULTIPLIER;
            }
            if (me.isPrimaryButtonDown()) {
                camera.setRotationAxis(Rotate.Y_AXIS);camera.setRotate(camera.getRotate() -
                   mouseDeltaX*modifier*ROTATION_SPEED);  //
               camera.setRotationAxis(Rotate.X_AXIS);camera.setRotate(camera.getRotate() +
                   mouseDeltaY*modifier*ROTATION_SPEED);  // -

            }
            else if (me.isSecondaryButtonDown()) {
                double z = camera.getTranslateZ();
                double newZ = z + mouseDeltaX*MOUSE_SPEED*modifier;
                camera.setTranslateZ(newZ);
            }

       }
   }); // setOnMouseDragged
 } //handleMouse
}

```

# Answer
I would recommend that you create a custom mesh for your cube utilising TriangleMesh. This should help...

https://stackoverflow.com/questions/19459012/how-to-create-custom-3d-model-in-javafx-8

You should also look at the JDK 8 JavaFX examples (http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html), as there are also importers for .obj file format models. It would then be very simple to import a custom cube created in .obj format with separate materials for each face. Or you could just create a simple billboard object with two triangles representing each face of each cube. And simply group 6 of these to form a cube, rather than using the RectangleBuilder approach. The depth buffer will then work correctly with the approach I've detailed here.

Also, http://docs.oracle.com/javafx/8/3d\_graphics/shapes\_3d.htm
> 1 votes

---
Tags: java, javafx
---


# Question
Title: What is the advantage of using "pixel coordinates" in a 2D engine?
From the Godot feature list:

> Work in pixels as your units, but scale to any screen size and ratio.

Reading the documentation they also use pixel coordinates to update the position of objects

```
move( Vector2(0,1) ) #move down 1 pixel per physics frame

```

What is the advantage of using pixel coordinates? The limitation seems to be that an object can't easily move less than one pixel per frame. For example `move object 1.5 pixels per frame`.

# Answer
> 4 votes
> ...you mean except in the case you mentioned in your question where an object moves 1.5 pixels per frame? If you want to avoid interpolation you often keep coordinates in floating-point in your game mechanics but round to the nearest integer when rendering. - Philipp

This boils down to being more convenient for humans. Why make it more complicated than it must be?

As an example, if you wanted to sample a texture directly beneath the mouse cursor:

```
Texture.Sample((MouseCoordinate.x + 1) / TextureWidth, MouseCoordinate.y / TextureHeight)
or
Texture.Load(MouseCoordinate.x + 1, MouseCoordinate.y)

```

Depending on the sampler state in use, both sample the same location.

Player movement:

```
//UINT coordinates
UINT PlayerPositionX += 0.456322f; //Camera doesn't move fast enough to increment
UINT PlayerPositionX += (UINT)0.456322f;
UINT PlayerPositionX += 0;
//All equivalent

//float (CPU) coordinates
float PlayerPositionX += 0.456322f;
then
UINT RenderPlayerAtX = round(PlayerPositionX); //Round
or
UINT RenderPlayerAtX = trunc(PlayerPositionX); //Always round down
or
UINT RenderPlayerAtX = ceil(PlayerPositionX); //Always round up

```

By drawing integer-pixel-sized sprites at integer locations, no portion of the objects (especially the edges along its' boundary) will fall in-between two pixels. Depending on the fractional part of the sprites location, the pixel that should be the left-most pixel of your sprite may output no color, distorting the sprites visual size.

---
Tags: 2d
---


# Question
Title: LibGDX efficient colored rectangle rendering
I'm creating a game in which I renderer around 1000 to 2000 solid colored squares per frame, 90% of which are the same size: ~4 px depending on the dpi. I am looking for the most efficient way to render them all using libGDX for Android and PC. Here's my past two approaches:

* **ShapeRenderer:** This worked alright but I would encounter medium lag with a 1000+ squares.
* **Meshes tutorial:** This caused heavy lag with only 100+ squares.

# Answer
> 1 votes
I'm not sure if you went that far in improving the performance, but usually the best performance you get is the smaller number of ModelBuilder::part is called.

Since, each time a new material (color) is used, you have to create a new part, it's very good to group your squares by color and create one part for each color and then use multiple MeshPartBuilder::rect to draw all of the same color.

That way the CPU and GPU will have to synchronize only once for each color in your frame.

# Answer
> 1 votes
Here is a working test class displaying 10,000 rectangles with random colors. The render loop takes \<1ms.

```
private ShaderProgram shaderProgram;
private Mesh mesh;

@Override
public void create() {
    int numberOfRectangles = 10000;

    int numberOfVertices = 4 * numberOfRectangles;
    mesh = new Mesh(true, numberOfVertices, numberOfRectangles*6, VertexAttribute.Position(), VertexAttribute.ColorUnpacked());

    int vertexPositionValue = 3;
    int vertexColorValue = 4;
    Random rnd = new Random(0);
    int valuesPerVertex = vertexPositionValue + vertexColorValue;

    short[] vertexIndices = new short[numberOfRectangles*6];
    float[] verticesWithColor = new float[numberOfVertices * valuesPerVertex];

    for (int i = 0; i < numberOfRectangles; i++) {
        float colorR = generateNumberBetweenZeroAndOne(rnd);
        float colorG = generateNumberBetweenZeroAndOne(rnd);
        float colorB = generateNumberBetweenZeroAndOne(rnd);

        float x = generateNumberBetweenNegativeOneAndPointNine(rnd);
        float y = generateNumberBetweenNegativeOneAndPointNine(rnd);

        int rectangleOffsetInArray = i * valuesPerVertex * 4;

        setValuesInArrayForVertex(verticesWithColor, colorR, colorG, colorB, x, y, rectangleOffsetInArray, 0);
        setValuesInArrayForVertex(verticesWithColor, colorR, colorG, colorB, x + 0.1f, y, rectangleOffsetInArray, 1);
        setValuesInArrayForVertex(verticesWithColor, colorR, colorG, colorB, x + 0.1f, y + 0.1f, rectangleOffsetInArray, 2);
        setValuesInArrayForVertex(verticesWithColor, colorR, colorG, colorB, x, y+0.1f, rectangleOffsetInArray, 3);

        vertexIndices[i*6+0] = (short) (i*4+0);
        vertexIndices[i*6+1] = (short) (i*4+1);
        vertexIndices[i*6+2] = (short) (i*4+2);
        vertexIndices[i*6+3] = (short) (i*4+2);
        vertexIndices[i*6+4] = (short) (i*4+3);
        vertexIndices[i*6+5] = (short) (i*4+0);
    }
    mesh.setVertices(verticesWithColor);
    mesh.setIndices(vertexIndices);

    String vertexShader = "attribute vec4 a_position;    \n" +
            "attribute vec4 a_color;\n" +
            "varying vec4 v_color;" +
            "void main()                  \n" +
            "{                            \n" +
            "   v_color = a_color; \n" +
            "   gl_Position =  a_position;  \n"      +
            "}                            \n" ;
    String fragmentShader = "#ifdef GL_ES\n" +
            "precision mediump float;\n" +
            "#endif\n" +
            "varying vec4 v_color;\n" +
            "void main()                                  \n" +
            "{                                            \n" +
            "  gl_FragColor = v_color;\n" +
            "}";

    shaderProgram = new ShaderProgram(vertexShader, fragmentShader);
}

private void setValuesInArrayForVertex(float[] verticesWithColor, float colorR, float colorG, float colorB, float x, float y, int rectangleOffsetInArray, int vertexNumberInRect) {
    int vertexOffsetInArray = rectangleOffsetInArray + vertexNumberInRect * 7;
    // x position
    verticesWithColor[vertexOffsetInArray + 0] = x;
    // y position
    verticesWithColor[vertexOffsetInArray + 1] = y;
    // z position (screen coordinates)
    verticesWithColor[vertexOffsetInArray + 2] = 0;
    // red value
    verticesWithColor[vertexOffsetInArray + 3] = colorR;
    // green value
    verticesWithColor[vertexOffsetInArray + 4] = colorG;
    // blue value
    verticesWithColor[vertexOffsetInArray + 5] = colorB;
    // alpha value
    verticesWithColor[vertexOffsetInArray + 6] = 1f;
}

private float generateNumberBetweenNegativeOneAndPointNine(Random rnd) {
    return rnd.nextFloat() * 1.9f - 1f;
}

private float generateNumberBetweenZeroAndOne(Random rnd) {
    return rnd.nextFloat();
}

@Override
public void render() {
    long start = System.currentTimeMillis();
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);

    shaderProgram.begin();
    mesh.render(shaderProgram, GL20.GL_TRIANGLES);
    shaderProgram.end();

    System.out.println("render() took: "+(System.currentTimeMillis()-start)+"ms");
}

@Override
public void dispose() {
    mesh.dispose();
}

@Override
public void pause() {

}

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

}

@Override
public void resume() {

}

```

Even if you were to generate mesh for each frame, the time is \<=5ms on my Mac, here is an example (Warning!!! - flashing images - epilepsy attach may be induced):

```
private ShaderProgram shaderProgram;
private Mesh mesh;
private Random rnd = new Random(0);

@Override
public void create() {
    String vertexShader = "attribute vec4 a_position;    \n" +
            "attribute vec4 a_color;\n" +
            "varying vec4 v_color;" +
            "void main()                  \n" +
            "{                            \n" +
            "   v_color = a_color; \n" +
            "   gl_Position =  a_position;  \n" +
            "}                            \n";
    String fragmentShader = "#ifdef GL_ES\n" +
            "precision mediump float;\n" +
            "#endif\n" +
            "varying vec4 v_color;\n" +
            "void main()                                  \n" +
            "{                                            \n" +
            "  gl_FragColor = v_color;\n" +
            "}";

    shaderProgram = new ShaderProgram(vertexShader, fragmentShader);
}

private void generateMesh() {
    if (mesh != null)
        mesh.dispose();

    int numberOfRectangles = 10000;

    int numberOfVertices = 4 * numberOfRectangles;
    mesh = new Mesh(true, numberOfVertices, numberOfRectangles * 6, VertexAttribute.Position(), VertexAttribute.ColorUnpacked());

    int vertexPositionValue = 3;
    int vertexColorValue = 4;

    int valuesPerVertex = vertexPositionValue + vertexColorValue;

    short[] vertexIndices = new short[numberOfRectangles * 6];
    float[] verticesWithColor = new float[numberOfVertices * valuesPerVertex];

    for (int i = 0; i < numberOfRectangles; i++) {
        float colorR = generateNumberBetweenZeroAndOne(rnd);
        float colorG = generateNumberBetweenZeroAndOne(rnd);
        float colorB = generateNumberBetweenZeroAndOne(rnd);

        float x = generateNumberBetweenNegativeOneAndPointNine(rnd);
        float y = generateNumberBetweenNegativeOneAndPointNine(rnd);

        int rectangleOffsetInArray = i * valuesPerVertex * 4;

        setValuesInArrayForVertex(verticesWithColor, colorR, colorG, colorB, x, y, rectangleOffsetInArray, 0);
        setValuesInArrayForVertex(verticesWithColor, colorR, colorG, colorB, x + 0.1f, y, rectangleOffsetInArray, 1);
        setValuesInArrayForVertex(verticesWithColor, colorR, colorG, colorB, x + 0.1f, y + 0.1f, rectangleOffsetInArray, 2);
        setValuesInArrayForVertex(verticesWithColor, colorR, colorG, colorB, x, y + 0.1f, rectangleOffsetInArray, 3);

        vertexIndices[i * 6 + 0] = (short) (i * 4 + 0);
        vertexIndices[i * 6 + 1] = (short) (i * 4 + 1);
        vertexIndices[i * 6 + 2] = (short) (i * 4 + 2);
        vertexIndices[i * 6 + 3] = (short) (i * 4 + 2);
        vertexIndices[i * 6 + 4] = (short) (i * 4 + 3);
        vertexIndices[i * 6 + 5] = (short) (i * 4 + 0);
    }
    mesh.setVertices(verticesWithColor);
    mesh.setIndices(vertexIndices);
}

private void setValuesInArrayForVertex(float[] verticesWithColor, float colorR, float colorG, float colorB, float x, float y, int rectangleOffsetInArray, int vertexNumberInRect) {
    int vertexOffsetInArray = rectangleOffsetInArray + vertexNumberInRect * 7;
    // x position
    verticesWithColor[vertexOffsetInArray + 0] = x;
    // y position
    verticesWithColor[vertexOffsetInArray + 1] = y;
    // z position (screen coordinates)
    verticesWithColor[vertexOffsetInArray + 2] = 0;
    // red value
    verticesWithColor[vertexOffsetInArray + 3] = colorR;
    // green value
    verticesWithColor[vertexOffsetInArray + 4] = colorG;
    // blue value
    verticesWithColor[vertexOffsetInArray + 5] = colorB;
    // alpha value
    verticesWithColor[vertexOffsetInArray + 6] = 1f;
}

private float generateNumberBetweenNegativeOneAndPointNine(Random rnd) {
    return rnd.nextFloat() * 1.9f - 1f;
}

private float generateNumberBetweenZeroAndOne(Random rnd) {
    return rnd.nextFloat();
}

@Override
public void render() {
    long start = System.currentTimeMillis();

    generateMesh();

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

    shaderProgram.begin();
    mesh.render(shaderProgram, GL20.GL_TRIANGLES);
    shaderProgram.end();

    System.out.println("render() took: " + (System.currentTimeMillis() - start) + "ms");
}

@Override
public void dispose() {
    mesh.dispose();
}

@Override
public void pause() {

}

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

}

@Override
public void resume() {

}

```

# Answer
> 1 votes
I'm not familiar with LibGDX or openGL so I can't provide code for you, but I believe what you are wanting is possible and called instanced drawing.

Essentially, you'll bind 2 (or more) vertex buffers:

1. Vertex buffer - A unit square
(0,0) (1,0) (0,1) and (1,1)
2. Instance buffer
WorldMatrix + Color for each instance

Using the appropriate instanced draw command, the GPU will render the same 4 vertices over and over, automatically swapping the WorldMatrix and Color for each. You can use multiple instance buffers to render more objects than will fit in a single one. The size of each instance I've suggested is 5 float4's == 80bytes. For comparison, the memory footprint that a typical 2048x2048 RGBA texture occupies (about 67MB) would hold about 838,000 instances. Once your instance count goes past 100k, your framerate may start dropping.... LOL!

```
//For 14567 instances
SetInstanceBuffer1(); //First 10000
DrawInstanced(10000);
SetInstanceBuffer2(); //remainder
DrawInstanced(4567);
SetInstanceBuffer3(); //100 frequently updated objects
//InstanceBuffer3 was created small so updating it is very fast
DrawInstanced(100);

```

If you'll be frequently updating one part of the buffer, but not the other, i.e. colors change per frame, but positions are usually the same, you can split one buffer into two. As such, you could upload a new color buffer every frame without having to upload a bunch of unchanged WorldMatrices.

```
//14567 instances (world matrix + color) occupies about 1.16Mb
//Smaller buffers means faster updates

SetUnitSquareVertexBufferToSlot1(); //4 vertices
SetPerInstanceWorldMatrixBufferToSlot2(); //14567 matrices
//14567 world matrices occupies about 932Kb
SetPerInstanceColorBufferToSlot3(); //14567 colors
//14567 colors occupies about 233Kb
DrawInstanced(14567);

```

**Edit:**
http://learnopengl.com/#!Advanced-OpenGL/Instancing

It's not specific to LibGDX; I leave it to you to understand where/how to integrate this into your code.

**Geometry shader version:**
Feed the GPU a single vertex buffer. Each vertex contains the top-left corner of each square, width, height, and color. The geometry shader emits the same four vertices for each input vertex:

```
(Position.X, Position.Y)
(Position.X + Width, Position.Y)
(Position.X, Position.Y + Height)
(Position.X + Width, Position.Y + Height)

```

As such, each input vertex **is** an "instance". As with instancing, each input vertex may be assembled from multiple buffers/slots, again, allowing you to update the color buffer without uploading redundant information.

---
Tags: java, libgdx, rendering, efficiency
---


# Question
Title: Should I always prefer a Uniform Buffer Object to a uniform variable for per-model uniforms in OpenGL?
I was looking for a way to update uniforms for all of my scene objects efficiently and I came across the following gamedev stackexchange question, where the top answer gives a bonus tip. It states:

> So long as all your shaders agree on the layout and binding point of each such buffer then updating becomes a breeze. **Models have no need to know anything about shaders at all. They need only update the model-view matrix in their constant buffer and the rendering pipeline will use it automatically**

emphasis mine.

On the face of it, this seems like a preferable option; I don't have to worry about the uniform's location in a specific program object, or whether a program is bound to the current OpenGL context. I'll just establish a convention in my application for uniform variable names, update some global uniform buffer and render. This would also be nice if I have to support GLSL 1.5 and earlier, where I can't explicitly have a layout location qualifier in my vertex shader.

However, I read in this thread that some users disagree, saying that using UBO's over plain old uniforms incured an undesirable performance penalty.

Should I always prefer using UBO's over uniform variables? What are the pros and cons of each option for *per-model uniforms*?

# Answer
> 1 votes
**CPU side:**

```
struct ModelPerInstance
{
  matrix World;
}

class Model
{
public:
  void Draw() = 0;
  ...
private:
  ModelPerInstance m_perInstance;
}

UpdateUniformBufferSlot0(camera->GetViewProj()); //Once per frame
foreach...
{
  UpdateUniformBufferSlot1(model->GetPerInstance()); //Once per frame, per model
  model->Draw();
}

```

Children of the Model class can append more-specific, per-instance, data to subsequent uniform slots.

```
UpdateUniformBufferSlot2(specificTypeOfModel->GetModelSpecificPerInstance());

```

The contents of slot 2 may contain entirely different layout/data from model to model and the model doesn't need to know about which shader is active to bind it. When you create the shared buffer, you just need to be sure to size it for the largest thing you are going to put into it. Since shaders can't read beyond the end of a constant buffer, it doesn't matter that the unused part of the buffer is empty or garbage; it won't be read anyway.

**GPU side:** (sorry for D3D-style)

```
cbuffer cb_ModelPerInstance
{
  matrix g_World;
}

```

---
Tags: opengl
---


title: Build a vbo once every second

text:
# Question
Title: Build a vbo once every second
I have a VBO storing some data in my game. The thing is, the data can change at a rate of about a second. The data is not fixed size, meaning that some objects will sometimes be visible, sometimes invisible and could even have a different polygon count. I'm trying to figure out how I could do that efficiently using VBOs. In immediate mode, I would simply not call the render method of the single objet, and it would simply not appear! And if I needed more polygons, I would just... call glVertex2f more often! I understand why using immediate mode is really bad in performance, but I really can't think of any good way to "build" the VBO.

I thought about using a list, append the vertices to the list and then create the vbo, but this would have, I think, three drawbacks. More CPU intensive, requires more memory copying, and would require me to recreate (I could work this out) the VBO every time, since I don't know the size before building the lists!

Is there a common way of building a VBO for many small objects without using a list?

Some pseudo code:

```
void GlobalRender()
{
    foreach (chunk in chunks)
    {
        if (chunk.RequiresUpdate)
        {
            chunk.UpdateVBO(); //In there, that's where I don't know how large I'll need my VBO to be.
        }

        chunk.Render();
    }
}

void UpdateVBO() //The code called above
{
    foreach (node in nodes)
    {
        if (node.Visible)
        {
        //Emit vertices from here!
        }
        else
        {
            //There's nothing here really, just pointing out that there could be no vertices for a single node
        }
    }
}

```

# Answer
> 1 votes
Firstly, I'm sure you're aware of this, but I'll state it just in case: your draw calls don't take their data from the buffers directly, rather, they refer to the enabled attribute arrays in the currently bound **Vertex Array Object**, or VAO. So, for every object you want to draw, you bind the associated VAO and GLSL program, and call the `glDraw*` function you need to draw your model. So, when you say

> In immediate mode, I would simply not call the render method of the single objet, and it would simply not appear!

This is the same thing that you would do with modern, programmable OpenGL. Just don't call the `glDraw*` command related to your model, and it won't show!

Now, onto your question. We need to know more about the nature of your data in order to properly answer, but right off the bat, we can address a few issues:

> And if I needed more polygons, I would just... call glVertex2f more often!

Well, this is not a good idea at all. Even in immediate mode, using `glBegin()` and `glEnd()` and all those `glVertex()` calls between them is not recommended at all. You mention that the option of updating the buffer is CPU intensive, but it doesn't get more CPU intensive than `glBegin()` and `glEnd()` when it comes to OpenGL.

> I really can't think of any good way to "build" the VBO

Without knowing more about your models, I will assume that your model's vertices will indeed need to change once per second, in which case you have a Dynamic VBO. In that case, you have no choice; you have to update the vertex buffer object. However, there are several practices you can adhere to to make this process more performant, and these are discussed here and here

# Answer
> 0 votes
**Disclaimer: I am by NO means an expert. I've written projects similar to this and this is the way I used and it seemed to work well.**

This is a very complicated subject. Optimizations are a huge part of video games, and very difficult. Here are a few of my suggestions.

You have a list of nodes that can be visible or not. You need to come up with a formula to reduce the number of vertices so not show the inside vertices. It'll be worth it. This can save you like 100k vertices.

Secondly for each chuck make sure to record the size and beginning vertices so when you update you can use `glSubBufferData`

You mentioned it's a voxel engine. I know when dealing with them you should simplify the vbo to only include the edges. Basicly don't include the middle. I'm not sure if you're doing this already but obviously this can save like 100k worth of vertices.

As for objects *(Anything not being the map itself)* should be in a separate vbo.

---
Tags: c#, opengl, models, vbo, vertex-buffer
---


# Question
Title: 2D Infinite Runner : how to manage background layers?
First of all, sorry for this post, I guess this already has been discussed. I browsed stackexchange and the web but I couldn't seem to find a clear information for my case, with always mixed results.

So I'm making a mobile game with Unity, and am re-starting the development from the beginning in order to have smooth performances. The game is a 2D runner (Canabalt style). Though there will be two modes :

* One story mode with about 12 levels precisely designed which will be always the same
* One arcade mode with randomly generated level (platforms).

**Main features :**

* Back and Foreground Parallax (5-6 layers totally, with different movement speed)
* Automatically running, manually jumping over holes and attacking ennemies

**So I have a few interrogations :**

* The classic question : should I make it like a theadmill, having a fixed player position, and making the level move forward. Or should I be moving the character as the camera follows him ? Given the fact that I want multiple parallax background. Are there differences performance-wise ?
* A linked question : should I use the perspective camera and play with the Z axis ? or keep the orth camera ? I'm not sure how it affects the performances.

Then, having read many topics, I guess I should try to move back the objects and backgrounds, instead of instantiating and destroying them all the time when doing a random level, right ? And for my pre-designed levels (not random) should I split the background to display it step by step, in terms of performance ?

*I already know how to scroll my backgrounds, make a parrallax effect with my 5-6 layers, here I'm looking for tips to start clean with the smartest development style, especially in terms of performances and would like to have some hints on which are the best practices to follow*

Maybe you have other good practices to share with me... I'm hoping I'm not asking too much, thanks for any insights !

Have a good day

# Answer
Many infinite runners scroll the world instead of the player to prevent the problem of float overflow. Also, this makes several things easier to manage like player movement and the camera.

For scrolling backgrounds, you can use parallax scrolling. Basically, farther objects appear to move less relative to closer objects across the same distance.

For example, when you scroll the endless terrain by a value of 5f to simulate movement, you can scroll the background by half that value which makes it look farther away. By scrolling, I just mean position.x -= 5f.
> 1 votes

# Answer
If it's a 2D game you'd be better off using ortho camera. If you want to "zoom in" / "zoom out", you can change the orthographic size, which would give an effect similar to moving the camera closer and farther in perpsective mode.

About your first question, I'd recommend moving the player rather than moving the world. You can check the limits of unity in terms of position (which are very large) and if you decide you might reach those limits, then you can have a code that as soon as the player reaches a certain position, move it and the entire world back. But don't move all the objects and background every frame.

About your parallax, since I recommended using orthographic camera, you can't just put them in different Zs. What you can do is either have the backgrounds that are farther away move a bit in the direction that the camera moves (but less than the camera), making it so the camera moves slower compared to those backgrounds than to the level objects.

Another method which might be easier, is to have a separate camera that only shows the background, and it moves slower than the main camera. This will cause the background to move slower. (the main camera will not display the background)
> 0 votes

# Answer
Re: #2 - There is no "performance difference" between ortho projection and perspective. In both cases, vertices are transformed by a similarly sized matrix (4x4). One may produce larger on-screen geometry than the other and, therefore, more pixels to shade, but neither is preferred-by or optimized-for the GPU. Perspective will probably just look wrong.

Re: #1 - Yes, do treadmill:
Consider:

-A stationary ortho camera
-1 full-screen quad for each parallax level
-A number of recyclable sprites for powerups (instanced quads)
-A number of recyclable sprites for the terrain (also instanced quads)
-A number of recyclable sprites for the enemies (also instanced quads)
-A sprite for the character (yep, a quad instance)

The character is animated in place at (0,0).
The camera is always at (0,0).
The position of on-screen objects are in view/camera space.
The camera's position delta, per frame, is added to each of the parallax quads' UV coordinates. The delta is scaled by a different factor for each quad producing the parallax effect.
The camera's position delta, per frame, is subtracted from each of the on-screen objects' positions.
The camera's position delta, per frame, is used to determine whether new objects have come on screen and/or old objects need to be recycled.

The framerate for drawing everything except the power-ups is approximately fixed. With fewer than 100 textured power-up quads on screen, you should expect no significant framerate decrease.

Since everything I've described being on screen is a textured quad, each frame could be rendered with a single, instanced, draw call. I would expect a game organized as such to produce upwards of 1200 fps on my couple-year-old GTX (not counting update logic).
> 0 votes

---
Tags: unity, parallax-scrolling
---


title: Ray casting fails when it shouldn't

text:
# Question
Title: Ray casting fails when it shouldn't
I have two objects that should collide. My player should stand on a ship. The position where my player stands, is exactly on the edge of two adjacent triangles (in the ship's model). To Check for collision, I'm using ray picking. I cast a ray from the player's hips downwards. This intersection tells me if the player should be falling (no collision), or if there is a floor under his feet (collision). In some occasions, the ray is fired exactly between two triangles, causing the ray to not collide, causing the player to fall through the floor.

I've solved this in my "RayIntersectsTriangle" function by slightly increasing the triangle's size. It feels hacky, and like it's bad practice.

I realise I could also solve this by casting multiple rays from the player downwards, and check if at least one collides. But obviously, this consumes more operations, and also feels like it should not be the way to do it.

FYI: The RayIntersectsTriangle function definitely works, no question. I'm just wondering if floating point precision is messing this up.

Is there a way to make sure that a raycast can never pass between two triangles in a mesh due to floating point errors, or should I make a workaround like I did?

# Answer
> 0 votes
Casting multiple rays won't hurt your performance much since your running time will still be O(n).

Another word of advice. Programming is a pretty messy enterprise. You shouldn't worry about something being "hacky" or bad practice if your solution works (i.e it doesn't cause bugs, runs in a reasonable time/space complexity). You'll find that a lot of things in game design and graphics are "hacky" but work (one such example is phong shading).

Hope this helps.

---
Tags: xna, raycasting
---


# Question
Title: Dynamically generating triangles from points
I'm working on 2D lighting.

I have a list of points that have been calculated and when I draw lines from the light origin to the point it works. The problem is connecting the points into triangles. It always overlaps the walls, and I can't figure this it.

The problem not being the drawing, but connecting the points as to not overlap the map is my problem.

This is my code that generates the vertices

```
for (int i = 0; i < rays.size(); i++) {
    int roffset = (i * 2);
    glm::vec3 ray = rays[i];

    glm::vec3 ray2 = rays[i+1];

    if (i == rays.size()-1) {
        ray2 = rays[0];
    }
    pointsV2.push_back(ray.x);
    pointsV2.push_back(ray.y);
    int offset = (6* i);

    lines[offset + 0] = ray.x;
    lines[offset + 1] = ray.y;
    lines[offset + 2] = mX;
    lines[offset + 3] = mY;
    lines[offset + 4] = ray2.x;
    lines[offset + 5] = ray2.y;

}

```

The rays are sorted clockwise. I'm not sure what else to include, but let me know if I need to give something else.

These are just the lines:

# Answer
First sort all the intersection points either clockwise or anticlockwise around the origin. There are many answers here on gamedev that will help you out in doing that. Just add one more condition that if two points are on the same line (angle is the same), the less distant point will be pushed to the array first.

Once you have done that, finding each triangle is easy. A triangle is made of two adjacent points in the sorted array and the origin point. If the points are collinear (`abs(triangle_area) <= epsilon`), then don't render the triangle.

**NOTE:** From your second image, it can be seen that your ray intersection test doesn't handle all vertex cases correctly (maybe due to floating point errors), which I think you should fix.
> 2 votes

---
Tags: opengl, c++, 2d
---


# Question
Title: How do I find and change a value of ALL the instance around another instance GAME MAKER
I basically need that, changing a variable of all the instance (all of the same object) around another instance (another, or the same object).

I have tried with collision\_rectangle but it doesn't work.

Edit: This gives a better explication of what i want to do

ObjA = Object that inicially changes ObjB variable

ObjB= Object that is produced massively

ObjC= Object that produces ObjB

What im doing(or trying to do):

1. ObjA Appears.
2. ObjA moves down, and check for any ObjB instance
3. If it finds a ObjB instance, change the variable "chain" from "false" to "true". If the ObjA gets out of the room, without finding any instance, delete it
4. (In ObjB) If chain = true && any other ObjB instance near{ other ObjB chain = true} 5.(In ObjB).If Obj chain = true && instance of ObjC near{ with (objC){ //Do something, for example, create ObjD in the same position and erase itself } }

What i want to do is change the objC that emmits ObjB, To ObjD that produce ObjE. And ObjD will work the same as objC but is going to produce ObjE. Its like a cycle

# Answer
By "around" I am assuming that you want to change the variable of the target objects a certain distance to the flag object, now, let the object whose variable will change be obj\_A, and the object which will make obj\_A change variable be obj\_B. Now try the following:

```
//this is run in obj_A
if distance_to_object(obj_B)<100
{
variable1+=1
}

```

Of course the 100, "variable1" and "+=1" are just examples. If you want the region of space where changes take place to be rectangular, try this:

```
//this is run in obj_A
if abs(x-obj_B.x)<50 and abs(y-obj_B.y)<50
{
variable1+=1
}

```

With regards to the expansion of the question, I am not sure what is described here. I would suggest giving some background information on what the game is like and why are the objects doing what they are doing, perhaps given the objects names like "bullet" "player" etc. so it is more recognizable.

I would suggest, in case you are not aware, to use the "with" command, which allows an instance to temporarily make another instance or all instances of another object do something. Examples:

In obj\_Explosion:

```
if instance_exists(obj_Enemy)
with(obj_Enemy)
{
    if distance to object (other)<100
    {
    HP-=10
    }

}
with (instance_nearest(x,y,obj_Enemy))
{
instance_destroy()
}

```

The annotate version of the above is this:

```
if instance_exists(obj_Enemy) //the object "obj_Explosion" is checking if there are any enemies.
with(obj_Enemy)  //the "Explosion" now asks all the "Enemies" to do the following:
{
    if distance to object (other)<100 //the enemies each check if it is close to the "other" instance, in this case, the explosion.
    {
    HP-=10 //if the enemy is close, it takes damage from its own "HP"
    }

} //here the section in which the enemy is doing things is over, back to the "Explosion"
with (instance_nearest(x,y,obj_Enemy)) //Now the explosion checks for the particular enemy that is the closest to itself
{
instance_destroy() //...and destroys it
}

```
> 0 votes

---
Tags: software-engineering, game-maker
---


title: Unity particle system not working

text:
# Question
Title: Unity particle system not working
I have a prefab with a particle system attached. In the code I play the particle by using this code

```
            ps.enableEmission = true;

```

When i run the game, and that code executes, the particle emitter does not emit anything in the "game" window unless i press simulate button in the "scene" window.

Anybody knows why?

# Answer
Yea, it is difficult to handle it like this.

Just mark it as Play On Awake, set any duration (no unlimited life), make prefab and instantiate it instead of Play or Enable
> 1 votes

# Answer
For the emission property to work the particle system has to actually be playing. To do this you can either enable `Play On Awake` in the `ParticleSystem` component or you use the `Play` method on an instance of the component.

As a side note, if you are using 5.3+ the `enableEmission` property is now obsolete and you may want to consider using the `emission` property. One thing to keep in mind when using this property is you have to assign it to a variable before attempting to modify it:

```
public ParticleSystem _ps;
...
private void Update()
{
    ParticleSystem.EmissionModule module = _ps.emission;
    module.enabled = true;
}

```
> 1 votes

# Answer
set the particle system as Play on Awake, and disable the particle system. set it active when you want to start and de-active when you want to stop.
> 0 votes

---
Tags: unity
---


title: Unity 3D: Raycasting for gun hits

text:
# Question
Title: Unity 3D: Raycasting for gun hits
I am having trouble understanding raycast hits in Unity3D.

I am trying to create an FPS game, so I have a gun, bullets and so on.

My script for the bullets is:

```
 var Bullet : Transform;
 var Spawn : Transform;
 var fireRate : float;

 private var nextFire : float;

 function Update ()
 {
     if(Input.GetButtonDown("Fire1") && Time.time > nextFire)
     {
         nextFire = Time.time + fireRate;
         Shot();
     }
 }

 function Shot()
 {
     var pel = Instantiate(Bullet, Spawn.position, Spawn.rotation);
     pel.rigidbody.AddForce(transform.forward * 8000);

 }

```

It is very simple, but now I don't know how to make, that I have an object somewhere or terrain or something like that, and when I shoot, it reacts e. g. by displaying a little smog where you hit and ground parts blow up and so on.

I was searching for it on the net, but I can't find a solution. I read something about raycast, but I have no idea how to use it.

# Answer
> 1 votes
Unless your projectile is going slow enough to see you probably don't want to spawn it using physics and then throw it. It's really to end up with a lot of unwanted behavior this way.

Instead, I'd use Physics.Raycast and then use the resulting RaycastHit to see what you hit. In order to raycast:

```
    RaycastHit hit;
    if (Physics.Raycast(transform.position, transform.forward, out hit))
    {
        Collider target = hit.collider // What did I hit?
        float distance = hit.distance; // How far out?
        Vector3 location = hit.point; // Where did I make impact?
        GameObject targetGameObject = hit.collider.gameObject; // What's the GameObject?
    }

```

If you find that you're casting and hitting things you shouldn't, use the overloaded method call to add a `LayerMask` or if you want to hit multiple things you can instead use Physics.RaycastAll which will return a `RaycastHit[]` and then you can iterate through the things you hit.

I know your question was worded more towards how to do the effects (like impact) but this route will also allow you to do that specifically by giving you the exact coordinates of the impact.

The only arguments I've heard against this approach are

1. Wanting to get a hint of where you're shooting. IRL this is done using tracer rounds. In your game you might want to replicate this sort of thing using a TrailRenderer.
2. Wanting bullets to be affected by gravity and wind. That's not something raycasting can do. I still wouldn't instantiate a bullet GameObject and throw it with force. I'd probably recommend in this case actually calculating the trajectory yourself and then you'd have to manually do some sort of casting.

# Answer
> 0 votes
If you didn't use raycast you could just do something like

```
explosionclone = Instantiate(explosion,this.gameObject.position, Quaternion.identity);

```

If that was attached to the bullet prefab it would spawn the explosion at hit point, as the bullet already knows its position =)

If you want only explosions on walls, tag your walls - 'walls' then use:

```
function OnCollisionEnter (col : Collision)
{
    if(col.gameObject.tag == "walls")
    {
        explosionclone = Instantiate(explosion,this.gameObject.position,
        Quaternion.identity);
    }
}

```

---
Tags: unity, raycasting, unityscript
---


# Question
Title: Unity 5.3 C#: How to disable multiple game objects with one collision?
I'm making a top down perspective game with a gunner automatically moves on a pre-set path, and you shoot and destroy targets to remove barriers. The idea is that you control the bullet's direction after firing and it can pass through laser gates, but the gunner cannot. There are several targets and barriers.

What I want: If the bullet hits the local target, the local target and local barrier are destroyed.

I tried making each target and barrier as children of empty game objects, and I attempted to destroy the empty parent to solve this problem. Please advise.

(Showing only relevant code)

```
using UnityEngine;
using System.Collections;

public class MagicBulletScript : MonoBehaviour {

    public Transform magicBulletTransform;

    void Start () {
        magicBulletTransform = transform;
    }

    void OnTriggerEnter (Collider other){
        var progressParent = this.transform.parent.gameObject;

        if (other.gameObject.CompareTag("Obstacle")){
            Destroy (this.gameObject);
        }

        if (other.gameObject.CompareTag("Target")){
            Destroy (progressParent.gameObject);
            Destroy (other.gameObject);
        }
    }
}

```

# Answer
Order does matter man..

First destroy obstacle then bullet itself, otherwise after destroying itself it will never execute next lines. And once you destroy own parent then no need to destroy child (itself).

And there is no need to keep own `transform` in a `public Transform`, you can access it anywhere through `transform`.

```
using UnityEngine;
using System.Collections;

public class MagicBulletScript : MonoBehaviour {

    //public Transform magicBulletTransform;

    void Start () {
        //magicBulletTransform = transform;
    }

    void OnTriggerEnter (Collider other){
        var progressParent = transform.parent.gameObject;

        if (other.gameObject.CompareTag("Target")){
            Destroy (other.gameObject);
        }

        if (other.gameObject.CompareTag("Obstacle")){
            Destroy (progressParent);
        }
    }
}

```
> 3 votes

---
Tags: unity, c#, collision-detection, 3d, game-design
---


# Question
Title: Managing game states (states flow, controlling the state machine...)
I am currently struggling really bad to make the game states management. Before we dig into the problem, I must point out that I do know about state machines, I do have both implemented (states and state machine) and they look SIMILAR to this, or you can also see my real outdated implementation from my github. Alright, my questions are:

1. Do states usually operate state machines? Eg.: when the LoadingState finishes (based on the 'update' method) loading something, it tells the state machine to pop the stack (which would pop the LoadingState) and to push a new state, such as PlayingState **OR** should the LoadingState only notify the state machine and the state machine itself will be responsible of knowing whats the next state based on the state that has requested a pop? Knowing which state has requested a pop (pop, push or whatever) is kind of difficult because it needs some advanced C++11 stuff, which requires a lot of 'not-easy-to-understand' code and validations (asserts), unless we use an enumeration inside each state and do a simple switch (again, more typing).
2. Should the state machine be opperated/accessed (pointer/static functions) by any component (class, system, manager...) of the game? Eg.: the main player has moved into a map teleport and it triggered a map load, since it should be teleported to a new map. Should the Map class notify the state machine to push the MapTransitionState into the stack, through a static (it doesnt really make any sense to have a pointer to the state machine in the map class) public function?

Thanks a lot!

# Answer
> 1 votes
The state machine is used to change its behaviour depending on the current state active, it:

1. Contain states
2. Execute the behaviour of the current state
3. Contain the behaviours and values shared by *every* states it contains

Some implementations of state machines do not know the states they contain. This makes hard for them to know to which state transition. So the 'decision' to change state, and to which state, is made by the state itself. This makes the code more localized: State A only knows about State B and C, while State C only knows about State D. It's easier to look at the code and see right away what's going on from that state.

And the "Tteleporter" class should not know about the concept of "state machine". Your play state should know about the Teleporter, and detect a 'collision' between the Teleporter and the Player, and then do what's appropriate.

---
Tags: game-state
---