# Question
Title: Why do I get this EventException in Bukkit?
Could any one tell me why I get the exception (and how to fix it):

> Bukkit Plugin Couldn't pass Playerdeathevent to Plugin \[org.bukkit.event.EventException\]

with this code?

```
@EventHandler
public void ondeath(PlayerDeathEvent event) {
    int XP = event.getDroppedExp();
    event.setDeathMessage(ChatColor.YELLOW + event.getEntity().getPlayer().getDisplayName() + ChatColor.RED + " was killed by " + ChatColor.YELLOW + event.getEntity().getPlayer().getKiller().getName() + ChatColor.RED + " with a total of " + ChatColor.YELLOW + XP + ChatColor.RED + " XP!");
    event.setNewExp(0);
    event.setNewLevel(0);
    event.getEntity().setGameMode(GameMode.SPECTATOR);
    event.getEntity().getPlayer().kickPlayer(ChatColor.BOLD + "" + ChatColor.RED + "You Lost" + ChatColor.RESET + " (Reconnect to spectate, but don't help other Players!)");

    for (Player p : Bukkit.getOnlinePlayers()) {
        p.playSound(p.getLocation(), Sound.ENDERDRAGON_DEATH, 1, 0);
    }
}

```

EDIT: I know now what the cause was but I don't know what exactly is wrong.

The cause is the following line.

```
event.setDeathMessage(ChatColor.YELLOW + event.getEntity().getPlayer().getDisplayName() + ChatColor.RED + " was killed by " + ChatColor.YELLOW + event.getEntity().getKiller().getName() + ChatColor.RED + " using " + ChatColor.YELLOW + event.getEntity().getKiller().getPlayer().getItemInHand().getItemMeta().getDisplayName() + ChatColor.RED + " with a total of " + ChatColor.YELLOW + XP + ChatColor.RED + " XP!");

```

Here is my Error:

```
16:49:12 [ERROR] Could not pass event PlayerDeathEvent to UHC v0.1
16:49:12 org.bukkit.event.EventException
16:49:12 at org.bukkit.plugin.java.JavaPluginLoader$1.execute(JavaPluginLoader.java:310) ~[craftbukkit.jar:git-Spigot-db6de12-18fbb24]
16:49:12 at org.bukkit.plugin.RegisteredListener.callEvent(RegisteredListener.java:62) ~[craftbukkit.jar:git-Spigot-db6de12-18fbb24]
16:49:12 at org.bukkit.plugin.SimplePluginManager.fireEvent(SimplePluginManager.java:502) [craftbukkit.jar:git-Spigot-db6de12-18fbb24]
16:49:12 at org.bukkit.plugin.SimplePluginManager.callEvent(SimplePluginManager.java:487) [craftbukkit.jar:git-Spigot-db6de12-18fbb24]
16:49:12 at org.bukkit.craftbukkit.v1_8_R3.event.CraftEventFactory.callPlayerDeathEvent(CraftEventFactory.java:396) [craftbukkit.jar:git-Spigot-db6de12-18fbb24]
16:49:12 at net.minecraft.server.v1_8_R3.EntityPlayer.die(EntityPlayer.java:417) [craftbukkit.jar:git-Spigot-db6de12-18fbb24]
16:49:12 at net.minecraft.server.v1_8_R3.EntityLiving.damageEntity(EntityLiving.java:812) [craftbukkit.jar:git-Spigot-db6de12-18fbb24]
16:49:12 at net.minecraft.server.v1_8_R3.EntityHuman.damageEntity(EntityHuman.java:800) [craftbukkit.jar:git-Spigot-db6de12-18fbb24]
16:49:12 at net.minecraft.server.v1_8_R3.EntityPlayer.damageEntity(EntityPlayer.java:496) [craftbukkit.jar:git-Spigot-db6de12-18fbb24]
16:49:12 at net.minecraft.server.v1_8_R3.EntityLiving.e(EntityLiving.java:939) [craftbukkit.jar:git-Spigot-db6de12-18fbb24]
16:49:12 at net.minecraft.server.v1_8_R3.EntityHuman.e(EntityHuman.java:1440) [craftbukkit.jar:git-Spigot-db6de12-18fbb24]
16:49:12 at net.minecraft.server.v1_8_R3.Block.fallOn(Block.java:640) [craftbukkit.jar:git-Spigot-db6de12-18fbb24]
16:49:12 at net.minecraft.server.v1_8_R3.Entity.a(Entity.java:811) [craftbukkit.jar:git-Spigot-db6de12-18fbb24]
16:49:12 at net.minecraft.server.v1_8_R3.EntityLiving.a(EntityLiving.java:160) [craftbukkit.jar:git-Spigot-db6de12-18fbb24]
16:49:12 at net.minecraft.server.v1_8_R3.EntityPlayer.a(EntityPlayer.java:621) [craftbukkit.jar:git-Spigot-db6de12-18fbb24]
16:49:12 at net.minecraft.server.v1_8_R3.PlayerConnection.a(PlayerConnection.java:456) [craftbukkit.jar:git-Spigot-db6de12-18fbb24]
16:49:12 at net.minecraft.server.v1_8_R3.PacketPlayInFlying.a(SourceFile:126) [craftbukkit.jar:git-Spigot-db6de12-18fbb24]
16:49:12 at net.minecraft.server.v1_8_R3.PacketPlayInFlying$PacketPlayInPosition.a(SourceFile:57) [craftbukkit.jar:git-Spigot-db6de12-18fbb24]
16:49:12 at net.minecraft.server.v1_8_R3.PlayerConnectionUtils$1.run(SourceFile:13) [craftbukkit.jar:git-Spigot-db6de12-18fbb24]
16:49:12 at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [?:1.8.0_65]
16:49:12 at java.util.concurrent.FutureTask.run(FutureTask.java:266) [?:1.8.0_65]
16:49:12 at net.minecraft.server.v1_8_R3.SystemUtils.a(SourceFile:44) [craftbukkit.jar:git-Spigot-db6de12-18fbb24]
16:49:12 at net.minecraft.server.v1_8_R3.MinecraftServer.B(MinecraftServer.java:715) [craftbukkit.jar:git-Spigot-db6de12-18fbb24]
16:49:12 at net.minecraft.server.v1_8_R3.DedicatedServer.B(DedicatedServer.java:374) [craftbukkit.jar:git-Spigot-db6de12-18fbb24]
16:49:12 at net.minecraft.server.v1_8_R3.MinecraftServer.A(MinecraftServer.java:654) [craftbukkit.jar:git-Spigot-db6de12-18fbb24]
16:49:12 at net.minecraft.server.v1_8_R3.MinecraftServer.run(MinecraftServer.java:557) [craftbukkit.jar:git-Spigot-db6de12-18fbb24]
16:49:12 at java.lang.Thread.run(Thread.java:745) [?:1.8.0_65]
16:49:12 Caused by: java.lang.NullPointerException
16:49:12 at com.gmail.apply55gx.UHC.Listener.ondeath(Listener.java:40) ~[?:?]
16:49:12 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_65]
16:49:12 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_65]
16:49:12 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_65]
16:49:12 at java.lang.reflect.Method.invoke(Method.java:497) ~[?:1.8.0_65]
16:49:12 at org.bukkit.plugin.java.JavaPluginLoader$1.execute(JavaPluginLoader.java:306) ~[craftbukkit.jar:git-Spigot-db6de12-18fbb24]
16:49:12 ... 26 more

```

# Answer
> 0 votes
Without the exact error I can assume what the problem is.

Both `Player#getItemInHand()`, `ItemStack#getItemMeta()` and `ItemMeta#getDisplayName()` can return null and thus can throw a nullpointer exception.

You need to check if any of these is null before using them.

---
Tags: server, minecraft-modding, events, plugin, bukkit
---


title: tic tac toe computer opponent

text:
# Question
Title: tic tac toe computer opponent
I am just starting to do some very very very basic game dev(in java), i'm trying to create a game of tic tac toe but i am having some trouble implementing an a computer opponent.I just wanted to know if there is anyway to do this other than check every possibility with if statements.This is my best attempt at this but it is kinda broken. ie if points (1,1) and (2,2) are equal to x then it will think that (0,2) is the "best" move but in that situation there would be no "best" move.

some background info on the code, board is a global 3,3 int array. x is just that value that would be inserted when that location is selected. Coor is a class that contain just 2 ints x and y. availableMoves is an arrayList of all the empty areas on the board.

```
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            if (i <= 1 && j <= 1) {
                if (board[i][j] == x && board[i][(j + 1)] == x && availableMoves.contains(new Coor(i, ((j + 2) % 3)))) {
                    idealMove = new Coor(i, ((j + 2) % 3));
                } else if (board[i][j] == x && board[i + 1][j + 1] == x && availableMoves.contains(new Coor(((i + 2) % 3), ((j + 2) % 3)))) {
                    idealMove = new Coor(((i + 2) % 3), ((j + 2) % 3));
                } else if (board[i][j] == x && board[i + 1][(j)] == x && availableMoves.contains(new Coor(((i + 2) % 3), j))) {
                    idealMove = new Coor(((i + 2) % 3), j);
                }
            }
        }
    }

```

Thanks in advance for the guidance

# Answer
> 2 votes
The solution set is pretty small, so we could just brute force it, but that's no fun.

First we run a check to see if a victory condition will be met this turn for either the AI or its opponent (this should be quick; there are only 8 ways for either player to win).

If such a move exists, block/take it. Moves that cause the AI to win take priority.

Otherwise, if there is a move that contributes to your winning in the next turn, take it. Sort by number of win conditions it can meet. The side squares can meet 2 win conditions, corners meet three, and middle meets four.

Otherwise, if there is a move thate stops your opponent winning in the next turn, take it. Sort the same way.

Otherwise, simply use the Sort and randomly select from the appropriate squares.

This will give you a reasonably logical (but ultimately beatable) AI without being needlessly complex.

# Answer
> 2 votes
The Minimax algorithm would guarantee that the opponent would never lose, but you're probably looking for an opponent with flaws so it can be beaten sometimes.

A simple idea would be to keep a list of pairs of boards and a next move. You could iterate through the list, and if you find that all the marks on one of the boards corresponds to the actual game, you choose that next move. For example, here is a list of winning moves:

