# Question
Title: How to block the player from moving left and right from two empty game objects?
I made the game space shooter in that game my spaceship move left and right but its not stop in right and left corner. When its move to left its go out of the screen. how i stop/block in the left and right screen edges.

```
using UnityEngine;
using System.Collections;

public class PlayerMovement : MonoBehaviour {
    public float speedMove = 3;
    public float bonusTime;
    private Rigidbody rb;
   private float _limit = 3;

    // 1 for right and -1 for left.
    private float _direction = 1;

    // You can call it as speed
    private float _speed = 0.01f;

    private bool toLeft = false;
    private bool toRight = false;

    public GameObject shield;
    public GUIText bonustimeText;

    private bool counting = true;
    private float counter;

    private Weapon[] addWeapons;

    public Sprite strongShip;
    public Sprite normalSprite;
    public Sprite shieldSprite;

    private SpriteRenderer sRender;
    private Weapon weaponScript;

    void Start () {

        counter = bonusTime;
        rb = GetComponent<Rigidbody>();

        sRender = GetComponent<SpriteRenderer> ();
        addWeapons = GetComponentsInChildren<Weapon> ();
        foreach (Weapon addWeapon in addWeapons) {
            addWeapon.enabled = false;
        }

        weaponScript = GetComponent<Weapon>();
        weaponScript.enabled = true;
    }

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

        transform.position = Vector3.MoveTowards (transform.position,new Vector3 (transform.position.x + _direction, transform.position.y, transform.position.z),_speed);

        if (Input.GetMouseButtonDown (0))
            _direction *= -1;

    }

    void OnCollisionEnter2D(Collision2D coll)
    {
        if (coll.gameObject.tag == "StrongMode") {
            Destroy (coll.gameObject);
            counting = true;
            StrongMode();
            Invoke ("Downgrade", bonusTime);
        }

        if (coll.gameObject.tag == "ShieldMode") {
            Destroy (coll.gameObject);
            counting = true;
            ShieldMode();
            Invoke("Downgrade", bonusTime);
        }

        if (coll.gameObject.tag == "Life") {
            GUIHealth gui = GameObject.Find ("GUI").GetComponent<GUIHealth> ();
            gui.AddHealth();
            SendMessage("AddHp");
            SoundHelper.instanceSound.PickUpSound();
            Destroy(coll.gameObject);
        }

        if (coll.gameObject.tag == "Enemy") {
            SendMessage("Dead");
        }
    }

    void Downgrade()
    {
        SoundHelper.instanceSound.BonusDownSound ();
        counting = false;
        bonustimeText.text = "";
        counter = bonusTime;

        sRender.sprite = normalSprite;
        weaponScript.enabled = true;
        foreach (Weapon addWeapon in addWeapons) {
            addWeapon.enabled = false;
        }
        weaponScript.enabled = true;
        shield.SetActive (false);
    }

    void StrongMode()
    {
        SoundHelper.instanceSound.BonusUpSound ();
        sRender.sprite = strongShip;
        foreach (Weapon addWeapon in addWeapons) {
            addWeapon.enabled = true;
        }
        weaponScript.enabled = false;
    }

    void ShieldMode()
    {
        SoundHelper.instanceSound.BonusUpSound ();
        sRender.sprite = shieldSprite;
        shield.SetActive (true);
    }

//  void OnDestroy()
//  {
//      bonustimeText.text = "";
//  }
}

```

# Answer
The easiest solution would probably be to put some box colliders at the edges of the screen. Then collision will prevent your ship from passing through and force it to stay on screen.
> 0 votes

# Answer
Although you could use just box colliders as already suggested, it's pretty much killing a fly with a canon.

A simple approach through code is to compare player's position to camera boundaries position, so if the next position to move to is out of bounds, you don't apply it.

Following this link to the Unity3D forums, you can get an idea of how to get World's position out of screen's.

Then, you just compare the next player's position to corners', and you apply the movement if it won't get out of boundaries.

```
int leftUpBoundX = x; //Calculate using link
int leftUpBoundY = y; //Same
int movX = -10
int movY = 5
if (playerX + movX >= leftUpBoundX
    && playerY + movY <= leftUpBoundY) {
    playerX += movX;
    playerY += movY;
}

```

You just do this for the 4 corners and X/Y coords. If you wanted to move in 1 axis even if you can't move in both, you just split X/Y if statements too.

This may seem complicated or CPU consuming but it's actually just adding and comparing integers.

Besides that, have in mind that you can extract this to a common script and use it to both player and/or enemies as well, having no more work than sending the appropiate object's position parameters.
> 0 votes

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


# Question
Title: Why do my variables reset when calling Destroy() in Unity?
I need to Collect and Destroy the money but when I add `Destroy` or an equivalent function, it resets and always says 5 instead of 5-10-15...

I watched videos on YouTube and the only difference we're having is that they do something like this:

```
Class object = new Class();

```

I don't think this can cause the problem because when I remove the `destroy()` function, the problem is solved! But I can't not have this call.

How can I fix this?

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class moneysystem : MonoBehaviour {

    bool intrigger;
    variables asd = new variables();
    private void OnTriggerEnter(Collider other)
    {
        intrigger = true;
    }
    private void OnTriggerExit(Collider other)
    {
        intrigger = false;
    }

    public void FixedUpdate()
    {
        if (intrigger)
        {
            if (Input.GetKeyDown(KeyCode.G))
            {
                asd.summoney =  asd.money += asd.moneyonpaper;

                Debug.Log(asd.summoney);
                asd.summoney = asd.lastmoney;
                Debug.Log(asd.lastmoney);
                Destroy(this.gameObject); // when I remove This then there is no problem remains
                // I also tried Destroy(gaemobject) and gameobject.setactive(false) and same problem
                Debug.Log(asd.lastmoney);
            }
        }
    }
}

```

**Variables.cs**

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class variables : MonoBehaviour {

    public int moneyonpaper = 5;
    public int money;
    public int summoney;
    public int lastmoney;
}

```

# Answer
> 2 votes
It seems like you attached this `moneysystem` to each gameObject the player can pick up. That means each of these gameObjects has a completely independent `moneysystem` with its own `variables`. When you destroy the object, the moneysystem attached to it gets destroyed too, and so do its variables.

There are two solutions for this conundrum:

**Clean solution:** Separate the money system from the behavior of collectable game objects. Attach the `MoneySystem` to one invisible controller game object in your scene and the `Collectable` behavior to each game object which can be collected. The trigger-method of the `Collectible` would destroy the game object it is attached to and notify the `MoneySystem` component on the controller game object to change the money count.

**Quick&Dirty solution:** Just make variables a `static` variable. Then it is shared by all instances of `moneysystem`. I am calling this solution "quick" because it would likely fix your problem with just adding one keyword, but "dirty" because this architecture makes it awkward to add any other features than money pickups which interact with the account balance.

# Answer
> 2 votes
When you collect (press `G`) the money you destroy the `moneysystem` by calling `Destroy` and because your `variables` are part of your `moneysystem`, they get destroyed as well. So to prevent resetting of `money`/`summoney` you should change how the collection of money works.

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


# Question
Title: Canvas not filling up the whole screen in Unity 5
I am trying to make my canvas auto resize to any screen size. These are my canvas scalar settings:

UI mode: change with screen size

match height and width

reference resolution: 600x800

I looked up in various tutorials where they say to set it to "change with screen size" and "match height and width" so I did that but still it's not fitting. The weird thing is that it fits horizontally but not vertically.

screenshot: https://s15.postimg.org/ue99zehkr/Screenshot\_20161207\_132731.png

# Answer
Is the canvas scaler set to Preserve Pixel resolution? I make that mistake sometimes, that's the default and there's a setting for Scale with Screen.
> 1 votes

# Answer
I can't comment because I don't have sufficient KP. So, i will just write here

Given the information provided by you, It seems like you're setting the resolution in Portrait mode (height \> width). And from looking at the screenshot, it seems like the game is set up on Landscape mode, which is why it's showing like this. So, try changing the reference resolution to a landscape one (800 x 480, 854 x 480 etc.).
> 0 votes

# Answer
Have you looked at unity anchors? These help you specify what you want to happen when the window resizes. Here's the Unity documentation on that: https://docs.unity3d.com/Manual/UIBasicLayout.html
> -1 votes

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


title: Raycast Movement on a sphere

text:
# Question
Title: Raycast Movement on a sphere
so I'm working on a mobile game where I have touch input from a Asset from the asset store. It all works perfectly fine, except for one thing: I want to implement a "drag and drop" feature so when I pick up an Item it should follow to the position of my finger. But because the playground is a sphere, I have to do the movement with a Raycast. So my plan is that the item should follow the Raycasts position. My current attempt looks like this:

```
public void DragTo(float screenX, float screenY)
{
    if (draggingObject == null)
    {
        return;
    }

    Debug.Log("Dragging");

    //Converts the screen space to world space
    Vector3 mousePosFar = new Vector3(screenX, screenY,      Camera.main.farClipPlane);
    Vector3 mousePosNear = new Vector3(screenX, screenY, Camera.main.nearClipPlane);

    Vector3 mousePosF = mainCam.ScreenToWorldPoint(mousePosFar);
    Vector3 mousePosN = mainCam.ScreenToWorldPoint(mousePosNear);

    //shoots an ray to the world space
    RaycastHit hit;

    if (Physics.Raycast(mousePosN, mousePosF - mousePosN, out hit))
    {
        float step = speed * Time.deltaTime;
        draggingObject.GetComponent<Rigidbody>().MovePosition(hit.point);
    }
}

```

I already have tried the following options:

```
draggingObject.GetComponent<Rigidbody>().MovePosition(hit.point);
draggingObject.GetComponent<Rigidbody>().MovePosition(hit.normal);
draggingObject.transform.position = hit.point;
draggingObject.transform.position = normal;

```

They all work, but they all have really buggy and strange behaviors. Also when I dont freeze the z. axis on the Rigidbody the item just "flies" up on the z axis, until it reaches the camera. Then it teleportes again down and it all starts again. So its flying up on the ray. So if you have any Ideas why this happens let me know. Any help is appreciated. (Also dont forget that its all happens on a sphere)

UPDATE: It works now. When the dragging began i changed the layer from the object to "Ignore Raycast" and when it end changed it back to "Default".

# Answer
It sounds like your raycast is hitting the draggingObject you are trying to place. You need to ignore your controlled draggingObject while ray-casting.
> 2 votes

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


