# Question
Title: Different objects interacting based on type
Many many thanks to anyone who chooses to take the time to read through this all and offer any advice.

I'm writing a game in which multiple different kinds of Objects move around a grid-based board structure and interact with each other in various ways. The objects are all derived from a relatively barebones base class

```
class Object{
    int ID;
    virtual void render() = 0;
    virtual void update() = 0;
    ...
};

```

I'm also loosely using a component system. So for example there's a MovementComponent,

```
class MovementComponent{
    direction currentMovementDir;
    int movementTimer;
    int speed;
};

```

Which Objects that can move contain a pointer to an instance of, which is instantiated upon creation of the Object. The Object base class has a virtual function for returning each kind of Component, as follows:

```
class Object{
    ...
    virtual MovementComponent * getMovementComponent() {return NULL;}
    virtual PathfindingComponent * getPathfindingComponent() {return NULL;}
    //etc. for every kind of Component I introduce to the game code.
};

```

And then the derived classes just override these functions to provide pointers to their components. This is great, because I can sort of determine the kind of object I'm dealing with based on whether or not I get NULL when I request to see the object's various components. So as an example,

```
class Player : public Object{
    MovementComponent * movementC_;
    Player(){
        movementC_ = new MovementComponent;
    }
    ~Player(){
        delete movementC_;
    }
    void update(){
        //Perform input stuff here etc.
    }
    virtual MovementComponent * getMovementComponent(){return movementC_;}
}

```

and so on so forth.

My board structure is simply an array of pointers to Objects, and the movement of Objects on the board is handled by a whole different system. All of the Objects are in a linked list held by a wrapper class called ObjectManager which handles adding new objects of any kind to the game or removing them etc.

My question is that I'm having an increasingly hard time writing elegant code for the various kinds of object interactions that are meant to take place in the game. The controls are intended to be fairly simple, so for example the player just 'actions' the tile they are facing and the game logic handles how this should play out.

Lets say for example its an enemy. 'Action'ing the enemy should just attack the enemy's health based on our current weapon's strength (or something along those lines, this game isn't really about combat, but just for the sake of the example). Within the player class's update function, the part that processes input might look like

```
void Player::update(){
    ...
    if(actionKeyPressed){
        //Uses the map's list of pointers to get a pointer to whatever object is in the tile in front of the player.
        Object * target = WorldMap.getObject(pos,facing);
        if(target.getHealthComponent() && target.getIsEnemyComponent()){
            target.getHealthComponent.attack(weaponstrength);
        }
    }
}

```

But you can see how this turns into very ugly code very fast. I can't not check for a healthComponent because if there isn't one, I'll throw an error when I try to invoke its 'attack()' member function. Is there an elegant way to avoid the massive if-else branch I'm going to be sitting on here? It starts to get even worse when we look at Object interactions that might function differently in different contexts with the same Object types. Maybe there's a FriendlyTroop Object that, when actioned by the player at \< full health, heals the FriendlyTroop, but when at full health, instead sets a flag to true in the FriendlyTroop's AI that tells it to head out into battle. I guess in addition to any general advice anyone has to offer, the big questions I have are:

-Am I doing this right at all? Is there a better way to handle this overall type-checking dilemma?

-Does every element of that FriendlyTroop's AI need to be pushed out into a unique FriendlyTroopAIComponent type now so that the Player class can interact with it?

-What if I wanted to add an NPC that could perform the same actions as the Player? Would this 'action' if-else structure be better in a PlayerAction component that this NPC could then also have an instance of? Or should the NPC just be a derived class of the Player? Or vice versa???

# Answer
> 2 votes
Okay, disclaimer: this has gone completely overkill. But it was a lot of fun to put together!

The end product looks like this:

```
Object *target = WorldMap.getObject(pos,facing);
target->dispatch([&](components::EnemyTag &, components::Health &h) {
    h.attack(weaponStrength);
});

```

`dispatch` takes in any function or function object (here a lambda), and inspects its parameter list. The parameters' types are used to call the correponding `getSomethingComponent` virtual functions. If all components are found, then the lambda is called with them and `dispatch` returns `true`. Otherwise, nothing happens and `dispatch` returns `false`.

See it live on Coliru

To make the wiring simpler, I have replaced the `getSomethingComponent` virtual functions with overloads of a virtual `get_(tag<SomethingComponent>)` function. These are now an implementation detail, and are generated with a macro.

### Full code:

```
#include <type_traits>
#include <tuple>
#include <iostream>

////////////////////////////////////////////////////////////////////////////////
// Dummy tag to hold one or more types

template <class... T>
struct tag { };

////////////////////////////////////////////////////////////////////////////////
// typename params<F>::type is tag<P1, P2, ... Pn>
// where P's are the parameter types of the function or function-object F.

template <class F>
struct params : params<decltype(&F::operator())> { };

template <class R, class T, class... Params>
struct params<R (T::*)(Params...)> { using type = tag<Params...>; };

template <class R, class T, class... Params>
struct params<R (T::*)(Params...) const> { using type = tag<Params...>; };

template <class R, class... Params>
struct params<R (*)(Params...)> { using type = tag<Params...>; };

template <class R, class... Params>
struct params<R (&)(Params...)> { using type = tag<Params...>; };

////////////////////////////////////////////////////////////////////////////////
// Dereference every pointer in Args and call f with them

template <class F, class Args, std::size_t... Idx>
void derefCall(F &&f, Args &args, std::index_sequence<Idx...>) {
    std::forward<F>(f)(*std::get<Idx>(args)...);
}

////////////////////////////////////////////////////////////////////////////////
// Defining your components

namespace components {
    struct Health {
        int value = 100;
    };

    struct EnemyTag { };
}

////////////////////////////////////////////////////////////////////////////////
// Defining the base class

struct Object {

    // obj.get<Comp>() : retrieves a component by type (or nullptr)
    template <class CompType>
    CompType *get() {
        return get_(tag<CompType>{});
    }

    // dispatch : tries to call f with all of the components it requires
    // Returns whether all components were found and f was called.
    template <class F>
    bool dispatch(F &&f) {
        return dispatch_(std::forward<F>(f), typename params<std::decay_t<F>>::type{});
    }

private:

    // Define one virtual function get_(tag<Comp>) for every component type.
#define OBJECT_DECLARE_COMPONENT(CompType) \
    virtual ::components::CompType *get_(tag<::components::CompType>) { return nullptr; }

    OBJECT_DECLARE_COMPONENT(Health)
    OBJECT_DECLARE_COMPONENT(EnemyTag)

#undef OBJECT_DECLARE_COMPONENT

    // Implementation of dispatch, Params are the parameters needed by f.
    template <class F, class... Params>
    bool dispatch_(F &&f, tag<Params...>) {

        bool allGood = true;

        // Construct a tuple with the component pointers
        // For each component required by f:
        auto ptrs = std::make_tuple([&]() -> std::decay_t<Params>* {

            // One component is already missing, skip the rest
            if(!allGood)
                return nullptr;

            // Get the component of the adequate type
            auto *comp = get<std::decay_t<Params>>();

            // Failure: break the chain
            if(!comp)
                allGood = false;

            return comp;
        }()...);

        // Missing component, bail out
        if(!allGood)
            return false;

        // Call f with the dereferenced pointers
        derefCall(std::forward<F>(f), ptrs, std::index_sequence_for<Params...>{});
        return true;
    }
};

// Helper macro to override the component getters
#define OBJECT_OVERRIDE_COMPONENT(CompType) \
    ::components::CompType *get_(tag<::components::CompType>) override

// Enemy class
struct Enemy : Object {

    OBJECT_OVERRIDE_COMPONENT(EnemyTag) {
        return &enemyTag;
    }

    OBJECT_OVERRIDE_COMPONENT(Health) {
        return &health;
    }

    components::EnemyTag enemyTag;
    components::Health health;
};

int main() {
    Enemy e;
    Object &o = e;

    // Nice call syntax
    bool dispatched = o.dispatch([](components::EnemyTag &, components::Health &h) {
        h.value -= 10;
    });

    if(dispatched)
        std::cout << "Dispatched successfully!\n";

    std::cout << "Enemy has " << e.get<components::Health>()->value << "hp left.\n";
}

```

---
Tags: c++, entity-system, component-based, gameobject, entity-component
---


# Question
Title: texlod() is not supported on ps_4_0_level_9_3 , how can I do a similar operation in this case?
Ihave an interesting problem for you guys

I am trying to compile a pixel shader that I ported from GLSL and I am having trouble with a texCUBElod() function that the compiler say's is not supported on the current target, which is ps\_4\_0\_level\_9\_3 in this case.

Here is the function I am trying to compile:

```
uniform samplerCUBE EnvMap;
uniform float EnvMapLod;
float4 FS():COLOR:
{
   float4 color;
  float4 reflected;

   /*
   Processing values
   */

  color = texCUBElod(EnvMap, float4(reflected, EnvMapLod));
  return color
}

```

The compiler returns this error:

```
error X4532: texlod not supported on this target

```

Thank you very much

# Answer
> 1 votes
Yes, it's not available on the ps\_4\_0\_level\_9\_3 target.

If we look at the documentation for texCUBElod we see that it's only available in the pixel shader and only for Shader Model 3 and 4 targets; it's not available at all for Shader Model 1 and 2 targets.

Cross-check with the documentation for ps\_4\_0\_level\_9\_3 and we find that this is actually a Shader Model 2 target (with a handful of additional capabilities), not a full Shader Model 3 target.

texCUBElod is not one of those additional capabilities, hence it's not available.

Footnote 2 explains this (my emphasis):

> Feature level 9.3 effectively requires hardware that complies with the requirements for legacy Direct3D 9 shader model 3.0, but **this feature level does not make use of vs\_3\_0 or ps\_3\_0 targets**.

The solution is to use the legacy Direct3D 9 Shader Model 3.0 target, i.e. **ps\_3\_0**, not ps\_4\_0\_level\_9\_3.

---
Tags: opengl, directx, hlsl, directx9
---


# Question
Title: How do I incorporate .tmx files into my game?
Ok, so I have made a .tmx file for my first level, but I am unsure how I would load it into my game. Currently I am iterating through an internal array to set the blocks, but I need to know how to load the .tmx file into the code.

Here is my World.java:

```
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import javax.imageio.ImageIO;
import java.io.*;

class World {
    Image ground;
    Block[] blocks = new Block[46];
    int map[][] = {
            {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1},
            {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
            {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
            {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
            {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
            {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1},
            {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
            {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
            {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
            {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
        };
    World() {
        int enc = -1;
        for (int i = 0; i < map.length; i++) {
            for (int j = 0; j < map[i].length; j++) {
                if (map[i][j] == 1) {
                    enc++;
                    blocks[enc] = new Block(j * 32, i * 32, 32, 32, 1);
                } else if (map[i][j] == 2) {
                    enc++;
                    blocks[enc] = new Block(j * 32, i * 32, 32, 32, 2);
                }
            }
        }
    }
}

```

# Answer
I'd suggest taking a look at the following classes from the LibGDX framework- TiledMap, TMXMapLoader and MapRenderer.

I found a decent tutorial here with example code for reading in and rendering a tile map from a TMX file that makes pretty short work of the problem. But for the sake of providing a complete answer, what you want to do is

1. Create an Orthographic Camera- camera
2. Load your TMX file into an empty TiledMap object- tileMap, using TMXMapLoader.load(filename.TMX)
3. Create a OrthogonalTiledMapRenderer object- mapRenderer, passing tileMap as a parameter to the constructor
4. Set the view of your renderer to the camera using
mapRenderer.SetView(camera)
5. Render the tile map to the screen with mapRenderer.Render()

When stuck with solving a problem that you know would have been solved many times over by programmers before you, my advice would be to turn to well known libraries for the solution- it will save you a lot of time and avoid a lot of mistakes!
> 1 votes

# Answer
The easiest way to parse TMX files with Java is to use the **libtiled** library. It is licensed under 2-clause BSD, which means you can use it for anything as long as you give credit.

But if you would like to implement it yourself: The .tmx format is an XML-based format. That means you can parse the files with an XML parser. There are several options for this in Java. Which one you use depends on personal taste.

Depending on how you saved the TMX file, the actual layer data will be either encoded in a stream of ascii-decimal encoded integers separated by commas (aka. CSV) or a stream of int's encoded with base64. The layer data can also be compressed with gzip or zlib. You might want to disable that in the Tiled settings for now because it just makes things more complicated. When your finished game turns out too big, you can achieve even better compression by putting all of your assets in a zip archive.

You might also want to take a look at the other export formats Tiled supports. In one project I found it much easier to use the JSON format. That was because the project was using JSON for other things so I already had a good JSON library and some useful utility functions.
> 1 votes

---
Tags: 2d, tiled
---


# Question
Title: Why doesn't SDL_Surface rendering work in SDL2?
I have done the following using C++:

1) I used `SDL_CreateWindow()` to create an SDL window