```
Board:     Next Move:

x - -      (2,2)
- x -
- - -

x x -      (2,0)
- - -
- - -

x - -      (0,2)
x - -
- - -

```

If you don't find any matches in the list, maybe just choose a random coord.

# Answer
> 2 votes
For games like tic-tac-toe (broadly speaking, 2 player board games), the usual method is to try all possible moves, and rank them. Obviously winning moves would rank best and losing moves worst. Between, it's up to you as programmer to recognize what features of a position constitute "better".

Once you have this, add Minmax.
Once you have minmax, add alpha-beta. Once you have that - you are well on your way, and there are whole universe of additional improvements and ways to go about it. You'll find lots of useful stuff on the web.

# Answer
> 1 votes
Tic-tac-toe is a great target to try to write an AI when learning a new language. These steps are proven to maximize your chances in the game. You always draw with perfect play of both opponents and win if opponent makes a mistake. You should check these conditions in the order they appear:
(1) If this is the very first move - take a corner (or the center).

(2) Is there your move that creates a winning position? If yes - play there.
(3) Is there an opponent's move that wins them the game? If yes - block it.
(4) Is there your fork? * If yes - play there.
(5) Is there an opponent's fork? If yes - block it. \[takes 7\*6=42 evaluations\]
(6) Play center.
(7) Play any corner. Pick randomly among free corners.
(8) Play any side. Moving towards inevitable draw.

---

* A fork is a move that creates a position with two or more ways to win the game on a second move for the player. This is the most computationally expensive step in the whole algorithm. Takes 8\*7=56 evaluations at worst if you don't use board's symmetry.

Homework - try to implement symmetry constrains to the board evaluation. Note, for example, that if your opponent's first move was in the center you can only choose from side and the corner. This is not important in tic-tac-toe because all options can be brute forced. However it can get important with more complex games.

---
Tags: java, algorithm
---


title: Confused about using libGDX dispose()

text:
# Question
Title: Confused about using libGDX dispose()
Can anyone please help me to understand the proper use of the dispose().
Does dispose() get called automatically or do I have to make a call to it?

In a game I'm writing, I use a texture atlas and an asset manager for all of the textures I use. I have an abstract class called Enemy and every type of enemy extends it. I have an arraylist that holds all of my enemies, and when an enemy is dead, I remove it from the arraylist. Do I need to make a call to the dispose() method in the individual enemy classes to remove the textures from memory before removing it from the arraylist or does it happen automatically or is that not how dispose() gets used period? (Each individual type of enemy class sets its own textures by using a TextureRegion)

# Answer
> 5 votes
`Dispose()` is not called automatically. You have to call it manually whenever you with to dispose a texture (or anything that implements disposable). The only `dispose()` that's called automatically is `ApplicationListener.dispose()` and `Game.dispose()`, since it implements `ApplicationListener`.

**As for solving the memory leak** I'd suggest only using `AssetManager` for **ALL** (textures, sound, atlases, skins etc.) of your assets. This way you ***only*** have to call `AssetManager.dispose()` on your `AssetManager` when you exit your program, and in turn this will dispose of all of your assets automatically.

I can also vouch for not removing objects once they die. Instead, re-use them if you need more enemies. Only remove them once you absolutely have to. Although this might be a bit overkill if your game is not very big, or you're not using a lot of enemies.

Hopefully this answered your question!

# Answer
> 1 votes
libGDX's `Game.dispose()` method gets called automatically when you quit the game. The `Screen.dispose()` method should be called manually when you want to exit a screen. When you want to dispose of your textures, you could call the dispose method in your Enemy class from the `Screen` or `Game` dispose methods. You should never explicitly call the `Game` dispose method yourself. However, if you meant the `Texture.dispose()` or `TextureAtlas.dispose()` methods then yes, you need to call these once for every texture or texture atlas, respectively, that you want to dispose of.

# Answer
> 1 votes
You don't need to to dispose those enemies,Instead use an zOrdering and hide the enemies from the screen and put a condition to prevent the enemies from rendering onto the screen ,If you want to reuse those dead enemies just set enemy.setZorder(1 or some greater value) :

```
ArrayList<Enemy>EnemyList;

EnemyList.add(enemy);

if(enemy.life<=0)
{
            enemy.setZorder(0);

}

```
* setZorder method should be custom written since libgdx does not support setZorder unlike most other engines
* setZorder method is also capable of preventing the enemy sprites in the array list to be rendered on the screen

If you need setZorder code sample I can post some sample codes here.

# Answer
> 0 votes
In Libgdx some objects need to be disposed, as they are not managed by the garbage collector. The `dispose()` methode is supposed to dispose all of this objects, to release their ressources. The objects, which need to be disposed are mentioned here.
The `dispose`-method of the `Game`/`ApplicationListener` is called by LibGDX automatically, while the `Screens` `dispose()` is not called automatically (This is mentioned in the Screen API).
The `Screen`s should generally be disposed, when the user probably won't return to it for a longer time. This might be the case for a `Splash-Screen` which shows only when the game is started.
Also, every not disposed `Screen` should be `disposed` when the `ApplicationListener`/`Game` gets `disposed`.

---
Tags: libgdx
---


# Question
Title: Unity - How to match camera bounds to width
While stretching camera bounds, changing width adds black offset while changing height stretches image.

How can I achieve opposite behavior and match the bounds to the width instead of height ?

# Answer
Try changing the camera's orthographic size based on aspect ratio. The larger the orthographic size the farther out it will have "zoomed". For instance, if your camera's orthographic size is 10 normally, when you switch to 16:9 aspect ratio set the orthographic size to a smaller value.

Or for perspective camera you can try this
> 1 votes

---
Tags: unity, camera
---


# Question
Title: Libgdx How to overlay two images on Table
I'm trying to set the player image inside the circle of the bars. I've tried to use stack, to position it topLeft but it does not work.

```
    Stack stack = new Stack();

    healthbar = new Image(new Texture(Gdx.files.internal("data/ui/healthbar.png")));
    playerLook = new Image(player.getFrame());
    stack.add(healthbar);
    stack.add(playerLook);

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

    table.add(healthbar).expandX().pad(10).left();
    table.add(playerLook).expandX().pad(10).left();

    stack.add(table);
    stage.addActor(stack);

```

# Answer
First of all, we remove these two lines, because we **don't** want to add them separately:

```
table.add(healthbar).expandX().pad(10).left();
table.add(playerLook).expandX().pad(10).left();

```

Then we change this:

```
stack.add(table);
stage.addActor(stack);

```

to this:

```
table.add(stack);
stage.addActor(table);

```

Because we don't wish to add the table to the stack, we wish to add the stack to the table, and then we add the table to the stage. The result is this:

```
Stack stack = new Stack();

healthbar = new Image(new Texture(Gdx.files.internal("data/ui/healthbar.png")));
playerLook = new Image(player.getFrame());
stack.add(healthbar);
stack.add(playerLook);

Table table = new Table();
table.top();
table.setFillParent(true);
table.add(stack);

stage.addActor(table);

```

If you have any questions just leave a comment and I'll try to answer them :)
> 0 votes

---
Tags: libgdx, ui-design
---


# Question
Title: How to store level data in a libgdx game if implementing ECS pattern
I am writing a beat'em up like game in **Libgdx** while following the **ECS** pattern brought up by **ashley**. For setting up the stage, I am using TileMap and Tiled. An object layer for collisions, and a tile layer for the tiles. Usually, an entity -in this case, an enemy- has a lot of components so harcoding one class for each stage on start up is out of the box. I have already considered this options:

1. SQLite database. Seems rather complex for the task, somehow.
2. Json files. I'd have to overwrite and create my own serialization class
3. Using another object layer for spawning enemies by using the "Custom attributes" option in order to store extra data.

Have anyone come up with a similar problem or experience already? What would be the best approach?

# Answer
I'm not 100% sure if I understood your question, so *hopefully* this answer answers some of your questions haha :)

## My current approach

I've encountered this problem multiple times, and the method which I'm using right now is creating my own interpreter. Basically I have a file that looks something like this:

```
[catapult]
setName:catapult,
setType:siege,
addComponent:health,
addComponent:attack,
...

```

This file contains information that is split into two parts: `action:value` and separated by a comma. I then use my own interpreter called `ObjectLoader` that reads this file and creates objects. Pseudo code might be something like this:

```
MyObject myObj = new MyObject();

// Here I read the file and add all action:value pairs to a list.

for(Pair pair : pairs) {
    if(pair.getAction().equals("setName")) {
        myObj.setName(pair.getValue());
    } else if(pair.getAction().equals("addComponent") {
        if(pair.getValue().equals("health") {
            myObj.getEntity().addComponent(new HealthComponent());
        }
    } else if(...) {
        ...
    }
}

```

This can also be applied to creating a stage, perhaps by doing something like this:

```
[SomeEnemy]
addComponent:health,
...

[SomeStage]
addEnemy:([SomeEnemy], 4), //Create 4 of "SomeEnemy"
...

```

This is of course not very clean code, and can quickly get very long if you have a lot of different components, for example. With this in mind I've started developing a better method using annotations and reflection, but that's not finished yet.

## My previous approach

Previously I used one of the methods you named yourself; JSON. LibGDX already has JSON functionality built into it, using their Json classes (official tutorial). This works very well, and you can customize your serialization using their `Json.Serializable` and `Json.Serializer<T>` classes. I would suggest this method if you absolutely don't need the functionality of the other method I mentioned. It is also a lot easier to use.

## Honorable mention

If you want an alternative to JSON you could look into XML. LibGDX also has built in functionality for this, just like JSON (official tutorial).
> 1 votes

---
Tags: libgdx, game-design, serialization, shoot-em-up, json
---


title: Does the age of test users matter?

text:
# Question
Title: Does the age of test users matter?
Does the age of test users matter? Should I get users that are around my intended age level, knowing that some games are played by younger or older people than were originally intended? Should I have my test users be all around the same age for consistency, or a variety of ages to gather more useful data?

# Answer
> 1 votes
Testers don't grow on trees :-). Few game coders have the luxuary of accepting or rejecting testers. Additionally, it is not at all easy to keep them for a longer period of time than maybe a few months, at most. Those who are really dedicated, of some specific reason probably, may become lifetime helpers and even friends, but most of the testers will simply disappear over time.

