# Question
Title: How flat-file and databases compare in games development?
Typically games built with a goal of being easily modded often store data in plain text documents, such as Rimworld. I can't see why an entire database system would be implemented just to read a few saved variables in other games? Sure if it's more efficient or built into the engine there's likely no reason not to use it.

# Answer
*I'll focus on answerable bit of the question:*

> I can't see why an entire database system would be implemented just to read a few saved variables, but at the same time, if it's more efficient or built into the engine there's likely no reason not to use it.

You are missing the point. There is no real reason to invent bicycle (own DB system) when you can just grab some which is already field-proven and attach it to your game (custom engine or whatever). DB systems are typically 3rd party tools or legacy from previous games studio has made - they come at lower "cost" or free.

On the other hand - plain-text has following drawbacks, which contributes to its lesser use in app-making:

* it takes more space and is longer to read from HDD
* it needs parsing before it can be used
* it does not have random access (unless structured in some non-texty way)

However there are pros too:

* human readable
* could be tweaked with simplest of tools (Notepad)

Those pros come in handy when you need more editing and less playing (think Alpha-Beta stage). But they become drawbacks in Release. That is why some games support both text and binary, because the text has remained from early dev stages.
> 1 votes

---
Tags: databases, data, storage
---


# Question
Title: Procedural generation of evenly distributed random points (2d)
I am coming here because I've have a performance problem with my current implementation of an algorithm. I am the idea of Voronoi diagrams to distribute patches on an infinte 2d layer.

For a Voronoi pattern you need to have a set of points which is in my case procedural generated to allow an infinite generation of the Voronoi pattern.

And there is the problem. I have an algorithm which requires uses a grid of `interval` for the distance between each point on the grid. But I don't want a perfect square pattern so I add a randomization to each point on the grid with `amplitude` as possible randomization on X and Y axis.

Here you can see how the points are shifted by adding the randomiation. (The randomization depends on the coordinates of the point on the grid to allow procedural generation. They are generatied by a noise map, but let's assume they are just a seed for a RNG)

And now we come to the performance problem. I have a point (x,y) which I need to find the nearest point. So what I do is I take all points within the maximum randomization amplitude and apply the randomization to get the points in my layer.

Now I take the random point with the shortest distance to my point (x,y) and return it.

The performance of the code is exploding very quickly though.

```
n = amplitude / interval
runtime = (2n + 1)^2

```

A basic shape of the code is here, in the actual code I already use caching to avoid costly randomization of one point multiple times.

```
Vector2d currentlyBest = null;
double bestDistance = Double.POSITIVE_INFINITY;

double gridX = round(x / interval) * interval;
double gridY = round(y / interval) * interval;
for (double ix = 0; ix <= interval + amplitude; ix += interval) {
    for (int loopX = -1; loopX < 2; loopX += 2) {
        double dx = gridX + ix * loopX;
        for (double iy = 0; iy <= interval + amplitude; iy += interval) {
            for (int loopY = -1; loopY < 2; loopY += 2) {
                double dy = gridY + iy * loopY;
                Vector2d point = new Vector2d(dx, dy);
                randomizePoint(point);

                double px = point.x - x;
                double py = point.y - y;
                double disSq = px * px + py * py;
                // save point if disSq is smaller than before
            }
        }
    }
}

```

Thanks for reading so far! My question now is, if anyone knows a way to improve that or if you know a better way to produce evenly distributed randomized points on a 2d layer.

Thank you very much!

PS: I am not allowed to post more images so I can't give you more images, sadly :(

# Answer
> 4 votes
I guess what you're looking for is what's called "Worley's Noise".

An In Depth Cell Noise Tutorial (archived)

It's very similar to what you're already doing. But instead of placing the points at the corners of the grid and moving them around, you place one (or more) points within each cell at random. When you want to find the closest point to a point P, you find which cell the point P lies in, and then start from that cell outwards. There will be a moment where all other cells are further away from the closest point you already have, and then you stop. If there's always one (or more) points within each cell, you'll never need to search in more than 9 cells (assuming this is in 2D)

---
Tags: 2d, algorithm, random, procedural, world-design
---


# Question
Title: Fastest way to neutralize scale in the transform matrix?
Let's assume we have 4x4 3D transformation matrix, that is the result of scale, rotation, and translation transforms. How to set its scale to (1,1,1) in the fastest way? Assume also that the matrix is represented by float\[16\] array.

By fastest way I mean, the most performance accurate way, that will be low CPU cost.

# Answer
Assuming your matrix multiplication follows the convention...

`M * v = (T * R * S) * v`

(where `M` is your composed matrix, `T` is a Translation matrix, `R` rotation, `S` scale, and `v` is a vector you want to transform using the matrix)

...then you can **normalize the first three columns** of the matrix to get just the `T * R` part.

If you use the opposite matrix multiplication convention (`v * M`) then you'd normalize the first three *rows* instead. Either way, you only want to modify the 3x3 block of entries in the top-left of the matrix, ignoring the last row & column (which contain translation information and the homogeneous unit)

If you want to eke out every last CPU cycle, you can play with SIMD instructions to do the three vector normalizations with one multiply & square root, but this is likely to only be noticeable if you're processing big batches of these matrices in a very friendly data layout.
> 4 votes

# Answer
There's a trick you can use to numerically remove (or rather reduce as much as you want) any scaling from the upper 3x3 sub-matrix, assuming it's not singular. Let's call that 3x3 sub-matrix M. You can take the transpose of the inverse of M, and average it with M. That will be the new M for the next loop.

```
while (...) {
   N = (transpose(inv(M)) + M)/2
   if M is almost like N then stop
   M <-- N
}

```

You can set a max number of loops, and stop earlier if M is close enough to N
> 0 votes

---
Tags: algorithm, matrix, optimization, transformation
---


# Question
Title: Why do I have to do minus-equals for the x-coordinate but plus-equals for the y-coordinate?
I found a simple script in C# in Unity5 to make the camera follow the mouse:

```
xRotation -= Input.GetAxis ("Mouse Y") * lookSensitivity;
yRotation += Input.GetAxis ("Mouse X") * lookSensitivity;
transform.rotation = Quaternion.Euler (xRotation, yRotation, 0);

```

I understand why the y-axis is used for `xRotation` and visa versa. I just don't understand why if I change `xRotation -= ...` to `xRotation += ...` it inverts it and the same with `yRotation`.

# Answer
> 2 votes
It has to do with the way the coordinates systems are set. In particular, what it means to increment the Y coordinate for the mouse? an on the screen?. I'm not sure which convention Unity follows, but to put an example. The mouse coordinates might be (0,0) at the top-left corner and Y would increase when moving the mouse downward. On the other hand, the screen coordinates might have a Y component that increases when going up. That's why you need to flip the sign of Y but not for X, as increasing X, both for the mouse and on screen means moving to the right.

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


# Question
Title: Player jitter when positioned at large coordinate values
I am trying to make a simple top down scrolling shooter using Unity3D comprising of the following elements:

1) Top down orthographic camera: points at 65 degrees towards the ground. At a height of 1000 units. Size 100.

2) Spaceship: Moves around based on the up/down/left/right keyboard commands. Each press moves the ship 1/100 of the screenwidth in distance. I keep its position in screen coordinates and use a ray cast to project it to a height of 500 units off the ground in the camera space using the following code:

```
Ray ray = mainCamera.camera.ScreenPointToRay(screenLocation);
Plane plane = new Plane(new Vector3(10, 500, 0),
    new Vector3(0, 500, 10),
    new Vector3(-10, 500, 0));
float enter;
plane.Raycast(ray, out enter);
transform.position = ray.origin + ray.direction * enter;

```

3) A camera scroll component that moves the camera forward by 0.75 units every frame.

When I play the game the spaceship is controlled in screen space and its world coordinates are calculated relative to the scrolling camera. The camera starts at y: 1000, z:0 and z is incremented by 0.75 (scroll per frame).

The problem I am running into is that after a while, the player ship begins jittering. The jittering gets worse the longer the game goes on. The jittering is noticeable around the time z becomes 4200 which gives me about 1m30s game time at 60fps before the jittering starts. The levels I want to create would only be less than 20 mins which would mean that I need a max Z value of 2700 assuming my Z started at -2700 and finished at +2700.

I realised this must be caused by the limitations of floating point precision so I started playing around with the numbers to see what I could do to solve this.

I found that modifying the height of the camera to 50 and the ship to height 25 whilst keeping the orthographic camera size at 100 allowed me to set the distance to around 32,000 with no jittering. I didn't fully understand why this worked as the values of the ship transform and camera transform were still truncated to 2 decimal places at the extreme distance of 32,000. Scaling the camera size to 5 brought back the original problem. This 'fix' seemed mighty hacky to me though as it pretty much screws up the scale of objects in the game and only looks 'normal' because of the orthographic perspective. I don't know how well this would play with other things I plan to add to the game.

I have 3 options at this point:

1) Continue to find a way to get it to work with the limit of 20 minutes and using a virtual camera that tracks around the world coordinate frame. This would be great if it works as I could easily use the editor to add enemies at correct positions e.t.c.

2) Make it so that when it reaches a z limit, the camera resets to z = 0 and all objects in the scene revert back relative to the camera shift. The downside to this I guess is that I would need to figure out how to get the objects to shift back correctly when the limit is reached and also it would be trickier to use unity's editor to do enemy placement e.t.c.

3) Keep the camera at position z=0 and scroll the world backwards towards the camera. This seems like the ideal thing to do as I could place objects and scripts in unity world space and when the game runs, these elements could shift back every frame. I don't know how to achieve this at the moment however. I thought of using a parent object that moves back by 0.75 every frame. Enemies would be children of this object and the player camera would not be a child but be at the same place all the time. However I think this would still cause problems as maybe enemies placed far out in the z direction might jitter as they moved around. Is this concern legitimate?

I am wondering if anyone has any better ideas to solve my problem or understands why changing the height scale seems to temporarily fix the problem?

# Answer
Another, very invasive, fix might be to create the levels in sections. Each section is built around a local origin and is brought in when needed (and offset) and prior levels discarded. At each transition the offsets are reapplied to keep active levels in a local range.

I'm unsure if that's possible in the Unity environment, however.

Kind of like Gumby train tracks
> 2 votes

# Answer
I was facing same issue on "large" world. My PointLight shadows started to jittering at coords \>4090, it also depends how you set your Perspective (near and far plane), if near plane is around 0,1 (for big close up), the world starts jittering at around 4000, if you set near plane to 1.0f, you are safe till 8000 coords (in my case). But this is not solution, just improvement.

