title: Isometric scene in SpriteKit

text:
# Question
Title: Isometric scene in SpriteKit
I tried play with spritekit in isometric grid. But i can't understand how to fix level.

```
import SpriteKit
import XCPlayground

let view:SKView = SKView(frame: CGRectMake(0, 0, 1024, 768))
XCPlaygroundPage.currentPage.liveView = view

func + (left: CGPoint, right: CGPoint) -> CGPoint {
  return CGPoint(x: left.x + right.x, y: left.y + right.y)
}

func - (left: CGPoint, right: CGPoint) -> CGPoint {
  return CGPoint(x: left.x - right.x, y: left.y - right.y)
}

func * (point: CGPoint, scalar: CGPoint) -> CGPoint {
  return CGPoint(x: point.x * scalar.x, y: point.y * scalar.y)
}

func / (point: CGPoint, scalar: CGPoint) -> CGPoint {
  return CGPoint(x: point.x / scalar.x, y: point.y / scalar.y)
}

enum Tile: Int {

  case Ground
  case Wall

  var description:String {
    switch self {
    case Ground:
      return "Ground"
    case Wall:
      return "Wall"
    }
  }

  var image:String {
    switch self {
    case Ground:
      return "ground"
    case Wall:
      return "wall"

    }
  }
}

class GameScene: SKScene {

  //1
  required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

  //2
  let view2D:SKSpriteNode
  let viewIso:SKSpriteNode

  //3
  let tiles = [
    [6, 1, 0, 0, 0],
    [1, 1, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0]
  ]
  let tileSize = (width:32, height:32)

  //2
  override init(size: CGSize) {

    view2D = SKSpriteNode()
    viewIso = SKSpriteNode()

    super.init(size: size)
    self.anchorPoint = CGPoint(x:0.5, y:0.5)
  }

  //5
  override func didMoveToView(view: SKView) {

    let deviceScale = self.size.width/667

    view2D.position = CGPoint(x:-self.size.width*0.25, y:self.size.height*0.17)
    view2D.xScale = deviceScale
    view2D.yScale = deviceScale
    addChild(view2D)

    viewIso.position = CGPoint(x: 50, y: 50)
    viewIso.xScale = deviceScale
    viewIso.yScale = deviceScale
    addChild(viewIso)

    placeAllTiles2D()
    placeAllTilesIso()
  }

  func placeTile2D(image:String, withPosition:CGPoint) {

    let tileSprite = SKSpriteNode(imageNamed: image)

    tileSprite.position = withPosition

    tileSprite.anchorPoint = CGPoint(x:0, y:0)

    view2D.addChild(tileSprite)

  }

  func placeAllTiles2D() {

    for i in 0..<tiles.count {

      let row = tiles[i];

      for j in 0..<row.count {
        var tileInt = row[j]

        if (tileInt > 1) {
          tileInt = 1
        }

        //1
        let tile = Tile(rawValue: tileInt)!

        //2
        let point = CGPoint(x: (j*tileSize.width), y: -(i*tileSize.height))

        placeTile2D(tile.image, withPosition:point)
      }

    }

  }

  func point2DToIso(p:CGPoint) -> CGPoint {

    //invert y pre conversion
    var point = p * CGPoint(x:1, y:-1)

    //convert using algorithm
    point = CGPoint(x:(point.x - point.y), y: ((point.x + point.y) / 2))

    //invert y post conversion
    point = point * CGPoint(x:1, y:-1)

    return point

  }

  func pointIsoTo2D(p:CGPoint) -> CGPoint {

    //invert y pre conversion
    var point = p * CGPoint(x:1, y:-1)

    //convert using algorithm
    point = CGPoint(x:((2 * point.y + point.x) / 2), y: ((2 * point.y - point.x) / 2))

    //invert y post conversion
    point = point * CGPoint(x:1, y:-1)

    return point

  }

  func placeTileIso(image:String, withPosition:CGPoint) {

    let tileSprite = SKSpriteNode(imageNamed: image)

    tileSprite.position = withPosition

    tileSprite.anchorPoint = CGPoint(x:0, y:0)

    viewIso.addChild(tileSprite)
  }

  func placeAllTilesIso() {

    for i in 0..<tiles.count {

      let row = tiles[i];

      for j in 0..<row.count {
        var tileInt = row[j]

        if (tileInt > 1) {
          tileInt = 1
        }

        let tile = Tile(rawValue: tileInt)!

        //        if (tile.rawValue == Tile.Wall.rawValue) {

        let index = tileSize.height

        for int in (0..<row[j]).reverse() {

          let x = (j*tileSize.width) + index * int

          let y = -(i*tileSize.height + index  * int)

          print("index = \(int) height: \(row[j]) x: \(x) y: \(y)")

          let pointx = point2DToIso(CGPoint(x: x, y: y))
          placeTileIso(("iso_"+tile.image), withPosition:pointx)

        }

//        let pointx = point2DToIso(CGPoint(x: (j*tileSize.width) + tileSize.height, y: -(i*tileSize.height + tileSize.height)))
//
//
//        placeTileIso(("iso_ground"), withPosition:pointx)

      }
    }
  }
}

let scene:SKScene = GameScene(size: CGSizeMake(2048, 1024))
scene.scaleMode = SKSceneScaleMode.AspectFit
view.presentScene(scene)

```

In result i have:

But need draw block as level in matrix

As matrix levels:

```
  let tiles = [
    [6, 1, 0, 0, 0],
    [1, 1, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0]
  ]

```

All sources in github git@github.com:rmuhamedgaliev/IsoWorld.git

# Answer
> -1 votes
I fixed it:

```
import SpriteKit

func + (left: CGPoint, right: CGPoint) -> CGPoint {
  return CGPoint(x: left.x + right.x, y: left.y + right.y)
}

func - (left: CGPoint, right: CGPoint) -> CGPoint {
  return CGPoint(x: left.x - right.x, y: left.y - right.y)
}

func * (point: CGPoint, scalar: CGPoint) -> CGPoint {
  return CGPoint(x: point.x * scalar.x, y: point.y * scalar.y)
}

func / (point: CGPoint, scalar: CGPoint) -> CGPoint {
  return CGPoint(x: point.x / scalar.x, y: point.y / scalar.y)
}

enum Tile: Int {

  case Ground
  case Wall

  var description:String {
    switch self {
    case Ground:
      return "Ground"
    case Wall:
      return "Wall"
    }
  }

  var image:String {
    switch self {
    case Ground:
      return "ground"
    case Wall:
      return "wall"

    }
  }
}

class GameScene: SKScene {

  required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

  let viewIso:SKSpriteNode

  let tiles = [
    [9, 8, 1, 1, 9],
    [8, 8, 1, 1, 1],
    [1, 1, 1, 1, 1],
    [1, 1, 1, 1, 1],
    [2, 1, 8, 1, 1]
  ]

  let tileSize = (width:32, height:32)

  override init(size: CGSize) {
    viewIso = SKSpriteNode()
    super.init(size: size)
  }

  override func didMoveToView(view: SKView) {

    let deviceScale = self.size.width/667

    viewIso.position = CGPoint(x: 200, y: 200)
    viewIso.xScale = deviceScale
    viewIso.yScale = deviceScale
    addChild(viewIso)

    placeAllTilesIso()
  }

  func point2DToIso(p:CGPoint, inverse: Bool) -> CGPoint {

    //invert y pre conversion
    var point = p * CGPoint(x:1, y:-1)

    //convert using algorithm
    point = CGPoint(x:(point.x - point.y), y: ((point.x + point.y) / 2))

    //invert y post conversion
    if (!inverse) {
      point = point * CGPoint(x:1, y:-1)
    } else {
      point = point * CGPoint(x:1, y:-1)
    }

    return point

  }

  func placeTileIso(image:String, withPosition:CGPoint) {
    let tileSprite = SKSpriteNode(imageNamed: image)
    tileSprite.position = withPosition
    tileSprite.anchorPoint = CGPoint(x:0, y:0)
    viewIso.addChild(tileSprite)
  }

  func placeAllTilesIso() {
    for i in 0..<tiles.count {
      let row = tiles[i];
      for j in 0..<row.count {
        var tileInt = row[j]
        if (tileInt > 1) {
          tileInt = 1
        }

//        let tile = Tile(rawValue: tileInt)!

        if (tileInt > 0) {
          let index = tileSize.height

            let xxx = ((j*tileSize.width) + index * 0)
            let yyy = -(i*tileSize.height + index  * 0)

            print("index = \(0) height: \(row[j]) xxx: \(xxx) yyy: \(yyy)")

            let pointxxx = point2DToIso(CGPoint(x: xxx, y: yyy), inverse: false)
            placeTileIso(("iso_wall"), withPosition:pointxxx)

          if (row[j] > 1) {

            if (j > 0 || i > 0) {
                for indexs in (0..<row[j]){
                    let xx = ((j*tileSize.width) + index * (-indexs))
                    let yy = -(i*tileSize.height + index  * (-indexs ))

                    print("index = \(0) height: \(row[j]) xx: \(xx) yy: \(yy)")

                    let pointxx = point2DToIso(CGPoint(x: xx, y: yy), inverse: false)
                    placeTileIso(("iso_wall"), withPosition:pointxx)
                }
            } else {
                for indexs in (1..<row[j]) {
                    let xx = -((j*tileSize.width) + index * indexs)
                    let yy = (i*tileSize.height + index  * indexs)

                    print("index = \(0) height: \(row[j]) xx: \(xx) yy: \(yy)")

                    let pointxx = point2DToIso(CGPoint(x: xx, y: yy), inverse: false)
                    placeTileIso(("iso_wall"), withPosition:pointxx)
                }
            }
          }

        }

        }
    }
  }
}

```

---
Tags: algorithm, sprites, ios, isometric, spritekit
---


# Question
Title: SceneGraph in Entity Component System, Transformations
I'm recently learning entity component systems, and started implementing it into my test engine, however I'm having an issue integrating this with scene-graph, which I'm trying for the first time.

All my entities have a `TransformComponent` which transforms the entity in the scene, with it's position, rotation and scale. This is how I'm doing this:

```
transform.reset();

Entity entity = this.entity;

while (entity != null)
{
    if (!lockScale) transform.scale(entity.scale);
    if (!lockRotation) transform.rotate(Vector3.AXIS_Z, entity.rotation);
    if (!lockPosition) transform.translate(entity.position);

    entity = entity.parent;
}

```