# Question
Title: Character permanently disappears when camera zooms in
I am using ThirdPersonController and FreeLookCameraRig, both from the standard assets package. The camera generally follows the player fine but there is an issue when I move the camera very close to the player. When I do this, the character disappears, though it still behaves as though it is in the scene. For example, the xyz coords still show it as being in the scene and when it jumps, the camera still follows it.

Here's a visual explanation. Notice how the character disappears after about 5-10 seconds and doesn't come back.

(Note: the gif is too large to display here, so please see it on imgur. http://i.imgur.com/PbMDlXD.gifv).

The ThirdPersonController has Transform, Animator, CapsuleCollider, Third Person User Controller, and Third Person Character

The FreeLookCameraRig has Transform, Free Look Cam, and Protect Camera From Wall.

I have tried messing with many of these settings, but nothing has worked.

By the way, some of the course was created in Sketchup.

# Answer
I figured it out ... I had a rigid body defined on the Skeleton of the ThirdPersonController ... I needed to remove this. It was ending up separating from the ThirdPersonController and free-falling.
> 0 votes

---
Tags: unity
---


# Question
Title: Is it possible for a particle to have an infinite lifespan in SceneKit?
I'm trying to do an experiment where the user creates particles when they touch the screen, and then the particles just stay in place, only dying in collision. I'm wondering if it would be possible to do this in a way where the particles have an infinite lifespan? I feel like I've done this in Unity before, but never in SceneKit.

# Answer
There is currently no way to completely eliminate particle death, but you can set the particle life span to an outrageously high number (20,000 seconds is pretty close to the upper limit of the safe zone) well beyond what would be expected for user interaction on an iOS game.
> 2 votes

---
Tags: ios, particles
---


# Question
Title: How to implement stress/strain mechanics in voxel terrain?
I am in the process of developing a Minecraft-like world where the terrain is divided into voxels. However, I would also like for unstable configurations of landscapes to collapse predictably. For example, an overhang that is too heavy would fracture and break off at 'high stress' voxels, as would a pillar formation with an asymmetrically eroded base. I was thinking about adding a 'stress vector' field to each voxel in the terrain, and doing the following (pseudocode):

```
foreach voxel in terrain
    foreach neighbor in voxel.neighbor_voxels()
        if magnitude(voxel.stress - neighbor.stress) > stressThreshold
            detach_voxels(voxel, neighbor)

```

But the problem is that I don't know how I would go about calculating these individual stresses. Is there some kind of FEA-based algorithm specialized for voxel discretizations that I can use to calculate the stresses on a per-voxel basis? Or am I approaching this all wrong and there's some other way to do this?

# Answer
You may consider a DFS search of all of the connected voxels and determine the voxel that is the single most depended on or "branched" from. And then run your nice little pseudo code. :)
> 1 votes

---
Tags: physics, mathematics, game-mechanics, terrain, voxels
---


title: Correct the rotation of a car gun?

text:
# Question
Title: Correct the rotation of a car gun?
This script for drive a car by arrows. I added a gun above it to aim at target. My issue here is the rotating of my gun effected by my drive when I turn left or right. How to stop the rotation of my gun to be effected by car turns ?

```
using UnityEngine;
using System.Collections;

public class RearWheelDrive : MonoBehaviour {

private WheelCollider[] wheels;

public float maxAngle = 30;
public float maxTorque = 300;
public GameObject wheelShape;

public Transform target;
public Transform gun_car;

// here we find all the WheelColliders down in the hierarchy
public void Start() {

    wheels = GetComponentsInChildren<WheelCollider>();

    for (int i = 0; i < wheels.Length; ++i)
    {
        var wheel = wheels [i];

        // create wheel shapes only when needed
        if (wheelShape != null)
        {
            var ws = GameObject.Instantiate (wheelShape);
            ws.transform.parent = wheel.transform;
        }
    }
}

public void Update()    {

    // Gun rotation
    Vector3 dir = target.position - gun_car.transform.position;
    Quaternion lookr = Quaternion.LookRotation(dir);
    Vector3 rotationy = Quaternion.Lerp(gun_car.localRotation,lookr, Time.deltaTime * 7).eulerAngles;
    gun_car.localRotation = Quaternion.Euler (0f,rotationy.y,0f);

   //    Drive
    float angle = maxAngle * Input.GetAxis("Horizontal");
    float torque = maxTorque * Input.GetAxis("Vertical");

    foreach (WheelCollider wheel in wheels)
    {
        // a simple car where front wheels steer while rear ones drive
        if (wheel.transform.localPosition.z > 0)
            wheel.steerAngle = angle;

        if (wheel.transform.localPosition.z < 0)
            wheel.motorTorque = torque;

        // update visual wheels if any
        if (wheelShape)
        {
            Quaternion q;
            Vector3 p;
            wheel.GetWorldPose (out p, out q);

            // assume that the only child of the wheelcollider is the wheel shape
            Transform shapeTransform = wheel.transform.GetChild (0);
            shapeTransform.position = p;
            shapeTransform.rotation = q;
        }

    }
}

```

}

# Answer
> 1 votes
If you are wanting the Gun to maintain it's rotation relative to the rotation and position of the car (a gun pointed straight ahead remains pointed straight ahead as you turn and drive), make sure that the Gun's GameObject is a child of the Car GameObject that is being turned and rotated. Inspect your GameObject Hierarchy in the scene view to verify, and if you have doubts - just take a screenshot of the fully expanded hierarchy and update your question with it. You might have a GameObject.

Conversely, if you do not want the gun to maintain it's rotation relative to the car's rotation (you turn, but the gun remains pointed at it's old target, seemingly turning to counteract the vehicle position), You will need to subtract the Car GameObject's Rotation Vector3 from the Gun's rotation to compensate for any extra rotation inherited from the parent Car GameObject.

Looking at your script, you seem to be trying to have the gun look directly at some other object. You are working with the localRotation, which would be relative to the car, not in global transform space, and that could be why your rotation isn't what is expected.

---
Tags: unity, rotation
---


# Question
Title: Determine if the player should be able to interact with a door
You know the drill, standard first person door mechanics. How do they do it?

My most noticeable and frustrating problem is when there is a door within range and in view, but the closest door is actually behind the player.

I'm aware of the "dot product trick" but say the player position is point 1, what is point 2? The center of the doors bounding box? The center of the open door way?

Any insight would be gold.

# Answer
Ok, so when the player hits an "interact" button, this should trigger a search for interactable objects within range in front of the player character.

This search can be performed by, as previously mentioned, a raycast of objects within range. You can then, out of this set of objects, get the dot product of the player's "forward" direction (normalised), and the direction to the object (normalised).

As the dot product of two unit vectors is the cosine of the angle between them, you can say that if the dot product is above a certain threshold (say... 0.8) then you can say that the object is in front of the player.

In addition, if the object is definitely interactable, and is a door, trigger the interaction behaviour, and open the door.
> 1 votes

# Answer
For opening doors, performing a dot product with either the closed door or doorway is fine.

Usually for doors, you only want to open them if:

* They are close enough
* The player is facing the door
* The door is closed

A simple distance test for the first is fine. For the second, perform a dot product test between:

* The player's facing direction
* The vector going from the player to the centre of the door
> 0 votes

# Answer
Get a direction vector from the player to the door, and do a dot product between that and the direction the player is facing. The dot product is 1 if the two vectors are the same, and -1 if they are exact opposites. Thus, if the dot product is greater than some threshold (exactly what threshold looks good is up to you) then the player is facing the door.
> 0 votes

---
Tags: 3d, linear-algebra
---


# Question
Title: Should I make my games graphics lower quality so everyone can play it?
The game I'm working on targets lower end graphics capabilities machine users.

Should I make my game's graphics lower quality so that everyone can play it or make its graphics high quality so that people must go and buy a new GPU to play it?

# Answer
### Most effects are nice, but unnecessary

Many of the expensive effects (lighting, high-res textures, etc) make a game beautiful, but are not usually necessary. Of course there are exceptions. A stealth game, for example, would depend heavily on lighting and shadow effects, making it really difficult to cut corners. Turning off most effects won't break a game, even if it makes it look ugly.

### Lower system requirements = more potential players

Unless you are a AAA game studio with a high marketing budget and a highly anticipated game, you cannot expect players to upgrade their computers just to run your game. To them, a game with high system requirements is a broken game. You don't get to assume a certain reasonable benchmark, like you would if publishing for a console. Instead you must assume that there will be at least some players who don't have the latest and greatest, buy the game, and then feel cheated because they can't run it. On the flip side, having expensive effects is great for showing off the game. Those with powerful machines are probably the ones sharing screenshots and gameplay videos. You want people watching these to see that this is a modern game, not something from last decade.

### Different quality settings is made easy by some game engines

I know Unity at least makes it easy to work with, by default, six different quality settings, although you can add more. These adjust the texture resolutions, pixel light counts, shadow distances, etc., and the default values for those already work well for most requirements. I would expect that most modern game engines would have a similar system.
> 1 votes

# Answer
**It depends on how much effort you want to put into this**

You could, of course, make the graphics very simple so that anyone can run it. This may put some people off from playing it though, since they want a game that looks good.

To fix this, you could have different graphics settings which the user can select. This is done in lots of big PC games these days, where there are defaults for different graphics levels. Most of them also allow players to turn on and off features like shadows and particles to adjust the performance.

This will take a lot of work to implement though and it is only done by the big games made by companies. If you don't want to go into that much length, you could perhaps just have two settings. One of them will have shading, textures, and all of the high level graphics. The other will have all of those disabled so that any computer can run it.
> 2 votes

---
Tags: graphics, marketing
---


# Question
Title: Making quick time events in my text adventure more noticable
I'm making a post-apocalyptic text adventure in Unity. One of the gameplay features I've added is a quick time events on certain parts. Whether a part is a quick time event is defined inside the story json data like this:

```
  "PartName": {
    "text": "",
    "choices": {
    },
    "timer": { // if this key exists, the timer event will be triggered..
      "time": "10",
      "nextPart": "" //what part it goes to when the timer ends.
    },
    "background": "" //background of part
  },

```

When the timer runs out, you'll be forced into a part where the player dies or a unfavorable decision is made that will effect you later on in the game.

Here's a screenshot of a part that contains a quick time event:

Notice anything? The timer is the circle(radial timer) in the right hand corner. My main problem is trying to make sure players **know** there's a quick time event happening. These will be rare occurrences since I don't want to over-do them(ex: a quick time event every couple of parts) so I feel like the average player will not know that there's a quick time event.

One way I've thought of addressing this issue is by stating what a quick time event looks like in the how-to-play section of my menu, but since that's "locked" away by a button (you have to click a button to get to the section), people may just skip it entirely since text adventures aren't really known for the most complex controls in gaming.

Other ways I've thought of addressing it:

* Music cues

+ pros: I have complete control over what music I can put there
    + cons: Since some parts have a defined background music, it might not be noticed by the player
* Background tints (changing color of background)

+ pros: Easily noticeable change and will be unique only to timed parts.
    + cons: Might look ugly or players may not notice the significance of why the background suddenly changed color
* Large timer in the middle of the screen

+ pros: Easily noticeable and players will notice it's a timer
    + cons: May be obscured by a text and or look ugly.

So I need help either deciding which the best course of action will be to address the issue from the list above over

# Answer
There is really just one real solution to this conundrum: Playtest it! If players complain about not noticing they were making a decision under time-pressure, you need to find a solution. When they don't complain, everything is fine.

However, of the solutions you present, solutions one and two are unlikely to work because neither a musical cue nor a color change would give an intuitive indication how much time is left. The player would have to experience failure at least once to know how much long the danger music will play / how much redder the screen will become until they get a game-over. Having the player fail when they had no way of knowing how much time they had left during a timed challenge will be frustrating.

The circle indicator is far more intuitive in this regard. But the way it looks and is positioned on that screenshot it *might* be confused with a save-in-progress indicator. If playtesters complain about not noticing or misinterpreting it, consider placing it in a more prominent location. The gap between the introductory text and the answers seems like an obvious location. The two con's you mentioned are easily solvable by 1. using proper layouting to prevent it from obscuring anything and 2. redesigning it in a more aesthetically pleasing way. I personally find the decreasing progress bar which appears in some Telltale games quite nice (especially because it doesn't take much vertical space), but that's just a personal preference.
> 2 votes

