# Question
Title: How to "hide" an adventure game in an RPG
I have a shakey idea for a game, and I need help fleshing out what mechanics could make this work.

I want to make a game that, on the surface, is a fun little exploration/dungeon crawler/rpg-lite sort of game. There's some story, a large map, and basic quests to go off to various dungeons and defeat all the monsters that are threatening the kingdom.

The idea is that a player can play through, and defeat the game by just going and defeating the monsters everywhere, and that should be a rewarding enough way to play the game.

However, I don't want that to be the only way to play the game. What if the monsters attacking the kingdom from a nearby "dungeon" are just misunderstood, or are being provoked? What if they could instead be made into allies?

For each set of set of monsters threatening the kingdom, I want the player to either be able to just go and kill them all, or find some other solution, but for killing all the monsters to be the only obvious thing to do.

The idea being that finding a different solution should feel very rewarding, or a suggestion that there are other solutions should come late in the game and provide motivation for the player to replay the game.

My question is: What sort of game mechanics could be used to provide an alternative way of progressing through the game while not making it obvious that the alternative exists? I think if a dialog tree open up with the first monster you met in each dungeon, it would telegraph the idea that there's an alternative solution. So how could there be a dungeon of monsters that you can wade into and immediately start fighting, while at the same time there being a non-violent solution?

# Answer
> 21 votes
Here are a bunch of ideas you could try standalone or in combination:

1. **Rosetta Stone**

To speak with the monsters, the player needs to learn their language. Of course, we don't tell the player they even have one. ;) But there can be clues - marks in their dwelling places or in items they carry. If the player collects enough of them, they can use it as a guide to translate.

Now, if we make it an obvious collectable, players will tend to collect it out of sheer completionist habit, and might stumble into this route by accident. To make this less likely, we can either make the necessary items hard to find, or hide them in plain sight by making them look mundane. Say the monsters drop gold coins/nuggets or gems (pretty standard) which the player can trade for goods in town. These items can't be equipped or consumed, and don't stack in your inventory, so players will tend to want to trade them out regularly for gear. An astute player might notice that they're not all the same though, with different inscriptions on each. If the player collects a full set in their inventory, and puts them in the right order (say based on writings in the monsters' dwellings), they unlock a primer/key they can use to start translating some of the monsters' language.

At this point you can have a puzzle the player needs to solve to gain the monsters' trust, but the instructions written in monsterese, so only a player who's learned the language can complete the trial. Or, you can have the player try to speak with the monsters directly, which means first we need to get them to listen...
2. **A show of force** (spoiler warning for Spec Ops: the Line)

> There's a moment in the game where you're surrounded by civilians and it looks like the only way to proceed is to shoot them. But if you aim up and shoot into the sky, they take the threat and scatter without you needing to injure anyone (assuming the bullets never land...)

Give the player an option to deliberately miss a monster in a showy way, or destroy a prop like a big tree, boulder, or statue where they can see it. This proves to the monsters that the player has the means to destroy them, but also the restraint to not use it, and they can back down and give the player an opportunity to parlay. (Which the player might need the language as above to be able to act on)

To pull this off well, the demonstration needs to be something the player wouldn't do by accident - maybe requiring a special weapon or multiple consecutive hits, or a reckless disregard for their own safety...
3. **Impersonation / homage** (spoiler warning for Brothers: a Tale of Two Sons)

> In the game you come across a hostile tribe who won't let you pass. But observing them from a distance you can discover that they worship a tall, 4-armed deity of some kind. By stacking the brothers one on the other's shoulders, you can impersonate this deity and use this to get past.

(See also: impersonating the Ilwrath's god, or learning the words that give the Khor-Ah pause in Star Control II)

Leave enough environmental details in the monster's caves, dress, or in items they drop for an observant player to glean something about their culture. A god they worship, a mark of status or royalty they regard, a traditional gift or offering used on special occasions. A stealthy or evasive player can glean this information or steal the required artifacts without necessarily killing for them.

Then give the player a means to act on the information. If your dungeon crawler has an equipment system, let them equip what would otherwise be junk loot in a particular combination to, say, imitate a divine figure in the monsters' mythology, or a high-ranking royal or shaman. Monsters encountering the player in this state don't attack right away (but you may still need something like the language key to be able to act on this opportunity). Or, if you have a drop mechanic, let the player gather a very specific gift or offering the monsters will like, and drop it in a combat encounter to signal good-will.
4. **Pacifist play**

In the game Bastion, the player has a shield that can block enemy attacks. Putting up the shield at exactly the right moment deflects the attack, damaging the attacker. In my playthrough, I chose to use the shield alone when fighting a particular in-game faction, and never strike them with my weapon, because I felt a lot of empathy for them and didn't want to be an aggressor. The shield can only damage an attacker in self-defense, so it was my way of saying "I'm willing to make peace if you are." Unfortunately, the game doesn't seem to recognize that avenue for expression. But yours could!

Give the player a similar defensive ability, and track streaks when they use it exclusively without taking aggressive action in-between. After a while, your monsters can catch on, and pause in their attacks as they try to figure out why this adventurer doesn't attack like the others. That can put them in a state where you can talk to them directly, or set them up for a further puzzle (like the language example)
5. **Friendship dance**

This slightly silly idea came to me from thinking about bees communicating through dancing. What if when encountering the monsters, they initially rush right up to you, but don't attack immediately. They have a particular set of dance steps they're looking for to know if you're friend or foe. If you step the wrong way (or run, or attack them), they know you're an invader and they pounce. Otherwise they keep on you in what looks to the player like a combat strafe, circling to attack.

Through trial and error, players can discern the particular sequence of movements the monsters will accept without attacking, discovering something like a cheat code to de-escalate the confrontation. ;)

# Answer
> 3 votes
Expanding on my comment, I was once designing a game where I had a specific "boss monster" encounter (in this case, a dragon). Much of the game's treasure rewards were hidden behind obtuse puzzles with few/no hints as to how to get them (see also: Tower of Druaga). But that's only ancillary to this particular puzzle.

The whole way through the game the player's trained to assume that monsters are inherently hostile (as every one up until this point has only existed to attack the player), so upon entering the floor with a giant sleeping dragon, they naturally assume that the only interaction with this singular monster would be to fight--e.g. walk up and wave their sword around.

But I also let this specific boss monster react to the generic "Use" action which would open up the alternative: a dialog box where they can converse with the dragon instead. The game never points out that the Use key is available in this situation (or really, any, beyond the semi-tutorial that indicates that the key exists) so it isn't telegraphed any: no "E to Open", no "E to Talk" popups anywhere.

On top of that, the dragon is *asleep* when it is first encountered, so its not immediately hostile, giving the player the opening needed to walk up and talk to it, or walk up and start poking it with a pointy stick. What the player does is *entirely in the hands of the player.*

The item the player got (regardless of approach) was always good, just that the one they get from talking rather than fighting was 'better.' There might've even been three possible outcomes, but I've lost track at this point. I never finished the game and I haven't worked on it in probably ten years (I had most of the *content* done, but was missing art for a good portion of the enemies).

---
Tags: game-design
---


# Question
Title: Why do some videogame sequels become bigger?
Sometimes I'm wondering why sequels in games usually strive to have new features, making them more complex, taking much longer to finish and also sounds much harder to keep motivated into it.

I understand that it's needed because gamers don't want to buy the same game with just a different story. but occasionally these features seem to make the original intention of the game more complex than I think it should be.

If a developer is always with the thought to make his next game bigger than the previous, then that means that they'll become overly cluttered with tons of features that a gamer may or may never use. That sounds like a waste of effort to me.

Maybe it's just that I prefer a simple style from indie games, but when I look at the larger companies, then sometimes I've a feeling they're trying out a lot (if not too much) to sell well.

Just take a look at Mario Kart 8, Breath of the Wild and Super Mario Odyssey as example.
They're all so complex compared with what the series used to be. Now imagine how large their next game has to be in order to top that, if that's even possible.

So my question is: what leads game developers to focus on making the next game even bigger? And are there viable ways to avoid this trend?

I'm used to the phrase 'less is more', but I wonder if that also fits in this situation.

# Answer
The expectation that sequels be bigger actually balances out the trade-off between making a sequel and starting a new series.

### Starting a new series

Advantages

* No expectation to one-up the last game
* Can experiment with new core mechanics

Disadvantages

* It is hard to tell if players will even like the core mechanics.
* No prior marketing
* You start with an empty code base and art collection.

### Creating a sequel

Advantages

* Can piggyback off the marketing of the previous game
* Tried-and-true core mechanics
* Can focus more on adjusting supporting mechanics
* You can reuse assets from previous games.

Disadvantages

* Must be big enough to still be novel.
* Cannot mess too much with the core mechanics because of player expectations.

All games must have a certain level of novelty. The big difference is that the first game in a series focuses on providing that novelty through core mechanics while sequels focus on supporting mechanics. Changing the supporting mechanics is tricky, because you risk either ruining the core mechanics or not affecting it enough, resulting in unnecessary bloat instead. This means sequels usually leave in most of the supporting mechanics from the previous game to keep the core mechanics intact, while adding additional supporting mechanics to make it novel. Nearly all of the original game + more novel stuff = a bigger game.

