title: Rotate Sprite towards another sprite

text:
# Question
Title: Rotate Sprite towards another sprite
I have a Sprite class like this:

```
class Sprite
{
  double rotation ; // in degrees 0-360
  double x;
  double y;
}

```

I'd like to have one sprite to rotate to another point with a constant rotation rate, the sprite should not rotate directly but mor like "rotate more left, rotate more right"  The reason for this is that I want to implement a homing lethargic missile.

Someone knows the math behind this? :)

# Answer
The steps required are;

1. Calculate velocity based on the speed and the current direction of travel.
2. Add velocity to position.
3. Calculate difference between direction of travel and direction to target.
4. Add the angle to the rotation of the missile.

If the `Sprite` class is defined as;

```
public static class Sprite {
    public double rotation;
    public double x;
    public double y;

    public Sprite(double rotation, double x, double y) {
        this.rotation = rotation;
        this.x = x;
        this.y = y;
    }
}

```

The the logic could look something like this;

```
    Sprite missile = new Sprite(0, 0, 0);
    Sprite target = new Sprite(0, 100, 100);

    double missileSpeed = 1.0f; // in units/s
    double missileRotationSpeed = 1.0f; // in degrees/s

    // This loops simulates the time running up to 100 seconds, extract the calculations as you see fit
    for(double t = 0; t < 100; t += 0.1f) {
        // First, calculate new position based on direction
        double vx = Math.cos(Math.toRadians(missile.rotation));
        double vy = Math.sin(Math.toRadians(missile.rotation));
        double vl = Math.sqrt(vx*vx + vy*vy); // normalize the velocity

        // Add the velocity to the old position to get the new position
        missile.x += (vx /vl) * missileSpeed * t;
        missile.y += (vy /vl) * missileSpeed * t;

        // Second, calculate the difference in direction compared to the direction to the target
        double dm2tx = target.x - missile.x; // This is the direction from missile to target
        double dm2ty = target.y - missile.y;
        double dm2tl = Math.sqrt(dm2tx*dm2tx + dm2ty*dm2ty); // Need the length of the vector to normalize

        // angle is signed difference between direction of travel and direction to target
        double angle = Math.toDegrees(Math.atan2(dm2ty / dm2tl, dm2tx / dm2tl) - Math.atan2(vy / vl, vx / vl));

        // Snap the angle to the rotation speed
        if (angle < 0)
            angle = Math.max(-missileRotationSpeed, angle);
        else
            angle = Math.min(missileRotationSpeed, angle);

        missile.rotation += angle * t;
    }

```

As a side note; you really should look into using some sort of **Vector** class to represent the coordinates, all of this logic would compress down to a few lines if you had that.
> 1 votes

# Answer
We can achieve this through trigonometry.

Angle calculation (pseudo code):

```
public double calculateAngle(double yourX, double yourY, double targetX, double targetY) {
    double distanceX = yourX - targetX;
    double distanceY = yourY - targetY;
    return Math.toDegrees(atan2(distanceY, distanceX));
    //For radians just remove 'Math.toDegrees()' around 'atan2(distanceY, distanceX)'.
}

```

then you just type this where you update your object:

```
if(rotation < calculateAngle(yourX, yourY, targetX, targetY))
    rotation += calculateAngle(yourX, yourY, targetX, targetY)/someNumber;
else if(rotation > calculateAngle(yourX, yourY, targetX, targetY))
    rotation -= calculateAngle(yourX, yourY, targetX, targetY)/someNumber;
// the bigger 'someNumber' is the less you rotate every time step.

```
> 1 votes

# Answer
I'm not entirely sure I get what you are asking, but here goes.

Mathematically all rotations happen around the origin. So if you want to rotate something around a different point, you'd move it so that the difference from the origin is the same as it would be from that point and then moving it back by the same amount.

Now I think what you are asking is how to rotate one point smoothly so that it ends up on another specific point. Let's call the first point **a** and the second point **b**.

You first need to pick a point that has the same distance from both of them. If you are in 2D you can pick any point like this:

```
//t is some arbitrary value
x=(a.x+b.x)/2+t*(b.y-a.y);
y=(a.y+b.y)/2-t*(b.x-a.x);
p=new Vector(x,y);

```

In 3D it's slightly more complicated, but you can always find a plane that goes through both points and treat it like it's a 2D problem.

Now if you have your point **p** that you want to rotate around, you need to figure out the angles here. That's where the atan2 function is super helpful. It tells you the angle that a 2d vector has relative to the positive x axis.

So you get:

```
startAngle = atan2(a-p);
endAngle = atan2(b-p);

```

Now you can smoothly rotate from a to b. (Note that you will always rotate counter clockwise if you do this naively, so check if clockwise is faster)

Be advised that you want to figure out how fast to rotate depending on the length of the ark. So you basically want to divide your rotation speed by 2\*pi\*length(a-p).

Now with all that being said:
If you want to make tracking rockets this is a bad way to go about it.
I think what you actually want is to shoot the tracking rocket in a direction that is slightly off target and let it slowly correct it's path. Potentially allow it to change it's direction faster over time or something. That way your rocket will react much more naturally to for example an enemy spaceship moving after it's been fired instead of looking like it's been glued to an invisible ark attached to the spaceship.
> 0 votes

# Answer
Calculate the angle between the first and the second sprite using trigonometry, then modify the first sprite's angle according to the angle you got.

To calculate the angle between two points, you need to have the distance in the x and y axis between them. x1 and y1 are the positions of the first sprite, x2 and y2 are for the second second sprite:

```
x = x2 - x1
y = y2 - y1

angle = atan2(y, x) //The correct order is y, x, don't mix them up
/*
Also, it's very important, to use atan2, you could use atan, but then,
it wouldn't return the correct angle, and you would need to handle -x and -y
values differently as x and y values.
*/

```

After you got the angle you just do

```
if (angle % (2 * Math.PI) < currentAngle) {
    currentAngle -= 2 * Math.PI / 180;  //Rotates the object with 2 degrees
} else if (angle % (2 * Math.PI) > currentAngle) {
    currentAngle += 2 * Math.PI / 180;
}

```

I do here `angle % (2 * Math.PI)`, so if the angle is 540, it wouldn't turn in the wrong direction, if the angle between the sprites is 190.

Hope I helped.

BTW.: If you use degrees instead of radians, then always convert the angle to degrees, before you use it. Math.atan2 returns the angle in radians
> 0 votes

---
Tags: rotation
---


# Question
Title: assigning script to dynamically created button
I have a script `main.cs` which creates a prefabricated button based on this SO post. I thought `btnController.cs` was providing the methods for the `Button` created in `main.cs`? Why would it have a casting issue?

Error

```
Assets/scripts/main.cs(21,51): error CS0030: Cannot convert type `UnityEngine.UI.Button' to `btnController'

```

main.cs

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

public class main : MonoBehaviour {

    public Button myButtonPrefab;

    // Use this for initialization
    void Start () {
        createButton ("minion");
    }

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

    }

    //this is giving a button prefab all the methods from the class btnController
    void createButton(string name){
        btnController b = ((btnController)Instantiate(myButtonPrefab));
        b.Setup(name,0);
    }
}

```

btnController.cs

```
using UnityEngine;
using System.Collections;

public class btnController : MonoBehaviour {
    string name="";
    int value=0;

    public void Setup(string n, int v){
        name = n;
        value = v;
    }

    void OnClick(){
        Debug.Log("btn clicked");
    }
}

```

# Answer
Instantiate will always give you an object. The better way to do that is first convert it in GameObject then access your script from there.

```
GameObject go = Instantiate (myButtonPrefab) as GameObject;
btnController bc = go.GetComponent<btnController>();
bc.Setup(name,0);

```

It is for when your prefab has already btnController attached.

If you want to add script, do that as,

```
btnController bc = go.AddComponent<btnController>();
bc.Setup(name,0);

```
> 1 votes

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


# Question
Title: How to get dynamic RigidBody rotation/tilt on uneven platform?
I have a rigid body with PolygonCollider2D which has some complex circular shape and I'm using uneven platform.

Im using Following code to move the object forward

```
CharacterRigidBody.velocity = new Vector2 (speed, CharacterRigidBody.velocity.y);

```

**Problem :** The rigid body keeps on rotating when it moves forward.

I want the character to move without rotation on asymmetrical platform(above).But i don't want to freeze rotation because i want the character to tilt when climbing or decending platform.

My RigidBody2D config(I'm using unity 5.1.2)

Can collider do anything with this problem?

# Answer
It you look at the `Rigidbody` or (`Rigidbody2D`) in the inspector under Constraints \> Freeze Rotation you will see a checkbox for each applicable axis. These checkboxes will stop the physics engine from applying any rotation about that axis.

---

Now that we have stopped the physics engine from managing the rotation we can control it ourselves by manipulating either `Rigidbody.rotation` or `Rigidbody2D.rotation`.

---

A `Raycast` can be used to do a quick search for any colliders below the player. `RaycastHit.normal` can then be examined to determine the slope of the collider.

Here is a sample implementation:

```
void FixedUpdate()
{
    // my test sprites were sometimes misaligned
    const float standardRotation = 90f;

    // we want to ignore any colliders more distant than this
    const float rayDistance = 1f;

    // default angle
    float angle = standardRotation;

    // do we have any ground under us?
    RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down, rayDistance);
    if (hit)
    {
        // what is the angle of the ground?
        angle = Mathf.Atan2(hit.normal.y, hit.normal.x) * Mathf.Rad2Deg + standardRotation;
    }

    // set our rotation to this angle
    _rigidbody2d.rotation = angle;
}

```
> 2 votes

---
Tags: unity, physics, rigidbody
---


# Question
Title: Send Messages in Update Function Button UI Unity 5
I've been working on a project where i need to fulfill the following behaviors:

1) when clicking anywhere in the screen the character should do something

2) there are some buttons so except when you click a UI Button (which is the pause button in this case )you should move.

So, the problem is since the character behavior is in the Update Function when the player clicks on the pause button unity executes first the Update function, moves the character and pauses after that.

Is there any way to pause tell Unity to execute first the OnClick function inside the UI Button than the Update function?

What i tried was this but it didn't work:

1)do 2 booleans click1,click2;

2)click1 equals true when we click anywhere in the screen

