# Question
Title: OpenGL Poor FPS when models outside view
I have been testing my game to see how well it renders a few hundred complex models onscreen at once point but even when all the models are outside my viewpoint, i still get poor fps.

I have face culling enabled to get rid of back facing triangles, but I'm not sure how to stop processing triangles behind or outside my viewpoint.

# Answer
> 2 votes
As the comments under your question suggest, frustum culling is the way to improve performance.

To explain further:

The graphics hardware pipeline does not differentiate between what the camera can see and cannot. At the vertex shader stage, all that's happening is that a matrix transformation is applied to every vertex, and some other per-vertex work is done. Then (to simplify) rasterization takes place and then lighting & other work is carried out per fragment (or pixel).

In order to reduce the amount of work the gpu does, you must filter out what the camera cannot see, as to render those elements would be unnecessary work.

consider the following image:

This is a 2d representation of a frustum, with the red circle outside, and the green inside.

Think of a frustum in 3d as a trapezium. It has six faces, all of which have a face normal. For each face, project the cameras position, and the circle, or sphere's position onto the normal, and if the sphere's projection, += it's radius, is less than the camera projection, then on that side it can be deemed to be intersecting the frustum.

If this is true for all faces, then the sphere is at least partially inside the frustum, and is therefore visible, and so should be renderered. If this is not true for at least one face, then it is not visible and so should not be rendered.

It is relatively trivial to compute the frustum dimensions, and the maths can be found here.

To save on additional processing, you can have a flag in your camera, which marks it as "dirty" if it moves, which in turn, lets the rendering system know that the frustum needs updated for that frame.

---
Tags: opengl, c++
---


# Question
Title: Game build in unity3d project transfer from a previous developer
Can someone help or give me some idea what are the necessary deliverables from a previous developer that I need to ask regarding the game project transfer?

The situation is, there is a company that is developing our game in unity3d and it is already available in Apple store and Playstore. They developed it from scratch and on our part, we are just doing the game testing process. So now, we are going to ask them to transfer the entire project development to us. The company is in another country so we are just communicating thru emails, and we never done the communication by video calls.

And That's it. what are the things they need to transfer to us?

Thanks in advance.

# Answer
Assuming that your game exists in a single Unity project, the bare minimum that you'll *need* from them is the project folder that the project belongs to. This is enough to build and run the project and you'll have access to all of the code and assets used in the project.

Anything beyond that is somewhat optional, but it may be a good idea to ask for their acquisition, assuming they were used by the previous developers.

* **Asset Project Files**: Things such as Photoshop PSDs, Maya Projects, etc. Anything that may increase productivity and make it easier to make changes to existing game assets.
* **Game Design Documents**: This is assuming that the previous developers had creative responsibilities on the game, but if so, it may be a good idea to ask for any documents they've used so that you have an appropriate understanding of what they were going on.
* **Project Management**: Anything from a to-do-list text file to a Trello or Slack. Anything that was used by the previous developers, and may alert you of existing bugs or unfinished systems in the project, so that you know how to properly continue where they left off.
* **Unity Version**: If they're not using the latest version of Unity, it would probably be a good idea to know what version they were using, since large projects may contain many breaking changes when ported to a newer version.
* **Unity Asset Store Extensions**: Most assets that any previous development team used will be included in the Project file, and will work fine, but I can imagine some that used advanced DRM/Authentication systems may pose a problem when launched on a new system. It may be a good idea to ask for a list of third-party assets that the previous developers used, not only so you know what to expect if you encounter problems, but also so you'll have the same tools that they used for development.

You should be able to communicate with the previous developers if you encounter any problems with the transition, or find out that there's something you need that they haven't provided.
> 3 votes

---
Tags: unity, c#, project-management
---


title: AdMob - my own impressions

text:
# Question
Title: AdMob - my own impressions
I wanted to test my in-game ads and I forgot to add my device as a `Test Device`. My game is not yet in Google Play and App Store but I have 12 impressions on AdMob. What I have to do in this situation? I know that Google bans for fake click and impression so what can I do? do I have to inform Google about that?

Thank for help.

# Answer
> 2 votes
I can't imagine that you'll get banned for just forgetting to add your device as a Test Device. Plenty of developers make this mistake; it's nothing to be worried about.

The rule against fake impressions is most likely just to prevent someone from sitting there for hours, clicking on every ad that they're presented, and just raking in money for fake impressions.

If your account hasn't been suspended or you haven't been contacted by AdMob, I don't think you need to worry about it. If anything does happen, you can just tell them that you forgot to add your device as a Test Device. From what I could tell from AdMob's Help Center, **if your account is disabled for Invalid Click Activity**, you can repeal it at this link.

---
Tags: c#, c++, java, android, ios
---


# Question
Title: Uniforms stop working when loading multiple programs via glUseProgram()
The rendering keeps happening, and the debugger shows my camera is getting its position updated properly, but for some reason the camera doesn't appear to have its position updated. I'm not sure what I'm doing wrong.

Can uniforms fail to get set when swapping between different programs/shaders?

# Answer
> 2 votes
*This is what I get for following bad tutorials online where their code works with a single shader, but fails when you do multiple...*

A newbie mistake on my part, my code looked like this (assume everything was compressed into one long function):

```
//...

glGetUniformLocation(prog1, ...);
glUniformMatrix4fv(...);

glUseProgram(prog1);
glDrawElements(...);

//...

glUseProgram(prog2);
glDrawElements(...);

//...

```

This occurred because `glUseProgram()` has to be called before updating the uniforms, because otherwise the second `glUseProgram()` was called, which left it active, and when the uniform setting started again it would be using `prog2` instead since that was loaded from the previous cycle, causing the uniforms to never get updated and looking like it froze.

Meaning it should have looked like this:

```
//...

glUseProgram(prog1);  // Move this before.

glGetUniformLocation(prog1, ...);
glUniformMatrix4fv(...);

glDrawElements(...);

//...

glUseProgram(prog2);
glDrawElements(...);

//...

```

Upon doing this, everything works great again.

**Note:** If I checked `glGetError()` I'd also have noticed an error when trying to get the uniform, which was in line with what is seen in the official documentation.

---
Tags: opengl
---


