# Question
Title: How are animations specified by an artist but implicitly understood by the game engine?
I'm trying to understand the relationships between 3D models (files) and the games that load and use them. As a software engineer, I'm willing to make the few following assumptions:

* I would *assume* that most (popular) 3D model formats are basically just storing coordinate positions for all the vertices that make up the model. They probably also store texture/theming information about each polygon (that is formed by combining 3+ vertices)
* I would also *assume* that "*labeled animations*"" are stored in these files as well. This way, a 3D artist could make a model of some character, and animate them running all from inside whatever tool they use for modeling. Then they associate that animation with some label ("*bad\_guy\_running*") and all that info is stored inside the resultant file. Then, in the game code, the developers can programmatically access + execute those labels somehow, therein reproducing the same animation from inside the game. In our case, the bad guys starts running.

Am I way off base here? If so, *please* begin by correcting me, and please be gentle, as again I'm not even sure what this subject matter would be called to even do the upfront research on my own.

# Answer
> 1 votes
> I would assume that most (popular) 3D model formats are basically just storing coordinate positions for all the vertices that make up the model. They probably also store texture/theming information about each polygon (that is formed by combining 3+ vertices)

For games, we will almost exclusively use triangles for the final geometry (although for some types of modelling, quads are more natural; they are easily converted to triangles after the fact, however). Otherwise, this is basically correct. Some file, somewhere, will store a bunch of vertex data which represents triangles.

> I would also assume that "labeled animations"" are stored in these files as well.

Somewhat less good of an assumption. Animations *are* stored somewhere, but not *necessarily* in the same file. One of the most popular approaches for animations is "skeletal animation," in which a simplistic rig (or skeleton) is what is actually being animated, and the more complex triangle mesh is weighted to various "bones" of this rig. One of the benefits of this approach is that the animations can be stored distinct from the actual model geometry and re-used across many similar models.

---

In general, animations are not "implicitly" understood by the game engine at all. There are many ways to store models and animations, and many ways to make use of them in an engine. During the development of a game (or of an engine), decisions will be made by the team about the representations and technology they want to use and the workflow they want to fit that in to. Somebody will then *explicitly* write the code to make the game understand the animation and model data exported from modelling programs.

It is common these days to have basically three steps to the pipeline: the artist works in some content authoring tool like Maya. The artist then exports their model to an "interchange" format, such as FBX or Collada. These are very generalized formats that can represent many kinds of data in many structured ways. These interchange files will be converted to the final representation loaded by the game, which may be highly optimized for precisely how the game wants to work with the data.

# Answer
> 0 votes
They pretty much store the coordinates in a binary file

What you described here is the COLLADA file format, or one of the morph formats (md1, md2, md4, etc.).

**COLLADA**

Collada supports animations by storing skeletal information about each state. It also needs to store weight information too. Because Collada is made to be a human-friendly format, it's pretty big compared to other formats.

If you want to know more about COLLADA, click here.

**MORPHs**

Any model file can be used in morph animation. The program reads in multiple mesh information for each model, then (usually with the GPU trough a vertex shader) interpolates between the values. If the format supports morph animation, like md1, then every state can be found in that one file, if not (e.g. .obj files), then it requires multiple files.

The more famous morph formats are the md1, and md2 formats, wich originally were made for QUAKE.

---
Tags: 3d, animation, art, file-format
---


# Question
Title: How could I access game data from a dev machine at runtime from a mobile platform?
When working on a game on a mobile platform, having read/write access to game data (assets, configuration files) stored on the dev machine at runtime would enable building of tools to quickly iterate, debug, and analyze the game at runtime.

For iOS & Android, is there any way to have access to these data files from the dev machine while the game is running on the mobile device?

Please do not recommend a tool, or a 3rd party engine that does this.

# Answer
> 1 votes
You generally need three things, basically, to accomplish this.

* First, you need a system in your game that can hot-reload assets or other data in response to some notification that the asset has changed. When a texture changes, you'll want to upload the new pixels to the GPU. When a monster description changes, you'll want to swap out the monster's old stats with the new ones. Et cetera. This is usually tied in to whatever system the game is already using for resource loading/caching/management.
* Second, you'll want to abstract the game's file IO operations so they talk through a virtual filesystem sort of API instead of directly reading files from the device storage. For the "shipping" version of the game you'd use an implementation that *did* just read files from the device storage, and which never sent any "file changed" notifications mentioned above (probably). For the development or iteration builds, you'd replace that with a version which talked over the network to a remote host and redirected all file IO to that host.
* Finally, you'll need some kind of editor shell or other wrapper running on the remote (desktop) machine; this machine looks for *actual* file changes to its files and sends notifications remotely to your game running on the mobile device that files have changed. It also probably implements the networking protocol that the game's remote virtual file system uses to talk with it and read the content of those files.

This also works well for consoles, not just mobile platforms. Even on games developed purely for desktops, it can be a useful collaborative editing tool.

Because of network latency issues you may need to be clever in how you transfer files; you may want to do some negotiating to make sure you always send files in an access-coherent manner, you may need to pre-send some files that you are pretty sure the device might need, or you might need to send only deltas of the changes. You'd have to do some experimentation.

However, this approach is used fairly often on current shipping and in-development titles/engines to achieve the kind of iteration improvements you're alluding to in your post.

---
Tags: android, ios, mobile, development-speed
---


# Question
Title: Finding cells within range on hexagonal grid
First up - I know I'm being super-dense here.

With that out of the way, I'm trying to write a C# implementation of this algorithm:

```
var results = []
for each -N ≤ dx ≤ N:
  for each max(-N, -dx-N) ≤ dy ≤ min(N, -dx+N):
    var dz = -dx-dy
    results.append(cube_add(center, Cube(dx, dy, dz)))

```

I've taken this from this tremendous resource.

My problem is that every implementation of this I've tried so far has had crazy results. For example, the code shown below currently results in this:

and this:

My code currently sits like this:

```
for (int x = this.CellPositionX - distance; x <= this.CellPositionX + distance; x++)
    {
        for (int y = this.CellPositionY - Math.Max(-distance, -x - distance); y <= this.CellPositionY + Math.Min(distance, -x + distance); y++)
        {
            HexPosition rangePosition = new HexPosition(x, y);
            range.Add(rangePosition);
        }
    }

```

Can anyone spot something awry here? All suggestions welcome. I've been banging my head on this one a while now.

Thanks!

Updated note: I am using Axial coordinates in the grid. Update #2: as pointed out below, I had my for..each loop wrong and wasn't using deltas for the working out. Thanks for the help!

I currently have an issue as shown below with the implementation from the answers:

I'm going to keep investigating - if I figure it out I'll post the full results back here. Thanks all!

# Answer
So upon further inspection your problem actually has nothing to do with coordinate system conversions. This could have been made more clear by not naming your axial coordinates X and Y but rather Q and R. The problem you're actually having is bad loop conditions. The original code sample produces delta q's and r's which you try to convert, in your for loops, to absolute coordinates and you made a mistake. The algorithm should look instead as follows:

```
for (int dx = -distance; dx <= distance; dx++)
{
    for (int dy = Math.Max(-distance, -dx - distance); dy <= Math.Min(distance, -dx + distance); dy++)
    {
        HexPosition rangePosition = new HexPosition(
            this.CellPositionX + dx, this.CellPositionY + dy);
        range.Add(rangePosition);
    }
}

```
> 4 votes

# Answer
As **Vector57** noted, the problem is you are using the **wrong coordinate system**. The algorithm described is meant to be used with **cube coordinates**, which have **x, y and z components**:

This may not be obvious from the algorithm's pseudocode, but that's because it's a simplification of this:

```
var results = []
for each -N ≤ dx ≤ N:
    for each -N ≤ dy ≤ N:
        for each -N ≤ dz ≤ N:
            if dx + dy + dz = 0:
                results.append(cube_add(center, Cube(dx, dy, dz)))

```

... a plain nested loop over x, y and z, what you'd expect from a range algorithm.

I don't know what coordinate system you are using, but I'm guessing it's one of the "offset coordinate" systems, which are popular because they are easy to implement by placing the grid cells inside a 2D array:

This doesn't mean you can't use these cube algorithms; it just means you need to convert from the cube coordinates to your own. For example, to convert to/from the "odd-q" vertical layout, use these:

```
# convert cube to odd-q offset
col = x
row = z + (x - (x&1)) / 2

# convert odd-q offset to cube
x = col
z = row - (col - (col&1)) / 2
y = -x-z

```
> 8 votes

---
Tags: c#, algorithm, hexagonal-grid
---


# Question
Title: Where to install game from my game launcher
I've created a game launcher that I'm pretty proud of :). I use nw.js and so the interface uses html/javascript/css. It makes ajax api calls to my web service that I've written in C# to do things like register/login/news. I'm now looking at having my game launcher do the initial install of the actual game and updates.

My question is, where should the game be installed by default. I will allow them to change the location but what should the default game location be? This will be on Windows only at this time. My concern is that I've heard (and I don't know because I'm always admin on my PC) that you can run into issues if your game is in program files because of permissions.

Does anyone who has made a game launcher have experience around the downloading/copying/unzipping of game files in a game launcher?