The sequel is going to have to be bigger to set it apart from the original, but you can work to make sure the size adds value to the game by using the previous game for research. Find out what made the game fun, and focus on new ways to encourage players to keep doing that. Did players play the first game because they like to explore? In the next game, add an incentive to pay closer attention to the scenery and to visit hard-to-reach places (e.g. Breath of the Wild's photo album of memories and the Korok seeds).
> 11 votes

# Answer
Because otherwise the programmers would need to be fired.

Ok, it's a bit extreme, and not the only reason, but it's one to think about.

A game company wants to keep their employees as much as they can, and this for several reasons. **¤**

If the game company decides to not add new feature but simply release a sequel that is not "bigger", a sequel with only new content (the content produced by artists, writers, level designers and such), what will the programmers do? Yes, they can work on a new IP, but there's going to be issues with the content at some point since the content creators are busy with something else.

So instead of firing them to not waste money, it's a good idea to make them work on the sequel to improve it and give users reasons to buy it (other than "Oh well, they've expanded the story and changed the graphics.").

---

How can you avoid that?

Well you have first to *want* to avoid that. It's not a requirement; it depends on the game, it depends on the team, it depends on the studio.

For an indie developer, working alone on their game, if the first instalment of the game was story based, and what came up in the review was mostly along the lines "nice little game, *great story*", it would perfectly make sense to spend little time on beefing up the gameplay, and a lot of time on creating a great story for the sequel.

---

**¤** The hiring process of game developers can be very tedious, hard and hazardous: letting go a developer to re-hire them later means more paperwork to do for the laying-off, more HR money spent on re-hiring them (even more paper work), the risk of them being hired by another company in the interval (intermediate and senior developers can be hard to find), the risk of them demanding a higher salary when re-hiring them, etc. An employee laid-off is a also some knowledge that a company loses. Replacing an employee is costly because they have to learn the processes and the tools, etc.
> 9 votes

# Answer
From the point of view of the investor, when someone invests in a sequel, there is usually a larger budget and an existing fanbase. Cutting out features that were there in the first version will enrage the fanbase, so your options are to make the sequel the same, or to make it more.

From the point of the designer, there were tons of ideas and features that were tested during development of the first game, some of which the designer liked a lot, but which had to be cut for money and time constraints.

If you want to make a sequel (on the same platform) less than the original, better not to make it a sequel but start a new brand or sub-brand instead.
> 4 votes

# Answer
I'm surprised that nobody has mentioned reusing code bases yet. When creating the first game in the series, programmers need to use large amounts of time just thinking about what the game is going to be about, the story behind it, and how to organize the game's code. At the same time, they must create a graphics engine (if they are not using a pre-made one), and code everything in the game from scratch.

However, when making the second game in the sequel, the graphics engine is already made, and several sprites and mechanics are likely to be reused. The New Super Mario Bros series is the best example of this, in my opinion (the 3-D Mario games too, but too a lesser extent).
> 0 votes

# Answer
Spectacle creep is why games strive to be more over the top than the last installment.
> -4 votes

---
Tags: game-design, marketing
---


title: LibGdx Table layout

text:
# Question
Title: LibGdx Table layout
I'm trying to layout a fairly simple Table on a menu screen. Using LibGdx, Android only, with Scene2D.

I need the first three rows to fill the table width, and be centered in the row, but not stretch across the whole screen.

Then have each Checkbox evenly take up the whole row, followed by the two bottom buttons evenly kind of centered in the row.

The Table Wiki doesn't help at all for this kind of layout and I can't find any tutorials or examples on the web that would help.

I've tried using fillX(), expandX(), colspan(), but it keeps turning out the same.

```
X                         L a b e l                      X

X                   S  l   i   d   e   r                 X

X                         L a b e l                      X

X     Checkbox     X     Checkbox     X     Checkbox     X

X               Button        X        Button            X

```

I'll worry about the padding later, at the moment I'll be happy just getting it looking something like the above.

It always ends up looking like this, with the first three rows only taking up half of the table width:

```
XXXXXX |
XXXXXX |
XXXXXX |
XXXXXX |XXXXXX | XXXXXXX
XXXXXX | XXXXXX

```

UPDATE:

I tried to look at some more examples and eventually figured out how to get the formatting looking fairly good, so I think I pretty much answered my own question.

I got it working before I saw the example posted below, but that's a really nice example, and I still might use some of it.

Thanks for your replies!

This was my Xth attempt that got it to initially look okay:

```
baseTable.add(label).colspan(3).center();
baseTable.row();

baseTable.add(slider).colspan(3).center();
baseTable.row();

baseTable.add(label2).colspan(3).center();
baseTable.row();

baseTable.add(Checkbox1).width(135f).center();
baseTable.add(Checkbox2).width(135f).center();
baseTable.add(Checkbox3).width(135f).center();
baseTable.row();

baseTable.add(imageButton1).colspan(2).width(202f).center();
baseTable.add(imageButton2).colspan(2).width(202f).center();

```

# Answer
> 3 votes
One approach that might help is to wrap the `Table` in a `Container`.

In the example above the logical structure is

```
Container
  Table
    Label
    Slider
    Label
    CheckBox|CheckBox|CheckBox
  Table
    Button|Button

```

I set the size on the `Container` to constrain the `Table` so that it doesn't fill the entire screen.

Each `row` in the outer `Table` except for the one with the `CheckBox`es have a `colspan` of 3 and pretty much every `cell` is set to `fillX` and/or `expandX`.

It's tricky to get the two buttons to center as they're part of a 2 column layout that exists inside a three column layout, that is why they are wrapped in their own `Table`.

The full source code for the example above (which uses the **uiskin** from the **libGDX** wiki):

```
package com.bornander.sandbox;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.CheckBox;
import com.badlogic.gdx.scenes.scene2d.ui.Container;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Slider;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.viewport.ScreenViewport;

public class SandboxGame extends ApplicationAdapter {

    private Stage stage;

    public void create() {
        stage = new Stage(new ScreenViewport());
        //stage.setDebugAll(true);

        Skin skin = new Skin(Gdx.files.internal("uiskin.json"));
        Container<Table> tableContainer = new Container<Table>();

        float sw = Gdx.graphics.getWidth();
        float sh = Gdx.graphics.getHeight();

        float cw = sw * 0.7f;
        float ch = sh * 0.5f;

        tableContainer.setSize(cw, ch);
        tableContainer.setPosition((sw - cw) / 2.0f, (sh - ch) / 2.0f);
        tableContainer.fillX();

        Table table = new Table(skin);

        Label topLabel = new Label("A LABEL", skin);
        topLabel.setAlignment(Align.center);
        Slider slider = new Slider(0, 100, 1, false, skin);
        Label anotherLabel = new Label("ANOTHER LABEL", skin);
        anotherLabel.setAlignment(Align.center);

        CheckBox checkBoxA = new CheckBox("Checkbox Left", skin);
        CheckBox checkBoxB = new CheckBox("Checkbox Center", skin);
        CheckBox checkBoxC = new CheckBox("Checkbox Right", skin);

        Table buttonTable = new Table(skin);

        TextButton buttonA = new TextButton("LEFT", skin);
        TextButton buttonB = new TextButton("RIGHT", skin);

        table.row().colspan(3).expandX().fillX();
        table.add(topLabel).fillX();
        table.row().colspan(3).expandX().fillX();
        table.add(slider).fillX();
        table.row().colspan(3).expandX().fillX();
        table.add(anotherLabel).fillX();
        table.row().expandX().fillX();

        table.add(checkBoxA).expandX().fillX();
        table.add(checkBoxB).expandX().fillX();
        table.add(checkBoxC).expandX().fillX();
        table.row().expandX().fillX();;

        table.add(buttonTable).colspan(3);

        buttonTable.pad(16);
        buttonTable.row().fillX().expandX();
        buttonTable.add(buttonA).width(cw/3.0f);
        buttonTable.add(buttonB).width(cw/3.0f);

        tableContainer.setActor(table);
        stage.addActor(tableContainer);

        Gdx.input.setInputProcessor(stage);
    }

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

        stage.act();
        stage.draw();
    }

}

```

---
Tags: libgdx, android
---


# Question
Title: GLfloat vs GLfixed vs GLint performance in 2017
Some people claim that floats should be used for rendering vertices in modern graphics cards, because graphics cards are optimized for floating-point arithmetic and therefore, integer calculations are often emulated. I would think that most graphics cards have ALUs, and therefore, an efficient way to process integer vertices. So, are floats actually faster than integers on modern graphics cards?

# Answer
There's a very nice throughput table here

If you take a look at the rows containing the throughput of 32 bit integers and floats, you'll see, that the float throughput is either higher (in case of the compute capabilities between 3.0 and 3.7) or exactly same (3.7+). This means, that depending on the GPU, integers are either worse or the exact same.
> 2 votes

---
Tags: performance, opengl-es, opengl-es2, graphics-programming, opengl-es3
---


# Question
Title: How can City-sim simulate hundreds of characters?
My games usually start lagging quite easily when there are a couple hundred of boxes representing possible characters. While games like SimCity or even Anno have hundreds of characters.

I realized that those games don't update everything at every tic, the needs are handled in intervals and it's not a render problem, but all of those tiny creatures have individual path-finding etc.
I simply can't understand how they can pull that off for thousands of characters even on old machines. How do they do this?

This question was updated to refer to huge Numbers where individuals don't really count and are simply simulated for immersion and aesthetics.

(Related if referring to individual characters: How does Dwarf Fortress keep track of so many entities without losing performance?)

(Different question but maybe related?: Rendering hundreds of animated characters in Unity3D)

# Answer
> 14 votes
**Like so much of gamedev, the answer to how city sim games accomplish this seemingly-impossible feat is: they probably don't. They're just faking it well.** ;)

Sims like these will typically operate on a "chunked" level, modelling groups of people, neighbourhoods, traffic corridors, or other city dynamics as a whole, rather than processing AI for every one of thousands or millions of residents.

There are a few ways we might approach this:

* **"Sparse" bottom-up:** here we still simulate individual city residents, but not "too many" of them, and not every frame. You could think of this like a poll or census issued to a random sample of the people each week. You interpolate the results to come up with estimates of the wider virtual population - where they live, their vocation, income, demographics, etc.

So for example, if you only simulate a hundred residents in your city, and 5 of them are students, then you can estimate that about 5% of your city's population is students, and model demand for schools accordingly.

You might need to re-generate your random samples from your city's population distribution occasionally, to avoid excess clustering / sparseness (eg. if a neighbourhood becomes unpopular and all of your census residents move away, you want to note the exodus without leaving it completely devoid of representation in your sim!)

* **Top-down:** Here you come up with a master formula that looks at your city and models its dynamics as a whole. In a style similar to macroeconomics, we neglect the details of individual agents, or consider them to be a kind of continuously divisible "fluid" of economic activity that flows according to principle-based laws.

Rather than thinking about individual preferences and variability of people, your game rules might look more like differential equations relating amenity proximities and tax rates and productivities and property values and crime rates and and and...
* **Middle-out:** Various hybrids between the two are possible - for instance, simulating each "faction," "industry," or demographic segment of the city as its own meta-person, making its own individual decisions, but spread out in a heatmap or wavefunction across the city rather than existing in any one body. Or chunking the city into neighbourhoods which each process their own smaller-scale rules in interaction with their neighbours.

Now, when the player zooms in close enough to see individual people, or looks at reports of statistics citing numbers of individuals - those are not necessarily the ground truth that's being used to run the sim. Rather, they can be an inferred product of it.

Let's say we zoom in on a particular city block. From our overall city sim, we know the rough population of this part of town, the types of activities that happen there, the times of day when it's active. So on demand, we can spawn an appropriate number of people of the appropriate demographics doing those kinds of activities there. Their AI can be dirt simple, maybe as little as playing an animation in place or following a waypoint to the nearest door/screen edge where they can de-spawn.

