# Question
Title: How can I make expanding bullet pattern shapes?
I want to make a series of expanding bullet patterns that form shapes such as squares, triangles, etc. An example of what I'm after can be seen in the following video where when the stars are collected the bullets explode in the shape of an expanding star:

https://youtu.be/7JGcuTWYdvU?t=2m41s

# Answer
> 10 votes
The easiest way to do this would be to first design the shape then calculate the movement of the particles. In this answer I will be constructing a square, but this applies to any shape.

Start by designing your shape as relative positions around some origin point.

Now you need to calculate how the shape will expand. To do this we simply calculate the vector pointing from the `origin` to every `point` by subtracting the `origin` position from our `point`'s position then **normalizing** the vector. `vector = normalize(point.x - origin.x, point.y - origin.y)`.

We can now calculate the position of the points at any point in time by using this vector. You calculate the next position of the points by doing `point.position += point.vector * point.velocity`. Pseudocode example using our previous point:

```
// When you start your program you set these values.
point.position = (-3, 3); // Start position. Can be anything.
point.vector = normalize(-3, 3); // Normalized vector.
point.velocity = 3; // Can be anything.

// You do this calculation every frame.
point.position += point.vector * point.velocity;
// point.vector * point.velocity = (-3, 3)
// point.position is now (-6, 6) since (-3, 3) + (-3, 3) = (-6, 6)

```

Doing this will move all points outwards at 3 units every frame.

---

Notes

* You can read up on some simple vector maths here.
* The position can be anything as long as all positions are relative to some origin point.
* The velocity of all points should be the same to ensure uniform movement, but having different velocities might give you interesting results.
* If the movement seems off you should check the origin point. If it's not in the exact middle of the shape the shape might expand in a strange way.

# Answer
> 1 votes
As pointed out by Charanor you can use an array of points to define your shape and then update their position over time. Below is a working example of how to implement a star shape or a custom shape using points:

```
package com.mygdx.gtest;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Array;

public class Test extends ApplicationAdapter{

    public SpriteBatch sb;
    private StarShape ss, ssBig;

    @Override
    public void create() {
        sb = new SpriteBatch();
        Pixmap pmap = new Pixmap(2, 2,Format.RGBA8888);
        pmap.setColor(Color.WHITE);
        pmap.fill();
        ss = new StarShape(50,50,new Texture(pmap), 10, true);
        ssBig = new StarShape(250,250,new Texture(pmap), 50, false);
        pmap.dispose();

    }

    @Override
    public void render() {
        super.render();

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

        ss.update(Gdx.graphics.getDeltaTime());
        ssBig.update(Gdx.graphics.getDeltaTime());

        sb.begin();
            ss.draw(sb);
            ssBig.draw(sb);
        sb.end();

    }

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

    private class StarShape{
        public float progress = 1f;
        public Texture bulletTex;
        public Array<Vector2> points = new Array<Vector2>();
        public Vector2 center;

        public StarShape(float x, float y, Texture tex, float initialSize, boolean mathWay){
            center = new Vector2(x,y);
            bulletTex = tex;

            if(mathWay){
                // define star shape with maths
                float alpha = (float)(2 * Math.PI) / 10;
                float radius = initialSize;

                for(int i = 11; i != 0; i--){
                    float r = radius*(i % 2 + 1)/2;
                    float omega = alpha * i;
                    points.add(
                            new Vector2(
                                    (float)(r * Math.sin(omega)),
                                    (float)(r * Math.cos(omega))
                                )
                            );
                }
            }else{
            // or define star shape manually (better for non geometric shapes etc

                //define circle
                points.add(new Vector2(-3f,0f));
                points.add(new Vector2(-2.8f,1f));
                points.add(new Vector2(-2.2f,2.2f));
                points.add(new Vector2(-1f,2.8f));
                points.add(new Vector2(0f,3f));
                points.add(new Vector2(1f,2.8f));
                points.add(new Vector2(2.2f,2.2f));
                points.add(new Vector2(2.8f,1f));
                points.add(new Vector2(3f,0f));
                points.add(new Vector2(2.8f,-1f));
                points.add(new Vector2(2.2f,-2.2f));
                points.add(new Vector2(1f,-2.8f));
                points.add(new Vector2(0f,-3f));
                points.add(new Vector2(-1f,-2.8f));
                points.add(new Vector2(-2.2f,-2.2f));
                points.add(new Vector2(-2.8f,-1f));

                // mouth
                points.add(new Vector2(-2,-1));
                points.add(new Vector2(-1,-1));
                points.add(new Vector2(0,-1));
                points.add(new Vector2(1,-1));
                points.add(new Vector2(2,-1));
                points.add(new Vector2(-1.5f,-1.1f));
                points.add(new Vector2(-1,-2));
                points.add(new Vector2(0,-2.2f));
                points.add(new Vector2(1,-2));
                points.add(new Vector2(1.5f,-1.1f));

                points.add(new Vector2(-1.5f,1.5f));
                points.add(new Vector2(1.5f,1.5f));

            }

        }

        public void update(float deltaTime){
            this.progress+= deltaTime;
        }

        public void draw(SpriteBatch sb){
            Vector2 temp = new Vector2(0,0);
            for(Vector2 point: points){
                temp.x = (point.x);
                temp.y = (point.y);
                temp.scl(progress);
                sb.draw(bulletTex,temp.x + center.x,temp.y +center.y);
            }
        }
    }
}

```

# Answer
> 1 votes
So, there's this project out there called BulletML which is a markup language for creating complex particle / bullet patterns. You'll almost certainly need to port the code to your own language, but it can do some really amazing things.

For example, this boss was done in a (heavily modified) extension of BulletML for Unity3D (the author of that pattern uploaded that video and Misery is insane, as well as good1). It's the most difficult variation of that enemy and it shows off what BulletML is capable of quite well (and check out some of Misery's other bosses, too, Like Wallmaster).

Or I can show of this example, which is a pattern I wrote while working on an expansion for The Last Federation, using an older revision of the system that's less mod-friendly and uses only single character A-Z variables:

The green bullets making those rings there are spawned from a parent bullet that rotates at high speed, but themselves have no motion. They deal massive damage, keeping the player at a longer range, restricting them to lower damage weapons and allowing mobile defenders to harass the player (the player won if the unmoving structure in the middle there was destroyed).

Here's a portion of the XML syntax that creates those bubbles:

```
<bullet_pattern name="Barrier">
    $WallShotAngle B=.3 A=90
    $WallShotAngle B=.3 A=-90
    $WallShotAngle B=.3 A=0
    $WallShotAngle B=.375 A=180
</bullet_pattern>

<var name="WallShotAngle">
    <bullet angle="[A]" speed="4000" interval_mult=".01" dumbfire="1" shot_type="GravityWavePurple">
        <wait time="[B]" />
        <change angle="0" speed="1000" time=".0001" />
        <spawn>
            <bullet_pattern>
                <bullet angle="[A]" speed="0" shot_type="CurveBarGreen" damage_mult="8">
                <wait time="12" />
                <die />
                </bullet>
            </bullet_pattern>
        </spawn>
        <die />
    </bullet>
</var>

```

You can see some of the purple "gravity wave" shots in the screenshot, which travel almost instantly from the source (which rotates) to the bubble's edge, whereupon it spawns the green "curved bar" shot, which sits there for 12 seconds before despawning. The blue and yellow shots I've omitted, as they are much more complicated.

One of the other patterns (an artillery shell) in the expansion was actually written by Misery, although I made some modifications to it. Initially it's a low-damage, penetrating shot that flies out to long range and then explodes into a huge fireworks display, dealing tons of damage. It's max range was much higher than the player could achieve, essentially forcing the player to engage at short range, which was advantageous for the other types of NPC units due to the shotgun effect (more bullets clustered in a small zone).

BulletML is easy to work with, generally, and can do amazing things. Bullets can change direction, change speed, spawn other patterns, die early, repeat collection of commands in a loop, use delays, change bullet sprite image, follow their parent (or not)...And anything it doesn't support you could *write into it.*

I'd definitely recommend it if you're doing a serious shoot em up game. You would still need to work out the coordinate math to get the desired shapes, as Charanor talks about in his answer, but a bullet engine like BulletML will give you so much more flexibility that you'll spend more time *designing* new patterns than figuring out *how* code them.