Solution (also for me was) is your option 3. Have static camera that can see, let's say 2000px far (much enough) and you move with world around it. Camera will be the origin of the world.

My pointlights at around Zero: http://www.youtube.com/watch?v=GFVaU9ZO2rQ

My pointlights at the edge around (4096,4096): http://www.youtube.com/watch?v=5V9zVoXFG9c

You can see the jittering, till camera finally stops moving. Yes it is float issue with high numbers.
> 1 votes

# Answer
That jitter you see comes from the way floating point numbers work. A float has only a fixed number of significant digits. If they are storing a large number, the decimals suffer from loss of precision.

Let me put an example using decimal numbers. Suppose floats can hold say, 5 significant digits only.

Also, let's say the ship is positioned at 10.000, If you want to move it slightly, you could move it to position 10.001. However, if instead the ship is located at position 10000, you can only move the ship to 10001, which is a jump of 1, instead of the 0.001 you previously had. Hence the jitter.

The solution 3) you mention would be the best option. Try having the coordinates of the camera and the ships as small as possible. In particular their absolute value should be small compared to the distance between them. That is, don't place the camera at position 10000 and the target at position 10005, instead make it so they are closer to 0 and 5.
> 1 votes

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


# Question
Title: How to get an game object to instantiate lower than where It's created?
When I press the collider where my allies spawn I want for them to spawn a little bit lower when I instantiate. I have tried to use Vector 3 and GetComponent, but It gives this error:

'Assets/Scripts/PlaceMonster.cs(26,33): error CS0131: The left-hand side of an assignment must be a variable, a property or an indexer'

I just want for my allies to spawn a little bit lower than the collider, but I'm stumped on what's the problem.

```
void OnMouseUp () {
    theAllyMenu.gameObject.SetActive (false);
    if (canPlaceAlly ()) {
        ally = (GameObject)
            //GetComponent<Transform>().transformPic = transformPic;
            transform.position = new Vector3(transform.position.x, transform.position.y - -5, transform.position.z);
            Instantiate (allyPrefab, transform.position, Quaternion.identity);
    }

}

```

# Answer
`ally = (GameObject)`

...is a syntax error. You need to comment this line just like you did the one below it.

The problem is on that line, but because it's so malformed (no semicolon at the end), the compiler doesn't recognise it and assumes the problem is on the next line,

`transform.position = new Vector3(transform.position.x, transform.position.y - -5, transform.position.z);`

...which actually has no problems, of course.

---

Really, this is why formatting is so important. If you had tab-indented your code correctly:

```
void OnMouseUp () {
    theAllyMenu.gameObject.SetActive (false);
    if (canPlaceAlly ()) {
        ally = (GameObject)
        //GetComponent<Transform>().transformPic = transformPic;
        transform.position = new Vector3(transform.position.x, transform.position.y - -5, transform.position.z);
        Instantiate (allyPrefab, transform.position, Quaternion.identity);
    }
}

```

Or even better, kept what is one statement, on one line,

`ally = (GameObject) GetComponent<Transform>().transformPic = transformPic;`

Then you might have seen the problem straight away.
> 4 votes

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


# Question
Title: Unintentional slight arm position change
In the scene I have a capsule with a camera parented and a looking script so when I look down or up the weapon slightly moves forward and then moves back when I look straight forward.

weapon when I look up or down-

and heres how it looks normally when I look straight forward-

Anyone knows how I can fix that?

EDIT: Here's how it looks in scene view

# Answer
> 1 votes
This is a strange behaviour in Unity's scale inheritance system. If the parent has a non-uniform scale, when you rotate the child, they deform/stretch like a rubber band.

Try adding an empty child GameObject to Player GameObject and parent the Camera GameObject to empty one, and put the rotation script on Camera. This makes parent of the Camera a uniform-scaled transform, so your rotations won't alter childs' scales.

***Note:*** Make sure the empty GameObject has a uniform scale (ie, 1-1-1).

# Answer
> -1 votes
Parent the gun to the player not the camera. The camera movement is changing the transform of the gun. The capsule for the player still tips forward and backwards so parenting it to the player will alleviate the issue. Otherwise you can code a fixed transform that only allows for verticle and horizontal transform change instead of a forward transform change to follow the camera if you don't want to change what it's parented to.

---
Tags: unity, camera, movement, first-person-shooter
---


# Question
Title: Maths ? coordinates rotating around coordinates
could you give me a tip please, a redirection to what is the "simple" math I need to learn and understand for the rotation of an object (its coordinate x, y) around an other object (an other x, y), I guess I could also describing my need as (x, y) moving coordinate orbiting around (x, y) fixed coordinates. It is for a little HTML5/Javascript game. Thank you.

# Answer
You don't need matrices at all. Just take the rotation angle in radians, get its cosine and sine, multiply them by the distance you want between the two objects and add the x and y values of the fixed object:

```
rotatingObject.x = Math.cos(rotationAngle) * distance + fixedObject.x
rotatingObject.y = Math.sin(rotationAngle) * distance + fixedObject.y

```
> 3 votes

# Answer
Edit: Added the simplified form. user6245072's answer works great if distance is known, and the way below works with known coordinates.

Edit: Nevermind the matrices, look at what user6245072's answer instead. It's more simple. I was thinking too hard :p

That, would be matrices. There's a lot of websites that explains it for you.

This is a matrix i took from an util class i made my self a while back:

```
[Math.cos(ang), -Math.sin(ang), 0.0f, (-X * Math.cos(ang) + Y * Math.sin(ang) + X)]
[Math.sin(ang), Math.cos(ang) , 0.0f, (-X * Math.sin(ang) - Y * Math.cos(ang) + Y)]
[0.0f         , 0.0f          , 1.0f, 0.0f                                        ]
[0.0f         , 0.0f          , 0.0f, 1.0f                                        ]

```

With (X, Y) to be the point of rotation and ang to be the rotation degree in radians.

If you multiply that with a vector it will rotate the vector relative to (X, Y). This is the multiplied form:

```
rotatedX = x * (Math.cos(ang)) + y * (-Math.sin(ang)) + (-X * Math.cos(ang) + Y * Math.sin(ang) + X);
rotatedY = x * (Math.sin(ang)) + y * (Math.cos(ang)) + (-X * Math.sin(ang) - Y * Math.cos(ang) + Y);

```

Edit: Simplified form for anyone running to this thread again:

```
float dx = x - X, dy = y - Y;
rotatedX = dx * (Math.cos(ang)) + dy * (-Math.sin(ang)) + X);
rotatedY = dx * (Math.sin(ang)) + dy * (Math.cos(ang)) + Y);

```

There should be some other approaches out there, but this work too.

The main idea:

1. Translate the point which you want the object to rotate to, to (0, 0)
2. Rotate normally (can be done with a normal rotation matrix)
3. Translate back to its original place
> 0 votes

---
Tags: mathematics, javascript, html5
---


title: Main game objects as static

text:
# Question
Title: Main game objects as static
I'm making a game for Android using Android Studio with Libgdx in Java. In my game there are main object like Screen, ObjectFactory, SoundPlayer, Painter (Responsible for drawing) and a few more. 'til now I passed them to each GameObject that uses them but then I realized I could just make them static and every GameObject who needs them will just call them statically. I wonder if I make these main objects static, would it hurt the performance? Because it seems like such a comfortable solution... Thanks in advance.

# Answer
> 9 votes
It won't hurt performance. It might in fact be (very, very negligible) faster because you save the overhead of passing these objects to the game objects.

The reason static classes are often frowned upon is that their static properties are global variables and globals cause all kinds of problems architecture-wise. For example, when you ever decide you might require more than one Screen, ObjectFactory, SoundPlayer or Painter object, you will have a hard time refactoring your application to allow that. Another problem is that you can't initialize these objects as soon as they are created, because they are always around. That means you need to keep in mind which one is already initialized and which one is not, which can cause quite a headache when they have dependencies on each other.

But if these reasons are not convincing for your particular project, there is nothing wrong with static classes.

# Answer
> 3 votes
If you're definitely only ever going to have one instance of these objects, and presumably you are, then this would be a better way to go. However, maybe a better solution would be to use the Singleton pattern, and (for example) create a static GetScreen() method in the Screen class that any other class can call to obtain the single instance of the Screen class.

---
Tags: java, android, libgdx, android-studio
---


# Question
Title: For a custom game engines, what should I do if my core data is malformed or missing?
I'm writing a custom engine for a game. I started this game well before I understood why I should use middleware, instead, and it's too far along to rewrite.

The vast majority of my data comes from external files, and I don't just refer to assets; I define all of my game objects through .JSON. But, alas, I am human; occasionally my data files are invalid, or I change the format but forget to update the file, or the loader itself is flat-out buggy.

If, for whatever reason, an attempt to load some form of asset in a custom engine fails, what options do I have?

This is not a duplicate of How should I handle missing resources?, as that question is about user-facing assets like models or textures. Bad textures can be replaced with a checkerboard, bad sounds with silence, and bad text with "ERROR". My problem lies with data that's critical to the game even running, such as levels, game object definitions, and GUI layouts.

# Answer
> 42 votes
**Log an error and gracefully exit.**

Ideally, display a human readable error on screen as well. There should be a core pipeline of hard coded functionality that operates without these data files. It's the same pipeline that loads the data files in the first place. It should be capable of detecting when these core data files are corrupt or otherwise faulty and end the application. If users are intended to modify these files, there isn't much else that can be done. Otherwise, you need to implement a testing strategy to ensure these kind of corruptions don't happen. Then you can ensure you're only releasing valid data files.

# Answer
> 11 votes
Byte56 mentioned one option. There is at least one other:

**Assume default values and display a Warning.**

Depending on the nature of your data, it might be perfectly acceptable to assume some default values and warn the user that "since file xxx failed to load, we are using a generic yyy object."

# Answer
> 6 votes
### It depends on whether this happens during development or release.

During development, you will have all kinds missing things, errors, and mess-ups, constantly, all the time, and you may even want to "hot" load assets on demand or replace an asset while the game is running. You might edit scripts with the game running to test an AI performs better, or anything the like.

