title: How do I hide an Input field?

text:
# Question
Title: How do I hide an Input field?
I have in my hierarchy tab a Canvas. Inside the canvas I have an **Input Field** that holds a placeholder and a text.

I read the documentations and didn't find how to hide the Input field.

I want that if a `if` statement is true, then it will show the input field. Else you won't see it.

How can I implement it?

---

**EDIT**

I thought about an idea to test: If I press the O key on the keyboard it disappears, and if I press again it appears; and so on.

This is what I tried:

```
bool shown = true;
// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    GameObject inputField = GameObject.Find("InputField");
    if (Input.GetKeyDown (KeyCode.O)) {
        shown = !shown;
        inputField.SetActive (shown);
    }
}

```

I play the scene and when I press the O key I get

```
NullReferenceException: Object reference not set to an instance of an object

```

If I double-click on the console message it highlights me the `if (Input.GetKeyDown (KeyCode.O)) {` line.

Something not good does the `SetActive(bool)` method, I suppose.

# Answer
You can reference the InputField as a GameObject and call the SetActive(false) method on it to turn it off. You can then use your if statement, to turn the same GameObject on.

```
public class SomeClass : MonoBehaviour {
    public GameObject inputField;

    void SomeMethod(){
        if(someCondition)
            inputField.SetActive(false);
    }
}

```

Set the GameObject in the inspector by drag drop, or use GameObject.Find in awake to set inputField
> 2 votes

# Answer
You can create a public GameObject variable and then disable/enable it accordingly:

```
public GameObject field; //  On Editor drag the inputfield GameObject here
...

...
if (*condition*) {
    field.SetActive(true);
} else {
    field.SetActive(false);
}

```

For the second question you made: `Change the GameObject inputField = GameObject.Find("InputField");`It should not be on the update. See this solution:

```
bool shown = true;
GameObject inputField;
// Use this for initialization
void Start () {
    inputField  = GameObject.Find("InputField");
}

// Update is called once per frame
void Update () {
    if (Input.GetKeyDown (KeyCode.O)) {
        shown = !shown;
        inputField.SetActive (shown);
    }
}

```

You can also use ,as I said in the first place, a public GameObject. Then on the unity editor you can drag the InputField GameObject to the Variable.
> 2 votes

---
Tags: unity, input
---


# Question
Title: Is it possible to add touch screen functionality to a Windows Standalone build for a Surface Pro?
I have an application which is currently PC/ Windows Standalone, however I need it to be able to work with the touchscreen on a Surface Pro tablet when the same build is run on here. The interaction the user has is that of clicking buttons to open and close windows etc (all buttons use the OnClick() functionality), so any input required would just be simple button taps.

I simply need this to work on a Surface Pro touchscreen display when it is run on there, so mouse clicks to be replaced with taps of the buttons.

I've read many posts on the subject, but many are from Unity 4.6 and nothing conclusive for Unity 5. Many posts I found stated that this feature was introduced for Unity 5, but others suggest it is not supported and third party plugins are needed.

I don't currently have access to a Windows touch screen device, so am unable to do a quick check. I therefore want to make sure it is possible before I purchase a device and commit to the update.

From what I gather, the 'Standalone Input Module' has now replaced the 'Touch Input Module' which apparently had a checkbox to tick if you wanted to have it work in Standalone. As such a checkbox does not exist in the former, I am unsure whether this feature is still supported.

So I would like to know -

1. Is it supported in Unity 5?

If so -

2. Does it 'just work' automatically or does extra work need to be done to tell it to use touch screen if it is running on a Windows touch screen device?

Many thanks in advance

# Answer
> 1 votes
Yes it works, as you'd expect. Just install Unity on your tablet and run a demo project.

---
Tags: unity
---


# Question
Title: Unity google play services login dont work properly
I have searched everywhere on the internet and I have found nothing about the problem I am encountering.

I am trying to implement google play services to my game (leaderboards especially) and I have made that "work" somehow. Here is the code:

```
void Start()
{
    PlayGamesPlatform.Activate ();

    Social.localUser.Authenticate((bool success) =>
    {
        if (success)
        {
            Debug.Log("Logging in: Success");
        }
        else
        {
            Debug.Log("Logging in: Failed");
        }
    });
}

```

The game opens properly and it shows that green window which then disappears and a "loading" icon appears turning in a circle. But after that it disappears too and the window which lists and ask you which account to link with the game does not appear, as it is supposed to do(which "ends" the logging in).

Any help would be much appreciated.

# Answer
> 1 votes
I have encountered this problem before. This happens if you are using an unsigned app. You should have a keystore for your game in order for GPG to work. I'm not sure if you need at least one version uploaded on Google Developers Console, so maybe someone with that knowledge can share if you need that or not?

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


# Question
Title: Ideas/suggestions to implement an item combination system
I'm designing a game where there is a relatively small set of items. A single player holds an inventory of item slots. Each item slot contains a single item. The inventory allows you to **use** the item directly, **move** item around the slots (to organize), **equip** the item (weapon), and lastly, to **combine** compatible items together.

I've come up with the diagram below:

Where I'm having trouble is combining. To simplify the game, the game will only do *Health+Health*, *Ammo+Ammo*, *Weapon+Ammo*, *Prop+Prop*.

Where should I check if the above is permitted? Should Inventory check, or should I delegate the checking to the items themselves?

If I have a green health item and a red health item, it would double the strength of the green potion (increases HP) due to the red health item. But what if the player tries to do: G+G+G+G+G or G+R+R?

I can see that with this design, I run into the problem of having a health item as an (subtype).

For Props, they're simply items used in the game, like keys, cranks, etc. Sometimes two props can be combined as one.

All combinations are designed. As in, the player wouldn't come up with a unique item combination.

**Edit 1**: The example, with health items, G+G+G+G+G implies that there's a limit as to how many green health items can be combined together. For example, the green health item has a `HealthItem.health_sum=.40` (40% of your HP). After the third combination, it becomes meaningless.

# Answer
When you handle all item combinations in the Inventory class, that class will potentially grow to an enormous size because it needs to implement the combination logic to handle every single item combination.

You could have items handle combinations themselves, but then you have the issue that you need to ensure that `itemA.combineWith(itemB)` has the same effect as `itemB.combineWith(itemA)`.

A third possibility is to introduce another class `ItemRecipe` with the attributes `ingredientA`, `ingredientB` and `result`. When the player wants to combine two items, you look at your list of recipes and return the one which matches. When more than one matches you could prompt the player to choose which combination to perform. When your game concept consider ambiguous combinations impossible, you should throw an error when an ambiguity is detected. To avoid the ordering problem, `ItemRecipe` could have functions `bool matches(item, item)` and `Item combine(item, item)` which accept the ingredient in any order.

Those methods should be the only ones which are part of the public interface. That would allow you to create a subclass of `ItemRecipe` which solves your health item combination problem by not having the above attributes. It instead implements `match` to return true for any two health items which still allow combining and then implements a `combine` method which implements your health item combination mechanics.
> 3 votes

# Answer
> Where should I check if the above is permitted? Should Inventory check, or should I delegate the checking to the items themselves?

Assuming that all items within an `ItemType` can always be combined with any other item of the same type, it would seem reasonable for this check to occur in `ItemInventory`, as it's really straightforward.

