# Question
Title: How to randomly spawn obstacles for infinite runner?
I am trying to create randomly generated path properly? Think of flappy bird (its not really) but my code/algorithm is all wrong. If I make BarMax, BarMin too large, then player can cheat cos in centre there will always be space. Make it too small and pipes are spawned randomly and sometimes very close to each other (unlike flappy). So my player sometimes could run into a situation where its impossible to move past two pipes. My adjacent pipes are really close together as well unlike flappy birds big gap between pipes.

So this is what i dont want to happen. I have also thought about spawning sets of pre-configured pipes but then i thought they might run into this impossible situation at some point too. I had my level set-up like this So when a bar touches the looper, it spawns again - code is above.

```
int numBGPanels = 35;

float BarsMax = 1.5f; float BarsMin = -1.5f;

float widthOfBGObject = 1; float offset = 0.75f; Vector3 pos;

void Start() {
    StartBarsPosition(); }

void OnTriggerEnter2D(Collider2D collider) {

    if(collider.tag == "Bars") {       // this is not getting called cos theres no collider attached atm
        pos = collider.transform.position;
        pos.x += widthOfBGObject * numBGPanels * offset;

        pos.y = Random.Range(BarsMin, BarsMax);
        collider.transform.position = pos;

    }

}

void StartBarsPosition() {
    GameObject[] bars = GameObject.FindGameObjectsWithTag("Bars");

    foreach(GameObject bar in bars) {
        Vector3 initialpos = bar.transform.position;
        initialpos.y = Random.Range(BarsMin, BarsMax);
        bar.transform.position = initialpos;
    }

```

}

# Answer
How it works in flappy is, all pipes are same size. Their "y" position is altered to create space at random. In this image, red area is the visible screen, green bars are the pipes.

As you can see, all pipes are same size. But by changing their "y" co ordinate, random gaps are generated.

So, in your game, you need minTopY,maxTopY that decides "y" co ordinate of the top pipe, minBottomY,maxBottomY which decides the "y" co ordinate of bottom pipe.

For each pair, "x" co ordinate is same, but "Y" co ordinate is different.

Hope this gives an idea of what you're looking at.

Next, to place each pair of pipes, you call the spawner at random interval of time.
> 1 votes

# Answer
generate the "holes" using a 1d perlin noise function
> 1 votes

---
Tags: game-mechanics, random, spawning
---


# Question
Title: 16-byte aligned matrix in DirectX9 and D3DX with Havok Physics 2012
I want to ask a question about `D3DXMATRIX` and `D3DXMATRIXA16`, and how to use them with Havok Physics.
I'm using Visual Studio 2012 on Windows 8.
I successfully created an instance of `hkpWorld`, added an `hkpRigidbody` instance with `hkpSphereShape`.
The class representing the sphere object has:

```
hkpRigidBody m_RigidBody;  // Rigidbody
D3DXMATRIX m_Transform;    // Rendering matrix

```

Judging from the values of `m_RigidBody->getPosition()`, the simulation is running without problem.
So now obviously I want to render the sphere according to its position and orientation calculated by havok.
This is how I tried to extract the matrix for rendering:

```
const hkTransform& t = m_RigidBody->getTransform();
t.get4x4ColumnMajor(&m_Transform._11);

```

Then I happily ran the program, which would break in `get4x4ColumnMajor` and give me this message through my error report function:

> C:\NightlyJobs\09-07-Sun-01\Source\Common/Base/Math/Vector/Sse/hkSseVector4.inl( 1831): \[0x64211C2F\] Assert: pointer must be aligned for SIMD.

I took this to mean that the matrix had to be 16-byte aligned, so I changed

```
D3DXMATRIX m_Transform;

```

to

```
D3DXMATRIXA16 m_Transform;

```

This time, the problem is still there **but isn't 100% reproducible**.
Sometimes it runs without problem, sometimes `get4x4ColumnMajor` fails with above message.
Changing the matrix declaration to

```
_declspec(align(16)) D3DXMATRIX m_Transform;

```

did not help either.
So, to summarize my question:

* How would I go about extracting the matrix suitable for rendering with DirectX9?
* Why do `D3DXMATRIXA16` and `_declspec(align(16))` seem to be inconsistent about being 16-byte aligned or not, every time I run the program ?

# Answer
> 2 votes
The main thing to remember is that `_declspec(align(16))` only affects the struct/class layout, is respected for local or global variables, but *has no affect on heap allocated memory*.

In other words, it doesn't matter if the member variable of a class is marked with alignment if the class is allocated with `new`. Heap allocations by default with x86 (32-bit) are only 8-byte aligned, so you have a 50/50 shot of getting the required alignment that way. By default x64 native (64-bit) alignment is 16-byte.

Otherwise you need to make use of `_aligned_malloc` to get other alignment behavior from heap allocation. See MSDN for some more notes on this.

---
Tags: matrix, directx9, havok, simd
---


# Question
Title: How can a one-man team create game audio?
I am basically a 14 years game programmer. I am using Unreal Engine 4.

I can't make a game without 3D models. So , I started to learn how to draw (for reference images) and how to make some 3D models. I am using Corel Painter and Blender.

I can't make a game without audio. This is a much larger problem than the models' one. There aren't high quality (or even low quality) tutorials that can teach you "How to make music for your game" or "How to make sound effects for your game"

I made a topic on Unity forums and they suggested to me to hire someone who can create the audio for me but I really want to make everything myself as the game I'm working on will not be published, it's just a 'showcase' for my programming 'skills'.

So, I need a program and maybe a MIDI controller that is user friendly like Ableton Push, for example, that I can use to create sound effects for my game like explosions, fire, engines' sound, ... etc. The Music isn't a much of a problem as I can use something like MAGIX Music Maker as it has user friendly interface and can create some really good music.

Thanks in Advance

# Answer
> 2 votes
Creating sound effects is a fairly simple task as long as you have a fairly decent microphone. I'd recommend watching the "Art of Noise" part of The Making of Fallout 3 as well as this video by the guy making effects for Project Zomboid, showing some more extreme ways of creating **very gruesome** effects.

If you listen closely, most effects are made from simple everyday objects, so the barrier of entry isn't too high.

# Answer
> -1 votes
I know a game team who used free audio music; I'm not sure what was the name of the site, but the idea was that you had to say where the music came from in the credits.

As for the sounds, you can find free audio effects online. Or you can learn the basis of a software like audacity and create sounds using your imagination (and use audacity to achieve what you need). I remember some sounds in a game I worked on are originating from hmm, my mouth, or a tap of a spoon on my work book.

Music composition is really not an activity you should invest time in, but learning how to modify and tweak sounds in a free sound manipulation program like audacity is a skill I would say is a good "rope to your bow".

P.S. If you really need precise music for your game, I'd suggest you try and partner with a free/cheap music composer and get something exactly suited for your needs.

---
Tags: sound, audio, sound-effects
---


title: 2D LibGDX Collision Avoidance

text:
# Question
Title: 2D LibGDX Collision Avoidance
I would like to know what is the best way to implement collision avoidance and eventually pathfinding in a LibGDX 2D top view game. Think of "Binding of Isaac".

I use a sort of tilemap to place the obstacles (squares), taken from an ASCII map, but I'd prefer to keep the movements free from it. (Enemies shouldn't move from tile to tile but freely)

Since the target is mobile I can't use heavy algorithms.

I'm not particularly concearned about enemies getting stuck on weird shapes (such as 'U') since it kind of makes sense (they are white globules, not particularly smart :P) but I still want them to be a challenge.

I've taken into consideration Steering Behaviors and the LibGDX-AI framework but I can't find good documentation, I can aswell code it by myself in case.

**ANOTHER QUESTION** Just to know, which kind of algorithm is used in the Binding of Isaac? It perfectly suits my needs

# Answer
> 1 votes
For path finding, A\* (pronounced a star) ought to fit your situation real nice (for people who don't know what binding of Isaac is, it's basically the original legend of Zelda).

For avoidance, I can't think of any named algorithms, but I think it will basically be pretty simple to code up some heuristics (rules) to where if an enemy is in the path of a projectile that can hurt it, it just moves out of the way. Similar for if the player starts getting into melee range or whatever else.