# Question
Title: Unity 3D [C#] - How to properly reset a scene
I have a problem when I try to reset a scene. It doesn't seem to run, I have a script (of all scripts that have Awake and Start methods on that scene) that on the Awake method starts a coroutine, but when reseting the scene it doesn't even run it. I've read that it may be a problem of using the DontDestroyOnLoad method, but that doesn't seem to solve the problem since that script on the start takes a lot of references of objects that are only on the scene that I want to restart. I don't use any static variables on any script.

I made an unitary test trying to restart a scene with just one object and one script attached, on its Start method it also starts a coroutine but even in that test it doesn't even run the coroutine.

Here's the script of the unitary test:

```
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;

public class LoadingSceneController : MonoBehaviour
{
    void Awake()
    {
        DontDestroyOnLoad(this.gameObject);
    }
    //Scene scene;
    // Use this for initialization
    void Start()
    {
        //scene = SceneManager.GetActiveScene();
        DontDestroyOnLoad(this.gameObject);
        useStartCoroutine();
    }

    void useStartCoroutine()
    {
        StartCoroutine(loadScene());
    }

    IEnumerator loadScene()
    {
        yield return new WaitForSeconds(3);
        SceneManager.LoadScene("gameplayScene 1");
        //SceneManager.LoadSceneAsync("gameplayScene 1");
    }
}

```

# Answer
> ...the Awake method starts a coroutine, but when reseting the scene it doesn't even run it.

The Awake method is only called when a script is first loaded. Because your script has `DontDestroyOnLoad` (which you don't need to put in `Start` because you already have it in `Awake`), it will be carried over to any new scene that you load, and it **will not be loaded again,** so `Awake` will not be called again.

What you want is a method that subscribes to the `SceneManager.sceneLoaded` event:

```
private void OnEnable()
{
    SceneManager.sceneLoaded += OnLevelLoaded;
}

private void OnDisable()
{
    SceneManager.sceneLoaded -= OnLevelLoaded;
}

private void OnLevelLoaded(Scene scene, LoadSceneMode loadSceneMode)
{
    Debug.Log(string.Format("The level '{0}' was loaded.", scene.name));
}

```

This code will be called between the `Awake` and the `Start` methods when loading a scene.

A bit unrelated, but it's important to note that, because your original code has `DontDestroyOnLoad`, if you switch from a scene that has your `LoadingSceneController` object within it to a different scene, and then switch back to that scene, it will create a second instance of your `LoadingSceneController` object. You can fix this by spawning your `LoadingSceneController` object through code only once (if it doesn't already exist), or adding some code at the beginning of your script's `Awake` that will destroy its `gameObject` if another object with that script already exists.
> 4 votes

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


# Question
Title: Unity reflections going white with camera movement
Please refer to this video to understand the issue I am facing.

With camera movement, there is a strong white reflection that appears over the complete model. What settings do I need to change to fix this ?

# Answer
> 2 votes
This looks like a specular problem. Assuming you're using the Unity 5 Standard Shader, try turning down the `Metallic` and `Smoothness` sliders, or the Specular's `Smoothness` slider if you're using the Specular workflow.

If you're using the **Metallic** workflow, and you supplied a texture to the `Metallic` map, keep in mind that:

> The Metallic levels for the material are controlled by the values in the **Red** channel of the texture, and the Smoothness levels for the material are controlled by the **Alpha** channel of the texture. (This means the **Green and Blue channels are ignored**).

(From Unity's Metallic Parameter Documentation)

Although, if you lower these sliders all the way, the smoothness won't have any effect.

If you still have the problem, you may want to look into the `Lighting` tab or see if there's any `Reflection Probes` that haven't been set up properly, but from the video it looks to be a specular issue.

---
Tags: unity, rendering, camera, reflection-rendering
---


# Question
Title: Should the objective of a game be obvious to the player?
Watching game dev talks and reading articles about 'good' game design, it seems consesus a game should always make the objective obvious to the player, making clear what 'skill check' is being made and what to do to advance in the game.

Thinking about this, I don't agree. Figuring out what the game wants you to do was an important aspect of older games like e.g. *Silent Hill* or *Castlevania: Symphony of the Night*.

In *Silent Hill* you have a map with marker notes on it, which add up progressing the story. These notes are more a 'log' of what happened, than a 'to do list'. Newer games, instead of kindly pointing the player to another part of the level, tend to be too helpfull, providing specific instructions on where to go and what to do there.

Is this type of challenge deprecated? In order to increase the market penetration of games? Or are there objective reasons to abandon this approach to game design? What are alternatives to this kind of challenge?

# Answer
> 3 votes
A good example of "figure it out yourself" is the game Antichamber. https://en.m.wikipedia.org/wiki/Antichamber

In that game you're literally told nothing; you have to figure it out by yourself. This leads to really good discovery mechanics. Some walls, as an example, will go away if you look at them for a few seconds. Some floors disappear if you walk too fast over them. Some halls are infinite...or are they? Maybe if you don't give up they will actually end. Some rooms change only if you walk into them backwards, etc. It's all psychological. The player discovers the rules through trial and error.

I would say it depends on the game. Antichamber was designed to be a psychological adventure game, it was meant for the player to figure it out. In the beginning you feel a sense of accomplishment, like an infant learning how to walk. Obviously, games like Call Of Duty shouldn't be like this, because it isn't the intended/desired playstyle.

---
Tags: game-mechanics, single-player
---


title: Random Disconnects on UNET

text:
# Question
Title: Random Disconnects on UNET
Using UNET, I can't host a game for more than a few minutes unless both server and client are on the same computer. It appears that I am not alone in this.

Essentially, any latency problems or packet loss triggers an immediate disconnect. Rather than just getting lag, the client gets booted.

Does anyone know how this could be dealt with?

# Answer
> 2 votes
you can try changing delay value in Network Manager from 0.01 to any higher value. 0.9 worked normally for me.

---
Tags: networking, server, unity-networking
---


# Question
Title: Is there anyway to filtere a texture in glsl that turns stair like texels into smooth lines
I'm trying to filter a static, low resolution shadowmap. Unfortunatly, it doesn't look smooth, because of the way the default trilinear filtering works.

It does have a smooth transition from light to shadow, but you can still see pixelation in the texture. Now I am wondering if there are some techinques to hide these blocky texels with some custom filtering tricks, and make it look a bit more natural.

Imagine a low resolution texture with a 2 pixel wide, perfectly diagonal line. Now I'd like this texture to be rendered in a way that makes the line look like it was actual a high resolution line, by basicly filling all the hard edges between the background and the line with triangles facing towards the line, in order to make it look smoother.

Is there some custom filtering trick that allows me to make my shadowmaps look just a bit more anti-aliased?

# Answer
> 0 votes
There is, it's called **PCF** (Percentage Closer Filtering). There are good tutorials on it, too.

Another way are variance shadow maps, however they are more complicated to understand. There are good video tutorials for both by "thebennybox" on YT, I found those really helpful.

---
Tags: glsl, shadows, antialiasing, filtering
---


# Question
Title: Filling of a multidimensional array with string
I'm trying to fill a dropdown with a lis,t if some input is correct.

now when trying to create the list from a text file (to save the program) i should split the line on a comma so i have 3 settings for one asset: For ex asset1,colour,used,broken. the list should show the asset if the item is broken (0 is not broken, 1 is broken).

```
 public string[,,,] UsedAssetList;

string[] lines = System.IO.File.ReadAllLines(@"" + Application.persistentDataPath + "/assetlist.txt");
    cmbAssetNumber.ClearOptions();
    for (int i = 0; i < lines.GetLength(0); i++)
    {

        UsedAssetList = ***lines[i].Split(',')***;
        if (UsedAssetList[i,0,0,1] == "1")
        {
            list = new Dropdown.OptionData(UsedAssetList[i,0,0,0]);
        cmbAssetNumber.GetComponent<Dropdown>().options.Add(list);
        }
    }

```

The `lines[i].Split(',')`gives me the error:

```
Error   CS0029  Cannot implicitly convert type 'string[]' to 'string[*,*,*,*]'

```

I think everything is on point, except the filling of my list. any idea on how i can get this right?

EDIT: I was thinking the list should look like this: `{{"asset1","Gold","1","0"},{"asset2","Green","0","1"} , ... }`

EDIT: While the text file looks like:

```
asset1,Gold,1,0

asset2,Green,0,1

...

```

# Answer
Found a way to fill the dropdown with the needed info: Using a mulitdimensional array was not needed.

my code to get it working:

```
public string[] UsedAssetList;
void ReloadDropdown()
{
    string[] lines = System.IO.File.ReadAllLines(@"" + Application.persistentDataPath + "/assetlist.txt");
    cmbAssetNumber.ClearOptions();
    for (int i = 0; i < lines.GetLength(0); i++)
    {
        UsedAssetList =  lines[i].Split(',');

      if (UsedAssetList[3] == "1")
       {
            list = new Dropdown.OptionData(UsedAssetList[0]);
               cmbAssetNumber.GetComponent<Dropdown>().options.Add(list);
      }
    }
}

```
> 1 votes

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


title: Mouse position to World Position, help!

text:
# Question
Title: Mouse position to World Position, help!
I have a plane `GameObject` on which I want to place cubes. The user can move the cube around on the plane and when LMB is clicked, the cube is placed at that position. Everything works great, besides the position of the cube is not that accurate. In the center of my plane, mouse pointer and cube position match perfectly, moving the mouse along the x-Axis also works fine, but up or down (z-axis in game world) doesn't work well, the mouse moves "more" than the cube object. Here's photos of the issue:

and here's my source code:

```
void Update()
    {
        Vector3 m = Input.mousePosition;
        Vector3 n = Camera.main.ScreenToWorldPoint(new Vector3(m.x, m.y, 1));
        float camDistance = (float)Math.Sqrt((Math.Pow(n.y, 2.0f) + Math.Pow(6, 2.0f)));
        Vector3 p = Camera.main.ScreenToWorldPoint(new Vector3(m.x, m.y, camDistance));

        cube.position = new Vector3(p.x, 0.3f, p.z);
    }

```

At first I used `camDistance` as a constant that doesn't change (distance from the camera to the center of the plane), then I tried to adjust it depending on where the object is (distance from the camera to the mouse position in world coordinates). It still doesn't look great, so I need some help.

Thank you!

# Answer
> 1 votes
I suggest using a raycast for this, either a physics one or a collider one. It's way easier than dishing out your own math calculations (probably faster and less of a resource hog too).

Something like this

```
Vector3 hitPosition;
void Update()
{
    if(Input.GetMouseButtonDown(0)) //check if the LMB is clicked
    {
        RaycastHit hit;
        Ray ray = camera.ScreenPointToRay(Input.mousePosition);

        if (Physics.Raycast(ray, out hit)) //check if the ray hit something
        {
            hitPosition = hit.point; //use this position for what you want to do
        }
    }
}

```

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


# Question
Title: Unity5 using non-convex meshcollider with rigidbody
I want to build a car using wheel collider, mesh collider and rigidbody. The problem is that unity wants the meshcollider to be convex, and that cannot happen because my base model is bigger than 255 poly's.

# Answer
> 1 votes
You should consider using a separate, lower-poly mesh for your mesh collider. Not only will it fix your problem (if you can manage a mesh that's lowpoly enough to be convex), but it will also make physics calculations much less expensive.

If your mesh has concave shapes that you need to be reflected through your colliders, you can split your mesh up in your 3D modeling program of choice and generate multiple collider meshes, then use multiple mesh colliders.

There are even commercial Asset Store tools that do this procedurally., but it should be trivial to do in any 3D modeling software.

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


# Question
Title: Mono Develop unable to load plugins or editor
When I load up MonoDevelop, it gives me an error, saying how it could not load the C# editor and plugins for my project. I have had this problem for as long as I can remember, and I can still use MonoDevelop to create scripts.

However, MonoDevelop no longer acts like an IDE, more like Notepad+. The lack of plugins causes MonoDevelop to lose even the most basic form of line suggestion. How do I fix this error, and restore the IDE capabilities of MonoDevelop?

---

> Could not load project 'Welp.CSharp.Plugins.csproj' with unknown item type '{E097FAD1-6243-4DAD-9C02-E9B9EFC3FFC1}'
>
> Could not load project 'Welp.CSharp.csproj' with unknown item type '{E097FAD1-6243-4DAD-9C02-E9B9EFC3FFC1}'
>
> Could not load project 'Welp.CSharp.Editor.csproj' with unknown item type '{E097FAD1-6243-4DAD-9C02-E9B9EFC3FFC1}'

# Answer
This is not the first time someone has raised an issue with an IDE reporting "unknown type '{E097FAD1-6243-4DAD-9C02-E9B9EFC3FFC1}'".

---

There are multiple answers, and they all seem to arrive at the same consensus: To fix this problem, *and actually re-enable the IDE functionality*, you should reinstall the software. This seems to be the only solution that has resulted in the IDE functionality resuming, and also covers the solutions for other potential causes:

* Some users have been able to simple "repair" their original installation; others have not. If the option is available, it is certainly worth the try.
* The problem may be caused by incorrectly installed .NET frameworks.
* The IDE might have a *differant* issue, where it *thinks* it can not support your project.
* The problem may be caused by an inconsistency in the .proj file, but feedback suggests that manually fixing this error *will not* resume IDE functionality. *If you want to try*, the suggestion is to remove `"<ProjectTypeGuids></ProjectTypeGuids>"`.

If you try this option, make sure you back up your projects, first. It might also be a good idea to double check the *version* of Unity you are using, if you do not automatically update. Older versions of the software are available from the website, if you do not wish to download the latest release.

---

It is worth noting that in the previously linked question, the top answer addresses this error as a result of *piracy*. This is *very unlikely*, especially in this case, given that MonoDevelop is a *free* IDE, and provided alongside Unity.
> 2 votes

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


# Question
Title: Offset direction stops working when I get too close
I have a script trying to get the gun aim at the target instead of the origin:

It's partially working.

but when I get too close with the mouse the player starts spinning

I would appreciate a help regarding why it happens and how to fix it.

# Answer
> 1 votes
You're using `image_angle` (the current rotation) to calculate the new rotation for your character, this is what's making it spin - it just keeps summing every frame.

If your goal is to make the character's weapon point at the mouse, take a look at the answers here.

---
Tags: 2d, game-maker, debugging
---


# Question
Title: What methods exist to implement a 2D looping world?
I would like to know what other methods exist to implement a 2D wrapping world.

I know the simple modulo solution *(ObjectPosition % MapSize)* but that doesn't really fulfills my requirements. My issue with this easy solution that it only works on points and not on objects.

I was trying to clone / duplicate my objects and make them visible on both sides of the level that way but it doesn't really works out with box2d physics. So i am thinking if there is any other solution?

I would like to make my game world a truly looping cylindrical world, but i don't know what other methods exist to implement such a thing in 2D.

# Answer
> 2 votes
Having a looping world can be summarised into two portions Rendering and gameplay.

**Rendering**

First divide up your world into chunks. The chunks preferably should be of equal length for easy tiling. Hide the seams of these chunks with some clever level design. After which, rendering the level should be as simple as repeating the draw calls of the chunks with a specified offset that's the width of your chunks.

**Gameplay**

This one is a little tricky. Any game mechanics you implement should account for the fact that the world data is stored in the chunks above. That means any physics, AI, etc will need to know that they are reading from the chunk info and act accordingly. Especially AI. They will need to know that they are moving from one chunk to another and transfer their data accordingly to be stored.

# Answer
> 0 votes
You could for example create a clone for the object before it leaves the screen on the opposite side and delete the original as soon as it is "outside" the world.

The drawback is you have to ensure they behave the exact same way and what happens to the clone has to be applied to the original as well and vice versa.

I don't have any experience with the usual box2d implementation, but I am using the broadphase of box2d for a similiar spherical world.

Depending on how customizable box2d and your rendering pipeline is, you could store an offset for such objects and render them at their original position. If the origin together with the offset is on screen render it a second time with the offset. However I would assume that this is not easily extendable for the box2d Collision and/or Physics.

---
Tags: opengl, c++, 2d, rendering
---


# Question
Title: How to get a smooth path for a vehicle in a 2D top down map?
I am making a 2D tile based game which involves having AI that needs to traverse the map avoiding obstacles in a natural and smooth path (NOT NECESSARY THE SHORTEST)

The orientation of the vehicle is also important in the example above the initial orientation of the vehicle is to NORTH but the orientation of the vehicle at the destination doesn't matter.

All I could do now is to compute the path using A\* or a BFS fill through the center of the tiles.

This is an example of a desired path:

# Answer
> 1 votes
You can place control points in evenly spaced intervals and use this Bezier curve technique: How do I generate a smooth random horizontal 2D tunnel?

It allows you to smooth the actual path which interpolation wouldn't do. You can control the smoothness by the step size between control points. In order to get a more "natural" looking path, you may want to discount the cost of moving in a straight line. This technique will results in paths that have long straight stretches which you could more easily smooth with Bezier by applying the curve to the corners. Please notice that this means your graph will need edges between tiles that are far away from one another (the cost can be `sqrt(distance)^1.5`) and also connections between tiles that are not aligned on `x` or `y` axis. This means, you will need to make sure these edges don't overlap with obstacles, something you don't have to do with a simple graph that only allows movement between adjacent tiles.

# Answer
> 0 votes
Marco Pinter has an excellent write up on modifying the standard A\* algorithm to calculate turning radius constrained path finding (also in 1 pg format & archive). Here's a summary of the portions that seem most applicable to your question.

Given starting point & heading, the shortest path to a given destination is found either by turning either as far left or right as needed until you are pointed at the destination & then moving forward in a straight line toward it as illustrated below:

Mathematically, this is solved by noting:

* the turns are on the two circles tangent to the starting vector
* the point of exit from either circle will form a tangent to the destination

Thus, the starting position, heading & turning radius can be used to determine the position of the circles and basic trig (illustrated below) can then be used to find the point of exit from each circle to the destination. After finding both paths, a simple comparison given the shorter of the two.

Next, the above technique is used in the path finding by including a heading component to the search. In your case, instead of 2D grid of nodes, you need a three-dimensional space of nodes: 2 for the original XY coords & a third representing a heading (N, S, E, W, NE, NW, SE, SW).

A\* pathfinding typically explores a neighborhood of 4 or 8 nodes. Unfortunately, this probably limits search in undesired ways. Consider the following:

The turning radius in the example prevents the sharp turn needed to go from a to b to c to d, but would allow a path from a to d directly. This requires expanding the search neighborhood from 8 to 24. In general, expanding the search neighborhood will allow additional solutions at the expense of additional calculation time.

Finally, because the underlying search space has changed, the search heuristic should be modified to reflect this. The typical A\* heuristic measures the straight-line distance from a given position to the destination that ignores obstacles. The shortest turning path (also ignoring obstacles) provides heuristic that functions similarly, but favors positions that are oriented more directly toward the destination.

Pinter's articles covers a number of other related topics that may also be helpful to you. I found the path smoothing useful, but found the hit-check table didn't help me much. The article is was written in 2001, so not all of the optimizations presented are necessarily applicable today. When in doubt, code simply first, measure performance, 'optimize' if needed & measure again to make sure it helped.

---
Tags: algorithm
---


# Question
Title: How to match UI background size with text length in Unity?
I am making an FPS game in which when you are near an item a UI Text appears at the bottom center of the screen indicating the name of the item and the button to pick it up (let's say \[E\]).

It works fine but since I couldn't get a clear contrast between the text and the game area (like if the player's standing in front of an egg and the color of the text is white, you can't see the text), I decided to add a black background image to the text.

Now since the item names are of different lengths, I need the image length to match the text length. The background image should just be enough to fit the text How can I go about doing this? Or is there a better way to show a message to the player?

# Answer
> 0 votes
You first get the text component, then get the image component, and then apply the length of text to the image. Inside a function or Start or Update, whichever you prefer (I'm assuming you have these objects set and ready to be processed):

```
{
    RectTransform uiText = textObject.GetComponent<RectTransform>();
    RectTransform uiImage = imageObject.GetComponent<RectTransform>();
    uiImage.sizeDelta = uiText.sizeDelta;
}

```

Not really sure about the design of your project but that should give you the general idea.

---
Tags: unity, gui, ui-design
---


title: How to structure my projectile code

text:
# Question
Title: How to structure my projectile code
I have a submarine model that I would like to shoot torpedoes.

I want these torpedoes' initial velocity to vary with the forward velocity of its shooting submarine (so they go faster if launched off a moving sub, slower if show from a stationary sub).

I have a few requirements I'm trying to achieve:

1. Torpedos despawn when they swim too far away. No need to keep them in memory if they're too far too see.
2. When a torpedo is updated, and collision detection is done, there should be a way to determine who shot the torpedo, so it can be determined who to award the kill.
3. Torpedos should outlive the lifecycle of its parent sub, in the case the sub is destroyed between the torpedo was shot, and the time the torpedo hits or veers too far away. (Who doesn't love double kill mechanics :D?)
4. I'm working in C++, so manual memory management is a concern.

I'm debating between two approaches:

1. Have subs be the owners of their torpedoes. This makes requirements 1 and 2 easy, but complicated 3.
2. Have the scene be the owners of torpedoes. This makes 3 easy, but complicates 1 and 2.

This seems like it would be a common problem. What's the preferred way to do this?

# Answer
I'm assuming that you dropped the concept of the speed of the torpedo influenced by the speed of the sub-marine, and having them traveling at a constant speed.

Have a TorpedoFactory that will spawn the torpedoes and add them to the scene.

The parameters:

* torpedo origin
* torpedo orientation
* time to live
* submarine that spawned the torpedo

Each frame, update all of your torpedoes

1. If the time alive is greater than the time to live, delete it.
2. Move the torpedo.
3. Check for collision
    1. If the torpedo hits a sub, and it the originator carry on.
    2. Otherwise create an explosion and destroy the sub and the torpedo.

> 1. Torpedos despawn when they swim too far away. No need to keep them in memory if they're too far too see.

Check. Time to live stored in the torpedo.

> 2. When a torpedo is updated, and collision detection is done, there should be a way to determine who shot the torpedo, so it can be determined who to award the kill.

Check. The data is in the torpedo object.

> 3. Torpedos should outlive the lifecycle of its parent sub, in the case the sub is destroyed between the torpedo was shot, and the time the torpedo hits or veers too far away. (Who doesn't love double kill mechanics :D?)

Check. The torpedo is independent of the sub, it's an entity of its own.

> 4. I'm working in C++, so manual memory management is a concern.

Not if you use smart pointers. Google about `std::unique_ptr` and `std::shared_ptr`. Prefer `std::unique_ptr` as much as possible, as described by Sean Middleditch here.
> 4 votes

# Answer
Both the torpedos and the submarines should be a separate object in the scene, and the torpedos should contain a reference to the parent submarine's position and to the owner of the submarine inside them.
> 0 votes

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


# Question
Title: Rotating a row of Rubik cube in response to mouse position and drag
I made this cube in ue4..now I am able to rotate cubes separately without any problem.

But how do I move a row of cubes in response to mouse drag..

How do I detect what row is selected when my mouse is clicked and dragged on only one cube

# Answer
> 1 votes
You need to know two things: 1) Where did the user click in your scene. 2) How did he move his mouse.

For 1) you need to cast a ray and check collisions to find out if and what "subcube" was clicked on. I am sure there's something like that in UE4.

2) is a little harder. You either want a horizontal or vertical slice of cubes to rotate. You could wait for a few milliseconds after the user clicked the left (?) mouse button and moved the mouse to check what direction he drags the mouse primarily. Then just dispose of the other value of the drag-vector and you have your movement vector. Input that in your rotation algorithm. There would be some input lag between clicking/dragging and the cubes moving, but I would not see how you can accurately determine the direction of the mouse drag otherwise.

What I find more intriguing is how you would find out what cubes to move. Do they each store their current neighbours or their absolute position in the main cube?

---
Tags: unreal-4
---


title: Build SDL_Surface before blitting it

text:
# Question
Title: Build SDL_Surface before blitting it
I have a function in which I'm looping `y` and `x` over my array of sprites. That's a lot of loops, and it is very slow; I'd like to improve the performance.

I would like to only have to build the surface once, calling a `buildMap` method at the start, and referencing the resulting surface each time I need to blit it *without* having to loop to find the correct sprite and position.

---

```
int aff_map(t_exe *exe)
{
    int         sprite_idx;
    int         y, x;
    SDL_Rect    srcrect, dstrect;

    dstrect.y = 0;
    srcrect.y = 0;
    srcrect.w = TILE;
    srcrect.h = TILE;

    for (y = 0; y < HEIGHT; y++)
    {
        dstrect.x = MARGE_X;

        for (x = 0; x < WIDTH; x++)
        {
            for (sprite_idx= 0; sprite_idx< NB_TILES; sprite_idx++)
            {
                if (exe->map[y][x] == g_assoc_map[sprite_idx].key)
                      srcrect.x = g_assoc_map[sprite_idx].idx * TILE;
                if (SDL_BlitSurface(exe->sprite, &srcrect, exe->screen, &dstrect)
                        < 0)
                    return (err_sdl(SDL_GetError()));
            }

            dstrect.x += TILE;
        }

      dstrect.y += TILE;
    }

  return (EXIT_SUCCESS);
}

```

---

Is it possible to build an SDL\_Surface *before* blitting it?

# Answer
So from what I could gather what you want to do is to pre-render your level into one surface, so that each frame you can just blit that one surface that you need to.

This is quite straight-forward. You can use `SDL_CreateRGBSurface` to create a surface of your required size. You can do this in your `main()` or some other appropriate place that gets only called once.

Now, you just need to change the call `SDL_BlitSurface(exe->sprite, &srcrect, exe->screen, &dstrect)` to `SDL_BlitSurface(exe->sprite, &srcrect, yourPrecreatedSurface, &dstrect)`. The difference between the two calls is that the former version blits directly to the screen, while the latter uses the surface you created previously.

Now, in your game loop you are probably calling your function `aff_map`. Instead of doing that, you can now call `aff_map` before the game enters the main loop, and in the main loop you can just do `SDL_BlitSurface(yourPrecreatedSurface, NULL, exe->screen, NULL);`

As a side-disclaimer, you might want to take a look at SDL2 and it's accelerated hardware rendering support. You might get a performance boost, and moving on to the newer SDL stuff might really be a good idea. The alternative there is to use textures and render targets instead of surfaces.
> 0 votes

# Answer
Your code is a little vague (I suggest using more descriptive names for variables) but I think the issue is that you are trying to render everything every time.

Rather than drawing all of it, only draw what you can see. Calculate the offset tile (if the camera is centered, `camera position - half screen`) and draw only the number of tiles needed to fill the screen (`screen size / tile size`).

You can also organize your sprites into a more spacial friendly representation like a grid - every 4x4 square of tiles for example has its own list of sprites. As sprites move, update which square they are in.
Then, only draw sprites in the grids which are visible.
> 0 votes

---
Tags: performance, sdl, c
---


title: Packaging JARs for Linux

text:
# Question
Title: Packaging JARs for Linux
I realise that this question exists but the answer doesn't explain how to create `DEB` packages and whether they're suitable.

I'd like to package my Java 8 game for Linux. Most people don't have Java 8 (and some don't even have Java), so including the JRE in the package would be great.

The package should also have a logo that shows up on most desktop environments.

Lastly, the package should be cross distro (or cover a large number of distros), if possible, because there are simply so many distros.

How would I go about achieving this?

# Answer
* DEB is only for Debian based GNU/Linux distributions. If you want a full cover, use a `.tar.gz` compressed archive.
* You can include Java files but review its Licensing and Distribution FAQs.
* As you have binary not source, it is better extract it in `/opt/<gamename>` folder for all user.

Create symlink in `/usr/local/bin/<gameshortname>`

To have an icon and menu launcher, prepare a `<gamename>.desktop` file, to be installed in `/usr/share/applications/`
* Users without root access can extract any where in his `/home/<username>` and modify a new copy desktop file and save it in `/home/<username>/.local/share/applications/`

`.desktop` file is a standard followed by most Free Desktop Environments (gnome, kde, ..). See Desktop Entry Specification
> 1 votes

---
Tags: java, linux
---


title: SDL_Mixer Halt halted Channels?

text:
# Question
Title: SDL_Mixer Halt halted Channels?
It's not stated in the documentation, so I'd like to ask if anyone knows if it's ok to halt a channel (via Mix\_HaltChannel()) that's been already halted?

I'm asking 'cause I'd like to halt every channel with Mix\_HaltChannel(-1)(which could possibly include already halted channels) before freeing the chunks for safety reasons, because the documentation states that it's not good to free chunks of channels that are still playing.

Thanks a lot in advance.

# Answer
Yes, looking quickly through the source of SDL\_Mixer it does seem like doing this is safe.

The code essentially flows as the following:

* Is the channel the call wants to halt -1?
    + If yes, call `Mix_HaltChannel` on all channels.
    + If no do the following:
        - Is the wanted channel still playing?
            * If yes, stop the audio.
        - Handle fading.

So as you can see, the code actually handles the case where the channel is already halted. If you want to check it yourself, `Mix_HaltChannel` can be found in mixer.c, starting on line 1042.
> 0 votes

---
Tags: sdl2
---


# Question
Title: How to Prevent Entities Snapping Through Platforms
I am using crafty.js to make a platformer. I assigned the main player entity the default jumping controls and movement with `.twoway()` and used `.checkHits()` against the obstacles ("`obs`") the player will jump on. The problem is that when the player jumps, if the top of the player entity hits the bottom of the obstacle, the player entity "snaps" to the top. How do I make it so that this movement does not happen? The intended effect is that the player entity will only land on the obstacle if the player entity lands on the top.

Here is the code:

```
window.onload = function() {

  Crafty.init(600, 400);
  Crafty.background('#07A6FF');

  // obstacle/platform entities
  // 'obs' means obstacle
  var obs = Crafty.e('obs, 2D, DOM, Collision, Color')
  .attr({ x: 100, y: 250, w: 400, h: 45 })
  .color('#E88D0C');

  var obs2 = Crafty.e('obs, 2D, DOM, Collision, Color')
  .attr({ x: 200, y: 150, w: 45, h: 45 })
  .color('#E88D0C');

  // player entity
  var player = Crafty.e('player, 2D, DOM, Color, Collision, Twoway, Gravity, Jumper')
  .attr({x: 50, y: 50, w: 60, h: 40 })
  .color('#0035AB')
  .twoway(200, 150)
  .checkHits('obs')
  .gravityConst(200)
  .gravity('obs');
}
```

```
<script src="https://github.com/craftyjs/Crafty/releases/download/0.7.1/crafty.js"></script>
```

# Answer
> 0 votes
I found a solution on the crafty.js forums. This post explains this code (posted by mucaho):

```
.bind("CheckLanding", function(ground) {
  if (this._y + this._h > ground._y + ground._h) // disallow landing of player, if player's feet are not above ground
      this.canLand = false;
})

```

---
Tags: javascript, crafty
---


# Question
Title: What are the differant techniques to deal with different world and story states, in metroidvanias?
I am trying to figure out what is the best way to handle persistent changes in game world. Metroidvania games keep track of the player actions within a level, for example "this boss has been defeated", "this power up has been taken", "this button has been pushed", etc. In *"Cave Story"*, some completed actions will change the state of the main village, and some NPCs will have dialog specific to what the player has done, before.

I can think of two different ways to handle this functionality:

1. Having a copy of the same map, for each state; this sounds resource heavy, and inefficient.
2. Using some kind of "chapter" definition that allows me to load/initialise each object of the map in regards to the current chapter. For example, multiple versions of the same NPC would exist, on the map, at various locations, with a chapter attribute. The map can start to get messy, and it can be hard to test.

---

In regards to the second option, different behaviors and the object loading code would look like this:

```
if (object.currentChapter == currentChapter) {
    object.load()
}

```

I am using Tiled, and as proposed, it can then be possible to load the object layer corresponding to the current game state or chapter:

```
loadMap(map, chapter) {
    ...
    createObjects(map, objectLayerName)
}

```

As an example, in `object_chapter_1`, the wizard is outside of a laboratory. In `object_chapter_2`, the wizard is inside of the laboratory, preparing some magic potions.

I can't really figure out what is the best solution, and what techniques can be used to deal with this problem. What are the differant techniques to deal with different world and story states, in metroidvanias?

# Answer
Today computers and consoles have lots of storage. Storing multiple maps may be more efficient if there are very significant changes. The issue is, what if you wanted to change something minor in all the maps at once?

This is where layers come in. You can design your level editor to support layering. This means each change to the world is saved as a "delta" like a layer you apply on top of the existing world (think of an image editor). However, this layer may also move characters into new position if needed.

However, you'll need to make sure layers do not conflict. If change `a` does one thing and change `b` does another contradicting thing (non-linear game) than if both `a` and `b` happen you need to apply layer `c` that merges these changes in a desired manner.

You need to maintain a data-structure with relevant info about items like relics and bosses with states that need to be maintained. There is no magical way around it. This data-structure could be a large array that stores objects with info regarding each of these entities.
> 2 votes

# Answer
Store persistent game events somewhere, say in a `GameState` object or the like. This object would provide methods like `setState(name, value)` and `getState(name)`.

For dialogs, put conditionals on each branch of the tree or option. e.g. a dialog tree data file might look something like:

```
<dialog start="hello">
   <entry id="hello">
      <say who="npc">Greetings good person!</say>
      <option text="Bye" goto="goodbye"/>
      <option text="It is done" goto="quest_complete" requires="state['quest_147'] == 'complete'/>
   </entry>
   <entry id="goodbye">
      <say who="npc">Bye now!</say>
      <quit/>
   </entry>
   <entry id="goodbye">
      <say who="npc">That is fantastic! Here's your reward, as agreed.</say>
      <award type="gold" amount="1000"/>
      <set state="quest_147" value="closed"/>
      <quit/>
   </entry>
 </dialog>

```

For other map elements you might define the requirements in different ways. For example, an item spawner might have conditions to only spawn the item if a particular quest is complete *and* the player hasn't already acquired the item.

While the big bag of state is the simplest approach to implement, I might suggest you distinct types of state and track those explicitly. e.g., instead of checking if the player ever picked up a particular spawn of an item, check if the player currently needs the item and doesn't currently have it. The reason is that it will help avoid bugs; you generally want to depend directly on the game state (quest status, inventory, etc.) rather than a derived state (like the big state key/value map) to reduce the chance of state desync's breaking your game.
> 1 votes

---
Tags: architecture, design-patterns
---


# Question
Title: I have a problem rotating a 2D game object after collision
I'm developing a simple flip game where a cube flips and the bar a it collides with should start rotating after collision. Most snips involve destroying an object, but that's not my case.

Here is my code:

```
using UnityEngine;

public class CheckI : MonoBehaviour
{
    float x;
    public Rigidbody2D rb2d;

    void OnCollisionEnter2D(Collision2D col)
    {
        if (col.gameObject.tag == "bar")
        {
            x += Time.deltaTime * -10;
            transform.rotation = Quaternion.Euler(0, 0, x);
        }
    }
}

```

How do I start rotation after collision?

# Answer
> 1 votes
`OnCollisionEnter2D` is only called **once**, when the collider first makes contact with the object.

`Time.deltaTime` is the time that it took to complete the last frame, in seconds. This is almost always a very small number, so you're probably not noticing a very large change. You'll have to multiply this by a relatively large number if you want your change to be instantaneous.

If you want it to happen over time, you can use `OnCollisionEnter2D` to change a `bool`, and then apply your rotation in the `Update` method if `bool == true`.

---
Tags: unity, c#, 2d
---


# Question
Title: Loading an image from Disk to used to replace a source image for an image object
I am working on a Unity project where I need to be able to grab an image from disk and then have it be replaced as the source image for an image gameobject. Currently I already have a filebrowser implemented that gives me the filepath.

```
if (File.Exists(output)){
    GameOjbect imageselect = GameObject.Find("ImageSelection");
    imageselect.GetComponent<Image>();
    //I need to make the file location at path output be the sprite?/sourceimage? for imageselect
}

```

Sorry if this has already been asked, I have been looking at other examples this morning with no luck.

# Answer
You can use Texture2D.LoadImage to load your image into a Texture2D, assuming it's a PNG or JPG image.

The method takes in a `byte[]`, so you'll have to use `File.ReadAllBytes(output)`.

Something like this:

```
if (File.Exists(output))
{
    var fileBytes = File.ReadAllBytes(output);
    var texture2D = new Texture2D(2, 2);

    if (texture2D.LoadImage(fileBytes))
    {
        _image.sprite = Sprite.Create(texture2D,
                                      new Rect(0, 0, texture2D.width, texture2D.height),
                                      new Vector2(0.5f, 0.5f));
    }
    else
    {
        Debug.LogError("Error when loading file as Texture2D!");
    }
}

```

should work just fine.

The `Texture2D.LoadImage()` method will automatically resize the 2x2 texture2D object depending on the file loaded.

There's also an optional fourth parameter for `Sprite.Create()` that takes in a float pixelsPerUnit.
> 0 votes

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


# Question
Title: Unity, Does camera ALWAYS render to RenderTexture?
I have a camera that renders a simple model to a RenderTexture. I then use that RenderTexture as a texture for my UI with a RawImage component. However, sometimes I disable my UI and therefore you can not see the RenderTexture.

My question is: Does the camera continue to render to the texture in the background even when the texture is not visible?

If I understand how this works I believe it should. If so, simply disabling the camera should prevent it from rendering in the background?

Thanks.

# Answer
> 1 votes
Just because a RenderTexture isn't being used as a texture or sprite, doesn't mean that it's not being rendered to. You can see this yourself if you locate your RenderTexture in your project tab, and look at the preview at the bottom of the inspector. You should see a live updating version of your texture.

The only way to prevent the Camera from drawing to the RenderTexture (that I'm aware of) is to disable the Camera, or remove the RenderTexture from the Camera's `Target Texture` field.

---
Tags: unity, camera, rendertexture
---


# Question
Title: Collision code is creating allocations on heap every frame
I've been profiling my app trying to reduce allocations and garbage collection during gameplay.

The following code is SAT collision which i use for hill/ramp collisions, when the player is standing on a hill the profiler is saying this code is creating 5KB of Microsoft.Xna.FrameWork.Vector2\[\] allocations per second (88 bytes per frame).

Vector2 is a struct so I'm a little confused as to what is going on. Any help sourcing where its coming from appreciated...

The ramp collision Method (where the profiler is pointing):

```
/// <summary>
/// Detects and resolves the collision between two shapes
/// </summary>
private void HandleRampCollision(Shape ramp)
{
    axis = new Vector2[playerShape.Axes.Length + ramp.Axes.Length];

    playerShape.Axes.CopyTo(axis, 0);
    ramp.Axes.CopyTo(axis, playerShape.Axes.Length);

    float intervalWidth = 0;
    float minimumDistance = float.MaxValue;

    Vector2 resolutionAxis = Vector2.Zero;

    for (int i = 0; i < axis.Length; i++)
    {
        // Test to see if this axis seperates shapes A and B.
        if (AxisSeperatesShapes(axis[i], ramp, playerShape, out intervalWidth))
        {
            // We found a seperating axis! No need to carry on.
            return;
        }
        else
        {
            intervalWidth *= 1.01f;

            // Find the shortest distance needed to move to resolve collision.
            if (intervalWidth * intervalWidth < minimumDistance * minimumDistance)
            {
                minimumDistance = intervalWidth;
                resolutionAxis = axis[i] * minimumDistance;
            }
        }
    }

    // Make sure we are trying to push shape B
    // away and not pull it into shape A.
    if (resolutionAxis != Vector2.Zero)
    {
        isOnGround = true;
        Vector2 direction;

        direction = new Vector2(ramp.Center.X,
            ramp.Center.Y) - playerShape.Center;

        if (Vector2.Dot(direction, resolutionAxis) < 0.0f)
        {
            resolutionAxis = -resolutionAxis;
        }

        if (velocity.Y > 0 && resolutionAxis.Y > 0)
        {
            velocity.Y = 0;
        }

        if (playerShape.CanBePushed == true && ramp.CanBePushed == false)
        {
            playerShape.Position -= new Vector2(0, Math.Abs(resolutionAxis.Y));
        }
        else if (playerShape.CanBePushed == false && ramp.CanBePushed == true)
        {
            ramp.Position += resolutionAxis;
        }
        else
        {
            resolutionAxis /= 2.0f;
            playerShape.Position -= resolutionAxis;
            ramp.Position += resolutionAxis;
        }

        if (rampType == 1)
        {
            Position = new Vector2(playerShape.Position.X + (BoundingRectangle.Width), playerShape.Position.Y);
        }
        else if (rampType == 2)
        {
            Position = new Vector2(playerShape.Position.X - (BoundingRectangle.Width), playerShape.Position.Y);
        }
    }
}

```

The Axis Separates Shapes Method:

```
/// <summary>
/// Tests if an axis seperates two shapes.
/// </summary>
private bool AxisSeperatesShapes(Vector2 axis, Shape A, Shape B, out float intervalWidth)
{
    float minA = 0, maxA = 0;
    float minB = 0, maxB = 0;

    A.ProjectOntoAxis(axis, out minA, out maxA);
    B.ProjectOntoAxis(axis, out minB, out maxB);

    if (minB > maxA || minA > maxB)
    {
        intervalWidth = 0;
        return true;
    }

    float d0 = maxA - minB;
    float d1 = maxB - minA;

    intervalWidth = MathHelper.Min(d0, d1);
    return false;
}

```

Shape Class (used only for hills and contains the project onto axis method):

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace NewGame
{
    public class Shape
    {
        protected Vector2[] vertices;
        protected Vector2[] temporaryVertices;
        protected Vector2[] verts;

        // We only need to update certain aspects of the shape if it
        // has moved. So we store an old position to compare the new position to.
        protected Vector2 cachedPosition = Vector2.Zero;

        protected int width;
        protected int height;

        protected Vector2 origin = Vector2.Zero;
        protected Rectangle rectangle;

        public Color Color = Color.White;
        public bool CanBePushed = true;

        /// <summary>
        /// The position of the shape.
        /// </summary>
        public virtual Vector2 Position { get; set; }
        /// <summary>
        /// The center of the shape
        /// </summary>
        public Vector2 Center
        {
            get { return origin + Position; }
        }
        /// <summary>
        /// A rectangle containing the shape.
        /// </summary>
        public Rectangle Rectangle
        {
            get
            {
                return new Rectangle((int)(rectangle.X + Position.X),
                                        (int)(rectangle.Y + Position.Y),
                                        width,
                                        height);
            }

        }

        /// <summary>
        /// The axis used when doing SAT tests.
        /// </summary>
        public readonly Vector2[] Axes;

        protected Shape()
        {
            Axes = new Vector2[0];
        }

        /// <summary>
        /// Constructs a new shape.
        /// </summary>
        /// <param name="vertices">The vertices that will define the shape (In CW order).
        /// (The shape should be created at origin and moved using Position)</param>
        public Shape(Vector2[] vertices)
        {
            if (vertices.Length < 2)
            {
                throw new ArgumentException("A shape must have at least 2 vertices!");
            }

            // We clone the collections to avoid strange referencing issues.
            this.vertices = new Vector2[vertices.Length];
            this.temporaryVertices = new Vector2[vertices.Length];

            Axes = new Vector2[vertices.Length];

            int minX = int.MaxValue; int minY = int.MaxValue;
            int maxX = int.MinValue; int maxY = int.MinValue;

            for (int i = 0; i < vertices.Length; i++)
            {
                this.vertices[i] = vertices[i];
                this.temporaryVertices[i] = vertices[i];

                origin += vertices[i];

                minX = (int)Math.Min(minX, vertices[i].X);
                maxX = (int)Math.Max(maxX, vertices[i].X);

                minY = (int)Math.Min(minY, vertices[i].Y);
                maxY = (int)Math.Max(maxY, vertices[i].Y);
            }

            origin /= (float)(vertices.Length);

            CanBePushed = true;

            width = maxX - minX;
            height = maxY - minY;

            rectangle.X = minX;
            rectangle.Y = minY;
            rectangle.Width = width;
            rectangle.Height = height;

            CalculateProjectionAxes();
        }

        protected virtual void CalculateProjectionAxes()
        {
            int nextIndex = 0;

            for (int i = 0; i < vertices.Length; i++)
            {
                nextIndex = i + 1;

                if (nextIndex >= vertices.Length)
                {
                    nextIndex = 0;
                }

                Axes[i] = Vector2.Normalize(vertices[i] - vertices[nextIndex]);
                // Find the normal of the seperation axis.
                Axes[i] = new Vector2(-Axes[i].Y, Axes[i].X);
            }
        }

        public static Shape CreateRectangle(int width, int height)
        {
            return new Shape(new Vector2[]
            {
                Vector2.Zero,
                new Vector2(width, 0),
                new Vector2(width, height),
                new Vector2(0, height),
            });
        }

        public static Shape CreateRightTriangle(int width, int height)
        {
            return new Shape(new Vector2[]
            {
                new Vector2(width, height),  // Bottom Right Vertex
                new Vector2(0, height),      // Bottom Left Vertex
                new Vector2(0, 0),           // Top Left Vertex
            });
        }
        public static Shape CreateLeftTriangle(int width, int height)
        {
            return new Shape(new Vector2[]
            {
                new Vector2(0, height),      // Bottom Left Vertex
                new Vector2(width, height),  // Bottom Right Vertex
                new Vector2(width, 0),       // Top Right Vertex
            });
        }

        public static Shape CreateLeftTriangleBS(int width, int height)
        {
            return new Shape(new Vector2[]
                {
                    new Vector2(0, height),  // Bottom Left Vertex
                    new Vector2(width, height),      // Bottom Right Vertex
                    new Vector2(width, height / 2),           // Top Right Vertex
                });
        }
        public static Shape CreateLeftTriangleTS(int width, int height)
        {
            return new Shape(new Vector2[]
                {
                    new Vector2(0, height / 2),      // Bottom Left Vertex
                    new Vector2(width, height / 2),  // Bottom Right Vertex
                    new Vector2(width, 0),       // Top Right Vertex
                });
        }

        public static Shape CreateRightTriangleBS(int width, int height)
        {
            return new Shape(new Vector2[]
                {
                    new Vector2(width, height),  // Bottom Right Vertex
                    new Vector2(0, height),      // Bottom Left Vertex
                    new Vector2(0, height / 2),           // Top Left Vertex
                });
        }

        public static Shape CreateRightTriangleTS(int width, int height)
        {
            return new Shape(new Vector2[]
                {
                    new Vector2(width, height / 2),  // Bottom Right Vertex
                    new Vector2(0, height / 2),      // Bottom Left Vertex
                    new Vector2(0, 0),           // Top Left Vertex
                });
        }

        /// <summary>
        /// Projects the shape onto an axis.
        /// </summary>
        /// <param name="axis">The axis to project the shape onto</param>
        /// <param name="min">The minimum projection on the axis</param>
        /// <param name="max">The maximum projection on the axis</param>
        public virtual void ProjectOntoAxis(Vector2 axis, out float min, out float max)
        {
            verts = GetVertices();

            float interval = Vector2.Dot(axis, verts[0]);
            min = max = interval;

            for (int i = 0; i < verts.Length; i++)
            {
                interval = Vector2.Dot(axis, verts[i]);

                if (interval < min)
                {
                    min = interval;
                }
                else if (interval > max)
                {
                    max = interval;
                }
            }
        }

        /// <summary>
        /// Returns the translated vertices of the shape.
        /// </summary>
        public Vector2[] GetVertices()
        {
            if (Vector2.DistanceSquared(cachedPosition, Position) < float.Epsilon * float.Epsilon)
            {
                return temporaryVertices;
            }
            else
            {
                cachedPosition = Position;

                for (int i = 0; i < vertices.Length; i++)
                {
                    temporaryVertices[i] = vertices[i] + Position;
                }

                return temporaryVertices;
            }
        }
    }
}

```

# Answer
> Vector2 is a struct so I'm a little confused as to what is going on. Any help sourcing where its coming from appreciated...

`Vector2` is a struct, and thus a value type. However you're not allocating a `Vector2`, you're allocating an *array of them*:

```
axis = new Vector2[playerShape.Axes.Length + ramp.Axes.Length];

```

Arrays are not value types and are thus allocated on the heap.

If you can allocate this array once, at the largest possible size you'll need, and simply overwrite it every time, that may alleviate your trouble.
> 1 votes

# Answer
Problem was caused by this line:

```
axis = new Vector2[playerShape.Axes.Length + ramp.Axes.Length];

```

I fixed it by creating a pre calculated array in the constructor for each ramp and then re-using that array.

So if a ramp has 3 vertices and the player has 4 vertices an array for that ramp type would be:

```
Vector2[] axis = new Vector2[7]; // Creates array pre calculated in constructor

```

Thanks for the comments and help all.
> 1 votes

---
Tags: c#, xna, collision-detection, monogame
---


# Question
Title: What should I use instead of randomized start positions for good-looking 2D rain?
Right now I'm randomizing the position of my 2D rain's spawn positions on both the X and, slightly, on the Y axis. It looks pretty weird right now, it has a bunch of huge clumps and unfilled areas:

I want a more uniform, but not a completely boring and uniform distribution of my rain. I want something that doesn't look like a perfectly tiled texture, but doesn't look as crazy random as the picture above. What can I do?

# Answer
> 2 votes
Divide your rectangular area where you want to generate particles into tiles then spawn particles randomly inside of those tiles (round robin randomly or some other method) rather than uniformly across the whole rectangle.

---
Tags: 2d, platformer, random, distribution
---


title: Errors in Xcode using SDL

text:
# Question
Title: Errors in Xcode using SDL
I am using Lazy Foo's Production tutorials for making an SDL game in C in Xcode 6.1 - http://lazyfoo.net/tutorials/SDL/index.php#Hello%20SDL. I'm using Xcode 7 but I don't think they are very different.

In the second tutorial (http://lazyfoo.net/tutorials/SDL/02\_getting\_an\_image\_on\_the\_screen/index.php). I cannot seem to compile properly without an error regarding one of the functions.

The function prototype:

```
//Frees media and shuts down SDL
void close();

```

Then the function declaration:

```
void close()
{
    //Deallocate surface
    SDL_FreeSurface( gHelloWorld );
    gHelloWorld = NULL;

    //Destroy window
    SDL_DestroyWindow( gWindow );
    gWindow = NULL;

    //Quit SDL subsystems
    SDL_Quit();
}

```

And then the function call at the end:

```
close();

```

I am getting these errors and am not quite sure how to fix them. Other solutions online are for problems that are not quite the same as mine.

`SDL_Tutorial/SDL_Tutorial/using_image.c:28:6: Conflicting types for 'close'`

`SDL_Tutorial/SDL_Tutorial/using_image.c:28:6: Conflicting types for 'close'`

`SDL_Tutorial/SDL_Tutorial/using_image.c:127:5: Implicit declaration of function 'close' is invalid in C99`

`SDL_Tutorial/SDL_Tutorial/using_image.c:127:11: Too few arguments to function call, expected 1, have 0`

`clang: error: linker command failed with exit code 1 (use -v to see invocation)`

Any help would be much appreciated, as I am struggling to make progress with learning SDL game programming at the moment.

Thank you.

# Answer
> 1 votes
The lazyfoo tutorials don't have the best coding practices. I can see two problems:

* `close` is too generic of a name for a function. It's most likely conflicting with an existing function with the same signature. You should rename the function.
* In C, `void foo()` is not the right way to declare "a function that takes no arguments and returns nothing". It's `void foo(void)`. You should either fix the declaration, or compile your code as C++, as lazyfoo assumes (note that if you download their code their files are inside `.cpp` files). In C++ `void foo()` is a correct declaration.

---
Tags: sdl, c, xcode
---


# Question
Title: Date Time math (A little Detail Missing)
Ok, so I have this method, where I'm trying to subtract one date from the other, and then divide it by an integer number:

```
public void BonoDatos () {

    //public InputField StartTimeBono;
    //public InputField FinishBono;
    //DateTime BonoStart Datetime BonoFinish
    //public InputField NumeroDeBonos;
    //int NumDeBonos;

    NumDeBonos = int.Parse (NumeroDeBonos.text);
    BonoStart = DateTime.ParseExact (StartTimeBono.text, "MM/dd/yyyy HH:mm:ss", null);
    BonoFinish = DateTime.ParseExact (FinishBono.text, "MM/dd/yyyy HH:mm:ss", null);

    Start2 = DateTime.Now;

    BonoPeriodo = (int)((BonoFinish.Subtract(BonoStart).TotalSeconds) / NumDeBonos);

    print (BonoPeriodo);
    print ("funciona");

    if (MaquinasGanadoras.text.Length > 0) {

        NumGanador.text = Maquina.text;
        CancelInvoke ("NumerAzarBono");
        print (NumGanador.text);

    } else if (MaquinasGanadoras.text.Length == 0) {

        Invoke ("NumerAzarBono", 0.1f);
        print ("Numero al Azar");
    }
}

```

Now, this code is supposed to take the difference of time between the two dates, and then divide it by the integer, in this case "NumdeBonos" so that the code I have in the update repeats the amount of times I put NumDeBonos to be. For example if I divide the difference between 5, in that amount of time, I need my update to happen 5 times. Problem is, My update isn't working. This is the code:

```
    if(DateTime.Now.Equals(Start2.AddSeconds(BonoPeriodo))) {
    //if(DateTime.Now.Equals(DateTime.Now, Start2.AddSeconds(BonoPeriodo))) {

        print ("PERIOD FUNCIONA");

        PagPrincipal.SetActive(false);

        Bonos.SetActive(true);

        Invoke ("apagaBonos",5f);

        Start2 = DateTime.Now;

    }

```

Now, it doesn't show any mistakes, it just doesn't do anything. What little detail am I missing?

# Answer
`DateTime` has a millisecond resolution, and when you use `DateTime.Now` you'll be getting the timestamp for "now" to the full resolution of the type. You're comparing to a pre-recorded `DateTime`, adjusted by two whole seconds, but unless that exact line of code happens to run with in the exact millisecond that "now" is *exactly two seconds* ahead of what `Start2` holds, it will never execute.

If you only care about seconds-resolution, use the properties of `DateTime` to compare their year/month/day/hour/minute/second directly or create new `DateTime`s manually, stripping them down to seconds-level resolution:

```
var now = DateTime.Now;
var target = Start2.AddSeconds(BonoPeriodo);
if (now.Minutes == target.Minutes && now.Seconds == target.Seconds...)

```

Or use greater-than checks:

```
var now = DateTime.Now;
var target = Start2.AddSeconds(BonoPeriodo);
if (now > target)...

```

The default equality check for `DateTime` will compare to the full resolution of the type.
> 1 votes

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


# Question
Title: How to set a static size for an object in GameMaker?
I have many sprites with different sizes, and I have an object in which I set those sprites, but this object gets resized by the currently displayed sprite.

How can I set a fixed size for the object so that it can no longer change size?

Thanks for any help.

# Answer
> 2 votes
When you load the sprite:

```
image_xscale = (image_xscale/sprite_get_width(your_sprite))*SIZE_YOU_WANT_WIDTH

image_yscale =(image_yscale/sprite_get_height(your_sprite))*SIZE_YOU_WANT_HEIGHT

```

I can't check if the functions i've used there are the good ones, be sure to check in the doc (press F1 in the GameMaker interface, and look for xscale and sprite\_get\_width by example)

Basically what you do is that you consider that your sprite is only a 1\*1 pixel, and then strectch it to the value you have fixed.

# Answer
> 0 votes
Assuming that by "size" you mean the size of its collision shape, this is governed by the `mask_index` variable, to which you should assign the index of the sprite that will always be used for collision.

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


# Question
Title: Drawing a highlight over selected ability
(I am new to gamemaker)

In gamemaker, I'm not sure what a good way of drawing a highlight sprite over a specific area on my ability bar, when my "mode" variable is in a certain position. For example, when I press the key 1, my mode variable becomes 1, which should highlight the top right hand corner of my screen, (780,0) but when I press the key 2, my mode variable becomes 2, and the first highlight at (780,0) gets erased and another highlight gets placed at (780,80).

# Answer
> 0 votes
As far as I understand your problem, you should be using the following piece of code inside a `draw` event:

```
draw_set_rectangle(780, (variable * size_square), 780 + size_square,
        (variable * size_square) + size_square, 1)

```

.. where `variable` is the index of the ability to be highlighted.

---

You can change the highlight color with this:

```
draw_set_color(c_red)

```

.. where `c_red` is nothing more than `c_anyBasicColor`, `c_blue`, `c_green`, etc.

---

You should either list `variable` as a *global variable* by writing `global.variable` every time, which is a general programming *no-no*, or put your code inside an object that hosts `variable`.

---
Tags: game-maker
---


# Question
Title: Merging geometry/mesh without losing benefits
In three.js we can simply merge geometry to limit the amount of draw calls and thus increase performance. In a simple test with one material, I could draw 50.000 cubes + shadows @ 60fps on my GTX660 GPU. Without geometry merging, 5.000 cubes already caused a problem.

I wonder how to preserve the benefits of rendering each cube mesh on it's own. For example, how to pick a cube mesh when everything is merged into one geometry? By default that's not possible of course.

Is there any common technique for this problem? After all I do have all the unmerged mesh objects even after merging. So there must be some way to utilize them for picking?

### What I want to do in a nutshell

* SimCity like game for learning purposes
* Each house is a cube mesh
* Want to render 50.000 houses and be able to add & remove houses
* House-selection via mouse-cursor (picking) must be possible

# Answer
> 11 votes
Ok I got it. After merging the whole geometry together, I still have the individual meshes in an array. So I can simply use these meshes for raycasting, even though they are not even rendered. Took me a while to realize this.

For the picking I use this octree implementation: http://threejs.org/examples/#webgl\_octree\_raycasting

This brings down the intersection tests per update down from 50.000 to ~500. Without the octree the fps will decrease heavily.

The orange picking hull you see is actually the now rendered mesh (+1 draw call) with a changed material and modified size.

So I guess the next step is to implement some kind of map partitioning. That is, break the merged geometry up into several pieces. The reason for this is that the merged geometry has a large amount of vertices. That means If I move the map 99% off screen, the graphics card still has to process all the vertices because the geometry is still in view, at least the 1% of it. So if it's broken up, only the pieces in view have to be rendered.

# Answer
> 1 votes
For picking you could also render ID's for each cube to another render target and just check what the ID value is at the cursor. The benefit is that the picking is pixel perfect and works efficiently also for more complex geometry.

If all the objects have the same geometry, then you could use instanced rendering. One stream defines the geometry, while another defines properties per instance (e.g. transformation). For frustum culling you would need to build the instance stream each frame based on the visibility test. If you have large amount of objects though you may want to place those objects into a loose octree or something to speed up the culling.

# Answer
> 0 votes
I'm not sure about the particulars of three.js, but two possible performance hogs come to mind in general OpenGL:

1. Have you considered instancing? You will only need one draw call as well and use less VRAM.
2. Have you taken a serious look at the picking algorithm? If your cubes have bounding volumes in a list instead of a tree for example that would explain a difference of that magnitude.

# Answer
> 0 votes
Another approach you can take is to build some vertex attribute into your geometry and put highlight logic into your fragment shader. This is extremely useful when you don't want to have two copies of data in memory, and you'll have more control of how highlight is implemented.

---
Tags: three.js
---


# Question
Title: How to calculate vector of projectile initial velocity
There are point A (origin) and point B (target). And also there is gravity vector G. I need compute initial velocity of projectile (throwing arc trajectory from point A to point B).

Also I need to control speed of projectile (Speed) and flexion of throwing arc.

How compute this?

# Answer
Assume your variables are: initial velocity , initial position , and target position .

First, choose your initial y-velocity, and calculate the time it requires to reach its target on the y-axis using this equation:

If you want the projectile to reach its target while it's ascending, choose the plus sign, otherwise, choose the minus sign. (Note that gravity, g, should be \< 0).

Now you can calculate the initial x-velocity by using this equation:

Likewise, for the initial z-velocity:

You can modify the curve of the arc by changing the initial y-velocity.
> 5 votes

# Answer
Depending on how accurate you need to be and how much processing power you what to use for this, you could compute the position and speed of your projectile by using the **semi-explicit euler**:

Semi-explicit euler:

First calculate the new velocity:

* v(t + h, p(t)) = v(t, p(t)) - h\*g

Than you calculate the new position:

* p(t + h) = p(t) + h\*v(t + h, p(t))

Variables:

* v is velocity-vector
* t is your current time
* h is your timestep (e.g. 1 if you calculate every second)
* p(t) is the current position at time t
* g is your gravity

Depending on your context and actual needs you can calculate the flexion of this as well, because you have a specific amount of concrete points of your throwing arc.

Please mind the semi-explicit euler is not the most accurate one, but pretty fast and not so difficult to implement.
> 1 votes

---
Tags: movement, vector, trajectory
---


# Question
Title: LibGDX getYpercent of a child inside scrollpane
So I have this scrollpane with a bunch of labels alfabetic organized, its quite anoying scrolling all the way down to select a label starting with Z letter

So I put the whole alfabet in the right of the screen and my goal is that when users touch the letter 'X' it scrolls all the way to the names starting with 'X'

So I hard coded it like this...

```
if(letter.equalsIgnoreCase("a"))      setSPy(0);
else if(letter.equalsIgnoreCase("b")) setSPy(0.112212256f);
else if(letter.equalsIgnoreCase("c")) setSPy(0.21482526f);
else if(letter.equalsIgnoreCase("d")) setSPy(0.32874277f);
//etc...
private void setSPy(float percent) {
    scrollPane.setScrollPercentY(percent);
}

```

It works, but 2 problems:

it looks ugly and I refuse update it every time I decide to add another label.

Then since I could not find a function that tells me the percentY of the item I did this:

```
private void scrollToLetter(String letter) {
     //loop tru items inside scrollpane
    for (int i = 0; i < spItems.size; i++) {
        BrandSelectorItem  item = spItems.get(i);

        if(item.getString().substring(0, 1).equals(letter)){
            int number = i+1;
            //This gets the posY axis-Y starting on top
            float posY = (number*item.getHeight())- item.getHeight();
            float percentY = posY/(spItems.size*item.getHeight());

            scrollPane.setScrollPercentY(percentY);
            break;
        }
    }
 }

```

I thought this was going work, but if I hover the "A" works fine, go to 0%, if I hover the "B" its off by little bit, "C" more off, "D" more more off and etc..

seems like something about scrollpane coordinates that i do not understand.

Thank you!

**Solution:**

```
 private void scrollToLetter(String letter) {
     //loop tru items inside scrollpane
    for (int i = 0; i < spItems.size; i++) {
        //This is the label
        BrandSelectorItem  item = spItems.get(i);
        if(item.getString().substring(0, 1).equals(letter)){
            int itemNumber = i+1;
            //This gets the posY axis-Y starting on top
            float posY = (itemNumber*item.getHeight())- item.getHeight();
            scrollPane.setScrollY(posY);
            break;
        }
    }
 }

```

# Answer
> 1 votes
i'd do something like this:

Create a key-value map, where **key** \- is character, supposed to be first letters of labels-leaders (e.g. first occurrence for label text starting with 'b' from the list sorted alphabetically);

and **value** \- is the reference to the label object

```
private ObjectMap<Character, Label> labels = new ObjectMap<Character, Label>();

private void createLabels() {
    labels.put('a', new Label("a_label", new Skin()));
    labels.put('b', new Label("b_label", new Skin()));
    labels.put('c', new Label("c_label", new Skin()));
    labels.put('d', new Label("d_label", new Skin()));
}

```

* note I'm creating new label objects just to demonstrate, here should be references to earlier created labels.

method `getLabelPosition` searching up the labels map by letter and returns the label position:

```
private float getLabelPosition(char letter) {
    Label label = labels.get(letter);
    return label.getY();
}

public void navigateTo(char inputLetter) {
    pane.scrollY(getLabelPosition(inputLetter));
}

```

method `navigateTo` expected to be called when user pressed a letter. It does the actual focus move to the coordinates corresponding to the first label with the pressed letter.

---
Tags: libgdx
---


# Question
Title: How to make it so when my player dies, the game will restart?
when ever my player dies, he will be sent to the Menu State and when he plays again, he can start from the same place where he left off which results in an endless death. what I want is that when my game shows the Menu State, the game always resets.

How do I do that?

My Game Class

```
import java.awt.Graphics;
import java.awt.image.BufferStrategy;

public class Game implements Runnable {

private Display display;
private int width,
            height;
public String title;

private boolean running = false;
private Thread thread;

private BufferStrategy bs;
private Graphics g;

//States
public State gameState;
public MenuState menuState;
public SplashScreen splashscreen;

//Input
private KeyManager keyManager;
private MouseManager mouseManager;

//Camera
private GameCamera gameCamera;

//Handler
private Handler handler;

public Game(String title, int width, int height){
    this.width = width;
    this.height = height;
    this.title = title;
    keyManager = new KeyManager();
    mouseManager = new MouseManager();
    }
    //HERE IS MY INIT() METHOD

    private void init(){
    display = new Display(title, width, height);
    display.getFrame().addKeyListener(keyManager);
    display.getFrame().addMouseListener(mouseManager);
    display.getFrame().addMouseMotionListener(mouseManager);
    display.getCanvas().addMouseListener(mouseManager);
    display.getCanvas().addMouseMotionListener(mouseManager);
    Assets.init();

    handler = new Handler(this);
    gameCamera = new GameCamera(handler, 0, 0);

    gameState = new GameState(handler);
    menuState = new MenuState(handler);
    splashscreen = new SplashScreen(handler);
    State.setState(splashscreen);
}

private void tick(){
    keyManager.tick();

    if(State.getState() != null);
        State.getState().tick();
}

private void render(){
    bs = display.getCanvas().getBufferStrategy();
    if(bs == null){
        display.getCanvas().createBufferStrategy(3);
        return;
    }
    g = bs.getDrawGraphics();
    //Clear Screen
    g.clearRect(0, 0, width, height);
    //Draw Here!

    if(State.getState() != null);
        State.getState().render(g);

    //End Drawing!
    bs.show();
    g.dispose();
}

public void run(){

    init();

    int fps = 1000;
    double timePerTick = 1000000000 / fps;
    double delta = 0;
    long now;
    long lastTime = System.nanoTime();
    long timer = 0;
    int ticks = 0;

    while(running){
        now = System.nanoTime();
        delta += (now - lastTime) / timePerTick;
        timer += now - lastTime;
        lastTime = now;

        if(delta >= 1){
            tick();
            render();
            ticks++;
            delta--;
        }

        if(timer >= 1000000000){
            System.out.println("Ticks and Frames: " + ticks);
            ticks = 0;
            timer = 0;
        }

    }

    stop();

}

public KeyManager getKeyManager(){
    return keyManager;
}

public MouseManager getMouseManager(){
    return mouseManager;
}

public GameCamera getGameCamera(){
    return gameCamera;
}

public int getWidth(){
    return width;
}

public int getHeight(){
    return height;
}

public synchronized void start(){
    if(running)
        return;
    running = true;
    thread = new Thread(this);
    thread.start();
}

public synchronized void stop(){
    if(!running)
        return;
    running = false;
    try {
        thread.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
}

```

My GameState

```
import java.awt.Graphics;

public class GameState extends State {

private Player player;
private World world;

public GameState(Handler handler){
    super(handler);
    world = new World(handler, "res/worlds/world1.txt");
    handler.setWorld(world);
    player = new Player(handler, 200, 200);
}

@Override
public void tick() {
    world.tick();
    player.tick();

    if(handler.getMouseManager().isRightPressed())
        System.exit(0);
}

@Override
public void render(Graphics g) {
    world.render(g);
    player.render(g);
}
}

```

# Answer
As opposed to benh answer, I would personnaly not re-instanciate your objects, but rather re-initialize them.

Let's have a small example where you have a player with `x`, `y`, and `life` attributes, and a list of enemies with the same attributes, at the beginning of the game you need to initialize theses objects

```
void initGame() {
    player.init();
    initEnemies();
}

```

In your player class

```
void init() {
    this.x = 0;
    this.y = 0;
    this.life = 100;
}

```

And same for enemies

```
void initEnemies() {
    enemies = new ArrayList<>();
    Enemy enemy1 = new Enemy(5, 5, 100);
    enemies.add(enemy1);
    // ... And so on
}

```

**Whenever you start a new game**, call this `InitGame()` method, so it resets the game objects to the state you want.

One benefit I see in this method -aside from the fact that it is less expensive- is the fact that you can keep some data unchanged between games. Let's say for example that your player earns some money during each game, and that this money should not be reset, just don't put it in the `player.init()` method and your player will keep the hard-earned money.
> 2 votes

# Answer
You probably need to re-instantiate your player object, which means calling the constructor on the player reference. If your game architecture is a bit more messy you might have to re-instantiate multiple objects in order to reset the game. You should do this with the code which starts the game again after leaving the menu state.
> 2 votes

---
Tags: java
---


# Question
Title: Animation "Offset" in Unity 2D animation
I was playing around with Unity and its 2D Animator. When I press a Button now (to play for example the walk left Animation) it takes about 1 sec to begin the animation and same when I release the button to stop it. It's the same problem with every other animation.

Here's my Player Movement Controller:

```
using System.Collections;
using UnityEngine;

public class Player_Movement : MonoBehaviour {

public float speed = 10;
float old_pos;
float old_height;

void Start()
{
    old_pos = transform.position.x;
    old_height = transform.position.y;
}

void FixedUpdate()
{

    float h = Input.GetAxisRaw("Horizontal");
    float v = Input.GetAxisRaw("Vertical");

    Vector2 dir = new Vector2(h, v);
    GetComponent<Rigidbody2D>().velocity = dir.normalized * speed;

    GetComponent<Animator>().SetBool("isWalkingLeft", (h < 0));

    GetComponent<Animator>().SetBool("isWalkingRight", (h > 0));
  }
}

```

The problem also occurs when I switch directions and the animation should instantly switch over.

# Answer
The default setting for a animation transition in unity, is to blend the animation sheets. In 2D, for most cases, this is not what you want.

From the sounds of it, you do not want to have a transition period between the two animations. What you will want to do is set your transition duration to 0, and remove the check from "Has Exit Time".
> 1 votes

---
Tags: unity, c#, 2d, animation
---


# Question
Title: Controlling resolution in Unity 3D. Beginner's problems
i started working on developing games one month ago. I really like it, although it isnt easy.

The problem i have now, is with display resolution after i build game. So far i have been working with 2D Space Shooter game (getting help from the tutorial), everything is working smoothly. The only thing that i hardly understand is the resolution, aspect ratio thing. I have made a game that looks like this:

I have drawn a gizmos around the allien formation, and written a script with some calculations that everytime formation hits the edge, it goes to the other edge, hits the other edge, and goes to the other edge, and so on and on. In the free aspect movement looks great, but however, then i change the resolution to any other, movement is stuck, or it barely moves.

Now here is my question. What should i do, to make the game look and work smoothly on every resolution like it works on the free aspect display? I tried to change formation height and width and so on, but i assume this is not an option. I will add my formation controller script as well(it contains several other things so i printscreened only the code that helps formation to move):

Thank you for your time, and sorry if you can't understand everything or something is unclear to you, i'm beginner at game development and English is not my first language.

# Answer
> 2 votes
Shoot-em-ups are a genre where the gameplay is heavily affected by the horizontal and vertical size of the screen. There is a reason why the genre had its apex in the era of home consoles and arcade machines where the developers knew exactly what screen resolution they were targeting.

If you want to have the genre on modern PCs, there are several options, but neither is really satisfying.

* Decide to only allow your game to be played in a window with a fixed size or in fullscreen mode with a fixed screen resolution (Unity allows you to do that in the build settings)
* Change your camera size to stretch the playing field to fit the users screen. But the change to the aspect ration might look weird, and when you use 2d assets they will get blurry.
* Simply accept that your game will play differently with different screen resolutions and design the gameplay with that in mind.

# Answer
> 0 votes
Something come from script must be repaired with script, so also resolution. Something come from size must be repaired with size, this means you must use script to reorder the object location and resize your object based in the resolution.

**NOTE: THIS SCRIPT WON'T BREAK YOUR GAME, IF HAPPENED JUST REMOVE IT.**

I have a portable script ( **not affecting other script** ) that will make you understand easier (but the script still have weakness though, as you'll find out later), and in the script you must scale your object one by one, here is the script:

```
/*

The How-To-Use The Script Is Explained In The Script

*/

using UnityEngine;
using System.Collections;

/* change mainmenuresolution with your class name */

public class mainmenuresolution : MonoBehaviour {

    void CalculateResolution(string ObjectName) {

        /*change desiredWidth to width resolution you use when making the game*/

        float desiredWidth = 1366;

        /*change desiredHeight to height resolution you use when making the game*/

        float desiredHeight = 768;

        float currentWidth = Screen.width;
        float currentHeight = Screen.height;
        GameObject TheObject = GameObject.Find (ObjectName);
        float currentObjectPositionX = TheObject.transform.position.x;
        float currentObjectPositionY = TheObject.transform.position.y;
        float currentObjectPositionZ = TheObject.transform.position.z;
        float currentObjectSizeX = TheObject.transform.localScale.x;
        float currentObjectSizeY = TheObject.transform.localScale.y;
        float currentObjectSizeZ = TheObject.transform.localScale.z;
        float newObjectPositionX = (currentWidth / desiredWidth) * currentObjectPositionX;
        float newObjectPositionY = (currentWidth / desiredWidth) * currentObjectPositionY;

        /* if you want your object coordinate "z" scaled too , use : (currentWidth / desiredWidth) * currentObjectPositionZ */

        float newObjectPositionZ = currentObjectPositionZ;

        float newObjectSizeX = (currentWidth / desiredWidth) * currentObjectSizeX;
        float NewObjectSizeY = (currentWidth / desiredWidth) * currentObjectSizeY;

        /* if you want your object size "z" scaled too , change to : (currentWidth / desiredWidth) * currentObjectSizeZ */

        float NewObjectSizeZ = currentObjectSizeZ;

        // moving to new coord
        TheObject.transform.position = new Vector3(newObjectPositionX,newObjectPositionY,newObjectPositionZ);
        // resizing object
        TheObject.transform.localScale = new Vector3(newObjectSizeX,NewObjectSizeY,NewObjectSizeZ);

    }
    // Use this for initialization
    void Start () {

        /* change " Your Object Name " To The Name Of Your GameObject */

        CalculateResolution ("YourObjectName");

    }

    // Update is called once per frame
    void Update () {

    }
}

```

---
Tags: unity
---


# Question
Title: Changing an objects on through C# script in Unity
I am trying to export my Unity project to Android Studio so that I can create some Android buttons that "controls" the Unity app's behavior. I know what I have to do in order to let it access through Java, but I don't know how to change the color. I watched a video about on Youtube, and the guy used: `gameObject.renderer.material.color`. However, when I try to do the same it can't find material.

This is my script so far:

```
using UnityEngine;
using System.Collections;

public class ChangeColor : MonoBehaviour {

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

    }

    void ReceiveRotDir(string message)
    {
        if (string.Equals(message, "G"))
        {
            this.gameObject.renderer.m ///It can't find material
        }
        else if (string.Equals(message, "P"))
        {

        }
        else if (string.Equals(message, "B"))
        {

        }
    }
}

```

# Answer
Instead of referencing "renderer" you need to actually reference the renderer component you are targeting.

For example:

```
gameObject.GetComponent<MeshRenderer>().material.color

```
> 0 votes

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