If you have a really good, fancy, challenging game, or a series of games, you may get such amounts of interested people that you can make choices.

Otherwise take'em all. You get all kinds of input, and it is good that way. You are yourself the one who give emphasis on different input, depending on the quality of it. You will learn to read between the lines and recognize the nicknames, the kids, the old dogs, the musicians, the technocrats. And remember to make it public. Nobody wants to chat with you alone... or very few want to.

Do not invoke testers too early - nobody gets happy of crashing and incomplete software. It must be interesting, challenging and you must create the hype factor, and even harder, keep it. Let them shine!

So take it all with whatever means you have handy, and filter the input you get.

(If you aim to pay, for eg. Lithuanian testers, it is a totally different thing. They are good and they cost money)

5 cents :-)

# Answer
> 1 votes
It depends on what you want to test.

When you want to test user acceptance and behaviour, you should of course test within your desired demographic. People from a different demographic might give you different results and mislead you about the strengths and weaknesses of your product.

But when you want to test for bugs, you need professional testers who thoroughly test all the edge-cases of your game, systematically looks for bugs, find out how to reproduce bugs they find and then write useful bug reports which contain all the information you need to fix them. This is not how a normal player plays and experiences your game. Feedback about the gameplay itself is of course welcome, but it's not what you expect from these testers. Their feedback is also not very useful, because they are *testing* the game and not *playing* it. That's a completely different perspective. So it does not matter which demographic these testers fall under.

# Answer
> 0 votes
I think if you have a target demographic in mind, you should focus on that demographic for your playtesting (that would apply to age, gender, country of origin, income, and any other demographics).

If you're looking to feel out exactly who will enjoy your game, then getting your game into the hands of as many users from all demographics as possible would be a good idea.

# Answer
> 0 votes
Usually, for a game testing, you should look for experienced players, with a good eye to spot errors or bugs in your game. People with lots of experience playing videogames will spot these things better than people who don't know much about games. Plus, if the testers happen to know something about videogames developing or game logic, can help you out pointing out technical issues and hints on where to fix bugs.

But, if what you're aiming at making a demography study (finding out which crowd you'll aim your marketing at, or what population likes your game the most, etc) then it is recommended that you get as diverse people as you can, because this will give you nice data to work on.

# Answer
> -2 votes
I think you should gather test users which are all different ages. Most of Studies are made this way and (as you already said) you gather more useful data.

# Answer
> -2 votes
Depending on jurisdiction & age, you may be subject to certain laws regarding minors, I.E. the Children's Online Privacy Protection Act in the USA might cover online / remote testing by children under 13 years of age. If you plan on testing with minors, consult a lawyer.

---
Tags: playtesting
---


# Question
Title: Looking for a complete information game slightly more complex than Tic-tac-toe
I am testing various rating systems (Elo rating and some alternatives). I need a"world" with computer players participating in championships. Computer players are characterized by two parameters:
(1.1) Depth of search (probability to search yet another ply deeper)
(1.2) Probability to remember the outcome in their previous games. (Relatively high)
(1.3) Probability to learn from "published games". (Relatively low)

I tried tic-tac-toe, but there are two problems:
(2.1) Players learn too fast. (Decreasing learning rate turns it in a toss-a-coin)
(2.2) Ply count is granular. The difference between "can/cannot see a fork" or "can/cannot see opponent's fork/one move win is huge.

A battleship game doesn't have complete information. A game like chess or five in a raw would require prohibitively large amount of memory to remember all possible combinations.

# Answer
Checkers?

I don't know where you're drawing the line for a 'prohibitively large' data set, but a quick and naive consideration (read: definitely not even optimal) can store a board state in a maximum of 264 bits, and most will be far shorter. (Don't store info for captured/removed tokens.)

Your tree will be pretty big but storage requirements are pretty lightweight.

There's also various toothpick games like the one described at https://answers.yahoo.com/question/index?qid=20070410190739AAa18a3 . Such games are generally more complex than tic tac toe, but still very manageable.
> 2 votes

---
Tags: ai
---


# Question
Title: Drawing from an ArrayList drawing same image repeatedly (Slick2D)
This is the game I'm working on.

I isolated the problem into this class.

```
public class Runa extends BasicGame {
int startTime, tracker;
public ArrayList<Circle> circ = new ArrayList<Circle>();
public int[] a = new int[]{
        15, 16, 17, 18, 19, 32, 36, 40, 45, 46, 55, 56, 57, 58, 63, 65, 68, 70, 72, 74, 79, 80, 81, 82, 86, 94, 95, 96, 97, 98, 99,
        100, 101, 102, 103, 104, 105, 117, 120, 122, 126, 128, 129, 130, 131, 133, 138, 139, 140, 142, 149, 151, 155, 156,
        158, 164, 166, 172, 174, 180, 182, 184, 188, 189};
public ArrayList<Integer> aList = new ArrayList<Integer>();
public Runa(String title) {
    super(title);
}

@Override
public void init(GameContainer c) throws SlickException {
    startTime = 0;
    tracker = 0;
    //this just transfers the hard coded values into an arraylist
    for(int i = 0; i<a.length;i++){
        aList.add(a[i]);
    }
}
@Override
public void update(GameContainer c, int d) throws SlickException {
    //this calculates the rhythm of the game
    startTime+=d;
    if(startTime>((60/(calcBPM(195.8,89)))*1000)){
        startTime=0;
        tracker++;
    }

    //this adds a new circle every time the current beat (tracker) reaches a beat on the aList
    if(aList.indexOf(tracker)>0)
        circ.add(new Circle(50,50,50));
    //this should just move one circle at a time, meaning I thought that only one circle would be added above, and move it down 4 px
    for(Circle circle: circ)
        circle.setCenterY(circle.getCenterY()+4);
}

@Override
public void render(GameContainer c, Graphics g) throws SlickException {
    //draws each circle in the arraylist
    g.setColor(Color.red);
    for(Circle circle: circ)
        g.draw(circle);
}
//calculates the bpm
public double calcBPM(double d, int numSecs){
    return d*60/numSecs;
}
public static void main(String[]args) throws SlickException{
    new AppGameContainer(new Runa("Test"),680, 480, false).start();
}

```

}

Why is it doing that weird stretch thing? Is that because I'm using an arraylist?

# Answer
> 1 votes
The stretching is occurring because each circle that you add is getting moved down four pixels every time. For example:

Take this array:

`{ }`

> It will hold the Y coordinate of every circle.
>
> Your beat tracker reaches a beat on he lost and adds a circle. Let's put that circle at 50 y. The array now looks like this:

`{50}`

> After adding the circle, your code moves every circle in the array up four pixels, leaving our array looking like this:

`{54}`

> Now when you call your draw function, you have a circle at y = 54.

Next update cycle:

> Your beat tracker finds another beat and adds a circle to the list, again at 50 y. The array now looks like this:

`{54, 50}`

> Again your code moves every circle up 4 pixels, making your array look like this:

`{58, 54}`

> Now when you call your draw function, you get a circle at y = 54, and another at y = 58.

This is the stacking pattern you see.

Do you understand why that stacking pattern happens now?

# Answer
> 0 votes
Though I've got no experience in programming with slick, I've experienced a very similar problem when drawing in the paint method of a panel

The solution was to call the super.paintComponent(g); method in each draw cycle

So it should look like this

`public void paint(Graphics g){
 super.paintComponent(g);
 // draw stuff here
}`

I hope that helped at least a bit

---
Tags: java, slick
---


# Question
Title: Publishing an XNA project on Windows Store
I have made an application in XNA that I want to sell on Windows Store. When it comes to uploading in the Windows Store dashboard it says files need to be in the format xap, .appx, .appxbundle or .appxupload but I can't figure out how to create these files. The best information I could find is https://msdn.microsoft.com/en-us/library/hh454036.aspx but I don't have "Store" in my Project menu. I am using Visual Studio 2015 and XNA 4.0.5

# Answer
> 3 votes
XNA games aren't directly support in the Windows Store. The "appx" file types are generated when building a Windows Store app (it's one of the project options when you are creating a new project). As "rlam12" mentioned in his comment, there is a Win32 wrapper being worked on that can take a regular .exe and convert it into a Windows Store app. However, this won't be out for some time.

If you want to avoid re-writing your game from scratch into C++/DirectX, you could look into using MonoGame and then build a Windows Store MonoGame project. MonoGame is basically the open source version of XNA from when it stopped development back several years ago. I haven't used MonoGame is a long time, but it should hopefully not be a difficult transition. Here's a link to a short tutorial on how to get started with MonoGame and Windows 10 Store App development:

http://www.codeproject.com/Tips/1015929/XNA-Basics-Windows-and-MonoGame

---
Tags: xna, monogame, windows
---


# Question
Title: How can I implement explosion effects in a 3D game?
I was wondering how I could implement explosion effects in a 3D game. I'm specifically interested in graphical techniques for creating the effects, not the related logic or systems.

# Answer
Many particles which is actually sprites (So, yes. It is sprites). You might want to see this. It has images that might make you understand how it works.

Though i recall there's also volumetric effects for clouds/mist like in Sonic Ether's mod (The clouds is volumetric and the light too). And also, there's this volumetric explosion in unity, but i don't think that's a true volumetric because i feel like it is using trick to achieve the illusion of volume.
> 3 votes

---
Tags: graphic-effects
---


title: Tiled height level collision

text:
# Question
Title: Tiled height level collision
I have created the below tilemap in tiled and I am wondering about a good approach to "separate" these two different heights in the map. I would like to keep it tile based, so adding a object layer for collision detection is a no for me.

I would like the player to move from the low ground to high ground using the ladder. But as you can see, two walkable tiled adjacent to each other should not be "connected" since they are on different heights.

Since I can only add properties to the tile in the sheet and not on the map itself afaik, I cannot mark the heights on my map. So I guess I have to work with different layers for each height. Check if the layer the player currently on has a tile or something, if that is even possible.

The reason I do not want to use a object layer is simple. My creatures move from tile to tile and I just want to check if that tile is walkable and on the same height level. No need to test vs a rectangle or polygonal object.

What I am actually looking for is having properties per coordinate. This would make it a lot easier (pseudo code):

```
tileMap[x][y].floorCount;
tileMap[x][y].walkable;

```

instead of:

```
map.getLayer(player.currentLayer).layerMap[x][y].tileExists;
map.getLayer(player.currentLayer).layerMap[x][y].walkable;

```

I simply cannot add properties to a "global" tile (tiled seems to only allow me to add properties to the tile on the sheet which is carried over to every usage of it. This image uses that same corner tile as in the above image, only this time the player is allowed to cross it, or perhaps hop over it.

# Answer
In Tiled you can add layers. Use a layer for the ground level, elevation1, elevation2 etc.

Define a ladder/stairs tile with a property (in the tileset tile property) to indicate the player can move up or down one layer.
> 3 votes

# Answer
Instead of defining a tile-type as "blocked" or "walkable" in general, define the four edges of a tile as "blocked" or "walkable" separately (a completely impassable tile would have all edges as "blocked"). That way you can define a tile-type like that upper cliff corner which can be entered and left through the west-edge and north-edge but not through the east-edge and south-edge.

This system also allows you to create "thin" obstacles like fences which don't block a whole tile but only the edge between two tiles.
> 3 votes

# Answer
Looking at your responses to the two answer here so far, I don't think you're going to find a solution that works the way you want it to without it being some level of hacky because you're not using objects. The actual picture tiles do not have any properties support in Tiled. The only thing that has support for properties are the layers and objects.

The only solution I can think of that might work is to keep track of specific tile IDs (the picture tiles, not their location) and use that to help you determine things. For example, if your player steps on the "right-cliff edge tile", they can not move right anymore. If the player steps on to a "ladder tile", then they are allowed to move onto a cliff-edge tile.

I honestly wouldn't suggest this though as its VERY hacky. I think honestly using layers or objects is going to be a much better solution for you in the longer run and will allow you a lot more flexibility down the road, even if it doesn't seem as "nice to write in code" right now. That's what helper functions are for. :)
> 0 votes

---
Tags: collision-detection, tilemap, tiled
---


title: Additional dependencies in XNA/Monogame

text:
# Question
Title: Additional dependencies in XNA/Monogame
I made a game in monogame recently, using the XNA content pipleline. I then sent the whole folder (The release folder in visual studio) to a friend of mine who does not have visual studio or monogame. He said he can't open the game. What the are files I need to give my friend for him to be able to play it?

He has Windows 8

# Answer
Your friend either need to install all the same develop tools you have (Visual Studio and XNA/Monogame) or you can create an install package. Right click the project and pick publish.

Then you gill get a wizard. I put mine in E:\Temp

Next step is simplest if you select CD-ROM or DVD-ROM. You can just as well install from a folder on the hard drive. In my case the files were put in E:\Temp

Next step it to put all files in that folder in a zip file and send it to your friend for installation.
> 2 votes

---
Tags: xna, monogame, windows-8
---


# Question
Title: How to align a hint arrow to point along a path?
I am using CalculatePath and trying to use `path.corners` in order to give user a hint for path, that where should he lead next. I am using first two instances of `Vector3` of `path.corners`. Lets call those vectors A and B. Let me illustrate this using figure.

Now I want to position my arrow above the midpoint of the line from B to A, and orient it so it's pointing along the direction from B to A.

When I orient the arrow with LookAt(), it doesn't point in the same direction as the path. Here is an image of my arrow prefab, showing how it's oriented:

# Answer
It looks like your trouble isn't in computing the direction - it's that your arrow asset was imported with an unusual orientation, so when you use methods like LookAt or LookRotation they give you the "right" result for a standard orientation, leaving your arrow visually pointing somewhere else.

You tried to correct for this by adding angular offsets to the rotation, but the transform.rotation property is not measured in angles - it's a Quaternion, and so we need to use Quaternion methods if we want to modify it.

Usually the cleanest fix here is to re-export your asset in the orientation you really want, or parent it to an empty game object and then rotate the child to align properly with the parent - using the new parent as the root of your prefab.

I'll show you how we can correct the orientation in code though:

```
void TransformArrow(Vector3 start, Vector3 end, float height)
{
    // This is similar to what you already have.
    Vector3 arrowPosition = (start + end)/2f;
    arrowPosition.y = height;
    arrow.transform.position = arrowPosition;

    Vector3 direction = (end - start);

    // If you want to prevent the arrow from tilting up or down on slopes,
    // uncomment this line.
    // direction.y = 0f;

    Quaternion arrowOrientation = Quaternion.LookRotation(direction);

    // Your prefab arrow points along -x ("left"), with +z ("forward") pointing up.
    // We want to rotate this to Unity's standard: +z forward, y+ up.
    // We'll construct the orientation facing "left" with "forward" up, then invert it.

    Quaternion correction = Quaternion.Inverse(
                               Quaternion.LookRotation(Vector3.left, Vector3.forward)
                            );

    // Now we apply our orientation and the correction for the prefab's orientation.
    arrow.transform.rotation = arrowOrientation * correction;
}

```
> 3 votes

---
Tags: unity, vector, direction
---


# Question
Title: Does Phaser Arcade.Body velocity include deltaTime or not?
I want to move my character along the x axis with constantly speed. I thought move depends on frame rate. So, technically I should write

```
sprite.body.velocity.x = speed * deltaTime

```

where `deltaTime = game.time.elapsedMS / 1000;`

But if I'm doing that - my character moves vvvvverrry slooow, even if `speed = 1000`.

But if I'm writing

```
sprite.body.velocity.x = speed

```

it works fine. My fps = 60;

---

Phaser Documentation says:

> **velocity** \- The velocity, or rate of change in speed of the Body. Measured in pixels per second.

no deltatime....

and all demos do not have deltatime

http://phaser.io/examples/v2/arcade-physics/platformer-basics

http://phaser.io/examples/v2/arcade-physics/asteroids-movement

etc.

So, I don't understand: shoud I calculate deltaTime or just use `velocity.x`?

# Answer
> 2 votes
Well.... I think I'm stupid...

My calculation of the `deltaTime` was wrong

The correct formula will be

```
deltaTime = (elapsedMS * fps) / 1000

```

elapsedMS \- The time in ms since the last time update, in milliseconds, based on time.

fps \- Frames per second. (Only calculated if advancedTiming is enabled).

So, that was my problem.

---

As the result

body.velocity doesn't include calculation of deltaTime and for smooth movement should use deltaTime that calculated by the formula above.

And it will be something like that

```
function update() { // <-- it is phaser state method...is called every frame
    deltaTime = (elapsedMS * fps) / 1000;
    sprite.body.velocity.x = velocityX * deltaTime;
    sprite.body.velocity.y = velocityY * deltaTime;
}

```

---
Tags: phaser
---


# Question
Title: How can I create "events" that are called in scripts without requiring subscriptions?
I am creating an editor extension that includes an API for developers to use. It also includes events like (for example) "OnHealthChanged."

The problem is that events I have stumbled upon would require a user to subscribe to them, which is not what I actually want. I want developers simply type in the event handler in their script, and it would just work.

For example, I want a programmer to write a function "OnHealthChanged" in their own script. When the health changes, their code runs.

```
void OnHealthChanged()
{
    //code that is going to run when health changes
}

```

Any idea where can I look?

I want to create something like "OnCollisionEnter()" event in Unity, which runs code every time a game object collides with another game object.

Hope it makes sense.

# Answer
If you require `OnHealthChanged` to be part of some interface of the game objects in question, you can attempt to cast any arbitrary game object to that interface and then call the method:

```
// ...given...
interface ISupportHealthChangedNotification {
  void OnHealthChanged();
}

var supportsHealthChanged = someGameObject as ISupportHealthChangedNotification;
if (supportsHealthChanged != null) {
  supportsHealthChanged.OnHealthChanged();
}

```

You could also use reflection to do this.

Reflection allows you to look at, among other things, all of the methods on a given type. Using this, you can find the `OnHealthChanged` method on any game object whose health you changed and invoke it:

```
// ...somewhere after you've changed the health...

var onHealthChangedMethod = GetType().GetMethod("OnHealthChanged");
if (onHealthChangedMethod != null) {
  onHealthChangedMethod.Invoke(this, null);
}

```

Note that doing this lookup constantly, every frame, is not necessarily the most super-efficient thing in the world so you may want to cache the `MethodInfo` once you find it.

Note that both of these methods require you to know about the game objects whose health is being changed, and either be in control of the health actually changing or for your code itself to be hooked up to some existing event that tells you the health changed (which you then forward via the above method). You cannot feasibly do this if you don't have hooks into the code that should stimulate the events you are interested in.
> 1 votes

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


title: Bukkit - Loading chunks in a new world

text:
# Question
Title: Bukkit - Loading chunks in a new world
I'm looking to make a large-scale PVP plugin. On a server network (MCBrawl), there is a game mode that spawns players in a world that I assume is randomly generated every time. I want to make something similar. My go-to way so far was to find a random (x|z) coordinate on the map the players are already on, and then create their spawn points based on that. It works in theory, but it's really laggy, the chunks are generated at the moment people spawn there and when playtesting this often made the server time out. In the game mode I was talking about earlier, people actually get this loading screen (background of dirt blocks) for a second or so, and then end up in a world. You're also able to run around in it before the game starts, so the world and the chunks were already generated before..

So, TLDR: I'm looking to create a new world, have players spawn in them when the game starts, and later remove the world again. That way, I want the users to be able to start the game, and when it's over, remove the world again. Is that somehow feasible without putting too much strain on the server? I'm looking to pre-generate the world or find a similar solution.

# Answer
I've seen multiply ways this was done in the past. Most of them failed and none of them were good enough to jump across this obstacle completely. Everyone of them has some flaw in it. I post the 3 most sucessfull ones:

## Start a separate server using java and make it generate the worlds for you.

With java you **can** start another server in the same folder, and you can generate the worlds with it if you have the right plugins for it. However, this is not very server friendly, as some servers don't allow you to run multiply game servers at once.

## Use downtimes to generate worlds

If your plugin runs on a small server, then in the mean time, when there's no one on that server you can use the time to generate some worlds, then use them when there's actually someone playing the games. You don't need to create only 1, you can stack them up and create 20-30 or even 50 worlds at once. The obvious flaw to this one is that it's not 100% there will be a playerless timespan on that server.

And now the best one:

## Generate one world and copy it.

You can either ask the server owner to create a world or generate it yourself, then save a copy of this world to a separate folder, and when you need it, copy it back to the main folder to use it.
> 0 votes

---
Tags: java, bukkit
---


# Question
Title: Pong paddle algoritm - How to know the direction of the ball when the paddle is at bottom
I hope you can understand my question! I'll try to be very clear.

Watching a pong tutorial (it was originally written in Javascript but I made the game in Python) The developer used an algorithm to determine, depending on which part of the paddle the ball hit, the ball velocity changed.

As you can see, if the ball hits more towards the bottom or top of the paddle, the angle in which it bounces gets larger, and if it hits closer to the middle, the angle becomes narrower.

Here is the algorithm and it works (Check code comments):

```
player_interesected_ball = detect_collision(ball, player) #It's a function that just detects if two rectangles collided
if player_interesected_ball :
    offset = (ball.y + ball.s - player.y) / \
             (player.height + ball.s) # ball.s is the ball size like 10px it means that is 10px wide and 10px high
    phi = 0.25 * math.pi * (2 * offset - 1)

    ball.vel_x *= -1
    ball.vel_y = ball.speed * math.sin(phi)

```

This code works when the paddle is placed on the Right or Left side of the screen but I want to know what should I change in these values to make it work when the paddle is placed on the bottom of the screen.

Like this:  :) Thank you before hand!

