# Question
Title: Fill closed object with water - maintaining volume
I'm showing the problem in 2D, but basically given a volume V (can be approximate), where should the center point of an upwards facing plane P be for any given rotation of the object? I'm not doing a strict fluid simulation, it doesn't need to pool in isolated areas or slop around, it's just (I think) a volume preservation exercise.

To reiterate, V is known, P is what i'm trying to solve.

Do I need to voxelize the object and essentially count boxes from the lowest bounds up?

Edit: Here's the code based on Bálint's response. Note that I haven't tested it yet (you'd call the top function and the second one is iterative).

https://pastebin.com/N4Mimnwg

# Answer
> 0 votes
Every object is made of triangles. If it isn't, then it can be approximated. You basically need to do a binary search. Get the lowest and highest point in the object and set P halfway between these. Now extract every triangle and create tetrahedrons from current P and the triangles with a center point lower, than P. Calculate their total volume, if it's less, than the target volume, then move P upwards half as much as before (you move it by half of the height of the object first, then quarter, then eighth, etc.). If it's less, then move it downwards. After you reached the precision you want, stop. The last P point is your best estimate.

---
Tags: mathematics
---


# Question
Title: How do I implement flat shading in GLSL?
I'm working with GLSL and trying to implement flat shading on a 3D model (rather than smooth shading). To illustrate what I mean, here are two screenshots of cubes in Blender. Here's one with flat shading.

And here's the same cube with smooth shading.

I understand the theory behind this kind of shading. Each face on the cube (six total) has a normal facing away from the surface. Each vertex (eight total) has a normal computed by summing together face normals, then normalizing to unit length. This results in each vertex normal pointing directly away from the center of the cube.

Smooth shading can be implemented in basically two ways. In the first, color is computed per-vertex (using light direction and normal), then fragment color is interpolated among all vertices. In the second, normals themselves are interpolated, then color is computed per-fragment (using the same lighting calculations).

Here are my current GLSL shaders to implement the first option (there's no specular lighting yet, but it gets the idea across with ambient and diffuse). Vertex shader first.

```
in vec3 vPosition;
in vec3 vNormal;

out vec4 fColor;

uniform mat4 mvp;
uniform vec3 aColor;
uniform vec3 lDirection;
uniform vec3 lColor;

void main()
{
    gl_Position = mvp * vec4(vPosition, 1);

    vec4 ambient = vec4(aColor, 1);
    vec4 diffuse = vec4(max(dot(lDirection, -vNormal), 0) * lColor, 1);

    fColor = ambient + diffuse;
}

```

Then fragment.

```
in vec4 fColor;

void main()
{
    gl_FragColor = fColor;
}

```

So that works fine for smoothed shading, with fragment values interpolated among vertices. I'll also point out that I'm using buffers and index arrays for rendering.

For flat shading, each fragment on a face should instead use the **same** normal (such that every pixel on the surface has the same final color after lighting calculations). The problem is that I can't pass data to shaders per-face, but only per-vertex. Given this, I can think of three solutions.

1. **Pass four vertices per face, with each vertex storing the face normal**. This would still technically be smooth shading, but done in such a way that every interpolated pixel will use the same color (making if effectively flat). This approach seems wrong because it would basically ruin my vertex buffer, since I'd have to pass 24 vertices (four per face) despite the cube only containing eight unique vertices.
2. **Use GLSL's flat mode** (there's a `flat` keyword in GLSL). Using this approach, each fragment would only pull from a single "provoking vertex" rather than interpolating from all vertices on the face. This feels wrong because that I wouldn't actually be using the correct face normal. I also haven't been able to figure out the proper syntax for this style anyway. For the record, I'm aware of `glShadeModel`, but it's apparently deprecated.
3. **Average vertex normals per fragment rather than interpolating them.** To me, this feels like exactly the correct solution, since every pixel on a face would use the **same** normal, with that normal computed by summing and normalizing vertex normals (similar to how vertex normals are computed from face normals to begin with).

From those options, #3 clearly feels like the correct solution, but I haven't had any luck in figuring out how. So that's my question.

**How can I tell the fragment shader to use a normal averaged among all vertices, rather than interpolated?**

# Answer
> 8 votes
You may have heard 3D modelers talk about "hard edges" or "sharp edges", which are roughly equivalent to what you're looking for here. When modelers create a hard edge, their software will internally utilize your first method: *Pass four vertices per face, with each vertex storing the face normal.*

This allows a modeler to determine which edges of the object should be "smooth" (with light and other values interpolated between faces) and which should be "sharp" (with light calculated separately for each face), without needing to reconfigure the render pipeline.

That's especially useful because the "sharpness" of an edge is usually a property of that model. If this is something you wanted to manage scene-wide, changes to shaders and such might be more appropriate.

# Answer
> 11 votes
As @rutter says, your #1 option is the correct thing to do in the overwhelming majority of all cases. However, if you're really adamant that you want everything to be hard-edged, then you can do this trick:

In the vertex shader:

```
#version 330
out vec3 viewPosition;

void main()
{
    (...)
    viewPosition = (worldToView * worldPosition).xyz;
}

```

In the fragment shader:

```
#version 330
in vec3 viewPosition;

void main()
{
    vec3 xTangent = dFdx( viewPosition );
    vec3 yTangent = dFdy( viewPosition );
    vec3 faceNormal = normalize( cross( xTangent, yTangent ) );
}

```

Here, we using `dFdx` and `dFdy`.

`viewPosition` tells us where we are in view-space, in the current pixel. `dFdx(viewPosition)` checks the value of `viewPosition` in pixels to the left and right of us, and tells us how that value is changing as we move left and right on the screen. `dFdy` does the same thing vertically. In effect, it's telling us *view-space tangent vectors* for the face, in two different directions on the screen.

Since we have two different tangent vectors, we can take their cross-product to get the face's normal (again, still in view-space). That's exactly what we need for our lighting calculations, so we can simply use that rather than passing the normal in via vertex attributes at all.

That is, we're rebuilding the face normal inside the fragment shader based solely upon where the geometry *actually* is. Under this approach, vertex normals can be excluded from the vertex buffer entirely (if you don't need them for anything else). The big downside of this technique is that it becomes impossible to ever have a smoothly curving surface, because we're using the actual faces, and the faces are always actually flat.

Note that the above example assumes GLSL 330; you may need to switch "out/in" values to "varying", if you're in a much earlier version, but the maths itself should work anywhere.

And just to repeat, @rutter's answer is actually the right thing to do, you almost definitely want to do that. I've only added this answer since it provides the correct way to reconstruct actual face normals, when that's needed.

# Answer
> 3 votes
The third option is to use `flat` interpolation specifier when passing attributes from the vertex shader to the fragment shader.

This will make the gpu take the attribute of only 1 vertex and feed it to the fragment shader for the triangle, as opposed to interpolating the output of all 3 vertices per triangle.

---
Tags: opengl, 3d, glsl, lighting, shading
---


# Question
Title: HTML5 Canvas non-geometric edge trace for collision detection
I had a question about how to do edge tracing for use in collision detection for a game - think 'Asteroids'. I couldn't frame the question clearly so I did some R&D. The question I had in mind was '*how can I detect the edges of non-geometric shapes in a way that is pragmatic, fast and simple*'. The reading I did before I rolled up my sleeves seemed to be leading down the road of using a minimal bounding rectangle around whatever object is to be collision detected. I wanted more accuracy, and since my game will be using the HTML canvas....

I am posting this in case it is of use to other people and as an answer to my own question. I would be interested to know if this is a standard technique, which I am sure it must be, and if there are some standard ways to improve it.

The approach in this code is to copy the shape into a canvas, then grab the pixel array for the smallest bounding rectangle. The canvas pixel array is a continuous 1D array with slots 0,1,2,3 containing the R, G, B, and Alpha values for the pixel. So the array is 4 times the size of the w x h. That's not so important, but useful to know.

We traverse the array to run 4 line-scans scans, effectively running a finger along the canvas from left-right, top - bottom, right - left, bottom - top, looking for the edge pixels.

Say we are scanning left to right - we start on line 1 and inspect each pixels alpha value in turn. If the value is non-zero we know we have found a pixel on the boundary of the shape. We don't care about the details of the pixel colour or any pixels after this on line 1 so we move on to line 2 and repeat. If you do this left to right, right to left, top down and bottom up, the conclusion is a set of x,y points that represent a fair guess at the edges of the shape. It is not perfect as there is a 'shadow' effect as illustrated by the edge trace snippet (add square and star).

Negatives - clearly there could be a lot of pixels to scan, But on the positive side, you will only scan once, and you can store the results that you know are not going to change as part of your app data!

Consider an asteroids game - you could have 30 different asteroid shapes, well possibly really only 10 with the additional 20 being scaled versions of the 10. So you scan those and save the edge data. From there on, edge detection is a matter of rectangle comparison with some common sense techniques to avoid too much overhead.

Todo: For efficiency later the list of points needs to be sorted, and possibly collected into a tree structure, combined with a larger sector-grid and some code to identify which objects are in which sectors, and we need a process that works for when the objects are rotated.

The snippet lets you add some shapes to the left-hand canvas, and visualizes the edge trace on the right-hand side.