It is *most annoying* if the program shows an error dialog and exits every time, and you must restart it which takes 2-3 minutes. The goal in development is to stall you (whose time is the most precious asset) as little as possible.
So, if for example, a texture is missing, you would want to see something like a red-white checkerboard, maybe with the word "missing" spelled on top of it as a replacement texture, so it is immediately obvious that something is odd. But you do not want the game to exit gracefully, nor even crash. Detailled information about what is missing in your logfile is immensely helpful.

On the other hand, in a release, the complete set of asset files should ideally\[1\] have gone through your automated asset pipeline. This needs to be not much more than a simple parser that reads in all your JSONs and then cross-checks that every module is consistent in itself, and verifies that every asset that you reference is actually there, and then zips the whole bunch of files up in some known (but not necessarily standard) way that is easy for your engine to read, optionally adding a few checksums.

You *know* that there can be no failure because your pipeline checked that everything was there before you released the package to the end user. So if a failure happens, either there has been a transmission error, or more likely the user is trying to cheat. In either case, the program should display a message saying that asset files are damaged, and exit.

Alternatively, you might offer the option to download a pristine copy of the assets from the internet (if you have a download server). But in order to avoid a customer support nightmare, be sure to *ask* prior to downloading gigabytes of data.

---

\[1\]Reality may look different, you may even find missing assets on AAA titles whose makers "should know", but they usually have unrealistic deadlines and large, changing teams, too. Ideally everything you ship has gone through the automated pipeline and is guaranteed to be complete.

---
Tags: assets, loading, data, configuration
---


# Question
Title: How to save slider button positon on saved value.?
I am new to game dev. I have below code and it\`s work good. I can change volume using this code and with AudioSource slider script. I also saving this volume state using playerprefs from 0-1. My problem is I can not keep slider button to its saved value when reload / replay the game.

If slide has value like .72 or anywhere between 0-1. then audio play with perfect saved volume but button not set to .72. Any one can help.

How can i save button position on saved value when start play again.

My code is...

```
using UnityEngine;
using System.Collections;

public class vfxslider : MonoBehaviour {

void Awake(){
    GetComponent<AudioSource> ().volume = PlayerPrefs.GetFloat ("CurVol");
}
// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
//  AudioListener.volume = PlayerPrefs.GetFloat ("CurVol");
}

public void slidervolumecontrol(float volumecontrol){
    GetComponent<AudioSource> ().volume = volumecontrol;
    //audio = GetComponent<AudioSource> ().volume;
    // audio.volume = volumecontrol;
    PlayerPrefs.SetFloat("CurVol",GetComponent<AudioSource> ().volume);
    PlayerPrefs.Save ();
    }
}

```

In first picture I have sated volume value of first VFX slider to 0.60800. On this I can listen music.

but in second When i stop playing and play again then slide button remain in zero position but still i can hear music.and also I can not see saved value of volume in right side. check that volume is zero but still I can hear music with 0.60800 value.

# Answer
I hope this code I wrote helps you. If you have any more questions please ask.

```
using UnityEngine;
using UnityEngine.UI;

public class NewBehaviourScript : MonoBehaviour {

    private AudioSource src;
    public Slider slider;// This is so we can drag the slider to the inspector view ot this script
    // Use this for initialization
    void Start () {
        src = GetComponent<AudioSource>();// This gets a reference to the Audio source you can get it any way you want
        src.volume = PlayerPrefs.GetFloat("CurVol");// Set the saved volume
        slider.value = src.volume; //This sets the slider value to the same amout as the volume on the audio source.
        slider.onValueChanged.AddListener(delegate { ValueChangeCheck(); });
    }

    // Update is called once per frame
    void Update () {
        if (Input.GetKeyDown("a")) // I'm just using the A key as a event trigger for the save.
        {
            PlayerPrefs.SetFloat("CurVol", src.volume); // This will save the volume of the Audio Source not the slider
            // To save the slider value
            //PlayerPrefs.SetFloat("CurVol", slider.value);
            PlayerPrefs.Save();

        }
    }
    public void ValueChangeCheck()
    {
        src.volume = slider.value;
    }
}

```
> 1 votes

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


# Question
Title: What would be a perfect manner to load a scene then the player's position in Unity 5.3?
I have problem with scene's and objects' positions. My problem is that the position of object/player changes after I load the scene. I don't know why this happens.

I have saved my object position with "playerprefs". The object keeps its position if I remove the code that loads the scene but if I write the one line of code to load the saved scene with object/player position, the scene completely reloads with (0,0,0) as its position.

**I have seen that Unity player first loads the cube position and then loads the scene, but why? Because of this my cube position changes to default position (0,0,0). How can I load first the scene and then cube position?**

If any one can help me to keep position of object/player with loaded saved scene then many many thanks.

Here is my code:

```
public void save(){

    BinaryFormatter bf = new BinaryFormatter ();
    FileStream fs = File.Create ("D:/playerinfo.txt");

    playerData pd = new playerData ();
    PlayerPrefs.SetInt ("currentscenesave",SceneManager.GetActiveScene().buildIndex);
    PlayerPrefs.SetFloat ("cubeposx",cube.position.x);
    PlayerPrefs.SetFloat ("cubeposy",cube.position.y);
    PlayerPrefs.SetFloat ("cubeposz",cube.position.z);

    pd.x = PlayerPrefs.GetFloat ("cubeposx");
    pd.y = PlayerPrefs.GetFloat ("cubeposy");
    pd.z = PlayerPrefs.GetFloat ("cubeposz");
    pd.s = PlayerPrefs.GetInt ("currentscenesave");
    //cube.position = new Vector3 (PlayerPrefs.GetFloat ("cubeposx"), PlayerPrefs.GetFloat ("cubeposy"), PlayerPrefs.GetFloat ("cubeposz"));

    bf.Serialize (fs,pd);
    fs.Close ();
}

public void Load(){
    //loadScene ();

    BinaryFormatter bf = new BinaryFormatter ();
    FileStream fs = File.Open ("D:/playerinfo.txt",FileMode.Open);
    playerData pd = (playerData)bf.Deserialize (fs);

        fs.Close ();
        SceneManager.LoadScene (pd.s);
        cube.position = new Vector3 (pd.x,pd.y,pd.z);

    }
}

```

# Answer
Note: I'm by no means the lead authority on this, but I believe you've combined two different methods of saving the data.

Player Prefs don't require the binary formatter stuff Binary Serialization does not use player prefs

I'd say player prefs are easier to use (although not as great for saving lots of data)

To save the PlayerPrefs it's just `PlayerPrefs.Save()` -Here's a useful link to the docs: http://docs.unity3d.com/ScriptReference/PlayerPrefs.html

*Actually meant to be revising at the moment so my explanation isn't perfect, ask if you need more.*

Can't test it but try something on the lines of this:

```
public void Save(){
    PlayerPrefs.SetInt ("currentscenesave",SceneManager.GetActiveScene().buildIndex);
    PlayerPrefs.SetFloat ("cubeposx",cube.position.x);
    PlayerPrefs.SetFloat ("cubeposy",cube.position.y);
    PlayerPrefs.SetFloat ("cubeposz",cube.position.z);
    PlayerPrefs.Save()
}

public void Load(){
    //loadScene ();

   cube.position = new Vector3 (PlayerPrefs.GetFloat ("cubeposx"), PlayerPrefs.GetFloat ("cubeposy"), PlayerPrefs.GetFloat ("cubeposz"));

    }
}

```
> 0 votes

# Answer
When you load a scene from a script you cant execute code after that.You need to deserialize your player data and then set the position in a Awake() or Start() method. They get called once when the scene is loaded.
> 0 votes

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


# Question
Title: How to enable/disble vibration feedback in Unity?
I want to create toggle that enable/disable vibration feedback on the device, as i can't figure it out.

How do i do that?

```
public void ToggleVibration()
{
       //enable and disable vibration feedback..
}

```

I want to make a setting (toggle) that user want to use vibration in the game or not, as `Handled.vibrate()` makes the device vibrate only?

# Answer
I dont think you can turn off the vibration feature of the device. Your game will not vibrate the device unless you call `Handheld.Vibrate()`, so in your Toggle function why not just set a bool to true or false and do a check against that bool when you want to vibrate. You can actually implement a Toggle control from `UnityEngine.UI` and use its OnValueChanged to set the bool.
> 2 votes

---
Tags: unity, ios
---


# Question
Title: More efficient using invokerepeating or update?
Im fairly new to unity development and I am working on repeating an enemy. I currently have the functionality working correctly in which I use invokerepeating to spam an enemy. Now, I have an if statement that drops a different enemy if a specific Item is hit. This functionality works in both invokerepeating and update. Could someone explain to me which one is more efficient? And why?

# Answer
I would advise using neither for this particular case.

`InvokeRepeating` takes a method name, which means it's using reflection at runtime to look up the method to call. That's work we don't need to do, since we can already point the compiler at the exact method we want.

`Update` executes every frame, but for spawning we typically want to leave some time (or other condition) between spawns so things don't bunch-up. That means we're repeatedly calling the function just to do nothing until the right frame.

Neither of these is awful, but we can do better with coroutines. These let us set up recurring behaviours that execute only when we want them to, without any unnecessary string lookup complexity.

```
bool keepSpawning = true;

IEnumerator SpawnAtIntervals(float secondsBetweenSpawns)
{
    // Repeat until keepSpawning == false or this GameObject is disabled/destroyed.
    while(keepSpawning)
    {
         // Put this coroutine to sleep until the next spawn time.
         yield return new WaitForSeconds(secondsBetweenSpawns);

         // Now it's time to spawn again.
         Spawn();
    }
}

```

Then we can kick off the spawning with...

```
StartCoroutine(SpawnAtIntervals(3f)); // Or whatever delay we want.

```

And we can stop spawning by setting `keepSpawning = false;`

If you need more granular control (eg. the ability to switch between two spawning streams, etc.) this is possible too - you'll just need to include in your question more details about your use cases.
> 5 votes

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


# Question
Title: Collision causing First Person Controller to go haywire
I have created a first person controller as an enemy in my game (Zombie). My character is an archer that uses arrows as projectiles that are shot with the following code:

```
if(Input.GetButton("Fire1")) {
    shotForce += 45f;
}

if (Input.GetMouseButtonUp(0)) {
    Rigidbody shot = Instantiate (projectile, shotPos.position, shotPos.rotation) as Rigidbody;
    shot.mass = shotMass;
    shot.AddForce (Camera.main.transform.forward * shotForce);
    shotForce = 0f;
}