1. To explain just how good Misery is, those videos are against floor bosses with *starting equipment*: no modules, no consumables, and the basic pea shooter. And xe only takes one hit despite the elongated nature of the fight. Ok, 9 hits against Centrifuge (who doesn't show up until the third floor after the player will definitely have upgrades resulting in at least double damage comparatively).

---
Tags: java, libgdx
---


# Question
Title: Customizable 3D "growing" Avatars within Unity
I'm working on a project that allows the user to pick their personal avatar (change faces/body settings/etc), and then have child/adult versions of those. Ideally, they will allow an age progression from Age 3 - Age 100 (or something).

I've built an HTML5 page with something conceptually like what I want (github repo here), but obviously I'm looking for a system that works within Unity3D for fully animated avatars.

It *seems* that a possible solution is UMA2 (with the ingame avatar creator), but there's very little documentation and I can't find any "getting started guides online". It also seems to have a DNA system that I could use for having parents have representative children, but can't find details. There is a YouTube video series that I'm going through which seems quite good, but I haven't yet seen if there's anything to create children procedurally and how that would work.

Does anyone know whether the Unity team recommends this system or another one or what their roadmap is. I see some UMA tools look like they're discontinued, some posts say they don't work with latest versions of unity, etc... but no ground-truth.

My current plan is to just buy a bunch of UMA stuff and slowly learn it through Trial and Error, but would appreciate if anyone has a good analysis of this area that they can share.

Note: I'm familiar with Makehuman and Adobe's Mixamo (both awesome and things I've spent a lot of time studying), but I am looking for something in-game to allow people to grow and evolve over time. Bonus points if I can have 20 generations of marriages/children that show genetic traits passing down the line. I've built support for that into the HTML5 system above, but not sure if it exists in the 3d space.

Thanks in advance!

# Answer
> 1 votes
I would suggest looking into character customiation with blend shapes. This youtube tutorial covers how to set it up. Now for a simple DNA System all that you will need is to encode all the values of the blend shapes in some sort of string or hash for both parents and generate a new onefor the child based on the parents. This will "pass" down stuff like nose shape, cheek widht, height etc.

---
Tags: unity, models, character, avatar
---


title: Slick 2D Image move along with shape

text:
# Question
Title: Slick 2D Image move along with shape
I am trying to move my image along with the shape so I can make the collider with the shape (some kind of space shooter) but my image does not move along with the circle I make for it. It dissapears to the next spawned circle instead of completing it's track towards the bottom of the screen (I want to make a vertical linear move from top to bottom but everytime another circle+image spawns, the previous circle goes down but the image spawns to the next circle and so on)

update method:

```
    timePassed+=delta;
    if(timePassed>700){
        timePassed=0;
        RandomInt = random.nextInt(400);
        gigis.add(new Circle(200+RandomInt,0,40));
        gigiSkin.add(new Image("img/gegi.png"));
    }

    for(Circle c: gigis){
        c.setCenterY(c.getCenterY()+(delta/6f));
        gigiY= c.getCenterY()+(delta/6f);
    }

    for(Circle c: bullets){
        c.setCenterY(c.getCenterY()-(delta/1.25f));
        projY = c.getCenterY()-(delta/1.5f);
    }

```

render method:

```
    for(Circle c: bullets){
        g.draw(c);
    }
    for(Image skin: bulletSkin){
        skin.draw(projX,projY,80,80);
    }

    g.setColor(Color.red);
    for(Circle c: gigis){
        g.draw(c);
    }
    for(Image skin: gigiSkin){
        skin.draw(200+RandomInt,gigiY,80,80);
    }
}

```

# Answer
> 1 votes
Your variables naming is a bit... bad, what is gegi or gigy exactly? This code is messy.

Instead of making data collections for: bullets, bulletSkin, gigiskin etc. you should consister object oriented way to write this code.

For example:

```
class Transform
{
   public float posX, posY;

   public void SetPosition(float posX, float posY)
   {
        this.posX = posX;
        this.posY = posY;
   }

   public Transform(float posX, float posY)
   {
      this.posX = posX;
      this.posY = posY;
   }
}

class Skin
{
   public Image skinImage;

   public int width, height;

   public void Draw(Transform gameObjectTransform)
   {
        skinImage.draw(gameObjectTransform.posX, gameObjectTransform.posY, width, height);
   }

   public Skin(Image skinImage, int width, int height)
   {
      this.skinImage = skinImage;
      this.width = width;
      this.height = height;
   }
}

class Bullet
{
   public Circle bulletCircle;
   public Skin bulletSkin;
   public Transform transform;

   public void Draw(Graphics g)
   {
        g.draw(bulletCircle);
        bulletSkin.Draw(transform);
   }

   public Bullet(Circle bulletCircle, Image bulletSkinImage, int width, int height)
   {
      this.bulletCircle = bulletCircle;
      this.bulletSkin = new Skin(bulletSkinImage, with, height);
   }
}

```

Next you will able to:

```
for(Bullet b: bullets)
{
    b.transform.SetPos(someX, someY);
    b.Draw(g);
}

```

This looks more cleaner and OO.

After those changes your images will be rendered in circles positions, you can move circles and images will be moving with them.

---
Tags: java, slick
---


title: Issues with events changing game state

text:
# Question
Title: Issues with events changing game state
I am currently experimenting with creating a turn based game using Unity and am trying to come up with a sensible architecture for structuring my game systems.

So far I have decided to base everything around **Game states**. A game state represents a sort of "mode" of the gameplay, for instance "Select unit state" or "Game over state". A global game state manager holds a stack of these game states and can be called with pop (remove top game state), push (push the provided game state onto the stack) and replace all (pop all existing game states and push provided game state). Update is called on the top most element of the stack every logic frame.

I also have **Entities** which exist on the scene and represent stuff like as game units, terrain, projectiles etc. These are standard gameObjects with behaviors, unity lifecycle etc.

Finally there are a bunch of **services** which provide methods to handle stuff like menus and camera.

The idea is that the game states handle the "logic" of the game such as player input, transitions between game states, calling the services and controlling/modifying entities.

I also use **events** to facilitate the communication between state, entities and systems to avoid coupling too much. These events are stuff like "Unit destroyed" and "Objective complete" which are listened to usually by entities, calls to move the camera, create entities and such are still called normally using the relevant service methods.

Whilst this system works in theory I am having some issues with the interactions between events and game state logic. Consider the following:

Update of performActionState:

```
void update() {
  // Do something.
  Messanger.fireEvent(EventType.ACTION_COMPLETE);
  GameSystemManager.pushState(new NewTurnState());
}

```

Objectives system listening for action complete:

```
void handleActionComplete() {
  if (checkObjectivesAllComplete()) {
    GameSystemManager.pushState(new GameCompleteState());
  }
}

```

What I want to happen is for the objectives system to push a game complete state and finish the game. What actually happens is that the handle action complete pushes the game complete state, the rest of the perform action state update runs and a new turn state is pushed.

The above example might be a bit simplistic but I see this as an underlying issue with my architecture. Most events would be fired due to a change in the state of the scene or completion of something, for instance a unit being destroyed or a unit entering a trigger area. The probability of the game logic needing to change state from the game states is quite high in these cases usually.

I could easily fix the above sample in a number of ways, for instance I could move the checking of objectives into the start of NewGameState and invoke a pushGameState there instead to end the game but all the ways I can think of at the moment seem like hacks which will greatly increase coupling (New game state doesn't need to care about objectives) and code spaghetti.

Any advice for ways I could potentially architecture around issues like this?

# Answer
> 1 votes
I think the difficulty here is that, because you have bits of non-state code (the objectives system in this case) interfering with normal operation of the state machine, the state machine will get tangled up by out-of-band state changes.

If I understand correctly, your `performActionState` is on a stack with some other state beneath it (I'll call it `gameplayState`). I would move both the game-ending logic from the objectives system and the `GameSystemManager.pushState(new NewTurnState());` from `performActionState` into `gameplayState`. When `performActionState` ends, it will simply pop itself from the stack and let `gameplayState` decide what to do next.

If `performActionState` doesn't have such a useful parent state, then you could have it push an `endTurnState` that does the game-end logic and pushes the appropriate next state.

This seems to play to the strengths of your architecture because the state machine itself is responsible for detecting when to change state and what state to change to. If the current state (`performActionState`) can't do that, then it can get out of the way and let the next state handle it.

The objectives system could pass a "game over" event if you want to avoid direct coupling between it and the state machine.

# Answer
> 0 votes
Interesting question. Funny enough that is exactly what I was struggling with about a year ago.

What Victor suggested in his above answer is somewhat true. Queue is useful so I roll with it but suggest alternative approach to handling it.

Your problem which lies in multiple (tens or even hundreds) listeners reacting to your state change event asynchronously.

Let's break it down to simple (not necessarily real live) use case.

There are 3 components: `A`, `B`, `C` subscribed to a `StateManager`. `A` and `B` can trigger fire `LoadLevel (X)` event and `C` only reacts to `LevelLoaded (X)` event.

You fire `LoadLevel (A)` event from `A`. Level is loaded, `LevelLoaded (A)` is fired and `C` reacts to it. Same for component `B`. You fire `LoadLevel (B)` event from `B`. Level is loaded and `C` reacts to `LevelLoaded (B)`.

It is all fine if everything is handled properly internally. What can go wrong, right? Problem lays in asynchronous nature of those actions.

Consider this:

* loading levelA takes 10s
* loading levelB takes 1s
* you can fire loading each level at any time
* you fired loading lavel A and then loading level B

Level B should be loaded overriding initial request of loading level A, right? Not to difficult to handle if you know what you are after.

In this scenario, you can obviously LevelManager that will handle it correctly but you would have to create some sort of manager for every single async action you want to deal with.

As dependencies between components grow, it becomes difficult to even spot the problem. It is error prone solution.

The best way would be extending your event manager to handle state change better. To do so, firstly, you might consider adding more events:

* `StateUpdateInit(GameState newState)`
* `StateUpdating(GameState oldState, GameState newState)`
* `StateUpdateComplete(GameState currentState)`

It isn't a must but will give you bit more granular control.

More importantly, however, you will need couple additional parameters in your public method requesting state change.

* `ChangeState(GameState state, bool instant = false, bool async = false)`

If method is called with default params you go about your state changing business as usual. If you call `ChangeState(state, true, true)` checking for `instant == true` should clear state queue and fire state change event. Additionally if `async == true` you should toggle `lock` flag on your state manager which will prevent adding new states to the queue until state transition is complete. It can be achieved with calling another method, such us:

* `CompleteState(GameState state)`

Now you are save. Every time you know you want to fire async action just tell your `StateManager` to wait for completing the transition and other components will be prevented from triggering new states.

You can obviously extend it even more with pause and resume functionality, go back and forward methods and some other nice stuff but that is outside of the scope of this question.

Hope it helps.

# Answer
> 0 votes
A proper finite state machine doesn't just define the states themselves but also the transitions between them. When there is no direct transition from the `GameCompleteState` to the `NewTurnState` defined by the state machine, then this transition should simply not be possible.

That means state changes should never be triggered directly from any of your game services. They should always be triggered by the currently active state itself. For example, by having the State's update method poll all the game systems which might cause a change from this state to a different state. I could also see the entry-method of `NewTurnState` poll the `ObjectiveSystem` if the win- or loss-condition is fulfilled and when that's the case immediately transition to the `GameCompleteState`.

---
Tags: unity, architecture, events, game-state
---


# Question
Title: Clicking in a UI Button activate another
I'm new to unity and creating my first game to learn more about it. Now i got a problem wich i click on a button and sometimes another button active, for example: i press "Options" on pause menu and it active "Restart" or the "Main Menu". if someone can help me, I appreciate it. I set them up like this, if there's any error or need more info please let me know. And in the first image i tried split in 2 canvas, but didn't work. P.S.: It happens even with buttons with no actions or scripts on them.

```
public void OnPause()
{
    Time.timeScale = 0;
    isPaused = true;
    unPauseButton.SetActive(true);
    pauseButton.SetActive(false);
    PauseGameMenu.SetActive(true);

    GameObject.Find("PowerUpSpawner").GetComponent<PowerUpManager>().enabled = false;

}
public void UnPause()
{
    Time.timeScale = 1;
    pauseButton.SetActive(true);
    unPauseButton.SetActive(false);
    PauseGameMenu.SetActive(false);
    GameObject.Find("PowerUpSpawner").GetComponent<PowerUpManager>().enabled = true;
    isPaused = false;

}

```

# Answer
If you made sure that all of you functions are correctly mapped to the buttons (PauseAction for the Pause button etc.) then it must be your EventSystem object. You only need one for one canvas and having multiple can create conflits. You Canvas tree could look like this (I'm at work so no Unity image sorry) :

Canvas

* PauseButton
* MenuButton
* EventSystem

You can just add the EventSystem as it is, no special configuration is necessary for your purposes.
> 1 votes

# Answer
You can reference the object that you want to activate as a public field.

```
public GameObject Target;
private Button button;
private void Awake()
{
    // Find your button here.
    button = GetComponent<Button>();
    // Handle button event.
    button.onClick.AddListener(ToggleTarget);
}
private void ToggleTarget()
{
    // Activate/deactivate the target.
    Target.SetActive(!Target.activeSelf);
}

```

Add something like the code above, then you can set your target object in your inspector. You can use the same code for all button objects with same functionality.
> 1 votes

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


# Question
Title: LibGDX - Sending event to a button behaves differently from actually clicking it
I have a button on screen, and I want the user to be able to dismiss it by either clicking on it, or hitting space. The button is constructed as follows:

```
button = new TextButton("RESUME", skin);
button.setVisible(false);

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

  @Override
  public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
    button.addAction(
      Actions.sequence(
        // send out of the screen
        Actions.moveTo(WORLD_WIDTH / 2 - button.getWidth() / 2, -button.getHeight(), 0.2f),
        Actions.hide(),
        Actions.run( () -> {
          resumeGame();
        }),
        Actions.removeActor()
      )
    );
  }
});

...
table.add(button);
stage.AddActor(table);
...

```

So if I make the button appear and click on it, everything is fine. I can repeat the sequence "button appear/click" at will, and each time the button will move offscreen to the bottom and will be removed from the table. I want the button to do exactly the same when the user hits space, so I did:

```
private void clickButton(TextButton button){
    InputEvent inputEvent = new InputEvent();
    inputEvent.setRelatedActor(button);

    inputEvent.setType(InputEvent.Type.touchDown);
    button.fire(inputEvent);

    inputEvent.setType(InputEvent.Type.touchUp);
    button.fire(inputEvent);
}

// then:

stage.addListener(new InputListener(){
  @Override
  public boolean keyDown(InputEvent event, int keycode) {

    if (keycode == Input.Keys.SPACE){
      clickButton(button);
      return true;
    }
}

```

Now when the button is shown and I hit space, it looks like it works, but if I make the button appear again, it's shown briefly then it disappears (it's removed from the table). It's like the final Actions.removeActor() in the button listener is not executed when the button is "clicked" using space, and it's then executed the next time when the button appears again, making it disappear immediately.

EDIT: this is indeed the case. I put a debug print statement right before the Actions.removeActor() action, and upon mouse click the text is printed, but using clickButton() it's not (and it's printed instead when the button is shown again and readded to the table).

Am I doing something wrong here? What's the "correct" way to click a button programmatically (yes, I've already seen https://stackoverflow.com/questions/25870645/programatically-perform-click-on-actor-libgdx)

# Answer
You should use the `Button#toggle()` method together with `Button#setProgrammaticChangeEvents(true)`. From the docs:

> Toggles the checked state. This method changes the checked state, which fires a `ChangeEvent` (if programmatic change events are enabled), so can be used to simulate a button click.

Your code would be:

```
// When you create the button
button.setProgrammaticChangeEvents(true);

// In your listener
if (keycode == Input.Keys.SPACE){
    button.toggle();
    return true;
}

```

Note that you *might* need to change your `InputListener` to a `ChangeListener`. In that case your listener code will be this:

```
new ChangeListener() {
    @Override
    public void changed(ChangeEvent event, Actor actor) {
        // Your code in here.
    }
};

```

---

Looking at the docs it seems like `toggle()` fires a `ChangeEvent` but actual mouse input fires an `InputEvent`. There is no built-in listener that catches both of these events so we have to create one ourselves. This can be really simple as you don't need all of the advanced parameters:

```
public abstract class InputChangeListener implements EventListener {
    @Override
    public boolean handle(final Event event) {
        // We catch InputEvent and ChangeEvent
        if (!(event instanceof InputEvent || event instanceof ChangeEvent))
            return false;
        return handleEvent(event);
    }

    public abstract boolean handleEvent(final Event event);
}

```

Then do:

```
new InputChangeListener() {
    @Override
    public boolean handleEvent(Event event) {
        // Code here
    }
};

```

This should now work for both manual toggle and mouse input.
> 1 votes

# Answer
So after another round of adding features, here's what I came up with. Basically, when the "pause" button is shown on screen, I want the user to be able to do the following:

* Click on it to dismiss the button and resume game
* hit SPACE to dismiss the button and resume game
* hit ESC to dismiss the button and go back to main menu

To get the same button movement regardless of whether the user clicks or hits a key, when the user hits a key I simulate a programmatic button click. However, if the key is ESC, the action taken has to be different, so the listener has to be modifiable at run time.

Skeleton code:

```
// listener that catches mouse clicks and artificially generated ChangeEvent
// action taken can be set dynamically with a Runnable
private class ModifiableListener implements EventListener {

  private Runnable runnable;
  private TextButton button;

  public ModifiableListener(TextButton button, Runnable runnable){
    super();
    this.button = button;
    this.runnable = runnable;
  }

  public void setRunnable(Runnable runnable){
    this.runnable = runnable;
  }

  @Override
  public boolean handle(final Event event) {
    // We catch InputEvent and ChangeEvent
    if ((event instanceof InputEvent && (((InputEvent)event).getType() == InputEvent.Type.touchDown  || ((InputEvent)event).getType() == InputEvent.Type.touchUp))
      || event instanceof ChangeListener.ChangeEvent) {

      if (event instanceof InputEvent && ((InputEvent)event).getType() == InputEvent.Type.touchDown){
        return true;
      }
      this.button.addAction(getDisappearAction());
      return true;
    }
    return false;
  }

  private Action getDisappearAction(){
    return Actions.sequence(
      Actions.moveTo(WORLD_WIDTH / 2 - this.button.getWidth() / 2, -this.button.getHeight(), 0.2f),
      Actions.hide(),
      Actions.run(this.runnable),
      Actions.touchable(Touchable.disabled),
      Actions.removeActor()
    );
  }
}

// then in the screen code...

Runnable resumeAfterPause = () -> { resumeGame(); };
Runnable goToStartScreen = () -> { saveGame(); game.setScreen(menuScreen); };

TextButton pauseButton = new TextButton("PAUSED", skin);
pauseButton.setVisible(false);
pauseButton.setTouchable(Touchable.disabled);
ModifiableListener pausedListener = new ModifiableListener(pauseButton, resumeAfterPause);
pauseButton.addListener(pausedListener);
pauseButton.setProgrammaticChangeEvents(true);

table.add(pauseButton);
stage.add(table);

stage.addListener(new InputListener(){

  public boolean keyDown(InputEvent event, int keycode) {

    if (isPaused) {
      switch (keycode) {
        case Input.Keys.ESCAPE:
          // wait until button is shown and usable
          if (pauseButton.isTouchable()) {
            pausedListener.setRunnable(goToStartScreen);
            pauseButton.toggle();
            return true;
          }
          break;

        case Input.Keys.SPACE:
          if (pauseButton.isTouchable()) {
            pausedListener.setRunnable(resumeAfterPause);
            pauseButton.toggle();
            return true;
          }
          break;

// rest of code...

```

The key bit is that the action to run in the listener can be modified just before the simulated button click is fired, depending on what the user requests. Everything works fine, however the button doesn't "click" (does not draw itself pressed/clicked upon touchDown).

This still looks quite bulky and cumbersome to me, if someone has better suggestions, I'm all ears.
> 0 votes

---
Tags: libgdx, events
---


# Question
Title: Error if inventory is not open when enemy dies
In my game I have a simple loot system implemented. Enemies die and drop items which you can pick up. Picking up an item just draws that item's sprite in an inventory. All of this works properly if my inventory is open on the occasion of killing an enemy. However, if it is closed, i.e., if SetActive is set to false, then I get a strange NullReferenceException which I don't quite understand. Again, this happens if the inventory is closed when an enemy dies and generates an item, not when attempting to pick the item up. Attempting to pick the item up will work regardless of whether or not the inventory is open, insofar as the inventory was open when the enemies died and generated items. Error: NullReferenceException: Object reference not set to an instance of an object ItemPickup.Awake () (at Assets/Scripts/Items/ItemPickup.cs:16) UnityEngine.Object:Instantiate(GameObject, Vector3, Quaternion) ItemGenerator:GenerateItem() (at Assets/Scripts/Items/ItemGenerator.cs:40) ItemGenerator:Update() (at Assets/Scripts/Items/ItemGenerator.cs:32)

Here is the code.

Inventory scripts:

```
public class InventoryToggle : MonoBehaviour
{
    GameObject inventory;

    bool inventoryIsOpen;

    void Awake()
    {
        inventory = transform.Find("Inventory").gameObject;
    }

    void Start()
    {
        // Deactivate in Start instead of Awake to allow other scripts to cache references beforehand
        inventory.SetActive(false);
    }

    void Update()
    {
        if (!inventoryIsOpen && Input.GetKeyDown(KeyCode.I))
        {
            inventory.SetActive(true);

            inventoryIsOpen = true;
        }

        else if (inventoryIsOpen && Input.GetKeyDown(KeyCode.I))
        {
            inventory.SetActive(false);

            inventoryIsOpen = false;
        }
    }
}

```

and

```
public class InventorySlotManager : MonoBehaviour
{
    const int numSlots = 100;

    Item[] items = new Item[numSlots];
    public Image[] itemImages = new Image[numSlots];

    public void AddItem(Item item)
    {
        for (int i = 0; i < items.Length; i++)
        {
            if (items[i] == null)
            {
                items[i] = item;
                itemImages[i].sprite = item.itemSprite;
                itemImages[i].color = new Color(255, 255, 255);
                return;
            }
        }
    }
}

```

Attached to each enemy gameObject:

```
public class ItemGenerator : MonoBehaviour
{
    EnemyHealth enemyHealth;
    ItemRandomizer itemRandomizer;
    public GameObject itemPrefab;

    ItemLabelDisplay itemLabelDisplay;

    bool itemGenerated;

    void Awake()
    {
        enemyHealth = GetComponentInParent<EnemyHealth>();
        itemRandomizer = new ItemRandomizer();
    }

    void Start()
    {
        // Item pool
        itemRandomizer.AddItemsToContainer(ItemDatabase.sword, 1);
        itemRandomizer.AddItemsToContainer(ItemDatabase.axe, 2);
    }

    void Update()
    {
        if (enemyHealth.isDead && !itemGenerated)
        {
            GenerateItem();
        }
    }

    void GenerateItem()
    {
        itemGenerated = true;

        GameObject generatedItem = Instantiate(itemPrefab, transform.position, Quaternion.identity);

        ItemClassAssociation itemClassAssociation = generatedItem.GetComponent<ItemClassAssociation>();

        itemClassAssociation.item = itemRandomizer.GetRandomItem();

        // Set the text in the item label to display the item's name
        itemLabelDisplay = generatedItem.GetComponentInChildren<ItemLabelDisplay>();
        itemLabelDisplay.itemName.text = itemClassAssociation.item.itemName;
    }
}

```

Attached to each Item's UI label

```
public class ItemPickup : MonoBehaviour, IPointerClickHandler
{
    GameObject itemOnGround;
    ItemClassAssociation itemClassAssociation;
    InventorySlotManager inventorySlotManager;

    void Awake()
    {
        itemOnGround = transform.root.gameObject;
        itemClassAssociation = itemOnGround.GetComponent<ItemClassAssociation>();
        inventorySlotManager = GameObject.FindGameObjectWithTag("Inventory").GetComponent<InventorySlotManager>();
    }

    public void OnPointerClick(PointerEventData eventData)
    {
        PickUpItem();
    }

    void PickUpItem()
    {
        inventorySlotManager.AddItem(itemClassAssociation.item);

        Destroy(itemOnGround, 0.1f);
    }
}

```

# Answer
> 4 votes
`FindGameObjectWithTag` skips objects which are not active.

That means that if your inventory is disabled, this will return null:

`GameObject.FindGameObjectWithTag("Inventory")`

So this line in `ItemPickup`'s `Awake()` method:

```
inventorySlotManager = GameObject.FindGameObjectWithTag("Inventory")
                                 .GetComponent<InventorySlotManager>();

```

becomes:

```
inventorySlotManager = (null).GetComponent<InventorySlotManager>();

```

And trying to call an instance method on a null reference triggers a `NullReferenceException`.

Things you can do to fix this:

* Separate your inventory manager (model) from the visual inventory interface (view). Then you can toggle on/off or even delete the visual interface without upsetting the underlying system and game logic of the slot manager. This separation of concerns can set you up well for future iteration, if you ever need to change your UI presentation without upsetting all the code that depends on your inventory system.
* Provide another method of getting access to the inventory slot manager, such as a static reference (eg. a singleton pattern), or a central game manager that's never toggled off that can direct requests for common dependencies.

---
Tags: unity
---


# Question
Title: Depth of Field Blur - Weighted sampling?
I've been studying Intel's fantastic article titled "An investigation of fast real-time GPU-based image blur algorithms" (here), where-in they state that Gaussian blur would need to be customized for proper use in achieving a depth-of-field effect. The relevant part states:

> They are all generic algorithms that are fully applicable to effects like a Bloom HDR filter. However, in a specific scenario, for example for use in Depth of Field, they would require additional customization (such as weighted sampling to avoid haloing/bleeding) which can impact relative performance.

However they don't go into detail about how to compute the weighted sampling? Does anyone know what this means, or know of relevant documentation / example code?

I have been using guassian blur for DoF and have indeed seen the bleeding and other artifacts, so I've been looking for ways to solve these problems.

# Answer
> 2 votes
These are the key things that would make Gaussian Blur very fast on the GPU:

* Separated horizontal and vertical passes
* Remove tail parts of a large Gaussian number since they contribute next to nothing to the target pixel
* Use binomial coefficients as Gaussian number since binomial coefficients (or Pascal's triangle) is the discrete form of Gaussian function
* Use bilinear sampling from hardware to reduce number of samples you sample from the texture

The first two are quite obvious and so I won't explain them in detail. A good suggestion on how to "chop off" the tails of Gaussian numbers would be anything smaller than 1/255.0 because each channel is likely from 0 - 255. The last two are some what less intuitive. Basically the reason you want to use binomial coefficients is because mathematically, as you get closer to the bottom of the Pascal's triangle, the closer you are to the Gaussian function. In fact, binomial distribution is normal distribution with p = 0.5. To convert back and forth, use:

```
sigma^2 = 0.25n
mu = 0.5n

```

where n is the number of terms in the binomial distribution. This tells us, if we want a Gaussian filter with say sigma of 10, we will need 400 term binomial distribution! The center number is actually so large (1.029525991\*10^118) that the edge (1/(2.5822498\*10^120)) would basically be zero. However, if we apply our threshold of 1/255.0, this suddenly drops from 400 terms to merely 43 terms! So in conclusion, you want to use binomial distribution because:

1. The human eye cannot tell the difference between sigma of 1 and 1.75 when blurring with Gaussian. This means we can skip them. This works well in using binomial distribution because we don't need it to be continuous.
2. You can adjust the number of terms (hopefully with a script) without visually tell a difference between a full-blown Gaussian filter V.S. reduced binomial filter.
3. Statically bake these terms into the shader (or code) and therefore no dynamic calculation is needed.

Finally the last optimization is actually a bit harder to explain ... We know that bilinear sampling simply means that the hardware fetch the pixel weighted by their texture coordinates. So if we ask for a color at texture coordinate that's between two pixels, we get 50% of each. The goal is to calculate a texture coordinate such that we get X% of left and Y% of right where X and Y are Gaussian (or binomial) weights.

To actually answer your question, to compute the weighted sample, you calculate the weights (like described above), and then you offset by that number of terms. Say you use 43 terms, that means you offset by 21 pixels left and 21 pixels right of the target pixel. Since we work in texture coordinates, we first calculate how wide each pixel is: (in GLSL)

```
//horizontal pass
vec2 texCoordOffset = vec2(1.0, 0.0) / vec2(TEXTURE_WIDTH, TEXTURE_HEIGHT);
//If vertical, the above should be vec2(0.0, 1.0)
vec4 outputColor = vec4(0.0, 0.0, 0.0, 0.0);
for(int i = 0; i < 21; ++i)
{
    outputColor += binomWeights[i] * texture(TEXTURE_0, uv - vec2(1.0, 0.0) * binomOffsets[i]);
    outputColor += binomWeights[i] * texture(TEXTURE_0, uv + vec2(1.0, 0.0) * binomOffsets[i]);
}

```

The weights are simply 1/sum\_of\_binomial; For example, a 5 term binomial distribution would be 1, 4, 6, 4, 1 and their sum is 16 so the weights should be: 1/16, 4/16, 6/16, 4/16, 1/16; The texture offsets should be: (2\*(1/16) + (1\*(4/16)) / (1/16 + 4/16). The 2 represents 2 pixels from target pixel and 1 represents 1 pixels from target pixel. This gives you a number in texture coordinate and in this case it is 1.2; That is if we fetch at 1.2 pixels away from the target pixel (center), we get 80% of pixel that's 1 away from center and only 20% of pixel that's 2 away from center.

I hope this isn't too confusing ...

---
Tags: shaders, algorithm, effects
---


# Question
Title: Does creating a static instance of a class inside itself have any negative performance effects on game frame-rate
For example, if we have a class that is for handling GooglePlay. And instead of creating an instance of it in every class where you want to use it, you have:

```
public class GooglePlayHandler {

    public static GooglePlayHandler instance;

    private void Awake(){
        instance = this;
    }
}

```

If I then access this in say 5 of my scripts in Unity. Would it be the same, better or worse than having a separate GooglePlayHandler inside each class?

And furthermore if I continue using this style in my game with lots more classes and features would that badly affect the games frame rate. (For example if I did this with my inventory code, cash/points, total time taken, etc etc.

# Answer
> 6 votes
No. This is a standard practice called a singleton (you can see an example in Unity's tutorials with a game manager).

You likely won't see a performance difference between this and 5 instances. But you will have a shared instance instead of multiple, meaning any data created in one would be available to the others.

In the long run, worry about completing the game first, and performance second. Minor performance alterations like this can be performed after the game is complete as a refactoring effort with much better knowledge of the implications and the ability to test changes to see their effects on overall performance.

# Answer
> 2 votes
Ah Singletons - the best pattern. The worst pattern.

So, there should be no performance difference in either case. However, it's likely that with a Handler class (or a Manager class or similar) you'd want a singleton so there's only a single instance managing those data, especially if it's communication with a backend or the like.

http://www.labyrintheer.com/2017/07/22/random-class-singletons-and-the-big-debate-does-this-sound-familiar/

I recently wrote on how I'm using some singletons. There's also a link to a podcast that has some good info on singletons. They are often frowned upon because people tend to misuse them and because it's easy for them to get out of hand. Used correctly, though, the singleton can be a very simple and elegant solution to many issues.

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


# Question
Title: Infinite terrain generation performance: one big heightmap or several smaller heightmap?
I'm generating a procedural terrain using (a home-made fBm based on) Perlin noise as heightmap. To make the terrain infinite, I redraw part of it while the camera moves.

**There are two alternatives:**

1. either have several (say 9) heightmap-textures and rotate them while the camera moves;
2. or have only one heightmap (say 9 times bigger) and redraw only part of it as necessary.

**Note:**

The two approaches redraw exactly the same amount of pixels each time.

**But:**

1. in the first case, I must bind 3 small textures and entirely redraw them to redraw a line of my grid;
2. in the second case, I bind the whole bigger texture and redraw only a line inside it.

**Question:** Should I expect one to be faster than the other? Does `glBindTexture` has higher cost for larger texture?

# Answer
I know this is an old question, but I have played around with procedural terrain generation a lot. So, I would recommend the *smaller option* (i.e. nine "chunks"). There are a few key benefits of using chunks.

* **Modularity** \- You can fit squares of terrain together like puzzle pieces.
* **Speed** \- You don't need to recalculate the massive amount of terrain around the player whenever he/she moves.

They work together, of course. Here's how you can load/unload chunks, depending on where the player is. *Note: a chunk can be unloaded if its contents were generated using a consistent random or noise-generating algorithm (such as Perlin Noise); then they can be loaded again and look the same.*

### Initialization

Player=`P`, Chunk=`-`:

```
  ---
 --P--
  ---

```

### Player movement

Unloaded chunk=`X`; each illustration takes place after a couple of seconds since the last one.

```
                   ---
  ---  |  --P  |  --P--
 --P-- | ----- | XX---
  ---  |  ---  |  XXX

```
> 1 votes

---
Tags: opengl, procedural-generation
---


# Question
Title: How to detect a body between two points on LibGDX
I've two Vector2 (A and B), i draw a line between them.

Is there a way to check if the line intersect the Box2D CircleShape? I need to a boolean output

# Answer
> 2 votes
You should use `World#rayCast(callback, fromPoint, toPoint)` to raycast the line.

```
callback = new RayCastCallback() {
    @Override
    public float reportRayFixture(Fixture fixture, Vector2 point, Vector2 normal, float fraction) {
        // Do stuff here
    }
};
world.rayCast(callback, point1, point2);

```

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


# Question
Title: How to detect if instantiated prefab can be placed at current location or not
I'm using Unity 5.5.0f3 with C#.

My prefab(wooden fence) is instantiated at my mouse location when I click a UI button and follows my mouse until I click somewhere in the scene to place it. The fence has a box collider on it.

Currently, the fence is able to be placed intersecting and even inside of anything else on the scene right now, and I want to eliminate this issue.

I would like my fence (and any other future prefabs) to check if it is intersecting an object's collider when it is following my mouse and turn red if it is, or else be green if it is not to indicate if it can or cannot be placed there and either allow or deny placement accordingly.

I have read that there is no way to do this using transform.position since this is essentially using teleportation on my fence. I tried to use `GetComponent<Rigidbody>().MovePosition(hit.point + positionOffset);` but I get all kinds of weird behavior when I do this.

The following are the three scripts I am using to make this happen:

**Raycast Builder:**

```
public class RaycastBuilder : MonoBehaviour {

    public GameObject defense;
    public Vector3 positionOffset;

    public bool IsPurchased = false;

    public float speed = 2f;

    Vector3 mousePosition;

    BuildManager buildManager;

    void Start ()
    {
        buildManager = BuildManager.instance;
    }

    void Update ()
    {
        GameObject defenseToBuild = buildManager.GetDefenseToBuild();
        if(defenseToBuild == null)
        {
            return;
        }

            //To get the current mouse position
            mousePosition = Input.mousePosition;

            Ray ray = Camera.main.ScreenPointToRay(mousePosition);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit, 1 << 8))
            {
            defenseToBuild.transform.position = hit.point + positionOffset;

            if (Input.GetKey(KeyCode.E))
                {
                    defenseToBuild.transform.Rotate(Vector3.up * speed * Time.deltaTime);
                }
            if (Input.GetKey(KeyCode.Q))
                {
                    defenseToBuild.transform.Rotate(-Vector3.up * speed * Time.deltaTime);
                }
        }

        if (Input.GetMouseButton(0)&& IsPurchased == true)
        {
            buildManager.SetDefenseToBuild(null);
            IsPurchased = false;
        }

        if(Input.GetKeyDown(KeyCode.Escape))
        {
            buildManager.SetDefenseToBuild(null);
            Destroy(defenseToBuild);
            IsPurchased = false;
        }
    }
}

```

**Shop:**

```
public class Shop : MonoBehaviour {

    BuildManager buildManager;

    void Start ()
    {
        buildManager = BuildManager.instance;
    }

    public void PurchaseWoodenFence ()
    {
        Camera.main.GetComponent<RaycastBuilder>().IsPurchased = true;
        Debug.Log("Wooden Fence Started");
        buildManager.SetDefenseToBuild((GameObject)Instantiate(buildManager.woodenFencePrefab, Vector3.up, Quaternion.identity));
    }

}

```

**Build Manager:**

```
public class BuildManager : MonoBehaviour {

    public static BuildManager instance;

    void Awake ()
    {
        if (instance != null)
        {
            Debug.Log("More than one BuildManager in Scene!");
            return;
        }
        instance = this;
    }

    public GameObject woodenFencePrefab;

    private GameObject defenseToBuild;

    public GameObject GetDefenseToBuild ()
    {
        return defenseToBuild;
    }

    public void SetDefenseToBuild (GameObject defense)
    {
        defenseToBuild = defense;
    }

}

```

# Answer
I suggest using isTrigger property of collider instead of raycasting.

Basically instantiate the object you want to place in your scene with its isTrigger set to true, and when it is placed (by mouse click), set isTrigger to false to make it work as a normal collider.

Edit: Attaching my code to demonstrate trigger collider. Also, check out the unity documentation entry about colliders.

```
using UnityEngine;

public class Builder : MonoBehaviour
{
    private int colliderCount = 0;

    private void Update()
    {
        TrackMouse();
        Debug.Log("Number blocking colliders: " + colliderCount);
    }

    private void TrackMouse()
    {
        var mousePosition = Input.mousePosition;

        Ray ray = Camera.main.ScreenPointToRay(mousePosition);
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit, 1 << 8))
            transform.position = new Vector3(hit.point.x, hit.point.y, transform.position.z);
    }

    private void OnTriggerEnter(Collider other)
    {
        colliderCount++;
    }

    private void OnTriggerExit (Collider other)
    {
        colliderCount--;
    }
}

```
> 1 votes

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


title: Libgdx scene editor

text:
# Question
Title: Libgdx scene editor
Is there a 2D scene editor for Libgdx? Like the ability to create the scene and animate it, assign objects fast, then import it to libgdx and start coding?

Basically I want something close to the visual 2D editor of Godot with Libgdx, because Godot is easy but alien to me.

# Answer
> 3 votes
The only Visual 2D editor that I know of for LibGDX is VisEditor, although looking at their Github page it is marked as *deprecated*. It should still work though, but you might encounter some problems here and there. Using this you can create a scene in their 2D editor and then load it into LibGDX via code.

It also has support for `FreeType` (TTF) fonts and `Spine` animation.

---
Tags: libgdx
---


title: Reshapable polygonsprite

text:
# Question
Title: Reshapable polygonsprite
I have an sprite I want to use as a texture. I want to create an area, defined by a polygon collider, where the sprite is drawn.

For example:

* Having the following sprite
* And the following polygon collider 2d:
* I want to have the resulting sprite/mesh:

This way I would have an image that covers exactly the polygon collider area.

Having an sprite and modifying it's vertexes doesn't seem to do the trick, as they are only editable while loading the sprite into unity.

Is there a way to make it editable in the editor, so while I change my collider, the image is updated to fit inside of it?

# Answer
> 2 votes
As you've pointed out, Sprite.OverrideGeometry is a bit too picky with what it lets you do to make this simple.

But, we can get a lot of the same outcomes by using a MeshRenderer with a custom-shaped Mesh. The downside is losing the easy layer sorting we get with Sprites, but it's possible to imitate that by other means if you need granular sorting control.

In the example above I've got a GameObject with an (initially empty) Mesh Filter, a MeshRenderer with a basic Unlit Texture material assigned, and the script below. You can see it handles interactively reshaping the rendered polygon to match the collider and tiling the texture across the result. It does not correctly handle self-intersecting polygons in its current incarnation.

```
[RequireComponent(typeof(MeshFilter))]
[RequireComponent(typeof(PolygonCollider2D))]
public class 2DPolyColliderToMesh : MonoBehaviour {

    PolygonCollider2D _collider;
    Vector2[] _cachedPoints;
    List<int> _triangles = new List<int>();
    Mesh _myMesh;

    // In-editor, poll for collider updates so we can react
    // to shape changes with realtime interactivity.
#if UNITY_EDITOR
    void OnDrawGizmosSelected()
    {
        if (_collider == null)
            Initialize();
        else {
            var colliderPoints = _collider.GetPath(0);
            if(colliderPoints.Length == _cachedPoints.Length) {
                bool mismatch = false;
                for(int i = 0; i < colliderPoints.Length; i++) {
                    if (colliderPoints[i] != _cachedPoints[i]) {
                        mismatch = true;
                        break;
                    }
                }
                if (mismatch == false)
                    return;
            }

            Reshape();
        }
    }
#endif

    // Wire up references and set initial shape.
    void Initialize()
    {
        _collider = GetComponent<PolygonCollider2D>();
        var filter = GetComponent<MeshFilter>();

        // This creates a unique mesh per instance. If you re-use shapes
        // frequently, then you may want to look into sharing them in a pool.
        _myMesh = new Mesh();
        _myMesh.MarkDynamic();

        Reshape();

        filter.sharedMesh = _myMesh;
    }

    // Call this if you edit the collider at runtime
    // and need the visual to update.
    public void Reshape() {
        // For simplicity, we'll only handle colliders made of a single path.
        // This method can be extended to handle multi-part colliders and
        // colliders with holes, but triangulating these gets more complex.
        _cachedPoints = _collider.GetPath(0);

        // Triangulate the loop of points around the collider's perimeter.
        LoopToTriangles();

        // Populate our mesh with the resulting geometry.
        Vector3[] vertices = new Vector3[_cachedPoints.Length];
        for (int i = 0; i < vertices.Length; i++)
            vertices[i] = _cachedPoints[i];

        // We want to make sure we never assign fewer verts than we're indexing.
        if(vertices.Length <= _myMesh.vertexCount) {
            _myMesh.triangles = _triangles.ToArray();
            _myMesh.vertices = vertices;
            _myMesh.uv = _cachedPoints;
        } else {
            _myMesh.vertices = vertices;
            _myMesh.uv = _cachedPoints;
            _myMesh.triangles = _triangles.ToArray();
        }
    }

    void LoopToTriangles() {
        // This uses a naive O(n^3) ear clipping approach for simplicity.
        // Higher-performance triangulation methods exist if you need to
        // do this at runtime or with high-vertex-count polygons, or
        // polygons with holes & self-intersections.
        _triangles.Clear();

        // Mode switch for clockwise/counterclockwise paths.
        int winding = ComputeWinding(_cachedPoints);

        List<Vector2> ring = new List<Vector2>(_cachedPoints);
        List<int> indices = new List<int>(ring.Count);
        for (int i = 0; i < ring.Count; i++)
            indices.Add(i);

        while(indices.Count > 3) {
            int tip;
            for (tip = 0; tip < indices.Count; tip++)
                if (IsEar(ring, tip, winding))
                    break;

            int count = indices.Count;
            int cw = (tip + count + winding) % count;
            int ccw = (tip + count - winding) % count;
            _triangles.Add(indices[cw]);
            _triangles.Add(indices[ccw]);
            _triangles.Add(indices[tip]);
            ring.RemoveAt(tip);
            indices.RemoveAt(tip);
        }

        if (winding < 0) {
            _triangles.Add(indices[2]);
            _triangles.Add(indices[1]);
            _triangles.Add(indices[0]);
        } else _triangles.AddRange(indices);
    }

    // Returns -1 for counter-clockwise, +1 for clockwise.
    int ComputeWinding(Vector2[] ring)
    {
        float windingSum = 0;
        Vector2 previous = ring[ring.Length - 1];
        for (int i = 0; i < ring.Length; i++)
        {
            Vector2 next = ring[i];
            windingSum += (next.x - previous.x) * (next.y + previous.y);
            previous = next;
        }

        return windingSum > 0f ? 1 : -1;
    }

    // Checks if a given point forms an "ear" of the polygon.
    // (A convex protrusion with no other vertices inside it)
    bool IsEar(List<Vector2> ring, int tip, int winding) {
        int count = ring.Count;
        int cw = (tip + count + winding) % count;
        int ccw = (tip + count - winding) % count;
        Vector2 a = ring[cw];
        Vector2 b = ring[tip];
        Vector2 c = ring[ccw];

        Vector2 ab = b - a;
        Vector2 bc = c - b;
        Vector2 ca = a - c;

        // Early-out for concave vertices.
        if (DotPerp(ab, bc) < 0f)
            return false;

        float abThresh = DotPerp(ab, a);
        float bcThresh = DotPerp(bc, b);
        float caThresh = DotPerp(ca, c);

        for (int i = (ccw + 1) % count; i != cw; i = (i + 1) % count) {
            Vector2 test = ring[i];
            if (   DotPerp(ab, test) > abThresh
                && DotPerp(bc, test) > bcThresh
                && DotPerp(ca, test) > caThresh )
                return false;
        }

        return true;
    }

    // Dot product of the perpendicular of vector a against vector b.
    float DotPerp(Vector2 a, Vector2 b) {
        return a.x * b.y - a.y * b.x;
    }
}

```

# Answer
> -1 votes
You could make a nested for-loop to draw the sprite the right number of times in each direction. For each sprite, draw a point, if the point is within the bounds of the collider.

In other words, you need to define a boolean function that will return `true` if the point is within the collider and `false` otherwise. There are many ways to this, but by testing if the point is in a polygon (or in any one of a set of polygons) should do the trick.

---
Tags: unity, 2d
---


# Question
Title: OpenGL render shapes without texture file
I currently have beginner knowledge of OpenGL and something doesn't go into my head! How do I create shapes like eg. a triangle with rounded borders. Or a quad with rounded borders. Or some random irregular shape. How is something like that done?

The only thing I could think of is creating an empty texture2D and editing the pixel data per CPU, but is that the way to go or are there better ways to do something like this?

# Answer
Well let's see, you either:

* Have a texture that you made or downloaded, and supply it to the GPU
* **Generate a texture on the CPU** and supply it to GPU for use *in exactly the same was as above*; generation can occur either before your program runs, or *when* it runs
* Don't use textures; detail may be achieved by combining vertex colouring and geometry

Image generation is a whole separate field, which is why you do not see it in many games. The closest related fields in games are procedural generation and screen space / pixel shader effects (though *modification* that takes place here is not on the same order of complexity as *generation*).

`is that the way to go`

...for what? How can we answer if we don't know what you're trying to achieve? There are many reasons to use a generated texture, and more reasons *not* to, but we don't know which apply to you.
> 1 votes

---
Tags: opengl, c++, mesh
---


# Question
Title: Does 64-bit translation and transformation slow down the engine significantly?
So, how does one go with rendering world space calculated in 64-bit? How can that even work? GPUs can use Double Precision, but significantly slower than FP32. How can one achieve world space coordinates using 64-bits and then render it on consumer GPUs?

e.g.: Star Citizen and No Man's Sky claim 64-bit world coordinates.

# Answer
By handling your game mechanics in 64bit but then convert the coordinates to a local 32bit coordinate system when passing coordinates to the 3d rendering API. The origin of that local coordinate system should be either centered around the player or be a point nearby, so that objects close by are rendered with maximum precision. Nobody will notice when objects which are far away (like other stars) have a lower rendering precision.

Keep in mind that all you need to pass to the rendering engine per object and frame is its model-view matrix (which encodes the current position, rotation and scale), which is just 16 numbers you need to convert. The bulk of the floating-point calculation the GPU has to handle is sending all the vertices of the 3d model through that matrix. The vertices for each 3d model only need to be transferred to the GPU once. And considering that they are relative to the origin of the 3d mesh, there is very little reason to use 64bit vertex coordinates.

There are also situations where you want to use GPU acceleration for things which are usually considered game mechanics. Complex physics simulations or particle systems are a common example. But usually you only simulate them when they are close to the player. There is little reason in calculating the particles of a coronal mass ejection of a star at the other end of the galaxy.That means you can simulate these in a local coordinate system which uses 32bit as well.
> 7 votes

# Answer
Only coordinates (position) needs higher precision storage for game physics.

The GPU only needs to know everything relative to the camera (the screen) in order to render and does not necessarily needs to calculate physics so you can convert all the 64bits positions to 32bit camera-relative positions before feeding them to the GPU.

## Physics are another story:

Even 64 bit floats are not precise enough if you're walking on planets with the local star as the world origin.

You absolutely have to use a localized coordinate system for a space exploration game that lets you land and walk. You also need different systems for on-planet and off-planet physics.

This means at the game logic (CPU) level your coordinates, including the camera, are relative to a local reference point: the current planet's center (planetary exploration), the current solar system's center (local space travel), or the galaxy center (inter-planetary travel).

But this makes it somewhat more difficult to use the Engine's built-in collision and particle systems. You have to give the game engine everything in the local coordinate system and do conversions when switching areas and scales.

## Why is just switching to 64bits not enough:

If you're using the sun as the origin (zero):

* 64bits floats (doubles) have 53bits of precisions. (2^53 = 9.007199255×10¹⁵)
* Pluto is at 5,906,380,000,000 meters from the sun on average.
* 9.007199255×10¹⁵÷5906380000000 = 1/1525th of a meter of **precision (0.6mm, 0.024")**

That means that on Pluto with 64bit floats **any movement in a single frame smaller than 0.3mm** (0.6mm/2) will be **rounded down to zero** and any movement between 0.3mm and 0.6mm will be rounded up to 0.6mm and so on.

While this may still be fine for rendering this is not enough for physics and collisions.

If our minimum speed is 0.3mm **per frame** and that gets rounded up to 0.6mm this means that at just 60 frames per second:

0.3mm * 60 fps * 60 seconds * 60 minutes = 0.0648 kmh (0.04mph)

Gets rounded up to double this speed.

Assuming an acceptable error is a very forgiving 5% (1/20th) in order for movement to be visually tolerable this means the minimum acceptable speed would be 2.592kph (1.61mph).

Keep in mind a 5% error is still very perceivable.

Even on Earth movements would still look very coarse and collisions glitch due to rounding errors will be plentiful if the coordinate system's origin is the sun.
> 2 votes

---
Tags: rendering, precision
---


title: How can I fade out my overlay in Unity?

text:
# Question
Title: How can I fade out my overlay in Unity?
Something that I can accomplish in 5 minutes in libGDX is taking me forever in Unity. I have a `Canvas` with a button that covers my entire screen. When the button is clicked, I want the button to fade out and then for the underlying UI to be clickable (if the button is just faded out but it's still on top, you can't click anything).

I tried to use `crossFadeAlpha` on the `Image` attached to the button, but the problem is that `crossFadeAlpha` is async, so I can't do `image.enabled = false;` when it finishes.

Is there *any* simple way to accomplish this task in Unity?

# Answer
> 2 votes
Using a Tween engine may not be necessary here, a simple coroutines will do the job :

```
private IEnumerator FadeOut( float duration )
{
    Image image = GetComponent<Image>();
    Color color = image.color;
    float startAlpha = color.alpha;
    float endAlpha = 0;

    for ( float t = 0 ; t < duration ; t += Time.deltaTime )
    {
         color.alpha = Mathf.SmoothStep ( startAlpha, endAlpha, t / duration ) ;
         image.color = color;
         yield return null;
    }
    color.alpha = endAlpha;
    image.color = color;
    image.enabled = false;
}

// ....

StartCoroutine ( FadeOut ( 5f ) ) ;

```

I'm on my phone, I haven't tested and the formatting is bad, sorry.

# Answer
> 0 votes
Try the code below. The update method of the button's script:

```
private float alpha;

void Update(){
    //Apply fade process here
    if(alpha <= 0){
        GetComponent<Button>().enabled = false;
    }
}

```

---
Tags: unity
---


# Question
Title: Would directly modifying vertex array be a good idea in 2D?
I'm currently using opengl es 1.1 for simple 2D drawing and I was wondering if it would actually be inefficient to use the opengl transform functions (since using matrix operations to move a square seems like unnecessary work), and if directly modifying the vertex array would be a better idea.

# Answer
> 2 votes
This is a micro-optimization. How would you modify the vertex array? Would you upload it to the card again from main memory? If so, that will be much slower than 4 vertices doing a matrix multiply in parallel, which is likely to be what will happen using the transform functions.

In general, you should profile your code to see where the slowdowns are rather than guessing and trying to optimize before you know. What you've described so far doesn't sound very taxing on the hardware. Also, when you do find an area that needs to be optimized, you're often better off choosing a better algorithm than optimizing the implementation you currently have. (Unless of course you know that you're using the optimal algorithm.)

---
Tags: opengl-es
---


# Question
Title: (How exactly to use EventSystem?) Assigning string Name to UI Button in Unity without CrossPlatformInput?
I'm trying to make a new game for Android. There is a Jump button i've added as UI button , this works fine as I have a method for Jump() which I can just add to the OnClick() method in the Button's Inspector tab.

However, for my 'Pick Up' button I don't really want a method for pick up. I already have my item pickup handling code inside a OnTriggerEnter() method and what I was hoping to do was have an additional if condition into my code like:

```
if (Input.GetButtonDown("Pickup")){ //then it ok to pickup! }

```

This is how i did it in my other projects. But I had been importing the CrossPlatformInput namespace and then just copied and adapted the buttons from the Jump button that came as standard with that.

So now, I can't see how to name my button as 'Pickup'. I tried looking at the code from CrossPlatformInput, it seems it takes the name you provide it, and passes it to VirtualInput (also in the CrossPlatformInput namespace), I couldnt see a copy of this class anywhere, it think its closed source maybe :/

Of course, I could probably manually make a method to add to the OnClick() which just makes a bool true only when it's being clicked. But I feel like there must be a way to just add this UI button as 'Pickup' to the Input system (like you do with "Horizontal", "Vertical" or "Jump" for example).

Again, I tried to read the docs, and also lots of forums and sites like this. I found that the EventSystem will (or should) have the part I need, but i am now stuck.

I tried this:

```
EventSystem.current.currentSelectedGameObject.name == ??????????

```

I read that will return the name of the most recent button pressed, but how would that method know that my new Button is called "Pickup", I dont see how I added it to that yet?

Another reason why i'd like to do it this way is for Cross Platform compatibility. If I make it this way, I already now that there is a certain button on the keyboard mapped in Project\>Input to the same name (ie. "Pickup" ; Left-Ctrl). And it seems cleaner to use the existing way of doing this if possible, im sure its just that I dont know how yet.

Most options ive seen online involve the OnClick inspector function, or CrossPlatFormInput imported package.

I hope this makes sense to someone, and that there is a way to do it. Thanks for any help as usual very much appreciated.

# Answer
> 0 votes
Well, it's not really an answer, but I have managed to workaround it by hacking together my own button handling code. It doesn't involve the CrossPlatformInput at all, and it sadly doesn't include any reference to the Unity Project Settings \> Input like I was hoping. But it does work for the time being.

If anyone can explain a better way I should of done this, then I'd love to see it:

```
public class ButtonManager : MonoBehaviour {
public static ButtonManager instance;
public bool isPickUpPressed = false;
private float framesForClick = 3, clickCounter = 0;

private void Awake()
{
    instance = this;
}
void Start () { }

void LateUpdate () {
    // clears the button pressed bools:
    if (isPickUpPressed == true)
    {
        clickCounter++;
        if (clickCounter >= framesForClick)
        {
            isPickUpPressed = false;
            clickCounter = 0;
        }
    }
}

public void ClickButtonPickUp()
{
    isPickUpPressed = true;
}
}

```

For me this just feels over the top, and wrong.

I can't really say why, I just feel like I should of been able to assign the button with the 'name' of "Pickup" inside the Unity Settings. Instead I just call this ClickButtonPickUp method from my button's OnClick() inspector window.

Setting it to off (or false) involves me making two variables to count the number of frames since the button was pressed and making it back to off, so that it can be clicked again a few frames later. It just seems wrong but its the only way I could personally think of how to do it.

---
Tags: unity, c#, gui, input
---


# Question
Title: Mute/Unmute Sound For All Game Scenes by pressing Button
My Question is simple i just want to Mute/Pause All Sound of the Game having different scenes.

From Scene 1 Which is a Main Menu I Have Two Button On/Off . When i press On Button it stops or mute full game sound or music like Car sound etc in all Scenes. When i press off button then Sound become active again in all scenes ..

I'm new in this field so please give me some help My Game is almost Complete But i can not Control or Mute All scene Sound at the same time..Waiting

# Answer
Simply saving the audio volume to `PlayerPrefs` and then loading it on every scene should do the trick:

```
// When off is pressed
PlayerPrefs.SetFloat("volume", 0.0F);

// In every scene
AudioListener.volume = PlayerPrefs.GetFloat("volume");

```

To enable the volume simply change the volume value to something larger than 0.
> 0 votes

---
Tags: unity, sound
---


# Question
Title: Do you need a license for weapon models?
When creating your own model for a weapon, say the M4 carbine, and using the model in your game. Do you need a license to use it commercially? I know that racing games like GT5 has a license for each and every car, but the same apply for weapons?

# Answer
> 14 votes
**I am not a lawyer and you should consult one for real, accurate legal advice.**

The name and design are likely trademarked (you can see here for example that there have been trademark issues with the M4 in the past; other guns will likely have similar issues).

EDIT: It is possible that as far as a trademark is concerned I may have been misinterpreting things, and it may be okay depending on your circumstances. However, you will still potentially need to worry about other intellectual property restrictions (such as any copyrights held in relation to the item in question) which do apply regardless of whether or not your product is commercially available.

At the end of the day, if you violate somebody's intellectual property laws and they call you on it you can be in a world of hurt so it's best to get real legal advice because the risk is pretty severe. There's a good set of articles on intellectual property issues by a Real Lawyer here.

# Answer
> 6 votes
If you plan on releasing your game commercially, you will need to seek permission from each firearm's manufacturer for using its name and likeness. This is just from my experience in FPS development. I'm a programmer. Not a lawyer :)

# Answer
> 3 votes
It seems that in most cases the name of the weapon is partially changed and sometimes the model, though usually the weapon models are very similar to the actual weapon. tvtropes has several good real world examples of guns in games that have had changes to their names: http://tvtropes.org/pmwiki/pmwiki.php/Main/AKA47

# Answer
> 1 votes
IANAL but names and logos are trademarked. The appearance of a gun is not, unless there is a specific design patent, which is rare. Mechanical patents don't apply here.

So just don't use any actual names or logos. I am not sure about "M4" specifically. It is really a family of weapons and not specific weapon from a specific manufacturer. Definitely do not call it a Colt M4, for example. I saw another comment where you asked about an FN rifle. FN stands for the name of the company Fabrique Nationale, so you also can't use that.

I think you should just make up your own names for the guns, but consult an actual lawyer anyway.

# Answer
> 0 votes
**Not a lawyer...**

There are multiple fair use elements which serve as a defense in this scenario, in particular 'Purpose and character' in US law. In my interpretation it would be almost impossible to prosecute given the degree to which these defenses stand.

# Answer
> 0 votes
I don't think you do need a license for several reasons, but I'm not a lawyer.

1. Trademarks are not copyrights or patents. Trademarks are designed to protect consumers. The idea being that a trademarked M4 carbine, for example, is made by Colt Defense (or someone they have licensed to build them) and not by some other company making cheaper versions. The OEM can stop the cheaper company from calling its product an M4 but can't stop it from making the copies. Stopping manfuacturing can only be done through patents. Recently, there has been a dispute between Ford and the Ferari F1 racing team over the name F150. Although the two vehicles could never be confused, this was done primarily to keep hold of the trademark, not enforcing the trademark is one way of losing ownership of the trademark.
2. There are many other things that appear in video games that have trademarks, are they all licensed? Why should the M4 be special?
3. Do other media pay licenses to use the trademark. For example, if a James Bond novel had a description of someone hold an M4, would that require a license?
4. You are not selling a gun. Trademarks can only be enforced against similar products. A game is not a gun, in the same way it's not a drink, shop, car, etc.
5. In the USA, you can claim the First Amendment (free speech) and fair use.

As for games like GT5, they are probably not licensing the trademark, and probably couldn't license it as they aren't building cars. They are probably licensing the copyright on the names and logos.

# Answer
> 0 votes
In Reality and Legal terms, most guns are trademarked twice AND patented both in terms of manufacturing and looks. The trademark includes the gun's own logo and the gun's visual identification.

This means that any manufacturer and patent holder of any of those guns "could" do legal action against you if you were to use the exact replica of their guns. This includes visual, sounds and logotypes (logos).

Now, there are ways of moving around those legal possibilities:

1) Modifying the name and gun, visually, so that it's different. Ideally, you have to make it 20% different (80% alike) and you're safe. In terms of games, that's easier to do because you don't have to "create" the inner mecanism of the guns so having something like a different gun sound + changing some small details usually works.

2) Using old schematics that hasn't been renewed in the past 15 years. This is one of those legal grey zones where any manufacturer has the legal obligation to renew any of their product's visual trademarks every year. (It cost around 100 USD per trademark). After 15 years without any renew, the trademark becomes idle and anybody can "use" the visual as they like. There would be some difficulties if you were a gun manufacturer trying to use such as thing, but for games it's kinda like a legal grey zone where the manufacturer can't do anything as long as it doesn't renew its trademark license and, then, it can only stop any "further" additions.

The thing about guns is that they are usually modified every 4 to 5 years. If you find some pictures or schematics of any model that is 15 years old AND has been updated at least once since then (meaning the gun is now slightly different than its past form), you can usually use the older form due to the manufacturer who, usually, doesn't renew its older "look" as a trademark. The name is usually the same so you might have to change the name though.

There "are" some exception to that when, for example, a country take over a gun schematics for further modification and put up an open request for new versions such as the M4. This bring the complication of having multiple version of the M4's trademark "still" valid (one is owned by Colt, one is owned by the US Army itself and one is owned by Remington Arms Co. in the case of the M4).

The most ideal for you is to think of your own version of the gun by adding and removing details. It's not "that" hard as the manufacturer usually add many useless details or reinforcement part to their gun for the sake of making them look more "dangerous" (less toy-like). Change the cannon lenght, the hand grip, trigger and modify some of the details on the main body and you're mostly up to go. Instead of calling it a M4 (for example), call it ARM4 or even something like M-A4 could work if it doesn't exist already.

---
Tags: licensing
---


# Question
Title: Getting Vector at 90 Degrees from provided vector
I need a function that can take a vector as an input and provide a vector that is at a 90-degree angle to the provided vector. I understand that in 3D there is an infinite amount of vectors that could be produced from this calculation, but I only require 1. I have been using GLM and have tried using its built in vector rotation functions but to no avail. I would like to keep the solution compatible with GLM as I wish to have everything standardized.

Here is a basic visualization of what I need.

**Edit** The function's purpose is to pass a direction vector into a function, radius, and an angle and it will create a point around the origin at x angle in space. The reason for this is so I can loop through and create a point cloud in 3D space and then join them together to make shapes such as cylinders (see photo)

**Solution Code**

```
glm::vec3 CreateAngledPoint(glm::vec3 rotation_point, float radius, float angle, glm::vec3 normal)
{
    // Normalize the normal (axis to rotate on)
    normal = glm::normalize(normal);
    // Create a vector that will be used for the dot product
    glm::vec3 to_cross = glm::normalize(glm::vec3(0.0f,1.0f,0.0f));
    // Make sure that the normal and cross vector are not the same, if they are change the cross vector
    if (to_cross == normal) to_cross = glm::normalize(glm::vec3(0.0f, 0.0f, 1.0f));
    // Get the cross product
    glm::vec3 to_return = glm::normalize(glm::cross(normal,to_cross));
    // Rotate point around the axis
    to_return = glm::rotate(to_return, angle* RAD_TO_DEG, normal);
    // Scale the point up from the origin
    to_return *= radius;
    // Apply it to the point in space we are rotating around
    return rotation_point + to_return;
}

```

**Example of its usage**

# Answer
> 2 votes
Edit:

`So the question was for 3D and It isn't very clear whether you're drawing 2 vectors or 3. Use colors for each axis!`

To get the perpendicular of a plane you simply need 2 vectors and take the cross product of the two. The two vectors represent the plane. Visualize this by making a right angle between your thumb and index finger. Your fingers represent the vectors, that's your plane.

If GLM doesn't have the cross product function you can simply do it manually:

The cross product can be calculated very quick by applying the following trick: Shift the `x` component to the bottom, multiply each component with their diagonal and subtract

```
 [a.y]   [b.y]   [a.y*b.z - b.y*a.z]   [c.x]
 [a.z] x [b.z] = [a.z*b.x - b.z*a.x] = [c.y]
 [a.x]   [b.x]   [a.x*b.y - b.x*a.y]   [c.z]
 [a.y]   [b.y] // It loops around for completion

```

The c vector is your perpendicular vector to the plane. Provided that both vectors are normalized.

Note: if two vectors are parallel the resulting vector will be \[0,0,0\].

---

2d:

The perpendicular ( aka normal )can be found by simply swapping the x and y values and negating one of the two

```
  [2,5] -> [-5,2]

```

Depending on which on you negate gives you the directing your vector goes into.

Edit: Geogebra can easily visualize this.

https://ggbm.at/CuaUGr4d

Move point B and you will see that the perp is always the same with the x and y swapped and one negated.

# Answer
> 1 votes
You need to calculate the **Cross Product** ( https://en.wikipedia.org/wiki/Cross\_product ) of two vectors normalized.

One is your "provided vector" and the other is a vector perpendicular to the plane you want to rotate 90 degrees over.

```
template<typename valType >
detail::tvec3< valType > cross (detail::tvec3< valType > const &x, detail::tvec3< valType > const &y)

```

This will return a vector that is perpendicular (at 90 degrees) to **both** normals (unit vectors).

```
glm::cross( glm::normalize(provided_vector), glm::normalize(some_vector) );

```

some\_vector must not point in the same direction nor can be opposite to provided\_vector.

You must pick a `some_vector` depending on what you need.

If you want something "on the floor" at 90 degrees to something else "on the floor" making `some_vector` point straight upward or downward is a good choice.

What is up or down depends on how your game. Often it's the Y axis (0, 1, 0).

If you want to rotate 90 degrees the opposite way, negate the `some_vector`.

---
Tags: mathematics, vector, glm
---


# Question
Title: OpenGL only utilizing the last initialized sprite's positional data
I'm currently creating a 2d fighting game utilizing OpenGL and I have run into a problem where OpenGL is only drawing at my last initialized sprite position, regardless of how many sprites I initialize and try and draw. Even when I initialize a sprite1 and sprite2 but only draw sprite1, sprite2 is what will still be drawn. It starts with my sprite class where I initialize where on the screen I want my image as well as what image to use:

Sprite.cpp

```
 Init(int screenCoordinateX, int screenCoordinateY, uint imageWidth, unsigned int imageHeight, std::string imageFilePath)
{
    //casting to float since GLSL shader variables vec2,3,4 require vertex data to be in floats
    this->x = static_cast<float>(x);
    this->y = static_cast<float>(y);
    this->width = static_cast<float>(width);
    this->height = static_cast<float>(height);

    glGenBuffers(1, &vboID);

    Blz::Graphics::GLTexture texture(imageFilePath);
    this->texture = texture;

    float halfWidth = this->width / 2;

    //Setting sprite origin at bottom middle of image by subtracting half width
    this->vertexData.at(0).SetPosition(glm::vec3{ this->x + (this->width - halfWidth), this->y + this->height, 0.0f });//Top right corner
    this->vertexData.at(1).SetPosition(glm::vec3{ this->x - halfWidth, this->y + height, 0.0f });//Top left corner
    this->vertexData.at(2).SetPosition(glm::vec3{ this->x - halfWidth, this->y, 0.0f });//Bottom left corner
    this->vertexData.at(3).SetPosition(glm::vec3{ this->x - halfWidth, this->y, 0.0f });//Bottom left corner
    this->vertexData.at(4).SetPosition(glm::vec3{ this->x + (this->width - halfWidth), this->y, 0.0f });//Bottom right corner
    this->vertexData.at(5).SetPosition(glm::vec3{ this->x + (this->width - halfWidth), this->y + this->height, 0.0f });//Top right corner

    this->vertexData.at(0).SetUV(glm::vec2{ 1.0f, 1.0f });
    this->vertexData.at(1).SetUV(glm::vec2{ 0.0f, 1.0f });
    this->vertexData.at(2).SetUV(glm::vec2{ 0.0f, 0.0f });
    this->vertexData.at(3).SetUV(glm::vec2{ 0.0f, 0.0f });
    this->vertexData.at(4).SetUV(glm::vec2{ 1.0f, 0.0f });
    this->vertexData.at(5).SetUV(glm::vec2{ 1.0f, 1.0f });

    glBindBuffer(GL_ARRAY_BUFFER, vboID);
    glBufferData(GL_ARRAY_BUFFER, (sizeof(Vector3D) * this->vertexData.size()), &this->vertexData.front(), GL_STATIC_DRAW);

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vector3D), (void*)offsetof(Vector3D, position));
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vector3D), (void*)offsetof(Vector3D, textureCoordinates));

    //Unbind
    glBindBuffer(GL_ARRAY_BUFFER, 0);
}

```

I then try and render sprites passed in to renderer like so:

Renderer.cpp

```
void Renderer::Draw(Sprite& sprite)
{
    glm::mat4 orthoProjection = glm::ortho(0.0f, static_cast<sfloat>(1024), 0.0f, static_cast<sfloat>(768));
    GLuint transformationMatrixUniformLocation = this->shaderProgram.GetUniformLocation("transformationMatrix");

    glUniformMatrix4fv(transformationMatrixUniformLocation, 1, GL_FALSE, &(orthoProjection[0][0]));

    glBindTexture(GL_TEXTURE_2D, sprite.texture.id);
    glBindBuffer(GL_ARRAY_BUFFER, sprite.vboID);

    glDrawArrays(GL_TRIANGLES, 0, 6);

    glBindBuffer(GL_ARRAY_BUFFER, 0);
}

```

I here is my main.cpp where I begin to call everything:

```
int main()
{
    Blz::Graphics::Renderer renderer;
    Blz::Window window;
    Blz::Input input;
    Scene scene;

    window.Initialize();
    renderer.Init();

    Sprite sprite1;
    sprite.Init(900, 300, 200, 200, "CharImage.png");

    Sprite sprite2;
    sprite2.Init(100, 100, 200, 200, "CharImage.png");

    while (!input.IsKeyPressed(SDLK_ESCAPE))
    {
        window.ClearBuffers();

        renderer.Draw(sprite1);

        window.SwapBuffers();
    }

    return 0;
}

```

So even though I ask for sprite1 to be drawn, only sprite2's position at 100x 100y gets drawn to the screen. Even if I manually try and enter a vboID of 1 (which is the vboID of sprite1) within renderer.cpp, it still draws sprite2's position. What am I doing wrong?

Here are my Shaders if necessary:

VertexShader.glsl

```
#version 430

in vec3 vertexPosition;
in vec2 textCoord;

out vec2 TextureCoord;

uniform mat4 transformationMatrix;

void main()
{
    vec4 position = vec4(vertexPosition, 1.0f);
    gl_Position = transformationMatrix * position;
    TextureCoord = textCoord;
};

```

FragmentShader.glsl

```
#version 430

out vec4 daColor;
in vec2 TextureCoord;

uniform sampler2D basicTexture;

void main()
{
    vec4 texel = texture(basicTexture, TextureCoord);
    daColor = texel;
};

```

# Answer
> 0 votes
You are calling `glVertexAttribPointer` *in* `Sprite.Init`. So it makes sense that the last sprite initiated will be rendered, since that sprite's vertices are being pointed to.

Instead, one way to handler this is to create a method for `Sprite` called `Render` (I don't write in C++, so please excuse any case errors!). Call this method in your render loop, and call `glVertexAttribPointer` in the method. Then, the order in which you initiate the sprites won't matter.

---
Tags: opengl, c++, graphics-programming
---


title: Why would a property be returning null?

text:
# Question
Title: Why would a property be returning null?
I'm working on learning how pass data from one script to the other in Unity and I'm getting a little confused. I have two scripts, `PlayerData` and `CreateCharacter`. `PlayerData` is used to pass persistent data from one scene to another, so it's not going to be attached to any `GameObject` or `Transform`. `CreateCharacter`, however, is attached to a button which gets the information from user input. Here are the two scripts:

**PlayerData**

```
public class PlayerData{
    private string playerName;

    public string PlayerName{
        get{return playerName;}
        set{playerName = value;}
    }
}

```

**CreateCharacter**

```
public class CreateCharacter:MonoBehaviour{
    public InputField playerName;
    public PlayerData playerData = new PlayerData();
    public void AddStats(){}
    public void SubtractStats(){}

    public void CreateCharacterOnClick(){
        playerData.PlayerName = playerName.text;
        Debug.Log(playerData.PlayerName);
    }
}

```

What's happening is, when I click the button I'm getting a null reference error on `playerData.PlayerName` but if I just log `playerData` I actually get the object to return. What I'm trying to see is that the character name(`playerName`) is logged when the button is clicked. Can anyone explain to me what I'm doing wrong and how to fix it?

# Answer
> 2 votes
As I understand it, you get a null reference exception here:

```
playerData.PlayerName = playerName.text;

```

You seem to think it's because of `playerData`, but I don't think that's the case. You initialize `playerData` (`public PlayerData playerData = new PlayerData();`, above).

What you *don't* initialize... at least in the code you've posted here... is `playerName`. You declare it above (`public InputField playerName;`) but you don't assign it a new instance.

Unless you are initializing `playerName` elsewhere, then you try to read the text from that input field you will get a null reference exception, because it's null. That's probably why if you remove that and "just log `playerData`" you get sane results.

I'd suggest you initialize the input field somewhere.

# Answer
> 1 votes
Your problem is that you're never initializing the playerName property in PlayerData. By default, that particular string is going to be null, while the playerData object is not, hence why the log works.

All you have to do is give a value to playerName in playerData.

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


# Question
Title: Opengl Es 1.1 Setting Different Transformations For Different Parts of Array
I have the following code:

```
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glPushMatrix();
glTranslatef(.03f * state, 0.0f, 0.0f);

state = 0;

glDrawArrays(GL_TRIANGLES, 0, LOC);

glPopMatrix();

```

I pop the matrix at the end so that I can apply a different transformation to a different part of the array. The problem is, when `glPopMatrix()` is present at the end of this code, the object drawn keeps wiggling instead of moving like its supposed to.

Note: State is set somewhere out of the loop and does not cause the draw function to stop working (as the function works without glPopMatrix()).

# Answer
> 0 votes
I can't comment, and you did not supply enough information. From what I can see though, `state` never changes, since you set it to `0` in the display loop. Thus, the object will not move.

---
Tags: opengl-es
---


title: Do you need to call LibGDX's dispose?

text:
# Question
Title: Do you need to call LibGDX's dispose?
The LibGDX Actor does not have a dispose method, though it has a texture. Do I need to call dispose on its texture?

# Answer
> 2 votes
You call `dispose()` when you no longer need the resource. This is to free up the memory that the resource had been using. So yes, you need to call dispose when you're finished using your object.

---
Tags: java, libgdx
---