title: How To Animate A JavaScript Function

text:
# Question
Title: How To Animate A JavaScript Function
I've been making this game where one of the characters, The Bandit, runs away from you mistaking you for a zombie. However, I can't seem to be able to animate the bandit. Is there a way I could use this w3schools example and make it fit with this canvas function?

The code for bandit is here or the second site:

```
   function drawBanditFacingDown(){
        //His face
    ctx.fillStyle = "#FFDE7A";
    ctx.fillRect(banditX, banditY, 25, 25);
    //His left eye (your left not his)
    ctx.fillStyle = "black";
    ctx.fillRect(banditX + 5, banditY + 5, 5, 8);
    //His right eye (again your right)
    ctx.fillRect(banditX + 15, banditY + 5, 5, 8);
    //His bandit thing on his mouth? I don't know what it's called
    ctx.fillStyle = "red";
    ctx.fillRect(banditX, banditY + 15, 25, 10);

    //His shirt
    ctx.fillStyle = "black";
    ctx.fillRect(banditX + 5, banditY + 25, 16, 25);

    //His arms
    //His right arm (YOUR RIGHT!!!!)
    ctx.fillStyle = "#FFDE7A";
    ctx.fillRect(banditX + 21, banditY + 25, 8, 20);
    //His left arm (On your left side)
    ctx.fillRect(banditX - 3, banditY + 25, 8, 20);

    //His pants
    //His right pant leg (ur right)
    ctx.fillStyle = "#11226B";
    ctx.fillRect(banditX + 12, banditY + 49, 8, 20);
    //his left pant leg
    ctx.fillRect(banditX + 5, banditY + 49, 8, 20);
    ctx.fillStyle = "black";
    ctx.fillRect(banditX + 11, banditY + 53, 3, 15);
    //his shoes
    //200 LINES!!!!!!
    ctx.fillStyle = "black";
    ctx.fillRect(banditX + 5, banditY + 68, 15, 5);
    }

```

# Answer
> 2 votes
If I understand correctly you're asking how to get your function called multiple times in such a way to create an animation.

Its better to think of this problem in a different way however. Instead of thinking how can you get a moving animation, think of it as a repeating game loop that has two stages to it.

The first that updates your game's logic and the second that re-renders your entire scene.

Thankfully with the JavaScript environment in modern browsers, creating a gameloop is quite easy. You actually have a few options.

**Set Interval**

The `setInterval();` function takes two values, the first is the name of the function you want to repeat and the second is the time in milliseconds in which you want to delay when the function is called again.

So for example

```
function update() {

}

function render() {

}

function loop() {
    update();
    render();
}

// Sets loop to run at ~60FPS
// 1000ms = 1s, 1000 / 60 = 16ms
setInterval(loop,1000 / 60);

```

This will get your game running in a loop, but calling `setInterval();` again will cause problems by effectively creating two loops.

If you want to stop a loop you have created this way, you can use the value returned from `setInterval();` in the `clearInterval();` function.

```
let loopID = setInterval(loop,1000 / 60);

// stop the gameloop
clearInterval(loopID);

```

**Set Timeout**

The `setTimeout();` function is the exact same as setInterval apart from one important detail, It waits for the delay you give and executes your function only once.

This is slightly more preferable since control on weather the loop needs to continue can be given over to the programmer.

but to use this to cause a function to loop like before.

```
function update() {

}

function render() {

}

function loop() {
    update();
    render();

    setTimeout(loop,1000 / 60);
}

setTimeout(loop,1000 / 60);

```

Similarly `setTimeout();` has a cancel function as well `clearTimeout();` that you can use in the same was as `setInterval();`.

**Request Animation Frame**

Probably the most well suited looping function for game programming in browsers. `requestAnimationFrame();` will take a function and call it at the next vSync (This depends on the browser). In essense what this means is that it will automatically put a loop at 60FPS and take lag into account.

```
function update() {

}

function render() {

}

function loop() {
    update();
    render();

    requestAnimationFrame(loop);
}

// No additional values required
requestAnimationFrame(loop);

```

Like the two other functions, `requestAnimationFrame();` can be stopped with `cancelAnimationFrame();`.

A clear advantage that this function has over the other two is what happens when a user switches tabs. A game loop using this function will effectively become paused when a user switches tabs and resume when they come back, whereas the other two loops would still be running.

**Using A Loop For Animation**

Using the approach I provided for animation shouldn't be too difficult.

assuming I have a square as follows.

```
let square = {
    x: 0,
    y: 0,
    dx: 1,
    dy: 1,
    width: 10,
    height: 10
}

```

I can use the `update();` function to move it forward little by little each loop and then re-draw it at it's new position using `render();`

So the complete animation would look like this

```
function update() {
    // dx & dy refer to delta x & y (velocity)
    square.x = square.x + square.dx;
    square.y = square.y + square.dy;
}

function render() {
    // clear the canvas
    ctx.fillStyle = "gray";
    ctx.fillRect(0,0,canvas.width,canvas.height);

    ctx.fillStyle = "darkred";
    ctx.fillRect(square.x,square.y,square.width,square.height);
}

function loop() {
    update();
    render();

    requestAnimationFrame(loop);
}

// No additional values required
requestAnimationFrame(loop);

```

---
Tags: javascript, animation
---


# Question
Title: How to change size of collider attached to UI Image in unity
I have a circle image which has a Cicle collider 2D and Rigidbody 2D attached to it and its size (width and height) is constantly increasing in script like this:

```
rt = circle.GetComponent<RectTransform>();
float width = rt.rect.width + increment;
float height = rt.rect.height + increment;
rt.sizeDelta = new Vector2 (width, height);

```

The collider doesn't change size with UI Image as it expands...what should i do in order to make the collider change size as UI Image changes size.

# Answer
> 1 votes
Create `private CircleCollider2D _yourImageCollider;`.

Assign it on awake, so you don't need to lose performance for getting it every time.

```
private void Awake()
{
    this._yourImageCollider = GetComponent<CircleCollider2D>();
}

```

When you increase / decrease width and height - change colliders radius `this._yourImageCollider.radius += increment * 0.5f;`.

Or you can set radius of the collider to match exactly the size of an image plus the offset if it's necessary.

```
private float _colliderRadiusOffset = 0.4f;
.
. Code
.
    this._yourImageCollider.radius = rt.rect.width + this._colliderRadiusOffset;

```

# Answer
> 0 votes
```
void Update(){
     if(rt.sizeDelta.x > oldSizeX + accuracy){ //Compare UI circle X size to its old size + accuracy offser
          if(rt.GetComponent<CircleCollider2D>() != null) //If it actually has a circle collider
             Destroy(rt.GetComponent<CircleCollider2D>()); //Remove it
             rt.AddComponent<CircleCollider2D>(); //The add a new one to fit the current size
             oldSizeX = rt.sizeDelta.x; //Reset the old size, and wait for it to expand beyond the accuracy offset
     }
  }

```

The lower the accuracy, the slower your game will be, try to update the new collider once every 0.5 units or so, but it's your choice.

Also, this only works if the circle is expanding like you explained in your example.

---
Tags: unity, rigidbody
---


# Question
Title: Clearing screen in Pygame so content on the screen is not lost, but updated
I am creating a Tetris game using Pygame. It generates a random shape from a list and draws it onto the screen. However, when the arrow key is pressed by the user, it draws the shape again without removing the previous one. The problem is that I can't use `screen.fill(White)` as it will remove the other shapes at the bottom of the grid. How can I refresh the screen without removing the shapes at the bottom of the grid, and so that it doesn't draw the shape multiple times? The first image shows the original shape, and the second image shows the result of pressing the arrow key.

# Answer
> 1 votes
This is not how games are usually done. The basic gameloop is usually implemented as follows:

```
while True:
    handle_events()
    update_objects()

    clear_screen()

    for object in objects:
        object.draw()

    update_screen()

```

So instead of only updating a certain part of the screen, you redraw the whole screen every frame. That is extremely common.

So what you want to do is to keep track of all your objects, and implement a way to cleanly redraw them. Predrawing each piece to a surface might be something you'd want to consider. Doing this will save you a lot of trouble in the future.

# Answer
> 0 votes
You can fill only some area, not all screen by calling `screen.fill(White, areaToFill)`. Also, your problem might be that you draw the shape again in different place, though you need to move `rect` position of the shape - this should automatically redraw shape on other position not leaving any previous shape.

For `Surface.fill` look here: Surface.fill. This seems to be a good start to understanding how everything works in pygame: Pygame Tutorial . Aslo, Introduction to pygame.

---
Tags: python, pygame
---


# Question
Title: Textures drawn with visible missing lines of pixels
I am making a game in monogame and have encountered the following problem:

The black arrows mark the places where the rendering is "off". As you can see the gray lines aren't "flush" or "smooth". Instead they have a "cut".

The two cuts at the top is at the same height, suggesting that an error happens with the positioning during drawing in that height. The two topmost cuts are 1 pixel off (from the cut and down) and the bottom cut is 1 pixel off compared to the texture but 2 pixels in total (again from cut and down). Furthermore, the cuts are always in the same place. The topmost cuts and the bottom cut are part of two different "draws" and happens even if the other is removed.

The background experiences this too some other places, but vertically and not horizontally as with the HUD.

This only happens in the resolution of 1920x1080 and not in any other I've tried. The problem fixes itself in fullscreen though.

What causes this and how do I fix it?

**EDIT**

The resolution is certainly 1920x1080. I've double checked that.

This is how i draw the gray frame at the top

```
spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend);

spriteBatch.Draw(txtExpFrameLeft, new Vector2(0, 7), null, Color.White, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0.81f);

spriteBatch.End();

```

No resizing at all.

**EDIT 2**

Here is the result from the checker board:

As said, there are missing lines spread evenly around. When i move the gamecursor onto one of those "lines", it itself is also affected. Everything is still fine in fullscreen

# Answer
> 1 votes
Looks like you are drawing sprites with "nearest-neighbor" interpolation and sprite size on screen is set few pixels smaller than it should be.

Check your drawing dimensions, do you really output the images in their native size.

It could be that in windowed mode you still assume the canvas size (render area) is 1920x1080, while in fact it is smaller by windows borders.

---
Tags: c#, textures, graphics, monogame
---


# Question
Title: Publish game as pay-what-you-want on Steam
Is it possible to publish a game on Steam as pay-what-you-want? Something in the likes of the Humble Bundle. If it's not natively supported by Steam, would it be fine (as in, not violating any contracts or agreements) to have the game published as free (or at a very low cost) and include a link to a page where you, if you so wish, could donate a sum of money?