```

I have a script to parent the fired arrow to the collided object which works fine for most objects in the game, but my enemy object (Zombie) speeds up and moves all around the place on a collision, I'm new to unity, I've spent a few hours trying to resolve this with out success.

I have a Rigidbody, Charcter controller and First person controller on the Zombie.

I have a Rigidbody and Sphere Collider on the Arrow.

The method I think is causing the problem:

```
void OnCollisionEnter(Collision collision){
        if (this.flying) {
            this.flying = false;
            Destroy (this.GetComponent<Rigidbody>());
            this.transform.position = collision.contacts [0].point;
            GameObject anchor = new GameObject ("ARROW_ANCHOR");
            anchor.transform.position = this.transform.position;
            anchor.transform.rotation = this.transform.rotation;
            anchor.transform.parent = collision.transform;
            this.anchor = anchor.transform;
            collision.gameObject.SendMessage ("arrowHit", SendMessageOptions.DontRequireReceiver);
        }
    }

```

I think the issue is with the line `anchor.transform.parent = collision.transform;` Maybe there is a solution without parenting the arrow to the Zombie?

I'm stumped at this stage any help appreciated.

# Answer
> 1 votes
I solved this by adding `GetComponent<Rigidbody>().isKinematic = true;` to my Arrow script in the `OnCollisionEnter` function.

---
Tags: collision-detection, unity, first-person-shooter
---


# Question
Title: How to get the closest "visible" object from my "player"?
I'm using Unity 3d and i have to accomplish the following task: get the closest "visible" object to my player in forward direction.

It is a sort of radar.

I don't know where to start. Any advice is welcomed.

Thanks

# Answer
> 3 votes
Assuming that you're making a 3D game, you can use `Physics.OverlapSphere` to get a an array of `Collider`s that are within a certain range of the player. To check if the object is *"visible"* to the player, you could simply call `Physics.Raycast` in the direction of the object(s) returned by `OverlapSphere` and check if nothing that isn't the object you're checking for blocks the raycast. Here's a code example:

```
public class RadarController : MonoBehaviour
{
    public int RadarRadius;
    public string DetectableObjectTag;

    public void CheckForVisibleObjects()
    {
        Collider[] objectColliders = Physics.SphereOverlap(this.transform.position, this.RadarRadius);
        for(int index = 0; index <= objectColliders.Length - 1; index++)
        {
            GameObject colliderObject = objectColliders[index].gameObject;
            if(colliderObject.tag == this.DetectableObjectTag)
            {
                RaycastHit hit;
                bool hitOccurred = Physics.Raycast(this.transform.position, colliderObject.transform.position.normalized, out hit);
                if(hitOccurred && hit.gameObject.tag == this.DetectableObjectTag)
                {
                    // Do whatever you need to do with the resulting information
                    // here if the condition succeeds.
                }
            }
        }
    }

    public void Update()
    {
        this.CheckForVisibleObjects();
    }
}

```

**Disclaimer:** I am not able to check and see if this code works properly, or if it performs at an ideal rate. If there is an issue, just mention it and I'll see what I can do.

# Answer
> 5 votes
You can use the dot product trick to get a list of instances actually visible by the player (thus lying inside the camera frustum), and check for the distance from your camera object to get the closest one.

First, you can test a certain number of instances so that their distance is low enough for them to be considered "near" the camera (or the player). Instead of testing every object, which can be overkill for your game performance, you can consider a volume around the camera (a sphere, for example) and test only object inside this space partition. The number of instances to work with is now lower, and more tests can be performed.

In mathematics, the dot product of two vectors gives as result a scalar number, which represents the projection of vector *v1* upon vector *v2*. The length of projection depends on the cosine function of the angle between the two vectors. We can see it the other way: given two vectors, if their dot product is a value *k*, then their mutual orientation in the space (or plane, or any *n*-dimensional system) is such that the angle between them has a cosine value *cos(θ) = k*. So, the angle is *θ = arccos(k)*.

If your camera has a FOV angle ranges from  to *β*, assuming angle 0° is in front of the camera and that the frustum is just a cone, if *θ* is either lower than  or greater than *β*, your object is out of sight.

This said, you consider two vectors, *A* and *B*. Vector *A* is the relative position of an object, and *B* is the "front" vector of the camera. If the dot product of *A* and *B* is lower than or equal to the cosine of *β*, such object is potentially visible to the player. Otherwise, its position is away from the sight cone.

The final step is to search the list of remaining objects to find the one whose distance is lowest among all. Here's your closest, visible object to focus your attention on!

To sum up: consider a list of candidate object, so that every object is closer than a certain distance from camera. Help comes from space volume instead of checking every single instance. Then, compute dot product of those instances, to get a list of only instances lying in front of the camera. Finally, look for the closest one.

# Answer
> 2 votes
Typically, to get *the closest* object from the player, you do something like this (generic pseudo-code):

```
var listOfObjects = getAllObjects()
var closestObject = null
var distanceSquareOfClosest = infinite

for otherObject in listOfObjets:
  if otherObject != this:
    var distanceSquareOfThisObject = (otherObject.position - this.position).lengthSquare()
    if distanceSquareOfThisObject < distanceSquareOfClosest:
      distanceSquareOfClosest = distanceSquareOfThisObject
      closestObject = otherObject

```

I don't know how it's done in Unity, but I would assume there is something that lets you get all the objects, and there would be a way for you to check if they're visible or not. You'd modify the `if otherObject != this` to something like `if otherObject != this && otherObject.isVisible`.

To find all the game objects, you can take a look here.

# Answer
> 2 votes
As mentioned in the comments you probably want a Raycast.

An example of how to implement a forward-facing raycast in a Fixed Update cycle is spelled out exactly in the Unity Scripting API Documentation here. This will return true if the raycast strikes a collider in front of whatever object you attach the script to.

From the documentation above:

```
using UnityEngine;

public class ExampleClass : MonoBehaviour
{
    void FixedUpdate()
    {
        Vector3 fwd = transform.TransformDirection(Vector3.forward);

        if (Physics.Raycast(transform.position, fwd, 10))
            print("There is something in front of the object!");
    }
}

```

After that, to return the object you strike with your raycast, you use a Raycast.Hit to get the transform of whatever you're hitting. We do this because the transform has a variable of gameObject. SO:

```
        using UnityEngine;

public class ExampleClass : MonoBehaviour
{

public GameObject storedGameObject; //create a bucket to store the game object in when we find it

    void FixedUpdate()
    {
    RaycastHit hit; //define the raycasthit

        Vector3 fwd = transform.TransformDirection(Vector3.forward); //define the forward Vector3

        if (Physics.Raycast(transform.position, fwd, hit)) //use the current transform position to start, shoot outward "fwd", and return a RaycastHit
            {
            storedGameObject = hit.transform.gameObject; //set the bucket to the value of the target's transform.gameobject
        }
    }
}

```

Full disclosure: I'm at work and can't test this code, but it should be approximately what you need.

---
Tags: unity, vector
---


# Question
Title: Integrating specular, diffuse reflection and refraction
I am implementing an MLT bidirectional path tracer. I have a problem integrating diffuse, specular reflection and refraction.

1) The first problem is diffuse and specular reflection. Diffuse reflection is done by sampling ray in a hemishere. But specular reflection is done by finding the ray that have an angle to the normal equal to the incident ray with the normal. However, an object can have both diffuse and specular reflection. When to use specular reflection or diffuse reflection for a ray?

2) Same as the first question but this time integrating reflection with refraction.

I've seen a few research papers and websites online where the scene have specular, diffuse reflection and refraction, but they have no tutorial on how to do this.

# Answer
> 1 votes
The Phong model (diffuse + specular + ambient) is just an approximation of how light behaves. In reality, there's what's called a BRDF or bidirectional reflectance distribution function. It is a function which tell you, for a given point on the surface the probability of light bouncing in a given direction given an incident ray of light. The components (diffuse, specular) of the Phong model, (or any other model for that matter) are used to approximate the BRDF, by splitting it into roughly independent components which are easy to evaluate independently and then added together.

What does it mean? well, when you cast a ray and it hits a surface, you now have to decide where to shoot the next ray or rays. For perfectly specular surfaces, the ray is reflected with the same incident angle. How much those reflected rays will deviate from the perfect reflection vector will depend on the glossiness of the surface. For completely diffuse surfaces, the ray can be cast in any direction on the hemisphere above the point on the surface.

If you want to approximate diffuse and specular components independently, then you need to cast at least two other rays, one which will sample the diffuse contribution and another one which will sample the specular contribution. If you consider refraction as well, then you'll need a third ray.

In reality, when the reflection is not deterministic (when you don't have a perfectly reflective surface) you won't just shoot a single ray, but instead you'll shoot many rays to sample the surroundings. The more rays you shoot, the less noise you'll have in your final image, but it will become slower to compute.

How many rays to actually send and where is a very interesting and complex topic in itself. Shooting rays is not cheap, specially considering the noise in the final image decreases as the square root of the number of rays you sample. So sampling efficiently is important.

For example, for a particular material you might want to send a thousand rays, but send 90% to sample the diffuse component and 10% to sample the specular component because the diffuse part will contribute more to the final color and the surface is very smooth, and hence those 10% of the rays will all follow pretty much the same path.

---
Tags: algorithm, graphics, reflection-rendering, path-tracing
---


title: NGUI sprites become blurry on android

text:
# Question
Title: NGUI sprites become blurry on android
I have this screen in the editor made with NGUI and 8 sprites:

But when I build it for android and open the game the same sprites on the screen looks blurry

I don't know what could be causing this, I have all the sprites in Point(no filter) mode, no mip maps and in True Color. Their Max Size is according to each sprite size.

I haven't touched anything strange in the atlas maker(it's only one big atlas), so it should have all default settings. What could possible be the cause of this? I have been searching but I haven't found anyone who had the same problem. Is there a setting I could be missing?

# Answer
> 0 votes
I was able to fix it by going into the Atlas texture made by NGUI and unchecking the option of "Generate Mip Maps"

---
Tags: unity, hud, ngui
---


title: XNA/MonoGame creating a player

text:
# Question
Title: XNA/MonoGame creating a player
After some fine-tuning on my game's GUI I am finally ready to begin with the gameplay. But that's a tall order. My game will be something like a 2D platformer with RPG elements like collecting armor, helmets, weapons etc. So with that in mind I begun thinking about a way to create my player. First, I thought a single `Player` class would do the job for me but since I want to equip the armor/helmet I've acquired, I quickly abandoned this concept.

Next I got another idea. I could have the player's `Head`, `Arms` and `Legs` to be different classes and each of them drawing its own texture, respectively. So I can swap between different armor/helmet sprites for each of the body parts. But that would seem pretty complex to implement... or not?

Could I have a code example on how you would do this? Which path you would take if you are in my stead? Single `Player` class or different body parts classes? If the latter, how would you hook them so that it all looks like a single sprite?

# Answer
> 1 votes
Personally, I would use a single `Player` class element, for simplicities sake. Here I would just have drawing code that accounts for the various upgrades that the player purchases.

For example, I would have some kind of `UpgradeManager` class that holds all the upgrades in a list, based on some `List<Upgrade>` where each upgrade has a `Texture2D` property. Then I would assign the upgrades in a `List<Upgrade>` as a property with the `Player`.

Hopefully this will get you on the right track.

# Answer
> 0 votes
I would do both. I would make separate arms, legs, body, and head classes and keep track of them all within a player class. This way, in your Game1 class and other classes, the player is treated as ine object, but within the class, the body parts are treated separately. Hope this helps!

---
Tags: c#, xna, textures, monogame
---


# Question
Title: Having trouble setting a game object as a child of another. What is wrong here?
So I'm trying to raycast on mouse click if it hits any thing make that object a child of the sender (in this case the parent). Below is my code...

```
public class PhysGun : MonoBehaviour
{
    private GameObject Player;