However, if that's not the case, for example if there's a limit on how many items of a particular subtype can be combined into the same item (e.g. you can't combine more than 2 red potions together), then you would probably want to query each of the items about to be combined whether they can be combined with the other. I.e. `ItemInventory::CombineItems` could call both items' `CanCombineWith` method.

> (...) But what if the player tries to do: G+G+G+G+G or G+R+R?

Based on your description it's not quite clear what the problem here is, perhaps you could clarify.

The way I see it is, you would have a number of predefined 'templates' used to initialise 'base' items (e.g. a red potion), each of them would come with a list of item subtypes it can be combined with. As you combine the items, that list could be modified (e.g. red potion could be removed from the list once one item of that subtype had already been combined).
> 1 votes

---
Tags: c#, rpg, design-patterns, oop, inventory
---


# Question
Title: How to properly synchronize achievements on Google Play Services?
I have a mobile game with achievements on android, so the achievements are using Google Play Services.

For a couple of reasons, I must track the progress on the achievements locally (or so I think) because:

* If the user is not connected to the internet
* Some achievements have complex "step" that the simple increment system provided by the Google Play Service (number of steps, current step) cannot track.

When the game starts, the local copy data on the achievements is synced with what is on Google's server. Either

* both are the same, do nothing
* the local copy has more progress than what is shown on Google's: so update Google data (that happens if you play offline)
* the copy on Google's server show more progress than locally: so update the local data (that happens if you play on a different device)

Clearly, there's a way to abuse the system here. Given two players with different achievement progress (Player\_A (lots of achievements), Player\_B (few achievements)) they can do the following:

* Using Player\_B's device, Player\_B signs out of his account
* Player\_A signs in (the current active Google Account is now Player\_A)
* Start the game
* All of Player\_A's achievements are synced locally (they had more progress than the previous local version of Player\_B)
* Player\_A signs out and Player\_B signs in
* Re-start the game: the local copy will show as more advanced than Player\_B achievements, therefore they will get updated.

How do people deal with this problem? Not care? Key the local achievement progress to the logged in player (which causes some problems)? Not to track anything related to the achievements locally (but how to deal/detect being offline?)

# Answer
> 2 votes
This is a classical "local cache invalidation" problem, the very common case in which you really need to invalidate the cache when the user changes (so that, for example, when I access my home banking I don't see a chart about how much money the previous user has).

The usual solution is to include the player name in some form (a hash, a user\_id...) in the cached data (your local achievements) and then when the player starts the game you check the active username vs. the username whose ID was stored in the cache: if they're different, you download all data from Google Play Services anew.

Obviously, doing this will delete any progress made by the previous user, so you could add a warning to allow the player to stop the transfer and log in again with the username that was in use when the existing cache was last saved so that he can sync it.

A more complex and maybe satisfying option, especially if you really can't save those complex achievement steps on Google, is to keep a local copy of all users' "caches" (at this point I'd call them something like "custom user achievement stats dataset"): every new user will create a new dataset, all of them stored on your device so you can always keep those data you can't save on Google... with bonus points for allowing an easy path to port the game on other mobile OSes.

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


title: How to create follow leader behavior?

text:
# Question
Title: How to create follow leader behavior?
Assume that this behavior has `Separation` behavior. I tried to implement the `FollowLeader` behavior from this article. In the code below is my working implementation. But there is a problem, when I convert the owner linear velocity to direction (North, South, East, West), it doesn't give the proper direction to achieve the correct facing of my animation.

```
    protected SteeringAcceleration<T> follow(SteeringAcceleration<T> steering, Steerable<T> leader) {
        T tv = leader.getLinearVelocity().cpy();
        // calculate the ahead point
        tv.nor();
        tv.scl(LEADER_BEHIND_DIST);
        ahead = leader.getPosition().cpy().add(tv);

        // calculate the behind point
        tv.scl(-1);
        behind = leader.getPosition().cpy().add(tv);

        if(isOnLeaderSight(leader, ahead)) {
            evade.calculateSteering(steering);
            force.add(steering.linear);
        }

        arrive(steering, behind);
        force.add(steering.linear);

        // separation(..) assume exists

        steering.linear.set(force);
        steering.angular = angular;

       return steering;
    }

```

# Answer
> 0 votes
I fixed it, it's a little bit different when implementing using Gdx-ai. Here is the solution.

```
BlendedSteering<Vector2> followLeader = ...

followLeader.add(new ArriveBehind(owner, leader), 1f);
followLeader.add(new Evade(owner, leader). 1.5f); // tweak until matches, for me I used 1.5f

setBehavior(followLeader);

```

Then in the update method. Enable the evade behavior only if in the leader sight or ahead.

```
evade.setEnabled(isOnLeaderSight(leader, getAhead(leader)));

```

---
Tags: libgdx, ai, steering-behaviors
---


# Question
Title: Why does OpenGL require all coordinates in [-1,1] (NDC)?
Why shouldn't the z coordinate be normalized to the \[0,1\] range instead of \[-1,1\]? As I understand it, that happens some time after anyways, so what's the catch with this?

# Answer
> 14 votes
There's one massive advantage to NDC's Z being defined as \[0,1\] and it has to do with floating point precision.

Since about 2006, the standard advice from GPU vendors to avoid z-fighting has been to use a projection matrix that maps the far plane to z=0 and the near plane to z=1 and to use a floating point depth buffer.

Perspective projection results in a hyperbolic precision density that favours the near plane (which results in terrible precision beyond about near\*2). Floating point formats have logarithmic precision density that favours 0. Combining these two facts with the above mentioned "backwards" projection matrix results in those two curves almost cancelling out, giving approximate linear precision density across the entire Z range, without sacrificing performance or interpolation quality (unlike some other linear/logarithmic depth buffer schemes).

Unfortunately this trick (which is now standard practice) does not work with OpenGL's "nice, symmetrical" NDC coordinate system -- you have to enable a GL extension to opt in to the NDC definition used by every other sane graphics API.

# Answer
> 11 votes
The question could very easily be turned around: why the \[0, 1\] range? What makes that range special?

NDC space is a *cube*; every component is on the \[-1, 1\] range. So it's very nice, neat, and uniform. That's why OpenGL uses that space. It's simple, obvious, and very regular.

What you suggest is to turn that nice, neat, uniform cube into a rectangular prism. There is nothing to gain from such a space. Why be irregular when you can be regular?

> As I understand it, that happens some time after anyways

No, it does not. The transform from NDC space to window space uses the current `glDepthRange` setting. That ***may*** be \[0, 1\], and that's what it is by default. But there's no rule that it *must* be. It can be anything you want, so long as both values are between 0 and 1. You can even reverse the near and far, using a range of \[1, 0\].

---
Tags: opengl
---


# Question
Title: Am I allowed to use a real life celebrity in a game?
In previous questions many users asked whether or not an athlete can be used in a game. Yet the answer was no due to multiple copyright their images and names had. However anyone can use a politician's name and physical appearance due to the fact that they are "public figures" (example: Obama). In this case, I want to use famous game developers such as Kojima and Gabe Newell in a game. Am I allowed to use them? or should I make references to them using distinct names (I.E. Lord Gaben). How can I find out whether or not a person is a "public figure" and if their appearance/name is protected?.

# Answer
Generally speaking, personality rights prevent you from using another's name or likeness without permission.

There are exceptions, especially depending on your jurisdiction. The United States is particularly involved, as I recall, because many states have laws concerning publicity which may all differ slightly. It is best to talk with a lawyer familiar in the matter about your specific intent.

To determine who should be contacted to negotiate for a license to somebody's personality rights you should also consult a lawyer.
> 6 votes

# Answer
The consequences of using a celebrity likeness can lead to severe legal repercussions as Todd McFarlane could tell you.

> In the Spawn comic book series, Todd McFarlane created a mob enforcer character named Antonio "Tony Twist" Twistelli,\[2\] who McFarlane acknowledged was named after Tony Twist. Twist won a $15 million verdict in 2004 when a St. Louis, Missouri jury found Todd McFarlane Productions had profited from Twist's likeness.\[3\] The verdict was upheld after two appeals in June 2006.\[4\] In 2007, Twist and McFarlane settled the lawsuit out of court for $5 million.\[5\]\[6\]

Long story short - generally you cannot use celebrity likenesses for living figures. For dead, historical personages it's another story but still not 100% safe.

For living figures you can pretty much forget it. You can claim parody but only if the whole game is obvious parody and it helps a great deal if you are known as a comedic personality of some kind. Even so, nothing stops you from being sued on those grounds even if you are in the right and the legal bills could be quite expensive.

For historical figures you are generally OK but there still may be restrictions so it could be worth speaking to a lawyer, and anything touching on properties or companies that they may have been involved with is completely unprotected.
> 0 votes

---
Tags: game-design, copyright
---


# Question
Title: Unity - How to keep an object at the right or left of another object
I created a WallCheckRight and a WallCheckLeft linked to my character. However, I noticed that when my character do a flip, they switch place (right to left and left to right)

Is there any way to prevent that?

# Answer
> 3 votes
There are many ways to do this.

1) The easiest way to prevent that instead of changing animations like what Shraa has mentioned, is to restructure your hierarchy.

You only want to flip the scale of PlayerSpriteRenderer.

OR

2) Instead of using a empty gameObject's transforms to store left and right points, do it in code.

```
Vector3 rightWallCheck = transform.position + Vector3.right;
Vector3 leftWallCheck = transform.position + Vector3.left;

```

# Answer
> 0 votes
What flipping does is just change the scale from 1 to -1 (or whatever the value). So all colliders and children will have this effect that you're having.

What you could do is have animations for the player facing both right and left direction. Instead of flipping using scale, you can just switch between the animations.

Edit: Instead of changing animations, which will need you to have more sprites which may decrease performance and increase size, you should use the solution that Eclmist suggested

---
Tags: unity
---


# Question
Title: How to skip comparing if one of the value is null?
I am using libGDX - Ashley as entity-system framework. My problem is I don't know how do I avoid having a `java.lang.NullPointerException` when using `Comparator<Entity>` entity comparison. There is a situation where Entity is removed from the engine, but the `Comparator` is still continuing. Now how do I skip the comparing if one of the nearby is null?

```
@Override
public int compare(Entity nearby1, Entity nearby2) {
    Vector2 ownerPos = Mapper.transform.get(owner).position;
    Vector2 nearbyPos1 = Mapper.transform.get(nearby1).position; // possible null
    Vector2 nearbyPos2 = Mapper.transform.get(nearby2).position; // possible null
    return ...
}

```

When I sort the `Array<Entity>` for example, using my custom comparator, it returns an error because one of the entity is null or one of the component entity is null. I don't know what to return to make the comparison skip.

```
boolean skip = ownerPos == null || nearbyPos1 == null || nearbyPos2 == null;

if(skip) {
   return ???
}

```

I'm thinking of using try-catch statement to skip the sorting. But is this performance safe?

```
try {
   array.sort(comparator);
} catch(Exception e) {

}

```

# Answer
> 1 votes
I would say this responsibility should be located within the comparator. In other words if one is null and the other isn't the compare should return as -1 and if both are null it should return 0 (you might think to return -1 but this would violate the reflexivity requirement).

---
Tags: java, libgdx, entity-system
---


title: Issue implementing wall jump in Unity

text:
# Question
Title: Issue implementing wall jump in Unity
I'm having troubles implementing a satisfying wall jump in Unity. I managed to detect collision with a wall, but when I press the jump button, the result is alway weird or very weak. I think this have to do with the 2D physic in Unity, but I have no idead how to handle it correctly.

Here's my code with the concerned parts:

```
public void Move(float move, bool crouch, bool jump)
{
    // If the input is moving the player right and the player is facing left...
    if (move > 0 && !facingRight)
        // ... flip the player.
        Flip();
    // Otherwise if the input is moving the player left and the player is facing right...
    else if (move < 0 && facingRight)
        // ... flip the player.
        Flip();

    if (jump)
    {
        if (!grounded && walled)
        {
            StartCoroutine(WallJumpRoutine());
        }
    }
}

void Flip()
{
    // Switch the way the player is labelled as facing.
    facingRight = !facingRight;

    // Multiply the player's x local scale by -1.
    Vector3 theScale = transform.localScale;
    theScale.x *= -1;
    transform.localScale = theScale;
}

IEnumerator WallJumpRoutine()
{
    Vector2 wallJumpVector = new Vector2(jumpForce*10, 20f);

    GetComponent<Rigidbody2D>().AddForce(wallJumpVector, ForceMode2D.Impulse);
    yield return null;
}

```

To be more precise, the result I'm getting is either my player being moved a tiny bit (despite using the same force as my regular jump, which is working fine) or my player being moved a good distance but at very high speed (this is when I'm using `ForceMode2D.Impulse`).

Any help?

# Answer
> 1 votes
The velocity gained from AddForce in any particular direction is affected my a multitude of factors, including the current velocity of the rigidbody.

Two things you can try:

1) Setting velocity to zero before applying the force

```
GetComponent<Rigidbody2D>().velocity = Vector3.zero;
GetComponent<Rigidbody2D>().AddForce(wallJumpVector);

```

OR

2) Ditch addforce all together and control the velocity directly.

`GetComponent<Rigidbody2D>().velocity = wallJumpVector;`

Hope that helps.

---
Tags: unity
---


# Question
Title: How to force a custom component on every GameObject?
I want to have a custom component which will have a drop down. I want this to be applied to ever GameObject in the project, which means every GameObject in the hierarchy and every GameObject prefab. Something like a transform component. It should not be removable, and it should be added by default when creating new GameObjects.

In the drop down, I will select a few options, and I want to store those values in an array on that custom forced component for that GameObject.

So if I have 2 new GameObjects in scene named XYZ and ABC, and the component is PQR, I should be able to do this-

```
ABC.GetComponent<PQR>().someArrayVar = whatever;
XYZ.GetComponent<PQR>().someArrayVar = anotherWhatever;

```

Anyone know how to do this? Any help appreciated. Thanks in advance :)

# Answer
This is not possible because you are not allowed to derive from the GameObject class. The closest thing that I can think of would be to write an extension method for gameObject that both attaches your custom component to the gameObject, as well as updating your array.

```
public static class Helper {

    public static void ModScriptArray(this GameObject gameObject, Data arrData)
    {
        PQR script = gameObject.GetComponent<PQR>();
        if (script == null)
            script = gameObject.AddComponent<PQR>();

        script.someArrayVar = arrData;
    }
}

```
> 1 votes

---
Tags: unity, component-based
---


# Question
Title: How do I change iTween values at runtime?
I am trying to figure out how to run and change the speed of rotation on an iTween path at runtime. I'm trying to code it in Unity5 in C#. I have to rotate a few objects on an iTween path which I have created and I have to manage the speeds of the objects at runtime as they change.

**My problem is that:**
If I write the code in start method then it runs once within the whole game. How can I use this script in Update method so I can manage the speeds at the run time?

