# Question
Title: Revenue model for an open-source multiplayer game
I've had an idea for a multiplayer game, and ideally, I'd absolutely love for it to be open source.

However, I also want to make a profit from it so I can make more games and maybe even have a dev team.

Is it possible to keep it open-source and generate revenue?

One idea I've had is to charge for online multiplayer services, but then users could easily circumvent that by patching in their own servers.

Is there a revenue model that can work for this kind of game project?

# Answer
How much do you believe in the open source idea? When you are not 100% committed to the free software philosophy, then there are some interesting variants:

1. Release the client under an open source license, but not the server. Any private servers will have to write their own server software. That software will always be behind yours feature-wise, so those who want to experience the newest features and content will have to play on the official server. And this can be a serious competitive advantage when you consider how impatient players can become when a new update to their favorite game is about to be released. (Possible risk: If a private server project manages to mobilize more development resources than you, then their server software might actually become better than your own and you will become the one percieved as lacking behind feature-wise)
2. Release server and client under copyleft, but not the assets. Most software licenses don't apply well to works of art anyway. If they want to run their own servers, they can use your software, but they will have to design their own content. So it will end up being a completely different game. In addition to making money with your game, you can make an additional income by offering paid consultant services to people who want to build their game using your technology.
3. Release the server and assets as open source, but not the client. Make money by selling the client and leave the expensive long-term commitment of hosting the servers and constantly releasing new content to the community. When it comes to picking a license for your server, I would suggest to take a look at the AGPL. It forces people to publish changes to the server software even when it only runs on their own servers. The normal GPL does not have that requirement. That way the community is legally obligated to collaborate instead of monopolizing any new features they come up with.

But if you decide to completely commit to the idea of FOSS and open source *everything*, then you have to live with the fact that anyone can compete with you when it comes to offering your own game. Everyone will be able to fork your project and offer a new server with your content plus their own. The upside is that if you pick a strong copyleft license you can also use *their* content.

Still, if you want to make a profit, you have to offer a better service for a competitive price. As the official project maintainer, you will have a certain amount of momentum which is hard to compete with:

* Only you have the reputation of being "the official" server.
* Because your server will be the only server for a while, it will be the first to form a large and stable player community. Multiplayer games live from their community, so already having the most players will be a competitive advantage.
* The player community of the official server is the community which is closest to the mainline developers. Their feedback is the feedback which is most visible and most important to you. Their problems, needs and suggestions are what guides your game's development. So players who want to have influence will want to play on the official server.
* You can set your server as the default in the official client, so all new players will start playing on your server.
* You can also register your game's name as a trademark. Most large open source projects do that. So if others want to fork it, they can do that, but they have to do so under a different name. That makes them hard to find.

But if you rely too much on your reputation and offer a bad service, then parts of the community *will* split off and set up their own servers.
> 11 votes

# Answer
*Disclaimer: I do find the other answer from Philipp to be excellent*

I approach this from a much different point of view. I'm going to focus on Magic The Gathering: Online (Mtgo)

Mtgo is something with many (illegal) free competitors. First, it is illegal not because of the client/server, but the assets that are under copyright and the game rules itself (I believe.) There are people who play these, but there's a big second point here:

Tournaments.

If you're hosting tournaments for this game and other companies can't because (while your source is free) the assets are copywritten, then you have the only legitimate tournament platform. Tournaments in Mtgo are *very* well designed and influence the buying of product in game by giving hints of the workings of the metagame. These results (or at least, some subset of them) offer prestige on their website by showing you're good at the game with your build, or that you've come up with a new deck that eats the current meta-game (gaining prestige for being the first to find a new approach.)

While you're probably not doing a trading card game; it could be tournaments allow you to gain good items or people in the Top-X% of players within the last Y-days have special blessings (not even items!) that give them bonuses, abilities, etc.. making content easier, or accessible, etc.

Anyone can print sheet after sheet of fake magic cards and attempt to play, and they do! But they also buy the real product, want to play in the real tournaments (that require the real product), and want the prestige in that community.

NOTE: And Mtgo is famously bad as a platform. Despite being a glitchy, laggy, terrible user interface, garbage fire of a piece of software; it has entire businesses built around it for the secondary market, continuous tournaments all-day every-day (that are utilized by hundreds of players), professional grinders constantly tweaking their builds via the tournaments and twitch streamers and blogs and My Oh My is that a lot of community, secondary businesses, etc for something that is a true masterpiece of mediocrity.
> 2 votes

---
Tags: multiplayer, open-source, monetization, planning, revenue
---


# Question
Title: How to make sure that a GameObject which gets a certain tag first, is allowed to do something first?
I have created a trigger zone to make sure that only one gameobject should pass through the trigger zone at once. Other gameobjects approaching the trigger zone are made to stop just outside the trigger zone if there is already a gameobject in the trigger zone. I could get things working up until here. Now, I need to make sure that the gameobject that got to the trigger zone first and started to wait first is allowed to pass first while others wait and then the second gameobject is allowed to pass and so on. I am stuck at this part.

# Answer
> 1 votes
Myself I'd be tempted to do it like this - toggling on & off the `isTrigger` state to make the collider a hard boundary when I want it to be, and passable other times.

`IgnoreCollision` lets the first object inside bypass the repulsion applied to other objects that try to intersect the collision zone. (Depending on your setup, you may need to ignore a few other items)

```
[RequireComponent(typeof(Collider))]
public class PassOneTrigger : MonoBehaviour {
    Collider _collider;

    void OnTriggerEnter(Collider other) {

        // Initialize a reference to our attached collider.
        if(_collider == null)
            _collider = GetComponent<Collider>();

        // If we manage to get two OnTriggerEnter messages in one frame,
        // ignore the second.
        if(_collider.isTrigger == false)
            return;

        // The object that just entered our trigger volume is allowed to stay.
        Physics.IgnoreCollision(collider, other, true);

        // Everything else should be repelled. Make the collider solid.
        collider.isTrigger = false;

        // Wait until the first object leaves, then switch back to trigger behaviour.
        StartCoroutine(WaitUntilClear(other));
    }

    IEnumerator WaitUntilClear(Collider other) {
        while(other != null) {
            // Wait a frame.
            yield return null;

            // Check whether both colliders contain the same point
            // ie. whether they still overlap.
            Vector3 point = _collider.ClosestPoint(other.bounds.center);
            if(point != other.ClosestPoint(point))
                break;
        }

        // Clear the ignore collision mark
        if(other != null)
            Physics.IgnoreCollision(_collider, other, false);

        // Return to trigger behaviour to let the next object in.
        _collider.isTrigger = true;
    }
}

```

Put this on an object with just one collider - the trigger you want to use as the outer boundary. If you need other triggers, attach them to separate objects to make sure their messages get to the right places and there are no crossed wires.

---
Tags: unity, gameobject
---


# Question
Title: How do I port a game which uses print-output to pygame font rendering with the least amount of work?
I've been working on a text based RPG. It's pretty simple, I'm not very experienced with Python, or any other language for that matter.

Edit: For context, I recently posted this question: Python 3: How can I make my Text-based game windowed?

Here's my game you'd like to check out the code: https://gist.github.com/NervousTumbleweed/f42f326982f2af1549b528ce0156e34a

I took a long hiatus from working on the game because I became caught up in work, and after coming back to it today I've decided that I want it to run in a window, not a console.

I want my end product to have background art and audio files. I have a pretty good idea of how to do this (I've done very simple versions of this in languages like MATLAB and Processing)

What I'm beginning to realize though, is that many of the functions that I use in my game don't just magically "transfer" over to pygame. I don't get to just create a window and *poof* my game is there.

For example, my print() commands all won't appear in a pygame window, correct? So I did some research and it seems like I could (maybe) create a font, and replace them with:

```
textsurface = myfont.render('Some Text', False, (0, 0, 0))
screen.blit(textsurface,(0,0))

```

But then I realized, how the hell do I get commands in there?

What about strings that are attributes of objects, will those display?

Is the way my game logic is written even compatible with this module?

So now I'm pretty bummed out and frazzled. I'm willing to restart from scratch I guess, but part of what motivated me to come back to the game was that I wanted to finish it.

Would the best move be to completely start over, or can a good amount of my code be salvaged and made compatible with displaying in a pygame window?

# Answer
This sounds like a pretty classic abstraction problem, general to all programming and not just games. I'll provide some explanation in terms of a text *game* though to suit your question.

Absolutely nothing in your game logic should *ever* draw directly to the screen. In a console app, this would include `print`. If you want text to show up, do *not* just blit it. Instead, put it into a text buffer somewhere, and then once per update/frame, blit that whole buffer.

Likewise for input. The code that processes and handles input has nothing to do with rendering or keystrokes. Abstract the two. The core window renderer can deal with make an input area and handling keystrokes and the like, and then just provides the final string to the gameplay code when the user hits Enter.

This is after all exactly what your terminal emulator is doing when it renders your text app. :)

At that point, if your game is staying purely text, you'll have a simple abstraction for "print some text to the screen" and another for "process input from the user."

Since printing to the screen is the same at the abstraction level whether you're printing to the console or whether you're eventually rendering it to the screen, you can just do a big search and replace on your code right now and replace every `print` with `my_print`, which in graphics mode would put its text into a buffer. Likewise, the input-handling code would just be a function like `handle_input(text)` and it wouldn't have any reason to care whether that `text` parameter came from stdin on the console or came from a custom GUI text input box.

The input one is probably the harder abstraction to retrofit depending on how you've gone about coding everything... but if you *did* sprinkle raw input code all over your game logic, then you've got a bigger problem than just moving to windowed input, unfortunately. This happens even in games that are purely graphical from the start; I've seen a lot of novice/student game developers read raw input in game code and then get really stuck when they need to add game controller or key remapping support. Input should be abstracted.

Really, everything reasonable should be abstracted. Game logic code in your case figures out *what* to print. Another module should figure out *how* to print it. This is all part of the Single Responsibility Principle - a piece of code should only be doing *one* thing. Code that takes input, figures out new game state, formats an output string, and draws that to the string is doing *four* things, which is three too many for any single self-contained piece of code.