    void Start ()
    {
       Player = GameObject.Find("Player");
    }

    // Update is called once per frame
    void Update ()
    {
        Vector3 fwd = transform.TransformDirection(Vector3.forward);

        if (Input.GetMouseButton(0) && Physics.Raycast(transform.position, fwd, 10))
        {
            //this.transform.parent = Player.transform;
            transform.SetParent(Player.transform);
            Debug.Log("There is something in front of the object!");
        }

   }
}

```

The script is attached to a child of the player and I will eventually attatch it to a motion control (Vive).

What am I doing wrong exactly? I've tried multiple ways to do this and none of them work (or present any errors). Also to clarify the issue it's not parenting the game object hit by the ray cast to the Player like I want it to.

# Answer
When you write `transform` without anything in front of it, it refers to `this.transform`, ie. the transform attached to the GameObject this script instance is running on.

It sounds like you instead want to modify the transform *of the object hit by the raycast*. To do this, we need to capture a reference to it...

```
Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hit;

if (Input.GetMouseButton(0) && Physics.Raycast(ray, out hit, 10f))
{
    hit.transform.SetParent(Player.transform);
    Debug.Log("We hit: " + hit.transform.name);
}

```

That `out hit` parameter tells the `Raycast` function to capture information about what it struck (like the object, contact point & normal, distance...), so you can access it through the `hit` variable. `hit.transform` gives us the transform of the struck object.
> 2 votes

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


# Question
Title: Upgrading Unity from 5.1 to 5.3.4 has broken game, specifically models made in Blender
I recently decided to upgrade Unity after putting it off for some time as I have a rather sizable project started in 5.1. I knew there would be some hurdles, however, I have had very little luck in getting the game back up and running in the new version. My Blender model animations seem to be gone and many of the faces are disappearing. For example a characters arm is just missing and other similar issues across models. The warning I'm getting seems to be due, at least in part, to a shader I'm using attached to a prefab, however, when I change it to even the standard shader Im still getting the warnings and the issues persist.

My question is: Is there something I'm missing in the upgrade process that can make the transition easier, because right now, it would seem I need to recreate all of my Blender assets and reassign all of my materials and not be able to use some of my shaders?

The process in which I upgraded was very simple. I just opened the project folder with the new version of Unity and rebuilt the project for the new version.

Any help from anyone who has experience migrating projects between different versions of Unity would be appreciated.

# Answer
> 1 votes
I was able to eliminate all of the GpuProgram warnings and also fix all of my animations by trial and error elimination of several shaders and additionally re-importing the models from Blender. Steps as follows.

1. I set all of the models to use the standard shader in Unity.
2. I then deleted and reloaded the offending shaders and did not have any errors, this fixed the GpuProgram warnings.
3. To fix the animations and models missing faces etc. I went into Blender and saved the models in the project asset directory over their originals.
4. Unity seemed happy with the new imports and all models/shaders are now working.

I'm not sure why just deleting the library folder didn't work in this case, it seems like it would achieve the same thing. This was a lot of work but ultimately got me back to where I was before upgrading.

---
Tags: unity, shaders, models, blender, bug
---


# Question
Title: How to refer to a object that has just been hit by a ray cast?
I would like to use `RigidbodyConstraints.FreezeRotation;`in order to freeze the rotation of an object that is picked up. The problem is I don't know how to refer (or call) the currently selected object. The script in it's currents state is below...

```
public class PhysGun : MonoBehaviour
{
    private GameObject Player;

    void Start ()
    {
       Player = GameObject.Find("Player");
    }

    // Update is called once per frame
    void Update ()
    {
        Vector3 fwd = transform.forward; // Equivalent to the code you had.

        Ray ray = new Ray(transform.position, transform.forward);
        RaycastHit hit;

        if (Input.GetMouseButton(0) && Physics.Raycast(ray, out hit, 10f))
        {
            hit.transform.SetParent(Player.transform);
            Debug.Log("We hit: " + hit.transform.name);
            hit.transform. = RigidbodyConstraints.FreezeRotation;
        }

    }

}

```

So, how do I call (or refer to) the object that is hit by the ray cast exactly?

# Answer
> 1 votes
Rigidbody Contraints is a class to use for the rigidbody. In your case, instead of using `hit.transform. = RigidbodyConstraints.FreezeRotation;`, I would replace that with `hit.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeRotation;`
I see that you have tried to set a *Rigidbody* class on a *Transform*. Rigidbody constraints take a `RigidbodyConstraints` class, as said in the docs here. As I would guess, the source code might look similar to this:

```
public class Rigidbody {
    ...
    [SerializeField]
    public RigidbodyConstraints constraints;
    ...
}

```

The docs for the `RigidbodyConstraints` class is here.

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


# Question
Title: GLSL uniform array with size set by another uniform
Will the follwing GLSL code work?

```
#version 330

uniform int size;
uniform float[size];

void main() {
  //do something
}

```

# Answer
> 3 votes
No. The size of the array has to be a constant.

Specifically from the GLSL specification:

> 4.1.9 Arrays
>
> ...
>
> When an array size is specified in a declaration, it must be an integral constant expression (see Section 4.3.3 “Constant Expressions” ) greater than zero.

---
Tags: opengl, shaders, glsl
---


# Question
Title: Apply two animation on one object in unity
I am looking for a perfect example to apply two animation on same object and to run those animations simultaneously. In my game, a player is jumping as well as flapping. As per my research, I have got something like this. create both animation in different layer in animator control and then blending those animations. But I could't do that as I can't understand it properly. I need an example that can solve my problem. And I am not importing animations from anywhere. I am creating it in unity only. Hope for good example. Thanks in Advance.

# Answer
> 2 votes
I can't understand your question but refer this URL to Create more then animation to one gameobject https://www.youtube.com/watch?v=O\_0gZuqW6y8

https://www.youtube.com/watch?v=giSjcA109CE

https://www.youtube.com/watch?v=MtJhZ4pJXlM

# Answer
> 0 votes
If possible, you could have 1 animation running on the actual object, and run the second on a parent object, since all the values in the parent object automatically transfer to the animating object. Just make sure that the parent animation doesn't use the child object for one of the animating "properties".

---
Tags: unity, animation
---


title: How to search for a visible player?

text:
# Question
Title: How to search for a visible player?
I've an enemy static tank with a "rotable" cannon turret. I would like to rotate it in the player's direction . How to implement it ? I've thought something like

void Update { SearchForPlayer(); RotateTurret(); }

I don't know how to implement a sort of radar function. Thanks

# Answer
The method you are looking for is `Quaternion.LookRotation`.

First you need to calculate the relative vector between player and tank. You do that by simply subtracting the position of the tank from the position of the player. Then you use Quaternion.LookRotatation to create a rotation into that direction.

```
Vector3 playerDirection = player.transform.position - tank.transform.position;
Quaternion rotation = Quaternion.LookRotation(playerDirection);

