# Question
Title: Polygon trigger colliders for 2D platformer
I'm creating a 2D platformer in MonoGame and I'm thinking of using AABB as physical colliders for characters and then have a trigger polygon collider on each character for checking for example if an enemy's weapon is touching the player, making it more precise. The polygon collider is animated so every frame in every animation has its own points. That's a lot of work. Is that precision needed? What is usually done in this situation?

# Answer
Updating a primitive collider position is already costly, polygon colliders are really expensive by definitnion, i only use it for static objects, changing a polygon collider position is really expensive. And on top ot that changing a polygon collider actual polygon.? Its probably not a good idea, you could try but i dont thinl you will succeed. Most people use primitive colliders next to each other to fake a more complex geometry.
> 0 votes

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


title: No files in .net.minecraft

text:
# Question
Title: No files in .net.minecraft
So, I've been trying to make a minecraft 1.11.2 client for minecraft. Thing is, the mcp/src/minecraft folder is empty, without any net files. The only error I had while decompiling was missing lwjgl 2.9.4, which does not exist. I have everything ready, but those files are missing, and thus I cannot code anything on my client(I am only using allowed mods.) This is a massive project I am taking for my favorite server, and I would like some help. Can anyone be kind and tell me how to fix this?

I have installed Optifine files for my client, and seems to have got about half of the files that I need.

What I need:

What I have:

As you can see, I am missing a lot of packages and have errors in most of them.

# Answer
> 1 votes
# Get Minecraft Forge

There's no reason to decompile Minecraft yourself, the Forge team has already done everything that needs to be done and in a way that...

* Complies with the Minecraft EULA
* Insures compatibility
* Prevents modification of the vanilla source (see bullet 2)
* Allows *viewing* of the vanilla source (as a reference)
* Makes compiling your mod jar file easy

---
Tags: minecraft-modding, client
---


# Question
Title: Why don't variables in a script on a prefab clone store runtime changes?
I have a building prefab. There is a simple script attached to it that allows me to store unique data for each prefab instance, such as address. There are hundreds of clones of this prefab.

The prefab is instantiated like so:

```
//instantiate a "building" object :
    multiFamHigh = Instantiate(multifamilyHigh,myV3,Quaternion.identity) as GameObject;

//set a reference to the prefab's behavior script:
    BuildingBehavior bldgBhave = multiFamHigh.GetComponent<BuildingBehavior>();

//set the information for the prefab:
    bldgBhave.setInfo( mgr.lotsList[chose].getAddress(),buildingRef);

```

In the "TownCreator" script, after the prefab is instantiated, I call the setInfo function and pass the address to it. The setInfo looks like this:

```
public class BuildingBehavior : MonoBehaviour {

    private string address;

public void setInfo(string useString, int bldgListRef)
    {
        address = useString;
        Debug.Log ("Set Address = " + address);
        buildingListRef = bldgListRef;
    }
}

```

The debug log correctly displays "you set address 3071 N." - meaning at that time, the "address" variable of the prefab script is set to 3071 N. Perfect.

However; later, when I click on any of the prefabs at runtime (via the mousedown) the UI message box pops up (as intended), and the Text is changed from "New Text" (default) to a blank string. I added a similar Debug.Log, at that point, and it also tells me that "address" on the clone is blank.

That code is:

```
 void OnMouseDown()
    {
        thisCG = GameObject.Find("MainCanvas").GetComponent<CanvasGroup>();
        thisCG.alpha = 1;
        CanvasStuff thisCS = GameObject.Find("MainCanvas").GetComponent<CanvasStuff>();
        thisCS.setAddyText (address);
        Debug.Log ("clicked on " + address);
    }

```

This happens:

Any ideas why the script on the prefab clones is not storing the values?

Also - when I change (address) to ("Address"), the popup has "Address" above the OK, Thanks! button. :/

# Answer
> 1 votes
The problem was that my prefab was done in haste as a place holder until other assets were further refined and both the plane and the cube that made up the prefab had the script attached to it. The address was being stored on the plane during creation and the onMouseDown() was being triggered on the cube.

So, in a way @jhocking was right that two different "address" variables were being used.

*sigh* \- live and learn :)

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


# Question
Title: How would I tell the player what options they have without explicitly telling them?
I'm writing a script for a game story which starts with a bombing of a school. You spawn in a room at the second floor. You play as a child and his 2 best friends and you have 2 options:

1. Hide in the bombing shelter with everyone else
2. Risk your lives in an attempt to get out of the schools

I need a way to non-explicitly tell the player to choose one of these options. Rather than tell the user straight out with a message box, I would like the story to *tell* this to the player.

How I think I might do this:
1. Have an opening scene where the ncps talk with the main character (the main character and his best friends) and initially discus the 2 options.
2. Leave the user to figure this out by giving him/her some clues. This might be an open door to get out of the school `[2]` , all the other npcs moving to the bombing shelter, etc `[1]`.
3. Give a hint in the loading menu / pause menu. Not the smartest idea, however...

Does anyone have any ideas how to reveal the 2 options without explicitly stating so? I'm free to any ideas.

# Answer
The opening scene would work well. In specific, you could stage a conversation about what school policy is during a bombing, and allude too the two options. For example, one NPC could say this:

> Yeah, school policy is to go directly to the bomb shelter. But some of my friends say that they will just make a run for the door and try to get out.

You might want to adjust the wording so that the two options are presented perfectly, but this method seems to work well.
> 2 votes

# Answer
There are several layers to this. Give the player motivation, let them know it's possible, avoid mechanical confusions or distractions, and test and repeat.

I'd suggest providing some incentive to go outside. Create a risk / reward model. So maybe a window with something outside they can see and would want, or maybe a radio story overheard. But also some danger, if you want to build tension.

It'll also be important that players understand they can leave, from a functional / mechanics standpoint. So if you have doors, give them Windows so the player sees something on the other side. Maybe make your shelter have other doors that the player and npcs are using to move around inside the shelter.

If you have other exits keep this in mind. Usable exits versus just place setting. Yes, a shelter would normally have an air vent, but don't include it just for dressing if the player can't use it.

And get new players in to try it. You know the game, so any distractions you'll subconsciously ignore. Any confusion you won't see because you already know.

A good way to check this without watching players directly is to use heat maps. Track where players go, and see if there's a space they frequently go to. Maybe they expected an exit in the rear, and that the front door would be locked. Maybe one of your windows looks big enough to get out of. Look at where they first go, or where they go after you provide them a clue or some incentive to leave.

More so, you can add clues or details based on these behaviors. If half your players go searching for a back door, build the shelter in a loop that brings them right back to the front door.
> 0 votes

---
Tags: game-design
---


title: Do I need VR camera for VR Project?

text:
# Question
Title: Do I need VR camera for VR Project?
I am to make a project involving virtual reality for college, I have a budget of $800, the original idea is to get a VR camera (this camera https://www.stereolabs.com or any other similar camera) and program it with Unity to display objects in the environment and or hide real objects in the room by first recognizing it by the camera.

However while searching I found this product (vuforia) and made a simple demo on unity which accomplishes displaying objects on a certain position, I am not sure if I will need the VR camera after this since this can run on any camera. My expereince with unity is good mainly making games, but I have little information about both VR camera hardware and vuforia.

some features that I need to implement include:

* Displaying objects (virtual avatar)
* hiding objects (real objects that are there like a table)
* be able to control avatar using button (adding button as well)

So, the questions I have:

1- can these VR hardware camera be programmed with unity) ?

2- should I just use vuforia and forget about the VR camera, or are there some feature the VR camera can do that I can integrate with vuforia and unity?

3- is unity personal edition able to handle face recognition ?

Thank you

# Answer
> 2 votes
Do you need a VR camera for a VR game? No. Absolutely not. A VR camera is for *recording stereoscopic video* and has no bearing on using a 3D engine to *create stereoscopic views.* This is basically like asking "do I need a 360 degree camera in order to use Google Earth?" No, that would be silly.

Could you combine the two? Sure. The Microsoft HoloLens is doing pretty much that: using multiple cameras in order to map the real world and create immersive experiences by allowing the virtual holograms to "hide" behind real world objects.

Now, you would need a *VR headset* (such as an Oculus Rift, HTC Vive, or Google Cardboard) in order to properly test your game. This is the reverse of a stereoscopic camera, and it would be the only way to make sure that your game will feel right and that the controls are appropriate.

As for Vuforia, Vuforia is for determining the 3D position of a target object with respect to the camera. This is done primary for *AR* not *VR* (that is, displaying 3D content overlaid on top of the real world). Vuforia can do this with one camera or two or five (as the Microsoft HoloLens has). If your game isn't interacting with the real world at all, you don't need Vuforia.

Depending on what your goals are, you will have to evaluate these options and figure out which one actually fits your project.

---
Tags: unity, android, virtual-reality, augmented-reality, vuforia
---


title: Make Float Hindi (Devanagari)?

text:
# Question
Title: Make Float Hindi (Devanagari)?
Whenever the game sessions ends and the Game Over scene is loaded, the score is stored in this float, which is in another script that I do not have on here:

```
gameOverScore

```

How would I get `gameOverScore` to show in Hindi? The script I made earlier for the actual conversion is not quite working:

```
    char[] hindiNumbers = {'\u0966','\u0967', '\u0968', '\u0969', '\u096A', '\u096B', '\u096C', '\u096D', '\u096E', '\u096F'};
    int [] digits={0,0,0,0,0,0,0,0,0,0};
    //char[] hindiScore;

    private float gameOver_LastestScore;    //Score brought FROM Managers...

    public float gameOver_LastestScore_;    //Score GOING BACK TO Managers...

    private static GameOver_HindiConversion instance;

    void Awake ()
    {
        instance = this;
    }

    public static GameOver_HindiConversion Instance
    {
        get
        {
            return instance;
        }
    }

    void Start ()
    {
        gameOver_LastestScore = PlayerPrefs.GetFloat ("PlayerPref_ScoreCount");

        gameOver_LastestScore_ = convertToHidi ((int)gameOver_LastestScore);
    }

    public int convertToHidi(int score)
    {
        //Start: split score into digits
        int remainingScore = score, i = 0;
        while (remainingScore > 0)
        {
            int digit = remainingScore % 10;
            ///Debug.Log (digit.ToString ());
            digits [i] = digit;

            remainingScore = remainingScore / 10;
            Debug.Log (remainingScore.ToString ());
            i++;
        }
        ///Debug.Log ("i="+ i.ToString ());
        //End: split score into digits

        //Start: Display digits in hindi

        for (int j = i; j > 0; j--)
        {
            //textView.text += hindiNumbers [digits [j - 1]].ToString();

            gameOver_LastestScore += hindiNumbers [digits [j - 1]];
        }
        return (int)gameOver_LastestScore;

        //End: Display digits in hindi
    }
}

```

# Answer
Instead of converting the number to int you should construct a `String` from the characters instead. The only thing you have to change is your last part.

```
String number = "";
for (int j = i; j > 0; j--) {
    number += Character.toString(hindiNumbers [digits [j - 1]]);
}

// Use number elsewhere...

```