# Answer
> 1 votes
You're essentially swapping the axes x and y, going from horizontal play to vertical play. Along those lines, try swapping the axes in your bounce code. All the x variables become y and all the y variables become x (i.e. ball.y -\> ball.x). Width and height swap as well.

Specifically, that method would look like this:

```
player_interesected_ball = detect_collision(ball, player) #It's a function that just detects if two rectangles collided
if player_interesected_ball :
    offset = (ball.x + ball.s - player.x) / \
             (player.width + ball.s) # ball.s is the ball size like 10px it means that is 10px wide and 10px high
    phi = 0.25 * math.pi * (2 * offset - 1)

    ball.vel_x = ball.speed * math.sin(phi)
    ball.vel_y *= -1

```

# Answer
> 0 votes
You can easily do this with trigonometry.

The ball bounces off from the paddle in 90 degrees if it hits the exact center of the paddle and in 45 degrees, if it hits the edges of it.

This means, that the ball can bounce from the paddle between -45 and 45 degrees, in radians, this is -PI/8 -\> PI / 8.

Now you need to map each point of the paddle between these 2 values. If you know the distance of the bounce point from the top of the paddle and the height of the paddle, then this can be done with

```
angle = PI / 4 * (distanceFromTop / paddleHeight) - PI / 8

```

This is the direction of the ball, using cosine and sine you can get the velocity vector of the ball.

```
v.x = cos(angle) * speed
v.y = sin(angle) * speed

```

where v is the velocity vector of the ball.

---
Tags: physics
---


# Question
Title: How can I search for players in the same wifi in Unity?
I am creating a game in Unity and I would like to create an ability for players to join the game that others have created on the same wifi. I would like it to be as effortless as possible(e.g. players don't have to find out their wifi, etc). The game is cross-platform - you could have one player on PC, other on Android device, etc.

Now I know that there is a game that has similar mechanism to what I would like to achieve: SpaceTeam. Basically you select whether you use BT or wifi, and wait for other players to join.

How can I do this in Unity, or something similar that satisfies my needs?

# Answer
> 2 votes
A UDP datagram sent to the broadcast address is delivered to all nodes on the LAN.

I don't normally do networking in C# but it should go something like this: First, listen for packets with any destination address.

```
new IPEndPoint(IPAddress.Any, ...)

```

Now, send packets to the broadcast address:

```
new IPEndPoint(IPAddress.Broadcast, ...)

```

These packets will be received by every machine behind the same router, via WiFi or Ethernet.

---
Tags: unity, networking
---


title: SDL for 3D game programming?

text:
# Question
Title: SDL for 3D game programming?
I have been studying SDL for a few weeks and I have succeeded in making a 2D Ping-Pong game, but I want to get started in 3D development, and I'd like to know if SDL is capable (and suitable) for 3D game development, or I must use OpenGL?

# Answer
SDL isn't a 3D graphics engine. As is stated in its homepage:

> Simple DirectMedia Layer is a cross-platform multimedia library designed to provide low level access to audio, keyboard, mouse, joystick, 3D hardware via OpenGL, and 2D video framebuffer.

That "3D hardware via OpenGL" basically means that SDL contains some helper functions to ease cross-platform usage of OpenGL, but you'd still need to learn and code raw OpenGL (which isn't a bad choice if you want to better understand 3D graphics). If you'd like a higher level approach, you should look at some complete 3D engines, such as Ogre or Irrlicht. They use OpenGL underneath (or Direct3D on Windows), but provide easier API with lots of stuff like model loading and scene graph.
> 9 votes