```

If you want the turret to turn immediately, you would simply assign that rotation to the `transform.rotation` of the tank turret. If you would prefer to move it slowly, use `Quaternion.Lerp` to interpolate linearly between current and new position or `Quaternion.RotateTowards` to rotate with a limited angular speed.
> 2 votes

---
Tags: unity, ai
---


# Question
Title: Do I need to use a game engine to make a simple game function on other platforms?
I'm a complete beginner really enjoying learning how to code (currently in Python) and my first games will be very simple, mostly text based, but I'd like them to run on friends' phones and computers on various platforms, including windows, linux, mac and android. Is this easy to do without using a game engine, or should I use, say, Unity? If I use Unity will I still be learning to program in code, or is it silly to use a game engine for a game that is simple, like a 'choose your own adventure' game or, later, an ascii roguelike? Thanks.

# Answer
> 1 votes
This question skirts close to off-topic "what technology to use" territory, but I'll try to keep from getting bogged down in this-product-vs-that details, and look at it more in terms of general development process...

Philipp is right that using a full-featured 3D engine for a text game is using a sledgehammer to crack a nut, ie. much more power than you really need, but I think there are several reasons why as a beginner this isn't a bad idea:

* The problem you're solving isn't text (which is reasonably modest), it's cross-platform compatibility (which is reasonably thorny). Using a development environment that solves that for you lets you focus on learning the game bits of what you want to do, rather than the platform particulars.
* You're probably not jumping straight to commercial games where you need to justify to customers why your game has a particular file size. Sure, these engines contain a lot of unnecessary bloat for what you want to do, but if you're just sharing them with friends then they probably won't mind that much.
* A game engine already has a lot of the supporting code that's helpful in making games, but can be a deep rabbit hole to try to engineer from scratch, especially if you're new and don't have a feel for it yet. I've seen beginners get lost for weeks implementing their own update loops, component systems, dependency graphs, etc. with all the most fashionable features talked about on gamedev blogs... and not making anything playable. An engine lets you jump straight to the gameplay bits, and branch out to the supporting tech only as the interest strikes you.
* This gives you a lot of flexibility. If halfway into making your text game a friend says "hey, you should put on a CRT distortion & scanline shader so it looks like those old text adventures!" or "wouldn't it be cool if stuff I do in my game could affect yours" - implementing those ideas might mean re-engineering your whole rendering loop or building a networking layer from scratch in your own tech. In any of the big-name game engines, these features are already there for you to use anytime an idea strikes you.

That said, there are a couple of other approaches worth considering:

* Use the web. Browsers have already done the heavy lifting of solving (most) platform-specific issues for you and providing a roughly consistent environment across an immense range of devices. You can use text game tools like Twine and/or your javascript libraries of choice, and friends will be able to try your game without even installing it, as long as you have a bit of web space to host it.
* Look for a game library that has good cross-platform support built in. I haven't gone this route so I can't recommend any from experience, but you can take a scan over the tutorials they offer for each of the platforms you want to target. If each platform version has a lot of steps different from the others (or if the tutorials themselves are hard to find/understand) then it's probably not as painless as advertised and you should weigh how much time you want to spend focusing on these types of issues versus just writing your game itself.

---
Tags: cross-platform
---


# Question
Title: Sprites blurred in Unity (filter mode set to point)
I'm new to Unity and I'm developing Android game. When I connect my phone with Unity Remote and launch game, all textured are blurred and they look awfull.

Did some research and set Filter mode to point as everyone suggested but that didn't work at all.

My sprite settings are as follows: \- Texture type: Sprite (2D and UI) \- Packing Tag: isn't set \- Pixels per unit: 100 \- Pivot: Center \- Generate Mip Maps: unchecked \- Filter mode: point

Can anyone help me with this?

# Answer
Unity remote sends a compressed stream from the editor to your phone and then sends back the inputs from the phone to the editor. there is nothing you can do about it being bad quality. How ever this does not represent the final quality of the build. Try making a real build for android and check how it looks then.
> 3 votes

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


# Question
Title: Authoritative Server for single player but with leaderboard
I made a Fps single player, timed survival with a leaderboard ( a bit like devil daggers and others). I know would like to create a server that will prevent cheats such as avoiding collision or altering the timer.

My issue is I don't know the theory on how should my server behave. Should it run an instance of the game per player which will handle the collision and other stuff for that player ? is this viable

Any advice ?

# Answer
> 1 votes
If you want to prevent cheating then the client could be treated as a dummy terminal displaying state and accepting input. The problem with this is that you have offloaded ALL of the work to your server. As the number of people increases on the server so to will the computational load.

Correcting this problem can be solved in a number of ways such as multiple server processes sharing the work or load balancing. Another solution can be to offload more expensive computations to other processes.

Another solution is to store the player data and run cheat computations in parallel or when computational load is reduced to detect if any player actions violate game rules.

# Answer
> 0 votes
Requiring an always-on connection to a remote server and handling all mechanics on that server is not really justifiable for a single-player game.

But what you could do instead is add a replay-feature for your game. Have the game log all player input to a file. Then add a mode where the game plays itself automatically by using the log of a previous game as input. When your game uses randomness, also store the RNG seed in the replay so the game can exactly reproduce all random events.

When a player uploads a high-score, have them also upload the replay log. That way people can not just look at the names and scores of other players, but can also download the replay and see for themselves *how* the other player did it. When that player is grossly cheating, everyone can see it and report it. You could even have the server determine the score by itself by doing a replay and checking the score.

When you discover a hack for your game, you can also automatically check older replays for evidence that this hack was used and delete them retroactively.

---
Tags: unity, server
---


# Question
Title: Network interpolation wont work for local player
im currently developing a little duengon crawler. It should have lan multiplayer and it works great but i think im sending to much packets. Should i send packets over network, when a player moves in delta time? But thats not my question.... Sometimes it lags when more than 2 players are online. So i thought interpolation would be a great idea. But im not sure if i did that right, because it isnt much more fluently when the player moves :/ Heres what i did :

```
    positionFromInput.set(posX, posY);

    differenzX = positionFromInput.x-position.x;
    differenzY = positionFromInput.y-position.y;

    position.x += differenzX/10;
    position.y += differenzY/10;

```

I thought this would be right ... but it wont work what i did i missed ?

***\>\>\>UPDATE\<\<\<***

I think it only wont work for the local player because , if theres another player, his position is sended to the host, right after that the other player is drawn correctly with interpolation...

Heres how i move my local player :

```
public void update(){

            state = 0;

           if(Gdx.input.isKeyPressed(Keys.A) && moveDirections[0]){
               position.x -= Gdx.graphics.getDeltaTime() * 200f;

               state = 1;

           }
           if(Gdx.input.isKeyPressed(Keys.D) && moveDirections[1]){
               position.x += Gdx.graphics.getDeltaTime() * 200f;

               state = 2;
               //System.out.println(currentState);
           }
           if(Gdx.input.isKeyPressed(Keys.W) && moveDirections[2]){
               position.y += Gdx.graphics.getDeltaTime() * 200f;

               state = 3;
               //System.out.println(currentState);
           }
           if(Gdx.input.isKeyPressed(Keys.S) && moveDirections[3]){
               position.y -= Gdx.graphics.getDeltaTime() * 200f;

               state = 4;

           }

}