# Answer
Steam does not have direct support for this kind of model.

It's common to fake it on other store fronts (such as on iOS) by making the game available for free and selling some kind of renewable microtransaction that is effectively a "tip jar."

Steam does not mandate exclusivity from you, and many developers also sell their game elsewhere. There are plenty of examples of developers who are putting games on Steam and also receiving donations outside of Steam, for example from Patreon or the like. There does not appear to be anything in Steam's user agreements that contradicts such an approach.
> 2 votes

# Answer
Another work around, discussed in this Kotaku article is selling "support the devs" style DLC on Steam.

Some, like Thea: The Awakening - Coffee for Coding DLC (also discussed on their blog) include bonus content that doesn't change gameplay:

> Coffee for coding is an initiative inspired by our faithful fans who have expressed the desire to reward our efforts in delivering the free DLCs and frequent updates.
> We stand by our decision to make our content free, but we will not say 'no' to some loose change coming our way. After all, more coffee = more coding, right? ;)
> We also include a gift for all those who wish to say thanks – a full deck of Thea Cards, in the form of high resolution jpgs, featuring our gorgeous character artwork!
> You can use the cards for role playing games, or just enjoy the drawings.

Others, like the the Relic Hunters Zero: Remix Donation - "Thank You" DLC have no content:

> This DLC contains no data, no new content, and no bonuses or cosmetic rewards. Only buy this if you wish to thank Rogue Snail for supporting this game for free for over 4 years, while keeping the game Open Source and available for modding and teaching purposes.
>
> Thank you for your generosity!

You can find other examples in the previously linked Kotaku article or by searching Steam for 'donation'

Note: I have *not* read the fine print of Steam's developer or user agreements, I'm inferring permissibility based on prior examples.
> 2 votes

---
Tags: publishing, steam, payment
---


title: Color Switch Collision Detection

text:
# Question
Title: Color Switch Collision Detection
If you don't know what color switch is look here: http://poki.com/en/g/color-switch

I need a good way to detect the color collisions, one way would be to get the colors of pixels around the ball on the jpanel but I don't know how that would work. I can't use Shapes and Area intersections because some of the obstacle shapes have a hole in the center so I can't use the shape and area class to find collisions.

Any Ideas would be great.

All my Obstacles are made with A multiple Shape objects for different colors and holes.

# Answer
> 1 votes
I strongly suggest you to stay away from the pixel color checking, as it will decrease the performance a lot. Sorry for giving this kind of information but creating this kind of game with standard java libraries is completely the same with re-inventing the wheel.

What I would recommend to you is try using a framework at least, like Libgdx, slick2D. Because you need to create classes for obstacles, since you need to carry out the shape, color, rotation speed etc. at the same time. That is nearly impossible work to do with Java libraries. With those frameworks I guess you would be able to create obstacle shapes with hole in the center.

# Answer
> 1 votes
From the quick preview of the game, I assume it would be possible to just do a circle vs circle collision detection. You could accomplish this by seeing if the intersection range is more and less then a certain threshold (this would like you go inside the ball, but a small area would be intersectable).

To accomplish the color collision part, you could test the ball colour with a hard coded colour related to the rotation of the ring (rotation % 360) and say if it is less than 90 but more than 0, only a certain colour can pass. Of course this would only work for one axis (like in the demo), but I assume you could expand it to use the x axis aswell.

Demo (FLAWED doesnt take in account both rings will edit oops!)

```
public void testCollision()
{
    collision = false;
    float x1 = ballPosX;
    float y1 = ballPosY;
    float x2 = ringPosX;
    float y2 = ringPosY;
    r1 = ballScale;
    r2 = ringScale;
    float distanceBetween = (x2-x1)^2 + (y1-y2)^2;
    float ringThickness = 0.5f;
    if(distanceBetween <= (r1+r2)^2)
    {
        if(y1 + r1 > y2 + yScale - ringThickness && y1 + r1 < y2 + yScale + ringThickness )
        {
            collision = true;
        }
        //do same for bottom of ring
    }
    if(collision)
    {
        float ringRotation = someValue;
        if(ringRotation % 360  < 90 && ballColour == RED)
        {
            killBall;
        }
        else
        {
            //ball is OK
        }
        else if(ringRotation % 360  < 180 && ballColour == BLUE)
        {
            killBall;
        }
        //FOR OPPOSITE SIDE OF RING : do same thing but check if ball y > ring y (or other way around) and then do the opposite value check (eg: 90 degree = 270 degree)
        //etc etc...
    }
}

```

---
Tags: java, collision-detection
---


# Question
Title: Creating trading card board layout in libgdx
I wanna make a trading card game using libgdx. I have a general idea about how to implement the server side of the game and the game rules, but I don't know how to design the visual interface of the game (in the client side). I want to create a layout similar to the one in the image below, but quite a bit simpler. I don't have an idea of how to do it though. I'm thinking of using `scene2d` and `Table` and have a row the opponent, one for the player and two for the creatures and then each cell is a card/creature. Is that a good way or is there a better way?

# Answer
> 0 votes
If you are asking whether to use or not to use scene2d.ui as your interface i would say the answer is a definitive yes. As many people here will tell you that reinventing the wheel is not really the most efficient way to go about things.

The ui framework provided by libgdx is really powerful and should be taken advantage of whenever possible. Combine it with some form of tween framework and you can achieve very flashy effects akin to that of a AAA game like hs.

This feels like more of a design question though.

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


title: Pathfinding function crashes Unity?

text:
# Question
Title: Pathfinding function crashes Unity?
I've been trying to add this pathfinding function to my program, but when I run it, it just crashes. I've read other threads and this might be an infinite loop, but I don't see where it would be other than the recursion area (and it shouldn't break there because of the if-statement checking if it's out of bounds).

```
public void SetPath(Vector3 pos, Vector3 goal, Queue<Vector3> p, List<Vector3> visited, int cost) {

     Debug.Log("checking " + pos);

     //method which checks if the target tile is outside of the map
     if (core.OutOfBounds((int)goal.x, (int)goal.z))
         Debug.LogError("target tile " + goal + " is out of bounds!");

     //if the current position isn't out of bounds and hasn't been visited
     else if (!core.OutOfBounds((int)pos.x, (int)pos.z) && !visited.Contains(pos)) {

         Debug.Log("pos is within the limits of the map");

         //add tile to the visited list and path queue
         visited.Add(pos);
         p.Enqueue(pos);

         //add tile movement cost to total path cost
         cost += core.TileCost((int)pos.x, (int)pos.z);

         //if the current position is the target tile and the path is shorter than the current one
         if (pos == goal && cost < shortestPath) {
             Debug.Log("pos is the target tile");
             shortestPath = cost;
             path = p;
         }

         //else, check tiles around
         else {

             SetPath(new Vector3(pos.x + 1, 0, pos.z), goal, p, visited, cost);

             SetPath(new Vector3(pos.x, 0, pos.z + 1), goal, p, visited, cost);

             SetPath(new Vector3(pos.x - 1, 0, pos.z), goal, p, visited, cost);

             SetPath(new Vector3(pos.x, 0, pos.z - 1), goal, p, visited, cost);

         }
     }
 }

```

# Answer
> 1 votes
This function will recurse over the entire grid doing so very inefficiently.

If you have a 500 x 500 grid that will cause a (nearly) 250,000 deep call stack.

The solution: Use a `Queue<Vector3>` of **positions to visit** and a while-loop that consumes the queue rather than a recursive call. Also to speed up the visited check use a 2D array of visited `bool` rather than a linear `List<Vector3>` search.

---

But to explain what's happening right now, for example if you start at (0, 0, 0) and the exit is at (1, 0, 1) this is what it will do (I've shorten it from step 17 onward)

*For brievity I call (Z+1) down, (Z-1) up, (X+1) right, and (X-1) left in the explanation as if it was a 2D map in classic 2D orientation replacing Y with Z*

1. it will first recurse over `SetPath(new Vector3(pos.x + 1, 0, pos.z), ...)` until it hits the right-side boundary,
2. then return once,
3. then recurse once over `SetPath(new Vector3(pos.x, 0, pos.z + 1), ...)`
4. then `SetPath(new Vector3(pos.x + 1, 0, pos.z), ...)` hit the right side boundary
5. then return once,
6. REPEAT FROM 3 and recurse until it hits the bottom boundary
7. then return once,
8. then recurse once over `SetPath(new Vector3(pos.x - 1, 0, pos.z), ...)`
9. then recurse once over `SetPath(new Vector3(pos.x + 1, 0, pos.z), ...)` hit visited
10. then return once
11. then recurse once over `SetPath(new Vector3(pos.x, 0, pos.z + 1), ...)`, hit boundary
12. then return once
13. then recurse once over `SetPath(new Vector3(pos.x - 1, 0, pos.z), ...)`
14. REPEAT FROM 9 and recurse until it hit left boundary
15. then recurse once over `SetPath(new Vector3(pos.x, 0, pos.z - 1), ...)`, (going up)
16. then recurse over `SetPath(new Vector3(pos.x + 1, 0, pos.z), ...)` all the way to the rightmost column that got visited.
17. Try down: visited, return
18. Try left: visited, return
19. Recurse up,
20. Try right: visited, return
21. Try down: visited, return
22. Recurse left,
23. REPEAT FROM 20, until left boundary is reached
24. REPEAT FROM 15, **snaking its way back up very slowly eating up at the stack recursing on every cell until it crawls back up to (1, 0, 1)** or the stack overflows.

Every visited cell is 1 recursion on the stack until the end is reached, then returns until it finds an unvisited cell, then recurse again until they're all visited.

---
Tags: unity, path-finding, recursion
---


# Question
Title: AI: Turn-Based Movement with 2 actions per Unit
I am currently building a turnbased tactics game.

The Board is a small (about 4\*6) tiled grid.

The AI plans all moves of its units, each unit can

* move 2 times
* move and attack
* or attack

at least in this basic stage.

Only one unit can be on a grid cell at any given moment. But a Unit can take a turn to a grid cell which was just left by the former occupant.

The AI plans out the whole turn in advance, and then the actions is played.

**The Mission: The AI should maximize the attacks for each round. Currently only Melee is implemented, so this means maximize the count of own units in the grid cells next to the player units, and they should have a turn left to attack, if possible.**

I am having a hard time with units getting moved on tiles, where a other unit is still present and so on.

Is there some kind of algorithm or even brute-force approach to match the the criteria?