The `TransformComponent` is present for all the entities, and hence it cannot be removed from the entity, I restrict it.

Now I have another component, called as `CollisionComponent` which contains the polygon, and a callback when a collision occurs, along with a collision tag. It updates the polygon position upon update:

```
polygon.setPosition(entity.position);
polygon.setRotation(entity.rotation);
polygon.setScale(entity.scale);

```

This is working for all the entities that are in the scene root, they are displayed at their correct positions, and also the collisions are working. The issue starts with the entity's children if they are present.

I have attached a child entity with position set to (0, 50) whose coordinate system is local to the parent entity system. But here, the graphics work correctly, on rotating the parent, the children rotate too due to the transform matrix, but the polygon stays at the local position.

The solution that I'm thinking now is to make the entity positions in global coordinate system, even if they are in the children of an entity, and have the transform change correctly even when the parent moves.

How can I do that?

# Answer
I found my issue after getting some sleep, I forgot to take care of the parents in the `CollisionComponent`. All I had to do is to iterate up in the entity heirarchy chain (scene graph nodes) and apply the parent transforms to the polygon.

```
// Get some temporary Vector objects to work from the object pool
Vector2 tPosition = Vector2.REUSABLE_STACK.pop();
Vector2 tScale = Vector2.REUSABLE_STACK.pop();

// The temporary rotation variable
float rotation = 0;

// Set the entity properties into the temporary ones
tPosition.set(entity.position);
tScale.set(entity.scale);
rotation += entity.rotation;

// Get the parent of this entity
Entity parent = entity.parent;

// Iterate while the parent is not null and apply it's transforms
while (parent != null)
{
    rotation += parent.rotation;
    tScale.scale(parent.scale.x, parent.scale.y);
    tPosition.rotate(parent.rotation).add(parent.position);

    parent = parent.parent;
}

// Apply the transforms into the polygon
polygon.setCenter(tPosition);
polygon.setScale(tScale);
polygon.setRotation(rotation);

// Push back the temporary vectors into the object pool
Vector2.REUSABLE_STACK.push(tPosition);
Vector2.REUSABLE_STACK.push(tScale);

```

And this is how it looks in the screenshot:
> 1 votes

---
Tags: java, entity-system, transformation, scene-graph
---


# Question
Title: Black screen when switching from fullscreen to windowed mode with libgdx
I have just started working with libgdx, and have run into my first problem. I have a simple program that switches a desktop application from windowed mode to fullscreen and back again. If I start the program in windowed mode, it initially displays fine. When I toggle to full screen it is also OK.

However, when I toggle back to windowed mode the screen goes completely black. The application remains responsive though, and if I toggle again it will go back to fullscreen and display correctly.

I am using 64-bit Windows 7 with the IntelliJ IDEA IDE.

Any help with working out why it is doing this would be greatly appreciated.

A minimal example that displays the issue is shown below:

```
public class MyGdxGame extends ApplicationAdapter {

    @Override
    public void create () {
        fullScreen = false;
    }

    @Override
    public void render () {
        Gdx.gl.glClearColor(1, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        if (Gdx.input.isKeyPressed(Input.Keys.TAB)) {
            fullScreen = !fullScreen;
            DisplayMode currentMode = Gdx.graphics.getDesktopDisplayMode();
            Gdx.graphics.setDisplayMode(currentMode.width, currentMode.height, fullScreen);
    }
}

private boolean fullScreen;
}

```

# Answer
I've run into this problem on certain displays, while it had worked just fine on other displays.

My specific situation was a little different and was that I was trying to switch from 1280x1024 fullscreen to 800x600 windowed and the screen went black during the transition from fullscreen to windowed mode.

A borderless window configuration enveloping the whole screen had the exact same issue as well for me. (Transitioning from borderless fullscreen window to plain window mode)

The thing that worked for me was switching from fullscreen mode to another fullscreen mode but with the adjusted resolution, then immediately switching to the same resolution but without fullscreen enabled.

So in effect I called the `setDisplayMode()` method twice in succession.

i.e. (with hard coded values):

```
Gdx.graphics.setDisplayMode(800, 600, true);
Gdx.graphics.setDisplayMode(800, 600, false);

```

All in all it seems like a display-specific issue.
> 1 votes

# Answer
```
       Boolean fullScreen = Gdx.graphics.isFullscreen();
        Graphics.DisplayMode currentMode = Gdx.graphics.getDisplayMode();
        if (fullScreen == true)
            Gdx.graphics.setWindowedMode(currentMode.width, currentMode.height);
        else
            Gdx.graphics.setFullscreenMode(currentMode);

```
> 1 votes

---
Tags: libgdx
---


# Question
Title: Libgdx shaperender within a circle as limitter
I encountered a problem, where my small entities would be rendered out of the bounds of my radar.

At the time I solved it like this: ensure, that the object would be within the circle, but, that's not optimal, because I need variable scale for different entitie sizes, which causes further problems to be solved.

So is there a way, that I can do the following:

> draw all items within the circle and ensure that nothing is drawn outside

I thought about something, like a circle canvas, which draws all, but displays only that, which is in the bounds.

The points and lines within the circle are of a variable width / height. I'd prefer to draw everything, and cut the other stuff off.

Thanks in advance!

€dit: Gosh forgot an important thing: I draw the items with a shaperenderer, and all things are rect's , and it probably wont be polygons

# Answer
> 1 votes
I did it! Yay, I'm so proud! :P

Ofc I didn't stopped to google, and I found my answer in a depth buffer.

What I'm currently doing is the following stuff

```
    Gdx.gl.glClearDepthf(1f);
    Gdx.gl.glClear(GL20.GL_DEPTH_BUFFER_BIT);

    //1. set the function to LESS
    Gdx.gl.glDepthFunc(GL20.GL_LESS);

    //2. enable depth writing
    Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);

    //3. Enable depth writing, disable RGBA color writing
    Gdx.gl.glDepthMask(true);
    Gdx.gl.glColorMask(false, false, false, false);

    shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
    shapeRenderer.setColor(1f, 0f, 0f, 0.5f);
    shapeRenderer.circle(x, y, radius);
    shapeRenderer.end();

```

That enables my circular clipping area

now I draw some shapes:

```
shaperenderer.begin();
Gdx.gl.glColorMask(true, true, true, true);

//4. Make sure testing is enabled.
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);

//5. Now depth discards pixels outside our masked shapes
Gdx.gl.glDepthFunc(GL20.GL_EQUAL);
shaperenderer.rect(x,y,width,height);
shaperender.end();

```

And finally you need to disable the depth func, so it's only for this specific purpose, which is clipped

```
  Gdx.gl.glDepthFunc(GL20.GL_ALWAYS);

```

I got my informations out of this github project: github

So props to mattdesl!

---
Tags: java, libgdx, rendering, maps
---


# Question
Title: Do two balls of different mass bounce different heights?
There are two balls and the only difference between them is the mass. Both are dropped from the same height on to the floor (static object with infinite mass), would both balls bounce up to the same height, or would the heavier ball bounce higher as it enters the collision with more momentum?

From my own derivation it would appear that the calculation reduces down to a simple vector reflection about the contact normal, but it doesn't feel right. Can anyone verify this?

EDIT:

To be clearer, I am looking for a code sample of how to resolve a ball collision against a plane using a collision impulse. Does the collision impulse rely on the ball's mass when colliding with an object of infinite mass?

# Answer
The answer to your question is: **no**, as long as the system you're referring to implies no friction, there are no external forces, and the material the two ball are made of can be ignored.

In Classical Mechanics, the linear momentum of a body (any object) is defined as mass times velocity, ***p* *=* *mv***, and it is a vector, so that you can consider the linear momentum of an object as the sum of its components along the system axes (*x* and *y*, for example).

One of the common reasons linear momentum exists is to deal with collisions between objects, as there's need to give each object involved a magnitude of 'something' to compute the final state of the system, thus the speed and direction of an object after a collision.

Physicists (and matematicians too...) obtained a nice formula to get the velocity of two object *O1* and *O2* after they collide each other by working out the equation system of the two objects' linear momenta and their kinetic energy, there it is:

Here, *v* is the velocity vector, *m* the mass, *f* and *i* stand for 'final' and 'initial', thus after and before the collision occurs respectively. The indexes *1* and *2* are used to refer to one of the two objects you are considering for the collision. There's no difference about who is object 1 or 2, as long as you still refer to the same object during the calculations. Also, this formula can be used to compute collision between more than two objects by working on their couples. For example, if three ojects collide each other at the same time, all you need to do (although this is just an approximation) is to apply the formula to object 1 and 2, 1 and 3, and finally to object 2 and 3.

Anyway, if you figure out this formula, you will notice that any final velocity depends on the object masses, but if you consider the two masses the same, velocities are just exchanged betweeen the two objects as final result.

