# Question
Title: How can I ensure procedural levels in an RTS are fair?
I've seen that symmetry and coherance is important in RTS level design, but I'm lazy and want to do procedurally generated levels.

How can I ensure I generate a fair playing field when procedurally creating levels for an RTS?

# Answer
> 25 votes
Personally, I find symmetry in level design to be boring, and I don't think it's necessarily the case that it's needed for fair levels; symmetry is a way of ensuring that everybody has access to the same resources and the same bottlenecks by virtue of the level literally being mirrored for each player in some fashion. I think the important part is access to (roughly) the same advantages and disadvantages. Not so much the symmetry itself.

I also think that a game balanced such that all sides are of equivalent power and have equivalent opportunity is boring. You obviously don't want a total imbalance of those factors, but I think it can create an interesting play dynamic to offer each side slightly varying opportunities and roadblocks.

That's the sort of design context I'm thinking of as framing the actual answer to the question:

---

If the symmetry *really* matters to you, you can simply procedurally generate a chunk of level and then mirror that level across both axes. The chunk you generate is basically one quarter of the level and you mirror it so each quadrant is the same. For example, a procedural height map with randomly dispersed resource deposits:

But as I said above, that seems dull. A more interesting approach might be to generate the entire terrain procedurally, but when placing resources, make sure to constrain each quadrant to having the same number of each (within some tolerance to provide some variability). You may want to bias the placement of various resource types towards various areas (randomly, near the starting points, near the borders) based on the importance of the resources. For example:

You can perform analysis on the generated image to try to find feature edges -- narrow canyons, for example, which may be considered bottlenecks. You may decided to re-roll the terrain generation for a portion of the map if, for example, it has far more or far fewer bottlenecks or similarly detectable terrain features than others. You may also want to do similar terrain analysis to make sure each placed resource is, in some fashion, reachable.

For example, you may decide to re-roll the bottom-left quadrant because it has too much water (in red) or the quadrants containing the green because they are too tactically advantageous (potential canyon bottlenecks):

You can also opt to manually guide your feature generation; you can manually place certain elements, such as a river dividing the sections of the level or key resource deposits, and run the procedural generation afterwards such that it preserved the hand-placed key balancing features while still providing the interesting and organic variety you want out of procedural generation.

For example, a generated terrain that preserves a manually-placed river dividing the map in half and forested cover provided extra defense around the bases:

# Answer
> 7 votes
In some cases, it might be possible to rely on the players themselves to build balanced asymmetrical maps by using tile manipulation mechanics.

At one end of the spectrum, you can allow the players to create the map, either partially or entirely, by selecting & place map tiles. There are a bunch of different ways this could be tweaked:

* players select from a common deck of tiles
* layers select from a personal deck of tiles
* tiles are selected via a drafting phase
* some tiles might be fixed in advance via scenario (i.e. always spawns a bridged river across the middle of the map)
* players purchase tiles from a central market with some resource
* players may or may not be allowed to keep a hand of tiles

At the other end of the tile manipulation spectrum is allowing the players to manipulate map tiles. In this solution, the game start with an initial map. The initial map could be symmetric or might be 'fair enough' by using any of the other answers.

Next, a map manipulation phase occurs in which the players may do some of the following:

* rotate a tile
* swap tiles (adjacent or otherwise)
* mirror a tile
* push a row or column of tiles (tile that would fall off the edge wraps around)

These manipulations could be executed one at time, in which case one player would have a chance to react to another players manipulations, or the player might queue of a list of changes which get executed. Also, you could allow players to manipulate the entire map, or restrict things to their starting areas.

A drawback of this approach is it the final result needs to be guarded against undesirable outcomes - i.e. manipulating an impassible mountain range such that part of the map becomes inaccessible. Possible solutions for this drawback are:

* checking potential moves & disallowing ones that lead to illegal outcomes
* allowing all moves, but undoing anything that is illegal
* building the tiles so that no moves are illegal
* designing other game mecahnics (i.e movement) such that no moves are illegal

# Answer
> 2 votes
Have your map generation algorithm generate symmetric levels by generating a level, mirror it, and place each player on one side. A four-player map can be created by mirroring it on both the x- and y- axis.

That way the map will be equally good (or bad) for all players. A side-effect which you need to be aware of is that it means that the players are aware of the positions of the other players and of the layout of the other parts of the map after exploring their own.

Another option is to generate a map without this symmetry trick, but then show the whole map to the players and have each player pick their starting location freely.

# Answer
> 1 votes
One approach is to use other factors to balance the map. You might be able to automate this by using some map analysis algorithms & providing extra starting resources to locations that are deemed disadvantaged. Alternatively, you can use the players themselves for this step. A current example of this is the use of reverse auction in reveal mode in Offworld Trading Company (OTC) for founding your initial claim (i.e. picking a starting base location):

> As time ticks by, the starting debt for founding early goes down. This will eventually turn into starting money if it takes a long enough amount of time for the last 2 players to found. Once there is only one player left who hasn't founded their HQ, the values stop changing and that player no longer gains from waiting to found.

I don't recall if it was the 3 Moves Ahead or Game Design Round Table interview, but in one of them Soren Johnson (the developer) says this mechanic essentially changes the map problem from "can I find the best location first" into "how good is the 2nd best location on the map."

A benefit is this solution allows highly asymmetric maps. A disadvantage is that the entire map is revealed to all players, at least at the beginning. The OTC approach also reveals player base locations. Other mechanics like blind bidding, might avoid revealing base locations.

---
Tags: procedural-generation, level-design, rts, balance
---


# Question
Title: Should camera rotation be framerate independent?
I currently have my own custom first person controller, and the code to rotate the camera and controller based on the mouse position deltas looks like this:

```
public void ApplyRotation()
{
    this.transform.transform.Rotate(new Vector3(0, Input.GetAxis("Mouse X") * this.Sensitivity * Time.deltaTime, 0));
    this._VerticalRotation += Input.GetAxis("Mouse Y") * this.Sensitivity * Time.deltaTime;
    this._VerticalRotation = Mathf.Clamp(this._VerticalRotation, -85, 85);
    Camera.main.transform.eulerAngles = new Vector3(
        -this._VerticalRotation,
        Camera.main.transform.eulerAngles.y, Camera.main.transform.eulerAngles.z
    );
}

```

Right now, I'm using `Time.deltaTime` in the rotation code to keep the rotations framerate dependent, but I'm not sure if I should be doing this when I'm dealing with the mouse. Should I keep this framerate dependent, or should it be framerate independent?

# Answer
> 6 votes
Yes, you need to keep Time.deltaTime into account when you use Input.GetAxis, because the values it returns are also deltaTime-adjusted.

You can read this in the documentation:

> This is frame-rate independent; you do not need to be concerned about varying frame-rates when using this value.

The example code in the documentation makes it clear that multiplying by deltaTime is how it is supposed to be done:

```
 float translation = Input.GetAxis("Vertical") * speed;
 float rotation = Input.GetAxis("Horizontal") * rotationSpeed;
 translation *= Time.deltaTime;
 rotation *= Time.deltaTime;
 transform.Translate(0, 0, translation);
 transform.Rotate(0, rotation, 0);

```

It would be a different situation when you would use Input.mousePosition and compare the value to the previous value. The reason is that the mouse position changes are directly related to the physical distance the player moved their mouse across their desk between two frames. Higher update rate means you take more samples which means you measure smaller differences.

---
Tags: unity, timestep
---


