title: Camera movement, Draw grid

text:
# Question
Title: Camera movement, Draw grid
If I have a 20x10 grid (640x320) where tiles are 32x32

The grid are rendered:

```
for (var y = 0; y < 10; y++) {
  for (var x = 0; x < 20; x++) {

    var tileX = Math.round(Camera.x / 32);
    var tileY = Math.round(Camera.y / 32);

    var tile = Game.map[tileY][tileX];

    rect(x * 32, y * 32, 32, 32);

  }
}

```

The camera follows a Player object and is in the middle on the canvas.

Camera position (x) are calculated such as:

```
Player.x - Camera.x + 320 > 640
   Camera.x = Player.x - 320;

```

When the camera moves, it looks kinda solid (since it moves a whole tile). How can I make the movement a bit smoother? (Perhaps showing part of the next tile on either side, rather than the whole at once)

# Answer
A question similar to this was answered here.

But I'll repost my answer here as well.

So I've answered your question by creating this repo on GitHub. You can play the game here. Use cursor

**Edit:It had a bug, fixed it. Thank GOD! Added code explanation below**

So the game works like this

* We initialize the game:
    + We set event listeners for controls
    + We load all assets into the game
    + And when all the assets are loaded we start creating the world
* Create the world using the dimensions given & number of tiles specified.
* After the world is created a sprite is created and the game's loop started.
* In the loop:
    + update() and draw() the sprite
        - The update() checks for input and updates sprite `pos.x` and `pos.y` accordingly.
        - The draw() draws the sprite's image onto the player canvas.
    + We then clear the viewport's canvas (This is where the world is drawn. Think of the world as a static background. Anything that moves will have to be drawn on another canvas.) and draw the part of the world canvas that we want.
    + Lastly, we call the loop again.

This is the whole process. Remember that the world canvas is just a background, so any sprite or game element that does't move (e.g. castle walls) should be drawn here (of course adding them as sprite. So that you can, for example, check collisions with the wall).

## How the viewport and character are drawn

We draw the character using two different coordinate objects

* In the first we use the `pos2` object. We use this to draw the character onto the player canvas which is a canvas that tricks the player into thinking that the character is actually in the world and yet he is actually being drawn over the viewport. The player canvas is over the viewport canvas (using css to do that). This object is only used to draw the character not move it around the world. The character is drawn on the center of the player canvas until he reaches near the edge of the world canvas. At this point, we will use the character's world canvas coordinates to draw onto the player canvas.
* The `pos` object holds the character's world coordinates. You can use these for collision checking and movement around the world.

Remember that we don't draw onto the world canvas. This canvas is drawn only once. Drawing of movable sprites (e.g. enemies) should be done either on an enemy canvas, player canvas, or on the viewport canvas (Creating an enemy canvas is the best idea).

## Here's all the code. Use the above explanation to understand it.

```
/* General stuffs */
var can_vPort = document.getElementById('viewport'),
  /* Viewport canvas */
  can_pCanvas = document.getElementById('player'),
  /* Player canvas */
  grid = {
    'width': 60,
    'height': 60
  },
  /* This is in tiles not in pixels */
  tile = {
    'width': 64,
    'height': 64
  },

  viewPort = {
    'width': 640,
    'height': 640
  },
  /* Create world canvas */
  can_world = createElement('canvas', {
    'width': 3840,
    'height': 3840
  }),
  cursor = { /* Arrow keys */
    'rightPressed': false,
    'leftPressed': false,
    'downPressed': false,
    'upPressed': false
  },
  img = {}, /* This is where all images are saved */
  sprites = {}; /* This is where all sprites are placed */

var ctx_vPort = can_vPort.getContext('2d'),
  /* Viewport canvas context */
  ctx_pCanvas = can_pCanvas.getContext('2d'),
  /* Player canvas context */
  ctx_world = can_world.getContext('2d'); /* World canvas context */

function init(key, assets) {
  /* Begin handling key presses */
  document.onkeydown = keyDownHandler;
  document.onkeyup = keyUpHandler;

  /* Load assets. This is very simple, to save time. */
  for (var i = 0, len = assets.length; i < len; i++) {
    var image = new Image();
    if (i !== len - 1) { /* If this isn't the last iteration */
      var str = key[i];
      image.onload = function() {
        // console.log(str)
        img[str] = this;
      };
    } else { /* Now if this is the last iteration */
      var str2 = key[i];
      image.onload = function() {
        img[str2] = this; /* Add the image as a property to img */
        createWorld(grid.width, grid.height, tile.width, tile.height);
      };
    }
    image.src = assets[i];
  }
}

function createWorld(_numTileWidth, _numTileHeight, _tWidth, _tHeight) {
  /* Following for loop makes the world canvas */
  for (var i = 0, len = _numTileHeight; i < len; i++) {
    for (var k = 0, len2 = _numTileWidth; k < len2; k++) {
      var x = k * _tWidth,
        y = i * _tHeight,
        image = img['tile']; /*getImg('tile') ==> Don't know why this failed, but in the interest of time */
      ctx_world.drawImage(image, x, y, _tWidth, _tHeight);
    }
  }
  /* Here we add the sprite, 'player' */
  addSprite('player');

  /* The game starts here */
  requestAnimationFrame(loop); /* Start the game after world is drawn */
}

function loop() {
  /* Do game stuff here */

  sprites['player'].update(); /* Update player sprite position */
  sprites['player'].draw(); /* Draw player at new/old position. I didn't optimize */

  ctx_vPort.clearRect(0, 0, can_vPort.width, can_vPort.height); /* Clear viewport canvas */
  ctx_vPort.drawImage(can_world, (sprites.player.pos.x < 320 || sprites.player.pos.x > can_world.width - 320) ? 0 : (sprites['player'].pos.x + (sprites['player'].width / 2) - 320), (sprites.player.pos.y < 320 || sprites.player.pos.y > can_world.height - 320) ? 0 : (sprites['player'].pos.y + (sprites['player'].height / 2) - 320), 640, 640, 0, 0, 640, 640); /* This is the 'viewport' itself btw. Just read it ou loud, helps when you want to understand what's going on */
  requestAnimationFrame(loop); /* Loop!!!! */
}

function keyDownHandler(event) { /* Handler for keyup events */
  event.preventDefault();
  if (event.keyCode == 39) {
    cursor.rightPressed = true;
  } else if (event.keyCode == 37) {
    cursor.leftPressed = true;
  }
  if (event.keyCode == 40) {
    cursor.downPressed = true;
  } else if (event.keyCode == 38) {
    cursor.upPressed = true;
  }
}

function keyUpHandler(event) { /* Handler for keydown events */
  event.preventDefault();
  if (event.keyCode == 39) {
    cursor.rightPressed = false;
  } else if (event.keyCode == 37) {
    cursor.leftPressed = false;
  }
  if (event.keyCode == 40) {
    cursor.downPressed = false;
  } else if (event.keyCode == 38) {
    cursor.upPressed = false;
  }
}

function createElement(ele, attrObj) {
  /* Create the new Element */
  var element = document.createElement(ele);

  /* Do the following only if attrObj exists */
  if (attrObj) {
    /* Loop through attrObj's properties to set the element's attributes */
    for (var i in attrObj) {
      element.setAttribute(i, attrObj[i]);
      /* attrObj's format:
          {
              'attribute name': "Attribute's value"
          }
      */
    }
  }

  /* Return the new element */
  return element;
}

function Sprite(key) {

  /* Position of sprite in world */
  this.pos = {
    'x': can_world.width / 2,
    'y': can_world.height / 2
  };

  this.pos2 = { /* Sprite's position in player canvas */
    'x': can_pCanvas.width / 2,
    'y': can_pCanvas.height / 2
  };

  this.speed = { /* Speed of sprite */
    'x': 5,
    'y': 5
  };

  /* Use a helper function that returns an object with x and y as it's properties for the above */

  /* Image reference for sprite. */
  this.img = img[key]; /* The image for sprite */
  this.width = this.img.width; /* Width of sprite image */
  this.height = this.img.height; /* Height of sprite image */

  this.draw = function() {
    ctx_pCanvas.clearRect(0, 0, can_pCanvas.width, can_pCanvas.height); /* Clear the whole player canvas (a canvas used to draw the character only */
    /* This makes sure that the camera stops when the character is near the edge of the screen */
    if (this.pos.x < 320) {
      this.pos2.x = this.pos.x;
    } else if (this.pos.x > can_world.width - 320) {
      this.pos2.x = 640 - (can_world.width - this.pos.x);
    } else {
      this.pos2.x = can_pCanvas.width / 2;
    }

    if (this.pos.y < 320) {
      this.pos2.y = this.pos.y;
    } else if (this.pos.y > can_world.height - 320) {
      this.pos2.y = 640 - (can_world.height - this.pos.y);
    } else {
      this.pos2.y = can_pCanvas.height / 2;
    }

    ctx_pCanvas.drawImage(this.img, this.pos2.x, this.pos2.y); /* Draw the character using it's secondary position */
    // console.log(this.pos2.x, this.pos2.y)
  };

  this.update = function() {
    /* Here we check to see if any buttons where pressed and if our character is in the world */
    if (cursor.rightPressed && this.pos.x < can_world.width - this.width) {
      this.pos.x += this.speed.x;
    } else if (cursor.leftPressed && this.pos.x >= 0) {
      this.pos.x -= this.speed.x;
    }
    if (cursor.downPressed && this.pos.y < can_world.height - this.height) {
      this.pos.y += this.speed.y;
    } else if (cursor.upPressed && this.pos.y >= 0) {
      this.pos.y -= this.speed.y;
    }
  };
}

function addSprite(key) {
  sprites[key] = new Sprite(key); /* Add the sprite using the key as a reference*/
}

// document.body.appendChild(can_world); Don't uncomment this. Unless you want to see the whole world as it's rendering

/* The magic begins here */
init(['tile', 'player'], ['tile.png', 'player.png']);

```

If you run the game you'll see a black box (32x32px) in a world filled with 64x64px tiles. And yes, it's a grid of 60x60 tiles. The game runs quick (For me at least) and movement is smooth. Play it here. Use arrows for controls.

I hope this will be helpful to you, peace!

Check the link in my comment below, some really good ideas
> 2 votes

---
Tags: 2d, javascript, html-canvas
---


title: Top down tile based game render order

text:
# Question
Title: Top down tile based game render order
I'm making a simple top down (like this) tile based game (using JavaScript, for reference)

I use Tiled for making maps. I have sprites that are more than one tile high, and so whenever they are in front or behind of some objects more than one tile high tiles will be displayed in front of the player. I am looking for a way to give certain tiles 'height' such that only characters of that height could appear in front of those tiles.

Here is a screenshot showing my problem (the sprite is doge because it was the first image I found):