```
m_window = SDL_CreateWindow("My First Side-scroller
    SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH,
    SCREEN_HEIGHT, SDL_WINDOW_SHOWN);

```

2) I used `SDL_CreateRenderer()` to create a renderer for the SDL window

```
m_renderer = SDL_CreateRenderer(m_window, -1, SDL_RENDERER_PRESENTVSYNC);

```

3) I used `SDL_CreateTexture()` to create a texture

```
m_texture = SDL_CreateTexture(m_renderer, SDL_PIXELFORMAT_RGBA8888,
        SDL_TEXTUREACCESS_STATIC, SCREEN_WIDTH, SCREEN_HEIGHT);

```

4) I created a buffer of type `Uint32` to hold texture information which is passed to the `SDL_Texture`

```
m_buffer = new Uint32[SCREEN_WIDTH * SCREEN_HEIGHT];

```

5) I created a custom pixel drawing function which is use to draw pixels at a low level and pass it to the buffer.

```
void Screen::setPixel(int x, int y, Uint8 red, Uint8 green, Uint8 blue) {
    // Checking for pixels  off screen
    // This is sufficient because the rand function can generate a negative number
    if (x < 0 || x >= SCREEN_WIDTH || y < 0 || y >= SCREEN_HEIGHT) {
        return;
    }

    Uint32 colour = 0;

    colour += red;
    colour <<= 8;
    colour += green;
    colour <<= 8;
    colour += blue;
    colour <<= 8;
    colour += 0xFF;

    m_buffer[(y * SCREEN_WIDTH) + x] = colour;
}

```

6) I used 5) along with other functions to help draw pixels on random locations in the window and make them move vertically and loop from the top of the window to the bottom of the window (like moving stars).

```
Stars::Stars()
{
    m_x_star=((2.0*rand())/RAND_MAX)-1;
    m_y_star=((2.0*rand())/RAND_MAX)-1;
}

void Stars::moveStar(){
    // starSpeed is the desired change in co-ordinate position for each pixel plotted
    double const starSpeed = 0.001;

    if(m_y_star<-0.998 && m_y_star>-1) {
        m_y_star=0.995;
    }

    m_y_star-=starSpeed;
}

```

1) to 6) works with no-error

So, onto my issue: Blitting an image using `SDL_BlitSurface` seems to require that the window is created using SDL\_Surface() for its third flag. I want to load a .png image of a spaceship I drew. Here is the code I use to load the image.

```
void Screen::update_spaceShip() {
    SDL_Surface *Image;
    Image= IMG_Load("spaceship_stock2.png");
    SDL_BlitSurface(Image,NULL,m_window,NULL);
}

```

Error message:

> cannot convert 'SDL\_Window\*' to 'SDL\_Surface\*' for argument '3' to 'int SDL\_UpperBlit(SDL\_Surface\*, const SDL\_Rect\*, SDL\_Surface\*, SDL\_Rect\*)'

What am I doing wrong?

# Answer
> 7 votes
It seems that you are looking for `SDL_CreateTextureFromSurface`. As you seem to have learned (the hard way), SDL2 doesn't really support rendering surfaces directly anymore. There are ways to do that I believe, but you should be using hardware rendering, which is implemented using surfaces. So, the modern way is to load a surface, convert that into a texture that you can use and then get rid of the surface. So something like

```
SDL_Surface* image = IMG_Load("yourimage.png");
SDL_Texture* texture = SDL_CreateTextureFromSurface(m_Renderer, image);
SDL_FreeSurface(image);

```

So, you can load a surface using `IMG_Load` and then convert that into a texture that you can render using `SDL_RenderCopy` or I believe SDL\_Image even comes with a `IMG_LoadTexture` these days. You should note that calling `IMG_Load` in your render-method is a bad idea as it allocates memory each time, so you want to do this at initialization instead.

I recommend you do some reading on the `SDL_Renderer` and it's uses. However, if you are insistent on using `SDL_BlitSurface` instead of the faster new way to render, please let me know.

---
Tags: c++, image, sdl2
---


title: Why is my button script not working?

text:
# Question
Title: Why is my button script not working?
Okay so i'm new to C# and i made this script. The goal i have in mind is that when the player is on the button and presses a button ( W in this case ) the button is switched from on to off ( or vice versa). The problem i have is that when the character stands on the button and presses W it doesn't always switch its state and i have no idea why. Any info would be appreciated.

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

public class Button : MonoBehaviour {
     public bool Pressed = false;
     Animator Anim;

     // Use this for initialization
     void Start () {
         Anim = GetComponent<Animator> ();
     }

     // Update is called once per frame
     void Update () {
         Anim.SetBool ("Pressed", Pressed);
     }
     void OnTriggerStay2D(Collider2D other){
        if (Input.GetKey(KeyCode.W)){
            if (Pressed){
                Pressed = false;
            } else {
                Pressed = true;
            }
        }
    }
}