```
// add a stage
var s1 = new Konva.Stage({container: 'container', width: 800, height: 600});
var s2 = new Konva.Stage({container: 'container2', width: 800, height: 600});

// Add a layer and group to draw on
var l1 = new Konva.Layer({});
s1.add(l1);
var g1 = null;

// Add a display layer and group to draw on - only used to visualise what is going on
var l2 = new Konva.Layer({});
s2.add(l2);
var g2 = new Konva.Group({});

// this function is called from the buttons to throw some interesting shapes onto the canvas for tracing
var makeShape  = function(opts){

    var x = opts.x + opts.w;
    var y = opts.y + opts.w;

    // if the main group is not defined do it now.
    if (!g1){
      g1 = new Konva.Group({x: opts.x, y: opts.y, width: opts.w, height: opts.w});
      l1.add(g1);
    }

    // Draw the requested shape.
    switch (opts.type){

      case "circle":
        var c=new Konva.Circle({
              x: opts.x + opts.w, y: opts.y + opts.w,
              radius: opts.w/2,
              fill: 'white',
              stroke: 'black',
              strokeWidth: 4,
              listening: true
          });
          g1.add(c);
          break;

      case "square":
        var r = new Konva.Rect({ x: opts.x, y: opts.y, width: opts.w, height: opts.w, stroke: 'black' });
        g1.add(r);
        break;

      case "star":
        var star = new Konva.Star({
          x: opts.x + opts.w + 30, y: opts.y + opts.w,
          numPoints: 6,
          innerRadius: 40,
          outerRadius: 70,
          fill: 'yellow',
          stroke: 'black',
          strokeWidth: 4
        });

          // add the shape to the layer
          g1.add(star);
          break;

      case "blob":

        var blob = new Konva.Line({
            points: [23, 20, 23, 160, 70, 93, 150, 109, 290, 139, 270, 93],
            fill: '#00D2FF',
            stroke: 'black',
            strokeWidth: 5,
            closed : true,
            tension : 0.3
          });

        g1.add(blob);
        break;

      case 'rocket':
        var rocket = new Konva.Image({
        x: 50,
        y: 50,
        image: img,
        width: 106,
        height: 118
        });
        g1.add(rocket);
        break;
    }
    l1.draw();
    // and lets draw it all
    s1.draw()
}

// This is what this is all about !
function scanForEdges(){

  // get the imageData
  var c = l1.getCanvas();
  var ctx = c.getContext();
  // Now we have the inageData - this is a one-D array with a four-step sequence
  // where 1=R, 2=G, 3=B and 4=A. So positions 1-4 give RBBA values of pixel 1.
  // A lot of examples walk the entire array to flip colours, but we need to walk
  // a line-scan to find the outer edge of the shape by looking for any of the A
  // values not being zero. This is because A=0 is invisible
  // and all other values ARE a visible pixel. We only need to scan left to right
  // until the first hit, then right to left the same, then the top & bottom scans. As
  // long as the rect we select is not overly gappy around the shape then it
  // 'should' be quick.

  // Get the width and height of the box to scan,
  var gsz = g1.getClientRect();
  var x = 0, y = 0, w = gsz.x + gsz.width, h = gsz.y + gsz.height;

  // get the pixel data for that box
  var imgData = ctx.getImageData(x, y, w, h);
  var data = imgData.data;

 // console.log('h=' + h + ' w=' + w + ' data len=' + data.length);

  var pxWidth = w * 4, xStep = 1, yStep = 1; // steps > 1, like 3 or 7 can speed up the scan but they can miss edges of squares.

    // you can set these false to see the effect of each scan - all true for live.
  var doWEScan = true, doEWScan = true, doNSScan = true, doSNScan = true;
  var plotRects = []; // this is where we collect the boundary points

  if (doWEScan){
    // walk the Alpha pixels West to East.
    for (var y = 0; y < h; y = y + yStep){
      for (var x = 0; x < w; x = x  + xStep){
        pxNo = (y * pxWidth) + (x * 4)
        if ( data[pxNo + 3] > 0){
          xStep1 = xStep
          plotRects.push({x:x, y: y, w: 4, h:4, pxNo: pxNo});
          break;
        }
      }
    }
  }

  if (doEWScan){
  // walk the Alpha pixels East to West.
    for (var y = 0; y < h; y = y + yStep){
      for (var x = w; x >=0; x = x  - xStep){
        pxNo = (y * pxWidth) + (x * 4)
        if ( data[pxNo + 3] > 0){
          plotRects.push({x: x, y: y, w: 4, h:4, pxNo: pxNo});
          break;
        }
      }
    }
  }

  if (doNSScan){
    // walk the pixels N to S.
    for (var x = 0; x < w; x = x  + xStep){
      for (var y = 0; y < h; y = y + yStep){
        pxNo = (y * pxWidth) + (x * 4)
        if ( data[pxNo + 3] > 0){
          plotRects.push({x: x, y: y, w: 4, h:4, pxNo: pxNo});
          break;
        }
      }
    }
  }

  if (doSNScan){
    // walk the pixels S to N.
    for (var x = 0; x < w; x = x  + xStep){
      for (var y = h; y >= 0; y = y - yStep){
        pxNo = (y * pxWidth) + (x * 4)
        if ( data[pxNo + 3] > 0){
          plotRects.push({x: x, y: y, w: 4, h:4, pxNo: pxNo});
          break;
        }
      }
    }
  }

  // So now we have the results stored in plotRects[] - we are going to visualise then on another canvas
  // but in live use you would use this array for hit-detection processing.
  // clear the visualisation group & layer
  g2.destroyChildren();
  g2.destroy;
  s2.clear()

  // Addrect just...adds rects !
var addRect = function(x,y,w,h){
  w=1;h=1;
  var r = new Konva.Rect({
    x: x, y:y, width: w, height: h, strokeWidth:0.1, stroke: 'red', fill: 'red'
  });
  l2.add(g2)
  g2.add(r);
}

var c2 = l2.getCanvas();
var ctx2 = c2.getContext();
ctx2.putImageData(imgData, 0, 0);
ctx2.drawImage(c2._canvas, 0, 0);

for (var i = 0; i < plotRects.length; i = i + 1){
  var r = plotRects[i];
  addRect(r.x, r.y, r.w, r.h)
}
l2.draw();

//console.log('Done - calculated ' + plotRects.length + ' pts')

}

// Events for the buttons
$('.addShape').click(function(e){

  var type = $(this).prop('id');

  makeShape({w:120, x: 4, y: 4, type: type});

  scanForEdges();

})

$('#reset').click(function(e){
  g1.destroyChildren();
  g1.destroy()
  g1=null;
  l1.clear();
  s1.clear();
})

// fluff to get the svg image into the canvas.
var svg = document.querySelector('svg');
var img = document.querySelector('img');
// get svg data
var xml = new XMLSerializer().serializeToString(svg);
// make it base64
var svg64 = btoa(xml);
var b64Start = 'data:image/svg+xml;base64,';
// prepend a "header"
var image64 = b64Start + svg64;

// set it as the source of the img element
img.src = image64;

setTimeout(function(){
  // something to get is started
  $('#rocket').trigger('click');
  },
  500
  )
```

```
p
{
  padding: 5px;

}
.container
{display: inline-block;
width: 250px;
height: 300px;
background-color: transparent;
overflow: scroll;
border: 1px solid red;
}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src="https://cdn.rawgit.com/konvajs/konva/1.6.5/konva.min.js"></script>
<div>
  <button id='square' class='addShape'>Add square</button>
  <button id='circle' class='addShape'>Add circle</button>
  <button id='star' class='addShape'>Add star</button>
  <button id='blob' class='addShape'>Add blob</button>
  <button id='rocket' class='addShape'>Add rocket ship</button>
  <button id='reset'>Reset</button>
</div>

<div id='container' class='container'></div>
<div id='container2' class='container'></div>

<p>
  <span id='text'>Issue: Shadowing effect.</span>
</p>

<div style='display: none;'>
<img />
<svg  id='rocketship' version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
  viewBox="0 0 309.133 309.133" style="enable-background:new 0 0 309.133 309.133;" xml:space="preserve" width='200' height='200'>
<g>
 <path d="M30.078,172.934c23.695-34.108,37.633-56.082,47.795-72.321c-39.053,3.454-76.486,52.048-76.486,52.048l25.777,25.776
  C27.912,176.531,28.867,174.68,30.078,172.934z"/>
 <path d="M130.723,281.997l25.76,25.759c0,0,48.592-37.43,52.047-76.482c-16.234,10.158-38.201,24.091-72.32,47.792
  C134.484,280.264,132.644,281.242,130.723,281.997z"/>
 <path d="M91.549,268.678c-4.422,1.787-8.768,3.686-13.299,5.2c-12.102,4.045-24.566,6.778-37.203,8.522
  c-5.297,0.731-10.643,1.351-15.998,1.757c0.051-0.661,0.1-1.323,0.156-1.983c1.105-12.876,3.064-25.685,6.229-38.223
  c1.525-6.051,3.471-11.933,5.56-17.807c1.299-3.652,2.92-7.147,4.555-10.642l-2.834-2.832c-6.303,4.234-11.785,9.584-16.437,15.637
  c-6.887,8.963-12.049,19.117-15.658,29.817c-3.877,11.489-6.189,23.657-6.549,35.787c-0.051,1.704-0.168,3.445,0.096,5.136
  c0.34,2.184,1.299,4.251,2.74,5.926c1.426,1.657,3.303,2.908,5.383,3.579c1.746,0.563,3.502,0.573,5.313,0.559
  c11.012-0.092,22.195-2.005,32.736-5.137c19.279-5.728,38.742-16.504,50.15-33.532l-2.758-2.756
  C93.008,268.026,92.283,268.359,91.549,268.678z"/>
 <path d="M306.004,3.149c0,0-0.002-0.001-0.004-0.003c-2.006-2.005-4.725-3.128-7.555-3.128c-0.07,0-0.141,0.001-0.211,0.002
  c-34.41,0.675-119.307,7.111-164.393,52.199c-20.467,20.467-27.119,31.121-41.699,54.469c-10.5,16.81-24.875,39.835-51.147,77.649
  c-2.951,4.25-2.438,10.003,1.221,13.66l68.928,68.929c2.068,2.069,4.807,3.133,7.564,3.133c2.119,0,4.248-0.628,6.096-1.911
  c37.828-26.278,60.844-40.65,77.648-51.146c23.346-14.579,34.002-21.233,54.473-41.702c45.166-45.168,51.557-130.009,52.205-164.39
  C309.187,8.007,308.057,5.205,306.004,3.149z M226.187,133.206c-13.877,13.876-36.373,13.876-50.25,0
  c-13.879-13.877-13.877-36.372,0.002-50.248c13.875-13.877,36.371-13.879,50.248-0.003
  C240.06,96.831,240.062,119.331,226.187,133.206z"/>
</g>
</svg>
</div>
```

# Answer
> 1 votes
I am a hobby enthusiast and I made my 'clone' of 'Space Invaders'. Here is its Codepen link: GalactiX. I was thinking slightly different about sprite-sprite collision. I test all interactions between actors.

First step: those too far apart gets filtered out: distance between their center points being larger than preset constant (larger side of the biggest sprite in the game).

Second step: classic rectangle overlapping; if yes, then:

Third step: only overlapping parts of both sprites are checked for nontransparent pixels. If the nontransparent pixels are found on the same coordinate in both sprite, function immediately returns ***true***.

All sprites I am using are trimmed (have no transparent lines around). So the collision is either quickly found, or at least the overlapping areas are fairly small.

Relevant method from game:

```
collision: function(actor1, actor2) {
    var X = Math.abs(actor1.x - actor2.x);
    var Y = Math.abs(actor1.y - actor2.y);
    if (Y >= INI.COLLISION_SAFE) return false;
    if (X >= INI.COLLISION_SAFE) return false;
    var w1 = parseInt(actor1.width / 2, 10);
    var w2 = parseInt(actor2.width / 2, 10);
    var h1 = parseInt(actor1.height / 2, 10);
    var h2 = parseInt(actor2.height / 2, 10);
    if ((X >= w1 + w2) || (Y >= h1 + h2)) return false; //no rectangle overlapping

    var act1 = new Vector(actor1.x, actor1.y);
    var act2 = new Vector(actor2.x, actor2.y);
    var SQ1 = new Square(act1.x - w1, act1.y - h1, w1 * 2, h1 * 2);
    var SQ2 = new Square(act2.x - w2, act2.y - h2, w2 * 2, h2 * 2);

    var x = MAX(SQ1.x, SQ2.x);
    var y = MAX(SQ1.y, SQ2.y);
    var w = MIN(SQ1.x + SQ1.w - x, SQ2.x + SQ2.w - x);
    var h = MIN(SQ1.y + SQ1.h - y, SQ2.y + SQ2.h - y);

    var area = new Square(x, y, w, h);
    var area1 = new Square(
                area.x - SQ1.x,
                area.y - SQ1.y,
                area.w,
                area.h
    );

var area2 = new Square(
  area.x - SQ2.x,
  area.y - SQ2.y,
  area.w,
  area.h
);
    var CTX1 = LAYER.temp;
    var CTX2 = LAYER.temp2;
    ENGINE.draw("temp", 0, 0, SPRITE[actor1.name]);
    ENGINE.draw("temp2", 0, 0, SPRITE[actor2.name]);
    var data1 = CTX1.getImageData(area1.x, area1.y, area1.w, area1.h);
    var data2 = CTX2.getImageData(area2.x, area2.y, area2.w, area2.h);
    var DL = data1.data.length;
    var index;
    for (index = 3; index < DL; index += 4) {
        if (data1.data[index] > 0 && data2.data[index] > 0) return true;
    }
    return false;
},

```

Even with all sprite-sprite interaction testing, the game runs smoothly on current version of Chrome and Firefox.

---
Tags: collision-detection, javascript, html-canvas
---