# Answer
You should store your game data in `C:\Users\username\AppData\Roaming\yourgame\` as it is a logical place to put "appdata" and it does not require admin to access .

You should give the user the option to decide if they want to have a desktop shortcut to the launcher. Include an easy way to do this without doing first time setup as well as a button to open the game directory.

The launcher file should do both first time setup and regular updates and launch for easy use.

Every time it launches it should make sure all of the required files exist; if some or all of them are missing, it should perform first time setup.

I'm not sure about Windows 7 or Windows 8 but in Windows 10, you can place a shortcut in `C:\Users\username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\` and it will appear in the start menu as a new/recently added app until it is clicked on and will always show up under all programs.

This way, no administrator rights needed!
> 2 votes

---
Tags: deployment, installer
---


# Question
Title: Is it possible to make/translate a 3d engine to ruby on rails?
I am looking to make a 3D FPS that runs inside web browsers. I looked into using WebGL, but it didn't seem far enough along into development. I decided on using RoR because Ruby was a language I knew.

I realize this may seem like a ridiculous question, but is there any way I can port/rewrite/whatever a game engine(Say for instance IrrLicht) to run inside Rails? Or for that matter, any other language on the web.

# Answer
Server-side web languages such as Ruby on Rails are used to generate/serve HTML, JavaScript and CSS. They receive a request from the browser, act on it to make the HTML response, and then send it to the browser and the transaction is done. With the exception of tricks like long polling, they don't do anything dynamic in the browser; that responsibility is left to JavaScript (or plugins).

It doesn't really make sense to port a 3D engine to Rails. When the browser requests a page, it could certainly fire up the 3D engine and render something... But then two things could happen:

* Render and send one frame to the browser. This could be useful for an adventure game perhaps, or some other non-realtime format.
* Render several frames and send them to the browser translated into JavaScript; then those frames would be played back to the user via JavaScript, as a pre-rendered animation.

You could issue multiple requests, but you certainly can't keep up 30 HTTP requests per second (unless you were operating in a LAN environment), nor *should* you, because the overhead would be ridiculous. So then you could look into something like WebSockets or Flash sockets or long polling to stream those frames. But then that begs the question, why are you doing the 3D rendering on the server?

Essentially **it would be an exercise in futility, or purely academic, or useful for a dynamically-rendered web adventure game**.

So yes, it does seem like a ridiculous question, but the answer is yes, you can "port/rewrite/whatever" a graphics engine to run in any language. **3D graphics is just math, it's matrices and vectors and... well, at its essence, that's about it.** But *realtime* 3D graphics will not be possible in pure Ruby in Rails without the assistance of something client-side like WebGL. And you would certainly want realtime 3D graphics for a first-person shooter.
> 6 votes

# Answer
The short answer: You need client-side scripting to make real-time games possible.

The long answer:

**What is a server?**

A server is a computer used to run services for other computers on a network.

**What is a web request**

A web request is what web servers handle. It is a request, often created by a user from home on a home computer, netbook or a smartphone, generally asking for a certain page. The server receives this request, runs the script (unless a static html file is requested) and returns a response that is normally a html file. The nature of this request is that it is like a short handshake, it happens and then it's over.

**What is Ruby on Rails?**

Ruby on rails is a scripting language, designed to run on a server and handle web requests. This is used to design web application much like this website.

Meaning, I want to read page: Is it possible to make/translate a 3d engine to ruby on rails?

The server(s) at the domain gamedev.stackexchange.com take my request and send me back the textual data I wanted formed into a html file that my browser can render. They run some sort of server-side script to collect all the pears of wisdom related to this question and organize them. This kind of script could be written in Ruby on Rails.

**What is a 3d engine**

It is software that provides real-time 3D rendering capabilities - if you ever played any of these 3d games you know that unlike a short handshake the games provide a constant steam of imagery directly to your monitor. This is very expensive in processing power, namely in GPU power. Most modern games demand enough graphical processing power to occupy one modern computer\*. You do not want to pay for that power nor do you have the software tools to attempt something like this. Ruby on Rails was not designed for that purpose. It is designed for the short handshake situation where the server sends one page and forgets about the client while moving on to the next request.

3d game engines run on the home computer, you RoR never runs or gets near a home computer. You need client-side scripting to make real-time games possible. You could start with Unity or ActionScript with Stage3D if you have some aversion towards webGL.

To be honest, if porting a 3d engine to some language is practical, someone has already done it and a 3d engine that is used with that language already exists.
> 4 votes

# Answer
Yes you can.

I always find it odd how good programmers think in terms of what can not be done. Anything is possible.

Porting a 3d Engine to rails may not be how this would work. Using Rails to handle the backend and organize code certainly would work. Like previously mentioned you could use WebGL in the HTML Rails supplies to the client. Rails has a nice MVC model so you could use Rails to generate and organize Views and Controls for the game.

Now that I am thinking about it, you could also use Rails to do the graphics processing server side, compress into a video stream, and stream it to the client. Which may be a viable solution for clients without WebGL support. But most Servers are CPU heavy, not GPU heavy. But it depends on the server and how many clients you need to support blah blah blah.
> 0 votes

---
Tags: web, first-person-shooter, ruby
---


# Question
Title: Unable to open project from a scene.unity file
The tutorial I'm following has provided its project files, and I'm trying to open them in Unity. Here is the project download link. You can also go to the tutorial webpage and scroll down to download.

I can't figure out how to do it. Here is what I've done.

a) Extract zip to my `Unity Scenes/` folder.

b) Open Unity, create a new project called `tutorial`

c) File -\> Open Scene -\> navigate to `Unity Scenes/voxeltut3/scene.unity`

d) Click Open

It opens.. but then I don't see any of the tutorial's files in my project. There's none of the c# scripts, no art, no prefabs... It's just the original empty project that I created.

I also tried importing it as a new package:

e) Assets -\> Import New Asset... -\> select `Unity Scenes/voxeltut3/scene.unity`

f) Click Import

And nothing happens. The Import New Asset dialogbox is still open with the scene.unity selected. It's like it's telling me that I've selected an invalid file. So I guess this is wrong?

How do I open this tutorial project? I'm using unity 5.3.2

This is the folder structure the **new Unity project** that it created for me:

`C:\Users\me\Documents\Unity Scenes`

```
tutorial/
    Assets/
    Library/
    ProjectSettings/

```

I unzipped the **tutorial files** in

`C:\Users\me\Documents\Unity Scenes`

```
voxeltut3/
    Materials/
        tiles.mat
        tiles.mat.meta
    Block.cs
    BlockAir.cs
    BlockGrass.cs
    scene.unity
    ... (other files)

```

# Answer
> 4 votes
Let's assume your Unity project is in:

`C:\Users\me\Documents\Unity Projects\My Voxel Project\`

(If you don't already have a project, start by opening Unity and clicking "+ New" when it asks which project you want to open)

Now, copy the contents of the tutorial to:

`C\Users\me\Documents\Unity Projects\My Voxel Project\Assets\`

You can create additional subfolders below `Assets` if you want to further organize your files, but **all "asset" files you want built into your game need to be somewhere in this folder**. This includes:

* scene files (.unity)
* models & animations
* texture & sprite images
* materials & shaders
* music & sound effects
* scripts
* plugins
* metadata for all of the above (.meta)

---

**Now, as for the error you get:**

> I've copied all the tutorial files into my tutorial/Assets/ folder. Now the project loads those files, but nothing is correct. The objet he created is supposed to have a script attached, but it says Missing (Mono Script). When I run the project, I get all sorts of errors like The variable chunkPrefab of World has not been assigned.

The reason for this (after looking at the zip) is that **the author neglected to include metadata files** in this particular zip.

Unity uses a unique ID stored in each ".meta" file to handle asset references, so that renaming one of your assets doesn't break any links to it in your scenes & prefabs.

If an asset doesn't have a meta file, Unity assumes it's new and generates one with an arbitrary ID. That leads to the unique ID for *your version* of `Chunk.cs` being different than the one the author used and saved in `scene.unity`, so Unity doesn't know how to resolve this reference.

**You can fix this** by working your way through the tutorial steps and replacing each missing reference as you go. Or you can check whether the downloads for any later steps in the tutorial include the missing meta files, and use those versions.

If you ever run into a situation like this without a tutorial to work through, you can sometimes reconstruct this data forensically by going to `Edit -> Project Settings -> Editor` and setting `Asset Serialization Mode` to `Force Text`

Then you can open the scene file in a text editor, infer from the serialized property names which script each Monobehaviour is meant to reference, and copy its GUID information into the corresponding meta file.

This will be a slog, and since the tutorial is available you won't have to do that here so I won't go into further detail, but I thought I should point out that it's possible.

---
Tags: unity
---


title: Collision detection with PyGame

text:
# Question
Title: Collision detection with PyGame
I have been making a 2d platformer using Python with PyGame. It has all be going good, but I have stumbled accross many problems with collision detection. Here they are:

1. You can't go through objects that have the exact space for you to go through
2. You can go through the ceiling (very weird)

The code I have is very big and I think that, since it involves multiple classes, I should post it on GitHub, so here is the link to my repository: https://github.com/pta2002/SuperBros.

But just for reference, here is my colliion detection method:

```
def detectCollisions(self, x1, y1, w1, h1, x2, y2, w2, h2):

    if x2 + w2 >= x1 >= x2 and y2 + h2 >= y1 >= y2:
        return 1

    elif x2 + w2 >= x1 + w1 >= x2 and y2 + h2 >= y1 >= y2:
        return 2

    elif x2 + w2 >= x1 >= x2 and y2 + h2 >= y1 + h1 >= y2:
        return 3

    elif x2 + w2 >= x1 + w1 >= x2 and y2 + h2 >= y1 + h1 >= y2:
        return 4

    else:
        return 0

```

and here is my update method:

```
def update(self, gravity, block_list):
    if self.velocity < 0:
        self.falling = True

    collision = 0
    blockX, blockY = 0, 0
    self.canMoveRight = True
    self.canMoveLeft = True

    for block in block_list:
        collision = self.detectCollisions(self.x, self.y, self.width, self.height,
         block.x, block.y, block.width, block.height)

        if not collision == 0:
            blockX = block.x
            blockY = block.y
            break

    if not collision == 0:
        if self.falling:
            self.falling = False
            self.onGround = True
            self.velocity = 0
            self.y = block.y - self.height
        else:
            if collision == 2:
                self.canMoveRight = False

            if collision == 1:
                self.canMoveLeft = False
    else:
        self.falling = True
        self.onGround = False

    if not self.onGround:
        self.velocity += gravity

    self.y -= self.velocity
    if (self.canMoveRight and self.xvel > 0) or (self.canMoveLeft and self.xvel < 0):
        self.x += self.xvel

    if self.jumping:
        if self.onGround:
            self.velocity = 8
            self.onGround = False

    if self.cur_image >= self.num_images - 1:
        self.cur_image = 0
    else:
        self.cur_image += 1

```

# Answer
The Pygame `Rect` already comes with a few collision detection functions that may just do what you need:

* `pygame.Rect.contains`: test if one rectangle is inside another
* `pygame.Rect.collidepoint`: test if a point is inside a rectangle
* `pygame.Rect.colliderect`: test if two rectangles overlap
* `pygame.Rect.collidelist`: test if one rectangle in a list intersects
* `pygame.Rect.collidelistall`: test if all rectangles in a list intersect
* `pygame.Rect.collidedict`: test if one rectangle in a dictionary intersects
* `pygame.Rect.collidedictall`: test if all rectangles in a dictionary intersect

Instead of having a `detectCollisions`method that takes `x1`, `y1`, `w1`, `h1`, `x2`, `y2`, `w2` and `h2`, at the sprite initialization you could set its `Rect`, move and blit the sprite using this same `Rect` as argument, **and** check for collisions with something as simple as:

```
sprite1.rect.colliderect(sprite2.rect)

