title: libgdx - Scalable UI without Scene2D

text:
# Question
Title: libgdx - Scalable UI without Scene2D
I currently have a fairly decent framework for a side-view strategy-ish game built around libgdx. While I may have reinvented the wheel a couple of times, I believe I've done the vast majority with tools already existing in libgdx parts properly: camera, viewport, sprites, etc.

One thing I've not used at all is Scene2D, as I've simply not had a need for it (yet). Drawing the sprites at their positions is more than enough. The terrain is procedurally generated pixel art that is drawn beforehand.

Now I've come to the point where I need to implement some fairly basic UI-systems. Nothing out of the ordinary: A few buttons to click, and an area with additional info.

I haven't decided entirely on which approach to use when implementing the UI, but in the meantime I'm going with a fairly simple approach: When everything else is drawn, I reset the projectionmatrix so that everything drawn after that never moves with the world:

```
    Matrix4 uiMatrix = camera.combined.cpy();
    uiMatrix.setToOrtho2D(0,0,viewport.getWorldWidth(), viewport.getWorldHeight());
    batch.setProjectionMatrix(uiMatrix);
    // Then draw the UI

```

This works fine, except when the aspect ratio changes and/or when the window resizes. Therefore I would like to find a more scalable way.

Is Scene2D the way to go? It currently looks like the only reasonable way of getting an UI that works well with resizing the screen and panning around.

The info I find on how to implement it either assumes a complete rewrite to use actors instead of sprites, or doesn't scale well at all.

# Answer
> 0 votes
Take a look at Viewports. In short, `Viewports` are handy little objects that handle the matrices for your player's view. Though they are integrated into `Scene2D`, you don't have to use `Scene2D` to use them. Before any render calls, just call

```
myViewport.apply();

```

Most `Viewports` take a `Camera` object in their constructor which you can use to easily pan the screen.

I do want to note however, that I love `Scene2D` and using it gives you a lot of helpful features. You may want to look into using `Scene2D` just for your UI layer.

You'll most likely need to use multiple viewports and cameras for your UI and game. Here's how you would do that

```
//Create the separate viewports and cameras
OrthographicCamera gameCamera = new OrthographicCamera();
FitViewport gameViewport = new FitViewport(800,600,gameCamera);

OrthographicCamera uiCamera = new OrthographicCamera();
FitViewport uiViewport = new FitViewport(800,600,uiCamera);

```

then in your render code

```
gameViewport.apply();
//render game
uiViewport.apply();
//render ui

```

To handle screen resizing, you need to tell your viewports about the new screen size whenever it is resized

```
public void resize(int width, int height) {
    gameViewport.update(width, height);
    uiViewport.update(width, height);
}

```

---
Tags: java, libgdx, ui-design
---


title: Unity2D: Frost Effect Animation

text:
# Question
Title: Unity2D: Frost Effect Animation
I want to know is there a way of using `Mathf.SmoothStep` to control the float of a variable? You see I downloaded this package ("Frost Effect by Steven Craeynest") on Unity Asset Store and created a `IEnumerator OnTriggerEnter2D` (in a new script) to control the effect once my player hits an orb, making it slow down but now I want to add an animation. Rather than having it appear of the screen and then disappearing, I want to make the frost effect slowly come in, kinda like controlling the frost amount in the inspector. It is possible, because I tried doing it like this:

(This is attached to orb)

```
// Use this for initialization
void Start () {
}

IEnumerator OnTriggerEnter2D(Collider2D other)
{
    if (other.tag == "Player") {
        //frost.enabled = true;
        GameObject.Find("Main Camera").GetComponent<FrostEffect>().enabled = true;
        FrostEffect.valToBeLerped = Mathf.SmoothStep(0, 1f, FrostEffect.FrostAmount);
        yield return new WaitForSeconds (1.01f);
        FrostEffect.valToBeLerped = Mathf.SmoothStep(1, 0, FrostEffect.FrostAmount);
        GameObject.Find("Main Camera").GetComponent<FrostEffect>().enabled = false;
    }
}

```

But it's still appearing automatically rather than it slowly coming in like an animation. Anyway this is the frost effect script I downloaded from the assets store:

(Attach to the main camera)

```
public static float FrostAmount = 0.3f; //0-1 (0=minimum Frost, 1=maximum frost)
public static float valToBeLerped = 0;
public float EdgeSharpness = 1; //>=1
public float minFrost = 0; //0-1
public float maxFrost = 1; //0-1
public float seethroughness = 0.2f; //blends between 2 ways of applying the frost effect: 0=normal blend mode, 1="overlay" blend mode
public float distortion = 0.1f; //how much the original image is distorted through the frost (value depends on normal map)
public Texture2D Frost; //RGBA
public Texture2D FrostNormals; //normalmap
public Shader Shader; //ImageBlendEffect.shader

private Material material;

private void Awake()
{
    material = new Material(Shader);
    material.SetTexture("_BlendTex", Frost);
    material.SetTexture("_BumpMap", FrostNormals);
}

private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
    if (!Application.isPlaying)
    {
        material.SetTexture("_BlendTex", Frost);
        material.SetTexture("_BumpMap", FrostNormals);
        EdgeSharpness = Mathf.Max(1, EdgeSharpness);
    }
    material.SetFloat("_BlendAmount", Mathf.Clamp01(Mathf.Clamp01(FrostAmount) * (maxFrost - minFrost) + minFrost));
    material.SetFloat("_EdgeSharpness", EdgeSharpness);
    material.SetFloat("_SeeThroughness", seethroughness);
    material.SetFloat("_Distortion", distortion);
    ///Debug.Log("_Distortion: "+ distortion);

    Graphics.Blit(source, destination, material);
}

```

Thank you. :)

**Second Edit** Because so far this is what I have:

```
        GameObject.Find("Main Camera").GetComponent<FrostEffect>().enabled = true;
        float duration = 2f;
        DOTween.To(x => FrostEffect.FrostAmount = x, 0.0f, 0.34f, duration)
            .OnComplete(()=>DOTween.To(x => FrostEffect.FrostAmount = x, 0.34f, 0.0f, duration));
        Time.timeScale = 0.05f;
        yield return new WaitForSeconds (6.5f);
        Time.timeScale = 1f;

```

# Answer
> 1 votes
Hey sorry was sleeping this side of the world :)

Setting delay can be as simple as adding `.SetDelay(float delay);`

I imagine setting the timescale would be similar, as far as I know DoTween uses it's own timescale (`DOTween.timeScale`) so you could modify it to affect game timescale too.

You should spend some time in the DoTween docs and explore what's possible!

http://dotween.demigiant.com/documentation.php

But I've done it for you here this time, should work fine, hopefully haha.

```
float duration = 1.01f;
float delayBeforeUnfreeze = 3.0f;
float previousTimeScale = Time.timeScale;

//Slow timescale
Time.timeScale = 0.01f;

//Freeze time effect
DOTween.To(x =>FrostEffect.FrostAmount = x, 0.0f, 1.0f, duration)
  .OnComplete(()=>
  {
    //Unfreeze tween effect
    DOTween.To(x => FrostEffect.FrostAmount = x, 1.0f, 0.0f, duration)
      .SetDelay(delayBeforeUnfreeze);

    //Set timescale back to previous.
    Time.timeScale = previousTimeScale;
  });

```

There are cleaner ways to do this via coroutine but that's another story, which I'm sure you will explore later on :)

Best of luck in your journey!

*To mods: Sorry for another answer but it wouldn't fit in another comment. Let me know if theres anything else I can do to keep the answer clean. Cheers!*

# Answer
> 1 votes
```
FrostEffect.valToBeLerped = Mathf.SmoothStep(0, 1f, FrostEffect.FrostAmount);
yield return new WaitForSeconds (1.01f);
FrostEffect.valToBeLerped = Mathf.SmoothStep(1, 0, FrostEffect.FrostAmount);

```

This will not start an animation of any sort unfortunately, what's happening here is you're setting the exact value to be FrostAmount, waiting 1.01 seconds and then setting it again. I understand what you're trying to do but it requires some sort of Tweening library.

Try DoTween for your project, it is a truly exceptional package in my opinion: http://dotween.demigiant.com/download.php

Once that's done, replace the above lines with:

```
float duration = 1.01f;
DOTween.To(x => FrostEffect.FrostAmount = x, 0.0f, 1.0f, duration)
.OnComplete(()=>DOTween.To(x => FrostEffect.FrostAmount = x, 1.0f, 0.0f, duration));

```

Make sure to include the using header for DoTween:

```
using DG.Tweening;

```

I haven't checked the above code 100% but I'll have another look when I get back from work. Best of luck!

---
Tags: unity
---


title: Unity Remote screen resolution

text:
# Question
Title: Unity Remote screen resolution
I just made a game using Unity. However, when I tested the game on unity remote, the resolution or graphic of the game was really low compared to the actual game. Would this change when I deploy the game or do I have to tweak the settings? If I have to tweak the setting, can you guys tell me what to tweak.

# Answer
> 4 votes
According this answer from Unity Answers Forum, Unity Remote doesn't really play game on device, rather than it stream video output to device from editor.

The final presentation of Your game will be different than what You get in editor/Unity Remote.

Additionaly You can always check how will Your game will presents under different resoultions while developing, just by switching resolutions in game view.

IMHO, it's always best to test on few real devices with game installed from apk file when targeting for Android.

---
Tags: unity, android, resolution
---