The variable `number` is now your number represented in Hindi numbers. You'd also have to save the number as a String instead of an integer since an integer can't be defined in hindi numbers (nor can any other primitive number data type).
> 0 votes

# Answer
If I understand correctly, this might do what you want. Just replace your `convertToHidi` with the provided one.

```
    public string convertToHidi(int score) {
        var scoreChars = score.ToString().ToCharArray();

        for (var i = 0; i < scoreChars.Length; i++) {
            scoreChars[i] = hindiNumbers[scoreChars[i] - 48];
        }

        return string.Join("", scoreChars);
    }

```

You pass your score, and it returns a `string`, not an `int`. The string will be using your hindi characters for each digit.

You can set it like

```
gameOver_LastestScore_ = convertToHidi(gameOver_LastestScore)

```

Try to use more descriptive variable names to avoid confusion. `gameOverLastestScoreText` would be easier to understand than `gameOver_LastestScore_`.

If you want to test it online, it is here.
> 0 votes

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


# Question
Title: Why does my 2D top-down joystick code occasionally stop working?
I'm working on a 2D top-down game, and am working on the player controls.

I have the following code currently controlling a player sprite:

```
void Update () {
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");
        float headingAngle = Mathf.Atan2(moveHorizontal, moveVertical);
        Debug.Log("Heading angle: " + (headingAngle * Mathf.Rad2Deg).ToString() + " degrees.");
        Quaternion newHeading = Quaternion.Euler(0f, 0f, headingAngle * Mathf.Rad2Deg);

        if (transform.rotation != newHeading && (moveHorizontal != 0f || moveVertical != 0f))
        {
            Debug.Log("Turning. Rotation: " + transform.rotation + " | New Heading: " + newHeading);
            transform.rotation = Quaternion.Slerp(transform.rotation, newHeading, turnSpeed * Time.deltaTime);
        }
        else
        {
            Debug.Log("Heading in the right direction, moving...");
            transform.position += new Vector3(moveHorizontal * moveSpeed * Time.deltaTime, moveVertical * moveSpeed * Time.deltaTime, 0);
        }
    }

```

This code sort of works, but occasionally the player will stop moving, even though it's rotated in the direction that the joystick is pointing. When that happens, the `transform.rotation` quaternion will be something like '(0, 0, -7, -7)', but the `newHeading` quaternion will be '(0, 0, 7, 7)', like they've flipped around. When that happens, the `transform.rotation != newHeading` in the `if` condition is always `true`, so the `else` condition is never reached.

If I keep moving the joystick to different locations, eventually the player will start moving again.

By the way, I have a sprite attached as a child to a game object, and the sprite is rotated 90 degrees in the z-axis, if that makes any difference.

Any help would be appreciated!

# Answer
> 1 votes
Remember, the basic `==` / `!=` operators, unless explicitly overridden to check for something else, are looking for *bitwise* equality. They answer the question "are these two items *literally* the same, down to the very last decimal place?"

This is important to keep in mind, because very often we don't *want* bitwise equality. Instead, we want to ask "are these two items *effectively* the same for gameplay purposes?" The 20th binary digit after the decimal is rarely visible to players, so checking for a match bit-for-bit is usually much more exacting than we want, finding mismatches when as players and designers we expect to see a match.

This is why you'll often see advice to never compare two floating point numbers for exact equality - use range based comparisons (`<` `<=` `>=` `>`) or epsilons like Unity's `Mathf.Approximately()` method instead, to match floats that have a meaningful value rather than an exact bit pattern.

This gets compounded in the case of quaternions by the fact that quaternions form a double cover over the set of 3D rotations. That means any single rotation in 3D can be expressed equivalently as two different quaternions, `q` and `-1*q`, like your example of `(0, 0, 0.707, 0.707)` and `(0, 0, -0.707, -0.707)`. You can verify that assigning your transform's rotation to either of these quaternions yields the same result, but we can see at a glance that comparing them for numeric equality won't find them to be the same, or even similar.

Instead of checking if two quaternions are bit-for-bit identical, what we really want to ask is **"do these two rotations face the same way?"** To do that, we can measure the similarity between the two quaternions using `Quaternion.Angle()` to determine the angle of rotation between them. If the angle is very very small, then you can be confident they're sufficiently equivalent.