The same tiles don't always equate to the same height, so I can't give tiles set height. I've thought of one way to give tiles height, and that is to have a (hidden) layer that describes the height level certain tiles are at.

However, that solution would be slow and painful to implement. I'm wondering if there's a better way to do it.

A few other potential ideas I've had: Have a tile layer for each height, hackily guess the height of a tile at runtime based on tiles below (would be buggy) but I think that there would surely be a better way to do it.

# Answer
> 1 votes
When you want to have overlapping sprites in your game, you need to put them in a list which you sort by the coordinate of the lower edge of each sprite and then render them in that order.

Further, when you are using a graphics API where `y = 0` is the upper edge of the screen, you need to take the height of each sprite into account when you draw it and draw it at `y - height`.

When you have objects in your game which are multiple tiles high (your big tree is a good example), these should be one sprite, not multiple tiles on different layers. Tiled does support tilesets with different tilesizes in one map and even on one map layer.

---
Tags: tilemap, tiled, draw-order
---


# Question
Title: libgdx - Trying to load ttf font using asset manager
I tried to load a ttf font using an `AssetManager` like this:

```
FreetypeFontLoader.FreeTypeFontLoaderParameter freeTypeFontLoaderParameter = new FreetypeFontLoader.FreeTypeFontLoaderParameter();
freeTypeFontLoaderParameter.fontFileName = "fonts/zrnic.tff";

FreeTypeFontGenerator.FreeTypeFontParameter freeTypeFontParameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
freeTypeFontParameter.minFilter = Texture.TextureFilter.Linear;
freeTypeFontParameter.magFilter = Texture.TextureFilter.Linear;
freeTypeFontParameter.flip = false;
freeTypeFontParameter.size = 62;

freeTypeFontLoaderParameter.fontParameters = freeTypeFontParameter;

game.assetManager.load("myFont62.ttf", BitmapFont.class, freeTypeFontLoaderParameter);

```

But I get

> Couldn't load dependencies of asset: myFont62.ttf

# Answer
I updated the LibGDX wiki to specifically address this issue. The old example code used there was just too confusing for anyone to take a quick glance at and figure out what they were doing. Take a look when you get a chance.

Anyway, you're loading `myFont62.ttf` which is a string identifier of the resource `fonts/zrnic.ttf`. Instead of using a different name, you might try making the string identifier the same as the font resource. This makes it so that you aren't using two names for the same thing, and so that your string identifiers match your filenames.

Your problem is coming from a filesystem issue. It looks like your `assets/` folder is not recognizing the location `fonts/zrnic.ttf`. In your filesystem, you should have your font accessible as `yourgamefolder/android/assets/fonts/zrnic.ttf`

If it's anywhere else, you're going to get that error. As far as closing and re-opening the IDE, I've never ran into that problem, before. Just put your `fonts/` folder inside your `assets/` folder, and it should work just fine.
> 1 votes

---
Tags: android, libgdx, fonts, ttf
---


# Question
Title: What are the practical limitations of using XNA?
Since development on XNA has long since stopped, it is unlikely that it will ever be updated to be in line with modern graphics technology, however aside from the obvious fact that it's Windows-only - what are the practical limitations of using XNA?

The obvious ones are:

1. It uses DirectX 9.0 - which means no compute or geometry shaders.
2. It's Windows-only (Excluding Monogame/FNA)
3. It requires the installation of .NET and XNA on a client's computer.

#2 and #3 are obvious limitations, but can be considered acceptable. #1 on the other hand, is a bit more complicated. In practical terms what does being limited to DirectX 9.0 mean in terms of game development and graphical capability? No geometry or compute shaders means having to do more heavy lifting on the CPU, but is there any other limitations that an end user would notice? Ideally beyond a generic term such as "graphical fidelity".

# Answer
Graphical fidelity is a funny one, because directX 11 doesn't look any better strait up it lets you write more complex shaders so at the end of the day stuff ends up looking better.

I worked with XNA for a long time and while I love it I can not recommend it because its slow(high cpu overhead), can have support dropped from windows at any time, holds your hand to much, no direct unmanged memory access and no VS graphics debugging tools.

Here is a list of some stuff you missout on with XNA:

* UAV's
* StructuredBuffers(good for moving data from cpu to gpu)
* AppendBuffers(really nice for particle systems)
* ConsumeBuffers(really nice for particle systems)
* Hardware Tessellation
* More shader instructions
* Writing to a UAV from any shader stage
* Direct access to the depthbuffer
* Can mix pixel bit depth when using MRT's
* Multithreading
* TextureArrays

The user will not notice much of that but you will, in short XNA is old and should not be used its now 2016 and its time to let the past go and embrace new technologys :)
> 2 votes

---
Tags: xna
---


title: unity real time terrain editor

text:
# Question
Title: unity real time terrain editor
im trying to make an editor for my game. but I want to know is it possible to edit terrain map heights or textures? if the answer is true, should i make it from scratch or can I use unity editor tools in real time? is there any asset for it? thank you for helping

# Answer
> 1 votes
Yes, it is possible. Take a look at the classes Terrain and TerrainData. You can edit the heights with the method "SetHeights" by passing float arrays. But it can be very expensive, depending on what you exactly want to do.

There are several Tutorials all over the web, covering this topic.

This answer is a bit vague, but your question is not very specific what you exactly want to do. But in fact it is possible to manipulate the Terrain in realtime as user.

---
Tags: unity, map-editor
---


title: Follow a path in Unity

text:
# Question
Title: Follow a path in Unity
I want to know how I can make this game object follow the specified path in unity

# Answer
> 1 votes
Take a look at the Navigation components. You can add a NavMeshAgent to a GameObject and control with a script the path he should walk.

You can easily do in this script:

```
NavMeshAgent navmAgent;
navmAgent = GetComponent<NavMeshAgent>();
navmAgent.SetDestination([your destination]);

```

The NavAgent will search for the fastest way to this destination, if you want a more determined path, you could use a set of "RallyPoints".

This is the example from the Unity tutorial, with a little adjustment:

```
// Patrol.cs
using UnityEngine;
using System.Collections;

public class Patrol : MonoBehaviour {

    public Transform[] points;
    private int destPoint = 0;
    private NavMeshAgent agent;

    void Start () {
        agent = GetComponent<NavMeshAgent>();

        // Disabling auto-braking allows for continuous movement
        // between points (ie, the agent doesn't slow down as it
        // approaches a destination point).
        agent.autoBraking = false;

        GotoNextPoint();
    }

    void GotoNextPoint() {
        // Returns if no points have been set up
        if (points.Length == 0)
            return;

        // Set the agent to go to the currently selected destination.
        agent.destination = points[destPoint].position;

        //Just choosing the next point (different to tutorial)
        destPoint = Mathf.Max(points.Length-1, ++destPoint);
    }

    void Update () {
        // Choose the next destination point when the agent gets
        // close to the current one.
        if (agent.remainingDistance < 0.5f)
            GotoNextPoint();
    }
}

```

So bascially create a set of points, which determine your path. Give your GameObject a NavMeshAgent and a script which tells the NavMeshAgent to walk aloing your points, similiar to the code above.

If you don't want to use the NavMesh-approach, then you could just interpolate the path and manually update the position of your GameObject.

---
Tags: unity, game-design, movement, path
---


# Question
Title: Multiplace instances of an object in Game Maker with a variable changing
I want to do a level selection menu in GameMaker. There's one button for each level. Clicking on the button 1 take you to level 1, button 2 take you to level 2 and so on.

But if I duplicate the first button, all of the buttons will get you to level 1. Is it possible for multiple instances of the same object to have different variables?

# Answer
If you placed all the buttons in the room editor then you can define variables in instance creation code (room editor -\> RMB on an instance -\> Creation Code).

If you created all the buttons via code, you can easily define different values, like this:

```
for (var i=0; i<10; i++)
{
    var obj = instance_create(50 + i*50, 50, obj_button);
    obj.level = i; // all the instances will has different value
}

```
> 1 votes

---
Tags: game-maker
---


title: VR Play postion Sync over the network

text:
# Question
Title: VR Play postion Sync over the network
**I am developing a multiplayer game where a normal character controller user and VR user can participate. So there are two modes of the games through a user can join:**

1. **Normal**
2. **VR Mode**

I am able to manage these modes and user can participate with any mode but the problem is Normal Player(charcter controller) is unable to view VR controller(HTC vive Controllers) as these objects are becomes off on the side of character controller. So how do I view VR controller at normal player that what VR player is doing.

*I make an object and tried to imitiate it position and rotation with respect to VR controller but it is not working as Imitating source(VR controllers) are off (at the normal player side but working in VR mode) and their postion is not changing. How do you manage to make multiplayer game with VR + normal player? or what else the solution.*

# Answer
> 2 votes
I have managed to solve this problem using these steps after trying hard three four days. These step are given below so that future user don't get stuck in this problem as there are no other comprehensive guide available:

1. Make one **Gameobject for Head** (simple cube) with Network Identity and network transform
2. Make one **Gameobject for(right) Controller** (simple cube) with Network Identity and network transform
3. Make one **Gameobject for(left) other Controller** (simple cube) with network Identity and network transform
4. Make prefab of all above gameobjects.
5. Add all three prefabs into Network Manager (registered Spawnable prefabs list)
6. delete three prefab from scene
7. Added below script(See comments for details) into my vr player and assign respective prefabs and gameobjects

```
public class VRPlayerCtrl : NetworkTransform {

//source gameobjects head, left and right controller object of htc vive prefab

public GameObject rightContSource;

public GameObject leftContSource;

public GameObject headObjSource;

//prefabs to assign head, left controller, and right controller
public GameObject vrHeadObjPrefab;
public GameObject vrLeftCtrlPrefab;
public GameObject vrRightCtrlPrefab;

GameObject vrHeadObj;
GameObject vrLeftCtrl;
GameObject vrRightCtrl;

void Start()
{

    Debug.Log("Start of the vr player");

    if (isLocalPlayer)
    {
        //instantiate prefabs
        CmdInstantiteHeadAndController();
        //disabled conroller meshes at VR player side so it cannont be view by him
        vrLeftCtrl.GetComponent<MeshRenderer>().enabled = false;
        vrRightCtrl.GetComponent<MeshRenderer>().enabled = false;
    }
}

//Instantiate on start head and vr controller object so that it can be view by normal players
void CmdInstantiteHeadAndController()
{
    Debug.Log("instantiateing the controller and head object");
    vrHeadObj = (GameObject)Instantiate(vrHeadObjPrefab);
    vrLeftCtrl = (GameObject)Instantiate(vrLeftCtrlPrefab);
    vrRightCtrl = (GameObject)Instantiate(vrRightCtrlPrefab);

    // spawn the bullet on the clients
    NetworkServer.Spawn(vrHeadObj);
    NetworkServer.Spawn(vrLeftCtrl);
    NetworkServer.Spawn(vrRightCtrl);
}

void Update()
{
    if (!isLocalPlayer)
    {
        return;
    }

    //sync pos on network
    CmdControllerPositionSync();
}
//sync position on VR controller objects so that VR player movemnts/action can be viewd by normal user
[Command]
public void CmdControllerPositionSync()
{

    vrHeadObj.transform.localRotation = headObjSource.transform.localRotation;
    vrHeadObj.transform.position = headObjSource.transform.position;
    vrLeftCtrl.transform.localRotation = leftContSource.transform.localRotation;
    vrRightCtrl.transform.localRotation = rightContSource.transform.localRotation;
    vrLeftCtrl.transform.localPosition = leftContSource.transform.position;
    vrRightCtrl.transform.localPosition = rightContSource.transform.position;
}

}

```