title: It lags when it collides. Help? :(

text:
# Question
Title: It lags when it collides. Help? :(
I am trying (and believing) to make a game of pong. I have got a slightly decent working game. I haven't implemented the scoreboard or AI yet because I want the physics to work first. I am trying to reverse the direction of the ball when it hits either paddle just to make it work cleanly and am having the issue where it changes direction twice, it bounces off the paddle as expected and then goes in the opposite direction to when it hit the paddle -.- If anyone could help me, it would be much appreciated.

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

    public class BallController : MonoBehaviour {

        private float randomNumber;
        private float range;
        private float pointOfContact;
        private float paddleTop;
        private float paddleBottom;
        private float[] limits;
        private int speed;
        private int caseNumber;
        private Vector2 direction;
        private Rigidbody2D ballRigidbody;

        void Start () {
            //Getcomponent finds the rigidbody of the attached object.
            ballRigidbody = GetComponent<Rigidbody2D> ();

            speed = 5;
            caseNumber = Random.Range (0, 2);
            range = PickARange (caseNumber);
            ballDirection (speed, range);
        }

        void FixedUpdate() {

        }

        void OnCollisionEnter2D (Collision2D coll) {
            if (coll.gameObject.tag == "Player" || coll.gameObject.tag == "Computer") {
    //          pointOfContact = ballRigidbody.position.y;
    //          print (pointOfContact);

                ballRigidbody.velocity = new Vector2 (ballRigidbody.velocity.x, ballRigidbody.velocity.y * -1);
            }
        }

        void ballDirection (int ballSpeed, float yDirection) {
            randomNumber = (Random.Range (0, 100));

            if (randomNumber < 49) {
                direction = new Vector2(Random.Range (-1.0f, -0.5f), yDirection);
                ballRigidbody.velocity = (direction * ballSpeed);
            } else {
                direction = new Vector2(Random.Range (0.5f, 1.0f), yDirection);
                ballRigidbody.velocity = (direction * ballSpeed);
            }
        }

        float PickARange (int number) {
            switch (number) {
            case(0):
                range = Random.Range (0.5f, 1.0f);
                return range;
            case(1):
                range = Random.Range (-1.0f, -0.5f);
                return range;
            default:
                range = 1.0f;
                return range;
            }
        }
    }

```

I thought to multiply the whole velocity by -1 but that just caused a loop because of the lag. Even though that's the right way to reverse the direction. I think.

Thanks Peeps!

# Answer
> 2 votes
`OnCollisionEnter(Collision collision)` handlers run *after* the physics engine has resolved the collision by displacing the objects and updating their velocities.

That means that at this moment, the ball has already bounced off the wall/paddle, and reversing its velocity will tend to send it *back into collision* which can cause it to linger in contact and look like it's lagging/stalled. The game's still running at normal speed, but the ball is changing direction too frequently to make progress until, by some luck, it eventually lands outside of collision and can continue on its way.

If you want to control your velocity after a bounce, the `Collision` argument contains information about the impact that you can use.

Specifically, if the collider you hit was not itself moving, then:

```
var preCollisionVelocity = -1f * collision.relativeVelocity;

```

will give you your incoming velocity, before the collision resolver ran. You can safely use *that* as the source to reflect from.

Just note that an object might experience several collisions in a single physics step, so you'll want to watch out for literal corner cases where you've reflected off two or more surfaces in rapid succession.

# Answer
> 0 votes
* Have you checked whether OnCollisionEnter2D is invoked multiple times when a collision happens? If that is the case, it might be that Unity is detecting several points on the ball to have collided with the paddle. In that case, you can cause the ball to be immune to direction-change for a short amount of time.
* Or it could be that you are negating the ball's direction after it has already changed its direction on collision.

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


# Question
Title: Unity Player Movement Script nullifies gravity
i want my Player to be affected by gravity, while being able to be moved in horizontal direction(the Player jumps up and down), but my script:

```
Vector3 move = new Vector3(Input.GetAxis("Horizontal"), (Input.GetAxis("Vertical")), 0);

transform.position += move * speed * Time.deltaTime;

```

...seems to nullifiy gravity. Can someone tell me how to fix that?

# Answer
As Savlon wrote: https://docs.unity3d.com/ScriptReference/Rigidbody.AddForce.html or this: https://docs.unity3d.com/ScriptReference/Transform.Translate.html But do not use "transform.position +=" for player movement script.
> 1 votes

---
Tags: unity, unityscript
---


# Question
Title: Memory is not getting freed on Destroy()
Manager script(simple script attached to an empty GameObject on scene) on Start() instantiates 1000 default cubes with rigidbody component added and gravity check ticked.

```
public class SpawnScript: MonoBehaviour {

    public bool MakeInstances = false;
    public bool GC = false;
    public GameObject instance;
    public int numberOfInstances = 1;

    void Start() {
        if (MakeInstances)
            for (int i = 0; i < numberOfInstances; i++)
            {
                Instantiate<GameObject>(instance);
                //GameObject tempInstance = Instantiate<GameObject>(instance);
                //GameObject.Destroy(tempInstance);
                //tempInstance = null;
                //Debug.Log("obj is " + tempInstance);
            }
    }

    private void Update()
    {
        if (GC)
        {
            GC = false;
            System.GC.Collect();
            Resources.UnloadUnusedAssets();
        }
    }

```

Cube prefab have self destruction script like this

```
public class SelfDestruct : MonoBehaviour {
    public float seconds;

    IEnumerator DestructIn(float time)
    {
        yield return new WaitForSeconds(time);
        Destroy(gameObject);
    }

    void Start () {
        StartCoroutine(DestructIn(seconds));
    }
}

```

Profiler "simple" shows memory usage around 0.7gb after instantiating is done. I expect it to get freed after destroy, but it does not. Tried to apply GC and UnloadUnusedAssets, did not help. Tried to destroy them all right after instantiating, still no luck.
Is it a bug or am I doing something wrong? This is definitely not a real world example, just wanted to study memory management in Unity and got stuck here.

P.S.A few more strange points I have noticied with profiler:

1. In Editor/"Detailed" mode it would not notice that I have 1000 cubes on a scene, while in Build/"Detailed" it did
2. In "detailed"(both editor and build) data usage is around 200mb which is definitely not true(broken?), because Windows Task Manager shows me that build is using around 0.9gb. Bigger than what "simple" tells me, guess some overhead is present

**EDIT:**
Thanks to @Candid Moon for performing a test, he did confirm that software won't eat all the memory. Guess I should add screenshots with my observations Here we have no instantiation, simple clean scene with a plane, eats around 100mb  Now let us go wild and make that instantiation on a startup

Alright, we did instantiate a lot of objects, they collided and flew away in outer space, in 5 seconds they were destroyed. We are back to clean scene with plane, just like the one with 100mb. Except for now it eats up 0.75gb. Left it hanging for half an hour to see if memory gets freed, nothing happened.
Is it a usual behavior? Is there any way to free all the used memory and go back to 100mb? Can/Should programmer do anything on his side to deal with such situations?

# Answer
1000 isn't enough. I have taken your scripts and modified them a bit and it's showing that everything is working correctly. Instantiating 1000 objects gives you less than 1 mb - if you have seen any change it was impossible to spot it because of many factors like unity editor own objects and garbage creation. Calling GC doesn't necessary start the process (as far as I know - but I'm not sure about this one).

Here you can see how the memory is freed. Also, if it didn't free the memory I wouldn't have a constant memory usage when instantiating and deleting 100 cubes every frame. It would just gradually increase until I run out of memory. On these pictures I'm trying to show that the memory increases because we create many instances at once.

Memory went back to normal. If you create them at the same position the physics engine creates a lot of garbage because of collisions, so I modified creation on random positions.

Here you go:

```
public class SelfDestruct : MonoBehaviour
{
    public float seconds = 5f;
    public double[] garbage = new double[12500]; //!!!!!!!!!!!!!!!!!! BE CAREFUL - IF your computer is slow and you attach this script the array will be so big to display that UNITY MAY LAG. TRY TO DECREASE THIS IF you experience freeze

    IEnumerator DestructIn(float time)
    {
        yield return new WaitForSeconds(time);
        Destroy(gameObject);
    }

    void Start()
    {
        StartCoroutine(DestructIn(seconds));
    }
}

public class SpawnScript : MonoBehaviour
{
    public bool MakeInstances = false;
    public bool GC = false;
    public GameObject instance;
    public int numberOfInstances = 1;

    private void Update()
    {
        if (GC)
        {
            GC = false;
            System.GC.Collect();
            Resources.UnloadUnusedAssets();
        }

        if (MakeInstances)
        {
            for (int i = 0; i < numberOfInstances; i++)
            {
                Instantiate(instance, Random.insideUnitSphere * 300f, Quaternion.identity);
                //GameObject tempInstance = Instantiate<GameObject>(instance);
                //GameObject.Destroy(tempInstance);
                //tempInstance = null;
                //Debug.Log("obj is " + tempInstance);
            }
        }
    }
}

```

I didn't call CG even once during testing. Only in the end to try if anything changes - result is nothing has been changed.

Conclusion: `Destroy` works as intended and it frees up the memory. Other problems might be in physics or something else. Coroutines were used as well, so they don't seem not to free up the memory usage.

**EDIT**

Now if we look at profiler.

---

We can see that profiling data stacks memory. And if you try to profile yourself you will be able to see how many objects in scene you have right now and if they are being destroyed and if the memory is freed.
> 2 votes

---
Tags: unity, memory-efficiency, memory, profiler
---


# Question
Title: How to efficiently spawn / instantiate a large amount of objects from a prefab
I am trying to make a game where the whole world is consists of a very large amount of cubes (sort of a Minecraft / Trove clone), but I keep running into huge performance issues due to the large amount of objects / vertices being rendered at once.

Just to clarify, the problem appears to be caused by the rendering, not the instantiation. I think so based on the fact that when I look away from the cubes, the frame rate will return back to normal (\>60).

Is there any way to optimize this? Many answers to similar questions suggest disabling colliders, but that does not really seem to make much of a difference for me. I have also tried making the prefab static, but the problem still remains.

Currently I keep getting ~40 FPS with 10000 cubes (just the built-in cube shape stored as a static prefab with a disabled collider). I believe there should be a way to have a larger amount of objects on screen without having such a performance drop.

Does Unity have any way of storing information about a prefab in graphics card memory that would allow it to mass-render its instances in a more performance-efficient way (much like modern OpenGL uses vertex buffers)?

# Answer
> 3 votes
Don't use thousands of `GameObject`s. Don't use the flyweight pattern. Do as Peter says: batch your vertices. You can learn the basics of procedural mesh construction here.

Between batching and instancing, you can do things with far better performance than by using thousands of `GameObject`s, which creates unnecessary overheads in such high-geometry tasks.

Golden Rule of voxel/cube terrain: NEVER use one object instance per tile, except possibly in exceptional circumstances.

# Answer
> 0 votes
It sounds to me like what you are looking for is Occlusion Culling.

Essentially if you are running a Minecraft like game, the renderer is going to try to render everything that is currently being seen by the camera even GameObjects that are obscured by other GameObjects. The problem occurs, because you what you actually want is to only render things that are actually showing, that is, only the GameObjects that are in view and not being blocked by other GameObjects.

Occlusion Culling to the rescue! Occlusion Culling fixes your problem by saying "Hey I know there is a ton of GameObjects in front of me, but can you only render the ones that the player is actually seeing, that is, not the ones that are being blocked by other GameObjects?"

Hopefully this makes sense!

Check this link for a nice guide from Unity that explains exactly what I'm talking about...much better then I did.

---
Tags: unity, performance, voxels
---


# Question
Title: Why the Render texture is not working when trying to preview a camera on a object?
In the editor in Assets right click Create \> Render Texture Then changed the Render Texture name to: SecurityCameraTexture

Dimension 2D size 480 x 256

Then created a new material Assets right click Create \> Material Then changed the material name to: SecurityFootage

Then changed the material shader from Standard to Mobile/Diffuse

Then dragged the render texture(SecurityCameraTexture) to the top right image place of the SecurityFootage(material)

Next I have a tv object in the scene. In the tv screen I dragged the new material:

The SecurityCamera. On the SecurityCamera I attached the script that rotate the camera from side to side:

And the script:

```
using UnityEngine;
using System.Collections;

public class scr_camera : MonoBehaviour {

    public float rotate_amount;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        transform.rotation = Quaternion.Euler(transform.eulerAngles.x, (Mathf.Sin(Time.realtimeSinceStartup) * rotate_amount) + transform.eulerAngles.y, transform.eulerAngles.z);
    }
}

```

Last step I did was to drag the render texture(SecurityCameraTexture) to the camera Target Texture.

When running the game and watching the tv I don't see the camera preview in the tv. It should the show the camera preview the camera moving from side to side and what the camera is showing.

The camera preview was working fine before I started working with the render texture. But it's not showing the preview in the tv.

# Answer
Some suggestions:

1. Set your Material As Unlit/Texture
2. Change your target display on your Camera component
3. For testing purposes, create a looped animation of your camera moving.
> 3 votes

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


title: Avoid rolling whith quaternion

text:
# Question
Title: Avoid rolling whith quaternion
I'm using a Look At function (idem as nasskov answer on this post) to orient a model:

```
osg::Quat result = quatLookAt(normalize(velocity));

```

It works but may let the model to roll. How I can avoid this ?

I'm thinking of decomposing the rotation into two quaternions (Pitch&Yaw) but not succeeded so far.

---

**The solution:**

```
inline osg::Vec3
VectorFront()
{
  return osg::Vec3(0, 1, 0);
}

inline osg::Vec3
VectorUp()
{
  return osg::Vec3(0, 0, 1);
}

inline osg::Quat
quatLookAt(const osg::Vec3& dir, const osg::Vec3& up)
{
  if (dir.length2() == 0.0f) {
    assert(false && "Zero length direction in quatLookAt(const osg::Vec3& "
                         "dir, const osg::Vec3& up)");
    return osg::Quat();
  }

  if (up != dir) {
    const osg::Vec3 v = dir + up * -(up * dir);
    osg::Quat       q;
    q.makeRotate(VectorFront(), v);
    osg::Quat r;
    r.makeRotate(v, dir);
    return q * r;// * q
  }

  osg::Quat q;
  q.makeRotate(VectorFront(), dir);
  return q;
}

// ...

const osg::Quat q = quatLookAt(new_forward, VectorUp());

```

# Answer
Although I'm not sure about the math behind it, you could replicate a Unity function that does this.

> https://docs.unity3d.com/ScriptReference/Quaternion.LookRotation.html

LookRotation has 2 parameters for your forward vector and up vector. If you use, for example, the Y axis as your upward vector, then your model should not roll.

Here is a post about replicating it manually:

> https://answers.unity.com/questions/819699/calculate-quaternionlookrotation-manually.html
> 1 votes

---
Tags: c++, quaternion
---


title: sf::mouse::getPosition method help

text:
# Question
Title: sf::mouse::getPosition method help
I am trying to write sf::mouse::getPosition(const Window &Relative To) in a function but I can't write the correct argument in it. Why is that?

Here is my Game.cpp File: EDIT: I pasted the current code:

```
#include "Game.h"

Game::Game() : m_window("Multiplayer Space Shooter Game", sf::Vector2u(800, 600)) {
    // Setting up class members.
    m_shipText.loadFromFile("C:\\Users\\AliTeo\\Desktop\\Piksel çalışmaları\\ship_pixel2.png");
    m_ship.setTexture(m_shipText);
    m_ship.setOrigin(m_shipText.getSize().x / 2, m_shipText.getSize().y / 2);
    m_ship.setPosition(320, 240);
}
Game::~Game() {}
void Game::Update() {
    m_window.Update(); // Update window events.
    m_ship.move(m_speedX, m_speedY);
    m_ship.setRotation(90 + m_angle);
    HandleInput();
}
void Game::HandleInput() {
    sf::Mouse m_mouse;
    m_angle = atan2(m_mouse.getPosition(&m_window).y - m_ship.getPosition().y, m_mouse.getPosition(&m_window).x - m_ship.getPosition().x);
    m_angle *= 180 / m_PI;

    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right) && m_speedX <= m_speedLimit) {
        m_speedX += m_acceleration;
    }
    else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left) && m_speedX >= -1 * m_speedLimit) {
        m_speedX -= m_acceleration;
    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down) && m_speedY <= m_speedLimit) {
        m_speedY += m_acceleration;
    }
    else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up) && abs(m_speedY) >= -1 * m_speedLimit) {
        m_speedY -= m_acceleration;
    }
}
void Game::Render() {
    m_window.BeginDraw(); // Clear.
    m_window.Draw(m_ship);
    m_window.EndDraw(); // Display.
}
Window* Game::GetWindow() { return &m_window; }

```

m\_window is a member of Game.h

```
no instance of overloaded function "sf::Mouse::getPosition" matches the argument list

#include "Window.h"
class Game {
public:
    Game();
    ~Game();
    void HandleInput();
    void Update();
    void Render();
    Window* GetWindow();
private:
    sf::Sprite m_ship;
    sf::Texture m_shipText;
    //sf::Vector2i mousePos = sf::Mouse::getPosition();
    Window m_window;
    const float m_PI = 3.1415f;
    float m_speedX = 0;
    float m_speedY = 0;
    float m_acceleration = 0.001f;
    //float m_friction = 0.001f;
    float m_speedLimit = 0.5f;
    float m_angle;
};

```

# Answer
The `getPosition` method inside of the `sf::Mouse` class is actually static. You'll need to use it like this inside of your game loop that preforms updates every frame:

```
sf::Vector2i mousePos = sf::Mouse::getPosition(m_window);

```
> 1 votes

# Answer
You forgot to pass m\_window to the **second** Mouse::getPosition
> 0 votes

# Answer
You're trying to pass a pointer to `m_window` but the function just wants a reference.

`m_mouse.getPosition(m_window)` should do the trick as opposed to your current `m_mouse.getPosition(&m_window)`.
> 0 votes

---
Tags: sfml
---


# Question
Title: Direct3D 12 STATE_CREATION ERROR #649: CREATE_CONSTANT_BUFFER_VIEW_INVALID_RESOURCE
Every time my constant buffer helper creates the "Constant buffer view" with the `CreateConstantBufferView` method i get an error which states:

**D3D12 ERROR: ID3D12Device::CreateConstantBufferView: pDesc-\>BufferLocation 0x00000000a9df6000 does not belong to any existing Resource or Heap. \[ STATE\_CREATION ERROR #649: CREATE\_CONSTANT\_BUFFER\_VIEW\_INVALID\_RESOURCE\]**

this makes no sense as the resource is created and used (just like in the previous **working** usages of this method) the only thing that is different is the descriptor heap and obviously the instance of the constant buffer helper.

Also it is used by a different command list and Pipeline state object (PSO), this may be the problem but I am unsure.

here is the relevant code for the creation of the constant buffer view:

```
D3D12_CONSTANT_BUFFER_VIEW_DESC desc = {};
desc.BufferLocation = cbvGpuAddress;
desc.SizeInBytes = size;
m_deviceResources->GetD3DDevice()->CreateConstantBufferView(&desc, cbvCpuHandle);
sizeInBytes = desc.SizeInBytes;