(You can also use a dot product for this, to get the cosine of the angle instead, but using the `Angle` convenience methods gives us a nice, linear, easy-to-interpret result that's often worth the extra trig)

---

One last thing before I finish this answer: your rotation update contains some common errors.

```
transform.rotation = Quaternion.Slerp(transform.rotation, newHeading, turnSpeed * Time.deltaTime);

```

When you interpolate between your current value and a target using a small step, the result is not a linear approach at a consistent speed, but an exponential ease-out. (Fast at the start, and slowing down as your value gets closer and closer to its target, approaching it asymptotically)

* This is fine and desirable at times, but because it's a non-linear rate of change, multiplying by `deltaTime` does not correctly adjust it for a variable framerate. You need to use an exponential weight, as described in this answer. You also probably don't need to use the more expensive `Slerp`, which ensures a more even rate of change. Since you're already using a non-linear easing, you probably wouldn't notice a change from switching to the simpler `Lerp`.
* Alternatively, if you want a constant rate of change, use the `RotateTowards()` helper method \- this handles the necessary math to rotate at a constant speed without overshooting.

---
Tags: unity, 2d, rotation, quaternion, joystick
---


# Question
Title: What is the mathematical explanation behind this implementation of simulating eyeballs roll in eyes?
I want to simulate eyeballs roll in eyes and I have found and forked this implementation in codepen.io. This is exactly what I need.

```
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var border = 10;
var centerX = c.width / 2;
var centerY = c.height / 2;
var radius = 40;

var radiusEye = 12;

var faceCenterX = centerX;
var faceCenterY = border+radius + 60;

var radiusEyeIn = 6;

var eyeYPosition = faceCenterY-8

var reyedx = faceCenterX+(radiusEyeIn/2)+13;
var reyedy = eyeYPosition;

var leyedx = faceCenterX-(radiusEyeIn/2)-13;
var leyedy = eyeYPosition;

var eyesgap = 4;

var eyeXGap = (radiusEye/2)+9;

var reyedxafter = reyedx;
var reyedyafter = reyedy;

var leyedxafter = leyedx;
var leyedyafter = leyedy;

function drawscreen(){

  ctx.beginPath();
  ctx.arc(faceCenterX, faceCenterY, radius, 0, 2 * Math.PI, false);
  ctx.fillStyle = 'rgba(100,100,100,0.5)';
  ctx.fill();
  ctx.stroke();

  var radiusEye = 12;
  ctx.beginPath();
  ctx.arc(faceCenterX-eyeXGap, eyeYPosition, radiusEye, 0, 2 * Math.PI, false);
  ctx.fillStyle = 'rgba(255,255,255,1)';
  ctx.fill();
  ctx.stroke();

  ctx.beginPath();
  ctx.arc(faceCenterX+eyeXGap, eyeYPosition, radiusEye, 0, 2 * Math.PI, false);
  ctx.fillStyle = 'rgba(255,255,255,1)';
  ctx.fill();
  ctx.stroke();
}

function draweyes() {

  ctx.beginPath();
  ctx.arc(reyedxafter, reyedyafter, radiusEyeIn, 0, 2 * Math.PI, false);
  ctx.fillStyle = 'rgba(0,0,0,1)';
  ctx.fill();

  ctx.beginPath();
  ctx.arc(leyedxafter, leyedyafter, radiusEyeIn, 0, 2 * Math.PI, false);
  ctx.fillStyle = 'rgba(0,0,0,1)';
  ctx.fill();
}

//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

function mouseMove(e) {
        var mouseX = e.pageX - this.offsetLeft - faceCenterX;
        var mouseY = e.pageY - this.offsetTop - eyeYPosition;

        var ratioX = Math.abs(mouseX)/(Math.abs(mouseX)+Math.abs(mouseY));
        var ratioY = Math.abs(mouseY)/(Math.abs(mouseX)+Math.abs(mouseY));

        if(mouseX > 0){
          reyedxafter = reyedx + (ratioX*eyesgap);
        } else {
          reyedxafter = reyedx - (ratioX*eyesgap);
        }

        if(mouseY > 0){
          reyedyafter = reyedy + (ratioY*eyesgap);
        } else {
          reyedyafter = reyedy - (ratioY*eyesgap);
        }

        if(mouseX > 0){
          leyedxafter = leyedx + (ratioX*eyesgap);
        } else {
          leyedxafter = leyedx - (ratioX*eyesgap);
        }

        if(mouseY > 0){
          leyedyafter = leyedy + (ratioY*eyesgap);
        } else {
          leyedyafter = leyedy - (ratioY*eyesgap);
        }

        ctx.clearRect(0, 0, c.width, c.height);
        drawscreen();
        draweyes();
}

function init() {
    //c.addEventListener('mousedown', mouseDown, false);
   // c.addEventListener('mouseup', mouseUp, false);
    c.addEventListener('mousemove', mouseMove, false);
    drawscreen();
    draweyes();
}

init();
```

```
<canvas id="myCanvas" width="500" height="400" style="border:1px solid #000000;">
</canvas>
```

I can just use this one but I don't understand the mathematical explanation behind this solution. I can only think of limiting the movement of the eyeballs in the eyes. Why do I have to do it like this one? What is the purpose of calculating `ratioX` and `ratioY`? Is there a simpler way to do similar simulation?

# Answer
It's much easier to just get the vectors of the point between the two eyes and the mouse, subtract the face vector from the mouse and normalize the result. The vector you get is the position of the pupils relative to the center of the eyes.

```
normalize(mouse - face)

```

You'll need a vector library for this. Without vectors:

```
x = mouseX - faceX
y = mouseY - faceY
mag = √(x² + y²)
if mag > 0 then
    x /= mag
    y /= mag

```
> 0 votes

---
Tags: mathematics
---


title: Update function only running once

text:
# Question
Title: Update function only running once
For some reason, the update function is only running once. Why does this happen?

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

public class LightFlicker : MonoBehaviour
{
    float timer;
    float timetowait;
    // Use this for initialization
    void Start()
    {
        timer = 0;
        timetowait = Random.Range(0.01f, 0.8f);
    }

    // Update is called once per frame
    void Update()
    {
        Debug.Log("Updating");
        timer += Time.deltaTime;
        if(timer >= timetowait)
        {

            if (gameObject.activeInHierarchy == true)
            {
                gameObject.SetActive(false);
            }
            else
            {
               gameObject.SetActive(true);
            }
            timetowait = Random.Range(0.01f, 0.8f);
            timer = 0;
        }
    }
}

```

The debug.log statement only fires 9 times. The timetowait changes, but the timer stays the same.

# Answer
> 2 votes
Once the gameobject is no longer active the code will no longer run in the update. You can also simplify the flicker by removing the timer and stuff from the update and replace with a coroutine. Get a reference to the Light and call it like so.

```
Light _light;
void Start()
{
    _light = GetComponent<Light>();
    StartCoroutine("Flicker");
}
IEnumerator Flicker()
{
    while (true)
    {
        _light.enabled = _light.enabled ? false : true;
        yield return new WaitForSeconds(Random.Range(0.01f, 0.9f));
    }
}

```

Another option would be to set the light up with a flickering animation loop that you can set whenever needed

# Answer
> 3 votes
When `timer >= timetowait` is `true`, since the game object IS active, you disable it with `SetActive(false)`. And from this point on, `Update` will never be executed, so you need to re-activate the game object from somewhere else. Or change your code based on what you want to accomplish.

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


# Question
Title: Delayed linear interpolation for networking
I'm trying to implement the delayed snapshot interpolation presented at Valve's article and also Gambetta's.

My current implementation is almost identical as described in the 'Multiplayer object interpolation' question posted here (can't link due to rep limit). I have an authoritative server that is sending snapshots to the clients about every other client. Those clients store each snapshot in a queue. I calculate a x millisecond delay (currently using twice my send rate) before starting to interpolate. This delay is calculated against peeking the first received timestamp in the queue and the current time.

What my code does is the following: Enqueue every entry from the server. The entry has a stamp from when the movement was captured, a position and a received time (client).

The client then keeps checking against the beggining of the queue if a set delay has passed since the most recent movement (currently 80ms). If it has, the client then sets the 'currentTime' (iterpolation begin time or T0) to the first entry stamp minus the interpolation delay. Then we know where we are:

```
  * The time is:
  *
  * T0           T0+dt <- currentTime
  * |-------------|========
  *
  * where T0 is the oldest entry in the queue.
  * Now we need to find the current two entries
  * that we need to interpolate to.
  * This is done by finding the first entry where
  * T0+dt is smaller the the timestamp.
  *
  * Entry(n-1)        T0+dt      Entry(n)
  * |-----------------=|=--------|-----------
  *
  * Then we just need to interpolate pos to from E(n-1) to E(n).

```

I handle the case where the current pos is less than E(n-1) and greater than E(n).

Since setting up unity is hard, building takes time and testing on the actual game code is heavy, I wrote a simulator in processing to test interpolation code. It is freely avaliable here and already contains an almost exact copy of my original Unity3D code.

The problem I'm facing is that interpolation is not working propperly. It is relatively jittery. It is probably a problem in the way I handle time but I can't figure it out how. The queue is never empty during movement. The edge cases also seem to be all handled. It can be something with the logic of the code itself.

I have a clip that shows the interpolation queue (the green line) and the previous interpolation movement (gray line): Can't post more than 2 links (link in the comments). In the clip, even though the queue seems to be 'full' and the movement almost presents no gaps, there is a noticeable stutter in the character movement. It seems like the character stops every x seconds and then starts again.

The current code I use is this:

```
public class PiecewiseLinearIntepolation {
    public static float interpolationDelay = 0.07f;
    private Queue<InterpEntry> interpolationQueue = new Queue<InterpEntry>();
    private float currentTime = -1f;
    private Vector3 latestPosition;
    private Quaternion latestRotation;

    private float latestStamp;
    private float oldestReceivedTime = 0f;

    public void Enqueue(float timestamp, Vector3 pos, Quaternion rot) {
        interpolationQueue.Enqueue(new InterpEntry(timestamp, Time.time, pos, rot));
        latestPosition = pos;
        latestRotation = rot;
        latestStamp = timestamp;
        lastReceived = Time.time;
    }

    public void Interp(float dt, Transform target) {
        //Store oldest
        if (interpolationQueue.Count > 0) {
            oldestReceivedTime = interpolationQueue.Peek().timeReceived;
        }
        //Delay the interpolation here, return oldest pos.
        if (Time.time - oldestReceivedTime < interpolationDelay) {
            //Reset current time
            currentTime = -1f;
            return;
        }

        //If we have elements, we need to start the interpolation
        if (interpolationQueue.Count > 0) {
            //This is E(n-1)
            InterpEntry prev = null;
            //If we don't have a time set, set the time to the oldest interp entry
            //The oldest entry is the first in the queue.
            if (currentTime < 0f) {
                prev = interpolationQueue.Peek();
                currentTime = prev.timestamp - interpolationDelay;
            } else {
                //If we had time, we need to move forward by adding the delta time
                //From the last frame.
                currentTime += dt;
            }

            //Boundaries More than last
            if (currentTime > latestStamp) {
                //Set to latest position
                target.position = Vector3.LerpUnclamped(target.position, latestPosition, currentTime / latestStamp);
                target.rotation = Quaternion.LerpUnclamped(target.rotation, latestRotation, currentTime / latestStamp);
                //Dump queue and clear time
                currentTime = -1;
                interpolationQueue.Clear();
                return;
            }
            //Current position is towards the first element of the queue
            //This means, since the first frame, the interpolation is still towards the first entry
            if (prev != null && currentTime < prev.timestamp) {
                target.position = Vector3.Lerp(target.position, prev.position, currentTime / prev.timestamp);
                target.rotation = Quaternion.Lerp(target.rotation, prev.rotation, currentTime / prev.timestamp);
                return;
            }
            //This is E(n)
            InterpEntry next = interpolationQueue.Dequeue();

            //Find the first entry where the current time doesn't pass it.
            while (currentTime > next.timestamp && interpolationQueue.Count > 0) {
                prev = next;
                next = interpolationQueue.Dequeue();
            }

            //Current position is towards the first element of the queue
            //This means, since the first frame, the interpolation is still towards the first entry
            //This is probably impossible
            if (prev == null) {
                target.position = Vector3.Lerp(target.position, next.position, currentTime / next.timestamp);
                target.rotation = Quaternion.Lerp(target.rotation, next.rotation, currentTime / next.timestamp);
                return;
            }

            //Calculate the time between points
            float timeBetween = next.timestamp - prev.timestamp;
            //Calculate T0+dt since prev instead of since begining
            float timeSincePrev = currentTime - prev.timestamp;

            //If there is no time, return next
            //This is probably impossible
            if (timeBetween == 0) {
                target.position = Vector3.LerpUnclamped(target.position, next.position, currentTime / next.timestamp);
                target.rotation = Quaternion.LerpUnclamped(target.rotation, next.rotation, currentTime / next.timestamp);
                currentTime = -1;
                return;
            }
            //Return the interpolation of T0+dt in this piece
            target.position = Vector3.LerpUnclamped(prev.position, next.position, (timeSincePrev / timeBetween));
            target.rotation = Quaternion.Lerp(prev.rotation, next.rotation, (timeSincePrev / timeBetween));
        } else {
            //We reach here each time we are within the oldest stamp delay but we cleared the list
            //Reset current time
             currentTime = -1f;
        }
    }

    private class InterpEntry {
        public float timestamp;
        public float timeReceived;
        public Vector3 position;
        public Quaternion rotation;
        public InterpEntry(float timestamp, float timeReceived, Vector3 pos, Quaternion rot) {
            this.timestamp = timestamp;
            this.timeReceived = timeReceived;
            position = pos;
            rotation = rot;
        }
    }
}

```

To replicate the problem, in Unity, just need to create an object, add a character controller, or any other controller to it. Then add a custom NWBehaviour and in it have an instance of this script. As server the object will call in FixedUpdate an RPC to send its position and rotation update along with a Time.time stamp. In this RPC (in the client), just call Enqueue with the data. In the Update, call Interp and pass in the Time.deltaTime and the object's transform.

# Answer
> 0 votes
I have solved the problem. There were two main issues (along with smaller issues) with the code logic.

The main issue was that the **delay** was beeing applied to all inputs. The delay code was counting on each input arriving equally spaced and this was a wrong assumption. The new delay code just waits for inputs to arrive, saves the first time an input is stored and uses this time to apply delay only to the current input 'session'. When inputs cease to come, the queue is empty and this time variable is reset to -1.

Then I disabled the delay and focused on the **interpolation**. Testing each step of the code repeatedly, I discovered that although the way of thinking was correct, the logic was not behaving as I imagined it to. The interpolation should indeed search the element to interpolate where the current time would be smaller than the element time but I thought this is were the code would spend most of the time. This actually happens only in one frame. After this frame the next interpolation is actually a interpolation to the first element of the queue (since in the prev frame the queue was cleared until the next element). Sounds confusing because it was a LOT of development... so resuming it all: The new logic (fixed and adjusted in account to what I have said) is:

* Wait for input.
* When input arrives, delay from the first input.
* When the delay is over, set currentTime to (first interp message timestamp) - (delay).
* Interpolate to the first element in the queue.
* \[Next frames\] Update current time.
* If the interpolation is greater than one find the next element to interpolate where the next interpolation will be less than one. Remove all elements before it. Interpolate to the point between the point found and its previous. Set prev element so that the next frame it will consider the next point as the first in the queue.
* Repeat until queue is empty.

And for those that like reading code:

```
[Serializable]
public class PiecewiseLinearIntepolation : Interpolator {

    //[...] class attributes removed for space

    public override void Receive(float timestamp, Vector3 pos, Quaternion rot) {
        interpolationQueue.Enqueue(new InterpEntry(timestamp, Time.time, pos, rot));
        latestPosition = pos;
        latestRotation = rot;
        latestStamp = timestamp;

        lastReceived = Time.time;
    }

    public override void Interp(float dt, Transform target) {

        //Delay the interpolation here, return oldest pos.
        if (ShouldDelay()) {
            //Reset current time
            currentTime = -1f;
            return;
        }

        //Update time
        if (currentTime >= 0f) {
            //If we had time, we need to move forward by adding the delta time
            //From the last frame.
            currentTime += dt;
        }

        //If we have elements, we need to start the interpolation
        if (interpolationQueue.Count > 0) {
            //This is E(n-1)
            prev = interpolationQueue.Peek();

            //If we don't have a time set, set the time to the oldest interp entry
            //The oldest entry is the first in the queue.
            if (currentTime < 0f) {
                currentTime = Math.Max(prev.timestamp - interpolationDelay, 0f);

                //Set the time this interpolation piece has started from
                startedTime = currentTime;

                //Set starting points to interpolate from
                startingPosition = target.position;
                startingRotation = target.rotation;
            }

            //Current position is towards the first element of the queue
            //This means, since the first frame, the interpolation is still towards the first entry
            if (currentTime < prev.timestamp) {
                timeBetween = prev.timestamp - startedTime;
                timeSincePrev = currentTime - startedTime;

                target.position = Vector3.LerpUnclamped(startingPosition, prev.position, timeSincePrev / timeBetween);
                target.rotation = Quaternion.LerpUnclamped(startingRotation, prev.rotation, timeSincePrev / timeBetween);
                return;
            }

            //This is E(n)
            InterpEntry next = prev;

            //Find the first entry where the current time doesn't pass it.
            while (currentTime > next.timestamp && interpolationQueue.Count > 0) {
                if (interpolationQueue.Count == 1) {
                    next = interpolationQueue.Dequeue();
                    prev = next;
                } else {
                    prev = interpolationQueue.Dequeue();
                    next = interpolationQueue.Peek();
                }
            }

            //Calculate the time between points
            timeBetween = next.timestamp - prev.timestamp;
            //Calculate T0+dt since prev instead of since begining
            timeSincePrev = currentTime - prev.timestamp;

            if (timeBetween == 0) {
                timeBetween = 1;
                timeSincePrev = 1;
            }

            //Return the interpolation of T0+dt in this piece
            target.position = Vector3.LerpUnclamped(prev.position, next.position, (timeSincePrev / timeBetween));
            target.rotation = Quaternion.Lerp(prev.rotation, next.rotation, (timeSincePrev / timeBetween));

            startedTime = currentTime;
            startingPosition = prev.position;
            startingRotation = prev.rotation;
        }
    }

    private bool ShouldDelay() {
        //If the list is empty, delay and reset the current piece start.
        if (interpolationQueue.Count == 0) {
            pieceStartTime = -1;
            return true;
        }

        //If the piece start time is reset and there are entries in the list,
        //set the piece to the oldest entry and delay until interpolationDelay has
        //passed since the oldest (stored in pieceStartTime).
        if (pieceStartTime < 0) {
            oldestReceivedTime = interpolationQueue.Peek().timeReceived;
            pieceStartTime = oldestReceivedTime;
        }

        return Time.time - pieceStartTime < interpolationDelay;
    }
}

```

---
Tags: networking, multiplayer, interpolation, unity-networking, lag
---


# Question
Title: Which to use for game Development? SDL_Surface or SDL_Renderer
I'm relatively new to game development compared to the pioneers in this field, and my question, as stated in the title is, Should I Be using SDL\_Surface for game development or SDL\_Renderer, I know that SDL\_Renderer is the *new*, and more *efficient* way, but i still do have a doubt...

Thanks in advance... Random Developer

# Answer
> 3 votes
`SDL_Renderer` is hardware accelerated on most systems, and falls back to software rendering when hardware rendering isn't for some reason supported. `SDL_Surface`s are always software rendered, meaning that you'll always have worse (or in some rare and odd cases, equal) performance. There's really no reason not to use `SDL_Renderer` over plain old surface blitting.

---
Tags: sdl2
---


title: Iterating in "box" formation

text:
# Question
Title: Iterating in "box" formation
I'm writing a minecraft clone in C++ and need some assisting with the chunk generation. Because I only want to load chunks that are near the player, I have to load and unload chunks based on the distance to the player.

**Of course the naive approach would be:**

```
glm::vec2 playerChunkPos = VoxelWorld::getChunkPosition(*playerPosition);
for(int x = -chunkRadius; x <= chunkRadius; x++){
    for(int y = -chunkRadius; y <= chunkRadius; y++){
        glm::vec2 chunkPos = playerChunkPos + glm::vec2(x, y);
        //Generate Chunk
    }
}

```

But the problem with this is, that it doesn't start nearest to the player. To fix that I'd like to generate in "circles", more like "boxes" around the player.

**Here is a simple illustration of what I mean:** *(The Center is the player position)*

**EDIT:** *Just saw that I skipped 1 iteration, whoops...*

How would you reach that kind of iteration or anything similliar? I couldn't get anything to work.. All coordinates are `signed` and can have any value! The center/player can also be anywhere!

# Answer
First, we need to identify the square consists 4 symmetric sides, each of them of length `2*r`.

```
1 1 1 1 2
4 x x x 2
4 x C x 2
4 x x x 2
4 3 3 3 3

```

As you can see, the sides are symmetric relative to center, that means we can can take one cell from each side in each iteration, one coordinate always fixed while the other controlled by offset. To make it easier to use for offsets, lets iterate `2*r` cells from `-r` to `<r`.

```
for(int offset = -r; offset < r; offset++)
{
   auto pos1 = glm::vec2(c.x + offset, c.y - r);//side 1
   auto pos2 = glm::vec2(c.x + r     , c.y + offset);//side 2
   auto pos3 = glm::vec2(c.x - offset, c.y + r); //side 3
   auto pos4 = glm::vec2(c.x - r     , c.y - offset); //side 4
}

```

which leaves us with following ordering(number is step of cycle in which the coordinate was produced):

```
1 x x x 1    x 2 x x x    x x 3 x x    x x x 4 x
x x x x x    x x x x 2    x x x x x    4 x x x x
x x C x x -> x x C x x -> 3 x C x 3 -> x x C x x
x x x x x    2 x x x x    x x x x x    x x x x 4
1 x x x 1    x x x 2 x    x x 3 x x    x 4 x x x

```

the only part missing now is the outer loop iterating over chosen radii.
> 5 votes

# Answer
You need to loop through between 0 and the draw distance, each time drawing one line from the square (-r, -r) to (-r, r - 1) . Each time you generate the square at that position. You can get the other lines by using the following formulas:

```
point1 = (x, y)
point2 = (y, -x)
point3 = (-x, -y)
point4 = (-y, x)

```

Generate each of these, this way you'll only need 1 loop.
> 0 votes

---
Tags: opengl, c++, minecraft-modding
---


# Question
Title: Intersecting Triangle and BoundingBox in 3D environment
I am trying to check if a triangle is intersecting a BoundingBox in a 3D space with libgdx, but I am unable to find anything that can help me with that.

I tried using a Plane but it is not precise enough and I would like to avoid using Bullet.

Is there any existing code that I can use to deal with this ?

# Answer
```
    //////////////////////////////////////////////////////
        //    use separating axis theorem to test overlap
        //    between triangle and box
        //    need to test for overlap in these directions:
        //    1) the {x,y,z}-directions (actually, since we use
        //       the AABB of the triangle
        //       we do not even need to test these)
        //    2) normal of the triangle
        //    3) crossproduct(edge from tri, {x,y,z}-directin)
        //       this gives 3x3=9 more tests

        static int TriangleVsAABB2(const glm::vec3 &bmin,
                                   const glm::vec3 &bmax,
                                   const glm::vec3 &boxcenter,
                                   const glm::vec3 &boxhalfsize,
                                   const glm::vec3 &trivert0,
                                   const glm::vec3 &trivert1,
                                   const glm::vec3 &trivert2,
                                   const glm::vec3 &normal)
        {

            // if triangle is entirely inside the bounding box, then exit

            if ((trivert0.x >= bmin.x && trivert0.x <= bmax.x) && (trivert0.y >= bmin.y && trivert0.y <= bmax.y) && (trivert0.z >= bmin.z && trivert0.z <= bmax.z))
                if ((trivert1.x >= bmin.x && trivert1.x <= bmax.x) && (trivert1.y >= bmin.y && trivert1.y <= bmax.y) && (trivert1.z >= bmin.z && trivert1.z <= bmax.z))
                    if ((trivert2.x >= bmin.x && trivert2.x <= bmax.x) && (trivert2.y >= bmin.y && trivert2.y <= bmax.y) && (trivert2.z >= bmin.z && trivert2.z <= bmax.z))
                        return INSIDE;

            // if we get here triangle maybe intersecting the cube or could be totally out

            float d,min,max;
            float p0, p1, p2;
            glm::vec3 fe,vmin,vmax;
            glm::vec3 v0,v1,v2;
            glm::vec3 e0, e1, e2;

            // center at 0,0,0

            v0 = trivert0 - boxcenter;
            v1 = trivert1 - boxcenter;
            v2 = trivert2 - boxcenter;

            // compute triangle edges

            e0 = v1 - v0;
            e1 = v2 - v1;
            e2 = v0 - v2;

            //  test the 9 tests for axis overlapping

            // axis test x01

            fe = glm::abs(e0);

            p0 = e0.z * v0.y - e0.y * v0.z;
            p2 = e0.z * v2.y - e0.y * v2.z;

            min = p2;
            max = p0;

            if (p0<p2)
            {
                min = p0;
                max = p2;
            }

            d = fe.z * boxhalfsize.y + fe.y * boxhalfsize.z;

            if (min>d || max<-d) return OUTSIDE;

            // axis test y02

            p0 = -e0.z * v0.x + e0.x * v0.z;
            p2 = -e0.z * v2.x + e0.x * v2.z;

            min = p2;
            max = p0;

            if (p0<p2) { min = p0; max = p2; }

            d = fe.z * boxhalfsize.x + fe.x * boxhalfsize.z;

            if (min>d || max<-d) return OUTSIDE;

            // axis test z12

            p1 = e0.y * v1.x - e0.x * v1.y;
            p2 = e0.y * v2.x - e0.x * v2.y;

            min = p1;
            max = p2;

            if (p2<p1)
            {
                min = p2;
                max = p1;
            }

            d = fe.y * boxhalfsize.x + fe.x * boxhalfsize.y;

            if (min>d || max<-d) return OUTSIDE;

            fe = abs(e1);

            // axis test x01

            p0 = e1.z * v0.y - e1.y * v0.z;
            p2 = e1.z * v2.y - e1.y * v2.z;

            min = p2;
            max = p0;

            if (p0<p2)
            {
                min = p0;
                max = p2;
            }

            d = fe.z * boxhalfsize.y + fe.y * boxhalfsize.z;

            if (min>d || max<-d) return OUTSIDE;

            // axis test y02

            p0 = -e1.z * v0.x + e1.x * v0.z;
            p2 = -e1.z * v2.x + e1.x * v2.z;

            min = p2;
            max = p0;

            if (p0<p2)
            {
                min = p0;
                max = p2;
            }

            d = fe.z * boxhalfsize.x + fe.x * boxhalfsize.z;

            if (min>d || max<-d) return OUTSIDE;

            // axis test z0

            p0 = e1.y * v0.x - e1.x * v0.y;
            p1 = e1.y * v1.x - e1.x * v1.y;

            min = p1;
            max = p0;

            if (p0<p1)
            {
                min = p0;
                max = p1;
            }

            d = fe.y* boxhalfsize.x + fe.x * boxhalfsize.y;

            if (min>d || max<-d) return OUTSIDE;

            fe = abs(e2);

            // axis test x02

            p0 = e2.z * v0.y - e2.y * v0.z;
            p1 = e2.z * v1.y - e2.y * v1.z;

            min = p1;
            max = p0;

            if (p0<p1)
            {
                min = p0;
                max = p1;
            }

            d = fe.z * boxhalfsize.y + fe.y * boxhalfsize.z;

            if (min>d || max<-d) return OUTSIDE;

            // axis test y01

            p0 = -e2.z * v0.x + e2.x * v0.z;
            p1 = -e2.z * v1.x + e2.x * v1.z;

            min = p1;
            max = p0;

            if (p0<p1)
            {
                min = p0;
                max = p1;
            }

            d = fe.z * boxhalfsize.x + fe.x * boxhalfsize.z;

            if (min>d || max<-d) return OUTSIDE;

            // axis test z12

            p1 = e2.y * v1.x - e2.x * v1.y;
            p2 = e2.y * v2.x - e2.x * v2.y;

            min = p1;
            max = p2;

            if (p2<p1)
            {
                min = p2;
                max = p1;
            }

            d = fe.y * boxhalfsize.x + fe.x * boxhalfsize.y;

            if (min>d || max<-d) return 0;

            //  first test overlap in the {x,y,z}-directions
            //  find min, max of the triangle each direction,
            //  and test for overlap in
            //  that direction -- this is equivalent to testing
            //  a minimal AABB around
            //  the triangle against the AABB

            // test in X-direction

            min = v0.x;
            max = v0.x;

            if (v1.x<min) min = v1.x;
            if (v1.x>max) max = v1.x;
            if (v2.x<min) min = v2.x;
            if (v2.x>max) max = v2.x;

            if (min>boxhalfsize.x || max<-boxhalfsize.x) return OUTSIDE;

            // test in Y-direction

            min = v0.y;
            max = v0.y;

            if (v1.y<min) min = v1.y;
            if (v1.y>max) max = v1.y;
            if (v2.y<min) min = v2.y;
            if (v2.y>max) max = v2.y;

            if (min>boxhalfsize.y || max<-boxhalfsize.y) return OUTSIDE;

            // test in Z-direction

            min = v0.z;
            max = v0.z;

            if (v1.z<min) min = v1.z;
            if (v1.z>max) max = v1.z;
            if (v2.z<min) min = v2.z;
            if (v2.z>max) max = v2.z;

            if (min>boxhalfsize.z || max<-boxhalfsize.z) return OUTSIDE;

            //  test if the box intersects the plane of the triangle

            // test x

            if (normal.x>0.0f)
            {
                vmin.x = -boxhalfsize.x;
                vmax.x =  boxhalfsize.x;
            }
            else
            {
                vmin.x =  boxhalfsize.x;
                vmax.x = -boxhalfsize.x;
            }

            // test y

            if (normal.y>0.0f)
            {
                vmin.y = -boxhalfsize.y;
                vmax.y =  boxhalfsize.y;
            }
            else
            {
                vmin.y =  boxhalfsize.y;
                vmax.y = -boxhalfsize.y;
            }

            // test z

            if (normal.z>0.0f)
            {
                vmin.z = -boxhalfsize.z;
                vmax.z =  boxhalfsize.z;
            }
            else
            {
                vmin.z =  boxhalfsize.z;
                vmax.z = -boxhalfsize.z;
            }

            // test max and min

            d = -(normal.x * v0.x + normal.y * v0.y + normal.z * v0.z);

            if (normal.x * vmin.x + normal.y * vmin.y + normal.z * vmin.z + d >  0.0f) return OUTSIDE;

            if (normal.x * vmax.x + normal.y * vmax.y + normal.z * vmax.z + d >= 0.0f) return INTERSECT;

            // box and triangle don't overlap

            return OUTSIDE;
        }

```
> -2 votes

---
Tags: libgdx, bounding-boxes, intersection
---


title: Debug logging in Factorio mod

text:
# Question
Title: Debug logging in Factorio mod
I'm writing a Factorio mod, and I'm trying to figure out why it doesn't work. Can I do some kind of error / debug logging somewhere? Both manual (printing variables) and simple error reporting (accessing a property that doesn't exist) would be great. I know about the `player.print` method, but I can only get it to print string literals, not objects:

```
script.on_event(defines.events.on_player_created, function(event)
    pcall(function()
        local player = game.get_player(event.player_index)
        player.print("Hi player") -- works
        player.print(player) -- does not work. Any error message would be nice
    end)
end)

```

I've also tried the log file in the application folder, and the various debug modes (F5/F6 in game), but so far haven't found anything useful.

# Answer
According to this forum post

> You can launch the game from console, so standard print function would send its output there. You can redirect that output to files.
>
> There is serpent pretty printer, which can print lua tables - syntax is `print(serpent.block(arg))`.
> 3 votes

# Answer
You can use the error() function which sends to factorio-current.log

For example:

error("Hi player")

or

error(serpent\_block(table\_name))
> 1 votes

# Answer
There is a write\_file method in LuaGameScript.

```
game.write_file("mylog.log", serpent_block(table_name)) -- normal write
game.write_file("mylog.log", serpent_block(table_name), true) -- appending

```

(http://lua-api.factorio.com/0.15.23/LuaGameScript.html#LuaGameScript.write\_file)

The file will end up in a folder called `script-output` under `%APPDATA%/Factorio`, next to your `scenarios` folder.
> 0 votes

---
Tags: modding
---


# Question
Title: How can I change or hide my process name to prevent Cheat Engine use?
I am writing a hack shield that can protect my game from Cheat Engine and similar programs. The ideas are to:

* build a hack shield that can hide the process name while the process is running.
* build a hack shield can change the process name to prevent attaching to the process from cheat engines.

I already searched Google but I couldn't find out how to do this effectively. Can I create an effective hack prevention system this way?

# Answer
Have a launcher application which creates a copy of the actual game executable with a random name and then starts that process. Make sure it deletes all the old copies on the next launch.

But what you are trying is futile. Any client-sided cheat prevention method can be circumvented. You can not protect a program from another program which runs with the same (or higher) privileges on the same system.

When the game is multiplayer, implement most game mechanics on the server where the client can't mess with it. When the game is singleplayer, just let them cheat. They are only ruining their own game experience.
> 6 votes

# Answer
You cannot. And even if you were able to they could use popular memory editors such as Cheat Engine or GameGuardian and use speedhacks to freeze one process after another until the game freezes.

I think you are better off encrypting or hiding your vital values through multiplication or actual encryption. Most casual game hackers wont figure it out.
> 0 votes

---
Tags: anti-cheat
---


title: Anti-cheat: How secure is the client?

text:
# Question
Title: Anti-cheat: How secure is the client?
Let's say, theoretically, that I'm developing a first person shooter with, of course, a map with things like walls. In the client code, the player is obviously halted upon collision with these wall objects. The server, however, only receives the player's location coordinates.

Without some sort of data encoding in the client, the player could easily read the network communication to the server and send false coordinates to the server, allowing them to go wherever they wanted.

My question is, is there a way to encode this location message to the server before it exits the client binary such that it would be extremely difficult for someone to read? Even by someone who disassembles the code to try and break the encoding? Or do all player collisions have to be detected by the server?

# Answer
> 3 votes
> The server, however, only receives the player's location coordinates.

No.

The server receives the key presses from from the client, makes sure they're valid, *then* authorizes the client to move.

The client has no say in where it can go. It should act as a dumb terminal.

Then you can add client side prediction and make your game look smooth.

> Without some sort of data encoding in the client, \[...\]

This is still a nice to have, though. Preventing players from sniffing the traffic would help avoid most hackers and trivial cheaters to create bots and the like.

> is there a way to encode this location message to the server before it exits the client binary

You also have to obfuscate the client per se. Programs such as *Cheat Engine* can sniff the information directly in the client's memory, the data does not have to "exit the client" before it can be read.

> it would be extremely difficult

That's unfortunately as far as you can get, you can't make it *impossible*. If there is enough money to be made by cheating in your game, some entities will try hard to reverse engineer everything and allow some players to take an unfair advantage.

# Answer
> 0 votes
Sadly, since the map still has to be rendered on the client, since we are nowhere near the server resources to process games server-side, there really is no way to prevent aimbotting, walling ect.

You would literally have to make the game unfair for players to fix it. Implement a good reporting system and maybe a server-sided stat analysis chron that bans people that have too high accuracy k/d ect.

---
Tags: multiplayer, anti-cheat
---


# Question
Title: What is the benefit of a sparse bindless texture array over just bindless textures?
I've seen the talks on AZDO, and they tend to suggest moving towards an architecture where you have one texture array per texture "shape". This is sparse, so you allocate loads of layers for potential future texture loads, and then commit each layer as you load a texture to it. You then make the whole thing bindless, and you can now pass a handle & layer to your shaders for texturing.

This is great, but what has it bought me above just using bindless textures? With bindless textures I seem to have to do exactly the same amount of work - in fact, a little less: I just pass in the texture handle (or sampler handle) to my shader.

So why the push for sparse bindless texture arrays?

# Answer
> 1 votes
> I just pass in the texture handle (or sampler handle) to my shader.

OK, so you pass the handle to the shader. Well... how do you do that?

Different objects will have different texture handles. Therefore, you will have to pass different textures for rendering different objects. And that means you will either:

1. Change the value of a program's uniform.
2. Change the value of memory that will be used by that program.

Either one of these represents some form of state change. If you changed a buffer object's memory, then (to avoid synchronization) you need to now change what buffer that shader uses, so that it will see the value you just wrote. So that's a `glBindBufferRange` call.

The point of using an array texture (or a small set of them) is that *all of the textures* come from that array. So when you start rendering your scene, you pass the shader that texture (probably through a UBO). Then, every object will access that one texture through the one value that you set at the beginning of the frame. You never need to update any state, whether UBO or uniform state.

What array layer a particular model uses for that data would come from that model's per-object data. Just like any other per-object data.

Now, you could send a bunch of texture handles, and let the shader pick them out of an array. That is, rather than an array texture, you have an array **of** textures. But texture handles aren't free; they're 64-bit values. An array of upwards of 1000 of them is approximately 64KB. And the minimum that OpenGL 4.5 requires is only 16KB, so there's no guarantee that implementations will even allow a UBO that big.

You could use an SSBO for them, but that (often) represents slower access times: going out to global memory rather than reading a value from shader-local memory.

The purpose of it being sparse is just to avoid committing memory that you don't need. You'd allocate a large number of layers, but only commit memory for the layers that you upload actual textures to them.

---
Tags: opengl
---


# Question
Title: Turn based game - how to deal with partial world state updates?
I'm implementing a simple "turn based" game where the player sets up a bunch of "actions" on a board and "objects" move on the board and are influences by those actions. The player is no longer involved after setting up the board and just watches the actions play out. Each "turn" of the game loop, a "move right" action will move any objects on its square one square to the right, for example.

My problem is now that each time I run the game loop, all actions are executed as follows:

```
for(auto& go: gameObjects) {
    go->update();
}

```

Each of these game objects mutates the world state in its update() method. What I'm seeing now is that when the board is updated by one object, the next one will immediately use that updated board state and perform its action "too soon".

For example: When I place three "move right" actions on the board and run the game loop, the object will be moved three spaces in one "turn" while it should actually take 3 "turns" for the object to move through all 3 of those actions.

How can I delay the board state update until all actions have had their chance to decide what to do? I'm considering two strategies:

1. Copy the board state for each turn and create a new board state as the result of a turn. This is complicated because all my views are tied to the objects on the board. If I copy the board, I'll have to re-create all views?
2. Have each action not update the world state, but only return a function which, when executed, will do the update. Once I have all the functions collected, execute them all to update the board.

Any suggestions?

# Answer
You can look into Double Buffering Pattern, which was designed specially for object updating in such way that every object has actual information about others, neither the previous nor the future one.
> 1 votes

---
Tags: c++, turn-based
---


title: Problem rendering cube using DirectX 11

text:
# Question
Title: Problem rendering cube using DirectX 11
I'm toying with DirectX 11 and am trying to render a simple cube, but I can't seem to get anything to show (except the clear color, which is a good sign I suppose...)

Everything seems to be working, every calls into D3D I make succeeds.

When I inspect my vertex buffers/index buffers/etc using VS2012, they show me the right data.

However, when I inspect the Input Assembler stage, when I should be seeing a cube, I see.. nothing. So I guess it's not a shader problem at least...

I joined a .vslog that can be opened with VS2012 and shows the different D3D calls I make and makes it possible to see the content of the different D3D objects. I imagine the problem lies in my vertex buffer/index buffer/input layout because it happens at the input assembler stage, but I just can't see the problem :(

Any idea?

Here's the .vsglog file: http://www.mediafire.com/?q3q77mlnuopj3g0

Here's the project file: http://www.mediafire.com/?sz4rc9qx31lmnw7

Here's the code without any error checking or cleanup:

```
// RenderTest.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include <fstream>

#include <d3d11.h>
#include <dxgi1_2.h>
#include <DirectXMath.h>

#pragma comment (lib, "d3d11.lib")
#pragma comment (lib, "dxgi.lib")

using namespace DirectX;

int g_Width = 800;
int g_Height = 600;

HWND g_HWND;

IDXGISwapChain*         g_pSwapChain;
ID3D11Device*           g_pDevice;
ID3D11DeviceContext*    g_pDeviceContext;
ID3D11RenderTargetView* g_pBackBuffer;

ID3D11Buffer*           g_pVertexBuffer;
ID3D11Buffer*           g_pIndexBuffer;
ID3D11Buffer*           g_pConstantBuffer;

ID3D11Texture2D*         g_pDepthStencilBuffer;
ID3D11DepthStencilState* g_pDepthStencilState;
ID3D11DepthStencilView*  g_pDepthStencilView;

ID3D11InputLayout*      g_pInputLayout;
ID3D11VertexShader*     g_pVertexShader;
ID3D11PixelShader*      g_pPixelShader;

char*                   g_pVSContent;
size_t                  g_VSSize;

char*                   g_pPSContent;
size_t                  g_PSSize;

#define HR(c)                       (void) ((!!(SUCCEEDED(c))) || \
  (1 != _CrtDbgReport(_CRT_ASSERT, __FILE__, __LINE__, NULL, #c)) || \
  (__debugbreak(), 0))

struct MatrixBuffer
{
    XMMATRIX WorldMatrix;
    XMMATRIX ViewMatrix;
    XMMATRIX ProjectionMatrix;
};

void CreateAWindow(void);
void CreateInputLayout(void);
void CreateIndexBuffer(void);
void CreateVertexBuffer(void);
void CreateConstantBuffer(void);
void CreateVertexShader(void);
void CreatePixelShader(void);
void CreateDepthStencilBuffer(void);
void LoadShadersContent(void);

int _tmain(int argc, _TCHAR* argv[])
{
    CreateAWindow();

    DXGI_SWAP_CHAIN_DESC scd = {};
    scd.BufferCount = 1;
    scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    scd.OutputWindow = g_HWND;
    scd.SampleDesc.Count = 1;
    scd.Windowed = TRUE;

    HR(D3D11CreateDeviceAndSwapChain(nullptr,
        D3D_DRIVER_TYPE_HARDWARE,
        nullptr,
        D3D11_CREATE_DEVICE_DEBUG,
        nullptr,
        0,
        D3D11_SDK_VERSION,
        &scd,
        &g_pSwapChain,
        &g_pDevice,
        nullptr,
        &g_pDeviceContext));

    ID3D11Texture2D *pBackBufferTexture;
    HR(g_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBufferTexture));
    HR(g_pDevice->CreateRenderTargetView(pBackBufferTexture, nullptr, &g_pBackBuffer));
    pBackBufferTexture->Release();

    CreateDepthStencilBuffer();

    D3D11_VIEWPORT viewport = {};
    viewport.TopLeftX = 0;
    viewport.TopLeftY = 0;
    viewport.Width = (FLOAT)g_Width;
    viewport.Height = (FLOAT)g_Height;

    g_pDeviceContext->RSSetViewports(1, &viewport);

    g_pDeviceContext->OMSetDepthStencilState(g_pDepthStencilState, 1);
    g_pDeviceContext->OMSetRenderTargets(1, &g_pBackBuffer, g_pDepthStencilView);

    CreatePixelShader();
    CreateVertexShader();

    CreateVertexBuffer();
    CreateIndexBuffer();
    CreateConstantBuffer();
    CreateInputLayout();

    g_pDeviceContext->PSSetShader(g_pPixelShader, nullptr, 0);
    g_pDeviceContext->VSSetShader(g_pVertexShader, nullptr, 0);
    g_pDeviceContext->VSSetConstantBuffers(0, 1, &g_pConstantBuffer);

    unsigned int zero = 0;
    unsigned int stride = 12;
    g_pDeviceContext->IASetVertexBuffers(0, 1, &g_pVertexBuffer, &stride, &zero);
    g_pDeviceContext->IASetIndexBuffer(g_pIndexBuffer, DXGI_FORMAT_R32_UINT, 0);
    g_pDeviceContext->IASetInputLayout(g_pInputLayout);
    g_pDeviceContext->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

    ID3D11RasterizerState * g_pRasterState;

    D3D11_RASTERIZER_DESC rasterizerState;
    rasterizerState.FillMode = D3D11_FILL_SOLID;
    rasterizerState.CullMode = D3D11_CULL_NONE;
    rasterizerState.FrontCounterClockwise = true;
    rasterizerState.DepthBias = false;
    rasterizerState.DepthBiasClamp = 0;
    rasterizerState.SlopeScaledDepthBias = 0;
    rasterizerState.DepthClipEnable = false;
    rasterizerState.ScissorEnable = false;
    rasterizerState.MultisampleEnable = false;
    rasterizerState.AntialiasedLineEnable = false;
    HR(g_pDevice->CreateRasterizerState( &rasterizerState, &g_pRasterState));
    g_pDeviceContext->RSSetState(g_pRasterState);

    MSG msg = {};
    while (msg.message != WM_QUIT)
    {
        // wait for the next message in the queue, store the result in 'msg'
        while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)> 0)
        {
            // translate keystroke messages into the right format
            TranslateMessage(&msg);
            // send the message to the WindowProc function
            DispatchMessage(&msg);
        }

        float clearColor[4] = { 0.0f, 0.2f, 0.4f, 1.0f };
        g_pDeviceContext->ClearRenderTargetView(g_pBackBuffer, clearColor);

        g_pDeviceContext->DrawIndexed(36, 0, 0);

        g_pSwapChain->Present(0, 0);
    }

    return 0;
}

LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    // sort through and find what code to run for the message given
    switch(message)
    {
        // this message is read when the window is closed
        case WM_DESTROY:
            {
                // close the application entirely
                PostQuitMessage(0);
                return 0;
            } break;
    }

    // Handle any messages the switch statement didn't
    return DefWindowProc(hWnd, message, wParam, lParam);
}

void CreateAWindow(void)
{
    WNDCLASSEX wc = {};
    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = WindowProc;
    wc.hInstance = GetModuleHandle(nullptr);
    wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)COLOR_WINDOW;
    wc.lpszClassName = _T("TestClass");

    RegisterClassEx(&wc);

    auto style = WS_OVERLAPPEDWINDOW;

    RECT windowRect = {0};
    windowRect.right = g_Width;
    windowRect.bottom = g_Height;
    AdjustWindowRect(&windowRect, style, FALSE);

    auto x = (GetSystemMetrics(SM_CXSCREEN) - g_Width) / 2;
    auto y = (GetSystemMetrics(SM_CYSCREEN) - g_Height) / 2;

    g_HWND = CreateWindowEx(0,
                _T("TestClass"),    // name of the window class
                _T("Test"),   // title of the window
                style,    // window style
                x,    // TODO: x-position of the window
                y,    // TODO: y-position of the window
                windowRect.right - windowRect.left,    // g_Width of the window
                windowRect.bottom - windowRect.top,    // g_Height of the window
                nullptr,    // we have no parent window, NULL
                nullptr,    // we aren't using menus, NULL
                GetModuleHandle(nullptr),    // application handle
                nullptr);

    ShowWindow(g_HWND, SW_SHOWDEFAULT);
}