# Answer
SDL by itself is not meant for 3D (you can make your own software renderer but you wouldn't get very far with it) however SDL does come with an OpenGL wrapper/addon so you can use SDL's windowing, audio, and input system while using OpenGL. Refer to the link in the other post (SDL + OpenGL) for more info and use nehe.gamedev.net for OpenGL tutorials.
> 6 votes

# Answer
If you can draw triangles, then you can technically create a 3d engine with it.

However, this involves the same amount of math as you need to do OpenGL if not more.

First, you need to define positions in 3 dimensional space. This is done by using 3d vectors. To render a triangle, you need 3 vectors, one for each vertex of the triangle.

Now, to project a point from 3d to 2d, you just need to divide the x and y positions of the point with the z position. If you done this, then you have a 3d triangle. Congrats.

However, if you render multiple triangles, you notice triangles at the back can overlap the triangles in the front. To solve this you need to sort each triangles based on the distance of it from the camera.

To rotate a model, you need to multiply each vertex of it with a rotation matrix.
> 2 votes

---
Tags: opengl, 3d, sdl, cross-platform
---


title: Unity, Solid Color to link Platforms

text:
# Question
Title: Unity, Solid Color to link Platforms
\[UNITY\] As you can see above a solid color is connecting one platform to another. My question is whether this color must be applied **through code or through a sprite**. In my game there are three lanes and for each platform you land on, it must connect the color to the platform...and so to put that into sprites seems to be a bit numerous...*in my opinion* with varying vertical and horizontal distances between the platforms it will much too difficult to make each individual sprite (as they also are of varying colors).

Hopefully, the above explains my dilemma well enough. Would anyone be so kind as to guide me through this?

# Answer
There are lots of ways you could solve this. Here are two...

1. Have one sprite that's a triangle, and another that's a solid rectangular fill. You can then form roads between platforms using a combination of these two sprite shapes. Here I've tinted them in different colours to show the construction:

2. You can write a script that uses the Mesh class to construct a new mesh whose triangles exactly fit the gaps between your platforms. Each bridge would need four corner vertices, and six indices joining them in the order (bottom left, top left, bottom right, bottom right, top left, top right)
> 1 votes

---
Tags: unity, color, platform
---


# Question
Title: Unity's Animator.GetBehaviour<T> always returning null
I have the following line:

As you can see "transitionOutAnimator" is null before the line runs. transitionOutAnimator is a StateMachineBehaviour of type ThoughtBubbleTransitionOutAnimator.

We can check that the StateMachineBehaviour of the correct type is actually stored in the run time animator:

Yet when the line runs:

Am I doing something obviously wrong? Is this a bug? I have another identical instance in the code where I do this, and it works perfectly.

EDIT: Immediate window:

EDIT: This is still a problem as of Unity 5.3.5f1.

# Answer
I figured out what was causing this issue. The game object that held the animator component was disabled initially. Having the game object enabled initially fixed the issue, and the behaviour reference was able to be accessed through GetBehaviour.

Why Unity does this is unclear to me. If this is intended, then hopefully they reflect it in their documentation in the future, at the least.
> 1 votes

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


# Question
Title: Draw the middle half of a sphere programmatically
I'm trying to create the middle half of a sphere. Basically to create a sphere, stack numbers and slice numbers are given, and there are two variables `phi` (for slices) and `theta` (for stacks) responsible for how much to progress. And the process is divided into creating bottom cap, body, and top cap (as seen below). To achieve middle half (`theta` of middle 50% as below), we need to omit the caps, and somehow modify the body. I was playing around with stack numbers (`1/4*stackNumbers to 3/4*stackNumbers`) but didn't give the result I wanted.

How should I modify the sphere generation to achieve the middle half (**`pi/4 <theta <pi*3/4`**)? My overall problem is how can I split the sphere into 3 different parts upper 25%, middle 50%, and bottom 25%?

Here is the popular code for generating a sphere programmatically:

```
private void generateSphere(int stackNumber, int sliceNumber, boolean facingOut) {
    int capVertexNumber = 3 * sliceNumber;
    int bodyVertexNumber = 4 * sliceNumber * (stackNumber - 2);
    int vertexNumber = (2 * capVertexNumber) + bodyVertexNumber;
    int triangleNumber = (2 * capVertexNumber) + (6 * sliceNumber * (stackNumber - 2));

    vertices = new float[3 * vertexNumber];
    normals = new float[3 * vertexNumber];
    texCoords = new float[2 * vertexNumber];
    indices = new char[triangleNumber];

    // bottom cap
    // createCap(stackNumber, sliceNumber, false, facingOut);

    // body
    createBody(stackNumber, sliceNumber, facingOut);

    // top cap
    createCap(stackNumber, sliceNumber, true, facingOut);
}

private void createCap(int stackNumber, int sliceNumber, boolean top, boolean facingOut) {

    float stackPercentage0;
    float stackPercentage1;

    if (!top) {
        stackPercentage0 = ((float) (stackNumber - 1) / stackNumber);
        stackPercentage1 = 1.0f;

    } else {
        stackPercentage0 = (1.0f / stackNumber);
        stackPercentage1 = 0.0f;
    }

    float t0 = stackPercentage0;
    float t1 = stackPercentage1;
    double theta0 = stackPercentage0 * Math.PI;
    double theta1 = stackPercentage1 * Math.PI;
    double cosTheta0 = Math.cos(theta0);
    double sinTheta0 = Math.sin(theta0);
    double cosTheta1 = Math.cos(theta1);
    double sinTheta1 = Math.sin(theta1);

    for (int slice = 0; slice < sliceNumber; slice++) {
        float slicePercentage0 = ((float) (slice) / sliceNumber);
        float slicePercentage1 = ((float) (slice + 1) / sliceNumber);
        double phi0 = slicePercentage0 * 2.0 * Math.PI;
        double phi1 = slicePercentage1 * 2.0 * Math.PI;
        float s0, s1;
        if (facingOut) {
            s0 = 1 - slicePercentage0;
            s1 = 1 - slicePercentage1;
        } else {
            s0 = slicePercentage0;
            s1 = slicePercentage1;
        }
        float s2 = (s0 + s1) / 2.0f;
        double cosPhi0 = Math.cos(phi0);
        double sinPhi0 = Math.sin(phi0);
        double cosPhi1 = Math.cos(phi1);
        double sinPhi1 = Math.sin(phi1);

        float x0 = (float) (sinTheta0 * cosPhi0);
        float y0 = (float) cosTheta0;
        float z0 = (float) (sinTheta0 * sinPhi0);

        float x1 = (float) (sinTheta0 * cosPhi1);
        float y1 = (float) cosTheta0;
        float z1 = (float) (sinTheta0 * sinPhi1);

        float x2 = (float) (sinTheta1 * cosPhi0);
        float y2 = (float) cosTheta1;
        float z2 = (float) (sinTheta1 * sinPhi0);

        vertices[vertexCount + 0] = x0;
        vertices[vertexCount + 1] = y0;
        vertices[vertexCount + 2] = z0;

        vertices[vertexCount + 3] = x1;
        vertices[vertexCount + 4] = y1;
        vertices[vertexCount + 5] = z1;

        vertices[vertexCount + 6] = x2;
        vertices[vertexCount + 7] = y2;
        vertices[vertexCount + 8] = z2;

        if (facingOut) {
            normals[vertexCount + 0] = x0;
            normals[vertexCount + 1] = y0;
            normals[vertexCount + 2] = z0;

            normals[vertexCount + 3] = x1;
            normals[vertexCount + 4] = y1;
            normals[vertexCount + 5] = z1;

            normals[vertexCount + 6] = x2;
            normals[vertexCount + 7] = y2;
            normals[vertexCount + 8] = z2;
        } else {
            normals[vertexCount + 0] = -x0;
            normals[vertexCount + 1] = -y0;
            normals[vertexCount + 2] = -z0;

            normals[vertexCount + 3] = -x1;
            normals[vertexCount + 4] = -y1;
            normals[vertexCount + 5] = -z1;

            normals[vertexCount + 6] = -x2;
            normals[vertexCount + 7] = -y2;
            normals[vertexCount + 8] = -z2;
        }

        texCoords[texCoordCount + 0] = s0;
        texCoords[texCoordCount + 1] = t0;
        texCoords[texCoordCount + 2] = s1;
        texCoords[texCoordCount + 3] = t0;
        texCoords[texCoordCount + 4] = s2;
        texCoords[texCoordCount + 5] = t1;

        if ((facingOut && top) || (!facingOut && !top)) {
            indices[indexCount + 0] = (char) (triangleCount + 1);
            indices[indexCount + 1] = (char) (triangleCount + 0);
            indices[indexCount + 2] = (char) (triangleCount + 2);
        } else {
            indices[indexCount + 0] = (char) (triangleCount + 0);
            indices[indexCount + 1] = (char) (triangleCount + 1);
            indices[indexCount + 2] = (char) (triangleCount + 2);
        }

        vertexCount += 9;
        texCoordCount += 6;
        indexCount += 3;
        triangleCount += 3;
    }

}

private void createBody(int stackNumber, int sliceNumber, boolean facingOut) {
    for (int stack = 1; stack < stackNumber - 1; stack++) {
        float stackPercentage0 = ((float) (stack) / stackNumber);
        float stackPercentage1 = ((float) (stack + 1) / stackNumber);

        float t0 = stackPercentage0;
        float t1 = stackPercentage1;

        double theta0 = stackPercentage0 * Math.PI;
        double theta1 = stackPercentage1 * Math.PI;
        double cosTheta0 = Math.cos(theta0);
        double sinTheta0 = Math.sin(theta0);
        double cosTheta1 = Math.cos(theta1);
        double sinTheta1 = Math.sin(theta1);

        for (int slice = 0; slice < sliceNumber; slice++) {
            float slicePercentage0 = ((float) (slice) / sliceNumber);
            float slicePercentage1 = ((float) (slice + 1) / sliceNumber);
            double phi0 = slicePercentage0 * 2.0 * Math.PI;
            double phi1 = slicePercentage1 * 2.0 * Math.PI;
            float s0, s1;
            if (facingOut) {
                s0 = 1.0f - slicePercentage0;
                s1 = 1.0f - slicePercentage1;
            } else {
                s0 = slicePercentage0;
                s1 = slicePercentage1;
            }
            double cosPhi0 = Math.cos(phi0);
            double sinPhi0 = Math.sin(phi0);
            double cosPhi1 = Math.cos(phi1);
            double sinPhi1 = Math.sin(phi1);

            float x0 = (float) (sinTheta0 * cosPhi0);
            float y0 = (float) cosTheta0;
            float z0 = (float) (sinTheta0 * sinPhi0);

            float x1 = (float) (sinTheta0 * cosPhi1);
            float y1 = (float) cosTheta0;
            float z1 = (float) (sinTheta0 * sinPhi1);

            float x2 = (float) (sinTheta1 * cosPhi0);
            float y2 = (float) cosTheta1;
            float z2 = (float) (sinTheta1 * sinPhi0);

            float x3 = (float) (sinTheta1 * cosPhi1);
            float y3 = (float) cosTheta1;
            float z3 = (float) (sinTheta1 * sinPhi1);

            vertices[vertexCount + 0] = x0;
            vertices[vertexCount + 1] = y0;
            vertices[vertexCount + 2] = z0;

            vertices[vertexCount + 3] = x1;
            vertices[vertexCount + 4] = y1;
            vertices[vertexCount + 5] = z1;

            vertices[vertexCount + 6] = x2;
            vertices[vertexCount + 7] = y2;
            vertices[vertexCount + 8] = z2;

            vertices[vertexCount + 9] = x3;
            vertices[vertexCount + 10] = y3;
            vertices[vertexCount + 11] = z3;

            if (facingOut) {
                normals[vertexCount + 0] = x0;
                normals[vertexCount + 1] = y0;
                normals[vertexCount + 2] = z0;

                normals[vertexCount + 3] = x1;
                normals[vertexCount + 4] = y1;
                normals[vertexCount + 5] = z1;

                normals[vertexCount + 6] = x2;
                normals[vertexCount + 7] = y2;
                normals[vertexCount + 8] = z2;

                normals[vertexCount + 9] = x3;
                normals[vertexCount + 10] = y3;
                normals[vertexCount + 11] = z3;
            } else {
                normals[vertexCount + 0] = -x0;
                normals[vertexCount + 1] = -y0;
                normals[vertexCount + 2] = -z0;

                normals[vertexCount + 3] = -x1;
                normals[vertexCount + 4] = -y1;
                normals[vertexCount + 5] = -z1;

                normals[vertexCount + 6] = -x2;
                normals[vertexCount + 7] = -y2;
                normals[vertexCount + 8] = -z2;

                normals[vertexCount + 9] = -x3;
                normals[vertexCount + 10] = -y3;
                normals[vertexCount + 11] = -z3;
            }

            texCoords[texCoordCount + 0] = s0;
            texCoords[texCoordCount + 1] = t0;
            texCoords[texCoordCount + 2] = s1;
            texCoords[texCoordCount + 3] = t0;
            texCoords[texCoordCount + 4] = s0;
            texCoords[texCoordCount + 5] = t1;
            texCoords[texCoordCount + 6] = s1;
            texCoords[texCoordCount + 7] = t1;

            // one quad looking from outside toward center
            //
            // @formatter:off
            //
            // s1 --> s0
            //
            // t0 1-----0
            // | | |
            // v | |
            // t1 3-----2
            //
            // @formatter:on
            //
            // Note that tex_coord t increase from top to bottom because the
            // texture image is loaded upside down.
            if (facingOut) {
                indices[indexCount + 0] = (char) (triangleCount + 0);
                indices[indexCount + 1] = (char) (triangleCount + 1);
                indices[indexCount + 2] = (char) (triangleCount + 2);

                indices[indexCount + 3] = (char) (triangleCount + 2);
                indices[indexCount + 4] = (char) (triangleCount + 1);
                indices[indexCount + 5] = (char) (triangleCount + 3);
            } else {
                indices[indexCount + 0] = (char) (triangleCount + 0);
                indices[indexCount + 1] = (char) (triangleCount + 2);
                indices[indexCount + 2] = (char) (triangleCount + 1);

                indices[indexCount + 3] = (char) (triangleCount + 2);
                indices[indexCount + 4] = (char) (triangleCount + 3);
                indices[indexCount + 5] = (char) (triangleCount + 1);
            }

            vertexCount += 12;
            texCoordCount += 8;
            indexCount += 6;
            triangleCount += 4;
        }
    }

}

```

# Answer
> 1 votes
Think of your question in terms of tessellation with your sphere formed by rings. If you have a tessellation factor of 5, you will have a top cap, 2 middle sections, and a bottom cap. The bottom two tessellation ring being the 25% bottom cap and the top tessellation two rings the 25% top cap. The center is therefore one ring at the equator with a set of faces on either side of it at 50%. Here is a sample of how to tessellate a sphere by first calculating the rings at each height and then generating the faces between each ring.

```
float radius = 1.0f;
const int tesselationFactor = 5;

for (int i = 0; i <= tesselationFactor; i++)
{
    const float PI = 3.14159265359f;
    const float PIDIV2 = PI / 2.0f;

    // find height of ring
    float height = (i*PI / tesselationFactor) - PIDIV2;
    float dy = sinf(height);
    float theta = cosf(height);

    // locate verticies equally around center to form a ring
    for (int j = 0; j <= tessellation * 2; j++)
    {

        float longitude = static_cast<float>(j) * PIDIV2 / (tessellation * 2);
        float dx = sinf(longitude) * theta;
        float dz = cosf(longitude) * theta;

        Vector normal{ dx, dy, dz }; // initialize vector
        vertices.push_back(VertexPositionNormal(normal * radius, normal));
    }
}
// Fill the index buffer with triangles joining each pair of latitude rings.
int stride = tessellation * 2 + 1;
for (int i = 0; i < tesselationFactor; i++) // verticle rings
{
    for (int j = 0; j <= tessellation * 2; j++) // horizontal verticies
    {
        //
        int i1 = i + 1;
        int j1 = (j + 1) % stride;
        /* connecting face */
         // triangle 1
        index_push_back(indices, i * stride + j);
        index_push_back(indices, i1 * stride + j);
        index_push_back(indices, i * stride + j1);
         // triangle 2
        index_push_back(indices, i * stride + j1);
        index_push_back(indices, i1 * stride + j);
        index_push_back(indices, i1 * stride + j1);
    }
}

```

---
Tags: opengl, 3d, graphics, 3d-meshes, sphere
---


# Question
Title: How do you convert angle with velocity to x velocity and y velocity?
This question can be simplified to: If you lean a pencil of a certain length at a certain angle what is the x and y position of the tip? So, basically, I am making a game that plots a balls path through the air as it travels. I want the user to enter an angle and velocity to launch a ball at and get the program to convert that to an x and y velocity so that it can work out how to plot the balls movement across the screen. The x velocity doesn't change through the simulation but the y velocity will decrease constantly until the ball touches the ground again. This is why I referenced to a pencil because it relates to turtle graphics calculations.

# Answer
This is a straightforward application of the Unit Circle, multiplied by the length of the vector we want as output:

```
x = length * cos(angle)
y = length * sin(angle)

```
> 3 votes

---
Tags: physics, angles, trajectory
---


# Question
Title: Euler adjustments between two quaternions
I have two quaternions, `q1` and `q2`. If my object's current rotation is at `q1`, but I need to get it to `q2`, what would be the process to figure out how much rotation I apply to x, y, and z in order to get there?

In this example, x=right, y=up, z=forward

I've tried getting the delta between the two quaternions and unwrapping that into Eulers and moving the x, y, z the amount of the unwraped Vector3f, but that does not seem to give the correct values. Current implementation in pseudo code:

```
var dQuat = Quaternion.Inverse(prevRotation) * target.rotation;
dChange = dQuat.eulerAngles;

```

This approach gives me only positive changes. If I rotate forward on x, I get positive lower numbers and if I rotate backwards on x, I get larger positive numbers.

I'm looking for, in order to get to `q2` from `q1`, rotate `n` degrees along your x, y, z...

Thanks in advance for any help!

# Answer
Sounds like you are working with step motors which will take a rotation along a fixed axis. Not an answer to your question but an alternative I have used successfully: Work with spherical coordinates (pitch and yaw) to match your two motors on the x and y axis? Keep your direction heading as a vector (pointing in the direction you are gazing). BTW, a quaternion is a gaze vector + rotation around the gaze vector. If you do not have a step motor for the roll around the gaze, you may ignore that anyways. You have +z as forward, so you are using left handed math presumably. I have done the same and display the results using DirectX which uses left handed math. Below is sample code to calculate pitch and yaw from a gaze vector. This gives two Eugler angles around two fixed axis 0 to 360 degrees. Perform this once on your current gaze vector and again on the "to be gaze" vector, and subtract them. Dive by the degree of each motor's step, and that and its sign will give you the proper motor rotation. If you do not have position feedback, then calculate your final gaze vector using your degrees per step intervals so it stay in sync with your motor's true position after every rotation and just use the code snippet below to calculate the "to be gaze" vector.

```
void CalculatePitchYaw(
    XMFLOAT3 &vectorInOut, // Input: vector direction in x, y, z; Output: x & z snapped to axis near zero & normalized.
    float &pitchRadiansOut, // Output: Pitch 0 to XM_2PI
    float &yawRadiansOut, // Output: Yaw 0 to XM_2PI
    const bool rhs) // set to false if using left hand system vector math
{
XMVECTOR dir = XMVector3Normalize(XMLoadFloat3(&vectorInOut)); // unit vector for direction only
XMFLOAT3 vec;
XMStoreFloat3(&vec, dir);

const float nearZero = 0.0005; // 1/12500.f increments of a circle (radians); // not too small as we are dividing and using atan2f.  If more accuracy is needed, drop this tolerance and use atan2 (doubles) instead.

// Calculate yaw & pitch
// yaw (bearing in XZ plane)
if (fabsf(vec.x) <= nearZero) // near zero x-axis
{
    vec.x = 0.0f;  // treat as only along the z-axis
    if ((vec.z > 0.0f && rhs) || (vec.z < 0.0f && !rhs)) yawRadiansOut = XM_PI; // 180 deg
    else yawRadiansOut = 0; // 0 deg
}
else if (fabsf(vec.z) <= nearZero) // near zero z-axis
{
    vec.z = 0.0f; // treat as only along the x-axis
    if (vec.x > 0.0f) yawRadiansOut = XM_PIDIV2; // 90 deg ; right of z-axis
    else yawRadiansOut = XM_2PI - XM_PIDIV2; // 270 deg ; left of z-axis
}
else yawRadiansOut = atan2f(vec.x, vec.z);// rotation about the y-axis; neither near x nor z axis

// pitch (bearing in YZ plane)
vec.z = fabsf(vec.z);
vec.x = fabsf(vec.x);
if (vec.x > vec.z) vec.z = vec.x;

pitchRadiansOut = atan2f(-vec.y, vec.z); // rotation about the x-axis

vectorInOut = vec;

while (yawRadiansOut < 0.0f) yawRadiansOut += XM_2PI;
while (pitchRadiansOut < 0.0f) pitchRadiansOut += XM_2PI;
}

```
> 1 votes

# Answer
If I understand the question correctly, here's an approach that might work:

1. Choose an arbitrary vector, e.g. (0, 0, 1)
2. Multiply it by the first quaternion (q1) to get v1
3. Multiply it also by the second quaternion (q2) to get v2
4. Now calculate a new quaternion (q3) from v1 and v2. See code from the GLM library.
5. Convert q3 to Euler angles and you have your answer. See code from the GLM library.
> 1 votes

---
Tags: rotation, quaternion
---


# Question
Title: Deriving from base class but not calling base method
I am very new to C#, XNA, and OOP. This is my question: I have an abstract class called Sprite. Sprite handles position and drawing from the sprite sheets, from its update and draw methods, for my other automated and user controlled classes. I have another class that I need to create that also uses a sprite sheet but not in the same way. The sprite sheet in this case shows the texture in 5 states, from whole to destroyed, and I am going to write the update method for it so that when a missile collides with the texture, then and only then does the next frame of the sprite sheet get drawn. Is there a way that I can have this class, called bunker, be a child of the sprite class but never call the update method from the parent? Or should I just make it a seperate class altogether? Thank you for bearing with my noobish question.

# Answer
There are many ways to do that like using interfaces,abstract classes, etc. But you can use virtual methods. You can make the update method of Sprite class "virtual" like this:

```
public  virtual void update()
{  // code for sprite update
}

```

And then in bunker class you should override update method and change it from what it was in sprite class :

```
class Bunker: Sprite
{
...
public override void update()
{//here your update code
//different
 //from  base(Sprite) class}
}

```
> 1 votes

---
Tags: c#, xna, oop, inheritance
---


# Question
Title: Why are most windowed games not resizeable?
I find it incredibly rare to find a game where the window can be resized, even if permitting it is a single click away in their game engine. For what reason is this done?

Thoughts that come to mind are...

* Performance, is it possible that certain resolutions still perform better in windowed mode?
* Easy switching to fullscreen, as fullscreen usually requires supported resolutions. However, I find even borderless fullscreen games still prevent resizing.
* Management of aspect ratios? I don't think this would be a big issue to overcome however.

There's so many games that I want to be able to resize so I can fit them where I want on my screen, but alas, it's rare.

# Answer
When you have a 2d game with pixel-art graphics, having a fixed resolution makes many things far easier. You know exactly how much fits on the screen without having to stretch your graphics (and automatic resizing by non-integer factors really hurts the image quality on pixel art). There are games where the camera-space doesn't have much effect on the gameplay. But for other games the sight-range of the player makes a huge difference. This is especially the case for games which do not scroll at all and assume that the screen always shows the complete level. In such games the size of the levels is dictated by the resolution, so you can't support other resolutions anymore unless you either use windowboxing (not much different from running in a window) or stretching (with aforementioned disastrous effects on your graphics).

UI design also becomes far more challenging when you don't know the users resolution. An UI which looks well-proportioned and readable on one aspect-ratio might look like a complete mess with a different one. You also run into problems with UI elements being either too big or too small depending on the users resolution. Automatic resizing is also a problem for 3d games in this case, because many 3d games still use raster-graphics for the UI. I don't want to claim that these problems can not be worked around. A good UI designer using the right tools can create UIs which work on any resolution. But that takes time, skill and dedication, which directly translates to added development cost.

Many low-budget projects do not consider support for multiple resolutions worth the added development cost, so they stick to a single resolution.

Personally I think that running a game in a small window is a huge immersion breaker and very detrimental to the game experience, so I usually take the pain and do my best to make my games able to run fullscreen on any resolution. But that's just my opinion. Other developers might set their priorities differently.
> 4 votes

---
Tags: graphics, pc, window-management
---


# Question
Title: In GameMaker how to check if instance is a given object?
Let's say, I have three objects: `obj_square`, `obj_circle` and `obj_triangle`.

Instances of all three types of objects exists in the room and call the same script: `scr_test`.

Inside of this script, how can I check instance of which object is calling it?

Pseudocode:

```
if(self is instanceof(obj_circle))
{
// do stuff
}

```

# Answer
> 5 votes
`object_index`

> This read only variable returns the index of the object that the instance has been created from.

So your code would read:

```
if(object_index == obj_square) {
    // ...
}

```

---
Tags: game-maker, gameobject
---


title: one time rotation Unity

text:
# Question
Title: one time rotation Unity
How do I rotate the object only once after a key press. So after it rotates say 10 degrees upwards, the user can't rotate it anymore.

this is my code which as continuous rotation -:

```
   void Update(){
 if (Input.GetKey(KeyCode.J))
     transform.Rotate(0, 0, 3f);
  }

```

# Answer
Add a `private bool isRotated` variable to the script. This variable stores the information if the user did already rotate this object or not.

Then check that variable in your code.

```
 if (Input.GetKey(KeyCode.J) && isRotated == false)
     transform.Rotate(0, 0, 3f);
     isRotated = true;
  }

```

Another solution might be to disable or even destroy the component which handles the rotation of the object. But that's of course only an option when the component only handles the rotation and nothing else.
> 2 votes

# Answer
@Philipp's answer is correct but I want explain more about limiting

if you want rotate the object only once after a key press you should use Input.GetKeyDown In Update function

but if you want limit rotation between two value min\_max you can use Mathf clamp

> function clamp(x, min, max):
>
> if (x \< min) then x = min; else if (x \> max) then x = max;
>
> return x;
>
> end clamp

Mathf.Clamp(float value, float min, float max);

```
using UnityEngine;
using System.Collections;

public class RotationController : MonoBehaviour {

    void Update () {
        transform.rotation = Quaternion.Euler(new Vector3 (
            transform.rotation.eulerAngles.x,
            transform.rotation.eulerAngles.y,
            Mathf.Clamp (transform.rotation.eulerAngles.z, -3, 3)));

        if (Input.GetKeyDown(KeyCode.D))
            transform.Rotate(0, 0, 3);
        if (Input.GetKeyDown(KeyCode.A))
            transform.Rotate(0, 0, -3);
    }
}

```

in other way you can use Quaternion to limiting Quaternion definition:

```
using UnityEngine;
using System.Collections;

public class degree : MonoBehaviour {
  public float w,x,y,z;
  public float a = 0;

  void Start(){
    a = a / 360 * (float)Mathf.PI * 2;
    w = Mathf.Cos (a / 2);
    x = Mathf.Sin (a / 2);
    y = Mathf.Sin (a / 2);
    z = Mathf.Sin (a / 2);
    print (a);
    gameObject.transform.rotation = new Quaternion (w,x,y,z);
  }
}

```

you should know about Degrees 30° Radians(exact)π/6 Radians(approx) 0.524 learning link

so you can limit rotation:

```
void Update () {
    print (transform.rotation.z);
    if (Input.GetKeyDown(KeyCode.D) && transform.rotation.z <0.02617695)
        transform.Rotate(0, 0, 3);
}

```
> 2 votes

---
Tags: unity
---


# Question
Title: How to impale and stack targets correctly according to the collider and its coordinate?
I'm making another simple game, a catch game, where a spawning target game object must be captured using a skewer to impale it. Here how:

1. At the start, the falling object (**in red**) will fall in a vertical direction (**in blue**)
2. When aimed properly, the target will fall down along the line of the skewer. (**in blue**) Then, another target is spawned and will fall vertically. (**in red**)
3. When aimed successfully again in a streak, the second target will fall along the skewer and stacked. Same process over and over when another target is spawned.

However, when I test run it on the scene tab in Unity, when impaled several targets, instead of a smooth flow and stacking it ended up overlaying it instead of stacking it up like a pancake. Here's what it look like:

As I noticed when reaching the half-way of my progress, I tried to figure out how to deal with collider bodies without sticking each other so that it will actually stack like in the example of the image at no. 3. Here's the script code I added in the target game object:

```
using UnityEngine;
using System.Collections;

public class ImpaleStateTest : MonoBehaviour {

    public GameObject target;
    public GameObject skewer;

    public bool drag = false;

    private float stack;
    private float impaleCount;

    void Start () {
        stack = 0;
        impaleCount = 0;
    }

    void Update () {
        if(drag) {
            target.transform.position = new Vector3 (DragTest.dir.transform.position.x, DragTest.dir.transform.position.y - 0.35f, 0);
            target.transform.rotation = DragTest.degrees;
            target.rigidbody2D.fixedAngle = true;
            target.rigidbody2D.isKinematic = true;
            target.rigidbody2D.gravityScale = 0;

            if(Input.GetMouseButton(0)) {
                Debug.Log ("Skewer: " + DragTest.dir.transform.position.x);
                Debug.Log ("Target: " + target.transform.position.x);
            }
        }
    }

    void OnTriggerEnter2D(Collider2D collider) {
        impaleCount++;
        Debug.Log ("Impaled " + impaleCount + " time(s)!");
        drag = true;
        audio.Play ();
    }

}

```

Aside from that, I'm not sure if it's right but, the only way to stick the impaled targets while dragging the skewer left or right is to get the X coordinates from the skewer only. Is there something else to recommend it in order to improve this behavior as realistic as possible? Please help.

# Answer
You are using `OnTriggerEnter2D`, so i guess you are using triggers intead of colliders. Triggers don't get effected from collisions as oppose to colliders, instead, they send messages to scripts on it and colliding gameobject.

So, if you want your "circles" to collide, you should make them non-trigger.
> 1 votes

# Answer
**Stacking Issue**

Regarding the stacking issue, I am not sure how your class is setup, but I would consider handling the positioning of the stacked elements based on an indexed approach.

For Instance (pseudo code):

```
class Skewer : MonoBehaviour
{
   public List<SkewerElements> skewerElements = new List<SkewerElements>();
   public float skewerElementHeight = 1; //

   public void UpdateSkewerPositions()
   {
       int count = skewerElements.Count;
       float yOffset = count * skewerElementHeight; // use an offset to start

       for(int i = 0; i < count; i++)
       {
           // Basically by manipulating the yOffset you can "stack" elements based on the count of elements.
           skewerElements[i].transform.position = new Vector3(transform.position.x, transform.position.y + (-yOffset + (skewerElementHeight * i)), 0);
       }
   }
}

```

I used a negative yOffset because if the skewer y is 0. Then we move down the first element by the count of the skewerElements. Then we increment the y by the index of the element by its height.
> 0 votes

# Answer
Engines aside, circle collision is incredibly easy to program - you can do it from scratch. Every circle object must have a Vec2d position value and a radius.

In your update loop, iterate through your list of all circles and then test to see if any pos value of one, \>= the pos of any other, + both radiai.

If this is true, stop the gravity force from acting on the circles that are touching. Or, you can implement a repelling force for the object moving. Mind you, if the the two forces (gravity and repell) have a difference of less than 1, you have to set both to zero, or they will vibrate.

You will want a Vec2d library for this, unless you want to run the vector math yourself (it's not that hard).

As for the skewer: since the only forces you are dealing with are gravity and collision, you don't have to worry about any complicated physics. The skewer is a line, so you can test it's collision by determining if any of the circles x or y are \>= the skewer position.

This should all be pretty straight forward, comment if you need details.
> 0 votes

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


# Question
Title: A perfect information game with several millions of unique states
I want to model learning by having computer players compete against each other. Win/lose ratio will be tracked for each position for each player and used to search an optimal move. The depth of search and the learning rate will be two parameters characterizing a player. Which games have a relatively small set of unique states (1M-100M would be ideal), perfect information and decent length of a game?

# Answer
Mini-checkers should work. Played on 6x6 board on half of the cells. Checker that reach last line wins the game (not get flipped). Thus each cell in the first and last raw can be empty or home-player. Other 3x4 cells each can be empty, white or black. 2^6\*3^12 is \< 35 M. Game can last more than 10 moves.
> 1 votes

---
Tags: models
---


# Question
Title: Volumetric Lighting/Light Shafts in DirectX
So currently I am trying to implement Light Shafts into my DirectX Engine. I read the Nvidia GPU Gems Article (https://developer.nvidia.com/gpugems/gpugems3/part-ii-light-and-shadows/chapter-13-volumetric-light-scattering-post-process) I am new to Graphics Programming so could someone explain this in a much more dumbed down version? At this stage based on the article linked above I need to calculate a vector from pixel to light source in screen space and display a texture with those coordinates from the Vector?

# Answer
This technique consists of three main steps.

1.) Render your light source only, but occluded by the scene geometry to a black texture. This could be done by rendering the light source against the scene's depth-stencil buffer and performing depth-tests or stencil tests to only keep visibe pixels of the light source.

2.) You need to perform a radial blur with the light source's center as the blur center point.

3.) Finally, you additively blend the result with your scene like you would with bloom.
> 1 votes

