title: Why is text resolution so bad in VR?

text:
# Question
Title: Why is text resolution so bad in VR?
VR is already at a point where it can render some impressive 3D landscapes. But it is awful at rendering text. This renders things like VR Desktop as basically unusable.

**Question:** Why is text resolution so bad in VR? I'm talking about from a technical standpoint?

EDIT: Here is a quote from an article about text resolution in VR:

> “Text is tough in VR. It’s hard to read, given the resolution of today’s HMDs and it’s hard to write, since you’re typically blind in a headset and it’s annoying to be tied to a keyboard at a desk when you’d rather walk and move around in VR. I tolerate these problems with RiftSketch by making the text in the editor extremely large. I can only see 20 lines of code at a time in VR whereas my physical desktop has a 4K monitor where I’m usually looking at 140 lines of code per file with several files open side-by-side.”

My question is why, from a technical perspective, is this the case? If we can render i.e. Shrek in VR, why can't we render clear text?

# Answer
> 4 votes
Because the resolution is "bad".

I'm taking the Vive numbers and some numbers that are very rough estimates, they're pretty much identical to the Oculus Rift.

Each eye has a screen with a resolution of 1080x1200 and takes up more than a you can see without moving your eye. Your regular run of the mill monitor is 1920x1080 and takes up... let's say 2 thirds of your vision.

This leaves it with an effective resolution of 2880x1620, which is already quite a bit better.

Besides that, text rendering on a VR headset is typically done by rendering the text to a picture and then projecting that picture in 3D. This negates some of the advantages regular text has, namely the possibility to do anti aliasing on a known background and subpixel rendering.

It also *adds* the downside that you have to go through sampling again, which can introduce additional error.

Contrast this to rendering a model or a terrain. They have very little relevant detail. Just count all the little lines and curves in this text! Way less than a regular model and they are actually all *important* while a model just has to look close enough.

---
Tags: virtual-reality
---


title: Network protocol for chat -- UDP or TCP

text:
# Question
Title: Network protocol for chat -- UDP or TCP
I'm trying to develop a fast-paced multiplayer game.

Now I'm using UDP as a transport-layer protocol to communicate between clients and server. But what if I want to implement a chat? Should I send chat messages via UDP as well (with re-sending and other TCP-like stuff) or should I use another TCP socket for such purposes?

Which one is the best practice?

# Answer
> 6 votes
When it comes to chat systems, reliability is far more important than latency and bandwidth. That would usually make it a typical TCP/IP use-case. However, using both TCP and UDP in parallel through the same network can cause more UDP packet loss and adds additional complexity to your application. So it might be smarter to add some optional reliability features to your UDP protocol which mimic certain reliability features of TCP:

1. Every chat message gets a sequence number. When messages arrive out of order, the chat UI automatically reorders them.
2. The receiver must send a confirmation for every text message it receives. When the confirmation doesn't arrive within `n` ms, the message is resent (with the same sequence number) up to `m` times.

There might also be other features of your netcode where these reliability features might be handy, but others where you shouldn't bother with either. So decide on a case-by-case basis which message types need sequence numbers and which also need confirmations.

# Answer
> -2 votes
Your question sounds as if you are a beginner, as me, so my first advice is to use SFML as I did (I used the TCP option it provides). You will see that even if your problem of having to decide between TCP vs UDP is solved, the problem of managing your network will still be considerable, so just take a library which works, no matter if UDP or TCP, because as you gain experience, you will have to change all your code anyway.

Try using Enet if you insist with mixing UDP and TCP. Its actually UDP based, but with one button you can turn reliability on and off as if you were using TCP.

Ps: TCP will guarantee that your chat mesages arrive. UDP doesnt give you this guarantee by default, unless you tweak it to do so. Instead of tweaking it, you can ask Enet to do it automatically for you.

---
Tags: networking, multiplayer, udp
---


# Question
Title: Deserializing component array using JSON
I have a collection of serialized components in JSON format:

```
{
    "components": [{
        "class": "com.package.component.PositionComponent",
        "x": 100,
        "y": 100
    }, {
        "class": "com.package.component.VelocityComponent",
        "x": 4,
        "y": 2
    }]
}

```

I want to load this into a collection of base Components in Java, specifically into an Entity. I am currently using YAML (parsed using SnakeYAML) to achieve this. The following file (which is virtually identical to the JSON one) is parsed and the components are stored in an ArrayList:

```
components:
- ==: com.package.component.PositionComponent
  x: 100
  y: 100
- ==: com.package.component.VelocityComponent
  x: 4
  y: 2

```

Is there any way I can achieve this using the JSON parsing facilities provided by LibGDX? I am currently using the following code to parse the components, but I have no idea how to get it to construct the correct appropriate object for each component:

```
JsonReader reader = new JsonReader();
JsonValue base = reader.parse("components.json");

for (JsonValue component : base.get("components")) {
    System.out.println(component.getString("class"));
}

```

# Answer
So are you asking how to create a class given a class type as a string?

```
JsonReader reader = new JsonReader();
JsonValue base = reader.parse("components.json");

for (JsonValue component : base.get("components")) {
    Class<?> clazz = Class.forName(component.getString("class"));
    Constructor<?> ctor = clazz.getConstructor();
    Object object = ctor.newInstance();
}

```

Though I assume you probably have no arg consructors, if you need to pass arguments to a constructor, it is done like this (if the argument was a String):

```
Class<?> clazz = Class.forName(className);
Constructor<?> ctor = clazz.getConstructor(String.class);
Object object = ctor.newInstance(new Object[] { ctorArgument });

```
> 1 votes

---
Tags: java, libgdx, component-based, serialization, json
---


title: Libgdx, actor touchlistener not working

text:
# Question
Title: Libgdx, actor touchlistener not working
```
public class Main extends ApplicationAdapter {

SpriteBatch batch;

OrthographicCamera camera;

Stage stage;

Image greyback;
Image circle;

private float width;
private float height;

@Override
public void create () {

    batch = new SpriteBatch();

    camera = new OrthographicCamera();

    stage = new Stage();
    Gdx.input.setInputProcessor(stage);

    greyback = new Image(new Texture("greyback.png"));
    circle = new Image(new Texture("circle.png"));

    width = Gdx.graphics.getWidth();
    height = Gdx.graphics.getHeight();

    greyback.setWidth(width);
    greyback.setHeight(height);

    circle.setPosition(200,200);

    circle.setBounds(200, 200, circle.getWidth(), circle.getHeight());
    circle.setTouchable(Touchable.enabled);
    circle.addListener(new InputListener() {

        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {

            System.out.println("CLICKED");

            return true;

        }

        public void touchUp(InputEvent event, float x, float y, int pointer, int button) {

            System.out.println("REMOVED");

        }

    });

    stage.addActor(greyback);
    stage.addActor(circle);

}

@Override
public void render () {

    stage.draw();

}

```

} But, when I click on the circle the touchlistener doesnt fire, why?

# Answer
> 1 votes
In your call

```
circle.setBounds(200, 200, circle.getWidth(), circle.getHeight());

```

The `getWidth()` and `getHeight()` calls are methods on Actor, not Image. You have not set the Actor's width and height, so you are setting its bounds to a rectangle with a height and width of 0... no clickable area.

Change the call to

```
circle.setBounds(200, 200, circle.getImageWidth(), circle.getImageHeight());

```

# Answer
> -1 votes
You need to do this :

```
stage.act();

```

This will make your Stage acting, so your Button Listener will work :)

---
Tags: libgdx, game-design, touch
---


# Question
Title: LibGDX - How do you load huge spritesheets?
As we know, there is a `GL_MAX_TEXTURE_SIZE` on each mobile phone which makes things really hard. I write an app for all mobile devices and I need to load some huge spritesheets combined with 64 frames when each of them has 512x1024 dimensions.

As I tested and read, I should load spritesheets \<= 1024 so it will work on all mobile devices including IPhone3 and some old Androids.

If I have a spritesheet 512x1024 with 64 frames, it's dimensions are really, really large - for ex. if the spritesheet has 64 columns, it's with is ~61000 px.

Of course, I can cut it, but it gives me 64 images and I have no idea if this if efiicient of not.

How do you handle things like this? Scaling the graphics down is not an option - it lowers the quality and my game IS QUALITY.

If someone has any experience I would be grateful!

# Answer
> 1 votes
I never tested it before on Android ... But on Desktop im doing it like following :

First I create a big spritesheet using a TexturePacker . I put those files into the project Folder .

Then I use the libgdx AssetManager to load those SpriteSheet ( TextureAtlas ) dynamicly.

I haven't tested it yet but I think it should also work on Android if you Pack your spritesheet into a textureAtlas and load it via AssetManager into your game :)

Going to test that tommorow, hope I helped ya a little bit =)

---
Tags: libgdx, performance, spritesheet
---


title: libgdx actors and instant actions

text:
# Question
Title: libgdx actors and instant actions
I'm having trouble with actors and actions. I have a list of actors, they all have either no action, or 1 sequence action

This sequence action has either :

* a couple of actions (some are instant, some have duration \> 0)
* a couple of actions followed by a parallel action.

My problem is the following:

some of the instant actions are used to set the position and the alpha of the actor. So when one of the action is "move to x,y and set alpha to 0" the actor is visible for one frame at position 0,0 , move instantly to x,y for the next frame, and then disappears.

Though this behaviours is to be expected, I want to avoid it. How can I achieve that?

I tried to intercept the actions before I put actors in the stage but I need the stage width/height for some actions. So something like :

```
Action actionSequence = actor.getActions().get(0);
Array<Action> actions = ((SequenceAction) actionSequence).getActions();
for(Action act : actions){
    if(act.act(0))
        System.out.println("action " + act.toString() + " successfully run");
    else
        System.out.println("action " + act.toString() + " wasn't instant");
}

```

won't work.

It gets even more complicated when an actor can also have a repeat action in stead of the sequence action (because you have to only run the actions that have duration 0 once without repeat, and then start the repeat).

Any help is appreciated.

# Answer
Okay I found a way around.

I built a custom actor class that extends Image and overwrote CustomActor's `draw()` method like that

```
@Override
public void draw(SpriteBatch batch, float parentAlpha) {
    if(frameCount < 4){
        frameCount++;
        return;
    }
    super.draw(batch, parentAlpha);
}

```

