# Question
Title: Output pixel to different position from pixel shader?
Is it possible to output a pixel processed by my pixel shader to a different position?

For example if SV\_POSITION of the pixel is 14,26, can I change it to 14,27?

I see there are only two possible output semantics, COLOR and DEPTH, so I am guessing the answer is not directly.

But are there alternative techniques, workarounds for achieving this?

# Answer
> 1 votes
In DirectX 11, you can write to unordered access views from pixel shaders. You can create unordered access views for textures.

But this way you have to perform some sort of synchronization to ensure that no more than one thread is attempting to write to the same location at a given time. The easiest way would be to use a RasterizerOrderedTexture2D in the shader which makes this ensurance for you transparently. But this feature may not be supported by some of the older GPU drivers.

# Answer
> 0 votes
If you use a buffer with a color depth of 16 or more bits per channel, then you can output the color such as the first 8 bits of each channel contain the actual RGB color, and you can use the rest of the bits to store the intended position of the pixel.

For example with 16 bits per channel, you have 4\*8 bits to use to store the x and y coordinates, which allows you to store positions up to 65536 on each axis.

The red channel would look something like this:

```
Position  Color
10011101|11011101

```

Then you can run a postprocesser on the texture and move everything to it's intended location.

This has the obvious drawback, that some elements with different intended positions can't occupy the same original position.

# Answer
> 0 votes
(My most sincere apologies if i am wrong in my guess below, the intention is of course only to clarify)

I think you may have misunderstood how a shader works? My guess is that you think in the wrong direction.

You do NOT "re-position" a pixel, into a different location on the target (may it be a surface or the monitor) while you process it. You (kind of) do NOT process in a forward direction in a shader. You can NOT "place a pixel" just anywhere you like.

Instead, the system (hardware + driver + 3Dware) determines which pixels are visible and thus **need to be painted**. You can indeed affect this in advance, as a whole, eg. by painting only a part of the screen. But once the draw command is executed, the system concludes which pixels are involved and need to be painted, and this is non-negotiable and automatic.

Instead, your job is to **provide content** for that (and the other) pixels. The system kind of asks you (= the shader, your code) to "give something". This is where the re-positioning happens, as you can of course "give" anything you like. You can fetch it from anywhere, calculate it with code, or say clip() in which case you "give" nothing and the target pixel is left unpainted.

Example: You have a 8192x8192 px map that you what to paint onto a full 1920x1080 screen, with a 1:1px scale, by using a shader. Apparently, only part of the huge map fits the screen.

You do NOT first focus on a/any pixel, say for example (100,100), in the big 8192x8192 map and decide that you "throw it" into pixel (500,500) on screen. And you can not then focus on pixel (101,101) and decide that you "throw it" into say pixel (211,972) on screen.

Instead, the system will walk through all screen (target) pixels **in parallel** (in an order that you do not know in advance and will never know). All pixels are independent and unaware of each other - each pixel thinks it is the only pixel in the world but all pixels will be taken care of. The system WILL invoke your shader for each pixel.

At some point, the system will process screen pixel (500,500) - this is guaranteed and happens without your own active effort. Your job is now to **provide content** for this pixel. So in the shader, you say "yes, lets grab pixel (100,100) from the big source map this time". Equally well you could say "yes, lets grab pixel (99,100) from the big source map this time". And next frame (98, 100), then (97,100) etc., in fact that way producing a scrolling output for the user who views the result.

In the end, you will achieve exactly what you are considering with your question. You just need to think from the final result **backwards** into the source pixel - and not think from the source pixel **forwards** into the final result pixel.

# Answer
> 0 votes
You're thinking about it in the intuitive natural way, which unfortunately isn't actually the best way. It's much easier if you think about it a little backwards. Don't move the output of a pixel, move its input instead. Essentially, moving the vector that says where your pixel is is equivalent to moving the pixel itself.

To illustrate what I mean, your SV\_POSITION says (14, 26), but you want it to render at (14, 27) right? Rather than rendering it at (14, 26) and then moving the pixel, just take your SV\_POSITION and subtract one from it, so that (14, 27) thinks it's actually (14, 26) and renders everything at (14, 26) right where you need it to be.

---
Tags: hlsl, fragment-shader
---


# Question
Title: Function called only once from another script
I have a spawn function which is

```
public void spawnobstacle(){
    number_of_spawn = Random.Range (1, 3);
        if (number_of_spawn > 0) {
            spawnposition = Random.Range (0, 3);
            if (spawnposition == 0 && !rightisoccupied) {
                Instantiate (obstacle, rightpos, Quaternion.identity);
                rightisoccupied = true;
            }
            if (spawnposition == 1 && !midisoccupied) {
                Instantiate (obstacle, midpos, Quaternion.identity);
                midisoccupied = true;
            }
                if (spawnposition == 2 && !leftisoccupied) {
                Instantiate (obstacle, leftpos, Quaternion.identity);
                leftisoccupied = true;
            }
            number_of_spawn -= 1;
    }

```

and I have another script in the obstacle GameObject that if the obstacle is triggered by it, it destroys the obstacle and spawn some other obstacle.

The content of the script is this:

```
public class DestroyObstacle : MonoBehaviour {
public GameObject world;
void OnTriggerEnter2D (Collider2D thecollision){
    if (thecollision.gameObject.tag == "destroypoint1") {

        world.GetComponent<Spawn> ().spawnobstacle ();
        Destroy (this.gameObject);
    }
}
void Start(){
    world = GameObject.Find ("World");
    }
void Update() {

}

```

Why is the function only calls one obstacle every time and the function is called only once, 2 times max (not every time the obstacle is destroyed)?

# Answer
> 0 votes
You don't seem to clear the `rightisoccupied` `midisoccupied` and `leftisoccupied` flags when an obstacle is destroyed.

One option would be to add a variable to the spawned obstacles which state the lane they are on. Have the `DestroyObstacle` check that variable and clear the corresponding flag in `Spawn` before calling `.spawnobstacle ()`.

Another option would be to replace these flags with a reference to the actual game object. When you destroy a game object, it will be equal to `null`. So when you `Destroy` the rightObstacle and then call `.spawnobstacle()`, `rightObstacle == null` will be true.

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


# Question
Title: How do I render to a texture loaded from a PNG file using SDL2
I'm trying to create a simple 2D game using C++ and SDL2.

I thought it would be a good idea to go for a "layered" rendering model.