# Question
Title: Trouble loading sprite from spritesheet with Phaser
I am working on re-creating a breakout clone to help me learn Phaser (following the overall design of jsbreakouts.org). Anyway, I have the start screen set up. From the start screen, I can transition to the game state without any problems. In my game state, I can load the background and the paddle without issues. The paddle responds to mouse input as it is supposed to.

But the ball does not load for some reason. The ball is coming from a spritesheet. Each ball in the sheet is 16x16 and there are 5 of them. I can't even get one of them to load, let alone animate them.

The balls spritesheet is in the same directory as the paddle. I have looked at other code online and as far as I can tell, I'm doing it right. Yet, it is not working.

What am I doing wrong?

Here's my game state code:

```
var paddle;
var ball;

var Game = {

preload : function() {
        // Here we load all the needed resources for the level.
        game.load.image('background', './assets/bg_prerendered.png');
        game.load.image('paddle',     './assets/paddle2.png');
        game.load.spritesheet('ballsheet', './assets/balls.png', 16, 16, 5);
        game.load.spritesheet('tiles', './assets/tile_spritesheet.png', 32, 16);
    },

create : function() {
    //enable physics
    game.physics.startSystem(Phaser.Physics.ARCADE);
    game.physics.arcade.checkCollision.down = false;

    //add the background
    background = game.add.sprite(0, 0, 'background');

    //add score text placeholder
    game.add.text(50, 390, "Lives: 3    Score: 700   Level: 1", { font: "12px sans-serif", fill: "#000000"});

    //add the paddle and set it up
    paddle = game.add.sprite(136, 384, 'paddle');

    //set the anchor to be the lower center of the paddle
    paddle.anchor.set(0.5,1);

    //enable paddle physics
    game.physics.enable(paddle, Phaser.Physics.Arcade);
    paddle.body.immovable = true;
    paddle.body.collideWorldBounds = true;

    ball = game.add.sprite(100,100, 'ballsheet');
    ball.frame = 0;
    //ball.animations.add('rotate',[0,1,2,3,4], 10, true);
    //game.physics.enable(ball, Phaser.Physics.Arcade);
    //ball.body.collideWorldBounds = true;
    //ball.play('rotate');

},
    update: function() {
        paddle.x = game.input.x;

    },
};

```

# Answer
> 1 votes
You need to set the anchor for the ball sprite the same as you did for the paddle, e.g.: `ball.anchor.set(0.5, 1.0);`

Also when adding the ball animations, the 2nd parameter should generate the complete frame names of each individual sprite, not just their # on the spritesheet. Phaser's documentation can be a bit fuzzy on just how to do this properly but you can use this code for guidance:

```
ball.animations.add("rotate", Phaser.Animation.generateFrameNames("ball_seq_", 0, 4, ".png", 0), 10, false, false);

```

The call to generateFrameNames is meant to assemble the file path for every sprite in the sequence from the start value (0) up to (4) followed by the file extention and how many zeros you want to pad the file path with (e.g. a pad of 3 would look like "ball\_seq\_0004.png").

The rest of the ball.animations.add () parameters are the frame rate (e.g.: 10fps) and 2 boolean values describing whether to loop the animation continuously. See here in the Phaser docs for more on the parameters for the animations.add method.

---
Tags: javascript, sprites, spritesheet, phaser
---


# Question
Title: How to kill a fired bullet sprite after certain amount of time in Phaser?
The bullet should be killed after it was shot from the player, and after a certain amount of time.

```
function create() {
    bullets = game.add.group();
    bullets.enableBody = true;
    bullets.physicsBodyType = Phaser.Physics.ARCADE;
    game.physics.enable(bullets, Phaser.Physics.ARCADE);
    timer = game.time.create(false);

    for (var i = 0; i < 100; i++) {
        bullet = bullets.create(0, 0, 'bullet');
        bullet.exists = false;
        bullet.visible = false;
        bullet.checkWorldBounds = true;
        bullet.events.onOutOfBounds.add(resetBullet, this);
    }
}

function update() {
    if (game.input.activePointer.isDown) {
        fire();
    }
}

function fire() {
    if (game.time.now > bulletTime) {
        bullet = bullets.getFirstExists(false);

        if (bullet) {
            bullet.reset(player.x, player.y);
            game.physics.arcade.moveToPointer(bullet, 300);
            bulletTime = game.time.now + 150;
            timer.add(1000, resetBullet, this);
            timer.start();
        }
    }
}

function resetBullet(bullet) {
    bullet.kill();
}

```

As you can see I already tried adding a timer into the `fire` function which calls the `resetBullet` function after one second. But my game crashes one second after `fire()` was called:

```
Uncaught TypeError: Cannot read property 'kill' of undefined

```

Does anyone know how to achieve the kill of the sprite?

# Answer
> 2 votes
I found out that objects can be killed with `body.lifespan`

Adding the line `bullet.lifespan = 1000;` in my `fire()` function fixed the problem

# Answer
> 0 votes
You can also call `bullet.destroy()` after a set amount of time as well.

---
Tags: javascript, game-loop, timer, phaser
---


# Question
Title: How to read monogame log files on android device
I am working on a monogame android project where I want to log some data. First try was something like this:

```
Log.Info(tag, message);

```

This works great when debugging in Visual Studio via the Android Device Logging-Window. But when I run the app on my mobile android device I have no idea how to view the log entries. As far as I know the logging happens in the so called CatLog, which can be viewed with some Apps. But unfortunately these apps need root access, which I think cannot be given to them on a "normal" android device.

Is there any way to either view the Logfile on my Android device or is there a better way of adding logging to my project?

Thanks in advance Nick

# Answer
I'm not familiar with monogame but LogCat can be viewed not only by using apps but also from command line tool adb(android debug bridge).

Assuming that you had to install android sdk You should be able to do this steps in your command line/shell:

1. Change dir to /YOUR\_SDK\_PATH/platform-tools eg. `cd ~/android-sdk/platform-tools`
2. Run adb with logcat option `adb logcat` for windows `adb.exe logcat`

The problematic outcome is that it prints whole LogCat output so you may want to filter it for your needs.

For more information about filtering check this SO thread.

**Info:** You may need to enable option 'USB Debugging' in 'Developers Options' on your device.

If command line related solutions aren't for you try to install Android Studio. It has 'Android Monitor' panel that does the most work and allows you to define own filters using GUI.

**Extra:** After some googling I've found tool called mLogcat which maybe be useful for You as alternative to Android Studio.
> 1 votes

---
Tags: android, monogame
---


title: Creating terrain

text:
# Question
Title: Creating terrain
I am working on creating a 2D side-scrolling car game. My problem is generating the terrain. When creating the terrain, I need to have it random and recorded, so I can create collisions at a later point. I can't use any external assets.

```
var keys = [];

var keyPressed = function() {
    keys[keyCode] = true;
};

var keyReleased = function() {
    keys[keyCode] = false;
};

var car = function(locatio, accel, image, dragcoof) {
    this.loc = locatio;
    this.accel = accel;
    this.image = image;
    this.volocity = new PVector(0, 0);
    this.acceleration = new PVector(0, 0);
    this.drag = new PVector(0, 0);
    this.dragcoof = new PVector(dragcoof.x, dragcoof.y);
};

car.prototype.draw = function() {
    if (this.image === null) {
        fill(255, 0, 0);
        rect(this.loc.x, this.loc.y, 50, 10);
    }
    else {
        this.image(this.loc.x, this.loc.y);
    }
};

car.prototype.update = function() {
    if (this.volocity.x >= 10) {
        this.volocity.x = 9.99;
    }

    if (this.volocity.x <= 0.1) {
        this.volocity.x = 0;
    }

    this.volocity.add(this.acceleration);
    this.loc.add(this.volocity);
    this.drag = PVector.mult(this.volocity, this.dragcoof);
    this.volocity.sub(this.drag);

    if (this.loc.x >= 600) {
        this.loc.x = 0;
    }
};

car.prototype.move = function(keycodeLeft, keycodeRight) {
    if (keys[RIGHT] && this.volocity.x < 10) {
        this.acceleration.add(this.accel.x,0);
    }

    if (!keys[RIGHT] && !keys[LEFT]) {
        this.acceleration.set(0, 0);
    }

    if (keys[LEFT] && this.volocity.x >= 0.5) {
        this.acceleration.set(-0.1, 0);
    }
};

var a = new car(new PVector(10, 200), new PVector(0.01,0), null, new PVector(0.022, 0));

var draw = function() {
    background(255, 255, 255);
    a.draw();
    a.update();
    a.move();
    text(a.acceleration + "\n" + a.volocity+"\n"+a.drag, 25, 25);
};

```

# Answer
Generally for generating terrain(either 2D or 3D), you need a base "random" factor, something you can base your terrain of. There are several nice algorithms and tutorials for generating those, and with some arithmetic calculations you can easily customize them for you own needs. Some examples are the Perlin noise or the Simplex noise. Do a bit of research on those, experiment with parameters and you're good to go.
> 1 votes

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


# Question
Title: Hierachy organisational methodology in Unity
I'm just getting into Unity, so I do not know if my system of organisation will have any negative consequences.

I intend to store my project files and assets under an assets directory, then into scripts and such, as is commonplace. For the hierarchy I intend to have a top level empty object titled something like "Hierarchy", under which all objects will be children.

I am also thinking that I will further subdivide into logical and physical objects, putting objects that do not have components on them but have a physical space in the game (not including transforms) under the former, and anything with a physical presence under the latter (lights, player etc).

The main reason is so that I know where to look, based on functionality. I can also use alt-click to close all objects at once. I find this helpful for navigating the hierarchy.

Is this a bad plan?