This means we usually won't need to do pathfinding for every agent. Instead, we can do one master flow-mapping pass on the whole road network, to identify the overall volume of different kinds of traffic along each segment. Then we can spawn enough vehicles of the right types in those segments to reflect that density. Once spawned, agents can just get by with local steering or pre-generated waypoints to get to a de-spawn point. Keeping spawn closets along each segment correctly balanced with the de-spawning rate lets us maintain any steady volume of traffic we want.

In this way, the people & vehicles the player sees are figments, like a souped-up particle system giving the impression of realistic clouds without actually computing full fluid dynamics on every molecule of vapour. ;) We arrange them as set dressing to communicate the state of the simulation, rather than to drive it.

For many games this will be enough. The player often is't able to select an individual agent to interrogate them about what they're doing there or where they're going, so it's hard to spot the seams and notice if an agent does something that doesn't make sense, like driving around the same block three times.

But if you need absolutely consistent agents in a densely populated environment, you can look into a neat technique called "Alibi Generation." This is a sophisticated sampling technique that lets you generate agents you'd expect to find in a given situation. Then, if the player tries to investigate one in more detail, you can retroactively sample more detail about what they're doing, in a way that's consistent with what the player has observed about them so far. The idea is that you still gain the lightweight benefits of "cardboard stand-in" people most of the time, but on the spot they can make up a plausible alibi to pass as fully-simulated agents.

**Update**: Now that the game is out, I can say that Watch Dogs Legion works this way. Disposable cardboard cutout pedestrians are generated on demand to fill out the player's immediate vicinity, according to a "census system" that models the mix of demographics, professions, styles, etc. that we'd expect to see in each neighbourhood of London. If nothing happens to that person, they eventually walk out of the player's view and are forgotten entirely. But if something noteworthy happens to them or the player starts interacting with them, they can get "up-rezzed" to individual simulated agents who carry on existing and going about routines when the player isn't around, and can show up again later in the story. Check here for an interview with some of the developers explaining the workings of the system in more detail.

---
Tags: ai, game-loop, optimization
---


# Question
Title: Determining the first future intersection possible between ships and a planet
Somewhat of an extension of this.

# The Problem

I have a ship being launched from a planet, and I would like it to travel at a constant speed and direction such that it intersects another planet the soonest that it can.

(Beautiful diagram courtesy of Ausa)

I am **ignoring** initial velocity, end velocity, and gravity. The angular velocity of the planets and the velocity of the ship is constant. The physics that I am trying to achieve need not be realistic.