I would render my background first, then the world, then the constructs (things like building etc.), then the objects (NPC's etc.) and lastly a toggle-able debug-overlay.

Right now I'm just trying to render a background and a debug overlay but I've hit a wall.

I can't seem to be able to render my debug-overlay on top of my background.

I've set blending mode to SDL\_BLENDMODE\_NONE for the background and SDL\_BLENDMODE\_BLEND for the debug overlay.

The problem is however, that my background is loaded from a PNG file, but when calling SDL\_CreateTextureFromSurface() the texture access is set to SDL\_TEXTURE\_ACCESS\_STATIC. (Which can't be used as a target if I understand correctly).

My question is: How can I circumvent this issue? How can I make my background "drawable"?

EDIT: Grammar

# Answer
You don't actually want to render your debug UI to the background texture. You want to render the background texture to the screen, and then your debug UI to the screen.

So the code flow should look something like this:

```
SDL_RenderClear(renderer);

// Render background
SDL_RenderCopy(renderer, backgroundTexture, NULL, NULL);

// Render debug info.
RenderText(GetCurrentFPS(), 0, 0); // Or whatever your text rendering might look like.
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
for (BoundingBox* box : GetAllBoundingBoxes()) {
    SDL_RenderDrawRect(renderer, box->GetRect());
}

SDL_RenderPresent(renderer);

```
> 1 votes

---
Tags: c++, rendering, sdl2
---


# Question
Title: How to bend a 2D rectangle in an animation?
It is something done often in 3D but I've never heard of it in 2D. I want to bend a 2D rectangle looking a bit like that:

I've seen people adding lots of vertex around knees and elbows of 3D models for that purpose. Should I make my 2D rectangle be lots of smaller triangles in order to bend it, just like in 3D? I feel like it's overkill just to bend a rectangle. Is there a better way to do this? I'm using LibGDX. I would like the rectangle to stay *proportioned*. Is there common algorithms to do that?

# Answer
> 6 votes
# Background info on rendering textured polygons using the GPU

The approach you mention, adding extra vertices is the correct one. In 3D animation, it's the vertices of a mesh that are adjusted during animation. Your GPU simply takes these vertices and their connectivity (e.g. to interpret the verts as a list of triangles) to render textured polygons on screen. The GPU creates these triangles by linearly connecting the vertices.

In your example image, the rectangle can be drawn just fine using two triangles. The bended rectangle cannot be drawn using only 2 triangles, as there is no way to tell the GPU you want to connect the vertices using the curved lines you've drawn.

The reason your GPU can't draw curved triangles is optimization. GPU's are super optimized at one specific task: rasterizing triangles, at the cost of flexibility. If you were to render your rectangle using the CPU, you could implement your of rasterization algorithm that does allow polygons with curved lines. Here, you would use the CPU. CPU's aren't very optimized at anything, but they have a ton of flexiblity (aka. they can run a way bigger variety of operations).

# A similar problem: rendering curves and smooth surfaces

There actually exists a similar problem to the one you ask: rendering surfaces/curves not specified as a set of polygons. There are many ways to describe surfaces/curves that don't rely on polygons, e.g. implicit mathematical equations (e.g.: r^2 = (x - x1)^2 + (y - y1)^2, https://en.wikipedia.org/wiki/Implicit\_surface), NURBS surfaces (https://en.wikipedia.org/wiki/Non-uniform\_rational\_B-spline), Bezier curves (https://en.wikipedia.org/wiki/B%C3%A9zier\_curve), parametrized primitives (e.g. Circle(x=10,y=12,r=4)), ...

Let's say you want to render one of the above using the GPU's rasterization capabilities. The approach most graphics software uses is to simple create a polygonal mesh that approaches the "smooth" surface closely enough (https://en.wikipedia.org/wiki/Subdivision\_surface). This "close enough" criterion can even depend on the distance to the camera, which is where "lodding" comes into play (https://en.wikipedia.org/wiki/Level\_of\_detail). So in case of a curve, you just render a lot of tiny straight line segments to get it to look smooth. In case of a a surface, you draw a lot of tiny triangles to make the surface look smooth.

# Solution to your problem

So to get back to your problem, you probably want to add extra vertices indeed, so that the bended rectangle can be approached by a polygonal mesh. If you look at the image, you'll see it only has straight lines. By adding enough straight lines, it'll start to look like a smooth curve.

As you mentioned, it is for this exact same reason that artists add extra vertices to the knees of a character. It gives the knee some extra polygons to approach the smooth surface of a bended knee.

I added a lot of background info here, so you can understand the reason why the extra vertices are necessary. The big clue of the story is this: **rendering using GPU rasterization is based on polygons with straight edges!** It is exactly this inflexibility that makes GPU's lightning fast. GPU's can't really do a lot, but boy are they good at drawing polygons with straight edges.

# How others do it

A popular piece of software for animating 2D graphics with the bending behavior you described is Spine (http://esotericsoftware.com/). You can check out their video's to get a feel of how adding extra vertices works!

# Alternatives

As you'll understand from the above, the only away to avoid the extra polygons is to use a different method of rendering, e.g. raytracing using implicit equations for shapes. Or, you could develop your own algorithm. The downside, you won't be able to use the GPU's blazing fast rendering speed, because it known only one method: rasterization of polygons.

---
Tags: 2d, libgdx, graphics
---


# Question
Title: 2D Change Velocity Based on Distance XY While Moving Parabolic Arc
What I'm trying to achieve is that the entity moves in a parabolic curve, and no this has nothing to do with gravity before you ask.

I give the entity a target position which it should move to, but not in a straight line, it should move to that target position in a parabolic curve.

I'll Show an example below:

It doesn't matter where the start or target it, I just want the calculate the proper velocity separately for x and y. so that the x, y of the entity arrive at the target position at the exact same time. My entity can move in 8 directions based on targetXY.

What I do is calculate the middle point for each x ,y I separately between startPositionXY and targetPositionXY. I increase the velocity until the middle point and after the middle point I decrease it. But it the Entity x and y do not reach the intented target at the same time instead one either x or y always gets there before the other depending on which direction it's moving in.

Here is what I have so far.

```
    public function update():void {

        if(!_hasInitialized){throw new ReferenceError("Fish.initialize must be called once before calling update");}

        determineDirection();
        determineVelocityBreakpoint();
        determineDistance();
        determineVelocity();
        move();
    }

    private function move():void {
        switch(this._direction){
            case "left":
                if(getX() > this.pos_target_x){
                    this. x -= velocity_x;
                }else{
                    setX(this.pos_target_x);
                }
                break;

            case "right":
                if(getX() < this.pos_target_x){
                    this.x += velocity_x;
                }else{
                    setX(this.pos_target_x);
                }
                break;

            case "up":
                if(getY() > this.pos_target_y){
                    this.y -= velocity_y;
                }else{
                    setY(this.pos_target_y);
                }
                break;

            case "down":
                if(getY() < this.pos_target_y){
                    this.y += velocity_y;
                }else{
                    setY(this.pos_target_y);
                }
                break;

            case "left-up":
                if(getX() > this.pos_target_x){
                    this.x -= velocity_x;
                }else{
                    setX(this.pos_target_x);
                }
                if(getY() > this.pos_target_y){
                    this.y -= velocity_y;
                }else{
                    setY(this.pos_target_y);
                }
                break;

            case "left-down":
                if(getX() > this.pos_target_x){
                    this.x -= velocity_x;
                }else{
                    setX(this.pos_target_x);
                }
                if(getY() < this.pos_target_y){
                    this.y += velocity_y;
                }else{
                    setY(this.pos_target_y);
                }
                break;

            case "right-up":
                if(getX() < this.pos_target_x){
                    this.x += velocity_x;
                }else{
                    setX(this.pos_target_x);
                }
                if(getY() > this.pos_target_y){
                    this.y -= velocity_y;
                }else{
                    setY(this.pos_target_y);
                }
                break;

            case "right-down":
                if(getX() < this.pos_target_x){
                    this.x += velocity_x;
                }else{
                    setX(this.pos_target_x);
                }
                if(getY() < this.pos_target_y){
                    this.y += velocity_y;
                }else{
                    setY(this.pos_target_y);
                }
                break;

            case "idle":
                break;
        }
    }

    /**
     * Determines the Direction
     */
    private function determineDirection():void {
        if( getX() as int == pos_target_x && getY() as int == pos_target_y){//Idle
            this._direction = "idle";
        }else{//No Idle
            if( getX() != pos_target_x && getY() == pos_target_y ){//Linear X

                if(getX() < pos_target_x){//right
                    this._direction = "right";
                }else if(getX() > pos_target_x){//left
                    this._direction = "left";
                }

            }else if( getX() == pos_target_x && getY() != pos_target_y ){//Linear Y

                if(getY() < pos_target_y){//down
                    this._direction = "down";
                }else if(getY() > pos_target_y){//up
                    this._direction = "up";
                }

            }else if(getX() != pos_target_x && getY() != pos_target_y ){//Diagonal

                if(getX() < pos_target_x && getY() < pos_target_y){//Right Down
                    this._direction = "right-down";
                }else if(getX() > pos_target_x && getY() > pos_target_y){//Left Up
                    this._direction = "left-up";
                }else if(getX() > pos_target_x && getY() < pos_target_y){//Left Down
                    this._direction = "left-down";
                }else if(getX() < pos_target_x && getY() > pos_target_y){//Right Up
                    this._direction = "right-up";
                }
            }
        }
    }

    /**
     * Determines when the velocity should be decreased.
     */
    private function determineVelocityBreakpoint():void {

        _mPointX = (this.pos_old_x + this.pos_target_x) / 2;
        _mPointY = (this.pos_old_y + this.pos_target_y) / 2;

    }

    private function determineDistance():void {
        //Distance for x, y combined
        this.distance_point = Math.sqrt((getX() - this.pos_target_x) *  (getX() - this.pos_target_x) +
            (getY() - this.pos_target_y) *  (getY() - this.pos_target_y))

        this.distance_x = Math.sqrt((getX() - this.pos_target_x) *  (getX() - this.pos_target_x));
        this.distance_y = Math.sqrt((getY() - this.pos_target_y) *  (getY() - this.pos_target_y));
    }

    /**
     * Increases and decreased the velocity.
     */
    private function determineVelocity():void {
        switch(this._direction){
            case "left":
                if(getX() <= this._mPointX){
                    if(this.velocity_x > this.velocity_min){
                        this.velocity_x -= this.velocity_inc;
                    }
                }else{
                    if(velocity_x < velocity_max){
                        this.velocity_x += this.velocity_inc;
                    }
                }
                break;

            case "right":
                if(getX() >= this._mPointX){
                    if(this.velocity_x > this.velocity_min){
                        this.velocity_x -= this.velocity_inc;
                    }
                }else{
                    if(velocity_x < velocity_max){
                        this.velocity_x += this.velocity_inc;
                    }
                }
                break;

            case "up":
                if(getY() <= this._mPointY){
                    if(this.velocity_y > this.velocity_min){
                        this.velocity_y -= this.velocity_inc;
                    }
                }else{
                    if(velocity_y < velocity_max){
                        this.velocity_y += this.velocity_inc;
                    }
                }
                break;

            case "down":
                if(getY() >= this._mPointY){
                    if(this.velocity_y > this.velocity_min){
                        this.velocity_y -= this.velocity_inc;
                    }
                }else{
                    if(velocity_y < velocity_max){
                        this.velocity_y += this.velocity_inc;
                    }
                }
                break;

            case "left-up":
                if(getX() <= this._mPointX){
                    if(this.velocity_x > this.velocity_min){
                        this.velocity_x -= this.velocity_inc;
                    }
                }else{
                    if(velocity_x < velocity_max){
                        this.velocity_x += this.velocity_inc;
                    }
                }
                if(getY() <= this._mPointY){
                    if(this.velocity_y > this.velocity_min){
                        this.velocity_y -= this.velocity_inc;
                    }
                }else{
                    if(velocity_y < velocity_max){
                        this.velocity_y += this.velocity_inc;
                    }
                }
                break;

            case "left-down":
                if(getX() <= this._mPointX){
                    if(this.velocity_x > this.velocity_min){
                        this.velocity_x -= this.velocity_inc;
                    }
                }else{
                    if(velocity_x < velocity_max){
                        this.velocity_x += this.velocity_inc;
                    }
                }
                if(getY() >= this._mPointY){
                    if(this.velocity_y > this.velocity_min){
                        this.velocity_y -= this.velocity_inc;
                    }
                }else{
                    if(velocity_y < velocity_max){
                        this.velocity_y += this.velocity_inc;
                    }
                }

                break;

            case "right-up":
                if(getX() >= this._mPointX){
                    if(this.velocity_x > this.velocity_min){
                        this.velocity_x -= this.velocity_inc;
                    }
                }else{
                    if(velocity_x < velocity_max){
                        this.velocity_x += this.velocity_inc;
                    }
                }
                if(getY() <= this._mPointY){
                    if(this.velocity_y > this.velocity_min){
                        this.velocity_y -= this.velocity_inc;
                    }
                }else{
                    if(velocity_y < velocity_max){
                        this.velocity_y += this.velocity_inc;
                    }
                }
                break;

            case "right-down":
                if(getX() >= this._mPointX){
                    if(this.velocity_x > this.velocity_min){
                        this.velocity_x -= this.velocity_inc;
                    }
                }else{
                    if(velocity_x < velocity_max){
                        this.velocity_x += this.velocity_inc;
                    }
                }
                if(getY() >= this._mPointY){
                    if(this.velocity_y > this.velocity_min){
                        this.velocity_y -= this.velocity_inc;
                    }
                }else{
                    if(velocity_y < velocity_max){
                        this.velocity_y += this.velocity_inc;
                    }
                }
                break;

            case "idle":
                break;
        }
    }

    /**
     * Set the target position and start position
     */
    public function setTargetPosition(target_x:int, target_y:int):void {
        this.pos_target_x = target_x;
        this.pos_target_y = target_y;
        this.pos_old_x = getX();
        this.pos_old_y = getY();
    }

```

# Answer
# Background info: line drawing algorithms

A similar problem to yours is the line drawing problem, i.e. how to draw a "smooth" line on a raster display (a display with discrete pixels). A famous solution is Bresenham's line algorithm (https://en.wikipedia.org/wiki/Bresenham%27s\_line\_algorithm).

Its core idea is very simple. Let's start with only lines at an angle between 0 and 45 degrees. In this case, if we draw our line pixel by pixel, we have two options:

* we draw the next pixel to the east of the previous pixel (E)
* we draw the next pixel to the north-east of the previous pixel (NE)

The algorithm simply evaluates the explicit equation of the line in each step, and keeps track of the error (how far the previously drawn pixel's center is off the actual line y-position). If the error is bigger than half a pixel, its time to make a N-E move. If not, we just make an E move.

Lines of degrees over 45 degrees or below 0 degrees are simply handled by solving the base algorithm and mirroring the coordinates (x -\> -x and/or y -\> -y) and/or swapping them (x = y).

# Background info: curve drawing algorithms

To rasterize a curve different from a straight line, you simply substitute the line equation for a different one. E.g. in your case you would use the equation of a parabola: `y^2 = 4*a*x` (see Makcheese's answer). The rest remains the same: keep track of the error and make E-moves or N-E moves depending on the error magnitude.

One important different, the slope of a parabola is not constant. As Bresenham's line algorithm only works for slopes from 0 degrees to 45 degrees, you'll need to split the problem in two: from the start of the parabola to the point where the slope becomes 45 degrees, and from that point to the end of the parabola.

# Solution to your problem

I would use Bresenham's line algorithm with the equation of a parabola. You mentions your entity has 8 directions of movement, which is exactly what this algorithm does! If you would like 4 directional movement, you'd simple replace NE steps with a N and an E step in sequence.

You also mentioned wanting a specific timing. The time it takes to traverse the parabola will be determined by the amount of movements you make per unit of time (aka the speed). Assuming you want a constant x-speed, you simply wanna perform `(x_end - x_start) / desired_time_units` movements per `time_unit`.
> 1 votes

# Answer
You might benefit from knowing the equation of a parabola:

```
y^2 = 4ax,

```

where x = -a is called te directrix.

You know your current x, y, so you can easily calculate `a`, and can then calculate the required position of your object at each timestep.
> 0 votes

---
Tags: 2d, physics, mathematics, movement, actionscript-3
---


# Question
Title: How to SetActive or enable a Canvas attached to prefabs that get instantiated (tower defense style)?
I am back again after making much progress in quest for unity and c# knowledge. I have become stumped yet again by how to enable a canvas that is attached to my prefab. Here is the situation:

I am using C# on unity 5.5.0f3.

I have UI buttons that instantiate a defense based on a prefab. That prefab has a Canvas attached to it which has a health bar attached to it. Currently, the canvas is disabled so that the health bar does not show at all times. I am trying to make it appear only when I hold down a button, in this case "Z", and disappear when I release Z. My code is letting this work if I place a prefab before hand and set the GameObject reference in the editor. I want to get it to work for any object that has this canvas attached to it. This code does not work for all of the prefabs even if I take the canvas from the prefab and make it the reference.

I have tried to use an array like I have with other things that are currently working, but it does not work the same.

Here is my code:

```
public class DefenseHealthToggle : MonoBehaviour
{
public GameObject defenseHealthBars;
private bool isShowing;

void Update()
{
    if (Input.GetKeyDown(KeyCode.Z))
    {
        isShowing = !isShowing;
        defenseHealthBars.SetActive(isShowing);
    }

    if (Input.GetKeyUp(KeyCode.Z))
    {
        isShowing = false;
        defenseHealthBars.SetActive(isShowing);
    }
}
}

```

While this is a minor detail in the game, I am trying to not let any of the ideas go if it is because I could just not figure out how to do it. I think I will learn the most if I don't give up every time I hit a wall and so far it has improved my knowledge tremendously! Anyone point me in the right direction or help me with some code? Thank you for your time!

# Answer
You can leave the Canvas or object active initially and grab it using transform.find("nameofobject") in the start.

Then you can set active or inactive whenever you want. using `defenseHealthBars.SetActive(true);`

```
public class DefenseHealthToggle : MonoBehaviour
{
 private GameObject defenseHealthBars;
 private bool isShowing;

void Start(){
 defenseHealthBars = transform.Find("NameofObject").gameObject as GameObject;
 defenseHealthBars.SetActive(false);
}

 void Update()
{
    if (Input.GetKeyUp(KeyCode.Z))
    {
        ToggleHealthBars();
    }
}
void ToggleHealthBars()
{
    defenseHealthBars.SetActive(!defenseHealthBars.activeSelf);
}

```
> 1 votes

# Answer
I suggest you to automate the procedure like doing the following:

* Instead of having *defenseHealtBars* as public, make it **private**, you can use \[SerializeField\] if you want to have it visible in the editor anyways.
* Find the relevant canvas component (with *GetComponent()* or *GetComponentInChildren()*, depends where you placed the canvas object) in the `DefenseHealthToggle` script's `void Start()` method.
* Log an error if the script cannot find the object you want to control (enable/disable).

Also do not forget to type *using UnityEngine.UI;*
> 1 votes

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


title: Problem using SDL_TTF

text:
# Question
Title: Problem using SDL_TTF
I'm trying to create a 2D game, and I'm trying to use a layered drawing model.

First I draw the background, then the world, then the constructs (buildings etc.), then the objects (NPC's etc.) and lastly a debug overlay.

For this debug overlay I'm drawing the bounding boxes of all textures on screen, as well as some text, but for some reason, the text isn't visible.

I've tried and checked everything I can think of (Checked SDL\_GetError(), TTF\_GetError(), IMG\_GetError(), Check if I was using the right color, checked TTF\_WasInit(), ...) but I simply can not figure out what is going wrong.

I'll paste some of the relevant code below, if there's anything else you'd like to see, I'll add it in an edit.

Texture.hpp:

```
#ifndef GAME_TEXTURE_HPP
#define GAME_TEXTURE_HPP

#include <iomanip>
#include <iostream>
#include <string>

#include <SDL_system.h>
#include <SDL_image.h>
#include <SDL_ttf.h>

#include "../Math/Coord.hpp"
#include "../Math/Rect.hpp"
#include "../Settings/Object.hpp"

namespace Rendering
{
    class Texture : public Stringable
    {
        private:
            bool empty;

            double width;
            double height;

            SDL_Texture* sdlTexture;
            SDL_Renderer* sdlRenderer;

            void freeTexture();

        public:
            Texture();

            Texture (SDL_Renderer* renderer);

            void loadFromFile (std::string path);

            void loadFromText (std::string txt, SDL_Color color, TTF_Font* font);

            Math::Rect render (const Math::Coord& c) const;

            bool isEmpty () const;

            double getHeight() const;

            double getWidth() const;

            ~Texture();

            std::string toString () const;
    };
}

#endif //GAME_TEXTURE_HPP

```

A few extracts from Texture.cpp

```
void Texture::loadFromFile(std::string path)
    {
        this->freeTexture();

        SDL_Texture* newTexture = NULL;

        SDL_Surface* surface = IMG_Load(path.c_str());

        if (surface != NULL)
        {
            SDL_SetColorKey(surface, SDL_TRUE, SDL_MapRGB (surface->format, 0, 0xFF, 0xFF));

            newTexture = SDL_CreateTextureFromSurface(this->sdlRenderer, surface);

            if (newTexture != NULL)
            {
                this->width = surface->w;
                this->height = surface->h;
                this->empty = false;
            }
            else
            {
                std::cout << "[Texture::loadFromFile]\tCould not create texture from image" << std::endl;
            }

            SDL_FreeSurface(surface);
        }
        else
        {
            std::cout << "[Texture::loadFromFile]\tUnable to load surface from file" << std::endl;
        }

        this->sdlTexture = newTexture;
        SDL_SetTextureBlendMode(this->sdlTexture, SDL_BLENDMODE_NONE);
    }

    void Texture::loadFromText(std::string txt, SDL_Color color, TTF_Font* font)
    {
        this->freeTexture();

        SDL_Texture* newTexture;

        SDL_Surface* textSurface = TTF_RenderText_Solid(font, txt.c_str(), color);

        if (textSurface != NULL)
        {
            newTexture = SDL_CreateTextureFromSurface(this->sdlRenderer, textSurface);

            if (newTexture != NULL)
            {
                this->width = textSurface->w;
                this->height = textSurface->h;
                this->empty = false;
            }
            else
            {
                std::cout << "[Texture::loadFromText]\tAn Error occurred while creating a texture from a surface: " << TTF_GetError() << std::endl;
            }
        }
        else
        {
            std::cout << "[Texture::loadFromText]\tAn Error occurred while creating a surface from a text: " << TTF_GetError() << std::endl;
        }

        this->sdlTexture = newTexture;
        SDL_SetTextureBlendMode(this->sdlTexture, SDL_BLENDMODE_NONE);
    }

    Math::Rect Texture::render(const Math::Coord &c) const
    {
        if (!this->empty)
        {
            SDL_Rect rect {(int) c.getX(), (int) c.getY(), (int) this->width, (int) this->height};
            SDL_RenderCopy(this->sdlRenderer, this->sdlTexture, NULL, &rect);
            std::cout << "Rendering: " << this->toString() << std::endl;
            return Math::Rect(c.getX(), c.getY(), this->width, this->height);
        }
    }

```

Main render loop:

```
void GameScreen::renderLoop()
    {
        bool quit = false;
        SDL_Event e;

        Rendering::Texture backgroundTexture = Rendering::Texture (this->sdlRenderer);

        backgroundTexture.loadFromFile(Settings::Object::getInstance().get(Settings::GENERAL_SECTION_KEY).get(Settings::GENERAL_BACKGROUND_KEY));

        this->add(backgroundTexture, BACKGROUND);

        while(!quit)
        {
            while(SDL_PollEvent(&e) != 0)
            {
                switch(e.type)
                {
                    case SDL_QUIT:
                        quit = true;
                        break;

                    case SDL_KEYDOWN:
                        switch (e.key.keysym.sym)
                        {
                            case SDLK_BACKSPACE:
                                this->debugMask = !this->debugMask;
                                std::cout << "Toggled debug mask" << std::endl;
                                break;

                            default:
                                std::cout << "Unknown key pressed" << std::endl;
                                break;
                        }

                    default:
                        std::cout << "Unknown event occured" << std::endl;
                        break;
                }
            }

            SDL_SetRenderDrawColor(this->sdlRenderer, 0xFF, 0xFF, 0xFF, 0xFF);
            SDL_RenderClear(this->sdlRenderer);

            std::vector <Math::Rect> boundingBoxes = std::vector <Math::Rect> ();

            for (size_t i = 0; i < this->backgroundQueue.size(); i++)
            {
                boundingBoxes.push_back(this->backgroundQueue.at(i).render(Math::Coord (0,0)));
            }

            for (size_t i = 0; i < this->worldQueue.size(); i++)
            {
                boundingBoxes.push_back(this->worldQueue.at(i).render(Math::Coord (0,0)));
            }

            for (size_t i = 0; i < this->constructQueue.size(); i++)
            {
                boundingBoxes.push_back(this->constructQueue.at(i).render(Math::Coord (0,0)));
            }

            for (size_t i = 0; i < this->objectQueue.size(); i++)
            {
                boundingBoxes.push_back(this->objectQueue.at(i).render(Math::Coord(0, 0)));
            }

            if (this->debugMask)
            {
                Rendering::Texture debugTexture = this->generateDebugOverlay();

                if (!debugTexture.isEmpty())
                {
                    boundingBoxes.push_back(debugTexture.render(Math::Coord(0, 0)));
                }

                Settings::Section section = Settings::Object::getInstance().get(Settings::DEBUG_SECTION_KEY);

                SDL_Color boundingBoxColor = Rendering::colorFromString(section.get(Settings::DEBUG_BOUNDING_BOX_COLOR_KEY));

                SDL_SetRenderDrawColor(this->sdlRenderer, boundingBoxColor.r, boundingBoxColor.g, boundingBoxColor.b, boundingBoxColor.a);

                for (Math::Rect box : boundingBoxes)
                {
                    SDL_Rect rect = box.toSDLRect();
                    SDL_RenderDrawRect(this->sdlRenderer, &rect);
                }
            }

            SDL_RenderPresent(this->sdlRenderer);
        }

        this->quit();
    }

```

Generating Debug output (Really primitive right now, since well, it's not even working)

```
Rendering::Texture GameScreen::generateDebugOverlay() const
    {
        Settings::Section section = Settings::Object::getInstance().get(Settings::DEBUG_SECTION_KEY);
        std::string fontStr = section.get(Settings::DEBUG_FONT_KEY);
        std::string fontSizeStr = section.get(Settings::DEBUG_FONT_SIZE_KEY);
        std::string fontColorStr = section.get(Settings::DEBUG_FONT_COLOR_KEY);

        int fontSize = stoi(fontSizeStr);

        TTF_Font* font = TTF_OpenFont(fontStr.c_str(), fontSize);

        if (font != NULL)
        {
            SDL_Color debugColor = Rendering::colorFromString(fontColorStr);

            std::string debugText = "DEBUG\nFrame Cap: " + std::to_string(this->frameCap) + "FPS";

            Rendering::Texture debugTexture = Rendering::Texture(this->sdlRenderer);

            debugTexture.loadFromText(debugText, debugColor, font);

            return debugTexture;
        }
        else
        {
            std::cout << "[GameScreen::renderloop()]\tAn error occurred while trying to create a TTF font: " << TTF_GetError() << std::endl;
            return Rendering::Texture();
        }
    }

```

The Settings stuff is loaded when the program starts, the game reads all of its settings from an INI file (And this all appears to be working)

When running the main render loop the program reports that it's rendering the following textures:

```
Rendering: Texture: Empty: 0 1920x1080
Rendering: Texture: Empty: 0 176x18

```

I'm assuming the 1920x1080 is my background (which is a 1920x1080 PNG image) and the 176x18 is the debug overlay (this has a font size of 16, so 18px tall is realistic) The empty flag on a texture is used to indicate if it's been used already or not, before anything is loaded onto it, the flag is set to 1

**EDIT: Noticed for Texture::loadFromFile() I'm using SDL\_MapRGB(format, 0,0xFF,0xFF) changed the 0 for red to a 0xFF, this did not solve anything unfortunately...**

**EDIT2: I tried to run the same code, but with a different font, the reported size changed, which seems like an indicator that something is being rendered, but its not visible Here's 2 screenshots to give a better idea of what's wrong: https://i.stack.imgur.com/Irtzf.jpg**

**EDIT3: I just noticed I'm not undef-ing main, but undef-ing it now does not make any difference. As requested, the code for colorFromString:**

```
SDL_Color colorFromString (std::string colorString)
    {
        if ((colorString.at(0) == '#') && (colorString.size() == 9))
        {
            std::string redString = colorString.substr(1,2);
            std::string greenString = colorString.substr(3,2);
            std::string blueString = colorString.substr(5,2);
            std::string alphaString = colorString.substr(7,2);

            uint8_t r = (uint8_t) (stoi(redString, nullptr, 16) & 0x000000FF);
            uint8_t g = (uint8_t) (stoi(greenString, nullptr, 16) & 0x000000FF);
            uint8_t b = (uint8_t) (stoi(blueString, nullptr, 16) & 0x000000FF);
            uint8_t a = (uint8_t) (stoi(alphaString, nullptr, 16) & 0x000000FF);

            return SDL_Color {r, g, b, a};
        }
        else
        {
            std::cout << "[colorFromString()]\tInvalid color string passed to function: " + colorString << std::endl;
        }
    }

```

colorFromString is used to parse an HTML-like color string into an SDL color (Right now the config has #FF0000FF (RGBA) as the color for the bounding boxes and the debug text)

# Answer
**Solution:** To solve this issue you need to implement the assignment operator. There is no way to copy an SDL\_Texture (or at least not one that I know of) so you'll have to pass the pointer. This also means that you can not have the destructor get rid of the texture, because when the object goes out of scope (in the generateDebugOverlay() method), the texture will be deleted. Here's my implementation:

```
Texture& Texture::operator= (const Texture& texture)
    {
        if (this != &texture)
        {
            *this = Texture();

            this->empty = texture.empty;
            this->width = texture.width;
            this->height = texture.height;

            this->sdlTexture = texture.sdlTexture;
            this->sdlRenderer = texture.sdlRenderer;
        }
        else
        {
            std::cerr << "[WARNING]\tTried to assign Texture to itself!" << std::endl;
        }
    }

```
> -1 votes

---
Tags: c++, sdl2, text, ttf
---


# Question
Title: Using indices in obj files and handling normals
I have been loading obj files and using indices for handling duplicated vector positions, but I have not gotten to the point of requiring normal data to be passed to the shaders as well.

The problem I have is that obj files store the relevant normal data in the face field, and when it comes to loading a point that is used multiple times, the normal might be different for each subsequent face including a particular vertex, but I can only pass one normal per vertex.

How would people suggest getting around this issue?

I can only think of two ways, either stop using indices and that will allow me to pass unique position vector / normal pairings, or store all instances of position/normal pairs and if a new normal is required for a position, create it and index it accordingly.

# Answer
> 2 votes
First convert the obj mesh to a non-indexed mesh with vertex+normal+other attributes.

Then convert back to indexed by merging identical vertex entries.

The 2nd step can be made generic to be re-used for other mesh format loaders and indexing procedurally generated meshes.

---
Tags: normals, index-buffer
---


# Question
Title: Why is my Mario clone game sprite getting cut off when I try to change it?
In my Super Mario 3 clone, my sprite draws correctly upon instantiating the JFrame, but when I press one of the buttons I've set to jump, it gets partially cut off. Everything on the screen is a JLabel.

Here is the code in a truncated form:

```
//for all
import java.nio.file.*;
import javax.imageio.ImageIO;
import java.io.IOException;
import java.awt.image.*;
import java.net.*;
import java.awt.*;
import javax.swing.*;
import static java.lang.invoke.MethodHandles.*;
import java.awt.event.*;

//my Mario class (cut down a lot)
class Mario {
    // all numbers multiplied by 2 from OG game

    protected Direction dir;
    protected int x, y;
    protected BufferedImage sprite;

    public Mario() {

        this.x = 54;
        this.y = 808;
        dir = Direction.RIGHT;
        setSprite(MVCE.SMALLSTANDFACERIGHT);

    }

    public void moveRight() {
        if (this.dir == Direction.LEFT) {
            this.dir = Direction.RIGHT;
        } else if (this.dir == Direction.RIGHT) {
            this.x += 2;
        }
    }

    public void jump() {
        this.y -= 46;
    }

    public void setSprite(String spriteName) {
        URL spriteAtLoc = MVCE.urlGenerator(spriteName);
        this.sprite = MVCE.generateAndFilter(sprite, spriteAtLoc);
    }

    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        g2.drawImage(sprite, 0, 0, null); // DO NOT SET x and y TO ANYTHING,
                                          // this sets 0,0 to top left!!
    }

}

```

```
// my MarioRender class:
class MarioRender extends JLabel {

    protected Mario marioSprite;

    public MarioRender() {
        marioSprite = new Mario();
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        marioSprite.paint(g2);
    }

    public void moveMarioRight() {
        marioSprite.moveRight();
        setLocation(this.marioSprite.x, this.marioSprite.y);
        repaint();
    }

    public void jumpMario() {
        marioSprite.jump();
        setLocation(this.marioSprite.x, this.marioSprite.y);
        repaint();

    }

}

```

```
// direction class, solely for moving
enum Direction {
    LEFT, RIGHT
}

```

```
// my calling class, which I called MVCE where I make the frame
public class MVCE extends JFrame {

    MarioRender m = new MarioRender();
    JLabel bg;

    public MVCE() {
        bg = new JLabel();
        this.setSize(868, 915);
        this.setVisible(true);
        this.add(bg, BorderLayout.CENTER);
        bg.setLayout(null);

        bg.add(m);
        m.setBounds(m.marioSprite.x, m.marioSprite.y, m.marioSprite.sprite.getWidth(),
                m.marioSprite.sprite.getHeight());
        KeyListener kl = new MoveListener();
        this.addKeyListener(kl);
        this.setFocusable(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    public static final String SMALLSTANDFACERIGHT = "SmallStandFaceRight.bmp"; // 30
                                                                                // x
                                                                                // 32
    public static final String SMALLJUMPFACERIGHT = "SmallJumpFaceRight.bmp"; // 32
                                                                              // x
                                                                              // 32

    // generate URL
    public static URL urlGenerator(String name) {
        URL u = lookup().lookupClass().getResource(name);
        return u;
    }

    // return image with filtered color
    public static BufferedImage generateAndFilter(BufferedImage b, URL u) {

        try {
            b = ImageIO.read(u);
            int width = b.getWidth();
            int height = b.getHeight();
            int[] pixels = new int[width * height];
            b.getRGB(0, 0, width, height, pixels, 0, width);
            for (int i = 0; i < pixels.length; i++) {
                // System.out.println(pixels[i]);
                if (pixels[i] == 0xFFff00fe) {
                    pixels[i] = 0x00ff00fe;
                }
            }
            BufferedImage newSprite = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            newSprite.setRGB(0, 0, width, height, pixels, 0, width);
            b = newSprite;
        } catch (IOException e) {
            System.out.println("sprite not found");
            e.printStackTrace();
        }
        return b;
    }

    // key listener
    class MoveListener implements KeyListener {
        public void keyPressed(KeyEvent k) {

            if ((k.getKeyCode() == 39)) {
                m.marioSprite.setSprite(SMALLSTANDFACERIGHT);
                m.moveMarioRight();

            }

            if (k.getKeyCode() == 83) { // S key

                m.marioSprite.setSprite(SMALLJUMPFACERIGHT);
                m.jumpMario();
            }

        }

        public void keyReleased(KeyEvent k) {
        }

        public void keyTyped(KeyEvent k) {
        }
    }

    public static void main(String[] args) {
        MVCE m = new MVCE();
    }

}

```

# Answer
> 1 votes
Try changing the image size of SmallJumpFaceRight.bmp from 30x32 to 32x32. Most image loading libraries require the loaded image to have a size of power 2 (e.g. 2, 4, 8, ...). Height does not have to equal width.

# Answer
> 0 votes
I found it; the problem was that I needed to have this in my paintComponent() method:

```
setBounds(marioSprite.x, marioSprite.y, marioSprite.sprite.getWidth(), marioSprite.sprite.getHeight());

```

---
Tags: java, sprites, swing
---


# Question
Title: Phaser Always Fix Camera Position to Sprite
I am developing a cross-platform overhead game using Phaser.

Is there a way to always fix the position of a camera to a sprite? The following function works great, but I want the camera to always be centered on the sprite - even when the sprite is nearing the edge of the tilemap.

```
this.game.camera.follow(this);

```

The reason I would like this capability is because I am developing a mobile game, and the player sprite manages to get in the way of crucial UI elements. This could be fixed by providing a constant camera on the sprite. Areas without tiles can be filled with a black background.

Here is my problem visualized. As you can see, when nearing the edge of the tilemap, the sprite is no longer centered and it is in the way of my joystick. Instead, I would like the sprite to be centered and the camera to display a black background past the tilemap when it gets near edges.

Thank you in advance,

Christopher

# Answer
> 1 votes
Following the documentation mentioned here, the camera bounds are set to the size of the world by default. What you can do is set the `bounds` of the `world` to be a bit bigger than what your game requires. Think of this in a way that if your game was first centered at `(0,0)` being the top-left corner, then you will increase your world bounds by `(x,y)` so that everything you now draw will be positioned at `(x + sprite.x, y + sprite.y)`. This way the camera will move beyond the world and will show black (or whatever you colored your background) color.

Also, you would need to restrict player movement to a limit that it keeps within your game area (if you do not restrict it, then it would keep moving beyond the game area onto the black part and you would face the same problem that you are now).

---
Tags: camera, tiles, phaser
---


title: Applying MVC in Game Development

text:
# Question
Title: Applying MVC in Game Development
Suppose one is working on a game which has more than one component of code where the data, view, and logic is disjoint from the workings of another component of code (i.e. all games have a main menu and the game itself, with their looks, logic, and data being independent). How best should one lay an application out?

I see at least two options:

1. Top-level code creates model, view, and controller objects which then each have fields of each area of the application. For example, the model object may have a menuData field and a gameData field. Each of the view and controller would also have something similar. Additionally, the main controller would have access to the main view and main model.
2. Top-level code creates an object for each area of the code (i.e. menu and game), and then each of these has their own model, view, and controller.

Are either of these the best way to go about this? Is there a more common approach than MVC?

# Answer
Sounds like semantic noodling to me. I guess I tend more towards your option 2 in that I have lots of different model objects for different aspects of the game instead of just one monolithic model object that handles everything, but I don't keep "menu" and "game" areas strictly separate. After all, what if you want to be able to access the main menu every time the game is paused, so that the player can save/load games at any time, and then the main menu has options that affect the game?

Instead, I tend to break up my model and controller objects with little relation to each other and instead think of all the model objects as the model "layer" of the application. Unless my "layer" notion is what you meant by the model object in option 1, in which case, like I said semantic noodling.

Anyway, any controller can access any model object in the model layer, rather than only menu controller accesses menu model etc. Meanwhile the model objects are split up into areas of responsibility like missions, enemies, etc rather than menu, game, etc. The menu controller can access the mission model if the player hits "Cancel Mission" in the menu view, that sort of thing.
> 1 votes

# Answer
First, a quick review of MVC as it pertains to OOP:

* Model - objects that store and maintain *data consistency* with respect to the problem at hand, in our case simulation.
* View - objects that translate output to the user.
* Controller - objects that translate input into commands that alter the model.

In its purest form, we should be able to save a game's state using *only* the model and *a different view*. Or possibly change the type of game being played by swapping in different views and/or controllers.

Audio options, for example, could be seen two ways. On the one hand you could take it to be configuring how the view works (the audio portion of the user interface) and nothing to do with the model (the game state irrespective of user settings). Or, you could see it as configuring the model (the program state, including *user settings* and game state) and the view simply reflecting that.

My own preference is to have the model represent just the game state, because the view is supposed to be separable from the model. You could imagine changing the view to make the game work for deaf people, at which point it wouldn't make sense to incorporate audio options in the game state.

The usefulness of this modularity can be felt when swapping the controller to port a game to another platform. This often means literal controllers (mouse and keyboard for gamepad) as well as operating system input (checking whether the user alt+tabbed out of the game doesn't make sense on a console).

Finally, to address your question directly, having each layer in every component is probably going to mean that the view and controller layers too closely parallel the model, thereby making them less separable. They should be basically independent from each other, except where they must join together.
> 1 votes

# Answer
Separating model from view and controller is invaluable in one very specific aspect of game development often overlooked when not developing at scale: testing. Develop your game simulation as a model, and you can swap out a user input device controller for an automated, repeatable testing harness. This allows for incredible leaps forward in testability, allowing for automation frameworks to handle large swathes of regression testing without requiring legions of testers to replay the same levels over and over again just to find out if a systemic change has broken previously working assets.

This really comes into its own when you are suffering from a hard to reproduce problem, you can record simulation inputs and save them to allow automated tests to continually play through your game, over and over, exercising all those same parts that the user does.

It also allows you to measure metrics associated with your game - memory usage, framerate, etc. in a repeatable and methodical way. It better allows you to alter your View code, safe in the knowledge that changing the rendering timings probably won't lead to gameplay changes.
> 1 votes

---
Tags: mvc
---


title: What is wrong with my deltatime?

text:
# Question
Title: What is wrong with my deltatime?
I have this simple struct that is supposed to calculate the time difference between 2 frames:

```
struct Clock
{
public:
    Clock() {};
    ~Clock() {};

    double CalculateDifference()
    {
        previousFrame = currentFrame;
        currentFrame = SDL_GetPerformanceCounter();
        deltaTime = (double)((currentFrame - previousFrame) * 1000 / SDL_GetPerformanceFrequency());
        return deltaTime;
    }

private:
    uint64_t currentFrame = SDL_GetPerformanceCounter();
    uint64_t previousFrame = 0;
    double deltaTime = 0.0;
};

```

This is how I'm using it in my game loop:

```
DeltaTime = clock.CalculateDifference() * 0.001; // *0.001 to convert from ms to seconds because I heard deltatime should be in seconds...?

```

then:

```
velocityY -= 0.02f * m_DeltaTime;
Player.GetPosition().y += velocityY ;

```

The code above occurs every frame because I am making a simple doodle jump clone wherein the player is constantly jumping from one platform to another. I am using low level OpenGL programming for flexibility and exercise. I nearly got the game done but my timestamps seems messed up as sometimes the player jumps higher in one frame than previous frame...

Can someone please help me identify the issue with this?

Thanks!

# Answer
I take it the only issue with your timestep is that it's causing different sized jumps on each frame.

This is because your timestep is completely *variable*, the *velocity* that you're multiplying by the *time delta* is always going to be different because there's nothing to say that the time between each frame is going to be the same.

I would recommend you read some articles on **game loops**, and this article in particular on **fixing your timestep**: http://gafferongames.com/game-physics/fix-your-timestep/.

The code for finding the difference between frames *isn't* incorrect *per-se*, it does what you were trying to make it do; it's just the application of the timestep system that requires some revision.
> 1 votes

# Answer
This code is problematic:

```
Player.GetPosition().y += velocityY;

```

Adding positions and velocities does not make much sense unless the velocity is multiplied by an amount of time; it’s an indication that you need to use your delta time here:

```
Player.GetPosition().y += m_DeltaTime * velocityY;

```

However this still has the problem that `m_DeltaTime * velocityY` is not exactly the distance traveled during the frame; it would only be the case if `velocityY` had been constant.

This version is more physically accurate:

```
double prevVelocityY = velocityY;
velocityY -= 0.02f * m_DeltaTime;
Player.GetPosition().y += 0.5 * (velocityY + prevVelocityY) * m_DeltaTime;

```
> 0 votes

---
Tags: c++, physics, timestep
---


# Question
Title: Loading scene doesn't reactivate gameobjects
I have some levels and a main menu. When starting the game from the main menu (in the editor debug mode) I can select a level a load it, no problem. However, when I wish to go back to the main menu using

```
SceneManager.LoadScene(index);

```

A whole lot of my gameobjects throw exceptions like

> The gameobjects is destroyed, but you are trying to access it

and

> Missing reference exception

and so on.

However, when i start the level from the editor (and not using the main menu), I can go back to the main menu, it works as it should.

**NOTE** that I don't have any persistent gameobjects. I do have singletons, but no persistence here. Any ideas what could cause the issue?

# Answer
> 1 votes
Use DontDestroyOnLoad. It ensures that your Menu items will live beyond the point at which you load a new scene. This may allow you to work around the problem, as you probably always want the menu openable from within the game.

Better yet: Make one scene, and keep everything in there. But that can be slow to work with, depends.

# Answer
> 0 votes
With some days of reworking the whole Main Menu functionality from the ground up, I think I finally got it to work.

The issue was that I didn't structure my stuff as I should, namely I had logic on multiple objects, data on multiple objects and everything was dependent on everything. Without structure, I basically wrote logic to any script that was open, needless to say it was kind of dumb. But the main reason this crashed my game is that even if my objects are by default turned on (active), somehow after loading the main menu they remained turned off.

Now I have a persistent `gameObject` named `GameData` with a script on it named `Persistence`. It uses `DontDestroyOnLoad` and is a singleton, this is responsible for actually calling the initializers on the gameobjects.

At the first - as this main menu is sort of a small scene - I get all scene gameobjects into a collection - and only query them later on using LINQ. Also, I have no `Awake` or `Start` only any gameobjects in the scene.

Now, I also made an `abstract class` named `InitializeMe` that looks like so:

```
public abstract class InitializeMe : MonoBehaviour
{
    public int orderNumber;
    public abstract void INIT(Persistence pers);
}

```

Where the ordernumber is used in a LINQ query when getting the menu's gameobjects who has an `InitializeMe` on them.

Then I have descendants of this `InitializeMe` that obviously implement that abstract class and tell exactly what to do in their case. As They get access to `Persistence` easily (they are called from that very class) and this `Persistence` holds most of the data that is ever needed, initialization is made very easy in an order easy to predict and control.

With this and the save/load and check file integrity coming first, loading a scene was rather quick and stable.

---
Tags: unity, loading, scene, scenemanager
---


# Question
Title: How do you manage versioning across platforms in Unity?
I'm just beginning to look into versioning games in Unity and noticed that Unity seems to offer different things depending on the platform you are building for. For instance, Android and iOS seem to have their own individual properties for versioning while Desktop has no versioning functionality at all out of the box.

Since I'm working on a game that has builds for PC, Mac, Android, and iOS, I need to determine how we want to manage version numbers within our game without having to manually manage individual version for each platform. How do you solve this?

# Answer
> 2 votes
You could make a build script which sets the version number at build time. So you have some place which tells the script what the last build was, then increment by one, update this file and continue with the build. You might have to tweak it for each platform with compiler commands but it would result in virtually automatic build numbers. If you want more information about the build you could get the build script to append an Excel (or Google Excel equivalent for easy sharing) sheet with more information (build time, failure message, who built the particular version of the game, etc) you can get really intricate with this

If you use a build server this would be extremely useful as it will do this everytime and you would be able to track bugs which what build they first appeared in which might help find which source control commit caused the error.

If you do use this it will keep builds in sync so when it comes down to managing the builds later you should know what changes happened since the last build and you can go from there.

# Answer
> -2 votes
Well if your ready to write some code then just do this. Make a website with FTP

Make a txt file on a FTP account called Update with the version number in it

Before starting game download this file.

Check if it is the same as a local version of the file.

If it isn't the download game-VERSION.zip and extract in game folder and delete txt and start.

Else delete and start.

---
Tags: unity
---


# Question
Title: Why "polar angle" should be restricted to the range of [0,PI] when moving camera?
In the sample code `d3d12book-master\Chapter 6 Drawing in Direct3D\Box\BoxApp.cpp` of "Introduction to 3D Game Programming with DirectX12 : Frank D. Luna", the camera position is modified via three variables `mTheta` for the azimuthal angle, `mPhi` for the polar angle, and `mRadius`, in the mouse move event handler.

As shown in the code, there is not any restriction to `mTheta`. However, `mPhi` is restricted to \[0,PI\]; if the restriction is commented out, the image changes suddenly at the boundaries of \[0,PI\]. Could you help to comment the reasoning behind such restriction ? Is it possible to see a continuous rotation of camera across the boundaries of \[0,PI\] ? O\_O

### initialized to certain values in world space in constructor

```
    XMFLOAT4X4 mWorld = MathHelper::Identity4x4();
    XMFLOAT4X4 mView = MathHelper::Identity4x4();
    XMFLOAT4X4 mProj = MathHelper::Identity4x4();

    float mTheta = 1.5f*XM_PI;
    float mPhi = XM_PIDIV4;
    float mRadius = 5.0f;

```

### modified in mouse move

```
void BoxApp::OnMouseMove(WPARAM btnState, int x, int y)
{
    if((btnState & MK_LBUTTON) != 0)
    {
        // Make each pixel correspond to a quarter of a degree.
        float dx = XMConvertToRadians(0.25f*static_cast<float>(x - mLastMousePos.x));
        float dy = XMConvertToRadians(0.25f*static_cast<float>(y - mLastMousePos.y));

        // Update angles based on input to orbit camera around box.
        mTheta += dx;
        mPhi += dy;

        // Restrict the angle mPhi.
        mPhi = MathHelper::Clamp(mPhi, 0.1f, MathHelper::Pi - 0.1f);
    }

    mLastMousePos.x = x;
    mLastMousePos.y = y;
}

```

### used to update camera postion

```
void BoxApp::Update(const GameTimer& gt)
{
    // Convert Spherical to Cartesian coordinates.
    float x = mRadius*sinf(mPhi)*cosf(mTheta);
    float z = mRadius*sinf(mPhi)*sinf(mTheta);
    float y = mRadius*cosf(mPhi);

    // Build the view matrix.
    XMVECTOR pos = XMVectorSet(x, y, z, 1.0f);
    XMVECTOR target = XMVectorZero();
    XMVECTOR up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);

    XMMATRIX view = XMMatrixLookAtLH(pos, target, up);
    XMStoreFloat4x4(&mView, view);

    XMMATRIX world = XMLoadFloat4x4(&mWorld);
    XMMATRIX proj = XMLoadFloat4x4(&mProj);
    XMMATRIX worldViewProj = world*view*proj;

    // Update the constant buffer with the latest worldViewProj matrix.
    ObjectConstants objConstants;
    XMStoreFloat4x4(&objConstants.WorldViewProj, XMMatrixTranspose(worldViewProj));
    mObjectCB->CopyData(0, objConstants);
}

```

# Answer
It's because of the Up vector.

It points *up* and allows your camera to be 'turned' correctly. And it's always the same: you don't change the value when you change he orientation of the camera.

From what I remember, functions such as `XMMatrixLookAtLH` will "fix" the up vector: it will first create the "side" vector from up and (target - eye), then from the "side" and (target - eye) it will recreate the "up" to make a correct transformation matrix.

This makes it all simple and "fixes itself" when you don't go over pi or 0, but when you do, it's as if you were telling the camera to 'flip' direction. And when you're exactly at zero or pi, you have your 'up' vector parallel to your 'forward' vector which is not enough to form a basis (you need two, which is what you basically provide to `XMMatrixLookAtLH`).

By clamping phi between \[0, pi\], you make sure that your transformation matrix is always valid, and it provides a 'smooth' experience to your user.

---

To fix this, I'm not exactly sure how you could only use phi and theta. I can't think of the right way from the top of my head because I don't remember having had to make such a camera. A way you could explore would be to keep a "side" vector that you update at the same time you update theta, and you use this side vector, along with the (target - eye) vector, to make the 'up' vector (by using the cross product).
> 1 votes

---
Tags: 3d, camera
---


title: Fine tuning light shader mechanics

text:
# Question
Title: Fine tuning light shader mechanics
I'm currently trying to implement the lighting technique described in this article.

I've done pretty much exactly what is done in the article. My technique is the same, and my shader is the same. Here's my problem:

The lighting looks great when everything is kind of dark, but when it's not dark, the lights are far too bright.

This what it looks like when it's dark:

And here's what it looks like when it's light:

As you can probably tell, the light in the second image is far too bright. I'm looking for something about as intense as the first picture, but with the overall lighting like the second picture.

My fragment shader code is as follows: (Vertex shader is not relevant)

```
#define LOWP lowp
precision mediump float;
#else
#define LOWP
#endif
varying LOWP vec4 v_color;
varying vec2 v_texCoords;
uniform sampler2D u_texture;
uniform sampler2D u_lightmap;
uniform LOWP vec4 ambientColor;
uniform vec2 u_resolution;
void main()
{
    vec4 diffuseColor = texture2D(u_texture, v_texCoords);
    vec2 lightCoord = gl_FragCoord.xy / u_resolution.xy;
    vec4 lightColor = texture2D(u_lightmap, lightCoord);

    vec3 ambient = ambientColor.rgb * ambientColor.a;
    vec3 intensity = ambient + lightColor.rgb;
    vec3 finalColor = diffuseColor.rgb * intensity;

    gl_FragColor = v_color * vec4(finalColor, diffuseColor.a);
}

```

`ambientColor` is set to `(1, 1, 1, alpha)` or `(white, alpha)`, where the higher the alpha, the lighter it is. The dark image is `0.1f`, and light is `0.9f`.

I think the problem is with `ambient + lightColor.rgb`, but I am not sure how else I could write it and maintain the same effect for when it is dark.

# Answer
ambientColor.a could be the intensity? did u try turning that down?

I'm work with HLSL but could this work for you? play with intensity and ambientColor.a to change how intense each component is

```
varying  float intensity = 0.5;
vec3 ambient = ambientColor.rgb * ambientColor.a;
vec3 finalColor =ambient + (diffuseColor.rgb *(lightColor.rgb * intensity));

```

For my lighting I do this, its in 3d and I have a bit more to it but it may help.

```
 DiffuseAndAmbient = (Ambientcolor * CurrentMaterial.ambientpower) + (cubecolor.rgb * CurrentMaterial.cubepower) + AccumDiffuse;

 float3 OutputColor = 0;
 OutputColor += BGColor.rgb;
 OutputColor += Color.rgb * (DiffuseAndAmbient + AccumSpecular);

```
> 0 votes

# Answer
I had the exact same problem. I solved it by multiplying the alpha value of the ambient color to the lights color. Your shader should look like this:

```
#define LOWP lowp
precision mediump float;
#else
#define LOWP
#endif
varying LOWP vec4 v_color;
varying vec2 v_texCoords;
uniform sampler2D u_texture;
uniform sampler2D u_lightmap;
uniform LOWP vec4 ambientColor;
uniform vec2 u_resolution;
void main()
{
    vec4 diffuseColor = texture2D(u_texture, v_texCoords);
    vec2 lightCoord = gl_FragCoord.xy / u_resolution.xy;
    vec4 lightColor = texture2D(u_lightmap, lightCoord);

    vec3 ambient = ambientColor.rgb * ambientColor.a;
    vec3 intensity = ambient + lightColor.rgb * (1.0f - ambientColor.a);
    vec3 finalColor = diffuseColor.rgb * intensity;

    gl_FragColor = v_color * vec4(finalColor, diffuseColor.a);
}

```
> 0 votes

---
Tags: opengl, libgdx, shaders, glsl, lighting
---


# Question
Title: Getting world space vertex coordinates in Unity
I'd like to get world space coordinates for a specific mesh vertex. Transform.TransformPoint() seems to be what I need however I'm unable to get the correct position.

In the scene I have an object called "head" at Pos (0, 0, 0) Scale (0.03, 0.03, 0.03) and I'm trying to get the position of vertex id 590 in order to spawn another object at that specific location.

```
Mesh mesh = GameObject.Find ("head").GetComponent<MeshFilter>().mesh;
Vector3[] vertices = mesh.vertices;
Vector3 newPos = transform.TransformPoint (vertices [590]);
Debug.Log (newPos);

```

The value of newPos is not on the head object.

# Answer
> 1 votes
You're using the transform from the script's `GameObject` rather than the "head" `GameObject`.

```
GameObject gameObject = GameObject.Find ("head");
Mesh mesh = gameObject.GetComponent<MeshFilter>().mesh;
Vector3[] vertices = mesh.vertices;
Vector3 newPos = gameObject.transform.TransformPoint (vertices [590]);
Debug.Log (newPos);

```

Also, if your "head" object has skinned animations then just using `TransformPoint` will miss it.

You need to first create a snapshot of your skinned mesh using SkinnedMeshRenderer.BakeMesh to obtain the vertex position after skeleton animation, before passing it to `TransformPoint`.

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


# Question
Title: MMO Server with C# asynchronous sockets performance
I have developed a 2D RPG MMO client / server. The server is developed in C# with asynchronous sockets. It is a pretty simplet implementation. The server gets the client's input / coordinates and broadcasts it to the other players. It is a very alpha stadium so that I only want to test performance to know if this way to go is good.

Now I am living in Germany, I have a static public IP (accessible via the internet) and deployed my game server on a Raspberry Pi 3 (it runs in the command line with C# / Mono). The only database access (write / read) is currently made, when a client connects or disconnects (store / load coordinates).

I made a speed test right now and have the following result: Download Speed: 100840 kbit/s Upload Speed: 8973 kbit/s The Raspberry Pi is connected on a router (Fritz Box) via LAN and the port is set to bridge mode (because of the public static IP).

Everything runs fine, but I tested it with ony two clients and when one client begins to move, the second client "sees" it maybe 1 second later. The movement is "lag free". But of course, it takes a lot of time until the signal arrives to the other clients.

My question now is, will I have the same issues later, when I rent a server? I really hope that this is what I should expect, when I run my server in my home network. Maybe this question is pretty difficult to answer, because I give you no source code of the server here, but as I said, when the clients get the signal, it is "lag free". The only thing I have is kind of a "delay".

Thanks in advice.

# Answer
> 1 votes
A latency of 1000ms on a home LAN is not normal. It should usually be in the tenths of milliseconds with Wifi and even lower with Ethernet. But there might still be a problem with your home LAN. You should test the latency to the Raspberry Pi with the `ping` command line program while your server isn't running and check the latency time. You can't expect a better latency than that for your game.

When the latency on your home LAN is allright, the problem might also be that the small little Raspberry is simply not powerful enough to run your server. You might want to run it on proper hardware. If you don't want to buy a second computer, you can create a virtual machine on your development computer with a software like VirtualBox to run your server.

When you are playing on a VM running on localhost, the latency times should be pretty much unnoticeable. When the problem persists under these conditions, then the problem is definitely in your code. But without looking at it, it is impossible to guess where the problem might be. There is a million things which could be wrong. Not just on the server but also on the client-side.

# Answer
> -3 votes
I think your `accept-lag-delay` problem is in accepter loop.

**Dont Use -\> Sleep()**

**Use -\> ManualResetEvent**

When you are trying to accept a client with main loop accepter, dont use sleep or like functions. The best way to make this **ManualResetEvent**

https://msdn.microsoft.com/en-us/library/system.threading.manualresetevent(v=vs.110).aspx

I give you an example ;

```
ManualResetEvent Waiter = new ManualResetEvent(false);

void Listener()
{
    while (ListenerSocket != null)
    {
        Waiter.Reset();
        try
        {
            ListenerSocket.BeginAccept(new AsyncCallback(AcceptConnectionCallback), null);
        }
        catch (Exception ex)
        {
            Log.WriteError(ex, "void Listener()");
        }
        Waiter.WaitOne();
    }
}

void AcceptConnectionCallback(IAsyncResult iar)
{
    Socket ClientSocket = null;
    Waiter.Set();
    try
    {
        ClientSocket = ListenerSocket.EndAccept(iar);
    }
    catch (Exception ex)
    {
        Log.WriteError(ex, "void AcceptConnectionCallback(IAsyncResult iar) /1");
    }
}

```

`Sleep()` function is always a bad choice for `CPU Relax` in accepter loop. Because it can cause lag and little bit bottleneck. `ManualResetEvent` is best and optimized way to do this.

---
Tags: c#, client-server, server, lag
---


# Question
Title: Program compiled with assimp will not start
I have recently updated my game engine source code to use the visual studio(2017) vc141 toolkit.

I am using Assimp 3.1.1 for model loading. The project compiles and links, and the appropriate dll's are in the debug folder for the solution.

To begin with I was getting a missing dll error "assimp-vc140-mt.dll", which disappeared, when I redownloaded the library, and replaced the dlls/libs/includes, in my solution.

But now, when I try to run the program I get:

```
"The application was unable to start correctly (0x000007b). Click OK to close the application."

```

I've never seen this error before. Could this be related to the new toolkit?

# Answer
> 0 votes
I decided to recompile assimp from source, which gave me the proper files I needed.

---
Tags: c++, visual-studio, assimp
---


title: Gameserver Request handling

text:
# Question
Title: Gameserver Request handling
EDIT: I forgot to mention that in this implementation E stands for Entity which is just an ID, C =\> Component as data-only types and S for Systems which should implement logic

Currently i'm working on a small hobby project which is a multiplayer card game with a client/server architecture. I'm using a framework for the network part which triggers message events to services objects like this:

```
class AuthRequestMessage : public fqpnet::IMessage
{
public:
  //methods for serialization

  inline const std::string& getLoginId() const
  { return loginId_; }

  inline const std::string& getPassword() const
  { return loginId_; }

private:
  std::string loginId_;
  std::string password_;
};

//Handles authentication
class GatewayService : public fqpnet::Service
{
public:
  //registers handlers
  GatewayService()

private:
  void onAuthRequestMessage(const AuthRequestMessage* msg, ClientSession* session);
};

```

and now i'm at the point where i have to create the player entity. My first thought was to create the player entity directly in the message handler. But it feels like this code should be in a system so i created a system and added a method:

```
class PlayerSystem : public entityx::System<PlayerSystem>
{
public:
//Entity createPlayer(/*info needed...*/);

//update etc
};

```

But this feels rather bad too as the method is only used once in the handler. My third attempt was to use the builtin messaging system of the ECS:

```
struct PlayerAuthRequest
{
//id etc
};

class PlayerSystem : public entityx::System<PlayerSystem>
{
public:
void receive(const PlayerAuthRequest& request);

};

//and now just emit the event in the message handler
void GatewayService::onAuthRequestMessage(const AuthRequestMessage* msg,
ClientSession* session)
{
  //verify, load from db etc.
  eventMgr->emit<PlayerAuthRequest>(/*data*/);
}

```

Which of these approaches would be the best? Or are there alternative ones? Basicly i just want to do it in the right way to learn. Performance does not really matter to me.

# Answer
> 1 votes
> and now i'm at the point where i have to create the player entity. My first thought was to create the player entity directly in the message handler. But it feels like this code should be in a system ...

There is nothing inherently wrong with placing the code for creating a player entity somewhere else. The only difference is I would probably not refer to this as a *system* but more as a *factory* because the underlying goal is this class constructs some complicated object.

```
class PlayerFactory {
  static Player* CreatePlayer( /* whatever inputs */ );
}

```

Under the hood, the `PlayerFactory` may interact with various subsystems in your architecture in order to accomplish the task of creating a `Player` object. This may likely include interacting with the entity system to create an entity identifeir for the player and constructing any default components that a Player entity should contain.

> But this feels rather bad too as the method is only used once in the handler.

When this is the case, its often because we simply question whether the code belongs in some separate class unit or whether it should just be baked right into the business method or class that which is invoking the call.

What is important here is that code separation is a good thing. Long term, if you need to make changes to the construction of a `Player` object, where does it make more sense to locate that? The `PlayerFactory` or trying to find in all the handler spaghetti code where the actual logic happens?

Over the years, i have often preferred handlers that behave more like thin wrappers around other objects that more granularly describe and encapsulate specific behavior. Its the same mindset we approach component-based systems with, to decompose a larger problem into smaller reusable parts, allowing for flexibility and expansion downstream as needed.

> Which of these approaches would be the best? Or are there alternative ones? Basicly i just want to do it in the right way to learn.

As you can tell, your *event model* approach similarly aligns with what I've already discussed, you just use different terminology basically.

The real benefit with the event-model however is that you're allowing for other hooks to be able to respond to that authentication request, not just the player system. That can be a good thing too.

But at the end of the day, there is not one that is "best".

Personal projects in particular often are better suited to fit your own development style and preference style than try to be dictated by a style that you don't connect with well. You'll be able to make far better progress on the code and it'll make more sense to you.

At the end of the day, no design is perfect. We'll always find ways to improve code through refactor iterations and so write code that resonates with you. You can always change it later should you be compelled.

---
Tags: c++, architecture, entity-system
---


title: Unity - animations threading

text:
# Question
Title: Unity - animations threading
As one cannot play around with `threads` themselves, the user-made code that uses unity's API is executed on the main thread. I'm sure unity uses some sort of thread management on its own though.

Thing is, I wrote some basic UI animation toolkit (rotate, scale, lerp alpha, move and tie events etc) that - as being user code - runs on the main thread, taking up CPU power, even if they are not vital to be completely synchronized with the logic. (Event connected to them only start other animations).

I would like to know if Unity uses another thread for animations as well and if so, is it possible to mark this UI toolkit to be executed on that thread or - as I said - user code with unity api can be only ever executed on the main thread?

# Answer
So, you actually can use threads. You're just limited to what Unity features you can call on threads that aren't main. If you simply want to do math, and are using data that isn't locked to integral Unity classes (structs, Game objects, etc), then thread away.

A threaded approach in unity often requires a bit of work to decouple your data from Unity and then find a way to re-inject it when applicable. When I have to do such things, I often use coroutines that act as thread watchers allowing Unity to utilize threads for both asynchronous and parallel applications.

an example of how do decouple something like a transform:

```
//this contains whatever transform data your threads need to modify.
//Initialized at start / GO instantiation
struct xform{
   Vector3 pos;
   Quaternion rotation;
}

//Allows you to move data from worker thread to main thread.
IEnumerator xformUpdate(){
    while(runningCondition){
       //only grabs data if it's available
       if(readyForUpdate()){
         //transfers data from xform to Transform
         xformToTransform(args);
       } else {
         yield return null;
       }
    }
}

```

Obviously you'll need to implement your own systems to check if calculations are complete / ensure you don't run into data races.

The other big blocker is that your ability to use threads is very Unity version dependent. Unity 2017 (with experimental mono enabled) has access to tasking and parallel libraries that Unity 5.x does not. Both still have threading options available, but it's definitely worth looking into when developing your solution.
> 1 votes

---
Tags: unity, animation, multithreading
---


# Question
Title: How to detect RayHit on part of model and not entire model
I'm building a low poly role playing Hack and Slash game. When I click it renders a sprite & character moves to that location(with RayCast).

But in this case. I don't want the click to occur on side of the bridge. Clicks should only occur in green coloured part & not in the red part. How should I fix this problem?

# Answer
> 1 votes
The best way to limit clicking on a region would be to split it into two meshes and only raycast the walkable region. However, if you cannot do that, you could make it conditional on the relative position of the raycast hit.

Since the model appears to be a uniform width (no bulge or narrowing near the center along the z axis), we can imagine a box around that area. This box would exclude the bridge edges, but would include everything walkable and everything below the walkable area. Now when you raycast after a click, only move the character to the raycast hit location only if the raycast hits the bridge *and* lands in that box.

We can check this by simply comparing the z to a minimum and maximum value. For example, if the bridge is 4 units wide in total, and each side of the bridge is 0.5 units wide, and the origin of the bridge is in its center, then you can do something like the following:

```
//I'm guessing you are raycasting kind of like this:
if (Physics.Raycast(raycastStartPosition, raycastForwardDirection, out hit) {
    //Also, you are probably checking if you raycast the right thing
    if (hit.transform == target) {
        //We need to get the hit relative to the target
        var relativeHit = target.InverseTransformPoint(hit.point);
        //now just check if the hit is within our bounding box.
        //We don't need to check x or y because that is implied, since
        //we already know we hit the target.
        if (relativeHit.z < 3.5f && relativeHit.z > -3.5f) {
            //actually move the character
        }
    }
}

```

---
Tags: unity, raycasting
---


# Question
Title: How can I draw 500 million triangles with OpenGL?
I am a beginner. I have a problem with my frame rate. I am trying to see my GPUs maximum performance with using VBO. I saw that everybody says a GPU can draw 1 billion triangles (so 3 billion vertices) with VBO easily, is it right? If it is right, then why am I getting 37 FPS at only 8 million triangles (24 million vertices)?

I am not using a shader and I don't know how to use it.

My GPU is (amd radeon hd 6870).

When drawing 20k triangles, the frame rate is 6000, when drawing 8 million triangles, the frame rate is 37 and CPU usage 1%. I don't think the CPU is the bottleneck..

My code is like this:

I create in header file

```
GLuint terrainVBO;

```

I made an `init()` function:

```
glGenBuffers(1,&terrainVBO);
glBindBuffer(GL_ARRAY_BUFFER,terrainVBO);
glBufferData(GL_ARRAY_BUFFER,terrainVertices.size()*sizeof(terrainVec),&terrainVertices[0],GL_STATIC_DRAW);

```

and draw in my main loop:

```
glBindBuffer(GL_ARRAY_BUFFER,terrainVBO);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3,GL_FLOAT,3*sizeof(float),0);

glDrawArrays(GL_TRIANGLES,0,terrainVertices.size());

glDisableClientState(GL_VERTEX_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER,0);

```

Summary: How can I draw 500-600 millions triangles (1.5 billion vertices) with a good frame rate? I could only draw 8 million triangles.

# Answer
> 2 votes
I just don't know what you want to draw.
If you want to draw one object with that many triangles, you probably want to use indexed rendering. But if you want to draw that many independent triangles you should learn how to use instanced rendering because it's good for drawing many similar objects.
Maybe those two techniques can boost your performance. But as already said, it is ridiculous to draw that many triangles/vertices at once.

---
Tags: opengl, performance, vbo
---


# Question
Title: Get range of hexagon based on specified center
I have this method to get the cells inside a given N range:

```
public function getRadius($range, $center) {
    // $center[0] = X or Q
    // $center[1] = Y or R
    $cell = array();
    for ($dx = -$range; $dx <= $range; $dx++)
    {
        for ($dy = max(-$range, -$dx - $range); $dy <= min($range, -$dx + $range); $dy++)
        {

            $ddy = $dy + $center[0];
            $ddx = $dx + $center[1];

            $cell[] = array($ddx,$ddy);
        }
    }
    return $cell;
}

```

But it returns bad coordinates by adding the offset on the delta X and delta Y.

# Answer
Found a better way to do by moving a cursor N times.

```
    public function getRadius($x, $y, $range) {
        $points = array(array($x,$y));
        for($i=1;$i<=$range;$i++) {
            $curp = array($x,$y);
            for($j=1;$j<=$i;$j++) {
                $p = $this->hexagon->moveTo("N",$curp[0],$curp[1]);
                $points[] = $p;
                $curp = $p;
            }
            for($j=1;$j<=$i;$j++) {
                $p = $this->hexagon->moveTo("SE",$curp[0],$curp[1]);
                $points[] = $p;
                $curp = $p;
            }
            for($j=1;$j<=$i;$j++) {
                $p = $this->hexagon->moveTo("S",$curp[0],$curp[1]);
                $points[] = $p;
                $curp = $p;
            }
            for($j=1;$j<=$i;$j++) {
                $p = $this->hexagon->moveTo("SO",$curp[0],$curp[1]);
                $points[] = $p;
                $curp = $p;
            }
            for($j=1;$j<=$i;$j++) {
                $p = $this->hexagon->moveTo("NO",$curp[0],$curp[1]);
                $points[] = $p;
                $curp = $p;
            }
            for($j=1;$j<=$i;$j++) {
                $p = $this->hexagon->moveTo("N",$curp[0],$curp[1]);
                $points[] = $p;
                $curp = $p;
            }
            for($j=1;$j<=$i;$j++) {
                $p = $this->hexagon->moveTo("NE",$curp[0],$curp[1]);
                $points[] = $p;
                $curp = $p;
            }
        }
        return $points;
    }

```
> 2 votes

---
Tags: php, hexagonal-grid
---


# Question
Title: How reliable is glLineWidth() for parameters greater than 1?
It says in the OpenGL ES specification that `glLineWidth` is only required to support values up to 1, but how many OpenGL drivers actually keep this function at the minimum requirement?

# Answer
If the WebGL stats are anything to go by it looks like as of recently, 22% of all polled devices from WebGL stats data set only support a line width up to 1. Note that this data is skewed as OpenGL ES as exposed to the browser as WebGL is moderated by the ANGLE layer for Windows platforms for the major browsers which itself doesn't plan on supporting a line width greated than 1. It is also skewed based on the data sources and amount of devices of type that use sites that share data with WebGL Stats (See Contributing Sources)

Taken from WebGL Stats \-
> 2 votes

# Answer
Your question as posed is impossible to answer. How many drivers? Any answer will be wrong in a few months time as new devices come out.

Assuming that you're trying to draw thicker lines, you can do it manually by drawing connected quads covering the 2 endpoints of the line segments. You need to decide how you want the connections between segments to look and handle them, but it's not difficult to implement.

What I've done in the past is take the 2 end points and generate vectors perpendicular to the line segment. Extend the endpoints in both directions along the perpendicular by half the thickness of your line. You now have 4 corners for your "thick line segment." If you have another connected segment following the current one, you can calculate the new endpoints for both segments and either extend them so they meet, move the endpoints to the midpoint between them, draw another quad or circle that covers the joint, or any number of other options, depending on the look you want.
> 2 votes

---
Tags: opengl-es
---


# Question
Title: Turn-based multiplayer animate moves from last turn
I'm trying to make a 2-player turn-based strategy game, using the Google Play Games APIs

According to the documentation,

> As a match progresses, the current player can modify and store the game data on Google's servers. The other participants can then retrieve and update this data on their turn.

What this seems to be saying (sorry if I'm completely misinterpreting this; I've never played with the Play Games APIs before) is that, since each turn is just updating the game state data on the server, a round could look something like this:

1. Unit A is on Square 1, Unit B is on Square 3
2. *\[P1's turn\]* Player 1 moves Unit A to Square 2
3. *\[P1's turn\]* Player 1 kills Unit B with Unit A
4. *\[P2's turn\]* When Player 2 looks at the game, it shows Unit A on Square 2, and no Unit B

What I want is for both players to see the animation when Unit A moves, rather than Player 2 just seeing the new state and not the transition:

1. Unit A is on Square 1, Unit B is on Square 3
2. *\[P1's turn\]* Player 1 moves Unit A to Square 2
3. *\[P1's turn\]* Player 1 kills Unit B with Unit A
4. *\[P2's turn\]* When Player 2 looks at the game, it shows Unit A on Square 1 and Unit B on Square 3, then **animates** Unit A moving to Square 2 and killing Unit B

So basically each player gets a replay of the action from their opponent's turn before taking their turn.

I know it could be possible to do something like this by looking at the differences in position of a unit between turns, then animating the change; this, however, breaks down when you have something like an attack, where all you know is a unit was destroyed and wouldn't necessarily be able to infer which unit attacked and should be animated.

How would I go about implementing something like this?

# Answer
> 1 votes
In the same way you upload the new gamestate to google play's server, you can upload the previous one too.

1. Unit A is on Square 1, Unit B is on Square 3
2. \[P1's turn\] Player 1 moves Unit A to Square 2
3. \[P1's turn\] Player 1 kills Unit B with Unit A
4. \[P1\](Now you do) Upload the new game state -\> (Change for)\[P1\] Upload the initial state and the new state.
5. \[P2's turn\] Download both states. Now, using the previous and the new state you can do all the animations.

# Answer
> 0 votes
I'm far from a Google Play Games API expert, but I'm looking at this from an outsider standpoint assuming you can transmit any sort of data back and forth. As you stated, for moving you could just calculate the differences for their positions and make an animation out of that; but attacks become more complex. The way I see it, you need to tell the other side when something happens. Say, for example:

Soldier 1; who has a position of **(1, 2)** **destroys** a unit at **(3, 1)** by using a **grenade**.

Using the highlighted pieces of information, you could send to the server "(3,1) killed via grenade by (1, 2)", which might look like in pseudo code

```
int playerDeath = DEATH_GRENADE;
Vector2D killer = (1, 2);
Vector2D victim = (3, 1);

```

And you could assemble an animation out of that. Using different variants of those three variables, you could also say that x unit moved.

```
int playerMoving = player5;
Vector2D startPos = (1, 2);
Vector2D endPos = (3, 1);

```

Then, when you break it down, it's quite simple.

* At turn consists of (x) number of actions
* An action consists of one of the possible "action data structures"
* A list of actions (a turn) is sent back and forth to transmit the recent happenings

Of course, this is all a really rough outline; considering I've never used Google Play APIs, but this is how I would tackle this issue.

---
Tags: multiplayer, turn-based, google-play-services
---


title: Unity prefabs - chose what to Apply

text:
# Question
Title: Unity prefabs - chose what to Apply
I have some prefabs and if I change a value of a script on them - as to be expected - it turns **bold** meaning if I apply, that value will be input for all of my prefabs. The problem is, I wish to have a value changed *only on the instance* and then change something else and apply **only the latter**. How can I do that? So how can I specify which values are *"applyable"* and which are not?

# Answer
> 1 votes
The only way I know to do what you want is to change the value on the prefab, not on the instance.

1. Select your instance and change the value of the field you want
2. Once the value is correct, click on "Select" at the top of the inspector
3. Change the value of the prefab's field to the exact same value of your instance's
4. Select your instance, right click on the field you have changed an click on "revert to prefab"

It's quite fastidious, I concede, but the prefabs system of Unity needs to be reworked IMHO.

---
Tags: unity, assets
---