# Question
Title: Space Shooter: Multiple weapons approach
I'm building a small space shooter and want my player to have multiple weapons available. I'm using an array and a vector for the weapons (both initialized when the player is initialized). Both the weapon array and vector are members of the player.

```
    CWeapon     m_aWeapons[3];  // Array for unlockable weapons
    vector<CWeapon> m_vWeapons; // Vector for unlocked weapons

```

The weapons that can be unlocked are initialized in an array at the beginning.

```
// Set unlockable weapons
m_aWeapons[0].Init("LaserOrange.bmp", 0.2f, 400.0f, 20.0f);
m_aWeapons[1].Init("LaserBlue.bmp", 0.2f, 600.0f, 20.0f);
m_aWeapons[2].Init("LaserRed.bmp", 0.2f, 800.0f, 20.0f);

```

I save the weapons the player has available at current in the vector.

After each level the next weapon is unlocked, if possible, by pushing the next element of the array into the vector with the public method CPlayer::UnlockWeapon ().

```
// Unlock
//
// Task: Unlock next weapon
//
bool CPlayer::UnlockWeapon()
{
// Unlocked new weapon?
bool bUnlocked = false;

// Temp for size of weapon vector and array
int VectorSize = static_cast<int> (m_vWeapons.size ());
int ArraySize = sizeof(m_aWeapons) / sizeof(CWeapon);

// Not unlocked every weapon?
if (VectorSize < ArraySize)
{
    // Yes, then unlock next
    m_vWeapons.push_back(m_aWeapons[VectorSize]);

    // Unlocked new weapon
    bUnlocked = true;
}

return (bUnlocked);

} // UnlockWeapon

```

I save the index of the currently selected weapon in a variable and when the player shoots, I create a shot and initialize it with the speed and shotsprite of the vector element at the index of the currently selected weapon variable.

```
// ProcessShooting
//
// Aufgabe: Shoot weapon
//
void CPlayer::ProcessShooting ()
{
// Hasn't shot until now
m_bHasShot = false;

// Pressed "Space" and can shoot?
if (g_pFramework->KeyDown (SDL_SCANCODE_SPACE) && m_bShotLock == false)
{
    // Has shot
    m_bHasShot = true;

    // Create and initialize new shot
    CShot Shot;

    // Temp for ease
    CWeapon Temp = m_vWeapons.at(m_CurrentWeapon);

    Shot.Init(Temp.GetSprite(), m_fXPos, m_fYPos, Temp.GetSpeed ());

    // Insert shot into shotlist
    m_ShotList.push_back (Shot);

    // Shoot again, when space released
    m_bShotLock = true;

}

// Released space, so allow shooting
if (g_pFramework->KeyDown (SDL_SCANCODE_SPACE) == false)
    m_bShotLock = false;

} // ProcessShooting

```

Is that a strange approach or can I stick with it?

# Answer
It looks strange to me that you're copying the `CWeapon` objects everywhere: they look very much like the typical Type Object pattern, where an instance is immutable and represents an in-game *type* of weapon. In fact, I suggest renaming `CWeapon` to `WeaponType` and making it non-copiable. Then you pass around pointers to weapon types to use them, no copies needed.

You also apparently don't use constructors, which would be a good habit to get into: `Init` functions are neither needed nor practical in C++.

Refactoring your snippets, with some more inline tweaks, leads to:

### `Player.h`

```
class Player {

    // ...

    // std::array rather than C-style array
    // Also consider std::vector, even if the size doesn't change,
    // for you then don't need to update it when adding weapons.
    // Also made the member static (no need to duplicate it in various players)
    // and const (no apparent need to tweak weapon types on-the-fly).
    static std::array<WeaponType, 3> const unlockableWeapons;

    // Clear naming makes comments redundant
    std::vector<WeaponType const*> m_unlockedWeapons;

};

```

### `Player.cpp`

```
std::array<WeaponType, 3> const Player::unlockableWeapons{{
    {"LaserOrange.bmp", 0.2f, 400.0f, 20.0f},
    {"LaserBlue.bmp",   0.2f, 600.0f, 20.0f},
    {"LaserRed.bmp",    0.2f, 800.0f, 20.0f}
}};

bool Player::unlockWeapon() {

    auto const alreadyUnlocked = m_unlockedWeapons.size();

    // Simplify your control flow by returning early
    if(alreadyUnlocked == unlockableWeapons.size())
        // Everything is already unlocked
        return false;

    // Unlock the next weapon
    m_unlockedWeapons.push_back(&unlockableWeapons[alreadyUnlocked]);
    return true;
}

void Player::processShooting() {

    m_hasShot = false;

    if(!g_framework->keyDown(SDL_SCANCODE_SPACE)) {
        m_shotLock = false;
        return;
    }

    auto *const currentWeapon = m_unlockedWeapons[m_selectedWeapon];

    // Using emplace_back to construct the shot directly into the vector
    m_firedShots.emplace_back(
        currentWeapon.getSprite(),
        m_xPos, m_yPos,
        currentWeapon.getSpeed()
    );

    m_shotLock = true;
}

```

I've also tweaked the naming convention, which looked like it came from MFC. Usual (in my experience -- moderately broad but not a hard truth) C++ naming is:

* `PascalCase` with no prefix for classes;
* `camelCase` for functions;
* `camelCase` with prefix for non-public member variables. `m_` and `_` are two popular prefixes.
* No systems hungarian notation: C++ has types, no need to repeat them in the variable's name.

Yes, the standard library is a notable exception, which uses `snake_case` everywhere.
> 0 votes

---
Tags: c++
---


# Question
Title: Getting player cube to move left or right in relation to camera based on camera's rotation
Right now I'm trying to make the player cube move left, right, up and down in relation to the camera's rotation and position. I figured what I could do is create an empty game object, make the main camera the parent, and then get the vector pointing from the camera's child to another game object that follows the cube's exact position, and that would give me the direction the cube should roll towards.

I have my example in profile view, but in 3D view the camera should be facing the cube with the cube at the center.

So I have the following line of code code:

```
Vector3 forwardVector = (position1.transform.position - position2.transform.position).normalized;

```

If you look at the image on the right hand side, I Debug.GetLine'd the resulting vector from the cube's position and ended up with a vector pointing down. In theory though, it should be pushing off to the right hand side. Here's the rest of the code:

```
Vector3 perpendicularVector = Vector3.Cross (Vector3.up, resultant).normalized;

if (Input.GetKey (KeyCode.UpArrow))
{
    cube.rigidbody.AddForce ( forwardVector * moveSpeed);
}
if (Input.GetKey(KeyCode.DownArrow))
{
    cube.rigidbody.AddForce ( forwardVector * -moveSpeed);
}
if (Input.GetKey (KeyCode.LeftArrow))
{
    cube.rigidbody.AddForce ( perpendicularVector * -moveSpeed);
}
if (Input.GetKey (KeyCode.RightArrow))
{
    cube.rigidbody.AddForce ( perpendicularVector * moveSpeed);
}

```

As a result, when I press the up arrow key, I end up with the cube flying upwards toward the sky, and the down key brings it back down towards the plane, but my intention is for the vector to move along the XZ plane.

Also, with this line of code, I was hoping to get the line perpendicular to my intended vector and Vector3.up, but I naturally get wonky results from that.

```
Vector3 perpendicularVector = Vector3.Cross (Vector3.up, resultant).normalized;

```

If there's an easier method to achieving my goals, that's fine, but it would be nice too to figure out why the vector is pointing down instead of to the right.

It's also might be worth noting that the camera already successfully rotates around the player cube.

# Answer
Create a 4x4 rotation matrix:

```
Matrix4x4 rotation = Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(yourRotation), Vector3.one);

```

Then take the forward vector and multiply it with the rotation matrix:

```
Vector3 rotatedForward = rotation.multiplyVector(Vector3.forward);

```

Getting the vector that points left in the player's coordinate system can be simply achieved by using the vector (0, -1, 0) (Vector3.left) and rotating it with the rotation vector.

To move the object, just add/subtract the vectors from the current position of the object or add them as a force.
> -1 votes

---
Tags: unity, c#, software-engineering, vector, scripting
---


title: Visual Artifacts from motion blur

text:
# Question
Title: Visual Artifacts from motion blur
I tried to use this motion blur effect on my project but found some strange looking artifacts when setting it's alpha to low values. (Which increases the strength of the effect)

The effect works by only rendering a transparent image, so parts of the last few frames are still visible. When I set the alpha of the new image to a fairly low value (less than 0.5f) I get these strange artifacts:

Without the effect, the scene looks like this:

Notice that without the effect, the background is solid (minus lighting). The artifacts do not go away after any amount of time. For my implementation of the effect, I created a BufferedImage, rendered everything to it, then rendered the image to the screen with transparency. Could someone provide an explanation as to why these artifacts are occuring? Is there possibly a way that I could repair this?

```
image = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT)

//Draw everything to image

Graphics g = bs.getDrawGraphics();
Graphics2D g2d = (Graphics2D) g;
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
g.drawImage(image, 0, 0, null);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f));
g.dispose();

```

# Answer
When you redraw the scene with a transparent color it always leaves a trail behind. Because of the blending mode, the screen never gets completely cleared, thus the oldest frames will be visible.
> 1 votes

---
Tags: java, rendering
---


# Question
Title: Google Play Services and COPPA Compliance
I hesitated to ask this question here, since i'm not sure there is a definitive answer (but there can be, maybe i missed it).

I'm implementing Google Play Services for a game on Android target at all audiances, including children under 13.

So, I was wondering, does the use of achievements comply with COPPA rules? On one hand the app is not using personal informations (only reporting progress of achievements, which can be score, or number of games... nothing personal), BUT on the other hand, the authentication itself to google play games seems to be personal information sent to the internet (the auth process itself). I'm already using admob with the `tagForChildDirectedTreatment`.

So i was wondering, if achievements (and maybe leaderboards) need specific steps to comply with COPPA, is there something like this `tagForChildDirectedTreatment` but for achievements, ... or do I have to show a panel to get parental authorization? Or maybe set the google play connection as optional, not default as written somehow here?

The reason why i'm so concerned by this is this little $16000 fine i read several times, in case you don't respect whatever has to be respected.

# Answer
> 2 votes
You probably need to ask a lawyer to be sure; I am not a lawyer, so take what I say with a grain of salt. You can almost certainly find a lawyer to advise you on this matter for less than $16,000, so that seems like a good investment to me.

For reference, this is the COPPA law and these are the FTC's FAQs on compliance. This is the source of most of my conjecture, below, but you should read them both yourself.

---

First, Google Play's legal terms prevent users under 13 from using the service.

> Age Restrictions. In order to use Google Play you must be 13 years of age or older.

So legally, no such user can be *directly* accessing your application anyway. However, you probably still want to protect yourself from a child who illegally or indirectly accesses your application. COPPA does not *require* you to investigate the age of users, and it does not *require* you to offer your services to users under 13, so you can, like Google Play, simply block them from participating via your own EULA. However COPPA does not permit you to block them if your game is targeted to that audience. Thus, you should avoid explicitly targeting that audience. It's probably the safest option, because you don't have "actual knowledge" that a user is under 13.

What constitutes "targeting" that audience (making your app "child-directed," see the FAQs) is fuzzy, so perhaps you can't (or just won't) explicitly exclude or block them. In that case, you need to be aware that even a unique identifier suitable for tracking achievements is considered "personal information."