(There's exemptions to those code design guidelines that arise when one is worrying about performance, but that's more if you're working on the next Battlefield or whatever and not a pygame project.)

The short version is that you *probably* don't need to rewrite anything, but you will need to apply some sensible abstractions to your existing code to get ready for the transition to graphics.
> 3 votes

---
Tags: gui, python, pygame, text, text-based
---


title: Extract formula from vector drawing

text:
# Question
Title: Extract formula from vector drawing
I am creating a game with HTML5 canvas for browser. I want to create animations with many shapes, which would be drawed with canvas, not from spritesheets.

The problem i face now is - to create formulas for so many shapes. I need them resizeable, also different width/height ratio. I was drawing chess pawn, but took 1 week to complete it right using arc's.

This is that pawn formula:

```
function pawn_shape(ctx, xx, yy, fill, stroke, grid_size) {
  var g = grid_size / 100;
  g *= 0.8;
  ctx.lineWidth = grid_size / 10;
  xx += g * 12;
  yy += g * 10;
  ctx.fillStyle = fill;
  ctx.strokeStyle = stroke;
  ctx.lineJoin = "miter";

  ctx.beginPath();

  var x = xx + 50 * g;
  var y = yy + 25 * g;
  var radius = 10 * g;
  var startAngle = 0.8 * Math.PI;
  var endAngle = 2.2 * Math.PI;

  ctx.arc(x, y, radius, startAngle, endAngle);

  x = xx + 55 * g;
  y = yy + 48 * g;
  radius = 15 * g;
  startAngle = 1.6 * Math.PI;
  endAngle = 2.4 * Math.PI;

  ctx.arc(x, y, radius, startAngle, endAngle);

  x = xx + 50 * g;
  y = yy + 97 * g;
  radius = 35 * g;
  startAngle = 1.7 * Math.PI;
  endAngle = 1.955 * Math.PI;

  ctx.arc(x, y, radius, startAngle, endAngle);

  x = xx + 30 * g;
  y = yy + 92 * g;

  ctx.lineTo(x, y);

  x = xx + 50 * g;
  y = yy + 98 * g;
  radius = 35 * g;
  startAngle = 3.055 * Math.PI;
  endAngle = 3.3 * Math.PI;

  ctx.arc(x, y, radius, startAngle, endAngle);

  x = xx + 45 * g;
  y = yy + 48 * g;
  radius = 15 * g;
  startAngle = 2.6 * Math.PI;
  endAngle = 3.4 * Math.PI;

  ctx.arc(x, y, radius, startAngle, endAngle);
  ctx.stroke();
  ctx.fill();
  ctx.closePath();
}

```

This is only 1 pawn. I need many more figures as configurable formulas. What would be the ways to get faster such formulas?

So far I am thinking about a new open source project, where people could draw shapes and these would be converted into such formulas. Or maybe even extract formulas from simple images, like programs do image to vector.

Another idea was to find out how does normal vectors work - what formulas they have. Maybe i could reuse and modify that? No idea, hoping to find answer here..

# Answer
> 2 votes
A number of vector drawing tools like Illustrator or Gimp will allow you to export to a format called SVG, or Scalable Vector Graphics.

This is a reasonably human-readable-ish XML specification for vector drawings, and many of the tags and primitives align closely with the drawing commands you use with a canvas.

So you could use the vector drawing tool as a WYSIWYG editor to make your shape, then export to SVG to get a list of drawing commands you can convert to code. Or you can render SVG directly in the browser, or draw the SVG into the canvas natively.

As an example, here's a quick rook I drafted up in Illustrator:

And here's the SVG description:

```
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 16.0.2, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     width="512px" height="512px" viewBox="0 0 512 512" enable-background="new 0 0 512 512" xml:space="preserve">
<g>
    <polygon fill="#231F20" points="307.862,18.222 307.862,65.191 287.312,65.191 287.312,18.222 215.881,18.222 215.881,65.191
        195.333,65.191 195.333,18.222 123.901,18.222 123.901,65.191 123.901,165 379.292,165 379.292,65.191 379.292,18.222   "/>
    <polygon fill="#231F20" points="342.601,388.099 164.998,388.099 197.61,165 313.102,165  "/>
    <rect x="128.304" y="388.099" fill="#231F20" width="255.392" height="64.582"/>
    <rect x="101.886" y="452.681" fill="#231F20" width="308.229" height="41.097"/>
    <circle fill="#231F20" cx="101.886" cy="473.23" r="20.548"/>
    <circle fill="#231F20" cx="410.115" cy="473.23" r="20.548"/>
    <circle fill="#231F20" cx="128.303" cy="408.648" r="20.548"/>
    <path fill="#231F20" d="M197.61,185.547c-11.349,0-20.547-9.201-20.547-20.547h20.547V185.547z"/>
    <path fill="#231F20" d="M333.649,165c0,11.347-9.199,20.547-20.548,20.547V165H333.649z"/>
    <circle fill="#231F20" cx="383.696" cy="408.648" r="20.547"/>
</g>
</svg>

```

---
Tags: vector, html-canvas
---


# Question
Title: Deactivate VS warning "Macro in skipped region"
Since the UE4 API relies heavily on macros outside of function bodies, the **IntelliSense** function (not the compiler!) of Visual Studio 2017 throws a lot of warnings with update 15.7, also visible in the scroll area.

Is there a possibility in the Visual Studio settings to deactivate such kind of warnings?

---

The option to deactivate IntelliSense

* Tools -\> Options -\> Text Editor -\> C/C++ -\> Advanced -\> Disable IntelliSense

will disable those warnings. However I don't want to renounce IntelliSense completely. Maybe Visual Studio offers more fine grain control over IntelliSense via its GUI or some settings file to disable only those macro warnings?

---

EDIT: The Visual Studio team recommends using a *.hint* file to register macros as workaround. However maintaining a separate macro list is not the way to go. You can also vote there that the VS Team works on that.

# Answer
> 1 votes
## A Workaround

Bit of a hacky workaround, but try this for now:

1. Add a **cpp.hint** to your root folder
2. Add the missing defines in here, for example, mine is:

```
#define UCLASS()
#define GENERATED_BODY()
#define UFUNCTION()

```
3. Restart visual studio and give it a few seconds. This should get rid of your green squiggles.
4. List item

---

## Microsoft's Hint File Docs

https://msdn.microsoft.com/en-us/library/dd997977.aspx

---

## Similar Question in Epic's Forums

https://answers.unrealengine.com/questions/787769/visual-studio-editor-saying-macro-in-skipped-regio.html

---
Tags: unreal-4, visual-studio
---


# Question
Title: HTML canvas how to create big game world and show only a part of it on canvas?
I originally created this question at stackoverflow but got no answers, so hopefully someone will be able to help me here.

So for the first time ever I'm making a html canvas game. So far I came up with a simple one dimensional array map and render it to the canvas using a sprite sheet. I also made sure I can move the sprite character on the screen.

Now that I have achieved that and I can move the character, I want to have a bigger array map and render only a smaller part of it on the canvas and as I'm moving my character, make the canvas move to the side and show the rest of the map.

I have read some stackoverflow questions related to that but I just can't understand the code and some math behind it. Even if I get it, the example codes are totally different than mine and I don't know how to implement that in my case.

So far I have 580x540 size canvas and such a map:

```
var mapArray = [
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 2, 2, 0],
  [0, 0, 1, 1, 1, 0, 0, 2, 0, 0],
  [0, 0, 1, 1, 1, 0, 0, 0, 0, 0],
  [0, 0, 0, 1, 1, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
  [0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ];

```

So first I want to understand, how can I make a big map and show only a portion of it on the canvas?

Now I'm looping through the whole array and drawing on every item in array. But if then how can I make sure that for example only half of the array is shown on the canvas ant the other half will be shown only on the scroll then character moves to the side?

Here is my code so far:

```
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

var mapArray = [
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 2, 2, 0],
  [0, 0, 1, 1, 1, 0, 0, 2, 0, 0],
  [0, 0, 1, 1, 1, 0, 0, 0, 0, 0],
  [0, 0, 0, 1, 1, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
  [0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
];

var StyleSheet = function(image, width, height) {
  this.image = image;
  this.width = width;
  this.height = height;

  this.draw = function(image, sx, sy, swidth, sheight, x, y, width, height) {
    context.drawImage(image, sx, sy, swidth, sheight, x, y, width, height);
  };
  this.drawimage = function(image, x, y, width, height) {
    context.drawImage(image, x, y, width, height);
  };
};

var viewport = {};
/* Initial Sprite Position */
viewport.width = canvas.width/2;
viewport.height = canvas.height/2;

var boatPosX = 230;
var boatPosY = 200;

function render(viewport) {

  requestAnimationFrame(render);

  for (let i = 0; i < mapArray.length; i++) {
    for (let j = 0; j < mapArray[i].length; j++) {
      if (mapArray[i][j] == 0) {
        this.sprite.draw(
          background,
          190,
          230,
          26,
          26,
          i * this.sprite.width,
          j * this.sprite.height,
          this.sprite.width,
          this.sprite.height
        );
      }
      if (mapArray[i][j] == 1) {
        this.sprite.draw(
          background,
          30,
          30,
          26,
          26,
          i * this.sprite.width,
          j * this.sprite.height,
          this.sprite.width,
          this.sprite.height
        );
      }
      if (mapArray[i][j] == 2) {
        this.sprite.draw(
          background,
          200,
          20,
          26,
          26,
          i * this.sprite.width,
          j * this.sprite.height,
          this.sprite.width,
          this.sprite.height
        );
      }
    }
  }
  this.ship.drawimage(boat, boatPosX, boatPosY, 50, 50);
};

function move(e) {
  if (e.keyCode == 39) {
    boatPosX += 2;
    console.log("right");
  }
  if (e.keyCode == 37) {
    boatPosX -= 2;
    console.log("left");
  }
}

document.onkeydown = move;

var background = new Image();
background.src = "ground.png";
var sprite = new StyleSheet(background, 36, 36);

var boat = new Image();
boat.src = "ship.png";
var ship = new StyleSheet(boat, 90, 100);

render();

```

# Answer
The easiest way to implement this is to loop through the map and draw the images (like you're doing), but offset everything by a certain value so that your main character will stay in the middle.

Your code for drawing the images is looking pretty good and it looks you want the ship to be in the center. To have the visible part of the screen follow the ship, you will need to calculate a display offset so that this ship will always be in the center of the screen.

Let's say the ship is stored in `x` and `y` and the screen size is stored in `width` and `height`. The offset would be want to put the ship at `(width/2, height/2)`, but it's being displayed at `(x, y)` so the offset would be `(width/2 - x, height/2 - y)`.

When I was making The World of Engineers, I had way too many images being displayed at once, and this was creating lots of lag (especially when I was trying to manage collision). My solution to this problem was to first check if a sprite will even show on the screen, then draw and update it. This way there aren't a bunch of sprites being drawn that have no effect on the game.

EDIT:

I forgot to explain this, but you would display everything the same, except the x and y values for each thing should be translated by (offsetX, offsetY).

For the player, you would draw it at (player.x + offsetX, player.y + offsetY), and for the background images, you would draw it at (image.x + offsetX, image.y + offsetY)
> 2 votes

# Answer
I recommend starting in 1 dimension to understand it. Let's say you have tiles that are 32 x 32 pixels, and you have a screen that's 320 x 32 (remember we're only taking about moving in 1 dimension, so only left and right in this example). And let's say you have 100 tiles across. So your world is 3200 x 32 pixels. So at any given moment, you'll be showing 1/10th of the world at 320 x 32.

To keep everything straight, you'll need to keep track of a pixel offset that tells you how far left or right you are in the world. It starts at 0. As the player moves to the right, it increases up to the maximum. In this case, that would be 3200 - 320 = 2880. When it's at 2880, it's showing the rightmost 320 pixels in your world.

To draw the portion of the world that's currently visible in your game, you need to calculate which tiles intersect the canvas. You can do that by doing an integer division of the offset by the tile width. So in this case, `startTileIndex = offset / 32`. That tells you which element in your array of tiles you need to start at. Since the canvas is 320 pixels wide, you'll need the next 10 tiles.

Now, that tells you which tile you need, but you also need to account for the fact that you may be offset by a partial tile. This value can be calculated by using the remainder of the offset divided by the tile width. In case it would be `tileOffset = pixelOffset % 32` where the `%` operator is modulus division.

So you can loop over the tiles to draw the visible ones and place them at the right position:

```
startTile = pixelOffset / tileWidth;
tileOffset = pixelOffset % tileWidth;
numTiles = (canvasWidth / tileWidth) + 1;
for (tileIndex = 0; tileIndex < numTiles; tileIndex++)
{
    map [ startTileIndex + tileIndex ].drawAt(-tileOffset, 0, tileWidth, tileHeight);
}

```

To do this in 2 dimensions, you need to keep track of both an `x` and `y` pixel offset, and you need to index into a 2D array for your map. You calculate the indexes and offsets in a similar manner for both the `x` and `y` dimensions.
> 1 votes

---
Tags: javascript, sprites, tilemap, maps, html-canvas
---


# Question
Title: Calling method with enum parameters from buttons
I have the following enum:

```
public enum WeaponType { Sword, Spear, Blunt, Ranged }

```

And I have the following public methods on a component:

```
public void MyMethod1(int myparam) { ... }
public void MyMethod2(WeaponType myparam) { ... }

```

Why is it that when I try to call my methods from a `Button` component, I can not see the ones that use enumerations as parameters?

# Answer
As Draco18s stated in comments, sadly, you can't.

Thankfully, if it helps, you can still just cast it back and forth:

```
EMyEnum myEmum = (EMyEnum)myInt;

// Or.
int myInt = (int)myEnum;

```
> 2 votes

---
Tags: unity
---


# Question
Title: Why the camera is not moving only up but also to the right?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraMove : MonoBehaviour
{

    public float smoothSpeed = 3f;

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }

    private void FixedUpdate()
    {
        transform.localPosition = Vector3.MoveTowards(transform.localPosition, new Vector3(0, 500, 0), smoothSpeed * Time.deltaTime);
    }
}

```

The script is attached to the Main Camera.

I want the camera to move directly up and a little bit also to the back. But the way it is now it's moving up but also to the right. Why it's moving also to the right ? I tried transform.localPosition and also only transform.position

# Answer
> 2 votes
Is your camera rotated to look at a specific angle maybe?

You are moving your camera based on its `localPosition` which means that it moves in its own object space. If the camera is rotated, it's Y axis is also rotated, so moving along the Y-axis will cause it to move diagonally most likely, depending on its rotation.

If you want to move your camera upwards in world space, replace

```
transform.localPosition = Vector3.MoveTowards(transform.localPosition, new Vector3(0, 500, 0), smoothSpeed * Time.deltaTime);

```

with

```
transform.position = Vector3.MoveTowards(transform.position, new Vector3(0, 500, 0), smoothSpeed * Time.deltaTime);

```

Now the object will move towards the +Y axis, based on your world.

# Answer
> 0 votes
The argument to `MoveTowards` is an absolute position, not a relative position.

You need to figure out where you want to move, then provide it as an argument.

```
public class CameraMove : MonoBehaviour
{
    public float smoothSpeed = 3f;
    public bool isInitialized = false;
    public Vector3 moveHere;

    private void FixedUpdate() {
        if (!isInitialized) {
            moveHere = transform.localPosition + new Vector3(0, 500, 0);
            isInitialized = true;
        }
        transform.localPosition = Vector3.MoveTowards(transform.localPosition, moveHere , smoothSpeed * Time.deltaTime);
    }
}

```

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


# Question
Title: What is "cold storage" in the context of larger MMOs?
What is a cold storage and what is it used for? I'm not sure if I should use cold storage in my game. I heard it can be used for chat logs, however I'd rather someone here answer all my questions.

# Answer
The "temperature" of different data storage layers usually refers to how fast that data can be accessed. Different levels of "temperature" from hottest to coldest are:

* In the gameserver's memory
* In an in-memory database or in-memory caching layer
* In a ssd-backed database
* In a hdd-backed database
* In a flatfile
* In a compressed flatfile
* Offsite Backup

Note that these are just examples. Not every game will use exactly these tiers of data storage. There might also be sub-layers like indexed vs. non-indexed and denormalized vs. normalized data structures.

When you have data which you need to access very frequently, like the data of characters which are currently on-line, you would want to move them to a "hotter" storage layer. When you have data which you need to access very rarely, you will want to move them to a "colder" layer.

Old chatlogs are data which you usually archive just in case you need to investigate some reported TOS violation at a later date. Most of your chatlogs won't be accessed ever, and in those cases where you do need to access them, performance isn't very important. So they are a usually a candidate for colder storage layers (if you want to archive them at all).
> 3 votes

---
Tags: mmo, terminology
---


# Question
Title: Tile Texture If Dimensions of Sprite Are Larger Than Texture
I have a sprite that acts as a wall in a game that I am building. I would like to have the brick texture repeat itself instead of stretch to fit the height of the screen. I tried:

```
Texture lSideTexture = new Texture(Gdx.files.internal("wall.png"));
lSideTexture.setWrap(Texture.TextureWrap.Repeat, Texture.TextureWrap.Repeat);

lSideSprite = new Sprite(lSideTexture);
lSideSprite.setPosition(-50, -100 * (height/width) / 2);
lSideSprite.setSize(5,100 * (height/width));

```

But I am still getting a texture that has been stretched to fit the dimensions rather than repeated.

Any ideas?

# Answer
> 1 votes
Late answer but this might help.

LibGDX needs you to set the wrap on the Texture like you did, but then, you need to make a TextureRegion of the wrapped Texture and call `setRegion(int x, int y, int width, int height)` on the created TextureRegion. Then it's the setRegion width and height parameters that will allow your sprite to draw the repeated texture with the specified width and height.

Something like this

```
Texture textureToRepeat = new Texture(Gdx.files.internal(YOURTEXTUREPATH);
textureToRepeat.setWrap(TextureWrap.Repeat, TextureWrap.Repeat);

TextureRegion repeatedTexture = new TextureRegion(textureToReapeat);
repeatedTexture.setRegion(0, 0, WIDTHAFTERREPEAT, HEIGHTAFTERREPEAT);

Sprite sprite = new Sprite(repeatedTexture);

```

And it should do the trick.

Hope it helps

**Disclaimer**: this code has not been tested

---
Tags: libgdx, textures
---


# Question
Title: Issue with using two StartCoroutines in one script
I'm having a Issue with trying to use multiple StartCoroutines within my Script. I'm having an error at line 50 where is says StartCoroutine does not exist in the current context

```
void OnCollisionExit(Collision theCollision) {
    if ((theCollision.gameObject.tag == "Boost")) {
        movementspeed = 13000;
        //StartCoRoutine (Delay2 ());  error here
        Destroy (theCollision.gameObject);
    }
}

IEnumerator Delay2 () {
    yield return new WaitForSeconds (1);
    movementspeed = 10000;
}

void OnCollisionEnter(Collision theCollision) {
    if ((theCollision.gameObject.tag == "Wall")) {
        movementspeed = 5000;
        StartCoroutine (Delay ());
    }
}

IEnumerator Delay() {
    yield return new WaitForSeconds (3);
    movementspeed = 10000;
}

```

# Answer
The correct spelling is `StartCoroutine( ... )`

From Unity: MonoBehaviour.StartCoroutine
> 3 votes

---
Tags: unity
---


# Question
Title: ArgumentException: The Object you want to instantiate is null
I am trying to copy data over from a binary file but when trying to instantiate a gameobject, it comes out as "null".

```
static void LoadBuildings(SaveBuilding[] buildings)
    {
        if (buildings.Length == 0)
            return;
        foreach(SaveBuilding b in buildings)
        {
            if(b.type.ToString() == "Farm")
            {
                Farm build = Instantiate(Resources.Load("Farm")) as Farm;
                Debug.Log("Build: " + build);
                build.position.x = b.positionX;
                build.position.y = b.positionY;
                build.level = b.level;
                build.levelText = build.GetComponentInChildren<Text>();
            }
        }
    }

```

The debug line shows there is no object and when the next line tries to execute I get an error *ArgumentException: The Object you want to instantiate is null*.

I initially had it as *Farm build = Instantiate(build.prefab) as Farm;* as I get an error "Use of unassigned local variable".

I tried adding a prorperty above the if statement "GameObject build", I tried doing Farm build = new Farm() above the if statement also but still get the initial error.

I have a folder titled "Resources" and confirmed a prefab labelled "Farm" is there also.

Could it have anything to do with the "static" prefix for the method?

# Answer
> 1 votes
You can specify a Type when you call Resources Load. Try loading the object in as a gameobject, instantiating it and then calling GetComponent() to retrieve the farm component.

I am guessing that the Farm is a script that you wrote and attached to a GameObject? If so, it is a component so you'd want to load/instantiate the GameObject and get the component

```
GameObject prefab = Resources.Load<GameObject>("Farm") as GameObject;
GameObject farmObject = Instantiate(prefab);
Farm build = farmObject.GetComponent<Farm>();

```

You could combine these into a line or two but it may be easier to debug like this.

Although, remember that Resources.Load is an expensive operation. So avoid using it unless necessary

# Answer
> 0 votes
When using `Resources.Load(string)` you have to supply full path of a file. I'm not the most familiar with it, but I assume ~~the problem with your code is that you put just "Farm" instead of "Farm.prefab" (file extensions do not show up in Unity's UI).~~ Edit: This was a wrong assumption, based on Unity's Resource.Load documentation, "extensions must be omitted". (Thanks @DMGregory)

Personally I prefer using `public Transform farmPrefab;` in the beginning of the file, then drag and drop the prefab from the inspector, and use `Instantiate(farmPrefab)` from the script. It makes things easier when you want to rename the prefab, or use another one, without editing the code itself.

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


# Question
Title: How can I get Visual Studio to build FXOs when I build my game?
I'm trying to compile a .fxo file when I compile my game.

The compile command-line is:

```
fxc.exe /T fx_5_0 /Fo Basic.fxo Basic.fx

```

Instead of manually using fxc.exe, where can I put this in Visual Studio so when I compile the game, the .fxo gets generated?

# Answer
The simplest solution is to add that command-line as a pre-build step in the project properties. The UI is slightly different for C++ versus C# projects, but basically involves the following steps:

* Open the project's properties window.
* Select the "Build Events" tab.
* Type the appropriate command-line string into the "pre-build" text box.

You can apply the usual set of VS macros in these command-line strings.

---

A more involved, but more flexible, solution is to to edit the project's MSBuild directly to add a custom build tool. Both C++ and C# project files are actually MSBuild projects, so you can open them with a text editor (or within VS, if you unload them first) and edit the MSBuild commands directly.

For example, something like:

```
<ItemGroup>
  <CustomBuild Include="*.fx">
    <Message>Building shaders...</Message>
    <Command>fxc.exe /T fx_5_0 /Fo "$(OutDir)%(Filename).fxo" "%(Identity)"</Command>
    <Outputs>$(OutDir)%(Filename).fxo</Outputs>
  </CustomBuild>
</ItemGroup>

```

This is vastly more powerful, because you don't have to adjust the command-line for every new `.fx` file you add, and because MSBuild can be told about the relationship between inputs and outputs and thus avoids rebuilding things that aren't dirty... but at the same time, it's vastly more complex, because MSBuild is exactly that, and there can be quite a learning curve there.

---

There are also plugins and extensions you can find on the VS extensions marketplace to support this kind of stuff for you, if you'd rather go that route, although there are none I can personally recommend.
> 1 votes

---
Tags: visual-studio
---


# Question
Title: Animations only play when moving along the Y axis
My problem is, I have walk animations which only play when my character is moving upward or downward, and I don't know why. This is my code:

```
public float speed = 5f;
private Animator anim;

void Start () {
    anim = gameObject.GetComponent <Animator>();
}

void Update () {
    anim.SetFloat ("Speed", Mathf.Abs (Input.GetAxis ("Horizontal")));
    anim.SetFloat ("Speed", Mathf.Abs (Input.GetAxis ("Vertical")));

    if (Input.GetAxis ("Horizontal") < -0.1f) {
        transform.localScale = new Vector3 (-1,1,1);
    }
    if (Input.GetAxis ("Horizontal") > 0.1f) {
        transform.localScale = new Vector3 (1,1,1);
    }
}

void FixedUpdate {
    Vector3 move = new Vector3 (Input.GetAxis("Horizontal"), Input.GetAxis ("Vertical"),0);
    transform.position += move*speed*Time.deltaTime;
}

```

# Answer
> 3 votes
You're overwriting

`anim.SetFloat ("Speed", Mathf.Abs (Input.GetAxis ("Horizontal")));`

with

`anim.SetFloat ("Speed", Mathf.Abs (Input.GetAxis ("Vertical")));`

So only vertical movement is taken into account. To fix it, you can try this

```
anim.SetFloat("Speed",
              Mathf.Max(Mathf.Abs(Input.GetAxis("Horizontal")),
                        Mathf.Abs(Input.GetAxis("Vertical"))
              )
);

```

---
Tags: c#, animation
---


title: 2D Plattformer Controller

text:
# Question
Title: 2D Plattformer Controller
I'm currently developing a 2D Plattformer in Unity. And now I'm stuggling with the Character Controller. I know there are a lot of usefull tips for 2D Plattformer Controller in a Mario or Donkey Kong way of Controlling, which are great, but they don't fit my type of 2D Plattformer. My Levels have a similar concept to those in Ori and the Blind Forest and I wanted to have a similar kind of Movement. So does Anybody know how they achieved this kind Character Movement?

For those unfamiliar with Ori and the Blind Forest Control:

In Mario and Donkey Kong the Levels are very horizontal and you run from left to right. The Ground is sometimes interrupted and you have to jump on several Plattforms to reach the next part of the Ground. The Environment like Ground, Plattforms, Walls are mostly boxes.

in Ori and the Blind there is no run from left to right. The Levels go in all Directions. The Environment is more realistic so you have to slide down curvy Walls and no disappearance of the Ground. Also Plattforms are very rare. So instead of jumping through the Level you have to climb through.

I don't know if that Description is enough so here is some Gameplay.

EDIT: I tried .addForce() for every Movement, but this had a weird Slipping Effect. After releasing a button the Charracter slips a few Meters until it finally stops. So I'm currently manipulating the rigidbody.velocity directly for normal horizontal Movement and addForce for the rest like jumping or dashing.

But I have a lot trouble with Sliding along Walls. As mentioned above the Walls are curvy so just cancelling out horizontal Movement and apply some Vertical Force with rb.velocitiy doesn't work. The Character have to follow along the Wall shape. Thus I added a Force towards the Wall, which pressed the Character to the Wall. But this doesn't work very well with my jumping.

# Answer
In Unity terms, the difference between the two movement types are `Coordinate Based Movement`, and `Physics Based Movement`

**Coordinate Based Movement** is used largely with tile based games like pretty much any NES game like the Mario you mentioned, Chess, Checkers, etc. Games like this take player input, and adjust the `WorldSpace` Coordinate of the `GameObject` based on rules. This usually means the `GameObject` moves by *whole units*; 1 left, 2 up, etc.

**Physics Based Movement** is used in games like you've described, Terraria, etc. These games move `GameObjects` by applying `forces` and allowing the `Physics Engine` to adjust their `WorldSpace` Coordinates. `GameObjects` moving under this scheme can be positioned on any *float representable* value; not limited to whole units.

Your mention of sliding down the curvature of the ground is a pretty good indicator that you want to use `Physics Based Movement` in your game.

Sliding when the player input stops is an indicator that the `Friction Coefficient` of your `Physics Material` is not at a value to get the behavior you like. Have a look at the documentation to learn more about how this works.
> 1 votes

---
Tags: unity, 2d
---


# Question
Title: How can I set a property for the upper limit for another property's range
I have two properties, I would like to set one property as the upper limit of another property, hence making the upper rely on a property. As below:

```
public int fullLength;

[Range(0, fullLength)]
public int segmentLength;

```

Is there a way to do this, possibly with a custom editor? If yes, how can it be done?

# Answer
> 3 votes
It's pretty simple, use `OnValidate()`:

```
public int fullLength;
public int segmentLength;

private void OnValidate() {
    if (segmentLength < 0) segmentLength = 0;
    else if (segmentLength > fullLength) segmentLength = fullLength;
}

```

This method is called (in editor only) whenever the script is loaded or a value is changed in the Inspector.

P.S.: You're not using properties here, you're using fields.

---
Tags: unity
---


# Question
Title: How to rotate a sprite in 2D with LWJGL3 and GLSL
I have all the basic rendering already set up, with translation, scaling etc. What matrix(s) and/or vector(s) do I need to multiply/add with my existing code to rotate an object.

Preferably around a point given by a vector2fa, also only in degrees because quaternions aren't implemented and its only 2D not 3D.

Snippet of the vertex shader:

```
gl_Position = transformation * vec4(position, 1.0) + translation

```

Where transformation is done in java as (Note not actual code as * is replaced with .mul()):

```
Matrix4f transformation = ortho * scale

```

And translation is given by a method:

```
Vector4f translation = new Vector4f(x , y , 0f, 0f).mul(gc.getOrtho());

```

All the code listed before works as expected. It is just lacking the rotation feature mentioned at the top.

How can I add rotation to my code?

# Answer
> 0 votes
If you use JOML with LWJGL3 then you can use the Matrix3x2f class to do 2D transformations, like so:

```
Matrix3x2f transformation = new Matrix3x2f()
  .view(-10, +10, -10, +10) // <- like ortho2D in Matrix4f
  .translate(x, y)  // <- multiply translation
  .rotate(radians); // <- multiply rotation
FloatBuffer buffer = <16xfloat>;
GL20.glMatrixUniform4fv(transformationLoc, false, transformation.get(buffer));

```

and your vertex shader then becomes (I am assuming that all you need is a vec2 as a position as well):

```
gl_Position = transformation * vec4(position, 0.0, 1.0)

```

---
Tags: opengl, java, glsl, lwjgl3
---


# Question
Title: Implementing Multiplayer: entire world ticks or just changes?
i'm working an a very simple multiplayer experience (for now node.js, later will probably remake all in c++, but my question is more about theory).

All guides and tutorial i saw about making something multiplayer Always speak about sending all the "world" information, once per tick, deciding optimal tickrate, making smooth movements on client side with interpolation or stuff like that.

Honestly i thought of another way, and i really cant see why its never mentioned. My idea would be the following:

* Client sends to server when input happens; eg if you move with arrows, you send to the server a message only when your moving status changed. If you was moving right and then start moving upright, then you send a message about you changing your movement.
* Server recives the messages, sets variable on player object for its movement, and sends to all other clients information about the change. Also sends current time and current position in the server at the moment of movement change.
* Clients recive a movement status update, place the player object in recived coordinates moved by the new movement * ping delay. That way position in all clients should Always be up to date with the server.

Why should i send hundreds of positions to each client per each player every x milliseconds when i can just send the changes?

I feel like its about polling vs interrupt... (yeah i know its not polling anyway, but the concept is sending the change vs keep sending everything)

# Answer
> 2 votes
I am leaving my answer for posterity, but it seems that I've failed to answer the user's question. The user seems to be looking for a justification that guides are sending updates about everything, not for the "correct" thing to do.

As indicated by others in the comments, the guides are doing the "dumb" thing because optimizations are generally saved for once you understand the code and the impact of these optimizations. F.E. Frustrum culling is learned *after* learning how to draw everything on the screen; even though 3/4ths or even 100% of your geometry will not actually be drawn on screen while you move your camera around.

Sending exacting information is actually not only inefficient, but generally bad. The more you correct the client when it is approximating the correct thing, the more you encounter stuttering or other issues that let the client know that some of their information is being dropped. In general you want the experience to be as seamless as possible so that the user feels in control and immersed in the game. Faking it and correcting things only when necessary is generally going to make it seem like they have an excellent connection even when they don't.

An example can be walking in an FPS. If you lose a couple frames worth of information when your connection drops you will notice that you move backwards 10 feet (or w/e.) If instead the server says "well.. they didn't tell me to *stop* moving, I'm going to keep moving them in this direction" then most of the time when packets are dropped your user will only get a jarring experience IF they are doing something at that exact moment that would alter their Character but instead the predictive model had them do something else. This is generally acceptable as regular lag (your gun didn't fire, you didn't aim correctly, you thought you rounded a corner but didn't, or some other such thing.)

---

*Disclaimer: I haven't implemented this yet, so take it with a grain of salt*

I believe this type of this is normally handled by sending "objectives" and not "constant updates." This is to say, if something is told to go to position X, the server is moving that unit towards position X and the client is doing that, but the server has the "truth." The client has an "approximation."

The client and server are running similar code, so in theory things will line up reasonably. Then you simply update things on the client when it matters. Did something fire? Put that projectile oriented correctly on the client. The client *should* do the right thing in general. Did smething die? Let the client know.

The client only needs an outline of what's changed to update itself and the Server should always have the truth; sending what little information needs to be sent to keep the client on track.

This not only abstracts your clients' ability to cause bad data on the server (as in, the server doesn't care *at all* about the client other than its inputs) but it also minimizes the data that needs to be sent to and fro.

Let the client estimate what is going on and only correct it as needed. Some things will be off due to dropped packets, lag, etc, in which case you should occasionally correct the client I imagine. Don't worry about giving the exact state of the server (*very often*.) I suggest looking at Path of Exile for a game that started off having desync issues and has become fairly reliable even on mediocre wifi connections. It looks smooth most of the time and feels pretty good, and I believe most of it is because it's not micromanaging what's happening, but instead it's approximating and correcting things as it goes.

---
Tags: networking, multiplayer
---


# Question
Title: How does Speed in Animator Window in Unity work?
If speed 1 is considered normal playback, is it by a second? So animation play once in a second? If I have my animator speed set as 100, would it make the speed become 0.06 then ?

# Answer
The speed value is a multiplier.

1 means 1 x animations speed. So if the animation was originally authored as 10 seconds long, it will play over the course of 10 seconds.

If you set the speed multiplier to 2, then you'll play back at double speed, and the 10-second-long animation will finish in 5 seconds.

If you set the speed multiplier to 0.5, then you'll play back at half speed, and the 10-second-long animation will finish in 20 seconds.

Setting the multiplier up to 100 would make the animation finish in a tenth of a second if it was originally 10 seconds long.
> 1 votes

---
Tags: unity, animation
---


# Question
Title: Why is my inherited class's transform always null?
I have a class inherited to another class, and I can't get the transform on the inherited class.

Here's what i have and trying to do

```
Class A:Monobehavior{}

Class B:A{}

//somewhere else

A object = new B();

```

but right now, whenever I try to get the transform of object, either from a function in B or out here via `object.transform`, it will always return null.

How do I fix this?

# Answer
Because what you have is a lone Monobehavior in a void.

It's not on any GameObject and it's not in the Transform tree.

You need to create it right on a GameObject by using AddComponent:

```
A object = some_game_object.AddComponent<B>() as A;

```
> 2 votes

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


# Question
Title: Exporting steps/actions with a 3D Studio Max plugin
I'm trying to figure out how this plugin works behind the scenes. Do you know if there is any 3ds-max API function (maxscript/c++/python) which allows to record the action history somehow?

You could claim there is the max-recorder... in fact, this one does "almost" what I want... but the idea would be writing a plugin to export the max actions to my own custom format.

Example:

```
1) I create a cube with certain parameters
2) I select it
3) I apply a modifier with certain parameters