```

# Answer
> 1 votes
As informed by the auto-generated comment, these methods are called at every frame, which means between 60 and 120 times every second approximately.

When you press `W`, you can be sure it lasts more than 1/100 seconds, which means the `bool` will switch values many times, and you have 50% chances that in the end you have what you wanted, and 50% chances that you don't.

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


# Question
Title: Why doesn't my material show up on my imported model (Unity / Blender)
UPDATE :

The material does work on smaller objects like a simple sphere, but not on my big arena model, which is actually imported from blender, any suggestions?

UPDATE :

Tried to export as .fbx, but doesn't change anything.

I've imported this material pack : https://www.assetstore.unity3d.com/en/#!/content/13004

I tried to apply it to my mesh, but only weird things happen, I can't see the texture at all. So I tried to apply this material in the "shader calibration scene" and that worked without any problem, even updating to the standard shader worked fine. So I tried to fix it with the following things :

* Rebaking lighting
* Restarting Unity
* Tweaking the material settings
* Tweaking quality settings in Unity
* Building the project

All these things couldn't fix it, but it should most likely be related to my project settings, since this material is working in another project (shader calibration)

Here are my quality settings :

I'm not sure, which information is needed to answer the question, but I can provide it if you ask for it.

Update with Object properties :

# Answer
What is described in the question is probably due to missing UV data in the model (or all UVs set to zero).

To solve it, load the original model in Blender and add an UV map. You probably need to unwrap the model, and maybe manually adjust some UVs after unwrapping.

Just get to the point of seeing the model texture in Blender isn't enough, Blender can map textures on meshes without UVs but that won't export to most game engines (if not all of them).

*The user asking the question already knows what follows but I'm adding it to the answer for a more complete answer*

**To unwrap a model**

It is recommended to use a split view, with the UV editor visible in one of the views. To split views in Blender: https://www.youtube.com/watch?v=rhh513vUgME

Then, working in the view with the model, select model, enter edit mode, press U, in the context menu that appears click Unwrap or any of the unwrapping algorithms that Blender offers (try to minimize the amount of manual edit to the UVs you will have to do after unwrapping, to zero if possible).

Double check in the UV Map editor if everything is OK with the UVs, fix what you see is wrong. This is artist work and intuition plays a fundamental role.

Now go to the texture panel and check that you are using the UV map and not generated coordinates.

Finally export your model, probably FBX is the best available option when working with Blender and Unity. Or let Unity handle the blend file (I keep my blend files away from the Unity assets directory, long story, and only place there the FBX export. This is no standard procedure or anything, just my personal preference).

In the case of this question, the use of an external material probably means that the material already comes configured to use the UV data from the model. So the step of changing the properties of the texture panel in Blender may have no effect at all. When authoring both, your own models and materials, you probably need to check the texture panel in Blender.
> 5 votes

---
Tags: unity
---


# Question
Title: Finding the Balance - Income vs Expenditure
I'm working on a game idea that uses an in-game currency, and basic business (income/outcome).

Basically, a certain type of building will generate 'income' per seconds until it hits a certain capacity (per building).

There are many different types of buildings, each with their own 'rate', 'income' and 'capacity', as well as 'cost to purchase building' in the first place.

I want to know if there is a good tactic, or strategy on how to balance this out? I don't want to make the purchasing of the buildings too easy - so the user has to only wait a few seconds ... thats pointless.

And on top of that - each building can be upgraded, which basically increases the 'rate', 'amount' and 'capacity' - with each upgrade increasingly getting more expensive - however this is relative as the user is now getting more cash flow.

Thanks.

# Answer
> 3 votes
Incremental games (not sure if you are making one) make use of a multiplication factor between building upgrades. The ideal factor is within `1.07 and 1.14` for these games. So if you pay 10 for the first building/level you pay `10 * 1.14` for the 2nd upgrade and `10 * 1.14^21` for the 20th building/upgrade. This creates a curve and eventually it takes a long time before you can upgrade. To help out you can add some extra perks after X levels to level things out and give the game some more depth as well.

Cookie clicker docs give some nice insight into these numbers. I also advice to use spreadsheets to work out the numbers and balance your game further.

# Answer
> 1 votes
Make subsequent upgrades much more expensive with smaller upgrades, for example:

1. Juice Stall - 60 coins - 1 coin / second
2. Vending Machine - 360 coins - 3 coins / second
3. Coffee Vendor - 1080 coins - 5 coins / second
4. Charity Store - (`nc^2 where n is number of buildings and c is the total CPS output of those buildings`) coins - Upgrades the output of all buildings by 1 coin / second.
5. Fast Food Chain - 12800 coins - 12 coins / second
6. ...

# Answer
> 1 votes
Every game is different, so there is no golden hammer solution. But there are a few key concepts which usually show up in every game.

## Amortization Time

When an investment generates income, it will have amortized itself sooner or later. You need to take this into account to avoid any investments from either being pointless (it won't amortize before the player completed/quit the game) or a complete no-brainer (will amortize almost immediately). When an investment generates the same resource which it costs, that's trivial to calculate: `Cost / production = amortization time`.

But it gets more complex when you have multiple resources. In that case you need to figure out the relative values of your different resources. For example, when a quarry costs 100 stone and 200 wood, and wood is twice as valuable to the player as stone, the actual cost is equivalent to 500 stone. Note that when you don't have a straightforward way to convert one resource into another, then the values of different resources can be hard to estimate. It might take a lot of testplaying to figure out if experienced players will *really* find 100 wood as valuable as 50 stone and vice versa.

## Income Growth Curve

In many economical games, the income of the player will steadily increase. That will make investments which seem ridiculously high at the start to look like spare-change in the late-game. It is important to understand how the player's income will grow over the course of your game. Ideally you should figure out a formula to calculate how much income the player should have at what stage of the game. You can then regulate your prices according to that formula.

## Diminishing Returns

This is a method to suppress income growth: The amortization time of every further upgrade to an investment should increase. This can be done by making each upgrade level more expensive, less effective or both. When you don't do that, each upgrade will take less time to achieve than the last one. At some point the player will earn resources faster than they can hammer the upgrade-button, which usually doesn't make for a very interesting game experience.

---
Tags: game-mechanics, balance, economy
---


title: Avoid unreachable rooms in duengons

text:
# Question
Title: Avoid unreachable rooms in duengons
Good evening.

Im currently trying to create a Dungeon Generator . First I place randomly some rooms. Right after that I dig in a randomized maze.

But sometimes it happens that some rooms or even some maze paths are unreachable.

Is there any way to avoid that ? Are there any good Methods for avoiding that ? Any ideas or examples?

Im currently doing it like so (pseudocode) :

1. Pick a random Number of rooms
2. Create an arraylist for those rooms
3. Pick random Positions with random sizes
4. Try to place all those rooms without overlapping and add them to the list.

-- Room placement Done --

-- Maze Generation Begins --

1. Loop over the whole Map, if Theres an empty tile ( No wall, No floor and No paths) than Beginn to grow the maze .
2. When the Statement above ist true, than create a 'Cell arraylist' and put the 'start' cell into it with the coords of the empty tile above . ( A cell just contains x and y coords) .
3. While the cell list isnt empty, Pick the latest cell (cellsList.Size()-1) and Check the possible direction it Can move. If Theres just empty space in that direction ( No wall, No floor and No paths) than the direction is true.
4. Pick a random Number and Check for every direction if the assigned Number fits with the random one. If it fits, then dig into that direction and create a new cell at the End . If Not redo this step until one paths ist diged Out.
5. At least kill 'Dead ends'. Those path tiles which are surounded by 3 empty tiles or those which are completly isolated.

I Hope I mentioned everything . Im currently at my phone and cant acess my Files at my Home PC :/ im gonna Update this later when im Back Home.

# Answer
> 5 votes
It depends on what algorithm you are using to generate your dungeon. There are algorithms which by their very nature ensure that everything is reachable:

* Algorithms which start with one room and then keep attaching new rooms at random to already existing rooms
* Algorithms which use recursive division (you start with a huge, empty room and keep subdividing by creating horizontal and vertical walls with a doorway in a random position)

But when you have already implemented an algorithm you like and you don't want to start from scratch, you can just check which parts of its output are walkable by performing a flood fill and then just delete everything not covered by the flood-fill. The main problem with this approach is that you can randomly end up with really tiny dungeons.

# Answer
> 1 votes
I once ran into a similar situation on a proof of concept, and this is how I solved it.

My dungeon was simulated as a single mesh, with different nodes which held a boolean state (floor or wall; walkable or unwalkable). I picked the center node of the largest room, then used Dijkstra's algorithm to find the shortest path between each other room to the largest room. I also weighted the values of the nodes such that a walkable node cost significantly less than an unwalkable tile. I can not remember the exact values, but it was like 1 vs 100. This was done to make sure I didn't accidentally create a duplicate path. Once the path had been found, it made all nodes in that path walkable, thus connecting all the rooms.

---
Tags: java, libgdx, algorithm, windows
---


title: Need help solving EventHandler issue

text:
# Question
Title: Need help solving EventHandler issue
I have an issue with my EventHandler for Key events in my game.

The specifics are in this forum thread: http://www.java-gaming.org/topics/problems-with-key-event-handling/37998/view.html

Basically, the issue is that a KeyReleasedEvent is fired in a very inconvenient way. I recently switched from polling to interrupting to take key input, so I'm hoping somebody has had this problem before and knows an elegant way to solve it.

I can provide more code and details if needed. Thank you for any help!

# Answer
> 1 votes
In short, you want to track whether each key is pressed separately. I can't speak to the engine you're using, but normal java events for a key being released tell you which key with `getKeyChar()` or `getKeyCode()`, even for key released events.

You can make an `int` variable for the handler object and set it equal to the key code in the `keyPressed` handler. Then, in your `keyReleased` handler, only stop the movement if the current key code equals the value of the `int` that holds the last keycode pressed.

---
Tags: java, input, events, keyboard
---


# Question
Title: What's the difference between CUDA and Shader?
I am new to CUDA, and it seems that CUDA and Shader are both GPU programs.

When we talk about GPU programming in rendering, like GPU voxelization, are we talking about CUDA or just converting data to Shader?

# Answer
In opposite to Shaders, CUDA is not restricted to a specific step of the rendering pipeline. It can be used to do calculations that are best suited for the GPU architecture, allowing people to take advantage of today GPUs architecture.

To gain better intuition on it, search the web for "GPU computing". For example, in Machine Learning with really massive data sets to process, when vectorized implementations are possible, doing it in the highly parallelized GPU will took a fraction of the time to process all that data than doing it in the CPU (note, depending of what data set we are speaking of, the process may still take a lot of time, and doing it in chunks may still be needed).

You will use CUDA to implement those algorithm to run on the GPU (or part of them). Taking advantage of its highly parallelized architecture.

http://www.nvidia.com/object/what-is-gpu-computing.html

I'm not expert on the field, but as general rule: vectorized implementations are for the GPU, while a lot of "if" conditionals or loops won't really gain a lot or probably run even slower when compared to the CPU.

A vectorized implementation is when you try to accommodate your data in big vectors/matrices and process them in a single vector/matrix multiplication (or any other supported operation required). When that isn't possible or you don't know how to do it, you will process the data sequentially using loops, one at a time (bad for GPU, little or no gain in speed).

**A brief on shaders**

With the old fixed pipeline, you can configure the GPU behavior by uploading different matrices or set certain parameters. This is the best that can be done with the old chips design back in the day when the fixed pipeline was the only option.

Modern chips evolved to be programmable. But shader standards are thought only to allow people to customize what happens in the different steps of the rendering pipeline.

The vertex shader: allow you to modify a vertex at a time. Here you will apply the projection matrix (or, as optimization, hardcode the projection calculations required by your game).

The pixel shader: allows you to "program" what happens in the production of a fragment (pixel). Lighting happens here. Yes, you heard it well, your pixel shader program will run again per each pixel (note that the number of fragments processed, the times the shader will run, won't be equal to the number of pixels on your monitor). This may sound inefficient but the GPU, with his highly parallelized design, can handle it. These kind of things is what makes necessary to have a specialized chip for 3D graphics, making software implementations only useful for didactic purposes or for the production of non real time renders.

About voxelization and the GPU: with vertex shaders and pixel shaders there are little to do to optimize voxels. But there are others stages of programmable pipelines that may helps here, like the Geometry Shader or the Tessellation Shader. They require a very modern GPU.

Each stage has a reduced set of possible inputs and produce specific outputs related to they role in the rendering process.

The language to write these shader programs is different to CUDA. OpenGL has GLSL and Direct3D has HLSL.

**Conclusion**

CUDA is used to do very expensive calculations, in the GPU, and recover the result.

Shaders are used to program what the GPU must do in each of the programmable stages of the rendering pipeline.
> 9 votes

# Answer
Shaders are typically referenced in the context of a graphics API, like OpenGL or Direct3D. They originated as small program that allowed tweaking the lighting calculations for a surfade, aka "shading" objects. Eventually, shader support was added to various parts of the fixed-function rendering pipelines inherent to GL/D3D. Folks eventually figured out how to use these shaders to do things unrelated to graphics, or at least unrelated to the fixed-function rendering pipeline. The GPUs gained support for more and more general-purpose programming and the graphics APIs eventually gained support for "compute shaders" that live outside the rendering pipeline. The last important bit is that the graphics APIs defined shaders in terms of their own unique languages, aka HLSL and GLSL.

CUDA (and the many, many related technologies) is essentially just a way to run compute shaders without the graphics API and without requiring a particular language. CUDA programs are compiled into PTX (NVIDIA's analoque to x86 assembly for the GPU, though a bit more abstract to remain compatible with GPU revisions) and come be compiled from any number of languages, be it C++, Rust, (variants of) Python, or so on. These kinds of programs could be compiled into HLSL or GLSL as well, but this is often a lot harder to develop and debug.
> 3 votes

---
Tags: shaders, gpu, cuda
---


# Question
Title: Texture filtering of look-up table in post process shader
I am doing post processing by drawing to an FBO and then applying a certain fragment shader when drawing the FBO's texture to the screen. I want to use a look-up table texture to apply color grading. Since I am targeting OpenGL ES 2.0 and possibly older PCs, I cannot use 3D textures. Instead I can use a 2D texture as an atlas of the layers of my 3D look-up table.

What I'm concerned about is correctness and performance when the texture lookup is performed. My look-up texture needs to have linear filtering so I don't have to have a full 256^3 sized look-up table to cover all hues.

My fragment shader would look something like this: Round B up and down to get the two regions of the texture to sample from, add offsets accordingly to R/G and sample the texture twice with the two offset .rg values. And finally linearly interpolate based on B.

But I as I understand it, the when the GPU encounters a `texture2D` call on a texture with linear filtering, it will be calculating the input coordinates for those calls for neighboring pixels in parallel to get a derivative. This derivative is used to determine how to sample the texture pixels.

Since this is a post process, I don't want two neighboring pixels to influence each other. It could be a black pixel from the edge of a sprite next to a bright blue sky pixel. In the look-up table, these two would need to sample distant points. So is the GPU going to decide the derivative is huge (minification) and try to linearly sample and involve all the random in-between texels on my look-up table?

Is there a way to get my linear filter to ignore neighboring pixels and only interpolate from the 4 nearest texels? Sort of like treating everything as magnification?

The problem is similar to this question that was asked in regards to HLSL, but I'm targeting OpenGL 3.0 and OpenGL ES 2.0: Color grading, shaders and 3d textures

# Answer
> 1 votes
That derivative is only used to select which mipmap out the the set to sample.

If mipmaps are disabled either by selecting GL\_LINEAR as the minimizing texture sampler interpolation or by setting the mipmap level limit to 0 then the GPU will do a simple linear interpolation.

---
Tags: opengl, glsl, opengl-es2
---


# Question
Title: Unity: How to keep the music muted on reloading the scene?
I am giving the user a UI button to mute and unmute the ingame sounds but the problem is when I mute the sounds and then when the game ends and the game scene reloads the sounds comes back up which is really annoying.

After some searching I came to know that I need to use `DontDestroyOnLoad(transform.gameobject);` but it makes the copy of the whole thing and now I have two copies of the same music.

Also I don't know if this is the only way or not but just to mute/unmute an audio source it feels kind of overkill to me since I have a many components attached to my gameobject and then just to mute/unmute it copies the whole thing.

Can someone tell me how to fix that duplicating problem and also is there any simpler way to achieve this?

# Answer
Another approach is to save a volume setting in Playerprefs from your button click function like this `PlayerPrefs.SetFloat("Volume", 0f);`

For the music object, attach a script and retrieve the volume setting in awake to set the volume on or off like this:

```
AudioSource audio_src;