Using some quick maths I created a function! The function determines the smallest fly-by distance from the ship to the planet over time if the ship were to take the optimal route (a linear route since there's no gravity). So by determining when the fly-by distance is 0 (when the paths of the ship and planet intersect) I can work backwards to easily determine the angle of which I must launch the ship at to achieve this.

I created an implementation of the Bisection Method to find the first root of the function but depending on the variables of the function, the bisection method isn't the best solution to this problem. So now I'm trying to solve it mathematically! This is essentially what I need to solve:

Any solutions or ideas are greatly appreciated, thank you!

# TL;DR:

This means I want to find the x-intersection of the function nearest to the origin.

# Desmos

If you're interested in playing around with this function, I graphed it in Desmos https://www.desmos.com/calculator/tdtzt1gqkl

**r\_0** radius from the planet to the sun ("magic" units)

**a\_0** current angle of the planet in relation to the run (clockwise radians)

**s\_0** angular speed of the planet (clockwise radians per second

**x\_1** current *x*-position of the ship ("magic" units)

**y\_1** current *y*-position of the ship ("magic" units)

**s\_1** speed of the ship ("magic" units per second)

**x\_p** planet *x*-position at x time ("magic" units)

**y\_p** planet *y*-position at x time ("magic" units)

**d\_x** delta *x*-position from ship to planet at x time ("magic" units)

**d\_y** delta *y*-position from ship to planet at x time ("magic" units)

**d\_net** net delta position from ship to planet at x time ("magic" units)

**v\_x** optimal *x*-component of ship velocity ("magic" units per second)

**v\_y** optimal *y*-component of ship velocity ("magic" units per second)

**x\_s** ship *x*-position at x time ("magic" units)

**y\_s** ship *y*-position at x time ("magic" units)

**f(x)** net distance from planet to ship at x time

# Answer
I don't think a purely analytical solution to this is possible.

Any way we slice it, we have part of the problem in polar coordinates and another part in cartesian coordinates. So we end up trying to find an intersection between a line or curve and a sinusoid/periodic trig function. If the line were a constant we could use the arcsine/arccosine/arctangent functions. But unfortunately we're dealing with curves or lines with slope so no standard function gets us what we need.

In a previous answer I showed how we can solve this to within the needed accuracy by binary search. But since you've specified you don't want to solve it that way, let's see if we can reframe our problem differently.

First, to simplify our math, let's apply some (reversible) changes of coordinate system and units.

* Define the center of the planet's orbit as the origin
* Define the radius of the orbit as 1 (effectively our distances are now measured in AU)
* Define our unit of time as the duration it takes the planet to travel 1 unit of space (so now 1 planetary year = 2 pi time units)
* Define time `t=0` as the most recent moment that the planet passed between the spaceship's start position and the center of the orbit, and time t\_0 is the "start" time when our ship begins moving from that location

This lets us standardize the situation like so:

So our parameters are:

* t\_0, the time forward from which we want to find solutions:

```
t_0 = angleDifference(planetStartAngle, atan2(shipStartPosition - orbitCenter))
if(t_0 < 0)
    t_0 += 2 * pi

```

This is just the clockwise (orbit-wise) angle in radians between the ship's start position and the planet's, as viewed from the center of the orbit. Starting from perfect alignment with the ship at t = 0, the planet needs to orbit through angle t\_0 before it arrives at its start position relative to the ship.
* p, the scalar distance of the ship's start position from the center of the orbit:

```
p = length(shipStartPosition - orbitCenter)/orbitRadius

```
* s, the speed of the ship in our new spacetime coordinate system's scale:

```
s = shipSpeed * 2 * pi / (planetAngularSpeed * orbitRadius)

```

We're interested in the function L(t), the distance from the ship's start position to the planet.

L(t)2 = (p - cos(t))2 \+ sin2(t)
= p2 \+ 1 - 2p cos(t)

And we want to set this equal to the distance the ship has traveled by time t \> 0,

T(t)2 = (s(t - t\_0))2
=s2t2 \- 2s2t\*t\_0 + s2t\_02

At the times of intercept, T(t) = L(t) so...

s2t2 \- 2s2t\*t\_0 + s2t\_02 = p2 \+ 1 - 2p cos(t)

Which we can rephrase as:

cos(t) = (1/2p)(-s2t2 \+ 2s2t\*t\_0 - s2t\_02 \+ p2 \+ 1)

Which is "just" an intersection between a parabola and a garden-variety cosine wave (unscaled, unshifted).

Take the parabola side of that equation and call it P(t). We know we can't possibly have an intersection before P(t) drops to less than or equal to 1, so we can use the garden variety quadratic formula and find the greater of the two solutions P(t\_low) = 1 to get a lower bound on t.

We know the cosine wave rises back up to 1 by `t_high = ceil(t_low/2pi)*2pi`, but the parabola is strictly decreasing, so our earliest intersection must lie between `t_low` and `t_high`, at most one wavelength apart.

We can also find the greatest solution for P(t) = -1 to get a potentially tighter bound on t\_high

Unfortunately this seems to be about as far as a pure analytical approach can take us, and we're again forced to use some type of iterative root finding method in this span, but at least we've reduced it to about the simplest case we could hope for. There could still be multiple roots in this span, but our bounds are tight enough that this should be rare.

If your planet orbits much faster than your ship moves, the parabola will be nearly flat in this span and you can closely approximate it as a constant, using acos to find a very close first guess between `t_low` and `t_high`. Or if your ship travels much faster than your planet, the parabola will be nearly vertical the solution will be quite close to `t_low`. For intermediate cases like the example above, you might be able to approximate each curve as a straight line and iteratively refine from there.
> 4 votes

# Answer
You can solve this by expressing the position of the ship using parametric equations, expressing the position of the planet using the equation for one side of a circle, and solving a system of equations.

The ship's x position can be expressed as `x = vcos(theta)t`, where theta is the absolute value of the ship's angle below the horizontal.

The ship's y position can be expressed as `y = vsin(theta)t`.

The planet's x-position can be expressed as `sqrt(1 - (y - k)^2) + h`, where k is the translation of the circular orbit from the origin of the coordinate system.

Combining these equations yields: `vcos(theta)t = sqrt(1 - (vsin(theta)t - k)^2) + h`

To make this a system of equations, the arc length traveled by the planet from a\_0 to a\_0 + theta is equal to s\_0t(2 * pi * r). Due to the same-side angles theorem, this theta is the same as the ship's theta below the horizontal.

The arc length can be given by the equation: **Assume o is theta for the rest of this answer.**

```
integral(from 0 to (a_0 + theta))(sqrt(1 - (dr/do)^2)dx - integral(from 0 to
a_0)(sqrt(1 - (dr/do)^2)dx.

```

The equation for the circle is `r^2 - 2rr_0cos(o - o_2) + r_0^2 = a^2`.

(r\_0, o\_2) is the location of the center of the circle

```
dr/do = (2r_0rcos(o - o_2))/(2r + 2r_0sin(o))

```

Finally,

```
integral(from 0 to (a_0 + theta))(sqrt(1 - (dr/do)^2)dx - integral(from 0 to
a_0)(sqrt(1 - (dr/do)^2)dx = s_0t(2 * pi * r)

```

The above equation most likely will require the trapezoidal rectangular approximation method or Simpson's approximation method in order to solve the integrals.

After solving for t, substitute t into the two ship-position equations to get the x and y positions of the collision.
> -1 votes

---
Tags: mathematics, collision-prediction
---


# Question
Title: Bullet uses host's camera to tell where to fire rather than using client's camera
# Problem

In my 2d top-down multiplayer game, whenever the client player fires a bullet, the bullet is supposed to go towards the direction of the clients mouse. However, when the client fires, it goes towards the direction of the host's mouse, despite having locally disabled all cameras other than the camera attached to the player.

# Scripts

*This script is attached to the player.*

For disabling the camera - `if(!isLocalPlayer) {cam.enabled = false; return;}`

---

*This script is attached to the player.*

For spawning in the bullet

```
    void Update () {
    if (!isLocalPlayer)
        return;

        if (fireRate == 0)
    {
        if (Input.GetButtonDown("Fire1"))
        {
            Shoot();
        }
    } else
    {
        if (Input.GetButton("Fire1") && Time.time > timeToFire)
        {
            timeToFire = Time.time + 1 / fireRate;
            Shoot();
        }
    }
}

public void Shoot ()
{
    Debug.Log("Arrived at Shoot()");

    Instantiate(BasicBullet, firePoint);
}

```

---

*This script is attached to the bullet.*

For firing the bullet

```
Attack attack;
Vector3 targetCursorDestination;
Camera camera;

private float speed;
private float floatTime;
private float damage;
private Vector3 direction;

private void Awake() {
    GameObject MagePlayer = GameObject.Find("Player Red Mage(Clone)");
    attack = MagePlayer.GetComponent<Attack>();

    camera = attack.transform.GetChild(1).GetComponent<Camera>();

    targetCursorDestination = camera.ScreenToWorldPoint(Input.mousePosition);

    transform.SetParent(null);
    gameObject.layer = 9;
}

void Start () {
    speed = attack.speed;
    floatTime = attack.floatTime;
    damage = attack.damage;

    direction = targetCursorDestination - transform.position;
    direction.Normalize();

    StartCoroutine(WaitingBullet(0));
}

IEnumerator WaitingBullet(float waitTime)
{
    //Set direction
    Vector3 targ = targetCursorDestination;
    targ.z = 0f;

    Vector3 objectPos = transform.position;
    targ.x = targ.x - objectPos.x;
    targ.y = targ.y - objectPos.y;

    float angle = Mathf.Atan2(targ.y, targ.x) * Mathf.Rad2Deg;
    transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle));

    yield return new WaitForSeconds(floatTime);
    // give the bullet some velocity to fly off in its set direction
    GetComponent<Rigidbody2D>().velocity = direction * (speed);

    yield return null;
}

```

# Answer
Upon awake you are using `GameObject.Find("")` to get the reference to a player character.

This provides the first `GameObject` of that name. Which in this case is the hosts character. By changing it to assigning the `Attack` class on instantiate it will solve this by specifying the correct instance. See below for the updated `Shoot()`

```
public void Shoot()
{
    // Create the bullet as a Gameobject we can reference from a prefab.
    GameObject Bullet = Instantiate(bulletPrefab, firePoint) as GameObject;
    // Assign the correct instance of the Attack script.
    Bullet.GetComponent<BasicBullet>()._Attack = this.GetComponent<Attack>();
    // Set the bullets parent as null.
    Bullet.transform.SetParent(null);
}

```

When it comes to `BasicBullet`, it appears that your `Awake()` function can be removed split into the `Start()` and the `Shoot()` functions, see below to see how I have altered it to use the current player camera.

```
void Start()
{
    // Get the reference to the correct Camera using Attack Instance
    _Camera = _Attack.transform.GetChild(1).GetComponent<Camera>();
    // Get required Destination from the Mouse Pointer
    targetCursorDestination = _Camera.ScreenToWorldPoint(Input.mousePosition);

    gameObject.layer = 9;

    direction = targetCursorDestination - transform.position;
    direction.Normalize();

    StartCoroutine(WaitingBullet(0));
}

IEnumerator WaitingBullet(float waitTime)
{
    //Set direction
    Vector3 targ = targetCursorDestination;
    targ.z = 0f;

    Vector3 objectPos = transform.position;
    targ.x = targ.x - objectPos.x;
    targ.y = targ.y - objectPos.y;

    float angle = Mathf.Atan2(targ.y, targ.x) * Mathf.Rad2Deg;
    transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle));

    yield return new WaitForSeconds(_Attack.floatTime);
    // give the bullet some velocity to fly off in its set direction
    GetComponent<Rigidbody2D>().velocity = direction * (_Attack.speed);

    yield return null;
}

```

For this test I did set it up to use `Monobehaviour` not `NetworkBehaviour`. This had 2 cameras in the scene instead and the 2 players that called fire got the correct camera reference.
> 0 votes

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


# Question
Title: How can i use draw gizmos to draw dots between each waypoints?
```
private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.blue;

        for (int i = 0; i < waypoints.Length; i++)
        {
            Gizmos.DrawLine(transform.position, target.position);
        }
    }

```

Before that i'm not sure how to draw at all between all the waypoints.

Instead line maybe to draw spheres or something else and scale it to dots/points ? And i also want to be able to set and change the number of dots/points between each two waypoints.

For example from waypoints\[0\] to waypoint\[1\] to draw 30 dots and from waypoints\[1\] to waypoints\[2\] 10 dots or just the same maount of dots between all waypoints.

For not not curves lines only straight lines like showing the path between the waypoints in game view.

# Answer
> 3 votes
If you found methods such as **DrawLine**, then you would find more methods on the Gizmos API, such as **DrawWireSphere** and **DrawSphere**. You should always consult Unity's API.

To draw lines between each waypoint, it's easy, the number of lines, or intermediates of a number of waypoints its always **(the number of waypoints) - 1**, so you cando something like this:

```
for(int i = 0; i < _waypointsQuantity; i++)
    {
        for(int j = (i + 1); j < _waypointsQuantity; j++)
        {
            Gizmos.DrawLine(_waypointsPositions[i], _waypointsPositions[j]);
        }
    }

```

# Answer
> 1 votes
I agree with @LinkWindcrafter. Just the other way around. As you need to draw dots, relatively close to spheres.

```
float radiusOfDot = 0.1f;
//if you want to add spacing, just iterate i = i+2
for(int i = 0; i < _waypointsQuantity; i++)
{
    Gizmos.color = Color.yellow;
    Gizmos.DrawSphere(_waypointsPositions[i], radiusOfDot );
}

```

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


# Question
Title: How can i change direction each time one direction?
I have two scripts the first one is class not monobehaviour:

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

public class LightsEffects
{
    private Renderer[] renderers;
    private float lastChangeTime;
    private int greenIndex = 0;
    private bool shouldChangeDirection = false;

    public void LightsEffect(List<GameObject> objects, Color instantiateColor, Color colorEffect)
    {
        renderers = new Renderer[objects.Count];
        for (int i = 0; i < renderers.Length; i++)
        {
            renderers[i] = objects[i].GetComponent<Renderer>();
            renderers[i].material.color = Color.red;
        }

        // Set green color to the first one
        greenIndex = 0;
        renderers[greenIndex].material.color = Color.green;
    }

    /// <summary>
    /// Running the effect
    /// </summary>
    /// <param name="isReversed">Changing the lights movement directions - false = forward, true = backward.</param>
    public void LightsEffectCore(float delay, bool isReversed)
    {
        // Change color each `delay` seconds
        if (Time.time > lastChangeTime + delay)
        {
            lastChangeTime = Time.time;

            // Set color of the last renderer to red
            // and the color of the current one to green
            renderers[greenIndex].material.color = Color.red;

            if (shouldChangeDirection)
            {
                Array.Reverse(renderers);
                isReversed = !isReversed;
            }

            greenIndex = (greenIndex + 1) % renderers.Length;
            renderers[greenIndex].material.color = Color.green;
        }
    }
}

```

And in this script the part i'm trying to set what direction is:

```
if (shouldChangeDirection)
                {
                    Array.Reverse(renderers);
                    isReversed = !isReversed;
                }

```

The problem is that i'm using this class in another monobehaviour script:

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

public class Waypoints : MonoBehaviour
{
    public Transform traveller;
    public GameObject[] waypoints;
    public Transform nextWaypoint;
    public float moveSpeed = 10f;
    public float slowDownSpeed = 3f;
    public float rotationSpeed = 1f;
    public float distancetoRotate = 3f;
    public bool random = false;
    public bool reverse = false;
    public int howmanylight = 5;
    public Generatenumbers gn;
    public LightsEffects lightseffect;
    public bool changeLightsDirection = false;

    private int targetsIndex = 0;
    private Vector3 originalPosition;
    private List<GameObject> objects = new List<GameObject>();

    private bool rotateNumber = false;
    private int currentIndex = 0;

    // Use this for initialization
    void Start()
    {
        waypoints = GameObject.FindGameObjectsWithTag("Waypoint").OrderBy(go => go.name).ToArray();
        if (random == false)
        {
            targetsIndex = 0;
        }
        else
        {
            targetsIndex = UnityEngine.Random.Range(0, waypoints.Length);
        }
        originalPosition = traveller.position;

        GameObject go1 = GameObject.CreatePrimitive(PrimitiveType.Sphere);
        duplicateObject(go1, howmanylight);

        lightseffect = new LightsEffects();
        lightseffect.LightsEffect(objects, Color.red, Color.green);
    }

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

        if (rotateNumber == true)
        {
            gn.newTexts[currentIndex].transform.Rotate(Vector3.up, 10 * 50 * Time.deltaTime);
        }

        lightseffect.LightsEffectCore(0.1f, changeLightsDirection);
    }

    private void WayPointsAI()
    {
        if (targetsIndex == waypoints.Length)
            targetsIndex = 0;

        nextWaypoint = waypoints[targetsIndex].transform;
        float distance = Vector3.Distance(traveller.transform.position, nextWaypoint.transform.position);
        traveller.transform.rotation = Quaternion.Slerp(traveller.transform.rotation, Quaternion.LookRotation(nextWaypoint.position - traveller.transform.position), rotationSpeed * Time.deltaTime);

        if (reverse == true)
        {
            var targetAngles = traveller.transform.eulerAngles + 180f * Vector3.up;
            traveller.transform.eulerAngles = Vector3.Lerp(traveller.transform.eulerAngles, targetAngles, rotationSpeed * Time.deltaTime);
            var lastWaypoint = waypoints[currentIndex];
            Array.Reverse(waypoints);
            reverse = false;
        }

        if (distance < distancetoRotate)
        {
            traveller.transform.position += traveller.transform.forward * slowDownSpeed * Time.deltaTime;
        }
        else
        {
            traveller.transform.position += traveller.transform.forward * moveSpeed * Time.deltaTime;
        }
        if (distance < nextWaypoint.transform.localScale.magnitude)
        {
            rotateNumber = true;
            currentIndex = targetsIndex;

            if (random == false)
            {
                targetsIndex++;
            }
            else
            {
                targetsIndex = UnityEngine.Random.Range(0, waypoints.Length);
            }
        }
    }

    public void duplicateObject(GameObject original, int howmany)
    {
        howmany++;
        for (int i = 0; i < waypoints.Length - 1; i++)
        {
            for (int j = 1; j < howmany; j++)
            {
                Vector3 position = waypoints[i].transform.position + j * (waypoints[i + 1].transform.position - waypoints[i].transform.position) / howmany;
                GameObject go = Instantiate(original, new Vector3(position.x, 0, position.z), Quaternion.identity);
                go.transform.localScale = new Vector3(0.3f, 0.1f, 0.3f);
                objects.Add(go);
            }
        }
    }
}

```

In the top of the waypoints script i have two lines:

```
public LightsEffects lightseffect;
public bool changeLightsDirection = false;

```

Then in the Start i'm creating instance for the LightsEffect:

```
lightseffect = new LightsEffects();

```

Then in the Update i want to be able to change the direction of the lights false/true states:

```
lightseffect.LightsEffectCore(0.1f, changeLightsDirection);

```

The problem is that no matter if changeLightsDirection is false or true since in the Lights Effect class i'm using: shouldChangeDirection and it's true all the time.

Anyway it's not working when the game is running and i change the changeLightsDirection state in the waypoints script it's not effecting the LighsEffect direction it's not reversing the array each time.

In the Lights Effect class/script i'm using:

```
if (shouldChangeDirection)

```

Since i want to track the state of the array reversing. What i did before was: is just checking if isReversed false or true but then if it's on true or false state all the time it will keep reversing the array non stop.

I messed up all the flags in both scripts.

# Answer
Ok. Let me try to describe what I think of the problem:

you have a flag to keep track if you should change direction in this method call:

```
private bool shouldChangeDirection = false;

```

then you are passing it to the method

```
lightseffect.LightsEffectCore(0.1f, changeLightsDirection);

```

to base reverse operation on it.

---

Here is what I think you should do:

Change method definition to this:

```
public void LightsEffectCore(float delay, ref bool isReversed)

```

Notice the `ref` keyword, it will modify the variable passed as the parameter.

Now in `LightsEffectCore()` method:

```
if (!isReversed)
{
    Array.Reverse(renderers);
}

isReversed = !isReversed;

```

And remove

```
private bool shouldChangeDirection = false;

```

from `LightsEffects` class as it's not being used anymore.

---

**UPDATE:**

You don't need to reverse the array, alternatively, you can use *First* and *Last* elements in the array using `Linq`:

firstly, add `using System.Linq;` at the start of the file.

then use this code:

```
if (isReversed)
{
    renderers.Last().material.color = Color.green;
    greenIndex = renderers.Length-1;
}
else
{
    renderers.First().material.color = Color.green;
    greenIndex = 0;
}

```

Hope this helps :)
> 1 votes

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


# Question
Title: Skill vs. Luck, the ratio and its measurement
Gamer buddies, is there a term to describe the level of variance in a game, in comparison to luck. The card game war would have 0 skill and 1.0 luck because the player cannot affect the game. I can't think of something that has 1.0 skill. At first I thought Spelling Bee, but the words chosen for each contestant is randomly chosen suggesting some luck involved... What ratios do different games have, and how can those ratios be accurately measured? What metrics could be used to accurately measure such a ratio? I'd also like to hear of any 1.0 skill games if anyone can think of one.

To reiterate the question clearly: does there exist such a measurement and if so what is it? Furthermore is there a term for the target of this measurement, so we can have a discussion using a noun.

EDIT: the term luck is used to describe the level of effect that chance, i.e. random events, have in affecting who the winner is. I appreciate everyone's responses.

# Answer
*This answer assume familiarity with normal distributions and standard deviations.*

A simple but usually reasonable assumption is that we can describe the outcome of a game as a random event where player1 wins if player1's skill plus a normal distributed random variable is greater than player2's skill. The standard deviation of that normal distribution can be compared to the difference between the two player's skills, and for a larger group of players we can compare the standard deviation of the normal distribution to the standard deviation of the skill levels of that player group.

Thus if we for instance have a group of players where the standard deviation of those players's skills is double the standard deviation of the luck of the game we could with some reason say that the game for this group is 1/3 luck and 2/3 skill, but this is only valid for that specific group of players, there is no universal way to measure luck versus skill in a game.

## Edit: Some examples to illustrate the difficulties of the question

All games for two players.

**Flip and choose**
First a coin is flipped to determine who goes first, then each player in turn choose a number from 1 to 10. Whoever choose the biggest number wins, in case of a draw the player who started wins.

**Gomoku with coin flip**
First a coin is flipped to determine who goes first, then the players play a standard match of Gomoku on a 15x15 board, whoever wins that game wins.

### Analysis

Intuitively we'd say that Flip and choose is a game of luck, an average person would figure the optimal play before even playing a single round, so effectively the coin flip is all that matters.

Gomoku is game of skill, an average person will not be able to produce optimal play. Still, starting is an advantage so at least the flip of the coin must count for some luck in the final verdict.

With optimal play Gomoku is a win for the player who goes first, it is also a solved game, so a computer equipped with the solution database will always win if it is allowed to go first. Thus to computer players both games are trivial extensions to a standard coin flip, whoever wins the flip wins the game. This would suggest that they are both games of 100% luck. To reach any other conclusion we must consider a player base of less skill.
> 6 votes

# Answer
> does there exist such a measurement and if so what is it?

**No**, no such measurement exists. While you may be able to come up with a metric for skill. You'll be hard pressed to come up with a metric for luck (unless it's *controlled* luck). However, the two metrics would likely be different enough that you're essentially taking the ratio of apples/oranges. Further, the metrics will vary from game to game, so comparing ratios between two games is comparing apples/oranges to GI Joes/cats.