void LoadShadersContent(void)
{
    if (g_pVSContent)
        return;

    std::ifstream isVS("SimpleVertexShader.cso", std::ios::binary);
    isVS.seekg(0, std::ios_base::end);
    g_VSSize = (size_t)isVS.tellg();
    g_pVSContent = new char[g_VSSize];
    isVS.seekg(0, std::ios_base::beg);
    isVS.read(g_pVSContent, g_VSSize);
    isVS.close();

    std::ifstream isPS("SimplePixelShader.cso", std::ios::binary);
    isPS.seekg(0, std::ios_base::end);
    g_PSSize = (size_t)isPS.tellg();
    g_pPSContent = new char[g_PSSize];
    isPS.seekg(0, std::ios_base::beg);
    isPS.read(g_pPSContent, g_PSSize);
    isPS.close();
}

void CreatePixelShader(void)
{
    LoadShadersContent();
    HR(g_pDevice->CreatePixelShader(g_pPSContent, g_PSSize, nullptr, &g_pPixelShader));
}

void CreateVertexShader(void)
{
    LoadShadersContent();
    HR(g_pDevice->CreateVertexShader(g_pVSContent, g_VSSize, nullptr, &g_pVertexShader));
}

void CreateConstantBuffer(void)
{
    MatrixBuffer constants = {};
    constants.ProjectionMatrix = XMMatrixPerspectiveFovLH(XM_PIDIV4, (float)g_Width / g_Height, 1.0f, 1000.0f);
    constants.ViewMatrix = XMMatrixTranslation(0.0f, 0.0f, -1.0f);
    constants.WorldMatrix = XMMatrixIdentity();

    D3D11_BUFFER_DESC desc = {};
    desc.ByteWidth = sizeof(MatrixBuffer);
    desc.Usage = D3D11_USAGE_DYNAMIC;
    desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;

    D3D11_SUBRESOURCE_DATA data = {};
    data.pSysMem = &constants;

    HR(g_pDevice->CreateBuffer(&desc, &data, &g_pConstantBuffer));
}

