# Question
Title: Using CNN's in Unity via Tensorflow and TensorFlowSharp
I have a project that tracks hands made in python, shown here: https://github.com/timctho/convolutional-pose-machines-tensorflow

I want to effectively import this into Unity. I have generates the .bytes file from the model, but have no idea how to do anything further than this. If anyone has worked with ML-Agents or TensorflowSharp in Unity and/or would be willing to have a look, this would be great. The image-processing stuff would be done probably in a C# file beforehand, I just want to know how to run the network.

Thanks.

# Answer
> 1 votes
Best way to do this is to create a frozen graph (with the extension .pb) and use TensorFlowSharp so this no interaction with any Python. For example, my code looks like this:

```
        TFGraph graph = new TFGraph();
        graph.Import(File.ReadAllBytes(Application.dataPath + "/frozen_model.pb"));

        TFTensor input = ImageUtil.CreateTensorFromImageFile("C:/Users/Lopes/Desktop/longhand.jpg", TFDataType.Float);

        float[][][][] outfloats;

        using (TFSession sess = new TFSession(graph))
        {
            var runner = sess.GetRunner();
            runner.AddInput(graph[input_tensorname][0], input);

            runner.Fetch(graph[output_tensorname][0]);
            var output = runner.Run();
            outfloats = (float[][][][])output[0].GetValue();
        }

```

Hope this helps anyone with a similar conundrum.

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


title: Seams between tiled textured cubes

text:
# Question
Title: Seams between tiled textured cubes
I've created a textured cube in Blender, which I have uv-mapped like this:

The tiles are 256x256, and I've mapped the coordinates exactly at the edges (e.g. x: 256, y: 512). I then export my model as an fbx-file to Unity. In Unity, if I put many cubes adjacent to each other, seams appear between the cubes, like this:

I think I understand why this happens, because the uv-coordinates are exactly on the edges, and thus two faces sample from the same points along an edge.

I could solve this in some ways:

* By making the uv-tiles smaller, but it would look ugly with patterns.
* By adding some space between the tiles in the texture, and aligning the uv-coordinates to them.

**My question: is there a better proper way for achieving this?**

---

# UPDATE:

So, about half a year later I still have issues with the seams. I've tried many things:

* Start uv-coordinates at 256.5 instead of 256, and so on...
* Turned of mipmapping.
* Set wrap mode to clamp.
* Set filter mode to point filter.
* Edge padded the texture atlas with first 4px, 8px, 16px, 32px. But still bleeding occurs at certain angles. Also updated the uv-coordinates accordingly.
* Changed my atlas to be of Power of 2 instead, i.e. 1024x1024 instead of 1024x768.
* Set "Non Power of 2" in Unity to None so Unity doesn't rescale my texture to nearest Power of 2.
* Set texture format to Automatic Truecolor instead of Compressed.

With 32px edge padding it actually gets a lot better, but it still isn't perfect, I guess I could go on and try even more padding, but my textures will get bigger and bigger.

I understand now that it is the mip-levels that are causing the bleeding. At far distances I don't think this is a problem, but I can see this occuring just about 5-7 units away from the player, if the player is looking down.

I believe there is something trivial about this that I'm missing. This is really a showstopper for me, forever grateful to the one who helps me solve this.

Thanks in advance!

This is how I have edge padded my texture (lines not visible on real texture), the problem does not only occur when the faces has such extremes distinct difference in colors as this one. It also occurs when the faces have patterns.

# Answer
> 1 votes
I would say **Edge padding**.
(Even if you have disabled `MipMaps`)

> If the ‘gutters’ (blank areas between UV’s) have colors/transparencies that are very different from the colors inside the UV’d areas, then those colors can ‘bleed’ together which creates seams on the model. This problem will also occur when neighbouring UV shells have different colors; as the texture is downsampled eventually those colors start to mix.

http://docs.unity3d.com/462/Documentation/Manual/HOWTO-alphamaps.html

http://wiki.polycount.com/wiki/Edge\_padding

# Answer
> 0 votes
I had the same problem with a very simple labyrinth I made. I tried playing around with the quality settings (Edit \> Project Settings \> Quality) and switched between them. I noticed that the seams were present exclusively when it was set to either "Beautiful" or "Fantastic". The main difference between Beautiful and the next best setting ("Good") was the fact that anti-aliasing (2x MSAA) was on. Turning it off for every quality setting solved the problem.

I plan on trying out another AA solution than Unity's. I read that Valve's AA (used in The Lab) is supposedly very good for VR.

(hope this helps)

Note: yes, in my labyrinth everything is vertex-snapped.

# Answer
> 0 votes
Use a separate texture for each surface of your cube. That way there is no way they can bleed into each other.

It would also be more memory-efficient to use six 256x256 textures than one 768x1024 texture, because in your large texture, 42% of the pixel-space is wasted.

It also allows you to apply different shader settings on each surface. This might be interesting when you start to use more complex materials than just single colored textures. It also allows you to highlight individual surfaces with shader properties. If you want to keep using single-colored textures, you do not need a texture at all because you can simply implement the material of each surface with a textureless material.

# Answer
> 0 votes
I had the same problem and it was resolved by making sure Unity treat the alpha as transparency.

Click on the actual texture, in the inspector, the texture type was "default" so I had to manually check "Alpha is Transparency".

# Answer
> -1 votes
If you send mesh objects with different positions to the graphics card, unity's precision is not high enough and the actual vertex positions in the graphics cards, the seams, will not be the same. hence you will see seams inside the graphics card. the further you go from origin, the bigger the rounding error will be.

If you put all your cubes on 0,0,0 and instead change their vertex positions to the positions you want, and send them all to the graphics card, they will not contain seams. they will have identical object position and seam position rounding errors sent to the graphics card.

AFAIK i solved the issue after some time and puzzling, perhaps waster 50 hours to solve it, becaues i was told that my problem was inside the game engine not the graphics card.

So... keep all cubes on zero zero zero, edit their vertex positions, rewrite all the vertices to the new positions you want the cubes to be in, otherwise the seam positions in the graphics card differ microscopically.

Its a weird error inside Unity that no one else than me knows about because i am a lame coder who never managed to code a game but i am basically a genious:) mark me down.

---
Tags: unity, textures, blender, uv-mapping
---


# Question
Title: How do I make educational games engaging not boring?
We make educational games for school students, age 7-18; we can't have any violence or blood in them.

I have scoured Google Play and YouTube for good examples of educational games.

So far I found this math game. The cannon fires at number-enemies, to score, the player should bring their values to **exactly zero**. As levels advance, the bigger numbers occur - 10, 20, 30, etc.

Why is it hard to make educational games that are not boring? It seems violence is what attracts most young people nowadays! One big exception could be puzzles.

# Answer
> 108 votes
The reason you see so few high-quality educational games is because the most educational games do not look like they are educational. They don't even pretend to be.

As a kid I learned English mostly from playing non-localized RPGs on my Sega Mega Drive. I discovered the scientific method for myself as a teen by analyzing online games and trying to figure out the game mechanics. I obtained the ingame resources necessary to test my hypotheses by applying economical theory to corner the ingame markets and get rich. And even now that I am an adult, I keep discovering games which teach me something. For example, Kerbal Space Program taught me a lot about spaceflight and lately Crusader Kings 2 awoke my interested in medieval history.

What do we learn from that?

Do not hammer down the point "This is the thing I am going to teach to you, no matter if you want it or not". Design the look and feel of the game so it appears to be about something completely different. But design the game mechanics so that the player needs to reach your educational goal to progress in the game.

This, of course, begs the question "Then how do I *market* it as an educational game to pedagogues and parents when it doesn't *look* educational"? Well, you didn't ask about that :). That's the reason why many games marketed as educational suck so much. They are not designed to appeal to the young players, they are designed to appeal to the adults who buy them to educate their children.

# Answer
> 24 votes
The issue comes from the fact that the general public hasn't accepted NORMAL GAMES as a learning tool, so in order to be an 'Educational' game you have to make the game with 'education' first, instead of 'fun'. This creates pressure to lean on the side of boring, prettied-up digital homework instead of simply making a game that happens to teach you stuff.

Minecraft teaches you about wildlife conservation and resource management. It doesn't claim to be educational.

Many RPGs will expand your vocabulary exponentially.

The point is, to be a good game you have to have fun first, not education.

You should do some google searches on the ideas surrounding "play time as education" and the like.

# Answer
> 18 votes
Most of these answers are on point when they say the game should first be a good game, but an educational game tends to be in a different format than a normal game. They tend to be made for shorter sessions of about 15 to 30 minutes, try to teach you more than you can learn with the same amount of time from a normal game, and have a broader and younger audience.

I think the answers that mention how much you learn from normal games are exceptions to the rule. Your average person wanting to play a game (think Wii or Wii U audience instead of Xbox One, PS4 or PC) isn't going to spend a lot of time thinking about game mechanics or even reading large blobs of dialog in an RPG if they don't have to.

**Try to solve problems using the material you are teaching**. Take for instance, "Where in the World is Carmen San Diego" franchise of yore. Using clues from the text to solve a crime was engaging and forced you to read the text. By not being timed, it allowed children with lower reading skills the opportunity to read at their own pace. This example also picks up from other answers in that it didn't feel so much like an "educational" game, just a game.

**Use reward systems**. These work and can be a great way to persuade your players to keep playing.

**Allow for depth**. Don't just look up a quick fact about Saturn and paste it on the screen for your players to regurgitate later, allow them to explore all kinds of things about the topic (and get further rewards with the more they know).

**Make the game feel like a higher quality game** with animation, sound, music, etc. Too many educational games play like something that was made for a programming course's assignment. Take for instance Auralux, which has good graphics and a very nice sound and music system. Without it, the slow and simple gameplay would probably be too boring for most people to play for more than a few minutes.

**Make the experience personal**. People (especially children) love to have a custom experience. Let the player customize their character, choose a name, and have achievements.

If you can, ramp up the difficulty based on how easily the player overcomes obstacles. Someone who can't get anywhere will just get frustrated and give up and someone who beats the game in 10 minutes isn't going to come back. If you can't spend the money for elastic gameplay, then try to find a good balance based on your target audience.