congrats you have done!

---
Tags: unity, c#, virtual-reality, htc-vive
---


# Question
Title: Instantiated Different player objects in multiplayer game in unity
I am using two different objects for player in network multiplayer game. Two different kinds of gameobject will be instantiated by unity network behavior but the problem is there is only single property of playerprefab. How can i set two different objects even i tried to change it on run time but its giving me error.

> Failed to spawn server object, assetId=4d293c8e162f3874b982baadd71153d2 netId=1 UnityEngine.Networking.NetworkIdentity:UNetStaticUpdate()
>
> Failed to spawn server object, assetId=4d293c8e162f3874b982baadd71153d2 netId=7 UnityEngine.Networking.NetworkIdentity:UNetStaticUpdate()

# Answer
> 1 votes
In multiplayer Game object if you want to instantiate different gameobject for different player you have to inherit NetworkManager into your script and required its customization.

1. Add this script to a gameobject

```
public class NetworkManagerCustom2 : NetworkManager
{
    public class MsgTypes
    {
        public const short PlayerPrefab = MsgType.Highest + 1;

        public class PlayerPrefabMsg : MessageBase
        {
            public short controllerID;
            public short prefabIndex;
        }
    }

    // in the Network Manager component, you must put your player prefabs
    // in the Spawn Info -> Registered Spawnable Prefabs section
    public short playerPrefabIndex;

    public override void OnStartServer()
    {
        Debug.Log("OnStartServer");
        NetworkServer.RegisterHandler(MsgTypes.PlayerPrefab, OnResponsePrefab);
        base.OnStartServer();
    }

    public override void OnClientConnect(NetworkConnection conn)
    {
        Debug.Log("OnClientConnect");
        client.RegisterHandler(MsgTypes.PlayerPrefab, OnRequestPrefab);
        base.OnClientConnect(conn);
    }

    private void OnRequestPrefab(NetworkMessage netMsg)
    {
        Debug.Log("OnRequestPrefab");
        MsgTypes.PlayerPrefabMsg msg = new MsgTypes.PlayerPrefabMsg();
        msg.controllerID = netMsg.ReadMessage<MsgTypes.PlayerPrefabMsg>().controllerID;
        msg.prefabIndex = playerPrefabIndex;
        client.Send(MsgTypes.PlayerPrefab, msg);
    }

    private void OnResponsePrefab(NetworkMessage netMsg)
    {
        Debug.Log("OnResponsePrefab");
        MsgTypes.PlayerPrefabMsg msg = netMsg.ReadMessage<MsgTypes.PlayerPrefabMsg>();
        playerPrefab = spawnPrefabs[msg.prefabIndex];
        base.OnServerAddPlayer(netMsg.conn, msg.controllerID);
        Debug.Log(playerPrefab.name + " spawned!");
    }

    public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId)
    {
        Debug.Log("OnServerAddPlayer");
        MsgTypes.PlayerPrefabMsg msg = new MsgTypes.PlayerPrefabMsg();
        msg.controllerID = playerControllerId;
        NetworkServer.SendToClient(conn.connectionId, MsgTypes.PlayerPrefab, msg);
    }

    // I have put a toggle UI on gameObjects called PC1 and PC2 to select two different character types.
    // on toggle, this function is called, which updates the playerPrefabIndex
    // The index will be the number from the registered spawnable prefabs that
    // you want for your player
    public void UpdatePC()
    {
        Debug.Log("UpdatePC");
        if (GetComponent<NetworkManagerHUDCustom2>().isVR)
        {
            Debug.Log("UpdatePC" + 0);
            playerPrefabIndex = 0;
        }
        else //if (GameObject.Find("PC2").GetComponent<Toggle>().isOn)
        {
            Debug.Log("UpdatePC"+ 1);
            playerPrefabIndex = 1;
        }

    }
}

```

2. Add your Different Player objects prefabs in in above script's Registered Spawnable prefab list.
    3. Customize the NetworkManagerHUD so that after joining the server or creating the host you can provide player prefab index which has to instantiate. Complete script given below. I have added GUI toggle option so that if it is check a VR player will be instantiated otherwise a normal player will be instantiate.

.

```
using System;
using System.ComponentModel;
#if ENABLE_UNET

namespace UnityEngine.Networking
{
    [AddComponentMenu("Network/NetworkManagerHUD")]
    [RequireComponent(typeof(NetworkManager))]
    [EditorBrowsable(EditorBrowsableState.Never)]
    public class NetworkManagerHUDCustom2 : MonoBehaviour
    {
        public NetworkManager manager;
        [SerializeField]
        public bool showGUI = true;
        [SerializeField]
        public int offsetX;
        [SerializeField]
        public int offsetY;

        public GameObject vrPlayer;
        public GameObject normalPlayer;
        public bool isVR;
        // Runtime variable
        bool m_ShowServer;

        void Awake()
        {
            manager = GetComponent<NetworkManager>();
        }

        void Update()
        {

            if (!showGUI)
                return;

            if (!manager.IsClientConnected() && !NetworkServer.active && manager.matchMaker == null)
            {
                if (UnityEngine.Application.platform != RuntimePlatform.WebGLPlayer)
                {
                    if (Input.GetKeyDown(KeyCode.S))
                    {
                        manager.StartServer();
                    }
                    if (Input.GetKeyDown(KeyCode.H))
                    {
                        manager.StartHost();
                    }
                }
                if (Input.GetKeyDown(KeyCode.C))
                {
                    manager.StartClient();
                }
            }
            if (NetworkServer.active && manager.IsClientConnected())
            {
                if (Input.GetKeyDown(KeyCode.X))
                {
                    manager.StopHost();
                }
            }
        }

        void OnGUI()
        {
            if (!showGUI)
                return;

            int xpos = 10 + offsetX;
            int ypos = 40 + offsetY;
            const int spacing = 24;

            bool noConnection = (manager.client == null || manager.client.connection == null ||
                                 manager.client.connection.connectionId == -1);

            if (!manager.IsClientConnected() && !NetworkServer.active && manager.matchMaker == null)
            {
                if (noConnection)
                {
                    if (UnityEngine.Application.platform != RuntimePlatform.WebGLPlayer)
                    {
                        if (GUI.Button(new Rect(xpos, ypos, 200, 20), "LAN Host(H)"))
                        {
                            manager.StartHost();
                        }
                        ypos += spacing;
                    }

                    if (GUI.Button(new Rect(xpos, ypos, 105, 20), "LAN Client(C)"))
                    {

                        manager.StartClient();
                    }

                    manager.networkAddress = GUI.TextField(new Rect(xpos + 100, ypos, 95, 20), manager.networkAddress);

                    //Getting the user selected player option from GUI so that it related object player should be instantiated
                    isVR = GUI.Toggle(new Rect(xpos + 100 + 100, ypos, 95, 20), isVR, "is VR set");
                     if(isVR){
                         GetComponent<NetworkManagerCustom2>().playerPrefabIndex = 1;
                     }
                     else {
                         GetComponent<NetworkManagerCustom2>().playerPrefabIndex = 0;
                     }
                    ypos += spacing;

                    if (UnityEngine.Application.platform == RuntimePlatform.WebGLPlayer)
                    {
                        // cant be a server in webgl build
                        GUI.Box(new Rect(xpos, ypos, 200, 25), "(  WebGL cannot be server  )");
                        ypos += spacing;
                    }
                    else
                    {
                        if (GUI.Button(new Rect(xpos, ypos, 200, 20), "LAN Server Only(S)"))
                        {
                            manager.StartServer();
                        }
                        ypos += spacing;
                    }
                }
                else
                {
                    GUI.Label(new Rect(xpos, ypos, 200, 20), "Connecting to " + manager.networkAddress + ":" + manager.networkPort + "..");
                    ypos += spacing;

                    if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Cancel Connection Attempt"))
                    {
                        manager.StopClient();
                    }
                }
            }
            else
            {
                if (NetworkServer.active)
                {
                    string serverMsg = "Server: port=" + manager.networkPort;
                    if (manager.useWebSockets)
                    {
                        serverMsg += " (Using WebSockets)";
                    }
                    GUI.Label(new Rect(xpos, ypos, 300, 20), serverMsg);
                    ypos += spacing;
                }
                if (manager.IsClientConnected())
                {
                    GUI.Label(new Rect(xpos, ypos, 300, 20), "Client: address=" + manager.networkAddress + " port=" + manager.networkPort);
                    ypos += spacing;
                }
            }

            if (manager.IsClientConnected() && !ClientScene.ready)
            {
                if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Client Ready"))
                {
                    ClientScene.Ready(manager.client.connection);

                    if (ClientScene.localPlayers.Count == 0)
                    {
                        ClientScene.AddPlayer(0);
                    }
                }
                ypos += spacing;
            }

            if (NetworkServer.active || manager.IsClientConnected())
            {
                if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Stop (X)"))
                {
                    manager.StopHost();
                }
                ypos += spacing;
            }

            if (!NetworkServer.active && !manager.IsClientConnected() && noConnection)
            {
                ypos += 10;

                if (UnityEngine.Application.platform == RuntimePlatform.WebGLPlayer)
                {
                    GUI.Box(new Rect(xpos - 5, ypos, 220, 25), "(WebGL cannot use Match Maker)");
                    return;
                }

                if (manager.matchMaker == null)
                {
                    if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Enable Match Maker (M)"))
                    {
                        manager.StartMatchMaker();
                    }
                    ypos += spacing;
                }
                else
                {
                    if (manager.matchInfo == null)
                    {
                        if (manager.matches == null)
                        {
                            if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Create Internet Match"))
                            {
                                manager.matchMaker.CreateMatch(manager.matchName, manager.matchSize, true, "", "", "", 0, 0, manager.OnMatchCreate);
                            }
                            ypos += spacing;

                            GUI.Label(new Rect(xpos, ypos, 100, 20), "Room Name:");
                            manager.matchName = GUI.TextField(new Rect(xpos + 100, ypos, 100, 20), manager.matchName);
                            ypos += spacing;

                            ypos += 10;

                            if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Find Internet Match"))
                            {
                                manager.matchMaker.ListMatches(0, 20, "", false, 0, 0, manager.OnMatchList);
                            }
                            ypos += spacing;
                        }
                        else
                        {
                            for (int i = 0; i < manager.matches.Count; i++)
                            {
                                var match = manager.matches[i];
                                if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Join Match:" + match.name))
                                {
                                    manager.matchName = match.name;
                                    manager.matchMaker.JoinMatch(match.networkId, "", "", "", 0, 0, manager.OnMatchJoined);
                                }
                                ypos += spacing;
                            }

                            if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Back to Match Menu"))
                            {
                                manager.matches = null;
                            }
                            ypos += spacing;
                        }
                    }

                    if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Change MM server"))
                    {
                        m_ShowServer = !m_ShowServer;
                    }
                    if (m_ShowServer)
                    {
                        ypos += spacing;
                        if (GUI.Button(new Rect(xpos, ypos, 100, 20), "Local"))
                        {
                            manager.SetMatchHost("localhost", 1337, false);
                            m_ShowServer = false;
                        }
                        ypos += spacing;
                        if (GUI.Button(new Rect(xpos, ypos, 100, 20), "Internet"))
                        {
                            manager.SetMatchHost("mm.unet.unity3d.com", 443, true);
                            m_ShowServer = false;
                        }
                        ypos += spacing;
                        if (GUI.Button(new Rect(xpos, ypos, 100, 20), "Staging"))
                        {
                            manager.SetMatchHost("staging-mm.unet.unity3d.com", 443, true);
                            m_ShowServer = false;
                        }
                    }

                    ypos += spacing;

                    GUI.Label(new Rect(xpos, ypos, 300, 20), "MM Uri: " + manager.matchMaker.baseUri);
                    ypos += spacing;

                    if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Disable Match Maker"))
                    {
                        manager.StopMatchMaker();
                    }
                    ypos += spacing;
                }
            }
        }
    }
}
#endif //ENABLE_UNET
    /**/

```

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