```

From a A Newbie Guide to pygame:

> **Rects are your friends**.
>
> \[...\] I have to admit my favorite part of pygame is the lowly Rect class. A rect is simply a rectangle – defined only by the position of its top left corner, its width, and its height. Many pygame functions take rects as arguments, and they also take ‘rectstyles’, a sequence that has the same values as a rect. So if I need a rectangle that defines the area between 10, 20 and 40, 50, I can do any of the following:
>
> ```
> rect = pygame.Rect(10, 20, 30, 30)
> rect = pygame.Rect((10, 20, 30, 30))
> rect = pygame.Rect((10, 20), (30, 30))
> rect = (10, 20, 30, 30)
> rect = ((10, 20, 30, 30))
>
> ```
>
> If you use any of the first three versions, however, you get access to **Rect’s utility functions. These include functions to move, shrink and inflate rects, find the union of two rects, and a variety of collision-detection functions**.
>
> For example, suppose I’d like to get a list of all the sprites that contain a point (x, y) – maybe the player clicked there, or maybe that’s the current location of a bullet. It’s simple if each sprite has a .rect member – I just do:
>
> ```
> sprites_clicked = [sprite for sprite in all_my_sprites_list
>                    if sprite.rect.collidepoint(x, y)]
>
> ```
>
> Rects have no other relation to surfaces or graphics functions, other than the fact that you can use them as arguments. You can also use them in places that have nothing to do with graphics, but still need to be defined as rectangles. Every project I discover a few new places to use rects where I never thought I’d need them.

So unless you have a specific reason not to rely on Pygame `Rect` and its functions, my suggestion would be: don't reinvent the wheel, stick with it.

They might even make use of some internal c code that provides better performance then implementing a pure python approach, although I'm not sure about this specific point.
> 4 votes

---
Tags: collision-detection, python, pygame
---


title: shuffle a sprite group

text:
# Question
Title: shuffle a sprite group
Is there a way to shufle a group of sprites created with:

```
pygame.sprite.Group()

```

I have tried using random.shuffle but it apparently doesn't work on sprite groups.

# Answer
Since groups are an iterator, you can use:

```
sprs = list(spr_group)
random.shuffle(sprs)

```

You should not rely on Python's hashing order to randomize sprites for you. It is not a good RNG.
> 3 votes

# Answer
According to pygame documentation:

> The Sprites in the Group are not ordered, so drawing and iterating the Sprites is in no particular order. http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Group

I think the best you can do is not to use the Group, and make your own group mechanism. If you need only ordered update then use http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.OrderedUpdates
> 0 votes

# Answer
As other already said, the `sprite.Group` iterator yield its members in an unordered way (like a `dict`, not like a a `list`).

So if you're after a simple unordered list (not properly shuffled with a random method - if you want that follow user744's answer), just get what it gives by default.

The "problem" here is quite the contrary: how to get an ordered list of sprites from it (or a sprite by its index in the group)
> 0 votes

---
Tags: sprites, python, pygame
---


title: Destroy object on Collision

text:
# Question
Title: Destroy object on Collision
I have a strange problem... I need a 2D projectile to destroy itself after colliding with an object. I have used all of the different ways to do this on the internet but to no avail; the object always collides with the way but is never destroyed! This is my code:

```
public void OnCollisionEnter(Collision2D other)
{
    Destroy(gameObject);
}

```

The projectile is a prefab I made and it's attached to a controller I made for the main character. The console is giving me the error, "This message parameter has to be of type: " ... and I'm not sure what type is " ".

The projectile has a rigidBody2D attached to it and a circle collider. The wall is an empty object with an edge collider. I know that there is a collision because the projectile hits the wall and rolls down it. However, my function "public void OnCollisionEnter(Collision2D other)" is never activated, and I don't know why. I'm not sure what you mean by framework... I'm totally new to unity and programming.

When the object hits the wall it simply rolls down it and lands on the ground.

# Answer
You want the 2D version of the method: OnCollisionEnter2D

Collisions with a Collider2D/Rigidbody2D won't send the "OnCollisionEnter" message, only "OnCollisionEnter**2D**"
> 5 votes

---
Tags: unity, collision-detection, projectile-physics
---


# Question
Title: How to structure code for many unique weapons/spells/powers
I'm an inexperienced programmer creating a "roguelike-like" game in the vein of FTL, using Python (no PyGame as of yet as I'm still only concerned with text).

My game will contain a large number of weapons (around 50 for starters) that yield unique abilities. I am struggling to understand how to structure the object code in a way that is both powerful (in terms of allowing weapons to have radically different effects) and extensible (so that I can easily add more weapons later by eg. dropping them into a folder).

My first instinct was to have a BasicWeapon class, and have different weapons inherit from that class. However, this seems problematic to me: either I have to make the BasicWeapon class so barebones that it's basically useless (the only features all weapons have in common are name and type (pistol, axe, etc)), or I have to predict every unique effect I will ever come up with and code that into BasicWeapon.

The latter is clearly impossible, but the former can still be worked. However, that leaves me with the question: where do I put the code for individual weapons?

Do I create plasmarifle.py, rocketlauncher.py, swarmofbees.py, etc etc, and drop them all into a folder from where the game can import them?

Or is there a way to have a database-style file (maybe something as simple as an Excel spreadsheet) that somehow contains unique code for each weapon - without needing to resort to eval/exec?

In terms of the latter solution (database), I think the fundamental issue that I'm struggling with is that while I understand that it is desirable to maintain separation between code and data, I feel like the weapons blur the line between "code" and "data" a little bit; they represent the great variety of similar things that can be found in the game, in which sense they are like data, but most of them will require at least some unique code not shared with any other item, in which sense they are, naturally, code.

A partial solution I have found elsewhere on this site suggests giving the BasicWeapon class a bunch of empty methods - on\_round\_start(), on\_attack(), on\_move() etc - and then overriding those methods for each weapon. At the relevant phase of the combat cycle, the game will call the appropriate method for every character's weapon, and only the ones that have methods defined will actually do something. This helps, but it still does not tell me where I must put the code and/or data for each weapon.

Is there a different language or tool out there that I can use as a sort of half-data, half-code chimera? Am I completely butchering good programming practice?

My understanding of OOP is sketchy at best, so I would appreciate responses that are not *too* computer science-y.

**EDIT:** Vaughan Hilts has made it clear in his post below that what I'm essentially talking about is data-driven programming. The essence of my question is this: how can I implement a data-driven design in such a way that the data can contain scripts, enabling new weapons to do new things without changing the main program code?

# Answer
You want a data-driven approach almost certainly unless your game is going to be completely un-expected and/or procedural generated to the core.

Essentially, this involves storing information about your weapons in a markup language or file format of your choice. XML and JSON are both good, readable choices that can be used to make editing fairly simple without the need for complicated editors if you're just trying to get a quick start. (And Python can parse XML pretty easy, too!) You'd set attribute like 'power', 'defense', 'cost', and 'stats' that are all relevant. The way you structure your data will be up to you.

If a weapon needs to add a status effect, give it a Status effect node, and then specify the effects of a status effect through another data-driven object. This will make your code less reliant on the specific game and making editing and testing your game trivial. Not having to recompile all the time is a bonus, too.

Supplemental reading is available below:
> 17 votes

# Answer
(I'm sorry to submit the answer instead of a comment, but I don't have rep yet.)

Vaughan's answer is great, but I'd like to add my two cents.

One of the main reasons you'd want to use XML or JSON and parse it in runtime is to change and experiment with new values without having to recompile the code. As Python is interpreted and, in my opinion, pretty readable, you could have the raw data in a file with a dictionary and everything organized:

```
weapons = {
           'megaLazer' : {
                          'name' : "Mega Lazer XPTO"
                          'damage' : 100
                       },
           'ultraCannon' : {
                          'name' : "Ultra Awesome Cannon",
                          'damage' : 200
                       }
          }

```

This way you just import the file/module and use it as a normal dictionary.

If you want to add scripts, you can make use of the dynamic nature of Python and 1st class functions. You could do something like this:

```
def special_shot():
    ...

weapons = { 'megalazer' : { ......
                            shoot_gun = special_shot
                          }
          }

```

Although I believe that would be against data driven design. To be 100% DDD you'd have infomation (data) specifying what would be the functions and code that specific weapon would use. This way you don't break DDD, as you don't mix data with functionality.
> 7 votes

# Answer
# Data-Driven Design

I submitted something like this question to code review recently.

After some suggestions and improvements, the result was a simple code that would allow some relative flexibility on weapon creation based on a dictionary (or JSON). The data is interpreted at runtime and simple verifications are done by the `Weapon` class itself, without the need to rely on a whole script interpreter.

Data-Driven Design, despite Python being an interpreted language (both source and data files can be edited without the need to recompile them), sounds like the right thing to do in cases such as the one you presented. This question goes into more details about the concept, its pros and cons. Theres also a nice presentation on Cornell University about it.

Compared with other languages, such as C++, that would probably use a scripting language (such as LUA) to handle data x engine interaction and scripting in general, and a certain data format (like XML) to store the data, Python can actually do it all on its own (considering the standard `dict` but also `weakref`, the latter specifically for resource loading and caching).

An independent developer, however, may not take the data-driven approach to its extreme as suggested on this article:

> How much about data-driven design am I? I don't think a game engine should contain a single line of game-specific code. Not one. No hardcoded weapon types. No hardcoded HUD layout. No hardcoded unit AI. Nada. Zip. Zilch.

Maybe, with Python, one could benefit from the best of both object-oriented and data-driven approach, aiming for both productivity and extensibility.

# Simple sample processing

In the specific case discussed on code review, a dictionary would store both the "static attributes" and the logic to be interpreted - should the weapon have any conditional behavior.

On the example below a sword should have some abilities and stats in the hands of characters of the class 'antipaladin', and no effects, with lower stats when used by other characters):

```
WEAPONS = {
    "bastard's sting": {
        # magic enhancement, weight, value, dmg, and other attributes would go here.
        "magic": 2,

        # Those lists would contain the name of effects the weapon provides by default.
        # They are empty because, in this example, the effects are only available in a
        # specific condition.
        "on_turn_actions": [],
        "on_hit_actions": [],
        "on_equip": [
            {
                "type": "check",
                "condition": {
                    'object': 'owner',
                    'attribute': 'char_class',
                    'value': "antipaladin"
                },
                True: [
                    {
                        "type": "action",
                        "action": "add_to",
                        "args": {
                            "category": "on_hit",
                            "actions": ["unholy"]
                        }
                    },
                    {
                        "type": "action",
                        "action": "add_to",
                        "args": {
                            "category": "on_turn",
                            "actions": ["unholy aurea"]
                        }
                    },
                    {
                        "type": "action",
                        "action": "set_attribute",
                        "args": {
                            "field": "magic",
                            "value": 5
                        }
                    }
                ],
                False: [
                    {
                        "type": "action",
                        "action": "set_attribute",
                        "args": {
                            "field": "magic",
                            "value": 2
                        }
                    }
                ]
            }
        ],
        "on_unequip": [
            {
                "type": "action",
                "action": "remove_from",
                "args": {
                    "category": "on_hit",
                    "actions": ["unholy"]
                },
            },
            {
                "type": "action",
                "action": "remove_from",
                "args": {
                    "category": "on_turn",
                    "actions": ["unholy aurea"]
                },
            },
            {
                "type": "action",
                "action": "set_attribute",
                "args": ["magic", 2]
            }
        ]
    }
}