# Answer
> 0 votes
One bug you could encounter is that in a single turn moving up to make space will *never* increase the total attacks that turn. Since moving up consumes one action it prevents one attack. The ally that moves into the freed space can attack once. The total attacks this turn are unchanged.

You could resolve this in two ways:

1. looking ahead multiple turns and maximizing attacks using a brute force method (something like min-max) this is doable but of approximate complexity O( (36p)^n ) where p=pieces and n=turns that you look ahead.
2. Decide on a behavior, and write a program to have the pieces move that way. This is less resource intensive, but a bit abstract. It will not give a strategically perfect AI.

Given what you describe I would recommend the second option. The desired behavior is to shuffle up in oder to let an ally advance.

This could be done by evaluating units that are within one tile of the players units. They can mark tiles as desired. Units whose tile is desired by an ally will try to advance and attack instead of attacking twice. If this is not possible they decide to attack twice, and the piece behind them tries to find a different square to move into. Pieces further away will move towards enemies, until they get close enough to start requesting that their allies give them space.

---
Tags: algorithm, ai, path-finding, grid, turn-based
---


# Question
Title: Is there a value in unifying animation lengths in turn based game?
It might be a small detail, but I'm wondering if there is a significant impact on the game feel between scenario where for example all characters in a game have the same attack animation length and scenario where each character may have different attack animation length.

Has there ever been anyone exploring such topic?

# Answer
In a turn based game, your intuition is probably correct - it's a small detail. More important is making sure none of them are too long. Especially if they aren't skippable, overlong animations can turn an asset (beautiful animation) into a liability (annoyed players feeling like their time is being wasted watching the same attack for the millionth time).

If you have simultaneous animations (i.e. defender parrying an attack), I suppose a uniform animation length might make synchronizing them easier, but that sounds a bit like premature optimization.

In contrast, if it was real time, animation lengths matter a lot. For instance, in a platformer, different jump animations could make some characters feel floaty. In a fighting game or brawler, animations lengths can be critical to strategy of high performance game play.
> 1 votes

# Answer
It can make sense from a development perspective. When all animation sequences are unified, your animation management code can be a lot more concise.

From a user experience perspective: You want attack animations in a turn-based game to be short and sweet anyway. Remember that players will see these animations *a lot*. A super-elaborate 30 second attack cutscene might be awesome the first time you see it, but after 10 or 20 repetitions it just becomes tedious and the players will start to google for a mod to get rid of them. This might be an extreme example, but the same also applies to *slightly* longer than average attack animations. In the long run, players will start to detest the units which just steal their precious time with their longer attack animations. By putting a self-imposed time restriction on your attack animations, you avoid that.

There is also a more subtle UX effect: An unified animation length can put the player into a steady and regular clickclick-watch-clickclick-watch-clickclick-watch rhythm. This puts the player into an immersive, trance-like flow-state where they are completely focused on the game. This is usually a very pleasurable experience for the player. When that interaction rhythm is more irregular due to different lengths of watch-phases, the player will have a harder time to "get into the flow". This is more of a subconscious effect. So the test players will likely to be unable to tell why, but they will be able to tell that *something* is off with the how the game feels.
> 1 votes

---
Tags: game-design, animation, turn-based
---


title: Disc based storage medium

text:
# Question
Title: Disc based storage medium
I am only just dipping my toe in the water of game development, so forgive my ignorance if you will:

Regarding console AAA titles with massive open-world settings: How do all of the art assets and game data fit on a double-layer Blu-ray Disc with around 55GB of available space?

I have a game idea that would utilize street data from Open Street Maps, but the single file for the world's street data seems to large to fit, much less anything else like code or art. Is the secret here compression, or just that 55GB is typically not a concern because games aren't using file sets as large as the entire world's road maps?

# Answer
> 2 votes
I'm sure there are any number of approaches, these are some of them:

* Compression: reduce the space need on the disc at the cost of retrieval+decompression later which costs cpu usage and time
* Download as needed: get the data you need as you need it and cache/discard data that is no longer needed. Requires some kind of server infrastructure, but it may already exist and be available for your application.
* Pre-process: Take the original data and strip out anything you don't actually need for the game itself, which might pose some problems if the game isn't totally complete/planned out and so you end with a full disc and needing some additional data/metadata.

There is also always the option to go with lower quality assets (art, music) and less sophisticated code/AI. The core game/mechanic may not require that level of detail or accuracy to approximate realism and still be fun/playable. It sounds like you need to flesh out the idea somewhat and figure out exactly what is contained within the Open Street Map data. The reason is that you need to know exactly what data the game will require and if there is anything you can just straight out omit. Such an inquiry might also prove to show that the scope of the game is just too broad and should be simplified regardless.

It's almost certainly a balancing act in the end, you may actually have to immerse yourself in such a project to know beyond a doubt whether it's viable. You can also just shove the requirement at at the player and hope for the best. Most people don't balk at a 10GB game these days because their hard disks are very large. I remember that Neverwinter Nights 1 was ~4GB of disk space back when my hard drive was only 80GB. That's 1/20 or 5% of the total disk. Obviously that didn't keep people from playing it. On the other hand Team Fortress 2 takes up 18.4GB of my hard drive except that my current hard disk is a 1TB drive so it's only 20/1000 or 2% of the disk space.

I am giving PC numbers, but the PC/console difference seems less and less every year. In any case the point is that there's some hardware use target and they develop toward it intentionally, probably even more so on a console. A game requiring 7 DVDs seems rather insane to me, but if the players will buy it and play it. The fact of a captive audience that needs a game to play on their console seems relevant here.

# Answer
> 3 votes
Many games get bought on the internet. Stuff like the Call of Duty Infinite Warfare and Modern Warfare bundle simply won't fit on a CD (They take up together around 200Gb), or the new version of GTA 5 (that was 60 GB), which did have a physical version, but it required 7 DVDs to fit, which is unacceptable if you're playing.

That said, there are ways to get data without having it on your hard-drive/Disc. Put the street information on a server and make the game request it from there in smaller chunks. If this isn't available for you, then try to compress it.

# Answer
> 0 votes
Does your game really need *all* the data of Open Street Maps at the same time? When your player is only playing in a small area in North Bolivia, then your game likely doesn't need the map data from South Cameroon. That means you might want to consider to ship your game without map data (maybe except for a low-detail world map to allow the player to navigate to the location they want to play in) and then download the required map data from the Internet whenever the player enters a new map area.

---
Tags: data, storage
---


title: Calculate the leaning angle

text:
# Question
Title: Calculate the leaning angle
I have an object moving around, let's say it's a cycle. In cycle dynamics, when the object takes a turn, it often leans into the direction of the turn. I would like to simulate this.

I'm using the equation: `atan(v^2 / r * g)`, where `v` is the current velocity, `r` is the radius of the turning circle and `g` is the gravitational force. I get `r` with `v^2 / a`, where `a` is the current acceleration.

However it doesn't seem to work right. In some cases it leans to the right direction, in others, it leans to the opposite, meanwhile the leaning should always be inwards.

I've determined the direction where the acceleration force pulls the object with `sign(velocity.y * acceleration.x - acceleration.y - velocity.x)` and multiplied the leaning with the result, but it has no effect.

What am I missing?

# Answer
> 1 votes
To calculate how an object leans when it turns, you need a lot of things, such as: the center of mass, the points of support (in the case of a vehicle these are the outer edges of the wheels), the suspension strength, the speed, the friction coefficient of the road and the wheels, etc. Due to this, you'll have to fake it to some extent, but even that doesn't make the mathematics simple, just *simpler*.

So, we can assume the vehicle is a box, the center of mass is in the exact middle. You need to define the friction coefficient (a value between 1 and 0, 0 is frictionless and the car can't lean, 1 makes the car stop immedialitely), you need to know the radius of the turning circle and the mass of the object.

Let's look at the actual formula:

```
Fcf = mrw²

```

`Fcf` is the centrifugal force, `m` is the mass of the object (in kilograms), `r` is the radius of the turn (in meters) and `w` (should be a lowercase omega) is the angle speed (in 1 / second). We can calculate the last by getting the angle the object rotates in a second in radians and divide it by 2π, or if it is in degrees, then divide it by 360°.

With this we can calculate the centrifugal force's strength. This force always points outwards from the center and applies to the center of mass.

We can then calculate the strength of the frictional force with the following formula:

```
Ff = μFcf

```

Where `Ff` is the frictional force, `μ` (mu) is the friction coefficient and `Fcf` is the centrifugal force.

This force doesn't apply to the center of the mass however, this always applies to the lowest point in the object under the center of the mass. This force difference is why the vehicles lean. The center of the mass is trying to go to somewhere, but the base is going in the other direction. What happens is basically the same as when you hit someone in the stomach from the left and you swipe his leg to the right in the same time (it's literally the same), then he will fall over to the left.

We need to calculate the rotational force the frictional force makes. If you use an engine with a good physics engine in it, then I highly recommend just applying these two forces to the object at the right places, but if you don't, here's how you calculate the rotation:

First let's calculate the force, which is marked by `τ` (tau). Because the force vector is always in 90 degrees to the vector between the center of the mass and the base of the object, so the formula is a bit simpler than usual. The length of `τ` is

```
τ = rF

```

Where `r` is the distance from the center of mass and the base and `F` is the force, or in this case the frictional force.