void CreateVertexBuffer(void)
{
    XMFLOAT3 vertices[8];

    //Top
    vertices[0] = XMFLOAT3(-0.5f, 1.0f, -0.5f);
    vertices[1] = XMFLOAT3(-0.5f, 1.0f, 0.5f);
    vertices[2] = XMFLOAT3(0.5f, 1.0f, 0.5f);
    vertices[3] = XMFLOAT3(0.5f, 1.0f, -0.5f);

    //Bottom
    vertices[4] = XMFLOAT3(-0.5f, 0.0f, -0.5f);
    vertices[5] = XMFLOAT3(-0.5f, 0.0f, 0.5f);
    vertices[6] = XMFLOAT3(0.5f, 0.0f, 0.5f);
    vertices[7] = XMFLOAT3(0.5f, 0.0f, -0.5f);

    // Vertex buffer
    D3D11_BUFFER_DESC desc;
    ZeroMemory(&desc, sizeof(D3D11_BUFFER_DESC));
    desc.ByteWidth = sizeof(vertices);
    desc.Usage = D3D11_USAGE_DEFAULT;
    desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;

    D3D11_SUBRESOURCE_DATA data;
    ZeroMemory(&data, sizeof(D3D11_SUBRESOURCE_DATA));
    data.pSysMem = &vertices;

    HR(g_pDevice->CreateBuffer(&desc, &data, &g_pVertexBuffer));
}