3)click2 equals true when we click on the UI Button

4)then i do something like this so unity should wait 1 frame before executing the movement when click1 == true && click2 == false, we execute the behavior else that means we hit the UI button.

This is how it looks in actual code

```
void Update()
{
    if (platform == RuntimePlatform.WindowsEditor || platform == RuntimePlatform.WindowsPlayer)
                {
                    Debug.Log("1");
                    if (v_click1 == true && v_click2 == false)
                    {
                        if (v_inGround)
                            v_changeGravity = ChangeGravity();
                        Debug.Log("2");

                        v_click1 = false;//reset the value
                    }
                    if (Input.GetMouseButtonDown(0))
                    {
                        Debug.Log("3");

                       v_click1 = true;
                    }
                }
}

```

As you can see i have logged some numbers and Number 4 is not there but it displays when Onclick function sends the message from the UI Button.

The order this is taking is the following:

1

3 we detect a click which is in the button but we dont know that

2 we do the behavior(movement)

4 the function for pause gets called...

So, this is basically the problem is there any way to do this or should i just try not using the UI?

if the question is too confusing i will try to rephrase it haha.

Thanks!!

# Answer
You can put an empty button (button without sprite) in background of screen size and ui buttons above that.
> 2 votes

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


# Question
Title: Can Soomla directories be safely moved one directory down in Unity?
I'm integrating in-app purchases in my game. To do so, I chose to use Soomla (http:soom.la) asset. I use the free version registering for the `grow` bundle. I've downloaded a `unitypackage` named `unity3d-grow-spend` from my `grow` web console.

When I'm going to import the `unitypackage` I find that it wants to import things in a variety of top-level directories, like:

```
/GROW/*
/Plugins/Android/*
/Plugins/GROW/*
/Plugins/iOS/*
/Plugins/Soomla/*
/Plugins/WP8/*
/Soomla/*
/WebPlayerTemplates/SoomlaConfig/*

```

All this installs inside my `/Assets` directory.

The thing is that in my assets I only have

```
/Assets/Scenes
/Assets/Plugins

```

and I do not want pollution in there.

**Question:**

Is it safe to move `/Assets/GROW` into `/Assets/Vendor/GROW` and move `Soomla` and `WebPlayerTemplates` also into the `Vendor` directory?

Or doing that movement some in-app purchases mechanism will fail?

This would result in having only

```
/Assets/Scenes
/Assets/Plugins
/Assets/Vendor

```

in the top-level, which is rather nice.

# Answer
Yea, you can safely replace folders and keeping in mind about the Special Folders Name. Other than that you can play around with.
> 1 votes

---
Tags: unity, architecture, asset-management, in-app-purchase, soomla
---


title: How to add images?

text:
# Question
Title: How to add images?
I was adding images after reading in the documentation:

> This means that if you generate a 200x200 image for xhdpi devices, you should generate the same resource in 150x150 for hdpi, 100x100 for mdpi and finally a 75x75 image for ldpi devices.

So should my images in XHDPI be `200x200` pixels, my images in HDPI be `150x150` pixels, my images in MDPI be `100x100`, and my images in LDPI be `75x75`? After reading the documentation, that is what I thought, but when I came across this page:

https://stackoverflow.com/questions/19875158/android-background-image-size-in-pixel

The answers state to use different pixeol amounts for the different directories. I am very confused now on what to do. Here is what I have here right now, please tell me if I am doing this correct:

So basically, I spent the past 4-5 hours re-sizing lots of my images to the sizes in those folders. Now I'm thinking...did I even re-size them correctly? Is it supposed to be 100x100 for mdpi? I really need to use these images for my 2d game.

**Basically, I just want to know if the directories are supposed to have that many pixels each. Because the question I linked says otherwise.**

Thanks so much,

Ruchir

# Answer
Don't get caught up in the exact numbers used in the example. Those are not the main point. It's how they are relative to each other. You see that xhdpi 200x200 is twice as big as mdpi 100x100. Notice the **if** in the example.

List of densities:

* xxhdpi: 3.0
* xhdpi: 2.0
* hdpi: 1.5
* mdpi: 1.0 (baseline)
* ldpi: 0.75

Sample example but with different numbers:

> This means that if you generate a 512x512 image for xhdpi devices, you should generate the same resource in 384x384 for hdpi, 256x256 for mdpi and finally a 192x192 image for ldpi devices.

* 512 = 256 * 2
* 384 = 256 * 1.5
* 256 = 256 * 1
* 192 = 256 * 0.75

So just figure out whatever size you want in pixels for whatever display density your phone is, and then calculate the size of any other densities from the multiplier above. If a 90x90 images looks good on your hdpi phone, then use that on hdpi and calculate the others and re-size the image. E.g. xhdpi would be 120x120 in this case.
> 1 votes

---
Tags: java, 2d, android, optimization, image
---


# Question
Title: How could we use trigonometry for moving around a 3D World?
Well I have a question about geometry and 3-Dimensional player movement in general. I'm using Java, OpenGL and LWJGL.

This is basically what I got:

* *currentFrontSpeed:* Is a float that contains the speed of the Player.
* ***player.*** *increasePosition:* Just adds the current Position of the Player to the value that is given on the X, Y and Z axis.

```
//The point we want to go: Forwards(+) Backwards(-). getFrameTimeSeconds
//just adjust the speed depending of the speed of the computer.

float distanceFront = currentFrontSpeed * DisplayManager.getFrameTimeSeconds();

//Distance of Movement
float fx = (float) (distanceFront * Math.sin(Math.toRadians(player.getRotY())));
float fz = (float) (distanceFront * Math.cos(Math.toRadians(player.getRotY())));

//This just increase the position of the player (x,y,z)
player.increasePosition(fx, 0, fz);

```

Another thing that I didn't explained is that the Player is always looking at the same position as the camera (if the camera turns to the right, the player would also turn to the right. Like Maincraft). That's why I use the Y-Axis to move.

The problem is that my player can only move forwards and backwards (if *currentFrontSpeed* is positive, my player will move FORWARDS, and if is negative BACKWARDS). And the only form to go to a place that is to the right is to move the Camera to the right and the press UP to go FORWARDS.

I've tried to achieve this doing this:

```
   //The same as above, the speed of the player this time Right(+) and Left(-)
    float distanceSides = currentSideSpeed * DisplayManager.getFrameTimeSeconds();

    float sx = (float) (distanceSides * Math.cos(Math.toRadians(player.getRotY())));
    float sz = (float) (distanceSides * Math.sin(Math.toRadians(player.getRotY())));

    //I just add the "horizontal" speed to the "vertical" one
    player.increasePosition(fx + sx, 0, fz + sz);

```

Of course this doesn't work good: if the player Y-rotation is 0, the player moves to the right and to the left perfectly; but for example, if the player rotation is 90 (looking at the right from the original position), moving up or moving to the right would take us to the same position (because is the "right" from the original position with the Y-axis 0).

I don't know if I should use another trigonometric function or add the sx and the sz to another value in the X, Y and Z axis.

**EDITED**

I've just edited and gived some information because of the bad explaining I did. Also this is one of my first long-writed post.

Thanks for helping!

# Answer
If I understand you correctly you are having problems going left and right. First off `currentFrontSpeed` should never be negative since it's speed not velocity. Speed is a scalar and as such should not capture any direction and will *always* be positive.

To move in different directions you should modify the angle instead where for example right is -90 from forward and left is +90 from forward.

Here is one example. You might want to do it differently but hopefully you get the idea.

```
float distanceFront = currentFrontSpeed * DisplayManager.getFrameTimeSeconds();
float speed;
float angleY;

// A direction key is being pressed
if (KEY_FORWARD) {
    angleY = player.getRotY();
    speed = distanceFront;
}
if (KEY_RIGHT) {
    angleY = player.getRotY() - 90;
    speed = distanceFront;
}
if (KEY_LEFT) {
    angleY = player.getRotY() + 90;
    speed = distanceFront;
}
if (KEY_BACKWARD) {
    angleY = player.getRotY() + 180;
    speed = distanceFront;
}

float fx = (float) (speed * Math.sin(Math.toRadians(angleY)));
float fz = (float) (speed * Math.cos(Math.toRadians(angleY)));

player.increasePosition(fx, 0, fz);

```
> 1 votes

---
Tags: opengl, java, 3d, lwjgl, geometry
---


# Question
Title: Increasing the rotation angle on a quaternion makes the rotation stop at a certain angle
I'm using the following code to change the rotation of an object:

```
Quaternion rot = getRotation();
setRotation(make_quaternion_axis_angle(rot.v,rotationSpeed*dt)*rot)

```

This code works as expected until a certain angle where it suddenly stops.

Why does it stop?

# Answer
I realized why this happens. When the quaternion is made, the axis is multiplied by sinus of the half angle. When the rotation gets to 360 that value will be zero so the axis information will be lost.
> 1 votes

# Answer
Well given 360-degree angles. Then a 360-degree rotation makes a full turn and as such is equivalent to 0-degrees or simply no rotation.
> 0 votes

---
Tags: rotation, quaternion
---


# Question
Title: SSAO issue - surfaces darken based on camera angle
I have a strange issue in my engine where my SSAO effect will extremely darken or lighten based on my camera angle:

In that example, I'm just outputting the ssao texture to the screen. The texture is stored as a single (red) 8 bit channel.

I've been following a few tutorials here and there for building my SSAO shader, primarily this and that, so my code is pretty much identical.

---

I've done some research beforehand, however I couldn't really find anything that matched my error.

The only thing I found was that some people who were doing SSAO do this thing where they offsetted their scene's normals before saving it:

> normalTexture = normal * 2.0f - 1.0f;

And then when needing to access the scene's normals, they revert the offset such as:

> vec3 normal = texture2D(normalTexture) * 0.5f + 0.5f;

This type of thing I can almost understand, but I've never come across this is any tutorial that I've been following for any of the shading I've been doing up to this point. Further, the normals are normalized so much anyways. Regardless, if I do this or not, surfaces running parallel to different axes do the exact same thing anyways in my SSAO shader.

---

During my geometry pass, where I fill my GBuffer with the current frame's textures, this is how I calculate the normals:

```
...
layout (location = 2) out vec3 NormalOut;
...

void main()
{
    vec3 Normal        = normalize(Normal0);  // The geometry's physical normal, in world space
    vec3 Tangent       = normalize(Tangent0); // The geometry's physical tangent, in world space
    Tangent            = (Tangent - dot(Tangent, Normal) * Normal);

    vec3 Bitangent     = cross(Tangent, Normal);
    vec3 BumpMapNormal = texture(NormalTexture, TexCoord0.xy).xyz; // The bumpmap texture for the skin of the object
    BumpMapNormal      = (BumpMapNormal * 2.0 - 1.0);
    mat3 TBN           = mat3(Tangent, Bitangent, Normal);
    vec3 NormalFinal   = normalize((TBN * BumpMapNormal));
    NormalOut          = normalize(0.5 * NormalFinal + 0.5); // Final normal
}

```

My SSAO fragment shader:

```
in vec2 TexCoord;
layout (location = 0) out float FragColor;

uniform sampler2D ViewPosMap;
uniform sampler2D NormalMap;
uniform sampler2D NoiseMap;

const int MAX_KERNEL_SIZE = 128;
uniform vec3 Kernel[MAX_KERNEL_SIZE];
uniform int USABLE_KERNEL_SIZE;

uniform vec2 NoiseScale;
uniform float SampleRadius;
uniform mat4 pMatrix;

void main()
{
    vec3 Pos = texture(ViewPosMap, TexCoord).xyz;
    vec3 Normal = texture(NormalMap, TexCoord).xyz * 2.0 - 1.0 ;
    vec3 RandomVec = texture(NoiseMap, TexCoord * NoiseScale).xyz;
    vec3 Tangent = normalize(RandomVec - Normal * dot(RandomVec, Normal));
    vec3 Bitangent = cross(Normal, Tangent);
    mat3 TBN = mat3(Tangent, Bitangent, Normal);

    float occlusion = 0.0;
    for (int i = 0 ; i < USABLE_KERNEL_SIZE ; i++) {
        vec3 sample = TBN * Kernel[i]; // From tangent to view-space
        sample = Pos + sample * SampleRadius;

        // project sample position (to sample texture) (to get position on screen/texture)
        vec4 offset = vec4(sample, 1.0);
        offset = pMatrix * offset; // from view to clip-space
        offset.xyz /= offset.w; // perspective divide
        offset.xyz = offset.xyz * 0.5 + 0.5; // transform to range 0.0 - 1.0

        // get sample depth
        float sampleDepth = texture(ViewPosMap, offset.xy).z; // Get depth value of kernel sample

        // range check & accumulate
        float rangeCheck = smoothstep(0.0, 1.0, SampleRadius / abs(Pos.z - sampleDepth));
        occlusion += (sampleDepth >= sample.z ? 1.0 : 0.0) * rangeCheck;
    }

    occlusion =  1.0 - (occlusion / USABLE_KERNEL_SIZE);
    FragColor = occlusion;
}

```

And here is a sample of what the normals look like in the scene:

---

I feel like I'm banging my head against the wall here, I'm not quite sure why I'm getting the results that I am. If anyone wants any further information, I'll post it as soon as I can.

---

The solution provided in this thread was exactly what I needed. I created an additional GBuffer texture, one which held the scene's normals but in viewspace. I then sent this texture to my ssao shader, and it corrected the issue I was having.

# Answer
To me it looks very much like your issue here is that you are mixing world and viewspace or something similiar.

Now your GBuffer normals look like they might be in viewspace in that picture, but the code in your geometry pass definitely doesn't transform them from world to view space.

If they are in world space then your NBT matrix is basically oriented incorrectly by exactly the rotation of your view matrix, so your kernel will end up being rotated into or out of the wall depending on where you are looking. And that would give you exactly the result you are seeing.

Hope this helps.

(Minor sidenote: you are only interested in offset.xy, so after projecting you can just use the two rather than offset.xyz)
> 4 votes

---
Tags: opengl, deferred-rendering, normals, ssao, ambient-occlusion
---


# Question
Title: How to make Frame Independent Timer Clock
I want to make a frame Independent Timer that it work consistently across different computer configuration.

# Answer
```
// ORIGINAL TIMER COUNTDOWN IN SECONDS
const float TIMER = 3;

// TIMER CURRENT TIME
float Timer;

// RUNS ON EACH FRAME
void Update()
{
    // SUBTRACT DELTA TIME FROM CURRENT TIME
    Timer -= Time.deltaTime;

    // TIMER WENT OFF
    if (Timer <= 0)
    {
        //DO SOMETHING
        Foo();

        // RESET TIMER
        Timer = TIMER;
    }
}

```
> 2 votes

---
Tags: unity, timer
---


# Question
Title: How to make difficulty progression in my endless-runner game?
I want to further develop this game I created for a game jam. Currently spiders chase squirrels with the same speed. Tree branches are randomly generated. Even if you perfectly time your jumps the spiders will eventually catch you. Squirrels are able to pick up randomly generated acorns to throw at the spiders knocking them back.

I want to implement some kind of difficulty progression. Any ideas are appreciated. My main idea is to accelerate the spiders, but the squirrels can't jump any quicker because of physics. They are propelled by one of two jump strengths, and gravity.

**The question is**: Would it be a good idea to increase the jump high and/or gravity accordingly to the speed of the spiders? (allowing the player to continue to evade the spiders)

Please take into consideration that other obstacles will be added; for example a bat attacking the squirrel from a hole in the tree trunk.

# Answer
Increasing how fast they can jump is only a temporary solution. Eventually, the speed will get to be too fast for a person to physically do. Infinite runners get their difficulty from endurance (how far can you get before you mess up?). Increasing the speed makes this more challenging, but there should be a cap on it and let endurance be the challenge from there.
> 5 votes

# Answer
Depends how you want the game to work.

Guaranteed capture: The enemy accelerates so only perfect timing, and luck of more power ups, or bonuses can get you further. This can severely diminish replay value.