# Question
Title: unable to map one object position to another object over network
objective: I have a player which instantiate by network manager class. I want to map/sync its position/rotation to another object which is also instantiate by my player object.

*(what it i have tried)* Below code is attached to my network player which instantiating another object (mimic object)

```
         void Start() {
                if (isLocalPlayer)
                {
                    CmdInstantiate();
    }

         [Command]
            void CmdInstantiate()
            {
                // This [Command] code is run on the server!
                mimic = (GameObject)Instantiate(
                     mimicObject);
                // spawn the bullet on the clients
                NetworkServer.Spawn(mimic);
            }

void Update()
    {
        if (!isLocalPlayer) {

            return;
        }
        CmdMimicObjectPosSync();//updating position on server
    }

   [Command]
    void CmdMimicObjectPosSync()
    {//position sync method
        mimic.transform.position = this.transform.position;
        mimic.transform.GetChild(0).position = this.transform.GetChild(0).position;
        mimic.transform.GetChild(1).position = this.transform.GetChild(1).position;
        mimic.transform.GetChild(2).position = this.transform.GetChild(2).position;
    }

```

it is working fine on the player side but another player who has joined the network unable to see it although mimic object has instantiated but its value remains same (no change). Mimic object has attached network identity and network transform.

# Answer
> 0 votes
Each object that you want to instantiate over network must need to be added in Register spawn able list of Network Manager . By adding mimic object into spawnable list i am managed map one object postion/rotation to another object.

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


# Question
Title: SetActive true/false only once when game install first time unity?
In my unity game I try to give player instruction how to play but it only in first level and first time when game install so how i can do this?

# Answer
Store the information about having showed the tutorial in permanent local storage, such as:

* A file (if file doesn't exist, run tutorial and create file)
* The content of a file (if file doesn't exist, run tutorial and set a flag in file)
* A registry entry (if registry entry doesn't exist or is 0, run tutorial and set entry to 1)

Additionally, allow players to run the tutorial on their own, and also allow the players to skip the tutorial.
> 1 votes

# Answer
You can use PlayerPrefs to store an int value to achieve this. See the following example.

---

In this example, I have stored a key named "Test" in preferences.

1. Check if the preferences has the key. `bool exists = PlayerPrefs.HasKey("Test");`
2. If the key exists, then don't display the instructions.
3. Otherwise, display the instructions and use the following code to add the key. `PlayerPrefs.SetInt("Test",1);`
> 1 votes

---
Tags: unity
---


# Question
Title: how to make a fast fragment shader that converts intensity to saturation?
I have a simple fragment shader that looks like this:

```
#ifdef GL_ES
precision lowp float;
#endif

varying vec4 v_fragmentColor;
varying vec2 v_texCoord;
uniform vec4 u_desiredColor;
uniform sampler2D u_texture;

void main()
{
    gl_FragColor = texture2D(u_texture, v_texCoord) * u_desiredColor;
}

```

My goal is to take a grayscale image and apply a color to it, but maintain luminance. There was a stackoverflow post from years ago where the poster was after exactly what I want:

https://stackoverflow.com/questions/4361023/opengl-es-1-1-how-to-change-texture-color-without-losing-luminance

The answers however are outdated (OpenGL ES 1.0) and also I am a little confused by them. The accepted answer says to use multi-texturing, and the 2nd answer says that is "nonsense". Regardless, the code example there is incompatible with the version of OpenGL ES 2.0 that my game is using with cocos2d v2.x.

Here are my original grayscale sprites:

With my simple shader applied and setting u\_desiredColor to vec4(1.0, 0.0, 0.0, 1.0), you can see it does exactly what I don't want it to do-- it completely tints the entire image, turning everything red, including the white.

What I really want is for the darker shades of gray have the richest color, but as the sampled grayscale pixel approaches white, the colorized pixels lose saturation, where ultimately a sampled pixel of white has 0% saturation-- but a sampled pixel of dark gray would be 100% saturation.

My desired output is:

My thought was that the simplest approach would be to have my shader make the output pixel color's saturation be something like (1.0 - samplePixelIntensity). So, if the sample pixel's intensity was 1.0, that would mean 0% saturation in the output, if the sample pixel's intensity was 0.5, it would have 50% saturation.. if the sample pixel's intensity was 0.2, then it would have 80% saturation.

However, I am not very familiar with writing shaders, so I am wondering how I might construct something like this?

# Answer
> 1 votes
Simple interpolation to get the color and then applying to the grayscale image

```
#ifdef GL_ES
precision lowp float;
#endif

varying vec2 v_texCoord;
uniform vec4 u_desiredColor;
uniform sampler2D u_texture;

vec4 saturation;
vec4 grayscale;

void main()
{
    grayscale     = texture2D(u_texture, v_texCoord);
    saturation     = (1.0,1.0,1.0,1.0) - grayscale;
    gl_FragColor   = grayscale*(saturation * u_desiredColor + grayscale*vec4(1.0,1.0,1.0,1.0));
}

```

---
Tags: opengl, shaders, opengl-es2, fragment-shader
---


# Question
Title: Access to varibles in other attached gameobject script is ambiguous
I'm trying to create reusable scripts that I can drop on my GameObjects. I am currently trying to figure out how to build a projectile script. Ideally, I want to be able drop this scrip on an enemy, give it a gameobject prefab to shoot (bullet, stone, arrow, energy ball, newspaper, whatever) and it will spawn that object and make it move.

Right now, the object is just Instantiated at the enemy's position.

Then enemies can walk around (top down 2d), and face one of the 4 directions (up, down, left, right). That part works fine.

How can I get the parent game object (an enemy) current facing direction so I can make the projectile travel that direction? I have a `bool` ***canShoot*** that I want to be able to check if it is true and then use that to fire the projectile. Maybe not all of the same time of enemy shoots something.

I made and accessor to the enemyMovement variable. But I get a 'this is ambiguous error.

If someone can help me figure out how to either the facing direction or the `bool`, I should be able to figure out how to access the other variables.

Here is my walking controller script that is also attached to the enemy.

**WalkingController Script**

```
using UnityEngine;
using System.Collections;

public class WalkingController : MonoBehaviour {

    public float moveSpeed      = 0.75f;
    public float shootDamage    = 1.0f;
    public bool canShoot        = false;

    public Animator     anim;
    public Rigidbody2D body;

    public Vector2 enemyMovement;

    void Start () {
        anim = GetComponent<Animator> ();
        body = GetComponent <Rigidbody2D> ();
        StartCoroutine ("ChangeDirection");
    }

    void FixedUpdate () {
        body.MovePosition (body.position + enemyMovement * moveSpeed * Time.deltaTime);
    }
    public Vector2 getEnemyMovement() {
    return enemyMovement;
}
    IEnumerator ChangeDirection() {
        Debug.Log ("Change Direction");
        while(true){
            yield return new WaitForSeconds(Random.Range (0.3f, 1.5f));
            randomDirection();
        }
    }

    void randomDirection() {
        switch(Random.Range (0,3)){
            case 0:
                //Debug.Log ("Moving enemy Up");
                 enemyMovement = new Vector2 (0,1);
                break;
            case 1:
                //Debug.Log ("Moving enemy Right");
                 enemyMovement = new Vector2 (1,0);
                break;
            case 2:
                //Debug.Log ("Moving enemy Down");
                 enemyMovement = new Vector2 (0,-1);
                break;
            case 3:
                //Debug.Log ("Moving enemy Left");
                 enemyMovement = new Vector2 (-1,0);
                break;
            default:
                 enemyMovement = new Vector2 (0,0);
                break;
        }
        anim.SetBool ("Walking", true);
        DefineFacingDirection (enemyMovement);

    }

    void DefineFacingDirection (Vector2 vec){
        anim.SetFloat ("InputX", vec.x);
        anim.SetFloat ("InputY", vec.y);
    }

}

```

**Projectile Script**

```
using UnityEngine;
using System.Collections;

public class Projectile : MonoBehaviour {

    WalkingController wcs; // THIS DIDN"T WORK EITHER
    public GameObject objectToSpawn;
    /*public GameObject parentObject;*/
    public float timeToSpawn = 1.0f;
    public int maxObjects = 1;
    public float maxSpeed = 1.1f;
    public bool ShootAtPlayer;

    private float internalTimer = 0.0f;
    private Rigidbody2D body;

    void Start() {
        //parentObject = gameObject.GetComponent<WalkingController> ();
        body = gameObject.GetComponent <Rigidbody2D>();
 wcs = GetComponentInParent <WalkingController> ();
    }

    // Update is called once per frame
    void Update () {
        this.internalTimer += Time.deltaTime;

        if (this.internalTimer > this.timeToSpawn) {
            this.Spawn();
            this.internalTimer = 0.0f;
        }
    }

    private void Spawn()
    {

//Vector2 enemyMovement = new Vector2(GetComponentInParent <WalkingController> ().enemyMovement.x, GetComponentInParent <WalkingController> ().enemyMovement.y) ;

        Instantiate(this.objectToSpawn, this.transform.position, Quaternion.identity);

 //this doens't work. call is ambiguous????
        this.body.MovePosition (this.objectToSpawn.transform + wcs.enemyMovement() * maxSpeed * Time.deltaTime);

        Destroy (this.objectToSpawn, 4.0f);
    }
}

```

# Answer
> 2 votes
I'd be tempted to flip this around, and put the `Projectile` script on the prefab that gets fired (ie. the bullet/missile/fireball/what-have-you)

```
// Since we want this to fly with velocity & detect collisions,
// we'll trust the Rigidbody2D component to handle these aspects.
[RequireComponent(typeof(Rigidbody2D))]
public class Projectile : MonoBehaviour {

    // Projectile firing speed - might want damage/explosion fields too...
    public float speed;

    // Cache a reference to the body so we don't look it up every time.
    Rigidbody2D _body;

    // Initialize the Rigidbody2D reference so it's ready when we need it.
    void Awake() {
        _body = GetComponent<Rigidbody2D>();
    }

    // Expose method to fire a projectile.
    public Projectile Shoot(Vector3 origin, Vector3 direction) {

        // This gets called on the prefab, which never gets an Awake,
        // so we need to initialize this bit ourselves.
        if(_body == null)
            _body = GetComponent<Rigidbody2D>();

        // Spawn a copy of this GameObject, and get a reference to the
        // spawned copy's Projectile script instance.
        Projectile bullet = (Projectile)Instantiate(
                              this,
                              origin,
                              Quaternion.LookRotation(direction));

        // Awake() runs on our spawned bullet, so its _body property is set.
        // Fire the bullet the way we want it to go.
        bullet._body.velocity = direction * speed;

        // Return a reference to it, in case our parent script
        // wants to do something with it.
        return bullet;
    }

    void OnCollisionEnter2D(Collision2D collision) {
        // Implement "projectile hit" logic here or in OnTriggerEnter2D
    }
}

```

Now if I want to build an enemy or turret that uses this, I just need two lines...

```
public Projectile projectilePrefab;

```

...to expose an Inspector field to assign the projectile prefab into. And when I want to fire....

```
projectilePrefab.Shoot(barrelTransform, firingDirection.normalized);

```

This decouples the `Projectile` script from your `WalkingController` \- the bullet doesn't have to care who fired it or what kind of logic they want to use to do so (maybe some characters fire on a timer, others in bursts, others only when they see an enemy...) - its job is just to spawn & shoot when they tell it to, and damage whatever it hits.

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


# Question
Title: Performance optimization when changing Textures LibGDX
In the main `Screen` class of my game there is a `ListArray<Card>` which makes up the `deck` of cards . The `Card`'s texture is set in the constructor like so :

`cardTexture = new Texture(Gdx.files.internal("backface.png"));`

and in the `Card` class there are 2 methods to show and hide the "CardFace"

```
public void hideCardFace() {
    cardTexture = new Texture(Gdx.files.internal("backface.png"));
}
public void showCardFace() {
    cardTexture = new Texture(("CardTextures/" + this.getFace() + this.getSuit() + ".png"));
}

```

(in the *android\assets\CardTextures* there are 52 *.png* files with a size of 500x726 and rangeing in filesize from 20-220 kb)

The problem is that when I have to show or hide the "CardFace" for the entire ArrayList like so :

```
for (int i = 0; i < deck.size(); i++) {
    ((Card) deck.get(i)).hideCardFace();
}

```

I experience a performance drop both on PC and Android to the point where the Game lags for 1-2 seconds until all the CardFaces are hidden or showed.(I did multiple tests and the FPS dips only when I call the 2 methods)

Is there any other way (better for performance) to change the CardFace?

# Answer
> 1 votes
Read about the `AssetManager` here: https://github.com/libgdx/libgdx/wiki/Managing-your-assets

You are loading new `Texture`'s objects with each card change which equals DEATH. What you should do is have 52 card textures in memory and 1 back card texture, so 53 textures at max.

Your code allocates new ram with every card change you make. It's unacceptable.

Create a class for all the assets for example:

```
public class Assets{
    private AssetManager assetMgr;
    private static HashMap<CardType, Texture> cardsTextures = new HashMap<>();
    private static Texture faceDownTexture;
    public Assets(){

        assetMgr = new AssetManager():

        // load all the 53 assets with AssetManager

        // assetMgr load...

        // and now put these values from assetManager into the map
        // make a loop or something !
        cardsTextures.put(ACE_OF_SPACES, aceofspadestexture);
        cardsTextures.put(THREE_OF_SPACES, aceofspadestexture);
        cardsTextures.put(SEVEN_OF_SPACES, aceofspadestexture);

        // load faceDownTexture texture for example
        faceDownTexture = new Texture(Gdx.files.internal("cards/facedown.png"));

        cardsTextures.put(FACE_DOWN, faceDownTexture);
    }

    // a method that will give you your textures from anywhere in the code

    public static Texture getCardTexture(CardType type){
        return cardTextures.get(type);
    }

    public static Texture getBackTexture(){
        return backTexture;
    }

}

```

Use the class above to load all these textures with AssetManager and create your card class like this:

```
public class Card{

    private Texture cardTexture, backTexture;
    private boolean isFaceUp;

    public Card(CardType type){

        cardTexture = Assets.getCardTexture(type);
        backTexture = Assets.getBackTexture();

        isFaceUp = false;

        setSize(cardTexture.getWidth(), cardTexture.getHeight());

    }

    @Override
    public void draw(Batch batch, float parentAlpha){
        if(isFaceUp)
            batch.draw(cardTexture, getX(), getY(), getWidth(), getHeight());
        else batch.draw(backTexture, getX(), getY(), getWidth(), getHeight());

    }

    public void showFaceUp(boolean b){
        this.isFaceUp = b;
    }
}

```

This is all pseudocode, but this is the right way.

Then, your 'switching' code should look like this:

```
// 10000 nanoseconds and 0 RAM!
for (int i = 0; i < deck.size(); i++) {
    ((Card) deck.get(i)).showFaceUp(false);
}

```

---
Tags: java, libgdx, textures, sprites, performance
---


# Question
Title: How can I detect when all numbers are a certain value?
I'm trying to write "you win" when all numbers are "green" (in this case, equal to the constant `Fez.color.g`). This is the script I have so far:

```
void Start () {
    for (int SD = 0; SD < 10; SD++) {
        number = Random.Range (0, 9);
        print ("X:" + X);

        Fez.text = number.ToString ();
        //print (Fez);
    } else {
        Fez.text = ("   ");
    }
}

void Update ()
{
    if (number != Fez.color.g) {
        if (Input.GetKeyDown (KeyCode.Space)) {
            print (script.randomnumber);
            if (script.randomnumber == number) {
                Fez.color = new Color (0, 1, 0);
                //Destroy( number);
                //  print (SD);
            } else {
            }
        } else {
            print (" YOu  win");
        }
    }
}

```

But right now there's a bug, it prints "you win" even when all numbers aren't green. How do I change this to print the text only when all the numbers are green?

# Answer
> 1 votes
I think the fundamental issue you're having is that you refer to "numbers" but you only seem to track *one* number. To store multiple numbers you want an array:

```
int numbers = new int[10]; // 10 numbers.

```

Then you can assign values to individual elements of the array in your `Start` function:

```
for (int SD = 0; SD < numbers.Length; ++SD) {
    numbers[SD] = Random.Range(0, 9);
}

```

Then you can check to see if they are "all" some value. One simple way to do this is to assume they are all the desired value:

```
bool areAllGreen = true;

```

But then check every number anyway; if you ever see one that isn't the desired value, update the state of `areAllGreen`:

```
for (int SD = 0; SD < numbers.Length; ++SD) {
  if(numbers[SD] != Fez.color.g) {
    areAllGreen = false;
    break;
  }
}

```

You can do the above in your `Update` function. Then you can check `if (areAllGreen) print("You win!");`

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


title: how to correctly scale box2d in libgdx

text:
# Question
Title: how to correctly scale box2d in libgdx
I'm currently using 800x480 resolution and FitViewPort and I divided that by PixelPerMeter variable which is equal to 10 and that helped to move my box2d body faster. But when I tried to use fonts I could easily see pixels. What am I doing wrong and what can I do to fix that ?

# Answer
> 0 votes
Fonts aren't drawn using Box2D so the PPM is irrelevant here.

If you need device-dependent resolution to ensure maximum quality, crisp fonts, you could use a ScreenViewport positioned over your FitViewport, and render all your font related output onto the ScreenViewport.

---
Tags: libgdx, box2d, resolution, scale
---


# Question
Title: Unity: Trying to add an in-scene 'press E to open' tag as UI element
In Unity 5.4.1 I'm trying to add a tag that says 'press E to open' to a door as you approach it. I've got a RayCast pointing forward from the player, detecting the door and , connected to my PlayerController, I've got a copy of a prefab GameObject which itself contains a Text UI element. The GameObject \_interactionTag is instantiated into the scene when the player is close enough.
But I'm having some trouble getting it to display correctly in the scene and I'm not sure why.

Here are the relevant parts of my PlayerController:

```
public class PlayerController : MonoBehaviour {
    public Canvas _canvas;
    private Vector3 _fwd;
    private RaycastHit _hit;
    public GameObject interactiveTag;
    private GameObject _interactiveGameObject = null;
    private GameObject _interactionTag;

    void Update () {
        _fwd = transform.TransformDirection(Vector3.forward);
        if (Physics.Raycast(transform.position, _fwd, out _hit, 3)) {
        if (_hit.distance<1) {
            _interactiveGameObject = _hit.collider.gameObject;
            GameObject _interactionTag = (GameObject) Instantiate(interactiveTag, _interactiveGameObject.transform.position, _interactiveGameObject.transform.rotation);
           _interactionTag.GetComponentInChildren<Text>().text = _interactiveGameObject.GetComponent<IsInteractive>().interactionText; // this gets a text string from the door 'press E to open'
           _interactionTag.transform.SetParent(_canvas.transform, false);
        }
    }
}

```

In game, the \_interactionTag is appearing - though it's backwards and does not appear attached to the door. Also is any of this the best way of getting the 'press E to open' tag to appear attached to the center of the door? I'm beginning to wonder if what I'm doing is best practise. Thanks for any help.

# Answer
I think in this case it would be much easier if you just add the world-space canvas to the prefab as a child and disable it at start-up. Then in your code you just enable it when your distance condition is true and vice versa.
> 1 votes

---
Tags: unity, gui
---


# Question
Title: Unity - Particle System Shuriken - Setting particles in code with random row in texture animation?
Good day, I'm attempting to randomly generate a space scene (quite large actually) in Unity through C# code mainly. So far, I've gotten stunning results up to what image #2 will show you. However, now I'm looking to expand the look with more random particles. So, I've made a texture atlas of 8 in a vertical row, which works on the random setting if you have an emitter and the particle system is called with `PS.Play();`

Assigning different materials would only work on a per particle system basis(which would be new texture PER cloud, so to speak) which is not what I want. So, my question:

How can I use the Shuriken Particle System's Texture Sheet Animation functionality through code, without having an "active" particle system? More precisely, I wish to use the 'Random Row' feature of it to assign random textures to each particle.

Since I can't share my code (due to policies), here is a bit more info on how I do it:

1. I create an array with coordinates for each cloud.
2. Assign a particle system to that cloud.
3. Randomly generate all the particles for the cloud with relative offsets.
4. Use `PS.setParticles(particlesArray);`

Using a Texture Atlas consisting of the letters A to H to test, only B showing on all particles.

Using a Texture Atlas consisting of the fog particles to test, only 2nd showing on all particles.

Thank you @DMGregory for the help, I've tested it multiple times and it works perfectly now, I've also went ahead and tweaked a few of my settings just to get a more "clear" space:

# Answer
> 4 votes
In my tests, it's sufficient to set a random seed on each particle as we place it into our particle buffer.

That seed is then used to calculate all the runtime randomized properties on the particle (including texture sheet random row / random start frame, but not initial properties like StartColour which are already stored separately)

Here's an example:

```
using Particle = UnityEngine.ParticleSystem.Particle;

[RequireComponent(typeof(ParticleSystem))]
public class ParticleCloudRandomizer : MonoBehaviour {

    public float radius = 10f;
    ParticleSystem _system;

    void Start () {
        _system = GetComponent<ParticleSystem>();

        // Create a buffer large enough for all our particles.
        Particle[] particles = new Particle[_system.maxParticles];

        // Note the using statement above - I'm using "Particle" to mean
        // UnityEngine.ParticleSystem.Particle to save typing. ;)

        // Prep a template particle with any parameters we want constant.
        Particle template = new Particle();
        template.startLifetime = _system.startLifetime;
        template.lifetime = _system.startLifetime;
        template.startSize = _system.startSize;
        template.startColor = _system.startColor;

        // Fill our buffer with randomized copies of this particle.
        for(int i = 0; i < particles.Length; i++)
        {
            template.position = Random.insideUnitSphere * radius;

            // This is just a naive way to roughly fill the uint range.
            // I don't guarantee it gives good randomness properties,
            // but on visual inspection it looks "good enough"
            template.randomSeed = unchecked((uint)Random.Range(int.MinValue, int.MaxValue));

            // In the past I've also used this trick of setting the lifetime
            // to a random fraction of its initial value, then setting
            // "Texture Sheet Animation -> Frame Over Time" to "Curve"
            // template.lifetime = Random.value * template.startLifetime;

            // Save this randomized particle into our buffer:
            particles[i] = template;
        }

        // Pass our filled particle buffer to the ParticleSystem.
        _system.SetParticles(particles, particles.Length);
    }
}

```

Here's what it looks like in my setup:

(The particle system is not playing - it's just displaying the buffer of particles we gave it at Start)

If you want to add or overwrite more particles later, just do the same operation above, setting a random seed on each before it's added to the buffer and passed to the ParticleSystem with SetParticles.

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


# Question
Title: SDL2 and OpenGL: flickering with double buffering, what am I doing wrong?
I'm currently fiddling with SDL2 and OpenGL to get an understanding on how they work and, moreover, how shaders are done and work. Right now, I'm following this tutorial, using SDL instead of glfw; and in a SDL window I render 2 triangles via shader and change their color dynamically, but an obnoxious flickering effect shows, even though I'm sure double buffering is active.

Now, to the code:

```
    //Here they are SDL attributes for OpenGL
    SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 );
    SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 1 );
    //Double buffer should be on by default, but I set it anyway
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE );

    //SDL window creation
    mWindow = SDL_CreateWindow( "Window Title",
                            SDL_WINDOWPOS_UNDEFINED,
                            SDL_WINDOWPOS_UNDEFINED,
                            mWidth,
                            mHeight,
                            SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE );

    // Use Vsync
   if( SDL_GL_SetSwapInterval( 1 ) < 0 )
   {
         SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Warning: Unable to set VSync! SDL Error: %s\n", SDL_GetError() );
  }

    //OpenGL initialization
    glClearColor(0.f, 0.f, 0.f, 1.f);

    glEnable( GL_TEXTURE_2D );

    glEnable( GL_BLEND );
    glDisable( GL_DEPTH_TEST );
    glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );

```

while one of the shaders (no point in pasting the other one, too, as the issue is the same) I use is:

vertex shader:

```
#version 330
layout (location = 0) in vec3 position;
layout (location = 1) in vec3 color;
out vec3 LSampleFrag;
void main()
{
    gl_Position = vec4(position, 1.0);
    LSampleFrag = color;
}

```

fragment shader:

```
#version 330
out vec4 color;
uniform vec4 LSampleFrag;
void main()
{
    color = LSampleFrag;
}

```

Binding of vertex data to the shader:

```
    glClearColor(0.f, 0.f, 0.f, 1.f);

    //VBO data
    GLfloat vertexData[] =
    {
        0.5f, -0.5f, 0.0f,
        0.5f, 0.5f, 0.0f,
        -0.5f,  0.5f, 0.0f
    };

    glGenVertexArrays(1, &gVAO);
    glGenBuffers(1, &gVBO);
    // Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s).
    glBindVertexArray(gVAO);

    glBindBuffer(GL_ARRAY_BUFFER, gVBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW);

    // Position attribute
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), nullptr );
    glEnableVertexAttribArray(0);

    glBindVertexArray(0);

```

and its render function is this one, where I change, everytime is called shade of green:

```
GLfloat timeValue = SDL_GetTicks();
GLfloat greenValue = (sin(timeValue) / 2) + 0.5;
GLint vertexColorLocation = glGetUniformLocation(mProgramID, "LSampleFrag");
glUniform4f(vertexColorLocation, 0.0f, greenValue, 0.0f, 1.0f);

glBindVertexArray(gVAO);
glDrawArrays(GL_TRIANGLES, 0, 3);
glBindVertexArray(0);

//in the main render function, after rendering the shader
SDL_GL_SwapWindow( window_->getSDLWindow());

```

As I've already said, double buffering is active but flickering is still an issue: am I missing something? I really don't understand why it is happening.

# Answer
> 3 votes
In fact it's not a flickering problem, in the last codebox lies the root of the nuisance.

```
GLfloat timeValue = SDL_GetTicks();
GLfloat greenValue = (sin(timeValue) / 2) + 0.5;

```

Those two lines update the green value each millisecond, changing the colour far too fast, and it could look like a flicker, try increasing the period (decreasing the frequency) of the sin like this:

```
float period = 1000.0f;
GLfloat timeValue = SDL_GetTicks();
GLfloat greenValue = (sin(timeValue/period) / 2) + 0.5;

```

---
Tags: opengl, shaders, sdl2, double-buffering
---


# Question
Title: Explaining "dx" and "dy" as ball properties
A ball in a 2D volleyball game is described by 4 variables, `x` , `y`, `dx` and `dy`. What exactly does it mean by `dx` and `dy`?

# Answer
> 0 votes
I have encountered this, before, when dealing with computer graphics. In these cases, `x` and `y` are the co-ordinates for the *center* of the circle, while `dx` and `dy` are the *dimensions* (or commonly, the *diameter*) of the circle.

---

This seems especially valid in the described scenario, even if the volleyball would typically be a perfect circle (i.e. we only need a single diameter, as `dx == dy`). This is not always the case, in animation. A common practice for basic shapes is to simply alter the *width* or *height* with movement, to show greater animation.

# Answer
> 5 votes
I guess it is the **speed** of the ball.

At each frame, you can update the coordinates of the ball by doing

```
x = x + dx;
y = y + dy;

```

You should not update the position as written above in real life. If you are doing this in a game loop you should always keep track of the "delta", the time between 2 frames. That way, even if users have a different FPS, the ball will still move the same.

The code will look like :

```
x = x + dx * delta;
y = y + dy * delta;

```

The more time between 2 frames, the more distance traveled by the ball.

# Answer
> 1 votes
The dx and dy naming convention comes from calculus. In calculus you often find the derivative of a function which is often read as "the change in x" or "the change in y". These terms are notated using dx, dy, dz, etc. You can read more about it here.

---
Tags: 2d
---


# Question
Title: How to fix overly blurred texture / image in unity?
so, I'm not sure what caused this, let image below do the explanation :  How to fix the overly blurred texture in unity? It's so frustrating, since I can't get it right, because when I tried it in LibGDX, the image looks good (Well, it's not exactly a same image, but similar).

They both screenshot from android device (Samsung Galaxy Note 3 Neo)

Thanks

P.S. It's a pixel art

Edit, here's the screenshot of my relevant inspector window

And here's the alpha ingame screenshot

# Answer
> 1 votes
In order to get pixel-perfect 2D graphics in Unity, you need to correctly set the size of the camera. I explain it in this other question:

Why does Unity in 2d mode employ scaling and the default othographic size the way it does?

Long story short, set the camera to Orthographic (which you've done) and then set the Size to:

size of your screen / pixels-per-unit setting of your images / 2

# Answer
> 0 votes
This is weird tho. The unity remote view is blurred, while the built version is not. I think it's because the unity editor resolution is somehow forced to fit the window size (even though I've defined 1280x720 manually, but still forced down to around 400ish pixel), because, when I build the apk version and installed it on my device, the picture no longer blurred. Not sure why. (I tried with a new clean project btw.). But I think the problem is not on the camera ortho size.

# Answer
> 0 votes
I don't see an obvious problem in the settings you show, but I have seen a similar blurring effect with unusually wide sprite sheets. The program Aseprite likes to export in one long sheet, like a film strip, and that is where I've seen it happen. When this has occurred for me, changing the *Max size* on the **sprite import settings** did not fix the problem. I had to edit my sprite sheet and make it more grid based.

---
Tags: android, libgdx, sprites, unity
---


title: How do I create geometry in SceneKit?

text:
# Question
Title: How do I create geometry in SceneKit?
I have been experimenting with Apple's new SceneKit for fun, but I cannot seem to figure out how to input vertex data without loading a `.dae` file.

Does anybody who has been testing SceneKit have any idea how to set or modify vertex data?

# Answer
SceneKit is primarily a scene graph API and it isn't designed to be a complete solution for all your rendering needs; it's designed to augment existing APIs such as GLKit and CoreAnimation.

Primarily the focus of the API is loading serialized geometry assets (`.dae` files) and organizing them in a scene graph. There aren't very many robust alternative methods to get geometry into the API.

However, you may find SCNGeometry's geometryWithSources: selector to be what you need. Here's an example in practice.
> 1 votes

# Answer
I recently wrote an article on this topic which you might find helpful, it explains the basic of creating custom **SceneKit geometry**: http://sound-of-silence.com/?article=20161108

There is also related example code of creating custom geometry with SceneKit for deformable terrain meshes in that post, the code can be found on GitHub here: https://github.com/matthewreagan/TerrainMesh3D
> 0 votes

---
Tags: opengl, vertex
---


# Question
Title: Structure game database to store player info and items
Recently I started developing my tiny html5 multiplayer game made in *Node.js*, *Express.js*, *MongoDB(Mongoose)*, *Socket.io* and using *Phaser.js*.

I am quite new to these frameworks and especially new to database structuring/management.

My struggle comes when I think about how can I structure the database to store things as player username, password and general preferences (basic user info); and then things as player equipment such as items and currency.

I can figure out how to do the code part but what I do not know how to handle is the process I should follow.

I thought of the structure like so:

```
//Users Document
{
    "_id": "randId",
    "username": "ArthurConan",
    "password": "aquamarine12345",
    "credits": 20,
    "equipment": [
        {
            "name": "Sword of the Forsaken",
            "equiped": true,
            "slot": "weapon",
            "id": "itemId",
        },
        {
            "name": "Meteor Katana",
            "equiped": false,
            "id": "itemId"
        }
    ]
}

//Items Document
{
    "_id": "itemId",
    "name": "Sword of the Forsaken",
    "atk": 1400,
    "value": 500
},
{
    "_id": "itemId",
    "name": "Meteor Katana",
    "atk": 200,
    "value": 50
}

```

As I am using MongoDB the structure would be more or less similar to that.

With the code above then I would do the following: \- Player Registers and his basic info(username, password, ...) is added to the database and he will also get one weapon to start with. \- Player adventures into my world and gathers credits and equipment. Those items are stored in his inventory. \- Player can equip/use/sell/destroy/upgrade some of those items. Upgraded items will have its stats upgraded based on preset stats.

*As a side-note I would like you to know I am not the best at explaining myself, I hope you understand what I am trying to achieve. Also any suggestions are appreciated, have a good day :)*

# Answer
> 1 votes
A suggestion: Data storage structure

```
User
|  |-- id
|  |-- password
|  |-- storage password
|  |-- etc
|
Characters
|  |-- name
|  |-- id (User)
|  |-- Equipment1 on head //store item by equipping
|  |-- Equipment2 as armor
|  |-- etc
|
Storage
|  |--id_storage
|  |--id (User)
|  |--id_item (Item) //store item by storage
|  |--etc
|
Item
   |--id_item
   |--item name
   |--item description
   |--etc

```

---
Tags: javascript, html5, databases, node.js
---


# Question
Title: Destroying anything, after a moving trigger box exits it
I'm making a endless runner game, and i have a trigger box following the character, behind the camera. I want it to destroy any kind of object, after the trigger box exits the object. so far i have written this for the code, but it doesn't seem to be correct, and actually doesn't work!

```
 void OnTriggerExit (Collider other)
 {
     Destroy(other.gameObject);
 }

```

What should i add to this? Thanks.

# Answer
In order for `OnTriggerExit()` to work, at least one of the game objects involved in the collision must have a rigid body component attached.
> 1 votes

# Answer
Can I make a suggestion? Instead of moving the world, Move the objects via an offset. It will give the illusion that the player is moving through the world, while simplifying the process. To destroy objects you then just test for its position. Say negative X is behind you. Any object that goes beyond some arbitrary distance, say -10.0f will be eligible for destruction. You won't need any fancy collision detection. Remember, KISS: Keep It Simple Stupid.
> 0 votes

---
Tags: unity
---


# Question
Title: PhysX Capsule Character Controller floating above ground
I am using PhysX Version 3.0.2 in the simulation package I'm working on, and I've encountered some bizarre behavior with the capsule character controller.

When I set the controller's height and radius to the appropriate values (r = 0.25, h = 1.86)it **behaves** correctly (moving along the ground, colliding with other objects, and so on) except that the capsule itself is floating above the ground. The actor will then bump his head when trying to get through a door, since the capsule is the correct height but also floating above the ground.

This image should illustrate what I'm going on about:

One can clearly see that the rest of the scene has their collision bodies wrapped correctly, it's just the capsule that's going wrong!

The stop-gap I've implemented is creating a smaller capsule and giving it an offset, but I need to implement ray-picking for the controller next so the capsule has to surround the character model properly.

Here's my character creation code (with height = 1.86f and radius = 0.25f):

```
NxController* D3DPhysXManager::CreateCharacterController( std::string l_stdsControllerName, float l_fHeight, float l_fRadius, D3DXVECTOR3 l_v3Position )
{
    NxCapsuleControllerDesc l_CapsuleControllerDescription;

    l_CapsuleControllerDescription.height = l_fHeight;
    l_CapsuleControllerDescription.radius = l_fRadius;
    l_CapsuleControllerDescription.position.set( l_v3Position.x, l_v3Position.y, l_v3Position.z );

    l_CapsuleControllerDescription.callback = &this->m_ControllerHitReport;

    NxController* l_pController = this->m_pControllerManager->createController( this->m_pScene, l_CapsuleControllerDescription );
    this->m_pControllerMap.insert( l_ControllerValuePair( l_stdsControllerName, l_pController ) );
    return l_pController;
}

```

Any help at all would be appreciated, I just can't figure this one out!

P.S. I've found a couple of (rather old) threads describing the same issue, but it seems they couldn't find a solution either. Here are the links:

# Answer
> 1 votes
The first link has the answer to that problem http://forum-archive.developer.nvidia.com/index.php?showtopic=6409

> OK, well I figured out this "magic" number ... the capsule will always be \[Radius + (Height/2) + contactOffset \] off the ground. Hope this helps someone.

contactOffset is 0.1 by default and if you change it to 0.01 it should be really close to the ground

# Answer
> 0 votes
I had the same problem, Im using Unity 4,

Go to the character controller and change the skin width option to : 0.0001

I don't particularrly know what this does but I changed this option to that and it works, my character can detect the ground correctly on all objects with any type of collider.

Hope this helps :)

# Answer
> 0 votes
Skin width =Two colliders can penetrate each other as deep as their Skin Width. Larger Skin Widths reduce jitter. Low Skin Width can cause the character to get stuck. A good setting is to make this value 10% of the Radius.

---
Tags: c++, physx
---


# Question
Title: Cross-Platform CocosSharp Content Pipeline Project?
Just getting started with CocosSharp and Xamarin.Forms and I wanted to move on from using Circles and lines to draw everything. It looks like setting up a MonoGame Content Pipeline project is the way to go.

I've got the tool installed (on my mac). My "game" is actually really simple and is more of a visualization. I want to load up a texture file for a background, an image or two for the foreground, and a largish pile of sound files.

Do I have to manage the exact same files twice, in a separate tool from Xamarin Studio in order to do this? It seems like I'm missing something, but the documentation doesn't talk about cross-platform sharing at all.

# Answer
When you add the content project MSBuild overrides the set platform in your project (using it only as a default when you're building in the tool itself). You can use a single project, referencing it from both your platform specific tools to make sure MSBuild does this correctly.

Found the answer in a blog post by @darkside:

> \[The project's\] platform is determined when you build the project You can either fix the platform build type (which is like setting a default) and build the content manually (you can also call the MGCB tool programmatically from a build script to build it separately if you wish as well, for advanced users). Alternatively, if you have your content file attached to your solution (which is the default), then Visual Studio will tell the Content Project which platform to build based on the platform you are building automatically, regardless of whether you share the project or not. This means you don't have to worry if the content will work on the platform or not (as different platforms use different methods for compression, formatting and so on. An XNB file built for Windows likely won't work on Android for example.

Quote from: http://darkgenesis.zenithmoon.com/monogame-building-multi-platform-solutions/
> 1 votes

---
Tags: monogame
---


title: How to make the minimap inactive?

text:
# Question
Title: How to make the minimap inactive?
I have created a minimap for my top-down Shooter and it is showed on the top-left corner of the window. The problem is that if I press anywhere upon the minimap, its like pressing somewhere on the normal game as I have used views to make it. Is there any way to make the minimap inactive?

Thanks in advance.

# Answer
> 1 votes
It sounds like what you are doing for the minimap is another camera/viewport that is placed in the top-left corner of the screen. What should be done instead is a visualization of a portion of the area you are currently in.

For example, in a tile based game you can use the location of the player and choose a size for the minimap. What you do is then draw the minimap based on a box centered around the player and the tile data.

```
X = wall; E = enemy; @ = character; -| = camera bounds
   SCREEN           MINIMAP
XXXXXXXXXXXXX    XXXXXXXXXXXXX
X   EX      X    X   X       X
X   |X----| X    X   X       X
X   |X @--| X -> X   X @     X
X   |-----| X    X           X
XXXXXXXXXXXXX    XXXXXXXXXXXXX

```

In the example above, the character is centered in a 5x3 bounding box used to generate the minimap. You can scan the tiles in the box and draw the minimap based on what is located there. With this method, the minimap is treated as a GUI object rather than another 'screen' for the game input.

# Answer
> 0 votes
Check your mouse XY is outside of the minimap space. Something like

```
if (mouse_x > minimapWidth && mouse_y > minimapHeight)
{
    // OUTSIDE MINIMAP: do input stuff using mouseXY
}
else
{
    // INSIDE MINIMAP: do minimap stuff using mouseXY
}

```

I had a problem like this myself, but don't remember exactly if you have to subtract the minimap values from the view's width and height too (I'm pretty sure top left is 0,0 when it comes to game maker's views, but do remember plenty of GUI stuff I did requiring subtraction of the view's width and height... then again my minimap was top right).

Logging mouse\_x and mouse\_y in the debugger and watching what numbers come up as you scroll about the view will give you the numbers you need regardless, and is a helpful practice for doing GUI stuff.

# Answer
> 0 votes
If referring to the width/height of the mini map isn't working, you could try hard-coding in the parameters.

Or (silly idea), you could create a blank, transparent object the size of the mini map and check that the mouse isn't touching that?

Not a very efficient solution, but might get the job done for now.

# Answer
> 0 votes
A view is a part of your room, you can't have 2 different behaviors in each one of them. One partial solution is to check if the X and Y are inside the main viewport, so in case the player clicks far away where the main viewport can't "see", it won't execute your code.

You can make this by checking:

```
//Assuming the main viewport is 0
if((x >= view_xview[0] && x <= view_wview[0]) && (y >= view_yview[0] && y <= view_hview[0]))
{
    //Do stuff because I'm on a clickable area of the main viewport
}

```

---
Tags: game-maker, view
---


title: unity onCollisionEnter does not work

text:
# Question
Title: unity onCollisionEnter does not work
I know this question has been asked several times but none of the answers solved my problem.

I made an sphere and gave it rigidbody. then I draged the sphere on to a new made prefab.

on mouse-click Instances of this prefab are made and shot. the spheres collide with things in the scene but the onCollisionEnter function is not called. all things in the scene have colliders.

I would be grateful if you could tell me what's wrong

**edited**: it works if either the sphere or the other object's collider is trigger and I use onTriggerEnter.

# Answer
Since you mention onCollisionEnter, could it be a typo? because, the function is written OnCollisionEnter (upper case O)
> 1 votes

# Answer
I believe this happens because the bullet's speed is very fast so the collision doesn't have enough time to be detected, that's why I prefer using raycast for the shooting.
> 1 votes

# Answer
For me it worked when I made the first letter O of OnCollisionEnter capital. Hope that helps someone.
> 0 votes

---
Tags: unity, collision-detection
---


title: How to rotate to look at target

text:
# Question
Title: How to rotate to look at target
I have found other questions like this, but none seem to quite cover the situation I have.

I am using DirectX 11

I have an object that has:

* Position (vector)
* Rotation (quaternion)
* View angle (pitch, roll, yaw)

The view angle needs to be added to the rotation in order to know the true view rotation. You can think of view a head, and rotation as body.

I want to be able to turn the head so that it looks at a given point in space (vector)

The head needs to move slowly so I need to workout what way to turn and then move the head in that direction in small amounts. (pitch, yaw, roll) units

I have attempted to get this working but I don't even seem to be able to get close to what I need.

Thanks in advance.

# Answer
1)Convert your rotation angle to quaternion

2)Multiply this quaternion by your object's rotation quaternion

3)Use Spherical Linear Interpolation (SLERP) to interpolate between these two quaternions.
> 1 votes

---
Tags: directx, rotation, vector, matrix, models
---


# Question
Title: canvas not found in game view with unity
I am working on a GearVR app with Unity3D.I have an environement and I have placed a canvas in the scene.I have set the canvas Render mode to "**World Space**".But when I runned my project,the canvas is getting displayed on the scene view,but in the game view the canvas is not getting on the scene.But whereas in the camera view its showing the canvas.What will be the issue?.

When I set me canvas Rendere mode to **Screen Space-Overlay** the canvas is getting displayed in the scene but as the lookup change,the canvas is also moving along with the camera

Can anybody please help me out.

# Answer
> 1 votes
The issue got solved.I was unity 5.3.4 for developing the gearvr application.I switched the unity version to 5.4.2.Now the canvas is displayed on the screen.I searched a lot on this.It stated that there is problem with canvas rendereing in 5.3 on wards.

---
Tags: unity, gearvr
---


# Question
Title: Enemy AI chase twitching left and right to move vertically
I'm making an enemy follow the player based on his possition and attack if he is within a distance and his last movement (if the enemy last moved to the left, it will attack to the left, etc.). It attacks just fine left and right but not up or down. I tried watching frame by frame to see what happened and discovered that the enemy was twitching left and right to get to the player even if it was above or below him, which is the reason it is recording the last move to the left or right and not attacking top or bottom.

This is the code I use to update the position to where the enemy is going to move (pposX and Y is the player's current position and stillLock the last direction to where the enemy moved)

```
        xMove = 0;
        yMove = 0;

        if(pposY < y){  //UP
            yMove = -speed;
            stillLock2 = 3;
        }
        if(pposY > y){  //DOWN
            yMove = speed;
            stillLock2 = 4;
        }
        if(pposX < x){  //LEFT
            xMove = -speed;
            stillLock2 = 1;
        }
        if(pposX > x){  //RIGHT
            xMove = speed;
            stillLock2 = 2;

```

And this is the method I call to create a rectangle with the range of the attack if the cooldown limit is met and hurt the player if it intersects it's collision bounds. (attack is a boolean var indicating enemy is ready to attack)

```
public void checkAttacks(){
    attack2Timer += System.currentTimeMillis() - lastAttack2Timer;
    lastAttack2Timer = System.currentTimeMillis();
    if(attack2Timer < attack2Cooldown){
        return;
    }

    Rectangle cb = getCollisionBounds(0, 0);
    Rectangle ar2 = new Rectangle();
    int arSize = 50;
    ar2.width = arSize;
    ar2.height = arSize;

    /*
     * Still lock diagram
     * 1 = Left
     * 2 = Right
     * 3 = Up
     * 4 = Down
     */

    //creates collision rectangle

    if(attack && stillLock2 == 3){          //UP
        ar2.x = cb.x + cb.width / 2 - arSize / 2;
        ar2.y = cb.y - arSize;
    }else if(attack && stillLock2 == 4){    //DOWN
        ar2.x = cb.x + cb.width / 2 - arSize / 2;
        ar2.y = cb.y + cb.height;
    }else if(attack && stillLock2 == 1){    //LEFT
        ar2.x = cb.x - arSize;
        ar2.y = cb.y + cb.height / 2 - arSize / 2;
    }else if(attack && stillLock2 == 2){    //RIGHT
        ar2.x = cb.x + cb.width;
        ar2.y = cb.y + cb.height / 2 - arSize / 2;
    }else
        return;

    attack2Timer = 0;

    //if something above happened, check collisions
    if(handler.getWorld().getEntityManager().getPlayer().getCollisionBounds(0, 0).intersects(ar2)){ //damages if player is there
        handler.getWorld().getEntityManager().getPlayer().hurt(1);
        return;
        }
    }

```

I would appreciate so much if anybody had an idea of how to fix this! (And I'm trully sorry about the code dump).

# Answer
> 0 votes
The problem happen (guess) when you are at an adjacent position where even if position is up\down it still be left\right. Since left\right are the last conditions, it overwrite the value of up\down.

Resolve by either:

1. Use "case" condition instead of "ifs"
2. (Recommended) Use two variables. One for up\down and another for left\right.

As bonus, here's how to organize the attack.

Try this simple logical technique since width = height = size (s).

```
//position modifier
s = arSize;
m = s / 2;    //adjust as you wish  Range: [s]..[s/2]..[0]

if(attack)
{
     //UP
     if(stillLock2 == 3)
     {
         ar.y = cb.y + s;
         ar.x = cb.x - m;
     }

     //DOWN
     if(stillLock2 == 4)
     {
         ar.y = cb.y - s;
         ar.x = cb.x - m;
     }

     //LEFT
     if(stillLock2 == 1)
     {
         ar.y = cb.y - m;
         ar.x = cb.x - s;
     }

     //RIGHT
     if(stillLock2 == 2)
     {
         ar.y = cb.y - m;
         ar.x = cb.x + s;
     }
}

```

---
Tags: ai, tiles, tilemap, combat
---


# Question
Title: I don't think my shaders are working, looking for help
Using sharpdx(directx 11) developing on UWP.

This is a link to a previous question of not being able to compile the shader files(written in hlsl) How to compile shader files in UWP Later I have found some method to avoid the original exception(unable to open or find shader files) but still the shaders seem not to be working.

**My method** to "avoid the original exception" is to change the file path to

```
System.IO.Path.Combine(Windows.ApplicationModel.Package.Current.InstalledLocation.Path, "ProjectName")

```

If the method works, I would surely post it as an answer to the previous question

**The current problem** is no display on the screen(all black), while I can check the stored data in the vertex buffer using graphic diagnostics tools built in visual studio.

Here is my code for the shaders, problem may be going from here because this is the first shader file I've written. Please have a look and discuss may things go wrong.

pixel shader file Pixel\_PS.fx

```
struct VertexOut
{
    float4 PosH : SV_POSITION;
    float4 Color : COLOR;
};

float4 PS(VertexOut pin) : SV_Target
{
    return pin.Color;
}

```

vertes shader file Transf\_VS.fx

```
cbuffer dataBuffer : register(b0)
{
    matrix ViewProjection;
};

struct VertexIn
{
    float3 PosL : POSITION;
    float4 Color : COLOR;
};

struct VertexOut
{
    float4 PosH : SV_POSITION;
    float4 Color : COLOR;
};

VertexOut VS(VertexIn vin)
{
    VertexOut vout;
    // Transform to homogeneous clip space.
    vout.PosH = mul(float4(vin.PosL, 1.0f), ViewProjection);
    // Just pass vertex color into the pixel shader.
    vout.Color = vin.Color;
    return vout;
}

```

where I compiled them

```
byte[] vertexShaderByteCode = ShaderBytecode.CompileFromFile(this.path + "\\Transf_VS.fx", "VS", "vs_5_0");
                this.vertexShader = new D3D11.VertexShader(
                    device,
                    vertexShaderByteCode
                    );
                this.inputSignature = new ShaderSignature(vertexShaderByteCode);
                this.pixelShader = new D3D11.PixelShader(
                    device,
                    ShaderBytecode.CompileFromFile(this.path + "\\Pixel_PS.fx", "PS", "ps_5_0")
                    );

```

data structure definition

```
public struct ScatterVertex
    {
        SharpDX.Vector3 Position;
        SharpDX.Color4 Color;
    }

```

inputlayout initialization

```
this.inputLayout = new D3D11.InputLayout(
                    this.device,
                    inputSignature,
                    new SharpDX.Direct3D11.InputElement[]
                    {
                        new D3D11.InputElement(
                            "Position",
                            0,
                            SharpDX.DXGI.Format.R32G32B32_Float,
                            0
                            ),
                        new D3D11.InputElement(
                            "Color",
                            0,
                            SharpDX.DXGI.Format.R32G32B32A32_Float,//I'm not very sure whether or why I should use this option
                            0
                            )
                    }
                    );

```

Here's the projection matrix in the camera class, which is later sent to the constant buffer

```
private Matrix View { get { return Matrix.LookAtLH(this.Eye, this.Target, this.Up); } }
private Matrix Proj { get { return Matrix.PerspectiveFovLH(this.Fov, this.Aspect, this.Near, this.Far); } }
public Matrix WorldViewProject
        {
            get
            {
                Matrix wvp = (this.View * this.Proj);
                wvp.Transpose();
                return wvp;
            }
        }

```

If you need anything else to solve this, just let me know and I'll manage to get it. Thank you!

# Answer
I made it!

It turns out the problem is not with the shader, but the `Draw` method. I missed setting the first parameter of draw in my code, which should be the primitives I am intending to draw.

Thanks to everyone in this discussion and that of the previous question, I will update the answer to the previous question in very short time.
> 1 votes

---
Tags: shaders, directx11, hlsl, windows, sharpdx
---