# Answer
I'm not familiar with Unity's text-adventure capabilities--is there a technical reason not to just use text for this, by adding an additional message every N seconds until they act or time runs out?

> You quickly run into the bathroom of the shop and slam the door shut. Luckily, there's a lock; you flip the bolt into place just as the mutants start bashing on it...
>
> The door creaks under the strain; it won't hold long...
>
> Despite the thunderous pounding, you hear the unmistakable pop of wood splitting somewhere inside the doorjamb...
>
> Splinters spray on the floor when something massive crashes into the door, nearly ripping the topmost hinge free...
>
> A few frantic, grimy fingers appear in the gap next to the hinge and begin prying it open from top to bottom...
>
> The first few mutants fall into the bathroom atop the door as the rest stampede in over their backs.
> 2 votes

---
Tags: text, timer, text-based
---


# Question
Title: DirectX 11 Sprite Alpha (Invalid? + Bad Quality)
I have a bug with a texture font.

This is the texture file in photoshop:

This is the result I am getting:

The alpha from 0 and 1 shows weird artifacts as the final result, alongside the low quality of the image itself. How can i fix this?

```
blendStateDescription.RenderTarget[0].BlendEnable = TRUE;
blendStateDescription.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
blendStateDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;

blendStateDescription.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
blendStateDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_INV_DEST_ALPHA;
blendStateDescription.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ONE;
blendStateDescription.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
blendStateDescription.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;

float4 FontPixelShader(PixelInputType input) : SV_TARGET
{
   float4 color;

   // Sample the texture pixel at this location.
   color = shaderTexture.Sample(SampleType, input.tex);

   // If the color is black on the texture then treat this pixel as transparent.
   if(color.r == 0.0f)
   {
       color.a = 0.0f;
   }

   // If the color is other than black on the texture then this is a pixel in the font so draw it using the font pixel color.
   else
   {
       color.rgb = pixelColor.rgb;
       color.a = pixelColor.a;
   }

   return color;
}

// Create a texture sampler state description.
samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.MipLODBias = 0.0f;
samplerDesc.MaxAnisotropy = 1;
samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
samplerDesc.BorderColor[0] = 0;
samplerDesc.BorderColor[1] = 0;
samplerDesc.BorderColor[2] = 0;
samplerDesc.BorderColor[3] = 0;
samplerDesc.MinLOD = 0;
samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;

```

# Answer
> 1 votes
This is a rather odd setup for blend state:

```
// Default values
desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;

// Blend setup
desc.RenderTarget[0].BlendEnable = TRUE;
desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_INV_DEST_ALPHA;
desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ONE;

```

Typically you'd use the following for 'straight' alpha:

```
// Blend setup
desc.RenderTarget[0].BlendEnable = TRUE;
desc.RenderTarget[0].SrcBlend =
desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_SRC_ALPHA;
desc.RenderTarget[0].DestBlend =
desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;

```

And use this for premultiplied alpha:

```
// Blend setup
desc.RenderTarget[0].BlendEnable = TRUE;
desc.RenderTarget[0].SrcBlend =
desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
desc.RenderTarget[0].DestBlend =
desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;

```

And this for additive:

```
// Blend setup
desc.RenderTarget[0].BlendEnable = TRUE;
desc.RenderTarget[0].SrcBlend =
desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_SRC_ALPHA;
desc.RenderTarget[0].DestBlend =
desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ONE;

```

---
Tags: c++, directx11, alpha-blending, spritefont
---


title: PHP Quest System: Push or Polling?

text:
# Question
Title: PHP Quest System: Push or Polling?
I want to build a quest system in PHP. My idea so far was to create quests based on a class and write two functions for every quest: One is checking if its activated, the other will check the progress.

Since I have to do this on every page reload, this might be bad performance-wise. Is it possibleto build some kind of an event/push system with PHP? How would you do it? Yes, when something happens like the users buys something, a function gets called with for example "CAR\_BOUGHT\_BY\_PLAYER".

My problem is, I don't know how to go on from there. Any advice?

Thanks!

# Answer
There's two basic approaches to this.

**First, call a script at a regular frequency to perform the work.**

You can setup a Cron job that will call a given URL every so often, or at specific times throughout the day.

Your client could have a simple AJAX call that goes off if the timing is independent per player. This could even be adjusted if the player is doing something that needs more frequent checks, and then extended when they complete that task.

There are also other services that can be setup to call your scripts. For example, AWS Lambda can be scheduled to run every so often. While Lambda uses JS, Python, or Java. You could easily set something up with that to call your scripts on a regular basis. Bonus here is that if something goes wrong with your client or cron job, these should keep working.

**Second, only bother checking when players request information.**

Each time a player makes a request to your page, see if enough time has passed since the last check. If not, don't check.

If it has, then calculate if whatever events or timings your worried bout would have happened at that point. You control access to the data, they won't know if it was updated exactly and hour later, or three days later when they actually request it.

**Performance Notes**

If you find yourself needing to make frequent updates to data, or calculations that aren't based on a players immediate interaction, it may be best to decouple your architecture.

Have your data on a separate server than your PHP scripts. This way you can have a single server handling active page requests, and then another server to perform calculations or data updates/grooming.

This of course, is also dependent on volume. I recommend start by isolating your updating code from your code that serves information out to the users. Then just go with whatever approach seems easiest to you to run that updating code, knowing that if you need to, you can always pull it out and run it somewhere else.
> 1 votes

# Answer
You could use a Cron job that calls a .php file and checks the status of quests at whatever time interval you feel is appropriate. Run it every 30 seconds or every 24 hours. Whatever suits the game best.
> 0 votes

---
Tags: events, php, quests
---


title: How to make it my game level tough?

text:
# Question
Title: How to make it my game level tough?
I made the game space shooter. In my game the boss take too much time to fire and the enemy not even come in the screen. So how to manage the fire speed and make the level tough.Click the link on 2 and 3 also for image view.

shootscript. cs

```
using UnityEngine;
using System.Collections;

public class ShootScript : MonoBehaviour {

    public int dammage = 1;
    public bool isEnemyShot = false;
    public Sprite lightDestroy;
    public float laserTime;
    private float increament;

    void Update()
    {
        laserTime -= Time.deltaTime;
        if (laserTime <= 0) {
            Destroy(gameObject);
        }
    }

    void FixedUpdate()
    {
        if (!isEnemyShot) {
            this.transform.Translate (Vector2.up * 6 * Time.deltaTime);
        } else {
            this.transform.Translate (Vector2.up * -6 * Time.deltaTime);
        }
    }

    void OnCollisionEnter2D( Collision2D coll)
    {
        if (coll.gameObject.tag == "Player" || coll.gameObject.tag == "Enemy")
        {
            gameObject.transform.localScale = new Vector2 (1, 1);
            gameObject.GetComponent<SpriteRenderer> ().sprite = lightDestroy;
            gameObject.GetComponent<BoxCollider2D> ().isTrigger = true;
            Destroy (gameObject, 0.05f);
        } else {
            Destroy(gameObject);
        }
    }
}

```

Weapon.cs

```
using UnityEngine;
using System.Collections;

public class Weapon : MonoBehaviour {

    public Transform laserPrefab ;
    public bool isEnemyWeapon = false;
    public float shootDelay = 1.0f;
    private float waitToShoot;

    public bool firingContinously = true;
    float nextFire = 0;
    float fireDelay = 400; // 100 milliseconds between each bullet

    void Start () {
        waitToShoot = 0f;
        firingContinously = true;
    }

    void Update () {
        if(Input.GetKeyDown(KeyCode.G)){
            firingContinously = !firingContinously;
        }

        if(firingContinously && !isEnemyWeapon)
        {
            if(Time.time * 1000 > nextFire){
                nextFire = (Time.time * 1000) + fireDelay;
                Fire();
            }
        }

        if (waitToShoot > 0) {
            waitToShoot = Time.deltaTime;

        }

        if (Input.GetKeyDown (KeyCode.Space) && isEnemyWeapon == false) {
            Fire ();
        }

        if (isEnemyWeapon == true && EnemyAttack == true) {
            waitToShoot = shootDelay;
            var shootLaser = Instantiate (laserPrefab) as Transform;
            Vector2 pos = shootLaser.transform.position;
            pos.x = transform.position.x ;
            pos.y = transform.position.y - 0.1f;
            shootLaser.transform.position = pos;
//          SoundHelper.instanceSound.EnemyLaserSound();

        }
    }

    public void Fire()
    {
        var shootLaser = Instantiate(laserPrefab) as Transform;
        Vector2 pos = shootLaser.transform.position;
        pos.x = transform.position.x;
        pos.y = transform.position.y + 0.5f;
        shootLaser.transform.position = pos;
        //SoundHelper.instanceSound.PlayerLaserSound();
        Debug.Log("Fire Method");

    }

    public bool EnemyAttack
    {
        get
        {
            return waitToShoot <= 0f;
        }
    }
}

```