# Answer
> 2 votes
If what you're looking for is to change the speed of an ITween animation on runtime, you can place the object on the path manually.

```
float speed = 1;
float distance = 0;
Vector3[] path;
float pathLength;

void Start()
{
    path = iTweenPath.GetPath("path_name");
    pathLength = iTween.PathLength(path);
}

void Update()
{
    distance += speed * Time.deltaTime;
    float percentage = distance / pathLength;
    iTween.PutOnPath(gameObject, path, percentage);
}

```

You can now modify the `speed` variable on runtime, which alters the speed of movement along the path.

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


# Question
Title: jsonutility doesnt exist in the current context
I am working on converting a string into json format and sending the json formatted data to the server.Everything is working fine. I tested the project and exported the project.Current version of Unity I am using is Unity 5.3.5.

the problem is that when I imported this project package in Unity 4.7. Iam getting an error

**"The name "JsonUtility" does not exist in the current context"**

How can I resolve this issue by replacing with other function so as that get worked with Unity 4.7

Here is piece of code is used for converting into json format

```
  using UnityEngine;
  using System.Collections;
  using LitJson;
  //using SimpleJSON;

  using System.IO;
  public class JsonScript : MonoBehaviour {
  JsonData json;
  void Start()
   {
    Data1 data = new Data1();
    data.command = "state";
    data.payload = new Payload1() { text = "wwwwwww", image = "hello" };
    string json = JsonUtility.ToJson(data,true);
    P(json + "\t\n");

    }

// Use this for initialization
void P(string aText)
{
    print (aText +"\n");
}

 }

 [System.Serializable]
 public class Payload1
 {
    public string text;
    public string image;

   }

   [System.Serializable]
    public class Data1
     {
      public string command;
     public Payload1 payload;
     }

```

# Answer
According to the changelog of the documentation, the class JsonUtility was added in Unity Version 5.3.6. You said you used it in 5.3.5, so this seems to be incorrect. The earliest mentioning of it I could find is the release announcement for 5.3 which talks about "A new JSON API, that supports conversion of objects to and from JSON format".

So apparently the class JsonUtility requires at least Unity 5.3.

If you need JSON encoding and decoding in an earlier version of Unity, you will have to use a 3rd party library (or write your own).
> 1 votes

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


title: Difficulty with linked lists in drawing

text:
# Question
Title: Difficulty with linked lists in drawing
I've recently started game development in C++ and decided to make an ASCII based snake game. To hold the values of the snake tail I decided to use a linked list due to its flexibility when it comes to manipulating it.

Each node holds the x and y coordinates of a segment of the snake's tail.

The linked list is successful in holding data, creating a new node whenever the snake eats the fruit, but I do not know how to implement this data into my draw function.

I am aware of the issue being caused by a logical error in my program due to the while loop breaking my if else sequence. I just don't know how to fix it.

Here is my current draw function:

```
void draw() {
    system("cls");
    for (int i = 0; i < width+2; i++)
        cout << '#';
    cout << endl;

    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            if (j == 0)
                cout << '#';
            if (i == posY && j == posX)
                cout << 'O';

            Node *current = head->next;

            while (current != nullptr) {
                if (i == current->y && j == current->x)
                    cout << 'o';
                current = current->next;
            }
            if (i == fruit.y && j == fruit.x)
                cout << 'F';
            else
                cout << ' ';
            if (j == width-1)
                cout << '#';
        }
        if (i != height-1)
            cout << endl;
    }
    cout << endl;

    for (int i = 0; i < width+2; i++)
        cout << '#';
    cout << endl;

    cout << "Score: " << score << " || Tail len: " << tailLen << endl;

}

```

As you can see I've tried to retrieve the values from the nodes via a while loop. Unfortunately by doing so extra spaces are added and the frames are extremely glitchy. I've been racking my brain over this issue for ages. Any suggestions would be appreciated, thanks.

Screenshot:

# Answer
Let's go trough your code, especially this part:

```
        while (current != nullptr) {
            if (i == current->y && j == current->x)
                cout << 'o';
            current = current->next;
        }
        if (i == fruit.y && j == fruit.x)
            cout << 'F';
        else
            cout << ' ';
        if (j == width-1)
            cout << '#';

```

There are couple of logical errors here. Let's take a scenario, where you need to draw a snake tile:

You go trough each nodes of the snake, and you find one at the current position, so you draw an `o`. Next you check if there's a fruit at that position. If yes, then it'll draw an F there, if not, then a space. See, no matter what, you'll always draw at least 2 characters where a snake is, an o and a space or an o and an F.

The same happens if you're at the edge of the map. You draw a space for an empty tile **and** a hashtag.

To fix this issue, create a boolean flag wich marks if you found a snake at that tile and only draws a space if you didn't:

```
       bool found = false;
       while (current != nullptr) {
            if (i == current->y && j == current->x) {
                cout << 'o';
                found = true;
            }
            current = current->next;
        }
        if (!found) {
            if (i == fruit.y && j == fruit.x)
                cout << 'F';
            else
                cout << ' ';
        }
        if (j == width-1)
            cout << '#';

```
> 1 votes

# Answer
Your syntax is getting muddled because you're doing too many things at once: traversing the game space, traversing your snake (and fruits, walls, etc), and outputting. As you have seen, you don't have enough information at the innermost level to decide whether you should output one more character or not.

That can be solved by adding *more* logic as Bàlint's answer did, but it can also be done by splitting your code into more contained consituents. In your case, you must at one point decide on a *single* character to output in the current tile. That's a prefect use case for a lambda!

*Note: the code is untested*

```
void draw() {
    // Bring in some standard identifiers
    using std::cout;
    using std::endl;
    using std::system;

    system("cls");

    // Draw the top line of the playing field
    for (int i = 0; i < width+2; i++)
        cout << '#';
    cout << '\n';

    // Find out which character we should draw at a given position
    auto charAt = [&](int x, int y) -> char {

        // Left/right wall
        if(x == 0 || x == width - 1)
            return '#';

        // Fruit
        if(x == fruit.x && y == fruit.y)
            return 'F';

        // Snake head
        if(x == posX && y == posY)
            return 'O';

        // Snake body
        for(Node const *cur = head->next; cur; cur = cur->next)
            if(x == cur->x && y == cur->y)
                return 'o';

        // Default: empty space
        return ' ';
    };

    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++)
            cout << charAt(j, i);

        // `if` removed along with the redundant line break below
        cout << '\n';
    }
    // cout << endl;

    // Draw the bottom line of the playing field
    for (int i = 0; i < width+2; i++)
        cout << '#';
    cout << '\n';

    cout << "Score: " << score << " || Tail len: " << tailLen << endl;
}

```

I have replaced the `std::endl` calls with `'\n'`: `std::endl` forces a flush, which probably explain a good part of your frame gliching issues. You should use `std::endl` or `std::flush` only when you *really* want to halt the program, flush everything to the console, and then move on.

It looks like you're using `using namespace std;` at global scope as well. If so, you should stop doing it: it breaks the purpose of the `std` namespace completely. If you wish to omit `std::` for a portion of code, put the `using namespace` directive in the tightest scope possible, or better yet replace it with precise `using`-declarations.

There's still things that can be improved in this code:

* The code for drawing the top and bottom lines of the playing field are perfectly identical. Even if that doesn't hinder logic as much as the central issue of the question, that is a good candidate for refactoring inside a reused function.
* The loop that traverses the snake body will probably be useful elsewhere, such as when you're checking whether the snake bit its tail. Thus, it's a good candidate to be factored out into a function on its own.

That's all I've got! Have fun with C++ :)
> 0 votes

---
Tags: c++, data-structure
---


title: Random move to certain points?

text:
# Question
Title: Random move to certain points?
I want my enemy to move randomly to certain points on the scene. It moves to one point and then stops! It does not continue to the other points!

Here is my script:

```
using UnityEngine;
using System.Collections;

public class emove: MonoBehaviour {

NavMeshAgent ePath;
public GameObject[] POINT;

void Start () {
    ePath = GetComponent<NavMeshAgent>();
}

void Update () {

    foreach (GameObject waypoint in POINT) {
        ePath.SetDestination(waypoint.transform.position);
        ePath.speed = 2;

      // I write this, if you have different idea tell me please
        if (waypoint.activeSelf == false) // waypoint had it own script, when enemy touch any point it set off
        {
            ePath.SetDestination(waypoint.transform.position); // move to any other active waypoint.
            ePath.speed = 2;
        }
    }
}

```

What am I doing wrong?

# Answer
The problem lies in your Update(). You are setting a new waypoint for your NavMeshAgent *every* frame, throwing in *every* point without evaluating if your NavMeshAgent has reached the previous waypoint.

```
using UnityEngine;
using System.Collections;

public class emove: MonoBehaviour {

NavMeshAgent ePath;
public GameObject[] waypoints;
int currentPointIndex;

void Start () {
    ePath = GetComponent<NavMeshAgent>();
    currentPointIndex = Random.Range(0, waypoints.Length - 1);
    //Start navigating to first *random* waypoint
    ePath = SetDestination(waypoints[currentPointIndex].transform.position);
    ePath.speed = 2;
}

void Update () {

    //reaching current waypoint
    if (Vector3.Distance(waypoints[currentPointIndex].transform.position,
            transform.position < 1)
    {
        //Find next random waypoint
        currentPointIndex = Random.Range(0, waypoints.Length - 1);
        //Navigate to next waypoint
        ePath.SetDestination(waypoints[currentPointIndex].transform.position);
    }
}

```
> 2 votes

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


title: Where can I find the sprite base grid?

text:
# Question
Title: Where can I find the sprite base grid?
There's been many times where I've seen people use this tile grid. It's the one with the base pink background with deep purple bands around each section. Is this available online or will I have to make it myself?

# Answer
> 1 votes
Something like this?

Unfortunately, as Philipp mentioned, depending on your game it is unlikely that the grid would match your needs exactly. The one above is a 16px by 16px grid. For anything more specific, you'll probably have to make it yourself.

There is an answer on GraphicsDesign.stackexchange that shows how to make one using paint.net.

---
Tags: pixel-art
---


# Question
Title: Collisions on editor mode, or saving changes in play mode through script
I have a prefab that has a collider. This collider serves as an obstacle. The thing is that I want to remove this collider from all objects inside another collider defining the map limits.

This way, objects inside the game area will keep their collider, but those outside the play area get their collider removed, and serve just as decoration.

I can't use the OnTriggerEnter2D as physics are disabled in editor mode. But applying the changes in play mode is no good neither, as changes are not saved.

How can I create an script that checks if a collider is inside another collide in editor mode, so I can remove it if it does?

Or is there any way to create a script that runs on play mode and use the OnTriggerEnter to delete the collider I want, then save the changes for the editor?

Using bouding boxes is no good, as the collider delimiting the play area is an irregular polygon collider.

Any ideas?

# Answer
> 2 votes
There's a little hack that I used to do in order to save runtime object states. You simply create a prefab during runtime.

Presumably, you are only doing this in code because there is a large number of gameobjects. I will assume these objects are all childs of one parent object.

Next, run the game with a simple script that removes colliders from the obstacles in this collection of obstacles.