Basically, the first 3 frames aren't drawn. During those frames the actor is being placed correctly by the first instantaneous actions and doesn't glitch through the screen.

Kinda hackey but that will do it for now.
> 1 votes

# Answer
It looks like you are trying to put these actions in a SequenceAction, put both move and alpha action into a ParallelAction which then put into your sequence.

```
actor.addAction(Actions.sequence(Actions.parallel(moveAction,alphaAction), moreActionsInSequence));

```

Also consider using VisibleAction (Actions.show/hide/visible) instead of alpha 0 for hiding Actors.
> 1 votes

# Answer
I had this Problem a while ago. It's because of your Stage transparancy. Before you init your actions you need to set it to zero . Im currently at my phone so I don't know if that's right :

```
Stage.getRoot().getColor.a = 0;

```
> 1 votes

---
Tags: java, libgdx
---


# Question
Title: Using Quaternions to rotate a player towards a point
I am attempting to solve a problem involving Quaternions and 3D rotation.

I am using a games engine (Torque 3D) for a project that I am developing. I have modified the gravity system so that the player is pulled in three dimensions towards a central point (the center of a spherical world).

I would like the player to also turn so that their feet are facing this central point, regardless of their position or initial orientation. I want the player to be able to stand on the spherical world, and currently, even though they are being pulled to the center of the world correctly, the orientation doesn't change.

The orientation is held in a Quaternion called "mOrient".

I know that the solution will involve rotation matrices, and probably world/local space translations, but I am not sure how to put all this together.

I am currently attempting this, unsuccessfully: Assume (0,0,0) is the center point, getPosition() is the position of the player. mOrient is the players 3D rotation quaternion, this is what I need to change.

```
  Point3F gravityvec = Point3F(0, 0, 0) - getPosition();
  gravityvec.normalize();

  QuatF q = QuatF(gravityvec);

  mOrient = q;

```

Does anyone have a solution for this?

I'm programming in C++ inside a games engine, but Pseudocode would be fine, I just need some assistance with the mathematical side.

# Answer
Build a LookAt rotation matrix and then you can converter it to a quaternion.

Most engines already have that function built-in but here's the pseudo-code:

```
mat3 LookAt(vec3 up, vec3 front)
{
  vec3 right;
  mat3 m;

  right = CrossProduct(Normalize(up), Normalize(front)); // figure out the right vector

  front = CrossProduct(right, up); // make sure front is properly oriented

  m[0] = right;
  m[1] = up;
  m[2] = front;

  return m;
}

```

`up` is the vector from the center of the world to the player (the negative of your gravity vector)

`front` is where the player is facing (assuming your 3D model faces in the Z direction.)
> 1 votes

---
Tags: rotation, quaternion
---


# Question
Title: load scene - some time (2 seconds) after object is destroyed in Unity
How do I check if an object has been destroyed. And do something like change scenes 2 seconds later.

this is what I tried:

```
float delay = 2

void OnDestroy(){

 delay-= Time.deltaTime;
 if(delay<=0){
   Application.LoadLevel("scene2");
  }
}

```

# Answer
> 0 votes
you can use another script(for example GameManager) because when gameObject Destroyed haven't script component for checking if Delay \<= 0

```
using UnityEngine;
using System.Collections;

public class MyObject: MonoBehaviour {

void Start(){
    Destroy (gameObject);

}

void OnDestroy(){
    GameManager.Instance.StartCoroutine ("Delay");

    }
 }

```

---

```
using UnityEngine;
using System.Collections;

public class GameManager : MonoBehaviour {
    public static GameManager Instance;

    void Awake () {
        Instance = this;
    }

    IEnumerator Delay(){
        yield return new WaitForSeconds (2);
        print ("that works");
        Application.LoadLevel ("scene2");
    }
}

```

or you can use Invoke for delay

```
using UnityEngine;
using System.Collections;

public class MyObject : MonoBehaviour {

    void Start(){
        Destroy (gameObject);
    }

    void OnDestroy(){
        GameManager.Instance.Invoke ("Delay", 2);

    }
}

```

---

```
using UnityEngine;
using System.Collections;

public class GameManager : MonoBehaviour {
    public static GameManager Instance;

    void Awake () {
        Instance = this;
    }

    void Delay(){
        print ("that works");
        Application.LoadLevel ("scene2");
    }
}

```

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


# Question
Title: How do I detect UI button presses on Android
I have a game that has many UI buttons. How do I detect which UI button is pressed? I am using Unity5 so there are no GUI elements. I am not able to use the onClick standard functions because all of my game objects are spawned.
My player has to shoot, jump and reload their weapons. I am able to move the spawned player with a joystick. But for the shoot and reload I get a null reference if I use the onClick functions (but they work fine with get axis implementation for shoot).

```
using UnityEngine;
using System.Collections;
using UnityStandardAssets;
using UnityEngine.UI;
using UnityStandardAssets.CrossPlatformInput;
public class wepScript : MonoBehaviour {

public Camera fpsCam;
public GameObject hitPar;
public int damage = 30;
public int maxDamage = 60;
public int range = 10000;
public int ammo = 10;
public int clipSize = 10;
public int clipCount = 5;
public float recoilPower = 30;
public Animation am;
public AnimationClip shoot;
public AnimationClip reloadA;

public Texture hitMarker;
public int hitCD = 0;

public AudioClip shootSound;
public AudioClip reloadSound;

public animManager amM;

public string  weaponName = "";
public bool done = false;
public GameObject[] objectsToDisable;
public bool canAim = false;
public float aimFOV = 20;
public float regFOV = 60;
public float regOffset = 0;
public float aimOffset = -75;
public PhotonView pv;

public Texture scope;
public bool isAimed = false;

void Awake(){

}

void Update(){

    //Vector3 targetVelocity = new Vector3(CrossPlatformInputManager.GetAxis("Horizontal2"), 0, CrossPlatformInputManager.GetAxis("Vertical"));
    //Debug.Log (targetVelocity.x);
    //if (targetVelocity.x > 0 ) {
    //  fireShot ();
    //
//  }
    if () //
    {
        fireShot();//UI BUTTON PRESS
    }

    if (Input.GetMouseButtonDown (1)) {
        aim (true);
    }

    if (Input.GetMouseButtonUp (1)) {
        aim (false);
    }
    targetVelocity = new Vector3(CrossPlatformInputManager.GetAxis("Horizontal3"), CrossPlatformInputManager.GetAxis("Vertical3"));
    if (targetVelocity.x > 0) {
        reload();
    }

    hitCD += -1;
}

public void fireShot(){
    if (!am.IsPlaying (reloadA.name) && ammo >= 1) {
        if(!am.IsPlaying (shoot.name)){
            am.CrossFade (shoot.name);

            ammo = ammo - 1;

            pv.transform.GetComponent<RigidbodyFPSWalker>().getClip(shootSound);
            Debug.Log ("playing Sound!");
            pv.RPC ("playSound", PhotonTargets.AllBuffered, null);

            fpsCam.transform.Rotate (Vector3.right, -recoilPower * Time.deltaTime);

            RaycastHit hit;
            Ray ray = fpsCam.ScreenPointToRay (new Vector3 (Screen.width / 2, Screen.height / 2 + regOffset, 0));

            if (Physics.Raycast (ray, out hit, range)) {
                if (hit.transform.tag == "Player") {
                    hit.transform.GetComponent<PhotonView> ().RPC ("applyDamage", PhotonTargets.AllBuffered, Random.Range (damage, maxDamage), PhotonNetwork.playerName, weaponName);
                    PhotonNetwork.player.AddScore(1);
                    Debug.Log (PhotonNetwork.player.GetScore());
                    hitCD = 20;
                }

                if (hit.transform.tag == "Ai") {
                    hit.transform.GetComponent<PhotonView> ().RPC ("AiDamage", PhotonTargets.AllBuffered, Random.Range (damage, maxDamage), PhotonNetwork.playerName, weaponName);
                    PhotonNetwork.player.AddScore(1);
                    Debug.Log (PhotonNetwork.player.GetScore());
                    hitCD = 20;
                }

                GameObject particleClone;
                particleClone = PhotonNetwork.Instantiate (hitPar.name, hit.point, Quaternion.LookRotation (hit.normal), 0) as GameObject;
                Destroy (particleClone, 2);
                Debug.Log (hit.transform.name);

            }
        }

    }
}

public void reload(){
    if (clipCount >= 1) {
        am.CrossFade (reloadA.name);
        GetComponent<AudioSource>().PlayOneShot(reloadSound);
        ammo = clipSize;
        clipCount = clipCount - 1;
        //amM.reload ();
    }

}

public void aim(bool isIn){
    if (canAim) {
        if (isIn) {
            fpsCam.fieldOfView = aimFOV;
            disable ();
            regOffset = aimOffset;
            isAimed = true;
        } else {
            fpsCam.fieldOfView = regFOV;
            enable ();
            regOffset = 0;
            isAimed = false;
        }
    }
}

public void disable(){
    foreach (GameObject part in objectsToDisable) {
        part.SetActive (false);
    }
}
public void enable(){
    foreach (GameObject part in objectsToDisable) {
        part.SetActive (true);
    }
}

void OnGUI(){
    GUI.Box (new Rect(110,10,150,30), "Ammo: " + ammo + "/" + clipSize + "/" + clipCount);
    GUI.Box (new Rect (10, 45, 100, 30), "Score: " + PhotonNetwork.player.GetScore());

    if (hitCD >= 0) {
        GUI.DrawTexture (new Rect(Screen.width/2 - 25, Screen.height / 2 -25, 50,50), hitMarker, ScaleMode.StretchToFill);
    }

    if (isAimed) {
        GUI.DrawTexture (new Rect(0,0,Screen.width, Screen.height), scope,      ScaleMode.StretchToFill);
    }
}
}

```

Thanks

# Answer
> 1 votes
Besides the fact, that this screams for another way of separating your UI and logic code (the fact that your game objects are spawned at runtime does not mean, that you cannot have your UI listener functions in a script on a invisible dummy game object that always exists, right? Or are you spawning your buttons at runtime? Then see the last section of this answer), you can do the following:

You can add button listeners programmatically with `Button.onClick.AddListener()` where `AddListener` takes an `Action` (parameterless void function).

An example given a transform that has your button as a component using Linq would be:

```
transform.GetComponent<Button>().onClick.AddListener(() =>
{
    // put your action code here
});

```