It will probably take some iteration on the heuristics you come up with for each enemy type, to get the exact behaviors you want, as well as making sure they are not too easy or too difficult to fight (:

---
Tags: libgdx, ai, collision-avoidance
---


# Question
Title: GLSL 330 Core Bug? - Uniform variable will not set to value if it is named a certain way
In the code below I have a uniform variable named "vw\_matrix" used in the calculation for gl\_Position. When I run my program, a rectangle gets printed to the screen.

```
#version 330 core

layout (location = 0) in vec4 position;

uniform mat4 pr_matrix;
uniform mat4 vw_matrix = mat4(1.0);  // Rectangle!
uniform mat4 m1_matrix = mat4(1.0);  // No rectangle!
uniform mat4 mmmmm = mat4(1.0);      // No rectangle!
uniform mat4 test = mat4(1.0);       // Rectangle!
uniform mat4 aaa = mat4(1.0);        // No rectangle!

void main()
{
    gl_Position = pr_matrix * position * vw_matrix;
}

```

If instead I put "m1\_matrix" in the gl\_Position line instead of "vw\_matrix". The rectangle no longer appears. I'm not getting any GLSL compile errors.

```
void main()
{
    gl_Position = pr_matrix * position * m1_matrix;
}

```

There are no calls to glUniformMatrix4fv changing the value "m1\_matrix". It has the same value as "vw\_matrix" so for some reason it must not be initializing.

I did some experimenting, it won't set a uniform variable if it starts with a certain letter and "m" is one of those letters. Anything that starts with a "v" or "t" works fine. I can't make this up!

Is there anything I should double check/post or is this just a rather bizarre bug? The full code is available at https://github.com/nduplessis11/Freeze

I'm running on Linux Mint 17.1 and my GL\_VERSION is "OpenGL 4.4 13374 Compatibility Profile Context 15.20.2013". My video driver is AMD's fglrx version 15.200

UPDATE: Ok, I found a bug in my main program in a function that retrieves the location of a uniform.

```
GLint Shader::getUniformLocation(const GLchar* name)
{
  // This is a very slow operation, optimize later.
  glGetUniformLocation(m_ShaderID, name);
  return 0;
}

```

This was causing 0 to be passed as the location for glSetUniform\* calls. I'm not sure how, but fixing this function stopped the unpredictable behavior when initializing uniform variables from within the shader program. I'm still going to take Trevor's advice and set them from within my main program.

# Answer
This is a known issue in some drivers. Including (at time of writing) the most recent ATI drivers across both Windows and Linux.

From the OpenGL wiki page on GLSL uniforms:

> **Platform Issue (Unknown)**: Some drivers do not implement uniform initializers correctly.

Best practice is therefore to set all of your shaders' uniforms explicitly from inside your program, or else not to declare them as uniforms.

For example, your example code works just fine using any of the current mat4 variables, if you just remove the 'uniform' keyword from the ones which aren't actually being set inside the main program.
> 3 votes

---
Tags: opengl, glsl
---


title: Efficient Collisions Iteration?

text:
# Question
Title: Efficient Collisions Iteration?
My project has upwards of 3000 2D objects but not all of them collide with each other. Between each object that can collide, a CollisionPair is created and stored inside a flattened array.

Currently, a MaxObjects is defined for accessing the flattened array. Unfortunately, when iterating over this array for collision checks, I get a lot of overhead from the for loop and null checks.

Is there a more efficient way, both in memory and performance, to store and access CollisionPairs?

Note: Many of these objects are axis-aligned boxes - how does Minecraft handle these collisions?

# Answer
> 1 votes
The solution was a lot simpler than the other things I was thinking of. I store all CollisionPairs in a separate collection and iterate over that collection.

This allows me to do what I was doing before with partitioning, setting a boolean for the CollisionPair to true to represent that the involved bodies are in the same partition.

# Answer
> 0 votes
A common way to solve this is to have the concept of "islands" which are just groups of objects that might collide with each other. Objects from different islands are guaranteed to be far enough away that they can never collide. Objects can change islands as they move around and islands can join and separate.

Even though this is a common technique, its just one of many ways to solve the problem. Basically you need to find a way to break your large group of objects into smaller groups of objects so you have fewer objects to test each object against.

A quad tree is another common technique which recursively breaks the world up into 4 rectangles.

The nice thing about a quad tree versus islands is that you don't need objects to be in fae apart groups to get a benefit.

Quad trees are great when objects are clustered together with no clear way to separate them.

There are plenty of other techniques though (:

---
Tags: collision-detection, performance, data-structure
---


# Question
Title: How do game engines mitigate CPU cost for many trigger zones & entities?
It's a rather simple question, but a somewhat fundamental in computing in general. Let's say we have a player controlled character in an open world. The world is large. In this game-world we have a vast amount of trigger zones that basically responsible for changing music, changing lighting, changing animation and so on. And the game clock runs at 60 fps.

In this situation we have so many subroutines which sensitive to "If a player has entered the area" that we can count then by thousands. Here's where I'm not sure. Since we have so many trigger subroutines it seems we can't just simply put them to check, if a player has entered the area, every 60th of a second even though this simple "listening" is not gonna take up a lot of resources; but scaling the world bigger and bigger will create a performance hit for sure, with this approach. So, there must be some other mechanism to manage all of those trigger zones. I inclined to think that the mechanism goes like this:

* a player's character subroutine constantly (at 60 fps) updates its position. With each update frame the playable character subroutine goes something like this: Hey, I'm at the position x(5.0),y(3.0),z(10.5) so what branch of code should I execute being at this position? And the respond comes from an indexed map where we have every possible coordinates and corresponding code to execute. (of course we can have a lossless compression going on for saving up the memory)

Am I correct? ...or does every subroutine listen for an input every update frame? (hope it's not :) )

**Edit addition:** I'm not asking if games divide their worlds into chunks, areas or grid cells for saving up memory, but asking about their approach on saving up CPU/GPU cycles and how unactivated triggers are treated.

Thank you, who have already given their answers.

# Answer
> 2 votes
Typical approaches to reduce processing are:

**Spatial subdivision / coherence** \- Don't process everything in the whole world, instead only do so in pertinent regions - usually only those in close proximity to the player(s). \- Group units close together as a single unit to reduce overall count (Rome: Total War). Common in real-time rendering fields.

**Selective processing** \- Don't process every entity type for a particular effect. For example, maybe only magical objects need to be processed for particle emissions, only baddies need to be processed for collision detection against your forcefield, only non-flying units must be tested against pit trap triggers, etc. You will find that there are often discrete processing regimes for certain closely-releated types, this is why in many engines a type `Particle` is discrete from the more general type `Entity`... the only thing they share is transform information, outside of that `Particle` is an entirely different beast without collision physics, pathfinding, depth write during render, mesh animation etc.

**Temporal discretization** \- Don't process every 60th of a second. Rather, do say 1 update in 4 frames, i.e. 15 updates a second (Age of Empires). This enables 4x more logic *per update* than you would have at 60fps. You can work this idea further by having triggers act say only once in those 15 updates, i.e. once a second. There is nothing that says you need to do *all* processing, *every* frame.

**Outside of these things**, it comes down to improving engineering through adaptation of game design / loosening design constraints. Oftentimes, you just don't need as much processing as you originally thought, and in those areas where you overrun capacity, you adapt your design to reduce complexity.

P.S. Conditionals tend to be costly because of branch mispredictions. Forward-running, linear loops don't in themselves suffer from the degree of branch mispredictions that arbitrary conditionals may suffer; and arbitrary conditionals may take (compiler-specific) hints to indicate which branch they are likely to take in most cases, though this only applies in certain, rarer logical cases. Most of the time you want to avoid deeply nested conditionals, and too many conditionals per se. This is where the above approaches come into play. Having said that, these days you also have multiple cores to work with.

# Answer
> 4 votes
One way to go is to split the whole world into chunks, and load just the chunk the player character is currently in (or any number of chunks that are closest). This way you only have to listen for events in this chunk. This does not mean you have to split everything into "levels". Minecraft is a fairly good example of splitting a giant world into chunks that are only loaded when necessary. All of the other data can be stored in files so you don't have to keep everything in memory.

# Answer
> 0 votes
As mentioned in one of the comments, you want to partition the world into sections by using oct/quad trees. Then as the player moves, using the tree you can quickly get all the nearest elements in your world. Only those closest to the player are the ones you have to react to.

---
Tags: optimization
---


# Question
Title: Detect collision that happen between frames, between slices of moving, rotating circles?
To detect a collision between two circles, we check if the distance between their centers is smaller than the sum of their radii.

To detect a collision between a slice (in this case half) of a circle and a circle:

1. Check if the circles are in collision.
2. Find the two points of the imaginary segment that splits the circle (in the middle).
3. Check if either of these two points is contained inside the other circle (if so, it is colliding with both slices, red & blue).
4. If not, compute the angle between the two circles and use that to decide if the circles are touching from one side or the other.

Is there any reasonable way to compute this on moving objects? i.e, so collisions will not be missed because of the discrete nature of frames?

# Answer
> 1 votes
Swept object collision detection can be challenging but there are some common solutions.

One way is when testing two objects, using the concept of relativity you can set up the math such that one object gains the motion of the other, so that its moving object vs a static object test.

Another way is if you use something like MPR or GJK to do collision detection, you can literally do swept test shapes as if they were just regular objects. (Finding collision time isn't very straightforward though).

Lastly, the simple solution that I've seen used a lot in these situations... Just do multiple tests along the objects paths. Basically just take the large movement and break it into a series of smaller movements, such that you can be sure there won't be missed collisions, and collision test at each step.

Doing something like testing if the line segments of their motion intersects as a "pre filter" is obviously a good idea too (:

# Answer
> 0 votes
I'll try a semplified answer. Assuming you store previous frame time and position (and rotation)

calculate point X interpolte dT = frameTime * FrameDistance/(X-PositionC1atFrameA)

Check position of other circle C2 at dT (check if it intersect C1)

Calculate Rot C1 and Rot C2 at dt

finaly apply your logic (points 2,3,4)

EDIT : Found a detailed analisys on problem here: A Sphere-Sphere Sweep Test

---
Tags: collision-detection, geometry
---


title: UDK: Animating characters with weapons

text:
# Question
Title: UDK: Animating characters with weapons
I imported a custom character and a pistol model to UDK and both work, but the pistol doesn't appear with the animation of the pistol when I shoot or reload... Also, the character doesn't change its animation from its normal posture to the posture animation holding a pistol.

How can I set the character to change the character's animations to animate correctly when holding a weapon? Can I do this in Unreal Kismet or do I need code?

I don't know UnrealScript well; only C++. :/

**PS**: On AnimSet, the character's posture is correct with a pistol, walking, firing, reloading, everything.

# Answer
Couple things you can try, first try adding sockets to your character for helping weapon holding/animation.

Then find and existing character class and copy it, then rename the folders/files with your new characters parts.

Find out more about the process here - UDK Custom Characters
> 1 votes

---
Tags: 3d, animation, udk, character, skeletal-animation
---


# Question
Title: How can I fetch a list of games and DLC for a user via Steam's API?
We're trying to figure out how to fetch a list of all games and DLC owned by a Steam user using that user's Steam ID.

There is a method for fetching a list of games for an account by using the Steam Web API but this does not include any DLC. Another option is to use the public community XML data provided by Steam.

The problem with this is first of all that this information can be made public/non-public so we can't be sure to get the whole picture. Also this way of fetching data is flagged as deprecated by Steam.

Does anyone know of a way to achieve this using supported Steam APIs?

# Answer
I'd like to mention that there are also other ways to get the accurate DLC data instead of using the API.

For example, Steamdb extension gets owned games and DLC info from http://store.steampowered.com/dynamicstore/userdata/

It shows lists of item ids related to the user who is logged in at the moment. Those lists are:

* rgWishlist
* rgOwnedPackages
* rgOwnedApps
* rgPackagesInCart
* rgAppsInCart
* rgRecommendedTags
* rgIgnoredApps
* rgIgnoredPackages

I find this way of getting info about everything the user owns to be much more precise than others.

**The main downside is that dynamicstore data is not public**, and can be accessed only by the person it belongs to (and clientside scripts of course). Which makes it not that easily accessible as Web API, but still useful in some cases (like with steamdb extension, where the DLCs info is really important).
> 6 votes

---
Tags: steam
---


# Question
Title: LibGDX - Box2D: Realistic Light and Layers
I'm having some problems with my current game. Short description: It's a 2D game where you have to avoid the lights or you lose HP.

My problem is the following one:

Here is the rendering process:

1. The background is drawn
2. The Moon image is drawn
3. The point light is applied
4. The collision layer and the images attached to it are drawn
5. Player is drawn
6. The foreground image (on the top left and bottom middle)

My problem is that the rendering does not look realistic. I need some help on how I could make the light coming from "behind" the collisions and applying it everywhere.

Thanks for your help.

# Answer
> 1 votes
ideally, you configure group/mask for your lights and objects. Using this, you can tell your point light to ignore those branches. See a great write-up here.

alternatively, as a brute force approach, you could render lights before you draw your branch (though you should REALLY use the mask approach above):

```
// draw all objects that should create shadows
batch.begin();
...
batch.end();

rayHandler.setCombinedMatrix(camera.combined);
rayHandler.updateAndRender();

// draw your branches that should not cast shadows
batch.begin();
...
batch.end();

```

---
Tags: libgdx, rendering, box2d, lighting
---


# Question
Title: How do you set multiple collision rules with Swift and SpriteKit?
So basically I've got 2 types of balls and 2 types of enemies. Green can delete red only, red can hit delete only. Here's what I have for the first collision test:

```
 func didBeginContact(contact: SKPhysicsContact) {

        // 1. Create local variables for two physics bodies
        var firstBody: SKPhysicsBody
        var secondBody: SKPhysicsBody

        // 2. Assign the two physics bodies so that the one with the lower category
        // is always stored in firstBody
        if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
            firstBody = contact.bodyA
            secondBody = contact.bodyB
        } else {
            firstBody = contact.bodyB
            secondBody = contact.bodyA
        }

        // 3. react to the contact between ball and bottom
        if firstBody.categoryBitMask == RedBallCategory &&
           secondBody.categoryBitMask == GreenBarCategory {

            (secondBody.node!.removeFromParent())
            score++
            scoreLabel.text = "\(score)"
        }
    }

```

This works as expected, red ball hits the green bar and it deletes him.

You can't just make a func didBeginContact 2 and change the bit masks as far as I'm aware..or at least it didn't work when I tried it, so how do you handle multiple rules for collision? All of the basic tutorials I've seen handle something like one bullet hitting one type of enemy. What if you have 2 "bullets" and 2 enemies?

# Answer
Didn't realize it was as simple as just adding to the if statement. I thought I had already tried that.

```
func didBeginContact(contact: SKPhysicsContact) {

    var firstBody: SKPhysicsBody
    var secondBody: SKPhysicsBody

    if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
        firstBody = contact.bodyA
        secondBody = contact.bodyB
    } else {
        firstBody = contact.bodyB
        secondBody = contact.bodyA
    }

    if firstBody.categoryBitMask == RedBallCategory &&
       secondBody.categoryBitMask == GreenBarCategory {

        (secondBody.node!.removeFromParent())
        score++
        scoreLabel.text = "\(score)"
    } else if firstBody.categoryBitMask == GreenBallCategory &&
              secondBody.categoryBitMask == RedBarCategory {

        (secondBody.node!.removeFromParent())
        score++
        scoreLabel.text = "\(score)"
    }

```
> 1 votes

---
Tags: collision-detection, ios, spritekit
---


# Question
Title: What is the correct approach to implement multiplayer in a game?
I'm developing a game and it is intended to be a multiplayer game. I have experience in writing servers and clients in Java, but the game is written in C++. The server will be written in Java for sure.

I have 3 questions:

1. Am I forced to write the client in C++ ?
2. If not, is there a way to write the client in Java as well, and somehow communicate with the game program?
3. The game includes characters moving. Is the correct approach to calculate the positions of every dynamic object on the server and for the clients to only receive the current positions of everything from the server? The only thing the clients would send is their input(click, spell casts etc.).

# Answer
> 1 votes
In a client/server architecture it is not required that client and server are implemented in the same programming language. They usually communicate by sending raw data via network sockets. So you can choose the technology for each component separately, depending on your requirements, skillset and personal preferences. An exception would be when you want to use some library for netcode abstraction which isn't available for both languages you would like to use.

Only sending clients the data they need and only receiving their input and calculating the game mechanics on the server while only receiving the input is usually a good approach. This is called an authoritative server and it is the best way to prevent cheating. However, any actions the client performs locally should be performed without waiting for a confirmation to make the game appear smoothly regardless of the network latency.

---
Tags: opengl, c++, java, 3d, multiplayer
---


# Question
Title: How do I convert screen coordinates to isometric tile map coordinates in libGDX using matrices
I know this has been asked many times but my question doesn't quite fit the others. I have an `IsometricTiledMap` and I need to get the tile under a set of screen X and Y coordinates. Here is a picture of my game:

I need to get the tile that the player is standing on. I need to convert screen coordinates to isometric tile coordinates and the way that seemed the easiest was by using a matrix as described here: http://www.alcove-games.com/advanced-tutorials/isometric-tile-picking/#comment-56390

Unfortunately I have no idea how to change that code to fit a 128x64 tile instead of a 1.0x.5 tile. Here is my code

```
isoTransform = new Matrix4();
isoTransform.idt();
isoTransform.translate(0.0f, 32f, 0.0f);
isoTransform.scale((float) (Math.sqrt(2.0) / 2.0), (float) (Math.sqrt(2.0) / 4.0), 1.0f);
isoTransform.rotate(0.0f, 0.0f, 1.0f, -45.0f);

invIsotransform = new Matrix4(isoTransform.inv());

//touch vector
touch = new Vector3();

@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    touch.set(screenX, screenY, 0);
    touch = gameCamera.unproject(touch);
    touch.mul(invIsotransform);

    pickedTileX = (int)touch.x / 64;
    pickedTileY = (int)touch.y / 32;

    debug(touch.x + " " +  touch.y);
    debug(pickedTileX + " " + pickedTileY);

    return false;
}

```

I think the problem is in this line `isoTransform.scale((float) (Math.sqrt(2.0) / 2.0), (float) (Math.sqrt(2.0) / 4.0), 1.0f);` but I'm not sure what to change.

# Answer
So I finally found a method on some Github repository (I can't find the link again), and this one actually works. It doesn't use matrices and it doesn't to measure the screen or any of that crap.

```
private Vector3 worldToIso(Vector3 point, int tileWidth, int tileHeight) {
    gameCamera.unproject(point);
    point.x /= tileWidth;
    point.y = (point.y - tileHeight / 2) / tileHeight + point.x;
    point.x -= point.y - point.x;
    return point;
}

```

You probably want to round the coordinates down but other than that this works fine. 0, 0 is at the left most tile.
> 0 votes

---
Tags: libgdx, tilemap, isometric, coordinates
---


# Question
Title: Is there a way to check android version running the game using Unity3D?
I want to separate code to run only on android 4.4 or higher. If it's lower, I do not want to run this code. What should I do?

# Answer
> 3 votes
A ready to use method which is better than SystemInfo.operatingSystem :

```
public int GetSDKLevel() {
    var clazz = AndroidJNI.FindClass("android/os/Build$VERSION");
    var fieldID = AndroidJNI.GetStaticFieldID(clazz, "SDK_INT", "I");
    var sdkLevel = AndroidJNI.GetStaticIntField(clazz, fieldID);
    return sdkLevel;
}

```

Just copy and paste and that's all.

Note that if dots are uses instead of slashes as separators in the class name, it will crash in debuggable builds.

# Answer
> 2 votes
You can check SystemInfo.operatingSystem. The string should contain both OS name and version. Never tried on Android but should work.

---
Tags: unity, android
---


title: Render Occluded pixels to gray color

text:
# Question
Title: Render Occluded pixels to gray color
In 3d space, objects can be occluded by another objects.
By depth testing, the occluded faces are skipped rendering. Only the nearest(smallest) depth value pixels are drawn. But, sometime we need to render the occluded object or pixels for game play.

To differentiate the occluded object's pixels from foreground pixels, some game use gray color to render the pixels.

This is the sample images for the case.

I guess this can be achieved by some sort of shader.
How can I make this effects in Unity 3D Engine? Any hints or idea plz.

# Answer
I followed @nexx's comment.
and made a 2 pass surface shader which give colors to hidden pixels.

You can use built-in light function or Unlit version(commented).
Hope this help for others finding this kinds of effects.

```
Shader "Test/HiddenPixelColoring" {
   Properties {
      _MainTex ("Texture", 2D) = "white" { }
   }

   SubShader {
      ////////////////////////////////////////////////////////////
      // Pass #1

      Tags {"Queue" = "Geometry" "RenderType" = "Opaque" }

      CGPROGRAM

      #pragma target 3.0
      #pragma surface surf BlinnPhong

      struct Input {
         float2 uv_MainTex;
      };

      sampler2D _MainTex;

      void surf (Input IN, inout SurfaceOutput o) {
         o.Albedo = tex2D (_MainTex, IN.uv_MainTex).rgb;
      }

      ENDCG

      ////////////////////////////////////////////////////////////
      // Pass #2
      ZTest Greater

      CGPROGRAM

      #pragma target 3.0
      #pragma surface surf Lambert //lambertian reflectance lighting version
      //#pragma surface surf NoLighting //no lighting version

      struct Input {
        float4 color : COLOR;
      };

     /*
     //Lambertian reflectance lighting version
     fixed4 LightingNoLighting(SurfaceOutput s, fixed3 lightDir, fixed atten)
     {
         fixed4 c;
         c.rgb = s.Albedo;
         c.a = s.Alpha;
         return c;
     }
     */

      void surf (Input IN, inout SurfaceOutput o) {
         o.Albedo = float3(1.0, 0.0, 0.5);
      }

      ENDCG
   }

    Fallback "Diffuse"
}

```
> 1 votes

# Answer
What you are describing is not occlusion. Your objects in the image are rendered but are overwritten by the other object because of a higher Z depth.

What you are trying to achieve could be done using a shader that nexx mentioned earlier. For example this one could help you: http://forum.unity3d.com/threads/trying-to-make-a-silhouette-outline-shader.96005

you might need to modify it so that it won't display anything when the objects are visible. (There is an offset in the shader about the extrude value)
> 0 votes

---
Tags: unity, shaders, depth-buffer
---


title: UI button not working

text:
# Question
Title: UI button not working
Every time I try to click on the button, nothing happens. I am linking some picks to help everyone answer my question.

I have added a event system. I have a canvas. The button is set to interactable.

# Answer
> 0 votes
The problem is here: it looks like you directly dropped the script instead of the object to which it is attached.

Let's say your "Restart" script is attached to MainCamera. You need to assign Main Camera in the field marked red.Then select a script attached to main Camera, which is Restart, from that select a method which is ReStartGame().

When you do that, the field marked green would say: Restart.RestartGame

# Answer
> 0 votes
Put the Debug.Log before the Loadlevel instruction. What happens now is, LoadLevel is executed and everything is destroyed, including the button which was clicked. When new scene is loaded, everything in current scene is automatically destroyed. If you want an object to be present across multiple scenes, check the manual for DontDestroyOnLoad().

---
Tags: unity
---


# Question
Title: Is there a way to assign resource into a variable in the inspector programmatically?
I want to add resource to an inspector directly which could be done by drag and drop resource to the inspector. However, I want to know if there's a programmatic way to do this so, I will not need to add it hand by hand to perform a better performance than Resource.Load()

# Answer
As Ben's suggestion, help me to found an answer.

1. Mark \[ExecuteInEditMode\] on top of the Monobehavior class that I need to assign var to.
2. Use AssetDatabase.LoadAssetAtPath to load the resource I need into variable type that I want.
3. Save scene.
4. Remove script that add recently if you don't need it in production.
> 0 votes

---
Tags: unity
---


# Question
Title: Best practice for scrollable viewport rendering
I am working on a tile based game that renders the playing surface in a viewport. I am struggling with getting my head around the mechanics and best practices of rendering a viewport, specifically a scrollable viewport.

Typically the entire playing surface is made up of many adjoining tiles, and will display a portion of the surface to the user. The user will be able to scroll around the viewport by dragging or scrolling (North, east, South, west directions)

What would be considered best practice, for example.

* would one render and update every tile in the playing surface whether visible or not (I could see this using potentially a lot of processing time on larger maps with processing and needing to update every tile), or;
* should one only render what is visible to the user (and a few additional tiles around the edges to ensure that it looks like everything is rendered and avoid holes in the map)

I am quite new to game programming and would appreciate any thoughts and guidance of best practice in this area

# Answer
Both technics are ok. It's not that consuming to render more than it needs on modern devices, and the half of clipping/culling work made by graphical library itself. Most common technic is rendering chunks, such as rooms.
> 1 votes

# Answer
If you have maps that contain thousands of blocks, updating and drawing them all isn't efficient, and you lose a lot of valuable processing time. All you need to do is **just draw** what is in the viewport. Update blocks that are in the viewport as well, but make sure to update any moving blocks as well.

Say you have a camera and a 2-dimensional array of blocks.

You would do something like this:

```
for(int y = (camera.position.y - blockHeight) / blockHeight; y != (camera.position.y + screenHeight + blockHeight) / blockHeight; y++)
{
    for(int x = (camera.position.x - blockWidth) / blockWidth; x != (camera.position.x + screenWidth + blockWidth) / blockWidth; x++)
    {
        Blocks[x, y].draw/update();
    }
}

```

This will work for most setups.

One thing to note: This is a good option for **Drawing** 2D games.
> 0 votes

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


# Question
Title: Is the statement in Scratchapixel about transforming points correct?
I am reading this lesson from scratchapixel. To my understanding (and the example given in the same website) **M** is the matrix that transforms from **local** to **world**.

Giong through the paragraph before figure 7, though, I get the following:

> If we know the 4x4 matrix M that transforms a coordinate system A into a coordinate system B ...

Say **A** is the **local coord system** and **B** is the **world coord system**. Therefore **M** transforms from **local** to **world**.

> ... then if we transform a point whose coordinates are originally defined with respect to A with the inverse of M (...), we get the coordinates of P with respect to B.

We know, **A = local coord system**. The **Plocal = local point coords** are (-0.5, 0.5, -0.5). Then, as the quoted text says, we transform **Plocal** with the **inverse of M** to get the point w.r.t. to **B = woorld coord system**

However, this last operation (statement) confuses me, since the example they give the do **Pworld = Plocal * M**. But from the quoted text I understand that **Pworld = inv(M) * Plocal**

Can someone help me figuring out what am I missing? Is the wording of the text wrong?

# Answer
Let's take a simple example with the following variables

```
A: Local-space coordinates system
B: World-space coordinates system
M: Transformation matrix from local-space to world-space (A -> B)

```

Let's say we have a point `PA` in local space. To get the values of `PA` in world coordinates, we need to apply the transformation `M` on it:

```
// Local to World: A -> B
PB = PA * M    // If you are using row-based positions (your case)
PB = M * PA    // If you are using column-based positions

```

You can apply the inverse transformation to get `PA` back from `PB`:

```
// World to local: B -> A
PA = PB * inv(M)    // If you are using row-based positions (your case)
PA = inv(M) * PB    // If you are using column-based positions

```

The website you linked in the question has a part on this. It talks briefly about transforming a point from world-space to local-space:

> As suggested before, it is sometimes more convenient to operate on points when they are defined with respect to a local coordinate system rather than defined with respect to the world coordinate system. For instance, in the example of the cube (figure 6), defining the corners of the cube in local space is easier than in world space. **But how do we convert a point or vertex from one coordinate system (such as the world coordinate space) to another (converting points from a coordinate system to another is a very common process in CG)? That's easy. If we know the 4x4 matrix M that transforms a coordinate system A into a coordinate system B, then if we transform a point whose coordinates are originally defined with respect to A \[Should be B\] with the inverse of M (we will explain next why we use the inverse of M rather than M), we get the coordinates of P with respect to B \[Should be A\]**.

*I have added comments in square brackets (\[\]) for clarity.*

*NOTE: P with respect to A is PA, and P with respect to B is PB. X in respect to/of Y is a point X in the base Y: Coordinate vectors*

But this part is slightly unclear because in this paragraph **there are some typos inverting the letters**. Just ignore this passage, the rest of the article seems mathematicaly accurate.
> 1 votes

---
Tags: transformation
---


# Question
Title: How can I store a large amount of items in a space-efficient manner?
How can I store a large amount of items inside my game?

Are each of the items default data be loaded from a file into an item class and then stored in a giant array/list/dictionary?

For a point of reference, I'm talking about something like Skyrim where there are hundreds of items that the player is able to touch and pickup. And at any point the player can debug and add an item to their inventory.

I feel like the game would store everything is some kind of list but I also feel like this could consume a lot of memory, but maybe I am overthinking the size of each individual items data.

# Answer
> 2 votes
An item *type* and an item *instance* are two different things. The *type* is usually the "heavy" aspect of an item, the thing that describes what it is, how much damage it does, what it looks like, flavor text, et cetera. A type can also contain some kind of unique identifier, for example, in Guild Wars 2 every item type is uniquely identified by an integer ID.

An item *instance* is simply a reference to the item type ID, along with a small bit of local extra information such as position (if the item is placed in the world) and whatnot. This drastically reduces the amount of storage required to represent many instances of many items because little to no data is duplicated; only data which is *different* from the data stored in the type (or that doesn't make sense to store in the type) is unique to an instance.

You might have different kind of instance for an item based on where it is: an item in your inventory doesn't need a world position, for example, but one sitting in the world does.

Keeping track of item instances that exist in the world is largely a subset of keeping track of *anything* in a sufficiently large world and usually involves some kind of spatial partitioning to load and simulate only the currently-relevant sections of the world while keeping the rest of the data in some kind of persistent storage.

# Answer
> 1 votes
Generally games tend to use the Flyweight pattern. As needed, the data (models, textures, sounds, etc.) needed for an entity type are loaded into an associative table of `(type_id -> data)`. Then, the data that *varies* among instances of an entity is stored in a list or tree structure. Example of data that varies is the pose of an object, its animation state, health, etc. Each instance is associated with a `type_id`, that is used to render the object.

The more data that is shared between objects, the better in terms of memory/cpu performance.

# Answer
> 0 votes
Most games use some form of quadtree or octtree to organize and sort entities efficiently at runtime. The item's typeID is stored in the tree, and the renderer loads an instance of that type of entity when the player is within the same part of the octtree as the entity.

---
Tags: data-structure, inventory
---


# Question
Title: In Unity, how do I move my character to an object when I click on it?
Basic question here, and I feel like I'm close but can't quite get it.

I have an object--it's a pot on a stove--that is in my 2D game. There will be multiple pots that appear and disappear in the game, all in predefined places (like on top of the burners of a stovetop). There's also a chef in the game, who goes to each pot and does an action. The user never directly controls the chef's movement--instead, when the user clicks a pot, the chef runs over to the counter in front of that pot, where he can perform an action on the pot.

Can someone tell me how to do this? I'm not only looking for the code but for a "correct" design, in terms of where the various variables and methods should be located. In other words, what goes in the pot's script and what goes in the chef's script? (I'm using C#.)

My thought was that the pot GameObject would have an OnMouseDown() method, to catch the user clicking on it. And in that method, there should be a call to a Move() method that is attached to the chef GameObject.

But what I have is not quite working. The chef moves one small bit toward the pot but then stops. I realize that this is because I'm calling the Move function once and that's it; it seems like the Update method should be involved somehow (the pot's or the chef's?); or maybe I should have an if statement in my Move method that checks to see if the user is at the pot, and if not, runs the move code in a loop. Or maybe the design is just fundamentally wrong and it could be done more easily.

Here is the code I have:

```
public class PotController : MonoBehaviour {

    private GameObject chefObject;

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

    void OnMouseDown() {
        ChefController chefScript = chefObject.GetComponent<ChefController> ();
        chefScript.Move ();
    }

}

public class ChefController : MonoBehaviour {

    public float moveSpeed;
    private Vector3 moveDirection;

    public void Move () {

        Vector3 currentPosition = transform.position;
        if (Input.GetButton ("Fire1")) {
            Vector3 moveToward = Camera.main.ScreenToWorldPoint (Input.mousePosition);
            moveDirection = moveToward - currentPosition;
            moveDirection.z = 0;
            moveDirection.Normalize ();
        }
        Vector3 target = moveDirection * moveSpeed + currentPosition;
        transform.position = Vector3.Lerp( currentPosition, target, Time.deltaTime );

    }

}

```

# Answer
> 1 votes
What you want to do is program the chef to move toward its target destination; every frame in Update() check if the chef is at the target, and if not move a bit toward the target. Then clicking on a pot sets the target position. Something like this pseudo-code:

```
Chef {
  Vector3 target;
  Update() {
    if (chef.position != target) {
      TurnToward(target);
      MoveToward(target);
    }
  }
  SetTarget(Vector3 pos) {
    target = pos;
  }
}

Pot {
  OnMouse() {
    chef.SetTarget(transform.position);
  }
}

```

(this is kind of movement control is also explained in my book; look at my profile)

# Answer
> 1 votes
One thing I would be careful about is using the correct input callback. I would suggest one of two things, read the API's on the input methods available, and choose the one appropriate to your desired behavior. Some callbacks only fire if the key is held down, and others fire on a tap.

Secondly, your architecture should change a little bit. The callback should only set the Target transformation. When you click on a pot, copy the transform from the pot to the target of the move script. The move script should be changed to automatically strive to achieve it's current target transformation until it reaches it, at which point it will wait until it receives a new target. This is best done by having your movement code in the Update() method within the script. For a small game, this will achieve your goal, and not cause much overhead. (Bigger games with many moving entities need to approach the problem a little differently)

These changes will mean when you click a pot, the target will be set, and on each frame the movement script will adjust the chef's position if it doesn't match the target.

The beauty is that you can reuse the "moveto" script for any other objects, with either a fixed, random, or controlled target transformation to add a little extra to your game. (a rat, or an assistant for instance)

---
Tags: unity
---


# Question
Title: Optimization for lots of UV coordinates update for tilemap animation
In my game, I procedurally generate tile map mesh and modify it when travelling around the "world". Each tile is a quad. So they each, have their own UV points. (Obviously)

I am using Unity for this, and in Unity, i can't have more then 65k vertices in a single mesh.

So i made this "tile mesh", chunk based. It's still a single mesh. But while I am creating it, i first create the "chunks", (which are 16x16 quad meshes), then i "merge" the chunk meshes to create the tile map mesh.

I keep these "chunk meshes" in a list. So basicly i merge all the meshes in the list when i want to "update" the tilemap mesh.

While i am travelling in the world, i can remove farthest chunk from list, and add new chunkes when it's necessary. List capacity is fixed to 9, so i can never exceed the "65k vertices limit".

Now the problem is, when i zoom out in game, there becomes almost 40k vertices in the scene since whole mesh becomes rendered. (Actually since it's a single mesh, it always renedered as whole, but the animation doesn't occur out side of the camera view)

But when i zoom out, there are like atleast (6x6)x(16x16) = 9.216 tiles. Which makes 36.864 vertices (and UV points).

Now updating few tiles (so few uv points) is easy. But updating the whole 36k point takes like 1-2 seconds. Which is really bad for updating animation in that way.

The code snippet for single quad uv update is here

```
public void SetTile(Coord chunkCoord, Coord tileCoord, Sprite sprite)
    {
        Vector2[] uv = meshFilter.mesh.uv;
        Rect spriteRect = sprite.textureRect;

        int chunkIndex = SearchForChunk(chunkCoord);

        if (chunkIndex == -1)
        {
            Debug.LogError("Chunk not found");
            return;
        }

        int ui = chunkIndex * (16 * 16) + (tileCoord.Y * 16 + tileCoord.X);
        ui *= 4;

        uv[ui] = ToUV(new Vector2(spriteRect.xMin, spriteRect.yMax), sprite.texture);
        uv[ui + 1] = ToUV(new Vector2(spriteRect.xMin, spriteRect.yMin), sprite.texture);
        uv[ui + 2] = ToUV(new Vector2(spriteRect.xMax, spriteRect.yMin), sprite.texture);
        uv[ui + 3] = ToUV(new Vector2(spriteRect.xMax, spriteRect.yMax), sprite.texture);

        meshFilter.mesh.uv = uv;
    }

```

It takes chunk coordinate, and finds that chunk in the chunk list, so i can get the index of that chunk mesh for UV array.

The sprite that i get as a parameter is in a "sprite atlas", so i call a helper function to convert it's rectangle to uv points.

That's how i update a single tile's UV points.

But It's too slow, how can i optimize it, make it faster?

# Answer
> 1 votes
Without knowing more about your code, its difficult to say why it would be running that slow. I can't imagine it taking 1-2 seconds to update 32000 UVs, that's not that large of a number, so my guess is that its doing something else horrible because of the fact that you are updating that many UVs.

Either way, your solution will be similar. Since all the UVs need to get updated by the same values each frame anyway, I would take one of the standard shaders and modify it so that it can offset the UVs by some fixed amount. Then I would render your mesh with the new shader, and you can just update the offset U and offset V values, and it won't require modifying the actual UVs of each polygon.

# Answer
> 0 votes
One thing to think about here is that you are updating the entire mesh UV state for each tile you modify. I'd be sure to check and make sure it's not refreshing the mesh after each tile. you might return the UV updated array one level up and marge them all at once. Basically restructure so you calculate all, then apply the changes to the chunk/mesh.

I also notice you're searching for the chunk index once for every tile you update. Do this outside of the tile loop, and pass the result to the SetTile() so you only do this search once per chunk instead of once per tile.

---
Tags: unity, tilemap, optimization, uv-mapping
---


# Question
Title: Causes of Scene Build File Size Bloat in Unity
We are developing racing game for android and iOS.

Our problem is final game build size is getting more than 100+ mb.

So here is what we tried,

> to reduce it by compressing textures.
>
> Reducing "Max size" to 512 and 256
>
> Reduced .FBX size

All is well n good though the final "scene" size for each scene is more than 8mb.

I am not sure why scene size is that much? I would like to know what are the things that causes unity scene size to occupy that much memory?

# Answer
> 2 votes
You can see Editor build log to check which files contribute most to the size of your build. You can open it from within Unity by clicking on the list icon right abot the error icon on console view. (See image attached)

Then you can see if you have unecessary assets and reduce size of others.

You can also strip assemblies in the final build to reduce size. Go to Players Setting -\> Other Settings under "Optimization" select .Net 2.0 subset and Stripping Level use micro mscorelib.

---
Tags: unity
---


# Question
Title: LOVE Physics - Breaking Joint Chains (LUA / Box2D)
Wasn't sure whether to post here or on SO so please move if needed.

I've been having a look into the box2D physics API provided by LOVE to try and create a swinging flail or weighted rope but I'm having some trouble keeping the jointed elements close together.

So far I've made a series of circular bodies and linked them together using revolute joints with the first element being static and the final element being slightly larger/heavier to act as a weight.

The code to generate each link is as follows:

```
    for i = 1, segments, 1 do

        link = {}

        if (i == 1) then
            link.body = love.physics.newBody(world, xpos, ypos, "static") --Starting link
        else
            link.body = love.physics.newBody(world, xpos, ypos, "dynamic")
        end

        if (i == segments) then
            link.shape = love.physics.newCircleShape(endlink_radius) --Ending link
        else
            link.shape = love.physics.newCircleShape(link_radius)
        end

        link.fixture = love.physics.newFixture(link.body, link.shape) --Fix bodies to shapes

        table.insert(chain,link)

        ypos = ypos + link_distance --Place next link further down, keeping x position

    end

```

And the code to join each link:

```
    for i = 2, #chain, 1 do

        x1,y1 = chain[i-1].body:getPosition() --First link position
        x2,y2 = chain[i].body:getPosition() --Second link position
        chain[i-1].join = love.physics.newRevoluteJoint(chain[i-1].body, chain[i].body, x1, y1, x2, y2, false ) --Join the two with a revolute joint

    end

```

And this works quite well, producing a chain like this:

The next step is to move the chain, I'm currently moving the first static element and having it "drag" the rest of the links along with it using the following code:

```
    position = vo.add(position, velocity) --Vector addition add velocity to current position to get new position
    chain[1].body:setPosition(position.x, position.y) --Update the first link position

```

This works fine for slow speeds (chain currently moves towards mouse cursor) but any rapid movement causes everything to fall apart.

Is there anyway to easily keep the elements close together?

I've tried adjusting the weights and world gravity but couldn't see any difference, I've also thought about applying a force to each element when the first one moves but that doesn't seem quite right.

Thanks

**Solution (Thanks to NauticalMile)**

Change the previous position update:

```
    position = vo.add(position, velocity) --Vector addition add velocity to current position to get new position
    chain[1].body:setPosition(position.x, position.y) --Update the first link position

```

To a velocity update and have Box2D handle the movement:

```
    chain[1].body:setLinearVelocity(velocity.x, velocity.y)

```

# Answer
Directly editing the position of a box2d body will produce non-physical behaviour, it's present because sometimes you will need to teleport bodies to a far away location, or reset the position of an object without the need to destroy/re-create it, etc... In your case the joints are not handling the position adjustments well.

The `setPosition` function should *not* be used to advance the physics, box2d takes care of that all on its own when `b2World:step` is called. In order for the chain to move smoothly, you just need to manipulated the top link in a different manner. I propose one of two suggestions:

1. If the top link in the chain is supposed to be attached to something much bigger moving at a constant velocity, then I would recommend changing the `bodyType` of the top link to `'kinematic'` using the `Body:setType` function. Just initialize the velocity of the top link body to a reasonable value. This is demonstrated in RUBE:

2. If you want the top link to have a dynamic behaviour, while still constraining it to only move along a given axis, you can create a 'dummy' static body, and connect the top link to the static body via a `PrismaticJoint`. Again, here's an example done in RUBE where I have applied a small force at the beginning using the MouseJoint:

In the real world objects accelerate when forces are applied to them. box2d functions in much the same way; enter the `body:applyForce` function. You can use this to apply a force toward the cursor position. You can also add some `LinearDamping` to the first or any of the links to make sure things don't get too out of hand.

Both of these options should be very stable, but let me know if there are any issues.
> 3 votes

---
Tags: physics, box2d, lua, love2d
---


# Question
Title: How can I repeat a Texture Region in libGDX
I have a texture that is part of a sprite sheet. I want draw the texture to cover a certain length, but I want it to repeat not stretch. However,when I use the following code

```
batch.draw(hillBottom, hill1.getX(), hill1.getY(), hill1.getWidth(), hill1.getHeight(), 0, 0, 1, hill1.getNumBlocks());

```

I receive an error indicating that the first argument must be a Texture not a Texture Region. I am new to game development, but I have read from multiple different guides that loading seperate textures in a game hinders performance which is why it should only be done if completely necessary. Is there anyway I can repeat the Texture Region?

# Answer
> 1 votes
I don't think this is possible in your case. A repeating texture at the hardware level needs to span the entire texture, at least on the axis it is repeating.

You can still repeat the sprite if you write your own routine. You would just call draw() multiple times.

If you decide to load your repeating sprite as a separate texture so you can render it in one draw call, you might also want to make the width a power of 2 (e.g. 32, 64, 128), because even devices supporting NPOT textures might not support them as repeating textures.

---
Tags: java, libgdx, textures, texture-atlas
---


title: Error BCE0043,BCE0044 and UCE001

text:
# Question
Title: Error BCE0043,BCE0044 and UCE001
I got my code right here:

```
#pragma strict

var hSliderValue : float = 0.0;

function OnGUI(){
hSliderValue = GUI.HorizontalSlider (Rect (25, 25, 100, 30),hSliderValue, 00, 1.0);
GetComponent<AudioSource>().volume=hSliderValue;
}

```

I don't know why those errors keep popping-up but unity say it have something to do with the: GetComponent().volume=hSliderValue;

BCE0043: Unexpected token: ).

BCE0044: expecting ), found '.'.

UCE0001: ';' expected. Insert a semicolon at the end.

# Answer
```
GetComponent<AudioSource>().volume=hSliderValue;

```

This line is C#, not Javascript, or UnityScript.
> 0 votes

---
Tags: unity, javascript, scripting, unityscript
---


# Question
Title: Function messages wont send when identical conditions will message to activate another function
So in working with my game, there aren't any syntax or compile errors, but there's this one bug that I've been working on to fix for a few days on and off and I can't seem to make heads or tails of the reason why it doesn't work, let me explain.

This is what the player sees when they start out, and their actions are to be able to click on two wires on the same side (right-right and left-left) and the should both switch positions.

In this image,the blue wire was the first one clicked, and the highlight/highlightDirection variables I have set are assigned to 'w2' (the blue wire) and the 'topLeft' direction for the purpose of changing the wire's sprite correctly when it changes positions.

And now I've clicked on the yellow wire, setting the changelight/changelightDirection to 'w3' (the yellow wire) and the 'middleLeft' direction for the purpose of changing the wire's sprite correctly when it changes positions, and after changelight/changelightDirection have been assigned, the wires shoudl both switch positions, but instead, this happens.

Only the yellow wire (The changelight/changeligthDirection wire) switched sprites, and this has been consistent throughout all of the combinations possible.

To try and fix this, I've gone over the script for the TopLeft and MiddleLeft scripts dozens of times, yet for some reason the same problem persists, and only the second clicked wire changes positions **TopLeft.cs**

```
    void OnMouseDown () {
    if (levelManager.highlight == "none") {
        levelManager.highlight = levelManager.leftTopWire;
        levelManager.highlightDirection="topLeft";
    } else {
        levelManager.changelight = levelManager.leftTopWire;
        levelManager.changelightDirection = "topLeft";
        if (levelManager.highlight == "w1" || levelManager.changelight=="w1") {
            wireOne.SpriteChange ();
        }
        if (levelManager.highlight == "w2" || levelManager.changelight=="w2") {
            wireTwo.SpriteChange ();
        }
        if (levelManager.highlight == "w3" || levelManager.changelight=="w3") {
            wireThree.SpriteChange ();
        }
    }
}

```

**MiddleLeft.cs**

```
    void OnMouseDown () {
    if (levelManager.highlight == "none") {
        levelManager.highlight = levelManager.leftMiddleWire;
        levelManager.highlightDirection="middleLeft";
    } else {
        levelManager.changelight = levelManager.leftMiddleWire;
        levelManager.changelightDirection = "middleLeft";
        if (levelManager.highlight == "w1" || levelManager.changelight=="w1") {
            wireOne.SpriteChange ();
        }
        if (levelManager.highlight == "w2" || levelManager.changelight=="w2") {
            wireTwo.SpriteChange ();
        }
        if (levelManager.highlight == "w3" || levelManager.changelight=="w3") {
            wireThree.SpriteChange ();
        }
    }
}

```

In the code for each scripts, no matter if the that wire is assigned to either changelight or highlight, then that wire's script will run it's SpriteChange function, unless I'm missing something that's how the code should work, and suggestions on how to fix this?

EDIT: Here's the code for the SpriteChange() functions for scripts WireOne.cs, WireTwo.cs, WireThree.cs

```
public void SpriteChange(){
    if (levelManager.changelight == "w1") {
        if (levelManager.highlightDirection == "middleLeft" || levelManager.highlightDirection == "bottomLeft" || levelManager.highlightDirection == "topLeft") {
            if (levelManager.highlightDirection == "middleLeft" && rightPos == "Top") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = downUpTop;

            }
            if (levelManager.highlightDirection == "middleLeft" && rightPos == "Middle") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = straightMiddle;

            }
            if (levelManager.highlightDirection == "middleLeft" && rightPos == "Bottom") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = upDownBottom;

            }
            if (levelManager.highlightDirection == "topLeft" && rightPos == "Top") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = straightTop;

            }
            if (levelManager.highlightDirection == "topLeft" && rightPos == "Middle") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = upDownTop;

            }
            if (levelManager.highlightDirection == "topLeft" && rightPos == "Bottom") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = upDownTall;

            }
            if (levelManager.highlightDirection == "bottomeLeft" && rightPos == "Top") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = downUpTall;

            }
            if (levelManager.highlightDirection == "bottomLeft" && rightPos == "Middle") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = downUpBottom;

            }
            if (levelManager.highlightDirection == "bottomLeft" && rightPos == "Bottom") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = straightBottom;

            }

        } else {//This is if the highlight direction is from the right
            if (levelManager.highlightDirection == "middleRight" && leftPos == "Top") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = upDownTop;

            }
            if (levelManager.highlightDirection == "middleRight" && leftPos == "Middle") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = straightMiddle;

            }
            if (levelManager.highlightDirection == "middleRight" && leftPos == "Bottom") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = downUpBottom;

            }
            if (levelManager.highlightDirection == "topRight" && leftPos == "Top") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = straightTop;

            }
            if (levelManager.highlightDirection == "topRight" && leftPos == "Middle") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = downUpTop;

            }
            if (levelManager.highlightDirection == "topRight" && leftPos == "Bottom") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = downUpTall;

            }
            if (levelManager.highlightDirection == "bottomeRight" && leftPos == "Top") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = upDownTall;

            }
            if (levelManager.highlightDirection == "bottomRight" && leftPos == "Middle") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = upDownBottom;

            }
            if (levelManager.highlightDirection == "bottomRight" && leftPos == "Bottom") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = straightBottom;

            }

        }
    }
    else{ //This is if the wire is in the highlight instead of the changelight
        if (levelManager.changelightDirection == "middleLeft" || levelManager.changelightDirection == "bottomLeft" || levelManager.changelightDirection == "topLeft") {
            if (levelManager.changelightDirection == "middleLeft" && rightPos == "Top") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = downUpTop;

            }
            if (levelManager.changelightDirection == "middleLeft" && rightPos == "Middle") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = straightMiddle;

            }
            if (levelManager.changelightDirection == "middleLeft" && rightPos == "Bottom") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = upDownBottom;

            }
            if (levelManager.changelightDirection == "topLeft" && rightPos == "Top") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = straightTop;

            }
            if (levelManager.changelightDirection == "topLeft" && rightPos == "Middle") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = upDownTop;

            }
            if (levelManager.changelightDirection == "topLeft" && rightPos == "Bottom") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = upDownTall;

            }
            if (levelManager.changelightDirection == "bottomeLeft" && rightPos == "Top") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = downUpTall;

            }
            if (levelManager.changelightDirection == "bottomLeft" && rightPos == "Middle") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = downUpBottom;

            }
            if (levelManager.changelightDirection == "bottomLeft" && rightPos == "Bottom") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = straightBottom;

            }

        } else {//This is if the changelight direction is from the right
            if (levelManager.changelightDirection == "middleRight" && leftPos == "Top") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = upDownTop;

            }
            if (levelManager.changelightDirection == "middleRight" && leftPos == "Middle") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = straightMiddle;

            }
            if (levelManager.changelightDirection == "middleRight" && leftPos == "Bottom") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = downUpBottom;

            }
            if (levelManager.changelightDirection == "topRight" && leftPos == "Top") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = straightTop;

            }
            if (levelManager.changelightDirection == "topRight" && leftPos == "Middle") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = downUpTop;

            }
            if (levelManager.changelightDirection == "topRight" && leftPos == "Bottom") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = downUpTall;

            }
            if (levelManager.changelightDirection == "bottomeRight" && leftPos == "Top") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = upDownTall;

            }
            if (levelManager.changelightDirection == "bottomRight" && leftPos == "Middle") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = upDownBottom;

            }
            if (levelManager.changelightDirection == "bottomRight" && leftPos == "Bottom") {
                gameObject.GetComponent<SpriteRenderer> ().sprite = straightBottom;

            }
        }
    }
    levelManager.highlight = "none";
    levelManager.highlightDirection = "none";
    levelManager.changelight = "none";
    levelManager.changelightDirection = "none";
}

```

# Answer
> 1 votes
That one is easy and, yes, even after many years as a programmer I stumble upon this kind of situation.

In `SpriteChange` you change values held by your `levelManager`:

```
levelManager.highlight = "none";
levelManager.highlightDirection = "none";
levelManager.changelight = "none";
levelManager.changelightDirection = "none";

```

However, in your `else` parts of your two first scripts you rely on the values of `levelManager.changelight` or `levelManager.highlight` to be *something else* than *"none"*. This is why only the first part is done: when it is ready to go for a second time (evaluate to `true` in a second `if`), all the important values are set to *"none"*, which causes the condition checks to result to `false`.

To fix your issue, I would suggest to place the code that resets your values *after* the three `if`s in each of your `else` parts of your `OnMouseDown` methods instead of in your `SpriteChange` methods:

**TopLeft.cs**

```
void OnMouseDown () {
    if (levelManager.highlight == "none") {
        levelManager.highlight = levelManager.leftTopWire;
        levelManager.highlightDirection="topLeft";
    } else {
        levelManager.changelight = levelManager.leftTopWire;
        levelManager.changelightDirection = "topLeft";
        if (levelManager.highlight == "w1" || levelManager.changelight=="w1") {
            // If you got here because (levelManager.highlight == "w1") == true,
            // it means that levelManager.changelight == _something else_ so you
            // **should not** reset its value in wireOne.SpriteChange ()
            // so that it can be evaluated to true in the other ifs.
            wireOne.SpriteChange ();
        }
        if (levelManager.highlight == "w2" || levelManager.changelight=="w2") {
            wireTwo.SpriteChange ();
        }
        if (levelManager.highlight == "w3" || levelManager.changelight=="w3") {
            wireThree.SpriteChange ();
        }
        // You no longer need these at this point, you can reset them.
        levelManager.highlight = "none";
        levelManager.highlightDirection = "none";
        levelManager.changelight = "none";
        levelManager.changelightDirection = "none";
    }
}

```

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


# Question
Title: How do I use playerprefs to make ui slider keep the sound settings?
I have not use playerprefs before, I want to know how to keep the change of the audio when the player change it throughout the game.

# Answer
```
using UnityEngine;
using UnityEngine.UI;

public class SliderSaver : MonoBehaviour {

    public Slider slider;

    void Awake ()
    {
        slider.Value = PlayerPrefs.GetFloat ("Slider value");
    }

    public void OnSliderChange (float newValue)
    {
        PlayerPrefs.SetFloat ("Slider value", newValue);
    }

}

```

This sets the slider's value in the beginning to the saved value then changes that saved value whenever the slider changes.
> 1 votes

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


title: Circle Depth Penetration

text:
# Question
Title: Circle Depth Penetration
I'm resolving some collision between circles and I keep getting this problem.

Note: The rectangles are perfect squares fitting the circles so when I type rect.Width I mean the radius of the circle.

What I was trying to do was make it so that if it penetrated it would get pushed out and then the else if would take over and not call the if anymore. but the depth turns out to be a small number such as .6 and then since it's a float it rounds down and doesn't affect the rectangle at all. Even if I add a round function in there it just starts to jitter a bunch.

```
if (r < rect2.Width / 2 + rect1.Width / 2 && (fN + fG + fA).Length() != 0)
{
    // Resolve depth penetration
    float mDepth = rect2.Width / 2 + rect1.Width / 2 - r;
    Vector2 depth = new Vector2(mDepth * (float)Math.Cos(theta), mDepth * (float)Math.Sin(theta));
    rect2.X -= (int)depth.X;
    rect2.Y -= (int)depth.Y;

    // Apply an equal and opposite force
    fN = -fG

    // Stop the earth from moving
    v2 = Vector2.Zero;
}
else if(r == rect2.Width / 2 + rect1.Width / 2)
    fN = -fG;
else
    fN = Vector2.Zero;

```

I also tried changing depth penetration too this but the results are no different.

```
float mDepth = rect2.Width / 2 + rect1.Width / 2 - r;
Vector2 direction = rect1.Location.ToVector2() - rect2.Location.ToVector2();
direction.Normalize();
Vector2 depth = direction * mDepth;
rect2.X -= (int)depth.X;
rect2.Y -= (int)depth.Y;

```

The only solution we could think of is creating a range of 5 in which the object could be at rest.

```
if (r < rect2.Width / 2 + rect1.Width / 2 + 5 && r > rect2.Width / 2 + rect1.Width / 2)
    fN = -fG;
else if (r < rect2.Width / 2 + rect1.Width / 2 && (fN + fG + fA).Length() != 0)
{
    // Resolve depth penetration
    float mDepth = rect2.Width / 2 + rect1.Width / 2 - r;
    Vector2 depth = new Vector2(mDepth * (float)Math.Cos(theta), mDepth * (float)Math.Sin(theta));
    rect2.X -= (int)depth.X;
    rect2.Y -= (int)depth.Y;

    // Apply an equal and opposite force
    fN = -fG;

    // Stop the earth from moving
    v2 = Vector2.Zero;
}
else
    fN = Vector2.Zero;

```

Is there not a better way to do this?

Here is a video outlining the problem. https://www.youtube.com/watch?v=ZREQDA5BN0s Essentially since depth resolution isn't exact the == part of the if statement isn't used I know this because I placed a breakpoint in the first if statement it keeps going there with a depth of around .6. Then rounds down and doesn't move it at all. If I round it appropriately it just jitters a bunch.

# Answer
> 2 votes
Yes, you can do this with no expensive trig at all.

Steps:

1. Find the distance between the 2 circles.
2. Find the combined radius between the 2 circles.
3. Subtract the distance from the combined radius to get the depth of the penetration.
4. Multiply the direction between the circles by the penetration depth.

I.e.:

```
Circle c1;
Circle c2;

float Distance = (c1.position - c2.position).magnitude;
float CombinedRadius = c1.radius + c2.radius;
float Depth = CombinedRadius - Distance;

Vector2 Direction = (c1.position - c2.position).normalized;
Vector2 Penetration = Direction * depth;

//Resolve the collision
c1.position -= Penetration / 2;
c2.position += Penetration / 2;

```

That's the penetration of 2 circles. As for a circle and an axis-aligned square, I'm not really sure where you were going with it but the penetration vector is just the penetration of the objects' bounding boxes.

If you want to be more accurate, you could find the direction between the circle and squares' centers then project the circle and square onto it, then find the penetration vector by subtracting the circle and square's extents on that direction.

---
Tags: xna, c#, monogame, collision-resolution, windows
---


title: Different damage systems?

text:
# Question
Title: Different damage systems?
I am designing a simple "Plant vs Zombies"-like game, but without graphics (just polygons) for class homework.

I came to the point where I need to calculate damage to different entities. Por example, the zombie can kill the shooting turret in 3 bites, but would instantly kill the "engineer" that puts the towers if it touches him.

I was thinking on a List approach, where the Engineer always takes damage, from turret, zombie, land mine, etc, but he knows how much damage takes from any of those entities. It is not really realistic though, and if new entities are added, if I forget to add them to the engi or other entity's damage list, it would not get damaged at all.

Any help would be very appreciated.

# Answer
> 5 votes
The usual simple approach is to have attacks do X points of damage and creatures to have Y amount of hit points. An attack subtracts damage from hit points and the creature dies when it has 0 hit points left. Then you need only basic arithmetic and no weird data structures or explicit coupling between creature definitions.

An extension of this is to then add damage *types* and resistances. This is just another mathematical extension. In this setup, an attack might do X *bullet* damage or X *fire* damage, or so on. Creatures then have resistances or weaknesses to a set of types, which is just a multiplier (so a creature might take half damage from bullets and double damage from fire). A creature can also have a default resistance so that e.g. it might take 0% damage from all types except the one or two that it's vulnerable to.

Damage, hit points, and resistances can model a very huge variety of situations, including the one you outline. A direct port of your design to this model would be to give each attacking creature its own damage type; then you can explicitly set a creature's damage resistances to only accept the damage types of a specific set of attacking creatures.

I wouldn't necessarily recommend going that way, though, as it makes your game harder for a player to understand. Remember, humans are all about pattern recognition, and games tend to play into that. If a shooting turret kills a zombie in 3 hits and an tank in 6 hits, the player will want to extrapolate that experience into knowing that a strong turret that kills a zombie in 2 hits will kill the tank in 4 hits or less. Breaking that expectation will make your game impossible to predict, hard to understand, and ultimately unsatisfying to play.

Also, of course, coupling the creatures will make it harder to iterate on your design, as you pointed out. You should be able to drop in a new creature and just have it "work" without needing to go back and modify every single other creature.

# Answer
> 1 votes
iYou need maximum flexibility for your self.

Meaning you need config values for each damage dealer and damage receiver. Two types of damage cover for most of your situations. A flat amount (say 10) and a % amount say (20%). Obviously you need hit points for the damage.

This is for you however. Maybe you want damage overtime too.

Relaying this the players is an entirely another matter. You may not show any damage numbers at all. You may choose to show "Monster dies/in 3-5 hits from your selected creature" Or you may show only health bars and damage effects without the actual numbers.

What you want to have is good configure-ability, so when you do decide to fiddle with numbers it can be easy.

Most people hate excel but i really recommend it for configurations of the sort, when you don't have the time and patience for coding really dynamic configs.

I have a whole subset of units that have a whole lot of values to each one, I've linked all damage calculations for them to single cells. I start with a base damage number say 50 - every unit starts with it.

When you run past your logical considerations on what is how strong etc. You decide that X unit will have 5 times the base damage. Except in my case the unit has damage vs every kind of other unit. If you have to calculate these one by one each time you change them its a headache. Instead if you tied them all up, all you need to do is change 1 number and everything auto calculates.

Specifying damage vs each unit is a bit easier to manage than having one damage and assigning resistances to all other entities. You can have the machine translate that to you in terms of resistance. What do I mean? If your BASE damage is 200. And you say this unit has 150 damage vs rocks. It means the rock has 50 resistance to this unit's damage.

The more complicated damage you have the more precise planning you need to make to organize it. Obviously configuring resistances individually becomes much more convenient dependent on what you have/want/need to work with. It doesn't take rocket science. Even if you are not big at math, you just need a good plan/design. You need to understand what you want to achieve in the end, the rest is for the computer to calculate once you set the rules.

If you know your swordsman has to be 3 times stronger than your unarmed guy. and has to cost N times a much, the rest is just grinding it out into existence.

Balancing is much easier if you can translate everything to a universal value. But that takes some effort. A lot of designers just go blind in balancing stuff and fiddle with numbers manually until the game seems playable. Few have the will to go ahead and calculate everything, Its one of the reasons why many virtual economies fail. People have no idea how much comes into them and how much goes out. They think that some rudimentary concepts can do the work of exact math. But they can't.

---
Tags: game-design
---


# Question
Title: How do I make one ui slider control all of the game audio?
I use the ui slider to control how loud is the game, what I want to know is how to make one ui slider control all of the game audio?

# Answer
http://answers.unity3d.com/questions/16603/is-there-a-global-volume-setting.html

Use the slider's value to determine the AudioListener.volume static field.

http://docs.unity3d.com/ScriptReference/AudioListener-volume.html

It is between 0 and 1. You can get a normalised( between 0 and 1 ) value from the slider using Slider.normalizedValue.
> 1 votes

---
Tags: unity, c#, unityscript, audio, ui-design
---


# Question
Title: Jittery Movement, Uncontrollably Rotating + Front of Sprite?
So I've been looking around to try and figure out how I make my sprite face my mouse. So far the sprite moves to where my mouse is by some vector math.

Now I'd like it to rotate and face the mouse as it moves. From what I've found this calculation seems to be what keeps reappearing:

```
Sprite Rotation = Atan2(Direction Vectors Y Position, Direction Vectors X Position)

```

I express it like so:

```
sp.Rotation = (float)Math.Atan2(directionV.Y, directionV.X);

```

If I just go with the above, the sprite seems to jitter left and right ever so slightly but never rotate out of that position. Seeing as `Atan2` returns the rotation in radians I found another piece of calculation to add to the above which turns it into degrees:

```
sp.Rotation = (float)Math.Atan2(directionV.Y, directionV.X) * 180 / PI;

```

Now the sprite rotates. Problem is that it spins uncontrollably the closer it comes to the mouse. One of the problems with the above calculation is that it assumes that **+y** goes up rather than down on the screen. As I recorded in these two videos, the first part is the slightly jittery movement (A lot more visible when not recording) and then with the added rotation:

Jittery Movement

So my questions are:

1. How do I fix that weird Jittery movement when the sprite stands still? Some have suggested to make some kind of "snap" where I set the position of the sprite directly to the mouse position when it's really close. But no matter what I do the snapping is noticeable.
2. How do I make the sprite stop spinning uncontrollably?
3. Is it possible to simply define the front of the sprite and use that to make it "face" the right way?

# Answer
Only change the rotation whenever your distance is above a certain delta. Also center your sprite, right now you're using the top-left corner of the sprite.
> 0 votes

---
Tags: c#, sprites, rotation, sfml
---


# Question
Title: Where does Unity save the editor window layouts?
In every project there are the `CurrentLayout.dwlt` and `CurrentMaximizeLayout.dwlt` files, but those, as the name implies, are just the *current* layouts.

I've been unable to find the general files where it saves all your layouts, in order to copy it to another computer.

Where is it?

# Answer
> 6 votes
On Windows: %APPDATA%/Unity/Editor-n.x/Preferences/Layouts

On OSX: ~/Library/Preferences/Unity/Editor-n.x/Layouts

Where n is the major version number of the Unity Editor in question, %APPDATA% is your AppData/Roaming hidden folder in your user folder (on Windows) and ~ is your home directory (on Mac).

---
Tags: unity
---


title: How does unity size graphics?

text:
# Question
Title: How does unity size graphics?
I'm working on a 2D game. It has tiles. each tile is 50x50 px. I attached script to camera which sets the camera size to screenHeight/2/PixelsPerUnit.

Now in the player, as an example i selected 480x320 size. I expected it to show approx 9x6 tiles. However it shows 6tiles horizontally and 4 tiles vertically.

Similarly for other sizes, it shows lesser than calculated number of tiles.

How does this corelate?

**Edit** i created the tiles in photoshop with 300 dpi. Not sure if that affects anything though.

# Answer
> 1 votes
I asked this question when I was an absolute newcomer. Answering this now so someone looking for this finds the solution.

First part of my question was about setting camera size so a certain background fits the screen perfectly, both horizontally and vertically. Now I know that's a bad idea because having a background fit one single size means skybox will show on wider screens.

So, here is what I did. When we set camera size, there's a certain screen height. This height is fixed irrespective of the device screen. On larger devices, greater detail, on smaller devices, lesser detail. So, if I chose 760px as height of my background image, I calculate camera size as follows: cameraSize= (Height/2)/PixelsPerUnit which in my case is, (760/2)/100=3.8

Next, I need to make sure skybox doesn't show irrespective of the device's screen size. This means, design background for the widest aspect ratio which is 16:9. So, I calculated the width as

width=AspectRatio X height. Which in my case is (16/9) X 760=1352 px.

So my background is 1352 X 760 pixel. This fits 16:9 aspect ratio perfectly. On narrower ratios like 4:3, there is cropping towards the sides. But skybox never shows. Which was my main issue.

---
Tags: unity
---