# Question
Title: Level playing field: Punish the better player or enhance the worse player?
I am making a 1 vs 1 game where each player controls a car with an identical joystick. The objective for the players is to reach a goal destination before the other player.

The players of the game are placed into categories based of the skills controlling the car e.g. Skill level\[1,2,3,4,5\] with 5 being the highest skill level.

The players will not be intended to jump up and down in skill levels when playing the game. After a given period, e.g. a week, the skill levels will be updated. This will not be shown to the players.

The objective for me is to make every combination of players in the 1 vs 1 setting be a 50/50 win loss chance for the players.

Example: Player 1(Skill level 5) vs player 2(Skill level 1) should each have 50% change reaching the goal destination first.

I have not been able to find any research on whether the best practice is to limit the abilities of the good player or enhance the abilities of the bad player or maybe a combination.

The idea is to have disabled adolescents playing against their able bodied friends or family members. It is therefore not a possibility to not let good players play against bad ones. Data from field tests have shown that the disabled adolescents perform worse than able bodied consistently due to spasms.

I am looking for input on how to go about with this; research, your experiences, how other games are doing it? Is there any common recommendations for this?

# Answer
> 69 votes
## Match making

If you can keep updated skill metrics on the players, then you are able to create a system that can peer people of similar skill.

Granted, this could lead to starvation (and by that I mean players unable to play because there is no match availed) and will not fly on couch gaming.

*I believe this will not solve your particular case, so I will not elaborate any futher.*

## Handicaps

I would complain on any handicap system based on the skill of the players. *I believe Bálint expressed the issue better than I could*. With that said, handicaps in either direction are viable if they are on player volition.

That is, if the players go to a menu where they select what handicap they want and they are all conscious of that choice, then it can work. This is in particular useful in couch gaming with family or friends, because they would know each other and – given the motivation※ – they will find some setting that makes the game fun for everybody.

※: That is, if what they want is to win instead of have a good play session, then it will go wrong.

As I said, handicaps - as long as placed by player own volition - will work in both directions. That is, either making things harder for the "good" player, or making them easier for the "bad" player. However, I would side on making things easier for the "bad" player because...

## Catch up mechanics

You can give boosts to the player that is behind (regardless of skill score) in order to help that player get back to the front of the race. After all, it is when players are nearby in the racetrack that the game play is more interesting.

A traditional example will be Mario Kart. In the game, players that are behind will receive better power ups which will allow them to catch up to the players that are at the front.

You might be interested in the concept of rubber banding. Which is how we call the idea of adapting events to fit player performance. Read more about The approaches to Dynamic game difficulty balancing at Wikipedia.

## Address the issue

> They all have cerebral palsy and is therefore heavily affected by their spasms when using the joystick

Perhaps the solution is simply to smooth the input. You can:

* If the joystick moves too abruptly, ignore that.
* Let the joystick input be a target angle, but limit the angular velocity at which the direction can change.
* *Modern cars in real life already adjust the sensitivity of the input as a function of the current speed of the car, you can do that too.*

## Asymmetric gaming

*Mario Chase from Nintendo Land is an excellent example of asymmetric gaming.*

I would also start with the handicap approach. However not by giving some advantage or disadvantage to players, but by offering a different input mechanic※, and make it optional.

※: That does not imply to create or use a different input device - however, I admit that would be useful, I also recognize that might not be possible. When I say input mechanic I mean the way the game interprets user input.

For a first person shooter, consider the effects of auto aiming... it allows a player that has struggle with fine motion to enjoy the game. However, it does not offer means to improve the motor skill. Instead, I would suggest the following:

1. The player aims in the general direction they want
2. Then the game changes to an aiming mode where they can fine-tune the direction. The aiming mode may help the player by having:
    * Zoom
    * Less sensitivity
    * Snapping to important targets
3. The player shoots (or aborts out of the aim mode).

I suggest doing something like that for your car game. Let the person choose the general direction and then fine tune and apply the change. This means that for a turn, they will change mode ahead of time in the general direction of the turn, and then when they reach the curve they fine tune and apply. *In fact, you could let the game gradually apply the turn as appropriate, after all, the result of applying the turn should not be to put the car into a circular path.*

*I have a vague memory of hearing of a game that had such mode, I have been unable to find it.*

The good thing of this approach is that it is a difference in kind, *however I admit this is just a rought sketch and I cannot guarantee it will work*. If you take this idea, or any other similar one, you will have to take feedback from your players and iterate over it.

---

*Did you consider making a different kind of game instead of a racing game? I think your objective is help these people, perhaps a different kind of game will lend itself easier to the kind of balance mechanics you need. May I suggest a “shoot’em up”? - I strongly belive that a cooperative game will suit you better.*

---

## Addendum

You may also be interested in Incomparables, Perfect Imbalance, Co-pilot mode, Assit Mode and The Curb Cut Effect.

# Answer
> 53 votes
Neither is good. Why would you try getting better if all it does is give the opponent bonuses or makes you worse? You might as well just make a casino game if only the chances decide who wins.

It also makes good players less likely to improve. If they steamroll their opponents without even trying, then they don't get any sort of feedback.

Don't let bad players play against good ones. Create some sort of automatic ranking system, where good players play against other good players.

# Answer
> 19 votes
Your specific scenario is to allow fun competitive play between one or more players with cerebral palsy and other players without that condition. You mention that the main disadvantage is that of tremors, which effect the player by reducing the effectiveness of steering.

Perhaps you could implement a *game mechanic* which simulates tremors/loss of control for players, and which typically effects steady-handed players more than non-steady players in a believable way. Example: would the enemies from Borderlands like it much if everyone in a race were driving in a non-chaotic fashion? Perhaps they would try to "encourage" racers to be a little more interesting in their driving. The goal would be to take something that might be considered a disadvantage and turn it in to part of the game play. A challenge, rather than a hinderance. I honestly don't know how viable this strategy is - I'm just throwing the idea out there.

Another idea is to process the input of each player and come up with a "steady-hand profile". The least-steady profile in a given match could be used to automatically introduce simulated tremors in to the input of other players. This would create a direct correlation in disadvantages. It would also be a very intriguing experiment in machine learning.

# Answer
> 6 votes
When developing AI for arcade-style racing games, it is a common design principle to focus on the AI, giving a disadvantage (speed reduction) to a leading AI and an advantage (acceleration increase) to a trailing AI, thus keeping all players (although it would be 1 human player and multiple AI players) in close positions. When the AI is slightly ahead of the player the AI's disadvantage is then removed so that the player still has to try to win (and gets the emotional reward of achieving a win).

The difference is only relative, so whether the leading AI is given the disadvantage or the trailing player is given the advantage, there is not much difference to the competitive experience. The important thing is balancing it so that skill is still required. The point of the handcap/bonus should be to narrow the skill difference, not eliminate it, then the game will still be fun and it will be a close game that either player can win depending on how the race goes.

So as for whether to give a skill reduction to the more-skilled player or a bonus to the less-skilled player, I suggest making it a factor of the game itself, not of the player's historical wins/losses.

What happens after you balance the skills and your better players are losing half of their games to your worse players, will their skill rating be lowered while the less-skilled player's skill increases? If a 1/5 player keeps playing a a 5/5 player and the score is 50/50, will both players' skill ratings be adjusted to 3/5? Then they won't have the advantage again, right?

Are the skills dynamic, based on historical wins and losses, or will they be set before playing the first game and never change?

If you do it correctly you might find a balance, but I suggest making it a mechanic of the game that leading players are slightly penalized and trailing players get some speed boosts that they can activate. You can do this in a way that is not obvious to the players, such as building up a trailing player's boost bar more quickly, so they will be able to boost more often, etc, while the leading player's handling, acceleration curve, and top speed, may be slightly decreased, then as the players get closer together during a race the differences become less.

This way of keeping races tight is good in general, not only in your situation. There are people of many skills, or someone might just get unlucky and crash early, and it's always fun to have a close race.

Aside from these balancing issues, design your game so that it tends toward close races. For example, will a player be severely punished for running over the boundary with a 15s wait time for a helicopter to come and pick their car up and put it back on the track? Or will they just bump off the side and receive only a small speed reduction for their mistake?

# Answer
> 6 votes
If the question is only about bonus or malus, bonus is the way to go, as outlined by FFN in a comment:

> Since your system is hidden from the player, this probably won't be relevant, but it is a consensus in the roleplaying world (where bonuses and penalties are visible to everyone) that giving bonuses is by far the superior alternative. If you hinder a good player, he feels cheated because you are punishing him for being good, while he did nothing wrong. If you help a struggling player, instead, you are both empowering him (which feels good) and making the playing field level. Now the worse player has a chance to win and feel good and if the better player wins, victory is sweeter. – FFN

Ideally that bonus isn't just a change of the car's stats, but something more controllable, like a faster cooldown on user activatable special abilities. It can be hard for the user to get used to the behavior of a car if the car's speed and acceleration change every week, so that's something to avoid.

My advice is to think beyond bonus and malus. There are some alternatives.

* In racing games, poor players tend to perform less bad if all players are given slower cars, primarily due to less frequent fatal crashes.
* Features like auto brake (reduce speed to less than "suicide" before a turn), or auto/manual gear can and will affect proficient and novice players differently.
* Some racing games feature a built-in drawback for the car in the lead, such as a user launched homing missile or lightning strike that seeks out the car in first place (IIRC Mario Kart, and Blur), or the ability to summon doom on the track ahead (Split Second).
* NPC cars crossing intersections are a great way to hide preferential treatment of players.
* Some racing/fight games have a large yet non-obvious element of chance involved, which allows weaker players to win occasionally. I'm thinking of the original Carmageddon where the first place car getting wrecked in the first turn by the cars in the back was a rather frequent occurrence.
* Alternate game modes like the ones in Flatout also allow weaker players a chance to score

# Answer
> 4 votes
Bálint gives an excellent answer, and I'd like to add *why* I think so.

You'll find that in many games, such *quantitative* changes as you suggest are an extremely poor substitute for the *qualitative* difference in play style, especially as a broad/sweeping/unreasoned approach that you suggest, and to the degree that you suggest. It tends to either overkill good players who are being unfairly limited in crucial aspects of play, or not do enough to solve that which makes them highly effective at play. This sort of catch all handicap system has been tried since the early 1980s at least and it has very rarely if ever been shown to be a useful approach. If applied very selectively in limited areas of the game mechanics, for example multiplying a noob FPS player's health by double or triple compared to a moderately better player, it may be useful.