Then we can calculate the angular velocity, `τ = Iα` where `I` is the moment of inertia (I'm going to get to this in a minute) and `α` (alpha) is the angular velocity.

We need to first calculate `I`, which is

```
I = mr²

```

Where `m` is the mass of the object and `r` is the distance between the center of the mass and the base.

With this you can calculate `α`. Now you need to take this and every frame add it to the angular velocity of the vehicle, then you add that to the angle of the vehicle, and you should get yourself a leaning vehicle.

But you also need it to go back to normal, when you stop. This can be done by calculating the same thing with the gravity instead of the friction, making the center the edge on which the vehicle "stands" instead of the center of the mass and applying the force in the cebter of the mass instead.

That should also get you an angular velocity in the other way. You should divide this from the velocity of the vehicle, if it's currently leaning.

---
Tags: physics, geometry
---


# Question
Title: Proper names and wordings for Real/Fake fullscreen video modes
I have an option in my game which allows Player to choose between video modes:

* Fullscreen Fake
* Fullscreen Real
* Windowed

First and second corresponds to `SDL_WINDOW_FULLSCREEN_DESKTOP` and `SDL_WINDOW_FULLSCREEN` in the SDL library.

While their meanings whould be clear for GameDev people, for average Player, I think, it will be not so obvious. I never saw any examples of that kind of Video Settings. Other games often provide just a choice between the two: Fullscreen / Windowed.

What names and explanations I should provide, so it will not be confusing for a common user ? Are there any examples of games which have similar options ?

# Answer
From the SDL Docs:

> SDL\_WINDOW\_FULLSCREEN\_DESKTOP for "fake" fullscreen that takes the size of the desktop

This sounds like what other games call *Borderless Mode*, *Borderless Windowed Mode*, or similar. I'm sure, gamers will understand these terms.
> 10 votes

# Answer
I'll assume you're referring to PC because prior to Android Nougat, mobile doesn't really have "Windowed". On a PC, even one connected to an SDTV through a scan converter, you have room to explain what each mode does:

* **Exclusive full screen**
Uses full GPU capability and allows changing display resolution. Switching to other apps is slow.
* **Cooperative full screen**
Fills the screen and shares the GPU with the desktop. Switching to other apps is fast.
* **Windowed**
Runs in a window and shares the GPU with the desktop.

But in the era of fixed-pixel LCDs and cheap upscaling on the GPU, there's somewhat less of a need for exclusive full screen except on machines near the game's minimum system requirements that can't fit both the desktop and the game in VRAM.
> 1 votes

---
Tags: sdl2, user-experience, settings, fullscreen
---


title: Obstacle avoidance with 2.5D game

text:
# Question
Title: Obstacle avoidance with 2.5D game
I'm struggling to make the sprites avoid each other and other obstacles in the field. To achieve something like this:

To do so I decided to have a 3D environment with an Orthographic camera. It all looks as I wanted.

I have set up a plane. My sprites have a 3dCollider and a rigidbody as I want them to be affected by physics.

I move the sprites using `RigidBody.MovePosition`.

I checked the collisions, how far they where from their target position, etc...

I've tried also a few scripts that intend to do something like this, but I think they are not suitable from what I am doing as after adapting them they don't work.

Can somebody give me some guidance on a simple way to do this? I don't want to use a A\* pathfinding system as I think it's too complex to what I want to do, but if I have to use one I will... I just need some guidance on this...

# Answer
Change your sprites to use a capsule collider. They should allow for enough spacing to get the effect that you're looking for and also make sure that they can't run through each other. You will have to fiddle around with the capsules radius to get the spacing right but after that you should be good to go.

You might have to look into squad movement techniques if you want your units to move as a group without having them all try to go into a specific point. This often looks very messy since they all try to run at the same spot without giving which makes them run around to get a better position.
> -1 votes

---
Tags: unity, ai, 2.5d, collision-avoidance
---


title: Make a 2D tile map from isometric tile

text:
# Question
Title: Make a 2D tile map from isometric tile
So I have an isometric tile ( PNG ) and I was wondering how can I make a 2d tile map from it. I am using Unity.

# Answer
> 1 votes
It is definitely possible. You just have to have some method of converting from 2D coordinates to 2.5 coordinates. Usually this is done using an isometric projection matrix like so: http://www.petercollingridge.co.uk/interactive-svg-components/isometric-projection

This is the method that the isometric toolkits on the asset store use, like : https://www.assetstore.unity3d.com/en/#!/content/27851

and

https://www.assetstore.unity3d.com/en/#!/content/33032

Another common method is to work in 3d space and just adjust the camera so that everything appears isometric.

# Answer
> -1 votes
i don't think that's possible. AFAIK isometric is still just 2d just drawn from a different perspective. You'd have to draw the tiles again from the other perspective to change that

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


# Question
Title: How can I get accurate collision resolution on the corners of rectangles?
I have a working collision system implemented, and it's based on minimum translation vectors. This works fine in most cases except when the minimum translation vector is not actually in the direction of the collision.

For example:

When a rectangle is on the far edge on any side of another rectangle, a force can be applied, in this example down, the pushes one rectangle into the other, particularly a static object like a wall or a floor. As in the picture, the collision is coming from above, but because it's on the very edge, it translates to the left instead of back up. I've searched for a while to find an approach but everything I can find deals with general corner collisions where my problem is only in this one limited case.

Any suggestions?

# Answer
> 0 votes
You could try doing some apriori collision detection: Test whether they will be colliding after the force is applied, and if it is, only move it until the very beginning of the collision and then stop.

# Answer
> 0 votes
You can find the relative velocity vector between both objects and project the objects onto that vector. The overlap along the velocity vector should give you a vector you can use to translate both objects out of collision by 'reversing' them along their velocity vectors. This will normally give you a longer vector than the MTV.

Note this works well only if the objects are rotating relatively slowly.

# Answer
> 0 votes
I came on the VERY SAME problem as you earlier.
The solution is not easy and that's why I'm still looking.

My totally imperfect solution was made with some pretty complex code.

Firstly, I was not calculating only the MTV, but also the Minimum X translation and Minimum Y translation.

When the character is NOT colliding, I check where he is according to every other box. I keep some Left/Right/Up/Down variables for each box.
There are 3 cases:
1. The character is not left/right/up/down (ex. is upper left).
2. The character is just left or just up etc.
3. (on rotated boxes) The character is on a slope (ex up AND left).

Now when there IS collision, I resolve according to these variables I stored earlier.

Please, if you find this useful or you want to talk about it, message/email me!

---
Tags: collision-resolution, separating-axis-theorem
---


# Question
Title: How much logic should be in an individual behaviour tree node?
Let's say I have a condition node which has to spend a lot of time calculating something to finally return a bool to the behavior tree.
But in the following action, we need this information again. I now have a few options:

* I could just calculate the information again. That could unnecessarily take a lot of time and may result in redundant code.
* I could save the information into some kind of state data dictionary but now the action depends on calling the condition first.
* I could make it a single action that would just fail if the resulting calculation would end up being False. I would possibly end up with a bunch of very similar, very complex actions. Again possibly a lot of unnecessary redundancy.

How do I tackle something like that?
Is there a pattern that I could apply to the action/condition design (or whatever) or inside the behavior tree implementation that solves this?
Or am I using behavior trees wrong entirely?

# Answer
> 3 votes
## Handling conditions

> Let's say I have a condition node which has to spend a lot of time calculating something to finally return a bool to the behavior tree. But in the following action, we need this information again.

I worry about why you have to check the condition multiple times. Perhaps you could refactor your tree, so that you don't?

These are the options you have to apply conditions:

1. That could either be accomplished by having multiple identical condition nodes, or by adding the conditions to the action. In the later, if the condition fails then the action fails. And you already know that's not what you want.
2. You make a sequence, and inside the sequence you place a condition node (if conditions are decoration to action nodes in your implementation, you make a node with the condition but no action) if the condition fails, then the sequence fails, that prevents the other nodes in the sequence from running.
3. You make condition node, and have the actions be children of the condition. If the condition is true, you expand the subtree.

Using the second and third way I mention, you can have actions that run if the condition is true and actions that run if the condition is false.

---

## Avoiding redundant computation

Under the assumption that you can't create a behavior tree that avoid using the same condition in multiple places, there are still things you can do to avoid computing the result multiple times...

---

**Reuse subtrees**

it is a common practice to have a *dictionary of subtrees*, and have nodes call subtrees from the dictionary, this allows you to reuse subtrees (or it could be just single condition nodes) in various places of your tree.

---

**Use Memoization**

It is totally ok to use Memoization in your conditions. That is, you can let the condition store use an encapsulated backing storage※, if there is no value stored you compute the condition and store it, if there is a value stored... you check if it is valid※※ and decide if you use it or compute again.

※: If your conditions are lambda predicates, then you can just use a closure on some variable. No need for fancy data dictionary.

※※: you may also store the data needed to compute and compare it to check if it have changed. If the data is too complex you may use a version variable that you change every time the data needed changes... and then you can compare that. You may also use elapsed time as an heuristic to guess if it is worth to check or compute again.

---

**Agent memory**

Depending on your language/platform it may not be possible or it may not be convinient to encasulate the information used for memoization. There is no need to worry about that. It is valid to use an storage for information that the agent *knows about*. In fact, it is often needed to have some form of knowledge representation in your AI.

I wonder why people always go for the dictionary... perhaps it is the easier model to grasp. Yet, knowledge representation is a broad topic, and there are many datastructures that you can use for it.

In your behavior tree, the agent memory allows you to write more abstract actions, by having them pull informtion from it. With that said, using agent memory for flow control in your behavior tree makes it harder to maintain. It is coupling it to the knowledge representation, use sparsely.

---

## Handling long computations

If you need to handle processes that will take a while to compute in your behavior tree, there two other tools you need to know:

* Sending signals and waiting for signals.
* Parallel nodes.

Sending and waiting signals are action nodes. They can be used to interface between the behavior trees of various agents, or in this case, you can use them to post requests and wait for results. That should be simple to implement.

Parallel nodes on the other hand can be tricky: you need nodes that will expand their children in parallel. To decide if the node succeeds, it will have parameters telling it that it succeeds if X amount of children succeed and that it fails if Y amount of children fail. Furthermore, the parallel node should abort pending children once it reaches success or failure. That implies race conditions and actions you can abort.

To see how they can be of value, I'll present a use case from a real game and how to solve it with behavior trees.

**Real game use case**

The game Prototype needs to handle pathfinding for a large number of units (every person in the city), but pathfinding is expensive, so they restrict the CPU time dedicated for pathfinding as not to hurt FPS. However, that means that the game will not get all the pathfinding done in time.

The developers used two pathfinding methods... the first one is quick and dirty: it only checks for the general direction to where the person has to go and avoids nearby obstacles. The second one if a full-blown pathfinding algorithm.

Now, you see, the idea is to have units use the quick and dirty method until the pathfinding algorithm have a response. Therefore, they queue pathfinding requests in a queue. The pathfinding subsystem will takes those requests one by one. Meanwhile the unit is running the quick and dirty method... but when the pathfinding subsystem responds the system aborts the quick and dirty method and follow the found path instead.

**Implementing it with parallel nodes in a behavior tree**

Use a parallel node that expects one child to succeed. As children have: 1) an action that queues the pathfinding request, wait for it and store it on the agent memory, then succeed (triggering the parallel node to abort the other action) – Aborting this action means to un-queue the request and no longer wait. 2) Another action node that uses the quick and dirty method until abortion or reaches the goal, where it succeeds.