void CreateIndexBuffer(void)
{
    int indices[36];

    // Top
    indices[0] = 0; indices[1] = 1; indices[2] = 2;
    indices[3] = 0; indices[4] = 2; indices[5] = 3;

    // Bottom
    indices[6] = 4; indices[7]  = 5; indices[8]  = 6;
    indices[9] = 4; indices[10] = 6; indices[11] = 7;

    // Left
    indices[12] = 4; indices[13] = 5; indices[14] = 1;
    indices[15] = 4; indices[16] = 1; indices[17] = 0;

    // Right
    indices[18] = 6; indices[19] = 7; indices[20] = 3;
    indices[21] = 6; indices[22] = 3; indices[23] = 2;

    // Front
    indices[24] = 4; indices[25] = 0; indices[26] = 3;
    indices[27] = 4; indices[28] = 3; indices[29] = 7;

    // Back
    indices[30] = 6; indices[31] = 2; indices[32] = 1;
    indices[33] = 6; indices[34] = 1; indices[35] = 5;

    D3D11_BUFFER_DESC desc = {};
    desc.ByteWidth = sizeof(indices);
    desc.Usage = D3D11_USAGE_DEFAULT;
    desc.BindFlags = D3D11_BIND_INDEX_BUFFER;

    D3D11_SUBRESOURCE_DATA data;
    ZeroMemory(&data, sizeof(D3D11_SUBRESOURCE_DATA));
    data.pSysMem = &indices;

    HR(g_pDevice->CreateBuffer(&desc, &data, &g_pIndexBuffer));
}