Back to your question. What ball will jump higher? Let's have two schemes, the first is the collision between ball 1 and the pavement, the second one between ball 2 and the same pavement. For each scheme, we'll consider the pavement indexed as '2' in the formulas. Since the pavement has infinite mass, someone would be in trouble multiplying or dividing by infinite. We could apply mathematical calculus to obtain the velocities, *OR* we can rely on the Law of Conservation of Linear Momentum which says that inside an isolated system (a system where there's no friction) the momenta of every object is conserved entirely.
That means that an object with momentum *mv* directed downwards (the ball) collides with a fixed non-moving object with infinite mass (the pavement) should still have a momentum of *mv* regardless of the sign. And since the pavement is not supposed to move, the ball is then moving upwards with the same speed, despite several balls may have different masses.

So, your two balls will bounce to the same height, as equations of motion tell us.

As for the sample code, you can just adapt the above formula so that every object involved performs the first equation only on itself, where the object calling the function has index 1 and the other has index 2 referred to the formula:

```
    ...
    Ball a = new Ball(5);        // Mass is 5
    Ball b = new Ball(8);        // Mass is 8
    ...
    if (collision(a,b)) {        // Any collision check algorithm
        a.collide(b);            // Call
        b.collide(a);            // Call
    }
    ...

```

Your function may look somehow like this:

```
    void collide(Object other) {
        this.speed = (this.mass-other.mass)/(this.mass+other.mass)*this.speed+(2.0*other.mass/(this.mass+other.mass))*other.speed;
    }

```

This is just a hint about how to write your code; you can think of any possible implementation depending on your needs.

**BUT**, if you want to better simulate reality, your balls should bounce at different heights as time goes on. Any collision between two objects depends not only on masses and velocities, but also on centers of mass, angular momentum, friction, and the materials the objects are made of. A steel ball and a wood ball will bounce lower than a tennis ball, but that's because of the coefficient of restitution, the energy loss due to the sound of impact and heat generated... But that's physics stuff, as much interesting as boring (well, not for everybody). Usually you would implement a friction system so that a ball will stop sometime in the future when rolling on the floor, but that will influence the motion attitude of the ball too. I suggest further readings if you want to deepen this argument.
> 2 votes

# Answer
It is generally assumed that the mass does not matter and they bounce up to the same height. This is because the coefficient of restitution, which lets you calculate the velocity change after the collision, does not depend on mass. The velocity right after the collision determines the height that the ball will move up to, independent of the mass (just like how mass does not affect free fall duration). So, for games, it's safe to assume that they will end up at the same height.

However, in real life, it can be hard to make the two have the same contact properties and balls with different masses may end up bouncing to slightly different heights. This paper can provide further insight.
> 1 votes

# Answer
They won't necessarily. It doesn't depend on the actual mass. The important part is their elasticity as well as the applied friction.

The mass would come into play, but only if the difference between the balls and the surface are rather small.

So if you assume the ground or wall has infinite mass (i.e. it won't move), then the mass of the balls won't play into this at all (or, realstically, almost no effect).

Of course, everyone knows some piece of metal will drop faster than a feather, but this is mainly due to different shapes (air resistance!). In a vaccum everything accelerates (and falls) with the same speed (9.81 m/s² on Earth).

Given the same impact speed and elasticity/restitution, both would bounce back with the same force and therefore fly up the same height. In the real world this isn't always exactly true, even if you ignore air resistance, since the different weights can modify the actual impact (for example, the heavier ball might squeeze more upon impact).

How about some terms?

If you want proofs, just look at the actual free fall:

> h(t) = h(0) - 0.5 * g * t2
>
> v(t) = v(0) - g * t

As you can see, the actual height (and with that the acceleration and velocity) depends on the gravity `g` as well as the time passed `t`. However, mass doesn't play into this.

For the actual impact, the important rule is the conservation of momentum:

Let's start with the energy of the impact:

> Ekin = m * v

Since no energy is lost (perfect case), this means the ball will bounce back obtaining the same amount of energy. Due to the mass being constant, the velocity will be the same as well (just with changed direction).

For a more realistic simulation, you'll most likely want to add in some friction though. Due to this the ball won't bounce back with 100% energy, but maybe 90% instead (the actual value can be adjusted to simulate different materials).
> 1 votes

# Answer
How much an object bounces doesn't depend on its mass but rather on its material. When you create a physics engine, you usually model "bouncyness" by a factor of speed which is retained when the object collides with the ground. When the object hits the ground, you invert its speed and multiply it with the "bounce-factor" of its material.

A rubber ball with a high bouncyness would have a "bounce-factor" of close to one, like 0.9.

The "bounce-factor" of an NBA-conform basketball is 0.722 (the official definition is that it bounces to 1300mm when dropped from 1800mm).

A bowling ball which just bounces a tiny bit when dropped from a high height would have a very low "bounce-factor" like 0.1.

An object which doesn't bounce at all, like a hacky-sack, would have a bounce-factor of 0.0.

The "correct" bounce-factor for each material should be found out through experimentation. Just tinker with it until it "feels" right.
> 1 votes

---
Tags: physics, collision-resolution
---


# Question
Title: Libgdx Sprite rotation around specific point
I made complex dynamic body that rotates around other body that is static. It works perfectly, however I got messed up with sprite position on that body. Here's what I have now

and here's what I need to have

I will add my code

```
private Body createSide(float x, float y, Sprite tmpSprite, boolean sharp){
      BodyDef bDef = new BodyDef();
      bDef.type = BodyDef.BodyType.DynamicBody;

    PolygonShape shape = new PolygonShape();
    if(!sharp){
        shape.setAsBox(1.8f / PPM, 0.2f / PPM);
    } else {
        shape.setAsBox(0.2f / PPM, 1.8f / PPM);
    }

    FixtureDef fdef = new FixtureDef();
    fdef.shape = shape;

    bDef.position.set(x, y);
    Body body = world.createBody(bDef).createFixture(fdef).getBody();
    body.setAngularVelocity(-1f);
    tmpSprite.setPosition(bDef.position.x * 32, bDef.position.y * 32);
    return body;
}

private void createBody(int y, final int V_WIDTH){
        staticBody = createStaticBody(y, V_WIDTH);
        Body rightSide = createSide(5.5f, 15, sprites[0], true);
        Body leftSide = createSide(9.5f, 15, sprites[1], true);
        Body top = createSide(7.5f, 17, sprites[2], false);
        Body bottom = createSide(7.5f, 13, sprites[3], false);

        bodies[0] = rightSide;
        bodies[1] = leftSide;
        bodies[2] = top;
        bodies[3] = bottom;

...
...
...
    }

```

and here's my draw method

```
@Override
    public void draw(SpriteBatch sb) {
        for (int i=0; i<bodies.length; i++){
            sprites[i].setRotation(bodies[i].getAngle() * MathUtils.radiansToDegrees);
            sprites[i].draw(sb);
        }
    }

```

# Answer
Ok, after 4 hours of searching finally I found the mistake. Problem was with the sprite origin. Here's the line that was necessary (staticBody is the body around other bodies will rotate)

```
tmpSprite.setOrigin(staticBody.getPosition().x / 32 + tmpSprite.getWidth() / 2,
                staticBody.getPosition().y / 32 + tmpSprite.getHeight() / 2);

```

And here's full code

```
private Body createSide(float x, float y, Sprite tmpSprite, boolean sharp){
        BodyDef bDef = new BodyDef();
        bDef.type = BodyDef.BodyType.DynamicBody;

        PolygonShape shape = new PolygonShape();
        if(!sharp){
            shape.setAsBox(1.8f / PPM, 0.2f / PPM);
        } else {
            shape.setAsBox(0.2f / PPM, 1.8f / PPM);
        }

        FixtureDef fdef = new FixtureDef();
        fdef.shape = shape;

        bDef.position.set(x, y);
        Body body = world.createBody(bDef).createFixture(fdef).getBody();
        body.setAngularVelocity(1f);
        //body.setFixedRotation(true);
        tmpSprite.setX(body.getPosition().x * 32 - tmpSprite.getWidth());
        tmpSprite.setY(body.getPosition().y * 32 - tmpSprite.getHeight());
        tmpSprite.setOrigin(staticBody.getPosition().x / 32 + tmpSprite.getWidth() / 2,
                staticBody.getPosition().y / 32 + tmpSprite.getHeight() / 2);
        return body;
    }

    @Override
    public void draw(SpriteBatch sb) {
        for (int i=0; i<sprites.length; i++){
            float xball = 32 * (bodies[i].getPosition().x) - sprites[i].getWidth()/2;
            float yball = 32 * (bodies[i].getPosition().y) - sprites[i].getHeight()/2;
            sprites[i].setRotation(bodies[i].getAngle() * MathUtils.radiansToDegrees);
            sprites[i].setPosition(xball, yball);
            sprites[i].draw(sb);
        }
    }

```
> 2 votes

---
Tags: java, libgdx, sprites, box2d, rotation
---


# Question
Title: How do I make sure the player model only moves 1 unit?
I am doing a school assignment based off of the Unity3D tutorial 2D RogueLike (all code available here)

In my version though, the movement is not turnbased and I am having some trouble figuring it out.

If I I make the player lose its turn after movement, the character will stay perfectly aligned with the grid. But if I let the player keep his turn, the character moves in increments not in alignment with anything(ór how long the computer think I held down the movebutton for).

I tried to fix it with this:

```
    GameManager.instance.playersTurn = false;

    Thread.Sleep(500);

    GameManager.instance.playersTurn = true;

```

and it sort of 'fixes' it. It now only moves 1 unit, provided I don't hold down the movebutton for longer than the 500ms, hereafter it seems to 'lose sync' with the board again... Also, it now takes 500ms from i press move, till the character actually moves.

Here is an example of how it looks if i just quickly tap the button to move(so its in sync)

and here is one when i held down the button for more than the 500ms ( out of sync)

So the specific question.

How do I make sure that the character only moves 1 tile/unit with a single button press?

I would greatly appreciate a solution to this

# Answer
> 1 votes
**Disclaimer**: Coded in 3D, converted to 2D

You could use IEnumerator. Like this:

```
public const float stepDuration = 0.5f;
private Coroutine playerMovement;

private void Update()
{
    if (playerMovement == null)
    {
        if (Input.GetKey(KeyCode.W))        //In general not a good idea to use Input.GetKey; use Input.GetButton instead
            playerMovement = StartCoroutine(Move(Vector2.up));
        else if (Input.GetKey(KeyCode.S))
            playerMovement = StartCoroutine(Move(Vector2.down));
        else if (Input.GetKey(KeyCode.D))
            playerMovement = StartCoroutine(Move(Vector2.right));
        else if (Input.GetKey(KeyCode.A))
            playerMovement = StartCoroutine(Move(Vector2.left));
    }
}

private IEnumerator Move(Vector2 direction)
{
    Vector2 startPosition = transform.position;
    Vector2 destinationPosition = transform.position + direction;
    float t = 0.0f;

    while (t < 1.0f)
    {
        transform.position = Vector2.Lerp(startPosition, destinationPosition, t);
        t += Time.deltaTime / stepDuration;
        yield return new WaitForEndOfFrame();
    }

    transform.position = destinationPosition;

    playerMovement = null;
}

```

If you have boundaries you should fire a Linecast before moving. Something similar to this:

```
private IEnumerator Move(Vector2 direction)
{
    Vector2 startPosition = transform.position;
    Vector2 destinationPosition = transform.position + direction;
    float t = 0.0f;

    if (!Physics2D.Linecast(startPosition, destinationPosition))
    {
        while (t < 1.0f)
        {
            transform.position = Vector2.Lerp(startPosition, destinationPosition, t);
            t += Time.deltaTime / stepDuration;
            yield return new WaitForEndOfFrame();
        }

        transform.position = destinationPosition;
    }

    playerMovement = null;
}

```

If you don't want the player to float in the air (e.g. if there isn't a sprite on that position) simply fire a Linecast / Raycast to the ground. (**in 3D**)

```
private IEnumerator Move(Vector3 direction)
{
    Vector3 startPosition = transform.position;
    Vector3 destinationPosition = transform.position + direction;
    float t = 0.0f;

    if (!Physics.Linecast(startPosition, destinationPosition) && Physics.Linecast(destinationPosition, destinationPosition + Vector3.down * 3.0f))
    {
        while (t < 1.0f)
        {
            transform.position = Vector3.Lerp(startPosition, destinationPosition, t);
            t += Time.deltaTime / stepDuration;
            yield return new WaitForEndOfFrame();
        }

        transform.position = destinationPosition;
    }

    playerMovement = null;
}

```

# Answer
> 0 votes
I found a similar question on the unity forum a while ago, this may be useful since you are not limiting how many times your character can move(it is not turn based therefore the controller you are using will no longer be waiting for an opponent to move it will behave oddly because when moving it will be called again and again without waiting and will cause this offset) so instead try the script on this site and set the increment according to your project. http://answers.unity3d.com/questions/819654/problem-achieving-grid-based-movement-with-c.html

# Answer
> 0 votes
one good way of doing it, is creating a new gameObject where you want the anchor to be, and every frame checking if the player is farther than 1 unit from the anchor. When you want the anchor to stop it's effect, just create a script constantly moving the anchor to the player.

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


# Question
Title: Calculate initial velocity for trajectory given duration, launch angle, and distance
I need my entity to go from point A to point B with a given launch angle over a given time.

I've been able to figure out the initial velocity without the constraint of the launch angle, but I can't figure out how to incorporate that into the equation.

After launch the entity is only affected by gravity, and point A and B are not necessarily at the same height.

Thanks!

# Answer
> 2 votes
**Note:** the situation you describe (angle, start, end, and time of flight) is overdetermined. For many (most) inputs, there will be no solution that simultaneously satisfies all of these constraints.

(eg. If we take the start, angle, time, and just the horizontal coordinate of the endpoint, that already completely determines the launch speed - with no guarantee that this hits the necessary vertical coordinate of the endpoint!)

To address this I'll remove the time of flight constraint, so we're finding a ballistic trajectory from the start to the end point, with a given firing angle. The launch speed and duration before it hits the target will be left as unknowns to solve for.

---

I'll assume we're in 2D here. If 3D, you can reduce it to the 2D case by projecting onto the plane containing the start/end points and the gravity vector.

We'll subtract out the start position, so it becomes zero and disappears from our equations, and our `target` vector represents the *offset* from the start to the end of the trajectory, fired with an initial inclination of `angle` in radians.

Our initial velocity is then the speed of the projectile times a unit vector in the firing direction:

`initialVelocity = speed * Vector2(cos(angle), sin(angle))`

With this, the projectile's position at time `t` is given by:

`positionAt(t) = initialVelocity * t + (gravity/2) * t*t`

(where `gravity` is a downward-pointing vector, like `(0, -9.8)`)

Taking just the horizontal, `x` component at the time of impact `T`:

```
target.x = initialVelocity.x * T
target.x = speed * cos(angle) * T
T = target.x/(speed * cos(angle))

```

Substituting this into the vertical, `y` component:

```
target.y = speed * sin(angle) * T + (gravity.y/2) * T^2
target.y = speed * sin(angle) * target.x / (speed * cos(angle)
         + (gravity.y/2) * (target.x/(speed * cos(angle))^2
target.y = target.x * tan(angle) + (gravity.y/2) * (target.x^2/(speed^2 * cos^2(angle))
target.y - target.x * tan(angle) = (gravity.y*target.x^2/2*cos^2(angle))/(speed^2)
speed^2 = (gravity.y*target.x^2)/(2*cos^2(angle)*(target.y - target.x*tan(angle))

```

Finally, since a speed is positive by definition (direction coming from the unit vector above):

`speed = sqrt((gravity.y*target.x^2)/(2*cos^2(angle)*(target.y - target.x*tan(angle)))`

**Ta-dah! :D**

---

A few things to note: this becomes undefined...

* if `angle` is vertical: you can still hit something directly below you with any velocity at all (gravity does all the work) or directly above you if you fire straight up with `speed >= sqrt(-g*target.y/2)` If it's to the left or right at all then we can't hit it with this angle.
* if `target.y >= target.x * tan(angle)`: the target is too high. The parabola kisses the line `y = x * tan(angle)` only at the moment it's fired - from then on gravity pulls it downward, so if the target is above that line then we'll never hit it even with infinite speed.

---

I've written a few previous answers on the subject of planning ballistic trajectories - you might also find those useful for reference:

---
Tags: linear-algebra, projectile-physics, trajectory
---


# Question
Title: How can I easily determine the z-ordering of objects in multiple glDraw calls?
I have a simple 2D tile-based scene that I'm rendering with OpenGL. On each frame I first draw the static background, and then draw the dynamic elements (monsters, etc.). This way it seems that the later drawn elements "paint over" the earlier drawn ones (using separate `glDraw` calls).

However, when asking around, it seems that if I used a depth buffer the order in which things are drawn doesn't necessarily matter, as the depth buffer can be used to determine visibility.

But what happens when some things share the same z-value when using a depth buffer? Is the newer one "painted over" the older one?

If so, should I rely on this behavior, or rather use different z-values for my "layers"?

# Answer
When 2 objects share the same z coordjnate and are painted over one another, you get an effect called z fighting (I once heard it being called z achne), parts of each model gets visible, but they generate a strange texture.

This eventually happens less closer to the eye, because the depth buffer keeps a longer range of bits for them than the parts far back.

You can make this effect disappear, by giving each entity a slight offset according to their y coordinate in the vertex shader.
> 1 votes

---
Tags: opengl
---


# Question
Title: Context is NULL with SDL_CreateWindowFrom Win32
There is a `VC ++ Win32` project. It connected the library sdl, follows CreateWindowW I have written

```
 SDL_Window* w = SDL_CreateWindowFrom(hWnd);
 //  SDL_WindowFlags(SDL_WINDOW_OPENGL);
   SDL_GLContext glcontext = SDL_GL_CreateContext(w);
   if (glcontext == NULL)OutputDebugString("null");

```

But my glcontext == NULL and `SDL_GetError` returns `The specified window isn't an OpenGL window`

But if I use `SDL_CreateWindow`, context turns out successfully

Even after the creation of the window using

```
static PIXELFORMATDESCRIPTOR pfd = {
       sizeof(PIXELFORMATDESCRIPTOR), // strcut size
       1,                              // Version number
       PFD_DRAW_TO_WINDOW |    // Flags, draw to a window,
       PFD_SUPPORT_OPENGL, // use OpenGL
       PFD_TYPE_RGBA,          // RGBA pixel values
       24,                     // 24-bit color
       0, 0, 0,                // RGB bits & shift sizes.
       0, 0, 0,                // Don't care about them
       0, 0,                   // No alpha buffer info
       0, 0, 0, 0, 0,          // No accumulation buffer
       32,                     // 32-bit depth buffer
       0,                      // No stencil buffer
       0,                      // No auxiliary buffers
       PFD_MAIN_PLANE,         // Layer type
       0,                      // Reserved (must be 0)
       0,                      // No layer mask
       0,                      // No visible mask
       0                       // No damage mask
   };

   // Did We Get A Device Context?
   hDC = GetDC(hWnd);

   PixelFormat = ChoosePixelFormat(hDC, &pfd);

   SetPixelFormat(hDC, PixelFormat, &pfd);

   // Are We Able To Get A Rendering Context?
   hRC = wglCreateContext(hDC);

   // Try To Activate The Rendering Context
   wglMakeCurrent(hDC, hRC);
   ReleaseDC(hWnd, hDC);
   ShowWindow(hWnd, nCmdShow);

   SDL_InitSubSystem(SDL_INIT_VIDEO);

   SDL_Window* w = SDL_CreateWindowFrom(hWnd);
   SDL_GLContext glcontext = SDL_GL_CreateContext(w);
   if (glcontext == NULL)OutputDebugString("null");

```

Can not get context. How correctly get the context?

# Answer
> 2 votes
According to this thread it seems that creating OpenGL contexts from foreign windows isn't currently supported in SDL.

> We can either always set the OPENGL flag for foreign windows, allowing you to try to create a context and let it fail if it's not compatible, or we can add a new API, something like SDL\_CreateOpenGLWindowFrom()

According to various different threads it seems that there is no OpenGL initialization code in `SDL_CreateWindowFrom`, so OpenGL context initialization won't work with that method. If you are building your own SDL binaries, you might want to consider modifying the `SDL_CreateWindowFrom` function by adding the correct `SDL_WINDOW_OPENGL` flag to the correct place in that method. It seems to be what people experiencing this same problem have done.

Why are you not using SDL for window creation? Letting SDL handle the windowing makes it easier for you to develop, and it will also make your project more cross-platform. When you create the window using `SDL_CreateWindow()`, just remember to pass in the `SDL_WINDOW_OPENGL` flag to the creation, and then you should be able to create your OpenGL context just fine.

# Answer
> 3 votes
So I made it here looking for help on this, and actually managed to get the idea for a fix. Not sure if too late to help anyone who posted here though but there it goes anyway :)