```

Below is for the creation of the descriptor heap and constant buffer helper:

```
 m_cbvSrvHeapManager = std::make_shared<DescriptorHeapManager>(DX::c_frameCount + 1, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, m_deviceResources);
    m_cbvDescriptorSize = m_cbvSrvHeapManager->GetDescriptorSize();

m_mvpConstantBufferManager = std::make_unique<ConstantBufferManager<Structures::ModelViewProjectionConstantBuffer>>(DX::c_frameCount, m_mvpConstantBufferManager->GetAlignedSize(), m_deviceResources, m_commandListManager);
    for (int n = 0; n < DX::c_frameCount; n++)
    {
        m_mvpConstantBufferManager->CreateBufferDesc(m_mvpConstantBufferManager->GetAlignedSize(), n, m_cbvSrvHeapManager, m_cbvDescriptorSize);

    }

```

Below is for the previous **working** usage of the creation of the descriptor heap and and constant buffer helper:

```
m_cbvSrvHeapManager = std::make_shared<DescriptorHeapManager>(DX::c_frameCount + 2, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, m_deviceResources);

m_cbvDescriptorSize = m_cbvSrvHeapManager->GetDescriptorSize();
    m_mvpConstantBufferManager = std::make_unique<ConstantBufferManager<Structures::ModelViewProjectionConstantBuffer>>(DX::c_frameCount, m_mvpConstantBufferManager->GetAlignedSize(), m_deviceResources, m_commandListManager);
for (int n = 0; n < DX::c_frameCount; n++)
{
    m_mvpConstantBufferManager->CreateBufferDesc(m_mvpConstantBufferManager->GetAlignedSize(), n + 2, m_cbvSrvHeapManager, m_cbvDescriptorSize);
}

```

# Answer
Some how i fixed it, i created the vertex and index buffers **after** the constant buffers.
> 0 votes

---
Tags: c++, directx, directx12
---


# Question
Title: How to activate GearVR Menu in my own Unity-Apps?
So in normal GearVr-Apps, which you can download from the marketplace, you can activate the GearVr Menu to control brightness etc. with a long click on the back button. But this does not work for all of my apps which I made with Unity for the GearVr, is there something special I have to import into my project?

# Answer
Have you installed the utilities for Unity? According to the docs, the long click on the back button should **always** show the GearVr Menu. But, if it is not working, there is also a script (OVRPlatformMenu.cs) in the utilities that does that. You can find more info about the script here.

Good luck
> 1 votes

---
Tags: unity, mobile, virtual-reality, augmented-reality
---


# Question
Title: What does declaring a const float within a function do? (CGFX)
I've been working with this piece of code to get the mip map level that I should sample for a texture that I got off a forum somewhere. I noticed that they use a const float. Now from what I understand this would just immediately get discarded after the function was done, so if there was any performance gain here it would be hyper-small.

But I know that sometimes there is a lot of compiler magic that goes on in graphics programming languages, so I was wondering if the const declaration actually did matter (like, does it only calculate the value once and reuse that value for every fragment on the screen?)

```
        float MipLevel( float2 uv, half mipcount, half texturedim)
        {
            uv *= texturedim;

            float2 dx = ddx( uv );
            float2 dy = ddy( uv );
            float d = max( dot( dx, dx ), dot( dy, dy ) );

            // Clamp the value to the max mip level counts
            const float rangeClamp = pow(2, (mipcount - 1) * 2);
            d = clamp(d, 1.0, rangeClamp);

            float mipLevel = 0.5 * log2(d);

            return mipLevel;
        }

```

# Answer
A const value is never changed after it is initialized. By declaring a const the compiler can do certain optimizations, like calculating the const value at compile time instead of at runtime and replacing references to the variable with the actual value so that there is no extra overhead.

As well as being a hint to the compiler, it is also a hint to the developer who is reading the code. AKA self-documented. If the variable is declared as a const, even if there is no optimization advantage, the reader can be sure the value that is assigned at the time of initialization is the value that will be used when the const is referenced later.

In the case of the example in the question, it's possible and likely that the value passed to the mipcount argument is also a const. When compiling, the compiler will analyze the code, following the execution paths and if it finds that the value passed to mipcount is a const, it can then optimize rangeClamp to a literal value instead of a subtract, multiply and pow operation.
> 3 votes

---
Tags: shaders, glsl, hlsl, graphics-programming, cg
---


# Question
Title: Dynamic vs Kinematic, do either of these cause a collision before OnCollisionEnter2D?
Firstly, it would be a great deal of help if someone could explain to me the differences between Dynamic, Kinematic and Static (especially if there is a box for static by the name of the object. I've looked at the APIs and tried playing around with them, they are so confusing. :/

Secondly, I understand that the physics engine evaluates first and can cause a collision (when the ball hits the paddle in my Pong game) but is there a way around this? I'm trying to send the ball in the opposite direction to which it hit the paddle by using OnCollisionEnter2D but this method gets called second and therefore the ball changes direction twice and the physics engine causes an unnecessary collision...

I have looked to tutorials on the movement in pong and tried following the tutorials but get the same problem (even though their game is faultless), this leads me to think that it's the Body Type property that is causing the physics engine to produce the extra collision because theirs is an older unity version. It could possibly be the bouncy material with no friction also, I don't know much purely because I'm a newbie to unity. I wonder whether anyone has had the same problem as me and can set me free.

Thanks in advance. I seriously appreciate any help I can get! :)

# Answer
> 12 votes
* **Static** bodies have no Rigidbody component attached to them, so the physics engine does not consider them to be moving. (Avoid moving these frequently or you'll violate that expectation)

Use static colliders for level geometry like the ground and immovable walls, or stationary trigger volumes.

Static colliders on their own won't set off trigger/collision messages like OnCollisionEnter, unless there's a Rigidbody on the other participant.
* **Dynamic** bodies have a Rigidbody component attached to them and their `isKinematic` flag set to `false`. These objects move at the whims of physics according to their velocities/angular velocities and the forces/torques and collision impacts exerted on them. The physics engine takes responsibility for resolving their collisions with static, kinematic, and other dynamic objects and rebounding them as needed.

Use these for basic physics objects you want to be able to stack & topple and have them behave plausibly with minimal intervention, or for objects that you want to steer in a physics-focused way, like a rocketship.
* **Kinematic** bodies have a Rigidbody component with the `isKinematic` flag set to true. This tells the physics engine "this object moves, but I'll handle that part" — the kinematic object will process collisions with other rigidbodies, but only dynamic objects will automatically react by bouncing away, and cause `OnCollisionEnter` messages to be sent.

The kinematic object itself won't move except how you tell it to with `MovePosition()`/`MoveRotation()` — its velocity won't automatically integrate each timestep.

Use this for objects that you want to control in ways that don't behave like simple physics bodies — like a bipedal character controller or highly custom vehicle controls. Use physics queries like overlap checks and shape casts to scan for collisions preemptively, since they won't stop your object automatically.

You can refer to the Collision Action Matrix at the bottom of this documentation page for a quick reference of what types of collision are checked for each type of body.

For your case though, I think a simple dynamic Rigidbody is all you need. Just set its collider's `isTrigger` flag to true. Trigger colliders *detect* collisions, but do not generate collision resolution responses. That way the velocity of the object stays under your control.

Instead of `OnCollisionEnter2D(Collision2D collision)`, you'll listen for collisions with `OnTriggerEnter2D(Collider2D other)`

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


# Question
Title: GLSL Lighting with attenuation; how to add a fade-out color?
I am using the GLSL shader from this link, slightly modified and i got it working. The shader code is the following:

**VS:**

```
  vPosition = uMVMatrix * vec4(aVertexPosition, 1.0);
  vTransformedNormal = uNMatrix * aVertexNormal;
  gl_Position = uPMatrix * vPosition;

```

**FS:**

```
  float minLight = 0.01f;
  float radius = sqrt(1.0 / (uAttenuationFactor * minLight));
  float lightAdd = 0.0f;
  float dist = distance(vPosition.xyz, (uMat4Identity * vec4(uLightPosition, 1.0)).xyz);
  float att = clamp(1.0 - dist/radius, 0.0, 1.0);
  vec3 surf2light = normalize((uMat4Identity * vec4(uLightPosition, 1.0)).xyz - vPosition.xyz);
  vec3 norm = normalize(vTransformedNormal);
  float diffuseCoefficient = max(0.0, dot(norm, surf2light));
  lightAdd += att * (diffuseCoefficient + uSourceIntensity);
  vec4 textureColor = texture2D(uTex0, vec2(vTextureCoord.s, vTextureCoord.t));
  vec3 torch_output = lightAdd * uColorLight;
  vec4 final_color = (vec4(torch_output, 1.0f) * textureColor) * vVertexColor;
  gl_FragColor = final_color;

```

The shader computes point lighting with attenuation and give very satisfactory results. Look at the pic:

I give **uAttenuationFactor = 0.4f** and **uSourceIntensity = 0.2f** to get this result and it satisfies me. However, besides setting the light color, how i could modify the shader to fade-out to another color than black?? Anything i tried it just modifies the visible parts of the screen i.e. walls but the black remains unchanged. I would had liked to be able to set a grey color for rain or whitish for fog effect etc.

Thanx.

# Answer
After a number of hours, i finally found some shader way to mix both lighting and fog:

**VS:**

```
...
// fog
uniform LOWP float uFogDistance;
varying float vFogClampedDistance;
void main() {
   ...
   // fog
   if (uFogDistance >= 0.0) {
      vFogClampedDistance = clamp(gl_Position.z, 0.0, uFogDistance);
   }
}