However, there are ways to decide if a game is a game of skill or a game of chance, at least from juridical point of view. Specifically, gambling in law. A number of states in the US allow people to pay money to enter games of skill, but not games of chance (or at least significantly limit the amount of money that can be spent on games of chance). There is a paper on the topic, but the All Games of Chance website has a decent definition of how these are legally categorized:

> There are two main differences between games of chance and games of skill. The first difference is who the player is playing against. When a player is playing against the house, it is a game of chance. When the player is pitted against other players, it is considered to be a game of skill. Also, if an individual can prove that a particular game involves the use of skill like strategies, statistics or math along with a factor of luck or chance, the game would be allowed and would be categorized as game of skill.
> 2 votes

# Answer
An important point to remember is that the importance of skill vs luck in determining the winner of a match increases as the number of *games* in a match increases. For example, this is why golf tournaments are 4 days long; the influence of luck (at the PGA level of play) is simply too great over a mere 18 holes.

This then provides a means of measuring the relative importance of luck vs skill: the number of matches (or alternatively, hours played) required to accurately determine the better player with a given statistical confidence. (95% would be the usual standard in such a case, as in the familiar *19 times out of 20*.)

Then we get:

1. Golf would be rated at 16 *rounds* (of 18 holes) or 64 hours (16 rounds of *4 standard hours* play) if you take the FedEx playoffs as the standard to accurately rate the players.
2. Backgammon is usually played to *best of 21* I believe in tournament play, but individual games would be averaging 2 or 3 due to the doubling cube. It's rating would then be about 7 - 10 matches, but only perhaps the same 7 - 10 hours.
3. Duplicate bridge would be rated about 2 sessions of 4 hours each, looking at the elimination rounds of larger team events like Vanderbilt and Spingold.
4. Chess world championships are regularly best of 12 (and I believe Go championships are similar).

Noting particularly from the latter point, even such seminal games of skill as Chess and Go are believed to possess a considerable element of luck *per individual game*, when played at a professional level. This would seem to be borne out by the extreme rarity of *sweeps* in such competitions.

**Update**:
A confound when using *number of hours of play* is that organizing committees may have unstated reasons for extending the length of individual games. My personal belief is that the overall quality of chess games at the world level would not decrease much if the allotted time were halved. However, there seems to be the unstated intent to showcase **all** of the individual games as *best instances* of play, leading to the players having more clock time than might be strictly necessary to determine the best player. (This is not necessarily wrong, simply a complication to note when measuring relative importance of skill vs luck.)

For example, Chess and Go matches extend to an almost obscene number of hours, clearly more than necessary to determine the best player given the, both believed and evidenced, high ratio of skill to luck even in individual games. If the sole purpose of world championship matches were the determination of the best player, the number of play hours, and possibly the number of games, could be reduced for both of these games.
> 1 votes

# Answer
Back-of-the-Napkin approach:

1. Need a larger sample size and longer time series than you probably would suspect intuitively.
2. K.I.S.S.: How quickly do the winners and losers "revert to the mean?" If the mean "reversion/regression" is slow then skill plays a larger roll. If mean "reversion/regression" is fast then luck plays a more significant role in the outcome(s).
3. If the game is digital, and the code is locked, then trying to tease apart luck from skill is a waste of your time, since any algorithm imaginable could be shaping the outcomes.
> 1 votes

# Answer
Some measures have been proposed, see

The basic idea from the first paper is to estimate

`skill = (potential learning effect) / (potential learning effect + potential random effect)`

which gives skill as a number between 0 and 1. Alas, these effects are analytically computable only for "easy" games. For a one-player game, the above equation comes down to

`skill = (Gm - G0) / (Gu - G0)`

where the G's are the expected net gains of three players

> * '0': a beginner who plays the game in the naive way of somebody who has just mastered the rules of the game.
> * 'm': a real average player who can be thought to represent the vast majority of players.
> * 'u': a virtual average player whom we tell in advance (i.e. before he has to decide) the outcome of the chance elements.

As an example they calculate for American Roulette: Gu = 35 and Gm = -1/74, the latter corresponding a "simple" play (e.g. rouge/noir, pair/impair). The value for G0 is actually a matter of debate, even for this game. If the beginner goes for a simple strategy, then the skill is 0 obviously. However if G0 is for a non-simple strategy (e.g. plein, cheval, carre), then G0 is -1/37 (i.e. worse average loss.) So with the latter assumption, there is a minor potential for learning, so skill is 0.0004. I have to say I'm a little miffed that they use French terminology for the American Roulette; alas they source they cite for further details is in Dutch.

For Blackjack they derive from a computer simulation that Gm = 0.11, Gu = 27, and take G0 = -0.057 for a "mimic the dealer" strategy, and from that obttain a skill of 0.006.

For games where players compete directly and strategies like sandbagging or bluffing matter (these are the only games called multi-player games in game theory by the way), the second paper has a more sensible approach in that it considers players potentially changing strategy a source of randomness. They use the same skill formula as above (except that they calll the three types of players beginner, optimal and fictive player). The difference in their approach is that

> the expected gains for player i as an optimal player are given by his expected gains in the Nash equilibrium of the related two-person zero-sum game against the coalition of the other players

and for the "fictive" player they also assume that he knows the the outcome of the randomization process of his opponents.