```

For testing purposes, I created simple `Player` and `Weapon` classes: the first to hold/equip the weapon (thus calling its conditional on\_equip setting) and the latter as a single class that would retrieve the data from the dictionary, based on the item name passed as an argument during the `Weapon`initialization. They do not reflect the proper game classes design, but can still be useful to test the data:

```
class Player:
    """Represent the player character."""

    inventory = []

    def __init__(self, char_class):
        """For this example, we just store the class on the instance."""
        self.char_class = char_class

    def pick_up(self, item):
        """Pick an object, put in inventory, set its owner."""
        self.inventory.append(item)
        item.owner = self

class Weapon:
    """A type of item that can be equipped/used to attack."""

    equipped = False
    action_lists = {
        "on_hit": "on_hit_actions",
        "on_turn": "on_turn_actions",
    }

    def __init__(self, template):
        """Set the parameters based on a template."""
        self.__dict__.update(WEAPONS[template])

    def toggle_equip(self):
        """Set item status and call its equip/unequip functions."""
        if self.equipped:
            self.equipped = False
            actions = self.on_unequip
        else:
            self.equipped = True
            actions = self.on_equip

        for action in actions:
            if action['type'] == "check":
                self.check(action)
            elif action['type'] == "action":
                self.action(action)

    def check(self, dic):
        """Check a condition and call an action according to it."""
        obj = getattr(self, dic['condition']['object'])
        compared_att = getattr(obj, dic['condition']['attribute'])
        value = dic['condition']['value']
        result = compared_att == value

        self.action(*dic[result])

    def action(self, *dicts):
        """Perform action with args, both specified on dicts."""
        for dic in dicts:
            act = getattr(self, dic['action'])
            args = dic['args']
            if isinstance(args, list):
                act(*args)
            elif isinstance(args, dict):
                act(**args)

    def set_attribute(self, field, value):
        """Set the specified field with the given value."""
        setattr(self, field, value)

    def add_to(self, category, actions):
        """Add one or more actions to the category's list."""
        action_list = getattr(self, self.action_lists[category])

        for action in actions:
            if action not in action_list:
                action_list.append(action)

    def remove_from(self, category, actions):
        """Remove one or more actions from the category's list."""
        action_list = getattr(self, self.action_lists[category])

        for action in actions:
            if action in action_list:
                action_list.remove(action)

```

With some future improvement I hope that this will even allow me to have a dynamic crafting system someday, processing weapon components instead of whole weapons...

# Test

1. Character A picks weapon, equip it (we print its stats), then drop it;
2. Character B picks the same weapon, equip it (and we print its stats again to show how they are different).

Like this:

```
def test():
    """A simple test.

    Item features should be printed differently for each player.
    """
    weapon = Weapon("bastard's sting")
    player1 = Player("bard")
    player1.pick_up(weapon)
    weapon.toggle_equip()
    print("Enhancement: {}, Hit effects: {}, Other effects: {}".format(
        weapon.magic, weapon.on_hit_actions, weapon.on_turn_actions))
    weapon.toggle_equip()

    player2 = Player("antipaladin")
    player2.pick_up(weapon)
    weapon.toggle_equip()
    print("Enhancement: {}, Hit effects: {}, Other effects: {}".format(
        weapon.magic, weapon.on_hit_actions, weapon.on_turn_actions))

if __name__ == '__main__':
    test()