Then, in play mode, simply drag this parent `Obstacles` object into your project tab creating a prefab.

And voilà! You now have a prefab with colliders removed from certain objects.

Now go back to editor mode and replace the Obstacles object with your newly created runtime Obstacles object.

---
Tags: unity
---


# Question
Title: Decide whether bot is approaching or leaving
Consider a static obstacle placed in 3 Dimensional coordinate plane. A moving bot is programmed to pass through it. We know the position of obstacle. We also know the current position and current velocity of moving bot. Say, position and velocity are given as 3D vector.

How to decide whether the bot is approaching the obstacle or leaving the obstacle?

I think, the relative velocity should be able to differentiate it? Any approach please.

# Answer
Given the obstacle at position **A**, and the bot at position **B** with velocity **V**;
We calculate the dot product **p** = **AB · V** = **x**AB·**x**V \+ **y**AB·**y**V \+ **z**AB·**z**V.

Then **p** is:

* **\>0** if the bot is moving towards the obstacle;
* **\<0** if the bot is moving away from the obstacle;
* **0** if the bot is staying at the same distance (standing still or moving around the obstacle in a circle).
> 2 votes

---
Tags: 3d, software-engineering
---


# Question
Title: How to fake a 3d character displacement by sprite scaling in GameMaker?
I want my 2D sprite to become bigger when moving down the screen (closer to the camera), smaller when walking away and to maintain the same size when moving left or right.

The scaling along the y axis is fine but when I move left the sprite remains facing right. I have tied the `y_scale` to the `x_scale` so the sprite retains the correct proportions. Here is the problem:

For example, if the `image_yscale` is currently 9 and I want to move left, setting the `image_xscale` to -1 causes the sprite to shrink again. How can I flip the sprite along the `x_scale` while retaining the current size?

Here is my code:

```
// Sprite Scaling

if keyboard_check(vk_up)
{
    image_yscale -= 0.01
}

if keyboard_check(vk_down)
{
    image_yscale += 0.01
}

image_xscale = image_yscale

if image_yscale < 1
{
    image_yscale = 1
}

```

Thanks for any help in advance.

# Answer
So I think you want to change the line `image_xscale = image_yscale` to something like the following:

```
image_xscale = image_yscale

if keyboard_check(vk_left)
{
    image_xscale *= -1
}

```

Basically simply setting the `x_scale` to -1 when the player is walking left won't cut it, because that shrinks the sprite down as you said. As negative scales are considered as flipping the sprite around, this code should do the trick. Basically we use the value from `y_scale`, but invert it if the player is walking left.

EDIT: To fix the sprite flipping back to facing right when the player releases the left arrow, you need to introduce a boolean value that stores the last direction key held. So change your code to something like this:

```
image_xscale = image_yscale

if keyboard_check(vk_left)
{
    faceLeft = true
}
if keyboard_check(vk_right)
{
    faceLeft = false
}

if faceLeft
{
    image_xscale *= -1
}

```

Here `faceLeft` is a member value of your player object (or something similar, I'm not familiar with GameMaker).
> 1 votes

# Answer
In all honest, as much as i love GameMaker, i would not recommend this style of "2d" to be done using GameMaker.

But onto my approach to it!

After much thought, and some tinkering you probably want the character to gradually get bigger? Lets say yes.

So you have something in place for scaling? Good i don't have to re invent the wheel.

So we take your character, maybe use a Platformer physics *Based on the broad question, im doing my best here* So set up your platformer physics, and have them separate to the scaler. Now as for sprite fliping, your code is probably getting your scale\_sprite; and move\_object mixed up, so to fix this write a complete new method that does not affect the sprites size, and instead flip the sprite based on direction moved.

Use this;

```
image_index = 1;

```

Then every time your player pressed to move in a direction, flip it by using 1, or -1.

This is the way i would do it, but without knowing how you have implemented the scaling, i cant be 100% accurate with my answer.

I hope this helped, just throw a comment if you need any more help.
> 0 votes

---
Tags: sprites, game-maker, perspective, scale
---


title: 360 degree video of my OpenGL game

text:
# Question
Title: 360 degree video of my OpenGL game
I want to make a 360 degree video of my OpenGL game.

Concerning the rendering: Is it enough to render it in OpenGL with a specific projection matrix? If yes, which one? Or can I render it into a cube map, and then encode it? (Which will require much more rendering power and be more complicated, which I want to avoid)

And how do I encode a 360 degree video with FFMPEG?

# Answer
For performance reasons GPUs use some simplified approach to projection and assume that you want to project your geometry on a plane, so it works only for FOV angles \< 180 deg.

You could try some tricks in shaders and compute your custom projection there, but then you'll get into another problem - the assumption that polygons edges, being straight lines are rasterized also as straight lines. This assumption breaks for FOVs around 180 and more.

So basically what you can do is to render your scene into 6 separate views, and then join them in post-processing stage into one image.

And in case of encoding the video with FFMPEG - I think it works the same as for regular videos, you just need a different player to crop and pan the correct part of the frame.
> 4 votes

# Answer
You could also try Dual Paraboloid mapping. The idea is that you render your scene two times with a paraboloid projection - once for front and once for the back paraboloid. If you render the front and back paraboloid to two separate textures, you can combine them later with the inverse of the paraboloid projection to a 360 degree(-ish) image.
This technique is a bit more error prone than cubemapping around the edges where the two paraboloid maps connect, but can give you increased speed compared to rendering six times to cubemap faces.

UPDATE:
I've learned this technique from Kyle Hayward's blog sorry this I will post HLSL code but should be straightforward to convert to glsl):

Transform a vertex from view space to paraboloid space

```
output.Position = mul(input.Position, WorldView);
float L = length( output.Position.xyz );
output.Position = output.Position / L;
output.Position.z = output.Position.z + 1;
output.Position.x = output.Position.x / output.Position.z;
output.Position.y = output.Position.y / output.Position.z;
output.Position.z = (L - NearPlane) / (FarPlane - NearPlane);
output.Position.w = 1;

```

Map the dual paraboloid onto a sphere:

```
// calculate the front paraboloid map texture coordinates
float2 front;
front.x = R.x / (R.z + 1);
front.y = R.y / (R.z + 1);
front.x = .5f * front.x + .5f; //bias and scale to correctly sample a d3d texture
front.y = -.5f * front.y + .5f;
// calculate the back paraboloid map texture coordinates
float2 back;
back.x = R.x / (1 - R.z);
back.y = R.y / (1 - R.z);
back.x = .5f * back.x + .5f; //bias and scale to correctly sample a d3d texture
back.y = -.5f * back.y + .5f;
float4 forward = tex2D( FrontTex, front );    // sample the front paraboloid map
float4 backward = tex2D( BackTex, back );    // sample the back paraboloid map
float4 finalColor = max(forward, backward);

```
> 1 votes

---
Tags: opengl, rendering, projection-matrix, 360-video
---


title: Unlock cursor through script

text:
# Question
Title: Unlock cursor through script
I am using unity's default FPS controller script. My game switches scenes, and when it does I can't move the mouse. I know that this is because of unity's m\_mouselook's lock cursor is on. What I don't know how to do is turn that boolean to false through a different script.

# Answer
> -1 votes
If you are using Unity 5 just type `Cursor.LockMode = LockMode.Unlocked` or whatever the lock modes unlocked mode is

---
Tags: unity, input, mouse
---


title: OpenGL Perspective Issue

text:
# Question
Title: OpenGL Perspective Issue
I'm trying to troubleshoot a problem with my simple OpenGL test program, which I've written in C. I've written some math routines to do the matrix manipulation, but even after copying known working perspective functions, I cannot get anything to appear on screen.

The program is simply:

The only geometry is a simple cube centered around the origin, here is the render loop:

```
int renderer_draw_frame(float delta_time)
{
    glClearColor(0.2f, 0.3f, 0.2f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glUseProgram(prog);

    /* bind textures */
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, tile_tex);
    glUniform1i(glGetUniformLocation(spo_prog(spo), "Tex1"), 0);

    vec3f eye = { 0.0f, 0.0f, 3.0f };
    vec3f target = { 0.0f, 0.0f, 0.0f };
    vec3f up = { 0.0f, 1.0f, 0.0f };

    mat4f model_mat = mat4f_translate(0.0f, 0.0f, 0.0f);
    mat4f view_mat = look_at(eye, target, up);
    proj_mat = mat4f_projection(45.0f, (float)win_width / (float)win_height, 0.1f, 100.0f);

    glUniformMatrix4fv(modelLoc, 1, GL_FALSE, &model_mat.f[0]);
    glUniformMatrix4fv(viewLoc, 1, GL_FALSE, &view_mat.f[0]);
    glUniformMatrix4fv(projLoc, 1, GL_FALSE, &proj_mat.f[0]);

    glBindVertexArray(VAO);
    glDrawArrays(GL_TRIANGLES, 0, 36);
    glBindVertexArray(0);
    return 0;
}

```

mat4f and vec3f is just this:

```
typedef struct mat4f mat4f;
struct mat4f
{
    float f[4 * 4];
};

typedef struct vec3f vec3f;
struct vec3f
{
    float x;
    float y;
    float z;
};

```

The math routines in question:

```
#define M4(m,i,j) m.f[mat4f_idx(i,j)]
#define PI 3.14159265359f

mat4f mat4f_projection(float fov, float ratio, float near, float far)
{
    float d2r = PI / 180.0f;
    float ys = 1.0f / tanf(d2r * fov / 2.0f);
    float xs = ys / ratio;
    float nf = near - far;
    mat4f r = { 0 };
    M4(r, 0, 0) = xs;
    M4(r, 1, 1) = ys;
    M4(r, 2, 2) = (far + near) / nf;
    M4(r, 2, 3) = -1.0f;
    M4(r, 3, 2) = 2 * far * near / nf;
    return r;
}

mat4f look_at(vec3f eye, vec3f center, vec3f up)
{
    vec3f zaxis = vec3f_normalize(vec3f_subv(eye, center));
    vec3f xaxis = vec3f_normalize(vec3f_crossp(vec3f_normalize(up), zaxis));
    vec3f yaxis = vec3f_crossp(zaxis,xaxis);

    mat4f trans = mat4f_id(1.0f, 1.0f, 1.0f, 1.0f);
    M4(trans, 0, 3) = -eye.x;
    M4(trans, 1, 3) = -eye.y;
    M4(trans, 2, 3) = -eye.z;
    mat4f rot = mat4f_id(1.0f, 1.0f, 1.0f, 1.0f);
    M4(rot, 0, 0) = xaxis.x;
    M4(rot, 0, 1) = xaxis.y;
    M4(rot, 0, 2) = xaxis.z;
    M4(rot, 1, 0) = yaxis.x;
    M4(rot, 1, 1) = yaxis.y;
    M4(rot, 1, 2) = yaxis.z;
    M4(rot, 2, 0) = zaxis.x;
    M4(rot, 2, 1) = zaxis.y;
    M4(rot, 2, 2) = zaxis.z;
    return mat4f_mul(rot, trans);
}

```

Finally, the simple vertex shader:

```
#version 330 core

layout (location = 0) in vec3 position; //attrib pos 0
layout (location = 1) in vec2 texCoord; //attrib pos 1

out vec2 TexCoord;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

void main()
{
    gl_Position = projection * view * model * vec4(position, 1.0f);
    TexCoord = vec2(texCoord.x, 1.0f - texCoord.y);
}

```

Here is what I see:

If I change the shader as so:

```
void main()
{
    gl_Position = view * model * vec4(position, 1.0f);
    TexCoord = vec2(texCoord.x, 1.0f - texCoord.y);
}

```

I see:

Why does it completely disappear in projection view? I've tried changed the view look at parameter but I can't ever see anything through projection view. I've tried several different implementations, currently gluPerspective (the one above is pretty much that function copied).

I've been at this all night and I can't seem to get a grasp on what went wrong. Can someone gives me some pointers on where to go next?

# Answer
> 2 votes
This was caused by an uninitialized variable being fed into the projection function:

```
static int win_width; //is 0 at initialization
static int win_height; //is 0 at initialization

int renderer_init(int width,int height)
{
     <....>
     mat4f proj_mat;
     proj_mat = mat4f_projection(45.0f, (float)win_width / (float)win_height, 0.1f, 100.0f);
     <.....>
}

```

Caused the projection function to fail because of a division by zero (I believe). The matrix output was:

```
M(0,0): -nan(ind) M(0,1): 0.000000 M(0,2): 0.000000 M(0,3): 0.000000
M(1,0): 0.000000 M(1,1): 2.414213 M(1,2): 0.000000 M(1,3): 0.000000
M(2,0): 0.000000 M(2,1): 0.000000 M(2,2): -1.002002 M(2,3): -1.000000
M(3,0): 0.000000 M(3,1): 0.000000 M(3,2): -0.200200 M(3,3): 0.000000

```

In the projection function, M(0,0) is set by:

```
mat4f mat4f_projection(float fov, float ratio, float near, float far)
{
    float d2r = PI / 180.0f;
    float ys = 1.0f / tanf(d2r * fov / 2.0f);
    float xs = ys / ratio; // divide by zero
    < .... >
    M4(r, 0, 0) = xs;
}

```

I already had the static window width and height variables there, so setting them fixed the issue:

```
int renderer_init(int width,int height)
{
    win_width = width;
    win_height = height;
    < ... >
}

```

Resultant matrix (correct this time):

```
M(0,0): 1.810660 M(0,1): 0.000000 M(0,2): 0.000000 M(0,3): 0.000000
M(1,0): 0.000000 M(1,1): 2.414213 M(1,2): 0.000000 M(1,3): 0.000000
M(2,0): 0.000000 M(2,1): 0.000000 M(2,2): -1.002002 M(2,3): -1.000000
M(3,0): 0.000000 M(3,1): 0.000000 M(3,2): -0.200200 M(3,3): 0.000000

```

Picture:

If these matrices or projection code helps someone, you are more than welcome to use them. The problem was that I focused on the math instead of the simpler case of the variables not being initialized and it gave me tunnel vision. Instead of simply looking at the matrix to figure out *what* was wrong.

---
Tags: opengl, c, perspective, projection-matrix
---


# Question
Title: Optimizing thousand objects manipulation
I am developing a clone Minecraft for the purpose of study. I am working with Java and LibGDX. I have read some other codes on web, and reading LibGDX tutorials and currently I could develop something on map using Perlin Noise, etc.

But my biggest problem is the render performance. I splitted my map in chunks, as Minecraft does, but even with few elements on screen (2.000 blocks) the FPS drops to 20 by second on Desktop. Even if I not looking for any block.

My logic is that:

1. `Main()` calls `Region.draw()` to draw all loaded region chunks (currently about 16 chunks);
2. `Region.draw()` calls each `Chunk.draw()` to draw all blocks on each chunks, about 128 blocks (total 2048 blocks).