After diving in SDL 2.0.3's source, I found out that one can first create a "dummy" OpenGL window which SDL will look up at when setting up the foreign window. To make this work, you need to set the `SDL_HINT_VIDEO_WINDOW_SHARE_PIXEL_FORMAT` hint to point at the dummy window before calling `SDL_CreateWindowFrom` \- more info on that here (https://wiki.libsdl.org/SDL\_HINT\_VIDEO\_WINDOW\_SHARE\_PIXEL\_FORMAT).

After creating the foreign window, you might want to destroy the dummy, but that will make `SDL_GL_CreateContext` crash when called, since SDL keeps track of how many OpenGL windows have been created in order to unload the GL library when all are gone, but won't increase the ref count when creating a foreign OpenGL window. There are 2 fixes for this:

* Just keep the dummy window alive and hidden during the whole execution (simplest approach, and probably the best)
* Add the refcount increase to SDL (which was my choice)

If you want to go the latter way you would need to make the block starting at line 354 in file src/video/windows/SDL\_windowswindow.c look like this:

```
// If the otherWindow has SDL_WINDOW_OPENGL set, set it for the new window as well
if (otherWindow->flags & SDL_WINDOW_OPENGL)
{
    window->flags |= SDL_WINDOW_OPENGL;
    if(!WIN_GL_SetPixelFormatFrom(_this, otherWindow, window)) {
        return -1;
    }
    else
    {
        SDL_GL_LoadLibrary(NULL);
    }
}

```