void Awake(){
  audio_src = GetComponent<AudioSource>();
  audio_src.volume = PlayerPrefs.GetFloat("Volume", 1f);
}

```
> 1 votes

# Answer
You could create a static class, and just use a static variable to set if the sound is muted or not.

```
public static class ApplicationData {
    public static bool SoundOn = true
}

```

In this manner, you access the variable like so:

```
ApplicationData.SoundOn

```

This will allow you to retain the setting throughout your application.

This will not retain this data once the application closes however. If you want to retain this setting, you will need to look at storing it in PlayerPrefs before the application closes. And then load the setting from PlayerPrefs when you open the application again.
> 0 votes

---
Tags: unity, audio, gameobject, scene
---


title: Align Players Rotation

text:
# Question
Title: Align Players Rotation
I'm currently working on rope Swinging. The Rope consists of Physics Constraints/Joints and between them the rope is rendered.

I would like align my Character's Pitch to the Rope.

I'm horribly bad at vector Math, and I have trouble finding the solution. Here's a picture that shows what I want to achieve:

I tried using the Difference between two joints but somehow it doesn't work.

I'm using Unreal Engine if that helps.

# Answer
If I understand what you want, you make an object rotate to face a vector with a rotator.

So in this case you want your player's Z (Unreal's up) to face the vector between the two points on the rope it's touching.

So if we get the two nearest points on the rope (p1 and p2 for ex):

If we do (p2-p1) and normalize it, we get the direction we want the player to turn.

Then we can use a Rotator to orient the player to that vector. In this case we want to make a Rotator from a known Z axis (The vector we just found).

And then we apply the rotator we get from that on the player.

If you want to set the forward direction too, there's a "Make Rot from ZX" that will try to orient the player to meet those two vectors.

There's a Rotator class with these functions in C++ if you're using that.

(BTW some engines like Unity just let you set the up vector of your player explicitally like "player.transform.up = ropePitch" or something)

(I could also probably explain the math going on in the background but for practical use this is all you need!)
> 1 votes

---
Tags: rotation, vector, unreal
---


# Question
Title: how to change sprite of 2d object in unity during runtime?
I want to change the sprite of my 2d object from a blank box to a box with a 1 written on it upon clicking the box. how to I do that?

# Answer
> 1 votes
If you have the sprite ready, all you need to do is reference it in the script you're using.

So something like this:

```
public Sprite newSprite;
void Start () {
    gameObject.GetComponent<SpriteRenderer>().sprite = newSprite;
    //this will immediately change your sprite to the new one
}

```

Also tested the code, it works. See the SpriteRenderer reference for more info on this component.

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


# Question
Title: How can I easily render Box2D polygons with ShapeRenderer in LibGDX?
In the `PolygonShape` object, there is the method `setAsBox()` which allows for creating rectangles easily, but there is no `getAsBox()` for cases where you know the polygon is a box. I know Box2D comes with it's own renderer, but I need to make custom renders.

Also, `PolygonShape` objects have a `getVertex()` method, but it has no return, and it takes a second argument of a `vector2`, for some reason. I don't know how I'm supposed to get a vertex from that. Why isn't there just a method that returns an array of `Vector2` objects?

How can I easily render Box2D polygons with ShapeRenderer in LibGDX?

# Answer
> 0 votes
The `Vector2` parameter of `getVertex(Vector2);` is the *output* of the method (I.e. the vertex). I believe you have to supply your own `Vector2` so you can limit garbage (by using pooling or something else).

This means that you should use the supplied `Vector2` as your vertex when drawing. You can then use this `Vector2` and `drawLine();` to draw your shape.

# Answer
> 0 votes
It depends on what you want to achieve.

If what you're looking for is to, for debugging purposes, see the position of all your bodies you can use the `Box2DDebugRenderer` which takes a `World` and a transform matrix and renders a lot of information for you (it will for example show you contacts and the difference between a static and a dynamic body).

```
Box2DDebugRenderer renderer = new Box2DDebugRenderer();
renderer.render(world, camera.combined);

```

If that doesn't fit your purpose you need to iterate over the bodies in the `World` and then for each `Body` get all the `Fixture`s and render their respective `Shape`s. How to do that is slightly different depending on the type of `Shape` but for polygons it might look something like this;

```
void render(Body body, ShapeRenderer renderer) {
  for(Fixture f : body.getFixtureList()) {
    switch(f.getType) {
       case Shape.Type.Polygon:
       {
         PolygonShape s = (PolygonShape)f.getShape();
         // NOTE: You don't want to be newing this up every time, make sure you keep an array of Vector2s and reuse that!
         Vector2[] vertices = new Vector2[s.getVertexCount()];
         // Build list of transformed vertices
         for(int i = 0; i < s.getVertexCount(); ++i) {
           vertices[i] = new Vector2();
           s.getVertex(i, vertices[i]);
           body.getTransform().mul(vertices[i]);
         }

         // This assumes a closed polygon, the last vertex is connected with the first.
         for(int i = 0; i < s.getVertexCount(); ++i) {
           Vector2 a = vertices[i];
           Vector2 b = vertices[(i + 1) % s.getVertexCount()];
           renderer.line(a.x, a.y, b.x, b.y);
         }
       }
       break;
       // And then cover the other types, Circle and Egde here.
    }
  }
}