I really do not see reason to performance be poor like that. I read that small things like that send a lot of instructions to GPU, like each vertices coordinates, etc. and it make sense. But Minecraft do thinks even more complicated like that and works without lag on my PC. I could simulate, on Minecraft, a render of 51.522 blocks without FPS issues. So I think that there are some method to avoid upload my blocks each time to GPU, and just call draw on it directly (I don't know if I am on right direction).

I'm studying 3D game development currently, and I have a similar problem on Unity (lot of objects, low performance).

What I missing?

**My current code**

My current render with 20 FPS:

# Answer
Are you optimizing the geometry at all? Cull the unseen blocks and faces and combine like faces together so instead of four blocks side by side rendering eight triangles, you combine the four into one face, so only two triangles. This is called Greedy Meshing and I would highly suggest that you look into it. I also wrote a little something about this here, however, it is pretty outdated and juvenile compared to an Actual Greedy Mesh generator.

My other recommendation is to use "Chunks" like Minecraft does, and mesh this chunk into a single model, therefore you have only a single draw call instead of other deprecated ways of doing it, like rendering each block individually.

Good luck on your project. I had a lot of fun on my little voxel game.
> 1 votes

# Answer
One solution that is used in voxel-based engines is to compact zones of blocks into bigger block-zones, thus reducing the draw calls.

Let's take a 10x1x10 surface of blocks. You could compact this into 1 single *cube* instance and send that information to the gpu, instead of sending 100 block's info.

Of course you'd need to loop the textures instead of resizing them, and you may bump into other problems, but I'll let you expand on that idea by yourself.
> 1 votes

# Answer
That's pretty normal. The draw calls themselves affect performance a great deal. 2000 draw calls is simply way too many.

If you can't use instancing then you will have to somehow reduce the number of blocks you send.
> -1 votes

# Answer
The problem is, you're maxing out what your computer can handle, calls wise.

Look for objects that don't need to be updated.

If you look at minecraft, there are a lot of weird quirks that have to do with not updating all the blocks, such as "BUDs".

It's up to you to decide what's important and what's not important, separate it into chunks that take advantage of the data types, such as 16x16x16 chunks. Only update chunks near non static objects, such as players; minecraft doesn't even update near water half the time.

It's up to you to optimize your difficult-to-optimize type of game. Either that, or build a supercomputer.
> -1 votes

---
Tags: java, libgdx, performance
---


# Question
Title: OpenGL ES 2.0 Without The Use of Shaders
While refreshing my mind on OpenGL ES, I decided to read a few of the books I brought a while back and search for some tutorials online.

Whilst doing so, I came across many beginner's tutorials that show how to draw a triangle using simply the followings:

```
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
....
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);

```

or using simply:

```
glDrawElements

```

along with an index buffer.

However to my understanding, is that since OpenGL ES 2.0, one must supply both a vertex and a fragment shader and the modern rendering pipeline is:

```
Primitive Processing - Vertex Shader - Primitive Assembly - Rasterizer -
Fragment Shader - Depth Stencil - Color Buffer Blend - Frame Buffer

```

So my question is, how is it possible for those tutorials to draw without having any vertex nor fragment shaders using just `glDrawElements` or `glDrawArrays`? Or, does the program supply them automatically when no shaders are in use and when it detects that either or both `glDrawElements` and `glDrawArrays` are in use?

In addition, does the aforementioned flow of pipeline withhold when no shaders are in use?

Thank you.

# Answer
OpenGL ES 2.0 requires you to provide a set of shaders (vertex and fragment).

Those examples use the old shader-less OpenGL ES.

For an introduction use the old GLES1. Make sure you can draw something on screen. Then change the code to GLES2 adding the required shaders.

At least at that stage you'll know the issue will likely be in the shaders and not the rest of the draw calls.

Using shaders for 3D games effectively often requires first writing a shader code generator to generate many permutations (no light, 1 directional light, 2 directional lights, etc).
> 2 votes

---
Tags: shaders, opengl-es, opengl-es2, pipeline
---


# Question
Title: Unity 3D - Rotate (smoothly) towards a target
I wanted to know if there is a method on which I can rotate an object with an angle given (a float to be precise), I use trigonometry to calculate the angle between the two objects in a (x, z) plane perspective (using y as the height coordinates).

This is the code I use to calculate the angle, but I want to know if a float would be anough data (then pass a Vector3 with that angle calculation as the Y parameter, since I want to rotate the Y axis).

```
//Makes the player heads to the direction the ball is...
public float headOnBall()
{
    Vector3 playerPos = this.transform.position;
    Vector3 ballPos = ball.transform.position;

    float angle;
    float x = (playerPos.x - ballPos.x);
    float z = (playerPos.z - ballPos.z);

    if(playerPos.z < ballPos.z || playerPos.x < ballPos.x && playerPos.z < ballPos.z)
    {
        angle = (Mathf.Atan2(z, x) + (Mathf.PI * 2)) * Mathf.Rad2Deg;
    }
    else
    {
        angle = Mathf.Atan2(z, x) * Mathf.Rad2Deg;
    }

    return angle;
}

```

Thanks in advance.

# Answer
There's a few functions for this already in Unity 3D:
> 1 votes

---
Tags: unity, c#, angles, trigonometry
---


# Question
Title: How to open auto detect LAN connections?
After sucessfully creating my first online multiplayer with servers and clients in UDP, I am wondering how LAN connections works. As it is right now, I need to open a server and forward the ports for the server if public. In LAN, they connection is possible but requires the local IP address.

However, if we take Minecraft or Starcraft, the game is able to auto detects servers on your local network.

How are they achieving this ?

# Answer
To achieve this on a LAN you send a packet to the **broadcast address**.

For example if the network mask is 255.255.255.0 and the IP 192.168.1.100 you can send an UDP packet to 192.168.1.255 `(ip | ~mask)` and every computer on the LAN listening to the specified port *should* receive that packet.

Some rare network configurations don't let broadcast packets through, nothing you can do other than scan every possible IP addresses if that is the case.
> 1 votes

---
Tags: networking, multiplayer
---


# Question
Title: How can I guarantee a solvable Fifteen Puzzle shuffle?
I am making a 15 Puzzle game in C# that allows the user to enter a custom row and column value up to a maximum of a 10 x 10 puzzle. I am having problems with the shuffle method.

I want to make it so the puzzle is always solvable by first creating a winning puzzle then shuffling the empty space. The problem is it is too inefficient to call every click event each time. I need a way to invoke the click event of a button adjacent to the empty space but not diagonal. I also use an invisible static button for the empty spot. The `PuzzlePiece` class inherits from Button. I am not too sure how to do this.

Here is what I have:

```
private void shuffleBoard()
    {
        //5 is just for test purposes
        for (int i = 0; i < 5; i++)
        {
            foreach (Control item in this.Controls)
            {
                if (item is PuzzlePiece)
                {
                    ((PuzzlePiece)item).PerformClick();
                }
            }
        }
    }

 void PuzzlePiece_Click(object sender, EventArgs e)
    {
        PuzzlePiece piece = (PuzzlePiece)sender;

        if (piece.Right == puzzleForm.emptyPiece.Left && piece.Top == puzzleForm.emptyPiece.Top)
        {
            movePiece(piece);
        }
        else if (piece.Left == puzzleForm.emptyPiece.Right && piece.Top == puzzleForm.emptyPiece.Top)
        {
            movePiece(piece);
        }
        else if (piece.Top == puzzleForm.emptyPiece.Bottom && piece.Left == puzzleForm.emptyPiece.Left)
        {
            movePiece(piece);
        }
        else if (piece.Bottom == puzzleForm.emptyPiece.Top && piece.Left == puzzleForm.emptyPiece.Left)
        {
            movePiece(piece);
        }
    }

```

# Answer
> 6 votes
Separation of Concern, shuffling the board shouldn't be done by simulating a user, it should be done directly with the model (as in Model-View-Presenter)

```
class Puzzle
{
  IList<Direction> GetValidMoves();
  void MakeMove(Direction);
  enum Direction {Up, Left, Down, Right};
}

```

With a class similar to the one above you could shuffle the board in this manner (for instance):

```
Random random = new Random();
for (int i=0; i<ShufflingThoroughness; i++)
{
  var moves = puzzle.GetValidMoves();
  int chosenIndex = random.Next(moves.Count);
  puzzle.MakeMove(moves[chosenIndex]);
}

```

This is untested code, but would randomly pick any of the valid directions from the current puzzle state. You could remove the opposite of the previous move to prevent it from going back and forth, but it would be premature optimization (simply running the loop extra times would counter this and is probably faster than keeping track of the previous move and excluding it from the random sequence).

Once you have shuffled the board you read the internal state of the board (expose it through public properties on the puzzle) and set the view to match the model. Each time the player clicks one of the tiles next to the empty slot it would call `Puzzle.MakeMove(...)` using the direction to the empty tile. After each move you can call `Puzzle.IsSolved()` which would check if the puzzle is, in fact, solved.

This way your view can hold only the code necessary for rendering your puzzle nicely. Your presenter handles the mouse clicks as well as updates the view (`PuzzleView.ShowPiece(row, column, puzzlePiece)` would make a good start), and the model solves the core of the game. How you can move the empty piece around, and gives you the methods for moving it.

# Answer
> 5 votes
The solvability of an n puzzle can be tested (after shuffling) by computing the permutations of the puzzle.

"*While odd permutations of the puzzle are impossible to solve, all even permutations are solvable.*"

For the math behind this, please see http://mathworld.wolfram.com/15Puzzle.html

---
Tags: c#, .net, windows-forms
---


# Question
Title: What would be a fast way of detecting collision between 2 2d rotated rectangles?
Currently I am following this tutorial here for 2D collision detection: http://www.gamedev.net/page/resources/\_/technical/game-programming/2d-rotated-rectangle-collision-r2604

I have found that the way of converting the projected vectors to a scalar value doesn't seem to be correct and there are false reports of collision. I tried to only take the projected x value and using that as a scalar however this runs into the rare corner case of when the axis is pointing up the x values are all 0.

If there is a way to solve this problem it would be great. All help is appreciated.

# Answer
I realised I was just multiplying everything by a scalar and it would return the same result if I didn't multiply and just used the value
> 0 votes

---
Tags: 2d, collision-detection
---


# Question
Title: Line rect intersection - lines behave like rays
Why is this? I have a simple ship that is a 14x14 rectangle, and a contour map. I want to be able to determine when the ship hits the ground. Here's a link to the JSFiddle.

Here's what happens now: the crosshairs indicate where the ship "exploded". The red lines indicate the ground line that was last processed. It seems that the ship explodes when it hits the ray that the line is part of.

Here's the code...

```
function collision() {
  for(var i = 1; i < map.length; i++) {
    var res;
    var start = new VectorPoint((i - 1) * 20, map[i-1]);
    var end = new VectorPoint(i * 20, map[i]);
    c.strokeStyle = "#ff0000";
    c.beginPath();
    c.moveTo(start.x, start.y);
    c.lineTo(end.x, end.y);
    c.stroke();
    c.strokeStyle = "#00ff00";
    var d = VectorFunctions.sub(end, start);
    var len = VectorFunctions.len(d);
    d = VectorFunctions.norm(d);
    res = rectLineCollision(start, d);
    if(res != null && res > 0 && res < len) {
      var insec = VectorFunctions.add(start, VectorFunctions.mul(d, res));
      c.beginPath();
      c.moveTo(insec.x - 10, insec.y);
      c.lineTo(insec.x + 10, insec.y);
      c.moveTo(insec.x, insec.y - 10);
      c.lineTo(insec.x, insec.y + 10);
      c.stroke();
      console.log("Res: " + res + ", len: " + len);
      break;
    }
  }
  return res != null;
}

function rectLineCollision(start, d) {
    var largestMin = -Number.MAX_VALUE;
    var smallestMax = Number.MAX_VALUE;
    for(var i = 0; i < 2; i++) {
      var n = VectorFunctions.sub(shipCopy.body[i], shipCopy.body[i + 1]);
      n = VectorFunctions.norm(n);
      // the shipCopy.body is just an array of points
      var sub1 = VectorFunctions.sub(shipCopy.body[i], start);
      var sub2 = VectorFunctions.sub(shipCopy.body[i+1], start);
      var e0 = VectorFunctions.dot(n, sub1);
      var e1 = VectorFunctions.dot(n, sub2);
      var f = VectorFunctions.dot(n, d);
      if(Math.abs(f) > EPSILON) {
        var t0 = e0 / f;
        var t1 = e1 / f;
        if(t0 > t1) {
          var swap = t0;
          t0 = t1;
          t1 = swap;
        }
        largestMin = Math.max(largestMin, t0);
        smallestMax = Math.min(smallestMax, t1);
        if(largestMin > smallestMax) {
          return null;
        }
        if(smallestMax < 0) {
          return null;
        }
      }
      else if(e0 * e1 > 0) {
        return null;
      }
   }
   return largestMin > 0 ? largestMin : smallestMax;
}

```

# Answer
> 1 votes
```
 276   // v: VectorPoint
 277   // n: number
 278   div: function(v, n) {
 279     return new VectorPoint(v.x * n, v.y * n);
 280   },

```

Looks like you copied and pasted the `mul` method but forgot to actually change the operators to a divide.

Making those changes will fix your application.

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


# Question
Title: Meaning of errors when compiling Source animated assets
This question will be composed of 3 somewhat separate questions regarding the creation of animated assets in Source. The documentation is quite poor and I am having a hard time understanding the errors that the model compiler throws.

**1. Parent bones**

I was trying to modify the collision mesh of an existing animated asset. I was able to make it work OK when animated in Blender but when compiled it throws something along the lines of "joint1 and joint2 have no parents, there can't be two root bones".

In the model viewer I can see two collision boxes, one static and another that is animated but which doesn't behave as I expected (it moves like the original collision mesh of the asset).

The problem disappears when I make all the vertices of the collision mesh have the same parent bone. See https://developer.valvesoftware.com/wiki/Studiomdl\_Data#Triangles , it would be the field (first column).

So the question is: does source allow you to have a collision mesh where all vertices don't share the same parent bone ? if not, how could I go around making a collision box that could be deformed (not only translated with the common parent bone) ?

**2. Conflicting bone names?**

Sometimes, when creating certain skeletons the compiler throws the following error:

```
<Sergiy> Conflicting bone names: root vs root vs aaaa, try deleting one of the bones.
This is an old bug in studiomdl code that is about to be deprecated, so it may not be worthwhile fixing it

```

and the compilation is totally stopped. I tried renaming the bones, and changing the bones hierarchy to no avail. It should be noted that there are no two "root" named bones as the error might suggest. Even more, sometimes it shows three different named bones.

I don't understand what could be the cause of the error.

**3. bone\_followers**

Finally, I noticed that the .qc of the decompiled model of some asset has a part like this:

```
$KeyValues
{
    bone_followers
    {
        "bone" "joint15"
    }
}

```

what does this (bone\_followers) do?

# Answer
Regarding point 1, I think that it is just a limitation of the engine.

Regarding point 2, I decompiled Coach's model (from Left 4 Dead 2) and I started adding parts of his .qc to mine. In the end, I was able to solve the issue by adding this to my .qc (before **$CBox** although I don't think this matters):

```
$Attachment "eyes" "newroot" 2.92 -2.8 0 rotate 0 -89.37 -90
$Attachment "mouth" "newLeft" 0.84 -6.09 -0.16 rotate 0 -80 -90
$Attachment "survivor_light" "floorLeft" 6.3 25.2 0 rotate 0 0 0
$Attachment "forward" "newRight" 0 0 0 rotate 0 0 0
$Attachment "pistol" "floorRight" -3.48 2.17 -5.47 rotate -3.66 -0.47 96.14
$Attachment "weapon_bone" "colLL" 0 0 0 rotate 0 0 0
$Attachment "medkit" "barLeft" -1.34 -5.84 -1.37 rotate 5.03 77.16 0
$Attachment "primary" "colRR" 3.21 -5.16 -2.75 rotate -13.7 170.19 174.29
$Attachment "attach_R_shoulderBladeAim" "barRight" -11.07 -1.46 -5.33 rotate -90 -102.85 0
$Attachment "attach_L_shoulderBladeAim" "colLLg" -11.07 -1.46 3.69 rotate -90 -102.85 0
$Attachment "melee" "ledgeLeft" 2.87 -5.56 5.47 rotate 24.08 175.37 97.14
$Attachment "molotov" "colRRg" -3.78 -2.89 8.29 rotate -63.44 -74.67 -101.41
$Attachment "grenade" "ledgeRight" -0.8 1.38 9.33 rotate -90 -175.23 0
$Attachment "pills" "colRL" -3.1 0.74 -8.47 rotate -41.18 -88.48 -87.05
$Attachment "lfoot" "colLR" 0 5.25 0 rotate 0 0 0

```

You can read about what Attachment does here. The first string inside quotes is an identifier, so in principle the values shouldn't matter. I just copied them from Coach's decompiled .qc. Same with the numbers, I don't think their values matter.

The second string inside quotes is the name of one of my bones (of course, in Coach's .qc it was one of Coach's bones). In my case, I created an Attachment for every bone in my skeleton. I don't know if just adding an Attachment for the "conflicting" bones would have been enough.

Considering all this, I think the problem was indeed a bug and somehow doing this is sidestepping it. After adding those attachments the animated collision box is compiled correctly, and works as intended in game.

I haven't found an answer to point 3, so I will leave the question open.
> -1 votes

---
Tags: skeletal-animation, source-engine, valve
---


title: Line rect intersection

text:
# Question
Title: Line rect intersection
I've been reading Timothy Wright's "Fundamental 2D Game Programming With Java". I'm trying to apply its principles to a Lunar Lander game - it's a JSFiddle for now, and can be found here.

The problem is with the `collision` function. It never returns true. I don't actually understand how it works, I just ported it from Java to JavaScript. It would be nice if someone could enlighten me. (I'm bad at math...)

The ship is just a 14x14 rectangle (with an antenna on top :) ). It is translated with a translation matrix according to the changing velocity.