```

Imaginary output:

```
output = [
   {"action":"create_cube", "params":{"name":"cube1", "size":10, "tess_x":2, "tess_y":3, ...},
   {"action":"select_mesh", "params":{"name":"select_mesh1" "selection": "cube1", ...},
   {"action":"subdivide", "params": {"name":"subdivide1", "type": "catmull-clark", ...},
   ...
]

```

Thanks in advance.

PS: I haven't been able to contact that author's plugin to get some info about it, otherwise I wouldn't be asking ;-)

# Answer
> 2 votes
The plugin you have linked to doesn't seem to record command actions. Instead it records the modifier stack and allows the export of all animated parametric values. For example a cube of 1x1x1 is created on frame 1 but on frame 10 the cubes width is adjusted to 10. The exporter captures the animation of that data and allows playback of that animated value on a procedurally generated cube. 3D Studio Max works consistently in this way: every parameter presented to the user can be animated. Furthermore, each object primitive can have a stack of modifiers on top \- modifiers such as noise, subdivision, wave, taper, etc. These modifiers also have animatable parameters which the exporter supports. Finally, 3D Studio Max also allows modifiers to be stacked, so a noise modifier can stack on a cube, and a wave on the noise, etc. Each parameter can be animated independently. Materials are the same. As are lights, cameras and other elements in the scene.

Consider your original output in these terms:

```
1) I create a cube with certain parameters
2) I select it
3) I apply a modifier with certain parameters