And here's my code for creating the foreign window:

```
SDL_Window* pSampleWin = SDL_CreateWindow("", 0, 0, 1, 1, SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN);

char sBuf[32];
sprintf_s<32>(sBuf, "%p", pSampleWin);

SDL_SetHint(SDL_HINT_VIDEO_WINDOW_SHARE_PIXEL_FORMAT, sBuf);
mpWindow = SDL_CreateWindowFrom(aInitVars.mpExternalWindowHandle);
SDL_SetHint(SDL_HINT_VIDEO_WINDOW_SHARE_PIXEL_FORMAT, nullptr);

SDL_DestroyWindow(pSampleWin);

```

Note: I haven't dealt with releasing the library reference here, might be worth looking into.

---
Tags: sdl2
---


# Question
Title: How to calculate spherical harmonic coefficients for indirect diffuse?
After reading the article "An Efficient Representation for Irradiance Environment Maps", I'm a bit confused as how to calculate the spherical harmonic coefficients. I'd like to generate these coefficients given a cube map that I've generate dynamically in engine.

I'm currently using DirectX 11, but I have some familiarity with OpenGl. Some tips on calculating these coefficients would be greatly appreciated!

# Answer
> 1 votes
I don't know if you solved the problem, but since I am working with SH I can tell you that the best way to project a cubemap so far is that of Peter Pyke Sloan. Here his paper on SH, he basically sums each contribute from each pixel weighted by some value obtained from its uv (st in opengl) coordinates. And then all coefficients are normalized by a value obtained by the sum of all pixels weights.

---
Tags: opengl, directx, lighting, graphics-programming, spherical-harmonics
---


# Question
Title: Stuck the ball in the board (pingpong game)
this game isn't completed yet, i've created the part where the ball hits the board, but there's problem in playing and that's the ball stucking in the board. For a better comprehension and understaning i've attached a image down below , plz watch it and lemme know of your take on this bug.

```
    public partial class PingPong : Form
{
    public PingPong()
    {
        InitializeComponent();
        timer1.Enabled = true;
        timer1.Interval = 30;
    }

    int mx = 5;
    int my = 5;
    private void timer1_Tick(object sender, EventArgs e)
    {

        if (ball.Bounds.IntersectsWith(boardCenter.Bounds))
        {
            mx = mx * -1;
            my = my * 1;
        }
        else if (ball.Location.Y >= this.ClientSize.Height - ball.Height)
        {
            mx = mx * 1;
            my = my * -1;
        }
        else if (ball.Location.Y <= 0)
        {
            mx = mx *1;
            my = my * -1;
        }

        else if (ball.Location.X >= this.ClientSize.Width - ball.Width)
        {
            mx = mx * -1;
            my = my * 1;
        }

        ball.Location = new Point(ball.Location.X + mx, ball.Location.Y + my);

    }

    private void PingPong_KeyDown(object sender, KeyEventArgs e)
    {

        if (e.KeyCode == Keys.Up)
        {
            boardCenter.Location = new Point(boardCenter.Location.X, boardCenter.Location.Y - 4);

        }
        else if (e.KeyCode == Keys.Down)
        {
            boardCenter.Location = new Point(boardCenter.Location.X, boardCenter.Location.Y + 4);
        }

    }

}

```

# Answer
> 1 votes
I've had this exact same issue back when I made a version of PingPong.

Here's a walkthrough of your logic, to illustrate what it's actually doing. I'll point out the flaw afterwards, though you'll probably see it:

* Move on the X and Y axis
* Hits the paddle? Change X direction!!!
    + Move again!
* Hits the paddle? Change X direction!!!
    + Move again!
* Hits the paddle? Change X direction!!!
    + Move again!

Essentially, every frame it will change direction, if it keeps intersecting with the paddles Bounds. Which it will, if all you do it change the direction when you hit the paddle. You also need to move it out of the paddles Bounds.

Your best solution is to place it at the paddles Right side (Ball.X must be equal to Paddle.X + Paddle.Width (and maybe +1)). That way, no matter where you hit, it will always start out at somewhere along the right side of the paddle. Which will prevent something like this from being able to happen.

---
Tags: c#, windows-forms
---


# Question
Title: Would I need to delete unused assets from my Unity packaged build?
I'm going to make a release for my Unity game.

Does Unity include unused assets in build output? Would removing unused assets from a project reduce build size/Time?

I want to know if Unity packages all the assets to my build (which I would need to delete), or if Unity packages only the assets that are actually used in the game.

# Answer
> 9 votes
Unity just packs the thing that you are really using. So for example if you have 100 audio files and you just have one scene with one audio source where 1 audio file is assigned, then only this particular audio file will be delivered in your build. However when you have a script that has a reference to those 100 audio (in order to e.g. assign them randomly to the audio source), then all 100 files will be packed in the build.

Like DMGregory commented there is one exception: The "Resources" folders. All the files inside these folders will be packed in your build, since they are dynamically loadable at runtime, by name (so there is no direct reference in the scenes).

---
Tags: unity
---


title: Unity UI, how to hide on play

text:
# Question
Title: Unity UI, how to hide on play
I have created a menu on Unity using the built in UI components,I can't create this on a seperate scene because I used the toggle button, which basically when you click it, it spawns a specific object (I have 4 of these toggle buttons). I have completed making the menu on the my current scene. My problem is that when I start on runtime, the menu appears in front of the first person character controller, and when I move the mouse to click the toggle, the camera controller follows the mouse movement. How do I fix this? Also when I click all of the toggle buttons, I want the UI to dissapear, so it isn't shown when I am playing the game because atm when I click the toggle buttons, the actual buttons stay on the screen whilst I am navigating around the scene, is there any way to make this invisible?

# Answer
> 1 votes
I solved this problem in several different games with the state machine approach.

Your game has at least two different UI states in which it reacts differently to user input:

* the "in menu" state
* the "playing in first person" state.

It might have even more states you didn't mention or aren't aware yet that you will need them. For example what almost every game needs once in a while is a null-state in which most input is ignored.

Implement each of these different input-states as a separate MonoBehaviour.

Create another script `InputStateManager` which references all input-states in the scene and provides methods to switch between them. Such a state switch is performed by setting `enabled = true` on the state you request and `enabled = false` on all others. The `OnEnable` and `OnDisable` methods of your input states can also take care of activating and deactivating any UI objects which should only be visible while in that state (like the canvas of your menu).

The advantage of this method is that you achieve loose coupling between your different input states and can easily add a new one without touching the code of the existing ones.

# Answer
> 0 votes
I'll tell you what I did.

I had a `bool` on a camera scripts that says whether the camera should rotate or not, so I called it `bool shouldRotateCamera = true;`

And when you pop the menu, whether it's by using `Esc` or any other way, you can change that value in camera script to `this.shouldRotateCamera = false;`

In the update method of camera script always check `if (shouldRotate)`. The camera should rotate if so.

Regarding the UI, you can technically enable/disable it.

If there are any questions, feel free to ask.

---
Tags: unity
---


title: Pixel Picking vs Raycasting

text:
# Question
Title: Pixel Picking vs Raycasting
I was recently introduced to a way of picking in OpenGL known as pixel picking (or color picking).

From my understanding, how this is done is that the scene is rendered to the back buffer with a different rgb color representing each object. By reading the color of the pixel clicked by the cursor, the relevant object can be picked. The immediate issue I can think of when using this method is that during the picking process, the scene have to be rendered 2 times, once for picking and another time for display. Additonally this also limits the it to 256^3 unique objects for picking.

With this, I would assume this is a much more accurate way of "raycast" than to use physics raycast. By placing a camera at the raycast source, render once for "raycast" picking, and resetting the camera to the original position for normal render. This would reduce issues of "bullet hitting invisible walls" as its not dependent on physics collision, which can be affected by convex hulls for complex meshes.

Is there any reason why this method is not used? Could it be over complication? Or perhaps it is what is happening behind the scenes in raycasting?

---

As an example where pixel picking might be better would be when raycasting through a wire fence. Most wire fence models are just textures with a transparent channel, giving the illusion of a wire fence while saving on geometry by having 1 single plane. Using color picking, what the player see is what the camera picks. Whereas in raycast, the raycast will not shoot through the plane unless it doesnt collide with the plane at all.

# Answer
Pixel picking is effective if you need to do **lots** of raycasts from **one** source. You bear the overhead of rendering and readback once, then get all your many picks at low incremental cost each. To get just one ray result you've already had to calculate thousands or millions whether you use them or not.

If you're only doing a few raycasts at a time (say a handful of bullets or IK placements per frame), or you need to do casts from multiple sources/multiple disparate directions (say, multiple characters who each need to shoot from their viewpoint) then pixel picking gives you relatively little bang for your rendering buck.

A lot of games fall into this latter category, where they need small groups of raycasts all over the place rather than hundreds of raycasts from one source, so doing the raycasts individually with physics is more efficient for them.

Doing the physics raycast also lets you get access to the impact normal and high-resolution UV/position cheaply, which may cost extra storage & bandwidth to extract in a pixel-picking strategy.

Lars Viklund raises another important limitation: quite often gameplay raycasts like bullet shots are performed on the server to maintain fairness in multiplayer games. Servers often run without rendering so they focus strictly on processing gameplay logic as fast as possible. Making gameplay dependent on rendering may complicate or bog down the server code in these contexts.

For the chain link fence example, most games solve this though physics layers — categorizing permeable barriers like this as "see-through/shoot-through/no-nav-through" so raycasts for detection and shooting go through it but navigation/movement/collision checks still treat it as solid. If you need pixel perfect results around this kind of obstacle from the player's point of view, you might be able to check the raycast result versus the depth buffer, without a separate rendering pass.
> 8 votes