```

This is being called in an Launcher, which is called in the render method.

```
Class Launcher{

.
.
.

public void update(){

    gameScreen.player.update();

    // other stuff like updating packets
    .
    .
    .

}

.
.
.

```

}

And this is called in the render thread :

```
@Override
public void render(float delta) {

.
.
.

launcher.update();

.
.
.

```

}

Thats not all, i also need to draw my player :

```
public void draw( final float posX, final float posY,  OrthographicCamera camera){

    interpolate(posX, posY);

      camera.position.set(position.x/Box2dVars.UNIT,position.y/Box2dVars.UNIT,0);
    camera.update();

    batch.setProjectionMatrix(camera.combined);
    batch.begin();
    batch.draw(currentFrame, position.x/Box2dVars.UNIT, position.y/Box2dVars.UNIT, playerWidth/Box2dVars.UNIT, playerHeight/Box2dVars.UNIT);
    batch.end();

}

```

The interpolate() is just the interpolation....

```
private void interpolate(float posX, float posY){

    interpolatePosition.set(posX, posY);

    differenzX = interpolatePosition.x-position.x;
    differenzY = interpolatePosition.y-position.y;

    position.x += differenzX/10;
    position.y += differenzY/10;

}

```

To draw the player it is also gonna called in the render thread :

```
@Override
public void render(float delta) {

.
.
.

launcher.update();

.
.
.

player.draw(launcher.getPlayerX(),launcher.getPlayerY());

.
.
.

}

```

# Answer
It looks like you are interpolating your own player, this is not what you want to do. At this point it is not interpolation even, but extrapolation, that is we are guessing where another player went based on their previous path.

Interpolation can be though of as increasing resolution of movement in this case, but please reference better sources than myself.

Consider the following, a player moves 20 units from point A to point B. With no interpolation the player is at A then in time t the player is at B. Interpolation is adding points between A and B. Usually this is done as a function of time to smooth movement. Linear interpolation is of the form f(t) = mt + b, where f(t) is a line between points A and B such that at A + f(0) = A, and A + f(T) = B.

Now, what it appears we are trying to do is say that we have not received a player position recently but the player WAS moving in this direction, let us assume they will continue to do so. You have chosen to extrapolate or predict the players position in a linear manner with respect to their last two positions. The pseudo-code might look something like this...

```
PositionUpdateFromNetwork:
  newSlope = (B.y - lp.y) / (B.x - lp.x)
  lp = B
  lt = now

Update:
  networkedPlayer.position = lp + newSlope * (now - lt)

```

Note, this could still cause minor extrapolation because Update and PositionUpdateFromNetwork will not be computed at the exact same time, however note as now approaches lt, their value approaches 0 which means the networked players position will approach lp.

I would recommend not extrapolating for a dungeon crawler, but it is of course up to you.

A side note also, if you are experiencing latency problems with only two players you may wish to analyze your networking situation and attempt to make increase efficiency.
> 0 votes

---
Tags: java, libgdx, networking, interpolation, extrapolation
---


# Question
Title: Bullet: Apply any Transformation to RigidBody?
I'm using Bullet for CollisionDetection. I load a scene from a Collada-File using Assimp. Let's say I want to give every object in the scene a RigidBody with a box as CollisionShape. Right now I first load the vertices of the object from the file into my Model-Object and then store the transformation matrix. After that I create the CollisionShape with the following code:

```
btVector3 rigidBodyPos;
btCollisionShape* collisionShape;

glm::vec3* minMax = getMinMaxVertexCoords();
glm::vec3 minCoords = minMax[0]; //The minmum/maximum x/y/z values in the Mesh
glm::vec3 maxCoords = minMax[1];
glm::vec3 middleSize = glm::vec3((maxCoords.x - minCoords.x) / 2, (maxCoords.y - minCoords.y) / 2, (maxCoords.z - minCoords.z) / 2);
glm::vec3 middlePos = glm::vec3((maxCoords.x + minCoords.x) / 2, (maxCoords.y + minCoords.y) / 2, (maxCoords.z + minCoords.z) / 2);

collisionShape = new btBoxShape(btVector3(middleSize.x, middleSize.y, middleSize.z));
rigidBodyPos = btVector3(middlePos.x, middlePos.y, middlePos.z);

```

Here's a look at my getMinMaxVertexCoords():

```
glm::vec3* Model::getMinMaxVertexCoords() {
    float maxValue = std::numeric_limits<float>::max();
    float minValue = std::numeric_limits<float>::lowest();
    glm::vec3 lowestVec = glm::vec3(maxValue, maxValue, maxValue);
    glm::vec3 highestVec = glm::vec3(minValue, minValue, minValue);
    for (Vertex v : getVertices()){
        //Apply Transform
        glm::vec4 pos = getModelMatrix() * glm::vec4(v.position, 1);
        glm::vec3 homogenizedPos = glm::vec3(pos.x / pos.w, pos.y /     pos.w, pos.z / pos.w);
        lowestVec.x = min(pos.x, lowestVec.x);
        lowestVec.y = min(pos.y, lowestVec.y);
        lowestVec.z = min(pos.z, lowestVec.z);
        highestVec.x = max(pos.x, highestVec.x);
        highestVec.y = max(pos.y, highestVec.y);
        highestVec.z = max(pos.z, highestVec.z);
    }
    glm::vec3 res[2] = { lowestVec, highestVec };
    return res;
}

```

The problem doing it this way is, if my scene contains a rotated cube, the collisionbox is obviously not rotated, but parallel to the axes.

I tried solving this by applying the transformation matrix only after creating the RigidBody (so when creating the CollisionShape the ModelMatrix is the identity matrix) and then transforming the RigidBody afterwards:

```
btTransform transform;
transform.setFromOpenGLMatrix(glm::value_ptr(getModelMatrix()));
_rigidBody->setWorldTransform(transform);

```

The problem with this however is that the box might be rotated now, but if the transformation contains a Scaling - which is very likely - Bullet does not accept it, and my RigidBody basically disappears (no collision is detected anymore).

Does anybody know a solution to this problem?

# Answer
> 0 votes
I solved the problem myself!

I now create the CollisionShape before applying the transformation. For transforming the RigidBody correctly, I extract the sacling-value from the matrix and give it to \_rigidBody-\>getCollisionShape()-\>setLocalScaling. I then remove the scaling from the matrix and give that to the setWorldTransform.

Here's my code:

```
float scaleX = glm::length(glm::vec3(modelMat[0][0], modelMat[0][1], modelMat[0][2]));
float scaleY = glm::length(glm::vec3(modelMat[1][0], modelMat[1][1], modelMat[1][2]));
float scaleZ = glm::length(glm::vec3(modelMat[2][0], modelMat[2][1], modelMat[2][2]));
glm::mat4 matWithoutScale = glm::scale(modelMat, glm::vec3(1.0f / scaleX, 1.0f / scaleY, 1.0f / scaleZ));

_rigidBody->getCollisionShape()->setLocalScaling(btVector3(scaleX, scaleY, scaleZ));
btTransform transform;
transform.setFromOpenGLMatrix(glm::value_ptr(matWithoutScale));
_rigidBody->setWorldTransform(transform);

```

---
Tags: collision-detection, transformation, bullet-physics, rigidbody, scale
---


# Question
Title: If statement works fine until I add a tag check requirement. Why is this?
I'm trying to add a tag check to an if statement but for some reason when I add said tag check it stops working.

```
void Update ()
    {
        Vector3 fwd = transform.forward; // Equivalent to the code you had.

        Ray ray = new Ray(transform.position, transform.forward);
        RaycastHit hit;

        if (Input.GetMouseButton(0) && Physics.Raycast(ray, out hit, 10f) && isPlayerHolding == false && gameObject.CompareTag("Pickable"))
        {
                isPlayerHolding = true;
                hit.transform.SetParent(Player.transform);
                Debug.Log("We hit: " + hit.transform.name);
                hit.rigidbody.constraints = RigidbodyConstraints.FreezeRotation;
                hit.rigidbody.constraints = RigidbodyConstraints.FreezePosition;

        }
        if (Input.GetMouseButton(1) && Physics.Raycast(ray, out hit, 10f) && isPlayerHolding == true)
        {
            hit.transform.parent = null;
            isPlayerHolding = false;
            hit.rigidbody.constraints = RigidbodyConstraints.None;
        }

```

More specifically this is the bit of code that is holding things up "&& gameObject.CompareTag("Pickable")".

Things I've tried:

* Debugged variables in C# to be sure nothing is missing/null.
* Making sure the tag is setup properly within Unity.

I really can't think of what the problem is. Anyone have any ideas?

# Answer
Are you trying to use CompareTag on the gameObject that your RaycastHit is returning? If so it looks like you would need to do "hit.collider.gameObject.CompareTag".

Or if that doesn't work, you would need to move that condition into a nested if statement. So:

```
if (Input.GetMouseButton(0) && Physics.Raycast(ray, out hit, 10f) && isPlayerHolding == false && hit.collider.gameObject.CompareTag("Pickable"))
    {
            isPlayerHolding = true;
            hit.transform.SetParent(Player.transform);
            Debug.Log("We hit: " + hit.transform.name);
            hit.rigidbody.constraints = RigidbodyConstraints.FreezeRotation;
            hit.rigidbody.constraints = RigidbodyConstraints.FreezePosition;

    }

```

Or else perhaps:

```
if (Input.GetMouseButton(0) && Physics.Raycast(ray, out hit, 10f) && isPlayerHolding == false)
    {
          if( hit.collider.gameObject.CompareTag("Pickable")
           {
            isPlayerHolding = true;
            hit.transform.SetParent(Player.transform);
            Debug.Log("We hit: " + hit.transform.name);
            hit.rigidbody.constraints = RigidbodyConstraints.FreezeRotation;
            hit.rigidbody.constraints = RigidbodyConstraints.FreezePosition;
           }
    }

```

Let me know if I am misunderstanding; it is not immediately clear to me what you're trying to determine has a "Pickable" tag.
> 2 votes

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


# Question
Title: MonoGame renders texture in an almost compressed looking way
I was working on a game in MonoGame, which I have been doing for quite some time now. As I was implementing UI, I was noticing some sort of weird scanlines. Investigating further, to my surprise my whole scene was covered in it!

Notice how the texture when zoomed in has almost a JPEG squared compressed feel too it. I have no idea what is causing this.

We were using a RenderTargetTexture instead of the backbuffer, so figured I try it without, but the same happens. I checked if we were doing any weird Matrix transformations, we did not, in fact, I disabled them just to test it out. After that I thought "half pixel offset" (even though it should not really apply anymore post DX9), but also that did not solve a thing. Last but not least I thought maybe a MipMapping issue, but that would be weird since the exact same thing happens with the normal backbuffer.

**My Question:** Does anyone here recognize this "effect", and have any clue what might be causing it?

I'm basically just rendering a 1920x1080 image to a 1920x1080 backbuffer, but I can assure its not the image. When I for example draw a cursor and make it follow the mouse, the points where pixels "go missing", even the cursor texture deforms.

Might not be as clear in this picture, but notice how both the cursor and the orange curve basically "skip" a row of pixels, when I move the cursor to another location, it turns back to normal.

# Answer
> 2 votes
It looks like the issue is that you are doing non uniform scaling (different scale on x and y axis) and using nearest neighbour texture sampling.

If you switch to using uniform scaling and/or bilinear texture sampling (or better, like bicubic) the problem should go away.

---
Tags: textures, monogame, rendertargets
---


title: Unity5 build won't run on android 2.3.3

text:
# Question
Title: Unity5 build won't run on android 2.3.3
I made a game using one of the Unity tutorials on their site and now would like to run on my phone (LG P500). But when I try to run it on the device, it says:

> Failure to initialize: Your hardware does not support this application, sorry!

What can I do in this case?

# Answer
> 1 votes
Unity is probably set to build for Android 4.0.3 (or something higher than 2.3.3).

You can change this in the Player Settings.

---
Tags: android, unity
---


# Question
Title: Room generation with external walls and doors
I am looking to implement a means to generate rooms with outer walls with windows and doors from prefab game objects in Unity.

The idea is that a group of tiles is defined as a room which I then iterate through to find the outer tiles and then use their external edges to generate the walls of the entire room. Gathering the outer tiles is easy enough and working out the external edges is already implemented.

What I need to understand is the best approach for using prefab game objects as the set pieces for walls and floors.

Currently for a single wall piece, I have created a quad and made that into a prefab which I then clone, position and rotate into place along the outer edges. The below screenshot shows a room with walls made using the prefab wall GameObject. In this screenshot, the room consists of 12 wall GameObjects. I want to avoid having lots of GameObjects for single wall segments and instead perhaps merge them all into a single mesh on a single GameObject.

What I would like to achieve is to be able to create a consistent set of pieces for each outer wall, with windows and doors (most likely cloned from other prefabs) to build a realistic looking room. For example, any single length of a wall would be made up from

`Wall -> Wall -> Window -> Wall -> Wall`

Perhaps there is a much easier way to achieve this that I have overlooked but searching for room generation always leads back to examples for dungeon crawlers and roguelikes. I am not creating a dungeon crawler, nor am I generating the environment proceedurally, instead the player will be able to create rooms in a similar fashion to Evil Genius and The Sims.

In the current approach, creating a room which is 5x5 would mean that there are a total of 20 wall GameObjects and 25 floor GameObjects. I am not keen on having this many objects in the scene for a single room. I would prefer to be able to create a mesh for the entire room, adding in the vertices and triangles from the prefab mesh to cut down on the number of GameObjects in the scene.

Does anyone have any experience with building rooms in this fashion, or are there any clear examples of how to achieve this? I am not sure how to translate and rotate a prefab and then merge the translated meshes into a single mesh. Perhaps I am barking up the wrong tree and there is a better approach but for now, this is the only way I can see which is possible to achieve what I want.

# Answer
You can merge the meshes of multiple game objects into one using `Mesh.CombineMeshes`.

Note that this does not care about which materials you assigned to the input meshes. The GameObject into which you merge the meshes will use whatever materials you assign to its own MeshRenderer. That means when you are merging meshes with different materials, you should use `false` for the second argument, so you end up with a sub-mesh for each original mesh and then add all the materials to the MeshRenderer of the resulting GameObject.

There is a performance penalty for using the same material multiple times, so you might want to first merge all meshes with the same material with `mergeSubMeshes = true` and then the resulting meshes with `mergeSubMeshes = false`.
> 2 votes

# Answer
Disclaimer - I'm not a unity dev & as such I'm not familiar with all its options, but it does look like it has support for merging meshes together to increase performance.

In general how to tackle this problem will come down to tensions between player freedom, code performance, & development resources:

* The more you constrain player choice, the easier it is to optimize / special case stuff. I.E. limiting the player to chunky 'room at a time' type prefabs.
* If you want to give the player a ton of freedom, you may have to allow them to do stupid things - I.E. building a 3x3 room out of wall tiles instead of just using the 3x3 prefab.
* It is possible to have both high player choice & high performance, but it will likely come at the expense of development time / $ / code sanity.
> 1 votes

---
Tags: unity
---


# Question
Title: Is glxinfo saying that the 980 GTX doesn't support a 32 bit depth buffer?
I've been using the glxinfo command (glxinfo -v) to explore the supported framebuffer configurations. There are two values relating to depth, "depth" and "depthsize." According the source, it appears that the "depth" value relates to the X config and the "depthsize" value relates to the OpenGL config.

Assuming that is correct, would the lack of a "depthsize=32" entry suggest that 32 bit depth buffers aren't supported? Or is my understanding of the glxinfo output flawed?

# Answer
> 6 votes
It's important to note that `glxinfo -v` only reports the supported values for the default OpenGL framebuffer, the one that represents the visible screen itself. It's common for other configurations (ones not reported by `glxinfo`) to be supported in offscreen framebuffer objects (FBOs).

As you've noticed, most video cards do not support a 32-bit depth buffer for the default framebuffer, but any recent card can be expected to support them as attachments to an FBO.

So if you want a better depth buffer, you want to create a separate FBO, and attach a 32-bit depth buffer to it, and then render into it, instead of directly to the screen. Once you've finished rendering, blit the final rendered image back to the screen.

Note that NVidia cards historically have not supported 32-bit fixed-point (ie: integer) z-buffers even in FBOs, but do support 32-bit floating point z-buffers there (and have been like this for about a decade). So if you want 32-bit z-buffers, specify their depth attachment as using `GL_DEPTH_COMPONENT32F`, *not* as `GL_DEPTH_COMPONENT32`.

**EDIT:**

> Testing on an NVidia GeForce GTX 980, using the official NVidia drivers version 352.63, when creating an FBO the driver will not give me a 32-bit fixed point depth buffer. If I ask for one, it instead gives me a 24-bit fixed point depth buffer, exactly as other NVidia cards have done for many years.
>
> If I ask for a 32-bit floating point depth buffer, then I do receive one, which also matches the normal behaviour of older NVidia cards.

---
Tags: opengl, graphics, depth-buffer, linux, nvidia
---


# Question
Title: How do I trigger just once and not multiple times if I the Player enters the Trigger?
I wanna trigger just one time and not multiple times. I have a Health System and I want that the Player takes damage from an GameObject if he enters the Trigger but it directly triggers like 65 times in a sec. how can I trigger just once ? I dont have a Script attached to the GameObject what should give the Player Damage, it just have a Box Collider 2D. The Code for the Trigger enter has the HealtScript that is attached to the Player.

Here is my HealthScript

```
public Image Bar;
public float maxHealth = 100f;
public float currentHealth = 0f;

// Use this for initialization
void Start ()
{
    currentHealth = maxHealth;
    InvokeRepeating ("decreaseHealth", 0f, 2f);
}

void decreaseHealth()
{
//  currentHealth -= 5f;
    float calchealth = currentHealth / maxHealth;
    SetHealth (calchealth);
}

void SetHealth (float myhealth)
{
    Bar.fillAmount = myhealth;
}

void OnTriggerEnter2D (Collider2D other)
{
    if (other.gameObject.tag == ("Damage"))
    {
        currentHealth = -5f;
    }
}

```

}

# Answer
> 4 votes
According to the Unity documentation for OnTriggerEnter2D the trigger is "\[s\]ent when another object enters a trigger collider attached to this object (2D physics only)". The function should only be called once per entrance.

You could gather further data by logging the number of calls to OnTriggerEnter2D and OnTriggerExit2D. Perhaps some funny business is occurring causing one object to enter then exit, then re-enter.

# Answer
> -2 votes
Create a collection and store a reference of the GameObject once it enters and remove the reference once it exits.

For example, here I am utilizing HashSet.

```
using System.Collections.Generic;

private HashSet<GameObject> takenDamageFrom = new HashSet<GameObject>();

void OnTriggerEnter2D(Collider2D other)
{
    // If damager and not yet damaged (not contained in our references).
    if (other.gameObject.tag == "Damage" && !takenDamageFrom.Contains(other.gameObject))
    {
        currentHealth -= 5f;

        // Mark as damaged.
        takenDamageFrom.Add(other.gameObject);
    }
}

void OnTriggerExit2D(Collider2D other)
{
    // If contained in our references, remove.
    if (takenDamageFrom.Contains(other.gameObject))
    {
        takenDamageFrom.Remove(other.gameObject);
    }
}

```

But the idea is simple, store a reference.

If, for instance, you don't need it to apply damage on re-entry, simply do not remove the reference once the collider exits.

Keep in mind, this idea assumes that there might be multiple elements that can cause/take damage, hence the collection.
If you need it for one object only - take Uri Popov's answer, it's simpler.

# Answer
> -2 votes
Use a bool variable to make sure you only enter the if once, then reset it after you have left the trigger. Or dont reset it if it has to happen exactly once.

```
 void OnTriggerEnter2D (Collider2D other)
        {
            if (other.gameObject.tag == ("Damage")&&!isDamaged)
            {
                currentHealth = -5f;
                isDamaged = true;
            }
        }
    void OnTriggerExit2D (Collider2D other)
    {
      isDamaged = false;
    }

```

# Answer
> -2 votes
You can use a coroutines for this task, you should call this coroutine in order to damage you player, so you can set a time of invencibility with the

> waitForSeconds(3f);

function

```
bool finishedCoroutine = true;

void OnTriggerEnter2D (Collider2D other)
{
if (other.gameObject.tag == ("Damage"))
{
   {
      if(finishedCoroutine){
          finishedCoroutine = false;
          StartCoroutine("damageMyPlayer");
        }
}
}

IEnumerator damageMyPlayer ()
{

    this.currentHealth -=5f;
    yield return new WaitForSeconds(3f);
    finishedCoroutine = true;
    print("MyCoroutine is now finished.");

}

```

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


# Question
Title: How to handle angles in an isometric game?
I am working on my first isometric game, and I am not sure how to go about angles and rotation. Basically, I want the player's forward movement and rotation to coincide with the isometric angles.

I drew an image to represent what I am talking about.

The player's movement is based on the direction they are pointing. Being an isometric game, there are many sprites in the player rotation animation, and I want the sprites to match up with a certain rotation. Since the rotation of an isometric sprite is different to a straight 2D sprite, I'm not sure how to implement this. Any help would be appreciated.

# Answer
Keep your world coordinates, movement, and rotation on a standard X/Y coordinate grid (like your leftmost image) and then convert those coordinates to isometric coordinates via linear transformation before rendering.

This question has some good answers on how you might make that conversion.

As far as how you would rotate your sprites, assuming they're 2D bitmaps you would just have the "up" frames be rendered/drawn such that they're facing in the isometrically "up" direction. In other words, the sprite faces that way because it's drawn that way. This means all of your art is going to be drawn angled, not facing straight ahead or what-have-you. (Example: "Up" is the sprite facing towards the northwest corner of the screen.)
> 2 votes

# Answer
I had this same issue, I was using sprites with 8 different directions of movement. Here's how I detected which direction they were moving in:

The way the sprite is facing depends on the direction they were last moving in. You can find the direction of sprite movement by performing some calculations on their original coordinates, and the coordinates of their destination.

First, imagine there are four quadrants around your sprite. NorthWest, SouthWest, SouthEast and NorthEast. You can detect which one the sprite is moving towards by comparing the X and Y coordinates of their current position to those of their destination. For example, if X is less, and Y is more than their current point, we know that they are moving in a SouthEastern direction.

Next, you need to use some trigonometry. To find the angle that your sprite is moving, draw an imaginary right-angled triangle between the sprite and the destination. The length and width of this triangle are found by comparing the coordinates. For example, currentXPosition - destinationXPosition. Sometimes the result will be a negative value. This can't be used, so you have to convert it to a positive, or find its absolute value.

In this triangle, we know the length of the two sides (they are called the opposite and adjacent), so to find the angle you use ArcTan in the calculation. This will return an angle in radians, all you have to do then is convert it into degrees.

So now you have a movement angle. It will never be more than 45 degrees. Now you need to place this angle in a 360 degree space to find which direction your sprite is facing.

Because you know which quadrant the destination coordinates are in, you know one of four possible directions. This tells you how much angle you should add. For example, if I know the sprite is facing toward the North West quadrant, I have to add 270 degrees to my current angle. If they are moving toward the North East, I add zero. If they are moving toward the South East, I add 90 degrees to my angle. And so on.

The rest is easy, just using conditions to find out which of the eight different animations should be played based on if they are moving N, NW, W, SW, S, SE, E or NE.

Eg. They're moving toward the South East quadrant, so you add 90 to the angle. -If they are moving South East but the angle is less than 120, they are moving East. -If the angle is greater than 120 but less than 150, they are moving South East. -If they are doing neither of these things, they must be moving South.

I hope this is easy to understand and that it helps.

You can also find the distance that they move by calculating the hypotenuse side of the triangle.
> 0 votes

---
Tags: sprites, rotation, isometric, logic
---


# Question
Title: Is it safe to base a combo system in frames instead of time?
I'm building a prototype for a fighting game (not vs, something like Final Fight). I'm trying to define the data for the player combo tree and had a look around looking for inspiration and have seen games like Street fighter that base its combo timming on frames instead of time. The game is locked at a fixed frame rate too.

My question is, my game is targeting Windows, so, there are a lot of processes running in a computer. If I base my combo timmings on frames, can't a cpu spike produced by another process break my game?

A solution to fix this is to check every Update() how many real logic frames have passed (based that we want our game to run at 60 logic frames) and run the combo system all these number of frames at once. But not sure if this would work.

Beside all this, another problem is that Unity does not provide a separated thread for rendering and logic that could be configurable and accesible by the developer (It does not even have a frame rate independent input system *shame*).

Well, what do you think?

Cheers.

# Answer
Locking at 60 fps is certainly viable. From what I've seen, just as you've said, it appears fighting games typically describe timings in number of frames, even as most fighting games have transitioned to 3D (where it's rare to rely on discrete frames of animation). The drawback of doing this logic in *Update()* in Unity is that the game will slow down if the framerate dips below 60 fps.

If you want to, as you've put it, separate "logic" frame rate from "rendering" framerate, you can do your logic in *FixedUpdate()* instead of *Update()*. The physics system (which governs the rate of FixedUpdates) can be configured to whatever framerate you want to use, and won't be slowed down by rendering, although with enough of a load on the CPU, the FixedUpdate rate can fall behind its target, too.
> 5 votes

# Answer
Instead of checking how many frames have passed, try checking how much time has passed instead. In Unity, you can check how long the previous frame took to complete with Time.deltaTime. Delta time for 60 frames per second is 0.016666 (6 continuing). So, add delta time to a float variable every frame, then check if it is greater than X (where X would be about 0.3333 for 20 frames at 60 FPS). That way you won't have to worry about the framerate. It is almost never a good idea to tie your game logic to the framerate.

TL;DR: In short, don't add 1 each frame and check if it's greater than X, instead, add delta time (each frame) and check if it's greater than `1f / [target framerate] * X`. (X is number of frames)
> 0 votes

---
Tags: unity, input, fixed-timestep, timing, fighting-game
---