```
function collision() {
  for(var i = 1; i < map.length; i++) {
    var largestMin = -Number.MAX_VALUE;
    var smallestMax = Number.MAX_VALUE;
    var start = new VectorPoint((i - 1) * 20, map[i-1]);
    var end = new VectorPoint(i * 20, map[i]);
    var d = VectorFunctions.sub(end, start);
    var len = VectorFunctions.len(d);
    d = VectorFunctions.norm(d);
    for(var j = 0; j < 2; j++) {
      var n = VectorFunctions.sub(shipCopy.body[j], shipCopy.body[j + 1]);
      n = VectorFunctions.norm(n);
      var sub1 = VectorFunctions.sub(shipCopy.body[j], start);
      var sub2 = VectorFunctions.sub(shipCopy.body[j+1], start);
      var e0 = VectorFunctions.dot(n, sub1);
      var e1 = VectorFunctions.dot(n, sub2);
      var f = VectorFunctions.dot(n, d);
      if(Math.abs(f) > EPSILON) {
        var t0 = e0 / f;
        var t1 = e1 / f;
        if(t0 > t1) {
          var swap = t0;
          t0 = t1;
          t1 = swap;
        }
        largestMin = Math.max(largestMin, t0);
        smallestMax = Math.min(smallestMax, t1);
        console.log(largestMin + ", " + smallestMax);
        if(largestMin > smallestMax) {
          return false;
        }
        if(smallestMax < 0) {
          return false;
        }
      }
      else if(e0 * e1 > 0) {
        return false;
      }
    }
  }
  var t = t0 > 0 ? t0 : t1;
  return true;
}

```

The VectorFunctions namespace is defined as follows:

```
var VectorFunctions = {
  // v1: VectorPoint
  // v2: VectorPoint
  add: function(v1, v2) {
    return new VectorPoint(v1.x + v2.x, v1.y + v2.y);
  },
  // v1: VectorPoint
  // v2: VectorPoint
  sub: function(v1, v2) {
    return new VectorPoint(v1.x - v2.x, v1.y - v2.y);
  },
  // v: VectorPoint
  // n: number
  div: function(v, n) {
    return new VectorPoint(v.x * n, v.y * n);
  },
  // v: VectorPoint
  len: function(v) {
    return Math.sqrt(v.x * v.x + v.y * v.y);
  },
  // v: VectorPoint
  norm: function(v) {
    return VectorFunctions.div(v, VectorFunctions.len(v));
  },
  // v1: VectorPoint
  // v2: VectorPoint
  dot: function(v1, v2) {
    return v1.x * v2.x + v1.y * v2.y;
  },
  // x: number, y: number, w: number
  vectorW: function(x, y, w) {
    var v = new VectorPoint(x, y);
    v.w = w;
    return v;
  }
};

```

The VectorPoint class is here...

```
// x: number
// y: number
function VectorPoint(x, y) {
  this.x = x;
  this.y = y;
  this.w = 1;
};

```

# Answer
Same as your other question

Line rect intersection - lines behave like rays

```
  // v: VectorPoint
  // n: number
  div: function(v, n) {
    return new VectorPoint(v.x * n, v.y * n);
  },

```

You need to change the operators over to a divide.

Be aware of copy and pasting code, make sure all the building blocks are working first and foremost before tackling a higher-level problem. Unit testing would have caught this immediately.

Sorry for sounding like a nagging mum but it's problems like these that could waste you many hours.
> 0 votes

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


title: Rotating a circle on its axis

text:
# Question
Title: Rotating a circle on its axis
I have a circular shape object, which I want to rotate like a fan along it's own axis.

I can change the rotation in any direction i.e. `dx`, `dy`, `dz` using my transformation matrix.

The following it's the code:

```
 Matrix4f matrix = new Matrix4f();
 matrix.setIdentity();
 Matrix4f.translate(translation, matrix, matrix);
 Matrix4f.rotate((float) Math.toRadians(rx), new Vector3f(1,0,0), matrix, matrix);
 Matrix4f.rotate((float) Math.toRadians(ry), new Vector3f(0,1,0), matrix, matrix);
 Matrix4f.rotate((float) Math.toRadians(rz), new Vector3f(0,0,1), matrix, matrix);
 Matrix4f.scale(new Vector3f(scale,scale,scale), matrix, matrix);

```

My vertex code:

```
 vec4 worldPosition = transformationMatrix * vec4(position,1.0);
 vec4 positionRelativeToCam = viewMatrix*worldPosition;
 gl_Position = projectionMatrix *positionRelativeToCam;

```

But, it's not rotating along its own axis, it is flipping like a coin instead. What am I missing here?

# Answer
You apply your transformations in the wrong order. The usual way is scale first, then rotate, and lastly translate. Currently you are translating first, then rotating, and finally scaling.

See this question for more information.
> 2 votes

---
Tags: opengl, 3d, rotation
---


# Question
Title: How to put different textures on different sides of a Cube in DirectX 11?
I have recently learned how to texture a cube in DirectX with a single texture but **I am now trying to put multiple textures on a cube.** If your confused the photo below should clarify.

I am aware of the technique of Cube Mapping, but most tutorials online only use that method in the form of a Skybox which is not what I'm trying to achieve at the moment. **If someone can explain how I can have different textures for different cube sides or any shape** that would be great.

The MSDN documentation says that I need to use a Texture Cube/Array but it lacks information regarding implementation.

# Answer
It's quite simple. There are 2 approaches:

1. Split the model. Use one model per texture.
2. Merge the textures. Make one big texture out of many small textures. Then map the right parts of the texture to the faces of the model.

**Since you want it to work on any shape**, these are the primary tools you have. Later on there's also the option to write custom shaders, but you don't need that yet.
> 3 votes

---
Tags: c++, textures, directx, cubemap, multitexturing
---


# Question
Title: XNA player/tile collision not working perfectly
So I've built a map tile engine in XNA, and have been working on the player/tile collision. The method I'm using works well to some extent, but the player will often move through the walls and get stuck and I can't figure out what's going wrong.

Here's my player update loop. You can see I'm creating a motion vector based on player input, creating a new location where the player will move to, then getting the four surrounding tiles and checking each one for an intersect, then cancelling out the motion in that direction if necessary. If a tile is not null, it is assumed impassable.

Can anyone help point out my mistake?

```
    public override void Update(GameTime gameTime)
    {
        Motion = new Vector2();
        var newPosition = Position;

        //set movement speed
        Speed = 1;
        if (Controls.IsKeyDown(Keys.LeftShift))
        {
            Speed = 2;
        }

        //set movement
        if (Controls.IsKeyDown(Keys.S))
        {
            newPosition.Y += Speed;
            Motion.Y = 1;
        }
        if (Controls.IsKeyDown(Keys.W))
        {
            newPosition.Y -= Speed;
            Motion.Y = -1;
        }
        if (Controls.IsKeyDown(Keys.A))
        {
            newPosition.X -= Speed;
            Motion.X = -1;
        }
        if (Controls.IsKeyDown(Keys.D))
        {
            newPosition.X += Speed;
            Motion.X = 1;
        }

        //normalize speed vector to stop faster diagonal movement
        if (Motion != Vector2.Zero)
            Motion.Normalize();

        //calculate new position
        newPosition += Motion * Speed;
        var newBounds = new Rectangle((int)newPosition.X, (int)newPosition.Y, Width, Height);

        //check for block collision
        if (Motion != Vector2.Zero)
        {
            //get x,y tile index of player position
            var x = GetPlayerTileX();
            var y = GetPlayerTileY();
            //get surrounding 4 blocks
            var left = MapEngine.Layers[1].GetObject(x - 1, y);
            var right = MapEngine.Layers[1].GetObject(x + 1, y);
            var up = MapEngine.Layers[1].GetObject(x, y - 1);
            var down = MapEngine.Layers[1].GetObject(x, y + 1);
            //check for collision in all directions, and cancel motion accordingly
            if (left != null && left.Bounds.Intersects(newBounds))
                Motion.X = 0;
            if (right != null && right.Bounds.Intersects(newBounds))
                Motion.X = 0;
            if (up != null && up.Bounds.Intersects(newBounds))
                Motion.Y = 0;
            if (down != null && down.Bounds.Intersects(newBounds))
                Motion.Y = 0;
        }

        //move the player
        Position += Motion * Speed;

        //stops player leaving the map edge
        LockPlayer();

        //update bounds
        Bounds = new Rectangle((int)Position.X, (int)Position.Y, Width, Height);

        //camera follows player
        Camera.Position = Position;
    }

```

# Answer
> 1 votes
I think your issue is that you are incrementing `newPosition` twice. First you modify the corresponding components when you check for key presses from the player, and then you modify it again later with `newPosition += Motion * Speed;`. One or the other is unnecessary.

I personally would remove incrementing from the key checking, and simply set the `Motion` value.

---
Tags: c#, xna, collision-detection, tilemap, collision-resolution
---


# Question
Title: Picking cells which form a completed line between to 2d grid cells
I'm using Bresenham's line algorithm to calculate a "line" of cells between a start and end point on a 2D tile grid.

However, I'm using this during terrain generation to create a visible pathway, which means I need every cell to have at least one shared border with a neighbor.

This shows how the line algorithm is picking cells:

Yet if you imagine this as a road, there's no way to drive from one "segment" to the next.

How can I calculate a line that doesn't "jump" like this?

I've thought about using pathfinding or raycasting but they both feel like overkill because they worry about things I don't need here. I won't have obstacles to route around and I don't care about calculating ray intersections.

# Answer
> 1 votes
Lets start by defining an array 'p'. This array will contain booleans and will tell us if there is a path at a specific point on the terrain. The idea is that you will perform Bresenham's algorithm on that Boolean array and then you will create an "outline" for that line. Then you will add the line and the outline together, making the original line thicker.

Also another thing you could do is modify the line algorithm and make it so that it gives a thicker line.

# Answer
> 0 votes
Draw bresenham's line, adding the modified cells to a list, with the same number of "checked" flags. For each cell in the list, flag it, check how many unflagged neighbors it has, if it has 0 and is not the final cell in the array, then add a 4-connected cell between it and the next unmarked cell in the list, and continue.

This is based on image processing techniques in which you may outline or fill an area of pixels with a given color. Much like bresenham's you'll simply be filling the cells with a new map value instead.

---
Tags: 2d, algorithm, path-finding, grid
---


# Question
Title: How to confirm an actor location in a realtime multiplayer game at the exact same time on two devices?
I am trying to figure out how to make a game like Pong in multiplayer. I have two devices that run the same simulation. Now I want to make sure that each of them start at the exact same time and send packets from the host to the client that confirm the position of the ball.

I am not sure if this would be the right approach, but how do I make sure that both devices are running the same game?

# Answer
> 3 votes
The first fact that any multiplayer game needs to accept is: "No matter how good your connection is, there will always be some unknown delay between the server and clients."

Because of this, contemporary real time networked games "run" the game on the server and the clients are just snapshots that are as accurate as possible, given any network latency. Because of the speed of networks, it just appears as though both clients are completely synchronized.

In the case of a pong game, the server would keep track of the ball and paddle's coordinates and periodically push this data to the clients. The server is also the one running the movement of the ball and collisions with the boundaries or paddles. Whenever the clients receive updates from the server, they override whatever data they have with the server's data and then render the game.