---
Tags: raycasting, color, picking
---


title: Roatating a Game Object downward

text:
# Question
Title: Roatating a Game Object downward
In my game I have a rocket which is traveling horizontally across the screen.

What I am trying to do is when the player runs out of fuel, the rockets engine stops (already coded) and then the rocket will slowly rotate to point at an almost 45 degree angle and fall down off the screen as gravity takes its affect.

How do I do this?

# Answer
> 1 votes
You need to rotate the rocket after each "physics" update (I think you are not actually using rigidbodies or physics), like so:

You just need the rocket's `transform.forward` to always point in the same direction as its' velocity, regardless of how you calculate velocity. If "forward" is always pointing in the actual correct direction, you can just push the rocket along its' local Z axis rather than pushing it through world-space.

# Answer
> 0 votes
try this:

* put an empty game object a few units below the rocket, but horizontally in the middle of it. *(the more units below the rocket, the slower the rotation will be ).*
* use this code *( just a concept )*

---

```
//note that this code won't work like this, it's just a guideline

public float speed = 0.2f;
void Update ()
{
    if (outOfFuel)
        rocket.transform.Rotate ( emptyGameObject.transform.forward * speed * Time.deltaTime );
    /* You will see that the rocket won't stop spinning, it's ok.
     * Just press play, and when you feel the rocket is facing the direction
     * you want to set as a limit, go to the code and change it like this:
     * if (outOfFuel && rocket.transform.eulerAngles.z <= limitRotation )
     * where 'limitRoation' is a float.
     * Also, if after you change the code the rocket stops spinning or similar,
     * change the '<=' symbol with a '>=' symbol.
     */
}

```

Hope it helps, if anything, let us know.

---
Tags: unity, rotation, gameobject
---


# Question
Title: What is the best way to interpolate vertex data in OpenGL?
I am working on a game which has a board of falling down blocks, similar to Tetris. Each block is represented with for vertices and two triangles, each vertex consisting out of its location and texture coordinations. I am using `glDrawElements` to render the blocks.

I would like to interpolate the location data when blocks fall down. I am wondering, **what is the most efficient, elegant and easy way to interpolate such vertex data in OpenGL?**

I obviously need two location states `(x0 y0)` and `(x1 y1)` and a time step `t` (`0 < t < 1`), then I can lerp in my vertex shader. **How do I pass this information to the shader?** For the timestep, uniforms came into my mind. But what about the locations?

1. Pass both locations to my VBO at any time. This would work, but requires my VBO to be twice as big as it includes both location states, even if they are equal (= the block hasn't moved)! Blocks will move at times, but most of the time, they are static - wouldn't this approach be a wast of memory?
2. Keep `(x0 y0)` in the VBO, transmit `(x1 y1)` via uniforms if necessary (= if the block has moved). This would save memory, but completely destroy my rendering pipeline.
3. Anything else? Both of the approaches above seem silly to me. **How do other games do this?**

Thanks!

# Answer
> 3 votes
I would implement a model matrix as suggested in the comments.

Calculate the new position, `(x1 y1)`:

```
Vector2f newPosition = interpolatePosition(oldPosition);

```

Then apply that as a translation to the model matrix:

```
Matrix4f modelMatrix = new Matrix4f().translate(newPosition);

```

Then pass the model matrix into the shader as a uniform:

```
GLuint matrixUniform = glGetUniformLocation(shader, "modelMatrix");
glUniformMatrix4fv(matrixUniform, GL_FALSE, modelMatrix);

```

Finally, in your shader you can multiply the vertex positions by this model matrix:

```
in vec2 position;
uniform mat4 modelMatrix;

void main() {
    gl_Position = modelMatrix * vec4(position, 0, 1);
}

```

Check out the open.gl article on transformations for more details.

---

**How to do the same thing with only a single draw call**

Let's say we want to use the same VBO more than once but apply different transforms to each instance. We can utilize uniform buffers and `glDrawElementsInstanced`.

First lets define two model matrices with different translations:

```
Matrix4f modelMatrixOne = new Matrix4f().translate(-1, 0, 0);
Matrix4f modelMatrixTwo = new Matrix4f().translate(1, 0, 0);

```

Now we create the uniform buffer to store both matrices:

```
int ubo = glGenBuffers();
glBindBuffer(GL_UNIFORM_BUFFER, ubo);

int matrixSize = Float.BYTES * 16;
glBufferData(GL_UNIFORM_BUFFER, matrixSize * 2, GL_DYNAMIC_DRAW);
glBufferSubData(GL_UNIFORM_BUFFER, 0, floatBuffer(modelMatrixOne));
glBufferSubData(GL_UNIFORM_BUFFER, matrixSize, floatBuffer(modelMatrixTwo));

```

Attach the uniform buffer to a binding point:

```
int bindingPoint = 0;  // valid range: 0 to GL_MAX_UNIFORM_BUFFER_BINDINGS
glBindBufferBase(GL_UNIFORM_BUFFER, bindingPoint, ubo);

```

Then associate the shader's uniform block with that binding point:

```
int blockIndex = glGetUniformBlockIndex(shader, "ModelMatrices");
glUniformBlockBinding(shader, blockIndex, bindingPoint);

```

Now we update the draw call:

```
glDrawElementsInstanced(GL_TRIANGLES, elements, GL_UNSIGNED_INT, 0, 2);

```

This is the same as a normal `glDrawElements` call with an extra parameter, `2`, which specifies how many instances to draw.

Finally we update our vertex shader to use the uniform block we setup and `gl_InstanceID`:

```
in vec2 position;
uniform ModelMatrices {
    mat4 modelMatrix[2];
};

void main() {
    gl_Position = modelMatrix[gl_InstanceID] * vec4(position, 0, 1);
}

```

*NOTE: This method requires the shader to know exactly how many matrices will be used. If we're using one matrix per block then it essentially needs to know how many blocks*

---
Tags: opengl, vbo
---


# Question
Title: Creating a DPI and Resolution Independant GUI
How would one best go about it? Assuming I'm using OpenGL to do all the drawing.

It seems like the best approach is to have the GUI elements maintain the same physical size regardless of the screen it is displayed on.It seems that Windows will act as if you had a screen with 72 DPI regardless of its actual size unless you specifically request tell it that you handle high DPI cases. Which would greatly simplify things, does this hold for Linux as well?

Does things change between running things in Windowed mode versus fullscreen? It seems like it should, as the Window changes size depending on resultion while in fullscreen the image is always the same size, just with less or more density!

# Answer
Windows:

Imho, one should completely avoid fullscreen mode. There is no longer any performance advantage with it, those days are gone.

If you want to cover the entire screen, just create a borderless and captionless window with fullscreen dimensions. This gives you advantages:

* Only one set of code: If going directly fullscreen at program start, one reacts once only on a screen resize, if going to windowed mode, the same code reacts each time a resize event occurs. (And btw, i believe the video memory almost always gets badly beaten from device resizes, so prepare to re-construct various render surfaces).
* Easier development and debugging (multiple windows handy/accessible).
* You can easily extend the application to cover multiple screens, when the user has an "extended desktop" (when one can move mouse cursor from one display to another). Just make the window 6000 px wide for 3 screens and place it at x=-2000 or likewise. Windows provides an API for monitor coordinates & placement.
* Also from the users perspective positive: Allows to place other windows topmost (you must react on lostfocus or hasfocus).
* Be a good to the hardware. Old fullscreen feels destructive...

The easy going way is to not scale. Applications usually try to place their elements starting from upper lefthand corner. Same with a game GUI that may occupy a larger piece of the screen. BUT ofc one can justify isolated screen elements also right & bottom, as long as they aren't too big. Hence a good scaling would be to not alter icon sizes, fonts, picture sizes, etc. but indeed place them nicely according to screen pixels.

Then tell users with too few pixels (and too old hardware) to go grab something newer. Do not support anything too old-fashioned, rather aim at supporting what there will be 3.14 years from now :-).
> 1 votes

---
Tags: opengl, gui, resolution
---


# Question
Title: Switching Screens without initializing them every time
I have a UI with four Screens (all extending a "main Screen") that users switch between very frequently, at the moment I am switching Screens using `g.setScreen(new screen);`, but this leads to the problem that I have to reload and initialize everything inside the Screen every single time, which is causing memory leaks.

Is there some way I can save the Screens in memory and just load them without having to re-initialize everything inside them? Or is this bad? Because my current approach is not going to cut it.

I was thinking something like initializing all Screens on startup and saving them in an array, then just loading the Screen I need from that array when I need it, ie `g.setScreen(screenArray.get(nextScreen));`. Is this a viable approach? Please any advice you can give will help, really need help with this.

# Answer
Maybe setscreen causes a device reset, in which case things get properly nullified. Two suggestions:

1. Use windowed mode only, then you can place the window in any screen (and for "fullscreen", use a borderless, captionless window with size = physical full screen dimension, place it at any screen's origin).
2. Render (hidden) everything to a surface first, then copy/draw it to any window in any monitor.

Note however that a device resize also causes a hard reset. But if the monitors have same resolutions, there is no need to resize the device (= the window or the render surface).
> 0 votes

---
Tags: libgdx, screen, resource-management, screen-management
---


# Question
Title: How to enable Unity related syntax highlighting with VSCode?
I'm using VSCode, not VisualStudio for Unity scripting. VSCode has syntax highlighting for C#, which works fine, but all the Unity related stuff like `Vector3` doesn't get any highlights. I know, that you can change somehow the files, but I can't even find the C# folder in my extensions folder (There is everything else like cpp, css etc. just no c#). Would be great if someone could lead me to the folder location and how to add keywords for the highlighting.

Here is a screenshot, where you can see that `float` is highlighted, but `Transform` not.

# Answer
> 1 votes
Assuming you have the latest VSCode and have it configured for Unity development... https://code.visualstudio.com/docs/other/unity

Does Intellisense work for Unity classes? If yes, and you are just not seeing syntax colors, try a different theme. (Preferences-\>Color Theme)

Some of them highlight class names and some don't.

---
Tags: unity, c#, visual-studio-code
---


title: C++ Platformer Collision

text:
# Question
Title: C++ Platformer Collision
This is very simple, but I have spent nearly 6 months messing with this and it is always messed up.

This is a tile platformer, everything is "normal", x and y correspond to tile. Tiles are 32 x 32 pixels.

```
// Get all tile numbers, top left, top right, bottom left, bottom right
int X = 63; // and in this, say the player is moving right
int Y = 50;
int Width = 33; // This is the problem, if it is < 32, the collisions are all over the place, in the open, where there shouldn't be.
int Height = 50;

int tile_x = floor( (double) X/32);
int tile_y = floor( (double) Y/32);
int tile_x2 = floor( (double) (X + Width)/ 32);
int tile_y2 = floor( (double) (Y + Height)/ 32);
bool open = true;

// This is meant to catch cases where width < 32
if (tile_x == tile_x2) {
    if (IsOpenPt(tile_x, tile_y)) { return true; }
}

// loop through tiles
for (int y = tile_y; y < tile_y2; y++) {

    for (int x = tile_x; x < tile_x2; x++) {

        // this spot is not open
        if (!IsOpenPt(x,y)) { open = false; }

    }
}

return open;

```

This works if the width is greater than 32, but if it anything less, everything becomes random open point/ not.

See anything wrong with my formula? I have exhausted searches, nothing. Once again I emphasize, the entire project, I have been trying to get this part to work. I have literally a 100 page notebook of attempts at visualizing and grids to put it on paper.

# Answer
> 1 votes
I think you need some documentation about collisions. It seems you want to check the collision between 2 hitbox on a 2D game:

```
if (rect1.x < rect2.x + rect2.width &&
   rect1.x + rect1.width > rect2.x &&
   rect1.y < rect2.y + rect2.height &&
   rect1.height + rect1.y > rect2.y) {
    // collision detected!
}

```

But you're trying to make a pixel perfect collision, which is needed only when you have check a collision with this code.

This article seems to make a good summarize of the topic.

# Answer
> 0 votes
Your issue seems to be that you are only checking a single tile if your player is 32 or less pixels wide. That obviously does not work, because your player is taller than one tile. Hence, you need to remove the first easy-oit as it breaks the detection, and simply just rely on the looping method.

# Answer
> 0 votes
It's not clear what you are trying to achieve, but changing the \< operators to \<= might be a step in the right direction.

---
Tags: c++, collision-detection, platformer, tiles
---


title: Guided Missile with Constant Time

text:
# Question
Title: Guided Missile with Constant Time
I'm building a game with players and missiles.

I want to fire a missile from P1 to P2. The missile should always take exactly five seconds to reach P2. The missile should also track P2. If P2 moves farther away, the missile must speed up to satisfy the timing constraint. If P2 moves left, the missile must move left (and change speed as well). If P2 moves closer to P1, the missile must slow down.

Is this possible? What's the best way to accomplish this?

I don't currently have a Vector2D class (this isn't actually a game, but the analogy works well), so if possible, I'd like a solution that doesn't require one.

**Edit:** This isn't actually a missile either. :)

Thanks!

# Answer
> 10 votes
The edit is reassuring. :)

Okay, here's a straightforward update loop...

Assuming when we fire the missile we initialize `remainingFlightTime = 5f` then...

```
void UpdateMissile(float deltaTime)
{
   remainingFlightTime -= deltaTime;

   // At the end of the trajectory, snap to target & explode.
   // The math will put us there anyway, but this saves
   // on fancy logic related to overshooting. ;)
   if(remainingFlightTime <= 0f)
   {
      myX = targetX;
      myY = targetY;
      MissileImpact();
      return;
   }

   // Compute straight-line velocity that will take us
   // to the target in exactly the time remaining.
   velocityX = (targetX - myX)/remainingFlightTime;
   velocityY = (targetY - myY)/remainingFlightTime;

   // Integrate the velocity into the position.
   myX += velocityX * deltaTime;
   myY += velocityY * deltaTime;
}

```

# Answer
> 0 votes
Why not lerp the position and update the target destination as it changes?

You might have to look at how lerping works but it would look something like this:

```
public position startMarker;
public float duration = 5.0f;
private float startTime;
void Launch() {
    startTime = Time.time;
}
void Update() {
    float distCovered = (Time.time - startTime) / duration;
    missile.position = Vector3.Lerp(startMarker.position, target.position, distCovered);
}

```

by lerping you are basically changing the position of an object over a certain amount of time so you could say that you are 50% of the way from A to B and the object would be placed there. Lerping is direct so you will always move towards the target (as you want in the comments).

---
Tags: mathematics, movement, projectile-physics, trigonometry
---


title: Moving occluders in Unity?

text:
# Question
Title: Moving occluders in Unity?
I've made a shader for a racing game in Unity that billboards a headlight glow effect (the lights are not actually light sources so I can't use lens flares). The quad with the glow texture is rotated to always face the camera but attenuated by the angle between the original normal and view direction so it only appears when facing the camera. I noticed when viewing from an angle that parts of the billboard were being occluded by the car so I set it to 'ZTest Always' to prevent this.

This all works fine, except there's a part where new cars are delivered by truck, and the lights are glowing through the truck door before it opens :-(

I tried re-enabling Z-testing and manually tweaking depth in the vertex shader after the MVP matrix multiply, but can't find a sweet spot that doesn't cause either one problem or the other at some point.

So I'm wondering if there's some way to have a moving occluder for occlusion culling in Unity. This way I could have the billboard occluded by the door until the point that it opens. The docs mention 'occlusion areas' for dynamic objects but this seems to refer to moving objects being occluded by static geometry, I'm not sure if it works the other way round.

Otherwise I guess it will have to be some kind of animation script that activates the lights at the exact moment the door opens...

EDIT - this sort of thing

# Answer
Have you considered and/or tried using an emissive material for the lights?

I haven't done so before, but it seems like you could just have two materials for the reflectors and/or the light bulbs (sphere primitives). I suspect either of these would produce superior results with much less "magic". This will allow you to rely on standard occlusion/culling to take care of the rest (the car is not rendered through the truck, therefore the emissive material wouldn't either). As a bonus, emissive acts like a real light, even though it's not, and will even apply lighting to non-static objects. I also have not tried this, but the standard lens flares may work very well with it.

Doing the reflectors, the "off" material would be reflective, and the "on" material, emissive.

Doing spheres, don't draw the spheres when "off" (reflective reflector material is visible) and use emissive when "on".
> 1 votes

---
Tags: unity, culling, occlusion
---


# Question
Title: Flipping car animation with coroutine not functioning properly
I am creating a game in unity 3d that has to do with cars. If you double jump and you are holding the joystick in a certain direction then the car will flip that direction (360 degree flip). I am using a coroutine to run this asynchronously but for I am having a problem with smoothness.