\[\]\[1\[Boss Laser\[\]\]

# Answer
> 0 votes
If I am correct, your enemy will never shoot because `Time.deltaTime` is never `<= 0`. But that could simply be a typo here on Stackoverflow. So make sure you use

```
if (waitToShoot > 0) {
    waitToShoot -= Time.deltaTime;

```

instead of

```
if (waitToShoot > 0) {
    waitToShoot = Time.deltaTime;

```

And to achieve a higher fire rate from the boss you can change `shootDelay` to a smaller number.

And to make the level though I guess there are like a thousand possibilities. I would make some special bullets like those you can see in some bullet hell games (e.g. bullets that spawn new bullets in different directions, faster bullets, etc.) and give the boss a lot of health so you really have to battle him for a while and you have to avoid a lot of bullets. Maybe you can add some smaller enemies as well if your boss is too weak or shoots too less bullets. Something like this.

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


# Question
Title: What should I use as units for my 2D game?
I'm trying to create my first C++ 2D fighting game from scratch, using SDL, and so far I got things to where I am able to move a couple sprites around using some keyboard keys. Right now, I have it so 1 unit of measurement equals 1 pixel; setting my player position to 900.0f 100.0f (my pixel units are of type float) will place him 900 pixels in the x direction and 100 pixels in the y direction.

At first, I thought that using pixels units for a sprite based 2D fighting game would make sense, but after thinking about it, I realized that I might have issues with differing screen resolutions. Someone with a higher screen resolution of 2560 x 1600 would move slower than someone with a lower screen resolution of 1920 x 1080.

Now I'm sure there would be ways to correct this specific issue, but it got me wondering if there would be better basic units of measurement I should be using for a 2D game. What should I use as units for my 2D game?

# Answer
You could define your movement in terms of "design units". In other words, you figure out how much "logical" distance a sprite would cover in a certain amount of time, which is then scaled dynamically based on the window resolution.

To do this, first, visualize your game screen as a grid, perhaps 100 by 100, or 160 by 90 (to fit 16:9 resolutions), or some other value. Each asset is placed along this grid on the X/Y axis, as appropriate. First, you calculate where the thing would be in terms of its logical location, which is then upscaled to the device's resolution.

In this system, 160 by 90 would be exactly 12 pixels per unit at 1080p, exactly 8 pixels at 720p, etc. So in one resolution, the sprite would move 12 pixels, and on another only 8 pixels, but would move the same physical distance on the screen (assuming screens of the same size), or the same relative distance (e.g. expressed as a percentage).

Some languages, like Flash/ActionScript have a default resolution expressed in logical units, others allow you to design your own, and others still will require that you do all the scaling yourself. If possible, consider using some variant of SVG (Scalable Vector Graphics) instead of bitmaps (PNG, JPG, GIF, TIFF, etc) in order to minimize the visual artifacts.

You haven't specified your platform, so the *precise* answer about how to do this will vary, but the general idea is that you should separate the logical units (where things are placed in relation to each other) from physical units (pixels).

Note that you could still choose to use bitmap-based graphics, but the quality will suffer somewhat. Typically, games like this tend to look "blocky", but that's often done intentionally for nostalgic purposes, as if it were an 8-bit game created in the 1980's instead of a modern game. There seems to be a lot of that going on in the market today, so you might decide that's your look. Try searching on your favorite search engine for "retro game design" if you're not sure what I'm talking about.
> 4 votes

# Answer
It is worth noting that SDL runs on top of OpenGL, which uses 'normalized device coordinates', which is a coordinate system ranging from \[-1, 1\] in both axes and the center of origin (0,0) being at the center of the screen. Y grows upwards, and X to the right. Using this has the added benefit that a **logical point** will always be at the center of the screen, no matter the chosen screen resolution.

It could be worth a look ;)
> 1 votes

---
Tags: 2d, sprites, fighting-game
---


# Question
Title: Structure GameObject - States - Visual representation
**Question**: What is the best data structure for GameObjects that have different states and thus different visuals?

**The situation is**:

I'm creating a game for mobiles (written in Kotlin, no Engine used).

My simplified object structure looks like this:

I have 2 GameObjects (e.g. *Person* and *Obstacle*)

Each GameObject might have two different states (*IDLE* and *MOVE*)

But each state might also have different graphics. For instance depending on the movement direction, the MOVE state might show Bitmap-Left or Bitmap-Right.

> Person -\> WALK-State -\> Visualisation (WALK, PERSON) -\> draw(bitmap\_walk\_left\_person)

My problem is, that I'm really not sure about that structure. Should I make subclasses for each State or a composition? One Visual object for each State (e.g. MOVE, IDLE, TALK) containing all Bitmaps for Person and Obstacle and always showing the right one depending on the parent?

**Currently it looks like this**:

I have the GameObject. The object has a *state* that is called in the update() method (e.g. moving a bit to the left). Every State has a "Visual" object that knows its parent State (State = WALK). It draws itself related to its states type (e.g. WALK) and considers (if needed) the orientation (left or right).

This felt like it keeps structures as abstract as possible but I'm not sure sure thats a good solution because all objects have to keep references to their "parents". **So the visuals need a reference to the state (WALK) and to the GameObject (Person) in order to draw the visual for a walking person.** Would it be better to create subclases for each State? So I have a class "VISUAL\_MOVE\_PERSON", "VISUAL\_IDLE\_PERSON", "VISUAL\_IDLE\_TREE" ... That seems a lot of redundant code and classes.

Is there a common structure for Actions / States and their Visual Representation? Especially since I will have many more objects with at least a few different states (IDLE, MOVE, TALK, ...)

Should the visuals be part of each state? Or are they independent to each other (e.g. GameObjects have a State and a Visuals object) instead of the "chain of references" shown above?

# Answer
> 2 votes
This is usually handled in a data-driven fashion. By treating your visuals as data objects, you end up with less code micro-managing which visual to use, and you open the possibility of being able to change your art, add more character types, or even allow your game to be modded by players, just by changing data files, without editing & recompiling your source code.

There are a lot of forms this could take:

* you could have a Spritesheet data object that maps a key representing a visual state to its corresponding graphic/region of an atlas. Each character type would have its own instance of this data structure, indexing only its own visuals.
* you could have an Animation data structure that knows the particular sequence of sprites to display for one action (which can help decouple your game logic from rendering logic when showing change over time). Your visual data for a single character would then be a collection of Animations for each state.
* for maximum decoupling, you could build an Animation State Machine that keeps track of a collection of Animations and the triggers to switch between them. Now your gameplay & AI logic doesn't need to know anything about sprites or animations at all — it just sends events to its state machine and it handles the necessary visual transitions.

In all of these cases, the visual structure doesn't know anything about the kind of entity it's representing, it just exposes something like a SetState method where we can inject a signal that it can use to choose the right representation from its collection of data.

So

```
frog.animation.SetAnimationState(JUMP)

```

and

```
player.animation.SetAnimationState(SWING_SWORD)

```

Are the same code running in the same animation class but just different instances with different data.

In general, any time you're tempted to make a subclass for each variety of thing in your game, it's a good time to check if any of it can be handled by different instances of data objects instead.

---
Tags: android, architecture, data-structure, state
---


# Question
Title: How to create JSON file in notepad that will hold my positional vector3 data for one type of object
I'm trying to get my head around using JSON files to store level data . Specifically in this example is to make my walls. (its a top-down game like pacman). Each wall prefab is a 1x1x1 cube. I just want the JSON to hold the x,y,z. I have seen tutorials about how best to deserialise the data into Unity and I think im fine doing that, but I am unsure of how exactly to word the JSON file.

I see the example on Unity docs says the format is like this:

```
{"level":1,"timeElapsed":47.5,"playerName":"Dr Charles Francis"}

```

so, I could just do something like:

```
{"index":0,"x":5,"y":1,"z":0}

```

but I know that there needs to be a bit above, similar to XML and of this im clueless of what it needs to contain.

I looked on Json.org but i didnt really understand it still. This is one example:

```
{
"glossary": {
    "title": "example glossary",
    "GlossDiv": {
        "title": "S",
        "GlossList": {
            "GlossEntry": {
                "ID": "SGML",
                "SortAs": "SGML",
                "GlossTerm": "Standard Generalized Markup Language",
                "Acronym": "SGML",
                "Abbrev": "ISO 8879:1986",
                "GlossDef": {
                    "para": "A meta-markup language, used to create markup languages such as DocBook.",
                    "GlossSeeAlso": ["GML", "XML"]
                },
                "GlossSee": "markup"
            }
        }
    }
}

```

}

But what is 'Glossary' and 'title' in the context of my game? All I currently have is a cube called Wall, with a script attached called Wall.cs that currently does nothing, but I will be making an array of Wall and plan on using the deserialised data from the json file to lay the Walls\[\] out using my GameController.cs

Once I know what to put above and below to open and close the JSON file off, im pretty sure I can get it working how I need it to. I hope that made some sense.

# Answer
What you are looking for is probably an Array, unless you want to name each of your wall parts.

```
{
  "walls": [
    {
      "x": 1,
      "y": 1,
      "z": 1
    },
    {
      "x": 2,
      "y": 1,
      "z": 1
    },
    {
      "x": 3,
      "y": 1,
      "z": 1
    },
    {
      "x": 3,
      "y": 1,
      "z": 2
    }
  ]
}

```

Couple of quick tools to help:
https://jsonlint.com/
http://www.json.org/
http://json2csharp.com/

As for the C# serialization, getting this data into a class. You may be able to make a class that holds an array of Vector3 objects. I haven't done serialization with Unity specifically, but with C# alone.
> 1 votes

---
Tags: unity, c#, level-design, serialization, json
---


title: Oscillate an object's scale

text:
# Question
Title: Oscillate an object's scale
I am able to scale an object using a scaling function I wrote. Internally it builds matrices that are multiplied by each of the vertices to transform them. The parameters I give the scaling function tell it how much to scale the object by **as a factor of its current scale**.

I want my object's scale to smoothly oscillate between two values, so I have used Sin waves to build my scaling factor, which is:

```
1 + amplitude * (Mathf.Sin(2 * Mathf.PI * frequency* Time.time) - Mathf.Sin(2 * Mathf.PI * frequency * (Time.time - Time.deltaTime)))

```

The result looks very close to what I want, but with each oscillation, the object gets slightly smaller than before.

The problem is that my function is written so that it scales the vertices as a factor of its 'current' scale, which is always changing.

# Answer
Generally, you always apply transformations to the original unscaled/untransformed object.