Balancing this brute-force balancing attempts to work across all the differences in human skillsets is nigh-impossible. So again as suggested by Bálint, match players against others by proven skill.

**Possible solution**

In order carefully limit where you apply bonuses / penalties as suggested...

I can suggest a sort of intelligent approach to evaluating playstyles, and bolstering key values accordingly. For example, if it is found that a player reacts to the need to turn, too slowly, try to give them some sort of a preemptive hint that they need to start turning, which others don't get.

In Doom, a similar system was used to overcome the limitation of not being able to look up or down - if there was an enemy up or down from the current crosshair position, the game would auto-aim up or down, making the game easier to play as no-one had to worry about vertical control (this was especially important given it was originally written to be controlled with keyboard only).

This will probably require architecting things in a way that accommodates this data gathering on weak points in each player's skillset.

# Answer
> 4 votes
Odds makers have faced this problem since the beginning of team on team sports, and they devised a simple solution:

# Beat the spread

Due to the difference between the two skill levels, the goal is not to reach the end first, or the score the most points. It's to have a spread larger than the system says you need to win by. In games with a scoring system this is simple - you need to beat your opponent by X points to "win the match." Your matchmaking rating will go up by 0 points if you get exactly X points more, and go down if you get less than X points.

In a racing game, you would have to beat the opponent by a certain time. You could do this by giving the weak player a head start, but that's going to sound like a penalty (although it will make a more exciting finish because in theory they arrive at the finish at the same time.) You also could start them at the same time expecting the strong player to finish first. The weak player then has to make sure he finishes before his spread runs out.

In a deathmatch, this is going to be difficult. You could say you need to win with X amount of health remaining. Much like racing, this is similar to starting with a handicap.

At the end of the day, there's no way around the fact that you're trying to make a fair fight from an unfair fight. I play chess and beat a guy on Chess With Friends 5 times in a row. He challenged me again. I beat him without moving my queen or rooks at all in the whole game. Short of me getting super drunk and playing him, or him studying his keester off, this fellow will never beat me at chess. Only by imposing some artificial limit (maybe next time I only get 1 bishop and 2 knights... probably would still beat him really... whatever) are we going to be able to make this fair.

# Answer
> 4 votes
# Reframe the problem

In most 1v1 games like you describe, the goal is to reach a finish line first or otherwise do something the best. If you do the thing better than the other person, you win. That kind of competition is a tried and true approach. If you are trying to adjust it so that everybody wins 50% of the time, it requires a different mindset. If the competition is between me and another person, and no matter how hard I try, I always win *precisely* 50% of the time, and no matter how much I sandbag, I still win 50% of the time, I'm going to get bored.

The game needs to be rephrased as more of a battle with myself. I can always get better. I can always improve. If I happen to be improving alongside my disabled friend playing the same game, so much the better! I need to still keep the goal of "winning," to keep the emotional attachment to the game, but I need to decouple that from the deeper game.

My approach would be to to start with a simple racing game, where the first to the finish line wins. Then, over time, try to encourage the players to engage in activities that pit themselves less against eachother and more against themselves and the environment. Maybe add some mini-goals like trying to do a perfect 720 roll off every jump in the game, which is only given to people when that would be a good test of skill. Perhaps for those of lower skill, you might give them a goal for just a 360. Never give both players the same test on any given race. Maybe one player has to do precise 720s, while the other gets credit for drifting around the corners as much as possible. That makes the final race-time less comparable, because both players are doing slightly different things through the entire race.

If you can convince them to start thinking that way, then you can start playing pareto-optimality games. Offer "upgrades" to your vehicles which make them more suitable for the minigames, but which might negatively or positively affect race times. Maybe there's an upgraded differential that's better for drifting, but happens to decrease acceleration or something equally crazy.

The remaining key is to listen to the players. Get a sense of how much they are "digging" the minigames. If they're really down with them, you can 100% balance the final winner algorithmically without decreasing player happiness, because they aren't focused on the winner of the race. If they aren't doing any of the minigames, and just racing pedal-to-the-metal, then you aren't going to be able to optimize like this without a player noticing and refusing to play. In such a case, you will need to entice them to play the minigames. Pick minigames which don't affect the final race as much, and offer those instead. Offer slight bonuses which make your race-time shorter *if* you do the minigames properly (like speed boosts or whatnot) to get them interested in the games. Once you figure out that they're having fun with the minigames, you can try to decouple them from "winning the race" again by offering more interesting games of skill.

# Answer
> 3 votes
What you're asking for isn't possible, and is going to end badly.

The big problem is hidden, long-term-stateful leveling effects. These are going to be testable and thus noticeable by players. For example, if players accidentally or purposefully switch controllers without logging in/out of their profiles, they're going to immediately notice. See Ryanfae Scotland's comment:

> Please don't make this secret advantage completely hidden from players. I can see what you are doing and why you are doing it, and your heart is in the right place, but can you imagine how soul destroying it would be if someone finally found a game they were really good at, could beat their non-disabled and (in their eyes) more talented brother at only to then find out the game had been giving them an unfair advantage because they were actually so bad at it? I reckon it would be **heartbreaking** to find out.

Instead, if you want to do something like this and make it work, follow the "Mario Kart approach". Don't secretly record and respond to long-term play habits and results, but instead offer immediate, visible risk for being in the lead and immediate, visible advantages for being behind. In your case where disability might seriously impair one player's ability to control the game effectively, you probably want to make the effects more pronounced than in Mario Kart. But be careful not to make them too "gameable", and **whatever you do, don't try to detect spasms or other input that you think might reveal who the disabled player is**. Unless the able-bodied player is known to be friendly and empathetic, you must assume there will be malicious players who will mimic/mock your disabled players' play style to get advantage, and that's going to me the whole thing an extremely not-fun experience.

# Answer
> 2 votes
Based on the way I read the post, the game's purpose (first and foremost) is to make it fun for both parties playing. I propose an additional goal of helping a less challenged player to feel some of the difficulties a more challenged player would experience.

**Handicap/Enhance based on the other player's capability.**

Assuming you can determine the line for a "perfect" run, you can determine how much a player deviates from this perfection. We will call this "drift". You then adjust the controls to mimic the drift that your opponent would typically have through the race.

How you record this drift will be specific to your game design. One method is to look at key points (curves, narrow roadways, obstacles) and find how much far player is off from the perfect line. Another method is to record average deviation throughout the run and find an end average.

Say, based on the average of the past 5 games, PlayerOne is typically off by 30 points/pixels/feet/(whatever measure) and PlayerTwo is typically off by 10 points/pixels/feet. In a head to head game, PlayerOne will experience a "pull" toward the perfect line and PlayerTwo will experience a "push" away from the perfect line. The amount and exact methodology of this push is specific to the game.

You mention specifically that there are times where a more challenged player may have sudden jerking motions. These over-reactions can also be recorded and an adjustment made on both sides. If a PlayerOne averages (say) 3 of these sudden deviations further away from perfect in a typical run, that can be recorded. When doing the next run, the game can look at a sudden deviation away from perfect and (for a time) ignore (or minimize) that type of input, drawing the person back toward the perfect line for up to (that average) 3 times. Additionally, PlayerTwo can have sudden deviations pushing him away from the perfect line to mimic the challenge that PlayerOne would experience. An in-game explanation would be "a sudden gust of wind" (perhaps even add the sound effect?)

Adjusting the "push" and "pull" through user testing is important to balance the game and not make it overly frustrating for either type of player.

Also realize that if there are two players with the same average deviation, the calculation causes there to be no correction to either one. This still keeps the playing field level automatically.

# Answer
> 1 votes
# Different Classes

Your game is symmetrically balanced, which leads to the better player winning. A solution is to create classes of different cars. Have classes that don't take a lot of skill, and doesn't really punish the player. And create skill-based classes that are difficult to utilize optimally and/or punishes harder for mistakes of skill.

This will also have a side effect helpful to your situation: a "skilled" player may only be vary skilled in one or a few classes. If you make certain classes have an advantage against certain other classes, insomuch as to cause a 50-50 winning-losing chance for that combination, a you get closer to your goal. The skilled player either chooses their car or picks a different one he's not as skilled in. Either way the good player would be uncheatingly challenged, and the worse player has a real chance.

So classes seem great right? There is one major disadvantage: it is hard to create such a system, and much harder to create it right. This will require lots of thinking and creativity, and will never be perfect. Additionally, you will have to prevent new players from using very difficult cars, usually by a car unlocking system. And I am sure there are other disadvantages and advantages I missed or didn't think of, that will probably be pointed out in the comments of this awnser, but with dedication, you can overcome or mitigate these problems.

# Answer
> 1 votes
Cort Ammon's answer touched on the idea of playing against your own best, but I'd like to take that a bit further. Its success will depend on how important the theme of "racing game" is to your project.