```

---
Tags: java, libgdx, box2d, jbox2d
---


# Question
Title: What shape should you use for player collision?
I'm working on a simple Box2D platformer, and I was wondering, what is the best shape to use for the player's box? I'm currently using a circle with a radius of 10, but that doesn't work well, as when the player collides with a corner, they can get stuck on it, or won't be able to move forwards properly and it feels really awkward. What should I use instead?

I've heard ovals work well for this kind of thing, but there's no easy way to create an oval in B2D without creating 3 circles on top of each other. I've also seen rectangles used, but aren't those less accurate?

# Answer
> 4 votes
Every collision shape has it's pros and cons:

The axis aligned bounding box is very cheap to do collision against, but it's very rough and it's not possible to rotate it, thus it may need to be recalculated every frame.

The circle is nice if your shape rotates, because you don't need to recalculate the shape every frame, but it's the least exact.

Convex polygons are very good for complex shapes, but they are costy in terms of CPU usage.

Concave polygons are the best in terms of match. They can define any shape, but they are very very hard to do collisiom against them.

Choosing a shape for your character depends on how complex collisions you want. For a platformer or RPG you may want to stick with the AABB, but if you want a game, where precision is key, then you should go with one of the polygon types.

# Answer
> 2 votes
Using primitives like rectangles and circles is obviously the fastest, but don't fit every object exactly so you end up with less accuracy. If you need some more accuracy you can use multiple primitives to define the collision area of an object. A much more expensive way is to create a polygonal shape for your character but it's wise to first check with a box and if there is collision with it you then check again for the polygonal object.

A nice tool to create a polygonal object.

The Intersector class has all kind of handy methods for checking collisions on different types such Poly vs Point, Poly vs Poly, Ray vs Triangles, etc.

# Answer
> 1 votes
As mentioned by others, this depends a lot of the proportions of a character. In a sprite editor you can try drawing over various hit box shapes to see how they look. How "accurate" the shape is will depend on how close it comes to covering the entire shape, without some parts sticking out of the shape.

An oval might work well around the head, but miss the side of the feet (making it hard to stand half on a ledge). If your character has a giant head for example, you might instead want to use two separate boxes (one for the head and the body).

A rectangle is a simple collision box that roughly fits the shape of "human" characters. However, if you find it getting caught on corners, you can actually make the hitbox smaller than the character. This means part of the player's sprite will be able to overlap with the level geometry (like the player's arms), but the core (torso) is what will get caught. (The bottom of the rectangle should be lined with the bottom of the feet).

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


# Question
Title: What does Unity use for 2D rendering on an Android?
I was starting to develop a 2D game in Java and Android Studio, using SurfaceView. My idea was to make my first engine to understand how game engines work, and also get complete of control over the game flow.

I have had many problems, such as FPS, and handling the stop and resume functions. On the other side, I see many 2D games made with Unity that work very nice.

What does Unity use for 2D rendering on an Android?

# Answer
According to this, the current Unity rendering options are:

* OpenGL ES 2
* OpenGL ES 3
* Vulkan (experimental)

Android also has a rendering layer called Skia. I don't know whether or not Unity makes use of Skia or not. From what I could tell digging through the documentation, Skia uses Open GL on the backend. (SO post of possible interest: How do the pieces of Android's (2D) Canvas drawing pipeline fit together?)

It's a common technique to use a 3D API like DirectX or OpenGL for 2D rendering - for instance, a lot of game UI gets handled that way.
> 2 votes

---
Tags: unity, android, rendering
---


title: Snake game - Snake Collision

text:
# Question
Title: Snake game - Snake Collision
So I am making a snake game as final assignment for semester 1 of my game dev study.

We have to write it in C# in Visual Studio 2015. I am using the .NET 3.5 framework.

So basically how my snake works is as follows:

I made a vector2 List to store the snake parts. It starts only with the head obviously. When collission with the food occurs, I add a vector2 to the list. I draw a rectangle in the paint function and I make it take over the last position of the previous snakepart. That is how my snake works and how my snake gets longer as you eat the food.

I am having trouble with the snake collision itself though.

This is the code I came up with to check if the snake collides with itself:

```
for (int i = 1; i < Snake.Count; i++)
{
    if (Snake[0].X > Snake[i].X + (i * 64) || (Snake[0].X + (i * 64)) < Snake[i].X || Snake[0].Y > (Snake[i].Y + (i * 64)) || (Snake[0].Y + (i * 64)) < Snake[i].Y)
    {
        SnakeCollission = false;
    }
    else
    {
        SnakeCollission = true;
    }
}

```

So I check whenever the snake is NOT having collission, then snakecollission is false, else it's true.

What happens now though is that when I eat one piece of food, the snakecollission turns true, while the snake is not touching itself.

This is the link to my complete code: http://pastebin.com/gVUuazQN

Any help would be appreciated, I hope I have given an understandable description :)

# Answer
> 1 votes
First of all, your code detecting collision is wrong in 2 ways.

1. To check if your head collides with an other part you should just check if the 2 positions are the same

```
if (Snake[0].X == Snake[i].X && Snake[0].Y == Snake[i].Y)

```

is doing that just fine.
2. Whenever you find a collision, you need to **break** the loop, else `SnakeCollision` will go back to `false` if you are not colliding with the tail of your snake.

Now, your problem is about getting collision just after eating an apple. Well, it is pretty normal you are colliding with yourself as you add the new part at the same spot where you already are, so during next collision detection it will think you ate yourself. I believe you need to add a special case just after eating an apple to deal with this case.

By the way your code is really messy. The `paint` function should be used only to paint, but you are using it to add new snake parts, check user inputs, etc... That makes your code really hard to read and understand!

# Answer
> 0 votes
Try use same test collision of the apple. It's the same principle I think

```
if (Snake[0].X > (Snake[i].X + 64) || (Snake[0].X + 64) < Snake[i].X || Snake[0].Y > (Snake[i].Y + 64) || (Snake[0].Y + 64) < Snake[i].Y)
{
    Collission = false;
}
else
{
    Collission = true;
}

```

I hope that help.

# Answer
> 0 votes
In the original code, it will only detect collision if colliding with the tail of the snake (last iteration of the for loop). Any collisions with previous sections of the snake will be overwritten by the last value.

One solution (note that the if line is inverted):

```
SnakeCollission = false;
for (int i = 1; i < Snake.Count; i++)
{
    if (Snake[0].X <= Snake[i].X + (i * 64) && (Snake[0].X + (i * 64)) >= Snake[i].X && Snake[0].Y <= (Snake[i].Y + (i * 64)) && (Snake[0].Y + (i * 64)) >= Snake[i].Y)
    {
        SnakeCollission = true;
        break;
    }
}

```

By the way, you can simplify much code by using 0,1,2,3... as values for X/Y instead of 0,64,128,192..., and multiply by 64 in a single place (when drawing the snake on screen) instead of everywhere else in the code. Code will be simpler and much easier for you to change the scale if needed.) For example the "if" line above could be reduced to:

```
if (Snake[0].X == Snake[i].X) && (Snake[0].Y == Snake[i].Y)

```

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


# Question
Title: What Java class should I use to represent a Vector?
Does Java have a built-in Vector class suitable for handling collision detection / response? It should have methods like `subtract(Vector v)`, `normalize()`, `dotProduct(Vector v)`, ...

It seems logical to use `java.awt.Rectangle` and `java.awt.Polygon` to calculate collisions. Would I be right to use these classes for this purpose?

I understand collision detection; I'm only wondering what approach to it is idiomatic in Java. I'm new to the language and to application development in general.

# Answer
There is no built in math Vector class. You'll have to implement your own or use a library like JScience \- its project page is here.

EDIT: As comment below suggested, JScience isn't really designed for gaming application is missing some optimizations. A more game oriented vector math API can be found in libgdx. I imagine it should not be too difficult to extract just the math classes from libgdx.
> 5 votes

# Answer
The `vecmath`-package from *Java 3D* can be used separately from the rest of the project. It allows in-place modification of vectors and has various methods that are convenient and efficient for games (such as `lengthSquared`, which avoids a √-operation).

`vecmath.jar` is 312K and works well separately from the rest of Java3D. It may be included under `javax.vecmath` in some Java distributions, but you can download it at the below link if not.

Downloads | Documentation
> 4 votes

# Answer
There is also a Vector3D class in Apache Commons Math.
> 1 votes

# Answer
I use the Vector2 and Vector3 class from LibGDX (java gamedev library). It has some odd behaviour and you have to be careful when you do calculations with references, but I guess this is the fault of java not the vector implementation. On the other side, the vector class from XNA had some odd behaviour as well when it did come to normalization and I replaced it with another one from another library :)

LibGDX Vector2 Class
> 1 votes

# Answer
I've just starting using Vectorz, and it's great. Fast, in-place transformations, readily available from Maven Central, well documented.

From the README:

> Fast double-precision vector and matrix maths library for Java, based around the concept of N-dimensional arrays.
>
> This library is designed for use in games, simulations, raytracers, machine learning etc. where fast vector maths is important.
>
> Some highlights:
>
> * Vectorz can do over 1 billion 3D vector operations per second on a single thread.
> * Specialised matrix types for efficient optimised operations (identity, diagonal, sparse etc.).
> * Support for arbitrary n-dimensional numerical arrays.
> 1 votes

---
Tags: java, vector
---


# Question
Title: IgnoreCollision on trigger callbacks not working
I am making an elevator that passes through the terrain. The character should be allowed to pass through the ground temporarily when he is within the sphere collider. The code is as follows:

```
using UnityEngine;
using System.Collections;

public class TerrainHole : MonoBehaviour {

    public Collider player; // assign in inspector?
    public Terrain terrain; // assign in inspector?

    void OnTriggerEnter (Collider c) {
        if (c.tag == "Player") {
            Physics.IgnoreCollision(player.GetComponent<Collider>(), terrain.GetComponent<Collider>(), true);
        }
    }