Theoretically, in your case, since you are simply calculating a scaling factor, and under the assumption that it's never zero, you can always invert the scale transform by using the inverse of the old scaling factor before applying the new one.

Something like this (pseudocode):

```
if (/* sOld isn't set */)
{
    sOld = 1;
}

sOldInverse = 1/sOld;     // assuming sOld is never 0
s = (result of your function);

s = sOldInverse * s;  // the new scalling factor
sOld = s; // store somewhere until the next update

```

*However*, in practice you might run into issues with numerical precision; since you don't have the original scale, tiny errors may accumulate over time, leading to wrong results.
> 1 votes

---
Tags: unity, c#, 3d, matrix, geometry
---


# Question
Title: Position Text Mesh above parent transform in world space
I'm making an isometric-ish 2d game in Unity. I want to display text above a sprite during certain conditions. For this, I'm using a TextMesh instantiated as a child of the sprite.

In local space, this obviously means that when I rotate a sprite, its children rotate along with it. From the player's perspective, the label now appears to the side of the sprite, rather than staying above it.

I can always calculate the world space position of the TextMesh during LateUpdate(), but a) that solution requires a designer to know that a script will alter the local transform, and b) things built into Unity have more eyeballs on them, so I'd rather use that.

Is there a mechanism built into Unity such that I can set a child's transform in the inspector to e.g. `position.y = 0.4` and have it render 0.4 units above the parent in *world* space? Edit: Additionally, I want it to follow the parent as it moves, so just calculating once on `Instantiate()` isn't quite what I want either.

# Answer
> 1 votes
# Create your own component to do this

Create a MonoBehaviour component script that exposes a public `Vector3` that is then used to update the position of the object in WorldSpace instead of local.

---
Tags: unity, transformation, coordinates
---


title: Imitate a textured sphere in 2D

text:
# Question
Title: Imitate a textured sphere in 2D
I'm writing planet generator, using pico8. I got surface generation done:

And the last thing to do is to map the texture onto a sphere. Pico8 has no triangle function. So my question is, how do I make a sphere in my 2d space, and how do I apply a texture on it?

Looking for an effect like this (with no lighting, of course!):

I have really bad knowledge of 3d space manipulations. The full list of available API functions can be found **here**.

**Update 4:**

Solved!

Try it live here.

# Answer
Here's a rundown of a few different ways we can sample a panning texture to make it look like a globe...

Since I'm not deeply familiar with Pico-8 syntax & conventions, I'll try to present these as pseudo-code that should be reasonably straightforward to translate / token-reduce as needed.

```
// iterate over each pixel in the discSize x discSize bounding square
for x = left...left + discSize
    for y = top...top + discSize

        // convert pixel position into a vector relative to the center,
        // normalized into the range -1...1
        px = (x - left) * 2/discSize - 1
        py = (y - top) * 2/discSize - 1

        // get the squared magnitude of this vector
        magSq = px * px + py * py

        // if we're outside the circle, draw black/background and skip ahead
        if ( magSq > 1 )
           plotPixel(x, y, BLANK)
           continue

        // TODO: warp our local offset vector px py to imitate 3D bulge

        // convert our local offsets into lookup coordinates into our map texture
        u = time * rotationSpeed + (px + 1) * (mapHeight/2)
        v = (py + 1) * (mapHeight/2)
        // wrap the horizontal coordinate around our map when it goes off the edge
        u = u % (2 * mapHeight)

        // look up the corresponding colour from the map texture & plot it
        color = lookupFromMap(u, v)
        plotPixel(x, y, color)

```

If you just use this as-is, you'll get the left version: it's cropped to a circle and wraps around, but it's very flat-looking.

By tweaking `px` and `py` where it says "`TODO`" we can get different bending effects.

Here's an equivalent implementation of **Bálint's suggestion** in this form:

```
widthAtHeight = sqrt(1 - py * py)
px = px / widthAtHeight

```

If we want an exactly correct sphere as viewed by an orthographic camera, we can use inverse trig functions to convert to **latitude & longitude**:

```
widthAtHeight = sqrt(1 - py * py)
px = asin(px / widthAtHeight) * 2/3.141592653589
py = asin(py) * 2/3.141592653589

```

(This assumes asin's return value is in radians. If using another unit, divide by whatever value corresponds to 90 degrees, instead of by pi/2. The idea is to map asin(-1)...asin(1) back into the range -1...1)

This gives the version second from the right, which you can see is a very good match for rendering a real 3D sphere (far right). The downside is that transcendentals like the arcsine function can be expensive. This may or may not be an issue in your case.

If you're looking for something to give a more bulgy look without the trig, you can use something like a **lens distortion** for a cheap hack:

```
scale = 0.35 * magSq + (1 - 0.35)
px = px * scale
py = py * scale

```

At the edges of the disc, scale is 1 so there's no difference versus the flat version. Closer to the center, this shrinks the length of our local offset vector (down to a controllable minimum set by the 0.35 linear interpolation constant), which has the effect of magnifying features close to the middle.

Of course these are just a few different ways you could get a bulged look. You could try all kinds of other formulae, or even go for a perspective camera look instead of the orthographic version I've shown here.
> 9 votes

# Answer
First of all, this is going to cut corners, as this API is very small (I have concerns about the maximum 8192 tokens rule, which technically makes this non-turing-complete). The algorithms you need to use are the pythagorean theorem (`√(x² + y²)`) and the width of a circle at a specific height (`2√(r² + |y - cy|²)` where cy is the y coordinate of the circle).

So, you need to loop through the square that contains the circle. If the radius of the sphere is `r` and the center of it is `(cx; cy)`, then you need to loop through the coordinates between `(cx - r; cy - r)` and `(cx + r; cy + r)`. Let the coordinates of the current pixel be `(x; y)`.

If `√((x - cx)² + (y - cy)²)` is less then or equal to the radius of the sphere, then the pixel is inside the 2d projection of the sphere.

Next we need to map this coordinate to a coordinate on the texture. Here we use the circle width formula. Get the width of the circle at the current position, let's name it `segmentWidth` Because we usually see around half of a sphere, we can just say that the coordinates of the pixel on the texture is

```
x = round(((x - cx) / segmentWidth + 0.5) * textureWidth / 2)
y = round(((y - cy) / r / 2 + 0.5) * textureHeight)

```
> 2 votes

---
Tags: 2d, textures, sphere, pico-8
---


# Question
Title: GLSL shader error on different computers
I recently discovered a strange error with my fragment shader:

```
#version 330 core

in vec4 v_color;
in vec2 v_texCoords[10];

out vec4 frag_color;

uniform int actual_textures;
uniform sampler2D u_texture[10];

void main() {
    vec4 final_color = texture2D(u_texture[0], v_texCoords[0]);
    for(int i = 1; i < actual_textures; i++){
        vec4 tex = texture2D(u_texture[i], v_texCoords[i]);
        final_color = tex * tex.a + final_color * (1 - tex.a);
    }

    frag_color = v_color * final_color;
}

```

On my PC with a GTX 960 and OpenGL 4.5.1 there is no error at all. But on my laptop with an Intel HD 3000 and OpenGL 3.3, I get a compile error that the texture2D function is deprecated and that the sampler2D array size is too big because I only pass 3 textures at the moment and I want the array to be able to handle up to 10 textures. On any other computer I testedm the error didn't occur, but they all had nvidia or amd gpus. Why do I keep getting this error on my laptop?

# Answer
Don't use `texture2D`, it was replaced by `texture` after glsl version 130 and it supports every sampler type.

The `array size is too big` error isn't about unused space. It simply means that you can't have 10 active textures at once, so there's no reason to expect that much. Usually the limit is around 8. You should use array textures instead.
> 3 votes

# Answer
Use `texture` instead of `texture2D`.

Secondly, the max number of active texture units varies with hardware. I've ran into this problem before, and found that the HD4000 integrated graphics processor only supports two active texture units, so I'd imagine the HD3000 will be similar.

A call to `glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB,&value);` will tell you the max bound textures you can have per pass for a target graphics device.
> 1 votes

---
Tags: opengl, shaders
---


# Question
Title: GLSL shader performance reduced by loop?
I hav a fragment shader like this:

```
#version 330 core

in vec4 v_color;
in vec2 v_texCoords[10];

out vec4 frag_color;

uniform int actual_textures;
uniform sampler2D u_texture[10];

void main() {
    vec4 final_color = texture(u_texture[0], v_texCoords[0]);
    for(int i = 1; i < actual_textures; i++){
        vec4 tex = texture(u_texture[i], v_texCoords[i]);
        final_color = tex * tex.a + final_color * (1 - tex.a);
    }

    frag_color = v_color * final_color;
}

```

But somehow this slows my game down by 30 - 40fps in comparison to this approach:

```
#version 330 core

in vec4 v_color;
in vec2 v_texCoords[10];

out vec4 frag_color;

uniform sampler2D u_texture[10];

void main() {
    vec4 final_color = texture(u_texture[0], v_texCoords[0]);
    vec4 tex = texture(u_texture[1], v_texCoords[1]);
    final_color = tex * tex.a + final_color * (1 - tex.a);
    tex = texture(u_texture[2], v_texCoords[2]);
    final_color = tex * tex.a + final_color * (1 - tex.a);
    //...

    frag_color = v_color * final_color;
}

```

Why does a single loop slow the gpu down so much?

# Answer
I've encountered this issue when implementing other shader types with certain hardware configurations.

I believe the issue lies with `texture(u_texture[i], v_texCoords[i]);` : because the graphics hardware performs prefetch on texture units, it needs to be able to predict to some degree what it will be fetching, or you experience performance drop similar to a cache miss.

Unrolling the loop allows the code to perform the prefetch properly, allowing for a higher framerate.
> 2 votes

---
Tags: opengl, glsl, performance, gpu
---


# Question
Title: Unity2D Having trouble steering gameobject
So I am making a 2d maze game where one of the enemies has to follow the player once it detects the player. I am currently using a steering method to steer the enemy towards the player and also when it detects a wall. I am not using any sort of path finding algorithm, just using steering to make a "dynamic" path finder. But I am having some trouble steering the enemy away from the walls and then resume moving towards the player.

This is what I am doing right now:

* follow the player when it is detected
* set the enemy's velocity towards the player.
* use a raycast to detect if a wall is ahead
* if raycast detects the wall, steer the enemy towards the direction it is moving in, then steer it towards the position of the player again. E.g if it is moving up while following the player and hits a wall on the left or right, it will steer up.

I am having a hard time steering the enemy away from the wall and then back towards the player again, because once it steers away from the wall and isn't hitting a wall anymore, it checks where the player is to resume it's pursuit, but then the player goes too far away from the enemy and so it doesn't know where to move towards.

Here is the code:

```
 void Update()
  {
     RaycastHit2D hit2D = Physics2D.Linecast(transform.position, player.transform.position, 1 << 8);
     if (hit2D)
     {
         string wallTag = hit2D.collider.tag;
         FindMovementDirection(ref wallTag);
         wallHit = true;
     }
     else
     {
         wallHit = false;
     }
  }
 void FindMovementDirection(ref string wallTag)
 {
     int len = 3;
     if (wallTag == "V_Wall")
     {
         if (currentVel.y <= 0) currentDirection.localPosition = new Vector3(0, -len, 0);
         else currentDirection.localPosition = new Vector3(0, len, 0);
     }
     else if (wallTag == "H_Wall")
     {
         if (currentVel.x <= 0) currentDirection.localPosition = new Vector3(-len, 0, 0);
         else currentDirection.localPosition = new Vector3(len, 0, 0);
     }
 }
 void seekSteer()
  {
     float maxForce = 0.8f;
     float maxSpeed = 6;
     if (wallHit)
     {
         desiredVel = currentDirection.position - transform.position;
     }
     else
     {
         desiredVel = player.transform.position - transform.position;
     }
     desiredVel.Normalize();
     desiredVel *= maxSpeed;
     steerVel = desiredVel - currentVel;
     if (steerVel.magnitude > maxForce)
     {
         steerVel.Normalize();
         steerVel *= maxForce;
     }
     currentVel += steerVel;
     if (currentVel.magnitude > maxSpeed)
     {
         currentVel.Normalize();
         currentVel *= maxSpeed;
     }
 }
 void FixedUpdate()
 {
     transform.position += currentVel * Time.fixedDeltaTime;
 }

```

Another thing that I would like to ask is that, should I be using a path finding algorithm? I am aware that I am not using one and that is because I want the enemy to find it's path dynamically. I also know that path finding and steering go hand in hand most of the time, so am I doing it wrong? Thanks.

# Answer
Save yourself some trouble. Since you are using Unity, you have access to NavMeshes. You specify a surface as walk-able (the floor of the maze), and then Unity will form a mesh from all its flat surfaces. In other words, all walls will be excluded from this mesh. Unity uses this to figure out how to get from any point on the floor to any other point on the floor. Then, you make the enemy a NavMesh Agent, assign it the NavMesh, and then make the player a target. That will take care of all the pathfinding, and even update the path as the target player moves. The tutorials are easy to follow and shouldn't take that long.

Your other options are to implement pathfinding yourself, which is rarely worth it and usually more buggy, or to have your simple navigation get your enemy trapped in a dead end or going in circles.
> 1 votes

---
Tags: unity, c#, path-finding, steering-behaviors
---


# Question
Title: Still having problems using Json data in Unity
I have the following classes and json file, i thought id followed the documentation exactly but I am clearly wrong. Can anyone see why I get an error just saying : INVALID VALUE in my unity console:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

[Serializable]
public class DataReader
{
public float[] x;
public float[] y;
public float[] z;
}

```

GameController:

public class GameController : MonoBehaviour { public static GameController instance;

```
DataReader dataReader;

private string gameDataFileName = "level1.json";

private void Awake()
{
    dataReader = JsonUtility.FromJson<DataReader>(gameDataFileName);
    instance = this;
}

void Start () {

    // create level:
    print("DATA: " + dataReader.x[0]);
}

}