# Answer
If you're talking about the scene hierarchy, it's not a good idea. The scene hierarchy is meant to be designed in such a way that all objects that need to move together/are attached to each other should be placed as children of a parent game object.

For example, in a car object, the body and wheels are placed together under a parent "Car" object, since they generally move and rotate together in a real-life car. This set up allows the wheels to move and rotate in the same direction as the body when they aren't steered, but when they are an offset rotation is applied. The wheel still moves and rotates with the body, but it has some offset local rotation/position which is also added to it's world position and rotation.

You can also use parent and child Transforms to group objects for easy debugging like @SanSolo said, but only if you are sure that you won't change the Transform of the parent container in *any* way.
> 1 votes

# Answer
The hierarchy, as Evil Tak said, is meant to give a semantic organization to your gameobjects such as the car of the other answer is all contained in a root node. Also you have to consider that transofmrations applied to a gameObject reflects to children too.

That is a fact. But then you have to consider that heirarchy is fully customizable so if for your needs is best to separate physical from logical entities, do it, just keep in mind the above.

Keep in mind also just one thing, the execution order and rendering order. Without personalization, scripts are executed from top to bottom in the hierarchy (all `Awake()` functions in order top-bottom; all `Start()` functions in order top-bottom, and so on) and so rendering is performed hierarchy wise in the same order.

If you have this clear in mind you can organise your hierarchy as you prefere.
> 1 votes

# Answer
Hierarchy doesn't really matter in the "Hierarchy panel". Hierarchy is useful if you have a bunch of game objects,it would be wise to organize them. However there is a game object where hierarchy does matter. It's the `Canvas` game object. The `Canvas` is used to display pictures,text,buttons,etc. It's used for HUDs,menus and similar. If you place 2 images in it,the last image will be the one who will overlay all the previous images,in this case the previous image. And that's why hierarchy matters here.
> -1 votes

---
Tags: unity
---


# Question
Title: How can one create "network effects" in a game as it scales?
Is it possible to create network effects in a game? How?

Usually a product with network effects present gets more valuable to a user as more people have the same product. Examples can be Skype or Facebook. The more people are using them, the more it's important to a single user.

Does it even matter in games?

# Answer
> 2 votes
Network effect can most definitely exist in games. I can personally think of some clear examples, and they all have one thing in common: **Networking**.

## MMORPGS

MMORPGS have become a lot more common, of late. It seems like everyone is trying to jump on the bandwagon. If you are unfamiliar with the acronym, it stands for Massive Multiplayer Online Role Playing Games. The thing is, while a game can *boast* being *massive multiplayer*, it needs *people* to make this claim a reality. These games also commonly have a greater focus on the *role* part of the RPG genre; While most general RPG titles have some allowance for the user to play the game 'solo', many MMORPG titles restrict the player in such ways that many activities simply can not be engage successfully without the cooperation of a group of players.