```

It should print:

*For a bard*

> Enhancement: 2, Hit effects: \[\], Other effects: \[\]

*For a antipaladin*

> Enhancement: 5, Hit effects: \['unholy'\], Other effects: \['unholy aurea'\]
> 4 votes

---
Tags: python, objects, data-driven
---


title: Problem with trigger

text:
# Question
Title: Problem with trigger
I am making a melee attack with my game, but I'm stuck in a problem related to using triggers. The enemy NPCs have a sphere collider set on trigger so I will know who is inside their range (radius of 15).

Then, I wrote a simple OnTriggerEnter script to make that when my sword (its collider is set to trigger as well, so it will pass through the enemy) hits an enemy NPC, it will destroy that enemy. The problem is that when I test it, the enemies are destroyed once I enter their sphere collider.

So, is there a way to ignore the trigger from their shpere collider? Or what is the best way to do a melee attack?

NOTE: the destroy function is public in the enemy script and it was called in weapon script attached to the weapon.

# Answer
Not sure if I understand the question correctly, but let's try. Add an empty child to your hero character and add the sphere collider to this empty object.Add this object to a layer of it's own , e.g "radar". Let's say your enemy are assigned layer "enemy". Now, go to Edit-\>Project Settings-\>Physics and, set the matrix so that the "radar" does not collide with any layer other than "enemy".

Now, radar will have a collision detection script that will return the object with which it collided. The hero script will call this method to check if radar collided with anything and if it did, what did it collide with.
> 1 votes

# Answer
Well, it is most probably because you have your Trigger (Sphere) collider attached to the same object where your Sword would work. So it is showing the same behaviour as sword hits the enemy, because of same object and script.

What you can do is ,

* Make a parent gameobject in which player and another gameobject should exist as children.
* Attach two scripts separately on both (sword and sphere).
* Move parent as first person.

In this way you can get different trigger events for sword and sphere.

Hope this helps.
> 0 votes

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


# Question
Title: Pathfinding: longest route along tiles of same type
I'm programming a simple tile-based puzzle game, and I've gotten stuck trying to work out a pathfinding algorithm.

Here's how the game is set out:

* The game board is (arbitrarily) 8 tiles wide by 8 tiles tall.
* Each tile can be one of four types (shown below as red, green, blue and yellow)
* Additionally, a tile could be a *reactor* (the starting point of a path - this will become clear later on)

The board would look something like this:

(The reactors are the circles; the other tiles have no special properties.)

What I need to do is: starting from a reactor, trace the longest path along adjoining tiles of the same color as the reactor. Something like this:

The blue reactor is simple(ish) as its path doesn't branch. However, as you can see from the green reactor's start position, its path can branch two ways at the start (up or down), and take a detour midway through.

The path I'm looking for is the longest one, so that's the one that's highlighted in the screengrab (the first path only crosses two tiles, and the detour midway results in a sorter path).

When certain conditions have been fulfilled, the reactor will cause all the tiles in the longest path (where the arrows cross in the diagram) to disappear and be replaced with new ones. All other tiles will remain in place, including the extraneous green tiles adjacent to the green reactor's path.

I'm guessing something like a modified flood fill would work, but I'm not really sure how to start.

If it makes any difference, I'm using Swift to write the game.

The tiles are stored in an approximation of a 2D array (Swift doesn't have a robust native implementation of that yet, so I'm using the one described in this tutorial). They're retrieved using `tile[column, row]`.

**----------EDIT 2/12/2016----------**

With some help from a friend, I've written a recursive function that *should* return the longest path. It's looping through correctly, but it's not pruning shorter branches from the `longestPath` array.

Can anyone see where I'm going wrong in this code?

Here's the recursive function:

```
func pathfinder(startingTile: Tile, pathToThisPoint: Chain, var iteration: Int? = 1) -> Chain
{
    var longestPath: Chain? = nil

    var availableTiles = getNeighbouringTiles(startingTile)

    for var nextTile = 0; nextTile < availableTiles.count; nextTile++
    {
        let column = availableTiles[nextTile].column
        let row = availableTiles[nextTile].row

        if tiles[column, row]!.tileType == startingTile.tileType && (tiles[column, row]!.isReactor == false || startingTile.isReactor)
        {
            // if we haven't been here before
            if !pathToThisPoint.tiles.contains(tiles[column, row]!)
            {
                print(iteration)
                iteration = iteration! + 1

                // add this tile to the pathtothispoint
                // go to the next unexplored tile (recurse this function)
                pathToThisPoint.tiles.append(tiles[column, row]!)

                let tempPath = pathfinder(tiles[column, row]!, pathToThisPoint: pathToThisPoint)

                // if the resulting path is longer...
                if tempPath.tiles.count > longestPath?.tiles.count
                {
                    // then tempPath is now the longest path
                    longestPath = tempPath

                }
            }
        }

        if longestPath != nil
        {
            return longestPath!
        }
        else
        {
            return pathToThisPoint
        }
    }

```

It's dependent on the getNeighboringTiles function (shown below) that returns an array of valid tiles of the same type, excluding reactors:

```
func getNeighbouringTiles(tile: Tile, previousTile: Tile? = nil) -> Array<Tile>
{
    var validNeighbouringTiles = Array<Tile>()
    var neighbourTile: Tile
    // check top, right, bottom, left
    if tile.row < NumRows - 1
    {
        neighbourTile = tiles[tile.column, tile.row + 1]!
        if neighbourTile.tileType == tile.tileType && !neighbourTile.isReactor && (previousTile == nil || previousTile != neighbourTile)
        {
            validNeighbouringTiles.append(neighbourTile)
        }
    }
    if tile.column < NumColumns - 1
    {
        neighbourTile = tiles[tile.column + 1, tile.row]!
        if neighbourTile.tileType == tile.tileType && !neighbourTile.isReactor && (previousTile == nil || previousTile != neighbourTile)
        {
            validNeighbouringTiles.append(neighbourTile)
        }
    }
    if tile.row > 0
    {
        neighbourTile = tiles[tile.column, tile.row - 1]!
        if neighbourTile.tileType == tile.tileType && !neighbourTile.isReactor && (previousTile == nil || previousTile != neighbourTile)
        {
            validNeighbouringTiles.append(neighbourTile)
        }
    }
    if tile.column > 0
    {
        neighbourTile = tiles[tile.column - 1, tile.row]!
        if neighbourTile.tileType == tile.tileType && !neighbourTile.isReactor && (previousTile == nil || previousTile != neighbourTile)
        {
            validNeighbouringTiles.append(neighbourTile)
        }
    }
    // if we get this far, they have no neighbour
    return validNeighbouringTiles
}

```

The Tile class looks like this (methods omitted for brevity):

```
class Tile: CustomStringConvertible, Hashable
{
    var column:Int
    var row:Int
    var tileType: TileType // enum, 1 - 4, mapping to colors
    var isReactor: Bool = false

    // if the tile is a reactor, we can store is longest available path here
    var reactorPath: Chain! = Chain()
}

```

And finally, the chain class looks like this (again, methods omitted for brevity):

```
class Chain {
    // The tiles that are part of this chain.
    var tiles = [Tile]()

    func addTile(tile: Tile) {
        tiles.append(tile)
    }

    func firstTile() -> Tile {
        return tiles[0]
    }

    func lastTile() -> Tile {
        return tiles[tiles.count - 1]
    }

    var length: Int {
        return tiles.count
    }
}

```

# Answer
> 3 votes
If I am not mistaken these types of problems are usually solved by backtracking family of algorithms.
I would use an algorithm similar to DFS: recursively search the solutions tree and whenever leaf node is reached, save the path if it was the longest discovered. After reaching leaf node, backtrack to last "crossroads" and take the other turn(s). In order to prevent infinite loops you will also need to mark visited/searched nodes.

---

edit: adding C++ code example what I had in mind. I would maintain two integers forward and backward depth, first one being used to detect maximal depth found and as tile index in path, while the second is used to to detect backtracking from furthest path:

```
//simplified tile
struct Tile {
  int x,y,type;
  bool used;
}
//check for correct coords, same type and is not used. if not valid, return null
Tile* getValidTileAt(int x, int y, int type) { ... }

std::vector<Tile*> findLongestPath(Tile& tile) {
  std::vector<Tile*> path;//or pre-allocate array "long enough"
  int max_depth = -1;
  search(tile.x, tile.y, type, 0, max_depth, path);
  return path;
}
//max_depth must be globally available as well as the path -> passing refrences
int search(int x, int y, int type, int depth, int& max_depth, std::vector<Tile*>& path)
{
  var tile = getValidTileAt(x, y, type);
  if(!tile) return depth - 1; //not valid tile, return
  tile->used = true; //maintain used flag any way you find fit
  int branch_max = depth;
  if(branch_max > max_depth) //found new furthest tile
  {
    max_depth = branch_max;
    path.push_back(tile);//or if(branch_max  == depth) path.reserve(depth +1);
  }
  //search neighbours in *set order*
  branch_max = max(branch_max , search(x, y - 1, type, depth + 1, max_depth, path));
  branch_max = max(branch_max , search(x - 1, y, type, depth + 1, max_depth, path));
  branch_max = max(branch_max , search(x, y + 1, type, depth + 1, max_depth, path));
  branch_max = max(branch_max , search(x + 1, y, type, depth + 1, max_depth, path));

  //backtracking from longest branch, overwrite path
  if(branch_max == max_depth) path[depth] = tile;
  tile->used = false;
  return branch_max;
}

```

*note: did not run the code crtl+c/v at on risk*

---
Tags: ios, tiles, path-finding, swift
---


# Question
Title: AS3/Flash Develop - Radial Gravity (character on planet simulation)
I am trying to create a program where a character shape will be constantly drawn towards the centre of a planet shape. I have taken on previous advice into using physics equations to generate the desired effect yet I think I am missing some and therefore it does not work (I am only using v^2=u^2+2as). Am I over complicating things? All I need is for the player object to be constantly drawn towards the centre of the planet object; there will be no need for other planet objects to come into play and affect the player's gravity.

edit: To clarify, my question should have been "where did I go wrong?". I have now since solved the problem with the answers posted below, which were present because I wasn't going about trying to achieve what I wanted the right way. I didn't calculate the actual direction to move in as expected, and so the character could not move in the expected direction.

Here is my Main.as:

```
package
{
import flash.display.InteractiveObject;
import flash.display.Sprite;
import flash.events.Event;
import Math
import flash.display.Bitmap;
import flash.display.DisplayObject;
import flash.events.KeyboardEvent;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.utils.*;

/**
 * ...
 * @author Me
 */
public class Main extends Sprite
{
    public var planet1:Planet;
    public var character1:Character;
    public var initialXVelocity:Number = 0;
    public var initialYVelocity:Number = 0;
    public var finalXVelocity:Number;
    public var finalYVelocity:Number;
    public const gravitationalAcceleration:Number = 3;
    public var xDistance:Number;
    public var yDistance:Number;

    public function Main()
    {
        if (stage) init();
        else addEventListener(Event.ADDED_TO_STAGE, init);
    }

    private function init(e:Event = null):void
    {
        removeEventListener(Event.ADDED_TO_STAGE, init);
        // entry point
        planet1 = new Planet;
        character1 = new Character;

        //place entites in position to test note: planet 1 is 100*100 pixels, character 1 is 10*10 pixels
        planet1.x = 350;
        planet1.y = 250;
        character1.y = 100; //295
        character1.x = 396; //395
        addChild(planet1);
        addChild(character1);

        //Make sure character has gravity applied constantly
        setInterval(playerMove, 1000);

    }

    public function playerMove():void
    {
        //Calculate the distance between the character and the planet in terms of x and y coordinate
        xDistance = (character1.x + 5) - (planet1.x + 50);
        yDistance = (character1.y + 5) - (planet1.y + 50);

        //Make sure this distance is a positive value
        if (xDistance < 0) {
            xDistance = -xDistance;
        }

        if (yDistance < 0) {
            yDistance = -yDistance;
        }

        //Calculate velocity using physics equation v^2=(u^2)+2as
        finalXVelocity = Math.sqrt((initialXVelocity * initialXVelocity) + (2 * gravitationalAcceleration) * xDistance);
        finalYVelocity = Math.sqrt((initialYVelocity * initialYVelocity) + (2 * gravitationalAcceleration) * yDistance);
        /*trace(initialXVelocity);
        trace(gravitationalAcceleration);
        trace(xDistance);
        trace(finalXVelocity);
        trace(initialYVelocity);
        trace(gravitationalAcceleration);
        trace(yDistance);
        trace(finalYVelocity);*/

        //Make sure the character is moving towards the centre of the planet at all times by reversing the appropriate velocity once it passes the axis of the centre of the planet
        if (planet1.x < character1.x) {
            finalXVelocity = -finalXVelocity;
        }

        if (planet1.y < character1.y) {
            finalYVelocity = -finalYVelocity;
        }

        //Update the current velocity before new velocity is calculated
        initialXVelocity = finalXVelocity;
        initialYVelocity = finalYVelocity;

        //Send the character into the correct direction
        character1.x += finalXVelocity;
        character1.y += finalYVelocity;
    }

}

}

```

# Answer
I'll use vector notation to be concise. You can translate this into individual vectorX and vectorY numbers if you're not using a vector math library, just be careful to calculate the length below using both components.

```
// Get a vector pointing into the planet.
Vector offset = planetPosition - playerPosition;

// Note that x & y aren't separable:
// you need to consider them together to get the length
// (Pythagorean theorem)
float distance = length(offset);

// Scale the vector to unit length.
Vector direction = offset/length;

// To get constant acceleration regardless of distance:
// (near surface approximation)
Vector acceleration = gravityStrength * direction;

// OR, to get Newtonian gravitation:
// (weaker further away, following inverse square law)
Vector acceleration = gravityStrength * direction/(length * length);

// Euler integration for simplicity.
// Other options work too.
playerVelocity += acceleration * deltaTime;

playerPosition += velocity * deltaTime;

```
> 1 votes

---
Tags: physics, actionscript-3, flashdevelop
---


# Question
Title: How do I make an on-screen HUD in libgdx?
I'm new to libgdx, and I am finding I am getting stumped by the simplest of things. It seems to want me to do things a specific way, but the documentation won't tell me what that is.

I want to make a very simple 2d game in which the player controls a spaceship. The mouse wheel will zoom in and out, and information and controls are displayed on the screen.

But I can't seem to make the mouse wheel NOT zoom the UI. I've tried futzing with the projection matrices in between

Here's my (current) code:

```
public class PlayStage extends Stage {
...
    public void draw() {
    // tell the camera to update its matrices.
    camera.update();

    // tell the SpriteBatch to render in the
    // coordinate system specified by the camera.
    spriteBatch.setProjectionMatrix(camera.combined);

    spriteBatch.begin();

    aButton.draw(spriteBatch, 1F);

    playerShip.draw(spriteBatch, 1F);

    spriteBatch.end();
}
}

```

camera.zoom is set by scrolled(int amount).

I've tried about a dozen variations on the theme of changing the camera's projection matrix after the button is drawn but before the ship is, but no matter what I do, the same things happen to both the button and the ship. So:

What is the usual libgdx way of implementing an on-screen UI that isn't transformed by the camera's projection matrix/zoom?

# Answer
You can just use another SpriteBatch without setting projection matrix to draw the HUD,

```
camera.update();
spriteBatch.setProjectionMatrix(camera.combined);
spriteBatch.begin();
aButton.draw(spriteBatch, 1F);
playerShip.draw(spriteBatch, 1F);
spriteBatch.end();

hudBatch.begin();
//Draw using hudBatch
hudBatch.end();

```
> 19 votes

# Answer
I think the easiest way to accomplish a hud map would be to use a second camera and overlay them. This issue has been discussed on the libgdx forums a while back and I remember someone over there posting their hud code. You may want to poke around over there and see what you come up with.
> 8 votes

# Answer
Here is a method I use for working with a single batch:

First draw everything else, then draw your HUD last:

```
Matrix4 uiMatrix = cam.combined.cpy();
uiMatrix.setToOrtho2D(0, 0, WIDTH, HEIGHT);
batch.setProjectionMatrix(uiMatrix);
batch.begin();

```

If you want to draw more after, make sure you reset the projection matrix to whatever it needs to be.
> 6 votes

# Answer
I have done it like this:

First i have created a new Class called Hud. It implements `Disposable` because of the resource management. Then you need to define a `Stage` for your content and a new `viewport` because a new camera will be used. You need to define a new `Table`that you can add to the `Stage`. You can add your content to the `table` like usual. The rest of the code i will put to show how it works is game specific so just ignore it.

```
public class Hud implements Disposable{

public Stage stage;
private Viewport viewport;

//score && time tracking variables
private Integer worldTimer;
private float timeCount;
private static Integer score;
private boolean timeUp;

//Scene2D Widgets
private Label countdownLabel, timeLabel, linkLabel;
private static Label scoreLabel;

public Hud (SpriteBatch sb){
    //define tracking variables
    worldTimer = 250;
    timeCount = 0;
    score = 0;

    //setup the HUD viewport using a new camera seperate from gamecam
    //define stage using that viewport and games spritebatch
    viewport = new FitViewport(GetTheTriforce.V_WIDTH, GetTheTriforce.V_HEIGHT, new OrthographicCamera());
    stage = new Stage(viewport, sb);

    //define labels using the String, and a Label style consisting of a font and color
    countdownLabel = new Label(String.format("%03d", worldTimer), new Label.LabelStyle(new BitmapFont(), Color.WHITE));
    scoreLabel =new Label(String.format("%06d", score), new Label.LabelStyle(new BitmapFont(), Color.WHITE));
    timeLabel = new Label("LEFTOVER TIME", new Label.LabelStyle(new BitmapFont(), Color.WHITE));
    linkLabel = new Label("POINTS", new Label.LabelStyle(new BitmapFont(), Color.WHITE));

    //define a table used to organize hud's labels
    Table table = new Table();
    table.top();
    table.setFillParent(true);

    //add labels to table, padding the top, and giving them all equal width with expandX
    table.add(linkLabel).expandX().padTop(10);
    table.add(timeLabel).expandX().padTop(10);
    table.row();
    table.add(scoreLabel).expandX();
    table.add(countdownLabel).expandX();

    //add table to the stage
    stage.addActor(table);

}

public void update(float dt){
    timeCount += dt;
    if(timeCount >= 1){
        if (worldTimer > 0) {
            worldTimer--;
        } else {
            timeUp = true;
        }
        countdownLabel.setText(String.format("%03d", worldTimer));
        timeCount = 0;
    }
}

public static void addScore(int value){
    score += value;
    scoreLabel.setText(String.format("%06d", score));
}

@Override
public void dispose() { stage.dispose(); }

public boolean isTimeUp() { return timeUp; }

public static Label getScoreLabel() {
    return scoreLabel;
}

public static Integer getScore() {
    return score;
}

```

}

and then in the Playscreen like this:

first of all you need a variable to reference your hud like:

```
private Hud hud;

```

and then in the constructor you create an new instance of your class:

```
hud= new Hud();

```

in the update- method you need to put these lines of code since i think you want to display some game information like points or the lives left:

```
hud.update();

```

in the render- method do this:

```
//Set batch to now draw what the Hud camera sees.
game.batch.setProjectionMatrix(hud.stage.getCamera().combined);
hud.stage.draw();

```

and at the end don't forget to dispose your hud in the dispose- method

i hope that helps
> 5 votes

# Answer
Remember, the first camera is where the background is fixed. The second one is where the ground moves. If you're wondering why the sprite moves in the stage because the secret it the ground that moves. The sprite is just walking in place since you're using a third camera. You might scrolled the second camera's ground but the HUD is still in place on third. Promise, it's true! The third camera is where the it displays the sprite in center for direction, whether he goes left or right by a little animation code, and the HUD (i.e. score, remaining lives, item used). If you need something, ask me.
> 1 votes

---
Tags: libgdx
---


# Question
Title: Creating a highlight halo around a selected object
I'm looking to create a halo highlight around the selected objects in my game screen. The main platform is android, but I am writing an iOS version as well, updating it whenever I successfully add the next feature.

I am trying to ensure that the game is capable of working in both OpenGLES 1 and 2, but of course I expect v2 to have more effects eventually.

The effect I want to achieve is to have a halo around the edge of the selected object (I believe Diablo II did something similar). In theory my idea is to render the scene, enabling stencil ops when the selected object is rendered then enable stencil testing, disable depth and set an orthogonal projection and draw the halo colour 5 pixels larger in each of the X and Y dimensions from the object's centre with 0.2 alpha then successively draw again reducing the size and blending.

Using this method, I also need to figure out the most efficient way of determining the centre and extents of the objects.

EDIT: Another technique I just thought of after posting is, after the stencil op render, render a coloured ortho rectangle to texture through the stencil then shrink and re-enlarge the image to blur the edges then render the resultant texture back on top of the scene, around the stencilled area

1. Are either of these a good/efficient way to achieve the effect? Is there a better/faster/more efficient/more common way of doing this?
2. Should I bother doing it for v1 and make it a v2 only effect?
3. Should I bother with v1 at all if I want these sorts of effects?

# Answer
> 1 votes
Are you using 3D? Then you could just add slightly scaled versions of the same object wich are coloured in your halo colour and have 0.2 alpha. Then just render the real object after all these halo-objects

# Answer
> 3 votes
This question popped to the top because of Aeroson's answer (above/below/adjacent/falling in bits around this one) and thought I'd yoink my answer from this question in the event that it was useful to someone.

What the below shader does:

Downsides:

* not a mobile-friendly shader, due to using the stencil buffer and rendering the object twice (depending on the capabilities of the device in question this may be acceptable).
* requires forward lighting (Stencil functionality for objects rendered in the deferred rendering path is somewhat limited, as during the base pass and lighting pass the stencil buffer is used for other purposes).
* does not render the object itself (though possibly fixable by tweaking the geometry output).

I realize this question specifically asked for mobile solutions, however the more general "draw an outline around an object" question is very common and I spent a number of hours looking for a good solution and ended up having to write this shader by hand because the common solutions were insufficient for my needs.

```
Shader "Stencil/Outline"
{
    Properties
    {
        _Color("Color", Color) = (1,0,0,1)
        _Thickness("Thickness", float) = 4
    }
    SubShader
    {

        Tags { "Queue"="Geometry" "IgnoreProjector"="True" "RenderType"="Transparent" }
        Blend SrcAlpha OneMinusSrcAlpha
        Cull Back
        ZTest always
        Pass
        {
            Stencil {
                Ref 1
                Comp always
                Pass replace
            }
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma multi_compile_fog

            #include "UnityCG.cginc"

            struct v2g
            {
                float4  pos : SV_POSITION;
                float2  uv : TEXCOORD0;
                float3 viewT : TANGENT;
                float3 normals : NORMAL;
            };

            struct g2f
            {
                float4  pos : SV_POSITION;
                float2  uv : TEXCOORD0;
                float3  viewT : TANGENT;
                float3  normals : NORMAL;
            };

            v2g vert(appdata_base v)
            {
                v2g OUT;
                OUT.pos = mul(UNITY_MATRIX_MVP, v.vertex);
                OUT.uv = v.texcoord;
                OUT.normals = v.normal;
                OUT.viewT = ObjSpaceViewDir(v.vertex);

                return OUT;
            }

            half4 frag(g2f IN) : COLOR
            {
                //this renders nothing, if you want the base mesh and color
                //fill this in with a standard fragment shader calculation
                return 0;
            }
            ENDCG
        }
        Pass
        {
            Stencil {
                Ref 0
                Comp equal
            }
            CGPROGRAM
            #include "UnityCG.cginc"
            #pragma target 4.0
            #pragma vertex vert
            #pragma geometry geom
            #pragma fragment frag

            half4 _Color;
            float _Thickness;

            struct v2g
            {
                float4 pos : SV_POSITION;
                float2 uv : TEXCOORD0;
                float3 viewT : TANGENT;
                float3 normals : NORMAL;
            };

            struct g2f
            {
                float4 pos : SV_POSITION;
                float2 uv : TEXCOORD0;
                float3 viewT : TANGENT;
                float3 normals : NORMAL;
            };

            v2g vert(appdata_base v)
            {
                v2g OUT;
                OUT.pos = mul(UNITY_MATRIX_MVP, v.vertex);

                OUT.uv = v.texcoord;
                OUT.normals = v.normal;
                OUT.viewT = ObjSpaceViewDir(v.vertex);

                return OUT;
            }

            void geom2(v2g start, v2g end, inout TriangleStream<g2f> triStream)
            {
                float thisWidth = _Thickness/100;
                float4 parallel = end.pos-start.pos;
                normalize(parallel);
                parallel *= thisWidth;

                float4 perpendicular = float4(parallel.y,-parallel.x, 0, 0);
                perpendicular = normalize(perpendicular) * thisWidth;
                float4 v1 = start.pos-parallel;
                float4 v2 = end.pos+parallel;
                g2f OUT;
                OUT.pos = v1-perpendicular;
                OUT.uv = start.uv;
                OUT.viewT = start.viewT;
                OUT.normals = start.normals;
                triStream.Append(OUT);

                OUT.pos = v1+perpendicular;
                triStream.Append(OUT);

                OUT.pos = v2-perpendicular;
                OUT.uv = end.uv;
                OUT.viewT = end.viewT;
                OUT.normals = end.normals;
                triStream.Append(OUT);

                OUT.pos = v2+perpendicular;
                OUT.uv = end.uv;
                OUT.viewT = end.viewT;
                OUT.normals = end.normals;
                triStream.Append(OUT);
            }

            [maxvertexcount(12)]
            void geom(triangle v2g IN[3], inout TriangleStream<g2f> triStream)
            {
                geom2(IN[0],IN[1],triStream);
                geom2(IN[1],IN[2],triStream);
                geom2(IN[2],IN[0],triStream);
            }

            half4 frag(g2f IN) : COLOR
            {
                _Color.a = 1;
                return _Color;
            }

            ENDCG

        }
    }
    FallBack "Diffuse"
}

```

# Answer
> 2 votes
The idea is that you extrude the object vertices along their normals.

First render highlight:

* Render the object with disabled z write but enabled z test.
* Vertex shader: to each vertex add normal * highlight size before you pass it on
* Fragment shader: render only color, don't apply lighting

Then render the object:

* Render with z write and z test enabled.
* Render with your normal shaders.
* The object will render on top of it's highlight leaving only edges highlighted.

Here is nice tutorial video for Unity3D completely with shader sources: https://www.youtube.com/watch?v=00qMZlacZQo

It renders sharp highlights, I have no idea how to effectively blur them. Maybe from vertex to fragment you can pass the real vertex position and use the distance to change alpha. But that won't help since the position will be interpolated as well? Maybe use concept from Single-Pass Wireframe Rendering.

---
Tags: 3d, opengl-es, graphic-effects
---


# Question
Title: Why can't I store a value in transform.position.y?
Well I have this line of code

```
            Vector3 pos = cell.CellPosition;
            float light1Height = 10f;
            pos.y = light1Height;

            lightGameObject.transform.position.y = light1Height;
            lightGameObject.transform.position.x = pos.x;
            lightGameObject.transform.position.z = pos.z;

```

The error states that

Cannot modify a value type return of 'UnityEngine.Transform.position". Consider storing the value in a temporary variable.

What should i do? Thanks!

# Answer
> 3 votes
Getting the property transform.position returns you **a copy** of the Vector3 position. Modifying the copy won't modify the original struct. You should therefore create a new Vector3 and replace the current position with it.

```
lightGameObject.transform.position = new Vector3(pos.x, light1Height, pos.z);

```

You can also store the value in a temporary variable.

```
Vector3 position = lightGameObject.transform.position;
position.y = light1Height;
position.x = pos.x;
position.z = pos.z;
lightGameObject.transform.position = position;

```

# Answer
> 2 votes
In C# when a struct is accessed via a getter (like transform.position), the compiler won't allow you to modify a member, because it has no sense to do that, because a getter of a struct return a brand new struct that you have to reference first. If you don't your brand new struct will stay inaccessible...

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


title: How does one calculate color intensity?

text:
# Question
Title: How does one calculate color intensity?
How do I calculate color intensity if I have a image sample of RGB?

The sample is of a float3 of red, green, blue. I'm trying to do a bilateral blur and have to not change the image if the color intensity is the same so it will preserve edges.

```
 float4 BilateralFiltering(VertexOut input) : SV_Target
{

 const float pixel = 0.01f;

     float4 centralColor;
     float gaussianWeightTotal;
     float4 sum;
     float4 sampleColor;
     float distanceFromCentralColor;
     float gaussianWeight;
     float distanceNormalizationFactor = 1.0;
     centralColor = gDiffuseMap.Sample(samAnisotropic, input.Tex.xy + float2(0,0));
     gaussianWeightTotal = 0.18;
     sum = centralColor * 0.18;

     sampleColor = gDiffuseMap.Sample(samAnisotropic,  input.Tex.xy + float2(-pixel,-pixel));
     distanceFromCentralColor = min(distance(centralColor, sampleColor) * distanceNormalizationFactor, 1.0);
     gaussianWeight = 0.05 * (1.0 - distanceFromCentralColor);
     gaussianWeightTotal += gaussianWeight;
     sum += sampleColor * gaussianWeight;

     sampleColor = gDiffuseMap.Sample(samAnisotropic,  input.Tex.xy + float2(-pixel,0));
     distanceFromCentralColor = min(distance(centralColor, sampleColor) * distanceNormalizationFactor, 1.0);
     gaussianWeight = 0.09 * (1.0 - distanceFromCentralColor);
     gaussianWeightTotal += gaussianWeight;
     sum += sampleColor * gaussianWeight;

     sampleColor = gDiffuseMap.Sample(samAnisotropic,  input.Tex.xy + float2(-pixel,pixel));
     distanceFromCentralColor = min(distance(centralColor, sampleColor) * distanceNormalizationFactor, 1.0);
     gaussianWeight = 0.12 * (1.0 - distanceFromCentralColor);
     gaussianWeightTotal += gaussianWeight;
     sum += sampleColor * gaussianWeight;

     sampleColor = gDiffuseMap.Sample(samAnisotropic,  input.Tex.xy + float2(0,-pixel));
     distanceFromCentralColor = min(distance(centralColor, sampleColor) * distanceNormalizationFactor, 1.0);
     gaussianWeight = 0.15 * (1.0 - distanceFromCentralColor);
     gaussianWeightTotal += gaussianWeight;
     sum += sampleColor * gaussianWeight;

     sampleColor = gDiffuseMap.Sample(samAnisotropic,  input.Tex.xy + float2(0,pixel));
     distanceFromCentralColor = min(distance(centralColor, sampleColor) * distanceNormalizationFactor, 1.0);
     gaussianWeight = 0.15 * (1.0 - distanceFromCentralColor);
     gaussianWeightTotal += gaussianWeight;
     sum += sampleColor * gaussianWeight;

     sampleColor = gDiffuseMap.Sample(samAnisotropic,  input.Tex.xy + float2(pixel,-pixel));
     distanceFromCentralColor = min(distance(centralColor, sampleColor) * distanceNormalizationFactor, 1.0);
     gaussianWeight = 0.12 * (1.0 - distanceFromCentralColor);
     gaussianWeightTotal += gaussianWeight;
     sum += sampleColor * gaussianWeight;

     sampleColor = gDiffuseMap.Sample(samAnisotropic,  input.Tex.xy + float2(pixel,0));
     distanceFromCentralColor = min(distance(centralColor, sampleColor) * distanceNormalizationFactor, 1.0);
     gaussianWeight = 0.09 * (1.0 - distanceFromCentralColor);
     gaussianWeightTotal += gaussianWeight;
     sum += sampleColor * gaussianWeight;

     sampleColor = gDiffuseMap.Sample(samAnisotropic,  input.Tex.xy + float2(pixel,pixel));
     distanceFromCentralColor = min(distance(centralColor, sampleColor) * distanceNormalizationFactor, 1.0);
     gaussianWeight = 0.05 * (1.0 - distanceFromCentralColor);
     gaussianWeightTotal += gaussianWeight;
     sum += sampleColor * gaussianWeight;

     return sum / gaussianWeightTotal;

     }

```

# Answer
> 2 votes
"Intensity" of a color is often the purity of a hue in color theory. It's also known as saturation.

This means you can compute the intensity (saturation) of a single color by converting it from the RGB space to the HSV space. The saturation component, specifically, can be computed by selecting the minimum and maximum color components

```
Cmax = max(R, G, B);
Cmin = min(R, G, B);

```

and computing the delta between them

```
d = Cmax - Cmin

```

If the delta is 0, the saturation is 0. Otherwise, the saturation is

```
saturation = delta / Cmax

```

Note that this computation assumes the color components are specified in the 0..1 range, so if you're using 0..255 you'll want to scale them first.

---
Tags: directx
---


# Question
Title: How should I efficiently store faction relationships?
I'm working on a game that follows the life of a powerful magician as she lives, dies, and reincarnates dozens of times across hundreds of years. Meanwhile, empires rise and fall around her--she can influence them by killing their kings or even becoming their leader, but even without her they will go about their business, fighting wars with other factions and appointing new leaders.

The problem is this: **how do I store all those faction relationships?** Currently, I have a class Faction, which has an enemy list, a ally list, and a controlled list (the Government of Rezla controls the Army of Rezla, etc). However, simply using lists like these limit me to a binary ally/not-ally, enemy/not-enemy deal.

I suppose I could get around that to some degree by using a list of lists, so RezlaGovt.allies contains `[[AzosGovt, 2],[JupaGovt, 4]]`, where the first value in the sublist stores the name of the ally and the second value stores the current reputation, but that seems inelegant (and I don't really understand how to manage it properly in code). It also makes it much more difficult to later add tags to the relationships, like `hasTradeAgreement` or `hasMutualDefencePact`.

What data structure do other complex strategy games use to handle faction relationships?

**Other Details:**

I will have around 10 main factions for the world governments, each with subfactions and subsubfactions (and maybe even subsubsubfactions!), so a system that deals well with large datasets is a plus.

Not all factions need to be simulated all the time: the Fighter's Guild in a distant city might be completely ignored until the player does something in the area, at which point I can randomly generate some "history" for it, to make it seem like it's been doing stuff.

# Answer
> 3 votes
You could keep the factions in a dictionary inside your scenario/map/level instance, using `("groupA", "groupB")` tuples as keys to store the relations between groups.

In case relations are always symmetrical/bilateral (*I'm an ally for my allies, an enemy for my enemies*), you could subclass `dict` and change it in a way that sorted tuples would be used to get/set items (thus avoiding the need to keep a pair of similar data for the reversed key). With that, you would have:

```
>>> factions("AzosGovt", "JupaGovt") == factions("JupaGovt", "AzosGovt")
True

```

That could be obtained with a subclass like this one:

```
class Factions(dict):

    def __init__(self, *args, **kwargs):
        self.update(*args, **kwargs)

    def __getitem__(self, key):
        val = dict.__getitem__(self, tuple(sorted(key)))
        return val

    def __setitem__(self, key, val):
        dict.__setitem__(self, tuple(sorted(key)), val)

    def __repr__(self):
        dictrepr = dict.__repr__(self)
        return '{}({})'.format(type(self).__name__, dictrepr)

    def update(self, *args, **kwargs):
        for k, v in dict(*args, **kwargs).items():
            self[tuple(sorted(k))] = v

```

The value of the factions could be whatever you feel more comfortable working with.

Personally, I would go for readability and use another dictionary. If so, to set your factions up you could do:

```
factions = Factions()

factions.update({
    ("AzosGovt", "JupaGovt"): {
        "relation": 80,
        "trade": 1,
        "alliance": 1,
        "war": 0
    },
    ("AzosGovt", "ElvesGovt"): {
        "relation": -50,
        "trade": 0,
        "alliance": 0,
        "war": 1
    },
})

```

That would allow you to easily implement utility methods like those:

```
    def allies(self, key):
        allies = []
        for k, v in self.items():
            if v["alliance"]:
                for side in k:
                    if side != key:
                        allies.append(side)
        return allies

    def at_war(self, key):
        enemies = []
        for k, v in self.items():
            if v["war"]:
                for side in k:
                    if side != key:
                        enemies.append(side)
        return enemies

    def make_peace(self, key):
        self[tuple(sorted(key))]["war"] = 0

    def declare_war(self, key):
        self[tuple(sorted(key))]["war"] = 1
        self[tuple(sorted(key))]["alliance"] = 0

```

Testing it:

```
>>> print(factions.allies("AzosGovt"))
['JupaGovt']

>>> print(factions.allies("JupaGovt"))
['AzosGovt']

>>> print(factions.at_war("AzosGovt"))
['ElvesGovt']

>>> print(factions.at_war("ElvesGovt"))
['AzosGovt']

>>> factions.make_peace(("AzosGovt", "ElvesGovt"))
>>> factions.declare_war(("AzosGovt", "JupaGovt"))

>>> print(factions.allies("AzosGovt"))
[]

>>> print(factions.at_war("AzosGovt"))
['JupaGovt']

```

It's a simple implementation, but, usually, simple is good.

Main idea here is the `sorted(tuple)` as key.

For the relation itself you could use, instead of the dictionary, a list of booleans like the one you talked about, or create another class to hold attributes and properties like: at war, alliance, etc.

# Answer
> 2 votes
Have you considered a 2D array?

Visual representation:

```
Faction ->     |  A  |  B  |  C  |
   |           |     |     |     |
   V           |     |     |     |
----------------------------------
   A thinks... | --- | 15% | 89% |
----------------------------------
   B thinks... | 12% | --- | 40% |
----------------------------------
   C thinks... | 92% | 50% | --- |
----------------------------------

read as:
A has a 15% opinion of B
B has a 12% opinion of A
etc.

```

The kind of data you store might be much more complex than this, such as how The Last Federation handles it (full 'grid' view):

This being the breakdown of "A has a 15% opinion of B" into every factor affecting that total (eg how "15%" is calculated), in this case, a total of -1392.56, which is so bad as to be irreparable.

The internal representation is essentially a dictionary of to , so that when an event occurs the is increased (or decreased!) by some value, then everything is summed (some factors being positive, others negative) and a resulting total is generated.

---
Tags: python, simulations, strategy
---


# Question
Title: Why can't I patch my procedural terrain together?
I figured out how to implement a midpoint displacement algorithm to generate a map for my game. I wanted to create an infinitely large world, so I tried to patch two maps together, but they didn't look very seamless. I remembered the Diamond-square algorithm...

On the Wikipedia page for the Diamond-square algorithm it says:

> When used with consistent initial corner values this method also allows generated fractals to be stitched together without discontinuities

After reading that I decided to convert my midpoint displacement method into what I *believe* is a proper diamond-square method. However, it still does not look seamless despite me using "consistent initial corner values."
The method works perfectly otherwise.
Here are two generated maps next to each other:

As you can see, there are major discontinuities (even though it looks like they could *almost* fit together). What I wrote must not be a "true" diamond-square method, or maybe I am misunderstanding the Wikipedia article.

So in other words my question is this: What is wrong with my code or my understanding that prevents me from stitching together maps?
Thanks a lot!

```
public static float[][] generateMap(int power, float topLeft, float topRight, float bottomLeft, float bottomRight, float error, float persistence, boolean normalize, long seed){
Random random = new Random(seed);

int size = (int)Math.pow(2, power) + 1;

float[][] data = new float[size][size];

// these are for the normalization at the end.
// does it even do anything?
float min = MathHelper.min(topLeft, topRight, bottomLeft, bottomRight);
float max = MathHelper.max(topLeft, topRight, bottomLeft, bottomRight);

// set the corners to the initial values.
data[0][0] = topLeft;
data[size-1][size-1] = bottomRight;
data[0][size-1] = topRight;
data[size-1][0] = bottomLeft;

for (int i = 0; i < power; i++){

    int square = size / (int)Math.pow(2, i);
    int half = square / 2;

    for (int x = 0; x < size - square; x += square){
        for (int y = 0; y < size - square; y += square){

            // find the values of the corners of the square.
            float tl = data[y][x];
            float bl = data[y + square][x];
            float tr = data[y][x + square];
            float br = data[y + square][x + square];

            // find the values of the corners of the diamond (if they exist).
            Float xt = (y - square - half >= 0) ? data[y-square-half][x+half] : null;
            Float xb = (y + square + half < size) ? data[y+square+half][x+half] : null;
            Float xl = (x - square - half >= 0) ? data[y+half][x-square-half] : null;
            Float xr = (x + square + half < size) ? data[y+half][x+square+half] : null;

            // set the square's center to the average of the square's corners plus a random error.
            float centerVal = (tl + bl + tr + br) / 4.0f;
            centerVal += ((random.nextFloat() * 2) - 1) * error;
            data[y+half][x+half] = centerVal;

            // set the diamonds' centers to the average of the diamonds' corners (that exist) plus a random error.
            float leftVal = (tl + bl + centerVal + (xl != null ? xl : 0)) / (3.0f + (xl != null ? 1.0f : 0.0f));
            leftVal += ((random.nextFloat() * 2) - 1) * error;
            data[y+half][x] = leftVal;

            float rightVal = (tr + br + centerVal + (xr != null ? xr : 0)) / (3.0f + (xr != null ? 1.0f : 0.0f));
            rightVal += ((random.nextFloat() * 2) - 1) * error;
            data[y+half][x+square] = rightVal;

            float topVal = (tl + tr + centerVal + (xt != null ? xt : 0)) / (3.0f + (xt != null ? 1.0f : 0.0f));
            topVal += ((random.nextFloat() * 2) - 1) * error;
            data[y][x+half] = topVal;

            float bottomVal = (bl + br + centerVal + (xb != null ? xb : 0)) / (3.0f + (xb != null ? 1.0f : 0.0f));
            bottomVal += ((random.nextFloat() * 2) - 1) * error;
            data[y+square][x+half] = bottomVal;

            max = MathHelper.max(max, centerVal, leftVal, rightVal, topVal, bottomVal);
            min = MathHelper.min(min, centerVal, leftVal, rightVal, topVal, bottomVal);

        }
    }

    // reduce random error.
    error *= persistence;
}

// does this even do anything?
if (normalize) {
    float div = max - min;
    for (int i = 0; i < size; i++)
        for (int j = 0; j < size; j++)
            data[i][j] /= div;
}

return data;

```

}

# Answer
Before Diamond-Square begins, you'll have to make sure the outermost boundaries (and the maximum number of potential midpoints generated therein) are set equal on either side of the map (in x and y). Only then can you begin full generation of the centre with something *approaching* a seamless wrap. What they meant by "consistent" is "all outermost corners and edges need the same values", because when wrapping, they are all, in essence, the same point (origin). Set initial corners to zero, then elaborate the left edge using 1D midpoint displacement, copy that to the right edge, then do same with top and bottom (by the end, the corners must still all be zero, but those between can be anything). Alternatively, you can just set all boundary points to zero. Now you have the map "frame", so when running Diamond-Square, don't touch boundary points - just use them.

I say *approaching* because mind you, this may still not lead to a desirable result (depending on your point of view), since the operation of the Diamond-Square algorithm does not, by default, handle the concept of continuity across wrap boundaries. So it looks somewhat contrived, IIRC. If this is a problem, either find a way to do some sort of smoothing across boundaries, perhaps by picking random local maxima / minima on either side of the boundary and expanding these across the boundary, or look at other algorithms for your terrain generation... or lose the wrap requirement.
> 6 votes

# Answer
In my own bit of code (just to learn procedural terrain generation), instead of trying to stitch together two maps (eg. two 64x64 maps), I create one larger map (eg. 128x128, which wraps), and then throw away the bottom portion. This leaves me with a 64x128 map that wraps horizontally but not vertically (which is what I want).
> 1 votes

# Answer
I've thought about this, that is, creating matching heightmaps using diamond-square. I don't know how well this will work, as I've never tried implementing it, but here's my theoretical postulation:

For every point along an edge, if the adjacent map portion exists, make the point equal to the adjacent edge point.

What it looks like right now is that you're only setting the *corners* to the adjacent map's corners, but not following through for the other points. Because every other point is random, the rest of the edge is not guaranteed to line up. But if you were to insert an additional check that says, "am I an edge? ok, does an adjacent edge on another map portion exist? ok, it does, I am now that value instead of this random one" you should be able to get it to line up exactly.
> 1 votes

---
Tags: java, procedural-generation, terrain, heightmap, noise
---


# Question
Title: How can I mass-duplicate or "paint" Unity objects?
Let's say I have a basic map with a single box on it.

I want to make many, many more of these cubes, so they can cover a large portion of the map, like this:

Each box needs to be exactly one unit away from the adjacent boxes, so there is no overlap.

My idea was to clone the first box so the entire blue map is covered, then manually delete some of them to make the path.

In other software, there are ways to clone/duplicate large numbers of objects so that they fill an area, or follow a certain set of transformations. I cannot figure out how to do this in Unity.

I have tried manually duplicating the box and setting its location (so I have two properly-positioned boxes), then selected both of those and duplicating (so I have four boxes total), duplicating those, etc, but as soon as I select multiple boxes, I can't type in a location without all the selected boxes going there (so if I type a y-location of 12, every single selected box will be crammed on top of each other on y=12).

# Answer
> 1 votes
It's not a perfect solution (I hope others can suggest general-purpose tools for this), but I usually do this with keyboard shortcuts:

* `Ctrl + D` to duplicate the currently selected objects
* select all of them
* Hold `Ctrl` and drag the translation handles to move them, snapping to 1-unit increments

So I start with one object, dupe-move it to get 2 one unit apart, then select both and dupe-move them to get 4 in a line, then select all 4 and dupe-move to get 8...

It's laborious, but progress gets faster with each doubling so it's a lot better than positioning them all one-by-one.

If I had to do this a lot (say, making a dozen or more levels built out of cubes like the one above) I'd probably write an editor script to mass-duplicate objects in a rectangular array, or paint them as you describe (or maybe populate them on level load by reading a bitmap image, so I can paint my levels in a drawing program... depends on the game).

I haven't fully grokked editor scripting though, so it always involves a little trial and error for me to get it right, which means I can't give concise instructions that I'm sure will work, so I'll leave discussion of that option to someone with more experience. ;)

# Answer
> 1 votes
> I can't type in a location without all the selected boxes going there (so if I type a y-location of 12, every single selected box will be crammed on top of each other on y=12)

This issue is easy to fix:

1. Select all boxes and duplicate them.
2. Put them inside new empty parent GameObject.
3. Translate that GameObject by needed distance.
4. Take boxes out from that temporary parent and delete it.

Alternatively, you can fill required area with boxes with some help from free Immediate Window extension. It's very old but worked last time I checked (few months ago).

If you're going to level-design with this approach, better invest some time into creating editor script.

---
Tags: unity
---


title: NavMeshAgent in unity not working

text:
# Question
Title: NavMeshAgent in unity not working
I am making a game in unity and it is throwing the error "Failed to create agent because there is no valid NavMesh" and i don't know what the problem is.

```
using UnityEngine;
using System.Collections;

public class EnemyMotion : MonoBehaviour {
    public NavMeshAgent agent;
    public Rigidbody rb;
    public GameObject otwt;

    void Start () {
        rb = GetComponent<Rigidbody>();
        agent = GetComponent<NavMeshAgent>();
    }
    void Update () {
        gameObject.transform.Rotate(270, 0, 0);
        agent.SetDestination(otwt.transform.position);
    }
}

```

# Answer
> 3 votes
You need to bake a navmesh first.

---
Tags: unity, navmesh
---