    void OnTriggerExit (Collider c) {
        if (c.tag == "Player") {
            Physics.IgnoreCollision(player.GetComponent<Collider>(), terrain.GetComponent<Collider>(), false);
        }
    }

}

```

By all accounts this should work, but I can't get any variation of it to work so far.

What am I doing wrong?

# Answer
Small oversight on my part:

```
using UnityEngine;
using System.Collections;

public class TerrainHole : MonoBehaviour {

    public Collider terrainCollider; // assign in inspector

    void OnTriggerEnter (Collider c) {
        if (c.CompareTag("Player")) {
            Physics.IgnoreCollision(c, terrainCollider, true);
        }
    }

    void OnTriggerExit (Collider c) {
        if (c.CompareTag("Player")) {
            Physics.IgnoreCollision(c, terrainCollider, false);
        }
    }
}

```

I was referencing `Collider player` instead of `Collider c`. Since the player's collider is passed as an argument, there's no need to hold a reference to the player as a member variable.
> 2 votes

---
Tags: unity, physics, terrain
---


title: What is deferred rendering?

text:
# Question
Title: What is deferred rendering?
I've heard about deferred rendering and how using it can allow for "lots" of lights in a scene without a huge performance hit, but what is it and (from a high level) how is it implemented?

# Answer
> 67 votes
The defining characteristic of deferred rendering is that it essentially changes the complexity of scene rendering from O(geometry * lights) to O(geometry + lights).

This is achieved by first rendering the scene using shaders designed to output basic attributes such as (at a minimum) position\*, normal, and diffuse color. Other attributes might include per-pixel specular values and other material properties. These are stored in full screen render targets, collectively known as the G-buffer.

(\*: *It's worth noting that developers will more commonly opt to store depth, and use that to reconstruct position, since having depth available is useful for so many other effects.*)

Once the G-buffer has been generated, it's possible to compute a fully lit result for any pixel on the screen by solving the BRDF exactly once per pixel per light. In other words, if you have 20 meshes that each are affected by 20 lights, traditional ("forward") rendering would demand that you re-render each mesh several times in order to accumulate the result of each light affecting it. In the worst case, this would be one draw call per mesh per light, or 400 total draw calls! For each of these draw calls, you're redundantly retransforming the vertices of the mesh. There's also a good chance that you'll be shading pixels that aren't actually affected by the light, or won't be visible in the final result (because they'll be occluded by other geometry in the scene). Each of these results in wasted GPU resources.

Compare to deferred rendering: You only have to render the meshes once to populate the G-buffer. After that, for each light, you render a bounding shape that represents the extents of the light's influence. For a point light, this could be a small sphere, or for a directional light, it would be a full screen quad, since the entire scene is affected.

Then, when you're executing the pixel/fragment shader for that light's bounding volume, you read the geometry attributes from the appropriate position in the G-buffer textures, and use those values to determine the lighting result. Only the scene pixels that are visible in the final result are shaded, and they are shaded exactly once per light. This represents a potentially huge savings.

However, it's not without drawbacks. It's a paradigm which is very difficult to extend to handle transparent geometry (see: depth peeling). So difficult, in fact, that virtually all deferred rendering implementations fall back to forward rendering for the transparent portions of the scene. Deferred rendering also consumes a large amount of VRAM and frame buffer bandwidth, which leads to developers going to great lengths to cleverly pack and compress G-buffer attributes into the smallest/fewest components possible.

# Answer
> 10 votes
Also referred to as Deferred Shading, Deferred Rendering refers to a wide set of possible rendering paths that store intermediate results into textures, then complete the rendering equation later by sampling the intermediate data.

Geometry buffers are an early example, where the scene is rendered into a series of buffers that contain e.g. the position, normal, and base texture of opaque geometry. Lighting has not been applied, and the final color is not known. In subsequent passes lights are rendered, and the geometry buffers are sampled. This means that large numbers of lights can be rendered with a fixed cost of number of lights possibly visible on a screen pixel. Traditional rendering would have evaluated all light sources for surfaces that were occluded and never seen on screen.

Many variations exist, including rendering light information first for example.

See for more information: http://en.wikipedia.org/wiki/Deferred\_shading http://delicious.com/aancsiid/deferred-shading

# Answer
> -3 votes
Deferred rendering is processing where the geomtry is before doing a second pass to shade everything. It's useful because it changes the coplexity to O(pixels * light sources), allowing you to use complex scenes with only a small hit to performance.

Implementing it is rather simple. The first pass requires rendering, at a minimum, the distance, normal, and color. You can add more textures to render like specular, and position, at the cost of memory.

Once you have those rendered, you then render some spheres, where a unique light source is at the center of each one, add the light together, crop it all to the geometry in your scene, and finally, apply falloff.

---
Tags: rendering, deferred-rendering, terminology
---


# Question
Title: How should I balance temporary buffs to make my game fun?
As a game developer, I understand many players (usually in RPGs) expect short term buffs to be available to them, such as potions, war cries, drugs, etc.

As a player, I've never understood what fun there is in using them. I think it's because they never seem to be very strong. They usually grant a 10-20% bonus to some attribute, for example -- just enough to turn a rage-quit situation into a merely-annoying one.

Maybe I just don't know how to use them; so how should I approach temporary buffs when balancing them? For the people who enjoy using them, what are they getting out of it? How might I go about confirming if my players agree that the mechanic is fun?

# Answer
## How should I balance buffs?

This can be a tricky area, as realistically, there are a lot of ways you can temporarily buff a players ability. There are some key points I can make, here, though:

* If a particular buff is considered to powerful, you may consider increasing the *cost*, instead of lowering the strength. If the buff costs too much, players will either save it for a rainy day, or use it freely and risk not being able to acquire another one for when they *really* need it.
* If you intend to involve multiplayer co-op, consider "support temporary buffs"; buffs that you can not use on yourself, but can greatly benefit other players. This works in supporting cooperation between other players.
* If a particular set of buffs *in combination* make your game too easy, make them *mutually exclusive*; if you already have buff a, taking on buff b will cancel buff a.
* Playtest, Playtest, Playtest. Have your testers fight the same boss or complete the same scenario *without* buffs and *with* buffs. Feedback should tell you wether the buffs made the game *more playable* or *too easy*.
* Balance Buffs with Debuffs. You have not said anything about debuffs, but in theory, your already implementing the mechanic; a debuff is really just a buff with a *negative* effect - if buffs make a particular enemy to easy to beat, consider giving the enemy their own debuffs to inflict on players to make the fight a bit harder.

---

## What do players get out of temporary buffs?

I propose that players do not necessarily get *fun* out of the temporary buffs, themselves. Instead, the temporary buffs *facilitate* the player, to help them experience *more* fun from the game content.

Further to the fact; I personally find a direct correlation between my dependency on temporary buffs, and my opinion that the particular buff system is *not* fun. This might come down to my own opinion, or the types of games I play.

**Temporary buffs can speed up game play**

If temporary buffs make my character stronger, we can logically infer that the use of temporary buffs allows my character to kill the monster quicker. In turn, my character can kill more monsters in a minute *with* buffs, than they can *without* buffs. In games where the player might be killing a lot of monsters, this speeds up a process that is commonly *not* very much fun (i.e. "the grind").

As an example, World of Warcraft was once known1 for an excessive grind, and the ability to temporarily deal more damage simply meant you were leveling quicker, and grinding less.

**Temporary buffs can make certain game play strategies possible**

If temporary buffs increase the ability of my character, we can logically infer that there would be certain activities *outside* of my characters capabilities, that could otherwise be performed with the addition of a temporary buff. If the temporary buff makes the difference between doing something now or later, it can mean the difference between whether the player does it at all, or leaves it to later and forgets about it.

As an example, The Elder Scrolls is a game well known for its diverse character customisation, and includes a heavy "temporary buff" mechanic in the form of alchemy and potions. At certain points of the game, you may perform actions based off one of your skills; if the skill is to low, you have a poor chance at succeeding that "roll". The ability to quickly buff that skill for the purpose of the "roll" means that you *can* explore that avenue, even if you have not invested as much time in that skill, before.

**Sometimes, temporary buffs may be *required***

It is not uncommon for game mechanics to *require* the use of a temporary buff. In turn, this adds complexity to the scenario, as the player needs to determine the right buff.

Although I am not as experienced with the game, The Witcher series offers a good example. At certain levels of difficulty, the game becomes nearly impossible without the use of correct buffs that compliment the required strategies and resistances when fighting particular types of enemies. Think along the lines of "I need to coat my sword in a temporary silver potion so it can hurt the vampire".

**Temporary buffs are useful when I need to *maximise* my ability**

This is *provably* exclusive to MMO games, but in certain games, "end game" content usually involves a race to become "the best". You need to make sure your character can put out as much damage, healing or control as possible, in order to give you and your team a running chance at completing the scenario.

In such cases, temporary buffs are almost a requirement, assuming they *are* available. *If you can be fighting at 120%, why fight at 100%?*

**Immersion**

Lets be real, here. A lot of RPG games do use buffs, and if the player expects to be able to do something, limitations preventing them from doing so can break their immersion.

For example, there is no real reason I would want to down a hundred beers in World of Warcraft; but it pleases me that in doing so, my character gets drunk, my speech starts to slur and the screen becomes distorted.

**Humor**

This might be a lesser point, but I have seen it before, so it is worth addressing. Sometimes, buffs can be set up in a way that adds humor, instead of gameplay.

For example, there is a buff in The Elder Scrolls: Morrowind called "Icarian Flight", which temporarily boosts your acrobatics up to *five times its maximum level*. At such levels, your jump becomes so powerful that you can jump some of the highest mountains in the game - but if the buff wears off while you are still in the air, you will certainly die from the falling damage, when you land.

While this may have some benefit outside of humor, if used *very carefully*, I personally only found humor in this buff. To this day, it is one of my favorite examples.

---

## How can I tell if others find the mechanic fun?

As addressed in comments, it is difficult to define fun. Everyone has their own opinions, because everybody is different. I can not stress this enough; **do not fall into the trap where you insist your game is fun because *you* think it is fun - listen to your players, as well**.

How can you listen to the players without releasing your game? Quite easily, if you employ play testing - which you should, at some stage.

* At the base level, *ask your play testers*. Play testers may not only be able to point out elements that *are not* fun, but may offer impression towards how you would draw out the elements that *are* fun.
* Data analytics. At the end of the day, if you can determine that players *think* a mechanic *looks* fun, but they never actually explore it, you must ask yourself *why*. Regardless, a fun mechanic that is never explored is ultimately *not* fun.
* Based off data analytics, *ask your play testers, again*. "We have noticed that a lot of players completely ignore the potion mechanics. What are your thoughts, in regards to the potion mechanics?".
* Once your ready to *release* your game, it should not stop, there. Ask your players for feedback. Provide a form they can fill out for any suggestions (and bug reports, though I digress), and more importantly, *listen* to your players. If once in a blue moon, a player submits feedback that "your buff system is bad, take it down", don't worry about it. It is foolish to think that you can please *everybody*, especially with as many aspects as which go into a video game. However, if you start to see a *pattern*, investigate. Perhaps a lot of players simply don't like the mechanic; you might consider an overhaul, or removing it, entirely. Perhaps a lot of players simply find the mechanic to confusing; in this case, your buff mechanic is not necessarily "not fun", its just to hard for players to get to before they can start experiencing the "fun".

1 Some may say it still is, but game play changes have *severely* weakened the "grind" required to reach a suitable level for decent content exploration.
> 6 votes

---
Tags: game-design, game-mechanics, balance, difficulty
---


title: How should I store & read level map?

text:
# Question
Title: How should I store & read level map?
Ok, so I am trying to create a level map, but I don't know how I should store it. Should I use an array for every level? I feel like that wouldn't be very efficient though. I'm not sure what I should do. Any thoughts?

**EDIT**: Currently I am storing the single map as a 2D Array, it looks like

```
int test_array[][] = { {...}, {...} }