Here is the code I use (the alterations of the positioning of the car is to make sure that the bumpers don't hit the ground during the flip):

```
public IEnumerator FlipCar(float xDir, float yDir)
{ // Going to flip 36 iterations at 10 degrees each so a full 360 is traveled
    car.GetComponent<Rigidbody>().useGravity = false;
    while (flipInc <= 36)
    {
        // rotate car toward xDir and yDir
        if (yDir > .5f && (xDir > -.5f && xDir < .5f))
        {
            switch (flipInc)
            {
                case 1:
                case 2:
                case 3:
                case 5:
                case 6:
                case 7:
                case 8:
                case 10:
                case 20:
                case 20:
                    car.transform.position = new Vector3(car.transform.position.x, car.transform.position.y + .25f, car.transform.position.z);
                    break;
                case 4:
                    car.transform.position = new Vector3(car.transform.position.x, car.transform.position.y + .35f, car.transform.position.z);
                    break;
                case 13:
                case 29:
                case 30:
                case 31:
                case 32:
                case 33:
                case 34:
                case 35:
                case 36:
                    car.transform.position = new Vector3(car.transform.position.x, car.transform.position.y - .25f, car.transform.position.z);
                    break;
            }
            car.transform.Rotate(10, 0, 0);
        }
        else if (yDir < .5f && (xDir > -.5f && xDir < .5f))
            car.transform.Rotate(-10, 0, 0);
        else if (xDir > .5f && (yDir > -.5f && yDir < .5f))
            car.transform.Rotate(0, 0, 10);
        else if (xDir < .5f && (yDir > -.5f && yDir < .5f))
            car.transform.Rotate(0, 0, -10);
        // increment flipInc
        flipInc++;

        if (flipInc <= 36)
            yield return new WaitForSeconds(0);
        else
        {
            flipInc = 1;
            car.GetComponent<Rigidbody>().useGravity = true;
            yield break;
        }
    }
}

```

Basically my problem is that if I keep the `yield return new WaitForSeconds(0);` then the flipping is too slow and choppy...but if I remove it and just let the loop run until the flipInc is greater than 36, it runs too fast to even see. Is there a way to get this to run smoothly?

**EDIT**

Here is what I have changed it to but it doesn't function properly:

```
public IEnumerator FlipCar(float xDir, float yDir)
{
    car.GetComponent<Rigidbody>().useGravity = false;
    while (flipInc <= 360f)
    {
         //rotate car toward xDir and yDir
        if (yDir > .5f && (xDir > -.5f && xDir < .5f))
        {
            currRot = 10 * Time.deltaTime;
            flipInc += currRot;
            AdjustYPosition();
            car.transform.Rotate(currRot, 0, 0);
        }
        else if (yDir < .5f && (xDir > -.5f && xDir < .5f))
        {
            car.transform.Rotate(-10, 0, 0);
        }
        else if (xDir > .5f && (yDir > -.5f && yDir < .5f))
        {
            car.transform.Rotate(0, 0, 10);
        }
        else if (xDir < .5f && (yDir > -.5f && yDir < .5f))
        {
            car.transform.Rotate(0, 0, -10);
        }

        if (flipInc <= 360)
            yield return new WaitForSeconds(0);
        else
        {
            flipInc = 0;
            car.GetComponent<Rigidbody>().useGravity = true;
            yield break;
        }
    }
}

void AdjustYPosition()
{
    int rot = Mathf.RoundToInt(flipInc);
    switch (rot)
    {
        case 10:
        case 20:
        case 30:
        case 50:
        case 60:
        case 70:
        case 80:
        case 100:
        case 200:
        case 220:
            if (lastRot != rot)
                car.transform.position = new Vector3(car.transform.position.x, car.transform.position.y + .25f, car.transform.position.z);
            break;
        case 40:
            if (lastRot != rot)
                car.transform.position = new Vector3(car.transform.position.x, car.transform.position.y + .35f, car.transform.position.z);
            break;
        case 130:
        case 290:
        case 300:
        case 310:
        case 320:
        case 330:
        case 340:
        case 350:
        case 360:
            if (lastRot != rot)
                car.transform.position = new Vector3(car.transform.position.x, car.transform.position.y - .25f, car.transform.position.z);
            break;
    }
    lastRot = rot;
}

```

# Answer
> 0 votes
Allen highlighted the issue but didn't come right out and say it.

If you get one "iteration" per frame, it should take 36 frames to spin 360 degrees.

At 60 FPS, that's 0.6 seconds (**average** `deltaTime` of 0.0166666).
At 120 FPS, it's only 0.3 seconds (**average** `deltaTime` of 0.00833333)

You are frame-rate dependent; you need to move X-degrees **per second** rather than X-degrees per frame because there are no guarantees regarding how often frames are rendered or how much time has elapsed since the last. One second is always one second though. That means replacing every occurence of `10` with `10 * Time.deltaTime`. As Allen pointed out, it would be better to do `rotationFactorPerSecond * Time.deltaTime` to avoid forgetting to update one or more copies.

After modification, the car will rotate `10` degrees **per second**. At 60 FPS, the car will rotate, on average, `0.16666` degrees **per frame**. After one second, at 60 FPS, `flipInc` would *want* to be 60, well above your 36 cutoff. Flipping a full 360 degrees will take 36 seconds; `flipInc` would *want* to be approximately 2,160 (at 60 FPS average).

Allen has provided the solution for this as well. Basically, track the total amount of "flip" applied (add `rotationFactorPerSecond * Time.deltaTime` to a total each time through). When that total is `360.0`, or greater, the car should finish the flip during this frame. At the same time, you can use that total angle to determine how much to push the car up and replace `flipInc`.

# Answer
> 0 votes
Your yield makes the coroutine execute once per frame. The problem is that the time between frames is variable, so your rotation is changing by a variable amount per second. Thankfully there is an easy solution! Multiple your change in rotation, the 10 in your example, by Time.deltaTime. (Also, you may need to increase the speed, because deltaTime is a small decimal unless your game has very low fps)

Here is a great video on the subject: https://unity3d.com/learn/tutorials/modules/beginner/scripting/delta-time

Here is a simple code demonstration. This rotates 360 degrees smoothly around the forward axis. You can easily modify it to be whatever axis you want.

```
public float rotationFactorPerSecond = 30;
public GameObject car;

public IEnumerator Flip360()
{
    float flipAmount = 0;

    car.GetComponent<Rigidbody>().useGravity = false;

    while (flipAmount < 360)
    {
        car.transform.Rotate(transform.forward * rotationFactorPerSecond * Time.deltaTime);
        flipAmount += rotationFactorPerSecond * Time.deltaTime;
        yield return null;
    }

    car.GetComponent<Rigidbody>().useGravity = true;
}

```

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


# Question
Title: Wheels not facing right direction when car faces different directions
I am creating a real time multiplayer driving game in Unity. I am using google play's real time multiplayer service. I am having an issue where the wheels of the cars that are over the network are not facing the right direction. What I am currently trying to do is just add the calculated steering angle to the current rotation of that particular player's car, but for some reason the wheels face the wrong way and rotate incorrectly if the car is facing certain directions. Logically I thought what I have is correct. Basically for each wheel I use this code:

```
car.transform.rotation = Quaternion.Euler(0, car.transform.rotation.y + steerAngle, 0);

```

So I find the rotation of that car and then I add the steer angle to it. Why wouldn't this work?

# Answer
Assuming the wheels are children of the car, it will be easier to apply `steerAngle` to `transform.localRotation`. The numbers you see in the transform's inspector are local, not world. By adjusting/transmitting the local rotation for the wheels, you can apply them directly and let the transform hierarchy worry about getting them to come out right in world-space. You can rest assured that the local rotation is always relative to the parent car.

The wheel rotates constantly on its' **local** X axis whenever the car is moving forward. The wheel "steers" by rotating along it's **local** Y axis. In both cases, the wheel is only rotated around its' own, local, origin; unbeknownst to the wheel, that origin is actually moving all over world-space.
> 1 votes

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


title: PN TRIANGLES is Bezier Triangles right?

text:
# Question
Title: PN TRIANGLES is Bezier Triangles right?
JUst wondering the term pn triangles is the same thing as saying bezier triangle patch??/

# Answer
To keep it simple, in this context:

* "patch" generally refers to a surface generated by control points, rather than vertices
* "Bezier" generally refers to applying the Bernstein polynomial of an arbitrary degree to said surface
* "triangle" (probably) refers to the fact that the theoretical, smooth, surface is degenerated into real, flat, triangles for rendering. (A rectangular Bezier surface is in the quad domain, not triangle)

A *Bezier Triangle* is a special-case, bi-quadratic surface (the patch is a triangle), where a "bezier triangle patch" probably refers to a bi-cubic surface (the patch is a rectangle) rendered using triangles.

The main idea behind "PN triangles" is to produce better shading, using the same input data, faster, and without adding anything extraordinary to the graphics pipeline. The method uses Bezier Triangles which are, mathematically, easier to subdivide. It also "Beziers" the normals instead of lerping and contains optimizations to reduce creasing/cracking artifacts while still maintaining performance on less-capable hardware. The input PN triangles (lowest-LOD version of the geometry) render about as fast as normal triangles, take the same amount of space to store, and the same amount of time to upload to the GPU.

So, in essence, the algorithm just packs a superior description of the geometry into the same footprint that "normal triangles" have.

This image was extracted from this pdf, which is worth a read. The top shows a Bezier patch with lerp'ed normals and the bottom shows the PN algorithm's "Bezier'ed" normals. Subdivided PN triangles maintain more-accurate normals than their "normal" counterparts.

From Bézier surface:

> A Bézier patch of degree (m, n) may be constructed out of two Bézier triangles of degree m+n, or out of a single Bézier triangle of degree m + n, with the input domain as a square instead of as a triangle.
>
> A Bézier triangle of degree m may also be constructed out of a Bézier surface of degree (m, m), with the control points so that one edge is squashed to a point, or with the input domain as a triangle instead of as a square.

Also Bézier triangle.
> 1 votes

---
Tags: directx11
---


# Question
Title: Drawn frustum does not match with glm::perspective
I am working on a personal project and I got a 3d viewport with moving camera working nicely. Now I am working on being able to freeze the time and switch to a debug camera and move in the game freely. In order to do so I also wish to see where the original camera is and what the frustum is. I started by creating at the origin the camera shape and compute the proper frustum.

The camera frustum is the result of a vertical angle of view of 30 degree, near plane 100, far plane 5000. (no particular reason behind those value).

Those values are the exact same of the flying camera so I would expect if i put the camera at the origin, pointing in the same direction (-z), the frustum should match the screen size.

Unluckily that doesnt happen here is the result I get:

If in the frustum point calculation I scale the fov by 2.75~ I get the right size, no idea if that number has a specific meaning. I am quite sure the frustum is correct, I say that because if I do atan(plane-width/2 / near) I get half the fov\*window ratio. Same for far plane, which is correct. That lead me to think it might be a problem just in the visualization.

I use glm to compute both look at and perspective:

```
mat4 Camera3dPivot::get_world_view_matrix() const
{
    //just computing and returning the camera
    mat4 look = lookAt(m_pos , m_pivot, vec3(0.0,1.0,0.0));
    return look;
}

mat4 Camera3dPivot::get_projection_matrix() const
{
    //computing perspective

    mat4 temp44= perspective(m_fov,((float)m_width/(float)m_height),m_near,m_far);
    //flipping the perspective to avoid upside down effect
    temp44[0][0] *=  -1.0f ;
    temp44[1][1] *=  -1.0f ;
    return temp44;
}

```

After that the MVP matrix is nothing more that proj * lookM.

```
view_to_proj_matrix = projection_matrix* model_to_view_matrix;

```

So far the camera worked really nicely, no glitches or artefact I am aware of, so I am quite confidant in the code both cpu and shader. (shaders are the most basic one you can imagine, i can post them if needed).

This is how I compute the frustum:

```
Camera3dPivot* cam = (Camera3dPivot*)m_cam;
float angle = cam->get_fov()* (M_PI / 180.0);

float near =cam->get_near_plane();
float hnear = 2.0f*tanf(angle / 2) *near;
float wnear = hnear * cam->get_ratio();

float far = cam->get_far_plane()*0.9;
float hfar = 2.0f*tanf(angle / 2) * far;
float wfar= hfar * cam->get_ratio();

float hnearhalf = hnear / 2.0;
float wnearhalf = wnear / 2.0;

float hfarhalf = hfar / 2.0;
float wfarhalf = wfar / 2.0;

```

There is only one camera in the scene. The flying one, the drawn camera is just a not transformed drawn of the flying camera.

I went through the code several time checking the data and everything is fine and makes sense, from the angles, to the aspect ratio of the viewport etc.

So I am starting to think I am actually missing something, also because it has to work, since if I replicate the same exact scenario in maya the frustum matches the viewport. Although I might try to see if maya gives me the points of the frustum and compare them with mine.

Any help on the matter is appreciated. PS: this is the tuorial i looked at for the frustum calculation: View Frustum Culling Tutorial PPS: I am also sure i am inputting the right angle, glm::perspective I feed degrees , tanf I feed radians, you can see the conversion in the frustum code.

# Answer
> 2 votes
Looks like that by luck I found the solution to the problem. I really don't like the glm documentation, was my understanding that glm doc was intentionally skinny since it matches corresponding glsl and glut. Anyway documentation is a mess.

doc v 0.92 doesnt specify what unit to use, the gluPerspective uses degree, so that's why I used degrees.

doc v0.94 says is degree but if you define a macro you can use rad. doc v0.97 looks finally much better and now only states radiants. To be honest I downloaded the repo a while ago so I don't know what version i have (i removed glm git folder from my own repo). So I checked directly the source code and found: /// @param fovy Specifies the field of view angle, in degrees, in the y direction. Expressed in radians.

Which I found it really confusing. Anyway: TL;DR , switched to radians in glm::perspective all good.

Cheers

M.

---
Tags: opengl, c++, camera, glm, frustum
---