```

Imaginary output:

```
object = {  name : 'cube1',
            transform : { pos=[0,0,0], rot=[0,0,0,1], scale=[1,1,1] },
            stack = [ { create_cube : { x : 10, y : 10, z : 10, tess_x:2, ... } }
                      { subdivide : { type: catmull-clark, ... } },
            animation = [
                      { frame : 10, param : 'create_cube.x', 20 }
                    ]
                }

```

I added an example of the animation -- targeting specific parameters.

In your engine you would essentially be evaluating the entire stack every time it changes -- this is how 3D Studio Max works internally.

If I were trying to make a 64k demo it would be the cheapest way to get great art variety for cheap and would look super cool too. Obviously you do not want the complexity of modifiers to be too great, for performance reasons.

So I guess my answer to your question is that no - theres no easy way to export action history, but I think that's not what you want to do here. You want to export the object stack, animate specific parameters, and evaluate the stack in engine.

# Answer
> 1 votes
Short answer - See the Node Event System here.

Long answer - First, the MaxScript Macro Recorder in 3ds Max does something like this. It outputs a script which can potentially be replayed to achieve the same results as a sequence of UI operations. However, MaxScript exposure is incomplete, so many operations are not recorded, thus playback of the script is often not possible. Macro Recorder useful more as a training and inspection tool when learning about the MaxScript for features in the product.

Second, more realistically, to output a sequence of operations, you would have to listen for many events, such as with the Node Event System, and then provide recording logic for each event. It would be difficult/impossible to record every single parameter change. Some areas of the UI may be connected directly to the internal data, without an exposed API layer. That means some UI operations can never be repeated programmatically, and you'd have to record mouse operations to detect them, a big mess.

Still, it's quite feasible to record basic information, like when objects are created, moved, or their geometry is (somehow) changed, using the Node Event System. It's exposed in MaxScript and the SDK.

---
Tags: 3dsmax, plugin
---


# Question
Title: Extracting gamefiles from a game, modify it, then use it commercially, would it be illegal?
I kinda get a chance to extract gamefiles from the game fortnite(assets, sounds, etc), and then I want to use them for my animation, would that be illegal.

If it is illegal, what if I alter the assets, like modifying it to a voxel, and use it commercially, is it still illegal?

# Answer
Yes, this is in most cases a violation of copyright.

While many jurisdictions offer exceptions for fair use in specific applications (eg. education or parody), these don't prevent the original creators from suing you — they're just a form of argument you could try to use in defense. Even if you were technically in a permissible use case, the cost of arguing it in court alone might be enough to seriously threaten your business.

As a general rule of thumb: if you didn't make it or obtain explicit permission from the creator to use it in your game, then it's not your content to use.

Or more simply: don't steal other people's work, please.

(I am not a lawyer and this post is not legal advice)
> 0 votes

---
Tags: unreal-4, legal, copyright
---


# Question
Title: Pixel-art sprite distortion with 1:1 pixel ratio
So I've been studying the Unity's PPU, pixel density, camera settings topic to make my game pixel-perfect. I've set everything in a way that my screen pixel to sprite texel ratio equals 1.

The art looks very good and crisp overall on the game view...

But!

There are still some minor distortions and I don't know where it comes from.

Take a look at this example:

In this example my settings are:

* **Screen**: 870x510
* **PPU**: 100
* **Camera size**: 2.55
* **Pixel snap** on Sprite material: on

The issue happens when I move the sprite manually by ~0.001 values on the Y axis. Same happens on the X axis.

Any ideas what's the problem?

# Answer
> 1 votes
So the problem was that there was some kind of artifact going on caused by how the sprite meshes were constructed.

When i changed the **mesh type** of the sprite to **rect** \- the problem disappeared. Here's a comparison of a sprite with mesh type **tight** (left) and **rect** (right):

Here's how the sprites were mapped to meshes in Unity:

---
Tags: unity, pixel, pixel-art
---


# Question
Title: textelFetch returns black value with sampler2D when level is greater than 0
I am trying to write a code for rendering a object with material properties (diffuse and specular). I am trying to use textures to pass float data to the vertex shader (I am accessing the textures in vertex shader). I have two textures with 7 miplevels each to pass data pertaining to specular reflections. I am using texelFetch to access the data. But if the level of the texture is greater than 0, then the value returned by texelFetch is invariably 0. Here is the code used to setup the textures in c++.

```
glGenTextures(1,&textures[1]);
glBindTexture(GL_TEXTURE_2D, textures[1]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
for(int mipLevel = 0; mipLevel < 7; mipLevel++)
{
    glTexImage2D(GL_TEXTURE_2D, mipLevel, GL_R32F, 129, 129, 0, GL_RED, GL_FLOAT, specularTextures[mipLevel]);
    delete[] specularTextures[mipLevel];
}

```

As one can see I am using only the Red channel to pass the data. Now in vertex shader code I access the texture.

```
#version 450 core
layout (location = 0) in vec4 aVertex;
layout (location = 1) in vec4 aNormal;
layout (location = 2) in vec4 diffuseAlbedo;
layout (location = 3) in vec4 specularAlbedo;
layout (location = 4) in ivec4 brdfIndices[5];
layout (location = 9) in vec4 brdfWeights[5];

out vec4 ourColor;

uniform mat4 projection;
uniform mat4 view;
uniform vec3 camCenter;

uniform sampler2D diffuseTexture;
uniform sampler2D specularTexture1;
uniform sampler2D specularTexture2;

int main()
{
    gl_Position = projection * view * aVertex;
    float value = texelFetch(specularTexture1, ivec2(10,10), 1).r;
    ourColor = vec4(vec3(value),1);
}

```

No matter what index I use to access the texture with level greater than 0 ( 1 in this case) I get value = 0. But if the level is 0 I am getting correct value. I tried to look online but no one was facing the similar problem, so I am guessing it is some kind of silly mistake.

Note: I am binding the textures everytime I am rendering.

# Answer
Section **11.1.3.2 (Texel Fetches)** of the OpenGL specification (I'm using 4.4 for reference) explains this; you must use a mipmapped minification filter to access any LOD other than the base level.

> Unlike filtered texel accesses, texel fetches do not support LOD clamping or any texture wrap mode, and require a mipmapped minification filter to access any level of detail other than the base level.

Also:

> Texel fetches with incorrect parameters or state occur under any the following conditions ... the computed level of detail is not the texture’s base level and the texture’s minification filter is NEAREST or LINEAR.

And:

> In all the above cases, if the context was created with robust buffer access enabled, the result of the texture fetch is zero, or a texture source color of (0, 0, 0, 1) in the case of a texel fetch from an incomplete texture. If robust buffer access is not enabled, the result of the texture fetch is undefined in each case.

So this is wrong:

```
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

```

But this is correct:

```
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST);

```
> 2 votes

---
Tags: opengl, textures, glsl
---


# Question
Title: Why is my AABB vs AABB code returning false positives
I am trying to do AABB vs AABB collision and the code is never finding a collision.

```
    private static boolean checkFullCollision(Entity entity, Entity entity1) {
    float[] amin = entity.getMin();
    float[] amax = entity.getMax();

    float[] bmin = entity1.getMin();
    float[] bmax = entity1.getMax();
    return  (amin[0] <= bmax[0] && amax[0] >= bmin[0]) &&
            (amin[1] <= bmax[1] && amax[1] >= bmin[1]) &&
            (amin[2] <= bmax[2] && amax[2] >= bmin[2]);
}

```

where I calculate my min and max.

```
    public float[] getMax() {
    final float[] max = new float[3];
    max[0] = position.x + this.max.x;
    max[1] = position.y + this.max.y;
    max[2] = position.z + this.max.z;
    //System.out.println(position);
    return max;
}

public float[] getMin() {
    final float[] min = new float[3];
    min[0] = position.x - this.min.x;
    min[1] = position.y - this.min.y;
    min[2] = position.z - this.min.z;
    return min;
}

```

Can someone help me please.

Thanks in advance

# Answer
I figured out the answer.

For people trying to implement an aabb vs aabb collision here is the code.

```
private static boolean checkFullCollision(Entity entity, Entity id1) {
// VERY INPORTANY. The max and min are centered at the origin(0,0) and not at the entities posititon.

     Vector3f aextents = Vector3f.sub(entity.getModel().getMax(), entity.getModel().getMin(), null);
   Vector3f bextents = Vector3f.sub(entity.getModel().getMax(), entity.getModel().getMin(), null);

   boolean x = (abs(entity.getPosition().x - id1.getPosition().x) <= aextents.x + bextents.x);
   boolean y = (abs(entity.getPosition().y - id1.getPosition().y) <= aextents.y + bextents.y);
   boolean z = (abs(entity.getPosition().z - id1.getPosition().z) <= aextents.z + bextents.z);
   return x && y && z;
}

```
> 1 votes

---
Tags: java, collision-detection, physics, aabb
---


# Question
Title: Unity: Particle System start rotation completely incorrect when set via C# script
I am trying to set the starting rotation of a particle system via c# script so that the particles orientate with another object in the scene. My particle system 3d rotation is set as follows:

```
void UpdateParticleSystemRotation(Quaternion rotation)
    {
        if(this.gameObject.GetComponent<ParticleSystem>() != null)
        {
            var particleSystemMainModule = gameObject.GetComponent<ParticleSystem>().main;
            particleSystemMainModule.startRotationX = new ParticleSystem.MinMaxCurve(rotation.eulerAngles.x);
            particleSystemMainModule.startRotationY = new ParticleSystem.MinMaxCurve(rotation.eulerAngles.y);
            particleSystemMainModule.startRotationZ = new ParticleSystem.MinMaxCurve(rotation.eulerAngles.z);
        }
        else
        {
            Debug.LogError("There was an error");
        }
    }

```

The rotation.eulerAngles.x/y/z values are coming through correctly, and by debugging in VS I can see that the values have been correctly assigned, as below:

However I observe that the particle system is not at all orientated with this X value, and the particle system is showing a completely different value:

You can see from the screenshots above that a **value of 74.5f becomes 4274.2f** by the time it hits the particle system.

I have double checked that the type expected by the ParticleSystem.MinMaxCurve constructor is a float. I cannot understand why this is happening.

I would be very grateful if someone would be able to provide some clarification on this.

Many thanks in advance.

---

I should add, rotation seems completely random for any given input value, it doesn't follow any obvious rhyme or rhythm.

I am using Unity 2017.2.0f3

# Answer
> 2 votes
When in doubt, don't forget to read the docs:

> public ParticleSystem.MinMaxCurve startRotationX;
>
> The initial rotation of particles around the X axis when emitted.
>
> **Note that the value should be given in radians**

So 74.5 radians converted to degrees for display in the editor is:

74.5 • 180° / π = 4268.5°

Which looks on par with what you're seeing in the inspector.

Dropping the scale of all your code-provided angles to a few multiples of π should make things behave much more sensibly.

Also remember that order matters when composing rotations, like the x, y, and z angles in Euler form, so take this into account when planning the angles you use to avoid surprises.

---
Tags: unity, c#, rotation, quaternion, particles
---


# Question
Title: How can I handle a transition into building interiors?
I am trying some stuff on Unreal Engine to make something approching games like Commandos series. But for now, I'm stuck with something I can't figure how it is done : How are building interior handled ?

Here's a screenshot to illustrate what I say :

When you enter a building, everything become black, except the building's interior. The interior is isolated, there is no "communication" between the interior and the exterior, and between linked interiors. For exemple if you shoot with a weapon and there is an enemy outside just behind the door, he can't hear you.

Sometimes biggest buildings are divided in many parts, and each floor are a different "section" that are isolated from each other (you have a transition and can't communicate between). Here is an image that explain it well : Commandos 2 interior

**Teleport** : I first thinked that you were teleported to a different portion of the map, or a different small map, but it is unlikely. If you look at a window, you are at the same time outside (you can see your character outside at the window) and inside (you character is leaning out the window). Teleport would cause many sync issue.

**Section toggle** : Then, I thinked that the interior is already handled in the exterior map, but completely hidden, and when you enter it, it "deactivate" the exterior by hidding everything outside and displaying interior. Again, this is unlikely since map are full 3D (you can rotate 360°) and exterior are 2D.

How can I create this kind of transition?

I've specified that I am on Unreal, but I'm more searching the theorical way rather than Unreal specifics.

# Answer
There should be a variety of ways to do that, I'm not familiar with how smooth the transition is in the screenshot you showed, but here it goes:

**Organization:** Organise your project, in such way that you have one object representing the "open world" (with all of its children) and one (or more) object each representing an "area", like a house or a cave.

**Behaviour:** Now every time the player approaches one of these areas, simply disable the open world, and enable that area, in such way, that the open world is still in memory, but its paused, and the new area unpauses (or is being initialised, depending how you plan to make the game). Also make sure that if in the open world you are drawing a sky (with skybox or any other way) to switch to drawing only black (or maybe another skybox?) so that the aesthetics match the area.

**Return:** When you exit from an area, back to the open world, do the same thing, pause the area, and resume the open world. Please note that if you are making a big open world game, you may need to dynamically create and destroy areas that are too far away, but this is a little off-topic.

**Bonus transition effects:** You can create some effects like when you disable an object, it will slowly fade its alpha value towards 0, and when you enable another object it will fade in the same way.

I'm unfamiliar with Unreal engine, but make sure that an object that is disabled (or paused) that it does not draw itself. In Unity I know this happens automatically.
> 1 votes

---
Tags: maps, level-design, unreal
---


# Question
Title: What Unity object is my script linked to?
I am fixing an issue in a unity code that I have inherited. I have found the code file but need to fix the Canvas that is attached to that script.

Is there a way to determine, and load, the Canvas for the code file that I have found.

This is part of a vuforia enabled app. Here is the start of the file for the Canvas that I"m looking for

```
using UnityEngine; using System.Collections; using Vuforia;

public class InitErrorHandler : MonoBehaviour {
    #region PUBLIC_MEMBER_VARIABLES
    public UnityEngine.UI.Text errorText;
    #endregion //PUBLIC_MEMBER_VARABLES

