# Question
Title: Bank ship left/right based on virtual joystick
I have a 3D game in Unity with a top-down camera view centered directly above a space ship. The ship always stays in the center of the screen, but it allows you to orbit a planet freely using an on-screen joystick. The movement around the sphere is working great, and the camera and ship both move together to orbit the planet.

With that being said, I would like to "bank" the ship left and right as you turn to add a more realistic flight affect. At most the ship will bank 45 degrees to either side, but the amount will be based on how hard they are turning which will come from the joystick as well (distance joystick is from its origin).

I'm having trouble figuring out a good formula for this rotation. I have tried many different things with varying results, but my thought was that I would determine which way the ship is turning first, either left or right. Then apply a hard coded 45 degree angle for now to the y-axis. This actually gets me mostly there. But it seems I need to flip this to the x-axis at times, and when the ship is flying in the opposite direction (pointing down) it seems everything gets mirrored? As you can see, I'm confused haha. Does anyone have any insight as to a better approach, or if you can see issues with my current approach? Thanks!

Here is a bit of code that I have tried:

The update method to apply the rotation:

```
public void Update()
{
    TurningDirection turningDirection = GetTurningDirection(); // See below for this
    float direction = turningDirection == TurningDirection.Left ? 1f : -1f;
    bankRotationAngle = 45f * direction;

    // Using 45 degrees here for now, but will eventually change this to come from the joystick as well to get the correct amount to bank based on how hard they are turning
    if (Mathf.Abs(bankRotationAngle) > 45f)
    {
       bankRotationAngle = 45f * direction;
    }

    transform.localEulerAngles = new Vector3(transform.localEulerAngles.x, bankRotationAngle, transform.localEulerAngles.z);
}

```

The `GetTurningDirection` method (this is based off an angle to capture their last/current angle to see if the ship is turning left or right):

```
 private TurningDirection GetTurningDirection()
 {
     // If it hasn't changed, return the current direction
     if (joystickAngle == lastJoystickAngle)
     {
         return turningDirection;
     }

     if (joystickAngle < lastJoystickAngle)
     {
         return TurningDirection.Left;
     }
     else
     {
         return TurningDirection.Right;
     }
 }

```

# Answer
> 0 votes
After a bit of thinking and playing around, I have come up with a solution to this for anyone that has a similar problem.

I first created a new empty game object as a child of my existing "ship" game object. I moved the mesh renderer from the ship to the new game object. I then applied the above logic to the new game object in a separate script, and adjusted only the local x-axis during the roll rotation and this works. The roll angle amount is determined based on how far the joystick is away from its center. This gives a nice smooth roll effect, while allowing the yaw calculations to be performed on the original ship game object which keeps the rotations separate.

I think this could also be done in one rotation using a Quaternion from a bit of research that I've done, but I wasn't able to get that working correctly in my situation.

---
Tags: unity, physics, rotation, joystick
---


# Question
Title: How to generate water pools on a 2D tile grid?
I'm coding a algorithm that generate a map, fixed size 2D matrix of tiles (32x32, 64x64, ...), for a game. The game map contains 2 elements, ground and water tiles. I'm trying to flood some water pools on the map, but I don't come to any ideal conclusion.

I can do it with this steps:

1. Fill the map with Ground
2. Get a random position (x,y)
3. Set (x,y) as Water
4. Walk on, in spiral sequence, from the (x,y) point to a limit of N random steps, setting randomly tiles as Water
5. Jump to step 2, making K more random water pools

This is a good approach? I think not! That algorithm will make pools with ground on the inside, with irregular borders and square shape. But I desire random shaped lakes.

Anyone can give me a idea of a better solution?

# Answer
> 14 votes
I would give it a try like that:

1. Generate a heightfield for your map (e.g. with perlin noise)
2. Determine a height which represents sea level
3. Fill all tiles below sea level with your water pool tile

# Answer
> 3 votes
I'm not sure why you would be setting the tiles randomly to water in your spiral sequence, since that would (as you point out) leave ground on the inside of the pools. If you changed all of the tiles you spiral on into water, then you would have a whole pool, but it would always turn out to be square-shaped.

Instead of a spiral from your selected point, you could do a Random Walk.

1. From the current tile, pick one of the four directions to move (up, down, left, right)
2. Move to that tile and mark it as a water tile.
3. Repeat until you've taken enough steps.

You could also limit the tiles you can walk to by only stepping towards ground tiles. In that case, you also want to have an exit from that loop for when you no longer have any valid directions to pick.

The downside to this method would be that (as seen in pictures on the link above) the walk could be very oddly shaped.

To smooth over that odd shape, you could then run something similar to the Rules in Conway's Game of Life. Replace the words "live neighbor" with "water", and adjust how many neighbors are needed to create water, and that should smooth out the larger irregularities made by a Random Walk.

Edited to add: I added this answer as an alternative to going through the more natural looking but more complex to code answer of Perlin Noise. That does produce much more interesting and natural-looking landscapes, I thought to suggest something similar in scope to what the original poster was doing already and that would give something a little different/better than their original algorithm