```

I am iterating through each element and for every '1' or '2', draw a block. Is there a better way to do this?

# Answer
> 1 votes
If you are making a platformer or top down rpg style game an array can be very usefull.

As long as you can consistently convert from world coordinates to array coordinates (and back), you can easily iterate only through a subsection of the array that represents what is on the screen by controlling the start and end of the two loops you are using for iterating through the array.

I would recommend creating a "tile" or "square" object or enumerated that you store into the map array rather than ints. Each item in the enumerated list can have a different sprite variable, movement cost variable, ect.

That way you avoid having a bunch of if statements and having to keep track of what variables do what, you can just do testArray\[y\]\[x\].drawImage(x*gridSize,y*gridSize); or something along those lines.

This will make it harder to edit your level in a text editor, but making a crude level editor won't take too long and is worth the time.

You might also consider making maps an object (and have them store their tile arrangement in an array). This can be useful, because there might be a bunch of information that you want to save in a level that wouldn't belong in the array.

For example, what level is next, where do enemies start and what enemies are there. You can roll all of that information into a map object.

---
Tags: 2d, maps, levels
---


title: Build displays black screen with static

text:
# Question
Title: Build displays black screen with static
Something really odd happens when I'm trying to load a scene.

It is supposed to look like this (it also has to show the next scene after loading):

What is going on?

# Answer
> 0 votes
You confirm to have selected "Split Binary Application" from the publisher settings. Used incorrectly, this can have disastrous affect on your game. Unless you specifically intend to use this feature, turn it off.

---

This feature allows you to split your android application into multiple files, primarily for the purpose of publishing a game to the Google Play Store that would normally exceed the size limitations of 100MB. While you still end up with an `.apk` file, you build a lot of your required files into additional `.obb` files, including any *additional* scene (the first scene will still be packaged in the `.apk`) and any resources.

---

Using this feature, your application will still *look* for the additional data files, but if it can not find them it will continue on *as is*. It seems this is the case, here. The first scene looks unable to correctly display its game objects, likely due to the loss of your resource files. This also explains why you can not move to other scenes, as without the additional data files, you do not have access to your other scenes.

---

Going forward, you can still choose to "Split Binary Application". Just make sure that you *also* copy the required `.obb` files across with your `.apk`. You should place these files *together*, on your phone. Alternatively, you can set the path to your `.obb` files from the first scene, either from local access or after downloading them from an external source. You can read more about the "Split Binary Application" feature at the official Unity documentation.

---
Tags: unity, android
---


# Question
Title: Inverse Kinematics using Pseudoinverse Jacobian
I'm having problems solving IK with Jacobian Pseudoinverse method.

What I do is:

1. At each local joint frame `q_i` of the chain `q` calculate the cross product between rotation axis (taken from local transform) and joint-to-end-effector vector (end-effector is transformed to `q_i` coordinates):

```
// for each joint q_i -> to parent iteration

// Get Local Joint Position and Rotation Axis
lTransform = ... // local transform of i-th joint
if (lTransform.Decompose(s, q, t)) {
    q.AxisAngle(lRotationAxis, angle); // quaternion, XMQuaternionToAxisAngle
}

// Transform End-Effector To Local Joint Coordinates
lEndPosition = Vector3::Transform(lEndPosition, lTransform); // each iteration is updated to-parent
lJointToEnd = lEndPosition - lTransform.Translation();
lResultAxis = lRotationAxis.Cross(lJointToEnd);

jacobian(0, i) = lResultAxis.x;
jacobian(1, i) = lResultAxis.y;
jacobian(2, i) = lResultAxis.z;
jacobian(3, i) = lRotationAxis.x;
jacobian(4, i) = lRotationAxis.y;
jacobian(5, i) = lRotationAxis.z;

```
2. Set up desired change in position `dX = globalObjective - globalEndPosition` (fill the rest with zeros \[orientations\]).
3. Calculate configuration `dQ` with jacobian pseudoinverse:

```
jT = jacobian.transpose();
inv = (jacobian * jT).inverse();
jpinv = jT * inv;

dQ = jpinv * dX;

```
4. **So what exactly is** `dQ`? Each value should represents a local change in `i`-th joint.

* Is it the angle of rotation around rotation axis in local joint frame?
    * Or maybe translation value along cross product?

I tried applying both variations above updating local joint transform with simple matrix multiplication and none of this works. The end-effector position seems to be moving very randomly - at each iteration it's very different.

# Answer
> 0 votes
The answer is this:

1. Jacobian needs to be calculated globally. For each joint in global coordinates rotation axis needs to be calculated as a cross product between *joint-to-end* and *joint-to-target*. The vector that goes into the Jacobian position field is a cross product between *joint-to-end* and *rotation axis* \- it is a vector along which movement needs to be made (wikipedia under "angular velocity" names it: *cross-radial component*).

```
// For each joint (except end-effector)
JointPosition = ToWorld(jointChainID[j]).Translation();
JointToEnd = EndPosition - JointPosition;
JointToTarget = TargetPosition - JointPosition;

// Calculate Rotation Axis
RotationAxis = JointToEnd.Cross(JointToTarget);
RotationAxis.Normalize();

// Cross-Radial Vector
Result = JointToEnd.Cross(RotationAxis);

// Jacobian column entry
jacobian(0, j) = Result.x;
jacobian(1, j) = Result.y;
jacobian(2, j) = Result.z;
jacobian(3, j) = RotationAxis.x;
jacobian(4, j) = RotationAxis.y;
jacobian(5, j) = RotationAxis.z;

```
2. The result `dQ` contains rotation angles for each joint along `RotationAxis` (in global coordinates). Then I apply changes locally (this is weird, as I apply global changes to local joint coordinates, but somehow this works):

```
// Apply changes to local skinning matrices
// For each joint (except end-effector)
     jointID = JointChainID[j];
     gTransform = Matrix::CreateFromAxisAngle(cache.RotationAxes[j], ToRadians(dQ(j)));
     SkinningLocal[jointID] = gTransform * SkinningLocal[jointID];

```

---
Tags: mathematics, animation, skeletal-animation, inverse-kinematics
---


# Question
Title: Controlling screen and window size in Unity
In Java I know how to make a window of a certain size and make it not resizable.

How do I control my game's window size in Unity and prevent players from resizing it?

# Answer
Regarding the size your game is displayed in the editor window- have you customized the settings in the game preview window? If the game window of your editor is set to 'free aspect' or a resolution other than what is intended, the preview in the editor might not be an accurate reflection of what size your game window will be in your final build. If the desired size is larger than the size of your editor you'll want to click 'maximize on play' as well.

In terms of defining a set size for your game window though, if you go to 'File', then 'Build Settings', click 'Player Settings' and then under 'Resolution' un-check the box that says 'Default is Full Screen', you can set a default height and width for your player. You'll also want to un-check 'Display Resolution Dialogue' to avoid the user changing the resolution when the game first launches, and the 'Allow FullScreen Switch' box to prevent the player from switching to full screen mode using OS specific short cuts.

You can also set the screen resolution in your code with 'SetResolution'.

If you are interested in scaling your game for multiple screen sizes though, take a look at the following sections of the Unity API- Designing for Multiple Resolutions, Canvas Scaler.
> 1 votes

---
Tags: unity, screen
---


# Question
Title: How to avoid assigning the same GameObject individually for every prefab?
In many times, prefabs that share the same script may require the same GameObject in the script. For example, in my game I want to make a series of card prefabs. Each card has their own image when shown, but has the same back image when hidden. My script for card is:

```
public class DraggingCard : DragAndDropItem
{
    public Sprite secretSprite; //This is the same for every card
    Sprite oringinalSprite; //This is individual for every card
    Image image;

    public void Awake()
    {
        image = GetComponent<Image>();
        oringinalSprite = image.sprite;
    }

    public void Activate()
    {
        image.sprite = oringinalSprite;
    }

    public void Hide()
    {
        image.sprite = secretSprite;
    }
}