    #region PRIVATE_MEMBER_VARIABLES
    private Canvas errorCanvas;
    private string key;
    #endregion //PRIVATE_MEMBER_VARIABLES

    #region MONOBEHAVIOUR_METHODS
    void Awake ()
    {
        // Get the UI Canvas that contains (parent of) the error text box
        if (errorText)
        {
            errorCanvas = errorText.GetComponentsInParent<Canvas>(true)[0];
        }

        VuforiaRuntime.Instance.RegisterVuforiaInitErrorCallback(OnInitError);
    }
    #endregion //MONOBEHAVIOUR_METHODS
...
}

```

# Answer
One of the fastest ways would be to add a Start script like so:

```
void Start () {
    string path = gameObject.name;
    Transform parent = transform.parent;

    while(parent != null) {
        path = parent.gameObject.name + "/" + path;
        parent = parent.parent;
    }

    Debug.Log('Here I am!\n" + path);
}

```

Run your project and wait for the "Here I am!" message to spring up in the console, printing out the path where you can find the object in the currently open scenes.

Obviously this only works if the script is used somewhere in an easily-reproducible execution path. If it's in a prefab or scene that's not in the normal flow, you won't see it this way, and we need to investigate more deeply...

---

First, make sure you've set your asset serialization mode to Force Text, so we have human-readable data to look at for the next steps. Save your scenes/project.

Next, find the .meta file for the script you're looking at. (You might need to show hidden files to be able to find it)

At the top of that metadata file, you'll find a GUID, a long string of hexadecimal characters like

```
guid: a652b1795b650454a8270045af8e2a71

```

This ID is how Unity references the script internally. If the script is used in any prefabs or scenes, those files will contain this ID.

You can use a program like Notepad++ to search all files in your assets directory to find matches for this ID. That will let you identify which prefabs or scenes it's used in. You might need to scan up the parent tree to see which object it's connected to if there are multiple similar objects in the file.

---

The last case this might miss is where the script is attached by another script at runtime, and isn't referenced in a scene/prefab.

You can check for this by right-clicking on the name of the class and selecting "Find References" to get a list of all places the class is mentioned in another script (like in an `AddComponent<T>` call)
> 2 votes

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


# Question
Title: Implementation a Prefix tree or Trie in Unity C#
I am trying to make a word game in unity. The game shall be an online game with 4-6 players. The gameplay is somewhat like this:

1. Suppose 4 players are playing the game- p1, p2, p3, and p4.
2. All players start off with a score (let 5).
3. Each player is supposed to give a letter each, such that those letters make some meaningful word.
4. The person who gives the final letter and thus completing the word loses 1 point.
5. Words of length 3 or more are only taken as complete words. Words like 'he', 'hi', 'oh' etc. are ignored for the sake of the fairness of the game.
6. Some other features will also be added for an even fair gameplay. (Like 2 letter or 3 letter cards - where a player will be allowed to give 2 or 3 letters at the same time, or a life card which will sustain the players point even on losing the round etc.)

Let us take an example:

* p1 - H
* p2 - E
* p3 - L
* p4 - L

Now since HELL becomes the complete word, p4 will lose 1 point and the game continues, with p4 starting with a new letter. Taking another example:

* p1 - N
* p2 - O
* p3 - T
* p4 - H .... instead of completing with an 'E' players should try to continue
* p1 - I
* p2 - N
* p3 - G

So p3 will lose a point.

Now **if p3 uses any letter, which p4 thinks will not make any word, then p4 can challenge p3. If the word exists with those letters, p4 will lose a point. If the word doesn't exist then, p3 will lose a point**.

So, for this kind of a feature, I would need to implement a Trie data structure in my game in Unity C#.

Currently, my game only looks like this:

I can enter any word, in the Input Field and search, if the **word is complete and present** in the list of words then it shows **1** in the Text above the Input Field. If the **word is incomplete and can be completed**, then it'll display **2**, and if **no such word exists**, then it'll show **0**.

This is my code for Trie/Prefix tree:

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

namespace MyTree {
    public class Node {
        const int ALPHABET_SIZE = 26;
        // declaring 26 child nodes
        public Node[] children = new Node[ALPHABET_SIZE];
        // variable to check if at that node a word ends or not
        public bool isEndOfWord;
        // Node constructor
        public Node() {
            isEndOfWord = false;
            // initialsing all child nodes with null value
            for (int i = 0; i < ALPHABET_SIZE; i++)
                children[i]=(null);
        }
    }
    public class PrefixTree {
        public Node root;
        public PrefixTree () {
            root = getNode();
        }

        public Node getNode () {
            return new Node ();
        }

        public void Insert (string key) {
            int level;
            int length = key.Length;
            int i;

            // making a root
            Node pCrawl = root;
            // iterating from the first letter to the last letter
            for (level = 0; level < length; level++) {
                i = 'a' - key[level];
                if (pCrawl.children[i] == null)
                    pCrawl.children[i] = getNode();
                pCrawl = pCrawl.children[i];
            }
            pCrawl.isEndOfWord = true;
        }

        public int Search(string key) {
            int level;
            int length = key.Length;
            int i;
            Node pCrawl = root;

            for (level = 0; level < length; level++) {
                i = key[level] - 'a';

                if (pCrawl.children[i] == null)
                    return 0;   //Absent
                pCrawl = pCrawl.children[i];
            }
            if (pCrawl != null) {
                if (pCrawl.isEndOfWord == true)
                    return 1;   //Present
                return 2;       //Can be completed
            }
            else
                return 0;       //Absent
        }
    }
}

```

This is my Word Checking Script:

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

public class CheckDict : MonoBehaviour {

    public InputField inpText;
    public Text showText;
    public TextAsset dictFile;

    private string textToString;

    private List<string> dictList;
    private int dictLen;
    private PrefixTree dictionary;

    void Start () {
        dictList = TextToList (dictFile);
        dictList = dictList.GetRange (0, 20);
        dictLen = dictList.Count;
        dictionary = new PrefixTree ();
        //dictionary.root = new Node();

        showText.text = dictList[5];
        for (int i = 0; i < 20; i++)
            dictionary.Insert (dictList [i]);
    }

    private List<string> TextToList (TextAsset ts) {
        return new List<string> (ts.text.Split ('\n'));
    }
    public void OnSubmit () {
        textToString = inpText.text.ToString();
        int i = dictionary.Search (textToString);
        showText.text = i.ToString();
//      if (dictList.BinarySearch (textToString) < 0)
//          showText.text = "Word missing from dictionary";
//      else
//          showText.text = textToString;
    }
}

```

During runtime, this error is shown:

> IndexOutOfRangeException: Array index is out of range. MyTree.PrefixTree.Insert (System.String key) (at Assets/Scripts/PrefixTree.cs:40) CheckDict.Start () (at Assets/Scripts/CheckDict.cs:28)

The program runs, when I enter anything for example: 'aah' which is present in my list of words, I get a 0.

Here is the link to my list of words:

https://github.com/Souvik7cd/Game-dictionary/blob/master/dict.txt

# Answer
Thaks to DMGregory comment, I changed the Insert Function of the Prefix-Tree code:

```
           public void Insert (string key) {
                //int level;
                int length = key.Length;
                int i;

                // making a root
                Node pCrawl = root;
                // iterating from the first letter to the last letter
                for (int level = 0; level < length; level++) {
                    i = key[level] -'a';    // changed
                    if (i < 0)              // added if
                        break;

                    //Debug.Log ("New Node " + level);
                    //Debug.Log ("Key[level] " + key [level]);
                    //Debug.Log ("i: " + i);

                    if (pCrawl.children [i] == null)
                        pCrawl.children [i] = getNode ();

                    pCrawl = pCrawl.children[i];
                }
                pCrawl.isEndOfWord = true;
            }

```

the problem was that `'a' - key[level]` would generate negative values that resulted in the error. Just changed the line to `key[level] -'a'` and added a if statement to ensuring it doesn't get negative
> 1 votes

---
Tags: unity, c#, data-structure, tree, word-games
---


# Question
Title: How to rotate object just like in the scene?
Look at this image, I selected an object and pivot is set to local:

When I rotated selected object in the scene by X axis, it rotates exactly I wanted.

But if I rotate axis from inspector or script, it doesn't rotated to desired angle.

I'm not sure, but it seems it's related about Quaternion, but everything I tried doesn't worked well.

How do I rotate that object just like in rotated from scene?

# Answer
> 2 votes
The (local) transform gizmo shows you rings of possible rotations from the current orientation, about the current local x, y, and z axes respectively.

The Inspector / `transform.localEulerAngles` property show you the current local orientation expressed as Tait-Bryan angles (commonly called Euler angles) with x, y, and z components.

These are not the same thing.

Tait-Bryan angles are not a point in rotation space. They're directions for how to get there. In Unity's formulation, they say:

1. Starting from the default/identity orientation
2. Rotate `y` degrees clockwise around your local y+ axis
(note that this turns the local x & z axes)
3. Next, rotate `x` degrees clockwise around your new local x+ axis
(note that this turns the local y & z axes)
4. Finally, rotate `z` degrees clockwise around your new local z+ axis

So the y rotation always happens first and z rotation always happens last. (If you think of the rotations as local-space. If you think of them in parent space, the order is reversed but the result is the same)

But using the transform gizmo, you can grab & turn the green & blue rings in any order you want, or even interleave them. Three numeric fields aren't enough to specify this kind of interleaving, at least not alone.

If you want to get the result of turning the green (y+) gizmo in local mode no matter what orientation you're starting from, in code you can write any of these equivalent expressions:

* `transform.Rotate(Vector3.up, yawAngle)`
* `transform.Rotate(0, yawAngle, 0);`
* `transform.Rotate(transform.up, yawAngle, Space.World)`;
* `transform.rotation = transform.rotation * Quaternion.AngleAxis(yawAngle, Vector3.up)`
* `transform.rotation = transform.rotation * Quaternion.Euler(0, yawAngle, 0)`
* `transform.rotation = Quaternion.AngleAxis(yawAngle, transform.up) * transform.rotation;`

# Answer
> 1 votes
It seems you are trying to tell apart the local from the world space. From the scene, you can press a button next to pivot, to tell apart the `local` from the `world` space.

When it comes to scripting, it all depends what code you are using. By using `transform.localRotation` you affect the object's local rotation (what you see in the inspector). By using `transform.rotation` you are affecting the object's world rotation.

You can also use the `transform.Rotate(Vector3 eulerAngles, Space relativeTo = Space.Self)` function, which by default rotates around its local axis, but by changing the `relativeTo` variable, it can make a rotation in world space.

---
Tags: unity, rotation, quaternion, angles, rotate
---


# Question
Title: Why does my AI Enemy slide towards its target when it is supposed to be idle?
So using Unity standard assets to get a stage rolling, Ive built a simple terrain and used FPSController as the player and AI ThirdPersonController (Ethan) as the enamy.

Ive built the navmesh and everything was working in its default state, but then I changed the AI script slightly as I wanted Ethan to follow me only if I come within a certain range, so I changed it to the following:

```
public float dangerRadius = 5f;

        private void Start()
        {
            // get the components on the object we need ( should not be null due to require component so no need to check )
            agent = GetComponentInChildren<UnityEngine.AI.NavMeshAgent>();
            character = GetComponent<ThirdPersonCharacter>();

            agent.updateRotation = false;
            agent.updatePosition = true;
        }

        private void Update()
        {
            if (target != null)
                agent.SetDestination(target.position);

            if (agent.remainingDistance < dangerRadius)
                character.Move(agent.desiredVelocity, false, false);

            else
                character.Move(Vector3.zero, false, false);
        }

        public void SetTarget(Transform target)
        {
            this.target = target;
        }

```

But the problem is that when the remainingDistance is greater than dangerRadius or when I am out of range, Ethan just slides slowly towards the target in idle state and as the distance becomes lower than the threshold he starts running as expected.

Ive tried adding friction materials to the terrain and the collider on Ethan but he still slides.

Help thanks

# Answer
> 0 votes
I think the transition from Idle animation to Running might be dependent on the velocity of the AI character. As in, the velocity has to be higher than a certain value and in your case it might not be hitting the mark when it's outside the danger radius. Can you check the parameter being used for the transition in the animator window?

---
Tags: unity, movement
---


# Question
Title: Is multiple material on same mesh cause low perf?
I'm making something like "Low poly" style game. For that, I'm using multiple materials for each mesh without uv mapping and texturing.

Luckily, only weapon does this, others not. Also it's first person shooter so most of time, it just 7~8 materials requires for rendering.

However, I heard that lots of materials causes more rendering for GPU and it cause performance issue. My target platform is Android, and that could be a big problem.

Should I change all my weapons to have single material each?

This is the screenshot of my game. As you can see, single weapon uses 6 materials.

# Answer
> 0 votes
As the comments on the question indicate, multiple materials require more rendering costs. I fixed this issue by integrate multiple materials for each model one by one.

---
Tags: rendering, materials
---


# Question
Title: How to hide Game Progress Files saved in Application.persistentDataPath in Unity Android
I am developing a game that saves its state in a text file. I am writing that file in `Application.persistentDataPath` but my issue is that the game progress file is available to user in `Data/PACKAGE NAME/files/*`.

How can I hide the game progress file so that user can't access the files ?

# Answer
You can't.

The path represented by `Application.persistentDataPath` is a path on the *user's computer*. You can't really prevent the user from seeing and manipulating files on his or her own machine.

`Application.persistentDataPath` writes to locations that are hidden by default on macOS and Windows (I'm not sure about Android). In theory you could set the "hidden" attribute on the files you write, as well (if you access to an API to do so). But that doesn't prevent the user from toggling "show hidden files" or otherwise deleting them.

If you really want files to be written to a secure location where the user *cannot tamper with them*, you will need to write them on a machine *you* control (that is, a server), which is a whole new can of worms.

I suspect you're best off not worrying too much about this. Write a bit of code to handle the cases where the files don't exist (so for example your game doesn't crash), and that should be sufficient.
> 4 votes

# Answer
You can try using sqlite or go with encryption of the text.
> 1 votes

---
Tags: unity, android, unityscript
---


# Question
Title: Can't set object's local rotation like rotating from gizmo in the scene
Here, I have a plane model with some sub parts(like aileron) can rotate:

That red section is weight painted(rigged) vertices, and I need to control the rotation of this in Unity by script.

So this is the image in Unity, rotating through green ring(along x axis) of aileron bone from gizmo works exactly I want.

However as you can see in the inspector, I rotated along X axis but it doesn't changed only x axis, it also changed other axis like Y and Z.

So when I just rotate X rotation of aileron from the script or inspector, it gives me total wrong rotation, and here is the solution I got: How to rotate object just like in the scene?

So I wrote the code:

```
leftAileron.Rotate(0, value, 0);

```

Now it rotates desired angle but the problem is transform.Rotate method is just rotating the object, means adding the new value to current rotation.

In my case, I need to "set" the rotation, not adding it, because it gives wrong rotation in this case.

I made a slider for explain and demonstrate my problem: here is the slide and it's range is -5 to 5 and default is 0.

The code for rotating aileron is this:

```
sliderLeftAileron.onValueChanged.AddListener((value) => {
    leftAileron.Rotate(0, value, 0);
});

```

When I moved slide to left, value goes negative so it rotates like this.

But when I slightly moved the slide to right, it still rotate same direction because the value is still negative and just try to adding it.

So I need to set the rotation of aileron, not adding it, moving slide to right should moves opposite direction and vise versa.

Is there a way to set rotation just like Rotate(0, value, 0) but not adding it in this case, like this:

```
transform.rotation = Quaternion.Euler(0, value, 0);

```

I tried bunch of ways but none of them worked, how do I treat my aileron rotation just like in gizmo in the scene?

# Answer
I'd recommend doing something like this:

```
public class LocalRotator : MonoBehaviour {

    // Let the inspector / other scripts control how far to rotate this,
    // and about which local axis.
    public Vector3 localAxis = new Vector3(0, 1, 0);
    public float angleChange = 0f;

    // Cache your local rotation just after the object is loaded/enabled in the scene.
    Quaternion _initialOrientation;
    void Start() {
        _initialOrientation = transform.localRotation;
    }

    // Each frame (or in response to slider change events if you prefer)
    // update the local rotation as the composition of the input value
    // applied relative to the original orientation.
    void Update() {
        var change = Quaternion.AngleAxis(angleChange, localAxis);
        transform.localRotation = _initialOrientation * change;
    }
}

```
> 1 votes

---
Tags: unity, rotation, transformation, axis
---


# Question
Title: What type of network design should be used for my game?
Okay, so I am trying to design a multiplayer only game. Here is the gist of my multiplayer gameplay structure,

* When a player starts up the game and clicks Play, he will be send to a map with 7 other players (i.e only total 8 players per map) who also just started the game like him.
* It's basically like a deathmatch round. The last man standing is the winner.
* The winner of the map will be transferred to another map which will consist of 7 other players like him who won their previous matches. Note, the 7 losers of a match will be bought back to the main menu. When they click Play, they will start from the case mentioned in my first point.
* And for the winners they will continue to play against winners from different maps.

So, my question is how to implement this network? Do I just need one main server? I am new to this so sorry if this question is very crude or stupid. Note, I just need a very high level network design considerations and suggestions.

# Answer
There are essentially two ways to do this.

1. A dedicated gameserver all the players connect to. Someone needs run the gameserver(s) in a datacenter. That someone might be you or volunteers from the player community.
2. Peer-to-peer networking. One player is acting as the server, others act as clients. This has the advantage that nobody needs to pay for hosting the gameservers (although you might still need to pay for a global matchmaking server to allow players to find each other). The disadvantages are that players might not have internet connections as good as a dedicated server, and that you have a lot more technical challenges to solve, like NAT punchthrough for players behind routers or host transfer if the host leaves the game. It might also be difficult to prevent the host from cheating.
> 1 votes

---
Tags: networking, multiplayer
---


# Question
Title: How to Keep Unity From Changing Sprite When Changing Orthographic Size?
so I have a simple X animation, and at the end (when it looks like a full X), it looks good on one orthographic size, but bad on another. Here's what it looks like when the size is 3:

Now you can notice, there are a few pixels that look a bit off, but it still looks pretty good. Here's what it is supposed to look like:

So if you look closely, it is a bit different, and that's the point. However, if you change the orthographic size to.. say 5, you get this horrid thing:

Why is Unity doing this, and how can I fix this so that it looks how it's supposed to? Also, in this, my X is upscaled x2. Would it fix it just to have it made to the right size, and then upscaled x1 (e.g none)?

# Answer
> 1 votes
I found that this actually worked for me when I set the filter to bilinear, rather than point. It is more blurry that way, but that's fine in this instance.

---
Tags: unity, 2d, camera
---