---
Tags: c++, directx, hlsl, lighting
---


# Question
Title: click event not registered for an actor inside stacked cell within a table in libgdx
In the following code segment, the click event for image element is not registered. However, if i comment out stack.add(shapeLabel) statement, then the image button is able to register the click event. Why is it so ?

```
        private Array<Shape> tableShapes;
        private Array<Stack> tableofStackedShapes;
        ....
        ....
        Stack stack = new Stack();
        Label shapeLabel;
        colorIndex = MathUtils.random(colorsList.size - 1);
        cellShape = shapesList.get(MathUtils.random(shapesList.size - 1));
        String filename = cellShape + "/" + cellShape + "_" + colorsList.get(colorIndex) + ".png";
        img = new Shape(cellShape, colorsList.get(colorIndex), new Texture(filename));

        if (this.currentLevel > 2) {
            int randomNumber = MathUtils.random(0, 9);
            img = new Shape(cellShape, colorsList.get(colorIndex), null, randomNumber, new Texture(filename));
            img.setSize(cellSize * ((float)stage.getWidth() / stage.getHeight()), cellSize);
            stack.add(img);
            shapeLabel = new Label("" + randomNumber, new LabelStyle(new BitmapFont(), com.badlogic.gdx.graphics.Color.BLACK));
            shapeLabel.setAlignment(Align.center);
            shapeLabel.setBounds(img.getImageX(), img.getImageY(), img.getWidth(), img.getHeight());
            stack.add(shapeLabel);
        }   else {
            img = new Shape(cellShape, colorsList.get(colorIndex), new Texture(filename));
            img.setSize(cellSize * ((float)stage.getWidth() / stage.getHeight()), cellSize);
            stack.add(img);
        }
        stack.debugAll();
        tableofStackedShapes.add(stack);
        tableShapes.add(img);
    }

```

My suspicion is on chaining of events, and that the label is restricting the click events to be detected by the img element. But I don't know what exactly is triggering this and how to fix it. Thanks for any inputs .

# Answer
The answer lies in here : shapeLabel.setTouchable(Touchable.disabled);

With this I am able to achieve what I intended to do. The other alternative I found is to relay the events using InputMultiplexer. But, I felt the above solution to be simplest.
> 0 votes

---
Tags: java, libgdx, events
---