# Answer
> 2 votes
Another approach that ought to work is based on turning a 1d 'noise' function (Brownian motion or something like) into a closed path. Imagine that you wanted a perfectly circular pool; then a simple way of imagining that would be to express it in polar coordinates (r,θ) : r=C for some constant C. If you wanted to put a little wobble into the boundary, you could introduce a bit of a sine wave to it: something like r=C0+C1\*sin(θ), tracked for 0 \<= θ \<= 2\*π, where C1 is much less than C0 (you don't want to have too much wobble, after all!). But that's only a bit of low-frequency noise, and you want a little more wobble — and you want your wobbles to be out of phase with each other — so add more terms representing higher frequencies:

```
for (int idx=1; idx < NUM_COEFFICIENTS; idx++ ) {
  C[idx] = BASE_RADIUS*WOBBLE_FACTOR*rand[-1,1]/(idx*idx);
  phase[idx] = rand[0, 2*pi];
}
for (float theta = 0; theta < 2*pi; theta += SMALL_STE) {
  r = BASE_RADIUS;
  for (int idx = 1; idx < NUM_COEFFICIENTS; idx++) {
    r += C[idx] * sin(idx*theta+phase[idx]);
  }
  plot(r,theta);
}

```

Obviously there are a lot of constants to be fiddled with here (I would start with WOBBLE\_FACTOR around .2 or so and NUM\_COEFFICIENTS about 20), and you can look at producing bigger wobble (e.g., replacing the divide by (idx\*idx) with a divide by just idx so that the higher-frequency terms aren't as damped), but for the resolutions of pools you're talking about most of that will just vanish.

Note that this will (basically) produce the outline of a lake by drawing 'around' it; if you wanted to 'scanline' your lakes you could do it by just deciding whether the center of each cell in your grid is within the lake's outline - that is, whether its radius is less than the frequency sum at that point:

```
for ( int y = -MAX_LAKE_RADIUS; y <= MAX_LAKE_RADIUS; y++ ) {
  for ( int x = -MAX_LAKE_RADIUS; x <= MAX_LAKE_RADIUS; x++ ) {
    r = sqrt(x^2+y^2);
    theta = atan2(y,x);
    test_r = BASE_RADIUS;
    for (int idx = 1; idx < NUM_COEFFICIENTS; idx++) {
      test_r += C[idx] * sin(idx*theta+phase[idx]);
    }
    if ( r <= test_r ) {
      fill_lake(x,y);
    }
  }
}

```

This is somewhat similar to thalador's perlin-noise approach, except that we're building our noise function explicitly here (via its fourier transform, essentially) and using it to 'wobble' a 1d line (circle) rather than taking a level set.

# Answer
> 2 votes
One possibility is to use perlin noise as noted in the other answers, but just to share an alternative, I've also implemented this using probabilities before.

Coose the `center` and the `maxRadius` of the lake, and for each tile within that radius, use the following probability to determine whether it should be a water tile:

```
probability = 1 - (distanceFromCenter / maxRadius)

```

In other words, the probability of a tile being water increases the closest it is to the center. You can measure the distance either in a straight line, or using a manhattan distance. This gives the lake an overall round shape, but with enough variation because of the randomness involved.

To ensure that the lake is contiguous, start from the center which is guaranteed to be water, and call the function recursively for all neighbours, but only when the current tile is also water. This is enough to ensure that all the water is connected to each other.

Finally, to remove any ground tiles that remain on the inside of the lake, check this topic. In retrospective it might have been easier to use perlin noise though. :)

# Answer
> 2 votes
While I would recommend the heightmap answers, they may be more trouble than they're worth if you really don't want islands. In such cases in the past I have used a 'random floodfill'. The basic algorithm is:

1. Start with a point and a desired area.
2. Change the current point to water.
3. Add all of the current point's neighbors to a list
4. Sort the list by each entry's number of water neighbors.
5. Grab a (weighted) random item in the list as 'the current point'.
6. Return to step 2, unless the desired area has been covered.

This is easy to grasp and implement, except for step 5. How that is implemented changes the output considerably. One option is to use a geometric or exponential distribution, weighing the odds towards points with lots of (or fewer) water neighbors. Another option is to automatically fill in any points with 3 or 4 water neighbors, eliminating islands but flattening the coastline a bit.

```
//set up the pile of points
std::vector<Point> pile;
int covered_area = 0;

//push on the starting point
pile.push_back(points.get(start_x, start_y));

//keep adding water until we hit our desired area (or the whole map is filled)
while (pile.size() > 0 && covered_area < desired_area)
{
    //if there are any points with three or four neighbors, we should prioritize those by skipping this step
    if (pile.back().water_neighbors < 3)
    {
        //pick a point in the pile based on some distribution
        //int position = pile.size() - 1 - std::binomial_distribution<int>(pile.size() - 1, 0.5)(rng);
        std::uniform_int_distribution<> distribution(0, pile.size() - 1);
        int position = distribution(rng);

        //swap that point with the back
        std::iter_swap(pile.begin() + position, pile.rbegin());
    }

    //now pull off the top of the pile
    Point p = pile.back();
    pile.pop_back();

    //set it to water, update the area variable
    points.set(p.x, p.y, 1);
    ++covered_area;

    //now go through the list and remove any points that neighbor this cell (we'll re-add them below with updated neighbor counts)
    for (int i = 0; i < (int)pile.size(); ++i)
    {
        //if the manhattan distance bewteen the two points is 1...
        if (std::abs(pile[i].x - p.x) + std::abs(pile[i].y - p.y) == 1)
        {
            //remove the element
            pile[i] = pile.back();//the most efficient way to do this in a vector (where order doesn't matter) is by swapping with the back and then popping
            pile.pop_back();
            --i;
        }
    }

    //now add in this cell's land neighbors
    Point pw = points.get(p.x - 1, p.y);
    Point pn = points.get(p.x, p.y - 1);
    Point pe = points.get(p.x + 1, p.y);
    Point ps = points.get(p.x, p.y + 1);

    if (pw.valid && !pw.water)
        pile.push_back(pw);
    if (pn.valid && !pn.water)
        pile.push_back(pn);
    if (pe.valid && !pe.water)
        pile.push_back(pe);
    if (ps.valid && !ps.water)
        pile.push_back(ps);

    //then sort the pile by water-neighbor count (so the highest are at the end)
    //std::shuffle(pile.begin(), pile.end(), rng); //if using a non-uniform distribution, shuffle first to reduce blockiness
    std::sort(pile.begin(), pile.end());
}

```

This produces output similar to this:

Here's a link to a full implementation of it: Gist. Please note that this was written for clarity, not efficiency, and could be optimized considerably.

# Answer
> 1 votes
You might find this question & answer for creating random tea leaves offers an approach that could work...

How can I generate a texture that looks like left-over tea leaves?

Instead of sprites of tea leaves, create sprites of different size and shape water puddles that can be overlapped to create a larger water puddle.

---
Tags: c++, 2d, procedural-generation
---


# Question
Title: NavMesh stops working when changing scenes
In my game, upon reaching the end of the level, I change scenes to go to the next level. Most of the stuff is maintained from scene to scene using DontDestroyOnLoad, but the environment(floor) is not. So, I tried creating a new level environment in the next scene and baking it, but when the player enters that scene by reaching the end of the previous level, I get a NavMesh error stating that SetDestination can only be called on active agents. Why does this happen? Does the player have to be in the scene when baking occurs? Right now, the player does not natively reside in the scene, but gets loaded to it.

Edit: I created a new project with just the bare essentials for testing and it works as intended. Clearly, something was off with my other code which caused this kind of interference.

# Answer
> 0 votes
Because

> When baking is complete, you will find a NavMesh asset file inside a folder with the same name as the scene the NavMesh belongs to. For example, if you have a scene called First Level in the Assets folder, the NavMesh will be at Assets \> First Level \> NavMesh.asset (for more).

You have to baked your floor in each scene separately, and load in each scene.

---
Tags: unity
---


# Question
Title: Why are the app analytics for iTunes Connect so wrong?
I've developed a mobile game and have it listed both at Google Play and the Apple App Store. The install stats from Google Play are very close to my own stats, but the stats iTunes Connect shows are WAY off -- it shows nearly 1,000 "app units" (which I assume means installs) when there's only about 120.

Most of their "installs" come from China.

I'm trying to figure out 1) why iTunes Connect is counting all of these bogus "installs" and 2) what possible benefit someone could have from performing all of these fake installs.

Thanks in advance for your insight.

# Answer
I am experiencing the same issue - after updating my iOS apps, there is a period (a few days) when a lot of `App Units` get reported from China. In fact more `App Units` then `Impressions` / `Installations` / `Sessions`. And I have Google Analytics (Firebase) installed as well, where I don't see any increased activity.

I've read online that this might be due to click-farms (in China) that have been paid by some other apps for fake installs. And perhaps in order to not seem too suspicious, these click farms also install other random apps (perhaps ones that have been recently updated).

So until Apple figures out how to filter this out, I guess our only option is not to focus on App Units, but on other analytics (e.g. iTunes Connect's `Installations`, `Active Devices`, `Sessions`, or a third-party analytics tool such as Firebase, Mixpanel, Fabric etc.). Or to ignore data from China.
> 5 votes

# Answer
I have been experiencing something similar for my app too. However after having done some research, I think I understand this situation enough for this to not be a concern to me right now. Again this is purely based on my understanding of the situation.

1. iTunesConnect App Analytics is "OPT-IN": So the users have to agree to sending data to Apple for these things to show up in the App Analytics in iTunesConnect.
2. Analytics software: Now China (中国) has this thing they call the 'Great Firewall' and what it does is change the destination of the data being transmitted to servers outside of China. From what I understand Data for Chinese （中国人） users must be stored within China i.e. the server where the data for Chinese users is stored must be physically within China. I believe Google servers are not, hence it's blocked. Google owns Firebase now, ergo that's blocked too.
3. My case: Now for my app the downloads have increased overall, with over 60% of those coming from China and we are seeing some data (from China, it's not like we get 0 data from China. We see some sessions and why is that the case? Now after some digging around I found out that the way the Great Firewall(Google/Bing it) works is not 100%. The process of changing the destination doesn't always work i.e. it does not always change the destination and therefore some of it goes through and combine that with some tech savvy users using VPN in China. However for my case, it's unlikely that the users of my app are using VPN.

I have written a blogpost explaining all of the above in more detail.
> 2 votes

---
Tags: iphone, ipad, appstore
---


title: How to generate circles every 2 seconds

text:
# Question
Title: How to generate circles every 2 seconds
I want to generate circles every 2 seconds, in this case 5 but I can't get it. Instead of creating a circle every 2 seconds, the app wait 10 seconds and draw the 5 circles together. What am I doing wrong?

```
public class Juego extends SurfaceView{

boolean isItOK = false;

Paint paint;
int CantidadDeEsferas = 5;
int radio, alto, ancho;

public Juego(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);

    paint = new Paint();
}

public void onDraw(Canvas canvas){

    paint.setColor(Color.WHITE);
    canvas.drawRect(0, 0, getWidth(), getHeight(), paint);

    paint.setColor(Color.BLACK);

    for (int i=0; i<CantidadDeEsferas; i++) {

        Random r = new Random();
        alto = r.nextInt(canvas.getHeight());
        ancho = r.nextInt(canvas.getWidth());
        radio = r.nextInt(101 - 50) + 50;
        canvas.drawCircle(ancho, alto, radio, paint);
        run();
        isItOK = true;
    }
}

public void run(){
    while (isItOK){
        try
        {
            Thread.sleep(2000);
            isItOK = false;
        } catch (InterruptedException e) {

            e.printStackTrace();
        }

    }
}

```

}

# Answer
> 1 votes
**Don't sleep in `onDraw`**.

Instead use a timer of some kind to trigger creation of another circle:

```
List<Circle> circles = new ArrayList<Circle>();

private static class Circle{
    int radio, alto, ancho;
}
Handler handler;
public void generateCircle(){

    Circle c = new Circle();
    c.alto = r.nextInt(canvas.getHeight());
    c.ancho = r.nextInt(canvas.getWidth());
    c.radio = r.nextInt(101 - 50) + 50;
    invalidate();
    if(circles.size() < 5) handler.postDelayed(new Runnable(){public void run(){generateCircle();}}, 2000);
}

public void onDraw(Canvas canvas){

    paint.setColor(Color.WHITE);
    canvas.drawRect(0, 0, getWidth(), getHeight(), paint);

    paint.setColor(Color.BLACK);

    for (int i=0; i<circles.size(); i++) {
        Circle c = circles.get(i);
        canvas.drawCircle(c.ancho, c.alto, c.radio, paint);
    }
}

```

---
Tags: android, android-studio
---


# Question
Title: In a multiplayer game, should everything that is not user input be done server-side to prevent cheating?
I've heard this said before, but it seems somewhat unrealistic.

These are the two scenarios I'm working with:

> User Presses move key, moves themselves, and tells the server -\> server tells other clients

or

> User presses move key, and tells the server -\> server calculates if the user is allowed to move there -\> server tells all clients

It seems like option one would make the users movements feel very floaty and delayed. Do most multiplayer games use a combination? (user moves itself, gets confirmation from the server, and moves itself back if it was an illegal move.) Maybe it's a non-issue and I'm overthinking it.

# Answer
This is a very valid question, and the answers will probably differ between developers, as many will choose different approaches to secure the integrity of their games. The choice which implementation is eventually chosen will be impacted by numerous factors, e.g. how responsive the game needs to be, how much other information is being sent over the network already, how frequently user input is actually expected, and so on.

Your general considerations are two valid approaches, of which the first is probably more responsive but also more prone to abuse. The latter is technically the other extreme on the scale, providing the most security, but with the obvious potential to slow down the game significantly, if a lot of user interactions are to be expected.

One well-known hybrid model is using a similar approach to the one you also sketched out following your two proposed scenarios, that is based on implicit confirmation. Clients send all user actions to the sever, and periodically send their (full) world-state representation as well. Clients only receive periodic world-state updates and otherwise interpolate from previously received world states locally. The server is the authority on the world state (as it is the only place where all input information lands), and will check the periodically submitted world states for deviations/manipulations and the submitted user inputs for plausibility in general.

Note that in this approach there will usually be certain divergences between the clients' world states and the true world state (due to the interpolation nature of the client update), which necessitates the server-side updates of the world state to be issued on about a per-frame basis. Of course, numerous variations of this approach exist as well, depending on the requirements of the game.
> 2 votes

# Answer
I can't speak for other developers or games, but if I were in charge of security I would use a dictonary of moves or actions that are allowed in an online game or match. If a user somehow violates this dictonatlry, a flagging system should follow suit (just to be fair and certain), if say an illegal action is performed a certain ammount of times and/or within a pre-determined time period to ban or remove them from the game.

This way, you can use a standard player-registration system that won't be detremental to the game's performance. However, this *may* or may not work for your game. One thing that would be very important to remember is the likelyhood of a player (accadentaly or not) breaking your game's rules. The last thing you want is players being unfairly banned or removed from games due to a system like this because it does not bode well with the game in question. This is really a subjective matter that should be thought through very *thuroughly* before it's implementation is finialized.
> 0 votes

# Answer
> user moves it self, gets confirmation from the server, and moves it self back if it was an illegal move.

Yes, that's usually what you do. But snapbacks usually only happen when the server position diverges a lot from the client position. Small inconsistencies will always happen due to network latency. They usually don't affect the game and can be compensated over time. Large inconsistencies which warrant to teleport the player to a different location are usually a result of either a long network lag, a bug, or an attempt to cheat.
> 0 votes

---
Tags: multiplayer, online, anti-cheat
---


title: Nav Mesh Agent and obstacles

text:
# Question
Title: Nav Mesh Agent and obstacles
I have a scene with buildings and a Nav Mesh Agent. Should all the buildings contain the Nav Mesh Agent obstacle component, or them having colliders and being higher than agents step height is enough for the agent to avoid them at all times?

# Answer
> 1 votes
Stay with the collider and the height above the step height.

In the bake tab open the advanced options and change Min Region Area to a higher value and test it until the areas on your obstacles disappear.

Reference: https://docs.unity3d.com/Manual/nav-AdvancedSettings.html

---
Tags: unity, ai, navmesh
---


title: Problem in Splash Screen (Libgdx)

text:
# Question
Title: Problem in Splash Screen (Libgdx)
I made the game in libgdx and i want the splash screen in the starting but its show splash screen but not move to the game screen. I don't know what was the problem even the run time error also not occur.

GameScreen. java

```
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.gamestudio24.martianrun.stages.GameStage;

public class GameScreen implements Screen  {

    private GameStage stage;

    public GameScreen() {
        stage = new GameStage();
    }

    @Override
    public void render(float delta) {
        //Clear the screen
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        //Update the stage
        stage.draw();
        stage.act(delta);
    }

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

    }

    @Override
    public void show() {

    }

    @Override
    public void hide() {

    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

    @Override
    public void dispose() {

    }

}

```

GdxSplashScreenGame. java

```
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.utils.Timer;

public class GdxSplashScreenGame extends Game {

    private static long SPLASH_MINIMUM_MILLIS = 2000L;

    public GdxSplashScreenGame() { super(); }

    @Override
    public void create () {
        setScreen(new SplashScreen());

        final long splash_start_time = System.currentTimeMillis();
        new Thread(new Runnable() {
            @Override
            public void run() {

                Gdx.app.postRunnable(new Runnable() {
                    @Override
                    public void run() {
                        long splash_elapsed_time = System.currentTimeMillis() - splash_start_time;
                        if (splash_elapsed_time < GdxSplashScreenGame.SPLASH_MINIMUM_MILLIS) {
                            Timer.schedule(
                                    new Timer.Task() {
                                        @Override
                                        public void run() {
                                            GdxSplashScreenGame.this.setScreen(new SplashScreen());
                                        }
                                    }, (float)(GdxSplashScreenGame.SPLASH_MINIMUM_MILLIS - splash_elapsed_time) / 1000f);
                        } else {
                            GdxSplashScreenGame.this.setScreen(new SplashScreen());
                        }
                    }
                });
            }
        }).start();
    }

    @Override
    public void dispose() {
        // DISPOSE ALL RESOURCES
        getScreen().dispose();
        Gdx.app.exit();
    }
}

```

SplashScreen. java

```
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

public class SplashScreen extends GameScreen {
    private SpriteBatch batch;
    private Texture ttrSplash;

    public SplashScreen() {
        super();
        batch = new SpriteBatch();
        ttrSplash = new Texture("assets/splash.png");
    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        batch.begin();
        batch.draw(ttrSplash, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        batch.end();
    }

    @Override
    public void hide() { }

    @Override
    public void pause() { }

    @Override
    public void resume() { }

    @Override
    public void show() { }

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

    @Override
    public void dispose() {
        ttrSplash.dispose();
        batch.dispose();
    }
}

```

MartianRun. java

```
import com.badlogic.gdx.Game;
import com.gamestudio24.martianrun.screens.GameScreen;
import com.gamestudio24.martianrun.screens.SplashScreen;
import com.gamestudio24.martianrun.utils.AssetsManager;
import com.gamestudio24.martianrun.utils.AudioUtils;
import com.gamestudio24.martianrun.utils.GameEventListener;
import com.gamestudio24.martianrun.utils.GameManager;

public class MartianRun extends Game {

    public MartianRun(GameEventListener listener) {
        GameManager.getInstance().setGameEventListener(listener);
    }

    @Override
    public void create() {
        AssetsManager.loadAssets();
        setScreen(new SplashScreen());
        setScreen(new GameScreen());

    }

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

```

# Answer
I think you're over complicating things by using threads and timers. You can use your GdxSplashScreenGame as the main parent class which controls which screen should be shown. Then when you create a screen your simply pass the parent (GdxSplashScreenGame) to the screens and let the screens control when they are finished.

If you change your main game class to include a static var for each screen and a method to change screens like this:

```
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;

public class GdxSplashScreenGame extends Game {

    // one for each possible screen
    public static final int SPLASH_SCREEN = 0;
    public static final int GAME_SCREEN = 1;
    public static final int GAME_OVER_SCREEN = 3;

    public GdxSplashScreenGame() { super(); }

    @Override
    public void create () {
        changeScreen(SPLASH_SCREEN);
    }

    @Override
    public void dispose() {
        // DISPOSE ALL RESOURCES
        getScreen().dispose();
        Gdx.app.exit();
    }

    public void changeScreen(int screen){
        if(screen == SPLASH_SCREEN){
            this.setScreen(new SplashScreen(this));
        }else if(screen == GAME_SCREEN){
            this.setScreen(new GameScreen(this));
        }
    }
}

```

Then when you pass the this class to your screens you can simply call

```
parent.changeScreen(GdxSplashScreenGame.GAME_SCREEN);

```

Now instead of using a thread and a timer to change the screen after a certain time. You can use the built in delta time supplied in the render method to use as a countdown timer like this:

```
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

public class SplashScreen implements Screen {
    private SpriteBatch batch;
    private Texture ttrSplash;
    private GdxSplashScreenGame parent;

    private float timeToShowSplashScreen = 2f; // 2 seconds

    // pass the parent game to this screen so this screen can tell the parent its finished
    // and tell it to load the next screen
    public SplashScreen(GdxSplashScreenGame p) {
        super();
        parent = p;
        batch = new SpriteBatch();
        ttrSplash = new Texture("assets/splash.png");
    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        batch.begin();
        batch.draw(ttrSplash, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        batch.end();

        timeToShowSplashScreen -= delta; // remove delta from time
        if(timeToShowSplashScreen <= 0){ // 2 seconds are up
            // tell parent to change screen
            parent.changeScreen(GdxSplashScreenGame.GAME_SCREEN);
        }
    }

    @Override
    public void hide() { }

    @Override
    public void pause() { }

    @Override
    public void resume() { }

    @Override
    public void show() { }

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

    @Override
    public void dispose() {
        ttrSplash.dispose();
        batch.dispose();
    }
}

```
> 1 votes

---
Tags: java, libgdx, android-studio
---


title: Not placing tiles correctly on a grid

text:
# Question
Title: Not placing tiles correctly on a grid
I recently created a map editor, and i came across a problem: I can't position some tiles on some grid blocks, but if i go farther from Y-axis near 0, i can place blocks correctly.

This is the video: Test\_001

Map.cpp - createBlock func

```
void Map::createBlock(sf::Vector2f position, std::string name) {
        double gridPositionX = floor(position.x / grid) * grid;
        double gridPositionY = floor(position.y / grid) * grid;

        double ceiledGridPositionX = ceil(gridPositionX);
        double ceiledGridPositionY = ceil(gridPositionY);

        int mapPositionArrayX = ceiledGridPositionX / grid;
        int mapPositionArrayY = ceiledGridPositionY / grid;

        sf::Vector2f gridPosition( ceiledGridPositionX, ceiledGridPositionY );

        if (!isPositionOccupiedByBlock(mapPositionArrayX, mapPositionArrayY)) {
            Block block = blockTypes[ findBlockNameVector(name) ];
            block.setPosition(gridPosition);

            worldBlocks.push_back(block);
            wMap[ mapPositionArrayX ][ mapPositionArrayY ] = block.getID();
        }
    }

bool Map::isPositionOccupiedByBlock(int mapX, int mapY) {
    return (wMap[mapX][mapY] != 0) ? true : false;
}

```

# Answer
> 1 votes
Nothing jumps out at me as wrong. However, your video shows you having an issue on certain vertical columns, then going left and continuing to make more blocks without issue.

> if i go farther from Y-axis near 0

This indicates to me that you are moving into negative x coordinates. If wMap is an int\[\]\[\] or something similar then I'd be very curious how you're handling negative coordinates, since the code above has no safeguards or wraps. If you have special code to handle this elsewhere, I would check there first.

If I am misinterpreting you and the video (I have no sound at the moment, so perhaps you said something in there that I missed), then the only other option is that there is a specific arbitrary set of columns in your grid that can't be set. You should export the coordinates where you're having the issue, then perhaps we can narrow down the issue.

Other things to consider:

1. This could be a drawing issue. The blocks could be getting placed correctly, but not drawn correctly. Debug output of wMap would confirm or dismiss this. Based only on the code you provided this seems like the most likely option.
2. This could be an input issue. If you're using the standard SFML mouse stuff then this seems unlikely, but if you're doing something special then it's possible.

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


# Question
Title: How do I create Individual Health for each spawned object?
This question is probably asked many times, but how do I make sure that each time an object is spawned, that said object gains a value representing that objects health.

Basically I have an enemy spawner that creates multiple enemies.

Player shoots at one enemy, the enemy hit should be the only one to take damage, but I have never learned how to do that. Do I have to make the system create a new temporary integer each time a unit is created to represent it's health and then delete the temporary integer once it reaches 0?

I am not asking for help regarding one specific coding language (although c# would be the best), I only want to know a good (or simple) way to create individual health for multiple spawned objects.

# Answer
Simply make the health a property of the enemy type.

You've presumably got some kind of type or class that represents an entity or a character in your game:

```
class Enemy {
  // ...some stuff...
}

```

If you want each enemy to have a health stat, you can give the `Enemy` type an instance member representing health:

```
class Enemy {
  int health = 100;
  // ...some more stuff...
}

```

If you want them to have a varying amount of health when they spawn, you can pipe that value through whatever construction mechanism exists in your engine and/or language. The above example code is vaguely C#-like pseudo-code; if you were actually using C# you'd probably do this via an `Enemy` constructor, for example:

```
public class Enemy {
  public int CurrentHealth;

  public Enemy(int initialHealth) {
    CurrentHealth = initialHealth;
  }
}

```

That way, when you create a new `Enemy` from your spawning code, you just pass the desired health: `new Enemy(155)` for example.
> 8 votes

---
Tags: software-engineering
---


title: Attack Algorithm/Forula

text:
# Question
Title: Attack Algorithm/Forula
So I'm making a simple RPG game and I'm currently stuck on creating an attacking module for it.

I need to create a simple attack algorithm but I'm really not very good at it.

Each character has 3 base states - Attack, Defense, Dexterity

and all characters start off with 50hp and they gain 5hp per level.

What formula should I use to determine chance of hit, and how much damage is dealt? It doesn't have to to too overly complex. Just something simple for now.

# Answer
I'm going to give you my own, it may not be the right one as its rather subjective to what your looking for.

Attack will be the amount of damage done per tick / turn or individual attack. Dexterity will be considered the speed of the character in this instance. Defense we will subtract from the enemies attack with some random variation.

So for example

```
npc1.attacktimer = 0

game_loop/action loop ()
{
  npc1.attacktimer += frame_time;
  if (npc1.attacktimer >= 10.00 / dexterity)
  {
  //attack
  npc2.health-= npc1.strength - (npc2.defense / 2 + rand(6)) // randon number between 1 & 6
   npc1.attacktimer = 0;
  if npc2.health <= 0
   {
    npc1.exp + 5;
   }

  }

}

```

This is a very general example, pseudocode, I'd suggest however setting up a message handling interface or a interaction interface further down the line though thats semi off topic.

Where you check other conditions, example.

```
npc1 control loop(current targets)
{
 //checks whether combat is valid, then applies damage calculation.
 combathandler.attack(me, target)

}

```
> 0 votes

---
Tags: rpg, php
---


# Question
Title: Object Movement / Constant Movement Rate or Vectors
I' have some code to move a unit between two points in a series of points, when it reaches the next point it pops that point off the front of a stack, and then heads towards the next in the stack.

Issue: When the movement between two points occur, the object will slow down towards the point, I want a constant rate of movement between the two points, I'm thinking of implementing something like a physics engine would, there is some groundwork there already, however it would not ideally work with this code the way I think I should do it, I'd have to rewrite a fair deal where you create a movement vector in the direction of the point?

```
void EntityUnit::unitgmovement(CWaypoint* &TargetVec, float updatetime, CWaypoint* &Sourcewaypoint)
{
    // BUG why use this twice ? what happening ? probably resolve later tonight.
    // a moveto function without path smoothing used for infantry and tank movement
    pf_Dest = TargetVec;
    pf_Source = Sourcewaypoint;
    double xDistance = pf_Dest->GetX() - unit_x;
    double yDistance = pf_Dest->GetY() - unit_y;
    double zDistance = pf_Dest->GetZ() - unit_z;
    double distance = sqrt(xDistance * xDistance + yDistance * yDistance + zDistance * zDistance);
    util_timer_movedelay += updatetime;
    if (util_timer_movedelay > speed / 1000)
    {

    //  cout << "Distance:" << distance << endl;
        if (distance > 0.05)
        {
            unit_x += (0.5 * xDistance * speed * updatetime);
            unit_y += (0.5 * yDistance * speed * updatetime);
            unit_z += (0.5 * zDistance * speed * updatetime);
            util_timer_movedelay = 0;

        }
        else
        {
            pf_Source = pf_Dest;
            dest_reached = true;
            pf_waypoints.pop_front();

        }
    }

}

```

If I have an objects X,Y,Z global location, how do I create a movement vector for them ? that would work with this so I have a constant rate of movement? Or is there another easier work around ?

# Answer
The issue is in the following lines:

```
unit_x += (0.5 * xDistance * speed * updatetime);
unit_y += (0.5 * yDistance * speed * updatetime);
unit_z += (0.5 * zDistance * speed * updatetime);

```

The first half of each of those is saying to move 1/2 the distance to the goal, which will by nature shrink as you get closer, giving you the slowdown effect. This may be desirable sometimes, but not in your case.

To fix this, simply divide each component by the total distance before adding it, like so:

```
unit_x += (0.5 * xDistance * updatetime * speed / distance);
unit_y += (0.5 * yDistance * updatetime * speed / distance);
unit_z += (0.5 * zDistance * updatetime * speed / distance);

```

How does this work? The important bit is speed / distance. That gives you a fraction like, "I go 10ft per second, it's 40ft away, so I'll go 1/4 of the distance this second." If you take that times your component distances (xDistance, yDistance, and zDistance) that will give you the amount to move on each axis.

As a side note, the 0.5 * ... will mean you only move at half of your speed. Alternatively, your speed variable may mean something completely different to you and 0.5 is the true 'speed' of the object. The math remains the same in that case, but it's something to watch out for.
> 3 votes

---
Tags: c++, vector
---


# Question
Title: How can you use Fractals to perturb an image?
I've been playing around with Procedurally Generated World. I've so far managed to create the Height Map, and a translate map, but now i'm attempting to create Caves,

The main idea is to use another Noise map, with values being either 0 or 1, and multiply it with the Height Map.

I've managed to achieve this:

This is currently described with a float\[Width, Height\], which has value 0 for those points (x,y) such that (x,y) is black, or 1, for those which (x,y) is white.

I want to apply some fractal to this to achieve this:

However, i have no idea how to do this!

(I also apologize for any grammatical errors. I haven't slept in like 18 hours and i can't think straight)

# Answer
# Domain warping

What helped me wrap my head around the problem you describe is the following. I used to think of this problem as:

```
How do I move pixels around in my texture to warp it?

```

Instead, try thinking of it like this:

```
How do I pick samples from my original texture in a warped way?

```

This concept is known as domain warping. The procedure to do domain warping is as follows:

1. Start with your original image, in your case the `float original[width, height]`
2. Create a new empty array of the same size (just to keep things simple), let's call it `float warped[width, height]`. We now want to fill this new array with a distorted version of the original image.
3. To copy the image identically, you would iterate over all pixels and do: `distorted[x, y] = original[x, y]`. Instead of doing this, let's warp the domain by doing this: `distorted[x, y] = original[(x + 16) % width, (y + 16) % height]`. You'll notice, after looping over all pixels, `distorted` now contains a shifted version of the original image. This is because we warped the domain. Instead of doing `[x, y] -> [x, y]`, we warped out coordinates as `[x, y] -> [x + 16, y + 16]` (the modulo makes sure we don't go out of bounds of the array).

# Position-variant distortion

In the problem you describe, you probably don't want to shift every pixel equally. When you apply the same function to the coordinates, in every position, you'd call it a position-invariant distortion. Let's make the way we distort our pixels depends on the position we are sampling for (i.e. position-variant distortion).

Repeat the procedure above, but use the following transfer function: `distorted[x, y] = original[x + 10 * sin(x / 20), y + 10 * cos(y / 20)]`. Now, the offset in sampling (`10 * sin(x / 20)` for `x` and `10 * cos(y / 20)` for `y`) depends on the position of the pixel! As you'll see, you now end up with a wavy version of your image. Parts of it seem stretched, and parts of it seem squashed. The big clue here is that you are not just linearly shifting all pixels in the same way, you are varying your transfer function based on the actual pixel coordinate.

(**Note:** don't forget to add rounding code to sample on integer indices, e.g. by wrapping your indices in `round( ... )`)

# Solution to your problem: lookup of the distortion

Now to solve your problem, you want to use a procedurally generated pattern to distort your image. To do so, you could follow the procedure below:

1. Start with your original image, in your case the `float original[width, height]`, and create two images of the same size and will them with procedural values, let's call them `procedural_x[width, height]` and `procedural_y[width, height]`.
2. Instead of using a function like `sin` or `cos` to calculate our sampling offset, we will use our procedurally generated values. First normalize your procedural values to be in the range of `0.0` to `1.0`. Depending on the algorithm you use, they may already be in that range. If not, normalize using the following function: `procedural_x_normalized[x, y] = (procedural_x[x, y] - min_value) / (max_value - min_value)`
3. Now, fill your distorted image by iterating over all pixels and sampling using the following function:

`distorted[x, y] = original[
 x + 10 * (procedural_x_normnalized[x, y] - 0.5),
 y + 10 * (procedural_y_normnalized[x, y] - 0.5)
]`

Here, you are using your procedural patterns, as lookup tables for the sampling offsets. In other words, when you are sampling a pixel, you check your procedural arrays to determine how many pixels to shift horizontally and vertically. (**Note:** don't forget to add rounding code to sample on integer indices, e.g. by wrapping your indices in `round( ... )`)

In summary, to achieve distortion using procedural values, use those values as offsets when sampling your image. Instead of thinking of the problem as `How do I distort my original pixture?`, think of it as `How do I samples values from my original picture in a distorted way?`.

I highly recommend reading this article by Inigo Quilez: http://www.iquilezles.org/www/articles/warp/warp.htm .
> 3 votes

# Answer
To create a fractal like noise, you need to take your noise, create some values with it with decreasing frequency and weight, then divide the value with the total weight, in pseudo code (the base frequency and sample count can be changed):

```
value = 0, weight = 1, totalWeight = 0, frequency = 0.5
for (i = 0; i < 8; i++) {
    value += noise(x, y, frequency) * weight;
    totalWeight += weight;
    weight /= 2;
}
value /= totalWeight;

```
> 1 votes

---
Tags: procedural-generation, perlin-noise, fractal
---


# Question
Title: How to store the co-ordinates traced by a character in unity C# script?
I have a navmesh agent with a trail-renderer component attached to it, who travels to a pre-determined destination based upon user input using unity's built in Navigation system. I want to store the (x,y,z) cordinated of the path traced by the character in some kind of data structure and then I want the camera to trace that exact path, but at some height above so the path(trail-renderer) is visible.

# Answer
> 0 votes
So if the path is static after calculation you could use this:

CameraController.cs:

```
using UnityEngine;

public class CameraController : MonoBehaviour
{
  public float speed;
  public Vector3 offset;

  Player player;
  int nextWaypoint;

  void Start()
  {
    player = GameObject.FindGameObjectWithTag("Player").GetComponent<Player>();
    nextWaypoint = 0;
  }

  void Update()
  {
    if (player.reachedTarget && nextWaypoint < player.waypoints.Length)
    {
      float step = speed * Time.deltaTime;
      Vector3 target = player.waypoints[nextWaypoint] + offset;

      transform.position = Vector3.MoveTowards(transform.position, target, step);
      if (transform.position == target)
        nextWaypoint++;
    }
  }
}

```

Player.cs:

```
using UnityEngine;
using UnityEngine.AI;

public class Player : MonoBehaviour
{
  public Transform target;

  [HideInInspector]
  public Vector3[] waypoints;
  [HideInInspector]
  public bool reachedTarget;

  private NavMeshAgent agent;

  void Start()
  {
    agent = gameObject.GetComponent<NavMeshAgent>();
    StartPathfinding();
    for(int i = 0; i < waypoints.Length; i++)
    {
      Debug.Log(waypoints[i].ToString());
    }
  }

  private void Update()
  {
    if (agent.remainingDistance < 0.01f)
      reachedTarget = true;
  }

  void StartPathfinding()
  {
    agent.SetDestination(target.position);
    NavMeshPath path = new NavMeshPath();
    agent.CalculatePath(target.position, path);
    waypoints = path.corners;
    reachedTarget = false;
  }
}

```

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


# Question
Title: Why does XMVector4Dot return a vector with the dot product copied to it's components?
The documentation for XMVector4Dot lists the return value as a vector. It also states that the dot product is replicated into each component. Given that the dot product is going to be a single value, how does this offer an advantage over just returning float?

The only way I can see to get the value is to do something such as:

```
        XMVECTOR w = { -XMVectorGetX(XMVector4Dot(x, eye)), -XMVectorGetX(XMVector4Dot(y, eye)), -XMVectorGetX(XMVector4Dot(z, eye)), 1 };

```

Which seems unnecessary. Is there another reason I'm overlooking?

# Answer
These APIs are designed to leverage the SIMD registers and instruction sets of your CPU, which are vector registers (each one holds four floats). Getting data into and out of these registers is sometimes "slow" (relatively speaking): the best way to utilize them is usually to get data into them and then keep it there as long as possible while you operate on it.

If the dot product operation were to return a single float instead, it would need to pay that transfer cost every time you called it, even if you're just going to immediately transfer that result *back* into another SIMD register to perform more operations on it. So it's less pessimistic on the part of the API to assume you'll keep doing more SIMD math and thus give you a result that still facilitates that. That puts the decision about when to pay the transfer cost in your hands instead of theirs, and you presumably know better than they do about when the best time to eat that transfer cost is for your application.

Further, by replicating the results out to every component of the vector, you can perform further multiplications against that return in parallel with further SIMD operations.
> 3 votes

---
Tags: directx, vector
---


# Question
Title: Can ANGLE OpenGL ES 2.0 use the same color / depth surface as Direct3D11?
Lets just assume I have some simple OpenGL ES 2.0 code that renders a box with depth writing / testing. Is it possible to put this box in a middle of a Direct3D11 scene using angle?

The MS angle page https://github.com/Microsoft/angle/wiki/Interop-with-other-DirectX-code says that we can render to a texture, and I have tried that and it works fine. But this only allows for 2D integration, not 3D integration, as far as I can tell. I render my OpenGLES content to a texture (in 2d or 3d), but now I can only put a texture in the DirectX scene. How can I have my OpenGL ES code write / read from the same depth/color surface that the DirectX11 portion is using?

# Answer
It would be possible to render to textures from either the ANGLE or Direct3D and then using that texture to produce the final content that is inserted in the FBO that is drawn on the screen.

Read more here: ANGLE Interop with other DirectX code

Since ANGLE is basically just translating your OpenGL ES calls to DirectX the answer should be: Yes it is possible.

But it all depends on the engine you're using.
> 2 votes

---
Tags: directx, directx11, opengl-es2
---


# Question
Title: Making a pixel-perfect viewport in LibGDX
My game that uses LibGDX as the graphics library, should be playable with every display. Here's the problem: It have to be pixel-perfect. That means, the scale factor must be an integer value, so that my pixels do not stretch over two physical pixels - resulting in flickering pixels which I obviously do not want.

The player should see a constant amount Y of vertical space. The width is calculated by the screen resolution. My game field is designed for 4:3. Therefore a player with 16:9 or even 21:9 should see more in the horizontal space. Best example: An usual Pong field. The field is 4:3. A player with 16:9 should see the same field size, but with more "empty" space on the sides.

I've tried various approaches to achieve this. The first was the ScreenViewport, provided by LibGDX. Problem: Adjusting the unitsPerPixel would result in a smaller playfield. Or even mirroring it. I could provide a high-res playfield and scale it down with unitsPerPixels, but it is not very future-proof (Think of providing a 4k field for a future 512k monitor).

My second approach was a custom viewport. (No worries! It is written in Kotlin)

```
worldWidth *= (screenHeight/worldHeight).toInt()
worldHeight *= (screenHeight/worldHeight).toInt()

setScreenBounds(
    screenWidth/2 - worldWidth.toInt()/2,
    screenHeight/2 - worldHeight.toInt()/2,
    worldWidth.toInt(),
    worldHeight.toInt() )

```

It tries to scale up the field by a integer number (making it pixel-perfect). Problem: The unscaled zones (that would be normally covered by the non-integer-scaling) are black. Black bars. Instead, I want to show the game world.

Any ideas how to achieve this? Thanks!

# Answer
> -1 votes
Since Libgdx uses openGL to render using pixel perfect values is irrelevant since openGL converts all these units into a 0-1 range. The flickering issue you speak of is likely being caused by the texture filtering method you're using or how you are rendering the images.

You could however try to use the extendViewport and set your game field to the height of the current screen then the ExtendViewport will add the extra area when required.

The ExtendViewport (source) keeps the world aspect ratio without black bars by extending the world in one direction. The world is first scaled to fit within the viewport, then the shorter dimension is lengthened to fill the viewport.

---
Tags: libgdx, graphics, resolution
---


title: .PNG changes color in Love2D

text:
# Question
Title: .PNG changes color in Love2D
I have a small .PNG file. I load it with:

```
  picSmiley = love.graphics.newImage("salamander.png");

```

and I draw it with:

```
love.graphics.draw(picSmiley, objects.ball.body:getX(),
        objects.ball.body:getY(), math.rad(rotation), 1, 1, 40 / 2, 22 / 2);

```

---

Nothing else should influence it. The background color should not matter, as the image has an alpha channel. Despite being red, however, my image draws with a murky green color.

Only the color is wrong. How do I fix it?

Wrong (the salamander is on the grey block):

# Answer
Set the color to white before calling the draw method:

```
love.graphics.setColor(255,255,255,255);
love.graphics.draw(picSmiley, objects.ball.body:getX(),
    objects.ball.body:getY(), math.rad(rotation), 1, 1, 40 / 2, 22 / 2);

```
> 1 votes

# Answer
More specifically, the drawing color set by love.graphics.setColor acts as a kind of mask, and stays until it is overridden by another call to love.graphics.setColor.

So you may have to save the old color, set it to white, draw your salamander, then restore it so the rest of your graphics is drawn properly.

But as the post if months old, I believe you already know that ^-^
> 1 votes

---
Tags: image, love2d, png
---


# Question
Title: How can I manage resources in memory, and dispose of them at appropriate time with the Ashley framework?
I have been working on libGDX and the Ashley framework, and I have not been able to find any information on resource control in memory.

I would like to know if there is any way to control those entities that are in memory before and after closing the application or change the screen. Mainly to add the `dispose()` methods where necessary to avoid unnecessary resources loaded into memory.

# Answer
The Ashley ECS framework typically does not control the loading or management of resources as this would usually be done separately by something like an asset manager or in a bespoke loader.

If however you have a bespoke loading system and are more interested in using Ashley to trigger the dispose methods you can use an EntityListener

Let's just say you have a textureComponent which is used to store the image for an enemy and when the enemy is removed you no longer need any references to that image and you want it disposed.

You would first make an EntityListener:

```
import com.badlogic.ashley.core.ComponentMapper;
import com.badlogic.ashley.core.Entity;
import com.badlogic.ashley.core.EntityListener;

public class TexturecompListener implements EntityListener{

    @Override
    public void entityAdded(Entity entity) {
    }

    @Override
    public void entityRemoved(Entity entity) {
        TextureComponent tc = ComponentMapper.getFor(TextureComponent.class).get(entity);
        tc.region.getTexture().dispose();
    }

}

```

Now you have a listener you need to add it to your engine with a family so it knows which entities this listener should be linked to:

```
engine.addEntityListener(
            Family.all(TextureComponent.class).get(),   // set which entities to call this lisneter for
            new TexturecompListener());                 // set the listener

```

This would then dispose the image when the entity is removed from the engine.
> 2 votes

---
Tags: libgdx, entity-system, resource-management
---


title: Isometric 3d collision detection

text:
# Question
Title: Isometric 3d collision detection
I'm making an isometric map for a game, I can draw it, but I don't know how to implement a sort of 3d collision detection without Threejs or other 3d library.

It is possible? Maybe make the block an Object can help? I have searched a lot on the web, but I found only libraries. Thank you!

This is my JavaScript code:

```
var canvas = document.getElementById('canvas'),
 ctx = canvas.getContext('2d'),
 width = canvas.width = window.innerWidth,
 height = canvas.height = window.innerHeight,
 stop = false;

var tw, th;
var player;

setup();
draw();

function setup(){
  ctx.translate(width/2,50);

  tw = 60; //tile width
  th = 30; // tile height
  player = new Player(2,3,2);

};

function draw(){

  ctx.clearRect(-width/2,-50,width*1.5,height+50);

    for(var i = 0; i < 5; i++){
      for(var j = 0; j < 5; j++){
        drawBlock(i,j,1,tw,th);
      }
    }

    if(!stop){
     requestAnimationFrame(draw);
    }
}

function drawBlock(x,y,z,w,h){

 var top = "#eeeeee",
     right = '#cccccc',
     left = '#999999';

 ctx.save();
 ctx.translate((x-y)*w/2,(x+y)*h/2);

 ctx.beginPath();
 ctx.moveTo(0,-z*h);
 ctx.lineTo(w/2,h/2-z*h);
 ctx.lineTo(0,h-z*h);
 ctx.lineTo(-w/2,h/2-z*h);
 ctx.closePath();
 ctx.fillStyle = "black";
 ctx.stroke();
 ctx.fillStyle = top;
 ctx.fill();

 ctx.beginPath();
 ctx.moveTo(-w/2,h/2-z*h);
 ctx.lineTo(0,h-z*h);
 ctx.lineTo(0,h);
 ctx.lineTo(0,h);
 ctx.lineTo(-w/2,h/2);
 ctx.closePath();
 ctx.fillStyle = "black";
 ctx.stroke();
 ctx.fillStyle = left;
 ctx.fill();

 ctx.beginPath();
 ctx.moveTo(w/2,h/2-z*h);
 ctx.lineTo(0,h-z*h);
 ctx.lineTo(0,h);
 ctx.lineTo(0,h);
 ctx.lineTo(w/2,h/2);
 ctx.closePath();
 ctx.fillStyle = "black";
 ctx.stroke();
 ctx.fillStyle = right;
 ctx.fill();

 ctx.restore();

}

function drawTile(x,y,stroke,col){

 ctx.save();
 ctx.translate((x-y)*tw/2,(x+y)*th/2);

 ctx.beginPath();
 ctx.moveTo(0,0);
 ctx.lineTo(tw/2,th/2);
 ctx.lineTo(0,th);
 ctx.lineTo(-tw/2,th/2);
 ctx.closePath();
 if(stroke){
  ctx.stroke();
 }else{
  ctx.fillStyle = col;
  ctx.fill();
 }

 ctx.restore();

}

function Player(x,y,z){
  this.x = x;
  this.y = y;
  this.z = z;
  this.w = 10; //width
  this.h = 10; //height
}
```

```
canvas{
  width:100%;
  height:100%;
}
```

```
<canvas id="canvas"></canvas>
```

# Answer
> 0 votes
to compare any box with one axis-aligned box I use this approach:

```
method boolean checkCornerColission(x1, y1, z1, x2, y2, z3, width, height, depth):
  return x1 > x2 and x1 < x2+width and y1 > y2 and y1 < y2+height and z1 > z2 and z1 < z2+depth;

method boolean checkColission():
    for corner i=0 to 7:
      if checkCornerColission(x[i],y[i],z[i]...):
         return true;
    return false

```

---
Tags: collision-detection, javascript, isometric
---


# Question
Title: Unity - get screenshots from various resolutions
To upload my app to Google Play I need to provide various screenshots. Thing is, I have only one tablet, no phone and I don't feel like virtualizing a bunch of devices. Is there a way to create screenshots of different sizes? Like what would a 7" 1280X720 tablet see?

# Answer
Add this handy script to an empty game object.
Screenshot Key speaks for itself - you use it during play to take screenshots. They will be saved in "Screenshots" inside your project folder.
Scale factor is what you need to take screenshots of display sizes which you don't own.
Example: build settings, switching to Android. In left up corner of Game View instead of default free aspect set to what you need. Scale factor is for when you have to take screenshots of resolutions you don't own(need 2048x1536 while your monitor is 1024x768). For this particular case just scale it by 2.

```
using UnityEngine;
using System.Collections;
using System.IO; // included for access to File IO such as Directory class

/// <summary>
/// Handles taking a screenshot of game window.
/// </summary>
public class ScreenshotUtility : MonoBehaviour
{
    // static reference to ScreenshotUtility so can be called from other scripts directly (not just through gameobject component)
    public static ScreenshotUtility screenShotUtility;

    #region Public Variables
    // The key used to take a screenshot
    public string m_ScreenshotKey = "s";
    // The amount to scale the screenshot
    public int m_ScaleFactor = 1;
    #endregion

    #region Private Variables
    // The number of screenshots taken
    private int m_ImageCount = 0;
    #endregion

    #region Constants
    // The key used to get/set the number of images
    private const string ImageCntKey = "IMAGE_CNT";
    #endregion

    /// <summary>
    /// Lets the screenshot utility persist through scenes.
    /// </summary>
    void Awake ()
    {
        if (screenShotUtility!=null) { // this gameobject must already have been setup in a previous scene, so just destroy this game object
            Destroy(this.gameObject);
        } else { // this is the first time we are setting up the screenshot utility
            // setup reference to ScreenshotUtility class
            screenShotUtility = this.GetComponent<ScreenshotUtility>();

            // keep this gameobject around as new scenes load
            DontDestroyOnLoad(gameObject);

            // get image count from player prefs for indexing of filename
            m_ImageCount = PlayerPrefs.GetInt(ImageCntKey);
        }

        // if there is not a "Screenshots" directory in the Project folder, create one
        if (!Directory.Exists("Screenshots")) {
            Directory.CreateDirectory("Screenshots");
        }

    }

    /// <summary>
    /// Called once per frame. Handles the input.
    /// </summary>
    void Update ()
    {
        // Checks for input
        if (Input.GetKeyDown(m_ScreenshotKey.ToLower()))
        {
            // Saves the current image count
            PlayerPrefs.SetInt(ImageCntKey, ++m_ImageCount);

            // Adjusts the height and width for the file name
            int width = Screen.width * m_ScaleFactor;
            int height = Screen.height * m_ScaleFactor;

            // Takes the screenshot with filename "Screenshot_WIDTHxHEIGHT_IMAGECOUNT.png"
            // and save it in the Screenshots folder
            ScreenCapture.CaptureScreenshot("Screenshots/Screenshot_" +
                                          + width + "x" + height
                                          + "_"
                                          + m_ImageCount
                                          + ".png",
                                          m_ScaleFactor);
        }
    }
}

```
> 1 votes

---
Tags: unity, resolution, screenshot, screen-recording
---


# Question
Title: Still not get it, How to display cameras movement speed value in inspector?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class SwitchCameras : MonoBehaviour
{
    [Header("Cameras Init")]
    public Camera[] cameras;
    public Vector3[] originalPosition;

    [Space(5)]

    [Header("Cameras Switch")]
    public string currentCameraName;
    public Vector3[] lastCameraPosition;
    public float cameraSpeed;

    [Space(5)]

    [Header("Cameras Target")]
    public float nextTargetDistance;
    public Vector3 nextTargetPosition;
    public Transform nextTarget;

    private int currentCamera = 0;

    void Start()
    {
        cameras = Camera.allCameras;
        lastCameraPosition = new Vector3[cameras.Length];

        if (cameras.Length >= 1)
        {
            originalPosition = new Vector3[cameras.Length];
            for (int i = 0; i < cameras.Length; i++)
            {
                originalPosition[i] = cameras[i].transform.position;
            }
        }

        if (cameras.Length == 1)
        {
            Debug.LogError("Need more then 1 camera for switching..");
        }
        else
        {
            Debug.Log("Found " + cameras.Length + " cameras");
        }

        for (int i = 0; i < cameras.Length; i++)
        {
            cameras[i].enabled = false;
        }
        cameras[0].enabled = true;
        currentCameraName = cameras[0].name;
    }

    void LateUpdate()
    {
        if (Input.GetKeyDown(KeyCode.C))
        {
            cameras[currentCamera].enabled = false;

            if (++currentCamera == cameras.Length)
                currentCamera = 0;

            cameras[currentCamera % cameras.Length].enabled = true;
            cameraSpeed = (cameras[currentCamera].transform.position - lastCameraPosition[currentCamera]).magnitude / Time.deltaTime;
            lastCameraPosition[currentCamera] = cameras[currentCamera].transform.position;
            currentCameraName = cameras[currentCamera].name;

            Debug.Log(cameras[currentCamera].name + " Last position " + cameras[currentCamera].transform.position);
        }
    }
}

```

Two things i want to do:

1. When running the game display the movement speed of cameras\[0\] in the Update i want to see the speed in real time not only once like still.
2. Then when i click on C to switch between the cameras display each camera in real time the movement speed. Now when i click on C and switch between the cameras i see still speed value and not real time running value of the speed.

# Answer
So I think you want to move the speed calculation out of your key-check if-statement. So your late update function should look something like this:

```
void LateUpdate()
{
    if (Input.GetKeyDown(KeyCode.C))
    {
        cameras[currentCamera].enabled = false;

        if (++currentCamera == cameras.Length)
            currentCamera = 0;

        cameras[currentCamera].enabled = true;
        currentCameraName = cameras[currentCamera].name;
    }

    cameraSpeed = (cameras[currentCamera].transform.position - lastCameraPosition[currentCamera]).magnitude / Time.deltaTime;
    lastCameraPosition[currentCamera] = cameras[currentCamera].transform.position;

    Debug.Log(cameras[currentCamera].name + " Last position " + cameras[currentCamera].transform.position);
}

```

So here, when the key is pressed, we only update the camera index and name, and leave the speed calculation out of there. The actual speed calculation is now done each frame instead of only when a key is pressed.
> 1 votes

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


# Question
Title: What is a good strategy to switch my career from full-stack developer to game developer?
I am senior full-stack developer at age of 30 and I mainly work with Java EE/Spring/... in back-end and Angular/React/JQuery/... in the front-end.

I love programming but my dream job was game developer not full-stack developer. I am making good amount of money in my current position and I do not want to start from scratch again. What is a good strategy to switch my career to game-developer without a fresh start?

Update: By game-developer, I mean working on large game development companies not indie games.

# Answer
*Health warning: The following comes with a large amount of hindsight and I'm sure it's one of many experiences within game dev - but it's worth considering*

I'd like to offer a perspective from someone who left game development to do something different, who is a similar age to you. I was a developer at a first-party studio for five years straight out of university. First, a few questions to check suitability:

1. Are you (in your own honest estimation) good at what you do?
2. Are you unmarried (preferably single)?
3. Are you willing to work long hours?
4. Can you work public holidays (and maybe weekends too)?
5. Can you take a pay cut?
6. Do you have thick skin (can you take a bad review?)

If the answer to *any* of these questions is no, I would reconsider any career change into game development. To take these questions one by one:

**1. Are you good?**

You don't need to be a 'rockstar' developer to work in 'AAA' game development but you need to have a very good grasp of performance and CS fundamentals. It will help if you have a degree in this subject. Most of these games are going to be written in C++ (possibly C, in some cases) and will have a lot of low-level concerns. You'll need to know about memory management. For engine reference you'll probably want to know all about Unity and Unreal. Most will have some component of linear algebra. If you are good at what you do then I'd have every confidence you can retrain but it doesn't match the current list of languages or technology you're working with.

**2. Are you single?**

This might seem a bit personal but this is very much a move you're going to be making for you, not for anyone else - there will be very little upside for anyone except you in this. You will either need to have a very supportive partner and family in this or no attachments - especially if you're going to be working long hours it's going to cause arguments. Which brings us to...

**3. Can you work long hours?**

Look up crunch. It's a thing. I'm not going to go into detail on this as it's covered widely in game press, but it does appear to be very much part of a development process with a fixed date where it's hard (and expensive) to change the schedule. I used to convince myself crunch was a worthwhile trade because of a) the cameraderie you gain with colleagues in this kind of high-pressure environment and b) that my company looked after me (which they did, in general!) I later realised I was basically selling my soul for a cooked meal in the evening.

**4. Can you work weekends?**

I include this separately as it's something sometimes overlooked. It's not just late nights but also weekends and public holidays. You get to hear a lot about 'passion' and if you're 'passionate' about what you're making then you'll 'pull out all the stops' to make it happen. Cross out from your list any studios that make games you're not super keen on. On public holidays I got microwave ready meals instead of a cooked meal because they couldn't convince the kitchen staff to come in (but they got the devs!)

**5. Can you take a pay cut?**

In general game developers are towards the lower end of the pay spectrum and can afford to be because it's an industry in demand - it's quite easy these days to find young graduates who can work long hours an get paid peanuts, so they don't really need to pay you for your experience. Considering also that you'll be retraining significantly you need to expect you'll come in lower on the career ladder, so expect a pay cut there too.

**6. Do you have thick skin?**

The internet is a polarising place and it's a very significant difference working on a B2B application or something internal in comparison to having your work picked over on the internet. My studio didn't get a lot of press but not much of it was that positive while I was there. It just meant people sharing links on IM about how everything you do is terrible.

It can also be intensely rewarding - seeing something you helped make on a shop (or seeing someone buy it!) is a great feeling. But I suspect out of the population of game developers (and even smaller, the population of AAA developers) the number who get positive praise consistently from press and are loved by everyone is very low. Places at those studios will be limited and very competitive.

One last question that's important too. **Are you happy for your play thing to turn into work?** For the time I was a game developer, if I played anything all I did was analyse it - how did they do that animation, why does this mechanic work like that? It can suck the joy out of what you love.

In summary - while I enjoyed the time I spent in game dev I don't think I'd recommend it as a career to someone to retrain in to, especially someone at a similar age to me. It was definitely something for my youth and, now I have more responsibilities and a sense of what I'm worth, I don't think I'd want to go back. Obviously my experience is going to be one of many, but I think enough of the themes above come up in other war stories from game developers (I haven't even mentioned things like job security) that it's worth bearing in mind.

Have you considered a *better* full stack job? One with a more interesting domain? Have you considered working on something in your spare time to see if you like it? If you're going into this with your eyes open, and you know what you're getting in to - best of luck, you can read the above for some notes on what to do and what to expect.
> 7 votes

# Answer
I would think that making a few smaller games to release for console/mobile/whatever would be a good start. Then you'd technically have experience. You can then use that to get a higher position. But I still don't think that'd get you to as high as a position as you'd probably hope for.

But when it comes to making the games, you're going to want the code to be very well polished and to have it all function pretty well when showing it to a company.
> 3 votes

---
Tags: game-industry, career
---


title: What is meant by "System Programming"?

text:
# Question
Title: What is meant by "System Programming"?
I am preparing for an internship as game programmer at a world-renowned game development company. When I searched their website for necessary prerequisites, it showed me this:

> ### Added Advantage
>
> * Knowledge of DirectX/OpenGL.
> * Strong command on 3D Maths and Physics.
> * Visual Studio IDE for C++ development.
> * System Programming and OS concepts.

What exactly do they mean by system programming and OS concepts?

Should I be studying Windows programming? Or should I be going with Linux programming (meaning they want me to know the important concepts). Or is it something totally different?

# Answer
"System programming" (or "systems programming") tends to mean programming done at a lower level of abstraction than (for example) gameplay programming. Gameplay programming is usually about building the actual game mechanics and front-facing features that a user might see, whereas systems programming is more about building the frameworks upon which gameplay programmers work.

This might mean graphics, resource loading and streaming, audio, memory management, file IO, platform abstraction APIs, et cetera. The details vary quite a bit, and because there are no standards for job titles in the games industry there are similarly no standards for the names of programming domains. At one studio, you may find that "systems programming" means everything I listed above. At another, you may find that they distinguish "graphics programming" as a separate domain and call every other non-gameplay-programming task "systems programming." In yet another, they might not use the term at all and just call it "engine programming."

Since it's a lower-level domain, and typically involves interfacing more directly with the platform-specific APIs for whatever platforms the game is being built for, having knowledge of those platforms will be helpful, as will having knowledge of the more general domain (e.g., of OS concepts without regard to how specific OS's work, such as what virtual memory is, or how threads work, how IO buffering works, et cetera).
> 53 votes

# Answer
Josh's answer is really good but I figured I'd throw down some bullet points about the Systems team where I work. I don't work on Systems but I work with them a lot. The responsibilities of a Systems team varies a lot from company to company.

Our Systems team is in charge of a lot of stuff:

* Math Library
* STD Replacement Library
* Core Game Framework
* Core Application Framework
* Input
* Event messaging
* Component-Entity systems
* Script binding
* (and more)

There's a lot of Windows and Linux domain knowledge here as well as a lot of knowledge of Physics, core game logic and low level memory management. Systems teams will usually be involved at least in some part in each supported OS since most of their projects sit on each OS at a pretty low level.

Some things that might fall under a "Systems" team that we break up into separate teams (but our Systems team still interacts with pretty heavily):

* Physics
* Linux (dedicated server)
* Direct support for other OSes (iOS/Mac/Consoles/etc)
* Build Systems
* Audio
> 21 votes

# Answer
Added advantages listed above are mostly for game engine programming when necessary, thus involves utilizing low level APIs. Systems programming here expects you to know how to make calls to OS audio, process management, file manipulation, network calls and so on...
> 0 votes

# Answer
Systems programming is very well defined, but companies try to stretch it to their needs. If you are using or writing system calls, you are doing systems programming. System calls are the functions that are provided by the kernel, or userspace drivers. This includes OpenGL as it is basically a driver.
> 0 votes

# Answer
Since they reference Visual Studio, system programming refers to writing programs specifically for the windows Operating Systems, meaning: windows syscalls (for example there is no fork-exec chain), user accounts, where to put your user specific data, data sharing models in windows Look up,for example how you can check the current user in visual c++ Or how to start a new process

OS concepts, refer to scheduling, file abstraction, threads, userspace etc. os dev wiki and forums can be a good read

User authentication is for example in both sections, since windows is a single user operating system, that has a much deeper kernel integration of user management and user interface.

The msdn is the knowledge base for all things windows programming apis, libraries etc https://msdn.microsoft.com/

Stackoverflow for the actual coding if you are stuck.
> -5 votes

---
Tags: terminology, career
---


title: How is "resolution scaling" done?

text:
# Question
Title: How is "resolution scaling" done?
Lots of new games use Resolution Scaling as an option. At first I thought it was just Super-sampling but it does not appear to remove aliasing so I'm assuming there is more to it than that.

I guess my question is, how are developers implementing this? I'm assuming it means multiplying the width and height of the various rendertargets, and then what?

# Answer
> 1 votes
Google gives me this:

> For those that don't understand, a simple way to look at Resolution Scaling is that you set the game into a windowed mode then full-screen that. Let's say your screen is 1280x720 pixels, you set the "windowed mode" resolution to 640x480, then full-screen the 640x480 rendering
>
> Source

Implementation-wise, you simply render to a texture at lower resolution than the screen, then render that texture to the screen.

Many render techniques nowadays involve post processing, so by default you render to a texture with the same resolution as the screen, apply some changes (blur, bloom, flares, etc), then send the whole thing to the screen.

To speed up performance you can make that intermediate texture a lower resolution than the screen. You can then decide to apply the post processing to the same low resolution, or if you want to apply post processing to a high resolution image.

If there is a "Resolution Scaling" setting that allows higher resolution (200%) and doesn't remove anti aliasing, that can have 2 possible causes:

* Some sources of aliasing don't simply disappear by using twice the resolution. (that's why some anti aliasing settings allow you to specify 2x,4x,8x,16x)
* Some aliasing may be part of the post processing effects which may run at the target resolution.

I'd really need to see a screenshot to make an educated guess at what's going on.

---
Tags: c++, graphics, hlsl
---


# Question
Title: Unity CaptureScreenshot captures and editor as well
I'm trying to create some screenshots but `ScreenCapture.CaptureScreenshot` actually captures the entire editor and not just the Game view.

I'm using this few lines of code here:

```
public class ScreenShotTaker : MonoBehaviour
{
    public KeyCode takeScreenshotKey = KeyCode.S;
    public int screenshotCount = 0;
    private void Update()
    {
        if (Input.GetKeyDown(takeScreenshotKey))
        {
            ScreenCapture.CaptureScreenshot("Screenshots/"
                 + "_" + screenshotCount + "_"+ Screen.width + "X" + Screen.height + "" + ".png");
            Debug.Log("Screenshot taken.");
        }
    }
}

```

What could be the issue?

# Answer
Took a look at it and it's actually a Unity bug, filed a report, see where it goes.

There are methods that rely on `RenderTextures` but they don't capture the UI. In the meantime, I asked this on Stack Overflow as well and got some handy answer that saves all pixel info from the screen like so:

```
public KeyCode takeScreenshotKey = KeyCode.S;
public int screenshotCount = 0;

private void Update()
{
    if (Input.GetKeyDown(takeScreenshotKey))
    {
        StartCoroutine(captureScreenshot());
    }
}

IEnumerator captureScreenshot()
{
    yield return new WaitForEndOfFrame();
    string path = "Screenshots/"
             + "_" + screenshotCount + "_" + Screen.width + "X" + Screen.height + "" + ".jpeg";

    Texture2D screenImage = new Texture2D(Screen.width, Screen.height);
    //Get Image from screen
    screenImage.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
    screenImage.Apply();
    //Convert to png
    byte[] imageBytes = screenImage.EncodeToPNG();

    //Save image to file
    System.IO.File.WriteAllBytes(path, imageBytes);
}

```

Note that this script though works, it has to be modified for the sake of convenience. It also worths mentioning that if you use `Outline` on your UI elements, those will become transparent if saved as `.png`, so I used `.jpeg` instead.
> 2 votes

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


# Question
Title: Good item distribution for 2d scroller game
I have made a scroller game where player moves to the right of the screen. I add a new uniform ground block about every 5 seconds.

I was wondering how often should I put bonus items. Currently I put them with 0.5 chance per added block of ground and if I fail to do, I do another 0.5 as a secondary chance. Once the player has enough number of items, then she can buy skins.

Is there a well known item distribution algorithm or a resource I can benefit from? I only have 1 type of item to keep it simple and the game is for mobile, but sounds like those items shouldn't be rare.

# Answer
> 2 votes
The frequency of bonus items would mostly affect the time players spend to acquire the necessary amount and buy a new skin. So, it comes down to the cost of the skins, the movement speed and the percentage of all bonus items players manage to collect. You can get a rough estimate of the time spent on buying one skin by calculating it from these variables.

The more often the players encounter the items, the less time they need to buy a new skin.

Or just run several playtests and measure how long it takes. This is also more precise and takes into account all the variables (including level design, which can be hard to incorporate into a formula). It is up to you to decide how much playtime buying the skins should take — better ones would require more time, you get the point.

---
Tags: algorithm, mobile, side-scroller, scoring, inventory
---


# Question
Title: How do I draw two lines of text in GMS and keep one static?
I am making an intro sequence for my game, but I'm having some difficulty drawing two lines of text. The first line is "DEVELOPED BY:" referenced from a separate language file as "IntroSequence", "DevelopedBy". The next line (made by using `+ chr(13) + chr(10) +`) is my name which I want to be kept static. I would essentially like the user to be able to make different language files being able to change the string reference "DEVELOPED BY:", but not the developer name. Now, I can get the text to draw if I use "DEVELOPED BY:#Mr.Mendelli" in the language file, or keeping both strings static in the script by declaring `mytext = get_text("DEVELOPED BY:" + chr(13) + chr(10) +"Mr. Mendelli");`. But If I use the second method, the `DevelopedBy` string cannot be translated in the language resource any more.

When I use the below script, GMS says two arguments are declared, but three are provided:

```
mytext = get_text("IntroSequence", "DevelopedBy" + chr(13) + chr(10) +"Mr. Mendelli");
image_alpha = 0;
statetime = 0;

```

How do I use my alias as an unchangeable separate line?

# Answer
The closing brace at wrong place. Must be:

```
mytext = get_text("IntroSequence", "MadeBy") + chr(13) + chr(10) +"Mr. Mendelli";`

```

or even just

```
mytext = get_text("IntroSequence", "MadeBy") + "#Mr. Mendelli";

```
> 1 votes

---
Tags: game-maker, windows, scripting
---


# Question
Title: How to run a pathfinder thread and game thread concurrently
Issue:

I want to be able to set up my game loop to work concurrently with my pathfinder request, that would be a queue which different units request for in order in the pathfinder thread.

My current attempts have so far failed.

```
   -

while (ConqEngine->IsRunning())
{
    bool running = ConqEngine->IsRunning();
    // Draw the scene
    ConqEngine->DrawScene();
    updateTime = ConqEngine->Timer(); // Frame Timer
    s1.pathfinderthread(ref(unitsneedpathfinding)) // this here, beginning of
    if (menuloop)
    {
        initial_menu_loop(loaded_men_interface, menuloop, loadloop, infoloop ,textControl);
    }
    else if (loadloop)
    {
        preconqload(loadloop, gameloop, startingx, pipnumber);
    }
    else if (infoloop)
    {
        if (ConqEngine->AnyKeyHit())
        {
            ConqEngine->RemoveSprite(MainAB.LoadingSprite);
            infoloop = false;
            menuloop = true;

        }
    }
else if (gameloop)
{
    if (game_n_setup)
    {
        SetupMusic("sound/RA2.ogg");
        sMusic.play();
        game_n_setup = false;
    }

    ConqCamera->LookAt(0, 0, 0);
    CamLastFrame = CameraVec;
    gameloop_interface(cspeed, CameraVec, displaycubes, dcubestime, CamLastFrame,
    draycasttime, CitySprite, cityspriteno, wealthtick, myFont, myFont2, textControl);
    gameloop_player(wealthtick, gameloop, menuloop);
    gameloop_units();
    //gameloop_interface()
    if (ConqEngine->KeyHit(Key_Escape))
    {
        gameloop = false;
        loadloop = false;
        menuloop = false;
        ConqEngine->Stop();
    }

    s1.join();
}

```

}

Currently what this attempts to do is that i have a bool for gameloop as a global, and a global\[currently\] lists of units needing pathfinding, and i am trying to execute the thread each frame seperately from the rest of the thing running, and then do a join at the end to force the program to wait for all to be completed but this causes a crash.

What is a good structure for multithreading my game with a pathing requester ? I'm honestly not sure how to tackle this the best way, I don't mind my Unit having to wait a few seconds, as that would look somewhat realistic anyway, a thinking animation is really no problem for me.

Is there a standard practice for seperating out the game loop with something else?

# Answer
> 1 votes
I'm not sure exactly what your requirements are for pathing or how the game should behave so this is going to be a general approach. You'll have to tune what data needs to be shared.

**Separate the threads**
I think the first step may be to not consider the threads working in step with each other. That meaning, don't pause your game loop to wait for pathing results. You want your gameloop to run at whatever minimum frequency you require to keep smooth results.

**Communicate work needed and solutions**
I'll admit my understanding on threads in C++ is limited, but in a higher level language like C# or Java, I'd suggest a couple of concurrent data structures. One for queuing pathing requests to the pathing thread, and another for sending solutions back to the gameloop.

Then you can leave the pathing thread to have its own loop of, grab a pathing request, solve it and place the results.

And your game loop simply decides what pathing it needs, and then processes pathing solutions as they become available.

The goal is to make the data flow in one direction, one thread can write to a structure and the other reads from it.

Decoupling this way could also mean using more threads for pathing if it becomes necessary.

**Responsiveness**
This does also mean that there could be a number of iterations on the gameloop between when pathing is requested and when a solution is available. If your game is real time, you have a couple of options for what an object in the game can do during those loops (which may not even be noticable to a player).

* Begin moving towards the destination, then adjust when the pathing solution is available
* Have the object animate in some way that makes it look like it's trying to figure out where to go
* Setup your solution data structure to be updatable. Your pathing algorithm could quickly include some first steps and update as you go. (This might be necessary if the pathing is meant to represent incomplete terrain data.)

# Answer
> 0 votes
I managed to fix my problem and make a nice concurrent system, the communication is handled with an abstract interface.

```
void pathingrequester()
{
    if (AWorld.RequestingPath.empty() != true)
    {
        AWorld.RequestingPath.front();
        astarpathfinder(AWorld.HiFiWaypoints, AWorld.RequestingPath.front()->pf_Source->ret_posX(), AWorld.RequestingPath.front()->pf_Source->ret_posY(),
        AWorld.RequestingPath.front()->UltimateDestination->ret_posX(), AWorld.RequestingPath.front()->UltimateDestination->ret_posY(), AWorld.RequestingPath.front(), AWorld.lines, AWorld.pointsInLine, MainAB.Path);
        AWorld.RequestingPath.pop_front();
    }
}

void gameloop(IFont *myFont, IFont* myFont2, abstractTextHandler &textControl)
{
    if (MainAB.game_n_setup)
    {
        SetupMusic("sound/RA2.ogg");
        sMusic.play();
        MainAB.game_n_setup = false;
    }

    ConqCamera->LookAt(0, 0, 0);
    MainAB.CamLastFrame = MainAB.CameraVec;
    gameloop_interface(MainAB.cspeed, MainAB.CameraVec, MainAB.displaycubes, MainAB.dcubestime, MainAB.CamLastFrame,
        MainAB.draycasttime, MainAB.CitySprite, MainAB.cityspriteno, MainAB.wealthtick, myFont, myFont2, textControl);
    gameloop_player(MainAB.wealthtick, MainAB.bgameloop, MainAB.bmenuloop);
    gameloop_units();
    //gameloop_interface()
    if (ConqEngine->KeyHit(Key_Escape))
    {
        MainAB.bgameloop = false;
        MainAB.bloadloop = false;
        MainAB.bmenuloop = false;
        ConqEngine->Stop();
    }

    stringstream mui;
    stringstream mui2;
    stringstream mui3;

    if (ConqEngine->KeyHit(Key_O))
    {

        EntityUnit* a;
        a = dynamic_cast<EntityUnit*>(AWorld.EntitiesVector[45]);
        a->set_source_waypoint(AWorld.HiFiWaypoints[104][53]);
        a->UltimateDestination = AWorld.HiFiWaypoints[DebugUP->currLine][DebugUP->currDot];

        AWorld.RequestingPath.push_front(a);
        MainAB.x = DebugUP->currLine;
        MainAB.y = DebugUP->currDot;

    }
    if (ConqEngine->KeyHit(Key_Z))
    {
        EntityUnit* a;
        a = dynamic_cast<EntityUnit*>(AWorld.EntitiesVector[45]);
        for (auto i = a->pf_waypoints.begin(); i < a->pf_waypoints.end(); ++i)
        {
            cout << (*i)->ret_posX() << ":" << (*i)->ret_posY() << endl;
        }
    }
    //s1.join();
    MainAB.SkyboM->RotateLocalY(0.001);

```

## }

```
 /**** MAIN GAINLOOP ****///--------------------------------------------------
        while (ConqEngine->IsRunning())
    {
        bool running = ConqEngine->IsRunning();
        // Draw the scene
        ConqEngine->DrawScene();
        updateTime = ConqEngine->Timer(); // Frame Timer

        if (MainAB.bmenuloop)
        {
            initial_menu_loop(MainAB.loaded_men_interface, MainAB.bmenuloop, MainAB.bloadloop, MainAB.binfoloop ,textControl);
        }
        else if (MainAB.bloadloop)
        {
            preconqload(MainAB.bloadloop, MainAB.bgameloop, MainAB.startingx, MainAB.pipnumber);
        }
        else if (MainAB.binfoloop)
        {
            if (ConqEngine->AnyKeyHit())
            {
                ConqEngine->RemoveSprite(MainAB.LoadingSprite);
                MainAB.binfoloop = false;
                MainAB.bmenuloop = true;

            }
        }
        else if (MainAB.bgameloop)
        {
            thread gl(gameloop,ref(myFont), ref(myFont2), ref(textControl));
            thread pl(pathingrequester);
            gl.join();
            pl.join();
        }

        /**** Update your scene each frame here ****/

    }
// Delete the 3D engine now we are finished with it

ConqEngine->Delete();

```

}

This means my Normal A\* pathfinding only takes 0.9 seconds over medium distances, and will mean when I finish my implentation of HPA\* is complete, it will be near negligible performance loss.

---
Tags: c++, multithreading
---


# Question
Title: Is it legal to mod a MMORPG game to make it look like another franchise and profit from it?
Let's say I take World of Warcraft and I mod it to make it look like a Dragon Ball game and I obtain profit from it, would it be legal?

# Answer
**Simply put, no.** Not only are you using the copyrighted engine of *World of Warcraft*, you're also introducing another franchise's assets (this could mean anything—concepts, characters, etc.) and passing them off as your own.

According to Wikipedia's article on the Copyright law of the United States, the following six rights are the basic rights that the copyright law protects:

* To reproduce the work in copies or phonorecords;
* To prepare **derivative works based upon the work**;
* To distribute copies or phonorecords of the work to the public by sale or other transfer of ownership, or by rental, lease, or lending;
* To publicly perform the work, in the case of literary, musical, dramatic, and choreographic works, pantomimes, and motion pictures and other audiovisual works;
* To **publicly display the work**, in the case of literary, musical, dramatic, and choreographic works, pantomimes, and pictorial, graphic, or sculptural works, including the individual images of a motion picture or other audiovisual work.
* To digitally transmit sound recordings by means of digital audio transmission.

A company controls whether or not you can do any of these six things, and will generally, in their copyright info, will say what you can or cannot do.

A violation of any of these rights results in a copyright infringement suit, and as you may know in Flappy Bird's case (where the programmer used assets directly from Nintendo's *Super Mario Bros.* series), is a messy case and never works out in the accused's favor.

Now, let's check the copyright information on Dragon Ball's webpage, which states:

> Materials on FUNimation.com and related sites are solely for your personal, non-commercial use. Without the express written consent of FUNimation or other rights holder(s) listed below, these materials may not be copied, reproduced, republished, uploaded, posted, transmitted, or distributed in any way, including by e-mail or other electronic means. Without the prior written consent of the owner, modification of the materials, use of the materials on any other web site or networked computer environment, or use of the materials for any purpose other than personal, non-commercial use is a violation of the copyrights, trademarks, and other proprietary rights, and is prohibited.

As they say in the final sentence, "use of the materials for any purpose other than personal, non-commercial use" violates their rights, and is therefore prohibited. so, if you create a derivative work (something based off of and/or using the franchise's assets) and use it for commercial purposes (using it for any other reason than for personal or non-commercial use), you're in direct violation of their rights, and **it is illegal**.
> 4 votes

---
Tags: legal
---