```

**FS:**

```
...
// fog
uniform LOWP float uFogDistance;
varying float vFogClampedDistance;
void main() {
   ...
   // compute final_color by 'lighting'
   ...
   Vec4 textureColor = texture2D(uTex0, vec2(vTextureCoord.s, vTextureCoord.t));
   if (uFogDistance == 0.0) {
      gl_FragColor = ...use only lighting, not fog
   }
   else {
      gl_FragColor = mix(final_color, vec4(0.5,0.5,0.5,1.0), vFogClampedDistance/uFogDistance) * vec4(1.0,1.0,1.0,textureColor.a);
   }

```

}

I am now able to both use the lighting shader wth attenuation, plus with a very simple fog effect which works on the lighting colors. Of course where both are mixing i have to be careful not to wash the graphics out: Take a look in pics:

Even if i disable the lighting and use only *black* fog to simulate the lighting, the results resembles somehow those of lighting; while not perfect, they are blending nicely:
> 2 votes

---
Tags: glsl
---


# Question
Title: Make a Vector3 field in the inspector behave as the Transform's position
As the title suggests, I am looking to serialize on the Inspector a **Vector3** that behaves just like the **Transform's** position Vector3:

* If you modify the position **Vector3**, the **GameObject** positions itself according to the World Position.
* If you move the **GameObject** on the scene by picking the handles, the **GameObject** moves, and the position **Vector3** gets modified equal to the GameObject's position.

So, is there a way I can constrain a serialized **Vector3**, so if I modify it on the inspector I can change the **GameObject's** position, like this:

```
[ExecuteInEditMode]
public class LameExample : MonoBehaviour
{
    public Vector3 transformPosition;

    private void Update()
    {
        if(modifyingVectorOnInspector)
        transform.position = transformPosition;
        else if(gameObjectIsBeingMovedOnScene)
        transformPosition = transform.position;
    }
}

```

I've tried an approach using **Selection.contains(gameObject)**, but that does not take into account if it is dragged by the handles.

Thanks in advance for your help.

# Answer
> 1 votes
This seems to work, using the `Reset` method to initialize the position when the component is added, and `OnValidate` to react to changes made in the inspector.

```
[ExecuteInEditMode]
public class PositionMatch : MonoBehaviour {

    public Vector3 position;

#if UNITY_EDITOR
    void Reset() {
        position = transform.position;
    }

    void OnValidate() {
        if(transform.position != position) {
            UnityEditor.Undo.RecordObject(transform, "change position via variable.");
            transform.position = position;
        }
    }

    void Update () {
        if(transform.position != position) {
            UnityEditor.Undo.RecordObject(this, "change position via Transform.");
            position = transform.position;
        }
    }
#endif
}

```

Note that Unity's `==` operator for `Vector3`s has a little tolerance. If you don't want that, use `Vector3.Equals()` which uses exact equality.

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


title: Xna Spritefont from installed fonts

text:
# Question
Title: Xna Spritefont from installed fonts
I am using Spritefont in my game and I have downloaded a .ttf font and installed it on my machine. I am now using this font in my game.

My question is if this game is run on another machine will the .ttf font need to be installed on that machine to work?

# Answer
When a font is located in the content folder, and you keep the content folder along with your game, then it shouldn't be much of a problem.

Spritefonts are treated similair like images, They both remain in the contents folder.

I've used a downloadable spritefont before and I could use it on different computers without any problems. I think it's a bit depending on how you're releasing your game. (I've used the release folder after building the game in the release configuration)

I think the best way is to try it out yourself, by putting the game and the content folder on someone else's PC. :)
> 1 votes

---
Tags: c#, xna-4.0, fonts, visual-studio, spritefont
---


# Question
Title: How can I load a scene when starting a new game if the loading scene have a Main Camera?
The problem is that if I turn the camera on enabled in the editor it will show part of the scene mixed with the main menu scene. And if the loading scene main camera is enabled off I will get error Display 1 No cameras rendering.

I have two scenes in the Hierarchy. The first is Main Menu. The main menu have a camera.

Now I did that when I click on the button START A NEW GAME It will load another scene:

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

public class NewGame : MonoBehaviour
{
    public void StartNewGame(int SceneIndex)
    {
        SceneManager.LoadScene(SceneIndex);
    }
}

```

In this screenshot you can see in the Inspector I'm calling the method StartNewGame and the index 1. Index 1 present the second scene that should be load: The Space Station

Now in the scene: The Space Station I have also a MainCamera under Player. The MainCamera is turned off in the editor. And I need somehow to switch between the Main Menu scene camera and the The Space Station scene camera.

If I will turn on the MainCamera in the inspector I will see some objects of the first scene and the second scene and then the game will start without the main menu and the player will fall down.

If I start the game when the MainCamera is turned off I will the Main Menu but then when I click on START A NEW GAME it will show me the message Display 1 No cameras rendering.

The last screenshot is of the Build Settings: Edit \> Build Settings... I added the two scenes to the build. The first scene at index 0 is the Main Menu the second scene at index 1 is The Space Station:

# Answer
> 1 votes
Your StartNewGame() function does load a new scene, but you haven't specified what mode you want it to load in.

You should change your line of code from

```
SceneManager.LoadScene(SceneIndex);

```

To:

```
SceneManager.LoadScene(SceneIndex, LoadSceneMode.Single);

```

This specifies what kind of mode you want to load your scene in.

Edit: Because of this you should also enable you camera in the SpaceStation scene again

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


title: How to calculate a moving bonus limit

text:
# Question
Title: How to calculate a moving bonus limit
I'm trying to set a realistic limit on the number of bonus objects that randomly show up during a wave of enemies in my game.

With each new wave I increase the number of enemies. During each wave I have bonus objects for the player to pick up that show up at random intervals anywhere from 5 to 25 seconds apart.

The problem I have is I want a limit on the number of bonuses so that the player can't just leave a few enemies and pick up an endless amount of bonuses to increase their score. Theoretically they could kill no enemies and continuously pick up bonuses so just checking the number of enemies left won't work for me.

I've thought about a hard limit per wave, and increasing that by a certain amount as the player progresses through waves. The problem I have with that is that the player could figure this out and always get the max number of bonuses before moving to the next wave...

Does anyone have any good ideas on how to calculate a good max bonus amount or determine when to show the bonuses better than just using randomly selected time intervals? I'm trying to come up with a good pattern that allows for moving the bonus count so that it's fair but doesn't allow cheating. Or maybe I'm just overthinking it too haha.

# Answer
> 1 votes
I'd be tempted to do it like so:

* Start the level with some number of bonus tokens in a pool.
* Each enemy, on death, has a chance to add a bonus token into the pool.
* When your bonus spawner creates a new bonus item, it takes a token out of the pool, and delays the next spawn until the pool is non-empty.

This way players can't just stall enemies and collect bonuses forever: they have to keep killing enemies or the bonuses dry up. And the amount isn't fixed, so there's no set number for them to grind until they reach.

If you want more control over the number of bonuses, you can pre-allocate n bonus tokens to n randomly chosen enemies, rather than having each enemy independently roll for a chance of a token on death. As long as the player doesn't know which kills will refill the bonus pool, they can't single out those enemies to farm them while stalling non-token-holders.

# Answer
> 0 votes
Depending on the type of bonus, there are a number of different implementations you could do. For example, if you want to randomly drop ammo, you might be better off to calculate the ammount of ammo needed to kill an enemy. That way, you know the minimal amount of ammo that has been used so far in a wave. You can use that to make sure the player has used up enough ammo to warrant a new random bonus ammo drop, for which you can use a random interval off course.

Hope this helps a little bit.

# Answer
> 0 votes
> The problem I have with that is that the player could figure this out and always get the max number of bonuses before moving to the next wave...

Why, exactly, is that a problem?

Skill-based games with limited content, like most shoot-em-ups, gain most of their long term motivation through mastery of the more obscure game mechanics. Those mechanics novices are either not aware of or lack the skill to exploit effectively. A good study object in this regard are score-focused arcade shoot-em-ups like *DoDonPachi*, *Ikaruga* or the *Touhou* series. Players who play these games will usually have this skill progression:

* Beginners don't even look at their score. They just try to stay alive until the end of the stage.
* Intermediates will look at their scores and recognize opportunities to gain more score. They will take additional risks to make use of these opportunities.
* Masters don't just know about these opportunities, they also understand their exact risk/reward ratios and synergies. They don't just use them, they use them *intelligently*. They know exactly when to do what to ramp up insane high-scores others can just dream of.

They are all playing the exact same stage on the same difficulty. But they are still playing them in a completely different way. And each of them gets challenged to their skill ceiling. Games which manage to do this well are examples of great game design.

Mechanics which govern the spawning of bonus objects are one example for a mechanic the beginners can ignore, the intermediates can use and the masters can exploit. All you need to make sure is that the way to obtain the maximum number of bonus objects per wave requires not just knowledge but also skill. When you just spawn a bonus object every X seconds and don't punish the player for playing too slow, then you reward them for taking their time and punish them for playing quickly. That makes the game very boring for those who want to become masters.

Have you considered to **trigger the appearance of bonus objects through kills**? For example, every time the player kills X enemies within Y seconds, you spawn a bonus target? This also adds some adaptive difficulty to the game: The better the player is playing, the more additional targets they get to shoot. That means a skilled player will need all their skills to kill the enemies **and** the bonus targets on time. The beginner, on the other hand, who is already struggling with hitting just the normal targets, will get less additional targets, so they won't get frustrated when they don't manage to hit those too.

But if you really don't want to go down that path and make sure you always have the same number of bonus targets per wave, then pick a specific enemy per bonus target (at random or predetermined) and spawn the bonus target when that enemy is killed. If you don't want this mechanic to be too obvious, add a slight delay.

---
Tags: game-design, algorithm, level-design, balance
---


title: Dynamic Tilemap size changer

text:
# Question
Title: Dynamic Tilemap size changer
I have started coding this project using the library **SFML** a few months ago.

I have implemented a random map generation everytime I load the game thanks to Biome and the Perlin noise Algorithm.

**I wish i could increase the TileMap size on the border of the map according to the player position (Chunk system in minecraft) .**

I have managed to do it on the bottom and the right of the map :

But this isn't dynamic. There is a snap of my code where i add a new "chunck" :

```
void TileMap::AddChunckToTileSet(sf::Vector2i PlayerTile, char * direction)
{
    int previousWidth = _width;
    int previousHeight = _height;

    _height = _height + 24;
    _width = _width + 24;
    m_vertices.resize(_width * _height * 4);

    int tileNumber = 384; // ToDO

    // on en déduit sa position dans la texture du tileset
    int tu = tileNumber % (m_tileset.getSize().x / _tileSize.x);
    int tv = tileNumber / (m_tileset.getSize().x / _tileSize.x);

    if (direction == "Down")
    {

        for (int i = previousWidth; i < _width; ++i)
        {
            for (int j = previousHeight; j < _height; ++j)
            {
                // on récupère un pointeur vers le quad à définir dans le tableau de vertex
                sf::Vertex* quad = &m_vertices[(i + j * _width) * 4];

                // on définit ses quatre coins
                quad[0].position = sf::Vector2f((i - previousWidth) + PlayerTile.x * _tileSize.x, j * _tileSize.y);
                quad[1].position = sf::Vector2f(((i - previousWidth) + PlayerTile.x + 1) * _tileSize.x, j * _tileSize.y);
                quad[2].position = sf::Vector2f(((i - previousWidth) + PlayerTile.x + 1) * _tileSize.x, (j + 1) * _tileSize.y);
                quad[3].position = sf::Vector2f((i - previousWidth) + PlayerTile.x * _tileSize.x, (j + 1) * _tileSize.y);

                // on définit ses quatre coordonnées de texture
                quad[0].texCoords = sf::Vector2f(tu * _tileSize.x, tv * _tileSize.y);
                quad[1].texCoords = sf::Vector2f((tu + 1) * _tileSize.x, tv * _tileSize.y);
                quad[2].texCoords = sf::Vector2f((tu + 1) * _tileSize.x, (tv + 1) * _tileSize.y);
                quad[3].texCoords = sf::Vector2f(tu * _tileSize.x, (tv + 1) * _tileSize.y);

            }
        }
    }
}

```

I call the function AddChunckToTileSet like this :

```
void TileMap::Update(sf::Vector2i PlayerTile)
{

    if (PlayerTile.y + 15 > _height)
    {
        // Increase map on Down according to our X
        printf("Add Chunck Down\n");
        AddChunckToTileSet(PlayerTile, "Down");
    }

}

```

**Do you have any hints on how I could achieve this correctly ?**

# Answer
> 1 votes
1

The first thing you need to do is develop a method of expanding your m\_vertices array in the negative x and y direction.

One option is to pad it with an offset. As the array expands update the offset, so no value is ever less than 0. This will require you to first expand the array and move the previous data. You would access your tiles like this:

```
Tile(i, j) = &m_vertices[(i+offsetx + (j+offsety) * _width) * 4]

```

Another method would be to use 4 arrays in each quadrant and rotate them, so they expand away from each other.

2

The second thing you need to do is loop over all the tiles that need to be updated. And expand where needed. An example using offset method would look something like this...

```
min_j = min(min_j, playerTile.y-16);
max_j = max(max_j, playerTile.y+16);

if (min_j + offsety < 0) expandTileMap();
if (max_j - min_j + 1 > _height) expandTileMap();

for ( i = min_i; i <= max_i; ++i )
{
    // up
    for ( j = min_j-1; j > playerTile.y-16; --j )
    {
        doSomething(i, j);
    }
    // down
    for ( j = max_j+1; j < playerTile.y+16; ++j )
    {
        doSomething(i, j);
    }
}

min_i = min(min_i, playerTile.x-16);
max_i = max(max_i, playerTile.x+16);

if (min_i + offsetx < 0) expandTileMap();
if (max_i - min_i + 1 > _width) expandTileMap();

for ( j = min_j; j < max_j; ++j )
{
    // left
    for ( i = min_i; i < playerTile.x+16; ++i )
    {
        doSomething(i, j);
    }
    // right
    for ( i = max_i; i < playerTile.y+16; ++i )
    {
        doSomething(i, j);
    }
}

```

---
Tags: algorithm, tilemap, maps, sfml
---


# Question
Title: What do we call a feature that allows many kinds of game object to be "plugged in" modularly?
I'm currently at a very abstract level of designing a certain game (if interested, see this meta post), so my question is a bit abstract, too. But I'll provide a reasonable example, so please bear with me.

### My Description

In the game, there should be various "kinds of objects". The game would be too big to do alone, so - as I am currently working alone - I would need a high level of modularity to ensure I can later just "plug in the content". Here "content" means not something like "extended story line" but new "kinds of objects". E.g. in a game where you just have food, armor and weapons I want to add kitchen supplies, without having to touch the core code much. I'm a seasoned programmer, so I know this is hard and weird.

One way to do this would be that I would implement some sort of "template" what a "kind of object" could look like and what would be possible to do with it regarding interaction with the game world. "Kinds of objects" would be written in plain text (with a certain structure to it, e.g. XML), I could then write an interpreter for these files, so they can be loaded in runtime. Then, in the game, specific objects can be created from a "kind of object", which then can be interacted with as previously inscribed in the text files.

### Question

**I want to know the name of the feature/method described in the previous paragraph.** If possible, I would also like to get resources where I can learn more about this subject and/or which other games also use this concept. Opinions or references about how far this feature/method is helpful or not and for what games or not are appreciated, too.

I only know one game where something similar has been implemented, now presented as example of my abstract concept.

### Example for Description

YGOPro is a program where one can play the Yu-Gi-Oh! Trading Card Game. The source code for the underlying engine can be found here. As it is typical for TCGs, there are often new cards (with new effects) introduced in regular intervals while the overall rules stay the same (most of the time). YGOPro deals with this by implementing the overall rules normally and implementing an interpreter that can read and implement the various card effects, which in turn are implemented for one card at a time, see full list and example. Within a play of the card game (called "duel") within the program, specific instances of a card can have different properties due to the gameplay in general and their own and other card's effect specifically.

In comparison to my abstract idea, a "template" would be the implementation of a card, a "kind of object" would be one of the several cards, represented by their effect, and an "object" would be a specific card in the game. Of course this isn't exactly what I'm imagining, e.g. only the card effects are separately handled in files while all other base properties of the cards are stored within a database. But I think it is good enough to understand my idea.

### Why I ask this here

Note that I'm not asking "what technology some particular game used" but what it is called. I don't ask "which technology to use for \[my\] game idea" or "how to make (or start making) a particular type of game", because I thought of a concept myself, but I don't mind if you post an alternative solution in the comments. So as far as I'm concerned, this question is on topic regarding the help center.

> Would a professional game developer give me a better/different/more specific answer to this question than other programmers?

I clearly think so. My basic question, written in **bold** above, could likely be answered by other programmers as well. But my specification about how/if other games used this feature (in which case I would study these to help me understand the feature better as well as its benefits and drawbacks) or which type of games should use/avoid it, which, if asked standalone, would be considered off-topic, can provide a more specific answer and deeper insight into the topic, instead of e.g. giving me some financial program with that type of feature where I have problems seeing the analogy.

### Thank you

This question was difficult to formulate and type and I'm sure also difficult to read, so thanks for your patience. English is not my native language, so I'm very open to edit suggestions if some part of the text is especially difficult to digest (except for the "My Description" part, which is by nature of its abstraction difficult, I think).

# Answer
This sounds to me like "**data-driven design**" or "data-driven content & behaviour"

You want each kind of object to be a piece of data, rather than relying on each kind being implemented in your game's codebase.

Ways in which we often do this in games include:

* **Scripting systems** \- like in your Yu-Gi-Oh example, using an interpreter or bytecode pattern, with scripts written in text or node graphs.

These let you load completely custom behaviours at runtime, but they do place a medium bar on the technical skill required to create new content, and can result in a lot of duplicated work if you don't have shared script libraries (imagine scripting up 100 breeds of dog, each with their own version of the "bark" script).

There's also a bit of a security implication: you need to carefully vet and sandbox scripts that might have been produced outside your control, to make sure they won't corrupt the game state, break the rules beyond what you want to allow, or cause harm to the user's computer / privacy. Many mobile platforms won't allow apps that execute untrusted scripts for this reason.
* **Component systems** \- here we look at each object/kind as a collection of traits and behaviours it has. Each component is defined within your game's code, but content defined in data can combine, configure, and remix those components freely.

For instance, you might have a `Breakable` component that accepts parameters for its durability against different types of damage, an effect to fire off when it breaks (including triggering other components), and a list of other object types to spawn as fragments once it's broken.

An object data file can indicate that it should include a `Breakable` component with the following values/parameters. When spawning the object in your game, you create a new game entity, and attach to it a new instance of the `Breakable` component configured with those parameters. Then continue through the rest of the components the object's kind file specifies, adding them as it goes, assembling a complete object with arbitrarily complex combinations of behaviours.

Components put more work on the main game's code to expose an expressive, modular collection of behaviours, but lower the bar for being able to define new content with those modules, and guarantee more safety against malformed or malicious content.

You might like to look into Scribblenauts as an example of another set of games that use data-driven content to try to simulate an aggressively vast range of possible objects.
> 2 votes

---
Tags: architecture, software-engineering, terminology
---


# Question
Title: Algorithm for fitting geometrical 2d shapes like in the android game Six! (or Tetris)?
In the game Six!, there's a perfectly rectangular tower of geometrical 2d shapes, that you destroy on tap to reach the ground with your player. The easy way would be to design the levels by hand. However, I wondered how to do this with an algorithm, so that you save a lot of time? Any idea?

I use the Godot Engine 3.0, fyi.

# Answer
EDIT: Here's another solution that would be simpler but not as random. You could make a set of many large n by n uniform squares that you fill in with predefined shapes, then use the squares with different rotations to form the tower. This is a much simpler approach, but it requires you to make enough combinations to feel random, and there will be seems that aren't crossed by any shape. Unless you offset the squares every layer, or use a different shape that can fill in a tower.

---

You could place the pieces by dropping random shapes randomly across the top like in Tetris until no more shapes can be dropped, then rotate the tower and let the shapes fall back into place, then continue to drop shapes from that direction. Repeat the process until you can no longer drop shapes and fill in the remaining holes with small shapes.

If you need all shapes to fit a certain profile, then you could also remove shapes around blockages that aren't fully filled in and restart the algorithm, but it might take a long time to find a configuration that works.

Here's an algorithm for dropping shapes.

---

0 background

1 piece 1

2 piece 2

```
0 0 1 1 1 0 0
0 0 0 1 2 0 0
0 0 0 0 2 0 0
0 0 0 0 2 0 0

```

Form a matrix that defines each piece by the grid of square locations taken up by that piece.

Start by assuming all pieces are falling.

In each iteration loop through every piece to determine which pieces are definitively anchored, and stop iterating when the previous iteration finds no new anchored pieces.

To determine whether a piece is anchored, loop through every component of the piece. If any of the following conditions are true, then the piece can be considered anchored.

1. A component is in the bottom row.
2. The space below a component is from another component that is determined to be anchored.

Once you have determined which pieces are falling you can update the matrix and the scene by dropping all the components of those pieces by 1 and restart the algorithm until you have a situation where all pieces are anchored.
> 1 votes

---
Tags: 2d, android, game-design, algorithm, godot
---


title: SharpDX Y position inverted

text:
# Question
Title: SharpDX Y position inverted
I am currently drawing objects and it works perfectly, when i make x bigger the objects go right and when i make x lower they go left perfect, but when i make y bigger the object goes down and when i make y lower it goes up, i am having problems discovering the part of the code that is making y inverted.

This is the code that i use to initialize:

```
    static public BitmapManager bitmapManager;
    static public Maze CurrentScene;
    static public Sound.Sound Sound;
    static public InputManager Input;
    static public Renderer renderer;
    static public Point WindowPosition;
    static public Size WindowSize;
    static public GameTime gameTime;
    static public float DeltaTime;
    static public Hierarchy hierarchy;

    static internal RenderForm form;

    static private Device device;
    static private SwapChain swapChain;
    static private Stopwatch stopwatch;
    static private Thread UpdateThread;

    static public void Initialize(Size size)
    {
        GC.Collect();

        form = new RenderForm();
        form.StartPosition = FormStartPosition.CenterScreen;
        form.ClientSize = new System.Drawing.Size((int)size.Width, (int)size.Height);
        form.MaximizeBox = false;
        form.FormBorderStyle = FormBorderStyle.FixedSingle;
        form.FormClosed += form_FormClosed;

        SwapChainDescription SCDescription = new SwapChainDescription()
        {
            BufferCount = 1,
            ModeDescription = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
            IsWindowed = true,
            OutputHandle = form.Handle,
            SampleDescription = new SampleDescription(1, 0),
            SwapEffect = SwapEffect.Discard,
            Usage = Usage.RenderTargetOutput
        };

        Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, SCDescription, out device, out swapChain);

        Factory2D d2dFactory = new Factory2D();

        Factory factory = swapChain.GetParent<Factory>();
        factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

        Texture2D backBuffer = Texture2D.FromSwapChain<SharpDX.Direct3D11.Texture2D>(swapChain, 0);
        RenderTargetView RenderView = new RenderTargetView(device, backBuffer);

        Surface surface = backBuffer.QueryInterface<Surface>();

        RenderTarget RenderTarget2D = new RenderTarget(d2dFactory, surface,
                                                       new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)));

        form.SizeChanged += Form_SizeChanged;
        form.GotFocus += Form_GetFocus;
        form.LostFocus += Form_LostFocus;
        form.Move += Form_Move;

        WindowPosition = new Point(form.Location.X + SystemInformation.FixedFrameBorderSize.Width + SystemInformation.DragSize.Width,
                                   form.Location.Y + SystemInformation.FixedFrameBorderSize.Height + SystemInformation.CaptionHeight + SystemInformation.DragSize.Height);

        WindowSize = size;
        renderer = new Renderer(RenderTarget2D);
        Input = new InputManager();
        Sound = new Sound.Sound();
        bitmapManager = new BitmapManager(RenderTarget2D);

        hierarchy = new Hierarchy();

        gameTime = new GameTime();
        stopwatch = new Stopwatch();
        stopwatch.Start();
    }

```

and this is the code i use to render:

```
RawMatrix3x2 CurrentTransform = renderTarget.Transform;
Sprite NewSprite = Component as Sprite;
Bitmap Texture = Game.bitmapManager.GetTexture(NewSprite.texture.TexturePath);
RawRectangleF PositionRectangle = new Rectangle(new Point(0, 0), new Size(NewSprite.texture.TextureSize * Zoom)).ToRawRectangleF();
float Transparency = NewSprite.Transparency;
RawRectangleF ImageRectangle = new Rectangle(new Point(0, 0), new Size(NewSprite.texture.TextureSize * Zoom)).ToRawRectangleF();
Vector2 NewScale = (Vector2)Gameobject.transform.Scale;
Matrix3x2 Translation = Matrix3x2.Translation((Vector2)Gameobject.transform.Position);
Matrix3x2 Rotation = Matrix3x2.Rotation(Gameobject.transform.Rotation.X);
Matrix3x2 Scale = Matrix3x2.Scaling((Vector2)Gameobject.transform.Scale);
renderTarget.Transform = (Translation * Rotation * Scale).ToRawMatrix3x2();
renderTarget.DrawBitmap(Texture, PositionRectangle, Transparency, BitmapInterpolationMode.NearestNeighbor, ImageRectangle);
renderTarget.Transform = CurrentTransform;

```

If you need anything else please warn me

# Answer
You haven't done anything wrong, the direct2d coordinate space origin is in the upper left and the y axis increases downward. From the direct2d documentation:

> Direct2D uses a left-handed coordinate space; that is, positive x-axis values increase to the right and positive y-axis values increase downward. Everything on the screen is positioned relative to the origin, which is the point where the x-axis and y-axis intersect (0, 0), as shown in the following illustration. Direct2D render targets use this coordinate space.
> 0 votes

---
Tags: directx, directx11, sharpdx, direct2d
---


# Question
Title: How do I exchange information between JavaScript front end and C++ back end?
I am trying to make a chess like 2-player game that has game logic written in C++ and front end in JavaScript. How do I exchange information between the two? I am not familiar with network programming, so resources regarding that would be helpful as well.

# Answer
> 1 votes
Just use WebSockets directly.

In C++ you can use µWebSockets to create a server. In JavaScript you can use the WebSocket object to connect to the server and send messages.

---
Tags: c++, javascript, server
---


# Question
Title: Idle/Clicker games, supporting numbers many factors bigger than trillions in C# using Unity
Apologies for sloppy work and probably a poor grasp of fundamentals.

I have a (likely primitive) way to convert the ever increasing number values of my enemy hp into a string format to display in game. (K for thousands, M for millions, B for billions etc)

```
 if (target_healthmax >= 1000)
     {
         if (target_healthmax >= 1000000000)
         {
             enemy_hp_text.text = "Health: " + (target_healthcur * 0.000000001f).ToString("#.00") + "/" + (target_healthmax * 0.000000001f).ToString("#.00") + "B";
         }
         else
         {

             if (target_healthmax >= 1000000)
             {
                 enemy_hp_text.text = "Health: " + (target_healthcur * 0.000001f).ToString("#.00") + "/" + (target_healthmax * 0.000001f).ToString("#.00") + "M";
             }
             else
             {
                 enemy_hp_text.text = "Health: " + (target_healthcur * 0.001f).ToString("#.00") + "/" + (target_healthmax * 0.001f).ToString("#.00") + "K";
             }
         }
     }
     else
     {
         enemy_hp_text.text = "Health: " + target_healthcur + "/" + target_healthmax;
     }

```

but I stopped here after I noticed that although I could convert long numbers I would eventually hit a number too large to handle such as "-2.147484e+09" in my editor, and it would stop working.

I am using floats currently, is there a different type of variable that handles this easily? if not, what is an efficient way of solving this?

Would it be efficient to convert every new factor of 100 to a new variable and only handle the highest valued variable? eg

```
if num >= 1000, k += 1, num = 0;

 if k>= 1000, m += 1, k = 0;
 ...

```

(Please feel free to let me know anything about my post I may need to amend, I am new here)

# Answer
> 0 votes
> -2.147484e+09

That looks like the maximum of a 32-bit signed integer. are you sure `target_healthmax` is a float?

A 32-bit float should give you something like a 38-digit value, and a 64-bit double will give you a 308-digit value.

# Answer
> 0 votes
If you need really big numbers, you need a BigNumber library.

I've been using this one myself, although there may be some bugs in it. I've attempted to open issues and get fixes in, but the author doesn't look to be around any more.

They're easy things to fix (check the issues tab, the first two are the ones I've reported and has enough information to apply the fixes), though it may be worth looking for a different library instead. I founds that one when I was looking for one that was already in C# and would work on Unity's .NET version (if you use Unity 2017 or newer, you should be able to use Microsoft's own System.Numerics library).

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