# Question
Title: How can I encourage players to "talk to" to each other in team-based games?
With the goal of attracting a certain kind (highly sociable, that is) of players, I have wondered what game mechanics require, or at least encourage, players to *verbally* (I'm assuming an advanced text chat system, with team and private channels, maybe even chat-bots) communicate with each other, if they want to succeed as a team, or at least get the best possible results, within a game.

I'm interested in anything that requires discussion; before, during or after a "match".

If it matters, it would be (mostly) a team-vs-environment game, but also allow some tasks to be achieved by players alone (team is offline), or the occasional PvP/GvG (I'm bored with the grunts).

Getting team players to talk (rather than argue!) to each other increases their "closeness", and so plays an important role as a long-term "retention mechanism".

# Answer
A useful mechanic is to provide each player with only a part of the solution. This works especially well if certain classes can have information others don have. For example there could be a sort of "seer" class that can get information about the enemies that other players cannot. This means that the other players in order to succeed must have information from the seer. Another option is to require cooperation by making the game strategic, you can easily see that in a game like WoW players must first communicate who can "tank" and who can heal. This means that they communicate a bit before they attack and during the fight they might try to attack at the same time. What you should avoid if you want a lot of coordination is making action speak much louder then words, in team fortress for example it's often faster to inform your team mate that you are not a spy by shooting then by saying something, that means that players are not talking but taking actions (through that might not be so bad). Lastly it's important that the phasing is not so fast that the players cannot speak in (so if it required 2 seconds to get out a message in a fast fps then nobody is going to do it).

Another thing to to do is allow players to organize a form of groups/clans/alliances. If people are easily able to find the people they enjoyed working with again then they are likely to stick together in the future.

Additionally think about giving them items to trade with, this works especially well if certain items can only be used by certain classes, for example say we have a healer class who uses a healer staff. Let's say that this staff can be upgraded but doing so require a set of really hard to get items. These items drop at random time from all types of monsters. Of course now every player is going to find these items meaning that they can try to sell or trade them with the healers thus encouraging cooperation.

A last interesting mechanic I found a long time ago was where players would be able to "share" with others, sharing meant that they were giving a part of their xp to the players they were sharing with and meant informing the other player that that player had "fallen" meaning he was in dead and would require a healer to bring him back up. The healers were encouraged to do so because doing so would mean that players sharing with them would be quickly back on their feet giving them xp (this works well if your healer class is otherwise incapable of getting xp).
> 16 votes

# Answer
When you want players to chat with each other, you need to make sure that communication is rewarded and not punished.

When a player passes information via chat and as a result wins the game, this is a reward, and the player will communicate more often.

When a player passes information and they get nothing from it, they will not communicate this information anymore.

When a player tries to pass information via chat and gets killed while they are typing, they are punished for communicating and will avoid any communication in the future.

1. Give players a reason to communicate. Do not give all information to everyone and make sure that a team can only be successful when they share information with each other. Give the players the ability to do awesomely overpowered things, but make sure they only work when they convince others to cooperate with them.
2. Do not make your game so fast-paced that the players lose valuable seconds through communicating. Give them a few seconds now and then where they feel safe and have no other input to do, so they have time to chat without having a disadvantage.
3. Allow the player to still do stuff while they compose a chat message. Preferably they should be able to start typing, switch back to the normal game controls with an easy and intuitive action and return to the chat prompt without losing what they already typed.
> 12 votes

# Answer
As you express the desire to generate "closeness" I think it's important that the communication come with an emotional tone. Dry, business like communication, such as is promoted in tactical cooperation, doesn't always have the same method of generating closeness.

Consider how close you feel to colleagues at college/work and how that changes depending on how you interact and why you're interacting. Some people you only communicate with when things go wrong, some you only talk with around a water-cooler. Some you write;

> "Hey, mate. The latest patch doesn't quite work. You got time to chat?"

and some you write

> "The latest round of testing has brought some issues to light with the current patch. I have arranged a meeting for 12, please attend if possible."

There is also a requirement here to avoid alienation - this may come through putting certain players above others in any form of hierarchy. This may be structural, in that the game may require a team leader to make decisions etc, but it could also be the result of allowing player skills and equipment to become unbalanced within the game.

It is also worth considering the atmosphere and setting you are putting the players in. Often the tone of conversation follows on from the tone of the game. A light hearted game often breads light hearted conversation, while cold, serious tactical games often yield cold and serious communication.

Due to these reasons I think some of the simplest ways are;

* Provide interesting things to find that players may want to show their fellow players. Often this can be accomplished through hidden areas/items, unique gear and unique set pieces. The keywords here really are "unique" and "hidden".
* Allowing user generated content. It is often the case that players like to brag or show off. This can be alienating in a competitive sense (consider team play games where players can be ranked by performance) but with games like minecraft this alienation is mitigated (some jealousy and resentment can still occur).
    + Content generated as a team helps even more - working together on a project. This can also be the case in cooperative strategy or campaigns although the thing created as a team is a victory.
* Cause unique emotional reactions. By this I really mean, surprise the player. A reaction "OMG" from one player often gets the secondary reaction of "What?" from another who wasn't in the same location and therefore ins't aware what happened. These kind of moments can help break the ice as well as give players something to reminisce about afterwards.
* Give players breathing room in the game. Allow for breaks to discuss and chat. Games like borderlands have this by giving you room to chat about the last battle before the next begins and tactical discussion is often provoked during levelling up, trading gear, picking a mission and shopping.
> 5 votes

# Answer
In order to get players to communicate with each others, we must first understand ***why players communicate in the first place***.

People do not communicate for fun**1**, they communicate to share information. And here we have reached the essence of the problem, **information**. Players are much more likely to communicate when information is necessary to progress.

Information comes in many forms.
**In MMOs** it can take the form of planning and efficiency, when a dungeon is so difficult it requires good cooperation and coordination, which cannot be achieved without sharing information.
**In puzzle games** it can take the form of a puzzle's partial solution, where each player only sees a part of the puzzle and need to synchronize with each other in order to solve it.
**In shooter** it can take the form of troop positioning and movement, or maybe even tasks and objectives. What if only the leader knows what to do and where to go?

Getting players to communicate is much easier in a PvE game, than in a PvP one, why?
Because the CPU is always going to have the same difficulty within the same configuration, whereas a team consisting of human players is most likely going to be made of random people, basically a bunch of lone wolves; if they had strong players, the next team might have weaker ones.

Once the players have been conditioned to communicate in PvE, they will be more likely to communicate in PvP as well.
\__

So much for the design aspect of the problem, but what about the technical one?

There isn't much an engineer can do, but to ensure the interface is as comfortable and practical as possible. For the sake of argument, we will assume our game is a fast paced one.

Obviously, having an easy-to-use voice chat system is going to be very important in situations where people need to convey a lot of information in a short amount of time, or even in the heat of the battle. So let's talk about what we can do with the text chat system, for people who refuse to, or simply can't speak.

1. A speech-to-text system would definitely benefit those who don't want to talk, but is expensive and difficult to implement properly, plus it would only benefit a very small part of your target audience; how many "sociable" players refuse to let others hear their voices anyways? However, speech-to-text does convey benefits that are hard to ignore, such as the ability for people to re-read what you were saying earlier.
2. The game must remain more-or-less playable while chatting. Nothing is more frustrating than typing, then suddenly having to take cover; "*enemy approaching from sdddddddddddddddddddd*".
3. Allow the player to say more with less, for instance using predictive text entry. A long string like: "*enemy approaching from South*" can be as short and easy as typing "*e a f s*" or "*en ap from s*".

\__

To summarize:

Make sharing information a necessity**2**.

Make sharing information as easy and comfortable as possible.

---

**1**: Actually, they do, but since that is not something a game dev can influence very well, we are simply going to assume that humanity is anti-social :p

**2**: This can be done by making the game too hard for a group of lone wolves to solve.
> 4 votes

# Answer
I want to point out a system that existed in one of my favorite shooter games, Battlefield 2142. Now, there's a lot of cross-over between BF 2142 and BF 2, so a lot of this applies to both, but I'll focus on BF 2142.

Battlefield, overall, had a system called the "Comma Rose", which, simply put, was a 'rose' of commands you could pop up on-screen, select an option, and your character would speak it for you(and put it in chat). If I remember correctly, you could hit 'Q' for your player rose, and 'T' for your squad leader/commander rose. Most commonly, people would use their player rose to say things like "Thank you!". In fact, when the rose was removed(I believe in BF3), the community raised a huge stink about not being able to thank people anymore. I want to repeat that: *The community was upset about not being able to be gracious to fellow players!* I can't remember off the top of my head everything that was on the 'Q' rose, but after using it for a while, you get used to it and for many people using it was second nature.

The 'T' squad leader/commander rose was far more useful. As a squad leader, you could hit 'T' to bring up the rose, and then left click to put a waypoint on the thing you're looking at. Which meant you could give commands to your squad members without taking your hand off your mouse to type, and you could do it while running their too! Commanders could do the same thing with way points, and they also had the ability to use their assets. Their assets included:

* A supply drop(magical ammo crate + vehicle repair box),
* orbital strike(AoE damage),
* EMP(AoE technology disabler),
* SAT-Track(Reveal all enemy units for commander on the entire map - the intent being that the commander relays that information to his team by 'Spotting' them, another feature entirely),
* and UAV(reveal all enemies within a certain radius, and show it to all team members)

The `T` comma rose gave commanders access to all five of those without ever taking their hands off the mouse. I could be piloting a walker(bi-ped armored vehicle) as a commander, drop a supply crate to repair me and offer cover to allies in a street, pop a UAV to reveal nearby enemy positions, and call orbital strikes to kill enemies, prevent movements, etc, and I could do that in mere *fractions of a second*, while losing almost no ability to pilot the walker I was in. At the same time, I could be issuing commands to my squad leaders, and as soon as they accept the order, it would show up on their squad member's screens and give them a goal to strive towards.

I can't possibly praise this system enough. It's a shame it was swept under the rug without becoming more mainstream across more game genres. You have the ability to communicate between teammates, squad-mates, and even up and down command hierarchies. I could write a book on all of the benefits I gained from using the comma rose in Battlefield - it offered complex rewards and it was *so ridiculously simple to use!*

In the end, and other answers have touched on this as well, what you want to do is allow players to communicate without just giving them a text chat. Typing text is expensive to any player. They have to take a hand off their mouse, find their bearings on the keyboard, and then move their hand back to the mouse. That is an expensive set of operations in a time-sensitive situation.
> 3 votes

# Answer
**Require players to coordinate different tasks at the same time** in order to encourage them to communicate.

For example, let's say you want players to kill two bosses in order to open a gate to continue.

The first team just has to kill boss A and then kill boss B on a linear path to open the gate. That team probably won't have to communicate in order to achieve that, unless those bosses have certain mechanics that require coordination.

The second team has to split up and kill boss A and boss B within 10 seconds of each other to open the gate. This team is much more likely to communicate because they have to decide who is fighting which boss and make sure they don't kill one of the bosses too soon.
> 1 votes

# Answer
If players could benefit greatly from "closeness" in xp they are more likely to want it. An example would be allowing players to preform powerful combo attacks (that require two classes).. for instance one player has a long recharge "spill slippery oil on the ground" attack that makes monsters slip and fall while another has a magical fire arrow attack. Combine the two and get a fire pit but only if timing is right. If players need to time their moves to get better xp, they will need to plan and talk first.

Another example would be monsters that have a strong aoe buff and therefore are far more powerful when they are together.. The players would need to lure the monsters in different directions (divide and conquer).
> 1 votes

# Answer
You'd have a much easier time just having the characters in the game talk to each other automatically, which would have mostly the same effect.
> 0 votes

---
Tags: game-mechanics, teamwork
---


# Question
Title: Should I check all the collisions in the game world?
I'm developing a 2D game engine and right now I'm designing the collision system.

I've read about space partitioning and quad trees, and I understand that only the objects that are in the user's view need to be drawn and checked for collision.

All the objects, regardless whether or not whether are in the user's view, need to updated, but what's happen if an object out off the user's view collide with another object? I mean:

*Should I check all the collisions in game world,* even if the objects are not in view?

# Answer
Generally game mechanics should not behave differently depending on whether or not the player observes the event. The player expects that the game mechanics outside of their field of view behave exactly as those inside their field of view. It is very immersion-breaking when they leave an area, enter it again shortly afterwards and apparently in the mean-time something happened which actually shouldn't have been possible according to their understanding of the game's collision rules.

However, for larger game worlds it can sometimes be too performance-intense to do so. There are different methods to deal with this:

* Freeze the game world in areas where the player is not present. This includes updating. Continue the simulation where you left off when the player comes closer again.
* Discard the state when the player leaves and initialize it as if they had never been there when the player enters again (a lazy but actually very common solution)
* Simulate far-away areas with a simplified model of your game mechanics which is less accurate but still results in the things happening as the player would expect them to happen.
> 4 votes

---
Tags: collision-detection, spatial-partitioning
---


# Question
Title: How can I make my character 'flip' in Game Maker?
I want my character to 'flip' or 'mirror' when I press 'A' or 'S'. Thing is, I've placed the origin everywhere on the character and he seems to only face one direction.

Video showing what I see: https://www.youtube.com/watch?v=1zZEDpO0yAM&feature=youtu.be

(This video shows the character not 'mirroring' or 'flipping' properly.)

I have done hours of research into this, and I get the same results: "Make sure the sprite has the center origin."

How would I accomplish this?

# Answer
That's pretty simple if you think about it. All you have to do is scale the sprite using a negative factor, which in the end will cause sides to mirror around it's origin.

So all you have to do is assigning a negative scale using `image_xscale`:

```
image_xscale = -1;

```

The documentation page for `image_xscale` actually shows you an example with different scaling factors.
> 1 votes

---
Tags: sprites, game-maker
---


title: Transparency issues Unity5

text:
# Question
Title: Transparency issues Unity5
I made a potion that displayed and rendered perfectly in 3DS max. When I imported it to Unity it didn’t render correctly as the transparency was all over the place. I first imported it with a png texture with a separate png map for the alphas. I then tried using a .tga and a .psd file with alpha channels set up within the file but I got the same issues happen with both file formats. Does anyone know how to fix this I cannot seem to work it out.

# Answer
It may be a case of backface culling. The back of the textured thingy also may not be showing because the liquid inside is also zclipping the back side of it.
> 1 votes

# Answer
Change the Alpha value in color swatch for water material.

Keep the cork in opaque but potion and jar in transparent rendering mode. Give them different alpha value.
> 0 votes

---
Tags: unity
---


title: Saving with PlayerPref problems

text:
# Question
Title: Saving with PlayerPref problems
I'm having troubles saving how much of an item I have in my game. Right now I have it so the price goes up the more items you buy, that works, but every time I reset the game, the count goes back to 0, while the price acts as if the count is at a higher number.

```
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class ItemManager : MonoBehaviour {

public UnityEngine.UI.Text itemInfo;
public GPS gps;
public Click click;
public float cost;
public int tickValue;
public int count = 0;
public string itemName;
private float baseCost;
private Slider _slider;

void Start()
{

    Load ();
    baseCost = cost;
    _slider = GetComponentInChildren<Slider> ();
}

void Update()
{
    PlayerPrefs.SetFloat ("Count", count);
    PlayerPrefs.SetFloat ("Cost", cost);

    itemInfo.text = itemName + " (" + count + ") " + "\nCost: " + cost + "\nGold: " + tickValue + "/s";

    _slider.value = click.gold / cost * 100;

    if (_slider.value >= 100) {
        GetComponent<Image> ().color = buyColor;
    }else{
        GetComponent<Image>().color = standard;
    }
}

public void BuyItem()
{
    if (click.gold >= cost)
    {
        click.gold -= cost;
        count += 1;
        cost = Mathf.Round (baseCost + Mathf.Pow (2f, count));
    }
}

public void Load()
{
    count = PlayerPrefs.GetInt ("Count");
    cost = PlayerPrefs.GetFloat ("Cost");
}
}

```

I've tried to figure this our for hours, and I just don't know what to do with this.

# Answer
> 1 votes
I'm not seeing you use PlayerPrefs.Save (); which is how you save the values so they are kept when the application is closed.

# Answer
> 0 votes
Make sure you are consistent with which GetInt or GetFloat you are using, on Public void load you are using GetInt for "Count", but in Update you are using SetFloat for both.

# Answer
> -1 votes
As saboehnke said, you need to save the informations if you want it after reset the game. To do this, simple add PlayerPrefs.Save () after you set something as a PlayerPrefs. But remember: if you want to save a resonable amount of information, consider use XML.

---
Tags: c#
---


# Question
Title: How to use touch screen for movement instead of keyboard narrow keys
I wrote this code and run the game on my desktop, now I need to build this game for android and I need to change to touch to move the player, what it should be changed in the following code and what is the necessary steps to build my desktop 2D game to be run on android device, the following is the player code:

```
#pragma strict

var speed : int = 5;

function Start () {
}

function Update () {

  if(Input.GetAxis("Horizontal") >0){

    if(collided_with != null) {
      if(collided_with.tag== "Right") {
        //collided_with=null;
        return;
      }
    }
    transform.Translate(Vector3(Input.GetAxis("Horizontal")*speed*Time.deltaTime,0,0));
  }

  if(Input.GetAxis("Horizontal") <0) {
    if(collided_with != null) {
      if(collided_with.tag == "Left"){
        // collided_with=null;
        return;
      }
    }
    transform.Translate(Vector3(Input.GetAxis("Horizontal")*speed*Time.deltaTime,0,0));
  }
}

```

# Answer
> 2 votes
Touchscreen devices do not have keys, so you need to think about another input method.

A quick and dirty solution to adapt a game designed to be controlled with directional keys to a touch device is to use a "virtual keypad". Use the Unity UI system to create four buttons on the screen the player can tab on, and bind each to an appropriate function which moves the player-character. But this is an obvious crutch which shows that the game was clearly not designed with touchscreens in mind.

A better solution would be to reconceptualize the game input to tilting the device, touch and/or swipe gestures, but there is no canonical solution for this because different kinds of input actions are suitable for different kinds of games and the choices you make here greatly affect the player experience.

# Answer
> 0 votes
Unity has a separate function for touch screen devices. Here' the code. Note that functions MoveLeft() and MoveRight() are exaggerated, so you need to replace them with your own.

C# Code:

```
function Update ()
{
     for (int i = 0; i < Input.touchCount; i++)
     {
         Touch touch = Input.GetTouch(i);

         if (touch.phase == TouchPhase.Began)
         {
            if (touch.position.x > (Screen.width/2))
            {
                MoveRight(); //moves player right
            }

            if (touch.position.x < (Screen.width/2))
            {
                MoveLeft(); //moves player left
            }
         }
     }
 }

```

JavaScript Code:

```
function Update()
{
    for (var i = 0; i < Input.touchCount; i++)
    {
        var touch : Touch = Input.GetTouch(i);

        if (touch.phase == TouchPhase.Began)
        {
            if (touch.position.x > (Screen.width/2))
            {
                MoveRight(); //moves player right
            }

            if (touch.position.x < (Screen.width/2))
            {
                MoveLeft(); //moves player left
            }
        }
    }
}

```

The main problem with such method is that player won't be able to have a control over how fast he moves left and right since everything is determined by a screen touch. So, normally, you would need to re-do alter game mechanics a bit to adapt to such changes.

In order to implement such feature, you'll have to get rid of Input.GetHorizontal() and Input.GetVertical() methods, as they'll always return 0 on mobile devices. So, in your case, if you want to make your character move to the left, it could be something like this:

```
transform.Translate(speed*Time.deltaTime,0,0);
//replace 'MoveLeft()' with this line of code

```

This can be avoided by using an on-screen joystick, but they won't work well with users using small-screen touch devices. So, unless you're targeting tablet devices, you're in trouble.

This shouldn't conflict with your Desktop build, but if you want to ensure that the code would never run on anything other than mobile devices, you can make a use of platform dependent compilation technique.

Hope this solves your underline problem!

---
Tags: unity, 2d, android, unityscript
---


# Question
Title: World Space canvas rendering in front of line mesh
I'm attempting to attach a pointer to my steamvr controller to simplify world interactions. I'm very new to unity, but found a nice volumetric line asset (VolumetricLines) that aesthetically is exactly what I want. However, it seems to be rendering behind my canvas, as you can see here:

The canvas is set to world space with the event camera set to the VR camera, and renders properly for all world objects except this line. The line also renders properly with all objects except this canvas.

What exactly is the mechanic that causes the line to render behind the canvas, when it renders in front of other game objects, and what could I do to fix the render order?

# Answer
Change the order in layer on the canvas to -1.
> 0 votes

---
Tags: unity, rendering, htc-vive
---


# Question
Title: How to convert -1 to 1 coordinate back to screen coordinates?
Here is a question in which Questioner asks how to convert world coordinates to 1 to -1 coordinates like Opengl, I want to know how to do that in reverse, that given a coordinates between 1 and -1 (both x and y axis), how can i change it back to screen coordinates. i.e if my width and height is 1000, and given a coordinate (0,0), how can i change it to 500, 500, So that i can render it.

# Answer
For this problem specifically:

```
screenX = ((glX + 1) / 2.0) * maxScreenX;
screenY = ((glY + 1) / 2.0) * maxScreenY;

```

In general, the solution for going from coordinate system A to coordinate system B is: $$ B = \frac{A - min\_A}{max\_A - min\_A} (max\_B - min\_B) + min\_B $$ or as pseudocode:

```
B = ((A - minA) / (maxA - minA)) * (maxB - minB) + minB;

```

For example substituting into your example with \\$B\\$ representing `screenX` and \\$A\\$ representing `glX`, we'd get:

$$ \begin{align} \text{screenX} &= \frac{\text{glX} - \text{minGlX}} {\text{maxGlX} - \text{minGlX}} (\text{maxScreenX} - \text{minScreenX}) + \text{minScreenX} \\ \text{screenX} &= \frac{\text{glX} - -1}{1 - -1}(1000 - 0) + 0 \\ \text{screenX} &= \frac{\text{glX} + 1}{2}1000 \end{align} $$ or as pseudocode:

```
screenX = ((glX - minGlX) / (maxGlX - minGlX)) * (maxScreenX - minScreenX) + minScreenX;
screenX = ((glX - -1) / (1 - -1)) * (1000 - 0) + 0;
screenX = ((glX + 1) / 2) * 1000;

```
> 5 votes

---
Tags: mathematics, matrix
---


title: midpoint displacement algorithm in sdl

text:
# Question
Title: midpoint displacement algorithm in sdl
I am trying to implement moving random hills in SDL. I am using midpoint displacement algorithm to create some random terrain and I have also accomplished to move the terrain too. But the problem is that the terrain repeats itself after certain period of time. Why is that exactly happening and how to rectify it. Here is my source code.

```
#include <SDL2/SDL.h>
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
SDL_Window* gWindow = NULL;
SDL_Renderer* gRenderer = NULL;
int arr_size = pow(2.0,11.0) + 1;
int terrain_array[10000];
float roughness = 0.5;
int intial_displacement = 150;
int count = 0;
bool init()
{
    bool success = true;
    if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
    {
        cout << "SDL could not initialize. SDL_Error: " << SDL_GetError() << endl;
        success = false;
    }
    else
    {
        if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" ) )
        {
            cout << "Linear texture filtering not enabled.\n";
        }
        gWindow = SDL_CreateWindow( "Midpoint_Displacement_Algortihm", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
        if( gWindow == NULL )
        {
            cout << "Window could not be created. SDL_Error: " << SDL_GetError() << endl;
            success = false;
        }
        else
        {
            gRenderer = SDL_CreateRenderer( gWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC );
            if( gRenderer == NULL )
            {
                cout << "Renderer could not be created. SDL_Error: " << SDL_GetError() << endl;
                success = false;
            }
            else
            {
                SDL_SetRenderDrawColor( gRenderer, 96, 96, 96, 96 );
            }
        }
    }
    return success;
}
void close()
{
    SDL_DestroyRenderer( gRenderer );
    SDL_DestroyWindow( gWindow );
    gWindow = NULL;
    gRenderer = NULL;
    SDL_Quit();
}
void initializeArray()
{
    for(int i = 0; i < arr_size; i++)
    {
        terrain_array[i] = 0;
    }
}
void generateTerrain(int leftindex, int rightindex, int displacement)
{
    if((leftindex + 1) == rightindex)
        return;
    int midindex = floor((leftindex + rightindex) / 2);
    int change = ((rand()%1) * 5 - 1) * displacement;
    terrain_array[midindex] = (terrain_array[leftindex] + terrain_array[rightindex]) / 2 + change;
    displacement = displacement * roughness;
    generateTerrain(leftindex, midindex, displacement);
    generateTerrain(midindex, rightindex, displacement);
}
void drawTerrain()
{
    int start_point = 1;
    int i;
    SDL_SetRenderDrawColor( gRenderer, 96, 96, 255, 255 );
    for(i = 1; i < arr_size; i++)
    {
        SDL_RenderDrawLine( gRenderer, start_point, SCREEN_HEIGHT, i, (terrain_array[(count + i)%arr_size] + 3 * intial_displacement));
        start_point = i;
    }
    count++;
}
int main()
{
    initializeArray();
    if( !init() )
    {
        cout << "Failed to initialize\n";
    }
    else
    {
        bool quit = false;
        SDL_Event event;
        while( !quit )
        {
            while( SDL_PollEvent( &event ) != 0)
            {
                if( event.type == SDL_QUIT )
                {
                    quit = true;
                }
            }
            generateTerrain(0, arr_size - 1, intial_displacement);
            SDL_SetRenderDrawColor( gRenderer, 96, 96, 96, 96 );
            SDL_RenderClear( gRenderer );
            drawTerrain();
            SDL_RenderPresent( gRenderer );
        }
    }
    close();
    return 0;
}

```

I am new to this stuff and trying to learn. This is what it looks like.

# Answer
> 1 votes
You are generating a random number incorrectly.

```
int change = ((rand()%1) * 5 - 1) * displacement;

```

Change will always be (-1 * displacement), because anything modulus 1 is always zero.

Try this for a range of \[-5, 5\]:

```
//rand() % 11 returns range [0, 10], subtract 5 makes range [-5, 5]
int change = ((rand() % 11) - 5) * displacement;

```

I also recommend you seed rand with the system time. Otherwise the application will generate the same terrain every time (though this behavior is often useful for testing):

```
#include <time.h>

//Call this once at program start, before the first call to rand()
srand(time(NULL));

```

http://www.cplusplus.com/reference/cstdlib/rand/

---
Tags: c++, algorithm, sdl2
---


# Question
Title: What revenue cuts will I take by using Unity combined with Facebook's platform?
Basically me and a friend want to develop a Facebook game by using Unity. What I wanted to know is *if* we do earn any money on it, how would we be required to use the profits of said money? I remember reading that Unity requires you to pay royalty (or something like that) after having earned a certain amount of money from your product.

What confuses me is where Facebook would enter the equation? I can't seem to find any sources on royalty on such from FB-based games.

Does anyone have any sources covering FB-games made in Unity on how it all comes together?

# Answer
> 7 votes
I am not a lawyer, and interpreting legal documents can be tricky. When in doubt you should always consult a lawyer about your specific scenarios.

That said, these things are usually covered in the EULAs for the software or services in question. They are generally completely independent of eachother.

Unity's EULA is here. The relevant two passages are:

> a Commercial Entity that has either: (a) reached annual gross revenues in excess of US$100,000, or (b) raised funds (including but not limited to crowdfunding) in excess of US$100,000, in each case during the most recently completed fiscal year;

and

> an individual (not acting on behalf of a Legal Entity) or a Sole Proprietor that has reached annual gross revenues in excess of US$100,000 from its use of the Unity Software during the most recently completed fiscal year, which does not include any income earned by that individual which is unrelated to its use of the Unity Software.

These are describing the conditions under which you *cannot* use Unity Personal any longer. Basically, once you make $100,000 in annual gross revenue, or get external funding (from investors, Kickstarter, et cetera) for an equivalent amount, you must purchase a Unity Pro license.

Facebook's platform policy is here. You may publish to it and use its APIs for free, although you read that entire document and be aware of what you're exchanging for "free" (especially the parts about how they can analyze your app and traffic for any purposes, et cetera). They do not promise the platform will always be free:

> 10. We don’t guarantee that Platform will always be free.

You also have API limits you have to confine yourself to:

> 11. If you exceed 5M MAU, 100M API calls per day, or 50M impressions per day, you may be subject to additional terms.

These terms are not spelled out; that usually means that if you exceed these limits, a representative from Facebook will contact you and you will have to work out a private legal agreement between the two of you that defines you terms (including any payments you may need to make) in terms of your API usage volume.

You're probably not going to hit those limitations at this point in your career, so usage of the platform is effectively free, *unless* you are using their payments APIs (for e.g., microtransactions). Those are a separate service, and using them involves a 30% cut that Facebook reserves for itself.

Other than that, you are free to use your revenue however you see fit; it's yours.

# Answer
> 2 votes
Taken from Facebook's Payment Terms:

> Whenever you complete a sale on our platform, Facebook will credit the proceeds from that sale, less our service fee, to your Developer Balance. Facebook will earn a 30% service fee, plus any applicable sales tax or VAT, in connection with each Facebook Payments transaction on our platform.

---
Tags: unity, facebook
---


# Question
Title: How to animate material change to get a status bard effect, in unity
Imagine a long cube, like a bar, that has a dark material, and you want to animate changing its material to a light material, but do it gradually from one end to the other, like filling up a tube, or like a progress bar that fills from one end to the other.
Is there a way to achieve this in Unity?
Or do you need to generate the animations in Blender or similar and control them in unity?

# Answer
Hey what you can do is make a large texture with half dark and another smooth transition to bright, then zoom up on the dark area and simply change the horizontal (x) offset to gradually move in the bright part of the texture, this method should be pretty simple and effective as well as easy to do vie script.
> 1 votes

---
Tags: unity, animation, materials
---


# Question
Title: Moving a character to a point without any floating point operations
So I'm writing an adventure game for MSDOS, just a fun challenge for me. I'm trying to get the character to walk along a straight line to his destination (either the next navMesh node or where you clicked). Normally I would simply store the characters x,y as floats and add the direction vector to it for each move, the problem is that cpus before the 486 didn't have FPUs at all so floats are out of the question. So naturally I thought about Bressenham's line algorithm which can be done using all ints. Taking inspiration I came up with this function here which runs every frame:

```
void character::doWalk()
{
    int x_diff = destination.x - x;
    int y_diff = destination.y - y;

    int x_dist = abs(x_diff);
    int y_dist = abs(y_diff);

    int walk_x_dir = x_diff > 0 ? 1 : (x_diff < 0 ? -1 : 0);
    int walk_y_dir = y_diff > 0 ? 1 : (y_diff < 0 ? -1 : 0);

    if(y_dist >= x_dist || yerror > 0)
    {
        y += walk_y_dir;

        yerror -= path_dist_x;
    }
    else
    {
        yerror += path_dist_y;
    }

    if(x_dist >= y_dist || xerror > 0)
    {
        x += walk_x_dir;

        xerror -= path_dist_y;
    }
    else
    {
        xerror += path_dist_x;
    }
}

```

path\_dist\_y is the vertical distance calculated when the character begins walking path\_dist\_x is the horizontal distance.

This algorithm almost works, it seems that he begins walking at an angle just too shallow to get to the point correctly and he has to change direction near the end of his walk to make it to the point. Any idea what else I could try?

# Answer
In Ye olden days we used to use the bottom 16 bits of a long as the fraction part.

```
struct HiLo
{
public:
    unsigned short m_lo;
    unsigned short m_hi;
};

union LongFraction
{
public:
    LongFraction()
    {
        m_all = 0;
    }
    HiLo m_hilo;
    unsigned long m_all;
};

```

Then 0-65535 becomes the fraction part.

```
LongFraction pos;

pos.m_all += 32768; //32768 is 0.5
pos.m_all += 32768; //32768 is 0.5

short x = pos.m_hilo.m_hi;  // this will be 1

```

Endian-ness would probably require reordering the elements in the HiLo struct.
> 1 votes

# Answer
You could try doing all relevant calculations on numbers multiplied by e.g. 1000 and then divide/round by 1000 before display.

So if your source and destination are `(16;44)` and `(85;140)` you could make the walk logic move say between `(16000;44000)` and `(85000;140000)`, then on display - convert back tox1 scale. Of course if you are limited to `WORD`s - multiply by something that stays within `WORD`s bounds.
> 0 votes

---
Tags: c++, movement
---


# Question
Title: Creating colour spectrum by light flux values
I am using radiosity method to compute the inter-reflected light within a room. The room is gridded into small patches and the light flux in lumen is calculated for each. This part is done. Now I want to change the colour of each patch so that the room surfaces show a continuous colour banding contours like this image, but have no clue how to this.

**Update:**

Here is a sample data for a room surface. The data is in this format: (x, y): value

# Answer
Here is a little help on getting you started with this rendering. This may not be the best way to accomplish this task however, it should work.

First I created a structure to hold your data for parsing from text file:

```
public struct Data {

    public Data(float x, float y, float value){
        X = x;
        Y = y;
        Value = value;
    }

    public float Value;
    public float X;
    public float Y;
}

```

I then initialized the color palette based on your above image (reversed because I messed up the ordering initially):

```
Color[] Colors;

private void InitColors()
{
    Colors = new Color[20];

    Colors [19] = new Color (230 / 255f, 29 / 255f, 0 / 255f, 1);
    Colors [18] = new Color (230 / 255f, 74 / 255f, 0 / 255f, 1);
    Colors [17] = new Color (230 / 255f, 119 / 255f, 0 / 255f, 1);
    Colors [16] = new Color (230 / 255f, 164 / 255f, 0 / 255f, 1);
    Colors [15] = new Color (230 / 255f, 207 / 255f, 0 / 255f, 1);
    Colors [14] = new Color (185 / 255f, 207 / 255f, 0 / 255f, 1);
    Colors [13] = new Color (140 / 255f, 207 / 255f, 0 / 255f, 1);
    Colors [12] = new Color (94 / 255f, 207 / 255f, 0 / 255f, 1);
    Colors [11] = new Color (49 / 255f, 207 / 255f, 23 / 255f, 1);
    Colors [10] = new Color (3 / 255f, 207 / 255f, 73 / 255f, 1);
    Colors [9] = new Color (0 / 255f, 207 / 255f, 173 / 255f, 1);
    Colors [8] = new Color (0 / 255f, 198 / 255f, 223 / 255f, 1);
    Colors [7] = new Color (0 / 255f, 153 / 255f,  230 / 255f, 1);
    Colors [6] = new Color (0 / 255f, 108 / 255f, 230 / 255f, 1);
    Colors [5] = new Color (0 / 255f, 63 / 255f, 230 / 255f, 1);
    Colors [4] = new Color (37 / 255f, 18 / 255f, 230 / 255f, 1);
    Colors [3] = new Color (82 / 255f, 0 / 255f, 230 / 255f, 1);
    Colors [2] = new Color (128 / 255f, 0 / 255f, 230 / 255f, 1);
    Colors [1] = new Color (173 / 255f, 0 / 255f, 230 / 255f, 1);
    Colors [0] = new Color (219 / 255f, 1 / 255f, 230 / 255f, 1);
}

```

I then wrote a parsing function to get the data from your text file into memory, and analyze parts of the data for future use:

```
private HashSet<float> XValues;
private HashSet<float> YValues;

private List<Data> DataList;

private float Min, MinX, MinY;
private float Max, MaxX, MaxY;

private void ParseData()
{
    Min = float.MaxValue;
    Max = float.MinValue;
    MinX = float.MaxValue;
    MaxX = float.MinValue;
    MinY = float.MaxValue;
    MaxY = float.MinValue;

    DataList = new List<Data> ();
    XValues = new HashSet<float> ();
    YValues = new HashSet<float> ();

    if (File.Exists ("data.txt")) {

        StreamReader file = new StreamReader ("data.txt");
        string line = "";

        while ((line = file.ReadLine ()) != null) {

            line = line.Replace("(", string.Empty);
            line = line.Replace(")", string.Empty);
            line = line.Replace(":", ",");
            string[] split = line.Split (',');

            float x = System.Convert.ToSingle(split [0]);
            float y =  System.Convert.ToSingle(split [1]);
            float value =  System.Convert.ToSingle(split [2]);

            Data data = new Data (x, y, value);

            Min = Mathf.Min (Min, value);
            Max = Mathf.Max (Max, value);
            MinX = Mathf.Min (MinX, x);
            MaxX = Mathf.Max (MaxX, x);
            MinY = Mathf.Min (MinY, y);
            MaxY = Mathf.Max (MaxY, y);

            XValues.Add (x);
            YValues.Add (y);

            DataList.Add (data);
        }

        file.Close ();
    }
}

```

Now it is easy to convert the parsed data into a Dataset that we can use:

```
private Data[,] Data;

private void GenerateDataSet()
{
    Data = new Data[XValues.Count, YValues.Count];

    for (int x = 0; x < XValues.Count; x++) {
        for (int y = 0; y < YValues.Count; y++) {
            Data [x, y] = DataList [x + y * XValues.Count];
        }
    }
}

```

If we visualize this data now, we get the following:

In order to smooth this out, we are going to add values in between and interpolate based on the distance between known node values:

```
float[,] Interpolated;

private void Interpolate()
{
    int steps = 25;

    Interpolated = new float[Data.GetLength (0) * steps, Data.GetLength (1) * steps];

    for (int y = 0; y < Interpolated.GetLength (1) - steps; y++) {

        for (int x = 0; x < Interpolated.GetLength (0) - steps; x++) {

            int x1 = x / steps;
            int x2 = x1 + 1;
            int y1 = y / steps;
            int y2 = y1 + 1;

            float distance1 = (new Vector2 (x, y) - new Vector2 (x1 * steps, y1 * steps)).magnitude;
            float distance2 = (new Vector2 (x, y) - new Vector2 (x1 * steps, y2 * steps)).magnitude;
            float distance3 = (new Vector2 (x, y) - new Vector2 (x2 * steps, y1 * steps)).magnitude;
            float distance4 = (new Vector2 (x, y) - new Vector2 (x2 * steps, y2 * steps)).magnitude;

            float value1 = Data [x1, y1].Value;
            float value2 = Data [x1, y2].Value;
            float value3 = Data [x2, y1].Value;
            float value4 = Data [x2, y2].Value;

            int totalCount = 0;

            int count = steps - (int)distance1;
            count = Mathf.Max (count, 0);
            float total = value1 * count;
            totalCount += count;

            count = steps - (int)distance2;
            count = Mathf.Max (count, 0);
            total += value2 * count;
            totalCount += count;

            count = steps - (int)distance3;
            count = Mathf.Max (count, 0);
            total += value3 * count;
            totalCount += count;

            count = steps - (int)distance4;
            count = Mathf.Max (count, 0);
            total += value4 * count;
            totalCount += count;

            total = total / (float)totalCount;

            Interpolated [x, y] = total;
        }
    }
}

```

Now if we draw this interpolated data, we get something that looks a lot more like what you are trying to output. Here is the Texture generation code that was used:

```
public Texture2D GetHeatMapTexture()
{
    int width = Interpolated.GetLength (0);
    int height = Interpolated.GetLength (1);

    var texture = new Texture2D (width, height);
    var pixels = new Color[width * height];

    for (var x = 0; x < width; x++)
    {
        for (var y = 0; y < height; y++)
        {
            float value = Interpolated [x,y];

            float normalized = (value - Min) / (Max - Min);
            normalized *= Colors.Length;
            int colorValue = (int)normalized;
            colorValue = Mathf.Clamp (colorValue, 0, 19);

            pixels [x + y * width] = Colors [colorValue];
        }
    }

    texture.SetPixels(pixels);
    texture.wrapMode = TextureWrapMode.Clamp;
    texture.filterMode = FilterMode.Point;
    texture.Apply();
    return texture;
}

```

And here is what it looks like with your provided dataset:

There are probably better ways to accomplish this result, but at least this can provide you with a way to at least get started doing what it is you are trying to do.
> 5 votes

---
Tags: color, radiosity, srgb
---


title: How to determine a "Hit\miss" system?

text:
# Question
Title: How to determine a "Hit\miss" system?
I always try to fix my problems on my own, but i've reached a point where my mind is stuck so i trust myself in your hands, if you're willing to help and have the time.

I'm starting to make a RPG system, and I find myself struggling at the first formula: How can I determine if a character hits or miss?

Let me explain; the matter is not so simple, or i would have done it already, but what I don't understand are lots of things, and i'll show you:

Character's BaseHit is called "Precision", and it is calculated with this formula=

```
Pre.=MeleeHitAbility + MeleeWeaponHit x WeaponCharacterAbility

```

And as you can see it's pretty elementary, but now things start to get complex; now that i have my BaseHit value, how do i determine if my character misses, or maybe hits but the opponent dodge, or maybe block, or if my character gain a full hit, or even a critical?

Just so you know, my problem only rotates around these four chances, as I already have formulas for anything, but i really can't decide how to apply all of them in one simple hit.

I understand it could be easily done with if\then\else functions, but it doesn't convince me, it doesn't feel right; am I forced to make a formula for all of those possibilities? or there is a way I can integrate them all in one?

Also, if I am to make four formulas, how do I determine and tell the player the percentage for miss, hit, being blocked, being dodged or critical?

One last thing, I am aware that is probably not possible what I ask, so if it's not, do you know of a way to make it more convincing? because four formulas feels too much like four tries from just one hit, and it feels strange to me.

EDIT: Since I literally have no idea how to express myself with words, i've done this little block system. Also, what I'm requiring is just a formula sample that has three output values, basically i ask for an example of some sort, the rest is already made and decided, as you can see from the picture; I only need that one piece to make it work, and if you need more info about how I want to make it work, I want the formula to make a check roll against one of the enemy stat, then the other, and decide if the enemy is hit, dodge or block.

EDIT2: About how the player should see it, I basically want a simple display on the side of the screen so when the player click on the opponent it can tell the player the percentage success of "FullHit\Block\Dodge" so that he\she may decide what opponent to take and whatnot.

# Answer
> 0 votes
If I understood you correctly, there are three possible outcomes of a successful hit:

* The enemy blocks and receives reduced damage
* The enemy dodges, receives no damage and an advantage on their next roll
* The enemy neither blocks nor dodges and receives full damage

This begs the question of what has priority: The dodging or the blocking mechanic?

One option is to first check one of those mechanics and only when it doesn't occur check the other. In that case the one which is checked first will happen more frequently. Regarding calculating the likeliness: The likeliness of the first mechanic happening is unmodified, the likeliness of the second is reduced by the fail-chance of the first. So when the first mechanic has a 60% chance of failing and the second a 40% chance of succeeding, the actual chance that the second event happens is 24% (60% of 40%)

Another option is to check both mechanics and then use the one where the random number generator generates a success by a greater margin.

Let's say the character has a 40% block chance and a 30% dodge chance on a particular attack. The random number roll(s) for the block test results in something which would have also succeeded at a 30% chance, the random result for the dodge test is slightly better and would also have worked with just 25%. In that case the block-test succeeded within a margin of 10% and the dodge-test within a margin of 5%. In that case the character would block, not dodge, because the block-test result was further below the result the character required.

When you use this option then not only are both mechanics on equal grounds, you can also add more damage mitigation mechanics later.

---
Tags: rpg, mathematics
---


# Question
Title: In Unity, how can I get trigger enter/exit every frame when I change Time.timeScale?
In my game I have a power-up that slows everything down. I keep the player at regular speed by dividing deltaTime by timeScale. Everything works perfectly except for OnTriggerStay2D which appears to be affected by the timeScale.

I thought I could just use trigger enter and trigger exit, pushing everything up to the update function that IS running every frame, but those are also slowed down and I'd like to keep things accurate to the player perspective.

So, is there any way to force trigger stay, enter or exit to work in regular time after I've changed Time.timeScale?

# Answer
The only way I know of to make OnTriggerStay2D get called just as often in real-time when you change the timescale would be to change the physics timestep when you change the timescale. Here's a link with details: http://answers.unity3d.com/questions/24748/altering-fixed-timestep-when-your-game-is-running.html
> 3 votes

---
Tags: unity, time-travel
---


title: Animation inside a .obj file?

text:
# Question
Title: Animation inside a .obj file?
Ok, so yesterday I understood that "rigging (bone and joints)" are things that are use inside a 3D animation software like maya. By that I mean that those bones and joints are not inside the .obj file but only inside the software to help you animate the model.

My plan was to create my own voxel model using my own editor, then load it up into maya to animate it and then put it inside Unity to use the animation but from what I understand, its impossible to put multiple frame inside a file to use the pre-made animation inside a software like Unity.

Does that mean that I will have to load my voxel model inside unity and animate it using the Unity Animation Engine ?

# Answer
> 1 votes
Its true that .obj files contain only “one frame“. You could try a different file format like md5. It should be supported by many 3D modeling programs and it is also a text based file like the obj.

---
Tags: unity, 3d, animation, models
---


# Question
Title: How should I animate sprites with separate body parts?
I am not an artist. I have a 2D Sprite broken up into different body parts that I want to animate. I know how to do it in Unity, but every artist I know would prefer to use Flash. I am trying to figure out if I should do it in Unity, or learn how to do it in Flash.

My understanding is that in Unity, I'd have to animate directly, or Flash would output sprite sheets.

Is there anything Flash offers for animating sprites that Unity does not? Is there a benefit to using sprite sheets over animating directly? Is there an option I should consider over Flash and Unity?

# Answer
We don't answer questions about which technology to use here, since it comes down largely to personal preference, compatibility with your studio's workflows, and the needs of an individual project.

There is an on-topic question here though about the differences between animating individual body part sprites versus pre-rendering your frames to a spritesheet and playing them back like a flipbook.

**Individual body parts** (this is often called 2D skeletal animation, particularly if you use hierarchies & constraints to help align the parts)

* Interpolate frames for smoother animations / control over playback speed
* Modify animations at runtime (eg. swapping body parts for character customization, blending/layering animations, using inverse kinematics to control things like looking/aiming angle, or adding dynamic animation like physics-driven wiggles)
* Smaller file size (typically)
* Author directly in Unity's built-in tools, or use middleware like Spine or Puppet2D

**Exporting complete frames**

* Simpler setup in your game engine (typically) - all you have to do is display the right frame
* Exact results - the frames you export are the frames you see
* Freedom to vary the content as much as you want from frame to frame - you can even hand-draw each frame uniquely (compare to animating body parts, where you typically re-use a collection of shapes with a limited set of transformations)
* Author in Flash or other animation program and export an image sequence or spritesheet.
> 3 votes

---
Tags: unity, animation, sprites, flash, spritesheet
---


title: Monogame - custom json content importer

text:
# Question
Title: Monogame - custom json content importer
I am trying to build a JSON tile map importer for the content pipeline of Monogame but I'm having difficulty doing so. I have been following this tutorial and got something... But now it appears my entire JSON level cannot be loaded since it has an array-based structure, and my code expects an object, here is my level file:

```
[
    [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
    [2,0,0,0,0,0,0,0,2,2,2,0,0,0,0,0,0,0,0,0,1,1],
    [2,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,1,1,2,2],
    [2,2,1,1,1,0,0,0,0,1,1,1,2,2,2,1,0,0,0,0,2,2],
    [2,2,0,0,0,0,0,0,1,2,2,2,2,2,2,2,1,0,0,0,2,2],
    [2,0,0,0,0,0,1,1,2,2,2,2,2,2,2,2,2,1,1,1,2,2],
    [2,0,0,0,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2],
    [2,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2],
    [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2],
    [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2]
]

```

And below are the custom content pipeline classes I made:

```
public class MapFile
{
    private MapFile map;

    public MapFile(MapFile map)
    {
        this.map = map;
    }

    public int[,] MapContent { get; set; }
}

```

---

```
[ContentImporter(".json", DefaultProcessor = "TileMapProcessor",
DisplayName = "TileMap Importer")]
public class MapImporter : ContentImporter<MapFile>
{
    public override MapFile Import(string filename, ContentImporterContext context)
    {
        context.Logger.LogMessage("Importing Map file: {0}", filename);

        using (StreamReader streamReader = new StreamReader(filename))
        {
            JsonSerializer serializer = new JsonSerializer();
            return (MapFile)serializer.Deserialize(streamReader, typeof(MapFile));
        }
    }
}

```

---

```
public class MapReader : ContentTypeReader<MapFile>
{
    protected override MapFile Read(ContentReader input, MapFile existingInstance)
    {
        string json = input.ReadString();
        StreamReader reader = new StreamReader(json);
        JsonSerializer serializer = new JsonSerializer();
        MapFile mapFile = (MapFile)serializer.Deserialize(reader, typeof(MapFile));
        MapFile map = input.ContentManager.Load<MapFile>(mapFile.MapContent.ToString());
        return new MapFile(map);
    }
}

```

**The problem:** As I said above, I get the following error at the content pipeline app:

> Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current \> JSON array (e.g. \[1,2,3\]) into type 'my class' because the type requires a \> JSON object (e.g. {"name":"value"}) to deserialize correctly.
>
> To fix this error either change the JSON to a JSON object (e.g. \>{"name":"value"}) or change the deserialized type to an array or a type \>that implements a collection interface (e.g. ICollection, IList) like List \> that can be deserialized from a JSON array. JsonArrayAttribute can also be \> added to the type to force it to deserialize from a JSON array.

Changing the type from `int[,]` to `List<List<int>>` would be easy, but I have the following code to generate visual representation of the map files:

```
public void Generate(MapFile map, int size)
{
    for (int x = 0; x < map.MapContent.GetLength(1); x++)
    {
        for (int y = 0; y < map.MapContent.GetLength(0); y++)
        {
            int number = map.MapContent[y, x];
            if (number > 0)
            {
                CollisionTiles.Add(new CollisionTiles(number, new Rectangle(x * size, y * size, size, size)));
            }
            Width = (x + 1) * size;
            Height = (y + 1) * size;
        }
    }
}

```

So that is what I am using. I hope you can help me, I've got everything right, including the collision so loading my maps from XNB files is the last thing I need to do. Thanks in advance! **Edit:** new level format:

```
{
    "Name": "My Level",
    "MapContent":
    [
      1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
      2,0,0,0,0,0,0,0,2,2,2,0,0,0,0,0,0,0,0,0,1,1,
      2,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,1,1,2,2,
      2,2,1,1,1,0,0,0,0,1,1,1,2,2,2,1,0,0,0,0,2,2,
      2,2,0,0,0,0,0,0,1,2,2,2,2,2,2,2,1,0,0,0,2,2,
      2,0,0,0,0,0,1,1,2,2,2,2,2,2,2,2,2,1,1,1,2,2,
      2,0,0,0,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
      2,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
      2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
      2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
    ]
}

```

# Answer
I think your level file needs to look like this:

```
{
    "MapContent":
    [
    [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
    [2,0,0,0,0,0,0,0,2,2,2,0,0,0,0,0,0,0,0,0,1,1],
    [2,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,1,1,2,2],
    [2,2,1,1,1,0,0,0,0,1,1,1,2,2,2,1,0,0,0,0,2,2],
    [2,2,0,0,0,0,0,0,1,2,2,2,2,2,2,2,1,0,0,0,2,2],
    [2,0,0,0,0,0,1,1,2,2,2,2,2,2,2,2,2,1,1,1,2,2],
    [2,0,0,0,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2],
    [2,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2],
    [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2],
    [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2]
    ]
}

```

Note that I've changed the outer square brackets (`[`, `]`) to curly braces (`{`, `}`) because you're deserializing into a JSON object.

It may look a little odd that you have to add the `MapContent` property to the file but one advantage of this approach is that you'll be able to easily add extra metadata to your map file. For example, you could add a `Name` property like this:

```
{
    "Name": "My Level",
    "MapContent":
    [
    [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
    [2,0,0,0,0,0,0,0,2,2,2,0,0,0,0,0,0,0,0,0,1,1],
    [2,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,1,1,2,2],
    [2,2,1,1,1,0,0,0,0,1,1,1,2,2,2,1,0,0,0,0,2,2],
    [2,2,0,0,0,0,0,0,1,2,2,2,2,2,2,2,1,0,0,0,2,2],
    [2,0,0,0,0,0,1,1,2,2,2,2,2,2,2,2,2,1,1,1,2,2],
    [2,0,0,0,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2],
    [2,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2],
    [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2],
    [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2]
    ]
}

```

And change your `MapFile` class accordingly

```
public class MapFile
{
    public string Name { get; set; }
    public int[,] MapContent { get; set; }
}

```

Btw, while we are on the topic. I find it very strange that you are passing a `MapFile` into the `MapFile` constructor. I think you can remove the constructor completely to simplify the code.

```
public MapFile(MapFile map)

```

If you really don't want to change the level format you might be able to change the deserialization method instead. However, I think this approach is going to lead to some pretty confusing code.
> 1 votes

---
Tags: c#, monogame, tilemap, json
---


title: How to merge VRPN and Unity

text:
# Question
Title: How to merge VRPN and Unity
I'm new to virtual environments, having worked mostly with Arduino and other physical applications. I'm trying to set up VRPN server on one of the computers in my lab to pass some triggers from a Unity game to a VR environment and there is little to no documentation that a novice can at least hack through to explain how VRPN even works.

Can anyone shed a little light on it and explain how to set up a VRPN server using c#?

# Answer
Welcome to the wonderful/horrible world of VRPN. While I have not integrated it with unity, I have integrated it with another game engine. VRPN is a network transparent protocol for transferring data from one device to another. The devices can be local, remote, etc.

VRPN treats every input device as a server, and the VR environment (Eg unity) needs to connect to each of these. First you need the devices addres

```
W5D_INPUT_ADDRESS = "W5DTracker@192.168.1.4:3889"

```

And then you need to connect to it. In the VRPN python bindings this looks like:

```
w5d_device = vrpn.receiver.Tracker(W5D_INPUT_ADDRESS)

```

Note that a tracker is a generic device, capable of inputting rotations and positions and velocities and accelerations and button presses and.....

Then we need to poll the device and extract data from it. In the python bindings this is done by creating two callback functions and setting up change handlers:

```
w5d_device.register_change_handler(0, onPositionData, 'position')
w5d_device.register_change_handler(0, onVelocityData, 'velocity')

```

Where those functions (again in python) simply store the data they are passed which is a dict of `{'position':[x,y,z], 'quaternion': [x,y,z,w]}`

---

Now, how to do it from unity in C#? I'm not quite sure, not being a unity user. But there are some examples of using VRPN from C in the client\_src directory. Just remember that your game is a client, connecting to the input device (unless you're doing force feedback, in which case you are a server as well, so the force feedback device can fetch data from you).
> 1 votes

---
Tags: unity, networking, virtual-reality, vrpn
---


# Question
Title: AutoFill function and methods not working in unity 5.3.5
I opened one of c# code in my projects, and edited something in the code, and I noticed that MonoDevelop no longer gives auto filling of function and method options.

Below is the screen shot of the code.When I type debug,its not showing the dropdown with list of function and methods.

Iam using 5.3.5 (64 bit)Personal and windows 8.

Can anybody help me sorting this issue.

When I open a c# code. its showing the namespace in redcolor

this is how the code structure looks

# Answer
Open C# project by right click on Project tab. It opens the project solution file not just one script.

---

**Suggestion:**

Get visual studio community. After installation, go to (in Unity) Edit\>\>Preferences\>\>External Tools. Select VS instead of MonoDevelop.
> 1 votes

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


# Question
Title: Normal map does not export into .dae file. Does Collada not support normal maps?
Every time I try to use DAE FBX export in Autodesk Maya and export a .dae file the normal map doesn't export with it? Does Collada not support normal maps?

# Answer
> 1 votes
One thing I can think off is that it's not correct in the .dae.

Open the .dae file in a text editor. Search for:

```
<bump>

```

If it's just called `<bump>`, change it to:

```
<bump bumptype="NORMALMAP">

```

Then, below your material type, and above `</technique>`, paste the following and replace with your normal texture name. In context, it should look like this:

```
</phong>
<extra>
  <technique profile="FCOLLADA">
    <bump bumptype="NORMALMAP">
      <texture texture="example_Normal_jpg-sampler" texcoord="UVMap"/>
    </bump>
  </technique>
</extra>
</technique>

```

---
Tags: maya, normal-mapping, collada
---


title: Why circles are not created if small?

text:
# Question
Title: Why circles are not created if small?
I have changed the scale in 3DSMax to my own and now I can't create any object, including circle, if it is of the size which is normal for my scale. Instead, I have to create big object first and then modify it to a smaller size. It looks like there is a minimal size protection is set somewhere - where is the setting for it?

**UPDATE**

While creating a circle, if I drag for 0.04m circle disappears after drag end. If I drag for 0.08m circle also disappears. If I drag for more than 0.1m, circle persists after drag end.

How can I set it so that it persist after 0.01m too?

# Answer
It's probably because the camera that renders your editor window has a near and far range that it uses to display the circles (spheres?) called the clipping plane. It's a good idea to get in the habit of working in a real unit system like meters, inches 3dsmax has always had the issue of working at small scales. If you select the object and retarget it with the camera, it may adjust the clipping plane to make the object visible. So if your sphere is a basketball, make it the actual size of a basketball given the units you are working in.
> 1 votes

# Answer
The problem is with your unit setup.

If you require centimeter accuracy, set your system units to centimeters (and your display units to meters if you like).

You will then have no problem creating circle shapes of centimeter (or even millimeter) radius.

Alternatively, use the keyboard creation tool instead of clicking and dragging, and you should be able to create the circle as well.

At some point you may also want or need to increase the precision of displayed values, in the preferences the default is 3 decimal places.
> 0 votes

# Answer
Hi guys I found out how to solve the thing. Its again a 3ds Max bug. Whec creating circles just change the Creation Method from Center to Edge, make one and than again change it to Center. That worked for me :)
> 0 votes

---
Tags: 3dsmax
---


# Question
Title: Webgl: is possible to use one color buffer to unsharp masking the depth buffer?
I'm noob to webgl. After reading the tutorials at webglfundamentals.org and "Introduction to Computer Graphics", i'm able to succesfully draw some stuff and the depth buffer without thirty-party libraries.

Now, i try to go a step further and apply some visual enhancement to my drawings, by usharp-masking the depth buffer, also called "the cheap SSAO".

What i understand is, that i should:

* draw the depth buffer
* blur X
* blur Y
* combine the blurred depth buffer with the diffuse component of the initial image

What i learned so far is, that to apply these four steps, i could use two textures, ping-pong back the textures, apply the effects in sequence to the textures and at the end draw to the screen the final result.

It would be easier with a gl.RGB4 color attachment?

It seems to me, that the final effect is just only to dim the diffuse color of the initial image, so i could draw the depth buffer to the red channel, blur-X the red channel to the green channel, blur-Y the green channel to the blue channel, and then combine this last with the initial drawing.

Isn't this faster or memory-cheaper than swapping two textures, for example by thinking mobile-first?

What are the drawbacks? Anyone already tried this? Thanks in advance

# Answer
No, actually is not allowed to read and write to/from the same buffer at the same time. This results in undefined behavior. If it does work on one piece of hardware, it may not work on another. Here is a more detailed explanation: https://www.opengl.org/wiki/Framebuffer\_Object#Feedback\_Loops

Here is the resulting error:

> GL\_INVALID\_OPERATION\> Source and destination textures of the draw are the same.
> 0 votes

---
Tags: webgl, depth-buffer, ssao
---


# Question
Title: How to keep sprite on screen while increasing its width to screen width
I have been able to increase the width of a sprite to the width of the screen size, but the sprite exceeds the borders of the screen width to the right or left when I try expanding it when it's not at the center. How can I scale the sprite in such a way that it's width increases on both sides till it occupies the screen width without exceeding it's bounds, regardless of the sprite's initial position? Please see my code below:

```
bool isScaling = false;

IEnumerator scaleToX(SpriteRenderer spriteToScale, float newXValue, float byTime)
    {
       if (isScaling)
         {
           yield break;
         }
       isScaling = true;

       float counter = 0;
       float currentX = spriteToScale.transform.localScale.x;
       float yAxis = spriteToScale.transform.localScale.y;
       float ZAxis = spriteToScale.transform.localScale.z;

       Debug.Log(currentX);
       while (counter < byTime)
        {
          counter += Time.deltaTime;
          Vector3 tempVector = new Vector3(currentX, yAxis, ZAxis);
          tempVector.x = Mathf.Lerp(currentX, newXValue, counter / byTime);
          spriteToScale.transform.localScale = tempVector;
          yield return null;
        }

       isScaling = false;
  }

```

# Answer
> 3 votes
This is actually very simple. All you need to do is determine the Camera Bounds, and then set the final resting position of your sprite, based on these bounds.

So, you would have the start position and size -- Determine the end position and size that you want, then lerp to it. It is that easy.

Here is the script that will do this:

```
using UnityEngine;
using System.Collections;

public class Square : MonoBehaviour {

    Bounds CameraBounds;

    Vector2 EndScale;
    Vector2 EndPosition;
    Vector2 StartScale;
    Vector2 StartPosition;

    float Speed = 2;
    float SPEED = 2;

    void Start () {

        CameraBounds = GetCameraBounds ();

        StartPosition = this.transform.position;
        StartScale = this.transform.localScale;

        EndScale = CameraBounds.size;
        EndPosition = CameraBounds.center;
    }

    void Update () {

        Speed -= Time.deltaTime;
        if (Speed <= 0)
            Speed = 0;

        this.transform.localScale = Vector2.Lerp (EndScale, StartScale, Speed/SPEED);
        this.transform.position = Vector2.Lerp (EndPosition, StartPosition, Speed / SPEED);
    }

    public Bounds GetCameraBounds()
    {
        float screenAspect = (float)Screen.width / (float)Screen.height;
        float cameraHeight = Camera.main.orthographicSize * 2;
        Bounds bounds = new Bounds(Camera.main.transform.position,new Vector3(cameraHeight * screenAspect, cameraHeight, 0));
        return bounds;
    }

}

```

And this is an example of this script running on a 1:1 ratio sprite:

---
Tags: unity, scale
---


# Question
Title: A python script controlling a Unity game
I wish to build a simple game in Unity such that the objects in the game can be controlled via a Python script (or a code in any other programming language). Is this possible? If yes then how? If no then are there any other alternatives to achieve similar results?

To make it more clear, say that I have 10 objects in my current scene. What I wish to do is to address each object individually via Python. One way of doing this is setting up keyboard bindings to select a particular object and then using keyboard and mouse events to control this object. But, is there a more cleaner (a native) way of doing the same?

# Answer
Ok so first follow this tutorial. Then i wrote some code to try and test it out. C# code. I used the editor example from the tutorial but you can make it run during runtime or what ever:

```
 [MenuItem("Python/LoadFromFile")]
    public static void ReadFile()
    {
        var ScriptEngine = IronPython.Hosting.Python.CreateEngine();
        var ScriptScope = ScriptEngine.CreateScope();
        ScriptEngine.Runtime.LoadAssembly(typeof(GameObject).Assembly);
        ScriptEngine.Runtime.LoadAssembly(typeof(Editor).Assembly);
        StringBuilder example = new StringBuilder();
        FileInfo pySourceFile = new FileInfo("PyExampleString.txt");
        StreamReader reader = pySourceFile.OpenText();
        while(!reader.EndOfStream)
        {
            example.AppendLine(reader.ReadLine());
          //  Debug.Log(reader.ReadLine());
        }

        reader.Close();
        var ScriptSource = ScriptEngine.CreateScriptSourceFromString(example.ToString());
        ScriptSource.Execute(ScriptScope);
    }

```

Then I had to read how to do if statements in phyton and got one indentation error but I ended up with this in a .txt file named PyExampleString.txt

```
import UnityEngine as unity
if unity.GameObject.FindGameObjectWithTag("Test"):
    unity.Debug.Log("Found one")

```

This is tested and logs Found one if there is a game object with a tag Test in the scene. Hope you find this helpfull.
> 3 votes

# Answer
I hope I understood your question correctly. What I gathered was that you have an Unity game, and you want to have a Python script that provides input to the game instead of a human playing the game. Is that right?

In that case, yes, you can use a Python script to provide input to the game. The task isn't very pleasant, but yes, it can be done. Basically what you are looking for is a way to generate regular OS input events: mouse movement and clicks, key presses and releases, and perhaps even controller input events (all though this might be the hardest one to implement). Now, generating these events isn't something you can easily do in a cross-platform manner, so I'll only go trough some options you have for Windows.

There are libraries from Python that allow you to interact with the underlying Windows libraries. You might want to take a look at pywin32, and investigate the WinAPI on how to generate key events. A quick google search also showed me this SO answer which does exactly what you are looking for. You would then extend that piece of code posted on the great answer.

And this task can be also achieved with other languages, as long as there is a way to generate OS input events in the language in question.
> 1 votes

# Answer
Yes you can, but instead of working directly with pywin32 for Windows which is a pain in the ass you can use pywinauto, it allows you to send mouse and keyboard actions to windows accesing their widgets/controls directly, which is better but it's not crossplatform just for Windows.

Or you can use PyAutoGUI for (Windows, OSX, Linux), which instead of sending the input to a specific window or dialog I think it works like if you 'capture' the screen and you send the inputs in a determined position, so the window must be visible in front of any other thing.
> 0 votes

---
Tags: unity, python, scripting, unityscript
---


# Question
Title: Using phy_rotation to follow the mouse [Gamemaker]
My `oPlayer` object (a physics object in Gamemaker) uses the following code to follow the mouse:

```
phy_rotation = point_direction(phy_position_x,phy_position_y,mouse_x,mouse_y)
direction = phy_rotation - 180
image_angle = direction

```

However, though it does rotate in reaction to mouse movement, the `oPlayer` object's `image_angle` is always the opposite of the `point_direction` to the mouse!

I've tried to set it to

point\_direction = (phy\_position\_x,phy\_position\_y,mouse\_x,mouse\_y) - 180

but to no avail.

Any help with getting **the `oPlayer` object to point in the direction between itself and the mouse's position** would be greatly appreciated.

# Answer
> 0 votes
I have managed to solve this now, for anybody looking for a similar solution.

Rather than adding `-180` to the `point_direction`, you must instead make it a *negative* value, thus:

```
phy_rotation = -point_direction(phy_position_x,phy_position_y,mouse_x,mouse_y)

```

With this code, the physics-enabled object will always face towards the mouse position. This is because `phy_rotation` operates in the **opposite** direction from the `direction` value in non-physics Gamemaker objects.

---
Tags: game-maker
---


# Question
Title: Gaussian blur spritesheet/texture atlas without clipping edges
I'm trying to apply a Gaussian blur to a shadow to soften them a bit. I can apply the blur fine, but the problem is that I end up with this:

Instead of this:

Which isn't great. The image is part of a spritesheet with a single pixel gutter around each frame.

I don't want to have to go back and add gutters big enough to accommodate the blur to every single frame of every spritesheet. Additionally because of the way the sprites have to be sorted I can't render all the shadows to a render target and then blur the entire target. I can achieve the effect I want with a sprite as a single image instead of as a spritesheet. I do that by creating the triangles 20% bigger than they need to be and then sampling the texture outside the bounds when the UV addressing is set to clamp. That doesn't work with a spritesheet though because then it just starts sampling the frames on either side of the current frame.

Is there a way to achieve what I want with a shader or other trickery? I really don't want to have to alter every spritesheet.

# Answer
This is an issue with any non 1x1 filter(such as a Gaussian one). If you don't want to clip, you can not apply the filter on the edge, or apply only part of it(and it will be darker probably). Another option, if the background outside the image, is known to be a specific color or transparency, is when you apply the filter, apply that color as part of the filter outside the image for border pixels.
> 1 votes

---
Tags: xna, shaders, sprites, texture-atlas, blur
---


# Question
Title: Unexpected Execution Order in Unity (uNet)
I made a little game in Unity. It works fine in the Editor. But if I run the build version I get a NullReferenceException.

This problem does only appear if the build-version-client hosts the game.

* No problems if the BUILD-version plays as client or server only.
* No problems when played in EDITOR

I have a class (CharacterSpawner) that is meant to run on the server only.

```
public static CharacterSpawner instance;

...

public void Awake()
{
    instance = this;
    print("Character Spawner Awake");
}

[Server]
public void SpawnCharacter(NetworkConnection owner)
{
    GameObject character = Instantiate(characterPrefab, randomSpawnPoint, Quaternion.identity) as GameObject;
    NetworkServer.SpawnWithClientAuthority(character, owner);
}

```

I have another class (Player) that should send a Command to the server in order to spawn a character right at the beginning.

```
void Start()
{
    if (isLocalPlayer)
    {
        CmdSpawnCharacter();
    }
}

[Command]
public void CmdSpawnCharacter()
{
    CharacterSpawner.instance.SpawnCharacter(connectionToClient); // throws NullReferenceException
}

```

'instance' is here the only thing that could cause the NullReferenceException, because connectionToClient would not cause a NullReferenceException even if it was null! This means the instance is not set yet.

As problem I can think that the Start-method in the Player-script is called before the Awake-method in the CharacterSpawner Script. Because if I call CmdSpawnCharacter like this:

```
Invoke("CmdSpawnCharacter", 0.5f);

```

It works perfectly, but that is not the way I want to do this.

I even changed the priorities of the scripts, but without success.

**QUESTION:** Why does Start() gets called before Awake() gets called? This does not line up with the docs http://docs.unity3d.com/Manual/ExecutionOrder.

# Answer
I'm having similar issues with UNET calls running in a different order in the Editor vs in a build.

The reason your issue is happening is that networked scene objects are turned off when an online scene first loads, and Awake won't run until the object is enabled. For whatever reason these objects seem to get enabled slightly later in a build than they do when running in the editor, hence why Awake hasn't run yet in this case.

It's not a solution, but hopefully that explanation will help you come to one!
> 2 votes

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


# Question
Title: Unwanted roll when rotating camera with pitch and yaw
I have a quaternion class implementation, and when I apply this class to my objects all gone right (rotations), but I have a lot of troubles with the camera. I've been searching a lot trying to solved my problem but nothing works.

When I do a yaw and then a pitch rotation (or vice versa) a roll rotation is introduced. If I do the Y rotation around local axis the undesired roll disappears, but looking up and down will not work properly after a roll rotation (so I need to apply the Y rotation around the global axis).

Like I said, applying the quaternion to the object works fine, so maybe the problem is when passing the rotation data to opengl. I do this like that:

```
 mainCamera.getAnglesAxis(angle, vAngle);
 glRotatef(-angle, vAngle.getX(), vAngle.getY(), vAngle.getZ());
 glTranslatef(-mainCamera.getX(), -mainCamera.getY(), -mainCamera.getZ());

 glTranslatef(obj.getX(),obj.getY(),obj.getZ());
 cube.getAnglesAxis(angle, vAngle);
 glRotatef(angle, vAngle.getX(), vAngle.getY(), vAngle.getZ());

 drawCube();

```

I'm doing it right?

# Answer
As I explained above, this is not an issue with quaternions. Quaternions just represent your rotation.

The problem is that you have mutually conflicting goals for this rotation:

1. The camera can look in any direction and always turn left/right/up/down about its own local axes
2. The camera never rolls relative to the world up direction

To see why these are contradictory, imagine the following:

* Start with your camera facing north
* Look 90 degrees up (its local up vector/the top of its head is now facing south)
* Look slightly to the right by rotating the camera around its local up vector (as point 1 says we're allowed to do)
* We're now looking slightly east, with our local up vector still pointing straight south. In other words, our viewpoint has a roll of 90 degrees relative to the world up direction! (Violating point 2)

Games usually solve this in two ways:

* For first-person games, camera rotation is often clamped to you can't look a full 90 degrees up or down. Yaw rotation follows the world up axis. (Sacrifice point 1) See this answer for more details
* For free-flying games, the camera lets you look any way you want, and by doing certain moves (like the one above) you can develop some roll in your viewpoint. (Sacrifice point 2) Often these games have an auto-righting feature, where they twist the camera to reduce the roll angle over subsequent frames until you're looking straight upright again.

A neat trick I saw recently in Star Wars Battlefront's fighter battles is that they apply this roll correction only when the player is turning the camera. If you let go of the controls you'll keep whatever roll you have, avoiding the disorienting lurch when the camera twists on its own. For most maneuvers the movement on screen from the player's camera manipulation does a good job of masking the roll correction, so it's hardly noticeable.

So, these are your options. This isn't an artifact of your rotation method or quaternion math, this is just the way rotations in 3D space work, and the best you can do is correct for unwanted roll (gradually, so as not to snap the viewpoint distractingly) or restrict the rotation freedom to avoid it.
> 7 votes

---
Tags: camera, vector, quaternion
---


title: Damping the Camera "lookAt" rotation

text:
# Question
Title: Damping the Camera "lookAt" rotation
I have created a very short piece of code to make the camera look at a transform object. I locked the rotation of the x and z axis as it is only supposed to rotate on the y axis. I would like to add some damping to this and make it rotate slowly, thanks. Here is my Code:

```
public Camera Camera;

public void lookAt (Transform target)   {
    Camera.main.transform.LookAt (target);
}

```

# Answer
To do this you'll want to use a routine that runs every frame, like Update, LateUpdate, or a coroutine, so you can adjust the camera's position repeatedly.

You'll also want to store information about where you're supposed to be looking so you can keep turning towards it (particularly if you want to use this to follow a moving object)

Here's one way to do it:

```
Transform _lookTarget;

// Cache the target we're supposed to look at.
public void LookAt(Transform target)
{
   _lookTarget = target;
}

// LateUpdate so it runs after any scripts/animation
// that might move _lookTarget this frame.
void LateUpdate()
{
   if(_lookTarget != null)
   {
       Transform camera = Camera.main.transform;
       Vector3 toTarget = _lookTarget.position - camera.position;

       // This constructs a rotation looking in the direction of our target,
       Quaternion targetRotation = Quaternion.LookRotation(toTarget);

       // This blends the target rotation in gradually.
       // Keep sharpness between 0 and 1 - lower values are slower/softer.
       float sharpness = 0.1f;
       camera.rotation = Quaternion.Lerp(camera.rotation, targetRotation, sharpness);

       // This gives an "stretchy" damping where it moves fast when far
       // away and slows down as it gets closer. You can also use
       // Quaternion.RotateTowards() to get a more consistent speed.
   }
}

```
> 2 votes

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


title: Love2D: Calling two files

text:
# Question
Title: Love2D: Calling two files
Okay so i have two files one named Player.lua and one named Main.lua

Main:

```
function love.load()
end

function love.update()
end

function love.draw()
end

```

Player:

```
function player.load()
end

function player.update()
end

function player.draw()
    love.graphics.setColor(255, 0, 0)
    love.graphics.rectangle("fill", 50, 50, 50, 50)
end

```

Output is just a black screen!

# Answer
> 1 votes
The `main.lua` file is automatically executed from the Löve application and the overriden functions `love.load`, `love.update` and `love.draw` get called.

This means that if in your main.lua file you've included the love.load function, at the start of the game that function is called; then, if there's a love.update function, it gets called too, then the love.draw if it's present, and then back to update, draw, update, and so on.

So the player.lua file will never gets executed, unless you tell the program to execute it from main.lua.

main.lua

```
function love.load()
    require "player.lua"
    player.load()
end

function love.update()
    player.update()
end

function love.draw()
    player.draw()
end

```

This is how it should look like.

---
Tags: love2d
---