# Answer
> 12 votes
Puzzle games, with some quests or riddles could be a great start. I think that kids may find educational games boring not because they lack blood or violence but because they **lack a goal**.
For the game above: **why** should a kid play it? How does he/she gets **rewarded**? How his/her victory affects the game?

# Answer
> 8 votes
The number one thing I have found that limits educational game is a hard lined insistence that the adult programming the game define what will be learned in the game. Much of a game's appeal is from the player deciding what they want to get out of the game. The game maker can make suggestions, but in the end, it is the player that decides. If your game suggest "You should want to learn to add positive and negative numbers," and that's not the player's definition of "fun," they'll quickly put the game down.

Instead, make room to permit the player to decide what they want from the game. **If they want to have fun in their particular way shape or fashion, let them!** Sure, reward them for wanting to have fun in ways that support your educational goals, but don't make it hard to enjoy the game outside of a narrow window.

Let's use your cannon game as an example to brainstorm on. Unless you feel like adding numbers to get to a zero, it's a rather boring game. However, what if summing numbers to zero instead offered you power ups, and the "game" was a more standard cannon game. Now the game is just a game, but there's a way to make it easier by doing math. If a player wants to win simply by shooting every number out of the sky, guess what: *they learned geometry!* As the game progresses, you may try to encourage them to play the math part of the game more by making it gradually harder to progress without playing the part of the game you want them to play. If they want to stick to the easy stuff, that's fine. If they want to rely on raw twitch fingers to blast everything, that's fine. If they want to concentrate on the math, great. **If they want to find their own balance between math and twitch, that's even better!**

Now, consider that paragraph with respect to Candy Crush, one of the more addictive games of all time. The primary focus of the game is on studying patterns in the game grid. Instead of making that the game, they make it a way to power up: cookies kill off whole colors, wrapped sweets slaughter columns or rows, etc. At first you can just play the game any way you like. However, as you progress in the levels, the power-ups smoothly become more and more important, until you reach a point where some of the simpler power-ups are absolutely and utterly required to beat a level, and the game encourages you to reach for the more powerful power ups.

Candy Crush is a good example for how to not make a game boring!

# Answer
> 7 votes
---

## Consider:

"How do I make educational games engaging (and) not boring?"

---

Everything that can be used to make a game engaging in general - and there is a lot to do - should apply to educational games too. The matter is that if you set to create an educational games you are placing upon you an extra set of constraints that may make it hard to desing engaging game mechanics.

Yet, not knowing the gnre, I gotta cover from cooperative to competitive, from single player to massive multiplyer... so, gotta go the abstracts and the generalizations.

---

To see how to make games engaging, go back and look at how individuals play. Not just video games (and not just humans). A common theme of all play time is make-believe^1, without good immersion any game will become boring. But the immersion is not in the graphics or the music (even tho, they can help) but in the mind of the player.

^1: You should also consider: challenge, chance and thrill.

Consider how a child may enjoy playing with toys. Even if the toys doesn't have rewards or goals. How is that possible? Meditate on that.

Now, if we consider that all games have some form of make-belive, then we can consider that all games are a form of simulation. You may consider them training - except that people enjoy it!

By extension, all games prepare you for something. Even if that something is just playing the game itself. So making a game that teaches something is not hard, but when you settle to make an educational game, you are setting yourself to make a game that teach certain things - in particual those of academic value - and that teach them in a way that is measurable or testable.

---

Note: Another thing that makes the game boring is repetition, which sadly is one of the things that is used for memorization. So if you want to use repetition for the educational content (because it requires memorization) then your should do it in a way that is not predictible.

---

## How to motivate

Before going futher, I would like to encorage you to ponder... why do you play the games you play?

---

The naive approach for decision making is that people choose what give them more value. And so there would be some value function that can be applied for each option (which assumes that the set of options is discrete and finite), that gives a value and you pick the one that give you more. Addendums to this approach will consider cost, risk, simulataneos tasks, etc...

But what is "value"? What is it that motivates people? What need do games fullfill to people?

As per Self-determination theory there are three core needs that could be fullfilled by games:

* Competence: Games can give you the skill to do things. Become better at the challenges the game presents.
* Relatedness: Games can serve a means to connect with other people.
* Autonomy: Games can provide a framework in which people can own their actions.

Note: Also constrast with Maslow's hierarchy of needs: Games can provide a sense of belonging, can improve your self-esteem, and may help you become a better individual.

---

You can use tricks techniques such as random possitive stimulus rewards and conditioning creating habits that are known to bring poeople back to the game.

On the other hand you may inspire curiosity - and imho this is what you should try to do - so that people doesn't come back because they may get a new virtual medal^2 but because they want to know what's next, it is the unknown that calls to them^3. Of course this will be easier with certain topics than others. This is done in a game by surprising the player, and being ever changing. If the game is always the same, well it is boring.

^2: It is known that people attribute real value to virtual things, so yeah, they come back for the virtual medal.

^3: Which is also an argument of why people don't find interesting a game where they do what they do for work. Instead people are interested in games where they are and do things that they don't in real life.

So: More replay value =\> more engagement.

---

Yet, if the game is meant to have some challenge. And as the player has more experience their skill is expected to increase, and as such the challenge should increase too. Otherwise the game will become dull over time. If you consdier a competitive game, then you will have to balance the skill level of the players.

A measure of player skill will be handy, it will allow you to provide the appropiate challenge and also will be useful to see how well the players/students are learning the game/lessons.

Difficulty curves and how to adapt them is broad topic, and while it should not be overlooked, that discussion doesn't belong here.

---

Consider how to use randomness and combinations to provide structure to the game. For instance the game in the OP shows a game where - I pressume - numbers appear at random. Yet, the structure of the game doens't really change, it only makes you stop and think what number to pick. Now consider a game like Mario Kart where the random roll of the power ups (even if it doens't have an uniform distribution) may change the way you play the game (from an defensive to an offensive game play, for instance). Or the random maps of Age of Empires or Civilization may alter the means you use to expand your territory. Or for Minecraft, depending of your spawn location you may have to decide if you dig, build or explore first. And the next day, the player knows that the game may have a new experience for them, and so the player comes back.

Consider the other side of random: grinding. Many games use griding as a way to provide virtual difficulty. Grinding is tiresome, so it translate as making a difficult task. But it is not really making the game harder or more complex, just longer. And for each step of the grind, the player get a random reward, and maybe there is a chance of a really good prize. This thrill provides engagement, but for many player it doens't really make the game fun.

---

It should be noted that a frustrating game maybe both a good or a bad thing from the engagement perspective. You may decide to drop the game if it is frustating, or you may be enraged with the enemies in the game (but not with the game itself) and want to get back in to play it and beat it (or kill the enemies for the sake of it). If you want to laverage rage for engagement, you have to make sure that the frustation comes from the enemies and not for a bad game (riddled with bugs or bad controls, for example) and that it doesn't break the immersion or consistency.

---

## Your players

Ok, that's the next thing to consider: your players. Not all players are equal.

You maybe interested in learning about Bartle's Taxonomy of Player Types (which is intended for online RPGs). For abstract it classifies player in four types: Achievers (people that want prizes), Explorers (people that want to learn about the game and its mechanics), Killers (people to who like to express power and domination), Socializers (people who like to build communities).

You will find that nobody fits any category exactly, instead people are to some degree one and to some degree the other. But it may be possible to tell if they have a dominant type.

You should provide game mechanics that interest to player of the categories of player that you want to have. For a tradicional MMORPG it is argued that you want a balance of the four. But many games may do well without players of some of the categories \[Or the classification may be need to be adapted for other gnres\].

* Archivers will want to have prizes, titles, archivements, etc...
* Explorers will want huge worlds, secrets, shortcuts, a good lore, etc...
* Killers want taunts, competition, player vs player, anything that can act upon other players (including griefing and bullying), etc...
* Socializers will want means of communication, chat, teams, guilds, markets, etc...

---

## And make it educational

Just like you can't put all your player on the same bucket, you cannot assume that they all learn the same way. Some may prefer to be presented with examples, some may prefer to be told what to do, and some will prefer to be explore by themselves and learn by committing mistakes.

In fact, it is a sign of a good game the one where you don't notice where the tutorial ends, in particular if it is tematically consistent. For instance consider Portal, most of the game is an elaborate turorial for the final battle, but it doens't feel like you are just playing the tutorial. Also consider Mega Man X that introduces all game mechanics on the tutorial level without telling them to you explictly. An alternative is to have the tutorial be engaging by itself, for instance VR training in Metal Gear Solid plays like its own game, while the main game will do its best to teach you as it goes.

Now, since you want to teach certain particular things in the game, you will have to build them in the game. The ideal is the case where learning to play your game is learning what you want them to learn. You want the player to have some rewards^4 if they do it correctly, in particular you need the player to understand when they have done it wrong and WHY. And you want the player to be able to get textual visual help if they request it.

^4: You may have to tailor "rewards" to the player type, it may not always be in term of archivement. Also consider if the rewards is instrinsic (for instance is a successful execution rewarding by itself) or a skinner box extrinsic (it gives you access to something else, or point to buy stuff, etc...).

Futher more you want it make sense. If you can provide an in-game reason why are you doing that task (that you are trying to teach) the better. If it can be related to the real world much better. Consdier this a test for you: when in your life do you need the skill you are trying to teach? Who will use this kind of skill on a daily basis? How can you turn that into a game? It may be required to find other problem that has isomorphism to what you want to teach (mainly because academic problems are abstract) in order to add them thematically in the game.

Remember that the game has to teach how to be played in addition to whatever is your agenda for the current educational program. So if you can build in it affordance and utilize mechanics that the player may already be familiar with (perhaps from another game, or earlier in the same game) then it will be more accesible.

---

If you are pitching this to teachers you want statistics. It is good to know how much the players are playing, how long are the session? how frequent are the sessions? how much progress are the players doing? It may help you to improve your game by finding what are the cases where the players are not really engaged, and what are the cases where the players are having trouble learning. This will help the teachers too - they may take it as an aid for evaluation, and it may be an extra incentive if the students can skip some tests or homeworks if they are good at the game. It may be worth noting that if you go to the path of gamifing the claass room, you want cases where the players/students cooperate.

# Answer
> 6 votes
I'd suggest looking up and taking cues from game play in the following:

1. The Lost Mind of Dr. Brain (personal favorite - plus it emphasizes IQ building from more of a Weschler scale approach, i.e. problem solving over straight memorization)
2. Math Blaster / Reading Blaster (Davidson)
3. Jump Start (Phonics, Reading, Typing)
4. Number Munchers (pretty sure this is given).

My guess is, if you're old enough to be asking this question, you're familiar with everything I've listed, but maybe not.

# Answer
> 2 votes
"Why is it hard to make educational games and not boring games?"

Educational games just as hard to make interesting as any other game. If you look at the example you gave, the graphics alone would be enough for anyone to say that game is of low quality. But if you apply a couple iterations of continuous redesign and improvements to that game, you may end up with Tetris, which was and still is a blockbuster, despite its very limited graphics.

Educational games often use the fact that they are educational as an excuse to publish a poorly made game. As a result, people have come to expect games that are sold as "educational" to be of lower quality. So if you make a good educational game and you want it to sell well, you don't label it as "educational game". Thus, **if you want to look for truly good educational games, you look at games that are educational, but don't brand themselves as such.**

Tetris is great for spotting and matching shapes, Pong teaches about elastic collisions, Microsoft Flight Simulator teaches almost everything about aviation, Kerbal is great for learning all about gravity and kinetics, Civilization 1 teaches a lot about history, Cities Skylines teaches about traffic and congestion, etc.

Focus on making a great game first. One affordable way to do that is to "get inspiration" (aka copy/borrow/steal) from good games that already teach most of what you want to. For simpler concepts - like the one in your example - I recommend to specifically "get inspiration" from board games.

# Answer
> 2 votes
Let me start off by saying something somewhat controversial: **This is absolutely the wrong place to ask**. Game developers are 1. hard core gamers and 2. the kind of people who analyze those games. The majority of people do not fall in to those categories. Most kids *do not* analyze the optimal way to do things in games, instead they just do whatever they want. This will still teach them certain things like foreign languages, but if the goal is to teach them a wide variety of skills then you do end up what others are making fun of as glorified homework. Just because those games seem boring to adult hardcore gamers does in no way imply those games do not fulfill their intended purpose.

So, whom should you ask this question? Well, probably two groups:

1. Those who study psychology and gamification,
2. and those who study didactics/the science of education (not sure of the proper english name).

And what you will find out is that just because a game is not violent in no way means it's going to bore young kids. The important thing is just to reward them for a job well done (gamification), though doing that in the right way and actually making the educational part stick is *hard*. So I am not even going to think about trying to answer this question here, as it's big enough to study for years and still only know the basis of.

# Answer
> 2 votes
When our kids were growing up there were two sets of educational "games" that stood out

1. the Reader Rabbit series, and
2. the Zoombini adventures/games.

Both of them had reasonable graphics, etc, but what made them really stand out was

* **they had a story behind them.** The kids were on an "adventure", and there were characters to interact with (in a limited fashion) and puzzles to solve. The "puzzles", of course, were what the kids were learning from, and they were well thought out and interesting.
* **they were age-appropriate.** In the Reader Rabbit series there were programs from Toddler through Kindergarten to 1st and 2nd grade, then various program for ages up to 6-9. Also in the Reader Rabbit series there were a couple of programs where the story line was rather extensive (looking here at the list of Reader Rabbit programs I'm particularly thinking about "Reader Rabbit 1st Grade: Capers on Cloud Nine!" and "Reader Rabbit 2nd Grade: Mis-Cheese-ious Dreamship Adventures!").

The Zoombini series again were a "quest" or "adventure" type game where the player had to solve puzzles to move through the game world.

Our kids would play these for hours.

Were these programs effective? I think so. Obviously there's more to producing a successful student than a few computer programs, but of our three kids:

1. Eldest was a straight-A student from 6th through 12th grade (in gradeless Montessori programs before that), took I-don't-know-how-many honors and AP classes, was valedictorian in her high school class, and is now a freshman at Harvard.
2. Second is still in high school - straight-A student 6th through 11th grade (current), taking as many honors and AP classes as are available.
3. Third is in middle school - straight-A student and captain of her school's Academic Challenge team.

I think that these educational programs helped. YMMV.

Best of luck.

# Answer
> 1 votes
While there are some good points among the answers, I feel that none have really nailed what I consider to be the essence of a good game that teaches things. Here's my take on it:

1. Start with the hook. Make the subject appear as exciting as possible. The game should have some kind of narrative that uses the subject-to-teach in the background, while leaving the foreground to the genuinely exciting parts.
2. Use progression and variety to maintain interest. Rewards in the commonly understood sense are too narrow and often, bland. Plot twists, new "weapons" for puzzles, new scenery and interactions - that's where the excitement is at. Similarly, doing the same puzzle (but slightly more difficult) over and over should be avoided at all costs.
3. Repetition is also necessary. Switching between entirely different kinds of tasks and sets of information is mentally tiring. While the content is full of variety, the subject shouldn't be.
4. Associative transitions. Whenever the information taught is changed, it must be done gradually, to help the brain form links between things. Sudden jumps in context are hard to deal with and make things seem pointless - what's the point in remembering something if you're going to move on soon?
5. There can be no time limits. If the player wants to understand something better, let it happen. In a typical classroom setting, everyone is forced to learn in sync with others, which is boring for some and stressful for other students. A computer is not constantly in a hurry, so it's an opportunity to do things right.
6. Subject tree traversal:

What I call the subject tree is a graph where nodes are small bits of information and links determine which information depends on other information to be understood (nodes generally depend on deeper nodes).

Most teaching is done starting from the end (the small and simple things), breadth-first, towards the root (the big and complicated thing). This way, the reason to learn things is rarely, if ever, addressed. Things seem pointless.

However, if you start with the big goal and move deeper until understandable information is reached (depth-first), the reason for learning is always obvious.

*The exception to this are muscle memory/calculation tasks (like playing musical instruments) that require copious amounts of practice and nothing else - though it seems that something like that can't really be taught in a typical setting, so I'm assuming the question isn't about teaching anything like that.*

---

Plain gamification, while a somewhat valid solution, won't last long. Creating motivation and inspiration in students is what produces the best results. Coincidentally, I remain somewhat unconvinced that a game posessing such qualities can be produced from the starting point of wanting to create a good educational game.

# Answer
> 1 votes
As a kid, Civilization II broadened my understanding of the world and the way it works. My vocabulary was largely increased as a result of studying the game's concepts to become a better player. The game wanted you to play to win, not immediately to learn, so in wanting to play to win (and have fun) I took it upon myself to learn.

The game should tell you to play, instead of telling you to learn.

You should choose to learn because you want to play, instead of playing because you want to learn.

# Answer
> 0 votes
First of all, I'd like to state that this is a very good question.

Young population likes to be free, they like to play the games in their way. Their "way" is usually not education. You can play chess for hours even if you don't like it, but they won't if they don't like it.

You need to "inject" education into game. For example lets say that your game is Minecraft. Add a feature that gives you a **chance** (I mean optional, and non-intrusive) to solve a maths problem, and you get diamonds for it! Easier math problem, less diamond. Harder? More diamond!

You can reward the user for educating themselves, and they'll enjoy it too.

I used to play a MMO called hero years ago, and it used to ask you a random math question every hour or something, mainly to check if you are a bot or not. You had like 15 seconds to solve it, and if you did, you'd get some free loot. If it didn't give out anything, most people wouldn't solve it.

However, as stated in other answers, while the players will like this approach, families will probably not. "The game asks you to solve a math problem every 10 minutes, it is optional and it gives out free loot" will probably not satisfy the parents as an "educative game".

Another type of games that are educative and are liked by parents are puzzle games like Wordament. It is fun to play for some (believe me, the "some" here is way more than the "some" who will play purely educative "e-homework" games). The competitive factor is really important in these kind of games, for example leaderboards. You can give out real world prizes to the top 3 monthly etc, and it'll be liked by more players. (however, this requires the game to be paid or ad-supported)

# Answer
> 0 votes
Very important question! Maybe no single right answer, but here are some thoughts:
The term 'computer game' is harmful to the technology it describes reaching it's true potential. That's my main point. We need a new word to describe a different ambition.

3 billion hours spent playing 'computer games' per week is costing humanity a lot. Find a way of making *the player* go up a level, rather than the character, and you've cracked the problem.

That probably means understanding your "game lesson" so well yourself, that you can break it down into unimaginably tiny pieces.

The (sceptical) 'player' should almost immediately crush the first piece and be rewarded with praise and power-ups. "CORRECT!" "THAT'S RIGHT!!" "SUPERB!" "ACHIEVEMENT UNLOCKED!!" Build up her confidence quickly; make her contemptuous even, of the difficulty of the 'lesson'. Whatever your trying to teach, French, Physics, Math or the Fiddle; the state of play can take the fear out of failure. Mario dies? Mario gets the hell back up.

Remember, 'games' are repetitive. Use that. and then give her a challenge (boss) that looks impossible, but is easy-when-you-know-how. If you can reveal the boss's weakness in the lesson fragments of the preceding challenges, I think that's the bridge we're trying to cross.

You can't skimp on the fun. Normal games only have to work, and be fun. Ours have to work, be fun and deliver a truth beyond the parameters of the 'game'. But yeah, step 1, stop thinking of it as a computer game. This is post-game software.

# Answer
> 0 votes
The reason why your game is boring is because the player finishes learning the game objectives, and too quickly.

When playing a game, boredom depends on the game objective complexity, if the game's difficulty level is low, the player will quickly realize there is no challenge to the game, thus, easy, thus no reason to continue playing since it would be a waste of time, hence, boring.

If you want players to latch on your game, you need to make the difficulty dynamic, you can't expect people to keep playing a game where things don't change or get harder as you go.

This is one of many reasons.

Another could be that the rewards for playing is not well-thought out. So what if your player is doing good in the game, how do you reward a player and make them feel like the challenge was worth it?

These are many things game-developers must master in order to make great games.

# Answer
> 0 votes
for everything "boring" to be engaging and interesting, it should be a "way" not a "goal" to be achieved, for example learning English is much more interesting if your goal is to do something fun or interesting with it rather than to make learning English the goal itself.

therefore it will be much more interesting to make the goal of the game something fun as every other games. and i think it's best for the game to contain around %70 of fun and actions and %30 educational and you shall learn them willingly to pass the game.

---
Tags: puzzle, educational-games
---


# Question
Title: Can Cloud Functions be used for a multiplayer game server?
I'm building a turn-based online multiplayer game with Unity for both desktop and mobile.

Traditionally, I would build a Java socket server, host it in Google Compute Engine or similar, and have players connect to it. Since this works with sockets I can easily notify players of relevant events, such as matchmaking, chat, enemy turn, etc.

I've been curious about Serverless Functions for a while, such as Google Cloud or Amazon Lambda.

However, at first glance it doesn't seem to me like that would work for my game: because there ins't a constant connection (with sockets), I can't notify players of relevant events in realtime - or can I?

For mobile I realize I could probably use something akin to push notifications (so the serverless code may push messages to the relevant player's phone). But that doesn't seem as simple for desktop games.

Well, what if the players poll for messages? Like every second, call a Cloud function and ask them if there's anything for them.

I'd image that would work, but that seems rather overkill - with as little as a couple thousand players, calling the same function every second for prolonged times (the game's matches are long) sounds like it would easily increase expenses.

Is there something I am missing? A coding practice that would make serverless code feasible for a cross-platform online multiplayer game? I want to make it work, but it would seem like a socket server is still my only option.

# Answer
> 3 votes
I think the simple answer is: yes, depending on your game design.

What you touch on here is a fundamental of any server (or serverless) API design. You have to trade responsiveness off against scalability. Maintaining a connection to clients incurs overhead, and the more clients you have the more time you spend just handshaking back and forth. If all of your traffic goes through those mechanisms those nodes have to get larger and larger.

If you need clients to become aware of events within a second, or within a few render frames, the costs of polling become astronomical and wasteful, because the vast majority of the traffic is just "anything for me? No." If your clients can live with only finding out events every few seconds more more, then maintaining a continually open TCP connection when the majority of the time there's nothing to send is also wasteful, not to mention the difficulties you have maintaining and restoring those connections in the presence of poor network conditions.

That said, I think a smart architect these days would be able to leverage both solutions. Perhaps making edge nodes which your clients connect to and maintain those connections, but make them dumb, stateless and highly scalable. Effectively just brokers for message passing, like in MQTT. You send messages to the game clients when you have to, but you try to keep them short so that those nodes can cope with a lot of clients. You try to keep them disposable so that if a client loses connection or the node fails, you can shuffle those connections onto another node. Internally, your main workhorse doing game processing is not just one big monolithic service, but many little processors, working their way through their own job list, co-ordinating where they need to, sending messages to clients when something interesting happens. But you're never sending big gobs of data to the clients through the connections, you're just sending a notification, and when the clients hear about the event, they can then call the serverless API to actually pull down the data, or to do an expensive operation on the state (like querying a lot of objects around the player).

That's all purely hypothetical but you can see how it might bridge the gap between the ability to push events to disparate clients promptly while still allowing you to scale up your handling.

Back down to reality, I think the real issues with serverless probably boil down to:

* Contention over the data store: instead of fighting over server compute resource and failing to scale because it can't cope, you get unlimited server compute, and instead the bottleneck shifts to the database that has to be shared amongst all the serverless functions to collaborate. A truly scalable database is just as hard a problem to solve, perhaps even harder, than a scalable server.
* Unpredictable execution times: the price you pay for unlimited compute is variability in execution time. An operation on a traditional server will typically take the same amount of time every time, the startup costs are all paid when bringing the big server online. In a serverless model, you pay much smaller startup costs but have to do so every time a new context of your function spins up. Just because it's handled for you, doesn't mean it doesn't take time to do. The first execution of a function might take 500ms and the next 50 executions might only take 10ms. You don't know when or where the 500ms delay will hit, because you have no control over how fast requests are coming in for the function or how the Cloud provider will choose to scale the function up.

---
Tags: unity, multiplayer, online, cloud-computing
---


# Question
Title: How do I rotate the Camera around the player by Keypress in Unity?
I want to rotate the camera around the player by pressing E and Q but it doesnt rotates around the player. I tried RotateAround but didnt worked.

Code:

---

```
public Transform player;
public float smoothSpeed = 0.125f;
public float rotateSpeed;
public Vector3 offset;
private Vector3 velocity = Vector3.zero;

void LateUpdate ()
{
    transform.position = Vector3.SmoothDamp(transform.position, player.position + offset, ref velocity, smoothSpeed * Time.deltaTime);
}

void Update()
{
    if(Input.GetKey (KeyCode.E))
    {
        transform.RotateAround(player.position, Vector3.up, rotateSpeed * Time.deltaTime);
    }

    if(Input.GetKey (KeyCode.Q))
    {
        transform.RotateAround(player.position, -Vector3.up, rotateSpeed * Time.deltaTime);
    }
}

```

}