World of Warcraft is always a good case example for MMORPGs. In the earlier days of "WoW", you would sit around the nearest main towns, and yell out to the many other users playing that you were "LF2M HEALZ DPS DM" (or "Looking for two more, one healer and one damage dealer, to run Dead Mines). Veterans will snicker at the trivial nature of running the Dead Mines in early WoW (given that at the time it was a very low level dungeon), but the point remains; Core damage dealers were generally not very good at absorbing damage, and relied on "tank" characters who were better at distracting enemys and absorbing damage than actually dealing damage. Tanks would not last indefinitely, and relied on a healer to keep them alive, to in turn keep the heat off the damage dealers.

Given that the cooperation of multiple users was required to engage many of the activities, it is not surprising that the reliability of being able to quickly get a group together and run a dungeon was somewhat based off how many users were actively playing on that server at the same time. The amount of users become a point of advertisement.

The above picture is my old box from roughly 2006. You would be naive to think the big gold "Over 5 million online!" was not placed with extreme deliberation; In reality, it is clear that someone has stuck this sticker on *after* the original box was printed. Almost as if they wanted to make sure the players new that *even more* people were playing World of Warcraft.

## Online Competitive Games

The thing about any game that basis most of its game-play off online competition is that much of the game becomes unplayable if there isn't actually anyone to compete against. Games like League of Legends are only playable in online competition - without other users playing the game, online, you would not be able to play it. These games rely on networking, in that sense. Nobody wants to look at menu screen all day.

Other games may provide a single player experience, but are arguably much more substantial due to their online counterpart. Star Wars Battlefront, Call of Duty and Battlefield come to mind. While these games offer varying degrees of single player campaigns, it is the online multiplayer that has players racking up hours on hours. These days, such games matchmaking the player into giant battles featuring dozens of other players, a system that basis its productivity off of how many users are currently online.

These games become more valuable as more people play them, because it provides greater reliability of being able to find a game. Likewise, as a games user-base dwindles, the hardcore fans that stuck around start to worry that the dwindling number of users might lead to server closures, as the game company behind the IP move their investments towards more popular titles.

## Augmented Reality games

Yes, I'm talking about Pokemon Go. Games like this may increase in value as you notice more people playing, as it simply becomes more socially acceptable.

In the early days, I personally gave a couple of AR games a go. Along with killing my battery, I often stopped playing because they made me feel weird. The people around me would be oblivious to the type of game I was playing, and it would not be uncommon to get curious stares, as onlookers tried to work out why I was waving my phone around like mad.

These days, I go to my local park, and there's always a group of people walking around playing Pokemon Go. Seeing so many other people play it, its value increases, for me. I see that it is socially more acceptable, and am less concerned about pulling out my own phone and trying to catch a Pikachu.

It is worth addressing that while I do not have any social phobias, I do know people that do. This sort of "oh hey, other people are doing it, too! I'm allowed to" feeling goes a long way for someone who feels social anxiety, or otherwise doesn't want to 'stand out'.

## Any game you want support for after 10+ years

Ultimately, I personally see increased value in any game I enjoy, as more user take it on - even if I never engage with *any* of these users *whatsoever*. Ultimately, I know that if many *other* users are playing the game, the developer is more likely to support the game for longer, and release more content for it.

A good example is Diablo 2. One of my all time personal favorites, and made that much more valuable to me by the consistency in *others* playing it. In part due to the fact that 16 years down the track the game is still very popular, Blizzard have recently released a new patch for it. As a result, I can now replay my old favorite on my brand new Windows 10 laptop. It's value absolutely *skyrockets*, in part due to personal opinion and nostalgia.

## There's always a downside

There is always a downside to increased 'traffic', if you will. In my personal experience, these downsides take a while longer to reveal themselves, and are far rarer.

* **Congestion**: If too many people play a game, it can mean longer waiting times. I use to leave my game queued for half an hour or so to log in to World of Warcraft, because too many players played on the same server, and it was always full. Too long experiencing such wait could easily devalue the experience, and in turn, the game. Blizzard quickly countered these issues with new servers, and free character transfers to pull your high-level characters off the highly-congested server.
* **Law of Averages**: If you put too many people in a room together, your pretty much guaranteed to not like a group of them. It is not uncommon for me to hear that particular users have stopped playing a game, because the *community* was off-putting. A good example might be Battlefield, where it is not uncommon for users to be hesitant to join team chat. Another good example that springs to mind is the early days of RuneScape 2. RuneScape is the first MMORPG I was ever able to play, due to having incredibly low system requirements, and offering a freemium model to play. Unfortunately, the users that made up the free-access servers were often very immature, especially as more mature users jumped to the subscription model and could access members-only servers. Ultimately, too many users *can* kill the mood of a game, if their all a bunch of 15 year olds fighting over one block of iron.

# Answer
> 2 votes
@Gnemlock said most of it already.

There's another concept I'd like to point you at: The business model used by Rayark Games in their game Cytus.

I am not sure if it really fits the term "network" effect, since it technically it rewards a big 1:N connection instead of N! 1:1 connections, but since the benefit scales with the userbase and there is a user-to-user connection of some sort, I'd like to mention it.

Cytus is a rythm Game for touchscreen devices. They made it possible to play completely free with a 30 second timer before every round, which can be removed by a small one-time purchase of 1,50. Content is released in chapters, sets of 10 songs. The first few were free, later chapters cost 4,99 each.

So far so f2p, but here is the genius part:

For every 100.000 purchases, another chapter was made available for free. So you invest 1,50 and get multiple sets of content each worth three times as much, great deal for the player. Every player that gets hooked (and that's likely) is a potential buyer of yet unlocked chapters, great deal for Rayark Games. By now the counter has exceeded a million purchases and is still climbing. Purchased chapters are not factored in, that's just the number of monetized game downloads.

Interestingly, while this system ultimately aims to increase the userbase and make money, it doesn't feel that way. Instead, it feels benevolent. And who can honestly say that it isn't?

It also manages to foster a sense of community without enforcing or even enabling in-game contact to other players (although players do communicate through other networks like google play games, youtube, twitter or facebook, also the wiki).
Even if you just play the game, you know that there are hundreds of thousands of players who unlocked all those chapters for you. And when a new chapter is unlocked, you know that you helped accomplish that. Some might underestimate the impact of a mostly psychological connection, but that's what really counts.

Another aspect is that there is no diminishing effect for the userbase if players don't keep playing regularly, the worst that could happen is less new content. There's also no chance for conflict within the game.
What we have here is a system that - at least for the player - scales up *but not down* with the userbase.

For reference, www.rayark.com/g/cytus

---
Tags: game-design, business-model
---


# Question
Title: Can we measure the distance between and AR marker and camera?
I'm in the middle of developing a game in Augmented Reality using Unity and ARToolkit plugin. I wanted to measure the approximate distance between the AR marker and the position of camera. Can anyone help me with a solution to this problem? Thanks in advance.

# Answer
if AR marker have Transform Component attached, then you can measure the distance.

```
  public Transform ARMarker;   //attach ar marker gameObject here
  float dist;
  void calDistance(){
  dist=Vector3.Distance(ARMarker.position,transform.position);
  Debug.Log("Distance is:"+dist);
  }

```

Attach this script to Camera.
> 0 votes

---
Tags: unity, camera, augmented-reality
---


title: Bounding box messed up for .fbx models

text:
# Question
Title: Bounding box messed up for .fbx models
I am trying to make bounding boxes for my models. My code works fine if the model is imported as a COLLADA (.dae) file. When I try to import a model that has .fbx extension, my bounding box messes up. Here's a screenshot (purple cylinder is imported as .dae and the red jet is imported as .fbx):

As you can see the box is perfect for the cylinder but for the jet it's massive. It extends beyond the playing field. I don't understand why this is happening. Here's my code for generating a bounding box:

```
class MeshModel
    {
        public List<BoundingBox> boundingBoxes;

        public MeshModel(Model model)
        {
            // Set up model data
            boundingBoxes = new List<BoundingBox>();

            Matrix[] transforms = new Matrix[model.Bones.Count];
            model.CopyAbsoluteBoneTransformsTo(transforms);

            foreach (ModelMesh mesh in model.Meshes)
            {
                Matrix meshTransform = transforms[mesh.ParentBone.Index];
                boundingBoxes.Add(BuildBoundingBox(mesh, meshTransform));
            }
        }

        private BoundingBox BuildBoundingBox(ModelMesh mesh, Matrix meshTransform)
        {
            // Create initial variables to hold min and max xyz values for the mesh
            Vector3 meshMax = new Vector3(float.MinValue);
            Vector3 meshMin = new Vector3(float.MaxValue);

            foreach (ModelMeshPart part in mesh.MeshParts)
            {
                // The stride is how big, in bytes, one vertex is in the vertex buffer
                // We have to use this as we do not know the make up of the vertex
                int stride = part.VertexBuffer.VertexDeclaration.VertexStride;

                VertexPositionTexture[] vertexData = new VertexPositionTexture[part.NumVertices];
                part.VertexBuffer.GetData(part.VertexOffset * stride, vertexData, 0, part.NumVertices, stride);

                // Find minimum and maximum xyz values for this mesh part
                Vector3 vertPosition = new Vector3();

                for (int i = 0; i < vertexData.Length; i++)
                {
                    vertPosition = vertexData[i].Position;

                    // update our values from this vertex
                    meshMin = Vector3.Min(meshMin, vertPosition);
                    meshMax = Vector3.Max(meshMax, vertPosition);
                }
            }

            // transform by mesh bone matrix
            meshMin = Vector3.Transform(meshMin, meshTransform);
            meshMax = Vector3.Transform(meshMax, meshTransform);

            // Create the bounding box
            BoundingBox box = new BoundingBox(meshMin, meshMax);
            return box;
        }

        public void Draw(BasicEffect boxEffect, Matrix View, Matrix Projection, Matrix World, GraphicsDevice device)
        {
            // Initialize an array of indices for the box. 12 lines require 24 indices
            short[] bBoxIndices = {
                0, 1, 1, 2, 2, 3, 3, 0, // Front edges
                4, 5, 5, 6, 6, 7, 7, 4, // Back edges
                0, 4, 1, 5, 2, 6, 3, 7 // Side edges connecting front and back
            };

            // Use inside a drawing loop
            foreach (BoundingBox box in boundingBoxes)
            {
                Vector3[] corners = box.GetCorners();
                VertexPositionColor[] primitiveList = new VertexPositionColor[corners.Length];

                // Assign the 8 box vertices
                for (int i = 0; i < corners.Length; i++)
                {
                    primitiveList[i] = new VertexPositionColor(corners[i], Color.White);
                }

                boxEffect.World = World;
                boxEffect.View = View;
                boxEffect.Projection = Projection;
                boxEffect.TextureEnabled = false;

                // Draw the box with a LineList
                foreach (EffectPass pass in boxEffect.CurrentTechnique.Passes)
                {
                    pass.Apply();
                    device.DrawUserIndexedPrimitives(PrimitiveType.LineList, primitiveList, 0, 8, bBoxIndices, 0, 12);
                }
            }
        }
    }

```

I draw my models like this:

```
public void Draw(GraphicsDevice graphicsDevice)
{
    foreach (ModelMesh mesh in model.Meshes)
    {
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.View = camera.View;
            effect.World = worldMatrix;
            effect.Projection = camera.Projection;
            effect.EnableDefaultLighting();

            mesh.Draw();

            // Debug: Draw bounding boxes
            modelBox.Draw(effect, camera.View, camera.Projection, effect.World, graphicsDevice);
        }
    }
}

```

Any help would be appreciated!

# Answer
> 1 votes
When you draw the mesh you only supply your worldMatrix, it looks OK because the plane is most likely one mesh or all parts have similar transforms.

First get the Matrix array with all transforms from your model:

```
Matrix[] transforms = new Matrix[model.Bones.Count];
model.CopyAbsoluteBoneTransformsTo(transforms);

```

Then in your inner loop, when setting the World matrix, you also multiply with the mesh transform. The mesh local transform (rotation, scale of the current part):

```
effect.World = transforms[mesh.ParentBone.Index] * worldMatrix;

```

# Answer
> 0 votes
I see you created a `Matrix[]` called `transforms` for use while building your boxes (`BuildBoundinBox(ModelMeshesh, Matrix[])`). That Matrix\[\] modifies the position, rotation, scale of the boxes. This causes the size of the boxes to be what they are when drawn.

You need to create a similar Matrix\[\] to for the model itself that get applied to the effect.World when drawing the model so it gets the same changes that the boxes have.

My guess is that .dae bakes the transforms into the output of the model application exporter. .fbx doesn't. It's actually more flexible that way.

---
Tags: xna, monogame, models, bounding-boxes
---


title: Loading maps on HTML5 Games

text:
# Question
Title: Loading maps on HTML5 Games
I was wondering if my 2D Pixel Art platformer HTML5 game(a lot of words there..) should have loading screens for maps.

My game has different maps and I don't know if a loading screen should be implemented to transition to those maps, they are already loaded when the page finished loading right?

The framework I am using is Phaserjs.

*Thanks for your help :')*

# Answer
On some consoles, it is required to have a loading screen if it takes more than x seconds to load, and the loading screen has to have a 'loading' animation if it takes more than x+y seconds to load.

This is on console, where you know the device and can be quite certain that the time it takes to load a part of the game will be the same for all users.

Since this is in JavaScript, you don't have such control, so the time to load a part of the game will vary a lot from a user to another.

If you're not able to stream content while the user is playing the game, and your game is made in such a way that the player could be waiting for a part of it to load, it would be advisable to plan to use a loading screen.
> 1 votes

# Answer
That depends on how you load your maps and how long it takes. Depending on how it is programmed, a Javascript application can either start downloading a resource on pageload or when it actually needs it. Both can optionally be hidden behind a loading screen with a bit of effort.

When your application has a lot of resources to load (or is on a slow server), there are two possible ways it could react (again, depending on how you programmed it). It either shows a blank page or it looks really broken because it tries its best to run even though not all images are loaded yet. The first makes the user think your game doesn't work at all and the second makes them think it's super glitchy. Both will result in the user closing the browser tab before they got a real impression of your game.

But when you add a preloader which immediately shows a nicely designed loading bar, it gives the player the immediate impression "Yes, this game is working fine, just keep the tab open for a moment. I promise you won't regret it". And when the loading is finished you can be sure that all resources are there and the player experiences your game as you designed it.

When you add preloaders, there are two options: Either one in the beginning which loads all resources at once or one before every level. The first option means it will take longer until the title screen appears. Some players will get impatient and close the browser tab. But on the other hand, loading during the game can also be an annoying interruption. This is a decision you have to make on a case-by-case basis.

By the way, when you want to test how your game would load with a bad internet connection, I recommend the question "How can I simulate a bad internet connection for testing purposes?" (the question applies to stand-alone games, but the answers can be applied when you install a local webserver to put your game on).
> 1 votes

---
Tags: 2d, javascript, html5, phaser, pixel-art
---


title: Switching camera position on collision

text:
# Question
Title: Switching camera position on collision
I'm trying to switch the camera to another object on collision.

This is what I've tried to do:

```
    public Camera switchCamera1;
public GameObject player2;

private Vector3 offset;

void Start () {
    offset = transform.position - player2.transform.position;
}

void OnCollisionEnter (Collision col) {
    if (col.gameObject.name == "triggerCube") {
        //SceneManager.LoadScene ("test2");
        Debug.Log ("HIT SOMETHING");
        setWinText ();

        switchCamera1.transform.position = player2.transform.position + offset;

    }
}

```

However it simply doesn't work. I've set my camera to switchCamera1, I've set the other object to player2. The script is assigned to the collider object.

# Answer
Are you perhaps forgetting to reparent the camera so it follows player2?

```
switchCamera1.transform.SetParent(player2.transform);

```

Not sure this is what you're after but perhaps a better explanation of the effect you're trying to achieve is required.

Hope that helps! :)
> 1 votes

# Answer
Well, I'd suggest to use `Smooth Follow` script rather than making it child (if it is not particularly required).

* You can grab the `Camera Follow` code from this answer
* Attach it to your camera (please un-child your camera first)
* Drop the initial target in Target in just attached `Smooth Follow` script.
* Access this script in your current script in which you want to play with it. (By `public SmoothFollow smoothFollw;` or by `FindObjectOfType< SmoothFollow>()` whatever you want)
* Now change the target on collision by changing its `target` transform value.

Hope this helps.
> 1 votes

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


# Question
Title: How remove banner adView from a Screen in libgdx?
I have an AdMob banner in the game. But I need this banner not to be shown in `Screen_1` and when user enter `Screen_2` I need to show the banner. When I call `AdView.gone()` it dissapears from screen but coordinates becomes wrong and touch position doesn't match with coordinates. How can I properly remove `AdView`.

# Answer
First, in the class with the Activity, create a new `Handler` instance and override the method `handleMessage(Message msg)`. Then, create two constants

```
private final int SHOW_ADS = 1;
private  final int HIDE_ADS = 0;

```

Pretty much, the `Message` has a variable called `what` with some information that you'll use for a switch line. This switch line will have to test if, what was passed in, is telling the method to display or hide the ad. It should look like this:

```
handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                switch (msg.what){
                    case SHOW_ADS:
                        adView.setVisibility(View.VISIBLE);
                        break;
                    case (HIDE_ADS):
                        adView.setVisibility(View.GONE);
                        break;
                }
            }
        };

```

After you did that, you'll need to be able to call this from outside the main thread. The best way to call this method from outside the main thread is like this:

First, create a new interface with the method `showAds(boolean show)` and **make `AndroidLauncher` implement it (or whatever your Main Activity is called)**

```
public interface AdHandler{
    public void showAds(boolean show);
}

```

The overridden method in the class with the Main Activity (most likely AndroidLauncher) has to just relay the message to the `handleMessage()` method because you can't call the method directly:

```
@Override
    public void showAds(boolean show) {
        handler.sendEmptyMessage(show ? SHOW_ADS : HIDE_ADS);
    }

```

The final step is to pass the class itself into your main Gdx class

```
initializeForView(new MyGdxGame(this), config);

```

From there you can use the `showAds()` method whenever and wherever you want (you'll have to pass the variable around yourself).
> 1 votes

---
Tags: android, libgdx
---


# Question
Title: Deleting faces or triangles from an object by material on load scene
I have objects that have multiple materials imported from blender as a .FBX.

I'd like to find the objects where materials are used, and destroy faces when a certain material name is used ("!null", in my case).

I know this is not the correct way to work. *Normally* I should delete the faces in Blender, but as I am building quite complex geometry using faces that I need in Blender but don't want the Unity engine to render, it seems the only way to go.

I tried "cutout", but although they are invisible, it does not make any difference in rendering times.

Is this at all possible? If it is, how do I do it?

# Answer
I have had this question answered on Unity Answers, though I needed to modify the original code to work properly.

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

/// <summary>
/// Class: ClearNull Derived from MonoBehaviour
///
/// Purpose: Debugging of objects not yet completely finished in blender.
///          This class will destroy any face marked with !NULL to avoid  them to render
///          Restore the Original settings once destroyed
///
/// Parameters DestroyString by default "!NULL" *** Warning this is case insensitive***
///
/// Notes: The code was inspired by Bunny83 in thread
///        http://answers.unity3d.com/questions/1232964/
///
///        This code should only be use for debugging and not for final products
///
///        It will not work on children viewed from the parent.
///
/// Further develepment ideas:
///         - Make scene wide check on load to save and destroy
///               every !NULLL face in the scene.
///         - Make it so it supports children
///
/// Copyright: Code originally by Bunny83 adapted by Napivo on 2016/08/23
///            free for anyone... Hope It help you as much as it does me
/// </summary>
public class ClearNull : MonoBehaviour
{
    List<Material> oMats; // used to store the orriginal Materials
    List<int[]> oTris;    // used to store the orriginal triangles
    public string DestroyString = "!NULL";

    void Start()
    {
        //get the renderer
        MeshRenderer renderer = GetComponent<MeshRenderer>();
        //GetComponent the mesh
        Mesh mesh = GetComponent<MeshFilter>().sharedMesh;
        //Get the list of materials and save them for restore
        oMats = new List<Material>(renderer.sharedMaterials);
        List<Material> mats = new List<Material>(renderer.sharedMaterials);
        //Create a list to store the old and new triangles
        oTris = new List<int[]>();
        List<int[]> tris = new List<int[]>();

        int i = 0; // stores current number minus the one(s) lost
        int j = 0; // stores the current number

        while (i < mats.Count)
        {
            if (mats[i].name.ToUpper() == DestroyString.ToUpper())
            {
                Tris.Add(mesh.GetTriangles(j));  //Make a backup
                mats.Remove(mats[i]);
                j++;
            }
            else
            {
                oTris.Add(mesh.GetTriangles(j)); //Make a backup
                tris.Add(mesh.GetTriangles(j));  //Copy to new triangles
                j++;
                i++;
            }
        }

        mesh.subMeshCount = tris.Count;         //Set new triangle count

        for (int n = 0; n < tris.Count; n++)    //Set new triangles without those lost
        {
            mesh.SetTriangles(tris[n], n);
        }

        renderer.sharedMaterials = mats.ToArray();  //Set the material without those lost
    }

    /// <summary>
    /// Purpose: Reset the object to the stati it was before
    /// </summary>
    void OnDestroy()
    {
        MeshRenderer renderer = GetComponent<MeshRenderer>();
        Mesh mesh = GetComponent<MeshFilter>().sharedMesh;

        mesh.subMeshCount = oTris.Count;
        for (int n = 0; n < oTris.Count; n++)
        {
            mesh.SetTriangles(oTris[n], n);
        }

        renderer.sharedMaterials = oMats.ToArray();
    }
}

```
> 0 votes

---
Tags: unity, blender
---


# Question
Title: Why are character-classes used in game design?
We had a long discussion in my company about character-classes. We are building a skill based game where you will eventually need to select 8 to enter a battle. I am a fan of classless systems, I have always felt that they are created to extend your gameplay hours in a fake way.

We reached a few conclusions:

* **Classes are there to prevent "best build" scenario where everyone plays with optimal** (Personally I feel that this is a weak case, You should be able to design a system where there is no win combination without classes)
* **Classes create variety by offering different style of play** (I agree with this but if you have the freedom to combine different skills you can actually create your own class)
* **Classes make choosing style of play easier to players. Most of the times players play the same type of character in different games. (Damage Dealer, Healer, Thief/Assassin etc.)** (For me this makes most sense from all the arguments from above, but why force people to only part of the skills when you could offer them as templates)

Why are character-classes used in game design? Do you agree with the above points? Yes or no, why do you think like that?

# Answer
I agree with your points however I would like to expand them a little further:

1. **Classes gives player identity.** He can talk and think about himself as *a* rogue for example.
2. **Classes can give player the feeling of belonging somewhere/membership.** Expanded previous point - if he is a paladin, he belongs to some order of NPC paladins and also other players (often with similar personality and values) this goes as far as creating community around a class.
3. **Classes make the game balance much easier.** Effectively your first point but from other point of view.
4. **Classes are part of the RPG tradition and help players get used to your game.** Effectively your 3rd point but again, other perspective - it can help you get more players as they will feel like "at home".
5. **Classes can help skillful play.** If somebody charges at you with no-class system you have no idea what is his skill set and what to expect, in classes system you can sooner identify threats if you memorize other classes skill sets and thus know how to counter it.
6. **Classes don't prevent you from creating shared skill pool.** It just does not work the other way around - if you don't have class system you can hardly introduce new class while if you do have class system, you can introduce skills potentially available to everyone.

From what you read, the mixed system could be the best way to go...but there is always a downfall. Mixed systems are currently modern but also there is not a great(=legendary) game with such system yet ...as far as I know(correct me if I am wrong). There might be some hidden difficulties with semi-open systems.
> 35 votes

# Answer
**Making sense of the world**

Part of the reason for this is about world-building and storytelling, which may not seem relevant in the genre or type of game you are writing but if you aren't giving your users any kind of story or world hooks, they will be creating their own to make sense of what they are playing.

If you look at it in that respect, then a character-class system represents the development of an individual in a set of skills. Let us imagine that we had a game in which you could be a musician, a high jumper or a barista. If we just listed all their skills in one place, you might have something like:

* jumping quite high
* making an americano
* playing a C major scale
* jumping higher than average
* making a good latte
* playing the melody from 'Ode To Joy'
* jumping hella high
* being able to carry six mochas
* playing 'Moonlight Sonata'

Now that set of skills falls naturally into three categories and it would make sense to someone playing it that you need to progress through `jumping quite high` and `jumping higher than average` to master `jumping hella high`. If you were to progress from `playing a C major scale` through `making a good latte` to `jumping hella high` that doesn't really make sense and your players would probably find it a little weird.

In this respect character classes map to the real world fact that you get better at what you practice, so higher level skills are available to you as you master their predecessors. That helps the world of the game feel sensible.

This type of increasing specialisation is treated in a lot of games as a *skill tree* rather than a *character class* and this makes sense but is basically the same thing.

If you have a skill tree that goes through `playing a C major scale` to `playing Moonlight Sonata` that is no different than levelling up in the *Musician* class really. Of course there is the option to learn other base skills, so you could learn to `jump quite high` and `make an americano` and become a high-jumping barista but in many class based systems - particularly "proper" RPGs - this available through multi-classing.

The other way that skills and powers are often represented is through equipment- do you need to have a character class at all if you just let the user choose equipment that gives them the skills they want?

Again I would argue that if you have the best Wizard Hat and the best Wizard Staff to gain all the Wizard skills, you're effectively playing a Wizard class. The terminology changes but the theoretical mechanic is broadly similar.

**Classes enable progression and specialisation**

Now the big advantage of a class/skill-tree progression system is that you can make the pinnacle of any given class much more awesome *because* a player has to specialise to get there. A game where everyone is an average generalist is typically a lot less compelling than one where they are diverse and can do a selection of awesome things. Rather than favouring micro-optimisations, this can lend itself to more interesting play and open the door to having different strategies for different situations. If you watch people playing one of the DOTA family of games, the diversity of strategies needed for different heroes is what makes it interesting and keeps people coming back.

If I am playing a game I would rather be able to do a few powerful and awesome things and have to think about how and when to use them. If the game is team based it allows strategy to take place on the level of the whole team rather than just individual players, which is often a lot more compelling.

The sense of advancement and growing in power is easier to conceptualise in a class/skills-tree type framework and that is part of what makes games that offer this type of progression work and part of the reason that it is such a common pattern.
> 29 votes

# Answer
### *You* can balance a classless system, but your *players* probably can't.

In addition to the other answers above, I'd suggest that giving people classes is a way to ensure that players don't sabotage themselves with a poor build.

Common things people do that produces a sub-optimal build include:

* **Choosing non-synergistic abilities.** People who do this may be competent in their chosen abilities, but lack the "whole is greater than the sum of the parts" that other builds exhibit.
* **Dabbling in everything.** People who do this often end up underpowered in the end game because they miss out on the ultimate abilities.
* **Choosing abilities for the short term.** People who do this pick the most powerful ability in their current situation. This gives them a temporary bump in power, but causes them to fail in the long run because they don't have the final build in mind.

If a person has a build they feel they like, but it ends up being underpowered in your game, it can make them feel like the game is unfair or too hard.

Ways to avoid these problems include adding a "retraining" feature or something like that. With this feature, players are free to experiment with builds and don't get trapped in a poor build.
> 19 votes

# Answer
For the same reason that you can buy a jar of curry sauce.

There are some who make a meal from scratch. They know the exact ratios of spices they like and adjust them and choose meat/vegetables that they like and that combine well with their sauce.

Some people don't have time for that. They know that they want to cook a satay, so they buy a jar of sauce, add meat/vegetables, and then maybe tinker with 1 or two small ingredients? Add some more salt, chili and garlic as desired.

Some people don't even have time for that. They buy microwave meals and click 'go'.

None of these people are wrong in their attitude to curry. Why would they be wrong in their attitude to games?

You like to make your characters from the raw ingredients, others like to take prebuilt bases and customise, and still others just want to get into it straight away.
> 15 votes

# Answer
Actually the character classes usually play many roles in the game design and the game itself.

To begin with the class system will make the character attributes (as in everything from skill, durability...) much easier to design, you can make up a class background, a story which is usually a base concept for all ideas. So from the development point of view it is easier to create a class system then classless.

As from the player perspective the classes again give some simplicity to the game as the player usually has very little choice in putting some points to modify its attributes. Another very usual thing is that when playing online with other players you can easily see what class did your opponent choose and you simply know how to act against it.

Now just considering this two points you should ask yourself what kind of users are you targeting, the truly committed ones or those hit-and-run users...

So about the classless system.. There is no reason to think that making such system will increase the chance of having an ultimate win combination. I can think of no "pure class" game where certain classes werent overpowerd. In each scenario there is always a way to exploit some ability(s) which lead to an overabuse and destroy the game balance you so much struggled to maintain. The classless games it would seem are extremely rear and adding a PvP filter to that list we can be pretty close to number of zero. You might not agree with this but actually ANY character progression that limits some ability is pretty much the same, even creating a large skill tree where you would need to choose a skill in order to get to a new skill will limit you in getting all the skills you qualify for since you have no more "skill points". This system is far from limited to the RPG, even strategies in PvP where you select a race present the same limitations as selecting a character class. So somewhat most interesting classless games to talk about would be Morrowind, Fallout 1 and 2: These are all non PvP and in each of them pretty much every combination is a winning combination. Mostly if you have any experience with any of these games you would know that you will restart the game with many characters taking "better" paths. To look at somewhat different game you can look at Eve online which has an extremely complex gameplay of waring with spaceships. Even if the game does not include classes it does limit you to fly a single ship. This single ship has specific capabilities, limits and benefits which again presents the same system as having a class, the only difference is you have an "undo" button as you can dock and switch the ship you are piloting.

So my point is this "classes" thing is just one of the many ways where you fragment the player progression into some subsystems and many of such exist. Why this is very important (even more in online games) is so you as developer can easily maintain the ballance over time after the game has been published. There is no way you can expect to create a game which was perfect ballance between different character paths. And if you create some classes and see that a specific class is underpowered at some stage you can simply modify few attributes to make it stronger and ballance is restored and more importantly it is restored without effecting any other characters. On the other hand if for instance you had just one large skill tree and you change a certain skill to help one kind of players it will also affect (some) other players.

I am not saying that classless system is impossible or even wrong, it is simply hard to maintain. And more people play the game, more talking on the web, more exploits will come to life. If you wish to be able to correct those exploits you best be ready for it, one way or another. Some do it with classes, some with ships, the items... still the reason is all the same.
> 9 votes

# Answer
Before I get into "why they are used in games at all", I'm going to mention "why they're useful now". Character classes are *iconic*, which helps with continuity and **innate understanding**. If I know that I like playing a mage in other games, when I pick up yours I can just say "I'm playing a mage", and I'll already understand that I'll be using different spells, and that there will be some form of limited magic resource I will use for my spells. Because I already know these things implicitly, I can more easily just pick up your game and play it.

In the olden days of game design, classes encouraged players to have **unique experiences** with gameplay, since I am limited in what my choices are, and frequently have my starting parameters change. If my character starts out with lots of HP and defense, I'll be more likely to hop into the middle of battle and destroy your enemies, while if I only have a small amount of HP but higher magic, I'll be more likely to stand at a distance and tactically pick off your enemies. Similarly, having multiple classes can lead players to explore avenues of gameplay they might not have considered before. Having played the game before, they might have only thought they could bash enemies with weapons until they died. However, playing with the rogue, they might realize they can sneak around enemies, or other such possibilities. Each class encourages a different way of interacting with game mechanics, and because of that tends to offer more replay value.

As you noted, this can similarly be accomplished without character classes. However, when you limit them to specific classes, you challenge them to succeed within those limitations, instead of simply allowing them to create something that is "best for them" and have them get bored because the game isn't tailored to challenge their particular build.
> 7 votes

# Answer
## Identity

When you have a class based system the player can quickly identify a protayal of a character **type**.

This is done through conscious/unconscious memory of earlier experiences in games this would make the player able to make a better decision.

They all enable different play styles, and gamers do identify themselves with their play styles as well as their way of playing their games.

## Progression of character

The progression of character is limited to their skillset. This is done because a "true" class-less system could also well be skill-less, telling or making the player need to explore different areas within the game.

A good example of this is GTA which progresses base skills like Driving, Shooting, and Flying based upon the progression of these skills, and the individual players willing to explore diversity in the gameplay.

## Template not a cookie cutter

What is good to remember when creating a class based system, is to remember that a class is not a straightforward path, you can allow the gameplay and the traits of the class to contribute to the gameplay.

Even making the game unbalanced can increase the player retention - and the interest value of your game
> 6 votes

# Answer
In addition to the points made above, there's also the fact that nearly all RPGs take place in societies that have experienced the Agricultural Revolution. This might not seem important, but one of the effects of the Agricultural Revolution was specialization of labor. For this reason, specialization forms a major part of settings and of how characters interact with the world regardless of how the system is set up.

In Skyrim, for example, I did each of the specializations separately, having different careers as a mage, a thief, and an Imperial agent, devoting myself to each campaign for a while before moving on to the next. Even though Skyrim has a classless system, it still ended up having class-specific campaigns, because Mage, Thief, and Fighter are more than just classes, they're also careers.

Skyrim felt a little unnatural, though, because people in one campaign had no conception of the progress I'd made in other campaigns, which led to numerous NPCs accidentally mouthing off to the Archmage and then being turned into bunnies for their impertinence. The game could have adjusted for this by creating variables like `$progress_in_mage_campaign`, and maybe another variable to track overall progress, like `$badass_quotient`, but these would be essentially the same as a very basic class system.
> 4 votes

# Answer
> Why are character-classes used in game design?

They are a realistic representation of peoples' skill sets.

The classic example is Dungeons and Dragons, which came originally from a medieval table top combat game by Dave Arneson called Blackmoor. Blackmoor came from a wargaming background and so was intended to be a (perhaps loose) simulation of medieval combat. And it would be unrealistic to have infantry performing the same as knights, for instance.

> I am fan of classless systems \[...\] if you have the freedom to combine different skills you can actually create your own class\[.\]

True, and players are likely going to build a set of skills that suit their purposes best.

If you want to be a strong combat player and rush right in to things, you will pick skills that allow you to do this (a "fighter" or "tank" class perhaps?). If you are someone who wants to primarily kill opponents from a distance and sneak around, you will pick skills that allow you to do this (an "assassin" class perhaps?). That the game designer picks the groups or the player does hardly matters if the game designer does it in an interesting and logical way.

> Do you agree with the above points? Yes or no, why do you think like that?

* **"Classes are there to prevent "best build" scenario\[s\] where everyone plays with optimal \[characters\]"**

Anyone who designs games will want to limit a player's ability to steamroll the game environment or other players. Everyone likes winning, but reasonable players won't mind reasonable limitations. Reasonable limitations are the job of the game designer, and are independent of classes (though not having an indestructible tank that can fell opponents in one strike, throw fireballs that kill everything and dodge/hide perfectly could be consideration -- which might happen if you design poorly and allow players to "roll their own").
* **"Classes create variety by offering different style of play"**

True, but more importantly they can provide alternate combinations of skills that the players may not have considered.
* **Classes make choosing style of play easier to players. Most of the times players play the same time of character in different games.**

Yes and no. Some people have a preferred method of play, and classes certainly can make this play choice easier, but I would say that assuming that this is why designers include classes isn't true.

> For me \[easy play style choice\] makes most sense \[of\] all the arguments \[...\] above, but why force people to only part of the skills when you could offer them as templates\[?\]

I think templates are the best solution, but there are other things in game design to take in to consideration. The specifics are too numerous to list, but if game designers limit players to some specific skill sets, it is (should be) beneficial to game play overall.

Arguably the biggest reason to use classes is for multiplayer games where player's interact in groups. Not only does it simplify game design in certain critical aspects, it helps encourage rational groupings of abilities so that hopefully players aren't at a disadvantage because they picked all the same "cool" abilities and bypassed the "lame" (but from a game design point, still extremely necessary) skills.
> 3 votes

# Answer
You're focusing a lot on what the character CAN do as opposed to what the character CAN'T do. Having a player to choose a character class forces them to **make an interesting decision** by **restricting access to game elements**. And as famed game designer Mark Rosewater would say, *"Restrictions breed creativity."*

If you implement a classless system, you'll find it difficult to allow the players to pick and choose at will while at the same time restricting them enough that they can't just pick everything. Some classes shouldn't be able to heal. Other's should be able to but perhaps not as well, or perhaps not other players. Some classes shouldn't be able to do damage from a distance. Some classes should be at a disadvantage at close range.

I would also like to highlight a couple other issues identified in other answers, because they're very important:

* Kai: some playtypes are just incompatible/mutually exclusive.
* lpdechow/wondra: classes allow you to identify with your character
* glenatron: classes allow progression in a structured way
* wondra: classes are kind of an expectation of RPGs these days

Now this isn't to say that you can't pull off a classless system. Lots of games have done so, some of them even successfully. Runescape and Eve Online are two games I've played that I don't recall picking a class, although I would say there are orders of magnitude more games that managed to be successful with classes than without.
> 3 votes

# Answer
Although there are some very good explanations about the actual usefulness of character classes from a game design point of view, I wanted to act the actual historical original of character classes.

**Character classes were invented by role-playing games... as a mean to play roles.**

On this Wikipedia article we can see how D&D is referenced as the first game to introduce character classes. On the D&D page we get further detail.

> Many Dungeons & Dragons elements appear in hobbies of the mid-to-late 20th century. For example, **character-based role playing can be seen in** **improvisational theatre.**

So not only character classes are a great design device to, for instance, make sure that different players in a game session fulfill complementary roles (something hard to achieve if players were completely free to choose their abilities), but it is also itself in the very root of the concept of "role playing" a game.
> 2 votes

# Answer
From the players point of view classes can help with establishing a play-style and simplicity in resource management.

Imagine all the skills from World of Warcraft were available to all players. The skills in many classes use resources that collect in different ways (Mana, Rage, Concentration, Runes, Combo Points.) Providing all those resources to every player would be overwhelming - yet each resource style introduces a unique playstyle.

Maybe you can provide a single resource that combines all these features - but I think that'd be non-trivial - and easy to get broken and unbalanced.
> 2 votes

# Answer
The #1 reason I think of why you might choose to use multiple classes instead of a classless system is so that you can give the player the choice between multiple incompatible types of play. This is not possible with a classless system.

For example, in Diablo 3, mages use mana which steadily regenerates over time, and barbarians use fury which builds as they do damage and depletes over time. Obviously these two mechanics are completely incompatible, and apply for the entire duration of the game, and so players would have to be asked to choose between them before playing regardless. This choice is presented as a class choice.

As for other reasons why you might choose classes or class-less, it is really influenced by your design decisions, what makes sense based on the design decisions you've already made, what makes sense to your players, and what feels right for the game you are making. For the most part, there isn't a right or wrong in the classes versus class-less debate.
> 2 votes

# Answer
A rose, by any given name...

Many great answers above, but i feel there's one thing to add.

I firmly believe that a truly classless RPG system does and will not exist, ever.

You might not *predefine* classes, but every game that uses a variety of stats will always have certain classes emerge. You won't have wizards, but you'll have INT builds. You won't have Knights, but DEF builds. AGI builds replace your rogues, and DEX builds replace rangers.

Then you'll have a number of builds that focus on two stats, like STR-DEF instead of warriors or DEF-WIS which replace paladins. Maybe even INT-STR in place of sword mages if they have a good tank around.

Finally, there will be a number of noobjacks. Characters who didn't specialize, or specialized in a way that doesn't work.

See, in this so-called classless system, all the common classes will appear, even if you don't predefine them.

What's more important, and here is the interesting part:

**They always thrive**. Well, maybe with a few exceptions here and there, but most of the time they are superior.

Pretty much every stat constellation that is effective has been popularized by use as predefined class in a number of games. The classes you open up for the players are the ones that were either too ineffective or unattractive to be implemented as predefined class in other games.

So, not defining classes changes very little, compared to the alternative of creating a wide range of predefined classes. What it mostly does is cause inexperienced players to ruin their first characters and then, frustrated, use the optimum build from the forums. In the end, it might even stifle creativity more than it helps it. Because, let's be honest, the number of players that can build unusual but powerful classes like maybe a slow DEF-INT build with Auras and AOE, as well as the possible builds themselves are extremely limited. (P.S. DEF-INT usually doesn't work due to metal interference)

To summarize, classes are an emergent phenomenon inherent to any diverse skill system. They are less rules that dictate play, but more of a tradition created through evolution of play. They are common because they have repeatedly succeded over other classes/builds.
> 2 votes

# Answer
I've seen several mention "class identity", and would like to expand on that piece because I feel it is highly important.

In this instance, I will call it "flavor". Imagine the variations you can have on a simple "fireball" skill, but think more of the concept than the name - a flaming ball of fire.

* A wizard may conjure up one from the aether
* An explosives expert may shoot one from his gun
* A priest may create one from holy divine power
* A necromancer may create one from unholy hellish powers

Each of these could (arguably, *should*) look very different from each other. However, a classless system generally can not recognize what the player is trying to role-play, so it ends up with a generic fireball which simply cannot look as "cool" as it would on a specific character flavor. Keep in mind that visuals can be considered as part of the "reward" aspect of a game, so players are not receiving as strong of a reward for playing.

If you *did* include all these variations into the classless system, it becomes more apparent that they are all the same skill, because the player will compare them when making their choice and think, "what is the difference?". Players may feel cheated if they heard about the huge variety of skills but find that 20 of the skills are the same in 20 different flavors. You may now decide to make them slightly different in terms of stats and the players find that the wizard's fireball is slightly better for a specific situation - so even though you included one for the explosives expert, he takes the wizard one. Sure, they might be balanced just fine, but right now the explosives guy is facing a situation that favors the wizard one.

The next place that problem-solving may take you is the "skill-tree", even though some may not consider it quite as "open". Any character may be able to achieve any skill off the tree, but to get to the "most powerful" (and typically "most flavorful") skills, they have to go through the other similarly-themed skills. This is where Estharon's answer comes in play, and I will not repeat his well-made argument. (*TLDR; certain classes and ideas emerge regardless of whether they were purposely designed*) It is worth noting that without some type of "tree" to encourage specialization in certain areas, it becomes better to pick the best parts out of each area regardless of *why* your character would choose to be a vampire(regen) berserker(health-pool) spellcaster(spells) wearing heavy armor(armor) and mastering a sword finisher(in case of melee)

In the end, it is much easier for games which allow completely open skill selection to become bland and boring more quickly than games where the skill selection can be more focused, flavorful, and appeal to the role they were created for.
> 2 votes

# Answer
> **Classes create variety by offering different style of play** (I agree with this but if you have the freedom to combine different skills you can actually create your own class)

If you are free to choose your own skills then people will optimize a single attack combo and do nothing else. Why have 3 different attacks that do 5 damage each when I can have one attack that do 6 damage and use it over and over? That makes for very boring combat scenarios. In a class based system we can give the players a large variety of abilities with different properties, in a skill based system such builds would gimp the character. Thus the restriction that comes with having classes usually increase the amount of viable options a player has. The fix for that is to group abilities into a single skill or force prerequisites, like a "martial arts" skill gives you kicks, punches, grapples etc. But then we basically reinvented classes.

I do love skill based systems for survival games with permanent death though. There you try to build a character that don't die instead of a character that is the best at one thing. Another good case is in open world single player games with unrestricted amount of skills (Think Elder Scrolls:Oblivion). But in arcadey games where you never die I prefer classes all the way. In those games a skill based system almost always means that the rest of the game is very stale and boring. Sure it is fun to think of builds, but why play the game when the best part is optimizing spreadsheets?
> 1 votes

# Answer
**Why are character-classes used in game design?**

The main reason is because both the designers and players tend to expect them.

They do also help to simplify and make sense of choices, for players, designers, and AI. They can help organize and make sense of what would otherwise be potentially more complex.

Therefore it tends to end up being easier for many people, especially those used to classes, to design and play games with classes. In general, designing a class-based system and game can be much easier than trying to design a classless system that can support a wide spectrum of choices. That can depend a lot on the details of the game.

Also, classes can provide some useful things that classless systems may (but don't need to) leave out, mainly:

* Showing how some groups in society are typically trained with a set of abilities.
* Giving some emergent effects of having some combinations of abilities that work together to provide other abilities, such as some advanced abilities having prerequisites, or some tasks requiring a set of several skills.
* Showing how people who do the things needed to get some abilities, may tend to get other abilities or biases as a side-effect.
* Other social/cultural tendencies that tend to go together.

**Do you agree with the above points? Yes or no, why do you think like that?**

Well let's see:

```
**Classes are there to prevent "best build" scenario where everyone plays with optimal (Personally I feel that this is a weak case, You should be able to design a system where there is no win combination without classes)**

```

Some designers think that way. It's not necessary to think that way, however. You are correct that it is possible to design systems without classes that don't have a "best build". Also classes don't prevent "best build" thinking, and many class-based games end up with some classes relatively stronger than others.

```
**Classes create variety by offering different style of play (I agree with this but if you have the freedom to combine different skills you can actually create your own class)**

```

Classes don't create **actual** variety. Classes themselves actually reduce variety. But they can create perceived variety, at least between each other. Whether that's apparent in a game depends on the variety the game presents, and the way players approach it. If the game world consists of a limited set of things to do, then players might abuse a weak classless system to just pick the abilities that they read on the Internet will be best for that challenge. But if the game world has practical uses for a wide range of skills, and the system makes a wide range of combinations viable, then a classless system can end up providing more variety of viable character types. On the other hand, if a classless game doesn't provide any equivalent flavor to these varieties, it can feel less varied because it may seem like the player only has one choice (to be generic). To make a classless game give a matching impression of variety, one may need to design in the same sorts of things you find with classes, but without the limits. See the *Fable* series for one successful approach classless design with varied and distinct characters...

```
**Classes make choosing style of play easier to players. Most of the times players play the same type of character in different games. (Damage Dealer, Healer, Thief/Assassin etc.) (For me this makes most sense from all the arguments from above, but why force people to only part of the skills when you could offer them as templates)**

```

This seems sort of true, but as you point out, classes tend to be offered as exclusive choices with limitations. The same ease can be achieved without the limitations, by offering filters to find things, rather than restrictions.
> 1 votes

---
Tags: game-design
---


# Question
Title: Best way to blend colors in tile lighting? (XNA)
I have made a color, decent, recursive, fast tile lighting system in my game. It does everything I need except one thing: different colors are not blended at all:

Here is my color blend code:

```
return (new Color(
       (byte)MathHelper.Clamp(color.R / factor, 0, 255),
       (byte)MathHelper.Clamp(color.G / factor, 0, 255),
       (byte)MathHelper.Clamp(color.B / factor, 0, 255)));

```

As you can see it does not take the already in place color into account. `color` is the color of the previous light, which is weakened by the above code by `factor`. If I wanted to blend using the color already in place, I would use the variable `blend`.

Here is an example of a blend that I tried that failed, using `blend`:

```
return (new Color(
       (byte)MathHelper.Clamp(((color.R + blend.R) / 2) / factor, 0, 255),
       (byte)MathHelper.Clamp(((color.G + blend.G) / 2) / factor, 0, 255),
       (byte)MathHelper.Clamp(((color.B + blend.B) / 2) / factor, 0, 255)));

```

This color blend produces inaccurate and strange results. I need a blend that is accurate, like the first example, that blends the two colors together.

What is the best way to do this?

Update: I noticed that the reason simply adding them together and the above isn't working is because the light was spreading onto itself and blending with itself. I am going to try and prevent this by writing the light spread onto one array, a temporary one, not using `blend` at all, only using the first method. After each light is finished with the recursion process I'll draw it to the main one using a custom pixel shader that will blend the light together properly. This may or may not solve my problem.

# Answer
> 1 votes
Your own idea isn't that far off. However, you'll have to multiply the final color, not the light color alone:

```
final_light = (color1 * factor1 + color2 * factor2) / 2;

```

To elaborate a bit more, both `factor1` and `factor2` are based on the distance to the light sources, their range, etc. I just picked multiplication over division - in your example, you could just replace them with divisions, if your factor fits that operation.

Let's assume the distance to the first light is big enough for it to be dimmed to 50% and the distance to the second light would result in something like 75% (it's brighter/stronger or just closer):

```
final_light = (color1 * .5 + color2 * .75) / 2;

```

Or - using your way of doing the math, using division:

```
final_light = (color1 / 2 + color2 / 1.33) / 2;

```

# Answer
> 0 votes
Check out the Blend modes article on Wikipedia. It's really useful for these kind of things.

For example, the "screen" blend mode might work in your case. I.e. something like:

```
newColorR = 1 - (1 - color1R) * (1 - color2R)
newColorG = 1 - (1 - color1G) * (1 - color2G)
newColorB = 1 - (1 - color1B) * (1 - color2B)

```

where all the variables are in the range 0…1 (and `color*NX*` is the result after you've applied your `factor`).

---
Tags: xna, c#, lighting, color, blending
---


# Question
Title: How to prevent intepolated texture in fragment shader (Unity CG)
Think about minecraft - all the textures in minecraft have a very nice crisp pixelated look. Well, I'm trying to write a shader that will do this but it appears "sampler2d" returns some sort of interpolation between pixels of the underlying texture. I'm pretty new to shader writing and I'm not even sure if it can be done - but I'm hoping to get a nice crisp blow up of small textures rather than a blurry one like this:

If anyone knows a way to make a shader crisp rather than interpolated like this (using Unity), I'd be thrilled to know as this hitch is pretty detrimental to what I'm trying to accomplish...

Here's the subshader as it is right now (it's skipping all the light calculations and just outputting the sampler as I'm just trying to resolve the blurry texture sampling):

```
SubShader
{
    Pass
    {
        Tags { "LightMode" = "ForwardBase" }
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag

        //user
        uniform float _BlendVal;
        uniform sampler2D _DiffuseTex;
        uniform sampler2D _NMTex;
        uniform sampler2D _PixelMap;
        uniform float4 _DiffuseTex_SV;
        uniform float4 _SpecColor;
        uniform float _SpecIntensity;
        uniform float4 _RimColor;
        uniform float _RimIntensity;
        uniform float _RimCoefficient;

        //unity
        uniform float4 _LightColor0;

        struct vI
        {
            float4 pos : POSITION;
            float3 norm : NORMAL;
            float4 uv : TEXCOORD0;
        };

        struct vO
        {
            float4 pos : SV_POSITION;
            float4 uv : TEXCOORD0;
            float3 worldPos : TEXCOORD1;
            float3 normDir : TEXCOORD2;
        };

        vO vert(vI i)
        {
            vO o;

            o.uv = i.uv;
            o.worldPos = mul(_Object2World, i.pos).xyz;
            o.normDir = normalize(mul( float4(i.norm, 0.0), _World2Object).xyz);
            o.pos = mul(UNITY_MATRIX_MVP, i.pos);

            return o;
        }

        float4 frag(vO i) : COLOR
        {
            float3 lightDir;
            float3 viewDir = normalize( i.worldPos - _WorldSpaceCameraPos.xyz);
            float atten;
            float3 normDir = normalize(i.normDir);
            float4 RimLight;
            float4 DiffuseLight;
            float4 SpecularLight;
            float2 UVCoord = i.uv.xy;

            float4 test = tex2D(_PixelMap, UVCoord);

            //float4 Clrx0 = lerp(

            //Directional Light
            if(_WorldSpaceLightPos0.w == 0)
            {
                lightDir = normalize(_WorldSpaceLightPos0.xyz);
                atten = dot(lightDir, normDir);
            }
            //point light
            else
            {
                float3 dist = i.worldPos.xyz - _WorldSpaceLightPos0.xyz;
                lightDir = normalize(dist);
                atten = (1/length(dist))*(dot(lightDir, normDir));
            }

            DiffuseLight = atten * _LightColor0;
            SpecularLight = atten * _LightColor0 * _SpecColor * _SpecIntensity * pow(max(0.0,dot(reflect(lightDir, normDir), viewDir)), 1)*(1-tex2D(_DiffuseTex, i.uv.xy).w);
            RimLight = atten * _LightColor0 * _RimColor * _RimCoefficient* pow((1-saturate(dot(-viewDir, normDir))),_RimIntensity)*saturate(dot(lightDir, normDir));

            float4 totalLight = DiffuseLight + SpecularLight + RimLight;

            float4 fin = float4(UVCoord.xy,0,0);

            return test; ///Fin * totalLight;
        }

        ENDCG

```

# Answer
Set the `filterMode` of your textures to `FilterMode.Point`.

This will use nearest-neighbor interpolation, which will result in blocky rendering.

**Note:** Your `Texture2D` must also have a suitable `graphicsFormat`. The default is `R8G8B8A8_UNorm` which does not work with `filterMode` set to `FilterMode.Point` for some reason.

`TextureFormat.RGBA32` and other 32bit formats have worked for me. This is a read-only property, but you can set this format in the constructor of the Texture2D.
> 7 votes

# Answer
If you want to do this without a script, simply in the Project Window:

* Select your image in the Assets folder
* The Import Settings will now be visible in the Inspector Window
* In Import Settings, Find "Filter Mode" below the Advanced section
* Change Filter Mode to "Point (no filter)"
* Click "Apply"
> 2 votes

# Answer
My Stupid: apparently you can change the filtering mode of your textures by using: "(TextureName).filterMode = FilterMode.Point" and that will take care of this problem. Had nothing to do with the shader.
> 0 votes

---
Tags: unity, shaders, fragment-shader, cg
---