```

and the json is stored in StreamingAssets folder (I also tried a copy in Resources folder):

```
{
"x": [{1},{1},{1},{1}],
"y": [{1},{1},{1},{1}],
"z": [{1},{2},{3},{4}]
}

```

# Answer
> 1 votes
Remove the curly braces from your values.

```
{
"x": [1,1,1,1],
"y": [1,1,1,1],
"z": [1,2,3,4]
}

```

Though I'd also recommend for sanity sake to group by point and not by axis.

```
[Serializable]
public class Point
{
  public float x;
  public float y;
  public float z;
}

[Serializable]
public class DataReader
{
  public Point[] points;
}

{
  "points": [
    {
      "x": 1,
      "y": 1,
      "z": 1
    },
    {
      "x": 1,
      "y": 1,
      "z": 2
    },
    ...
  ]
}

```

# Answer
> 1 votes
```
public class GameController : MonoBehaviour {
public static GameController instance;

//public InterstitialAd interstitialAd;

TextAsset textAsset;

DataReader dataReader;

List<float> xList = new List<float>();

private void Awake()
{
    textAsset = Resources.Load<TextAsset>("level1");
    print("JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJSON = " + textAsset.text);
    dataReader = JsonUtility.FromJson<DataReader>(textAsset.text);

    instance = this;
}

void Start () {
    // this just requests the ad, doesnt show it:
    //interstitialAd = AdvertsInterface.instance.RequestInterstitial();

    for (int i = 0; i < dataReader.x.Length; i++)
    {

        xList.Add(dataReader.x[i]);
    }
    // create level:
    print("DATA: " + xList[0]);
}

void Update () {

}

```

}

This code fixed it. I was missing the TextAsset taht whats confused me the whole time.

---
Tags: unity, c#, level-design, serialization, json
---


# Question
Title: How to change the virtual joystick Input direction depending on camera rotation so the player moves to its current forward direction?
I have a scene set up where the player moves and rotates with Virtual Joystick Input. I have button which rotates the camera to the back of my player at that point I want to change the joystick input direction so it moves my player to towards its current forward direction.

> The joystick Scripts:

**1)** script to handle events:

```
public class joystickEvents extends EventSystems.EventTrigger{
  var position:Vector2=Vector2.zero;

  public var joyStickHolder:Transform;
  private var pointerUp:boolean=false;

  function Update(){
    if(position!=Vector3.zero && pointerUp){
       position=Vector3.Lerp(position,Vector3.zero,5*Time.deltaTime);

    }
  }
   public function OnDrag(data:EventSystems.PointerEventData){
      position=data.position-joyStickHolder.position;
   }
   public function OnPointerUp(data:EventSystems.PointerEventData){

     pointerUp=true;

    }
  public function OnPointerDown(data:EventSystems.PointerEventData){
     pointerUp=false;
  }

}

```

**2)** script for joystick movement:

```
   public class joystick extends MonoBehaviour{
    var joystickEvents:joystickEvents;
    var joystickHolder:RectTransform;
          var dir:Vector3;
    private var maxDist:float;
    private var direction:Vector3;
    private var magnitude:float;

     function Start(){
        maxDist = joystickHolder.sizeDelta.x;
        maxDist=maxDist/2.5;
     }