# Answer
Updating the **transform.position** inside *LateUpdate()* function **overrides** the effects of *RotateAround()* inside *Update()*.

*RotateAround()* actually modifies the position of the transform, hence, when you do the *SmoothDamp()* you are negating the effects of *RotateAround()*.

My suggestion would be to insert an empty game object into the hierarchy.

Then create two separate scripts:

**CameraFollow.cs** ( Add this to the **Camera Jig** gameobject )

```
public Transform player;
public float smoothSpeed = 0.125f;
public Vector3 offset;
private Vector3 velocity = Vector3.zero;

void LateUpdate ()
{
    transform.position = Vector3.SmoothDamp(transform.position, player.position + offset, ref velocity, smoothSpeed * Time.deltaTime);
}

```

**CameraOrbit.cs** ( Add to the **Main Camera** gameobject )

```
public Transform cameraJig;
public float rotateSpeed;

void LateUpdate()
{
    if(Input.GetKey (KeyCode.E))
    {
        transform.RotateAround(cameraJig.position, Vector3.up, rotateSpeed * Time.deltaTime);
    }

    if(Input.GetKey (KeyCode.Q))
    {
        transform.RotateAround(cameraJig.position, -Vector3.up, rotateSpeed * Time.deltaTime);
    }
}

```

So in the end the Camera Jig is positioned where the player is and the Camera rotates around the Jig.
> 2 votes

# Answer
This might help you,Assign this code to your camera

```
[Range (0.00001f,3)]
public float speed = 0.1f;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update ()
{
    Vector3 velocity = new Vector3 (Input.GetAxis ("Horizontal"), 0, Input.GetAxis ("Vertical")) * speed;
    transform.Translate (velocity);

    //Rotation
    float rotation =0;
    if (Input.GetKey (KeyCode.Q))
        rotation -= 1;
    if (Input.GetKey (KeyCode.E))
        rotation += 1;
    transform.Rotate (0, rotation, 0);
}

```

use Q or E button for rotation.
> 0 votes

# Answer
What you could use is an orbit camera. Here is an example:

```
using UnityEngine;
using System.Collections;

[AddComponentMenu("Camera-Control/Mouse Orbit with zoom")]
public class MouseOrbitImproved : MonoBehaviour {

public Transform target;
public float distance = 5.0f;
public float xSpeed = 120.0f;
public float ySpeed = 120.0f;

public float yMinLimit = -20f;
public float yMaxLimit = 80f;

public float distanceMin = .5f;
public float distanceMax = 15f;

private Rigidbody rigidbody;

float x = 0.0f;
float y = 0.0f;

// Use this for initialization
void Start ()
{
    Vector3 angles = transform.eulerAngles;
    x = angles.y;
    y = angles.x;

    rigidbody = GetComponent<Rigidbody>();

    // Make the rigid body not change rotation
    if (rigidbody != null)
    {
        rigidbody.freezeRotation = true;
    }
}

void LateUpdate ()
{
    if (target)
    {
        x += Input.GetAxis("Mouse X") * xSpeed * distance * 0.02f;
        y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;

        y = ClampAngle(y, yMinLimit, yMaxLimit);

        Quaternion rotation = Quaternion.Euler(y, x, 0);

        distance = Mathf.Clamp(distance - Input.GetAxis("Mouse ScrollWheel")*5, distanceMin, distanceMax);

        RaycastHit hit;
        if (Physics.Linecast (target.position, transform.position, out hit))
        {
            distance -=  hit.distance;
        }
        Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
        Vector3 position = rotation * negDistance + target.position;

        transform.rotation = rotation;
        transform.position = position;
    }
}

    public static float ClampAngle(float angle, float min, float max)
    {
        if (angle < -360F)
            angle += 360F;
        if (angle > 360F)
            angle -= 360F;
        return Mathf.Clamp(angle, min, max);
    }
}

```
> 0 votes

---
Tags: unity, c#, camera, rotation, movement
---


# Question
Title: How to keep an object in a certain part of the camera view?
I have a 3d camera that is viewing a character that is moving. As the character is moving i want the camera to adjust itself so as to keep the character in the left third of the camera view.

I understand how to move the character in world space but how do i check in what part of the camera view it is in? And then know how to adjust the camera to compensate?

**EDIT:** I am looking for the maths behind this. I understand that if i have the character world space postiton, i can convert that to screen coordinates by applying the view and projection matrices. I then get the camera view in screen coordinates. I am able then to create some 2d bounding box that will move the camera if the character enters it.

# Answer
Take a look at the lookAt matrix : https://www.scratchapixel.com/lessons/mathematics-physics-for-computer-graphics/lookat-function I can't explain to you myself as I use a matrix library for this, but there are tons of tutorials like this. This puts the point in world space you choose in the middle of the screen, and puts your camera where you want it be. You can then multiply that matrix by a yRotate matrix, or a rotate matrix with an axis of (0,1,0), with the angle that will place him at the wanted spot. I understand you wanted to understand the math, but matrices aren't complicated once you get how they work, and are just additions and multiplications packed to simplify everything for the gpu. I recommend this : https://webgl2fundamentals.org/webgl/lessons/webgl-2d-matrices.html This explains 2D matrix math, but in the 3D section he explains 3D math, and the lookAt matrix. Hope this helps.
> 1 votes

# Answer
Does it have to be fixed or smoothed? You need to figure out what position your center of the screen is at and how much distance it covers, the rest is just math. How you get that data however heavily depends upon the style of the game (3d or 2D)
> 0 votes