I haven't tried that, but you should also be able to assign any void function without parameters as `delegate` to be listener.

If I got you wrong and you are spawning your UI buttons at runtime and these should have different but repetitive behavior, then just create a bunch of prefabs with listeners defined beforehand.

Hope that helps.

# Answer
> 0 votes
Make a static GameManager class and attach it to the camera or an empty GameObject. Give it a variable

```
public GameObject player;

```

On the Player object, have a script saying:

```
void Start()
{
    GameManager.player = gameObject;
}

```

Then on your buttons, you can use a function:

```
void Click()
{
    if(GameManagaer.player != null)
    {
        // Do the thing
    }
}

```

And use that as the OnClick.

If you don't want to use a static GameManager class (though I recommend it, because they're awesome), you can do a *find*, so your click function would be:

```
void Click()
{
    GameObject player = GameObject.Find("Player");

    if(player != null)
    {
        // Do the thing
    }
}

```

Either way you're performing a null check so that a null reference doesn't break everything. With the two methods I've given, what will happen from a gameplay perspective is that nothing will happen if you click the button before the player has spawned. After the player has spawned, clicking the button will run the code.

---
Tags: unity, c#, software-engineering, input
---


title: Workflow for non human ragdolls

text:
# Question
Title: Workflow for non human ragdolls
So I want to make automatic ragdoll generation system for all my enemies in my game, the assets are already made and have been paid for a while ago so I can't really ask the artist to change anything or generate some extra info, they are a variety of models (humans, robots, beasts) with a hard limit of 32 bones. Each bone is labelled and there is only a single mesh provided, which is skinned and ready to go.

I am trying to understand how an automated system can generate ragdolls from this. So far my idea involves convex decomposition (v-hacd?) to split up the mesh into small convex hulls and attach them using hinge and cone twist constrains (in bullet physics).

The idea sounds simple in my head but actually there are so many questions such as, how to do it automatically? how to make each convex hull be attached to a bone correctly? how to join the convex hulls with constraints in the correct place? the ragdoll would be generated from the bind pose, but how to transform the ragdoll so that it is perfectly aligned with the skeleton after its death animation?

I would very much appreciate some guidance on this, thanks.

# Answer
If you make a convex hull that just means you are splitting up your existing geometry. So the binding to the bones should stay exactly the same. If you do add in some verts to plug holes, you can just average it to neighbors or bind it directly to the nearest bone. I makes no sense to make a split near a joint so it shouldn't be an issue. If you DO split near a joint then you will have to make all the geometry of any new verts AND surrounding verts skinned only to the bone that you keep. Otherwise you will have the detached bones influencing motion.

Now as far as why you need this...I am a little unclear. You shouldn't need to split the mesh up just to make ragdolls, you only need that for things like making an object explode into pieces. So I am guessing that you also want some ability like that as well. If you are going to have things like limbs blown off then I suggest to just have this done in the middle of a large bone and then split off the skeleton in code.

That should be theoretically easy, just take a particular node for the split and make everything that's a child of it part of the new skeleton. You should be able to run all the same animations if you want.

As for keeping the ragdoll from being too loose, just place some constraints on the motion. I would just do it manually for each joint because some joints can move a lot in some directions but very little in others or else it will look awful. You really only need some subtle motion for the most part, just enough to give the illusion of reactivity if you slam a dying enemy into the wall or throw him off of a cliff.

Going into the physics itself is probably too much for a post like this and I am not a big expert anyway but that should be sort of automatic once the physics engine gets your data. Hopefully this is enough to at least get you started, sometimes brainstorming is the hardest part!
> 1 votes

---
Tags: animation, bullet-physics, skeletal-animation, bones
---


# Question
Title: How to select coordinate position within uv texture in a shader - Unity
first of all I'm sorry for asking noob-ish question. This is my fifth day trying to make a shader in Unity.

I'm trying to select an area within my UV image as shown below

and here's how it looks like on the mesh

Basically I'm only selecting the red from the UV and apply it to the mesh. I encountered no problem when trying to select from the RGB, but when i try to use the XYZ for the coordinate position, it turns out that the value of x and r is the same, so is y and g, and z and b.

My question is, how to select by the coordinate position in the UV texture?

Thanks.

here's my code :

```
    Shader "Custom/ASK RGB" {
    Properties {
        _tex ("Tex", 2D) = "white" {}
    }
    SubShader {
        Tags { "RenderType"="Opaque" }
        LOD 200

        CGPROGRAM
        #pragma surface surf Lambert

        sampler2D _tex;

        struct Input {
            float2 uv2_tex : TEXCOORD1;
            float4 pos : TEXCOORD1;
        };

        void surf (Input IN, inout SurfaceOutput o) {
            // my variable used to store the UV texture mentioned
            half4 tex = tex2D (_tex, IN.uv2_tex.xy);

            // my attempt to use position which doesn't work
            half4 texPos = half4(IN.pos);

            half4 tryUV = tex2D(_tex, IN.uv2_tex.xy);

            tex.a = 1 - tex.b - tex.r - tex.g;

            tryUV.a = tex.r;

            o.Albedo = tryUV.rgb * tryUV.a;
        }
        ENDCG
    }
    FallBack "Diffuse"
}

```

# Answer
.xyz is just the same as .rgb, the idea is that you use whichever makes the most sense in the context you are using it.

I think the values you want are in IN.uv\_tex.x and IN.uv\_tex.y
> 0 votes

---
Tags: unity, opengl, shaders
---


# Question
Title: How to draw the imagebutton and place it in the lower left corner
I have the button:

```
soundBtnStyle = new ImageButton.ImageButtonStyle();
    soundBtnStyle.up = skinBac.getDrawable("on");//
    soundBtnStyle.down = skinBac.getDrawable("off"); //

    soundsButton = new ImageButton(soundBtnStyle);
    soundsButton.setSize(120, 120);

    soundsButton.addListener(new ClickListener() {
        @Override
        public void clicked(InputEvent event, float x, float y) {
            game.rainMusic.setVolume(0.0f);
        }
    });

```

call the button in the constructor,I can not figure out how to add a button to the stage.

```
game.batch.begin();
    game.batch.draw(soundsButton, 0, 0,120, 120);
game.batch.end();
enter code here

```

It does not work, an error

# Answer
If only there was a magical place where you could look up things like this.

https://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/scenes/scene2d/ui/ImageButton.html#draw-com.badlogic.gdx.graphics.g2d.Batch-float-

I wonder if that button classes draw routine could help. Hmmmmmm.
> 1 votes

# Answer
Right after you create a new ImageButton you can add it like:

`soundsButton = new ImageButton(soundBtnStyle);
 soundsButton.setSize(120, 120);
//add button here
stage.addActor(soundsButton);
//set position at x=0 & y=0 as
soundButton.setPosition(0,0);`
> 0 votes

# Answer
The `draw()` method only accepts `Texture` and `TextureRegion`. You're passing an `ImageButton`. `ImageButton` is an `Actor` and is part of Scene2d and they are usually used along with `Screen`, `Game` and `Stage`. You should check this tutorial to know more about Scene2D.
> 0 votes

---
Tags: java, libgdx
---


title: Implementing Story and Quests in RPG

text:
# Question
Title: Implementing Story and Quests in RPG
This question in very similar to this question, however I am still confused about how one would implement a story and quests in a finite state automaton RPG.

This is my first game that I am making (my background is in computational science not games) and it is similar to this game. At every frame in my game you are in a state. Examples of states might be `Shops`, `Worlds`, `Battle` state, `Inns`, `Player Stats` screen, etc. Each state has a `next` and `previous` state that allows one to progress (or back out) to one state after the other. For example if you are currently in the `World` state, upon moving to the door of an inn the state changes from `World` to `Inn`. After clicking to leave the inn the state then reverts back to the `World` state. All of this appears to be what is described in the this question.

However, quests and story don't seem to fit all that well here and I am confused about what data structures to use for quests and how they should be implemented in the game. One problem with quests is that they cross states and time. For example, you might get a quest from the inn keeper (in state `Inn`) and then have to go back into the world and perform some action to complete the quest (`World` state). Maybe you then have to turn in the quest to the potion shop keeper (`Potion Shop` state). All of this crosses multiple states and knowing when to post dialogue to the screen is time and state dependent.

The easiest solution seems to just create a quest dictionary and make it global. This way all states can see all the quests and data in the quest dictionary (e.g. different flags etc) can be modified at will. The downside here is that a) we are using globals, a generally frowned upon idea by most programmers, b) this quest dictionary could easily become quite large and cumbersome, and c) this idea is hardly OOP. Another idea I had was to create a class called `Quest` and each quest would just be an instance of a this class. I would then pass these instances to whatever states need them. This is also pretty cumbersome though. Having to pass quests around to different states (and basically hard coding different quests to all the states that need access to them) seems like a bad idea. I could also implement the quests directly into the states. For example the `Inn` state has methods and flags to deal with quest 1, quest 2, ... etc. This isnt very OOP though because what if I want more then one inn? The quests associated with my first inn would be different from those associated with my second inn (different inn keepers after all!!). I would have to write two different versions of my `Inn` state class.

I suspect I am missing something obvious here given that my background is not in game design. I understand the finite state automaton at least in terms of moving from location to location within my game, but I am failing to grasp how to do something similar for quests and story. Should I have a global quest data structure? Hopefully this isn't marked as duplicate. Thanks for any help you can give in clarifying this for me.

# Answer
As far as I see it the `Shop` class (for example) needs dependencies on at least two classes:

* The current status of the player-character (things like available money, inventory and what quests they are currently on)
* The current status of the shop the player is visiting (things like shop inventory, prices and available quests)

These dependencies must be injected when transitioning to the `Shop` state.

But where do these statuses come from?

Pretty much every state will need the player-status in one way or another, so it should simply be mandatory to pass it on with every state transition.

The status of individual shops is a bit more tricky. But when the player is on a World, then that World should know the status of each facility in it, so state-changes from facility to facility should be managed by the World-class.

When you have the status of the player and the status of the World(s), you have the whole progress of the game. That's what you need to save in a savegame, by the way.

How to do quests depends on what you actually mean by "quest". When you want a sandbox-style game with mostly procedurally generated cookie-cutter quests like "Kill monster X", "Speak to X", "Bring X items to person Y", then it seems like a good idea to implement each quest-type as a separate class inheriting from an abstract base-class `Quest` and then add a list of `Quest`s to the player-character representing the currently active quests. But when you want a more narrative style with a pre-written storyline, then a dictionary of quest-flags would be more appropriate.
> 3 votes