```

But if I write this, I'll have to assign the `secretSprite` in the inspector for every DraggingCard prefab. I tried to set `secretPrefab` to be `static` or `const` but neither worked.

I believe there must be a clever way to avoid the repeat work. Could anyone tell me that? Thank you!

# Answer
The easiest and cheapest method is to do it all in one go.

**Select all of your prefabs** in your project window (you can use search to get them all in one view, even if they're in different folders), and then assign the field once. The newly assigned value will be applied to every prefab in your selection.

Most scripts you write in Unity will support this type of multi-editing out of the box. If using a custom editor you might need to do a little work to enable this.

---

Some alternatives you can use if you need something more elaborate:

**A)** In your `Start` script, load the texture you want with `Resources.Load` \- you pass a path to the texture from a folder called Resources, which can be a static string. Just note that anything in a Resource folder will always be included in your build, even if you stop using it, and Unity won't be able to see this reference to pre-load the assets you need, so loading a lot of assets this way can introduce a performance hit.

**B)** Introduce an object with a "Manager" script into your scene, where the manager's job is to keep track of common references other scripts need. In `Start`, your other scripts can find the manager with built-in `Find` methods or a static `GetInstance` method, and ask it for their references. That way you only need to assign the references once to the manager object's prefab.
> 1 votes

# Answer
Assign the script and the secretSprite to your DraggingCard object before you make it a prefab. Then every DraggingCard instance that you place in your scene will already have the secretSprite assigned to it.
> -1 votes

---
Tags: unity
---


# Question
Title: Physics.CheckSphere never returning true despite being called to where a hitbox is
I'm trying to create a random level generator where I have a load of rooms 16x10 and I generate them when the player enters the room. I want to check the space where I want to place a room, in this case up for if there's already a room there. I've written this code to do that but it doesn't appear to be working. Currently it should ALWAYS return true (and not run the code) because the object it is on has a hitbox. I want it to hit triggers because then I don't need a physical block in the centre of every room (hard when the rooms are even both ways)

Can you see what's wrong here? The code does spawn a block in the correct place.

```
if (!Physics.CheckSphere(new Vector2(transform.position.x, transform.position.y), 1f, 6, QueryTriggerInteraction.Collide))
        {
            //Get list of open bottoms
            getList("Assets/Room Lists/bottom.txt");
            //Make a random number from the list
            int newRoomIndex = random.Next(0, prefabObjects.Count);
            //Get that object
            GameObject newRoom = prefabObjects[newRoomIndex];
            //Place it in the world in the correct position
            Instantiate(newRoom, new Vector3(transform.position.x - 8, transform.position.y + 15, transform.position.z), Quaternion.identity);
        }

```

# Answer
It appears that `Physics.CheckSphere` doesn't work with 2D colliders for some reason. I ended up using `Physics2D.OverlapCircles` instead.

Hope this can help someone out there :)
> 1 votes

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


# Question
Title: Pygame, how can I move a rect/sprite from point A to B smoothly?
As the title suggests, i want to move a rect/sprite from point A to point B in a smooth manner. What I mean more specifically is that the speed of the movement should change throughout the course. So it starts off slowly then speeds up as it reaches the half-way point then slows down again to finally land exactly on B. Or it can just start off fast then to slow down right till it hits B.

I've already tried to do this once by making the acceleration of the object 1/2 of the distance it needed to travel then halving the acceleration again before every frame. Then after a while it just reassigns the objects position to exactly where it needs to be. But i don't really like this method and i thought there had to be a more elegant and efficient way of doing it. But I can't think think of anything.

Here's what I've got so far(It's not the one that 1/2s acceleration):

```
clock = pygame.time.Clock()

class Block():
    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y

        self.rect = pygame.rect.Rect((self.x, self.y, width, height))

    def draw(self, surface):
        pygame.draw.rect(screen, (55,150,55), self.rect)

        self.x = self.rect.left
        self.y = self.rect.top

    def move(self, vect):
        x = vect[0] - self.rect.left
        y = vect[1] - self.rect.top

        self.rect.move_ip(x, y)

block = Block(100, 100, 50, 50)

def gameloop():

    loopExit = True

    while loopExit == True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                loopExit = False
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_d:
                    block.move([5,0])

            if event.type == pygame.MOUSEBUTTONUP:
                block.move(pygame.mouse.get_pos())

        screen.fill((25,25,25))

        block.draw(screen)

        clock.tick(60)

        pygame.display.flip()

gameloop()

```

# Answer
> 0 votes
As mentioned in a comment, you can use a tweening library, I will not go over that again, but it can be a useful learning experience to try programing those functions yourself (at the very least its good to understand the math).

Part of your problem is that acceleration does not work the way your description seems to think it is.

**Position:** Where you are

**Velocity:** How fast you are changing your position. Added to your velocity every time step.

**Acceleration:** How fast you are changing your velocity. It should be added to your velocity every time step.

If you want an object to speed up until the half way point do the following (if you want to start and end at rest).

Set your acceleration in the direction of your target. When you are at the half way point set your acceleration in the opposite direction. You should then come to a stop at your target.

Changing the magnitude of acceleration would only happen if you are changing the magnitude of your thrust, or whatever force is pushing you forward.

If you want the object to take a naturally looking curved path, I would recommend using a Bezier curve. The first and last points represent where you start and stop, and the lengths of the control points would represent how fast you start and end.

---
Tags: python, pygame
---


title: How to sort tiled decal list?

text:
# Question
Title: How to sort tiled decal list?
I have a tiled forward render pipeline (also called forward+). It assigns a list of lights for every 16\*16 block of pixels (tiles) on the screen. Lights are accumulated additively so their order doesn't matter inside the list.

The problem comes when I add decals to the light list. Decals need to be evaluated before the lights (because they can modify surface properties), and even their order among themselves matter because their texture is alpha blended on top of each other.

Because the lights and decals are culled in parallel, and added to the list by keeping a shared pointer to the end of the list which is incremented atomically when a light is added, the order of them can not be guaranteed. This is how I add a light to the tile's light list from a thread:

```
// I have a [numthreads(16,16,1)] thread group
for (uint i = groupIndex; i < g_nNumLights; i += 16 * 16)
{
  Light light = GlobalLightArray[i];
  if(IsLightVisible(light))
  {
    uint index;
    InterlockedAdd(LightCount, 1, index); // LightCount is a groupshared uint (the whole threadgroup can see it)
    LightArray[index] = i; // A light is always added to the back of the per tile light array
  }
}

```

I thought I should try to sort the light list after the culling and the creation of the list has ended, but I have no experience with highly parallel sorting algorithms. I however came across a nice presentation: Holy smoke! Faster Particle Rendering using Direct Compute by Gareth Thomas. From the 8th slide it has a brief explanation of the bitonic sort algorithm with pseudocode and nice pictures. I get the idea, but I have no idea how to implement it or if it could be even done efficiently for my case because my light list is variable in size for each tile. Maybe it could be done in the same dispatch when the culling occurs, on this array (which hold a variable amount of light indices \<= 1024):

```
groupshared uint LightArray[1024]

```

I have also seen a DirectX11 example of the algorithm of this kind of sorting, but on a different kind of dataset and across multiple dispatches and other post-processing transposing which is not clear to me at all.

Or maybe there is a completely different approach that I should take which doesn't involve sorting? Maybe when adding lights to the back of the array, the order of addition could be enforced somehow?

I have also learnt that the new Doom game also renders its decals this way.

# Answer
> 1 votes
OK, I haven't noticed, that in the same presentation I linked in my question, there was an other sorting algorithm for the per-tile LDS particle array, with source code. And that is nearly exactly my case, except that they are sorting their particles by distance, I only need to sort my decals by index.

It is a bitonic sorting running in a single dispatch pass, inside the light culling compute shader, after the culling phase, on the groupshared LightArray. Sadly, in the presentation, a line is not completely visible, but I have been able to fill in the missing pieces.

I am posting the sorting code:

```
    uint numArray = LightCount;

    // Round the number of particles up to the nearest power of two
    uint numArrayPowerOfTwo = 1;
    while( numArrayPowerOfTwo < numArray )
        numArrayPowerOfTwo <<= 1;

    GroupMemoryBarrierWithGroupSync();

    for( uint nMergeSize = 2; nMergeSize <= numArrayPowerOfTwo; nMergeSize = nMergeSize * 2 )
    {
        for( uint nMergeSubSize = nMergeSize >> 1; nMergeSubSize > 0; nMergeSubSize = nMergeSubSize >> 1 )
        {
            uint tmp_index = groupIndex; // It is the SV_GroupIndex, the flattened index of the thread within the threadgroup
            uint index_low = tmp_index & (nMergeSubSize - 1);
            uint index_high = 2 * (tmp_index - index_low);
            uint index = index_high + index_low;

            uint nSwapElem = nMergeSubSize == nMergeSize >> 1 ? index_high + (2*nMergeSubSize - 1) - index_low :  index_high + nMergeSubSize + index_low; // This is the line which is truncated in the presentation
            if( nSwapElem < numArray && index < numArray )
            {
                if( LightList[ index ] > LightList[ nSwapElem ] )
                {
                    uint uTemp = LightList[index];
                    LightList[index] = LightList[nSwapElem];
                    LightList[nSwapElem] = uTemp;
                }
            }
            GroupMemoryBarrierWithGroupSync();
        }
    }

```

---
Tags: rendering, directx11, hlsl, compute-shader
---


title: How to create scene template?

text:
# Question
Title: How to create scene template?
I'm creating a game with `Unity 3D`, where has many levels, and I want create a button in all levels, to back to level menu.

Is possible can I create a "scene template" where I can only change one time, and all level scenes inherit template changes?

# Answer
> 3 votes
You can use

```
SceneManager.LoadScene("myscene",  SceneManagement.LoadSceneMode.Additive);`

```

to load scene "templates" for things like pause menu, HUD, inventory, etc.

https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.LoadScene.html

---
Tags: unity
---