---
Tags: c++, camera, matrix, viewport, projection-matrix
---


# Question
Title: How can I stop startcoroutine when pressing once on the escape key?
I want like in games to pass over a cut scene or splash screen in this case. So the user can hit the escape key to pass it over.

```
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine.Assertions.Must;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class Splashes : UnityEngine.MonoBehaviour
{
    [Header("Splash Screen")]
    public bool useSplashScreen = true;
    public GameObject splashesContent;
    private List<Graphic> splashes = new List<Graphic>();
    public float splashStayDiration = 3f;
    public float splashCrossFadeTime = 1f;

    void Start()
    {

        if (!useSplashScreen || splashesContent.GetComponentsInChildren<Graphic>(true).Length <= 0) return;

        //if we use splash screens and we have splash screens
#region Get All Splashes
        //if you build on PC Standalone - you can uncomment this
        //foreach (var splash in splashesContent.GetComponentsInChildren<Graphic>(true).Where(splash => splash != splashesContent.GetComponent<Graphic>()))
        //{
        //    splashes.Add(splash);
        //}

        for (var i = 0; i < splashesContent.GetComponentsInChildren<Graphic>(true).Length; i++)
        {
            var splash = splashesContent.GetComponentsInChildren<Graphic>(true)[i];
            if (splash != splashesContent.GetComponent<Graphic>())
            {
                splashes.Add(splash);
            }
        }

#endregion

        //And starting playing splashes
        StartCoroutine(PlayAllSplashes());
    }

    private IEnumerator PlayAllSplashes()
    {
        //Enabling Splashes root transform
        if (!splashesContent.activeSelf) splashesContent.SetActive(true);

        //main loop for playing
        foreach (var t in splashes)
        {
            t.gameObject.SetActive(true);
            t.canvasRenderer.SetAlpha(0.0f);
            t.CrossFadeAlpha(1, splashCrossFadeTime, false);
            yield return new WaitForSeconds(splashStayDiration + splashCrossFadeTime);
            t.CrossFadeAlpha(0, splashCrossFadeTime, false);
            yield return new WaitForSeconds(splashCrossFadeTime);
            t.gameObject.SetActive(false);
        }

        //Smooth main menu enabling
        splashesContent.GetComponent<Graphic>().CrossFadeAlpha(0, 0.5f, false);
        yield return new WaitForSeconds(0.5f);
        splashesContent.gameObject.SetActive(false);
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {

        }
    }

    public void ExitGame()
    {
        Application.Quit();
    }
}

```

This splash is showing up each time the game is running. So I want to give the player the chance to press escape key to pass over it.

# Answer
`StartCoroutine()` returns a reference to the Coroutine it kicks off.

This reference can be passed to the `StopCoroutine()` method to stop running the coroutine prematurely.

You may need to do a bit more work in your case to handle any in-progress tweening from `CrossFadeAlpha()`, but that's a different question.
> 4 votes

# Answer
The answer by Chris Mills-Price is preferable in most cases: Keep the `Coroutine` object which gets returned by `StartCoroutine` and call `StopCoroutine` if you need to abort the running coroutine.

But sometimes it can be cumbersome to do this. For example if coroutines are started by objects which might no longer exist.

In that case you can also check for key inputs within your coroutine after each `yield return <expression>;`. If you detect the user-input which is supposed to abort the coroutine, you can do so with `yield break;`.
> 4 votes

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


# Question
Title: Why does Unity ignore normals when calculating backfaces?
Here's some code to generate a square mesh.

```
Vector3[] vertices = new Vector3[]
{
    new Vector3(x1, y1, z),
    new Vector3(x2, y1, z),
    new Vector3(x2, y2, z),
    new Vector3(x1, y2, z)
};

int[] triangles = new int[]
{
    vertexIndex, vertexIndex + 1, vertexIndex + 2,
    vertexIndex, vertexIndex + 2, vertexIndex + 3
};

Vector3[] normals = new Vector3[]
{
    this.normal, this.normal, this.normal, this.normal
};

```

The resulting mesh looks like this:

The normals have been set to (0, 0, 1), making the square face in the positive Z direction. I would like them to face in the negative Z direction, so the intuitive solution would be to set the normals to (0, 0, -1), but the result looks like this:

Despite the normals facing the opposite direction, the face's front is still in the positive Z direction. When viewed from the negative Z direction, the square is invisible due to backside culling.

Why do my normals not affect the directionality of the faces?

# Answer
This is not a decision by Unity, but a standard part of the GPU rendering pipeline. (See eg. OpenGL)

The primitive assembly step can be configured to discard faces based on their winding order on the screen, either...

* Culling faces that are wound clockwise (default behaviour in OpenGL)
* Culling faces that are wound counter-clockwise
* Culling neither

This allows culling to work on meshes no matter what weird stuff you might be doing with your normals (eg. whether your normals are in worldspace, object space, or view space, or whether you have multiple normal channels or none at all!), and no matter what camera projection you're using (eg. a perspective camera can technically see parts of meshes with normals pointing "away" along the camera's forward axis when the object is off to the side of the screen), and even if the vertices for a given face all have different normals interpolated across the face.

It's common for 3D authoring tools to pretend this decision is based on normals - but really what they do under the hood is choose which winding order to emit based on the direction of the normal you've specified.

So, if you want to flip the visible facing direction of a generated mesh face, invert the order of its vertex indices.
> 2 votes

---
Tags: unity, normals
---


# Question
Title: Occasionally nothing renders until the game window is resized - how to fix?
So, I'm making a game in Java, I'm using the BufferStrategy and Graphics class to render onto the screen.

But sometimes, when I run the game nothing is rendered onto the screen. But as soon as I resize the window, everything gets rendered fine.

At first I thought it had something to do with the BufferStrategy and graphics class, but when I printed those classes in the console after the initialization, they have the same values when the game is rendering fine and when the bug occurs.

I'm confused, is there a fix for this without altering a lot of code?

I'm creating my BufferStrategy as :

```
canvas.createBufferStrategy(3);

bs = canvas.getBufferStrategy();
g = bs.getDrawGraphics();

```

I'm not sure if the bug is occuring there though...

# Answer
> 1 votes
well im not sure due you lack information, like what are you doing in your update method but i will try to reply.

two things may happen here: 1.- bufferstrategy dont render anything until the memory is ready and an instance is created, in this case if createBufferStrategy is not ready will return null, what im doing below is to check again when its ready and if is, create BufferStrategy for the particular Canvas.

```
protected final Graphics getGraphicsBufferStrategy()
    {
        BufferStrategy bs = this.getBufferStrategy();
        if( bs == null )
        {
            this.createBufferStrategy( BUFFER_NUMBER );
            return null;
        }
         Graphics g = bs.getDrawGraphics();
         return g;

    }//

```

2.-when you use bufferstrategy you dont render anything until you flush all the data to screen, in this case you have to call lastly BufferStrategy.show();

i leave oracle example of bufferstrategy that you can find in this link // Check the capabilities of the GraphicsConfiguration ...

```
 // Create our component
 Window w = new Window(gc);

 // Show our window
 w.setVisible(true);

 // Create a general double-buffering strategy
 w.createBufferStrategy(2);
 BufferStrategy strategy = w.getBufferStrategy();

 // Main loop
 while (!done) {
     // Prepare for rendering the next frame
     // ...

     // Render single frame
     do {
         // The following loop ensures that the contents of the drawing buffer
         // are consistent in case the underlying surface was recreated
         do {
             // Get a new graphics context every time through the loop
             // to make sure the strategy is validated
             Graphics graphics = strategy.getDrawGraphics();

             // Render to graphics
             // ...

             // Dispose the graphics
             graphics.dispose();

             // Repeat the rendering if the drawing buffer contents
             // were restored
         } while (strategy.contentsRestored());

         // Display the buffer
         strategy.show();

         // Repeat the rendering if the drawing buffer was lost
     } while (strategy.contentsLost());
 }

 // Dispose the window
 w.setVisible(false);
 w.dispose();

```

# Answer
> 0 votes
Well, I came up with a cheap fix, which was basically resizing the window by 1 pixel and then back to original size within the code itself after all initialization is done.

But I still would like if someone let me know the reason as to why this is occurring.

---
Tags: java
---


# Question
Title: What does distance divided by acceleration mean?
I'm reading a book named "Programming Game AI by Example". Here's a method to help an autonomous character to slow down when it's getting closer and closer to its target:

```
Vector2D SteeringBehavior::Arrive(Vector2D TargetPos, Deceleration deceleration)
{
    Vector2D ToTarget = TargetPos - m_pVehicle->Pos();

    //calculate the distance to the target
    double dist = ToTarget.Length();

    if (dist > 0)
    {
        //because Deceleration is enumerated as an int, this value is required
        //to provide fine tweaking of the deceleration..
        const double DecelerationTweaker = 0.3;

        //calculate the speed required to reach the target given the desired
        //deceleration
        double speed =  dist / ((double)deceleration * DecelerationTweaker);

        //make sure the velocity does not exceed the max
        speed = min(speed, m_pVehicle->MaxSpeed());

        //from here proceed just like Seek except we don't need to normalize
        //the ToTarget vector because we have already gone to the trouble
        //of calculating its length: dist.
        Vector2D DesiredVelocity =  ToTarget * speed / dist;

        return (DesiredVelocity - m_pVehicle->Velocity());
    }

    return Vector2D(0,0);
}

```

For this line:

```
//calculate the speed required to reach the target given the desired
//deceleration
double speed =  dist / ((double)deceleration * DecelerationTweaker);

```

The Deceleration is an enum like this.

```
//Arrive makes use of these to determine how quickly a vehicle
//should decelerate to its target
  enum Deceleration{slow = 3, normal = 2, fast = 1};

```

I just don't understand how can it get a speed by dividing a distance by an acceleration (deceleration)? Did I misunderstand anything?

# Answer
This is difficult to understand because it’s incredibly unclear code. It begins to make more sense if you read "deceleration" as "factor of slowness", or even more precisely, "deceleration * DecelerationTweaker" is the "amount of time the object spends to traverse the distance".

The speed variable is the distance the object needs to traverse divided by some amount of time (0.9, 0.6, or 0.3) to give a normalized speed. It would be more readable if it were something like:

> double speed = distanceToTravel / timeToTravel

The speed is then checked against the object's maximum speed to ensure that it does not exceed it.

Finally, the desired velocity needed to traverse the desired distance is determined on a line that seems poorly structured for readability. The "ToTarget" vector should be first divided by "dist" to show with clarity that the intention is a normalized vector, since "dist" is merely the length of "ToTarget". The normalized vector is multiplied by the speed to obtain the proper velocity vector. It would be more readable if it were something like:

> Vector2D DesiredVelocity = (ToTarget / ToTarget.length) * speed;
> 0 votes

---
Tags: c++, ai, steering-behaviors
---


# Question
Title: Detect how much mouse has rotated in a circle around an XY point
How can I detect if the mouse cursor is moving in a circle around a target, and calculate how many turns it's done?

For example, if I rotate the mouse 4 times around a specific XY point on the screen, I would like to re-center my camera (in my context, I need this algorithm for a camera system)

# Answer
> 0 votes
Just take the mouse position in the last frame, subtract the center position from it and using atan2, get the angle of the vector. Then do the same for the current mouse position, subtract the first result from the second and you get the amount of rotation in that frame.

You need to save the total rotation in a variable. Divide it by `2 * pi` to get the number of circles the mouse did around the point. To stop this from firing even if the player didn't intend to center the camera, specify a minimum speed for the mouse. If it goes slower, than that, reset the total rotation variable.

So now that that's done, let's go over some problems. The biggest problem with this problem is accessibility. Some people have discomfort or some disability, that prevents them from doing fast and precise movements. This mechanic would put a big barrier in front of them.

The other thing is that doing precise circular movements using the mouse is still pretty hard. You can see this if you try drawing circles with it. This becomes a bigger problem, if the player has pointer acceleration turned on, which makes the task even harder.

---
Tags: javascript, rotation, input, mouse, pixi.js
---


# Question
Title: How to draw 2d road similiar to Outrun, Lotus, Pitstop, Cisco Heat games?
*** UPDATED 23/05/2018 ***

I've managed to implement road generation and curves using the techniques described here

I made a short gameplay video.

Hope it helps to anybody looking for answers.

# Answer
> 0 votes
I've managed to generate roads and curves using the techniques described in the links provided above, or you can watch the video here.

I cannot explain it better than that, so anyone wondering how to do it, please check it out.

---
Tags: 2d, libgdx, racing, curves
---


# Question
Title: How can you create a trigger collider between two moving objects?
I want to create a trigger-collider between two boxes. When one of the boxes moves, the trigger is supposed to change its size and shape so that its left and right edge stay attached to the two boxes.

How can I implement this in C# or JavaScript?

# Answer
> 2 votes
Get the two points on the side of the boxes

```
// Assuming that `box1` and `box2` are meshes
// Find the right side of box1 and left side of box 2

// `bounds` is the bounds of the mesh, so (max, center, center)
// is in the middle of the right face of the box
Vector3 box1r =  new Vector3(box1.bounds.max.x,
        box1.bounds.centre.y,
        box1.bounds.center.z);

// in a similar way, (min, center, center) is the left side of the box
Vector3 box2l = new Vector3(box2.bounds.min.x,
        box2.bounds.center.y,
        box2.bounds.center.z),

```

The location of the trigger should always be in the centre of the two boxes:

```
trigger.position = Vector3.Lerp( // `Lerp` returns a point between two other points
    box1r, box2l, // Take a point between the boxes
    0.5f); // 0.5 means take the center of those two points

```

Wether to change the trigger's `Center` position or the `position` of its `Transform` is up to you, this is pseudocode-like.

Then you need to resize the trigger, equal to the distance of the boxes:

```
trigger.scale = new Vector3(
    Vector3.Distance(box1r, box2l), // Its scale on X axis is exactly the distance of the boxes
    // This makes its scale on Y and Z axis the same as box1's size on that axis
    // This depends on your situation, are the two boxes the same size?
    // Can they change size?
    box1.bounds.extends.y,
    box1.bounds.extends.z,

```

The last part is to rotate the trigger in such a way that it connects the two boxes, I'm not very good with rotations, so I have this lazy way:

```
// Makes the trigger's front axis to look towards the right box
trigger.LookAt(box1r);

// Rotates the trigger 90 degrees on the Y axis, to make it's side point to the box's side (this might be -90 instead, depending on your objects)
trigger.Rotate(Vector3.up *90f);

```

Depending how your objects are placed in your project, you might need to do some adjustments on some numbers. Also the trigger, will not align perfectly. As far as I know, it's impossible to change the shape of the trigger outside of primitive shapes or fixed meshes, so this method assumes the trigger will always remain a cube:

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


# Question
Title: Loop through multidimensional array in C#(Unity)
I have this data

As you can see there's a 2nd board there.

Now what i want is something like this

**PSEUDO CODE**

```
If the first boards table[1,1] is not `NULL` then I will need to find out
now if table[0,1] and table[0,0] has the same length as table[1,1] and
table[1,0]

then display in the 2nd board a blue circle if it is the same in length if
not red circle

But if the table[1,1] is `NULL` then I need to know compare 1st column and
2nd column if they have the same length

then display in the 2nd board a blue circle if it is the same in length if
not red circle

```

# END PSEUDO CODE

I tried doing the following

```
//COLUMN
    for(int col = 0; col < table.GetLength(0); col++)
    {
        int sum = 0;
        //ROW
        for (int row = 0; row < table.GetLength(1); row++)
        {
            if (table[col, row] != null)
            {
                Debug.Log("Column 1 has this value : " + table[col, row]);
            }
        }
        //Debug.Log("table column: " + col + " has " + sum + " data");
    }

```

For now I can only get the whole Row and Column but I don't know how to do that pseudo code.

# Answer
> 0 votes
```
//COLUMN
int prevSum = -1;
for (int col = 0; col < table.GetLength(0); ++col)
{

int sum = CountRow(table, col);
Debug.Log("table column :" + col + " has " + sum + " data");
if (sum == prevSum)
{
   prevSum = sum;
}

//generic function
public static int CountRow<T>(T[,] table, int col)
{
    if (table == null || col < 0 || col >= table.GetLength(1))
    {
        //handle error
        return -1;
    }

    //this is the same as the block of the outer for loop
    int sum = 0;
    for (int row = 0; row < table.GetLength(1); row++)
    {
        if(table[col,row] != null)
        {
            sum++;
        }
    }
    return sum;
}

```

---
Tags: unity, c#, android, unityscript
---


title: Why is the rectangle not moving?

text:
# Question
Title: Why is the rectangle not moving?
```
public class Main {

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Character c = new Character();
        frame.add(c);

        frame.setSize(600, 600);
        frame.setTitle("Keyboard control");
        frame.setResizable(false);
        frame.setVisible(true);
    }
}

character class

public class Character extends JPanel implements KeyListener{

   int posx = 0, posy = 0;

   public void movementX(int i) {
        posx+=i;
    }
   public void movementY(int i) {
       posy+=i;
   }

       public void paint() {
           repaint();
       }

     public void paintComponent(Graphics g) {
        super.paintComponent(g);

        this.setBackground(new Color(0, 0, 0));

        g.setColor(new Color(0, 0, 255));
        g.fillRoundRect(posx, posy, 50, 50, 4, 4);

    }

    public void keyPressed(KeyEvent e) {
        movementX(10);
        paint();
    }

    @Override
    public void keyReleased(KeyEvent e) {

    }

    @Override
    public void keyTyped(KeyEvent e) {

    }
}

```

# Answer
> 1 votes
well, simple you are implementing KeyListener but you are never attaching that to the panel, also you must focus your component to be able to listen for events, here you can have a more explained response:

https://stackoverflow.com/questions/9333876/how-to-simply-implement-a-keylistener?utm\_medium=organic&utm\_source=google\_rich\_qa&utm\_campaign=google\_rich\_qa

---
Tags: java, game-mechanics, input, keyboard, swing
---


# Question
Title: Array of map data renders the map the opposite way
A while ago by following some tutorials I made a game map array consisting of 0, 1 and 2. I program it the way I want to see it:

```
var mapArray = [
  [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 2, 2, 0],
  [0, 0, 1, 1, 1, 0, 0, 2, 0, 0],
  [0, 0, 1, 1, 1, 0, 0, 0, 0, 0],
  [0, 0, 0, 1, 1, 1, 1, 1, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
  [0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 2, 2, 0],
  [0, 0, 1, 1, 1, 0, 0, 2, 0, 0],
  [0, 0, 1, 1, 1, 0, 0, 0, 0, 0],
  [0, 0, 0, 1, 1, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
  [0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
];

```

So for example the line `[0, 0, 0, 1, 1, 1, 1, 1, 0, 0]` lies on the X axis and I want to see grass `1` horizontally, but when I draw it on the canvas it's being rendered vertically instead. So the *y* and *x* axis are being swapped in place. Why is this so? Here is the rendering code:

```
function render(viewport) {
  context.save();
  context.translate(view.x, view.y);
  requestAnimationFrame(render);
  var oldPosX = boatPosX;
  var oldPosY = boatPosY;

  for (let i = 0; i < mapArray.length; i++) {
    for (let j = 0; j < mapArray[i].length; j++) {
      if (mapArray[i][j] == 0) {
        this.sprite.draw(
          background,
          190,
          230,
          26,
          26,
          i * this.sprite.width,
          j * this.sprite.height,
          this.sprite.width,
          this.sprite.height
        );
      }
      if (mapArray[i][j] == 1) {
        this.sprite.draw(
          background,
          30,
          30,
          26,
          26,
          i * this.sprite.width,
          j * this.sprite.height,
          this.sprite.width,
          this.sprite.height
        );

      }
      if (mapArray[i][j] == 2) {
        this.sprite.draw(
          background,
          200,
          20,
          26,
          26,
          i * this.sprite.width,
          j * this.sprite.height,
          this.sprite.width,
          this.sprite.height
        );
      }
    }
  }
  this.ship.drawimage(boat, boatPosX, boatPosY, 50, 50);
  var lineHeight = 16 * 2.286;
  var textWidth = context.measureText(theArray[moveCount].question).width * 3;
  context.textAlign = 'left';
  context.textBaseline = 'top';
  context.font="14px Verdana";
  context.fillStyle = 'rgba(0, 0, 0 ,0.9)';
  context.fillRect(boatPosX + ship.width / 2, boatPosY - ship.height / 2, textWidth, lineHeight);
  context.fillStyle = 'white';
  context.fillText(theArray[moveCount].question, boatPosX + ship.width / 2, boatPosY - ship.height / 2);

  answerBtn1.innerHTML = theArray[moveCount].answer1;
  answerBtn2.innerHTML = theArray[moveCount].answer2;
  if(isPositionWall(boatPosX, boatPosY)) {
    boatPosX = oldPosY;
    console.log("collision");
  }

  context.restore();

};

```