Alas there aren't any examples that are intersting but simple enough to relate in detail here. They compute for a simplified version of drawpoker a skill of 0.22.

Both papers emphasise however that the exact skill value depends on the definition/assumption of beginners’ behavior.

An experimental approach is needed for more complex games of practical interest, e.g.

> Those players identified a priori as being highly skilled achieved an average return on investment of over 30 percent, compared to a -15 percent for all other players. This large gap in returns is strong evidence in support of the idea that poker is a game of skill.
> 1 votes

---
Tags: game-design, game-mechanics
---


# Question
Title: Jump function moves object horizontal after dash function
I have a dash function in my game as well as a jump function. Both of them works completely fine all by themselves. The jump works find and the dash works fine, however, I want to be able to jump cancel from my dash. During my dash, when I try to hit the jump button, the charater object moves horizontally instead of vertically. It almost acts as a second dash.

What I want to happen is the character to be able to jump vertically out of my characters dash. Can someone guide me in the right direction to my desired results?

```
if (keyboard_check(ord("D")) && !place_meeting(x + 2, y, obj_hitbox_wall)) {
    x += 2;
    image_xscale =+1;
    directionFacing = "Right";
}
if (keyboard_check(ord("A")) && !place_meeting(x - 2, y, obj_hitbox_wall)) {
    x -= 2;
    image_xscale =-1;
    directionFacing = "Left";
}
///// WALL HIT DETECTION START /////
if (!place_meeting(x,y+2,obj_hitbox_wall)){
    gravity = .25;
    grounded = false;
} else {
    vspeed = 0;
    gravity = 0;
    grounded = true;
    jumpDash = false;
}
///// WALL HIT DETECTION STOP /////

///// DOUBLE JUMP PROPERTIES START /////
if (grounded == false && jumped == true) {
    if (keyboard_check_pressed(vk_space)) {
        vspeed = 0;
        vspeed -= 5;
        jumped = false;
    }
}

if (grounded == true) {
    if (keyboard_check_pressed(vk_space)) {
        vspeed -=5;
        jumped = true;
    }
}
///// DOUBLE JUMP PROPERTIES END /////

///// DASH PROPERTIES START /////
if (dashed == false && keyboard_check_pressed(vk_shift) && jumpDash == false) {
    if (directionFacing = "Right") {
        vspeed = 0;
        gravity = 0;
        speed += 8;
        dashed = true;
    }

    if (directionFacing = "Left") {
        vspeed = 0;
        gravity = 0;
        if (grounded == true) {
            speed -= 8;
        } else {
            speed+=8;
        }
        dashed = true;
    }

}

if (dashed == true && directionFacing = "Right") {
     speed -= .4;
     direction = 0;
    if (speed <= 0) {
        dashed = false;
        gravity = .25;
        speed = 0;
    }
}

if (dashed == true && directionFacing = "Left") {
    if (grounded == true){
        speed += .4;
        direction = 0;
    } else {
        speed -= .4;
        direction = 180;
    }
    if (grounded == true && speed >= 0) {
        dashed = false;
        gravity = .25;
        speed = 0
    } else if (grounded == false && speed <= 0) {
        dashed = false;
        gravity = .25;
        speed = 0
    }
}
///// DASH PROPERTIES END /////

///// JUMP DASH PROPERTIES START /////
if (grounded == false && dashed == true) {
    jumpDash = true;
}
///// JUMP DASH PROPERTIES END /////

```

# Answer
> 4 votes
I would recommend trying to clean up and reduce the number of variables you are keeping track of, as more bugs are likely to develop.

But on to your question:

The problem you are seeing is that jumping out of a dash appears to be acting like a second dash rather than a jump. This would tell me that there is a problem around how you are setting `speed` and `vspeed`.

The only place you are setting the character to move at "dashing speed" is in the dash block, which means this has to be evaluating to true:

```
if (dashed == false && keyboard_check_pressed(vk_shift) && jumpDash == false) {

```

So we can break this down to try to understand how that may resolve to true when you don't expect it to.

First, let's look at how `dashed == false` could evaluate to true.

The only places you are setting dashed to false are in this block (I've removed some of the code to expose the logic a little more clearly):

```
if (dashed == true && directionFacing = "Right") {
    if (speed <= 0) {
        dashed = false;
        gravity = .25;
        speed = 0;
    }
}

if (dashed == true && directionFacing = "Left") {
    if (grounded == true && speed >= 0) {
        dashed = false;
        gravity = .25;
        speed = 0
    } else if (grounded == false && speed <= 0) {
        dashed = false;
        gravity = .25;
        speed = 0
    }
}

```

Let's summarize the conditions. We set dashed to false if:

1. Player is dashing right, and speed \<= 0
2. Player is dashing left and they are grounded with speed \>= 0
3. Player is dashing left and they are not grounded with speed \<= 0

Next piece of logic is:

```
keyboard_check_pressed(vk_shift)

```

If you press shift, this is true.

Last piece is:

```
jumpDash == false

```

The only place you set this to false is in your collision logic:

```
if (!place_meeting(x,y+2,obj_hitbox_wall)){
    gravity = .25;
    grounded = false;
} else {
    vspeed = 0;
    gravity = 0;
    grounded = true;
    jumpDash = false;
}

```

So if the player is grounded, jump dash stays false.

The only variable to this bug seems to be how the `speed` variable is being set.

Putting it all together, it appears to me that this bug may only affect the player when moving `left`. My evidence to support this claim:

Player dashes left while grounded (hits this block of code):

```
    if (directionFacing = "Left") {
        vspeed = 0;
        gravity = 0;
        if (grounded == true) {
            speed -= 8;
        } else {
            speed+=8;
        }
        dashed = true;
    }

```

At this point `speed -= 8` is hit and the player how has `speed <= 0`

While dashing, the player tries to jump by hitting space, triggering this block of code:

```
if (grounded == true) {
    if (keyboard_check_pressed(vk_space)) {
        vspeed -=5;
        jumped = true;
    }
}

```

You don't include the code where the player is actually being moved based on these variables, but since `vspeed -= 5` was hit, I assume the player will be moved off of the ground.

After one loop, the collision check sees that the player is no longer grounded:

```
if (!place_meeting(x,y+2,obj_hitbox_wall)){
    gravity = .25;
    grounded = false;
} else {
    vspeed = 0;
    gravity = 0;
    grounded = true;
    jumpDash = false;
}

```

At this point we are in this state (roughly):

* `directionFacing = "Left"`
* `dashed = true`
* `speed <= 0`
* `grounded = false`

This sets us up to fall into this block of code:

```
if (dashed == true && directionFacing = "Left") {
    if (grounded == true){
        speed += .4;
        direction = 0;
    } else {
        speed -= .4;
        direction = 180;
    }
    if (grounded == true && speed >= 0) {
        dashed = false;
        gravity = .25;
        speed = 0
    } else if (grounded == false && speed <= 0) {
        dashed = false;
        gravity = .25;
        speed = 0
    }
}

```

Specifically this piece will be triggered:

```
} else if (grounded == false && speed <= 0) {
   dashed = false;
   gravity = .25;
   speed = 0
}

```

Which will set `dashed = false`

Once that happens, if you're still holding down `vk_shift`, the dash condition is now true again:

```
if (dashed == false && keyboard_check_pressed(vk_shift) && jumpDash == false)

```

Which will result in a dash instead of continuing to jump.

It looks like if you were to let go of shift, and then press space, you'd be able to jump out of a dash as expected.

Hopefully my reasoning through this made sense. There may be a couple gaps here since I don't know exactly how the variable are being used when your game is stepping the world.

---
Tags: game-maker
---


# Question
Title: AudioClip is empty saving recording from Microphone
EDIT: I updated the code to what I have currently. I'm not sure why but, the editor and my platform complained when I put the WWW in a co-routine, it seems to load the audio clips to the object but I cannot play them. In a script attached to the object I wait until the Audio Clip is loaded before I try to play it.

So I am trying to record some Audio through the microphone and then save an AudioClip to the disk as a .wav file and also save the filepath as a playerpref and then later I can come back and load the string into a url but, for some reason the Audio Clip doesn't get loaded properly as I can see that there is an audio clip on my audio source in runtime but, it has no name and it has no sound on it. **However, when I press play in the inspector I can hear my sound**

I am using SavWav.cs to save my audio clips to .wav files.

Here is the url(filepath) I am sending to my load method:

```
string filename = string.Format(@"CapturedAudio{0}_n.wav", Time.time);
string filepath = Path.Combine(Application.dataPath, filename);

```

Here is the method I am using to get the AudioClip:

```
private void SpawnObject(string savedNames, Vector3 savedPositions, Quaternion savedRotations)
{

        GameObject cubeToSpawn = Instantiate(cube, savedPositions, savedRotations);
        WWW www = new WWW("file:///"+savedNames);
        cubeToSpawn.GetComponent<AudioSource>().clip = www.GetAudioClip(false, false, AudioType.WAV);

}

```

The obj is just a cube with an AudioSource attached to it that I instantiate prior to calling this method above.

The filepath works fine for saving but, for some reason it doesn't want to load the audio clip. Any help would be greatly appreciated.

# Answer
Well, after a little more debugging I found that I was calling `Microphone.End` before I was saving the clip and also because I had my `StopRecording()` function containing `Microphone.End(deviceName)` on a button it was referencing my device name as null so it was never ending the Microphone and I assume this is what was really causing all of the problems.
> 1 votes

# Answer
I had better luck saving to the resources folder then loading from there.

`void SaveRecording(AudioSource aud)
{
 SavWav.Save(Application.persistantDataPath + "/Resources/" + aud.clip.name, aud.clip);
}`

and then load

```
AudioClip _clip = Resources.Load(_name) as AudioClip;
    AudioSource _aud = GetComponent<AudioSource>();
    _aud.clip = _clip;
    _aud.Play();

```
> 0 votes

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


title: Animation after enemy spawns

text:
# Question
Title: Animation after enemy spawns
right now in my game, four enemies spawn in four spawn points with a delay, but what I want to do is that if you don't kill the enemy after a couple seconds, an animation (it's an animation of a scratch, basically to let the player know it has been attacked) appears.