One example would be, instead of a race game, a chase game. The lead car has a headstart but a slower car, and would be played by whoever chooses to (assuming it's a group of friendly people, the preference would be for it to be chosen by the strongest player). The chase car is faster, but due to being driven by the lesser-skilled player it will not catch up in a determinate time period, but due to the advantage the chase car has it should eventually catch up. The lead car's score is how long it evaded being caught or overtaken; the chase car's score is the opposite. Over multiple games, both players can then try to improve their score against each other. There is no need to set a baseline, as the players can do that for themselves.

A similar game style still related to racing would be having some players go the opposite way around the track, and deliberately attempt to collide with the oncoming cars, and score points appropriately. This should not disadvantage a player that spasms as much, as a spasm would make the oncoming car's trajectory more difficult for the opposing player to predict and avoid/hit.

---
Tags: game-design, balance, game-theory
---


# Question
Title: Finding the normals of the planes of a View Frustum
Say I have a perspective view matrix function that takes in aspect, fovy, near, and far... Transforming the view into a frustum. Typical OpenGL stuff, right. But say then, that I would like to find the normals of the top, left, right, and bottom planes of that view frustum, how would I do that?

Edit: I forgot, the camera has a vector position, and a vector direction ...

# Answer
It becomes much clearer if you draw it from a top-down perspective:

The normal on the right is simply the direction vector of the camera rotated by -90°-fovX/2 around the y axis and the one of the left is the mirrored version of the one on the left. Same with the top two, but they use fovY instead of fovX and you rotate the direction vector around the x acis
> 5 votes

# Answer
Or you could calculate the plane equations of all the frustum planes, and get the normals from the equations.

A plane equation has the form:

Ax + By + Cz + D = 0

(A, B, C) represents the plane normal.

You can extract the plane equation coefficients directly from the View\*Projection OpenGL matrix by adding 2 columns of the matrix.

This method is described here: http://www.cs.otago.ac.nz/postgrads/alexis/planeExtraction.pdf

Letting vp = View\*Projection;

Here is some code I use;

```
struct Plane
{
    float A, B, C, D;
};

struct Frustum
{
    Plane top, bottom, right, left, zNear, zFar;
};

// column2 + column3
frustum.zNear.A = vp(2, 0) + vp(3, 0);
frustum.zNear.B = vp(2, 1) + vp(3, 1);
frustum.zNear.C = vp(2, 2) + vp(3, 2);
frustum.zNear.D = vp(2, 3) + vp(3, 3);

// column3 - column2
frustum.zFar.A = -vp(2, 0) + vp(3, 0);
frustum.zFar.B = -vp(2, 1) + vp(3, 1);
frustum.zFar.C = -vp(2, 2) + vp(3, 2);
frustum.zFar.D = -vp(2, 3) + vp(3, 3);

// column1 + column3
frustum.bottom.A = vp(1, 0) + vp(3, 0);
frustum.bottom.B = vp(1, 1) + vp(3, 1);
frustum.bottom.C = vp(1, 2) + vp(3, 2);
frustum.bottom.D = vp(1, 3) + vp(3, 3);

// column3 - column1
frustum.top.A = -vp(1, 0) + vp(3, 0);
frustum.top.B = -vp(1, 1) + vp(3, 1);
frustum.top.C = -vp(1, 2) + vp(3, 2);
frustum.top.D = -vp(1, 3) + vp(3, 3);

// column0 + column3
frustum.left.A = vp(0, 0) + vp(3, 0);
frustum.left.B = vp(0, 1) + vp(3, 1);
frustum.left.C = vp(0, 2) + vp(3, 2);
frustum.left.D = vp(0, 3) + vp(3, 3);

// column3 - column0
frustum.right.A = -vp(0, 0) + vp(3, 0);
frustum.right.B = -vp(0, 1) + vp(3, 1);
frustum.right.C = -vp(0, 2) + vp(3, 2);
frustum.right.D = -vp(0, 3) + vp(3, 3);

```

Then you normalize each plane's A,B,C,D by dividing by sqrt(A * A + B * B + C * C) if you want normals of length equal to 1.
> 5 votes

---
Tags: 3d, projection, perspective, frustum
---


# Question
Title: Planning Class Inheritance for Game Objects
This is specifically about the development and planning direction of the game development.

I'm creating a fairly basic RPG and am wondering about the approach that I should take. I've been trying to outline it all in a flow chart first, but want to see if this is a good way of going about it.

For example, I've created a class called "items", which then currently derives into "Weapons" "Armor" and "Potions". I then derive these classes further into specific types and I keep going and going, basically as specific as I want to get.

Before I get too deep into this (again, I'm still planning) - I just want to know if this is a good way of approaching this problem.

# Answer
> 5 votes
It's not.

What if you want to hit with a shield (e.g. "Shield bash"), i.e. use an "Armor" as a "Weapon", or defend with a sword (e.g. "Parry") i.e. use a "Weapon" as an "Armor"?

You'll end up with having a Shield that inherits from Armor and from Weapon. And when you introduce diamond inheritance, you introduce guaranteed headaches.

Also, you'll end up a huge hierarchy, in which you could get lost, and in which you'll not want to modify base classes because it'll potentially mess up too much other features.

An issue I noted with this kind of hierarchy is when you want a feature on Armor and Weapon, but not on Potion, all of which inherit from Item: durability. To avoid code duplication, you'll write the feature in Item, but you'll also have to add the infrastructure to not use it in specific cases. As time goes by, you'll be adding feature in classes that do not exactly belong there, getting lost some more. (This is just an example tongive you the idea.)

The favoured approach is to use Composition over inheritance. Basically, you add behaviours to your items which drive what they can do. If an "Item" has an "attack" component (which has a "damage dealt" property (for instance)) , it means that you can use it as a weapon. If the same item has a "defense" component (with a "guard ratio" property, for instance), it means that the item can be used as an "armour".

Another research term is component based architecture. This should get you re-thinking your architecture :)

# Answer
> 2 votes
Eh, that's pretty good IMO. Minecraft works that way.

I would say that you should keep your item definitions ("this is what a sword does" "this is how potions behave") as single-instance objects and the things the player sees on the ground and pick up are actually *item stacks* which hold information about how much damage the item has taken, how many items are in the stack, etc. and just forwards off any interactivity to the Item reference. This keeps the overhead down.

# Answer
> 2 votes
As you've probably seen from other answers, there are pros and cons to using a polymorphic approach.

The main two approaches to game software design fall into two broad categories:

1. Polymorphic (inheritance based, or the "is a -" approach) object. OO purists will push this, but you have to contend with deadly diamond, amongst other potential headaches. That said, it can solve many problems very easily, and all gang of four design patterns rely on this kind of thinking to work.
2. Composition (component based, or the "has a -" approach) objects. Each game entity has a collection of components, that define what it data is relevant to it, and what it can do. Then game subsystems which only care about certain components operate on only entities which have those components. This prevents up a lot of headaches, and completely avoids deadly diamond.

Consider the following crude example:

You want a sword that supplies your character with a built in shield: How would you do this in an inheritance based architecture. Not easily. In a component (ECS) architecture, it's simple:

Create entity: Add sword graphic component. Add combat damage component, add shield defence component.Add sword attack animation. Job done, you now have a combined sword and shield, without having to define any new classes.

In a OO architecture, this requires you to replicate code from a previously written class, resulting in code bloat, and two separate places your shield code needs to be maintained in. If you can get away with only writing code once, do so.

Personally, I would strongly advise you to research Entity Component Systems (a good tutorial is here), and then make a decision from there.

---
Tags: c++, architecture
---


# Question
Title: When a quest is completed in my game, money gets re-set rather than added
I have two quests in the game I am trying to create and each of the quests gives 50 coins if the quest is completed successfully and when I finish the first quest, I am given 50 coins and all is cool!

There's a problem when I complete the second quest: it has to give me additional 50 and overall I have to have 100 coins. However when I complete the second quest, it, kind of, regives me 50 coins and overall I have 50 coins but it has to be 100.

Here is the code I am using:

```
The fragment of quest 2 and 1 script since they are identical
------------------------------

 void OnTriggerStay(Collider col)
    {

        if (col.tag == "Player" & Input.GetKeyDown(KeyCode.E))
        {
            Money.MoneyAmount = +50;//here I am trying to reference Money class
            exclamation.SetActive(false);

            if (TextBoxOnCheck == 0)
            {
                BaseQuest.QuestNumber = 0;
                TextBoxOnCheck = 1; //Sets the variable to turn the box off
                MessageBox.SetActive(true); //Re-enables the box

                TextBox.GetComponent<Text>().text = "Local rezident: Thank you a lot"; //changes the message
                QuestText.SetActive(false); // input the quest name

The money class handles adding coins to UI text
-----------------------------------------------

public class Money : MonoBehaviour {

    public static int MoneyAmount;
    public int InternalMoney;
    public GameObject MoneyDisplay;
    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        InternalMoney = MoneyAmount;
        MoneyDisplay.GetComponent<Text>().text = "" + InternalMoney;
    }
}

```

# Answer
At this line it looks like you're setting the money amount to exactly positive 50, regardless of what it was before:

```
Money.MoneyAmount = +50;//here I am trying to reference Money class

```

This operation is not adding 50 to the MoneyAmount, it's setting MoneyAmount to that exact value.

Did you mean to say this instead?:

```
Money.MoneyAmount += 50;

```

This is equivalent to the following:

```
Money.MoneyAmount = Money.MoneyAmount + 50;

```

(See += operator)
> 3 votes

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


# Question
Title: Checkers games with computer random movement
Im studying Java OOP, and I have to make first assignment about making checkers board game. I have to get input from user if he plays, and than when his turn is over the computer will play. Computer's movement is random but if he has the opportunity to "eat" his rival, he has to do this and if not than making random move. Can someone help me with the coding?

# Answer
> 1 votes
The most straightforward way would be to build a list of all possible moves and then randomly select from them.

1. Initialize two empty lists, eatMoves and nonEatMoves
2. For each rival token:
    * For each possible move of that token:
        + if the move involves eating an opponent:
            - Add move to eatMoves
        + else:
            - Add move to nonEatMoves
3. Choose one of the moves:
    * If eatMoves is not empty:
        + Randomly choose from eatMoves list
    * else:
        + Randomly choose from nonEatMoves list
4. Return the random move selection

Actually choosing a random number is straightforward: https://docs.oracle.com/javase/8/docs/api/java/util/Random.html

---
Tags: java, movement, random, board-game
---


# Question
Title: Using raycast to detect whether a wall immediately blocks a player in Unity C#
I am working on a game project of which involves a procedurally generated maze. Within this maze, there are different types of tiles, such as walls and gates. I want to program the player so that it cannot move through a tile that is tagged as a "wall", and I am hoping to use ray casting to detect item tags. Now, you may think it would be simpler to use rigid bodies, but the game is set up so that the player moves 1 unit per movement, instead of being able to move at any randomly input distance, in order to keep the game adhering to a "grid" for the sake of other events that happen within the game.

So, for this reason, i wish to detect if a wall is north of the player (let's call "north" as "up", as I have an "up blocked" boolean to state if a wall is directly "north" of the player) but, my code doesn't always recognise walls that are immediately north of the player, and instead sometimes the "up blocked" boolean becomes activated as "true" when a wall is left, right, or "below" (down) of the player, irrespective of whether or not there is a wall "above" or down.

here is my code:

```
Vector2 vUp = new Vector2(transform.position.x, (transform.position.y + 0.05f));

    RaycastHit2D hitUp = Physics2D.Raycast(transform.position, vUp);

    if (hitUp.collider != null && hitUp.collider.tag == "wall")  {
        upBlocked = true;
    } else {
        upBlocked = false;
    }

```

I have spent many hours looking for a solution for this problem, but most mediums provide information that either didn't work, wasn't applicable or simply was grossly out of date.

# Answer
> 0 votes
When in doubt, check the docs for the methods you're using.

Physics2D.Raycast takes an origin position and a *direction*, but you're passing it an origin and a *destination*

If you want to check 0.05 units up on the y axis, try...

```
float rayDistance = 0.05f;

Physics2D.Raycast(
    transform.position,
    Vector2.up,
    rayDistance
);

```

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


# Question
Title: AI-possessed Pawn flies off at incredibly high speed immediately after hitting play (UE4)
I have a very simple pawn with a Sphere Collision and a child Static Mesh. This pawn is set to be possessed by an AI Controller on spawn and the AI Controller basically sets up the blackboard and runs the behaviour tree. The behaviour tree is set to do nothing. As soon as I hit play in the editor, the pawn falls to the floor and bounces off at speeds almost too fast to see and quickly flies out of the edges of the worldmap and gets deleted.

alt text

In the picture above, the blurred blue thing is the object thats rocketing away.

I've been stuck on this for a very long time, any help is appreciated.

# Answer
> 1 votes
Thanks to a friend and Stephan Mar, I figured out that the collision setup for the static mesh was touching the sphere collision, causing it to infinitely launch itself away. To fix it, I got rid of the Sphere Collision Component and created custom Physics Asset for the static mesh.

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


title: Update() method never called

text:
# Question
Title: Update() method never called
I have a class `BlinkingBehaviour` which inherits from `MonoBehaviour`. Game objects attached to scripts containing classes that inherit from `BlinkingBehaviour` should, as the name suggests, blink.

`BlinkingBehaviour` is a small class so I will share the entirety of its code here:

```
public class BlinkingBehaviour : MonoBehaviour
{
    private Renderer renderer;

    public bool BlinkingEnabled;
    public Color BlinkingColour = new Color(1.0f, 127f / 255f, 39f / 255f);

    protected float CurrentColourScale;
    protected float ColourScaleIncrementPerUpdate = 0.005f;

    protected const float MaxColourScale = 2f;

    protected void Start()
    {
        this.renderer = this.gameObject.GetComponent<Renderer>();
    }

    protected void Update()
    {
        if (this.BlinkingEnabled)
        {
            SetBlinkingColour();
        }
        else
        {
            SetColour();
        }
    }

    protected void SetColour()
    {
        if (this.CurrentColourScale <= 1f)
        {
            this.renderer.material.SetColor("_EmissionColor", this.BlinkingColour * this.CurrentColourScale);
        }
        else
        {
            this.renderer.material.SetColor("_EmissionColor", this.BlinkingColour * (MaxColourScale - this.CurrentColourScale));
        }
    }

    protected virtual void SetBlinkingColour()
    {
        SetColour();
        this.CurrentColourScale += ColourScaleIncrementPerUpdate;

        if (this.CurrentColourScale <= MaxColourScale)
        {
            return;
        }

        ResetBlinkingColourScale();
    }

    protected void ResetBlinkingColourScale()
    {
        this.CurrentColourScale = 0f;
    }
}

```

I have a class `Lamp` which inherits from `BlinkingBehaviour`. I attached `Lamp.cs` to an object in my scene. In my inspector, I checked the `BlinkingEnabled` option, expecting to see the `Lamp` game object blinking after I pressed "Play".

However, the object did not blink.

Here is my `Lamp` class:

```
public class Lamp : BlinkingBehaviour
{
    private void Start()
    {
        base.Start();
    }

    private void Update()
    {
        base.Update();
    }
}

```

After setting various breakpoints, I could see that the `Start()` method was hit in both `Lamp` and `BlinkingBehaviour`. I could also see that `this.gameObject.GetComponent<Renderer>();` returned a valid component.

On the other hand, my breakpoint in the `Update` method in `Lamp` was never hit.

What can I do to fix this issue?

**UPDATE:**

I deleted the `Start()` and `Update()` methods from my derived class. I discovered something new: The `Update()` method in `BlinkingBehaviour` is never called, even though `Start()` is.

# Answer
The Update in the derived class should be an override of a protected virtual Update in the base class.

Imagine when Unity reflects the non-public members on your behavior -

```
BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic;
MethodInfo theMethod = typeof(Lamp).GetMethod("Update", flags);
theMethod.Invoke(lampInstance);

```

Which Update method gets called? By having private and a protected methods that aren't associated as an override, both are available so one will be chosen depending on the underlying implementation - possibly throwing an exception.

The proper way to implement this pattern would be:

```
public class BlinkingBehaviour : MonoBehaviour
{
    protected virtual void Update()
    {
        // ...
    }
}
public class Lamp : BlinkingBehaviour
{
    protected override void Update()
    {
        base.Update();
        // ...
    }
}

```
> 3 votes

# Answer
I quickly tried your code by copy/pasting it on a test scene, and it's working perfectly fine.

First of all, you can delete both `Start` and `Update` methods from `Lamp`: since it inherits from `BlinkingBehaviour`, both `Start` and `Update` methods will be called anyway from the superclass if there're no overriding methods in the inheriting class.

The fact that `Update` from `BlinkingBehaviour` is never called, tells that there's something wrong elsewhere.

Are you sure that the `Lamp` script component is active?
> 0 votes

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


# Question
Title: What information would I need to calculate proper placement of my Unity 3D orthographic HUD elements?
I have a Unity project and I have managed to create a 3D HUD by creating a separate (orthographic) camera for rendering elements on the UI layer. I already have some objects appearing in the HUD and rendering correctly.

What I want to do now is calculate the proper position and scale of these elements to make sure they are in the upper left corner and only take up 60% of the vertical space.

I am optimistic the necessary information is available to C# script components, but I have no idea which formulas and which members or methods (probably on the Camera object) can tell me what the X/Y bounds of the orthographic view are (for whatever the current aspect ratio is).

# Answer
Use the new UI. Add the 3D object to the canvas, make sure the canvas is in Screen Space or World Space.

Some screenshots from a Unity Answers post about this very problem.

Once you do that, you can use the RectTransform and Gui Layout features that exist to place UI elements where you want them on screen, regardless of the screen resolution.
> 1 votes

# Answer
I ended up using the `orthographicSize` and `aspect` properties of the camera like so:

```
public class HUDManager : MonoBehaviour {

    public Camera HUDCamera;
...
    void Start() {
...
        float x = - ( HUDCamera.orthographicSize * HUDCamera.aspect -tileWidth/2);
        float y0 = HUDCamera.orthographicSize - tileHeight/2;
...
            line.transform.position = new Vector3(x, y0 - i*tileHeight*1.1f, 0);

```

I am unsure if this would malfunction if the game screen were tall instead of wide.
> 0 votes

---
Tags: unity, camera
---


title: Random Sobol 3D Cell in Unity

text:
# Question
Title: Random Sobol 3D Cell in Unity
There is a blueprint in UE4 for making Sobol random 3D cell. It places random objects inside cell structure. How to make this in Unity?

For example, if I make a sphere prefab I would need to generate Sobol distribution in some volume.

EDIT:

@Seyed Morteza Kamali have made a script:

# Answer
you can use `Mesh bounds` to generating inside the bounding volume of the mesh.

> The bounding volume of the mesh.
>
> https://docs.unity3d.com/ScriptReference/Mesh-bounds.html

Attach this script to your cube:

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

public class RandomInside : MonoBehaviour {
    public GameObject Prefab;
    public int Number = 50;
    public float Factor = 0.5f;

    void Start () {
        for (int i = 0; i <= Number; i++)
        {
        var obj = Instantiate(Prefab,GetRandomPosInsideTheMesh(),Quaternion.identity);
        obj.transform.parent = gameObject.transform;
        }
    }

public Vector3 GetRandomPosInsideTheMesh(){
    Mesh mesh = gameObject.GetComponent<MeshFilter>().mesh;
    Bounds bounds = mesh.bounds;
    var pos = transform.position;
    var scale = transform.localScale;
    float minX = pos.x - scale.x * bounds.size.x * Factor;
    float minY = pos.y - scale.y * bounds.size.y * Factor;
    float minZ = pos.z - scale.z * bounds.size.z * Factor;

    Vector3 RandomArea = new Vector3(Random.Range (minX, -minX),
                                 Random.Range (minY, -minY),
                                 Random.Range (minZ, -minZ));
    return RandomArea;
}
}

```
> 1 votes

---
Tags: unity, random
---


title: C++ game to Unity

text:
# Question
Title: C++ game to Unity
So I have made a game coded in C++ (using SFML as a library) and a custom JSON C++ library. Is there anyway I can port this to Unity so I could use its UI features as well as its compilation ( I want to build the game for phones ). I have read about Native Plugins but I am not sure if it will work.

# Answer
I'm not sure it's possible to *completely* port a c++ game to unity. Your game uses sfml for drawing things on the screen, sfml uses opengl(or its way to draw things).

Unity has a much more complex architecture: it uses shader files, scripts, scenes and so on; This does not mean that the same *concepts* and mechanics can be applied to a game in Unity: most of the things are going to be much easier to do and less error prone.

In my opinion the solution (IF you want to use Unity) is to completely switch to unity, for both the android and desktop platforms.

IF you want to stick to C++ and sfml, there are ways to build your game for android
> 2 votes

---
Tags: unity
---


# Question
Title: What should I watch out for in a 3d artist's portfolio?
I'm looking to hire a freelancer to help with 3d modeling. I've thought up a few qualifiers so far:

* Is their topology okay for animation?
* Have they demonstrated the technical capabilities necessary for my project? (Have they baked normals, AO maps, etc.)
* Have they shown an ability to execute from conceptual drawings?

Are there any massively important things I should watch out for that I haven't included?

Any red flags I should be aware of, like making sure the work isn't plagiarized?

**Note**

I'm specifically talking about reviewing portfolio content, before interviewing them. I'm looking for things I can say yes or no to, or that I might want to question them on further in an interview.

# Answer
> 1 votes
You should look for imagination, creativity, ability to work with a team, from where he gets inspiration, ability to schetch out a quick example of an idea... there are a lot of things to take in consideration when hiring an artist.

---
Tags: 3d-modeling, hiring
---


title: Relative motion physics

text:
# Question
Title: Relative motion physics
So, I built a simple physics engine (without rotation as of now)

You can click and then release to create block with velocity.

https://codepen.io/kingofdelphi/pen/vRZvxQ

Now, I want to apply force at the bottom most block. Currently, the block will only slide without affecting the other top blocks.

Now, I can only think of a simple algorithm to make all the top blocks slide when the bottom one slides which goes like this,

1. shift the current block
2. find the blocks on top that touch the current block,
3. recurse each such block and goto step 1

But there are problems with this algorithm(double additions for example, but easy to fix with a boolean flag).

So guys, how do I make all top blocks slide when the bottom one moves?

# Answer
> 1 votes
Moving a cube under another one is the same as moving the one on top in the other direction. Friction keeps them together. So, when you detect a collision from the top, get the force applied to the bottom cube and apply it to the one on top as well.

# Answer
> 1 votes
The force on top cube should be equal to the force applied on the bottom one, minus a slight amount, which is the dynamic friction coefficent

---
Tags: 2d, motion
---


# Question
Title: How can I get GetMouseButtonDown two positions on two clicks?
```
private void Update()
        {
            if (Input.GetMouseButtonDown(0))
            {
                Vector3 pos1 = Input.mousePosition;
            }
        }

```

Like two points. I click once and the click one on another position so I will have two positions and now I will be able to draw a line between them. I want to get and store two positions.

# Answer
> 1 votes
You can gather as many positions as you want into a collection:

```
List<Vector2> _positions = new List<Vector2>();

void Update() {
    if(Input.GetMouseButtonDown(0)) {
        _positions.Add(Input.mousePosition);

        if(_positions.Count == 2) {
            // Draw your line, and clear the _positions list,
            // or shunt it down by one if you want the second point to
            // become the first point of the next line (use a Queue for this).
        }
    }
}

```

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


# Question
Title: Handling User Input Based on the Current Game State
currently i'm developing a 2D game in my spare time and i'm confused on how to handle the input from the player.

Currently my game uses the state design pattern, each game state is a different object such as Inventory, Playing, Paused etc. All of these states implement an interface called State that have a Render and Input method that is called on whatever the "Current state" is in the game engine.

So my question is would you use multiple key listeners or key bindings, one for each state since the input the player will do differs dramatically between the different game states or would you use one key listener or keybinding somehow? Is there a best practice for this?

Thanks.

# Answer
Maybe use flags?? **(I use same thing in C#)**

```
   On_Keypress(key){
    if(key==Q){
        if(inventoryopen){

        dropitem(selected)

        }else if(is_dying){

        slow_bloodlose();

        }
      }
    }

```

On your inventory open method :

```
On_Inv_open(){
inventoryopen=true;
}

```

On your inventory close method :

```
On_Inv_close(){
inventoryopen=false;
}

```

Or set a `int sate`

```
if(sate==1)//Inventory state
if(state==2)//Shop state
//

```
> 0 votes

---
Tags: java, input
---


title: Armor damage reduction system?

text:
# Question
Title: Armor damage reduction system?
So I want to develop a Dota2-like armor system where damage reduction never reaches 100%.

Armor values be like:

```
Armor --- Reduction

10 ---------- 10%

20 ---------- 19%

30 ---------- 27%

40 ---------- 35%

```

How to make something like that, where reduction never reachs 100%?

# Answer
> 0 votes
What you want is an increasing function that approaches a limit of 1 (for 100%).

There are infinite options to choose from here, but without further constraints we could pick a few simple ones:

```
// Scale the armor value to control how quickly it approaches the saturating value.
// fiftyPercentThreshold = the amount of armor you want to achieve 50% damage reduction
input = armor / fiftyPercentThreshold

// Simple ratio
damageReduction = input / (input + 1.0)

// Arctangent
damageReduction = atan(input) * 2.0/PI

```

Generally the positive half of any sigmoid function will do the trick.

# Answer
> 0 votes
You can use the sum of a geometric sequence.

A geometric sequence has a starting value (\\$a\_1\\$) and a quotient (\\$q\\$) and the n-th member is the multiple of the starting value and the quotient to the power of n:

$$a\_n = a\_1 \cdot q^n$$

The sum of the first n elementh of this sequence is

$$a\_1 \cdot \frac{1 - q^n}{1 - q}$$

To make sure this doesn't go above 1 (100%), you need to make sure

$$\frac{a\_1}{1 - q} $$

Doesn't go above 1 either

If you want the reduction the max out at 80%, then use 0.8

---
Tags: mathematics
---


# Question
Title: How can I draw a linerenderer line between two vector3 positions using the mouse left button click?
This code is drawing a line but it's not drawing it on the camera in front of the camera.

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

public class DemoScriptDraw : MonoBehaviour
{
    private List<Vector3> _positions = new List<Vector3>();
    private LineRenderer lr;

    private void Start()
    {
        lr = this.GetComponent<LineRenderer>();
    }

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Vector3 pos = Input.mousePosition;
            pos = Camera.main.ScreenToWorldPoint(new Vector3(pos.x, pos.y, lr.transform.position.z));
            _positions.Add(pos);

            if (_positions.Count == 2)
            {
                SpawnLineGenerator(_positions[0], _positions[1], Color.red);
            }
        }
    }

    void SpawnLineGenerator(Vector3 start, Vector3 end, Color color)
    {
        GameObject myLine = new GameObject();

        myLine.AddComponent<LineRenderer>();
        myLine.AddComponent<EndHolder>();
        LineRenderer lr = myLine.GetComponent<LineRenderer>();
        lr.material = new Material(Shader.Find("Particles/Alpha Blended Premultiply"));
        lr.startColor = color;
        lr.useWorldSpace = true;
        lr.endColor = color;
        lr.startWidth = 0.1f;//0.03f;
        lr.endWidth = 0.1f;//0.03f;
        lr.SetPosition(0, start);
        lr.SetPosition(1, end);
    }
}

```

The result is that the line is seen in the scene view window but not in the game view window:

# Answer
In this line:

```
pos = Camera.main.ScreenToWorldPoint(new Vector3(pos.x, pos.y, lr.transform.position.z));

```

you're using the Z position of the camera itself.

Keep in mind that the Z returned by the method is the distance from the plane normal to the camera forward direction and the Z parameter itself.

In your case, since `Camera.main.position.z` is -10, and you pass -10 as the Z parameter, the Z returned will be -20.

If you position the camera to Z = 10, then the method will return Z = 20, etc.

So, if the camera is in Z = -10 and the new line renderer has both positions set to Z = -20, it will be behind the camera frustum and not rendered.
> 1 votes

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


# Question
Title: Sprite character/item less than tile size
I am starting to work on a 2d top down tile-map game for fun and learning purposes. I have read some great answers here re tile-map size vs character sprite size, pixel density, ppu, screen resolution etc.

A standard route is to set a constant PPU and do characters as 2 tiles (vertically usually). We went with 32x32 pixels for the tile and 32x64 for the character.

Unfortunately, our artist didn't draw the character to fill out that space on the extremes (the feet and head do not touch the vertical edges and there is also space between the character and the horizontal edges) and when Unity slices the sprite-sheet we get smaller characters of 28x53.

I imagine this is a problem for keeping the consistency I outlined above with the tile size.

Is this a problem? If so, are the solutions to this to either change the tile size to 28x28 or ensure that the sprite design actually fills the tile space (that is, touching edges of the 32x64 area)? Must one draw items as always filling out the full tile size or can one make, say potions, in a 32x32 tile but only take up say 12x16?

# Answer
> 2 votes
No, this is not a problem.

If you make your character only 24 pixels wide for example (three quarters of 32), with a Pixels Per Unit value of 32, then Unity will default to sizing it 0.75 units wide (three quarters of 1 unit), and all your sprite pixel densities will still match just fine.

What PPU controls is pixel density, not the absolute width or height of the sprite, which you're free to vary and mix & match over any range you want.

Have you observed any issues with this that you'd like help correcting?

---
Tags: 2d, sprites, tilemap
---


# Question
Title: In android studio, how can I move ball to point I click?
I try to create a game like billiards. I want to move the ball the point I clicked.

# Answer
On the ball object, create a global left button event and create a script with the following:

`move_towards_point(mouse_x,mouse_y,5);`

The ball will go at a speed of 5 toward the point where you clicked with the mouse.

You can change the speed as you prefer, but to make the ball stop you will have to add the same physical component (friction).
> 1 votes

---
Tags: android, game-maker, android-studio
---


# Question
Title: Some GAME MAKER function for windows close button?
In my game there are variables that go through all rooms, so if the player leaves the "variable x" worth 10, and goes to another room, when he returns there is the "variable x" worth 10, same thing when he close the game by the button (exit) that I created in the main menu.

It turns out that if for some reason he closes the game by the "close button of windows", this variable is not saved.

This is clear because there is no command for it to happen, it happens that I did not find anything related to the "physical button close windows window" in the game maker.

Detail that my game is not full screen, but if there is no way to create an event in the game maker so that the "variable x" is saved before closing, tell me how do I delete the "physical buttons of the windows window ".

I'm sorry for the awful translation, I'm not an English speaker.

# Answer
> 1 votes
You can use the *Game End* event in the "Other" section.

The *Game End* event executes any action inside before the game is closed. You can use it to save the value of any variable and store it on the disk.

On the other hand, you can use the *Game Start* event to read such value and set it in your game before the player can actually start playing.

Alternatively, if you want to keep it simple, you can just use the built-in Save/Load Actions; you can save on *Game End* and load on *Game Start*.

In other words, what you need to implement is just an auto-save/load functionality for your game.

---
Tags: game-maker
---


# Question
Title: How can I refer to a recipe defined in one function from elsewhere in my code?
I want to access the variable `recipes` defined in this code below.

Unfortunately I have to define my `recipes` inside `storage.loadGame(session, function(currentGame) {...` because I need to make use of the `currentUser` variable available inside that function.

Once I'm outside of that function, I don't know how to access my `recipes` anymore.

```
rPositivityWORLD: function(intent, session, answer) {
    storage.loadGame(session,
       function(currentGame) {
         var currentUser = currentGame.data.UserName;
         var recipes= [
           "<seak>hey </speak>" + currentUser + "<speak> i know that you can do it, also just one more thing thank you</speak>",
           "<speak>testing </speak>" + currentUser + "<speak> testing</speak>",
           "<speak>testing </speak>" + currentUser + "<speak> testing 2</speak>"
         ];
 return recipes; // so i did try changing it to this,let's see what will happen.
       }
    );

    var indexList = [],
    ANSWER_LENGTH = 2,
    recipe = storage.loadGame.recipes;

    var index = recipe.length;
    if (ANSWER_LENGTH > index) {
        ......
    }
 }

```

# Answer
When you define a variable with var, it exists only in the local scope: in this case, inside the anonymous `function(currentGame)`.

If you want the variable to have a lifetime beyond this function, you'll need to define it in another scope, or assign it as a property of some other, longer-lived object.

For instance, if the `function` argument passed to `loadGame()` is executed immediately, before `loadGame()` returns, then you could do something like this:

```
// Defined at an outer scope.
var recipes;

storage.loadGame(session,
     function(currentGame) {
          ...
          // This "recipes" refers to the variable captured from the outer scope.
          recipes = /* whatever */
     }
);

/* use recipes' contents here. */

```

But this won't work if this anonymous function is called asynchronously - say `loadGame()` needs to download some files, so it starts the downloads and returns immediately, but the load process won't finish and call that function until it's all the files come in. In that case, `recipes` won't have gotten its values populated by the time you try to use them with code like what's above. Instead, you'll need to put the code that uses recipes in a handler that fires only after the load completes - maybe inside that anonymous function itself, or have that anonymous function call your recipe-using logic once it's finished with its own work.

Unfortunately without seeing more of your code, we can only speculate on which pattern is more appropriate here. Whenever possible, including more context about the feature you're implementing and how your code is architected helps get better, more actionable answers.
> 1 votes

---
Tags: javascript, node.js
---


# Question
Title: Why when drawing a box using LineRenderer the connected points of the lines is not complete?
It looks like depending on the camera view angle that there is kind of space in the connected points between the lines:

What I mean not connected or kind of pspaces in the connection points of the lines is marked here with blue circles:

The script:

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

public class ShowMeshBounds : MonoBehaviour { public GameObject\[\] objectsToDraw; public GameObject prefabEffect; public Color color = Color.green;

```
private Vector3 v3FrontTopLeft;
private Vector3 v3FrontTopRight;
private Vector3 v3FrontBottomLeft;
private Vector3 v3FrontBottomRight;
private Vector3 v3BackTopLeft;
private Vector3 v3BackTopRight;
private Vector3 v3BackBottomLeft;
private Vector3 v3BackBottomRight;

private float counter = 0;
public bool animateLines;
public float speed = 1f;

private List<GameObject> allLines = new List<GameObject>();
private List<GameObject> instancesToMove = new List<GameObject>();
private Vector3 startPos;
private Vector3 endPos;

private void Start()
{
    DrawObjects();
}

private void DrawObjects()
{
    objectsToDraw = GameObject.FindGameObjectsWithTag("SpawnObject");

    for (int i = 0; i < objectsToDraw.Length; i++)
    {
        CalcPositons(objectsToDraw[i]);
        DrawBox();

        for (int x = 0; x < allLines.Count; x++)
        {

            allLines[x].transform.parent = objectsToDraw[i].transform;
        }
    }

    DuplicatePrefabEffects(1);

    StartCoroutine(moveStuff());
}

private void DuplicatePrefabEffects(int duplicationNumber)
{
    for (int i = 0; i < duplicationNumber; i++)
    {
        var go = Instantiate(prefabEffect);
        go.tag = "Duplicated Prefab";
        go.name = "Duplicated Prefab";
        instancesToMove.Add(go);
    }
}

void CalcPositons(GameObject objectToDrawTransform)
{
    Bounds bounds = objectToDrawTransform.GetComponent<MeshFilter>().sharedMesh.bounds;

    Vector3 v3Center = bounds.center;
    Vector3 v3Extents = bounds.extents;

    v3FrontTopLeft = new Vector3(v3Center.x - v3Extents.x, v3Center.y + v3Extents.y, v3Center.z - v3Extents.z);  // Front top left corner
    v3FrontTopRight = new Vector3(v3Center.x + v3Extents.x, v3Center.y + v3Extents.y, v3Center.z - v3Extents.z);  // Front top right corner
    v3FrontBottomLeft = new Vector3(v3Center.x - v3Extents.x, v3Center.y - v3Extents.y, v3Center.z - v3Extents.z);  // Front bottom left corner
    v3FrontBottomRight = new Vector3(v3Center.x + v3Extents.x, v3Center.y - v3Extents.y, v3Center.z - v3Extents.z);  // Front bottom right corner
    v3BackTopLeft = new Vector3(v3Center.x - v3Extents.x, v3Center.y + v3Extents.y, v3Center.z + v3Extents.z);  // Back top left corner
    v3BackTopRight = new Vector3(v3Center.x + v3Extents.x, v3Center.y + v3Extents.y, v3Center.z + v3Extents.z);  // Back top right corner
    v3BackBottomLeft = new Vector3(v3Center.x - v3Extents.x, v3Center.y - v3Extents.y, v3Center.z + v3Extents.z);  // Back bottom left corner
    v3BackBottomRight = new Vector3(v3Center.x + v3Extents.x, v3Center.y - v3Extents.y, v3Center.z + v3Extents.z);  // Back bottom right corner

    v3FrontTopLeft = objectToDrawTransform.transform.TransformPoint(v3FrontTopLeft);
    v3FrontTopRight = objectToDrawTransform.transform.TransformPoint(v3FrontTopRight);
    v3FrontBottomLeft = objectToDrawTransform.transform.TransformPoint(v3FrontBottomLeft);
    v3FrontBottomRight = objectToDrawTransform.transform.TransformPoint(v3FrontBottomRight);
    v3BackTopLeft = objectToDrawTransform.transform.TransformPoint(v3BackTopLeft);
    v3BackTopRight = objectToDrawTransform.transform.TransformPoint(v3BackTopRight);
    v3BackBottomLeft = objectToDrawTransform.transform.TransformPoint(v3BackBottomLeft);
    v3BackBottomRight = objectToDrawTransform.transform.TransformPoint(v3BackBottomRight);
}

void DrawBox()
{
    SpawnLineGenerator(v3FrontTopLeft, v3FrontTopRight, color);
    SpawnLineGenerator(v3FrontTopRight, v3FrontBottomRight, color);
    SpawnLineGenerator(v3FrontBottomRight, v3FrontBottomLeft, color);
    SpawnLineGenerator(v3FrontBottomLeft, v3FrontTopLeft, color);

    SpawnLineGenerator(v3BackTopLeft, v3BackTopRight, color);
    SpawnLineGenerator(v3BackTopRight, v3BackBottomRight, color);
    SpawnLineGenerator(v3BackBottomRight, v3BackBottomLeft, color);
    SpawnLineGenerator(v3BackBottomLeft, v3BackTopLeft, color);

    SpawnLineGenerator(v3FrontTopLeft, v3BackTopLeft, color);
    SpawnLineGenerator(v3FrontTopRight, v3BackTopRight, color);
    SpawnLineGenerator(v3FrontBottomRight, v3BackBottomRight, color);
    SpawnLineGenerator(v3FrontBottomLeft, v3BackBottomLeft, color);
}

void SpawnLineGenerator(Vector3 start, Vector3 end, Color color)
{
    GameObject myLine = new GameObject();

    myLine.tag = "FrameLine";
    myLine.name = "FrameLine";

    myLine.AddComponent<LineRenderer>();
    myLine.AddComponent<EndHolder>();
    myLine.GetComponent<EndHolder>().EndVector = end;
    LineRenderer lr = myLine.GetComponent<LineRenderer>();
    lr.material = new Material(Shader.Find("Particles/Alpha Blended Premultiply"));
    lr.startColor = color;
    lr.useWorldSpace = false;
    lr.endColor = color;
    lr.startWidth = 0.1f;//0.03f;
    lr.endWidth = 0.1f;//0.03f;
    lr.SetPosition(0, start);
    lr.SetPosition(1, start);

    allLines.Add(myLine);
}

IEnumerator moveStuff()
{
    for (int i = 0; i < allLines.Count; i++)
    {
        counter = 0;
        endPos = allLines[i].GetComponent<EndHolder>().EndVector;

        var dist = Vector3.Distance(endPos, startPos);
        while (counter < 25)//dist > 0f)
        {
            dist = Vector3.Distance(instancesToMove[0].transform.position, endPos);
            counter++;
            endPos = allLines[i].GetComponent<EndHolder>().EndVector;
            startPos = allLines[i].GetComponent<LineRenderer>().GetPosition(0);

            instancesToMove[0].transform.position =
                Vector3.MoveTowards(startPos, endPos, counter / 25f * speed);

            allLines[i].GetComponent<LineRenderer>().SetPosition(1, instancesToMove[0].transform.position);//tempPos);

            yield return null;
        }
    }
}

```

} What I want is to create animate the linerenderer lines and create smooth complete box

# Answer
Because they're LineRenderers, not "BoxRenderers."

Each one's job is just to draw the one line you give it. It doesn't know anything about nearby lines being drawn by other objects, and it doesn't know you want it to connect to them.

You can get nicer corners by drawing multiple segments with a single LineRenderer - then it knows about both sides of a joint, and can connect them properly. But this won't work from all angles (cubes have 3-way corners, but the LineRenderer knows only about corners where 2 consecutive segments meet, not 3)

The simplest fix is to turn up the **End Cap Vertices** property on the LineRenderers. This will cap each end of a line with a semi-circle, which will help fill-in the joints where two lines meet. A value of 4 or 5 works pretty well, though you can go higher if you need it to look smooth when viewed from very close-up.
> 1 votes

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


# Question
Title: A trigger collider in Unity doesn't allow the player to pass through
It's my understanding that checking "Is Trigger" on a collider should allow rigid bodies to pass through without collision prevention, but my trigger isn't doing that consistently. The player cannot pass through, but other objects can.

The trigger is a cube primitive with "mesh rendered" unchecked so that the cube won't be visible. The cube has a box collider with "is trigger" checked, and also a script. The script currently doesn't do anything except output from Debug.Log in OnTriggerEnter() as a test.

Primitives are able to pass through. The test is just a basic Unity sphere with all the default settings, including a sphere collider. The only change was that I added a RigidBody.

Imported models also pass through. I have a simple .blend model with a rigid body and box collider.

The player does not pass through. The main difference between the player's object and the other imported model is that the player is using a custom mesh collider which is different than the player's rendered mesh. The rendered mesh is the game object and the low-poly collision mesh is a child of that object.

I've tried several variations, including switching the player from a mesh collider to a box collider, and also moving the box collider to the main mesh rather than a child mesh, but the results are the same. The player stops moving as soon as he hits the location of the trigger's box collider.

Any ideas are appreciated. Thanks in advance.

**MORE INFO:**

Here's a screenshot of the scene layout, with the invisible trigger collider selected.

Also pictured is the hierarchy showing that the trigger collider ("Jump Pad Trigger") has no children. On the right is displayed every component that the trigger object has. I've also moved the collider from its original location several times to prove that it's not another object in the scene that the player is colliding with.

# Answer
> 0 votes
It was in the car's movement code.

**Even though trigger colliders can be passed through, raycasting into them apparently still fires off the moving object's collision handlers (depending on your physics settings). Good to know.**

I figured it out when I tried driving backward through the trigger and it worked fine.

I had a bit of old code in my vehicle's movement script to mitigate some weird physics behaviors during head-on collisions only.

```
  void OnCollisionEnter ()
    {
    check_forward_collision ();
    }

  void OnCollisionStay ()
    {
    check_forward_collision ();
    }

  void check_forward_collision ()
    {
    bool collision_front = false;
    Vector3 ray_start = transform.position + new Vector3 (0f, .5f, 0f);

    collision_front = Physics.Raycast (ray_start, transform.forward, 3f);

    if (collision_front && forward_speed > .3f)
      {
      forward_speed = .3f;  // <-- THIS LINE
      }
    }

```

When the player would continue pushing forward against a wall with the button held down, the car would sometimes climb the side of the wall or drive underneath it. This function would raycast forward and reduced the player's speed if the hit was directly in front.

This old code was apparently getting fired off by the trigger collider. I don't need it any longer, since I fixed those physics problems a different way.

---
Tags: unity, collision-detection, collider
---


# Question
Title: How can I generate random levels like in "Square it!" game?
In this game, you have a 2d field with some free squares and two colored squares which you can move but only together (they'll move only if the spot is still "free"). And you have to fill whole free space.

Here is a video that demos how the game is played.

How can I generate random game levels like in that game?

# Answer
The following should be enough to generate a level for a clone of the game:

1. Decide - at random - the start position for the squares.
2. Repeat n times:
    1. Decide a direction - at random.
    2. For each square, if block at that direction:
        1. Has been walked in, or is out of bounds: Do nothing.
        2. Has not been walked in: Decide - at random:
            1. Mark the block as solid.
            2. Mark the block as not solid. *Add it to the set of walked blocks, or mark it walked*. And move the square there.

These are the things you can tweak:

* What is the distribution for the starting positions? Would it prefer the squares to start nearby or not? Do you want to use a different distribution for one square than from the other?
* What is the distribution for the directions? Would it prefer to stay in the same direction, or will it prefer to change direction every step? Addendum: Here is an idea: you could have one square to prefer to move towards the other square, while the other prefer to stay in the same direction... or other combinations of distributions.
* What is the distribution of solid vs not solid? Will the squares find obstacles too often, or will the obstacle be more sparse.
* How many iterations does it do? Will the map requires few moves or lots of moves?

Note: it is possible that the above algorithm has steps in which it does nothing. That is ok. Eventually it will run out of iterations.

Teak until you have satisfactory results. You may consider to make the distributions a function of the number of level to create a difficulty curve.

---

You can do something more exotic with the same approach. Instead of picking a direction with a given distribution, you can pick a destination, and then use path finding to decide the steps the squares take to get there. In this case, you will not pick a direction n times, but pick a destination n times, and run until you have reached all the destinations or there is no more moves posible.

Addendum: A variation is to pick a set of destinations blocks, and on each iteration you decide for which one of those you want to go. You may, for example, always pick the nearest one, or pick at random.

Note: Be aware that the algorithm may lead to a sitiation in where there are no more possible moves, but it didn't reach all the destinations. In this case I suggest to just ignore the fact that you didn't reach the destinations, you should still have a valid level.
> 2 votes

---
Tags: algorithm, procedural-generation, level-design
---


# Question
Title: How can I correct an unwanted fisheye effect when drawing a scene with raycasting?
Hello I have a game using raycasting for the TI Nspire in Lua, and when the player faces a wall so that their degree they are facing is perpendicular to the length of the wall, I am having what is described as the fishbowl/fisheye effect.

How can I fix this? I have already looked here, and none of that makes sense to me. Here is my code:

```
map = {{0, 0, 50, 0},{50, 0, 50, 50},{50, 50, 0, 50},{0, 50, 0, 0}}

facing = 45 --"player rotation"
rays = {}
x, y = 25, 25

function raycast()
    for i,v in pairs(rays) do
        rays[i] = nil
    end

    rayf = facing + 30

    for i = 1, 320, 1 do --64, 5
        x_ray, y_ray = x, y
        ray()
        table.insert(rays, radius)
        rayf = rayf - (60/320)
    end
    platform.window:invalidate()
end

function ray()
    radius = 1
    for n = 1, 50, 1 do -- increase of testdot
        x_ray = math.floor(x + (radius * math.cos(rayf * 3.141592653/180)))
        y_ray = math.floor(y - (radius * math.sin(rayf * 3.141592653/180)))
        for k,v in pairs(map) do
            if (
                math.min(v[1],v[3]) <= x_ray and x_ray <= math.max(v[1],v[3])
            ) and (
                math.min(v[2],v[4]) <= y_ray and y_ray <= math.max(v[2],v[4])
            ) then
                --print("Collision")
                return true
            end
        end
        radius = n
    end
end

function on.paint(gc)
    gc:setColorRGB(0,200,255)
    gc:fillRect(0, 0, 320, 108)
    gc:setColorRGB(100,100,100)
    gc:fillRect(0, 109, 320, 109)
    gc:setColorRGB(100,0,100)
    for i,v in ipairs(rays) do
        gc:drawLine(i, 108.5 - ((100/v * 20)/2), i, 108.5 + ((100/v * 20)/2))
    end
end

function on.arrowKey(key)
    if key == 'left' then
        facing = facing + 3
    elseif key == 'right' then
        facing = facing - 3
    end
    if key == 'up' then
        y = y - 1
    elseif key == 'down' then
        y = y + 1
    end
    raycast()
end

```

I have also tried it like this:

```
map = {{0, 0, 50, 0},{50, 0, 50, 50},{50, 50, 0, 50},{0, 50, 0, 0}}

facing = 45 --"player rotation"
rays = {}
x, y = 25, 25

function raycast()
    for i,v in pairs(rays) do
        rays[i] = nil
    end

    rayf = facing + 30

    for i = 1, 320, 1 do --64, 5
        x_ray, y_ray = x, y
        ray()
        ----------------
        fisheyeradius = radius / (math.cos(rayf - facing))
        table.insert(rays, fisheyeradius)
        ----------------
        rayf = rayf - (60/320)
    end
    platform.window:invalidate()
end

function ray()
    radius = 1
    for n = 1, 50, 1 do -- increase of testdot
        x_ray = math.floor(x + (radius * math.cos(rayf * 3.141592653/180)))
        y_ray = math.floor(y - (radius * math.sin(rayf * 3.141592653/180)))
        for k,v in pairs(map) do
            if (
                math.min(v[1],v[3]) <= x_ray and x_ray <= math.max(v[1],v[3])
            ) and (
                math.min(v[2],v[4]) <= y_ray and y_ray <= math.max(v[2],v[4])
            ) then
                --print("Collision")
                return true
            end
        end
        radius = n
    end
end

function on.paint(gc)
    gc:setColorRGB(0,200,255)
    gc:fillRect(0, 0, 320, 106)
    gc:setColorRGB(100,100,100)
    gc:fillRect(0, 106, 320, 106)
    gc:setColorRGB(100,0,100)
    for i,v in ipairs(rays) do
        gc:drawLine(i, 108.5 - ((100/v * 20)/2), i, 108.5 + ((100/v * 20)/2))
    end
end

function on.arrowKey(key)
    if key == 'left' then
        facing = facing + 3
    elseif key == 'right' then
        facing = facing - 3
    end
    if key == 'up' then
        y = y - 1
    elseif key == 'down' then
        y = y + 1
    end
    raycast()
end

```

The wall originally looked like this:

But I have made changes around the ---------------, and now the wall looks like this:

I this supposed to occur?

# Answer
I actually had to solve this some time ago. The easiest fix is to simply divide by `cos(angle of ray - viewAngle)` and use that as the distance
> 1 votes

# Answer
It looks like you're firing out your rays at evenly spaced angular intervals.

```
rayf = facing + 30
...
x_ray = math.floor(x + (radius * math.cos(rayf * 3.141592653/180)))
y_ray = math.floor(y - (radius * math.sin(rayf * 3.141592653/180)))
...
rayf = rayf - (60/320)

```

This makes a kind of intuitive sense - you want to sweep rays across the field of view - but if you're mapping each ray to (a column of) pixels on a flat screen, then it's a mistake.

When the player looks at the grid of pixels on a flat screen, the angles from their eye to each column of pixels from left to right are *not* evenly spaced. They're spread apart widest in the middle of the screen, and bunch together toward the sides as the screen slopes away from perpendicular to the view ray, foreshortening in the player's view.

When you use rays fired off at even angular intervals, you're effectively stating that the rendering intent is to be displayed on a cylindrical or spherical screen that wraps around the player's head. And for such a screen, this pinched lens shape is indeed the correct appearance for a flat wall.

So, to ensure your rendering looks good on a flat screen, fire your rays based on the flat screen. Imagine you have an image plane hovering in front of the player, pick evenly spaced points on that plane, and fire your rays toward those points.

For example...

```
forward_x = cos(facing * pi/180)
forward_y = -sin(facing * pi/180)  -- following the convention you use for rays

projection_plane_width = 2 * tan(horizontal_field_of_view * pi/180);

right_x = -forward_y * projection_plane_width
right_y = forward_x * projection_plane_width

for i = 1, 320, 1 do
    -- step from -0.5 to +0.5 in equal increments
    progress = (i - 1)/319 - 0.5

    -- aim at a position ahead of the player and slightly to the left or right
    step_x = (forward_x + progress * right_x) * radius
    step_y = (forward_y + progress * right_y) * radius

```

For more info on projections for spherical vs flat screens, see this earlier answer.
> 4 votes

---
Tags: raycasting, lua, trigonometry
---


# Question
Title: How can I move a vehicle using speed and steering angle?
I want to drive a vehicle in x and y coordinate area with range from (0,0) to (6000,5000). I am using Visual Components (using Python API).

On input I have **speed** data and **steering angle** of wheels from Simulink. For example speed of 30 (0.25 m/sec) with the steering angle of wheels from 35 to -35.

I can use something like `x = speed * COS( steeringAngle )` and `y = speed * SIN( steeringAngle )` while adding up the values of x and y together respectively for each loop.

But the problem is it goes in one direction. If the vehicle turn and comes to area below the value of current x and y. I don't know how to actually get the right x and y value when the turn is so much that it goes to reduced values of x and y. A concept photo is attached. Anyone knows how to solve this?

Here is my code:

```
Speed= [1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000] #Incoming Speed
  Angle= [0,0,0,10,0,0,-20,-20,0,35,35,35,35,35,35,35,35] #Incoming Angle
  item = app.findComponent('Ball') #Find component in VC
  delay(0.1)

  newposition = [10,2500,0,90,0,180] #New position array
  x = newposition[0]
  y = newposition[1]
  z = newposition[2]
  w = newposition[3]
  p = newposition[4]
  r = newposition[5]   #wpr is yaw, pitch, roll
  Xold=0
  Yold=2500
  Rold=0     #store x y and r

  for s, a in zip(Speed, Angle):        #get values from array
    delay(1)
    print "(Speed, Angle) ->",(s, a)
    x=s
    y=Yold
    r=a         #just store

    rad=math.radians(a)
    x=math.cos(rad)*s
    y=math.sin(rad)*s           #convert to radians

    Xold=Xold+x
    Yold=Yold+y
    Rold=Rold+r              #add to prev value
    x=Xold
    y=Yold
    r=Rold
    print x,y,r

    mtx = item.PositionMatrix         #get position of BALL
    mtx.P = vcVector.new(x,y,z)   #Position
    mtx.WPR = vcVector.new(w,p,r) #Orientation as yaw,pitch,roll
    item.PositionMatrix = mtx             #store new location
    item.update()
    app.render()

```

# Answer
> 0 votes
If I understand it correctly, you want to create a steering effect. Inorder to achieve that you will have increase/decrease the value of the angle depending on input. Like so

```
    public float steeringSensitivity = 2;
    float angle = 0;
    public float speed = 4;
    void Update() {
        float direction = Input.GetAxis ("Horizontal");
        if (direction < 0) {
            angle -= steeringSensitivity * Time.deltaTime;
        } else if(direction > 0) {
            angle += steeringSensitivity * Time.deltaTime;
        }
        Vector3 offset = new Vector3 (speed * Mathf.Cos( angle), speed * Mathf.Sin(angle), 0);
        transform.position += offset * Time.deltaTime;
    }

```

---
Tags: 2d, mathematics, movement, python, coordinates
---


# Question
Title: Clamp camera view angles relative to moving object
I have a camera attached to an entity that moves in a circular pattern around a fixed center position. I am attempting to clamp the rotation of the camera such that it can only look inward toward the center of the circle.

I have tried for some time to accomplish this but haven't had much luck.

Simply clamping the angles like this will not work:

```
rotation = Vector3.Clamp(rotation, new Vector3(-50.0f, rotationY, 40.0f), new Vector3(-20.0f, rotationY, 100.0f));

```

(the rotation angles are relative to world space, and not the local rotation of the entity)

I need to get a clamp value that is relative to the direction the entity is facing.

Is there any way I can accomplish this?

Update-

Adding the rotation of the entity to the camera rotation like in the following seems to work intermittently, but now it seems the camera starts stuttering at certain points around the circle.

Still stuck.

```
Vector3 clampMin = new Vector3(-50.0f, 0, 40.0f);
Vector3 clampMax = new Vector3(-20.0f, 0, 100.0f);

public void Update()
{
       // adding the users input
       rotation = camera.Rotation + (new Vector3(GetInputY(), 0, GetInputX()) * 4.0f);

       float clampX = ClampAngle(rotation.X, clampMin.X, clampMax.X);

       float clampZ = ClampAngle(rotation.Z,
                entity.Rotation.Z + clampMin.Z,
                entity.Rotation.Z + clampMax.Z);

       camera.Rotation = new Vector3(clampX, 0, clampZ);

}

```

# Answer
You can set the position of the camera as an offset to the entity relative to the center. Then you can focus the ViewDirection of the camera directly on this center.

```
float scale;
Vector3 center;
var altitudeOffset = new Vector3(0, 0, x);
var entityRelativeToCenter = entity.Position - center;

// you can also use '+ scale'
camera.Position = entityRelativeToCenter * scale + altitudeOffset + center;
camera.ViewDirection = center;

```

If you wanted to move freely without the camera moving constantly, you can Clamp it with a range.

```
float allowedAngle;
var minRange = entityRelativeToCenter.Rotate2D(-allowedAngle);
var maxRange = entityRelativeToCenter.Rotate2D(allowedAngle);
camera.Position = Vector3.Clamp(camera.Position, minRange, maxRange);

```
> 1 votes

# Answer
The reason you are getting stutters is because you might be updating the camera position before the position of the moving object is updated.

You can fix this by moving your camera code into `LateUpdate()` or by adding script execution orders to both the object and camera scripts and setting the camera script's order to a higher value. You can set this under `Edit->Project Settings->Script Execution Order.`
> 1 votes

---
Tags: c#, 3d, rotation, vector
---


title: Move Object Around Sphere in Unity3D

text:
# Question
Title: Move Object Around Sphere in Unity3D
I am trying to get a `GameObject` to be able to be controlled to move freely around a sphere using a virtual on-screen joystick. I am building this for iOS and Android in Unity. I am using the standard `Joystick` script that comes with the Standard Assets (Mobile) package. I can get the object to turn around it's forward vector using the joystick by this code:

```
if (moveJoystick.IsFingerDown())
{
    // Rotate the ship according to the joystick angle
    currentAngle = moveJoystick.getAngle();
    thisTransform.RotateAroundLocal(Vector3.forward, Mathf.DeltaAngle(lastAngle, currentAngle)*Mathf.Deg2Rad);
    lastAngle = currentAngle;
}

```

That rotates the ship around it's local axis correctly. My problem is trying to get the joystick to move the object around the sphere based on the axis that the joystick is on. This would mean the object moves in the angle it is pointing but staying at the same radius from the center of the sphere which is located at (0, 0, 0). Then I also need to have the camera follow the object as it moves. Any ideas?

**Edit:** I got the orbit to work based off of the joystick using the code below. But the rotations seem to get messed up as soon as it gets to a certain point. Around 180 degrees? Also what is the correct way to have the camera follow the ship? I tried to make the camera a child of the ship in the hierarchy and that is when I really notice the messed up rotations and the ship doesn't respond correctly to my joystick. Also now the joystick doesn't rotate the ship around it's local axis anymore. Hmmm.

```
   if (moveJoystick.IsFingerDown())
        transform.RotateAround(Vector3.zero, Vector3.up, -moveJoystick.position.x * SPEED * Time.deltaTime);
        transform.RotateAround(Vector3.zero, Vector3.right, moveJoystick.position.y * SPEED * Time.deltaTime);
    }

```

# Answer
> 1 votes
So if I understand the issue, you are having a problem orbiting a point, rather than rotating around your own forward vector? The first coordinate allows you to specify an axis to rotate around within the world, and you are currently passing in the objects own forward vector. What you would need to do (if you want to use a function similar to this) is pass in a vector that represents an axis/location that you would like to rotate around, in this situation i am expecting you would like to rotate around the "Up" axis of the target sphere. Also, be sure you are transforming your objects on the correct coordinate system (local/world).

Here is a link to the unity reference page, offering more specifics. http://docs.unity3d.com/Documentation/ScriptReference/Transform.RotateAround.html

# Answer
> 0 votes
You can position an object around a sphere like this

```
transform.position = sphere.transform.position + radius * new Vector3 (Mathf.Cos (Mathf.Deg2Rad * angle), Mathf.Sin (Mathf.Deg2Rad * angle), 0);

```

**Remember that you wont need the Deg2Rad multiplication if the angle is in degrees**

Then rotate the object localy using

```
Quaternion newRotation = Quaternion.Euler (0, 0, angle);
transform.rotation = Quaternion.Slerp (transform.rotation, newRotation, Time.deltaTime * 5);

```

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


title: How can I optimize coroutines?

text:
# Question
Title: How can I optimize coroutines?
I have a script which has a Queue datastructure (code below). This queue holds more than 100 Actions. So currently my script does a `yield return null` after every Dequeue, which means that one `Dequeue()` call is executed every frame.

```
private static readonly Queue<Action> DataQueue = new Queue<Action>();
private bool _isHandlingQueue; // Helper bool to check if Coroutine is active

private IEnumerator HandleQueue()
{
    _isHandlingQueue = true;

    while (DataQueue.Count > 0)
    {
        DataQueue.Dequeue().Invoke();
        yield return null;
    }

    _isHandlingQueue = false;

    yield return null;
}

```

I'm trying to achieve that multiple Dequeue and Invoke actions take place in the same frame. One Dequeue and Invoke takes between `x` and `y` ms, this varies depending on the `Action` itself.

Example: Lets say the Queue has 100 entries and the game runs at 60 frames per second (minimum). One iteration (Dequeue + Invoke) in the `while` loop takes about 5 ms in this example. Here is the thing: In this case it is essentially waiting for 11.67 ms for the next frame (16.67 ms each frame at 60fps). I don't want the system to wait, but use the remaining 11.67 ms to Dequeue and Invoke 2 more Actions, so it only waits for 1.67ms each frame. In this ideal case the Queue get's cleared in 34 frames instead of 100 frames.

All help to point me in the right direction is appreciated!

# Answer
The obvious solution would of course be to not yield after every queue entry but only after every `n` entries, where `n` is a number you need to figure out through experimentation.

But that will of course lead to irregularities if some actions take much longer to invoke than others. An ideal solution would not process `n` queue entries but rather process queue entries for `n` milliseconds.

Most functionality of the Unity `Time` class won't help you here, because it represents the state at the beginning of the current frame. However, there is `Time.realTimeSinceStartup` which is a thin wrapper around the system clock. It should keep progressing during the frame.

```
private static readonly Queue<Action> DataQueue = new Queue<Action>();
private bool _isHandlingQueue; // Helper bool to check if Coroutine is active

private static readonly float QUEUE_PROCESSING_TIME = 0.01167f;

private IEnumerator HandleQueue()
{
    _isHandlingQueue = true;

    float frameStartTime = Time.realTimeSinceStartup;

    while (DataQueue.Count > 0)
    {
        DataQueue.Dequeue().Invoke();

        if (frameStartTime + QUEUE_PROCESSING_TIME < Time.realTimeSinceStartup)
        {
            yield return null;
            frameStartTime = Time.realTimeSinceStartup;
        }
    }

    _isHandlingQueue = false;

    yield return null;
}

```

Note that this will process the queue for *at least* 0.01167 seconds per frame (or until it is empty). Processing it for *exactly* 0.01167 seconds would be rather difficult because you can't predict how long each task will take.

Also keep in mind that not all platforms will provide you with the same clock accuracy. So if you want to support multiple platforms, then this is one thing you need to keep an eye on during cross-platform QA.
> 3 votes

---
Tags: unity, coroutines
---