void CreateInputLayout(void)
{
    LoadShadersContent();
    D3D11_INPUT_ELEMENT_DESC ied[] =
    {
        { "SV_POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT,    0, 0,  D3D11_INPUT_PER_VERTEX_DATA, 0 }
    };

    HR(g_pDevice->CreateInputLayout(ied, 1, g_pVSContent, g_VSSize, &g_pInputLayout));
}

void CreateDepthStencilBuffer(void)
{
    D3D11_TEXTURE2D_DESC descDepth;
    descDepth.Width = g_Width;
    descDepth.Height = g_Height;
    descDepth.MipLevels = 1;
    descDepth.ArraySize = 1;
    descDepth.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
    descDepth.SampleDesc.Count = 1;
    descDepth.SampleDesc.Quality = 0;
    descDepth.Usage = D3D11_USAGE_DEFAULT;
    descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL;
    descDepth.CPUAccessFlags = 0;
    descDepth.MiscFlags = 0;
    HR(g_pDevice->CreateTexture2D(&descDepth, NULL, &g_pDepthStencilBuffer));

    D3D11_DEPTH_STENCIL_DESC dsDesc;
    // Depth test parameters
    dsDesc.DepthEnable = true;
    dsDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
    dsDesc.DepthFunc = D3D11_COMPARISON_LESS;

    // Stencil test parameters
    dsDesc.StencilEnable = true;
    dsDesc.StencilReadMask = 0xFF;
    dsDesc.StencilWriteMask = 0xFF;

    // Stencil operations if pixel is front-facing
    dsDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
    dsDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
    dsDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
    dsDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

    // Stencil operations if pixel is back-facing
    dsDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
    dsDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
    dsDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
    dsDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

    // Create depth stencil state
    g_pDevice->CreateDepthStencilState(&dsDesc, &g_pDepthStencilState);

    D3D11_DEPTH_STENCIL_VIEW_DESC descDSV = {};
    descDSV.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
    descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
    descDSV.Texture2D.MipSlice = 0;
    HRESULT hr;
    HR(hr = g_pDevice->CreateDepthStencilView(g_pDepthStencilBuffer, // Depth stencil texture
                                        &descDSV, // Depth stencil desc
                                        &g_pDepthStencilView));
}

```

The Vertex Shader:

```
cbuffer MatrixBuffer
{
    matrix worldMatrix;
    matrix viewMatrix;
    matrix projectionMatrix;
};

struct VS_INPUT
{
    float4 position : SV_POSITION;
};

struct PS_INPUT
{
    float4 position : SV_POSITION;
    float4 color : COLOR;
};

PS_INPUT main(VS_INPUT input)
{
    PS_INPUT output;

    // Change the position vector to be 4 units for proper matrix calculations.
    input.position.w = 1.0f;

    // Calculate the position of the vertex against the world, view, and projection matrices.
    output.position = mul(input.position, worldMatrix);
    output.position = mul(output.position, viewMatrix);
    output.position = mul(output.position, projectionMatrix);

    // Store the input color for the pixel shader to use.
    output.color = float4(0.2f, 0.2f, 0.2f, 1.0f);

    return output;
}

```

And finally, the pixel shader:

```
struct PS_INPUT
{
    float4 position : SV_POSITION;
    float4 color : COLOR;
};

float4 main(PS_INPUT input) : SV_TARGET
{
    return input.color;
}

```

# Answer
From a quick flick through the major problem I see is in your SetVertexBuffers call:

```
g_pDeviceContext->IASetVertexBuffers(0, 1, &g_pVertexBuffer, &zero, &zero);

```

Basically you are setting the vertex buffer stride to 0. Your stride is actually 12 bytes.

```
UINT stride = 12;
g_pDeviceContext->IASetVertexBuffers(0, 1, &g_pVertexBuffer, &stride, &zero);

```

This is something the debug runtime ought to report to you if you create your device and swap chain with the correct flag:

```
HR(D3D11CreateDeviceAndSwapChain(NULL,
        D3D_DRIVER_TYPE_HARDWARE,
        NULL,
        D3D11_CREATE_DEVICE_DEBUG,
        NULL,
        0,
        D3D11_SDK_VERSION,
        &scd,
        &g_pSwapChain,
        &g_pDevice,
        NULL,
        &g_pDeviceContext));

```

Use it to save yourself loads of time tracking down bugs.

Its all worth bearing in mind that rendering a cube without a depth buffer will cause polygons to overlap each other in weird ways. You should definitely create and bind a DepthStencilView ...

**Edit:** Looking again its possible your view matrix is actually looking away from the object (I can't be 100% on that as I haven't gone through all the maths).

Try using XMMatrixLookAtLH instead.

```
constants.ViewMatrix = XMMatrixLookAtLH( XMVector( 0, 0, -50.0f ), XMVector( 0.0f, 0.0f, 0.0f ), XMVector( 0.0f, 1.0f, 0.0f ) );

```
> 4 votes

# Answer
You're not clearing your depth buffer, so every pixel gets rejected when you try to draw your cube.

In your message loop, clear the depth stencil view as such:

```
g_pDeviceContext->ClearRenderTargetView(g_pBackBuffer, clearColor);
g_pDeviceContext->ClearDepthStencilView(g_pDepthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0xFF);

```

The 1.0f indicates that you're clearing the depth buffer with the maximum value. Since you have your depth comparison test set to D3D11\_COMPARISON\_LESS, the cube's fragments will pass through unharmed.

Unfortunately you have a new problem - you'll see a gray stripe across the top of your screen instead of your cube from the proper perspective. I'm guessing your constant buffer isn't being properly referenced by your shader. Replacing the "bottom" vertices' Y coordinates with -1.0 extends the gray stripe to the bottom of the screen, which means your vertex values are passing through your vertex shader totally unmodified (clip space extends from -1.0 to 1.0 on the X and Y axes). I'd take a look at the shader but you only supplied compiled binaries. Hopefully this gives you a place to start.

On a related note, I don't think you're setting up your view matrix correctly. Unless you're taking a math shortcut, I think you're misunderstanding what the view matrix is (the inverse of your camera's transformation matrix). Replace this:

```
constants.ViewMatrix = XMMatrixTranslation(0.0f, 0.0f, -1.0f);

```

with something like this:

```
DirectX::FXMVECTOR eyePos = { 0.0f, 0.0f, -1.0f };
DirectX::FXMVECTOR focusPos = { 0.0f, 0.0f, 0.0f };
DirectX::FXMVECTOR up = { 0.0f, 1.0f, 0.0f };
constants.ViewMatrix = XMMatrixLookAtLH( eyePos, focusPos, up );

```

But since your shader isn't using the constant buffer, no changes I'm making to any of the constant buffer's values are having any effect. Intel GPA shows that your constant buffer is making it onto the GPU, so I think your shader just isn't using the data.
> 2 votes

# Answer
I know this is already answered but I think this will help some people. Try downloading Windows 8.1. To download it with Visual Studio 2015 just do Control Panel-\>Programs and Features(Add/Remove Program)-\>Right click VS2015 and select change. Then check Windows 8.1 and Windows Phone 8.0/8.1. Then retarget your project.

That worked for me, but I'm using DirectX 11.2 which is for Windows 8.1.

I'm using the tutorial from here: http://www.directxtutorial.com/
> -3 votes

---
Tags: rendering, directx11
---


# Question
Title: Object Touch/Drag Problem: Object moving to next finger
My Code is as follows:

```
 foreach (Touch touch in Input.touches) {

        switch (touch.phase) {

        case TouchPhase.Began:

            touchPosition = Camera.main.ScreenToWorldPoint (Input.mousePosition);
            offset = touchPosition - GOCenter;

            break;
        case TouchPhase.Moved:
            touchPosition = Camera.main.ScreenToWorldPoint (Input.mousePosition);

            newGOCenter = touchPosition - offset;
            newGOCenter.y = 0.0f;
            newGOCenter.z = 0.0f;
            gameObject.transform.position = newGOCenter;

            gameObject.transform.position = new Vector3 (
                Mathf.Clamp (gameObject.transform.position.x, -boundary.xMinMax, boundary.xMinMax),
                0.0f,
                0.0f
            );

            break;
        default:

            break;
        }
    }

```

What i am doing is i am moving the player left and right along x-axis by dragging in the screen.

When i drag/move the player with one finger then it works as expected.

But when i keep another finger in the screen and take out the first finger from the screen the player comes of the second finger.

I want the player to be moved from the place where it was left instead of coming to the second finger.

\[I have done\] \- disabled multiTouch but it does not worked. \- user fingerIndex

# Answer
> 1 votes
Try checking the `touch.fingerId` before moving your game object so that you can ensure you are only updating the position based on the first touch.

The reason you are seeing the behaviour that you are seeing is because you're updating the position for every single touch in the `Input.touches` array since you're continuing to iterate through the array after you have already updated the position. Checking the `fingerId` beforehand and only updating the position when it is the `fingerId` of your first touch should prevent this from occurring.

Also, I'd **highly** recommend using `touch.position` rather than `Input.mousePosition` as it is far more accurate; when more than one finger is being used `Input.mousePosition` will return the average of all touches so you won't be getting an accurate position.

---
Tags: unity
---


# Question
Title: Is UI anti-aliasing broken in Unity 5.6?
I have a project that was started in Unity 5.5. When I open it in 5.6, most 2D graphics look like they're not anti-aliased: left is 5.6, right is 5.5

What you see there are UI `Images` in a `Canvas`. The weird thing is that the red cross image looks OK, but the card with the red outline doesn't.

I've tried setting mipmaps to true, and Anti-aliasing set to 8x or 4x, with no difference. I hoped this was only in the editor, but a build shows the same jaggies.

Has some setting changed in 5.6 that I can edit so my graphics look anti-aliased again, or is this a bug?

# Answer
I've filed a bug report with Unity #898863 and they've confirmed it. So they broke it, and are  going to fix it hopefully **NOT** going to fix it. Below is an explanation given to me by Unity QA:

> Thanks for raising this issue. In unity 5.6 we made a change to how the backbuffer / msaa / hdr works. A side effect of this is that the backbuffer is never created with MSAA enabled, we go via an intermediate render texture. In the example you have sent the canvas is set to 'screen space overlay'. This means that is renders directly into the 'final' buffer (in this case the framebuffer).
>
> The normal scene camera is set to have MSAA enabled, if you change the camera mode to Screen Space - Camera and render them into the camera (last step via sorting layers), then MSAA will work as they will not be rendered direct into the backbuffer but into the intermediate render texture.
> 9 votes

# Answer
I've been playing with this, and you can still achieve smooth edges in the UI without anti-aliasing. The trick is to make sure texture filtering smooths out the sides.

Enabling mip-maps gets you half way there, but the other half of it is to make sure that sides you want smoothed are bordered by alpha transparency. The outer edge of everything you want smooth must be transparent.
> 6 votes

---
Tags: unity, 2d, antialiasing
---


# Question
Title: Is CryEngine documentation compatible with Amazon Lumberyard?
We are considering using it instead of UE4, and we're curious if the Cryengine docs could be used to help with developing in Lumberyard. I imagine they'd have diverged a bit by this point since Amazon has reportedly added "over 2000 improvements", but figured it'd be worth a shot at investigating.

Never really looked into Lumberyard until now, but I've heard that it has a huge lack of good documentation so I figured it could at least provide a much easier starting point if we could reference both.

# Answer
> 1 votes
Most of the documentation that you find on the internet can be used, but also a lot of parts of Cryengine became deprecated and shouldn't be used anymore.

One of the thing that you should get used to is the Entity System in Lumberyard, which I think is quite well done, and for this feature you can use Amazon Lumberyard's documentation which is quite well written, but is still lacking on a lot of aspects of the Engine.

This is the link of the documentation I'm talking about: https://aws.amazon.com/it/documentation/lumberyard/

Anyway I'd say that probably one of the biggest problem is the quantity of documentation that Amazon has created so far, it's surely not lacking in quality but is on quantity, but it looks like they are working a lot on this aspect as well.

---
Tags: cryengine, documentation, lumberyard-engine
---


# Question
Title: How can I see whether my sprite is .png or .jpg in the Inspector view or some place alike in Unity?
How can I see whether my sprite is `.png` or `.jpg` in the Inspector view or some place alike in Unity?

Here is an example of me trying to get the file extension using Editor:

# Answer
Is it right your question just show the extensions of sprite in Unity Editor?

That's simple.

You just change to 2 Column Layout of Project window.
> 2 votes

---
Tags: unity, editors, ide, extension
---


# Question
Title: Rotating GameObject does not rotate child
I am rotating a gameobject that has a child game object with a particle effect on it.

It's a missile with engine exhaust.

I am rotating the parent game object but the particle effect child objects do not rotate:

The missile object has this script on it:

```
void FixedUpdate () {
Vector3 dir = targetObject.position - transform.position;
dir.Normalize();

float zAngle = Mathf.Atan2( dir.y, dir.x ) * Mathf.Rad2Deg - 90;
Quaternion desiredRotation = Quaternion.Euler( 0, 0, zAngle );

transform.rotation = Quaternion.RotateTowards( transform.rotation, desiredRotation, 10.0f * Time.deltaTime );
rigidBody.AddForce( transform.up * 10.0f, ForceMode2D.Force );
}

```

Particle Effect:

Anyone see what I am doing wrong?

# Answer
> 1 votes
The answer is on the Particle, under the `Renderer`, Change `Billboard Alignment` to `Local`. Thanks to @spectre for the idea of using Local.

# Answer
> -1 votes
You are applying the rotation to the `rigidBody` component, which will apply transformation only to the object with the `rigidBody`, which the particle system does not have.
Note that the particle system will still be dragged along with the parent `gameObject` as it is a child of it, but it will not experience the force transformations. I would suggest to apply a `Transform.Rotate` to the particle system separately in the next line to match the parent rotation.

Read https://docs.unity3d.com/Manual/class-Rigidbody.html \- Parenting section.

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


# Question
Title: Why is my Canvas/RawImage not included in my Camera's RenderTexture output?
In my Unity2D game, I'm using a second camera to "screenshot" the current view. I then display this screenshot within the game. This works the first time I take a screenshot. When taking the second screenshot, I expect the first screenshot to show up in the second, creating a screenshot-within-a-screenshot effect. However, this doesn't happen - the previous screenshot doesn't show up in the next.

Here's a more visual description:

Before taking any screenshots:

After taking the first screenshot and displaying it in the bottom-left corner:

After taking the second screenshot:

Notice that this screenshot looks identical to the previous one. Here's what I expected:

It seems like my Canvas/RawImage that is displaying the screenshot isn't being captured by my second camera. Why is this?

Some additional details: my canvas is set to `Screen Space - Camera`. I'm using Unity 5.6.1f1.

# Answer
> 2 votes
**UPDATE:** Upon opening up this test project another day, this seems to be broken once again (even with my Canvas set to `World Space`). I'm suspecting this might be a bug with Unity, and I've filed a bug report. I'll update this answer once I hear back from Unity.

Previous answer:

---

Figured it out while posting, but in the spirit of Stack Exchange, I'll post my question with the solution. I just had to switch my Canvas's render mode to `World Space`:

---
Tags: unity, 2d, camera, rendertexture
---


title: Market as a single game or as a studio?

text:
# Question
Title: Market as a single game or as a studio?
I'm creating an RPG with a theme of a hero that must restore peace to a world fallen to evil forces. It serves as an educational tool.

I'm creating a promotional website for it and using other online social tools for marketing.

I only have one focus: to make this game as great as possible for people to learn. I've seen some companies that market themselves as their product name, like `DuoLingo`, and some that market as the studio, such as `Strawberry Games`.

I don't have a game studio and have simply been marketing (FB page, website URL, etc) as the game's name, `Lexicana's Destiny`.

Does it really matter which way I market it? If so, why?

# Answer
> 2 votes
If you really want to make this game stand out, then always go with a studio or company. It not only makes your life easier if you go to court for something (the name "the guy who made Lexicana's Destiny" sounds stupid), like when someone steals your assets, but it also makes future investors more willing to invest into your future projects.

# Answer
> 1 votes
Marketing as a single game :

* Easier for your players to find you
* The single game will likely be more promoted

Marketing as a studio :

* More professional
* Easier to market your other games

# Answer
> 0 votes
Going as a studio can be helpful since if you want to make a sequel or a different game series. That way people will recognize that one developer than different developers.

But, if you do NOT plan on sequels or other games, going by the name of your game will work.

---
Tags: marketing
---


# Question
Title: How to use transposition tables with MTD(f)
I'm writing an AI for a card game and after some testing I've discovered that using MTD(f) on my alpha beta algorithm - a series of zero-window searches - is faster than just using alpha-beta by itself.

The MTD(f) algorithm is described well here http://people.csail.mit.edu/plaat/mtdf.html

The problem I have is that for each pass in the MTD(f) search (for each guess) I don't reuse any of the previous positions I have stored even though the write up on the link suggests that I should (in fact clearing the table between iterations speeds up the algorithm).

My problem is that when I store a position and a value in my transposition table I also store the alpha and beta values for which it is valid. Therefore a second pass through the tree with a different guess (and therefore alpha and beta) can't possibly reuse any information. Is this what is to be expected or am I missing something fundamental here?

For instance if for alpha=3 beta=4 we come to a result of 7 (obviously a cut-off) should I store that in the table as valid for alpha=3 to beta=6? Or beta=7?

(Copied from stack overflow in hope of answers)

# Answer
> 1 votes
The reason you're storing things in the transposition table is to fetch the prior-found alpha and beta, to save yourself a new evaluation. If you're a C++ programmer, the board's ID hash is the key, and the alpha/beta are the value.

lookup\_board(hash, alpha, beta) -\> return (isset(some\_global\_assoc\_array\['hash'\]))? some\_global\_assoc\_array\['hash'\] : false;

store\_board(hash, alpha, beta) -\> some\_global\_assoc\_array\['hash'\] = { alpha, beta };

You should be storing the alpha and beta, yes, but not as part of the identifier - they're the associated data, instead.

# Answer
> 1 votes
When storing values in the transposition table, you have three possibilities:

1. alpha \< value \< beta: you have an exact value, and can store it: lb = ub = value;
2. value \<= alpha: you failed low. value is an upper limit on the true value: ub = value;
3. value \>= beta: you failed high. value is a lower limit on the true value: lb = value;

On subsequent visits *at the same depth*, you can use code along these lines to check the cache: if (entry.lb \>= beta) return entry.lb; if (entry.ub \<= alpha) return entry.ub; alpha = Math.max(alpha, entry.lb); beta = Math.min(beta, entry.ub);

I have found it best to ignore values from lower search depths, though.

---
Tags: algorithm
---


# Question
Title: Is there a way to make a game using lwjgl work on android?
I'm working on a platformer and I'd like to make an android version. Do I need to rewrite everything for android, or can I use something to make the lwjgl code work with android?

# Answer
> 1 votes
Unfortunately, I believe you're going to have to do some work to port it:

> One of LWJGL's main features is its OpenGL support. Android natively supports OpenGL ES so there's basically no need for LWJGL. As for the rest of LWJGL, it doesn't apply on the Android platform anyway - for example there is obviously no mouse to an Android device - so I don't see a direct LWJGL port ever being developed.
>
> Check out the Android reference, especially the android.opengl package, for a good starting point.

# Answer
> 0 votes
There is a port:

<sub>(image from the `android-test` repo linked below)</sub>

With LWJGL 3, there is now support for Android.

The linked repo has the setup instructions and the demo, the actual code is in the LWJGL3 repo under the Android branch.

I've been using it for a while now, and this library has a bunch of useful features that aren't just connected to OpenGLES, OpenAL, OpenVR and Vulkan, but it also has a lot of utilities for things like 3D model loading, layouts, dialogs, fonts and a lot more. Meaning the Android port of LWJGL is a considerable add-on to the current OpenGL ES support.

---
Tags: java, android, lwjgl
---


title: Saving feature in Unity5

text:
# Question
Title: Saving feature in Unity5
I'd like to know how to accomplish saving, accessing old save files, and overwriting them.

# Answer
> 0 votes
`PlayerPrefs` is a good place to start, but there are hundreds of ways to do this depending on what platforms, where you want to save, how often, etc.

https://docs.unity3d.com/ScriptReference/PlayerPrefs.html

It has limited space and a small set of data that can be saved (int, float, string), but it could be enough for a simple game.

If you need more space or more complex data structures to be saved, than you have to store them on the file system itself (or in a server if you have some backend support). Unity doesn't provide any built-in support for this.

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