Right now I have a script that display an image (it's an image because I was testing the scripts), but now I want to change the image for the animation but after trying and failing a lot of times I decided to ask here, and hopefully someone can help me.

This is the script of the "attack", and it's attached to the enemy prefab:

```
public Image TargetImage;

void Start ()
{
    TargetImage.enabled = false;
}

public void spawnAttack(){
    StartCoroutine (playerIsAttacked (5, TargetImage));
}

public IEnumerator playerIsAttacked (float t, Image im)
{
    yield return new WaitForSeconds (t);
    TargetImage.enabled = true;
}

}

```

and this is in the timed spawn script:

```
public class TimedSpawn : MonoBehaviour {

public GameObject spawnee;
public bool stopSpawning;
public float spawnTime;
public float spawnDelay;

void Start () {
    InvokeRepeating ("SpawnObject", spawnTime, spawnDelay);
}

public void SpawnObject (){
    GameObject newSpawn = Instantiate (spawnee, transform.position, transform.rotation) as GameObject;
    newSpawn.GetComponent <enemyAttack> ().spawnAttack ();

    if (stopSpawning) {
        CancelInvoke ("SpawnObject");
    }
}

```

}

# Answer
You need an Animator on your enemy object as well as an animation controller. You also need to create an idle clip and an attack clip for it, then an animation trigger "isAttacking".

Set the trigger on a timer of some sort, and set up your animation controller to play the attack animation when the trigger is set off.

https://docs.unity3d.com/ScriptReference/Animator.html

https://docs.unity3d.com/Manual/AnimationClips.html

https://docs.unity3d.com/Manual/AnimatorControllers.html

https://docs.unity3d.com/ScriptReference/Animator.SetTrigger.html

Here's the docs, otherwise find a simple tutorial on YouTube. It's not as confusing as I made it seem!
> 0 votes

---
Tags: unity, animation, spawning
---


# Question
Title: TModLoader reports a file to be missing when its not
I'm Making a terraria Mod that adds all sorts of Junk, but one single issue keeps hitting me: It Thinks one of the Items needed does not exist.

The error I seem to be getting is:

```
 The item Copper Shortsword Stack of twenty does not exist in the mod GrandFinale.
If you are trying to use a vanilla item, try removing the first argument.
   at Terraria.ModLoader.ModRecipe.AddIngredient(Mod mod, String itemName, Int32 stack)
   at GrandFinale.Items.OmegaHeadbutt.AddRecipes() in c:\Users\sjpar\Documents\My Games\Terraria\ModLoader\Mod Sources\GrandFinale\Items\OmegaHeadbutt.cs:line 32
   at Terraria.ModLoader.RecipeHooks.AddRecipes()

```

Even Though The item exists here (full code)

```
using System.Collections.Generic;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;

namespace GrandFinale.Items
{
    public class TwentyStack : ModItem
    {
        public override void SetDefaults()
        {
            item.name = "Copper Shortsword Stack of twenty";
            item.width = 40;
            item.damage = 1;
            item.melee = true;
            item.height = 40;
            item.toolTip = "This is a modded sword.";
            item.useTime = 20;
            item.useAnimation = 20;
            item.useStyle = 1;
            item.knockBack = 6;
            item.value = 10000;
            item.rare = 2;
            item.autoReuse = true;
            item.UseSound = SoundID.Item7;

        }
        public override void AddRecipes()
        {
            ModRecipe recipe = new ModRecipe(mod);
            recipe.AddIngredient("Copper Shortsword", 20);
            recipe.AddTile(TileID.WorkBenches);
            recipe.SetResult(this);
            recipe.AddRecipe();
        }
    }
}

```

And Is Being Called By this Other Item:

```
using System.Collections.Generic;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;

namespace GrandFinale.Items
{
    public class OmegaHeadbutt : ModItem
    {
        public override void SetDefaults()
        {
            item.name = "Omega Slash";
            item.damage = 10000;
            item.melee = true;
            item.width = 40;
            item.height = 40;
            item.toolTip = "The Sword Of The Ancients. Using it deals 499 Damage to the user, to deal 10,000 Base Damage";
            item.useTime = 20;
            item.useAnimation = 20;
            item.useStyle = 1;
            item.knockBack = 6;
            item.value = 10000;
            item.rare = 12;
            item.UseSound = SoundID.Item7;
            item.autoReuse = true;
        }

        public override void AddRecipes()
        {
            ModRecipe recipe = new ModRecipe(mod);
            recipe.AddIngredient(null, "Copper Shortsword Stack of twenty", 2);
            recipe.AddIngredient("Flask of Poison", 2);
            recipe.AddTile(TileID.WorkBenches);
            recipe.SetResult(this);
            recipe.AddRecipe();
        }
    }
}

```

(The Null on the line beginning tells of recipe.AddIngredient tells TModLoader that the item needed for crafting belongs to a Mod (not vanilla))

Any Help?

# Answer
You are getting an error because you are messing up the C# syntax in the mod recipes section (You can't have "" in () thats just how it works m8) You messed up at these places: recipe.AddIngredient("Copper Shortsword", 20); recipe.AddIngredient(null, "Copper Shortsword Stack of twenty", 2); recipe.AddIngredient("Flask of Poison", 2);
> -2 votes

---
Tags: c#
---


# Question
Title: Why don't Sin and Cos give expected results when rotating off axis around a non uniform shape?
When I rotate a rectangle and draw straight lines along it's edge using Sin and Cos the lines don't follow the edge as the angle approaches 45 degrees, why? The exact same code works just fine when I use it on a square. See Gif:

Left object has the same width and height, No distortion of angles. Right side has larger X axis and lots of distortion.

**Why does this happen and how do I prevent it?**

Unity code:

```
[RequireComponent(typeof(Image))]
class rotation : MonoBehaviour
{
    [SerializeField]
    private float left = 180f, up = 90f;

    private void OnDrawGizmosSelected()
    {
        RectTransform rect = GetComponent<RectTransform>();

        Vector3[] corners = new Vector3[4];
        rect.GetWorldCorners(corners);
        float rot = transform.eulerAngles.z;

        Gizmos.color = Color.red;
        Gizmos.DrawLine(corners[3], corners[3] + new Vector3(
                Mathf.Cos((left + rot) * Mathf.Deg2Rad) * rect.rect.width,
                Mathf.Sin((left + rot) * Mathf.Deg2Rad) * rect.rect.height));

        Gizmos.color = Color.blue;
        Gizmos.DrawLine(corners[3], corners[3] + new Vector3(
            Mathf.Cos((up + rot) * Mathf.Deg2Rad) * rect.rect.width,
            Mathf.Sin((up + rot) * Mathf.Deg2Rad) * rect.rect.height));
    }
}

```

# Answer
The length of the lines must always equal the length of the side. If you however multiply `sin(angle)` by the width of the rect and `cos(angle)` by the height, then if the angle point upwards, then the length of the line will be equal to the width of the rectangle and if the angle points sideways, then the length of the line will be equal to the height of the rectangle.

Do this instead:

```
Gizmos.DrawLine(corners[3], corners[3] + new Vector3(
    Mathf.Cos((left + rot) * Mathf.Deg2Rad) * rect.rect.width,
    Mathf.Sin((left + rot) * Mathf.Deg2Rad) * rect.rect.width)); // Change is here

Gizmos.color = Color.blue;
Gizmos.DrawLine(corners[3], corners[3] + new Vector3(
      Mathf.Cos((up + rot) * Mathf.Deg2Rad) * rect.rect.height, // Change is here
      Mathf.Sin((up + rot) * Mathf.Deg2Rad) * rect.rect.height));

```
> 1 votes

---
Tags: unity, mathematics, angles
---


# Question
Title: Unity2D - Placing text HP and health bar over character sprite
I've got a 2D character sprite that I will move through a game board. I want to add over it, in a corner of the sprite, a Text object with the remaining HP of that character and also a health bar. I want those elements to move with the Character. Wherever the character moves, the UI follows.

I've tried adding a Text element in World Space and attaching it to the character sprite, but the Text is so huge that it's not displayed properly on top of it. I need to know how to adapt that text to the size of the sprite and how to make it follow it automatically. I guess that by setting the ch sprite as parent of the Text/canvas it would work, but I don't know how to get it working.

Thanks in advance

# Answer
```
public Vector2 WorldToCanvasPoint(Vector3 a_position)
{
    Vector2 viewport = Camera.main.WorldToViewportPoint(a_position);
    return Vector2.right * (viewport.x - 0.5f) * m_canvasRect.width + Vector2.up * (viewport.y-0.5f) * m_canvasRect.height;
}

```

This is what you are looking for. Put this code on your Canvas, it could be called "CanvasManager" and should be a singleton. You can get m\_canvasRect by doing:

```
this.GetComponentInParent<Canvas>().GetComponent<RectTransform>().rect;

```

Then you can create a "FollowTransform" script, with a

```
public Transform m_objectToFollow;

```

variable on it.

You put this script "FollowTransform" script on your HP Text, and add this:

```
public Transform m_objectToFollow;
private RectTransform m_rect;

void Start()
{
    m_rect = GetComponent<RectTransform>();

void Update()
{
    this.m_rect.anchoredPosition = CanvasManager.Instance.WorldToCanvasPoint(m_objectToFollow.position);
}

```

This way, the text will follow the transform you specified.

If you don't know how to create a singleton and what is it, you should search on google "Singleton design pattern". It's really useful and commonly used. Here's a way of doing it:

```
public class CanvasManager : MonoBehaviour {

    private static CanvasManager _instance;
    public static CanvasManager Instance { get { return _instance; } }

    void Start () {
        if (_instance != null && _instance != this)
        {
            Destroy (this.gameObject);
        }
        else
        {
            _instance = this;
        }
    }
}

```
> 3 votes

# Answer
You should read the Manual on World Space UI

For a health bar, the Slider component would be ideal. Your HealthBar component script would require a Slider, and Health component, make the canvas follow the transform, and set its value to the health of the object.
> 0 votes

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


title: Small collision engine