# Answer
## Model the flow of data

Working with desktop computer apps and web for a while, I learned to love the notion of unidirectional data flow. (1df)

Without 1DF, the quests state lies somewhere, can be mutated by any objects that have access to it (if it's a global variable, this means *every object*), and reasoning about where and how to change them becomes quite hard.

1DF proposes a different approach. There's a state dispatcher which notifies subscribers about state changes. The state objects adhere to value type semantics, i.e. even if you changed the state in the "shop" screen, the "menu" screen's data would not be affected. Everyone gets a copy, essentially.

Now changes are performed through events which a state store processes. The store uses reducers (in reactive/Flux lingo) to apply the event to the current state and reports back a modified version. This new version of the state will replace the old in the store. The store will then make the dispatcher do its job and tell all subscribers. And there you go.

The flow is *unidirectional* because state changes are only performed by reducers, commanded by the store, and updates are pushed from a central place to subscribers.

This is a model of information flow or *process.* Your state machine musings relate to the *structure* of the app into modules which can issue transitions about which one is active.

## Handling quests state

Now if your quests are in a state object, a collection of active `Quest` objects say, each with a unique ID the game can understand, then you can have a quest log menu screen obtain the new state upon being displayed. If the quests change in a background thread, the quest log will receive updates and can re-display itself.

Quests affect dialogue. So you have to model NPC interactions to take this into account. Showing text on screen is easy. But the game has to have conditions that display some text if a quest is completed and another while it isn't. To write dialogue scripts it pays off to use some sort of scripting language. (Can be LUA, can be home-cooked.)

* I found a sketch of quest reprentation as JSON with C# interface code. Good to represent quests data.
* I myself used a simple GOTO-heavy scripting language for which I wrote my own parser. (Sample script.) There I set and checked "flags" for their value.

So now you have quests, dialogue branches depending on quest conditions that are best expressed through scripts, and the framework to push state changes to active objects in your app.
> 1 votes

---
Tags: architecture, rpg, pygame, quests
---


# Question
Title: How can I get separate caches for different coroutines? (Unity)
I want to fade out an image, so I have a coroutine `FadeOut()`. However, I want to have a separate image each time I call FadeOut.

If I try to do something like this:

```
IEnumerator FadeOut(GameObject image) {
    SpriteRenderer render = image.GetComponent<SpriteRenderer>();
    yield return null;
}

```

Ignoring all the color changing code which I took out, how do I make it so that I can save a separate cache for each image I add? I don't want to run `GetComponent()` each frame, because I'm running on mobile and because I want to think of a clever way to stash the renderer.

For example, if I declare the renderer at the top like this:

```
private SpriteRenderer render;

```

and want to cache it on the first frame of the coroutine, there's the chance that calling `FadeOut()` on another object will change the renderer to a new object and the first `FadeOut()` will cancel.

Can I make the method static? Will that cache a private version of renderer?

# Answer
The code that you provided should already be doing what you are asking. If I call `StartCoroutine(FadeOut(image1));` and `StartCoroutine(FadeOut(image2));`, the two coroutines have their own separate `SpriteRenderer renderer;` local references. Unity does not confuse the two. You can continue to fade out image1 even though image2 also started to fade out. That local `renderer` is the renderer specifically for the image that you started the coroutine with.

So, this kind of a code will work just fine. Inside the while loop, `renderer` is the renderer of the image that you initiated this call to the coroutine. You can have many such calls, for every new call, you have a separate local `renderer` variable. They don't affect each other.

```
IEnumerator FadeOut(GameObject image) {
    SpriteRenderer render = image.GetComponent<SpriteRenderer>();
    while(!renderer.isDone) {
        renderer.FadeOutOneMoreStep();
        yield return null;
    }
}

```
> 0 votes

---
Tags: unity, coroutines
---


# Question
Title: How can I use an object pool for optimization in AndEngine?
I have read up on a tutorial that allows you to reuse sprites that are re-added to the scene such as bullets from a gun or any other objects using an ObjectPool.

In my game i have a variation of sprites about 6 all together with different textures.

This is how the object pool is set up with its own class extending Java's GenericPool class

```
public class BulletPool extends GenericPool<BulletSprite> {
private TextureRegion mTextureRegion;

 public BulletPool(TextureRegion pTextureRegion) {
  if (pTextureRegion == null) {
 // Need to be able to create a Sprite so the Pool needs to have a TextureRegion
 throw new IllegalArgumentException("The texture region must not be NULL");
 }
 mTextureRegion = pTextureRegion;
}

/**
* Called when a Bullet is required but there isn't one in the pool
*/
@Override
protected BulletSprite onAllocatePoolItem() {
return new BulletSprite(mTextureRegion);
 }

/**
 * Called when a Bullet is sent to the pool
*/
@Override
protected void onHandleRecycleItem(final BulletSprite pBullet) {
pBullet.setIgnoreUpdate(true);
pBullet.setVisible(false);
}

  /**
  * Called just before a Bullet is returned to the caller, this is where you write  your initialize code
* i.e. set location, rotation, etc.
 */
   @Override
 protected void onHandleObtainItem(final BulletSprite pBullet) {
  pBullet.reset();
}
}

```

As you see here it takes a TextureRegion parameter. The only problem i am facing with this is that i need to have 6 different sprites recycled and reused in the ObjectPool. This ObjectPool is set up to only use one TextureRegion.

Any idea's or suggestions on how to do this?

# Answer
In AndEngine you need to `textureRegion.clone()` or `textureRegion.deepCopy()` depending on the version of AndEngine that you use.

This will make sure that each sprite uses independent graphics. Symptom if you don't is that all sprites will have same tile index for example or same modifiers applied.
> 2 votes

# Answer
A bit late, but let's see.

I have never used AndEngine, but if you create a texture atlas with all your shot sprites, the single TextureRegion can determine which sprite to use for each.

A sprite atlas is a big texture which contains several inside it, usually tiled in a regular fashion. You can specify which one to paint each time by using different regions of the texture. For some more info, check this Gamasutra article: http://www.gamasutra.com/view/feature/2530/practical\_texture\_atlases.php
> 1 votes

# Answer
Oh I just know what you want. I applied it to my game with the help of one of the stackoverflow answer.

If you are having to use 4 textures. you can iterate with a int variable, and use it like this.

you see onallocatePoolItem

```
@Override
protected Bubble onAllocatePoolItem() {
    switch(textureOrder){
        case 0:
            return new Bubble(0, 0, aITiledTextureRegionA,ResourcesManager.getInstance().vbom);
        case 1:
            return new Bubble(0, 0, aITiledTextureRegionB,ResourcesManager.getInstance().vbom);
        case 2:
            return new Bubble(0, 0, aITiledTextureRegionC,ResourcesManager.getInstance().vbom);
        default:
            //this is in case you specified something unknown, you can log an error or something
            return new Bubble(0, 0, aITiledTextureRegionA,ResourcesManager.getInstance().vbom);
    }
}

```

and when calling it.

```
public Bubble obtainPoolItem(int textureOrder){
this.textureOrder = textureOrder;
return this.obtainPoolItem();
}

```

You can also refer the answer in stack overflow which helped me. Multiple textures in objectpool
> 0 votes

---
Tags: android, java, andengine
---


# Question
Title: C++ OpenGL - 2D Lighting Around Object in a Pitch-Black Environment
I am making a 2D game in C++ with OpenGL where a maze is generated and you have to move the character through the maze and get it to the end. I have achieved all this, but now I want to make it more challenging by having everything pitch-black but a small light around the character. How can I achieve this? I don't want the light to be complicated and I don't want it to only go through the tunnels. I just want a simple light around the character to illuminate that area of the maze.

# Answer
> 0 votes
You can use the stencil buffer:

https://en.m.wikibooks.org/wiki/OpenGL\_Programming/Stencil\_buffer http://learnopengl.com/#!Advanced-OpenGL/Stencil-testing

This is what you are looking for?

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


# Question
Title: Unity2D - How to leave and come back to the same scene properly?
I am new to game development and for exercise I made endless runner where everything is generated randomly from prefabs and both player and obstacles are being destroyed once they are off the screen. There are two scenes - Start and Game. At the Start scene you can click on Play button which will take you to the Game scene and you can mute the sound.

When I start the game and I click on the Play button it loads the Game scene perfectly and game runs and works just fine. When player dies the game over window is shown. From there two options are available - either go to the Start scene or play the game one more time.

If I choose to play one more time everything works perfectly. But if I choose to go to the Start scene and then click on Play button to play the game then once the Game scene is loaded the player and the obstacle game objects are not being generated and floor and background Quads are not being resized properly to fit the screen. And I get the following error -

```
MissingReferenceException: The object of type 'RecycleGameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
ObjectPool.NextObject (Vector3 pos) (at Assets/Scripts/ObjectPool.cs:28)

```

My question is - what can I do so that every time I come back to the scene everything is being loaded just like the first time?

I am currently loading scenes with this code:

```
SceneManager.LoadScene("Start");

```

And this is the ObjectPool class:

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

public class ObjectPool : MonoBehaviour {

    public RecycleGameObject prefab;
    private List<RecycleGameObject> poolInstances = new List<RecycleGameObject>();

    private RecycleGameObject CreateInstance(Vector3 pos)
    {

        var clone = GameObject.Instantiate(prefab);
        clone.transform.position = pos;
        clone.transform.parent = transform;

        poolInstances.Add(clone);

        return clone;
    }

    public RecycleGameObject NextObject(Vector3 pos)
    {
        RecycleGameObject instance = null;

        foreach(var go in poolInstances)
        {
            if(go.gameObject.activeSelf != true)//here I get the error
            {
                instance = go;
                instance.transform.position = pos;
            }
        }

        if(instance == null)
        {
            instance = CreateInstance(pos);
        }

        instance.Restart();

        return instance;
    }

}

```

# Answer
It seems like you are using object pooling. In other words you have a class with a list of object instances.

A scene change usually destroys all objects in it. You somehow managed that your object pool is not destroyed on scene change (There are several ways to do that, but it is not clear from the question which one you used. I would suspect it might have something to do with the way you ensured that it is globally available to all classes which need it). So your object pool retains its list of references to instantiated objects, but the objects themselves get destroyed on the scene change. So after the scene-change the pool is full of references to destroyed objects.

To solve the problem either re-initialize your object pool on scene changes or have it clear itself automatically by checking if a pooled object is `== null` and if it is re-Instantiate it.

Alternatively you can also attach your object pool to an invisible game-object in your scene. That way it gets re-initialized each time the scene is loaded.

**By the way:** Many games do not really need object pooling. When you are not sure you have performance problems which are caused by object destruction and re-instantiation, then it's just premature optimization. That means you spend time on implementing a system which adds more complexity and more potential bugs to your software architecture without giving you any tangible benefit.
> 0 votes

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


# Question
Title: What is the technology behind screen sharing?
Came across an app called `Draw N Guess`(iTunes link) and the app uses screen sharing, i.e what a player draws is visible to others. I'm wondering how they are doing it in real time. I believe it is a cross-platform app. I got curios to know what is the technology behind it! It must be very interesting to learn :)

P.S. If this is not the site to ask plain question (i.e unrelated to programming), can you let me know where I can ask such questions? TIY!

# Answer
> 1 votes
If the image appears all in one go...

1. User A draws it
2. User A presses a button
3. A snapshot is taken of the drawing, into an image
4. The image is sent to user B

If you watch the other user draw it

1. User A makes some kind of input gesture (draw with finger)
2. User A's app converts that to a draw command and executes it locally
3. The command is sent to user B
4. User B's app executes the command

It's not screen sharing. Screen sharing shares an area of the screen regardless of which app is running.

---
Tags: game-design
---


# Question
Title: How can I change the color of an object at runtime?
I wish to have the shader effect as in the game 'The stack' by ketchapp

https://play.google.com/store/apps/details?id=com.ketchapp.stack&hl=en

As you can see, the color of the objects as well as the skybox keep changing.

I'm completely c# noob and trying my best to find shaders to replicate the effect. But I can't find anything.

How can I change the color of an object at runtime?

# Answer
You can change the color of an object with a very simple C# script on the object.

First the quick and dirty solution to make an object red:

```
GetComponent<Renderer>().material.color = Color.red;

```

This changes the first color property of the first material of the object to RGB `#ff0000`. When you would like to set a *specific* color property of a *specific* material, check out `Renderer.materials` and `Material.SetColor`.

Why is this solution dirty? Because what it actually does internally is to create a complete copy of the material, then change the color value on it and then assign the new material to the object. This is not just slow, it also means that the object now has an own material and no longer shares its material with all other objects which use the same material asset.

A far more elegant solution is to use a material property block:

```
 MaterialPropertyBlock props = new MaterialPropertyBlock();
 props.AddColor("_Color", Color.red);
 GetComponent<Renderer>().SetPropertyBlock(props);

```

When you set a property block, the material assigned to the object stays unchanged, but the renderer of this game object overrides its settings with those set on the property block.
> 4 votes

---
Tags: unity, shaders
---


# Question
Title: How to calculate the ideal hit of arrow?
I am trying to make the AI shoot an arrow and always hit the target. Assuming that the target is within his range I am stuck what the correct way is to do this. I search and found some solutions but they do not seem to work 100% perfectly in my code (How can I shoot an arrow if I know the shot power and target?).

My code is (`target` is the prefab I want the AI to hit):

```
arrow.GetComponent<Rigidbody>().AddForce (Aim()*speed, ForceMode.VelocityChange);

private Vector3 Aim()
{
    float xAim = target.transform.position.x - transform.position.x;

    float yAim = Mathf.Rad2Deg * Mathf.Atan((speed*speed + Mathf.Sqrt(speed*speed*speed*speed) - (-Physics.gravity.y) * (-Physics.gravity.y * HorizontalDistance()*HorizontalDistance()) + 2 * VerticalDistance() * speed*speed / -Physics.gravity.y * HorizontalDistance()));
    float zAim = target.transform.position.z - transform.position.z;
    Vector3 aim = new Vector3(xAim, yAim, zAim).normalized;
    return aim;
}
private float HorizontalDistance()
{
    float xDistance = target.transform.position.x - transform.position.x;

   // float zDistance = target.transform.position.z - transform.position.z;
    float distance = Mathf.Sqrt(xDistance*xDistance);// + (zDistance*zDistance));

    return distance;
}
private float VerticalDistance()
{
    return Mathf.Abs(target.transform.position.y - transform.position.y);
}

```

# Answer
> 0 votes
Thanks wondra, solved the issue by splitting everything and to translate the formula to C#:

where posX and posY is the target x and y where g is de phycics gravity where speed is the value I want to fill in.

Now I have the angleZ to put in my arrow Vector3

```
float s = Mathf.Sqrt((speed * speed * speed * speed) - g * (g * (posX * posX) + 2 * posY * (speed * speed)));
float angleZ = Mathf.Atan(((speed * speed) + s) / (g * posX))*Mathf.Rad2Deg;

```

I only still have the problem when y is not 0. The formula I now used only works if y=0. Have not found the correct formula so I can get the correct angle even when y is different from eachother.

---
Tags: unity, ai, projectile-physics, trajectory, aiming
---


# Question
Title: Unity C#: Using Linecast with collider bounds
I'm trying to to detect when two 3D objects overlap each other 'visually' without actually touching. For example, if I have two spheres in a scene that are 1 meter apart and I rotate my camera around the objects so that one sphere is blocked by the sphere in front of it, I want to detect when this occurs.

After many searches in this forum, I patched together the solution below. However, it only partially works: it only detects overlap when the center of the occluded object is reached (i.e., "bounds.center"). I read that there is a way to use the bounds in this scenario so that it samples multiple rays from around the object. This way, overlap is detected at the objects visual boundary and not just it's center. Unfortunately, my coding abilities are meager and I can't figure out how to do it.

Any help would be greatly appreciated.

```
using UnityEngine;
using System.Collections;

public class OverlapCheck : MonoBehaviour {

     public Transform myCamera;
     private Color mouseOverColor = Color.green;
     private Color originalColor;
     private Vector3 objectExtents;

     // Use this for initialization
     void Start () {
         originalColor = gameObject.GetComponent<Renderer> ().material.color;
         objectExtents = gameObject.GetComponent<Collider>().bounds.center;
     }

     // Update is called once per frame
     void Update () {
         if (Physics.Linecast (objectExtents, myCamera.position)) {
             gameObject.GetComponent<Renderer> ().material.color = Color.yellow;
         } else {
             gameObject.GetComponent<Renderer> ().material.color = originalColor;
         }
     }
 }

```

# Answer
> 0 votes
you should Line Cast near object to Camera.if you want know when object is behind me , you can use Vector3.Dot

https://docs.unity3d.com/ScriptReference/Vector3.Dot.html

> Dot Product of two vectors. The dot product is a float value equal to the magnitudes of the two vectors multiplied together and then multiplied by the cosine of the angle between them. For normalized vectors Dot returns 1 if they point in exactly the same direction, -1 if they point in completely opposite directions and zero if the vectors are perpendicular.

```
using UnityEngine;
using System.Collections;

public class CheckInDirection : MonoBehaviour {
    private Color originalColor;
    public GameObject  otherObject;
    public GameObject CurrenCheck;

    // Use this for initialization
    void Start () {
        originalColor = gameObject.GetComponent<Renderer> ().material.color;
    }

    // Update is called once per frame
    void Update ()
    {
        if (otherObject) {
            Vector3 forward = transform.TransformDirection (Vector3.forward);
            Vector3 toOther = otherObject.transform.position - transform.position;

            if (Vector3.Dot (forward, toOther) < 0) {
                print ("The other transform is behind me!");
                CurrenCheck = gameObject;
            } else {
                CurrenCheck = otherObject;
            }
            Debug.DrawLine (CurrenCheck.transform.position, Camera.main.transform.position, Color.white);
            if (Physics.Linecast (CurrenCheck.transform.position, Camera.main.transform.position)) {
                CurrenCheck.GetComponent<Renderer> ().material.color = Color.yellow;
            } else {
                CurrenCheck.GetComponent<Renderer> ().material.color = originalColor;
            }
        }
    }
}

```

another solution that don't need LineCast is calculating degree between camera and behind object.

```
using UnityEngine;
using System.Collections;

public class CheckDirection : MonoBehaviour {
    public Transform otherObj;
    public float angle1,angle2;
    public int Different;

    void Update ()
    {
        Debug.DrawLine (transform.position, Camera.main.transform.position,Color.white);
        Debug.DrawLine (transform.position, otherObj.position,Color.white);
        Vector3 targetDir1 = otherObj.position - transform.position;
        Vector3 targetDir2 = Camera.main.transform.position - transform.position;
         angle1 = Vector3.Angle( targetDir1, transform.forward );
         angle2 = Vector3.Angle( targetDir2, transform.forward );
        Different = (int)Mathf.Abs(Mathf.Round (angle2) - (int)Mathf.Abs(Mathf.Round (angle1) - 180));

        if(Different < 3)//Measurement accuracy
            print( "equal" );
    }
}

```

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


title: Aim up/down lookat aim target?

text:
# Question
Title: Aim up/down lookat aim target?
I have an animation of a character aiming a handgun 'straight', and firing a handgun from that straight pose. I want to have the character be able to aim up and down and fire from those poses too. Think Resident Evil 1/2/3, Alone in the dark, etc. I want to save time on my animator by not having him do the aim/up down.

I'm trying to find a way to dynamically achieve this effect from code. Do I have to write an IK solver system or is there a more straight-forward way to do it?

I'm pretty sure there's a technical name for this kind of thing, I Googled aim offset, aim target, lookat target etc but all I came up with was UE4 links. We're using our own engine.

Looking at UE4 'aim offset' it looks very similar to what I want. I wonder how it's implemented internally.

I'm not asking for code but just ideas, hints or pointers are appreciated.

# Answer
You're thinking of inverse kinematics. The effort you'd have to go to to do this 'simple' thing in code is actually quite extensive.

You are better off to have your animator do it, it should take him very little time compared to the time you'll spend.

If you can't afford that it's still going to be much faster to just learn how to make a pose yourself and export it to your engine.
> 1 votes

---
Tags: c++, animation, skeletal-animation, inverse-kinematics
---


# Question
Title: Using Google Play In-App purchases in Amazon store, can it be done?
I have an app currently in the play store (it's free), and google play IAPs are implemented in the app.

I'm new to the Amazon store, but if it allows me to upload an APK as is, what is to prevent my game from allowing users to make in app purchases via google play using an app they downloaded off Amazon? Would I be absolutely required to set up IAPs for Amazon if I use their store?

# Answer
> 0 votes
Yes if you are doing it seperately. Apps are identified with different app ID in different stores and transactions are done with related to it as well as to merchant accounts.

In app purchase feature is now unified in 5.4.0 with amazon app store too.

Soomla is paid but for all platforms as well.

---
Tags: unity, google-play-services, appstore, in-app-purchase
---


title: Re-use DOTween tweeners

text:
# Question
Title: Re-use DOTween tweeners
I am using DOTween, and I want to create a tweener, store it, and re-use it in the future several times.

```
    Tweener playerMoveUpTweener = player.transform.DOLocalMove(new Vector3(0,100,0), 0.5f, true);
    playerMoveUpTweener.SetEase (Ease.Linear);
    playerMoveUpTweener.SetRelative (true);
    playerMoveUpTweener.SetRecyclable (true);
    playerMoveUpTweener.OnComplete(() => {
        // some stuff
    });

```

But, in the future, I can't seem to be able to use it:

```
playerMoveUpTweener.Play();

```

Won't work. Not even with `Rewind()` or `Restart()`.

Is it actually possible to re-use this same tweener?

# Answer
> 9 votes
Tween is killed after it is completed, unless autokill is set to false.

```
playerMoveUpTweener.SetAutoKill(false);

```

Then use restart to play it again.

```
playerMoveUpTweener.Restart();

```

---
Tags: unity, dotween
---


# Question
Title: Why is my collision code blocking the player's movement in XNA?
I have the following code to check for collisions in my game, but this code doesn't work it as should. For example:

* I go from up to down and if collision is detect I can't turn right;
* if I go from right to left and collision is detect I can't turn down.

What is wrong with this code and how could I improve it?

```
foreach (var o in ObjectList) {
    previousPosition = player.Position;
    if (player.CollisionRectangle.Intersects(o.Rectangle) && o.isCollision == true) {
        if (o.ObjectUpdateLeftRight(player, o.Position) == 0) player.CanRight = false;
        if (o.ObjectUpdateLeftRight(player, o.Position) == 1) player.CanLeft = false;
        if (o.ObjectUpdateUpDown(player, o.Position) == 2) player.CanUp = false;
        if (o.ObjectUpdateUpDown(player, o.Position) == 3) player.CanDown = false;
    }
}

```

and `ObjectUpdateLeftRight` and `UpDown`:

```
public int ObjectUpdateLeftRight(Player.Player player, Vector2 objectToCheck) {
    if (player.Position.X < objectToCheck.X) return 0; // right
    if (player.Position.X >= objectToCheck.X) return 1; // left
    return -1;
}

public int ObjectUpdateUpDown(Player.Player player, Vector2 objectToCheck) {
    if (player.Position.Y >= objectToCheck.Y) return 2; // up
    if (player.Position.Y < objectToCheck.Y) return 3; // down
    return -1;
}

```

# Answer
> 1 votes
You are not taking into account what direction you were moving in so this isn't very surprising.

The simplest way to handle this is to split your movement into horizontal and vertical movement. Move horizontally first. If you collide with something move the player back to where he was. Then move vertically and if you collide move the player back again.

This has the advantage that you can slide along walls as long as they are vertically or horizontally aligned.

Once this works you can make additional improvements like figuring out how far exactly you have to move an object back for it to not intersect anymore.

Guaranteeing that no two objects that can move intersect at any frame makes a lot of things easier to handle, since you don't need code to handle unstucking.

# Answer
> 0 votes
The problem with the current code is that there is no displacement after a collision has been detected on one of the axis and thus when the player's rectangle intersects with the block's rectangle, the positional check is done on both sides without calculating which direction's depth is more prevalent.

Since these checks are not separated once the player enters a block from below, both the vertical and horizontal movement are blocked since your current conditions check for both after one another.

I would advise that you do additional depth checking based on the rectangle intersections either on both axis at the same time or separately as suggested by Nils. (Which is the safer the and as far as I know cleaner way to do so.)

---
Tags: xna, collision-resolution
---


# Question
Title: Using EaselJS, my spritesheet-based map is not showing up
I have a random map that generates based on a level and a set of Tile ID's, constructed using a Height Map generator I wrote using the BitmapData extension.

I've confirmed that the Tile IDs are generated correctly and can be modified to cycle through a set of tiles and changing circumstances.

The actual base image that holds the tiles is loaded and I was able to draw it separately.

However... after I update the stage when the function finishes building, I don't see any map at all and I don't understand why. I've tried to add to a container and to the stage directly, neither method is working.

Could anyone identify the problem?

```
function buildBackground()
{
    var mapSeed = Math.round(Math.random() * 2);

    var channel = Object.create(createjs.BitmapDataChannel);
    var channelOptions = channel.RED | channel.GREEN | channel.BLUE;

    var offsets = [new createjs.Point(0, 0), new createjs.Point(0, 0)];
    var interpolateType = "cos";

    var TileMap = new Array();

    accessMap = new createjs.BitmapData(null, 200, 200);
    accessMap.perlinNoise(100, 100, 6, mapSeed, true, false, channelOptions, true, offsets, interpolateType);

    var BitmapLayout = new createjs.Bitmap(accessMap.canvas);

    BitmapLayout.scaleX = 5;
    BitmapLayout.scaleY = 4;

    BitmapLayout.x = 0;
    BitmapLayout.y = 0;

    var gridSizeX = 10;
    var gridSizeY = 7;

    heightMap = new Array();

    for (x = 0; x < gridSizeX; x++)
    {
        heightMap[x] = new Array();
        for (y = 0; y < gridSizeY; y++)
        {
            heightMap[x][y] = 0;
        }
    }

var pixelPoint = new createjs.Point();
var darkest_pixel = 1;
var brightest_pixel = 0;

for (x = 0; x < gridSizeX; x++)
{
    for (y = 0; y < gridSizeY; y++)
    {
        pixelPoint.x = Math.round((x/gridSizeX) * accessMap.width) + 1;
        pixelPoint.y = Math.round((y/gridSizeY) * accessMap.height) + 1;

        heightMap[x][y] = accessMap.getPixel(pixelPoint.x, pixelPoint.y);

        heightMap[x][y] /= 0xffffff;

        if (heightMap[x][y] < darkest_pixel) {
            darkest_pixel = heightMap[x][y];
        }

        heightMap[x][y] = Math.round(heightMap[x][y] * (Math.random() * 3));
    }
}

for (x = 0; x < gridSizeX; x++)
{
    TileMap[x] = new Array();
    for (y = 0; y < gridSizeY; y++)
    {
        TileMap[x][y] = 0;
        TileMap[x][y] = Math.round(heightMap[x][y] * (Math.random() * 5));
    }
}

var bitmap = new createjs.Bitmap(preload.getResult("BackgroundTiles"));

var BackgroundTileObjData = {
    images: [bitmap],
    frames: {width: 100, height: 100}
};

var BackgroundTileInfo = new createjs.SpriteSheet(BackgroundTileObjData);

var frameSize = 100;

var graphic = new createjs.Graphics();

for (x = 0; x < gridSizeX; x++)
{
    for (y = 0; y < gridSizeY; y++)
    {
        var TileID = TileMap[x][y];

        var levelModifier = 1;
        var tile = new createjs.Sprite(BackgroundTileInfo);
        tile.gotoAndStop(TileID);
        tile.x = 100 * x;
        tile.y = 100 * y;

        stage.addChild(tile);

    }
}

stage.update();
console.log("Tile SpriteSheet?");

}

```

# Answer
As the EaselJS documentation states for SpriteSheet objects :

> SpriteSheets are an object with two required properties (images and frames), and two optional properties (framerate and animations). This makes them easy to define in javascript code, or in JSON.
>
> images : An array of source images. Images can be either an **HTMlimage instance, or a uri to an image**. The former is recommended to control preloading.

Instead you pass a createjs.bitmap object which is neither. So basically if you change your SpriteSheet object to :

```
var BackgroundTileObjData = {
 images: [bitmap.image],
frames: {width: 100, height: 100}};

//or even this should work :
//images: ['/uri/to/your/tile/image']

```

It should work.
> 2 votes

---
Tags: javascript, tilemap, easeljs
---


# Question
Title: How can I convey a sensation of speed in space?
I'm making a game where you see a spaceship (in 3rd person) travelling at high-speed between planets (it takes 2-3 seconds move between them).

What effect could I use to convey the effect of extreme speed? I already know about the usual effects, change in FOV, white lines around the subjects, etc..

I'm asking about some things that are more space-like, I mean even if it's not how it would be perceived in real physics, I need it to look like it's fast and it's in space.

Don't hesitate to ask for clarification, my English is nowhere near being perfect, maybe I didn't convey my thought perfectly.

# Answer
The thing is, in space nearly everything is so far away so will naturally look stationary. The things you could do to imply speed are

1. Use loud engine noise to simulate thrusters working extra hard.
2. Shake the cockpit to simulate thruster stress on the ship.
3. Have visual indicators of some kind of rate of acceleration (not speed, speed is relative so there is no absolute speed in space).
4. Make sure you have a suitable deceleration phase, to instil the idea that the built up velocity is very powerful and needs a lot of effort to counter (perhaps with visible exhaust matter exiting from the front of the ship)

I think though that the best way to simulate speed is to make your game unnatural. You can't hear far away explosions through space, but movies will put them in because humans expect to hear the explosion as that is what life on Earth has taught us to be excited by. So, ignore the fact that in real life the sky would look stationary and go for an effect like one of these

1. Star field streaking in Star Wars when the Millennium Falcon hits top speed.
2. The tunnel effect on Star Gate or the start of an episode of Dr Who.

Having the ship have to make very slight and very fast course corrections to avoid obstacles like planets would be good too. Perhaps some kind of visible + audible alert to the captain, with some little screen calculating impact etc. You could even show the occasional planet shoot past really close in your field of view (obviously motion blurred).

Finally, why not go for the Futurama approach? A spaceship can't move that quickly through space, so move space instead :) Press the warp button, the entire universe (except your ship) squishes down really small, then expands back to its normal size with you in a different place :)
> 6 votes

# Answer
Space is mostly empty and much of what you see while in it is very far away. So there isn't much you really do visually; fundamentally you're mostly going to be working with variants of "white lines around the subject" (speed lines, possibly elongated as the ship's speed increases, the occasional bit of "space debris" or dust particles zooming by) and FOV changes. In addition, you can play with subtle camera shake or distortion effects as the ship's speed increases. If it is thematically appropriate you can use a "hyperspace" like tunnel or wormhole (or really, anything) effect when you're traveling at super-light speeds, maybe. But that's basically it; there are very few other objects that both provide a visual frame-of-reference and are also regularly close enough to a ship in most space games to really illustrate the magnitude of the ship's velocity.

However, you can also work with non-visual cues. Specifically audio, physical and gameplay cues.

Audio effects such as engine whine or rumble can give a sensation of a powerful engine being put into gear, especially when paired with screen effects like a camera shake or FOV animation. Fly-by sounds for those rare cases where the ship does pass near something moving at a significantly slower relative speed.

Physical effects (mainly, force-feedback) can be fed back to the player during acceleration or when nearing "top" speed, if the player has the appropriate hardware.

Gameplay-wise you can alter the maneuverability or responsiveness of the ship based on its speed. Maybe it reacts more slowly to attitude adjustments at higher speeds, for example, or "fights" the player via force-feedback or slightly less smooth controls.

Most of the above are wholly unrealistic, so depending on the level of realism you're going for in your simulation you may not be comfortable with including some of them.
> 4 votes

# Answer
An option is to adopt an alternate paradigm for travel, rather than trying to convey the nonsensical1 speeds you'd require.

Since you're traveling FTL *anyway*, the playbook goes out the window, and it's time to get creative. For instance, instead of travelling through the space between the planets, you could take a page from Battlestar Galactica (2003)'s playbook, and have the ship spool up the drive, blink out of existence, then pop back into existence at the destination, complete with whatever visual and sound effects you'd prefer. (The ship shrinking to and growing out of nothing, a flash, a *woop* and a *poow*, whatever floats your boat.)

---

1: Anything traveling in excess of *c* leads to all sorts of nonsense and causality violations, and essentially invalidates physics2. Once you introduce FTL, you can *basically* do whatever you want, unless you're *extremely* careful, to the point of declawing your drive entirely.

2: I assume here that your planets are more than a few light seconds apart, and that the ship is *actually* travelling fast; that it's not just a contrivance.
> 3 votes

---
Tags: movement, visualization
---


title: Tiled object layer draw sprites

text:
# Question
Title: Tiled object layer draw sprites
I added some tiles to some object layers in my tiled map and now I want to draw them in game. I tried to render everything with

```
mapRender.render();

```

but the tiles doesn't show up. Then I tried to render just one object layer and all of its objects with

```
mapRenderer.renderObjects(tiledMap.getLayers().get(0));

```

but it wasn't working.

Ingame:

Tiled:

Could someone please tell me how to make the tiles show up? Thank you very much!

# Answer
> 4 votes
All current implementations of TiledMapRenderer, such as BatchTiledMapRenderer, do not have the functionality to render any MapObject. You'll have to create your own implementation of TiledMapRenderer. This should get you started:

```
public class TextureMapObjectRenderer extends OrthogonalTiledMapRenderer {

    public TextureMapObjectRenderer(TiledMap map) {
        super(map);
    }

    public TextureMapObjectRenderer(TiledMap map, Batch batch) {
        super(map, batch);
    }

    public TextureMapObjectRenderer(TiledMap map, float unitScale) {
        super(map, unitScale);
    }

    public TextureMapObjectRenderer(TiledMap map, float unitScale, Batch batch) {
        super(map, unitScale, batch);
    }

    @Override
    public void renderObject(MapObject object) {
        if (object instanceof TextureMapObject) {
            TextureMapObject textureObject = (TextureMapObject) object;
            batch.draw(
                    textureObject.getTextureRegion(),
                    textureObject.getX(),
                    textureObject.getY()
            );
        }
    }
}

```

I would also recommend against using Tile Objects to render sprites in-game, as they're more commonly used for Tiled purposes and identifying entities that you want to spawn in-game. This video explains what I mean here.

This depends on the type of game, however. This is an example of using an Object Layer with Tile Objects for creating levels in a Breakout game; it makes it very easy for Box2D bodies to be created and the bricks to be drawn:

# Answer
> 1 votes
Please consider that the previous answer is not complete.

If you render object with the 3 param batch.draw(...), the TextureMapObject would be rendered without the provided in the TileMap **scale** and **rotation**. I suggest using a more accurate

```
batch.draw (TextureRegion region, float x, float y, float originX, float originY, float width, float height,
        float scaleX, float scaleY, float rotation);

```

in my kotlin implementation it looks like this

```
 override fun renderObject(obj: MapObject) {
        if (obj is TextureMapObject) {
            batch.draw(
                      obj.textureRegion,
                      obj.x,
                      obj.y,
                      obj.originX,
                      obj.originY,
                      obj.textureRegion.regionWidth.toFloat(),
                      obj.textureRegion.regionHeight.toFloat(),
                      obj.scaleX,
                      obj.scaleY,
                      obj.rotation)
        }
    }

```

---
Tags: libgdx, tiled
---


# Question
Title: How can I implement multiplayer cloaking with visuals that resists client-side hacking?
I've been thinking about implementing stealth in a multiplayer game. It's a MOBA style game, so think League of Legends (LoL) and Heroes of the Storm (HotS). Multiple clients connect to a single server, which broadcasts the game state to all clients. Clients send their input data to the server, which might reject it when encountering invalid commands, thus rendering cheating impossible (well, in theory).

Now, I mention these games on purpose because both implemented stealth differently. LoL has stealth with two possible states: you're either completely visible or completely invisible. HotS on the other hand, implements stealth in such a way that you can tell by a shimmer in the air:

I think this is a neat mechanic, as it promotes / rewards paying attention to your surroundings. However, this being a multiplayer game made me realize that this might prove easily exploitable.

When you implement stealth in 'the LoL' way, you can simply stop sending player coordinates to the other clients. When the player's character breaks stealth, the server can broadcast the location again. However, with the HotS model, a shimmer can be seen in the air where the character is moving about. This means that the server must be sending the player's location to the other clients. Which means that players that change the texture or model or even the game code itself could render the cloak mechanic useless. Here is a thread on the HotS boards about it.

**My question is** whether there is *some way* to implement cloaking (with a 'shimmer', à la HotS), without having the issue that crafty players can modify the game (data) and 'beat the system'. Is this possible, and if not, how do other multiplayer games with this mechanic deal with this? Is only the LoL style of invisibility uncheatable?

I thought about having the server send bogus 'cloak' locations every now and then, but this also harms fair players that are just paying attention, so that won't do.

# Answer
You can't implement a shimmer effect without making it easy to exploit... but what if you used an indirect means of showing that someone is around, a means that also applies to visible players?

For example, what if players leave footprints, and "footprint created" messages are sent from the server independent of player location? Every player leaves footprints so you can't make the footprint model more visible without covering the arena in them and making every individual print less noticeable, but if a player sees a footprint appear without a visible character they know someone is there.

You can also do stuff like having small pebbles that are knocked around, rustling grass when someone is walking through it, or ripples that appear when someone moves through water. If 'signs' only apply to certain locations or materials, this could add extra strategy that forces invisible characters to move carefully and avoid things that will give away their positions.
> 20 votes

# Answer
When you look at the countless other questions about preventing cheating in multiplayer games which are on this site you will easily see that there really is no technical measure to prevent client-sided cheating.

All you could do is provide *less* information about the cloaked entity. All the client needs to know to render the distortion effect is that there is *something* cloaked at that position. But it doesn't need to know anything specific about it, like what exactly it is, how much health it has left and what it is doing right now. Depending on your game, that alone can be a game-changing information deficit for the player.
> 30 votes

# Answer
Yes, any information that you send to the client, can be showm more obviously than you intended. But here is the trick:

# Mitigate the impact

Sure, the client may have some information, but by thinking carefully on what information you are willing to share, and on what players can do with it you can at least mitigate the impact of client hacks.

## 1. What does the player observe?

1. You see the character with characteristics on the spot: In this case the client will have all information and hacks can simply undo the cloak
2. You see something on the spot: In this case the client has location information. It can make the location obvious but other information should still be hidden.
3. You observe something but it is not in the spot

a. You see something but it is not on the spot (Bridge or bush moves, but its large so you don't know where to aim; footsteps only become visible with a 2 second delay): In this case the client only knows that there is something, but not where/what exactly.

b. You observe something in a different way (sound if something is in the area; closeness indication like a radar with or without direction)

The screenshot in the quesition seems to be between 1 and 2 as it probably is based on limited information, but you still see the outline which could give away some information.

## 2. What can the player do?

Suppose you think someone is at coordinate XY, what can you do? Here are some typical choices:

### Attacking

1. You can attack him as if he is not cloaked
2. You can attack him with AOA attacks/traps which uncloak him or not
3. You can actively uncloak him and only attack him afterwards
4. You cannot attack him at all

### Moving

1. As you start to move, you notice that the engine mysteriously takes you on a detour
2. You start walking towards your goal normally, but when you reach the hidden character you move around him or stop
3. You don't get blocked by the hidden character

If the route selection is normally done client-side
> 1 votes

# Answer
The ripple effect could be done through shader code. You can disable texture usage in this mode so the simple texture change is no longer a problem.

In 3D, when model comes into play, you can still just change the shader to one that simulates refraction, using just model's surface, discarding the colour. Even when model is replaced somehow, the effect remains.

Modifying pre-compiled shader would be as hard as modifying game code and I think it is one level harder than some texture lookup within game files.
> -1 votes

---
Tags: multiplayer, game-mechanics, anti-cheat
---


# Question
Title: Unity WWW: Post a request to an URL with custom headers
I am using C# to try retrieve a token and my code is based on this example:https://docs.unity3d.com/ScriptReference/WWWForm-headers.html

```
IEnumerator Start() {
  string urlToken = "myUrl";

  WWWForm form = new WWWForm ();
  form.AddField ("username", username);
  form.AddField ("password", password);

  Hashtable header = form.headers;//where I am getting my error*

  header.Add("content-type", "application/json"); //header I need send over

  WWW tokenRequest = new WWW (urlToken, form, header);

  yield return tokenRequest;
  print ("Anything back?" + tokenRequest.bytesDownloaded);
}

```

**\*Assets/WWWDemo.cs(46,19): error CS0029: Cannot implicitly convert type System.Collections.Generic.Dictionary to System.Collections.Hashtable**

How would the header be assigned correctly? Does anyone have any ideas?

# Answer
> 3 votes
form.header is a `Dictionary<string, string>` \- you need to do this

```
form.headers["content-type"] = "application/json";

```

or this (my preference)

```
var headers = form.headers;
headers["content-type"] = "application/json";

```

or this

```
Dictionary<string, string> headers = form.headers;
headers["content-type"] = "application/json";

```

Then your WWW constructor needs to be called like this

```
WWW tokenRequest = new WWW(urlToken, form.data, header);

```

because the 2nd parameter is a byte\[\] and not a Form (you missed that part out from the tutorial).

# Answer
> 2 votes
I have not tested it, but maybe you can try:

```
header["content-type"] = "application/json";

```

Anyway, as a note, if this is a real example; the `content-type` header is typically sent by the server, is not a request header

---
Tags: c#
---


# Question
Title: What architecture should I use to support extensions in my game?
*What is the proper architecture for the game, that support extension modules, written in other languages*?

I mean I have a simple game - written in `Groovy` (basically `Java`), heavily relying on Game object pattern (resources, configurations, part of game logic), which have a couple classes with certain logic.

I want to provide an ability to override that logic, using external modules written in another language (ideally I want to support any language). Also I want to have an ability to add additional logic.

What is the proper architecture for that?

# Answer
You need to choose a standardized ABI (application binary interface) that all the languages you want to support can themselves support. Typically, this will be C (*not* C++) because C has a standardized ABI and many, many languages choose it as their method of inter-operating with other languages as a result.

You will need to define a expected interface, one you expect extensions to your game to expose (such a `PluginLoaded` entry point).

You'll then want to load your game's extensions from dynamically linked libraries (`.dll`s on Windows, `.so`s on non-Windows platforms). Once loaded into memory you locate and call your expected entry point (`PluginLoaded`, et cetera) at the appropriate time.

---

Another option you can use instead support extension via interprocess communication. In this approach you still define an agreed-upon interface, except this time it's a networking protocol (or similar form of IPC) instead of a binary interface, and instead of loading DLLs you simply wait for connections from other programs that are running to "extend" your game. You don't have to deal with DLLS or a mandated binary format in this approach, but your users instead have to write and run their own processes to leverage extensions, which is somewhat awkward.

---

Finally you could combine the approaches, so you load DLLs to avoid the annoyance of having to run "extension" processes, but once loaded you have only a minimal entry point into the plugin that is called. This minimizes the amount of boilerplate work you have to do to expose a C API to the various bits of your game you'd want to extend. Instead, invoking the single entry point tells the plugin to start communicating with your game via IPC, even though they are technically in the same process.
> 4 votes

---
Tags: architecture
---


# Question
Title: How to track if an action is executing with IEnumerator and StartCoroutine
My code:

```
public class CharacterBehaviour: MonoBehaviour {

bool isExecuting=false;
Action action;

void Start{
action=new Action();
}

void Update{
//Other methods
if(!isExecuting)
{
StartCoroutine(action.execute(out isExecuting));
}
}

public class Action: MonoBehaviour
{
IEnumerator execute(out isExecuting)
{
return YieldReturnNull)();

//Execution

isExecuting=false;
}

public IEnumerator YieldReturnNull()
{
yield return null;
}
}

```

I am using IEnumerator to start a coroutine right? But I need this out value to do not start a lot of coroutines in Update, just when it finalizes I must start another. The problem it's that I need to return of yield of course in the beggining (The YieldReturnNull method is a trick because IEnumerator does not accept out or ref as parameter in a method returning yield) but it returns for me this error:

*The out parameter \`isExecuting' must be assigned to before control leaves the current method.*

How to solve it? I need to return yield in the beggining and apply the bool in the end. Thanks. :)

# Answer
> 2 votes
Why not store the `isExecuting` variable within the action?

```
public class CharacterBehaviour: MonoBehaviour {
    Action action;

    void Start{
        action=new Action();
    }

    void Update{
        //Other methods
        if(!action.isExecuting)
        {
            StartCoroutine(action.execute());
        }
    }

    public class Action: MonoBehaviour
    {
        public bool isExecuting = false;
        IEnumerator execute()
        {
            isExecuting = true;
            yield return null;
            //Execution
            isExecuting=false;
        }
}

```

If you also need to access `isExecuting` from the `CharacterBehaviour` you can provide a property for that.

```
public isExecuting {
    get
    {
        return action.isExecuting;
    }
}

```

---
Tags: c#, coroutines
---


title: TileMap chunk generation

text:
# Question
Title: TileMap chunk generation
I have a class TileChunk which at it's most basic contains a rectangle that surrounds the chunk, and four bools isLeftLoaded, isTopLoaded, etc. Using the rectangle I can determine which chunk the player is in.

What I want to do is create some kind of method which checks the current chunk the player is in, and if nothing is loaded then create new chunks that surround the sides that haven't been loaded. The problem I'm coming across is that using the four bool variables doesn't seem to work correctly. At initialization, I create 9 chunks to make a 3x3 starting area but some of the bool variables aren't being set correctly.

My question is how should I write a method which determines what chunks have loaded chunks adjacent to them? Every chunk is stored in a List, but other than using the bool variables I'm not sure what is the best way to do this.

# Answer
> 1 votes
The general design is problematic, you might be able to get it to work, but it will be unnecessarily tricky.

Instead give chunks coordinates that correspond to their position in the game world in chunks. If they are all the same size or multiples of a common size, then figuring out which world position corresponds to which chunk will be very easy.

Now you could have a list of chunks that exist (preferably a hash table with the coordinates as keys). And depending on the player position just check if the chunks he should be seeing exist. If all of them exist you're good, if one or more of them don't exist create them and add them to your list. That way you also won't have to initialize a 3x3 starting area.

A problem with your system would also be that if you somehow teleport the player somewhere. Suddenly there might be no existing neighbour nearby, so how could you deal with that?

---
Tags: c#
---


# Question
Title: How do I read input from multiple keyboards/mice on one computer?
I want to be able to read inputs from **multiple keyboards** and still differentiate them. It's for split-screen. I know it's possible, because Serious Sam 3 allows it.

Edit : Well a whole lot of my description has been removed, anyway, one of the maine details was that it had to be cross-platform! However, I found just today a POSSIBLE solution, which is using libusb 1.0 (it's Windows-compatible since 1.0), I'm using 1.0.15 (which is actually libusbx, they've created a branch and have come back to the main branch for 1.0.16 =/ )! So my actual answer now is (because I have no PS/2 port :S), is libusb recognizing PS/2 devices (I know nothing about PS/2 standard, so I don't know, but I have some reasons to think it can be recognized). Does anyone know it? If noone knows, I wrote a program that enumerates USB devices and displays their Product and Manufacturer name, is anybody willing to test it? (you can run it in Avast! Sandbox if you prefer, it still works ^^)

Thanks in advance, and thanks for all the responses yet!

Oh by the way, using RawInput is out of question because of its Windows exclusive API, I thought about it once, but I want my game to be Windows/Linux/Mac compatible ;)

Edit2 : As marked in the tags, I'm coding in C++ (was also part of the original post)! I really don't understand what happened, since the original post title even changed =/ That was not my original question, the question was about the PS/2 / USB thing!

# Answer
Assuming Windows, an example of RawInput is on CodeProject, written for C#.

The gist is that you must use the RawInput API to enumerate input devices such as all keyboard devices. For each device you can then get a handle to the individual input device. This handle is passed in to the RawInput message reading API and stored in RAWINPUTHEADER structure. You can compare these to determine which keyboard the message came from. You could then correlate this with enumerated mouse devices to make it so the "first mouse" matches the "first keyboard" (which might change every time the app is run or whenever the computer is rebooted or whenever devices are (a|de)ttached; I don't know).

Note to be careful as many modern gaming mouse are also technically keyboards. Pressing some extended buttons on such mice will generate a keyboard event. Likewise, some keyboards also identify as mice for various reasons. You'll want a way to detect/select which keyboards/mice to use for each player rather than just taking the first two enumerated devices, just to be sure.

Note also that XInput supports up to four players on gamepads directly and does not use Win32 input events, raw or otherwise.

SDL does not appear to support multiple keyboards in its public API, which is disappointing. I'm unsure what the story is on GFML, SFML, etc.

GTK seems to have a group field in GdkEventKey, which is maybe what you're looking for. The documentation is not clear, so I don't know. The low-level X11 API definitely supports it through the deviceid field of X11 input events. IF you're using low-level input on Windows you should probably do the same on Linux (if you structure code sanely it's not hard to port), though using a high-level GUI library like GTK is preferable in general.

OSX should in theory support it via the Quartz Event Services API but I am not familiar with coding low-level input for their platform. You might have to delve into the "deprecated" Carbon API, which I've heard supports it but I can't find any examples online right now.

I'm unsure what the USB support on iOS is like, though I suppose you probably aren't looking to hook up multiple (or any) keyboards to an iPad or anything. Android should have support, too, but again I have zero experience with its low-level input capabilities.

JavaScript/DOM does not support it at all nor are there are workarounds currently; the DOM events API simply doesn't expose device information for keyboards/mice. The only way to properly handle multiple players with separate input devices there is the new gamepad API.
> 3 votes

# Answer
I know you asked not to use RawInput, unfortunately on Windows, it will not be possible to use raw USB/HID for mice and keyboards. Windows has an exclusive file lock on mice and keyboards and will not allow you to read from the device directly. You will have to use RawInput or some other Windows specific API for mice and keyboards. I recommend you use LibUSB like you wanted to and simply use #pragmas to separate out the Windows specific code.
> 1 votes

# Answer
ifdef is your best code portability tool. Write your high level API with multiple mice in mind. Write your low level API in such a way so it uses RawInput on Windows and whatever you like in Linux and Mac. By the way, the fun part, you cannot obtain HID devices on Windows without using RawInput, so you must use it anyway :)
> 0 votes

---
Tags: c++, input, mouse, keyboard
---