> (7) A persistent identifier that can be used to recognize a user over time and across different Web sites or online services. Such persistent identifier includes, but is not limited to, a customer number held in a cookie, an Internet Protocol (IP) address, a processor or device serial number, or unique device identifier;

Fortunately, you may be covered by the exception to requiring parental consent

> (c) Exceptions to prior parental consent. Verifiable parental consent is required prior to any collection, use, or disclosure of personal information from a child except as set forth in this paragraph:
>
> ...
>
> (7) Where an operator collects a persistent identifier and no other personal information and such identifier is used for the sole purpose of providing support for the internal operations of the Web site or online service. In such case, there also shall be no obligation to provide notice under §312.4;

So the tl;dr is:

* don't put yourself in a scenario where you have actual knowledge that a user is under 13
* if you just collect an identifier and only use it to drive your achievements, you're probably okay
* ask a lawyer, because I'm just some guy on the internet who doesn't mind reading legal documents now and then and could be missing something *very* important

# Answer
> 0 votes
The Google account already takes care of COPPA compliance. Google will refuse to make an account if you are ~~honest and don't want to lie~~ below 13 years old. Just open a private browser window and try to make a new Google account with a birthdate below 13: it will refuse.

So you don't have to worry about it.

---
Tags: android, google-play-services, achievements
---


# Question
Title: C# Adventure Game - Simple Dialog System
For school we have to make a small adventure game in C# (Visual Studio 2015) with a custom game engine made by our teacher. Now I want to implement a small dialog system between Liz (The main characer) and her teddybear.

The way I would like it to work is by using buttons. The bear starts out with "I can't let you pass Liz". Then the player can choose between three options (which are buttons) 1. \[Question\] 2. \[Demand\] 3. \[Observe\].

I am just not sure how to implement this and what would be the most efficient way of doing this codewise. To make it a bit more clear I've added an image of the entire dialog that needs to be implemented.

Any help/tips would be welcome!

Thanks in advance

# Answer
> 3 votes
Imagine the system as rooms with doors/teleports. Every decision is a door, each group of decisions is a room. When you pick a decision, you go from one "room" to a different one.

So, in code terms:

You should have 2 objects, Decision and Group

A decision should know it's type (question, demand, observer) and the next group of decisions it points to, and the groups should store decisions.

In the main class you should have a current group and present the options to the player. When he chooses one, get that decision object and set the current group to the one inside it.

This method is basically a linked list with multiple links.

# Answer
> -6 votes
Just code. Lots of IF statements. If your teacher wanted you to do this, the engine or classes would help you.

---
Tags: c#, dialogue-tree
---


title: Draw fonts in Hololens using SharpDX

text:
# Question
Title: Draw fonts in Hololens using SharpDX
I am using SharpDX to create an application in Hololens and I'm trying to understand how to use `DirectWrite` to draw variable text in 3D stereoscopic view. I have gone through this question, but the answers rely on other libraries.

MVP Dwight Goins provided me with this Rendering-3D-Text tutorial to help me out which uses the DirectX ToolKit. The closest I've got to is the Holographic-Tag-Along sample for holographic applications given by Microsoft. These two samples pretty much cover what I'm looking for but it is in C++. However, due to some project constraints, I need this to be in C#.

I am pretty new to computer graphics and therefore I do not fully understand how to achieve the same thing that the above two samples I've mentioned does in C# using SharpDX. Any help that could be provided to achieve the same output in C# would be much appreciated.

# Answer
The sample you provided is actually not using `DirectWrite` I think, which would not be your best bet in any case, because the `DirectWrite` feature is a strictly 2D one (it is part of the `SharpDX.Direct2D` API). While your application seems to need to render in 2D, you actually are rendering a flat 3D object in 3D space from various vantage points, multiple times, and ensuring that these are consistently facing in a set of pre-defined directions (see billboarding). Thus, you would need a 3D engine which incorporated 2D elements (i.e. billboarding), rather than a strictly 2D one that you would be using should you go the `DirectWrite` route. Plus, there's a good amount of overhead for rendering everything stereoscopically, and `DirectWrite` is notoriously slower than it's counterparts.

I'm not too versed in hololens, and I won't pretend know the specifics of how exactly such an effect would be achieved, but I imagine what you might do is have the 3d text sitting in 3d space, and billboard in the direction of the viewer. There's probably a slew of techniques for things such as stabilization and velocity estimation, but the underlying premise would be billboarding that image with respect to the viewer.

I hope this helps a bit. Again, hololens isn't necessarily something I'm familiar with, but I wanted to say mostly that if you try to do this with `DirectWrite` you're going to have a bad time.

### EDIT:

It occurs to me that this might be slightly misleading, because I phrased it in such a way that implies `DirectWrite` is incompatible with 3D, which isn't really true. You can indeed use `DirectWrite` in conjunction with Direct3D to render to 3D space, but `DirectWrite` itself only writes to a 2D surface. I really should have said don't use `DirectWrite` **by itself** to write to 3D space.

In order to use `DirectWrite` to write to 3D space, you would need to create a flat quad in 3D space, and use the render to texture technique in order to render your `DirectWrite` text to a texture. This texture may then be wrapped on that quad, and the quad may then be placed in 3D space to be rendered in 3D.
> 1 votes

---
Tags: c#, sharpdx, fonts, hololens
---


# Question
Title: Objects do not stop when colliding each other while using mouse drag
I work on a 2D game and I have multiple objects that the player can control.

The objects each have a RigidBody2D and a Collider, and a method `OnMouseDrag()` with which I can drag the objects.

I want the dragging to stop when the objects hit each other.

I tried by using this:

```
rigidbody2d.velocity = Vector3.zero;
rigidbody.isKinematic = true;

```

But the objects do not stop.

I want exactly like this video. I tried this but it isn't work too.

https://www.youtube.com/watch?v=ZfjVR-0ZFHU&t=270s

```
using UnityEngine;
 using System.Collections;
public class NewBehaviourScript1 : MonoBehaviour
{

bool allowDrag = true;
void OnCollisionEnter(Collision collision)
{
    allowDrag = false;
}

void OnMouseDrag()
{
    if(allowDrag)
    {
    float distance = 7;
    Vector3 mousePosition = new Vector3 (Input.mousePosition.x, Input.mousePosition.y , distance);
    Vector3 objPosition = Camera.main.ScreenToWorldPoint (mousePosition);
    transform.position = objPosition;
        if ((transform.position.x <0))
            {
            Vector3 _tmp = transform.position;
            _tmp.x = 0;
            transform.position = _tmp;
            }
            if ((transform.position.x > 4.5f))
            {
            Vector3 _tp = transform.position;
            _tp.x = 4.5f;
            transform.position = _tp;
            }

    }
}
void OnMouseUp()
{
    if ((transform.position.x > 0) && (transform.position.x < 0.375f))
        {
        Vector3 _tr = transform.position;
        _tr.x = 0;
        transform.position = _tr;
        }
    if ((transform.position.x > 0.375f) && (transform.position.x < 1.25f))
        {
        Vector3 _fs = transform.position;
        _fs.x = 0.75f;
        transform.position = _fs;
        }
    if ((transform.position.x > 1.125f) && (transform.position.x < 1.875f))
        {
        Vector3 _tr2 = transform.position;
        _tr2.x = 1.5f;
        transform.position = _tr2;
        }
    if ((transform.position.x > 1.875f) && (transform.position.x < 2.625f))
        {
        Vector3 _tr4 = transform.position;
        _tr4.x = 2.25f;
        transform.position = _tr4;
        }
    if ((transform.position.x > 2.625f) && (transform.position.x < 3.375f))
        {
        Vector3 _tr6 = transform.position;
        _tr6.x = 3;
        transform.position = _tr6;
        }
        if ((transform.position.x > 3.375f) && (transform.position.x < 4.125f))
        {
        Vector3 _tr7 = transform.position;
        _tr7.x = 3.75f;
        transform.position = _tr7;
        }
    if ((transform.position.x > 4.125f) && (transform.position.x < 4.875f))
        {
        Vector3 _tr8 = transform.position;
        _tr8.x = 4.5f;
        transform.position = _tr8;
        }
}
void Start ()
{
}
void Update()
{
}

```

}

Please help!

# Answer
> 3 votes
The drag movement is not being applied through a force on the rigidBody but directly on the object's transform position, so what you are trying to do wont work. Instead you need to detect the collision and then disable OnMouseDrag with a boolean value sort of like this:

```
bool allowDrag = true;

void OnMouseDrag() {
     if(allowDrag)
     {
        //... do something
     }
}

```

---
Tags: unity, collision-detection, rigid-body-dynamics, rigidbody
---


# Question
Title: How to make 2D bullet have smooth bounce?
I have an example:

```
//Code that need to run
var codeRun = `
function* example(x, y) {
  x = x || Shmup.advanced.data().scene.size.x / 2;
  y = y || Shmup.advanced.data().scene.size.y / 3.75;
  var angle = 0;
  while (true) {
    //for (var i = 1; i <= 360; i ++) {
      var obj = fireBullet(x, y, 5, angle);
      Shmup.util.task(testing, [obj], {update: true, reset: false});
      angle += /*360 / 8 +*/ 0.5;
    //}
    yield* wait(1);
  }
}
Shmup.util.task(example, [], {update: true, reset: false});
//The function above will create a generator and push it to a large array that will
//run every generator in it for every update

function* testing(obj) {
  //Main part of bouncing
  var angleBounce = 0, bounceTime = 2;
  //yield one frame
  yield;
  while (bounceTime > 0) {
    yield;
    //Function below will check for collision with border
    if (Shmup.util.out(5, obj.position)) {
      /*
      The "type" variable is just for choosing collision type,
      in this case "5": all 4 walls, return boolean
      function (type, position) {
        return position.x < 0 ||
        data.scene.size.x < position.x ||
        position.y < 0 ||
        data.scene.size.y < position.y;
      }
      And "0" is return integer what wall bullet hit
      */
      switch (Shmup.util.out(0, obj.position)) {
        case 1:
        case 3: {
          //Check if hit vertical wall
          angleBounce = 90;
        }
        break;
        case 2:
        case 4: {
          angleBounce = 180;
        }
        break;
      }
      obj.angle = Shmup.math.angle.bounce(obj.angle,
                  Shmup.math.angle.degree.radian(angleBounce));
      /*
      The function above:
      function bounce(angle, mirrorAngle) {
        return 2 * mirrorAngle - angle;
      }
      */
      bounceTime -= 1;
    }
  }
  while (true) {
    //This loop will just check if bullet hit wall then break it
    yield;
    if (Shmup.util.out(5, obj.position)) {
      break;
    }
  }
  //Delete bullet
  obj.data.isDelete = true;
}