text:
# Question
Title: Small collision engine
How can I do AABB collision engine? What do I need? I need it to do a platformer game (don't want to use box2d etc.).

I tried to make it like this

```
void GameplayScreen::Update()
{
    ePlayer->Update();
    collision();
}

void GameplayScreen::Draw(SDL_Renderer *renderer)
{
    DrawMap(renderer);
    ePlayer->Draw(renderer);;
}

void GameplayScreen::DrawMap(SDL_Renderer *renderer)
{
    for (int y = 0; y < map.size(); ++y)
        for (int x = 0; x < map[y].size(); ++x)
            if (map[y][x] != 0)
            {
                SDL_Rect destRect;
                SDL_Rect srcRect;

                srcRect.w = 32;
                srcRect.h = 32;
                srcRect.x = blockID * srcRect.w;
                srcRect.y = 0;

                destRect.x = (x * 32);
                destRect.y = (y * 32 );  /
                destRect.w = 32;
                destRect.h = 32;

                vBlock[Earth]->Draw(renderer, srcRect, destRect);
            }
}

void GameplayScreen::Collision()
{
    for(int y = 0; y < map.size(); ++y)
        for(int x = 0; x < map[y].size(); ++X)
            if(map[y][x] != 0)
            {
                int mapX = x * 32;
                int mapY = y * 32;
                int mapW = x * 32 + 32; // I tried (x + 32) * 32 also
                int mapH = y * 32 + 32; // I tried (y + 32) * 32 also

                int playerX = ePlayer->getPosX();
                int playerY = ePlayer->getPosY();
                int playerW = ePlayer->getPosX() + ePlayer->getHitBoxX();
                int playerH = ePlayer->getPosY() + ePlayer->getHitBoxY();

                AABB aabb(mapX, mapY, mapW, mapH);
                if(aabb.chechCollision(playerX, playerY, playerW, playerH))
                {
                    //I don't know what do write here
                    //I wrote what I thought would be good

                    if(playerX <= mapW && playerX >= mapX)
                    {
                        std::cout<<"Player collision Left"<<std::endl;
                    }
                    else if(playerW >= mapX && playerW <= mapW)
                    {
                        std::cout<<"Player collision  right"<<std::endl;
                    }
                    else if(playerY <= mapH && playerH >= mapH)
                    {
                        std::cout<<"Player collision top" <<std::endl;
                    }
                    else if(playerH >= mapY && playerH <= mapH)
                    {
                        std::cout<<"player collision bot"<<std::endl;
                    }
                }
                else std::cout<<"NO COLLISION"<<std::endl;
            }
}

bool AABB::checkCollision(float x1, float y1, float w1, float h1)
{
    if ((x <= w1 && x >= x1)
            && (w >= x1 && w <= w1)
                && ((y <= h1 && h >= h1)
                    || h >= y1 && h <= h1)) // I tried here with &&
    {
        return true;
    }
    return false;
}

```

The problem with this is that, even if map\[y\]\[x\] == 0 =\> no collision.

The game says that there is a collision.

# Answer
I think you should use the (x0,y0) (x1,y1) co-ordinates of the rectangle instead of the width and height, which it seems like you're doing now. Rectangle collision is answered here https://stackoverflow.com/questions/2752349/fast-rectangle-to-rectangle-intersection.

Code Complete has a pretty good example of how to make a simple platformer http://codeincomplete.com/posts/tiny-platformer/.
> -1 votes

---
Tags: c++, 2d, collision-detection
---


# Question
Title: Memory accumulation in monogame. ‘Dispose’ and ‘Unload’ aren’t working
I'm having a huge problem with memory accumulation in all my games. This happened after switching from monogame 3.4 to 3.5 so I switched back. Then recently I went to 3.6(latest release) and started having the same problem again. I would switch back again but I need 3.6 rather than 3.4 for certain reasons.

I've tried both .Dispose() and .Unload() for the content but it seems to only release a small portion of what was previously loaded.

Here is the code

```
public void UnloadContent()
        {
            if (overworldContent != null)
            {
                overworldContent.Unload();
            }
        }

```

I've also done

```
public void UnloadContent()
        {
            if (overworldContent != null)
            {
                overworldContent.Dispose();
            }
        }

```

This is a picture of the memory usage from just going in and out of an area just a few times over the course of several minutes. A player could easily have multiple gigabytes taken up from playing for even just one hour if it goes from 86MB to 235MB in just 2 minutes

I seriously need help.

# Answer
Thanks for your suggestions everyone, I think I've figured it out. Instead of using just Unload() or Dispose() using both at once seems to help a great deal. After it accumulates a certain amount (around 250MB) it clears over 100MB all at once. I've also noticed that if I also set the ContentManager to null it will clear the memory even faster. My code looks like this now.

```
        if (overworldContent != null)
        {
            overworldContent.Unload();
            overworldContent.Dispose();
            overworldContent = null;
        }

```

Apparently after using Unload() it will still keep some junk in a scratchbuffer (whatever that is) and using the other method along with nullifying the ContentManager for that class will ensure that the rest gets cleared out.
> 1 votes

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


title: Issues with an event trigger in unity

text:
# Question
Title: Issues with an event trigger in unity
I am working on a 2D platformer and I am trying to do a character selection menu. I have and button with an event trigger that I use for shooting for the character. My problem is that when I switch to a new character the event trigger that is on the button goes blank and I can no longer shoot. I have tried instantiating the characters and having the SetActive to false. Is there a way to set the event trigger through code or if anybody has any other suggestions I would love to hear them.

Thanks!!

# Answer
> 1 votes
From what I understood of your issue, you need to dinamically change the Button's onClick property when a character is switched, right? So you need to get access to either that button or its onClick property (which is of type **ButtonClickedEvent**) and use **RemoveAllListeners** to remove any method assigned of previous characters, and then use **AddListener** to add the method of a new character.

AddListener receives an **UnityAction** which is a delegate of a parameterless void Method's signature, so you need to pass a pointer to a method of that signature. Example:

```
public class Character : MonoBehaviour
{
    public Button eventButton;

    public void OnCharacterChange()
    {
        eventButton.onClick.RemoveAllListeners();
        eventButton.onClick.AddListener(ButtonEvent);
    }

    void ButtonEvent()
    {
        //...
    }

    void ButtonEventWithParams(string args)
    {
        //...
    }
}

```

Now, if you would like to add a listener of a method with parameters, you'd need to make a UnityAction's signature method that calls that method with parameter, for you to avoid a creation of that intermediate method, you can either use Lambda Expressions, or do a delegate encapsulation (I think that's the way of calling it, it may be wrong). A quick example:

```
public class Character : MonoBehaviour
{
    public Button eventButton;

    public void OnCharacterChange()
    {
        eventButton.onClick.RemoveAllListeners();
        //eventButton.onClick.AddListener(ButtonEvent);

        /// With Lambda Expressions:
        eventButton.onClick.AddListener(=>{ ButtonEventWithParams("Hello"); });

        /// With delegate encapsulation:
        eventButton.onClick.AddListener(delegate{ ButtonEventWithParams("Hello"); });
    }

    void ButtonEvent()
    {
        //...
    }

    void ButtonEventWithParams(string arg)
    {
        //...
    }
}

```

You can check more reference on ButtonClickedEvent's API. Hope it helps.

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


# Question
Title: When does OpenGL Perform Perspective Divide
When does OpenGL divide by W? Is this done automatically within the vertex shader? It is my understanding that the vertex shader outputs the final vertex position, so I presume no transformations can be made after this point...

# Answer
> 4 votes
It's somewhere between the vertex and fragment shader (after the geometry shader and right before the fragment shader if you want to be specific). Since the fragment shader runs for each drawn pixel, the positions have to be divided by W by then. The division is automatic, you don't need to do it yourself.

Even if you wanted to, doing transformations after this is simply not possible. The fragment shader already has a set of pixels it needs to draw, nothing can change that.

---
Tags: opengl, perspective
---


title: phaser.io mouse cursor sprite

text:
# Question
Title: phaser.io mouse cursor sprite
I am trying to build a game and i want people to be able to select stuff with a pointer but i don't want it to be just an ugly looking default pointer so i wrote this code to try and get a image as it

first i loaded the image

```
game.load.image('selector', 'assets/img/pointer.png')

```

then I put it into my game

```
selector = game.add.sprite(game.world.centerX, game.world.centerY, 'selector')

```

and then in my render() function i do this

```
selector.x = game.input.x;
selector.y = game.input.y;

```

it moves fine with my mouse but with one problem

my game is designed so that i have to use a camera that follows my character because the map is bigger than the view

so since for some reason my sprite always starts at 0,0 it can only move 800x600px since thats all that the canvas sees the mouse in so i need a way to fix this but i'm not sure how to do this because i am new to phaser

# Answer
You can use JavaScript's pointer lock API.

First of all, it's still an experimental feature, so to be sure, you might need to check for compatibility and make sure there's a single working function:

```
if (!("pointerLockElement" in document || "mozPointerLockElement" in document || "webkitPointerLockElement" in document))
    alert("No pointer locking");

canvas.requestPointerLock = canvas.requestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;

```

Then request pointer lock and setup an eventhandler:

```
canvas.onclick = function () {
    canvas.requestPointerLock();
}

function changeHandler(e) {
    // Do something with e.movementX and e.movementY
    // These are also prefixed, so you may need to use e.mozMovementX, etc.
}

canvas.addEventListener("pointerlockchange", changeHandler);
canvas.addEventListener("mozpointerlockchange", changeHandler);
canvas.addEventListener("webkitpointerlockchange", changeHandler);

```
> 1 votes

---
Tags: javascript, gui, phaser
---


# Question
Title: Can't find Model Substance Painter - Lost in the Void
I must have zoomed out too far, turned the camera in the wrong direction, whatever. The model is lost, I cannot find it in the 3D View. This is a complex project and I don't want to start over. I have tried orthographic view and all known keyboard shortcuts. But I am still lost in the void and I can't find my 3D Model. I'm about to plant a bomb at Substance Painter HQ or at least give them a phone call wishing death on them all.

# Answer
> 1 votes
F recenters the camera on the object you're editing.

---
Tags: 3d, camera
---


# Question
Title: Unreal engine project not responding to key binding changes
I'm getting started with learning Unreal development, and I've created a new project based off the FPS C++ template.

I've changed the key mappings inside the DefaultInput.ini, rebuilt the Visual Studio solution, and rebuilt the project in the Unreal editor, but none of my changes are taking effect.

What step am I missing?

# Answer
You wouldn't normally edit the key bindings by changing the DefaultInput.ini. The best way to do it is use Project Settings inside the editor.

Got to Settings -\> Project Settings. A new box will open up with options down the left. One of these is "Input" which you can open up and set up your key bindings or game controller settings as per your requirements.
> 2 votes

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


# Question
Title: Why the spotlight is working only in scene view window but not in game view?
What i did is disabled in the Hierarchy the Directional Light. The Spotlight is child of the character so it will move with it.

Then in Window \> Lighting \> Settings

In the Spotlight i just changed the range and rotation a bit. It's strange since it's showing the light in the scene view but not in the game view not even when running the game.

And this is the Spotlight config:

# Answer
Found how to do it. In Window \> Lighting \> Setting: Skybox Material set it back to original: Default-Skybox then in Environment Lighting setting the color to black. Then in Environment Reflections: Intensity Multiplier set to 0 then in the Main Camera in the Inspector: Changing Clear Flags to SolidColor and changing the Back Ground color to black.

You can see all the settings in the next screenshot:
> 1 votes

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