After that parallel node is node, you know that either the unit reached destination or the path it has to follow is stored in memory. To use it, you could make a sequence with that parallel node I described before, followed by a condition that checks if the path is in memory, and have that condition expand into an action that follows the path and then remove it from memory.

---

Using that technique, you can handle long computations in your behavior tree. Of course, there are other uses of these tools. For example, you can see how you could have the behavior be interrupted by signals (instead of writing pooling behaviors).

---

**Addendum: Will the agent know it?**

For example, the AI agent has to handle a unit that will go to the other side of a Drawbridge. Perhaps the Drawbridge is currently up, meaning that the unit cannot go there. However, will the unit know?

If the Drawbridge is outside of view, it makes sense that the unit doesn't know if it is currently up, and so it makes sense to implement a behavior that don't check for it... instead walk up to it, and let it fail. The same goes for obstructions in the way that the AI agent cannot foresee.

On the other hand, if the AI agent should know because something else gave it that information. Then you need to model information given to the AI agent, the agent memory is the go to solution. In fact, if it is responsibility of another AI agent to tell, you can use an action to send the signal ("Drawbridge up" or "Drawbridge down") from one agent to the other that could be waiting for it.

For abstract, consider what would the AI actually know and how would know it.

---
Tags: ai, behavior-tree
---


# Question
Title: SDL2: Why is my player's position not updating?
I've just started getting into game development, SDL in particular, so please go easy on me. I'm struggling to understand why my player's position isn't chaning when I press the left arrow button.

**main.cpp**

```
#include <iostream>
#include "SDL2/SDL.h"
#include "SDL2/SDL_image.h"

typedef struct
{
  float x, y;
  SDL_Texture *sprite;
} Player;

int processEvents(SDL_Window *window, Player *player) {
    SDL_Event event;
    int done = 0;
    while(SDL_PollEvent(&event)) {
        switch(event.type) {
            case SDL_WINDOWEVENT_CLOSE: {
                if(window) {
                    SDL_DestroyWindow(window);
                    window = NULL;
                    done = 1;
                }
            }
            break;
            case SDL_QUIT: {
                done = 1;
            }
            break;
        }
    }

    const Uint8 *keyState = SDL_GetKeyboardState(NULL);
    if( keyState[SDL_SCANCODE_LEFT] ) {
      player->x = 120;
    }
    return done;
}

void render(SDL_Renderer *renderer, Player *player) {
    SDL_RenderClear(renderer);

    SDL_Rect playerRect;
    playerRect.x = 0;
    playerRect.y = 0;
    playerRect.w = 32;
    playerRect.h = 32;
    SDL_RenderCopy(renderer, player->sprite, NULL, &playerRect);
    SDL_RenderPresent(renderer);
}

void update(Player *player) {
     player->x += 10;
}

int main( int argc, char *args[] ) {
    SDL_Window* window;
    SDL_Renderer* renderer;
    SDL_Event event;

    Player player;
    player.x = 50;
    player.y = 0;

    SDL_Init(SDL_INIT_EVERYTHING);
    window = SDL_CreateWindow("Dungeon", 100 , 100, 640, 480, SDL_WINDOW_SHOWN);
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

    player.sprite = IMG_LoadTexture(renderer, "assets/player.png");

    int done = 0;
    while( !done ) {
        done = processEvents(window, &player);
        update(&player);
        render(renderer, &player);
    }
    SDL_DestroyWindow(window);
    SDL_DestroyRenderer(renderer);
    SDL_Quit;
    return 0;
}

```

Any help would be much appreciated.

Thanks :)

# Answer
Okay, so there are a number of things I want to comment on, however first of all, in your render function, you are never actually setting the position of the drawn rectangle to the position of the player:

```
SDL_Rect playerRect;
playerRect.x = player->x;
playerRect.y = player->y;
playerRect.w = player->x + 32;
playerRect.h = player->y + 32;

```

I can only assume the update function you had was not working either?

---

If this doesn't work, it may be to do with how the keyboard data is being fetched. I've only personally used the **SDL\_GetKeyState(..)** function.

You can use it in a very similar way, but it definitely works well:

```
Uint8* keystate = SDL_GetKeyState(0);
if (keystate[SDLK_LEFT]) {
     player->x = 120;
}

```

As a personal design preference, I would also put the keyboard processing in the update function rather than the processEvents as you are polling the keyboard rather than waiting for incoming keypress events. (Though there is no difference in doing this, just organisation).

---

I understand this is a test project, however I feel it would be more productive for you to experiment and learn in a game engine environment rather than jumping straight into C++. I am only making assumptions of your experience from the code you have provided, however speaking from my own personal experience, it can be counter-productive to try and create games in C++ from the get go, simply because you will run into a lot of brick walls if you aren't all that experienced with the language. From another point of view, other engines can teach you strong skills in design patterns and program structure which do become increasingly important later on.

I would also say that pure SDL is pretty bad for game development. It is a reasonable "raw" rendering setup that is quick and easy to get setup, however is does not really provide many utility functions that aid in game development. I'd recommend SFML over SDL for this sort of thing, especially because it is a little bit more intuitive as well if you are focused on taking the C++ route. (SFML does a good job of abstracting away alot of the complexity)
> 1 votes

---
Tags: c++, sdl, sdl2
---


# Question
Title: Google Play Services Library not found. How can I get this?
So this question is in relation to, but not the same as my previous question (How do I successfully implement Google Mobile Ads and Google Play Services into my Unity arcade game?). That is why I am making a new one. I am almost ready to publish my app now the I have ads working but in the process of implementing Unity Ads I was forced to re-implement Google Play Services. I did so with an updated version of Google Play Services and now I am receiving this error:

Does anyone know how to fix this?

# Answer
> 1 votes
Ok so after much research I found the solution here: http://answers.unity3d.com/answers/1193742/view.html Google Play Services is now successfully integrated.

---

*Now the only problem is my app crashes on start after I build it to my device :/ Idk what to do at this point.*

---
Tags: unity, google-play-services, google-play
---


# Question
Title: Touch a specific area on the screen in Unity 5
I am building a Roulette game in Unity 5. I want to place bets on a Roulette table when I touch specific areas on the screen with mouse(PC) and touch(mobile).

For example when i touch Number 1 on the roulette table a bet should be placed on that number. I tried using box collider iwth trigger but I think thats for only colliders.

Screenshot attached

# Answer
> 1 votes
you're on the right way. now you should create a class that will listen to any clicks on the roulette table, and in the update function of that class you should get the location of the click (either touch or mouse click) with raycast, just attach the following script to an empty gameobject on the hierarchy and you're good to go. i would also recommend tagging the roulette numbers with certain tag like "rouletteNumber".

```
private InputMechanism _inputMechanism = new MouseInput { 0 };
// 0 - mouse left click
// 1 - right click
// 2 - middle click

void Start()
 {
       // change input mechanism according to platform
       if (Application.isMobilePlatform)
       {
             _inputMechanism = new TouchInputSingle();
       }
}

void Update()
{
    if (_inputMechanism.IsDown())
    {
        position = _inputMechanism.GetScreenPosition();
        Ray ray = Camera.main.ScreenPointToRay(position);
        RaycastHit2D hit = Physics2D.GetRayIntersection(ray, Mathf.Infinity);

        if (hit.collider != null && (hit.collider.tag == "rouletteNumber"))
        {
            // do whatever you want to do here
        }
    }

```

}

// Mouse input class

```
public class MouseInput : InputMechanism
    {
        public int Button = Globals.Mouse.Buttons.LEFT;

        #region Overrides of InputMechanism
        public override bool IsDown()
        {
            return Input.GetMouseButtonDown(Button);
        }

        public override bool IsUp()
        {
            return Input.GetMouseButtonUp(Button);
        }

        public override Vector2 GetScreenPosition()
        {
            return Input.mousePosition;
        }
        #endregion
    }

```

// touch input class

```
public class TouchInputSingle : InputMechanism
    {
        private int _trackedTouchId = -1;
        private Vector2 _touchPosition;

        #region Overrides of InputMechanism
        public override bool IsDown()
        {
            if (_trackedTouchId < 0)
            {
                for (int i = 0; i < Input.touchCount; i++)
                {
                    if (Input.GetTouch(i).phase == TouchPhase.Began)
                    {
                        _trackedTouchId = i;
                        return true;
                    }
                }
            }

            return false;
        }

        public override bool IsUp()
        {
            if (_trackedTouchId >= 0)
            {
                switch (Input.GetTouch(_trackedTouchId).phase)
                {
                    case TouchPhase.Ended:
                    case TouchPhase.Canceled:
                        _trackedTouchId = -1;
                        return true;
                }
            }

            return false;
        }

        public override Vector2 GetScreenPosition()
        {
            if (_trackedTouchId >= 0)
            {
                _touchPosition = Input.GetTouch(_trackedTouchId).position;
            }

            return _touchPosition;
        }
        #endregion

```

// abstract input mechanism

```
public abstract class InputMechanism
    {
        public abstract bool IsDown();
        public abstract bool IsUp();
        public abstract Vector2 GetScreenPosition();
    }

```

# Answer
> 0 votes
You can create a component that implements these interfaces `IPointerClickHandler , IPointerDownHandler, IPointerUpHandler`. This way you can can handle input with both the mouse and touch. Your class should look something like this.

```
public class MyInputClass : MonoBehaviour, IPointerClickHandler , IPointerDownHandler, IPointerUpHandler
{

    public void OnPointerClick(PointerEventData eventData)
    {
      Debug.log("We clicked on: "+gameObject.name);
    }

    public void OnPointerDown(PointerEventData eventData)
    {
       // throw new NotImplementedException();
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        //throw new NotImplementedException();
    }

}

```

---
Tags: unity, mouse, touch
---


# Question
Title: Animation Dilemma: How to create authentic discontinuous block-like character movement
I am using Unity. I have quite a bit of Unity experience, however I am a novice in animation. In the past I have had someone else do character Animation aside from some Camera animation and simple object movement.

In this game I have large 3D Cube-like characters I made in Blender. Now a normal humanoid character will change in shape as they walk. But these block characters however do not change in shape as they move around the world, as they attack, and so on; they are always rigid and block like in shape.

They get around the world by rotating themselves. Most of the time they would move by pivoting on the corners of their shape. Here is an image to show what I am talking about:

Bonus Image: https://i.stack.imgur.com/b9LlD.png

Think of moving a big cube of something heavy in real life by alternating pivoting it on the front two & bottom corners of the cube. That’s how they walk.

So by most means this is very simple animation: no need to alter a mesh’s shape. However I have a few issues that need to be resolved:

* 1) The objects velocity is discontinuous: its acceleration is jerky. For a normal running humanoid all you have to do is play the animation as they run in a straight line at a constant rate (of course it can get much more complicated). But for these block characters their center is technically swaying back and forth as it moves, take a look at the picture to see what I mean. Also it’s not moving forward at a constant rate, and instead slows down as each “step” comes to an end. This is an issue because animations don’t normally move the object: instead the game’s code actually moves the character’s center while playing animations that are consistent with the object’s movement. But now if I take that approach I would have to figure out how alter the character’s center that is consistent with this rotating block movement, which would be a huge hassle. It would be nice if these animations actually did move the object depending on how the animations would actually move the object, instead of the animation basically just rotating the object in local space while trying to figure out what that movement would mean in global space in code. It may seem that rotating objects around a point in code may be the best solution for this, avoiding Unity’s animation system all together, however it would quickly become a pain to figure out how to do every animation only in code.
* 2) These block characters come in different sizes. Some are tall, some are wide. Some characters will swing out more (have a larger angle) as they step forward. It would be nice to be able to basically create this animation once and have it able to be applied to different block sizes and stride types. If I were to use Unity’s or Blender’s animation system I don’t know how much I will be able to automate this. For example I want to basically be able to say okay this character takes these wide of steps this fast, and the rest would be figured out from there. Also while the characters move forward via the rotation animation some characters will lift the other three corners off the ground depending on their mass.
* 3) This kind of goes with the point above, but there may be a bit of randomness in some movements. For example some objects jump in the air, and when they do so they have a small random change in rotation due to unevenness in the jump.
* 4) These animations need to be fully interruptible. For example if a block is taking a step forward and then suddenly takes on a large force that sends them flying they would do so starting with the orientation they were at when they took on the force. Like rag dolling, except with something completely rigid. Not the most difficult thing on this list.
* 5) Lastly some movements would be complicated, for example one block character does a mid-air double round house kick.

This movement is more of a game play mechanic than it is cosmetic.

**TL;DR: This is my main issue: I am torn between how much to rely on code for these animations and when to use Unity’s (or Blender’s) animation system, if at all.**

These are what I see as my options:

1) “Standard Animation”: animate these animations in the animator, painstackingly figure out how to move these objects in global space that is consistent with these unusual animations. So basically have the character be a child of a parent transform, and figure out how to move the parent transform point depending on what animation is playing.

2) Programmatically: forgo the animation system and do all movement in code. May become also time consuming when doing more complicated movements, but maybe not.

3) Something else hopefully??? A smart mix of the two I haven’t through about?

The two options don’t sound great, and I am unsure on which one would be more time consuming. What would you do in my shoes? Is there a good third option I haven’t figured out?

# Answer
> 1 votes
If you only wanted to walk, I'd say you could get away with using Transform.RotateAround and simply have some anchor points on the corners.

But since you want more complex animation, and also some randomness, I suggest you use Mecanim. You can use root motion to let the animation drive the movement, eliminating the need to figure this out in code and using parent objects.

To add the randomness in the jump, for example, you can layer the animations in Mecanim. In that case you would make a clean jump, and afterwards an animation of some wiggling movement. Then you can additively add the wiggly movement to the jump using parameters to control the amount.

Since you have different sized cubes, you may want to create two animations for each type; like walking, jumping etc. and again, blend between the two based on their size.

Mecanim can sometimes be a little off when walking in straight lines or if you need to turn exactly 90˚ you want to look into Animator.MatchTarget.

You want to look into using **blend trees, layers and parameters in Mecanim**.

---
Tags: unity, animation, movement
---


# Question
Title: Problems with object collision detection using mesh colliders in unity
So I'm working on a project and I need to detect when an empty object with a mesh attached to it collides with another object. Essentially, I want to know when the mesh is touching a cube. I've tried using the mesh collider (And it works) but the problem is: I have a circular mesh and therefore need to Inflate the mesh. This decreases its accuracy and increases lag by a lot and I can't have that happen.

TL;DR: I copy my mesh to a mesh collider but the mesh collider is inaccurate and laggy for collision detection.

# Answer
> 0 votes
Use a simplified version of the mesh with less vertices and faces used for collision. This will give you better performance. If it works for the shape of the mesh, making the mesh collider convex makes it faster. If the object is too complicated to represent accurately using a single convex mesh, you can try to use multiple convex meshes approximate the shape.

---
Tags: unity, c#, mesh, collider
---


# Question
Title: Why am I getting white lines in my tiled map when my character moves?
I followed the tutorial here -

http://mainroach.blogspot.com/2013/02/fast-html5-canvas-rendering-tiled-maps.html

I can't really figure out why it's happening. At certain times the map looks fine and then when I move my character the map starts to look like this -

# Answer
My guess is there is a white tile above or below the offending tile in your tilemap. When it renders that tile a bit of the adjacent white tile it bleeds onto the other tile. Changing the blending mode to nearest neighbor should fix the problem.
> 1 votes

---
Tags: rendering, tiles
---


title: Can I use a 3d plane for a 2d game?

text:
# Question
Title: Can I use a 3d plane for a 2d game?
I am developing a 2d isometric game and I was wondering if I can use a 3d plane for a 2d game.

# Answer
Sure, you want an orthographic projection.

Aside from that, you can render using an isometric point of view. That will allow you to look at surface with square tiles and have them appear as isometric tiles. Also, should allow you to use 3D models in your isometric game without worrying about the projection.

The following is from the Wikipedia link above:

> There are eight different orientations to obtain an isometric view, depending into which octant the viewer looks. The isometric transform from a point ax,y,z in 3D space to a point bx,y in 2D space looking into the first octant can be written mathematically with rotation matrices as:
>
> where **α = arcsin(tan 30°) ≈ 35.264° and β = 45°**. As explained above, this is a rotation around the vertical (here y) axis by β, followed by a rotation around the horizontal (here x) axis by α.
>
> (...)
>
> The other 7 possibilities are obtained by either rotating to the opposite sides or not, and then inverting the view direction or not.

*Emphasis mine.*

Notice the article says there 8 possible such matrices. Some testing will be required to make sure you are use the right one for the coordinates of your map.

---

For unity, you want to set an orthographic matrix in `Camera.projectionMatrix` and the isometric matrix shown above in `Camera.worldToCameraMatrix`.

*Note: I don't really have experience with Unity. So I can't tell if `Camera.orthographic` is a better option than setting an orthograpic matrix to `Camera.projectionMatrix`.*

If you need to set the camera by hand, use the angles shown above (**α = arcsin(tan 30°) ≈ 35.264° and β = 45°**):
> 3 votes

# Answer
Yes. A plane is a flat, two-dimensional surface... There are infinite planes in 3d space... You can use any of them...
> 1 votes

# Answer
https://docs.unity3d.com/ScriptReference/Camera-orthographic.html

You want to be in orthographic view.

I found a script that tweens between orthographic and perspective views. I can post it if you'd like?
> 0 votes

---
Tags: unity
---


# Question
Title: How to create a Spawn Area that can be visualized in the Unity Scene Editor?
Consider a *Spawn Area* for GameObjects. We define a *Spawn Area* to be a boundary consisting of 3 or more points such that an object can spawn at any coordinate that is within the boundary of the *Spawn Area*. Contrast this with a *Spawn Point*, where objects can only be spawned at that specific coordinate.

In Unity, one method of creating such a *Spawn Area* is to place an Empty Game Object at a point, and then use `Random.Range` around that point.

```
Vector3 emptyGameObjectCoordinate = emptyGameObject.transform.position;
Vector3 randomSpawn = emptyGameObjectCoordinate + new Vector3(Random.Range(-1, 2), 0, 0);

```

My issue with this approach is that it is very difficult to visualize this area through the scene editor. It would look like a simple cube no matter what the area actually is.

I have considered possibly using a box collider as the area. This is can easily be visualized.

However, Unity Lacks a method to select points within a collider.

It would be ideal if we had a method such as `Random.insideCollider`.

```
BoxCollider collider = GetComponent<BoxCollider>();

// Ideally. But sadly, does not exist.
Vector3 randomSpawn = Random.insideCollider(collider);

```

**So my question is, what is the Unity way of creating a Spawn Area such that it can be visualized through the scene editor?**

As a bonus, how can we create areas that consists of arbitrary points, as opposed to just being rectangles or cubes? It would still need to be possible to visualize it, and it should be easy to select random points within it.

# Answer
Gizmo and Handles class are your friend! Though it is for Editor Only, i think...

Make sure to read the docs carefully, as you need to make these call in `OnGizmos()` or `OnDrawGizmosSelected()` \[Just like `Update()` or `OnGUI()`\]

If you are looking for something that you can see in builds (Not editor) check out the GL class.

Bonus : The Debug class has a DrawLine and DrawRay function that might be useful.

.. There might be more new stuffs, but these are all I am aware of at the moment.
> 1 votes

# Answer
I was able to reach a solution using Albert's answer. However, I just want to go into more details with regards to my exact approach, as it may be useful to future readers.

---

Continue using an Empty Game Object to represent the spawn area. We will define the center of the spawn area to be equal to the Transform position of the Empty Game Object. We will then define the width, height, and depth of the spawn area to be equal to the Transform scale of the Empty Game Object. For simplicity, we will assume the Empty Game Object is axis aligned.

This means the coordinate selection logic should be as follows:

```
Vector3 origin = transform.position;
Vector3 range = transform.localScale / 2.0f;
Vector3 randomRange = new Vector3(Random.Range(-range.x, range.x),
                                  Random.Range(-range.y, range.y),
                                  Random.Range(-range.z, range.z));
Vector3 randomCoordinate = origin + randomRange;

```

Create a C# script that extends `MonoBehaviour`, and attach it to the Empty Game Object. This script will be used to add visualization to the Empty Game Object through the use of Gizmos.

Add implementation to the `OnDrawGizmos()` method to draw a cube at the Transform position, with size equal to the Transform scale. Notice that this matches our definition of the spawn area above.

```
public Color GizmosColor = new Color(0.5f, 0.5f, 0.5f, 0.2f);

void OnDrawGizmos()
{
    Gizmos.color = GizmosColor;
    Gizmos.DrawCube(transform.position, transform.localScale);
}

```

This will then draw the Cube only in the Unity Editor, but it will be invisible in game, which is exactly what we want.
> 3 votes

---
Tags: unity, c#, 3d, random, visualization
---