//Nothing really important from here
function fireBullet(x, y, speed, angle) {
  return Shmup.projectile.bullet.add({
    position: {
      x: x,
      y: y,
    },
    angle: Shmup.math.angle.degree.radian(angle),
    speed: speed,
    data: {
      graphic: (function() {
        var bulletImg = new PIXI.Sprite(spritesheet);
        bulletImg.anchor.set(0.5, 0.5);
        stage.addChild(bulletImg);
        return bulletImg;
      })(),
      isDelete: false,
    },
    update: function(projectile) {
      projectile.data.graphic.position.set(projectile.position.x, projectile.position.y);
      projectile.data.graphic.rotation = -projectile.angle;// - Math.PI;
      if (deleteProjectile === true || projectile.data.isDelete === true) {
        if (Shmup.advanced.process().active.length <= 1) {
          deleteProjectile = false;
        }
        stage.removeChild(projectile.data.graphic);
        Shmup.projectile.bullet.remove(projectile);
      }
    },
  });
}
function* wait(data) {
  var waiter = Shmup.util.count({
    min: 0,
    max: data,
    change: 1,
    reset: true,
  });
  while (waiter() < data) {
    yield;
  }
}`;

//From here nothing inportant
HTMLCanvasElement.prototype.fitWindow = function() {
  var resize = function() {
    var rateWidth = this.width / window.innerWidth;
    var rateHeight = this.height / window.innerHeight;
    var rate = this.height / this.width;
    if (rateWidth > rateHeight) {
      this.style.width = innerWidth + "px";
      this.style.height = innerWidth * rate + "px";
    } else {
      this.style.width = innerHeight / rate + "px";
      this.style.height = innerHeight + "px";
    }
  }.bind(this);
  window.addEventListener("resize", resize, false);
  resize();
};

// requestAnim shim layer by Paul Irish
//http://paulirish.com/2011/requestanimationframe-for-smart-animating
window.requestAnimFrame = (function(){
  return window.requestAnimationFrame ||
  window.webkitRequestAnimationFrame ||
  window.mozRequestAnimationFrame ||
  window.oRequestAnimationFrame ||
  window.msRequestAnimationFrame ||
  function(callback, element){
    window.setTimeout(callback, 1000 / 60);
  };
})();

var keyboard = {
  up: false,
  down: false,
  left: false,
  right: false,
  shift: false,
};
window.addEventListener("keydown", function(e) {
  switch (e.keyCode) {
    case 37:
      keyboard.left = true;
      break;
    case 38:
      keyboard.up = true;
      break;
    case 39:
      keyboard.right = true;
      break;
    case 40:
      keyboard.down = true;
      break;
    case 16:
      keyboard.shift = true;
      break;
  }
}, false);
window.addEventListener("keyup", function(e) {
  switch (e.keyCode) {
    case 37:
      keyboard.left = false;
      break;
    case 38:
      keyboard.up = false;
      break;
    case 39:
      keyboard.right = false;
      break;
    case 40:
      keyboard.down = false;
      break;
    case 16:
      keyboard.shift = false;
      break;
  }
}, false);
window.addEventListener('keydown', function(e) {
  switch (e.keyCode) {
    case 37:
    case 38:
    case 39:
    case 40:
    case 16:
      //e.preventDefault();
    break;
  }
}, false);

function isSlow() {
  if (keyboard.shift) {
    return player.slow;
  } else {
    return 1;
  }
}

//Pre-processing
var renderer = new PIXI.autoDetectRenderer(
  384 * 2, 448 * 2,
  {antialias: false, transparent: true, resolution: 1}
);
renderer.autoResize = true;
document.body.appendChild(renderer.view);
renderer.view.fitWindow();

var stage = new PIXI.particles.ParticleContainer(10000 , {
  rotation: true,
  alpha: false,
  scale: false,
  uvs: false,
});

var spritesheet;

Shmup.configs({
  maxProjectile: {
    bullet: 10000,
    laser: 1,
    curve: 1,
    curveNode: 1,
  },
  scene: {
    size: {
      x: 384 * 2,
      y: 448 * 2,
    },
    boundary: 10,
  },
});

Shmup.advanced.performance.configs({
  smoothing: 10,
  maxMs: 0,
});

PIXI.loader
  .add("test", "https://cdn.rawgit.com/Trung0246/Shmup/stable/img/down_arrow_icon.png")
  .load(setup);

//Variables
var player = {
  x: Shmup.advanced.data().scene.size.x / 2,
  y: Shmup.advanced.data().scene.size.y - 50,
  speed: 3.75,
  slow: 0.55,
};

//Main process
function setup() {
  spritesheet = PIXI.loader.resources["test"].texture;
  console.log("Done Loading... Now entering main loop...");
  loop();
}

function loop() {
  Shmup.advanced.performance.start();
  if (keyboard.left) {
    player.x -= player.speed * isSlow();
  } else if (keyboard.right) {
    player.x += player.speed * isSlow();
  };
  if (keyboard.up) {
    player.y -= player.speed * isSlow();
  } else if (keyboard.down) {
    player.y += player.speed * isSlow();
  };
  player.x = Math.max(0, Math.min(player.x, Shmup.advanced.data().scene.size.x));
  player.y = Math.max(0, Math.min(player.y, Shmup.advanced.data().scene.size.y));
  Shmup.update();
  renderer.render(stage);
 Shmup.advanced.performance.end();
  requestAnimFrame(loop);
}

setInterval(function() {
  document.getElementById("data1").innerHTML = "Frame: " + Shmup.advanced.data().frame + "<br/>" + "Count: " + Shmup.advanced.process().active.length;
  document.getElementById("data3").innerHTML = "MS: " + Shmup.advanced.performance.ms().toFixed(3);
}, 0);
setInterval(function() {
  document.getElementById("data2").innerHTML =  "FPS: " + Shmup.advanced.performance.fps().toFixed(3);
}, 50);

document.getElementById("evalScript").onclick = function() {
  eval(codeRun);
};

document.getElementById("clearTask").onclick = function() {
  Shmup.advanced.temp().task = [];
};

var deleteProjectile = false;

document.getElementById("clearProjectile").onclick = function() {
  if (deleteProjectile === false) {
    deleteProjectile = true;
  } else {
    deleteProjectile = false;
  }
};
```

```
body {
  padding: 0px;
  margin: 0px;
}
#control {
  position: fixed;
  top: auto;
  bottom: auto;
  left: auto;
  right: 0%;
  width: 45%;
  height: auto;
}
p {
  margin: 0px 0px 0px 0px;
  position: absolute;
}
#showData {
  position: absolute;
  top: 20%;
  bottom: auto;
  left: auto;
  right: 0%;
}
p#data1 {
  top: 0%;
  bottom: auto;
  right: 0%;
  left: auto;
}
p#data2{
  top: 90px;
  bottom: auto;
  right: 0%;
  left: auto;
}
p#data3{
  top: 140px;
  bottom: auto;
  right: 0%;
  left: auto;
}
canvas {
  border: 2px solid black;
  border-radius: 5px;
}

input {
  margin: 0px 0px 0px 0px;
}
/*https://github.com/Trung0246/Shmup/tree/development-1.2%2B*/
```

```
<script src="https://pixijs.download/release/pixi.js"></script>
<script src="https://cdn.rawgit.com/Trung0246/Shmup/7e079cec9a7d478ad5add01a6c97e3717ae1a600/build/Shmup.js"></script>
<script src="https://cdn.rawgit.com/Trung0246/Shmup/d0e087c7ca5f6014e42a3fdcb6fee1a2f0e800af/plugins/basicProjectile.js"></script>
<body>
  <div id="control">
    <button id="evalScript">Run script</button>
    <button id="clearTask">Clear task</button>
    <button id="clearProjectile">Clear projectile</button>
    <div id="showData">
      <p id="data1"></p>
      <p id="data2"></p>
      <p id="data3"></p>
    </div>
  </div>
</body>
```