In return, whenever the clients receive input from the user, like a command to move the paddle, they send the inputs to the server and then let the server take care of the details of the result of that input.

For fast networks, this is usually enough, but what if you have a bit of a laggy connection? Do you want your game to freeze or appear choppy when the network slows down?

Many clients solve this problem by using Client Side Prediction. In a nutshell, this means that you are actually running your game on the client AND the server. Note that the server is the authority and any updates that the server sends overrides the data that the client has. If the network slows down, your client will continue to show a smooth experience to the user, but when a server update comes in and disagrees with the client, then the client will correct itsself by using the server's data. Really bad lag will still certainly make for jumpy movements in this case, but this smooths out most of the minor latency issues.

Here is the most helpful article I have found on the subject. Also here is a post I asked about a similar issue which had some pretty good responses.

# Answer
> 1 votes
Alternative approach, roughly:

1. Synchronize the clients against a public time server. Works over UDP packets. If you do it carefully and grab enough samples, you'll get down to 1 or a few ms of accuracy. You bacically grab the external timestamps, average/process/etc. them, and compare those to your internal crystal's (see the QueryPerformance API if Windows) current timestamp (= crystal count), and resolve an offset plus a crystal drift (typically a few secs / 24h). Your time function must take that into account. Do NOT use the system clock of the OS - it may change (slowly, gradually) as the OS adjusts itself.
2. At startup, issue a command to all clients (an agreement) to start the simulation at a specific, nearby timestamp.
3. Sync the frame paints of the clients to happen at for example n\*0.02 seconds (if 50 fps), n\*0.025 seconds (if 40 fps) etc. Do NOT use time deltas, only absolute time/elapsed time since start.
4. Send the UDP packets between clients, always together with the sender's local (and correct) timestamp.
5. Always store your own client's most recent actions for the last say 2 seconds.
6. At each client, run the simulation of others using extrapolation/prediction/deadreckoning/etc, but when a packet comes in, rewind to the timestamp of that packet and redo the simulation up to "now", this time taking the clients' most recent actions, as well as your own ones, into account.

Clients should now perform in sync. But this is not at all an easy task, and will require a lot of tuning. You may still need an authorative element, depending on the nature of the simulation.

---
Tags: java, networking, multiplayer, synchronization, realtime
---


# Question
Title: How to calcolate moving vector of object by its rotation degress in 2d
i have object in game which is rotating when i move my joystick , now i need to calculate its movement vector by its rotation
the object always moving forward and controlled by the joystick , the joystick is only setting its direction by degree .
here is the image which illustrate the scene .
i need some formula of the vector which the object will move .

# Answer
> 1 votes
Enter trigonometry!

To calculate the velocity vector of the ship, you need to use the following formula:

```
v.x := sin(angle) * velocity
v.y := cos(angle) * velocity

```

Also, if your angle is in degrees, you may need to convert it to radian:

```
angleInRadian := angle / 180 * pi

```

---
Tags: 2d, movement, vector
---


# Question
Title: How do I have a camera follow my object in Unity?
I have an object that automatically moves by itself and I want the main camera to automatically follow it.(Like in games such as geometry dash and jetpack joyride) This is the code for the automatic moving object in case it is needed:

```
using UnityEngine;
using System.Collections;
public class automove : MonoBehaviour {
public static int movespeed = 5;
public Vector3 userDirection = Vector3.right;

public void Update()
{
    transform.Translate(userDirection * movespeed * Time.deltaTime);
}
}

```

So does anyone know any good scripts I could add to the main camera to follow this object that automatically moves? Thanks in advance!

# Answer
> 10 votes
1. Make the camera object a child of the object that's moving. This is super easy and doesn't take any additional scripts.
2. Make a script for the camera that will update its position based on a target object:

Example:

```
public GameObject target;
public float xOffset = 0;
public float yOffset = 0;
public float zOffset = 0;

void LateUpdate() {
    this.transform.position = new Vector3(target.transform.position.x + xOffset,
                                          target.transform.position.y + yOffset,
                                          target.transform.position.z + zOffset);
}

```

You'll want to do this in `LateUpdate` so you're sure the object you're tracking has already moved. The offsets will be something you decide for your game.

# Answer
> 6 votes
You cited games like "Jetpack Joyride" and "Geometry Dash" so I understand you are working on a 2D game with side scrolling view. I assume the Y is up and X is right.

In Jetpack joyride: \- the camera is fixed \- the player only moves along Y-Axis \- you move transform the level and background to simulate that the player is moving, so the player speed is instead *-enviromentSpeed*. You can imagine your player on a treadmill.

In "Geometry Dash" the camera has an added grade of freedom as is smooth-following the player along Y-Axis.

You can refer to the included "Unity Script Package" from Standard Assets script present in Unity called CameraSmoothFollow2D.

Here a video: https://www.youtube.com/watch?v=MBA\_r3pCtxo

The key part is the Update part where you update the Camera position to match the *target* position (generally the target is the main character and you want the same X and Y maintaining your current Z as Z is the distance between the player and the camera.). You generally don't want to instantaneously match his position but introduce some smoothing function or damp like this

```
Vector3 destination = target.transform.position;
destination.z = transform.position.z;
transform.position = Vector3.SmoothDamp(transform.position, destination, velocity, dampTime);

```

you put this in a script attached to your camera and velocity and dampTime are parameters to tune the camera behaviour

# Answer
> -2 votes
Hey I know this is old but I released a project on this with a 3rd person camera, fps camera and an rts camera on github. Here's the link

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


# Question
Title: Libgdx Box2d RevoluteJoint And Attached Body Interfering With Main Body's Y-axis
I am making a 2d platformer where the character has a melee attack. To achieve this, I created a new arm body which I attached to the player's torso body (comprised of two circles). However, this interferes with the player's y-axis, which now jumps around between 0, 1.4901161E-8 and -1.4901161E-8 unless the player stays still for a few seconds. This interferes with the sprite generation and jumping, the player keeps flipping back and forth between facing left and facing right and when jumping sometimes the player's fall slows down and they gently float to the ground. Can anyone explain why this is happening? Is it something to do with the physics simulation?

My code is a bit of a mess right now, but I will include it in case it's relevant. So, at the moment, I have a definePlayer() and redefinePlayer() method where the player body and the arm body are created. The definePlayer() is called on construction and redefinePlayer() is called when necessary. They're not fully polished yet to say the least, but here they are.

```
public void definePlayer(){
    BodyDef bdef = new BodyDef();
    bdef.position.set(24 / GameName.PPM, 32 / GameName.PPM);
    bdef.type = BodyDef.BodyType.DynamicBody;
    b2body = world.createBody(bdef);

    FixtureDef fdef = new FixtureDef();
    CircleShape shape = new CircleShape();
    shape.setRadius(6 / GameName.PPM);
    fdef.filter.categoryBits = GameName.PLAYER_BIT;
    fdef.filter.maskBits = GameName.PLAYER_BIT |
            GameName.COIN_BIT |
            GameName.BRICK_BIT |
            GameName.ENEMY_BIT |
            GameName.OBJECT_BIT |
            GameName.ENEMY_HEAD_BIT |
            GameName.ITEM_BIT;

    //create player's 'torso' (lower circle)
    fdef.shape = shape;
    b2body.createFixture(fdef).setUserData(this);
    shape.setPosition(new Vector2(0, -10 / GameName.PPM));
    shape.setRadius(3 / GameName.PPM);
    b2body.createFixture(fdef).setUserData(this);

    //create player head (upper circle)
    EdgeShape head = new EdgeShape();
    head.set(new Vector2(-2 / GameName.PPM, 6 / GameName.PPM), new Vector2(2 / GameName.PPM, 6 / GameName.PPM));
    fdef.filter.categoryBits = GameName.PLAYER_HEAD_BIT;
    fdef.shape = head;
    fdef.isSensor = true;
    b2body.createFixture(fdef).setUserData(this);

    //define right Arm
    PolygonShape rightArm = new PolygonShape();
    rightArm.set(armRVertices);
    fdef.shape = rightArm;
    fdef.isSensor = true;

    //set armR
    bdef.type = BodyDef.BodyType.DynamicBody;
    armR = world.createBody(bdef);
    armR.createFixture(fdef).setUserData(this);

    //define joint connecting right arm to body
    RevoluteJointDef rightArmDef = new RevoluteJointDef();
    rightArmDef.bodyA = b2body;
    rightArmDef.bodyB = armR;
    rightArmDef.collideConnected = false;

    rightArmDef.localAnchorA.set(0, 0);
    rightArmDef.localAnchorB.set(0, 0);

    rightArmJoint = (RevoluteJoint)world.createJoint(rightArmDef);
}

public void redefinePlayer(){
    Vector2 position = b2body.getPosition();
    world.destroyBody(b2body);

    BodyDef bdef = new BodyDef();
    bdef.position.set(position);
    bdef.type = BodyDef.BodyType.DynamicBody;
    b2body = world.createBody(bdef);

    FixtureDef fdef = new FixtureDef();
    CircleShape shape = new CircleShape();
    shape.setRadius(6 / GameName.PPM);
    fdef.filter.categoryBits = GameName.PLAYER_BIT;
    fdef.filter.maskBits = GameName.GROUND_BIT |
            GameName.COIN_BIT |
            GameName.BRICK_BIT |
            GameName.ENEMY_BIT |
            GameName.OBJECT_BIT |
            GameName.ENEMY_HEAD_BIT |
            GameName.ITEM_BIT;

    fdef.shape = shape;
    b2body.createFixture(fdef).setUserData(this);

    EdgeShape head = new EdgeShape();
    head.set(new Vector2(-2 / GameName.PPM, 6 / GameName.PPM), new Vector2(2 / GameName.PPM, 6 / GameName.PPM));
    fdef.filter.categoryBits = GameName.PLAYER_HEAD_BIT;
    fdef.shape = head;
    fdef.isSensor = true;

    b2body.createFixture(fdef).setUserData(this);

    world.destroyBody(armR);
    PolygonShape rightArm = new PolygonShape();
    rightArm.set(armRVertices);
    fdef.shape = rightArm;
    fdef.isSensor = true;

    //set armR
    bdef.type = BodyDef.BodyType.DynamicBody;
    armR = world.createBody(bdef);
    armR.createFixture(fdef).setUserData(this);

    //define joint connecting right arm to body
    RevoluteJointDef rightArmDef = new RevoluteJointDef();
    rightArmDef.bodyA = b2body;
    rightArmDef.bodyB = armR;
    rightArmDef.collideConnected = false;

    rightArmDef.localAnchorA.set(0, 0);
    rightArmDef.localAnchorB.set(0, 0);
    rightArmJoint = (RevoluteJoint)world.createJoint(rightArmDef);

    timeToRedefinePlayer = false;
}

```

# Answer
> 0 votes
If I understand your question correctly, this is indeed most likely the physics simulation. Any two objects that are attached will influence each other.

If you don't want the arm to influence the body so much, try playing around with density of the different objects. In the extreme you could have an arm with a density of 0 and make it a sensor. You can then still implement yourself what happens when the arm collides with other objects. The best way to do this would be through a listener class.

---
Tags: libgdx, box2d
---