# Answer
> 1 votes
You are using the index `i` to read horizontal values and `j` for vertical values, but the way you stored values is reversed. If you had a 2D array (a matrix) it'd work, however you defined an array whose elements are arrays themselves.

When you read `mapArray[0]` you get the array `[0, 0, 0, 0, 1, 0, 0, 0, 0, 0]` which is the first row of world tiles. Then, `mapArray[1]` will return the second row, and so on. So, `mapArray[i]` returns the *i*-th row of your tilemap, and it means you're using the index `i` to navigate through columns, not rows; though you're using the variable `i` the other way round. Same applies for variable `j`.

To quick fix it, just change the way you read `mapArray`: to access the element in *i*-th row, *j*-th column, you need to write `mapArray[j][i]`.

### Edit #1

The quick fix is not ideal, since `i` and `j` aren't used to navigate the tilemap only but also to proper render sprites.

Then, you only need to reverse usage of `i` and `j` in loops, where they are used as coordinates of the map array. The new nested loop will look like this:

```
for (let j = 0; j < mapArray.length; j++) {
    for (let i = 0; i < mapArray[j].length; i++) {
        // draw
    }
}

```

You may also use separate variables to store `arrayMap` sizes, and the code will look even more clear:

```
var W;
var H = mapArray.length;

for (let j = 0; j < H; j++) {
    W = mapArray[j].length;
    for (let i = 0; i < W; i++) {
        // draw
    }
}

```

---
Tags: javascript, tilemap, html-canvas
---


# Question
Title: Things to keep in mind after upgrading from .NET 3.5 to .NET 4.6 on Unity3D
I have recently updated my forked project from .NET 3.5 to .NET 4.6, and for some reason (even though Unity3D advises that there isn't any problem) my project doesn't load things correctly:

> By default nothing should change about how Unity behaves or what .NET functionality is available.

Nothing should change, but now ground doesn't load in some parts of the same.

I have inspecting code, and well, I found that some functions aren't behaving as expected. (I didn't debugged them succesfully because if use Debug class, Unity stucks, and if use breakpoints I never find something relevant).

I have realized that some objects are disabled once they are loaded.

For example roads aren't loaded.

We select a object to know where it's located.

And here it is.

As we can see it's disabled. (I couldn't find any object under the player)

### Trying to understand what's happening

This fact notices me that something is setting Gameobject field `enabled` to `false` or `SetActive(false)`.

So, I searched in all the project and I found this:

The most probable case is the one from StaticGeometry:

https://github.com/z3nth10n/SanAndreasUnity/blob/40b95f56feb021aac13364d055424283b695d1bb/Assets/Scripts/Behaviours/World/StaticGeometry.cs#L65

In this case, the object is disabled once it's loaded (as I can see).

https://github.com/z3nth10n/SanAndreasUnity/blob/40b95f56feb021aac13364d055424283b695d1bb/Assets/Scripts/Behaviours/World/StaticGeometry.cs#L178

In this case if the object isn't visible it doesn't display.

And as you can see in line 31, if \_isVisible is the same value as `value` then we exit, so, keeping in mind that \_isVisible is `false` from the beginning we can say, that somewhere the IsVisible variable is being setted as `false`, and that happens on line 186 (`Hide()` method), that is called on:

This method is called in:

https://github.com/z3nth10n/SanAndreasUnity/blob/40b95f56feb021aac13364d055424283b695d1bb/Assets/Scripts/Behaviours/World/StaticGeometry.cs#L109

... if `ShouldBeVisible()` returns false.

https://github.com/z3nth10n/SanAndreasUnity/blob/40b95f56feb021aac13364d055424283b695d1bb/Assets/Scripts/Behaviours/World/StaticGeometry.cs#L70

In line 72, line 83, line 86, line 94.

... or in the same `IsVisible` property.

https://github.com/z3nth10n/SanAndreasUnity/blob/40b95f56feb021aac13364d055424283b695d1bb/Assets/Scripts/Behaviours/World/StaticGeometry.cs#L40

if the value that is being setted is true and LodChild is not null then we have to hide LodChild, why? I can't continue here, because I don't understand this logic.

### My assumptions on what's going on

Returning back to the road photo:

If we look in it's localPosition it looks weird.

But this is more weird:

Splits (that are baically chunks) are loaded so far away. (That's more weird, there is an unit problem as I can see).

But weirdest things are happening, for example, roads under other positions load correctly.

---

Other issue for example is that cars doesn't spawn, I think that is because there isn't any ground, when there is ground they spawn, but they pass through it, so the ground doesn't load or if it loads it's not solid where the player stands (maybe because of `ShouldBeVisible()` issue?)

If we spawn a vehicle using `V` key, they spawn, but it's wheels are very big.

If we watch its scale is about 10, if we set it to 1 then we recover the normal shape.

(I don't have photo of scale = 1, but I have already test it)

So, I said my assumptions is that something is returning bad numbers, they are multiplied.

I have looked into float.Parse, and yes, I found something, but I can't debug it due to big amount of data.

And there is the value... So, a possible problem is that because of my Culture, .NET is parsing this value as millions instead of thousands. And in .NET 3.5 this feature isn't available. I will search how to fix it.

Another fact is sustains my assumption is this:

As you can see position number on the X axis is very big.

So, I will ty to search it on the GTA SA files.

---

I have checked for empty `catch` statments, but I found nothing.

The project is being builded correctly. And If you return the version back to 3.5, everything works again well.

So, what can be happening here? I need to know if I have to keep in mind some fact after upgrading, also, I have searched in:

https://unity3d.com/es/search?refinement=issues&gq=.net%204.x

But didn't find anything.

# Answer
> 0 votes
Well, as it's not documented, I want to contribute with my own discoverties.

The first thing I realized is that when you convert to a string a float `float.ToString`, the output is the following -\> `1,4050` for `1.4050f`...

That fact said me that `float.Parse` has to work on a similar way: http://rextester.com/RPFNFS6685

This is causes because I'm spanish and my system CultureInfo is ES-ES, so if we force it to EN-US, the problem is solved. (This feature seemsn that isn't available on .NET 3.5)

```
    private static CultureInfo _enUs;

    private static CultureInfo enUs
    {
        get
        {
            if (_enUs == null) _enUs = new CultureInfo("en-US");
            return _enUs;
        }
    }

public float GetSingle(int index)
{
    return float.Parse(_parts[index], enUS);
}

```

**Test:** http://rextester.com/ENU16738

Now it works correctly.

**PD:** I will keep this updated as I find more issues.

---
Tags: unity, .net
---


title: What is morph target animation?

text:
# Question
Title: What is morph target animation?
I've been using Adobe Flash and its keyframe-based animation for some years. I recently about heard morph-targets animation from Wikipedia.

It seems that the morph target animation is also keyframe-based. What are the differences between Flash's animation and morph target animation?

# Answer
In short, they are actually very similar and just differ by 2D vs. 3D.

Flash's animation uses keyframes, and blends control points between those keyframes.

Morph target animation also uses keyframes, and blends the vertices between those frames.

The primary difference is the data involved. Flash is working with 2D vector graphics, so there are points, edges, line sizes, colors, etc. Whereas in the case of morph targets, it's just the position of the vertices.
> 1 votes

---
Tags: animation, terminology
---


# Question
Title: 3D infinite platform generation: Can't increase space between platforms. (Unity)
As seen in the images, changing the value of 'spawnZ' affects the distance between the initial platform and the first generated platform but afterwards it has no affect whatsoever.

```
public GameObject[] tilePrefabs;

public float spawnZ = 10f;
public float tilelength;
public int amnTilesOnScreen = 5;
public Transform playerTransform;

// Use this for initialization
void Start () {
    for (int i = 0; i<amnTilesOnScreen; i++)
    {
        SpawnTile();
    }
}

// Update is called once per frame
void Update () {
if(playerTransform.position.z>(spawnZ - amnTilesOnScreen * tilelength))
    {
        SpawnTile();
    }
}

private void SpawnTile(int prefabIndex = -1) {
    GameObject go;
    go = Instantiate(tilePrefabs[0]) as GameObject;
    go.transform.SetParent(transform);
    go.transform.position = Vector3.forward * spawnZ;
    spawnZ += tilelength;

}

```

# Answer
Try changing the last line of `SpawnTile()` to this:

```
spawnZ += tilelength + desiredGapDistance;

```
> 0 votes

---
Tags: unity, 3d
---


# Question
Title: How to get character position in 2D map array by its position on canvas
My arrayMap consists of 0, 1 and 2. 0 is water and character is allowed to be on. 1 and 2 are ground and the collision should happen.

To get and check what array number the character is standing on, I take the character position and divide it by my tileset size which is 36px and use Math.floor to round the number. I place it like this: `console.log(mapArray[Math.floor(boatPosX / 36)][Math.floor(boatPosX / 36)]);` and I know if its `0`, `1` or `2` he is standing on. Which is great so far. But my collision still doesn't work the way it should. Actually it acts so weird I don't even know how to fix it properly. If I put some `1` in my player start position, I get collision, but if I place it at `0` in array and move onto `1` myself, it doesn't work.

So it's giving me different results every time. I feel like I'm almost here but some stupid bug is ruining it all.

```
var mapArray = [
  [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
  [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
  [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
  [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0],
  [0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
];
function isPositionWall(ptX, ptY) {
  var gridX = Math.floor(ptX / 36);
  var gridY = Math.floor(ptY / 36);
  if(mapArray[gridX][gridY] == 1)
    return true;
}

var boatPosX = canvas.height/2 - 50;
var boatPosY = canvas.height/2 - 50;

function render(viewport) {
  context.save();
  context.translate(view.x, view.y);
  requestAnimationFrame(render);
  var oldPosX = boatPosX;
  var oldPosY = boatPosY;

  for (let i = 0; i < mapArray.length; i++) {
    for (let j = 0; j < mapArray[i].length; j++) {
      if (mapArray[j][i] == 0) {
        this.sprite.draw(
          background,
          190,
          230,
          26,
          26,
          i * this.sprite.width,
          j * this.sprite.height,
          this.sprite.width,
          this.sprite.height
        );
      }
      if (mapArray[j][i] == 1) {
        this.sprite.draw(
          background,
          30,
          30,
          26,
          26,
          i * this.sprite.width,
          j * this.sprite.height,
          this.sprite.width,
          this.sprite.height
        );

      }
      if (mapArray[j][i] == 2) {
        this.sprite.draw(
          background,
          200,
          20,
          26,
          26,
          i * this.sprite.width,
          j * this.sprite.height,
          this.sprite.width,
          this.sprite.height
        );
      }
    }
  }
  this.ship.drawimage(boat, boatPosX, boatPosY, 50, 50);

  if(isPositionWall(boatPosX, boatPosY)) {
    //boatPosX = oldPosY;
    console.log("collision");
  }
  console.log(mapArray[Math.floor(boatPosX / 36)][Math.floor(boatPosX / 36)]);
  context.restore();

};

function move(e) {
  if (e.keyCode == 39) {
    boatPosX += 5;
    view.x -= 5
    moveCount++;
    console.log(moveCount);
    console.log("right");
  }

```

That's parts of the code that are related to the question. If you need need more code, let me know. I'm looking for some directions what I'm doing wrong. Thanks.

Codepen: https://codepen.io/Limpuls/pen/deEGXX

# Answer
**EDIT:** Oh dear, how didn't I spot this earlier. All the stuff in my original answer still applies, but the issue you're having is being caused by a simple array indexing mixup. Rows (which function as Y values in this case) are accessed before columns (X values)!

If you change

```
if(mapArray[gridX][gridY] == 1)
    return true;

```

to

```
if(mapArray[gridY][gridX] == 1)
    return true;

```

it will work. Working codepen example: https://codepen.io/anon/pen/XqwNMp?editors=0010

Welcome to the joys of programming!

**Original answer:**

From a quick glance, your code looks ok. Your collision detection *may* be the issue - it only checks if a single point on the boat (the top left corner, I'd guess?) is intersecting with tiles, rather than the entire boat itself. That is to say, collisions will currently only be registered when the top left corner of the boat sprite hits another tile, rather than the whole boat.

If you'll forgive the crude MS Paint:

1 shows the boat beside a tile. The point you're using to check for collisions is marked in red (top left).

2 shows the boat intersecting the tile. A collision **should** be reported here, but isn't, because the red point isn't inside the other square.

3 is a case where a collision is reported.

Like I said, this *might* be the problem, but it's hard to tell from the code given.

If it is the issue, then the fix is relatively simple. If the user is moving the boat right, then check if both right-hand corners (top ***and*** bottom) are intersecting tiles to the right, and check what sort of tiles they are. If one of them is a collider, then you know what to do - set the boat pos to the old pos, just like you have commented out!

Same for moving left, up, and down.
> 1 votes

---
Tags: collision-detection, javascript, html-canvas
---


title: Grainy texture from distance

text:
# Question
Title: Grainy texture from distance
I am using SharpDX, a C# wrapper over DirectX 11 to render terrain. While I am able to render terrain correctly, I noticed that moving around creates a lot of visual noise and makes the texture of the ground very grainy. I have attached a picture of how the texture looks on the terrain. (Make sure to make full screen for clarity)

Here is the dirt texture I am using:

Here is the dirt texture normal map:

I thought I set up the mip maps appropriately in this code (note that filename is just the path to the terrain bitmap I showed above):

```
public bool Initialize(SharpDX.Direct3D11.Device device, string fileName)
{
  try
  {
    using (var texture = LoadFromFile(device, new SharpDX.WIC.ImagingFactory(), fileName))
    {
      ShaderResourceViewDescription srvDesc = new ShaderResourceViewDescription()
      {
        Format = texture.Description.Format,
        Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D,
      };
      srvDesc.Texture2D.MostDetailedMip = 0;
      srvDesc.Texture2D.MipLevels = -1;

      TextureResource = new ShaderResourceView(device, texture, srvDesc);
      device.ImmediateContext.GenerateMips(TextureResource);
    }
    // TextureResource = ShaderResourceView.FromFile(device, fileName);
    return true;
  }
  catch
  {
    return false;
  }
}

public Texture2D LoadFromFile(SharpDX.Direct3D11.Device device, ImagingFactory factory, string fileName)
{
  using (var bs = LoadBitmap(factory, fileName))
    return CreateTexture2DFromBitmapSource(device, bs);
}

public BitmapSource LoadBitmap(ImagingFactory factory, string filename)
{
  var bitmapDecoder = new SharpDX.WIC.BitmapDecoder(
      factory,
      filename,
      SharpDX.WIC.DecodeOptions.CacheOnDemand
      );

  var result = new SharpDX.WIC.FormatConverter(factory);

  result.Initialize(
      bitmapDecoder.GetFrame(0),
      SharpDX.WIC.PixelFormat.Format32bppPRGBA,
      SharpDX.WIC.BitmapDitherType.None,
      null,
      0.0,
      SharpDX.WIC.BitmapPaletteType.Custom);

  return result;
}

 public Texture2D CreateTexture2DFromBitmapSource(SharpDX.Direct3D11.Device device, BitmapSource bitmapSource)
{
  // Allocate DataStream to receive the WIC image pixels
  int stride = bitmapSource.Size.Width * 4;
  using (var buffer = new SharpDX.DataStream(bitmapSource.Size.Height * stride, true, true))
  {
    // Copy the content of the WIC to the buffer
    bitmapSource.CopyPixels(stride, buffer);
    return new SharpDX.Direct3D11.Texture2D(device, new SharpDX.Direct3D11.Texture2DDescription()
    {
      Width = bitmapSource.Size.Width,
      Height = bitmapSource.Size.Height,
      ArraySize = 1,
      BindFlags = SharpDX.Direct3D11.BindFlags.ShaderResource | BindFlags.RenderTarget,
      Usage = SharpDX.Direct3D11.ResourceUsage.Default,
      CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None,
      Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
      MipLevels = 1,
      OptionFlags = ResourceOptionFlags.GenerateMipMaps, // ResourceOptionFlags.GenerateMipMap
      SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
    }, new SharpDX.DataRectangle(buffer.DataPointer, stride));
  }
}

```

Here is my samplerstate code:

```
SamplerStateDescription samplerDesc = new SamplerStateDescription()
            {
                Filter = Filter.MinMagMipLinear,
                AddressU = TextureAddressMode.Clamp,
                AddressV = TextureAddressMode.Clamp,
                AddressW = TextureAddressMode.Clamp,
                MipLodBias = 0,
                MaximumAnisotropy = 1,
                ComparisonFunction = Comparison.Always,
                BorderColor = new Color4(0, 0, 0, 0),  // Black Border.
                MinimumLod = 0,
                MaximumLod = float.MaxValue
            };
            SamplerState = new SamplerState(device, samplerDesc);

```

Is there anything wrong here?

# Answer
> 0 votes
This function will load in your texture in, but you need to set your Mipmap level on your texture description to 0. Sample description I use is:

```
              case TextureDescriptions.MIPMAPPED:
                desc.ArraySize = 1;
                desc.Usage = D3D11.ResourceUsage.Default;
                desc.CpuAccessFlags = D3D11.CpuAccessFlags.None;
                desc.Format = DXGI.Format.R8G8B8A8_UNorm;
                desc.MipLevels = 0;
                desc.OptionFlags = D3D11.ResourceOptionFlags.GenerateMipMaps;
                desc.SampleDescription.Count = 1;
                desc.SampleDescription.Quality = 0;
                desc.BindFlags = D3D11.BindFlags.RenderTarget | D3D11.BindFlags.ShaderResource;
                break;

```

Use this function to load your buitmap into a texture2D.

```
    public static D3D11.Texture2D1 CreateTex2DFromBitmap(SharpDX.WIC.BitmapSource bsource, D3D11.Device3 a_device, D3D11.DeviceContext3 a_context, D3D11.Texture2DDescription1 a_desc)
    {
        D3D11.Texture2D1 t2d = null;

        try
        {
            int stride = bsource.Size.Width * 4;
            var buffer = new DataStream(bsource.Size.Height * stride, true, true);

            if (a_desc.MipLevels != 0)
            {
                // if we arent doing mip maps, then load the resource directly
                DataRectangle rect = new DataRectangle(buffer.DataPointer, stride);
                bsource.CopyPixels(stride, buffer);
                t2d = new D3D11.Texture2D1(a_device, a_desc, rect); /// this creates a texture and populates it, we need to create a blank one then populate it.
            }
            else
            {
                t2d = new D3D11.Texture2D1(a_device, a_desc); /// this creates a texture and populates it, we need to create a blank one then populate it.
                bsource.CopyPixels(stride, buffer);
                DataBox box = new DataBox(buffer.DataPointer, stride, 1);

                a_context.UpdateSubresource(box, t2d, D3D11.Resource.CalculateSubResourceIndex(0, 0, CountMips(bsource.Size.Width, bsource.Size.Height)));
            }
            buffer.Dispose();

        }
        catch (Exception ex)
        {
            ErrorHandler.DoErrorHandling(ex, ErrorHandler.GetCurrentMethod(ex), Environment.StackTrace);

        }
        return t2d;
    }

```

then finally, to create the mip map levels.

```
                    D3D11.ShaderResourceViewDescription1 srvDesc = new D3D11.ShaderResourceViewDescription1()
                {
                    Format = m_texture2D.Description.Format,
                    Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D
                };
                srvDesc.Texture2D.MostDetailedMip = 0;
                srvDesc.Texture2D.MipLevels = -1;

                srv = new D3D11.ShaderResourceView1(a_device, m_texture2D, srvDesc);
                a_context.GenerateMips(srv);

```

---
Tags: textures, directx, sharpdx
---