PS: Really sorry for long snippet :(, anyone can edit to hide html and css part?

P.S.S: Click both "Clear task" and "Clear projectile" for delete all bullet

When you click "Run script", you will see the problem that bullet when touching border will bounce back not smoothly, and I want it to be smooth curve...

How to do it? And explaination behind it?

# Answer
> 0 votes
I can't quite make head or tail of your code, and not knowing Javascript doesn't help (that's Javascript, right?)

However the solution to your problem is more of a physics one: when you detect that a projectile should bounce, you directly change its direction. This leads to the abrupt dent in the trajectories.

If you want more of a "smooth" bounce, you need to allow your bullets to decelerate, then accelerate towards the opposite direction. In other words, replace your walls with force fields.

Adding forces is much, much easier to do with cartesian vectors (i.e. `(x, y)` pairs) than with polar vectors (the `(direction, magnitude)` pairs you have). I suggest you switch to cartesian.

When it's done, you can use an approximation of Newton's physics to apply your forces directly on the projectile's speed:

```
// Returns the sum of the forces from all walls
vec2 getWallForce(vec2 pos) {

    float margin = /* AoE of the forcefield around the walls */;
    float strength = /* Strength of repulsion */;

    // Assumes boolean-to-int conversion
    return strength * vec2{
        (pos.x < margin) - (pos.x > data.scene.size.x - margin),
        (pos.y < margin) - (pos.y > data.scene.size.y - margin)
    };
}

// ...

foreach bullet {
    vec2 wallForce = getWallForce(bullet.pos);

    // Integrate with the elapsed time
    bullet.speed += wallForce * deltaTime;
}

```

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


title: Cubes are separating from each other

text:
# Question
Title: Cubes are separating from each other
I recently asked this question

```
        public void spawnCube() {
      cubes = new Array < Rectangle > ();
      for (int i = 0; i < 3; i++) {
          Rectangle cube = new Rectangle();
          cube.x = xpos;
          cube.y = ypos;
          cube.width = width;
          cube.height = height;
          xpos += 28;
          if (Gdx.input.justTouched()) {
              cubes2.add(cube);
              score++;
          }
          cubes.add(cube);
      }
  }

  public void moveCube() {
      Iterator < Rectangle > iter = cubes.iterator();
      while (iter.hasNext()) {
          Rectangle cube = iter.next();
          cube.x += speed * Gdx.graphics.getDeltaTime();
          if (cube.x + cube.width > 800 || cube.x < 0)
              speed = -speed;
      }
  }

```

The first method generates 3 cubes, the second one moves them from right to left and back. Cube size 15w 30h. Screen size 800w 400h.

The problem I have is that after 2 or 3 cycles of the cubes going from right to left, the cube on the left gets seperated from the other two. It seems that the other two cubes are pushing the first one out of place. How to prevent that from happening?

# Answer
> 1 votes
All cubes hare the same `speed`, so when you update the first with a new position and detect the collision and negate the `speed` the cubes that are processed after the first one will move in the opposite direction of the first for one frame. That could cause the behaviour you are describing. One way to fix it can be to update all positions first and then calculate a new speed. You can also try having individual speeds per cube.

# Answer
> 1 votes
The reason they are overlaying is that they are not moving at the same speed at each step.

Let's say you are moving to the left and your first box to move is the left one, if it reaches the border the direction will change but the left box' direction was **left** when the 2 other boxes' direction will be **right** which indeed causes the `the cube on the left gets seperated from the other two` problem

---
Tags: java, android, libgdx
---


# Question
Title: Create Render Target View [138][140] need to Bind the back buffer to the render target view DirectX 11
This is the error

```
D3D11 ERROR: ID3D11Device::CreateRenderTargetView: A RenderTargetView cannot be created of a Resource that did not specify the RENDER_TARGET BindFlag. [ STATE_CREATION ERROR #138: CREATERENDERTARGETVIEW_INVALIDRESOURCE]
D3D11 ERROR: ID3D11Device::CreateRenderTargetView: Returning E_INVALIDARG, meaning invalid parameters were passed. [ STATE_CREATION ERROR #140: CREATERENDERTARGETVIEW_INVALIDARG_RETURN]

```

So as i see here i need to set the BindFlag of the backBuffer to D3D11\_BIND\_RENDER\_TARGET, but in all the tutorial i saw nobody is doing it, they all create the render target view by using this code

```
hr=m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&m_backBuffer));
if (FAILED(hr)) MessageBox(0, L"Failed get buffer", 0, 0);
hr=m_device->CreateRenderTargetView(m_backBuffer, NULL, &m_renderTargetView);
if (FAILED(hr)) MessageBox(0, L"Failed to create rendertargetview", 0, 0);

```

And nobody, nowhere is doing as the msdn site says, that the render target view must be created with this specific flag: D3D11\_BIND\_RENDER\_TARGET

So I tried doing it by myself.

I created a texture2d desc like this for the back buffer:

```
D3D11_TEXTURE2D_DESC backBufferDescription;
    backBufferDescription.BindFlags = D3D11_BIND_RENDER_TARGET;
    backBufferDescription.ArraySize = 1;
    backBufferDescription.CPUAccessFlags = 0;
    backBufferDescription.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    backBufferDescription.Height = 600;
    backBufferDescription.Width = 800;
    backBufferDescription.MipLevels = 1;
    backBufferDescription.MiscFlags = 0;
    backBufferDescription.SampleDesc.Quality = 0;
    backBufferDescription.SampleDesc.Count = 1;
    backBufferDescription.Usage = D3D11_USAGE_DEFAULT;
    m_device->CreateTexture2D(&backBufferDescription, NULL, &m_backBuffer);
    if (FAILED(hr))
        MessageBox(0, L"Fallito back buffer desc", 0, 0);

```

And it doesn't work the same.

Help please

# Answer
The code you are referring to from MSDN is using the Texture2D resources created for the swap chain, which are only usable as render targets (i.e. `D3D11_BIND_RENDER_TARGET` is implicit).

In this *DirectX Tool Kit* tutorial, I'm creating my own render target textures that can also be used as a texture.

```
// Full-size render target for scene
CD3D11_TEXTURE2D_DESC sceneDesc(backBufferFormat, backBufferWidth, backBufferHeight,
    1, 1, D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE);
DX::ThrowIfFailed(m_d3dDevice->CreateTexture2D(&sceneDesc, nullptr,
    m_sceneTex.GetAddressOf()));
DX::ThrowIfFailed(m_d3dDevice->CreateRenderTargetView(m_sceneTex.Get(), nullptr,
    m_sceneRT.ReleaseAndGetAddressOf()));
DX::ThrowIfFailed(m_d3dDevice->CreateShaderResourceView(m_sceneTex.Get(), nullptr,
    m_sceneSRV.ReleaseAndGetAddressOf()));

// Half-size blurring render targets
CD3D11_TEXTURE2D_DESC rtDesc(backBufferFormat, backBufferWidth / 2, backBufferHeight / 2,
    1, 1, D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE);
Microsoft::WRL::ComPtr<ID3D11Texture2D> rtTexture1;
DX::ThrowIfFailed(m_d3dDevice->CreateTexture2D(&rtDesc, nullptr,
    rtTexture1.GetAddressOf()));
DX::ThrowIfFailed(m_d3dDevice->CreateRenderTargetView(rtTexture1.Get(), nullptr,
    m_rt1RT.ReleaseAndGetAddressOf()));
DX::ThrowIfFailed(m_d3dDevice->CreateShaderResourceView(rtTexture1.Get(), nullptr,
    m_rt1SRV.ReleaseAndGetAddressOf()));

Microsoft::WRL::ComPtr<ID3D11Texture2D> rtTexture2;
DX::ThrowIfFailed(m_d3dDevice->CreateTexture2D(&rtDesc, nullptr,
    rtTexture2.GetAddressOf()));
DX::ThrowIfFailed(m_d3dDevice->CreateRenderTargetView(rtTexture2.Get(), nullptr,
    m_rt2RT.ReleaseAndGetAddressOf()));
DX::ThrowIfFailed(m_d3dDevice->CreateShaderResourceView(rtTexture2.Get(), nullptr,
    m_rt2SRV.ReleaseAndGetAddressOf()));

```

See this link for the full source example.

**Of course the key thing to note is that you can't see or `Present` render targets that are not part of the swap chain. You have to copy them to the swapchain buffer or render with them into the swapchain render target at some point.**
> 1 votes

---
Tags: directx11, c++
---


# Question
Title: What happens to the RPM when I apply brakes to the wheel collider?
I'm very new to Unity game development, and I am working on a car controller script in C#. What happens to the RPM when I apply brakes to the wheel collider? I do not know how to view the RPM changes.

# Answer
> 2 votes
You would have to look at the Angular Velocity of the RigidBody your WheelCollider is connected to.

Angular Velocity is measured in radians per second.

One full revolution is equal to 2\*PI, which is about 6.28 radians.

So your active RPM can be measured as follows:

```
float RPM = RigidBody.angularVelocity / 2PI / 60;

```

---
Tags: unity
---


title: Java 2D Game: Collision help

text:
# Question
Title: Java 2D Game: Collision help
Ok, so in my Java2D Game, using swing/awt (I hear it is not the best to combine those), I am trying to finish collisions.

---

**So, the problem is, the "if (player.xvel \< 0) { }" and the "if (player.xvel \> 0) { }" in the Block class are still being executed even though the player hasn't run into the block horizontally.** How can I make it so the code is executed when the player runs/walks into the block horizontally?

My code for the collide function is below, in Block.java:

```
    void collide(Player player) {
        Rectangle player_hb = new Rectangle((int) player.x, (int) player.y, (int) player.width, (int) player.height);
        Rectangle block_hb = new Rectangle(x + Display.graphics_panel.WorldX, y, width, height);

        if (player_hb.intersects(block_hb)) {
            Rectangle intersection = (Rectangle) player_hb.createIntersection(block_hb);

            if (player.yvel > 0) {
                player.jumping = false;
                player.y -= intersection.getHeight();
            }
            if (player.yvel < 0) {
                player.yvel = 0;
                player.y += intersection.getHeight();
            }
            /* Execute this code ONLY if player is intersecting a block HORIZONTALLY!! */
            if (player.xvel > 0) {
                System.out.println("You shouldn't see this unless you run into a block!" + i++);
            }
            if (player.xvel < 0) {
                System.out.println("You shouldn't see this unless you run into a block!" + i--);
            }
        }
    }

```

# Answer
Ok, I finally found the solution! I made a hitbox for the x-axis so the x wouldn't interfere with the y. (by subtracting 10 from the y and 20 from the height) Now collisions are working abosolutely perfect!
> 1 votes

---
Tags: java, 2d, collision-resolution, collision-prediction
---


# Question
Title: gamemaker studio draw event to have collision detection/solid
i dont know if this was able at the first time but do any one know how to make an object draw event to be solid or have collision ? i really needed it, cause i'm too lazy to make for example a box sprite, and i have 1 more question. Do you guys know under tale? if you do how do they make the box in the battle system goinng smaller like an animation, if you had the answer please tell me :3, sorry if i had bad english

# Answer
I was searching for the same thing, and I found that if you use the transform sprite event and a regular square sprite, you can make rectangles by expanding them and set up a Collison system for the object like Undertale.
> 0 votes

---
Tags: game-maker
---


# Question
Title: MonoGame - render target drawn below other sprites and in the wrong location
This seems like a simple thing but still doesn't work. So I'm trying to draw a scrollable log window (not scrolling yet) by using a RenderTarget2D.

There are several bugs:

* The text should be drawn on a black background, now it seems transparent
* The text should be drawn in the black box below the game area, now it's drawn in the top left corner
* The text appears now on the background color only, it should be drawn over the other sprites

What's wrong with my code? The relevant parts are below.

```
    private GraphicsDevice graphicsDevice;
    private RenderTarget2D logRenderTarget;

    private bool redrawLogFlag;

    public void Init(ContentManager content, GraphicsDevice graphicsDevice)
    {
        this.graphicsDevice = graphicsDevice;
        logRenderTarget = new RenderTarget2D(
            graphicsDevice,
            10,
            10
        );
        Log.LogWritten += SetRedrawLogFlag;
    }

    private void DrawUiComponents(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(Scavenger.AssetManager.TextureMap["game_area"], Vector2.Zero, Color.White);
        spriteBatch.Draw(Scavenger.AssetManager.TextureMap["log_area"], new Vector2(0, Constants.GAME_AREA_HEIGHT), Color.White);
        spriteBatch.Draw(Scavenger.AssetManager.TextureMap["stats_area"], new Vector2(Constants.GAME_AREA_WIDTH, 0), Color.White);
        spriteBatch.Draw(Scavenger.AssetManager.TextureMap["help_info"], new Vector2(Constants.GAME_AREA_WIDTH, Constants.SCREEN_HEIGHT - 52), Color.White);

        DrawStats(spriteBatch);
        TryRedrawLog(spriteBatch);
        WriteLog(spriteBatch);
    }

    private void SetRedrawLogFlag(object sender, EventArgs e)
    {
        redrawLogFlag = true;
    }

    private void TryRedrawLog(SpriteBatch spriteBatch)
    {
        if(redrawLogFlag)
        {
            redrawLogFlag = false;

            logRenderTarget = new RenderTarget2D(
                this.graphicsDevice,
                Constants.GAME_AREA_WIDTH,
                Log.Height
            );

            this.graphicsDevice.SetRenderTarget(logRenderTarget);
            this.graphicsDevice.Clear(Color.Black);

            for (int i = 0; i < Log.Count; i++)
            {
                spriteBatch.DrawString(Scavenger.AssetManager.Font12,
                    Log.Entries[i],
                    new Vector2(Constants.LOG_MARGIN, Constants.LOG_MARGIN + i * Scavenger.AssetManager.Font12.LineSpacing),
                    Color.GreenYellow
                );
            }

            this.graphicsDevice.SetRenderTarget(null);
        }
    }

    private void WriteLog(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(logRenderTarget,
            new Rectangle(0, Constants.GAME_AREA_HEIGHT, Constants.GAME_AREA_WIDTH, Constants.LOG_HEIGHT),
            new Rectangle(0, 0, Constants.GAME_AREA_WIDTH, Constants.LOG_HEIGHT),
            Color.White
        );
    }

```

# Answer
> 0 votes
I decided to switch to using a Viewport. It seems, however, that MonoGame uses the last set-up Viewport before the call to `spriteBatch.End()`. It also seems that it is the same with the ScissorRectangle, so I could have made it also work. I have added the ScissorRectangle-specific code here in comments. Here's my new class:

```
public class LogWriter
{
    private GraphicsDevice graphicsDevice;

    private Viewport defaultViewport, logViewport;
    //private Rectangle scissor, scissorBackup;

    public void Init(GraphicsDevice graphicsDevice)
    {
        this.graphicsDevice = graphicsDevice;

        defaultViewport = this.graphicsDevice.Viewport;
        logViewport = new Viewport(0, Constants.GAME_AREA_HEIGHT, Constants.GAME_AREA_WIDTH, Constants.LOG_HEIGHT);

        //scissor = new Rectangle(0, Constants.GAME_AREA_HEIGHT, Constants.GAME_AREA_WIDTH, Constants.LOG_HEIGHT);
        //scissorBackup = this.graphicsDevice.ScissorRectangle;
    }

    public void WriteLog(SpriteBatch spriteBatch)
    {
        this.graphicsDevice.Viewport = logViewport;
        //this.graphicsDevice.ScissorRectangle = scissor;

        spriteBatch.Begin();
        //spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, new RasterizerState() { ScissorTestEnable = true });

        for (int i = 0; i < Log.Count; i++)
        {
            spriteBatch.DrawString(Scavenger.AssetManager.Font12,
                Log.Entries[i],
                new Vector2(
                    Constants.LOG_MARGIN,
                    Constants.LOG_MARGIN + i * Scavenger.AssetManager.Font12.LineSpacing),
                Color.GreenYellow
            );
        }

        spriteBatch.End();

        this.graphicsDevice.Viewport = defaultViewport;
        //this.graphicsDevice.ScissorRectangle = scissorBackup;
    }
}

```

`Init()` is called in the `LoadContent()` function. `WriteLog()` is called in the `Draw()` function after `End()` has been called on the spriteBatch after drawing all the other things.

---
Tags: c#, monogame, text, scrolling, clipping
---


# Question
Title: Gamemaker: Get from which children action is called
I've got 3 Children in 1 Parent which has "Left pressed" action. I just want to know from which child this action is called.

I try `object_index` but obviously it returns Parent index.

Thanks in advance.

**EDIT #1**:
put in Left pressed

```
with(other) { var id = object_index; }

```

will return object child which perform this event

# Answer
I assume you want to guess what child object is performing the `Left Click` Event at a given step.

My answer is: instead of returning the `object_index`, because the parent's one will be returned in this case, return the actual instance `id`; then, check the `object_index` of such instance reference.

This way a child's `id` will be returned, and you can check what `object_index` such child has.
> 0 votes

---
Tags: game-maker
---


# Question
Title: Is there any reason to use a "canvas" based approach to GUI in isometric games?
When designing game engine GUI systems, I know a lot of game engines (notably Unity and Unreal) use a sort of "canvas" system. However, in an isometric game where the camera is already orthographic, this seems like it might be overkill. Everything is already dictated in terms of pixels, as is the case in an isometric game; I feel that there would be little need for such a "canvas", which seems to be the bridge between world space coordinates and screen space coordinates.

With the orthographic view, world space is more seamlessly joined with screen space, so wouldn't it be simpler to get the position of the camera, define a set of points (i.e. top-left, top-right, center, etc.) on a plane that is directly in front of the camera and render controls directly in front of the camera? Would there be any downsides to this method, or am I missing the point entirely?

# Answer
> Because everything is already dictated in terms of pixels, as is the case in an isometric game, \[...\]

This statement is false. It's not because you use an isometric camera projection that everything is based on pixels.

And it's not because you implement a GUI that you'll calculate everything in pixels: you might want to use screen proportions for some reasons. There are even situations where you could use a hybrid approach: layout some screen elements based on pixel sizes and positions, and use screen proportions to layout the other elements.

The idea of having your GUI implemented as a 'standalone' feature means that you can use *the same system everywhere in your game*, not just in the 'game play' state, as you would be constrained with your suggestion.

In the long run, it's really more practical to *decouple* your UI code from the rest of your game, at least in terms of projection.
> 2 votes

---
Tags: rendering, gui, projection
---


# Question
Title: Can art syle proportions have copyright?
I like the art of a mobile game called **Battleheart**.

Is it copyright infringement if I copy **only the proportions** of his characters? Obviously the clothes, style of the brush, and all the rest of the art will be my own style. The gameplay of the game will be different, too.

# Answer
I am not a lawyer, but the idea of being sued for copyright infringement based *entirely* off the proportions of a character sounds ludicrous. Bearing that in mind, your asking if you *can* be sued. The answer is most certainly *yes*.

Ultimately, you can be sued for *anything*. If that person feels confidant enough in their case to warrant the required expenditure, they are entirely within their right to do so. It may get thrown out of court on the first day, but they still have the right to take action.

You *should* be asking if there *could* be a reasonable case against you. Ultimately, as pointed out by Alexandre Vaillancort, you should consult a copyright lawyer for a more reliable response. That said, I find it highly unlikely that there would be any issue.

---

In your given example, you suggest copying the proportions of a character, while changing the general style, the brush style, and all of the equipment on the character. Such a change should look *nothing like* the original art; this would make claims of copyright infringement pretty difficult.

As a small caveat, if you openly admit to copying the original art in some way, this may provide enough grounds for a case. Unless you openly admit that you sat there and drew over the original character models, this would be very difficult to proove; I, for one, can not see anything particularly special about the proportions of the characters you provide as example. They look pretty regular.

As long as you retain *your own style*, you should be perfectly fine. Once again, you should consult a lawyer before making any legally-based decisions.

---

Note that if there *is* some concern, you have the option of simply contacting the developers. A simple email could explain the inspiration you are taking from their work, and how the resulting product would differ from their work. The developers, themselves, could directly tell you whether they would consider this a breech of copyright.

In such cases, you might even get feedback for how you could use such art in a way that the developer would consider acceptable. The developer may simply wish to have a thank you mention in the credits, or wish to provide you explicit permission to use the style, in the first place.
> 1 votes

---
Tags: legal, art, copyright
---


# Question
Title: Artifacts when trying to implement Cook-Torrance BRDF
I am trying to implement the Cook-Torrance BRDF within OpenGL, but I keep running into issues. The most obvious one are black patches and a bright spot at (0, 0). I checked my shader multiple times, but I can't find what's wrong with it: the functions I use are in line with everything I've seen online, and I can't see anything obviously wrong, neither there nor in the way I've implemented my deferred rendering pipeline.

The code I am using is:

```
#version 440

uniform sampler2DRect samplerWorldPosition;
uniform sampler2DRect samplerWorldNormal;
uniform sampler2DRect samplerWorldMatInfo;
uniform sampler2DRect samplerWorldMatColour;

uniform vec3 ambient_light_intensity;
uniform vec3 light_direction;
uniform vec3 light_intensity;

out vec3 reflectedLight;

// Approximates the fresnel effect
float fresnel_schlick(float VHdot, float refractive_index)
{
    float F0 = pow(1 - refractive_index / 1 + refractive_index, 2);
    return F0 + (1 - F0) * pow(1 - VHdot, 5);
}

// Uses the GGX distribution function
float GGX_distribution_func(float NHdot, float roughness)
{
    float alpha = roughness * roughness;
    float alpha_sqr = alpha * alpha;

    float NHdot2 = NHdot * NHdot;
    float exp = NHdot2 * alpha_sqr + (1 - NHdot2);

    return (alpha_sqr * max(0, NHdot)) / (3.14159 * exp * exp);
}

// Attenuation based on geometry
float geometric_attenuation(float NHdot, float NVdot, float VHdot, float NLdot)
{
    float G1 = (2 * NHdot * NVdot) / VHdot;
    float G2 = (2 * NHdot * NLdot) / VHdot;
    return min(1, min(G1, G2));
}

void main(void)
{
    vec3 texel_position = texelFetch(samplerWorldPosition,
        ivec2(gl_FragCoord.xy)).rgb;
    vec3 texel_normal = normalize(texelFetch(samplerWorldNormal,
        ivec2(gl_FragCoord.xy)).rgb);
    vec3 texel_diffuse = texelFetch(samplerWorldMatColour,
        ivec2(gl_FragCoord.xy)).rgb;
    vec3 mat_info = texelFetch(samplerWorldMatInfo,
        ivec2(gl_FragCoord.xy)).rgb;

    float diff_kd = mat_info.x;
    float roughness = mat_info.y;
    float IOR = mat_info.z;

    float NLangle = max(dot(texel_normal, light_direction), 0.0);

    float specular_light = 0;
    float geometric_term = 0;
    float GGX_facet_term = 0;
    float fresnel_term = 0;
    if (NLangle > 0.0)
    {
        vec3 view_direction = normalize(-texel_position);

        vec3 H = normalize(light_direction + view_direction);
        float NHangle = max(dot(texel_normal, H), 0.0);
        float NVangle = max(dot(texel_normal, view_direction), 0.0);
        float VHangle = max(dot(view_direction, H), 0.0);

        geometric_term = geometric_attenuation(NHangle, NVangle, VHangle, NLangle);
        GGX_facet_term = GGX_distribution_func(NHangle, 0.5);
        fresnel_term = fresnel_schlick(VHangle, 0.5);

        specular_light = (geometric_term * GGX_facet_term * fresnel_term) / (3.14 * NVangle * NLangle);
    }

    reflectedLight = NLangle * (light_intensity * specular_light +
        (texel_diffuse)) + ambient_light_intensity;
}

```

This code uses (or at least is meant to use) the standard Cook-Torrance model, with GGX microfacet distribution, the Schlick fresnel approximation and the Cook-Torrance geometric attenuation.

This is an example of the errors I am getting:  The errors are quite evident. What is wrong with this shader?

# Answer
> 2 votes
When you see abrupt patches of black like these often the cause of this are NaNs (Not A Number) from divisions by zero.

And then anything multiplied by an NaN will give an NaN or (almost) any other operations and functions for that matter.

Things like

```
float NVangle = max(dot(texel_normal, view_direction), 0.0);

specular_light = (geometric_term * GGX_facet_term * fresnel_term) / (3.14 * NVangle * NLangle);

```

Are likely culprit.

I'd look at the `dot(texel_normal, view_direction)` to see if it gives a zero. Even if neither `NVangle` nor `NLangle` are zero, both multiplied by each other can give a number so small that it gets rounded to zero.

You need to leave a good safety margin before doing a division in a shader as there is practically no guarantee it will be done with full 32bit float precision.

Try:

```
specular_light = (geometric_term * GGX_facet_term * fresnel_term) / max(3.14 * NVangle * NLangle, 0.00390625);

```

And put a max() like this around every divider until you've found the culprit.

---
Tags: opengl, glsl, graphics-programming, deferred-rendering, pbr
---


# Question
Title: Can't find reason very basic collision detection is acting unreliably for me? (libgdx game project)
I am again trying to create a simple game to learn some libgdx coding skills. The game is a ball stuck on a track the track runs sideways, and there is also one that runs upwards which you have to hit by pressing SPACE. Once you get onto the upward path, the sideways one reappears at the top of the platform you are on and when you reach the new sideways one, the camera moves to put that platform on bottom of screen and then the process repeats.

It works ok , but for some reason it likes to 'stick' at the top of the "upwards" platform (when I say stick, i mean the direction variable seems to constantly flip "direction \*= -1" and the ball is sort of hanging off the edge vibrating.

Here is my code, it is fairly simple but i just cant seem to find my problem. Any help is massively appreciated thanks

```
package com.megabro.megaball.screens;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.megabro.megaball.objects.Ball;
import com.megabro.megaball.tools.Constants;

public class PlayScreen implements Screen {
Texture ballTexture;
Texture platformTexture;
SpriteBatch batch;
OrthographicCamera camera;
Viewport viewport;
Ball ball;
Rectangle platform1Rect;
Rectangle platform2Rect;
Rectangle currentPlatformRect;
float platformLongSide;
float platformFatSide;
float transitionTimer = 0;
float transitionDelay = 0.33f;
boolean isTransitioning = false;

public PlayScreen(SpriteBatch batch){
    this.batch = batch;
    ballTexture = new Texture(Gdx.files.internal("badlogic.jpg"));
    platformTexture = new Texture(Gdx.files.internal("track.jpg"));
    camera = new OrthographicCamera();
    camera.setToOrtho(false);
    viewport = new FitViewport(Constants.VIEWPORT_WIDTH, Constants.VIEWPORT_HEIGHT, camera);
    camera.position.set(viewport.getWorldWidth() / 2, viewport.getWorldHeight() / 2, 0);
    camera.update();
    ball = new Ball(ballTexture);
    platformLongSide = viewport.getWorldWidth() * 0.75f;
    platformFatSide = ball.width * 2;
    platform1Rect = new Rectangle(viewport.getWorldWidth() / 2 - platformLongSide / 2, 0, platformLongSide, platformFatSide);
    ball.setPosition(platform1Rect.x + 10, platform1Rect.y);
    currentPlatformRect = platform1Rect;
    platform2Rect = new Rectangle();
}

@Override
public void show() {

}

public void update(float dt){
    Rectangle previousPlatformRect = currentPlatformRect;
    if (currentPlatformRect == platform1Rect){
        if (platform2Rect.y != currentPlatformRect.y + currentPlatformRect.height && ball.movingSideways) {
            platform2Rect.set(MathUtils.random(currentPlatformRect.x,
                    currentPlatformRect.x + currentPlatformRect.width),
                    currentPlatformRect.y + currentPlatformRect.height,
                    platformFatSide, platformLongSide);
        }
    }
    else {
        platform1Rect.set(viewport.getWorldWidth() / 2 - platformLongSide / 2, currentPlatformRect.y + currentPlatformRect.height - platform1Rect.height, platformLongSide, platformFatSide);
    }

    if (ball.movingSideways) {
        if (ball.getX() + ball.getWidth() >= currentPlatformRect.x + currentPlatformRect.width || ball.getX() <= currentPlatformRect.x) {
            ball.directionX *= -1;
        }
    }
    if (!ball.movingSideways){
        if (ball.getY() + ball.height >= currentPlatformRect.y + currentPlatformRect.height || ball.getY() < currentPlatformRect.y) {
            transitionTimer += dt;
            if (transitionTimer >= transitionDelay){
                isTransitioning = false;
            }
            if (!isTransitioning) {
                ball.directionY *= -1;
            }
        }
    }

    if (Gdx.input.isKeyJustPressed(Input.Keys.SPACE)){
        if (currentPlatformRect == platform1Rect) {
            ball.movingSideways = false;
            currentPlatformRect = platform2Rect;
            isTransitioning = true;
            transitionTimer = 0f;
        }
        else {
            ball.movingSideways = true;
            currentPlatformRect = platform1Rect;
            camera.position.set(camera.position.x, currentPlatformRect.getY() + viewport.getWorldHeight() / 2,0);
            isTransitioning = true;
            transitionTimer = 0f;
        }

        ball.toggleMovement();
    }
    ball.update(dt);
    camera.update();
}

@Override
public void render(float delta) {
    update(delta);

    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    batch.setProjectionMatrix(camera.combined);

    batch.begin();
    batch.draw(platformTexture, platform1Rect.x, platform1Rect.y, platform1Rect.width, platform1Rect.height);
    batch.draw(platformTexture, platform2Rect.x, platform2Rect.y, platform2Rect.width, platform2Rect.height);
    ball.draw(batch);
    batch.end();

}

@Override
public void resize(int width, int height) {
    viewport.update(width, height);
}

@Override
public void pause() {

}

@Override
public void resume() {

}

@Override
public void hide() {

}

@Override
public void dispose() {

}
}

```

And the ball class:

```
public class Ball extends Sprite {
public float width = 32;
public float height = 32;
public Vector2 speed;
public float directionX = 1;
public float directionY = 1;
public boolean movingSideways = true;
public boolean isAlive = true;

public Ball(Texture texture){
    super(texture);
    setSize(width, height);
    speed = new Vector2(200,0);

}

public void update(float dt){
    if (isAlive) {
        setPosition(getX() + (speed.x * dt) * directionX, getY() + (speed.y * dt) * directionY);
    }
}

public void toggleMovement(){
    if (speed.x != 0){
        speed.y = speed.x;
        speed.x = 0;
    }
    else {
        speed.x = speed.y;
        speed.y = 0;
    }

}

public void killBall(){
    isAlive = false;
}

```

}

# Answer
Sorry to waste your pages here. I have remembered how to do it.

For anyone if they read this needing similar help. I needed to set the position of the ball to be equal to the platform it was bouncing off at the point of collision detection like so:

```
if (ball.movingSideways) {
        if (ball.getX() + ball.getWidth() >= currentPlatformRect.x + currentPlatformRect.width) {
            ball.setPosition(currentPlatformRect.x + currentPlatformRect.width - ball.width, ball.getY());
            ball.directionX *= -1;
        }
        if (ball.getX() <= currentPlatformRect.x) {
            ball.setPosition( currentPlatformRect.x, ball.getY());
            ball.directionX *= -1;
        }
    }
    if (!ball.movingSideways){
        if (ball.getY() + ball.height >= currentPlatformRect.y + currentPlatformRect.height) {
            ball.setPosition(ball.getX(), currentPlatformRect.y + currentPlatformRect.height - ball.height);
            transitionTimer += dt;
            if (transitionTimer >= transitionDelay){
                isTransitioning = false;
            }
            if (!isTransitioning) {
                ball.directionY *= -1;
            }
        }
        if (ball.getY() < currentPlatformRect.y) {
            ball.setPosition(ball.getX(), currentPlatformRect.y);
            transitionTimer += dt;
            if (transitionTimer >= transitionDelay){
                isTransitioning = false;
            }
            if (!isTransitioning) {
                ball.directionY *= -1;
            }
        }

```
> 0 votes

---
Tags: 2d, libgdx, collision-detection, game-design
---


title: Unity ignoring the deferred shader

text:
# Question
Title: Unity ignoring the deferred shader
I've been following this tutorial to get a cel-shader working in Unity 5 along with the standard shaders (explained in the last third of the article).

My issue is that when I got to replacing the built-in deferred shader, Unity seems to ignore it! I've been trying really hard to get it to work but it simply seems to be either ignoring my modified shader, which is actually just the default deferred shader with a small change in how the ndotl is calculated.

Here's a picture of what I've configured/modified in order to try to get it working:

Here's the full code for the modified Internal-DeferredShading file:

```
    Shader "Hidden/Celshading-DeferredShading" {
Properties {
    _LightTexture0 ("", any) = "" {}
    _LightTextureB0 ("", 2D) = "" {}
    _ShadowMapTexture ("", any) = "" {}
    _SrcBlend ("", Float) = 1
    _DstBlend ("", Float) = 1
}
SubShader {

// Pass 1: Lighting pass
//  LDR case - Lighting encoded into a subtractive ARGB8 buffer
//  HDR case - Lighting additively blended into floating point buffer
Pass {
    ZWrite Off
    Blend [_SrcBlend] [_DstBlend]

CGPROGRAM
#pragma target 3.0
#pragma vertex vert_deferred
#pragma fragment frag
#pragma multi_compile_lightpass
#pragma multi_compile ___ UNITY_HDR_ON

#pragma exclude_renderers nomrt

#include "UnityCG.cginc"
#include "UnityDeferredLibrary.cginc"
#include "UnityPBSLighting.cginc"
#include "UnityStandardUtils.cginc"
#include "UnityStandardBRDF.cginc"

sampler2D _CameraGBufferTexture0;
sampler2D _CameraGBufferTexture1;
sampler2D _CameraGBufferTexture2;

half4 CalculateLight (unity_v2f_deferred i)
{
    float3 wpos;
    float2 uv;
    float atten, fadeDist;
    UnityLight light;
    UNITY_INITIALIZE_OUTPUT(UnityLight, light);
    UnityDeferredCalculateLightParams (i, wpos, uv, light.dir, atten, fadeDist);

    half4 gbuffer0 = tex2D (_CameraGBufferTexture0, uv);
    half4 gbuffer1 = tex2D (_CameraGBufferTexture1, uv);
    half4 gbuffer2 = tex2D (_CameraGBufferTexture2, uv);

    light.color = _LightColor.rgb * atten;
    half3 baseColor = gbuffer0.rgb;
    half3 specColor = gbuffer1.rgb;
    half oneMinusRoughness = gbuffer1.a;
    half3 normalWorld = gbuffer2.rgb * 2 - 1;
    normalWorld = normalize(normalWorld);
    float3 eyeVec = normalize(wpos-_WorldSpaceCameraPos);
    half oneMinusReflectivity = 1 - SpecularStrength(specColor.rgb);

    if (light.ndotl <= 0.0) light.ndotl = 0;
    else light.ndotl = 1;

    //light.ndotl = 0;

    UnityIndirect ind;
    UNITY_INITIALIZE_OUTPUT(UnityIndirect, ind);
    ind.diffuse = 0;
    ind.specular = 0;

    half4 res = UNITY_BRDF_PBS (baseColor, specColor, oneMinusReflectivity, oneMinusRoughness, normalWorld, -eyeVec, light, ind);

    return res;
}

#ifdef UNITY_HDR_ON
half4
#else
fixed4
#endif
frag (unity_v2f_deferred i) : SV_Target
{
    half4 c = CalculateLight(i);
    #ifdef UNITY_HDR_ON
    return c;
    #else
    return exp2(-c);
    #endif
}

ENDCG
}

// Pass 2: Final decode pass.
// Used only with HDR off, to decode the logarithmic buffer into the main RT
Pass {
    ZTest Always Cull Off ZWrite Off
    Stencil {
        ref [_StencilNonBackground]
        readmask [_StencilNonBackground]
        // Normally just comp would be sufficient, but there's a bug and only front face stencil state is set (case 583207)
        compback equal
        compfront equal
    }

CGPROGRAM
#pragma target 3.0
#pragma vertex vert
#pragma fragment frag
#pragma exclude_renderers nomrt

sampler2D _LightBuffer;
struct v2f {
    float4 vertex : SV_POSITION;
    float2 texcoord : TEXCOORD0;
};

v2f vert (float4 vertex : POSITION, float2 texcoord : TEXCOORD0)
{
    v2f o;
    o.vertex = mul(UNITY_MATRIX_MVP, vertex);
    o.texcoord = texcoord.xy;
    return o;
}

fixed4 frag (v2f i) : SV_Target
{
    return -log2(tex2D(_LightBuffer, i.texcoord));
}
ENDCG
}

}
Fallback Off
}

```

Does anyone have an idea why this isn't working? I've even tried replacing the if/else that sets the ndotl to always 0 or always 1 but it almost seems like Unity is ignoring that line altogether, or something is overriding it later down the line and I'm not sure what.

Other than these modifications, the Unity Project only contains a handful of standard assets.

# Answer
> 6 votes
## Update for Unity 5.5

See @TWickz's answer.

---

## TL;DR

Add `#define UNITY_BRDF_PBS BRDF2_Unity_PBS` right before `#pragma`'s and `#define`'s in the shader.

---

Finding the solution was time-consuming, but I gained useful knowledge and so will you if you follow my “investigation log” below. I hope it's suitable answer format in this case.

## Step 1

Tinkering with `light.ndotl` doesn't change anything, as described by question author. Let's do a good old color change then:

```
half3 baseColor = gbuffer0.rgb; // find this line
baseColor.g = 0; // add this line after it

```

And we get nice purple shade:

## Step 2

Now we know that it's not shader that is ignored, but a `light.ndotl` specifically.

`UNITY_BRDF_PBS()` is pretty much the only possible suspect, because `light.ndotl` is used only there out of all code in the function after `light.ndotl` initialization.

No choice left other than remove the no longer useful `light.ndotl` and explore `UNITY_BRDF_PBS()` definition.

## Step 3

Let's find `UNITY_BRDF_PBS` in the files that are `#include`d into our shader.

In **UnityPBSLighting.cginc**:

```
//-------------------------------------------------------------------------------------
// Default BRDF to use:
#if !defined (UNITY_BRDF_PBS) // allow to explicitly override BRDF in custom shader
    // still add safe net for low shader models, otherwise we might end up with shaders failing to compile
    // the only exception is WebGL in 5.3 - it will be built with shader target 2.0 but we want it to get rid of constraints, as it is effectively desktop
    #if SHADER_TARGET < 30 && !UNITY_53_SPECIFIC_TARGET_WEBGL
        #define UNITY_BRDF_PBS BRDF3_Unity_PBS
    #elif UNITY_PBS_USE_BRDF3
        #define UNITY_BRDF_PBS BRDF3_Unity_PBS
    #elif UNITY_PBS_USE_BRDF2
        #define UNITY_BRDF_PBS BRDF2_Unity_PBS
    #elif UNITY_PBS_USE_BRDF1
        #define UNITY_BRDF_PBS BRDF1_Unity_PBS
    #elif defined(SHADER_TARGET_SURFACE_ANALYSIS)
        // we do preprocess pass during shader analysis and we dont actually care about brdf as we need only inputs/outputs
        #define UNITY_BRDF_PBS BRDF1_Unity_PBS
    #else
        #error something broke in auto-choosing BRDF
    #endif
#endif

```

It's clear that real work is done by one of `BRDF`*n*`_Unity_PBS()` functions. We should start by finding the best one.

## Step 4

Again, there is nothing more about `BRDF`*n*`_Unity_PBS()` in this file, so we should find it in the `#include`d files. **UnityStandardBRDF.cginc** contains all three variants of this function. №1 is apparently the best since comment of №3 starts with:

> // Old school, not microfacet based Modified Normalized Blinn-Phong BRDF

Variant №1 from the **UnityStandardBRDF.cginc**:

```
half4 BRDF1_Unity_PBS (half3 diffColor, half3 specColor, half oneMinusReflectivity, half oneMinusRoughness,
    half3 normal, half3 viewDir,
    UnityLight light, UnityIndirect gi)
{
    half roughness = 1-oneMinusRoughness;
    half3 halfDir = Unity_SafeNormalize (light.dir + viewDir);

#if UNITY_BRDF_GGX
    // NdotV should not be negative for visible pixels, but it can happen due to perspective projection and normal mapping
    // In this case we will modify the normal so it become valid and not cause weird artifact (other game try to clamp or abs the NdotV to prevent this trouble).
    // The amount we shift the normal toward the view vector is define by the dot product.
    // This correction is only apply with smithJoint visibility function because artifact are more visible in this case due to highlight edge of rough surface
    half shiftAmount = dot(normal, viewDir);
    normal = shiftAmount < 0.0f ? normal + viewDir * (-shiftAmount + 1e-5f) : normal;
    // A re-normalization should be apply here but as the shift is small we don't do it to save ALU.
    //normal = normalize(normal);

    // As we have modify the normal we need to recalculate the dot product nl.
    // Note that  light.ndotl is a clamped cosine and only the ForwardSimple mode use a specific ndotL with BRDF3
    half nl = DotClamped(normal, light.dir);
#else
    half nl = light.ndotl;
#endif
    half nh = BlinnTerm (normal, halfDir);

    // ... more code ...
}

```

> “As we have modify the normal we need to recalculate the dot product nl. Note that light.ndotl is a clamped cosine and only the ForwardSimple mode use a specific ndotL with BRDF3”

This comment looks suspicious. Everything suggests that this function blatantly ignores the `light.ndotl` value.

## Step 5

Apparently, function №1 is too fancy for us, better use a more old and faithful variant. Earlier in `UNITY_BRDF_PBS()` definition we read:

```
#if !defined (UNITY_BRDF_PBS) // allow to explicitly override BRDF in custom shader

```

Let's override and use a bit less fancy variant then, i.e. №2. To our shader file after the first `CGPROGRAM` add:

```
#define UNITY_BRDF_PBS BRDF2_Unity_PBS

```

And it works!

## Further development

It's a good enough solution for tinkering, but in production code it's probably a bad idea to force variant №2 unconditionally. Better mimic standard approach:

```
// Override UNITY_BRDF_PBS to exclude BRDF1_Unity_PBS variant,
// otherwise, it mimics the definition from UnityPBSLighting.cginc.
#if SHADER_TARGET < 30 && !UNITY_53_SPECIFIC_TARGET_WEBGL
#define UNITY_BRDF_PBS BRDF3_Unity_PBS
#elif UNITY_PBS_USE_BRDF3
#define UNITY_BRDF_PBS BRDF3_Unity_PBS
#else
#define UNITY_BRDF_PBS BRDF2_Unity_PBS
#endif

```

# Answer
> 4 votes
Note that some of the functions used here have been deprecated in Unity 5.5, but I have tested it to work.

---

In Unity 5.5, many changes have been made. The most significant, being that the dot product is now calculated on the fly, and the light.ndotl field is no longer taken into consideration anywhere in code.

I spoke to the original author of the blog David Leon and he mentioned that using the LambertTerm function with a slight modification, in the standard BRDF instead of the dot product would help.

Based on that input, these are the steps I followed to get the shader working.

**Step 1 :**

Download the built in shaders for Unity 5.5

**Step 2 :**

Copy the following files into your Assets/Resources folder (Create the folder if not available)

1. UnityStandardBRDF.cginc
2. UnityDeprecated.cginc

Rename the two files as UnityStandardBRDFCustom.cginc and UnityDeprecatedEX.cginc

**Step 3 :**

The LambertTerm function has been moved to the Deprecated section of code, so we make the change in the UnityDepcreatedEX.cginc file.

Remove all code in the UnityDeprecatedEX.cginc file and replace with this.

```
inline half CustomDotClamped ( half3 a, half3 b ){
 #if (SHADER_TARGET < 30)
    return saturate(dot(a,b));
 #else
    return max(0.0h, dot(a,b));
#endif
}

inline half CustomLambertTerm ( half3 normal, half3 lightDir ) {
  return smoothstep(0.0,0.05f, CustomDotClamped (normal, lightDir));
}

```

**Step 4 :**

Remove all content of the UnityStandardBRDFCustom file and replace with the following custom implementation of BRDF\_1\_Unity\_PBS method. Basically what I've done to the method is renamed it to BRDF\_CUSTOM\_Unity\_PBS and replaced the calculation of nl with the custom LambertTerm function.

```
#include "UnityCG.cginc"
#include "UnityStandardConfig.cginc"
#include "UnityLightingCommon.cginc"
#include "UnityDeprecatedEx.cginc"

half4 BRDF_CUSTOM_Unity_PBS (half3 diffColor, half3 specColor, half oneMinusReflectivity, half smoothness,
    half3 normal, half3 viewDir,
    UnityLight light, UnityIndirect gi)
{
    half perceptualRoughness = SmoothnessToPerceptualRoughness (smoothness);
    half3 halfDir = Unity_SafeNormalize (light.dir + viewDir);

// NdotV should not be negative for visible pixels, but it can happen due to perspective projection and normal mapping
// In this case normal should be modified to become valid (i.e facing camera) and not cause weird artifacts.
// but this operation adds few ALU and users may not want it. Alternative is to simply take the abs of NdotV (less correct but works too).
// Following define allow to control this. Set it to 0 if ALU is critical on your platform.
// This correction is interesting for GGX with SmithJoint visibility function because artifacts are more visible in this case due to highlight edge of rough surface
// Edit: Disable this code by default for now as it is not compatible with two sided lighting used in SpeedTree.
#define UNITY_HANDLE_CORRECTLY_NEGATIVE_NDOTV 0

#if UNITY_HANDLE_CORRECTLY_NEGATIVE_NDOTV
    // The amount we shift the normal toward the view vector is defined by the dot product.
    half shiftAmount = dot(normal, viewDir);
    normal = shiftAmount < 0.0f ? normal + viewDir * (-shiftAmount + 1e-5f) : normal;
    // A re-normalization should be applied here but as the shift is small we don't do it to save ALU.
    //normal = normalize(normal);

    half nv = saturate(dot(normal, viewDir)); // TODO: this saturate should no be necessary here
#else
    half nv = abs(dot(normal, viewDir));    // This abs allow to limit artifact
#endif

    //half nl = saturate(dot(normal, light.dir));
    //celshading
    half nl = CustomLambertTerm(normal, light.dir);

    half nh = saturate(dot(normal, halfDir));

    half lv = saturate(dot(light.dir, viewDir));
    half lh = saturate(dot(light.dir, halfDir));

    // Diffuse term
    half diffuseTerm = DisneyDiffuse(nv, nl, lh, perceptualRoughness) * nl;

    // Specular term
    // HACK: theoretically we should divide diffuseTerm by Pi and not multiply specularTerm!
    // BUT 1) that will make shader look significantly darker than Legacy ones
    // and 2) on engine side "Non-important" lights have to be divided by Pi too in cases when they are injected into ambient SH
    half roughness = PerceptualRoughnessToRoughness(perceptualRoughness);
#if UNITY_BRDF_GGX
    half V = SmithJointGGXVisibilityTerm (nl, nv, roughness);
    half D = GGXTerm (nh, roughness);
#else
    // Legacy
    half V = SmithBeckmannVisibilityTerm (nl, nv, roughness);
    half D = NDFBlinnPhongNormalizedTerm (nh, PerceptualRoughnessToSpecPower(perceptualRoughness));
#endif

    half specularTerm = V*D * UNITY_PI; // Torrance-Sparrow model, Fresnel is applied later

#   ifdef UNITY_COLORSPACE_GAMMA
        specularTerm = sqrt(max(1e-4h, specularTerm));
#   endif

    // specularTerm * nl can be NaN on Metal in some cases, use max() to make sure it's a sane value
    specularTerm = max(0, specularTerm * nl);
#if defined(_SPECULARHIGHLIGHTS_OFF)
    specularTerm = 0.0;
#endif

    // surfaceReduction = Int D(NdotH) * NdotH * Id(NdotL>0) dH = 1/(roughness^2+1)
    half surfaceReduction;
#   ifdef UNITY_COLORSPACE_GAMMA
        surfaceReduction = 1.0-0.28*roughness*perceptualRoughness;      // 1-0.28*x^3 as approximation for (1/(x^4+1))^(1/2.2) on the domain [0;1]
#   else
        surfaceReduction = 1.0 / (roughness*roughness + 1.0);           // fade \in [0.5;1]
#   endif

    // To provide true Lambert lighting, we need to be able to kill specular completely.
    specularTerm *= any(specColor) ? 1.0 : 0.0;

    half grazingTerm = saturate(smoothness + (1-oneMinusReflectivity));
    half3 color =   diffColor * (gi.diffuse + light.color * diffuseTerm)
                    + specularTerm * light.color * FresnelTerm (specColor, lh)
                    + surfaceReduction * gi.specular * FresnelLerp (specColor, grazingTerm, nv);

    return half4(color, 1);
}

```

**Step 5 :**

Create the shader file. Name it whatever you like. The shader code is at the end of the answer :)

Key things to note on the shader implementation.

1. We override the definition of the UNITY\_BRDF\_PBS macro with the customized function we implemented in the UnityStandardBRDFCustom.cginc (Be sure to do this right after CGPROGRAM and before the pragmas).
2. Secondly, since we override the UNITY\_BRDF\_PBS function completely, we no longer need a reference to the UnityPBSLighting.cginc. Therefore it's commented out.
3. We use both UnityStandardBRDF and UnityStandardBRDFCustom cginc files in the shader declared in the mentioned order respectively.

**Step 6:**

Go to Edit-\>Project Settings-\> Graphics and update the Deffered shader to your custom shader. Make sure that your camera's rendering path is set to deffered.

```
Shader "Hidden/Internal-DeferredShading" {
Properties {
    _LightTexture0 ("", any) = "" {}
    _LightTextureB0 ("", 2D) = "" {}
    _ShadowMapTexture ("", any) = "" {}
    _SrcBlend ("", Float) = 1
    _DstBlend ("", Float) = 1

}
SubShader {

// Pass 1: Lighting pass
//  LDR case - Lighting encoded into a subtractive ARGB8 buffer
//  HDR case - Lighting additively blended into floating point buffer
Pass {
    ZWrite Off
    Blend [_SrcBlend] [_DstBlend]

CGPROGRAM

#define UNITY_BRDF_PBS BRDF_CUSTOM_Unity_PBS

#pragma multi_compile FANCY_STUFF_OFF FANCY_STUFF_ON
#pragma target 3.0
#pragma vertex vert_deferred
#pragma fragment frag
#pragma multi_compile_lightpass
#pragma multi_compile ___ UNITY_HDR_ON

#pragma exclude_renderers nomrt

#include "UnityCG.cginc"
#include "UnityDeferredLibrary.cginc"
//#include "UnityPBSLighting.cginc"
#include "UnityStandardUtils.cginc"
#include "UnityGBuffer.cginc"
#include "UnityStandardBRDF.cginc"
#include "UnityStandardBRDFCustom.cginc"

sampler2D _CameraGBufferTexture0;
sampler2D _CameraGBufferTexture1;
sampler2D _CameraGBufferTexture2;

half4 CalculateLight (unity_v2f_deferred i)
{
    float3 wpos;
    float2 uv;
    float atten, fadeDist;
    UnityLight light;
    UNITY_INITIALIZE_OUTPUT(UnityLight, light);
    UnityDeferredCalculateLightParams (i, wpos, uv, light.dir, atten, fadeDist);

    light.color = _LightColor.rgb * atten;

    // unpack Gbuffer
    half4 gbuffer0 = tex2D (_CameraGBufferTexture0, uv);
    half4 gbuffer1 = tex2D (_CameraGBufferTexture1, uv);
    half4 gbuffer2 = tex2D (_CameraGBufferTexture2, uv);
    UnityStandardData data = UnityStandardDataFromGbuffer(gbuffer0, gbuffer1, gbuffer2);

    data.diffuseColor.rgb   = gbuffer0.rgb;

    float3 eyeVec = normalize(wpos-_WorldSpaceCameraPos);
    half oneMinusReflectivity = 1 - SpecularStrength(data.specularColor.rgb);

    UnityIndirect ind;
    UNITY_INITIALIZE_OUTPUT(UnityIndirect, ind);
    ind.diffuse = 0;
    ind.specular = 0;

    if (light.ndotl <= 0.0)
     light.ndotl = 0;
    else
     light.ndotl = 1;

    half4 res = UNITY_BRDF_PBS (data.diffuseColor, data.specularColor, oneMinusReflectivity, data.smoothness, data.normalWorld, -eyeVec, light, ind);

    return res;
}

#ifdef UNITY_HDR_ON
half4
#else
fixed4
#endif
frag (unity_v2f_deferred i) : SV_Target
{
    half4 c = CalculateLight(i);
    #ifdef UNITY_HDR_ON
    return c;
    #else
    return exp2(-c);
    #endif
}

ENDCG
}

// Pass 2: Final decode pass.
// Used only with HDR off, to decode the logarithmic buffer into the main RT
Pass {
    ZTest Always Cull Off ZWrite Off
    Stencil {
        ref [_StencilNonBackground]
        readmask [_StencilNonBackground]
        // Normally just comp would be sufficient, but there's a bug and only front face stencil state is set (case 583207)
        compback equal
        compfront equal
    }

CGPROGRAM
#pragma target 3.0
#pragma vertex vert
#pragma fragment frag
#pragma exclude_renderers nomrt

#include "UnityCG.cginc"

sampler2D _LightBuffer;
struct v2f {
    float4 vertex : SV_POSITION;
    float2 texcoord : TEXCOORD0;
};

v2f vert (float4 vertex : POSITION, float2 texcoord : TEXCOORD0)
{
    v2f o;
    o.vertex = UnityObjectToClipPos(vertex);
    o.texcoord = texcoord.xy;
#ifdef UNITY_SINGLE_PASS_STEREO
    o.texcoord = TransformStereoScreenSpaceTex(o.texcoord, 1.0f);
#endif
    return o;
}

fixed4 frag (v2f i) : SV_Target
{
    return -log2(tex2D(_LightBuffer, i.texcoord));
}
ENDCG
}

}
Fallback Off
}

```

---
Tags: unity, deferred-rendering
---


# Question
Title: The proper name for a state, view, screen, etc
Most of my experience is in programming in HTML, JavaScript, etc. I'm taking on a relatively large project, and while I'm the only developer, I eventually want to open source my code for other developers.

For project scaling purposes, I'd like to have decent terminology, because terminology affects all my variables, and changing it later is a pain.

---

What is the proper name for when you change views or screens? For example, changing between an options screen and the playing screen.

I mostly hear it called *"state"*, but when I refer to *"gamestate"*, I typically mean the locations of all entities, the turn count, the score, etc.

I think it may be called *"screen"*, but my games are not full screen, and I'm not sure if that one makes sense.

A *"view"* is something I don't hear very often, but when searching for *"views"* with *"games"*, I find material on the point of view.

Is there a proper word for it?

# Answer
**What is the proper name for when you change views or screens?**

I have always called this a *view / screen transition*. This seems to be an accepted term across a variety of contexts, ranging from game development to software development, both through documentation and physical demonstration.

This term does not just cover the *fact* that we are moving from one screen or view to the other, but may also include additional effects that take place, during the process. For example, you might refer to a "fade-out" effect as one such transition.

---

**I'd like to have decent terminology, because terminology affects all my variables, and changing it later is a pain**

It sounds like your not properly *documenting* your code. It *helps* to use more universally accepted names, but consider that correct use of *commenting* should override any minor inconsistencies caused by incorrect name use.

The few languages I have used enforce this as a standard. In `C#`, for example, you can use `///<summary> </summary>` above a variable to add a written summary of the variable as it should appear in documentation. *This would more carefully explain the purpose of the variable to user's in cases where your name is not clear enough*.

It is also worth considering the potential folly in assuming the level of understanding in others. The fact that such a term is universally accepted does *not* mean that every body who reads your code will take the same understanding.

---

**I think it may be called "screen", but my games are not full screen, so I am not sure if that makes sense**

In this context, you seem to be describing the *actual game screen*, as opposed to *movement between game screens*. Screen seems perfectly fine, here. Consider this: if "screen" meant "full screen", why would you need to make effort to say that your game is *not* "*full* screen"?

When I think of a "screen", in regards to games, I think of the area of the screen where the game is being drawn, and the context. If I had two separate games running, side by side, I would refer to them as separate game screens. If I moved from one menu to another, in either game, I would refer to it as changing menu screens.

If this term still feels awkward, to you, you might consider "viewport". A viewport is the space your game camera draws to; in most contexts, this is your game screen. Some games may involve multiple cameras, that each use a different viewport. Split screen multiplayer is one such example.
> 4 votes

# Answer
'**view**' is typically related to what is seen by a camera.

'**screen**' is generally what's in your top level game state, e.g. main game screen, option screen, title screen, main menu screen.

'**screen transition**' is when changing screen.

'**game state**' comes from the fact that most games are implemented using state machines.
> 2 votes

# Answer
`Scene` sounds proper for that.

You may wanna have a look at other game libs/frameworks, like unity, spritekit, gameplay kit, etc.
> -1 votes

---
Tags: screen, terminology, view
---


title: Save slider value and load it?

text:
# Question
Title: Save slider value and load it?
I'm trying to save a slider value and load it when I run again the game. but here is not working. yes, I can change the value and save it but not load it.

```
    public Slider Brightness;
    public float bri,briv; // only briv value I saving it.

    // Use this for initialization
    void Start () {
        PlayerPrefs.GetFloat("briv");
        Brightness.value = briv;
        }

    void Update() {
            briv = bri;
            bri = Brightness.value;

    if (Input.GetKeyDown(KeyCode.S)) {
        PlayerPrefs.SetFloat("briv",briv);
        Debug.Log ("save");
    }

        } // end update

```

# Answer
You're not setting the return value of the function, try this `briv = PlayerPrefs.GetFloat("briv");` instead of `PlayerPrefs.GetFloat("briv");` and it should work as you want it to.
> 2 votes

---
Tags: unity
---


# Question
Title: Unity - Basic AI Enemy Follows Player - Prevent Flocking Of Enemies Together
I'm in the process of implementing a 2D top-down shooter game. I have a basic AI script that allows enemies to follow the player around. Currently it works fine for one enemy, but as soon as there are multiple enemies, overtime they tend to flock together. How would I go about fixing this issue? I think that one possible solution would be to make the enemies move in a random direction every few frames, but I'm not sure on this.

Below is my C# Script that I am currently using.

```
using UnityEngine;
using System.Collections;

public class AIScript : MonoBehaviour
{
    public Transform target;
    public int moveSpeed;
    public int rotationSpeed;

    void Start()
    {
        target = GameObject.Find("Michael").transform;
    }

    void Update()
    {
        if (target != null)
        {
            Vector3 dir = target.position - transform.position;
            // Only needed if objects don't share 'z' value.
            dir.z = 0.0f;
            if (dir != Vector3.zero)
                transform.rotation = Quaternion.Slerp ( transform.rotation,
                    Quaternion.FromToRotation (Vector3.right, dir),
                    rotationSpeed * Time.deltaTime);

            //Move Towards Target
            transform.position += (target.position - transform.position).normalized
                * moveSpeed * Time.deltaTime;
        }
        rigidbody2D.velocity = Vector3.zero;
    }
}

```

# Answer
One simple way of doing it could be to make a few alternate versions of the script and have different AI profiles for the enemies (just give them a random one when created). This way you could have one type that goes straight ahead like you have now, but also others that try to get the player by curving right or left. Maybe even one that makes some random moves if that works in your game.

I don't think this is a perfect solution, but at least it would break up the enemies in smaller flocks without too much effort on your part.
> 3 votes

# Answer
You could try giving each enemy a mass in Unity and collision detection so they cant go thru each other, but without a lot of work if they are doing basic player tracking you are going to end up with a horde. You could also set it up with an if statement to where before they move it checks the area for other enemies within a certain radius. Then set it to look for a new space new space if that one is full or to move if it is empty.
> 0 votes

# Answer
You want a combination of behaviours. Use vectors to calculate an attraction to the player, and a repulsion from other nearby enemies. Weight those behavioural vectors to make them stronger or weaker, and then combine them together using vector addition. The resultant vector is the place the AI wants to be; you can then reverse engineer that vector into a direction and speed if that's how your AI move.
> 0 votes

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