# Question
Title: Genetic Algorithms - Fitness Function simple maze game
Trying to lay out the best fitness function for my simple game. I'm just trying to make bots go through a bunch of obstacles in order to reach a point. If they touch an obstacle, they die, they have 10 seconds max to solve the parkour.

I'm wondering which data I should track to make the best fitness function possible.

I thought of tracking:

```
Time

Distance to exit from position of death or timeout

```

And my Fitness score would be:

```
Fitness = Time / (Distance + 1)

```

But if a bot manages to get to the end of the maze in 10s, I'm scared the following generations will all take 10s or close to it to go through the maze and not try to do it in 3 or 4s for instance. Because he'll get the best fitness score, so he'll be the parent of most cross-overs.

Yet I didn't manage to get a working example so perhaps I'm worrying for nothing but I'd like some advice on generally how to determine such fitness functions.

# Answer
## Understanding the problem

Creating a good fitness function is about understanding the domain of the problem.

In this scenario, you will have simulations of the candidates going from the origin to the exit. The simulation will have a given time limit, that when reached the simulation is halted.

This means that the simulation for a given candidates ends either when it reaches the exit, or when the time is up.

And we have two measurements to work with: `Distance` (the of the candidate to the exit at the end of the simulation) and `Time` (the total elapsed time of the simulation).

We need to consider the values for these variables in both exit conditions:

* The the time is up: `Distance > 0`, `Time = TimeLimit`
* The exit is Reached: `Distance = 0`, `Time ∈ [0, TimeLimit)`

So, `Distance ∈ [0, ∞)`, and `Time ∈ [0, TimeLimit]`. Note that I'm assuming that the candidate can go backwards beyond the origin.

We observe that when the exit is reached, `Fitness` will be a function of `Time`, and we want its worst value to be at `Time = TimeLimit` from where `Distance` should dominate the function. This implies that there will be a notable `Fitness` value for `Distance = 0` and `Time = TimeLimit`.

I'll call this notable value `K`. So, `K = Fitness(Distance: 0, Time: TimeLimit)`.

*Note: you can use `K = 1`.*

---

## Modelling the fitness function with partial knowledge

I'll be using only information about the intervals of the variables and the fact that we want to minimize both `Time` and `Distance` to try to come up with a fitness function.

This will result into perfectly valid and functional fitness functions for genetic algorithms (with some tweaking here and there). However, if you want to see how to use the knowledge of the problem to create an ideal fitness function, skip to the next title.

Since we want to minimize the variables, the `Fitness` function would have to turn a lower value of these variables into a higher result.

We have two approaches to do that:

* Invert the fitness afterwards:

In this approach, we will work an inverse fitness function starting by assigning the lower possible value to the best results.

So, we start by mapping `Time ∈ [0, TimeLimit]` into `[0, K]`. Meaning that `Fitness'(Distance: 0, Time:0) = 0` and `Fitness(Distance: 0, Time:TimeLimit) = K`. That can be easily done with a linear function:

`Fitness'(Time) = Time * K/TimeLimit`

Then, we introduce `Distance`:

`Fitness'(Distance, Time) = Distance + Time * K/TimeLimit`

Finally, we invert the function. We can use the multiplicative inverse...

`Fitness(Distance, Time) = 1 / (Distance + Time * K/TimeLimit)`

... but, be wary that that may lead to a division by zero at the perfect score. Fortunately we know that `Time = 0` should not happen. Anyway, we will fix any possible divide by zero by adding 1:

`Fitness(Distance, Time) = 1 / (1 + Distance + Time * K/TimeLimit)`

Alternatively, we can just flip the sign:

`Fitness(Distance, Time) = - Distance - Time * K/TimeLimit`

Yet, this will lead to negative numbers. If you are using the And the proportionate selection algorithm, know that it can't work with negative numbers... you may have to normalize the values by adding a value to all them to make them positive (you can use the absolute value of the worst result):

`Fitness(Distance, Time) = a - Distance - Time * K/TimeLimit`

Where `a` is constant for the compared population.

*Note: this problem leads itself very well to this approach because we need to invert both variables.*
* Invert the variable beforehand:

In this case we will work as if we were creating fitness functions for each variable... inverting them as needed... and the combining them into a single fitness function.

For `Time` we start with:

`Fitness'(Time) = Time`

Again, we can invert this with the multiplicative inverse (leading to possible division by zero) or by flipping signs (leading to possible negative values).

We do the same thing with `Distance`:

`Fitness'(Distance) = Distance`

The next question: should add or multiply these functions? There is a clear advantage of adding: it makes it easier to add weights to the variables in the form of constant factors to the appropriate terms.

This leads us to four possible fitness functions:

`Fitness(Distance, Time) = b/(1 + Time) + c/(1 + Distance)`

`Fitness(Distance, Time) = d/((1 + Time) * (1 + Distance))`

`Fitness(Distance, Time) = e -Time + -Distance`

`Fitness(Distance, Time) = f -((1 + Time) * (1 + Distance))`

Where `b`, `c` and `d`, `e` and `f` are constants for the compared population.

Notes:

+ Above, in the second alternative presented, we are adding one to the individual variables instead of adding to the denominator. This is because of a simple reason... if you add to the denominator, for the situations where `Distance = 0` you would be multiplying `Time` by 0, negating the impact of `Time` in the result of the function, which results in having the same value for all cases where `Distance = 0`.
    + The final alternative is trickier! Not only you have to worry that when one of the variables is zero it negates the other, but also you have to worry that if you inverted both variables by changing their sing... when you multiply them, the result is now growing! Therefore, we have to tweak that.

---

*Comparison of the fitness functions*

We have come up with a total of six possible fitness functions:

```
1. Fitness(Distance, Time) = 1 / (1 + Distance + Time * K/TimeLimit)
2. Fitness(Distance, Time) = a - Distance - Time * K/TimeLimit
3. Fitness(Distance, Time) = b/(1 + Time) + c/(1 + Distance)
4. Fitness(Distance, Time) = d/((1 + Time) * (1 + Distance))
5. Fitness(Distance, Time) = e -Time + -Distance
6. Fitness(Distance, Time) = f -((1 + Time) * (1 + Distance))

```

Where `a`, `b`, `c` and `d`, `e` and `f` are constants for the compared population.

To pick one, let’s see how this functions behave...

The mapped values correspond to `Time` in the interval `[0, 10]` on the left of the graph, and `Distance` in the interval `[0, 10]` in the right of the graph.

In the graph all the functions has been normalized to give a score in the interval `[0, 120]`. This interval was chosen because the option 6 gives a value of -120 at `Time = 10 & Distance = 10` which is the last value mapped.

We observe that all the methods present a discontinuous slope at the notable value, except for option 5, which is just a linear function. We also observe that the methods that use flipping sign result in linear segments (as expected), while the other results in hyperbolic segments. In addition, all the options are decreasing functions.

We can't really discard any of these methods, although we could prefer the option that result in curved functions because they don't require to normalize to eliminate negative numbers.

---

## Modelling the fitness function with knowledge of the problem

While any of the fitness function presented above would work for a genetic algorithm, if you need a good representation of their comparative behavior... only the method 5 is good enough. However, even method 5 suffers from negative values.

Therefore, to find a good representation of their comparative and absolute behavior, we go back to the problem.

What we have been trying to do is extrapolate what would have happened in the simulation if we have let it run until the candidate reaches the exit.

For the `Time < TimeLimit` we know how much time the candidate took to reach the exit, for the other cases we extrapolate using `Speed = Distance / Time`:

```
ExpectedTime = |Exit - Origin| * |Candidate - Origin| / Time

```

Where `Exit`, `Origin` and `Candidate` are vectors. `|Exit - Candidate|` would be the distance from the candidate to the exit (`Distance`)

Now, we could score the candidate using `Time` when `Distance = 0` and using `ExpectedTime` when it isn't.

*Yes, you can do that, you can use conditionals in your code.*

Yet, we can do that in one function without conditional or tricks... what we need to compute is the expected extra time that the candidate needed to reach the goal...

```
ExpectedExtraTime = Distance * |Candidate - Origin| / Time

```

In addition, add to it the elapsed time:

```
Fitness' = Time + Distance * |Candidate - Origin| / Time

```

We still need to invert this; we can confidently do it by using the multiplicative inverse:

```
Fitness = 1 / (Time + Distance * |Candidate - Origin| / Time)
=>
Fitness = 1 / (Time^2/Time + Distance * |Candidate - Origin| / Time)
=>
Fitness = Time / (Time^2 + Distance * |Candidate - Origin|)

```

This fitness function will only cause division by zero when both `Time` and `Distance` are 0. Shouldn't happen. Anyway, we will fix any possible divide by zero by adding 1.

Either here:

```
Fitness = Time / (1 + Time^2 + Distance * |Candidate - Origin|)

```

Alternatively, here:

```
Fitness = 1 / (1 + Time + Distance * |Candidate - Origin| / (1 + Time))
Fitness = 1 / ((1 + Time)^2/(1 + Time) + Distance * |Candidate - Origin| / (1 + Time))
Fitness = (1 + Time) / ((1 + Time)^2 + Distance * |Candidate - Origin|)

```

Note: in these graphs I assume `|Candidate - Origin|` = 1.

Personally, I prefer this final option. The reason is that the prior has a change in curvature... that makes the final option better to compare differences of candidates (you can argue the improvement of “A” over “B” is greater than the improvement of “C” over “D”, by comparing the inverses of the differences of their scores)... not that you need that to implement a genetic algorithm.

Both are continuous, decreasing, and will give you a positive scores for any situation.

---

**Addendum**: experimenting with this I found another option to prevent division by zero instead of adding 1. That option is to use exponentiation. In particular a fitness function of the form:

```
Fitness = (v^Time) / ((v^Time)^2 + Distance * |Candidate - Origin|)

```

Where `v` is a constant greater than 1, will result in a similar curve to those presented here. The slop will be evidently discontinous for `v ≈ 1`, from `v ≈ 1.1` onwards there is no noticable jump in the slope. Higher values of `v` will make the function decrease faster. We wary of floating point errors.
> 1 votes

# Answer
Break the fitness into two parts.

Lets say a percentage of distance completed before timeout or death.

If the distance is completed, bonus is given based on the amount of time left on the clock.

So theoretically, the best score could be 200%.

If the whole distance was covered in 0 seconds, there would be 100% for distance, and an addition 100% for 10 seconds left of the 10 seconds allocated.
> 0 votes

---
Tags: ai
---