# Question
Title: How to Prevent Sticking to Overhead Slopes
I am having an issue with overhead slopes in my 2D platformer.

I implement slopes using a LineSegment class. My player sprite has a spine attribute which is just a line segment from the midtop of his bounding rect to its midbottom. If this spine ever intersects a slope's line segment, the sprite is adjusted upwards or downwards so that his midtop or midbottom is at the intersection point. To determine which direction to adjust, I look at where the previous bounding rect's center is in relation to this intersection point.

```
def collide_with_slopes(sprite, slopes):

    # create midline for the sprite
    spine = LineSegment(sprite.game, sprite.midtop, sprite.midbottom)

    # check if midline intersects any slope
    slopes = [slope for slope in slopes if spine.intersects_segment(slope)]

    if slopes:
        slope = slopes[0]
        intersection_point = spine.intersects_segment_at_point(slope)

        # sprite above slope
        if sprite.previous_bounding_rect.centery < intersection_point.y:

                sprite.on_slope = True
                sprite.pos.y = intersection_point.y - sprite.bounding_rect.height/2
                sprite.vel.y = 0

        # sprite below slope
        elif sprite.previous_bounding_rect.centery > intersection_point.y:

                sprite.on_slope = False
                sprite.pos.y = intersection_point.y + sprite.bounding_rect.height/2 + 1
                sprite.vel.y = 0

    elif not slopes:
        sprite.on_slope = False

```

This approach works well for slopes under the player, but I am having an issue with overhead slopes.

They work fine when the player jumps without horiztonal movement.

The problem is when the player is moving in the same direction that the overhead slope descends.

The sprite sticks to the ceiling and glides down the slope as if zip-lining.

I believe the problem is that even after slope resolution, if the player is pressing right, the sprite's new position will still be intersecting the slope on the subsequent frame, causing the slope code to keep readjusting the midtop point to be on the slope.

**How can I fix this issue?**

---

I have tried adjusting the sprite down a few extra pixels upon upward collision with a slope, but the result looks and feels bad.

I have also tried decomposing the update to my position into its x and y component, and only checking for slope intersections after one or the other. This did not solve the issue.

# Answer
> 0 votes
What I usually do when it comes to collision-detection is to first add the x velocity to the position then check if that is intersecting. If it is, set the x velocity to 0. Then do the same for y only.

```
if sprite.pos + sprite.vel.y intersects line:
    sprite.vel.y = 0

if sprite.pos + sprite.vel.x intersects line:
    sprite.vel.x = 0

sprite.pos += sprite.vel

```

---
Tags: collision-detection, physics, python, collision-resolution
---