Pure obstetrical avoidance (Probably won't work for this game): The enemy remains at a constant distance behind the player. When the player hits an obstetrical the distance is decreased. Perfect play for a certain length of time may increase the gap again.

Obstetrical avoidance, and independent enemy speed: The enemy moves at a constant speed, and have a maximum distance between them and the player; in the case of excellent player skill and/or power ups that increase player speed.
> 1 votes

---
Tags: game-design, balance, casual-games
---


# Question
Title: "Saving..." dialog isn't shown until after the saving is complete
I have implemented serialization/de-serialization process in my Unity game where I save/load data from/to XML file.

During the serialization, my game isn't responding until the serialization is finished and this is OK.

What is wrong is that before I call the serialization/de-serialization, I want to show saving/loading panel and show log process, but can't: this panel and all the log information show up only after the serialization/de-serialization is finished.

What I have verified and tried:

1. The panels hierarchy is correct
2. During serialization/de-serialization, no error occur
3. Panels are assigned manually to specified variables
4. If I comment out the save/load calls and leave only the panel, then the panel is shown
5. I have also tried to put the thread to `sleep` but still, nothing happens.

Can anybody can help me? Because I really don't know why this is happening like this.

Here is an snippet of my code:

```
public void SaveGameClick() {
  SavingPanel.gameObject.SetActive(true); // if I leave only this line and the other line
                                          // commenting the panel shows perfectly
  Debug.Log("Saving..."); // this Saving word shown only when the _savegame.Save() method
                          // finished
  if(_saveGame.Save("save.xml", Seed)) {
    Debug.Log("Saved");
    CyberTeamManagerSubMenu.gameObject.SetActive(false);
    _isShowCyberTeamManagerSubMenu = false;
    SavingPanel.gameObject.SetActive(false);
  } else {
    Debug.Log("Save Error");
    SavingPanel.gameObject.SetActive(false);
  }
}

```

# Answer
> 1 votes
Unity runs most scripts single-threaded. That means the same thread that's running your script is doing your rendering.

So, **a new frame isn't rendered until the engine finishes running every script** \- including your saving script.

In this case, your first line marks the saving panel to be visible in the *next rendered frame*:

```
SavingPanel.gameObject.SetActive(true);

```

But then you start serializing immediately. Since we haven't returned from this click function, the engine hasn't had a chance to *draw* that frame before it hits this line:

```
if(_saveGame.Save("save.xml", Seed))

```

What you can do instead is to queue-up your saving, so it starts after the frame has been rendered, or on the start of the next frame's update:

```
public void SaveGameClick() {
  SavingPanel.gameObject.SetActive(true);

  StartCoroutine(QueuedSave());
}

IEnumerator QueuedSave() {
  // Let the game display a frame before we try to save.
  yield return new WaitForEndOfFrame();

  // Now we're ready to save.
  if(_saveGame.Save("save.xml", Seed)) {
    CyberTeamManagerSubMenu.gameObject.SetActive(false);
    _isShowCyberTeamManagerSubMenu = false;
  } else {
    Debug.Log("Save Error");
  }

  SavingPanel.gameObject.SetActive(false);
}

```

Note that this method still won't let you show incremental save progress, or even animate a spinner while the game saves. We're still locking up the main thread and preventing new frames from rendering for the whole save process, we're just starting it one frame later now.

If you want to ensure that your game can remain responsive during heavy work like this, you'll want to either...

* break your saving coroutine into bite-sized pieces or a loop that can yield back to the main thread periodically so more frames can be drawn, or...
* start a separate thread to do the saving (just make sure that nothing important is able to change state during the save, or your saved data might end up inconsistent).

---
Tags: c#, unity, savegame, serialization
---


# Question
Title: how can I access to new function via getcomponent?
```
    using UnityEngine;
    using System.Collections;
    using AssemblyCSharp.portal.www.com;

    public class Game5_Player: MonoBehaviour
    {
//string Logo;
        void Start ()
        {
            func webservice = new func ();//I should use new func(); so how should I use public func?
            //Logo= webservice.getCompanyLogo ();//this work correctly.I can get component Logo In another script but I want know how can I getcomponent my function.
        }
    }

```

why have I error when use Getcomponent In below? other script:

```
using UnityEngine;
using System.Collections;
using AssemblyCSharp.portal.www.com;

public class MasterRange : MonoBehaviour {
        string Logo;
        void Start () {
        Game5_Player game5_Player = GameObject.FindGameObjectWithTag("Player").GetComponent<Game5_Player> ();
            Logo = game5_Player.webservice.getCompanyLogo;
        }
    }

```

error:

```
 Assets/MasterRange.cs(21,34): error CS0103: The name `webservice' does not exist in the current context

```

---

Is there any way to have a public new function?

```
using UnityEngine;
using System.Collections;
using AssemblyCSharp.portal.www.com;

public class ScriptA : MonoBehaviour {
string Logo;

public func webservice = new func();

void Start ()
{
    webservice();
    Logo = webservice.getCompanyLogo();
    }
}

```

# Answer
> 4 votes
In your first example, `webservice` is declared as a local variable within the scope of the `Game5_Player`'s `Start()` method:

```
public class Game5_Player: MonoBehaviour
{
    void Start ()
    {
        func webservice = new func ();
    }
}

```

This means that only code inside the `Start()` method can access `webservice`, and when `Start()` returns, `webservice` will generally be cleaned up/garbage collected, unless you've stored a reference to it elsewhere.

What you want to do is declare `webservice` in a longer-lived scope, like as a member variable:

```
public func webservice;  // Declared as a member variable.

void Start ()
{
    webservice = new func (); // Initialized in Start, Awake, or OnEnable.
}

```

Now anything with access to your `Game5_Player` instance can read OR overwrite `webservice`.

If you want to exert more control over how the variable can be used, you can do something like...

```
public func webservice { get; private set; }

```

This uses an auto-implemented property to ensure outside code can only get the value of `webservice`, but can't set it.

You could also declare your own getter function to initialize `webservice` the first time it's requested, something like...

```
private func _webservice; // Private backing member variable.
public func webservice    // Public property.
{
    get
    {
        if(_webservice == null)
           _webservice = new func(); // Initialize.

        return _webservice;
    }
}

void Start()
{
     // We can just use webservice directly,
     // knowing it will be initialized first if necessary.
     logo = webservice.getCompanyLogo();
}

```

This way even if another script tries to read `webservice` before `Game5_Player` has run its `Start()` method, it will get an initialized version back.

# Answer
> 0 votes
thank you DMGregory I can solve my problem:

```
using UnityEngine;
using System.Collections;
using AssemblyCSharp.portal.www.com;

public class ScriptA : MonoBehaviour {
    private crm1 _webservice; // Private backing member variable.
    public crm1 webservice    // Public property.
    {
        get
        {
            if(_webservice == null)
                _webservice = new crm1(); // Initialize.

            return _webservice;
        }
    }
}

```

other script:

```
using UnityEngine;
using System.Collections;
using AssemblyCSharp.portal.www.com;

public class ScriptB : MonoBehaviour {
    public string Logo;

    void Start(){
        ScriptA scripta = GameObject.FindGameObjectWithTag("Player").GetComponent<ScriptA> ();
        Logo = scripta.webservice.getCompanyLogo();
    }
}

```

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


title: Ball passing through box collider

text:
# Question
Title: Ball passing through box collider
My ball which has a circle collider 2D component occasionally passes through my box collider2D object. Both objects have rigidbodies attached. I have set a high mass for my box collider and a small mass for my ball. Strangely enough, it doesnt pass through every time (maybe due to varying velocity). Basically i am making pong.

# Answer
> 1 votes
This is because the ball -at high velovity- will be before the box in one frame and behind the box in the next: so no collision has occured.

To fix this make sure the collision is continious or interpolated.

Set your collision mode to DynamicContinious for high velocity objects or Continious for fast objects. This does have a bit of an impact on performance if you have a lot of objects so just apply it to objects that move fast.

See: http://docs.unity3d.com/ScriptReference/CollisionDetectionMode.html

# Answer
> -1 votes
It turns out all i had to do was increase the thickness of the box collider.

---
Tags: unity, collision-detection
---


# Question
Title: At which school levels do you learn to make games form scratch?
By which "school levels" I mean: high school, college etc....

---

So, I've just choose a high school in Sweden which has a game programming line.

I read some on their webpage and what you will learn there is Unity3D scripting. (and all other things, math, english, swedish etc)

My question is: At what "level" of school do you learn to make games from scratch?

And by school "level" I mean, do you learn it in high school, college or something else?...

Does it maybe change depending on what school you go to?

# Answer
You don't need to follow a game-programming programme to learn how to program games. It helps only on *some* aspects.

> Personal experience
>
> I've started to learn programming in high-school. We were free to chose the end-of-year project we had to do, and my friend and I decided to do a game. It was in VB6, the language we had learned the whole year.
>
> Then I studied computer science in college, then did a bachelor degree at university in computer science/software engineering. Then I got hired by a game development company and learned *a lot* while at work.

So to answer your question, *you can learn game development at **any** school level*. It depends on you, your motivation, and the school.

But my suggestion is: get a solid base in general programming *first*, then learn how to make games. Some school programmes will sacrifice crucial general programming concepts to make room for the game oriented stuff. You're better starting off with a solid base and transfer this knowledge to game dev, than jumping right away to the "cool stuff" but lacking some important concepts.

*And this is without saying that **some** schools just offer 'game dev' programmes just because it's cool and trendy, but in the end, they teach you bad concepts or just not enough of it and you end up paying the extra fee for bad quality teaching.*

P.S. You'll learn a lot by doing. Learn programming at school by day, and try to apply that by creating a game by night.
> 2 votes

---
Tags: software-engineering, education
---


# Question
Title: how to follow(center) a box inside canvas element
If inside a canvas I draw a box, and the I add arrows to move it, the box will eventually be out of my reach since it goes out the border and I **cant** see it. How could I follow the box so that it is always in the center?

# Answer
> 0 votes
Is simple, you have to use a simple "camara" system and make the cube or item or player be the center of it, so...done

Here's an example of a camera in pure javascript

Use arrows to move the camera

```
var map = [];

for(var t = 0; t < 100; t++){
  var r = [];
  for(var tt = 0; tt < 100; tt++)
    r.push(Math.floor(Math.random()*4));
  map.push(r);
}

var color = ["blue","red","orange","green"];

var canvas = document.getElementById("canvas");
canvas.height = 200;
canvas.width = 200;
var ctx = canvas.getContext("2d");

var camera = {x:0,y:0};
var fov = 5;
var ts = canvas.height/fov;

Draw();

document.addEventListener("keydown", move);

function move(e){
  e.preventDefault();

  switch(e.keyCode){
    case 38:
      if(camera.y-1 >= 0 && camera.y-1 <= 100)
      camera.y--;
    break;
    case 39:
      if(camera.x+1 >= 0 && camera.x+1 <= 100)
      camera.x++;
    break;
    case 40:
      if(camera.y+1 >= 0 && camera.y+1 <= 100)
      camera.y++;
    break;
    case 37:
      if(camera.x-1 >= 0 && camera.x-1 <= 100)
      camera.x--;
    break;
  }
  Draw();
}

function Draw(){
  for(var x = 0; x < fov; x++){
    for(var y = 0; y < fov; y++){
        var rpos = {
          x: Math.round(camera.x - fov/2) +x,
          y: Math.round(camera.y - fov/2) +y
        };

        ctx.save();

        try {
          var tile = map[rpos.x][rpos.y];
          ctx.fillStyle = color[tile];
          ctx.fillRect(x*ts, y*ts, ts, ts);
        } catch(e) {
          ctx.fillStyle = "black";
          ctx.fillRect(x*ts, y*ts, ts, ts);
        }
        ctx.restore();
    }
  }
}
```

```
canvas {
    border: 1px solid grey;
  }
```

```
<body>
<canvas id="canvas"></canvas>
  </body>
```

---
Tags: javascript, html-canvas
---


# Question
Title: Preferred option for indicating player's movement choices on a hexagonal grid on touch
I'm building a prototype turn-based game and I'm considering the best approach for user interaction with the game board. It's a hexagonal grid, where the user can select units and move to other cells on the board. The number of steps they can take in a single move is variable and depends on the unit.

I'm aiming this for use ontouch screen devices, so that will exclude hover-based indicators (which make the most sense in terms of interaction).

So, with that limitation, what methods are possible for indicating to the user the amount of cells they can move?

So far, I've come up with these options:

* Allow the user to take their turn and move step by step, highlighting the nearest 1 neighbour cells each time.
* Highlight all possible destination cells:

* Highlight the outer ring of maximum distance:

* Draw a line through the outer-most cells to indicate maximum distance:

Each of these has their own drawbacks. The first, will be done dynamically and will require creating the markers on the fly (not inconceivable) and will also look kind of strange when there are lots of options. The image shows a unit which can move 2 cells and already looks over-crowded.

The second would solve the problem of too many cells being lit up at once. Unfortunately, I'd be worried the user wouldn't understand that they could move to one of the non-highlighted cells within the ring.

The last has the same problem as the second where I'm not sure they'd understand where they can move. It would alleviate the need to create multiple markers and store temporarily as I'd only have to store a single hexagon of varying size.

So, any ideas? Am I over-thinking this one?

NOTE: I've made the images above from this extremely useful site: http://www.redblobgames.com/grids/hexagons/

# Answer
Quite honestly, I think you actually are over-thinking this. It's good to have a well thought-out design, but it's important not to get too hung up on the small details at an early stage. That being said, I think there is a fourth option here that might help you a bit:

As opposed to filling in all hexagons that can be moved to, you can draw an outline around the outside of the hexagons that you can move within. This method immediately shows a fixed border easily setting the distinction between inside and outside of your fixed range. It does add some drawing complexity but it's easy enough to write a simple method of determining this outline.
> 2 votes

---
Tags: game-design, turn-based, user-experience, hexagonal-grid
---


title: transform.Translate only for 10 units?

text:
# Question
Title: transform.Translate only for 10 units?
How can I `transform.Translate (Vector3.up * Time.deltaTime * 2);` a GameObject for 10 units? I mean only make it go up 10 units (10 y units).

# Answer
```
you can move a object 10 units up using
transform.Translate(0.0f, 10.0f, 0.0f);

```

many ways to implement but I wrote this out to get you started

```
float yPos;
float yEnd;
void Start () {
    yPos = this.transform.position.y;
    yEnd = yPos + 10;
}
void Update () {
    if(yPos < yEnd)
    {
        yPos = this.transform.position.y;
        transform.Translate(0.0f, 10.0f * Time.deltaTime, 0.0f);
    }
}

```
> 1 votes

# Answer
Set a variable as your target destination before you start moving, then use Vector3.MoveTowards to gradually move towards your destination.

You'll also want to specify a movement speed.

```
Vector3 targetPosition = transform.position + new Vector3(0, 10, 0);
float movementSpeed = 1f;

void Move () {
    transform.position = Vector3.MoveTowards(transform.position, targetPosition, movementSpeed * Time.deltaTime);
}

```
> 0 votes

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


# Question
Title: Performance differences: one empty GameObject with multiple child objects vs. single GameObject formed by pre-merging the former child objects
Imagine a robot game where robots are made of pre-built blocks. Therefore, each block is a separate GameObject, with one mesh each.

I am trying to understand the conceptual differences behind the following. Is it better performance-wise and memory-wise to have one empty GameObject representing the robot that is the parent of multiple child GameObjects/meshes (i.e. the parts from which the robot is made of), or is it better to transform all into one single joint GameObject/mesh that will be the final robot?

When I mention "understand the concept", I mean understand why each of both options have their downsides in terms of memory allocation for the mesh geometry data and also processing (cpu -\> drawcalls -\> gpu).

# Answer
There is no one size fits all answer to this, as is so often the case.

Generally though, **if you can precompute it, do it**.

If your robot doesn't change all the time, so for example you build it and it stays the same the whole time, then what's the point of calculating all of its parts every frame. But if it does change all the time then obviously you can't get away with making all of it one big object.

You are probably aware that there are tons of things that become computationally more expensive the more objects you have, for example collision detection. So you have an interest to keep the number of game objects low(-ish).

When it comes to rendering, ideally you would want to have a VBO and IBO for your whole robot, so you can push it over to the GPU once and then just reference it forever. If instead you split your robot up into bits you will have to make a draw call for each of the bits. While the amount of drawing that your GPU ends up doing will be the same, the amount of work for your CPU to translate all of those instructions for the GPU will be much higher.

So in most cases treating it as one big object would be better. However there are cases where the other treatment might work better as well.
Computing everything you need to treat your robot as one object is relatively computationally intensive and memory heavy. (Compared to just keeping everything as a collection of blocks) So if you are in a garbage collected environment and want to minimize your memory footprint, if each time a block is changed you have to recalculate the big object it could cause a garbage collection every time and make your game lag for a frame.
> 1 votes

---
Tags: performance, memory-efficiency, gameobject, mesh
---


# Question
Title: LibGDX - How to draw a filled rectangle behind a text?
I'm new in LibGDX and I want to create a grid based game. Every square will have a rectangle and a text and the background color of the rectangles can change during the game.

The problem is when I draw a filled rectangle with `ShapeRenderer`, it always in front of the `BitmapFont`. How can I set the rectangle behind the text?

The code I use to draw the squares:

```
// Draw numbers and rectangles
for (int i = 0; i < map.length; i++) {
    for (int j = 0; j < map[0].length; j++) {
        String value = String.valueOf(map[i][j].getNumber());
        float offset = fontSize/3f;
        Rectangle rect = rects[i][j];

        shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
        shapeRenderer.setColor(150/255f, 150/255f, 150/255f, 1);
        shapeRenderer.rect(rect.x, rect.y, rect.width, rect.height);
        shapeRenderer.end();

        // Draw font
        if (map[i][j].isActive()){
            fontActive.draw(batch, value, rect.x + offset, rect.y + offset);
        } else {
            font.draw(batch, value, rect.x + offset, rect.y + offset);
        }
    }
}

```

Thanks all!

# Answer
> 3 votes
The way I do it is, first the shapeRenderer (begin-end), and then the batcher (begin-end). I'm assuming you're begining the batcher before the shapeRenderer. I think I read somewhere that can cause trouble.

Example:

```
        shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
        shapeRenderer.setColor(80 / 255.0f, 80 / 255.0f, 50 / 255.0f, 1);
        shapeRenderer.rect(0, 0, 160, 160);
        shapeRenderer.end();
        batcher.begin();
        drawText(delta);
        batcher.end();

```

the drawText function uses font.draw to write on-screen.

---
Tags: libgdx
---


# Question
Title: Will scaling images at runtime impact my game's speed?
I have read the android developer guide to working on different screen sizes. My question is, **if I only provide one image in the drawable file, and let android scale it for me, will it impact the overall performance of my app?**

For example, I am simply displaying a red square, and there aren't any details to the square. Should I provide alternative resources, will android's scaling impact my performance as an app on bigger/smaller screens?

# Answer
The issue is due to memory usage, wasted memory bandwidth and/or the time it takes to rescale it to the proper size at load time.

In the case of Android using the 2D UI the image will be scaled once to the proper size at load time but this takes a bit of time and the larger original will be kept in memory if a reference to it is kept.

In the case of direct OpenGL draw calls without mipmaps drawing a large image by scaling it down on the fly forces the GPU to fetch a lot of unused pixel from memory. An image that is twice as big as it needs to be (2x width, 2x height) will take 4x the memory bandwidth.
> 3 votes

---
Tags: java, 2d, android, image, scale
---


# Question
Title: How can I render to texture in single mip-level?
I'm trying to implement Hi-Z Screen-Space Cone-Traced Reflections using Direct3D9. I already know how to render to specific mip-level texture using Direct3D11, but not using Direct3D9.

Has anyone tried the same before?

How would I generate a custom mip-texture using D3D9? Not just switch between two different sized textures from system memory.

Maybe something involving StretchRect functions might work?

# Answer
> 1 votes
Create your mipmapped texture as a rendertarget. Then grab the surfaces of each Mip level you want to render to like this:

`D3DXCreateTexture( device, width, height, numMips, D3DUSAGE_RENDERTARGET, texFormat, D3DPOOL_DEFAULT, &texture );
texture->GetSurfaceLevel( 0, &mipLevel0 );
texture->GetSurfaceLevel( 1, &mipLevel1 );
texture->GetSurfaceLevel( 2, &mipLevel2 );
...`

Then to render to the specified mipmap in the texture use `SetRenderTarget` with the appropriate surface. e.g. `device->SetRenderTarget( 0, mipLevel2 );`

---
Tags: rendering, directx9
---


# Question
Title: example for creating button programmatically
Can someone give me an example of programmatically (not using a prefab) creating a button in Unity 5 using C# that has the following features?

- a text on the button (that I can change)
- an OnClickListener
- attached to a script that will store values for the button and contain the OnClick event handler
- the create method for the button should return a reference to the button so I can modify it at a later point from another script

My attempt was:

main.cs

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

public class main : MonoBehaviour {

    public Canvas c;

    // Use this for initialization
    void Start () {
        createButton ("minion",999);
    }

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

    }

    //this is giving a button prefab all the methods from the class btnController
    void createButton(string name,int val){
        GameObject go =new GameObject();
        go.AddComponent<btnController>();
        go.transform.SetParent (c.transform,false); //add the gameobject to the canvas

        go.AddComponent<Button> ();
        //Button btnChild = go.GetComponent<Button> ();
        //btnChild.GetComponent<Text>().text = "hello";//doesnt work
        //go.GetComponentInChildren<Text>().text = "hello!";

        btnController bc= go.GetComponent<btnController>(); //get reference to script for this button prefab
        bc.Setup(name,val);//set values in this script for the GameObject to hold

        GameObject inst =Instantiate (go);
    }

}

```

btnController.cs

```
using UnityEngine;
using System.Collections;

public class btnController : MonoBehaviour {
    string name="test";
    int value=6;

    //this script is attached to the button prefab. the onClick of the button prefab points to this OnClick method

    public void Setup(string n, int v){
        this.name = n;
        this.value = v;
        //Debug.Log ("in button setup:"+name+" "+value.ToString());
    }

    //OnClick is public so I can set the On Click () function to this method (in the prefab button)
    public void OnClick(){
        Debug.Log("btn clicked: "+this.name+" "+this.value.ToString());
    }
}

```

# Answer
> 1 votes
You are on the right track with creating a GO and adding a component. Instead of adding a custom button and a base button component, you should just extend the UI.Button. This script will hold custom properties, and exposes the 'Button' component in the UI and for scripting.

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

public class ButtonTest : Button, IPointerClickHandler {

    private string _text = "Button Text";
    private int _value = 0;
    private Button baseButton;

    public Action Callback;

    //update button text and stored value
    public string text {
        get{ return _text; }
        set{ GetComponentInChildren<Text>().text = value; _text = value;}
    }

    public int value {
        get{ return _value; }
        set{ _value = value; }
    }

    void Start(){
        //you can expose onClick and assign a listener
        baseButton = GetComponent<Button>();
        if(onClick != null)
        baseButton.onClick = onClick;

        //update label
        baseButton.GetComponentInChildren<Text>().text = text;
    }

    //or you can implement click handler and use 'callback'
    override public void OnPointerClick(PointerEventData ped){
        Debug.Log("clicked button");
        Debug.Log("Label: "+this.text);
        Debug.Log("Value: "+this.value);
        if(Callback != null){
            Callback();
        }
    }
}

```

Then, when you want to use the button in another script:

```
//unique listener
public void DoStuff(){
    Debug.Log("Hello!");
}

//unique callback
public void DoStuff2(){
    Debug.Log("Hello from 2!");
}

// create object and add component
GameObject go = new GameObject();
go.AddComponent<ButtonTest>();

//once you have a reference, you can assign your custom props
ButtonTest myButton = go.GetComponent<ButtonTest>();
myButton.text = "Wow New Text";

//using Listener
myButton.onClick.AddListener( () => { DoStuff2(); } );

//using a callback method
myButton.Callback = DoStuff;

```

You don't need to use the Callback if your using 'onClick' and vice versa. I am just demonstrating two way to get notified of button click that is holding custom properties.

Also, if you want to use 'onClick' instead of a callback, you will need to trigger the base Button click event, with an EventTrigger component.

Then you should get both method calls, and your updated properties:

Hope this helps some.

# Answer
> -1 votes
Unity has a built-in function `GUI.Button` that is exactly what you are asking for. GUI elements are unique in unity though because all must be included in a function you create called `OnGUI()` like so:

```
void OnGUI()
{
    // do stuff
}

```

As stated by the unity documentation, `GUI.Button` at minimum takes in 2 arguments: position (a Rect) and text (a string). The position argument also is the size of the button. You can include other stuff but I'll let you read the documentation for that.

Now, in order to tell if the button has been clicked, you need to put the `GUI.Button` as the condition of an if statement (weird, I know). So for example if I wanted to create a square button I would do the following:

```
void OnGUI()
{
    // Remember Rect parameters are x, y, width, height
    if (GUI.Button(new Rect(50, 50, 100, 100), "Click Me!")
    {
        Debug.Log("Oh yeah it feels so good to be clicked!!!!");
        // Do other stuff like increment a global variable
    }
}

```

Now, I don't believe you can return a reference to the button as it is a function and not a structure, however, you can just have global variables like `buttonText` and `buttonRect` that you use in the function (i.e. `GUI.Button(buttonRect, buttonText)`) and then just change those global variables in another function when you want the button information to change. Also these global variables can just be public if you want to modify them from another script or you could just do some simple encapsulation (that means having `SetButtonText()` and `GetButtonText()` functions).

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


# Question
Title: Get the tile that my mouse pointer is currently over?
I want to get the tile that my cursor is over in my game.

I did some googling though most of the examples we're in other languages/libraries and if they weren't, they didn't work for me because I use a `sf::view`.

---

So, what I currently have is a tile generator which works like this :

**GameScreen.h :**

```
std::vector<sf::Sprite*> tiles;
std::map<std::string, sf::Texture*> textures;

```

**GameScreen.cpp :**

```
void GameScreen::Init()
{
    std::cout << "Loading map" << std::endl;
    textures.insert(std::make_pair("Grass", new sf::Texture()));
    if (!textures["Grass"]->loadFromFile("Res/Textures/Grass.png"))
        std::cout << "Could not load texture : Grass.png" << std::endl;

    for (int y = 0; y < MapSize; y++)
    {
        for (int x = 0; x < MapSize; x++)
        {
            sf::Sprite* tile = new sf::Sprite();
            tile->setTexture(*textures["Grass"]);
            tile->setPosition(x * 32, y * 32);
            tiles.push_back(tile);
            std::cout << "Loading : " << tiles.size() << " / " << MapSize * MapSize << std::endl;
        }
    }

    std::cout << "Map loaded!" << std::endl;

    initialized = true;
}

```

---

How would I get the tile my cursor is currently over, even if my `sf::view` is moving?

---

**This is how the newest code is looking :**

Calling the get tiles function :

```
gameScreen.GetSpriteByPosition(window.mapPixelToCoords(sf::Mouse::getPosition(window), view));

```

Inside the get tile function :

```
sf::Sprite* GameScreen::GetSpriteByPosition(sf::Vector2f mousePos)
{
    sf::FloatRect mouseBound(mousePos, sf::Vector2f(1, 1));

    for (int i = 0; i < tiles.size(); i++)
    {
        if (tiles[i]->getGlobalBounds().intersects(mouseBound))
        {
            std::cout << "Found tile, index : " << i << std::endl;
            return tiles[i];
        }
        std::cout << "not found" << std::endl;
    }

    return nullptr;
}

```

# Answer
> 1 votes
SFML has a few good functions that allows you to do what you want a bit simpler

```
window.mapPixelToCoords(sf::Mouse::getPosition(window), viewRect);

```

That line of code will convert the mouse position relative to the window (sf::Vector2i), to a world coordinate (sf::Vector2f). I have the window as an argument there, or else it will get the mousePos relative the the monitor

Luckily, SFML has it's own built in collision checking function in sf::FloatRect, so you don't need to write out the checking for if a x is less than another x and that

```
sf::Sprite getTile(sf::Vector2f mousePos)
{
    sf::FloatRect mouseBound(mousePos, sf::Vector2f(1, 1)); // create a floatRect with the mouse position for collision checking
    for (int i = 0; i < allTiles.size(); i++)
    {
        if (allTiles[i].getGlobalBounds().intersects(mouseBound))
            {
                std::cout << "Found tile at " << i << std::endl;
                return allTiles[i];
            }
    }

    return nullptr;
}

```

Combine the mousePos check above, and the code here below, and it should work out fine. If you have any questions about the stuff I used, make sure to ask.

Your edited code at time of the comment didn't work, because of that else statement. You check if the mouse hits the VERY FIRST tile, and if it doesn't return null

Documentation:

sf::Mouse::getPosition

sf::RenderTarget::mapPixelToCoords

# Answer
> 2 votes
Figure out your mouse position in world space and divide by the tile size.

Basically keep track of where your upper left corner is in world space, add the mouse position to that (with appropriate scaling etc.) and then divide it by your tilesize.

# Answer
> 2 votes
First off, you should really store the tiles in a 2d array. As far as I can tell from documentation, `sf::View` has a `getViewport()` method. This method gives the coordinates of the top-left point of your view. Next you will need the coordinate of the mouse, in relation to the top-left of your *window*. Finally, you add the two coordinates together, and you'll have the world-space coordinates of the mouse. From here, it's a matter of basic integer divisions to get the tile you are currently hovering.

```
const int TILE_WIDTH = 32;
const int TILE_HEIGHT = 32;

Sprite tiles[][] = { ... }

sf::View* view = { ... }
sf::Rect viewRect = view->getViewport();
int mouseX = { ... }
int mouseY = { ... }
int worldX = viewRect.x + mouseX;
int worldY = viewRect.y + mouseY;

int tileX = worldX / TILE_WIDTH;
int tileY = worldY / TILE_HEIGHT;

Sprite tile = tiles[tileX][tileY];

```

This is just off the top of my head, it may contain errors.

---
Tags: c++, 2d, sfml
---


# Question
Title: Bring GameObject in front of GUI Texture
I have a GUI Texture that dims the screen, however I want certain game objects to not be dimmed. I tried putting them in front of the GUI Texture, but it doesn't work. How can I do this?

# Answer
> 0 votes
Apparently the GUI texture hides everything that is not GUI, so I removed it altogether and put a semi-transparent black plane. Problem solved.

---
Tags: unity
---


# Question
Title: The better performance in occlusion culling, plane or quad?
In the above picture, when the left camera shows two small parts of the quad, all of that is rendered (it can be a very large quad). But in the right one only two small parts of it is rendered. Which of them has better performance?

On the other hand if camera rotates by 180 degrees then what? plane seems to have more vertices to be loaded than the quad.

What the overall decision should be? using quads or planes?

# Answer
> 3 votes
Unity's built-in frustum and occlusion culling features work on a per-renderer level. They'll disable the rendering of *whole objects* that can't be seen, but they don't select individual triangles to cull out of a single mesh.

In both your examples above, the full mesh will be processed by the GPU, because at least part of it is visible.

The extra vertices of the "plane" primitive are unlikely to give any noticeable performance impact unless you're rendering very many of them (modern game engines and GPUs are built to handle character and environment models which are far more complex than this!) so use whichever primitive is most convenient for what you need it to do.

Note that in the two cases you showed, it's really **clipping** that's at work, not culling. Clipping is the stage in the graphics pipeline that removes triangles (and parts of triangles) that are outside the rendering viewport and the near & far planes. So in both cases, your fragment shader is only being invoked for the pixels of each mesh which are actually in front of the camera. The rest of the surfaces are discarded after some (usually quite cheap) vertex transformations to determine they're outside the rendered area.

---
Tags: unity, rendering, optimization, culling
---


title: Admob - gradle configuration error

text:
# Question
Title: Admob - gradle configuration error
I've followed this tutorial https://developers.google.com/admob/android/quick-start, but I'm stucked at gradle configuration. I've added line

```
compile 'com.google.android.gms:play-services-ads:8.3.0'

```

to build.gradle (of application) like in tutorial, but error "Failed to find: com.google.android.gms:play-services-ads:8.3.0" appeared. Admob writers says, that android studio will offer download if that is missing, but I've only got error in output.

# Answer
> 0 votes
Solved. You need to download "Google Repository" from Android SDK.

---
Tags: java, android
---


# Question
Title: How can I make terrain texturing look detailed both close-up and far away?
I attempting to make my game have very detailed textures, and in general look pretty. However, I'm having some issues with that.

Let's take a look at a rock texture close up: Picture.

As you can see, this looks perfectly adequate for a 3D game up-close. However, I'm struggling to get this working at a distance: Picture

At a distance, the texturing looks obviously uniform, and looks very tiled and very bland. Picture

How can I solve this issue to make my textures look more detailed at all distances? I obviously have mipmapping enabled, but I don't understand why the texture looks so badly detailed and what I can do to improve it.

# Answer
I don't know if this could help you, but this is everything I do for good MipMapping:

```
public int loadTexture(String fileName){
    Texture texture = null;
    try {
        texture = TextureLoader.getTexture("PNG", new FileInputStream("res/textures/"+fileName+".png"));
        GL30.glGenerateMipmap(GL11.GL_TEXTURE_2D);
    //I preffer LINEAR_MIPMAP because depending of the distance,
    //the textures will be seen better or "worst".
        GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR_MIPMAP_LINEAR);
    //The more you increase the final value, the most the texture will be affected by the
    //AntiSotropic Filter, that also distorts the texture depending of the distance.
        GL11.glTexParameterf(GL11.GL_TEXTURE_2D, EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT, 16.0f);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    int textureID = texture.getTextureID();
    return textureID;
}

```

Other thing that you could do is decrease the texture quality, add FXAA or even make Cell-Shadding techniques that doesn't need to distort anything.
> 2 votes

---
Tags: opengl, java, textures, lwjgl, graphics-design
---


# Question
Title: Random equidistant points like a tree branch (JS)
I'm working on an algorithm to generate a "graph" like array of points in my game world. See Image Below:

Here is what i'm working on so far, which will generate the black line.. but this may not be the best route.

```
var angle = Math.random()*Math.PI*2;
var rx = Math.cos(angle)*radius + lastPointX;
var ry = Math.sin(angle)*radius + lastPointY;
lastPointX = rx;
lastPointY = ry;
points.push(new GamePoint(0, game, rx, ry));

```

I'm trying to expand upon this to make various other "branches" to add a randomness to the game but at all times the player has to have at least one option to move forward ( if not more ). Paths can cross but shouldn't get too close / overlap.

I'd eventually want the game to consist of multiple paths ( see image below ). The player will move up but doesn't see the whole "graph".

# Answer
It looks to me like you can use a variant on a Poisson disc sampling algorithm to achieve this.

Check out Mike Bostock's wonderful visual demonstration of these algorithms, particularly the explanation of Bridson's algorithm about a quarter of the way in.

Here you store your points in a grid where the cell size is `r/sqrt(2)` \- that way if all your points are a distance of at least `r` apart, then there is at most one point in each grid cell. This speeds up our neighbour checks.

Start with at least one point, classified as a frontier point (those are the red dots in the diagram above)

In each iteration, select a point on the frontier. Randomly generate candidate points around it, at a range of at least `r` (the Poisson disc example uses a range from `r` to `2r` but you can tune this). To get an "upward" growth like in your example, you might want to bias this random sample vertically.

As you generate each candidate, check to see if it's out of bounds, or if any other points are within `r` of it. (Using the grid, you only need to check certain cells)

If the candidate is too close to an existing point, reject it and generate a new candidate. If you exceed a maximum number of attempts without success, give up and mark the parent point as no longer part of the frontier. (This will terminate a branch)

If the candidate has no other points within a distance of `r`, add it to the grid as a new frontier point.

Here's where we'll break from the normal Poisson disc sampling algorithm: instead of leaving the parent point as part of the frontier, we can choose to immediately remove it from the frontier once it's spawned a single child point. This will produce chains of points instead of a dense cloud.

To get branching, we can occasionally allow a point to spawn 2 child points before it's removed from the frontier. (We can balance our tolerance based on the number of branches, ie. the size of the frontier set, to avoid spawning too dense a shrub)

This should get you pointed in a useful direction. Some improvements you can make from here:

* make your peer repulsion distance larger than your parent-child spawning distance, to keep branches spaced apart
* refine the branch termination condition - maybe if a candidate point is almost equidistant between the parent point and a point from a different branch, you place it as a non-frontier point to "merge" the two branches back together rather than rejecting it.
> 1 votes

---
Tags: javascript, algorithm, random
---


# Question
Title: Convert "analog stick radians" into "normal radians / degrees"
Sorry if the title isn't self explanatory. I've worked previously on the development of many small indie games for computers, but never really bothered on developing anything for a console, until recently when I got accepted for an indie development program for a well known game console. The games I'm working on (as most console games) will use the analog sticks for moving the character and rotating the camera, so far so good... except that the analog sticks don't work as I thought they would. When the analog stick is facing up, the "value" returned is pi / 2 (90°). When it's facing to the left the value is 0. When it's facing down, the value is (-pi / 2) (-90° ??) and when it's facing on the right the value is either -pi (-180° ??) or pi (180°). And obviously there are values in between all of those.

Small "ascii art" to demonstrate what I mean.

```
        ^   pi /2
+- pi <   > 0
        V   -pi /2

```

The values that I don't get are the negative ones, how can I convert those negative values to an actual circle, so that I get a value between 0° and 360° (0 and 2 pi)?

Sorry if the question might sound stupid, I'm really new to console development. At first I thought I would ask in the official developers forum for this game console, but I thought that a public resource like stack exchange might be better since, I'm most likely, not the only one that has to deal with this, and probably other consoles have the same mechanism too.

# Answer
> how can I convert those negative values to an actual circle, so that I get a value between 0° and 360° (0 and 2 pi)?

Since you have an angle in the range of `[-Pi, Pi]`, you can make the range positive *without rotating the angle* by adding `2*Pi` (360°).

Now your angle is in the range of `[Pi, 3*Pi]`. You can adjust the range *without rotating the angle* by computing the modulus: `angle % (2*Pi)`.

The resulting angle has the same direction, but is now in the range `[0, 2*Pi]`.

---

(In C++ this would look like `angle = fmod(angle + 2.0*M_PI, 2.0*M_PI);`)
> 0 votes

# Answer
In addition to the practical advice offered by MickLH on how to do the conversion, I would like to explain the trigonometry and address some of the misunderstandings apparent in your question, so that you can decide whether converting to 'normal degrees' is actually preferable. It probably isn't; both \[-π,π\] and \[0,2π\] describe 'an actual circle'.

There are many ways to describe a point on the unit circle with an angle. Since a circle is obviously symmetric, you have to arbitrarily define a reference point as zero radians. To differentiate between angles clockwise and counter-clockwise from your reference point, you have to define one of them as positive, the other as negative. Finally, since 1π and 3π describe the same point, you may want to select a point where the angle wraps around, which also determines the range of possible values for the angle.

In your example, the zero point is on the right, the positive direction is counter-clockwise, and the angle wraps around at ±1π. These decisions are not unique to 'analog stick radians', they are by far the most common convention, similar (and related, see image below) to how we usually draw two-dimensional plots with the x-axis to the right and the y-axis upwards.

This coordinate system allows us to describe a point in terms of the angle φ in arguably the simplest way possible, i.e.: *x = cos(φ)*, *y = sin(φ)*, while avoiding reflex angles. If you dislike negative angles, you could allow reflex angles, move the wrap-around point to the right and take the angular range from 0π to 2π instead. The point marked in the circle above would then be at *φ = 240°* rather than at *φ = -120°*, which is not the most convenient way to measure the red angle, though equally valid, e.g. should you need to find the x-coordinate of the marked point, both *cos(-120°)* and *cos(240°)* will yield the same, correct answer: .
> 0 votes

---
Tags: console
---


title: Client-side prediction for movement?

text:
# Question
Title: Client-side prediction for movement?
How would client-side prediction for movement work? From how I understand it, the player inputs "Move Forward" and the character on the player's computer instantly starts to move forward. It also sends the input to the server along with a framestamp, say frame 100. The input arrives at the server on frame 110. The server knows that the player started movement on frame 100 so the character would've moved forward for 10 frames. On the server, the character moves forward 10 frame's worth then the result is sent. The official state is received and since it nearly matches up with the player's gamestate, the transition is smooth.

My concern is about how this would look on other people's computers who don't have knowledge of the input - only gamestate. How is 10 frame's worth of movement smoothed out when the other computer hasn't started moving the character forward 10 frames earlier?

# Answer
> 2 votes
**Intro**

One smooth way to do this is to interpolate for a short period of time if the postions are "near enough" just for a "viewing" perspective, but still have the "proper position" in sync with the server for collisions and so.

**Definition of "near enough"**

Near enough is "what typically will happen in normal operation" of your servers, and to calculate this, you need to know what units you measure the "near enough" concept, what are the typical movement speeds, and what is the typical de-syncronization time.

For this example let's assume that

1. The world is in "meters".
2. The objects are people and cars.
3. The maximum typical speed of those is 200Km/h which is about 55m/s.
4. The maximum typical "lag" of the server is 400ms.

Conclusion =\> Objects due to server lag should not be further than 22 meters (`55m/s * 0.4s = 22m`) - Let's give a bit of air-room there so we'll round it to "far means 25 meters".

**Game state**

Then, you shall have two sets of variables, one representing the "real known position" and the other "the visible representation of the objects".

Additionally you'll have to track if you are in the interpolation mode.

Say we have a Car object, with a Vector3 position.

You may have that "model versus view" splitting in your classes, if you are more like a dirty programmer, like in:

```
Class Car
{
    Vector3 realPosition;
    Vector3 onScreenPosition;
    DateTime interpolationStartTime;
    Vector3 interpolationStartPosition;
    bool interpolating;
}

```

or you may opt to separate model and view in separate classes, if you consider yourself a more senior and skilled programmer, like in:

```
Class Car
{
    Vector3 position;
}

Class OnScreenCar : Car
{
    Vector3 onScreenPosition;
    DateTime interpolationStartTime;
    Vector3 interpolationStartPosition;
    bool interpolating;
}

```

**Updating the info from the server from a far distance**

When you are receiving a new real position from the server, you check if the new position is "far" from the previous visible position and if so, you just "update" the current position. This will produce a visual glitch but you calculated this to just happen in very few ocasions as normally it will be near.

```
onServerSendsData()
{
    OnScreenCar c = getCarToEvaluate();
    if( distance( c.position, c.onScreenPosition ) > MyEngine.ServerLagNearPosition )
    {
        c.onScreenPosition = c.position;
    }
[...]

```

**Updating the info from the server from a near distance**

When the new real position is "close enough" you may update the visual position by interpolating the position during a period of time. Save the initial position and time.

```
[...]
    else /*near distance*/
    {
        c.interpolationStartPosition = c.onScreenPosition;
        c.interpolationStartTime = now();
        c.interpolating = true;
    }
}

```

**Update in the game-loop**

Then in your normal update, if you are in the interpolating mode, just calculate a point in the middle "from where you were, towards the final position, within a specified time"

```
onGameLoopUpdate()
{
    OnScreenCar c = getCarToEvaluate();
    if( c.interpolating )
    {
         DateTime n = now();
         float alpha = ( n - c.interpolationStartTime ) / MyEngine.ServerLagInterpolationTime;

         if( alpha < 1 )
         {
             // Really interpolate.
             c.onScreenPosition = interpolate( c.interpolationStartPosition, c.position, alpha );
         }
         else
         {
             // Interpolation time has expired, cache the position and shut down interpolation mode.
             c.onScreenPosition = c.position;
             c.interpolating = false;
         }
    }
    else
    // Your normal non-interpolated code here.
}

```

**Collisions**

Of course, all the physics should be done on `c.position` and not `c.onScreenPosition` as the latter is only meant for a "visual softness" to the players, but are not representing the real objects but a "phantom" of them that goes to the real object.

**Final words**

All this is pseudo-code. You should change the events by the ones in your engine. Also you need to change the DateTime types to the ones suitable to your programming language and engine, those types are to give you a verbose idea on what's going on. Of course you must implement some way of interpolation if your engine does not have one.

You can do as many flourishes on this as you want, for example do "easy in-outs" instead of linear, or for example improve the handling of how changes are handled if you receive a new server update while you are still interpolating from the previous one.

Hope this helps!!

---
Tags: multiplayer, movement-prediction
---


title: How do I make 2 players from one Class?

text:
# Question
Title: How do I make 2 players from one Class?
I am teaching myself XNA and only started a few days ago. I am making a clone of Pong and have made a class for the Paddle:

I am wondering how I can create 2 paddles one for each player from the one class.

Thanks,

TeaBelliedTitch

# Answer
You need to create two different instances of the class.
I suggest you **not to check for input inside your class** but **in your game loop**, so you can handle events for both instances. Pseudocode below:

```
Pong::Paddle player1(texture1, bounds1);
Pong::Paddle player2(texture2, bounds2);

while(running){
  if(keyDown == W)
    player1.setYDirection(-1);
  else if(keyDown == UP)
    player2.setDirection(-1);
  else if(keyDown == S)
    player1.setYDirection(1);
  else if(keyDown == DOWN)
    player2.setDirection(1);

  player1.update();
  player2.update();
}

```
> 1 votes

---
Tags: c#, xna, xna-4.0
---


# Question
Title: Difference between orthogonal map and isometric map
I am laughing at myself ignorant on this. Google didn't produce an obvious answer. Could someone explain what orthogonal map and isometric map are, and how they are different?

# Answer
> 60 votes
I made a picture to sum it up. Basically, the difference between both types of maps has mostly to do with the **angle formed between each axis** which results in one appearing to be seen from a topdown point of view, while the other appears to be seen from an angle:

It is also worth noticing the visual difference between an *isometric* projection and *perspective* projection which is what almost every 3D game uses.

Notice how **lines are drawn parallel to each other** when using an *isometric* projection, while when using a *perspective* projection, lines converge towards one (or more) vanishing points.

# Answer
> 6 votes
An orthographic projection is one where the projection rays are perpendicular to the projection plane.

These are examples of orthographic projections, specifically axonometric. The first is perspective.

An isometric projection is a type of axonometric projection (and thus a type of orthographic) with 120 degrees between each projected coordinate axis.

Note that orthographic is sometimes used for instances where the plane of the object is parallel to the projection plane, such as a top-down map, however this is only a small case of what it encompasses.

Orthographic projections are a type of parallel projection, which is not shown in the diagram.

# Answer
> 5 votes
From what I understand, an orthogonal tile map is more of a top-down style (such as this), although they can appear to have some tilt (that is, showing more front, back, side, etc). Orthogonal tiles will appear rectangular. In isometric tile maps, you view the tiles at a 45-degree angle; as a result, the tiles are generally diamond shaped (as seen here). Also see this Wikipedia article on isometric projection in games.

Sorry that I can't explain it any more formally!

# Answer
> -2 votes
I don't have time to type up a good answer, but I wanted to throw in that the difference between orthogonal and isometric maps goes beyond visual perspective in games. Maps are not just images or views in games, but have many things which happen within them and these things work differently between the two map types. Many of these differences are not seen by the user. For example, an algorithm used to determine trajectory of an arrow being shot by a player can be different between the two map types. The differences in the sprite of the arrow/shot can be considered a matter of visual prospective, but the math differs as well and is outside of the players view/perspective. While this may not answer "the" difference between the two, it describes one of many ways that the two are different outside of visual perspective.

It's also worth noting that maps in games often use many levels and groups of objects to create a specific view. How objects interact between these different layers and groups is different in the two maps as well (such as collision detection) and is typically easier when orthogonal.

---
Tags: maps
---


# Question
Title: How do I run an APK in a device from the Unity IDE without rebuilding the binary?
I know that the button `Build` creates the APK in my disk.

And the button `Build and Run` creates it and sends it to a real device if connected via USB.

**Question:**

Is there any way to "Run" from the Unity IDE an APK in a physical device without having to re-build it (provided you properly built it a few minutes ago, for example?)

# Answer
> 2 votes
Unity Remote 5 allows the Unity editor to send a video stream of the editor's Game tab to your Android device, and responds to touch input like it was the real thing, which is a convenient way to test your touch input. More details here.

But if you want to test the APK properly (like if you're testing Google Play API integration or something), you'll have to build and run every time.

---
Tags: android, unity
---


title: DrawFont with VB

text:
# Question
Title: DrawFont with VB
I'm having a problem with fonts. As far as I can see from the very limited information on the SpriteFont, I should be able to add a font to my Content as a SpriteFont. However the SpriteFont doesn't exist in the Add New Item menu.

Has anyone else got around this problem?

# Answer
You don't specify which library you are using, XNA or monogame, so I'm assuming XNA; Adding a spritefont should be possible by right-clicking the content project, selecting Add -\> New Item...

and then selecting Sprite Font

However, XNA is really built more with C# in mind (citation needed), so I'm not sure exactly if this process changes for VB.

**Addendum**

After creating a VB project, the same options appear for me as in C#. However, a thought occurs to me; Make sure to select the Root "Visual C#" treenode and not General, as only the bitmap option shows in General.
> 1 votes

---
Tags: spritefont
---


title: Rendering a dynamically sized box

text:
# Question
Title: Rendering a dynamically sized box
So in games where there are textboxes with different sizes appearing, how does one actually render them efficiently? Games like Final Fantasy IX have dynamically sized speechbubbles for example, each with a size so it exactly matches the rendered text.

I know the basic idea is to render the frame around the bounding box of the text and with different images for each component of a box: corners, edges, center. Though how should one design that rendering if the edges aren't of 1 pixel in size when one has to compute how often an edge piece needs to be drawn next to each other to form the whole edge of the box.

Here is my naive implementation of a hopefully good enough abstracted method:

```
public void drawBox(Renderer renderer, int x, int y, int width, int height){
    int es = this.components.getEdgeSize();
    renderer.renderSprite(this.components.getTopLeftCorner(), x, y);
    /* Render top edge of box */
    int i;
    for(i = es; i < width - es; i += this.components.getTop().getWidth()){
        renderer.renderSprite(this.components.getTop(), x + i, y);
    }
    renderer.renderSprite(this.components.getTopRightCorner(), x + i, y);
    /* Render left edge of box */
    int j;
    for(j = es; j < height - es; j += this.components.getLeft().getHeight()){
        renderer.renderSprite(this.components.getLeft(), x, y + j);
    }
    renderer.renderSprite(this.components.getBottomLeftCorner(), x, y + j);
    /*Render bottom edge of box */
    for(i = es; i < width - es; i += this.components.getBottom().getWidth()){
        renderer.renderSprite(this.components.getBottom(), x + i, y + j);
    }
    renderer.renderSprite(this.components.getBottomRightCorner(), x + i, y + j);
    /*Render right edge of box */
    for(j = es; j < height - es; j += this.components.getRight().getHeight()){
        renderer.renderSprite(this.components.getLeft(), x + i, y + j);
    }
    int k = i;
    int l = j;
    for(i = es; i < k; i+= this.components.getCenter().getWidth()){
        for(j = es; j < l; j += this.components.getCenter().getHeight()){
            renderer.renderSprite(this.components.getCenter(), x + i, y + j);
        }
    }
}

```

I feel that some loops did not have to be done and the loop filling the center feels like it could potentially kill the framerate.

# Answer
A good way to think about it is this. You can always break the textbox up into 9 bits, top left, top center, top right, etc.

Now the corners will basically always be the same size the top and bottom side will be stretched along the x axis and the left and right sides will be stretched along the y-axis. The center will be stretched along both axis obviously.

So the question is then how do you draw each of those.

Drawing the corners is easy since they always have the same dimensions. But for the sides and the centers you have a few choices.
If the textures for them tile you can just scale the sides and their texture coordinates up to fit and use sampler state wrap so that it tiles naturally. You want to make sure to round your scaling so your highest uv coordinates are integers, so that the tiling continues properly towards the corners. You could also not scale your uv coordinates and just let the image be stretched if it isn't (too) noticeable.
And for the center you can do essentially the same thing.

TL;DR: You don't really need to figure out how many of those pieces to draw. Instead thing of just 9 parts that make up a box and draw each of the parts appropriately.
> 1 votes

---
Tags: sprites, gui, architecture
---


title: How do i set Lua variables?

text:
# Question
Title: How do i set Lua variables?
You can pretty easily read variables, but what about writing them to the lua file?

Ive given it a little go, but it doesnt seem to work...

```
void Lua::setBool(string path, string var, bool val) { //"Lua" is a class with my Lua functions (such as get bool, get float...)
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);
    if (luaL_dofile(L, path.c_str())) { // For some reason, "!luaL_dofile" triggers if i input the path Correctly
        string msg = "Unable to open file " + path;
        MessageBox(NULL, msg.c_str(), "Lua IO", MB_ICONERROR);
    }

    lua_pushboolean(L, val);
    lua_setglobal(L, var.c_str());

    lua_close(L);
}

```

And yes, ive inputted "var" and "path" correctly.

# Answer
> 0 votes
If you want to write them to the Lua file--as in the script text file itself--you'll have to do it as you would any other text file. As far as I know, Lua doesn't include any way to do this.

# Answer
> 0 votes
If your intention is to modify your Lua State so that your Lua script can access parameters set from C++, you need to actually set those values before calling into Lua (`luaL_dofile` is a helper for loading a chunk from a file, compiling it if necessary, and immediately executing it). So the following lines should be moved up just after `luaL_openlibs`.

```
lua_pushboolean(L, val);
lua_setglobal(L, var.c_str());

```

Note that a Lua chunk is actually a function from Lua's perspective, so you can actually just push parameters onto the Lua stack and avoid polluting the global environment. Then you could access them in Lua using something like:

```
local paramA, paramB = ...

```

However you can't use `luaL_dofile` to do this. It's just syntactic sugar for `(luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))`. In order to pass parameters on the stack you'd need to expand it out so you can replace the first `0` in `lua_pcall` with the number of arguments you want to pass. You can return values from Lua chunks in a similar fashion.

---

Regarding your confusion in the comments of your code regarding the return value of `luaL_dofile`, it returns an integer status code. Most `lua*` functions that aren't retrieving a value return a status code indicating if everything went alright, or a vague idea of what went wrong. If everything's peachy, it will return `LUA_OK`, which happens to be defined as `0`. So you should say:

```
if (luaL_dofile(L, path.c_str()) != LUA_OK)

```

---
Tags: c++, lua
---