     function OnGUI () {

        if(joystickEvents.position.magnitude>(maxDist))
              magnitude=maxDist;

        else{
          magnitude=joystickEvents.position.magnitude;

        }
        direction=joystickEvents.position.normalized;

      transform.localPosition=direction*magnitude;
        dir=direction*(magnitude/maxDist);
    }
  }

```

The player controller script takes the variable `dir` to move around the world. I think this value must changed somehow to so that move the player moves towards its current forward based on joystick input when camera is rotated.

> Here some part of playerController responsible for player movement:

```
public class charcterController extends MonoBehaviour{
 private var controller  : CharacterController;
 private var moveDirection : Vector3 = Vector3.zero;
 var speed : float = 6.0;
 var joystick:joystick; //reference to the joystick script
  function Start(){
       controller = GetComponent.<CharacterController>();
    }
  function Update() {
        var joyInput:Vector3=joystick.dir; //the dir in joystick script
        dir=Vector3(joyInput.x,0,joyInput.y);
        if (controller.isGrounded) {
        moveDirection = dir;

        moveDirection *= speed;
        controller.Move(moveDirection * Time.deltaTime);
         rotate();
      }
  function rotate(){
      if(dir!=Vector3.zero)
          transform.rotation = Quaternion.LookRotation(dir);
      }
 }

```

# Answer
> 1 votes
You want to transform `dir` according to the camera:

```
dir = cam.TransformDirection(dir);

```

This treats `dir` as if it was a direction relative to the camera, and returns what the direction would be if global. You can read more about it on the Unity Scripting API.

Also, I notice the camera has a slight downward angle. Getting it relative to the camera would mean trying to move slightly down all the time. You could fix that by setting the y on the transformed `dir` to zero. Then, if you want to preserve magnitude, `newDir.normalized * oldDir.magnitude`. Alsogether, it might look something like this:

```
var cam : Transform;
function Update() {
    ...
    dir = cam.TransformDirection(dir);
    moveDirection = dir;
    moveDirection.y = 0;
    moveDirection = moveDirection.normalized * dir.magnitude;
    ...
}

```

---
Tags: unity, movement, unityscript, joystick
---


# Question
Title: Why does Unity Eventsystem lag on first touch?
Hi I am making a very simple simple platformer game for android devices. I am using Unity's event system for player movement. The problem is when I touched the button first time there is a lag (hiccup) after then everything is ok. I have profiled my game there is a spike in EventSystem Update method.

here is the simplified code,

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent (typeof(Rigidbody2D)) ]
[RequireComponent (typeof(BoxCollider2D)) ]
public class PlayerController : MonoBehaviour {

public float movementSpeed = 5f;
public float jumpForce = 5f;
public float distanceToGround = 0.2f;
public LayerMask staticCollider;
public playerState state;

private Rigidbody2D rBody;
public Transform leftmost;
public Transform rightmost;

Collider2D[] platforms = new Collider2D[2];
public int hrInput = 0;

// Use this for initialization
void Start ( ) {
    rBody = GetComponent<Rigidbody2D> ();

}

//FixedUpdate is framerate independent, and therefore completely unrelated to your framerate

void FixedUpdate ()
{
    state.grounded = isGrounded ();

    if (hrInput > 0) {
        MOVE_RIGHT ();
    }
    else if (hrInput < 0) {
        MOVE_LEFT ();
    } else {
        STOP_MOVE ();

    }

}

public bool isGrounded(){
    print ("ground");
    if (Physics2D.OverlapAreaNonAlloc (leftmost.position, rightmost.position, platforms, staticCollider) > 0) {
        return true;
    } else
        return false;
}

public void setHrInput (int h ) {
//    print (h);

    hrInput = h;
}

public void JUMP(){
    if(state.grounded){
        state.onAir = true;
      //  rBody.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
        rBody.velocity = Vector2.up * jumpForce;
    }
}

public void MOVE_LEFT(){
    rBody.velocity = new Vector2 (-1 * movementSpeed * Time.deltaTime, rBody.velocity.y);
}

public void MOVE_RIGHT(){
    rBody.velocity = new Vector2(1 * movementSpeed*Time.deltaTime, rBody.velocity.y);
}

public void STOP_MOVE(){
    rBody.velocity = new Vector2(0,rBody.velocity.y);
    }

} // end

```

Here is the profiler Image.

Please help me to fix this issue.

# Answer
Touch input is always a bit of a PITA (I actually recommend the InControl package / not affiliated in anyway) regardless, I believe that the main problem you're experiencing is due to your check for input in FixedUpdate. Input should be checked in Update, FixedUpdate is for updating physic bodies. https://docs.unity3d.com/Manual/ExecutionOrder.html
> 1 votes

---
Tags: unity, unityscript
---


title: Setting up an "Oct-Tree"

text:
# Question
Title: Setting up an "Oct-Tree"
Instead of spam the same hard question like my previous one that Is difficult to get a minimum verifiable example for, I have decided to rework my path-finding and I can fix a lot of my issues with an oct-tree, not a true one but rather just subdividing my world into 8 or however many i specific in the function as this is all thats needed.

I already know what i need to do the stage after this, but I'm a not sure the best way to approach the subdivision so i get the right vector points of the subdivided cubes.

div = the number of cubes I want to create.

If I already have my 8 points,

```
    worldspace(Vector3 origind, float sized)
{
    //  face1
    ca = Vector3{ origin.GetX() + sized,origin.GetY() + sized, origin.GetZ() - sized };
    cb = Vector3{ origin.GetX() + sized,origin.GetY() - sized, origin.GetZ() - sized };
    //-----------------------------------------------------------------------------
    cc = Vector3{ origin.GetX() - sized,origin.GetY() - sized, origin.GetZ() - sized };
    cd = Vector3{ origin.GetX() - sized,origin.GetY() + sized, origin.GetZ() - sized };
    //  face 2
    ce = Vector3{ origin.GetX() + sized,origin.GetY() + sized, origin.GetZ() + sized };
    cf = Vector3{ origin.GetX() + sized,origin.GetY() - sized, origin.GetZ() + sized };
    //-----------------------------------------------------------------------------
    cg = Vector3{ origin.GetX() - sized,origin.GetY() - sized, origin.GetZ() + sized };
    ch = Vector3{ origin.GetX() - sized,origin.GetY() + sized, origin.GetZ() + sized };
};
~worldspace();

```

I can define my worldspace as worldspace(0,0,0,25) so thats a cube of 25 units, but then I want to divide it in the most efficient way into 8 = cubes lets say or so and make them into a vector.

I'd like the function to be able to specify how many subdivisions i want, I don't want a dynamic one, so I think. So I'm thinking I could do something along the lines of

semi pseudocode

```
createoct(div)
int divisions = div
for (int i = 1; i =< div; i++)
{
  dist of ca to cb / div ?
  store the new point
  do the same for the other points ?
}

```

Am I going about this the right way ? what would be the best way to calculate the subdivisions and store their 4 seperate points as one object ? perhaps a new class ?

# Answer
If you want `div` to represent the number of cubes then you need to ensure that `div` is a cube (as in, is an integer to the 3rd power). So 1, 8, 27, etc. Given that, you could do the following:

```
#include <stdlib.h>
#include <cmath>
#include <assert.h>
#include <vector>

struct Vector3 {
    float   x;
    float   y;
    float   z;
};

struct Cube {
    Vector3 origin;
    float   sideLen;
};

void subdivideCube(const struct Cube& cube, const int numCubes, std::vector<struct Cube>& newCubes)
{
    // Ensure that the input numCubes has an integer cube root
    assert(std::cbrt(static_cast<float>(numCubes)) == floor(std::cbrt(static_cast<float>(numCubes))));

    float numDivisionsPerSide   = std::cbrt(static_cast<float>(numCubes));
    float divisionLen           = cube.sideLen / numDivisionsPerSide;

    for (float x = cube.origin.x; x < cube.origin.x + cube.sideLen; x += divisionLen)
    {
        for (float y = cube.origin.y; y < cube.origin.y + cube.sideLen; y += divisionLen)
        {
            for (float z = cube.origin.z; z < cube.origin.z + cube.sideLen; z += divisionLen)
            {
                struct Cube newCube = { { x, y, z }, divisionLen };
                newCubes.push_back(newCube);
            }
        }
    }
}

int main()
{
    Vector3 origin  = {10.0, 10.0, 10.0};
    float   size    = 1000.0;
    Cube    volume  = { origin, size };
    int     divs    = 8;
    std::vector<struct Cube>   newCubes;
    subdivideCube(volume, divs, newCubes);
}

```
> 1 votes

---
Tags: c++, octree
---


title: LibGDX - Wait for action to complete

text:
# Question
Title: LibGDX - Wait for action to complete
With Scene2D, in the `act()` method of a `Group`, under certain circumstances I add actions to some children (eg a moveTo, or a fadeOut), which last a few tenths of seconds. Now I need ALL these action to complete before I start running the code in `act()` again. Right now I'm using a kludge with a timer, I set a variable `actionRunTime` before attaching the actions to children, set to the value of how long all actions should take to complete, then in `act()` I do

```
public void act(float delta){

  super.act(delta);  // to have the actions run on children

  actionRunTime -= delta;

  if (actionRunTime >= 0) return;

  // ... code to run when no action is running

```

This looks terrible to me. Is there some cleaner way?

# Answer
> 2 votes
You can create an `Action` that is shared across `Actor`s and that counts down a value to zero, then use this state in conjuction with a `SequenceAction` to find out when a series of `Action`s have completed.

For example, with an `Action` like this;

```
public class CountDownAction extends Action {
    private int count;

    @Override
    public boolean act(float delta) {
        --count;
        return true;
    }

    public void setCount(int value) { count = value; }

    public boolean isComplete() { return count == 0; }
}

```

You can have a `Group` where you add `Action`s to the children and always add them in sequence with the same `CountDownAction` instance as the last `Action`;

```
package com.bornander.sandbox;

import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.scenes.scene2d.Action;
import com.badlogic.gdx.scenes.scene2d.Group;
import static com.badlogic.gdx.scenes.scene2d.actions.Actions.sequence;
import static com.badlogic.gdx.scenes.scene2d.actions.Actions.fadeIn;
import static com.badlogic.gdx.scenes.scene2d.actions.Actions.fadeOut;
import com.badlogic.gdx.scenes.scene2d.ui.Image;

public class MyGroupActor extends Group {
    private final Image actorA;
    private final Image actorB;
    private final Image actorC;

    private final CountDownAction countDown = new CountDownAction();

    public MyGroupActor(Texture texture) {
        actorA = new Image(texture);
        actorB = new Image(texture);
        actorC = new Image(texture);

        addActor(actorA);
        addActor(actorB);
        addActor(actorC);

        actorA.setBounds(0, 0, 200, 200);
        actorB.setBounds(200, 200, 200, 200);
        actorC.setBounds(400, 400, 200, 200);
    }

    @Override
    public void act(float delta) {
        super.act(delta);
        if (countDown.isComplete()) {
            System.out.println("All actions have executed");
        }
    }

    public void addSomeActions() {
        // We have three Actors to track, so set count to 3
        countDown.setCount(3);
        // Note that it is the same instance of the CountDownAction that is being used across all Actors here
        actorA.addAction(sequence(fadeOut(1),            countDown));
        actorB.addAction(sequence(fadeOut(1), fadeIn(1), countDown));
        actorC.addAction(sequence(fadeOut(0.5f),         countDown));
    }
}

```

In the above example, three difference sets of `Action`s

* Fade out over 1 second
* Fade out over 1 second then fade in over 1 second
* Fade out over 1/2 second

all run with different execution times, but since the count down runs at the end of all those three, the `CountDownAction` will report `isCompleted() == true` only when all of them are done (in this case after 2 seconds) without you having to manually track the execution time.

---
Tags: libgdx, animation, scene2d
---


# Question
Title: How to make a field visible (attachable) in the inspector but inaccessible through code (private-like)?
Let's say I have a variable named `button` of type `Button` which is of course `System.Serializable`.

I want that variable to be assignable through the inspector, so I make it `public`:

```
public class SomeScript : MonoBehaviour{
    public Button button;
}

```

Which gives me that:

Now, I want to keep the code clean & secure (organized) and there's a real reason why I need to preserve the encapsulation.

I know that there are multiple ways of retrieving components on runtime like `transform.Find("Some/Genius/TypeUnsafe/Path")` or `GameObject.Find("3 seconds scene iteration").GetComponent(...).` I want to avoid that.

How do I mix a variable `private access` with it's `public access` in the inspector?

# Answer
You're looking for the SerializeField Attribute

From the docs:

> Force Unity to serialize a private field.
>
> You will almost never need this. When Unity serializes your scripts, it will only serialize public fields. If in addition to that you also want Unity to serialize one of your private fields you can add the SerializeField attribute to the field.

Your code would then look like this:

```
public class SomeScript : MonoBehaviour{
    [SerializeField]
    private Button button;
}

```
> 19 votes

# Answer
You can show your private variable By adding ***SerializeField*** attribute before the variable. Something like this

```
[SerializeField]
private Button button;

```

The above variable will be displayed to your inspector but your other classes will unable to get it. **Conversely** you can also hide your public filed in inspector through ***HideInInspector*** attribute. Something like this

```
[HideInInspector]
public Button button;

```

Your above variable will be accessible by your other script but it will not be displayed to inspector.
> 2 votes

---
Tags: unity, serialization
---


title: C++ Freetype advance X problem

text:
# Question
Title: C++ Freetype advance X problem
I'm currently working on a font-rendering system for my OpenGL based engine. I sure got something to work, but the only thing I still have problems with, is the horizontal advance!

This is what it spits out, obviously not correct. If I understood correct from the documentation and some other threads, this is the procedure to draw a string:

1. set current drawing position to (0, 0)
2. draw first character
3. move drawing position in the x for advance.x
4. draw second character
5. move drawing position in the x for next face-\>glyph-\>advance.x
6. ... repeat

Is that correct? If not, what am I doing wrong? I think its worth to say that I render every character as a texture!

# Answer
> 1 votes
As Bálint stated, the advance is for the next char. So just moving the cursor after drawing the current one solved it!

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


title: OpenGL glTexImage3D not working?

text:
# Question
Title: OpenGL glTexImage3D not working?
I'm trying to use arrax textures with opengl 3.3 since this the target version for my application. So I have to use the `glTexImage3D()` method instead of `glTexStorage3D()`. The problem is, if I use `glTexImage3D()` instead of `glTexStorage3D()` the screen is always black. The other way round, everything works. Here is how I create the array texture:

```
public ArrayTexture(int width, int height) {
    this.width = width;
    this.height = height;
    this.arrayTextureHandle = GL11.glGenTextures();
    GL13.glActiveTexture(GL13.GL_TEXTURE0);
    GL11.glBindTexture(GL30.GL_TEXTURE_2D_ARRAY, arrayTextureHandle);

        //Works perfect
        GL42.glTexStorage3D(GL30.GL_TEXTURE_2D_ARRAY, 1, GL11.GL_RGBA8, width, height, 10);
        //Doesn't work with these parameters
        //GL12.glTexImage3D(GL30.GL_TEXTURE_2D_ARRAY, 0, GL11.GL_RGBA8, width, height, 10, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, (ByteBuffer)null);

    GL11.glBindTexture(GL30.GL_TEXTURE_2D_ARRAY, 0);
}

public void addTexture(ScrollingSprite... sprites) {
    if(zLayerCounter + sprites.length <= MAX_LAYERS) {
        GL13.glActiveTexture(GL13.GL_TEXTURE0);
        GL11.glBindTexture(GL30.GL_TEXTURE_2D_ARRAY, arrayTextureHandle);

        Arrays.asList(sprites).forEach(sprite -> {
            sprite.getTexture().getTextureData().prepare();
            GL12.glTexSubImage3D(GL30.GL_TEXTURE_2D_ARRAY,
                0,                      //Mipmap number
                0, 0, zLayerCounter++, //xoffset, yoffset, zoffset
                width, height, 1,          //width, height, depth
                GL11.GL_RGBA,                 //format
                GL11.GL_UNSIGNED_BYTE,       //type
                sprite.getTexture().getTextureData().consumePixmap().getPixels()); //pointer to data

            GL11.glTexParameteri(GL30.GL_TEXTURE_2D_ARRAY, GL11.GL_TEXTURE_WRAP_S, sprite.getTextureWrapS());
            GL11.glTexParameteri(GL30.GL_TEXTURE_2D_ARRAY, GL11.GL_TEXTURE_WRAP_T, sprite.getTextureWrapT());
        });

        GL11.glBindTexture(GL30.GL_TEXTURE_2D_ARRAY, 0);
    } else {
        throw new IllegalArgumentException("Maximum number of textures reached!");
    }
}

```

# Answer
> 1 votes
Looking at http://docs.gl/gl3/glTexImage3D, the 8th parameter (*`format`*) has to be one of `GL_RED, GL_RG, GL_RGB, GL_BGR, GL_RGBA, and GL_BGRA`, you use `GL_RGBA8` which is not allowed. Use `GL_RGBA` instead.

---
Tags: opengl, textures, lwjgl
---


# Question
Title: Get VertexSize of Instance in VertexShader
I'm using Unitys `DrawProceduralIndirect` function to directly render the content of a ComputeShader.

I setup the argumentBuffer for this function as follows:

```
    int[] csArgs = new int[] { ptsOnLine, 2, 0, 0};
    argsBuffer = new ComputeBuffer(4, 4, ComputeBufferType.IndirectArguments);

```

So every instance consists of ptsOnLine (lets say 10) vertices.

My vertexShader then looks like this:

```
fsInput vert(uint id : SV_VertexID, uint instanceId : SV_InstanceId)
{
    fsInput fsIn;
    float3 worldPos = linePoints[id + (instanceId * 10)];
    fsIn.pos = mul(UNITY_MATRIX_VP, float4(worldPos, 1.0f));
    return fsIn;
}

```

The question is simple. My problem is: `(instanceId * 10)`. Is there a built in variable telling me the length of one instance? I couldn't find anything. I mean, its in the argument buffer so it shouldn't be too much of a problem? I could forward this value from the compute buffer but thats ugly. :)

Help is much appreciated!

# Answer
The "built in" variable is contained in the args buffer.

From the unity docs "Buffer with arguments, bufferWithArgs, has to have four integer numbers at given argsOffset offset: **vertex count per instance**, instance count, start vertex location, start instance location."

So make sure you pass that argsBuffer to your shader and then use the first index.
> 1 votes

---
Tags: unity, hlsl, procedural-generation, compute-shader
---


# Question
Title: In Theory, how much gain should I expect from instancing in OpenGL for small scene with large meshs?
I am trying to implement one-pass stereo rendering in OpenGL for a VR application that I am building. I am implementing this through instancing, so I make one render call `glDrawElementsInstanced` with `count=2` and do clipping in the vertex shader but I am not seeing that much gain in performance.

My scene has just 2 massive meshes (rendered two times (2 instances), one for each eye totaling around 3.5m triangles for each eye or ~7m per frame). Obviously I can reduce the triangle count by doing some decimation but my question here is,

In theory, should I expect a significant gain in performance by using instancing in this scenario even though the number of draw calls and state changes in the entirety of my application is around 15 per frame For each pass and 30 per frame?

Or to Rephrase the question, Does OpenGL instancing improve performance mainly by reducing state changes or by making less calls to glDraw\*?

# Answer
Instanced rendering is mainly there to reduce the overhead inherent in draw calls for a large number of low polygon models, and so would not really benefit you as much as other optimisations.

One possible optimisation is to break up your massive model into many smaller models, then perform frustum culling (if appropriate), only drawing the parts which will be visible.
> 1 votes

# Answer
Instancing helps by reducing the API calls.

Almost every API call has to go from the CPU to the GPU (which is very slow). In your case due to the low amount of API calls, instancing won't help much.

However, you could make it better by cutting those two meshes into smaller ones you could instance (e.g. if the mesh has a lot of cubes baked into it, then cut those out and draw them separately Then you can use instancing).
> 0 votes

---
Tags: opengl, virtual-reality, instancing
---


# Question
Title: C/C++ Flexible yet fast way of linking UI elements to functions
I am currently working on the UI functionality of my game, which will have very minimal GUI design, yet it needs to be functional and flexible e.g. easy to redesign.

I am planning to construct all my GUI elements (buttons, sliders, knobs, checkboxes) from Quads with an optional texture and a color. These quads will also serve as boundaries for text and mouse-click detection.

But I am having trouble to figure out an efficient way of linking actual functionality to triggers like buttons. I have thought of defining a Button like this:

```
struct Button{
    unsigned int quadIndex; //an index into the array of quads, which themselves store indices into arrays of positions and sizes
    void (*func)(int); //a pointer to the function to be called when this button is being interacted with. the parameter of the function will be the state of the relevant mouse button
}

```

But this way I could only make a button call a function `void func(int)`, which will often force me to write a wrapper function for every individual button functionality. Is this the way everybody does it or is there a better, more flexible way?

Edit: Since performance/high responsiveness is very important to me, i would like to avoid pointers, virtual functions and derived classes. I am looking for a transparent, concrete solution which focusses on the minimal data which has to come in play for a functional and flexible solution

# Answer
> 3 votes
First off, your part about avoiding pointers and virtual functions due to responsiveness of button clicks is terribly misguided - you listened to someone you should not have listened to. If we're discussing pointers for performance, we're talking nanoseconds (worst case of 65 ns, according to one source), and if you want to react fast enough to a button click to be seen as responsive, you have 100'000'000 of these nanoseconds to spend as you please.

That said, you're either looking at virtual functions (likely in combination with `std::unique_ptr`), at `std::function`, or if you're on an old C++ version at `boost::function`. All of these allow you to store any number of additional arguments, and also *allow* correct lifetime management of resources by their destructors. Done properly, `std::function` with lambdas should be the cleanest code to read, but an implementation with virtual functions will be easier to debug.

# Answer
> 2 votes
What C++ standard are you writing against? C++ 11 Introduced support for Lambdas, which are basically unnamed functions that can "capture" variables.

So you could just define a Lambda instead of your function and then write whatever function you actually want to call in there. You're still creating the function adapters, but since you can write them in-line it's much more compact:

```
myButton.func = [someExternalVariable](int idx){ doMagic( buttons[idx], someExternalVariable, 42 ); };

```

# Answer
> 1 votes
Create a `ButtonBehaviour` abstract class with a virtual `execute(Button& b)`

Then your button can have several behaviours:

```
class Button
{
public:
    void parseMouse(Mouse& m){
        if(isInside(m.pos)) {
            if(m.clicked) {
              m_on_click->execute(*this);
            }
            else {
                if (!m_mouse_inside) {
                    m_mouse_inside = true;
                    m_mouse_enter->execute(*this);
                }
            }
            else {
                if (m_mouse_inside) {
                   m_mouse_inside = false;
                   m_mouse_leave->execute(*this);
                }
            }
        }

    }
private:
    ButtonBehaviour* m_on_mouse_enter;
    ButtonBehaviour* m_on_mouse_leave;
    ButtonBehaviour* m_on_click;
    bool m_mouseinside;
};

```

The mouse then calls the appropriate one depending on the mouse state.

In such a way the `ButtonBehaviour` concrete classes can do whatever you want: call other, wrapped up functions, or interact with other modules in your code directly.

# Answer
> 1 votes
You could use templates and hide the function type under an interface:

```
class ICallback
{
public:
    virtual void Execute() = 0;
protected:
private:
}

template <typename T> ButtonCallback : public ICallback
{
public:
    ButtonCallback(T c_) : c(c_) {}

    void Execute() override
    {
        c();
    }
protected:
private:
    const T c;
}

class Button
{
public:
    Button()
    {
        clickCallback = new ButtonCallback(/* any function pointer/std::function here. */);
    }
private:
    ICallback* clickCallback;
}

```

All variables to callbacks need to be of the type `ICallback`, which means that you need to "double" any interface you want with the callbacks there.

# Answer
> 0 votes
Make `Button` an `abstract class` with a `virtual` function `click`.

Then create a derived class for each button which implements `click` by doing what the button is supposed to do on a click-event.

# Answer
> 0 votes
You can turn things around by looping over your gui every frame and doing

```
if(button(quadIndex)){
    // handle click
}

```

where `button(int)` will look up the quad and see if the player clicked in that area. At the same time it will also schedule it to be drawn.

For checkboxes you pass a pointer to a bool that represents the state

```
if(checkBox(quadIndex, &selected)){
    // handle that selected changed
}

if(selected){
    //...
}

```

This pattern is sometimes called an immediate mode GUI.

---
Tags: c++, gui, c, user-experience
---