# Question
Title: How to import assets to Unity3d Build on runtime
I am trying to import assets- ex:"fbx files"- into my app that is made using unity3d. this works easily inside the unity editor, but i need to do that in the actual build. any idea how to make this happen. Note: i already read about asset bundles, but my files are local, so what i need is a way to locally import these files.

thanks in advance

# Answer
> 6 votes
# TL;DR - Quick and Easy

Here is a free unity asset store package that claims to do exactly what you need. I haven't personally tried it, but it (or another like it) might solve the issue you are looking for specifically. https://www.assetstore.unity3d.com/en/#!/content/49547

# Longer Answer

## Why can't I use the code that obviously already exists?

It's important to remember that when you add an asset to your unity3d project, that isn't the data that ends up in the game's asset bundle to be loaded and used by the engine. The editor converts the file into a friendly format for simulation and rendering - as opposed to a convenient format for transport. For reasons I can only speculate (I am not a unity developer) they did not package these in the final runtime application (the version of the game you ship) so you cannot access them. It's possible that it is some combination of licensing (for things like FBX), binary size (adding a bunch of libraries, code, and code paths that would bloat most games), or some deeper technical hurdle where the cost wasn't worth the benefit.

Another consideration is that it's not just meshes that need to be imported, but textures, materials (and then shaders), and animations. Dragging and dropping a model (in my experience) is rarely the only step involved in getting an asset from disk to game. Perhaps the developers thought that since they could not make a clear, precise API for users that it wasn't a feature worth adding (no support for a feature is often a better choice than a half baked, bloated, confusing one - certainly QA / Customer Service / Technical Writers must think so!)

### From File on Disk to Asset In Game

Here's a really rough, naive guess at the steps involved in getting a file off desk and into the game:

1. Pick a model format you wish to support.
2. Parse the file, and build a heirarchy of meshes / sub meshes / skinned meshes from the verts, also making sure to load the bones and default bind pose information. This API is available (ie: procedurally generated meshes: https://docs.unity3d.com/Manual/GeneratingMeshGeometryProcedurally.html )
3. For each submesh, load whatever material data is supported in the mesh.
4. Using data from the file locate which textures and maps are used.
5. Have a fixed number of pre-determined materials in your game that you map to materials applied to the submeshes in the model.
6. Apply the mesh / skinned mesh to the appropriate mesh filter / mesh renderer.
7. Apply the appropriate materials to the mesh renderer
8. Apply the appropriate material parameters to the materials.

As you can see, unity asset pipeline API would only get you 1, 2 and 3. 4 debatably (personally, when I bring in a mesh it never applies materials properly, often times it doesn't even load the textures properly). The rest is done at design time by hand, so you'll have to figure out how to do that in code in a way that works best for your project. This isn't even touching on things like Mechanim trees, optimal texture format compression, generating mip maps, etc etc.

## So how do these plugins work?

My guess (not having used them or look at the code) is they do the absolute minimum amount of work. They support only a very specific model and version format, and only mesh and texture data. They assume you will just apply a single material or create a material using some default shader and settings, which might work for you but for most games this treatment would be insufficient. They also likely only support the legacy animation system, if they support animations at all. Likely they will do their best to make things look as default as possible, or ignore / skip settings that are inconvenient or difficult or impossible to tune without an artists eye.

I can attest that whatever they are doing most likely wouldn't pass muster with a discerning artist, but maybe that isn't a problem for your particular use case.

Good luck!

---
Tags: unity, assets, import
---


title: About learning c#

text:
# Question
Title: About learning c#
I am a high school student. I know different languages like c, c++(70%), html, python (half). Now I want to learn c# for unity development. I want to learn it from the very beginning and I have 1 year to learn C# perfectly.I found different ways to learn it but don't know which is the best....

1. Solo learn mobile app "Learn c#" / www.sololearn.com are same
2. Tutorial points PDF...( pages near 330)
3. Youtube channels

# Answer
> 0 votes
this is not a typical question you should ask in here, but since your target is to learn C# for unity development, I would suggest starting with the "unity tailored" Scripting tutorials. They are pretty basic and you should go through them with ease. from there on you could advance from a lot of references throughout the web. But starting with the mentioned tutorials is most recommended since it puts you on the track so you know what you want to look for later.

Hope this helps.

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


# Question
Title: How to make a 2D neon-like trail effect in Unity
Recently I've been toying around with neon-ish effects for a game I'm making and wanted to share my results with you.

If you guys have any other methods of achieving this result, please be sure to share.

# Answer
> 12 votes
To achieve this effect my friend has created a custom sprite, we played around with all sorts of sprites and you can customize this part to your liking. The shader I've written for this effect, takes in the sprite, makes the sprite grayscale, uses the color to make a colored version and uses the grayscale version together with the colored version to color the parts that are gray.

First of all, your sprite doesn't really need to be grayscale, but it will probably be better for grayscale sprites. The trail effect that I've used stretches the sprite horizontally, so making the sprite horizontal is quite necessary.

This is the sprite we've used in game (it has built in alpha which is necessary for the glow effect):

This is the shader I've made for the effect:

```
Shader "Trail/Neon"
{
    Properties
    {
        [PerRendererData] _MainTex("Sprite Texture", 2D) = "white" {}
    _Color("Tint", Color) = (1,1,1,1)
        _MainTexture("Sprite", 2D) = "white" {}
    [MaterialToggle] PixelSnap("Pixel snap", Float) = 0
    }

        SubShader
    {
        Tags
    {
        "Queue" = "Transparent"
        "IgnoreProjector" = "True"
        "RenderType" = "Transparent"
        "PreviewType" = "Plane"
        "CanUseSpriteAtlas" = "True"
    }

        Cull Off
        Lighting Off
        ZWrite Off
        Blend One OneMinusSrcAlpha

        Pass
    {
        CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma target 2.0
#pragma multi_compile _ PIXELSNAP_ON
#pragma multi_compile _ ETC1_EXTERNAL_ALPHA
#include "UnityCG.cginc"

        struct appdata_t
    {
        float4 vertex   : POSITION;
        float4 color    : COLOR;
        float2 texcoord : TEXCOORD0;
        UNITY_VERTEX_INPUT_INSTANCE_ID
    };

    struct v2f
    {
        float4 vertex   : SV_POSITION;
        fixed4 color : COLOR;
        float2 texcoord  : TEXCOORD0;
        UNITY_VERTEX_OUTPUT_STEREO
    };

    fixed4 _Color;

    v2f vert(appdata_t IN)
    {
        v2f OUT;
        UNITY_SETUP_INSTANCE_ID(IN);
        UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(OUT);
        OUT.vertex = UnityObjectToClipPos(IN.vertex);
        OUT.texcoord = IN.texcoord;
        OUT.color = IN.color * _Color;
#ifdef PIXELSNAP_ON
        OUT.vertex = UnityPixelSnap(OUT.vertex);
#endif

        return OUT;
    }

    sampler2D _MainTexture;
    sampler2D _AlphaTex;

    fixed4 SampleSpriteTexture(float2 uv)
    {
        fixed4 color = tex2D(_MainTexture, uv);

#if ETC1_EXTERNAL_ALPHA
        // get the color from an external texture (usecase: Alpha support for ETC1 on android)
        color.a = tex2D(_AlphaTex, uv).r;
#endif //ETC1_EXTERNAL_ALPHA

        return color;
    }

    fixed4 frag(v2f IN) : SV_Target
    {
        //standard sprite shader, only this part is different.
        //takes the sprite in
        fixed4 s = SampleSpriteTexture(IN.texcoord);

        //makes a colored version of the sprite
        fixed4 c = s * IN.color;

        //makes the grayscale version
        fixed n = (s.g + s.r + s.b) / 3;

        //So, I've scrapped the previous calculation in favor of this I'll leave the previous one in too, just for reference
        c = (c*3 + n*c.a)*c.a;
        //Adds the grayscale version on top of the colored version
        //The alpha multiplications give the neon effect feeling
        //c.g = (c.g + n * c.a) * c.a;
        //c.r = (c.r + n * c.a) * c.a;
        //c.b = (c.b + n * c.a) * c.a;
        // You can add c.a multiplications of colors
        //(i.e. turn  c.g to c.g*c.a) for less color in your effect
        //this saturates the insides a bit too much for my liking

        return c;
    }
        ENDCG
    }
    }
}

```

You will have to make separate materials for each different color because of how Unity works with shaders (if there's a way to overcome this, please do tell).

So, you make a new material, pick the shader for that material, change the color and the sprite input, and you've got yourself a neon-like effect.

And the effect achieved in a gif:

Effect on different sprites:

---
Tags: unity, sprites, fragment-shader, cg, special-effects
---


# Question
Title: What kind of ESRB rating do you get for IMPLIED sex?
My game is a story-driven horror game with lots of gore. Obviously, being a horror game places it on the higher end of the age rating already, but because of how backwards the rating system is (female nipples = **BAAAAAD!!!** Some guy getting his head split in two = *eh... who cares*) I'm kinda worried that I would get an even higher rating for the sexual themes.

No nudity is ever shown. Some of the characters mostly flirt and say dirty things, not dancing around the f-word (like I just did), and they don't really hold back on the cursing either, but the *"worst"* you can see is a couple naked in bed after they've done their deed. The actual deed is never shown and you don't see them naked.

Just to be clear, the sexual themes are not the focus of the game, in fact it only happens sparsely. It's mostly about the survival of the main characters.

What kind of rating would my game get?

# Answer
> 1 votes
According to the ESRB ratings guide (emphasis mine):

> **TEEN**
>
> Content is generally suitable for ages 13 and up. May contain violence, **suggestive themes**, crude humor, minimal blood, simulated gambling and/or **infrequent use of strong language**.
>
> **MATURE**
>
> Content is generally suitable for ages 17 and up. May contain **intense** violence, blood and gore, **sexual content** and/or **strong language**.

From your description, it sounds like your sexual aspects are merely suggestive, falling under the Teen category. For your suggestive wording and f-word usage, this would probably fall under Teen or Mature depending on how strongly the board feels about it.

All in all, you would have to get your game rated to find out, as every game is different.

---

If your game is only going to be distributed digitally and you publish using one of the International Age Rating Coalition's participating storefronts (eg Google Play), when publishing your game, the storefront will let you fill out the IARC's questionnaire to obtain an IARC certificate, which will give you an ESRB rating automatically based on the answers you provide.

*Further reading: Microsoft has written a blog post giving insight into how their IARC age rating questionnaire is filled out.*

---
Tags: content-rating
---