# Book of Defold

Learn to make games with Defold from a professional.

**TEXT MIGRATION IN PROGRESS!**

This book is a community project and is published into the public domain. Its license is:

<https://creativecommons.org/publicdomain/zero/1.0/>

This book is for anyone who wishes to learn how to make games professionally with the Defold game engine by King. This book is for the Defold Editor 2.0 release. You can always read the latest version of this book at <https://www.bookofdefold.com/>

Defold can be downloaded at: <https://www.defold.com/>

If you want to start making games right now without reading too much then jump straight ahead to the [**Dive into Defold**](https://read.bookofdefold.com/dive-into-defold/make-games-now) section.


# What is Defold?

Defold is both a cross-platform game creation tool and a cross-platform game engine. You can work with Defold on Windows, Mac, and Linux, and publish to Windows, Mac, Linux, HTML5, iOS, and Android. Defold enables quick collaboration between artists and coders in small to large teams. Defold is made to be fast, light weight, and stable. Defold has many features built in which will enable you to build high quality games quickly without needing to worry about engine stability or platform support. Defold has an active community, and a team of committed developers who want it to be the best technology it can be. Who want to help you to make the best games possible. Defold is completely free to use. There is no price to pay, no subscription, and no royalty. With Defold, you can get started learning how to make games, and make professional quality games that are played by millions of people world wide.

![This character is a sprite from one of the original Defold tutorials.](https://59336108-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LHnmfJK3HDz-s0f74qO%2F-LHnu41EE7S25wiFOv2z%2F-LHnv6OURtasedZU3VLd%2F2018-07-19%2012_02_04-Window.png?alt=media\&token=6df90746-d42a-44f8-a463-f63ed7fb615a)


# Why Defold?

**Defold is great!** It is one of the best (most feature rich, most productive) game development option for 2D focused dev available today (and is making progress toward being great for 3D in the future too).

**Cross platform** - iOS, Android, Win / Mac / Linux / HTML5. 2D first class, but still supports 3D.&#x20;

**Light weight**, super high performance, very highly optimized (works great on older, slower devices - for when you want as many people to be able to play your games as possible).&#x20;

**Many useful built in features** such as signed distance field fonts, automatic texture atlas generation, automatic per-target texture compression, support for IAP billing for iOS/Android, support for delivering a smaller game binary and then streaming in extra content as needed.&#x20;

**Enables productivity** and collaboration out of the box. Make changes, sync to server, and then your team members can pull to see the changes. References are updated as you move files around in the editor which cuts down on tedious work when refactoring.

**Has great support from great devs**. The Defold development team makes frequent updates, and is very supportive and active in the community.&#x20;

**Defold’s future is very bright**, it has a growing community, and strong support from its developers who also have a strong desire to not break current projects with updates as the Defold engine and editor continues to evolve&#x20;

Besides the technical reasons, there are other reasons which you should be aware of that should make Defold an appealing option. By working with Defold, there may be opportunities you may never be able to get using other similar tools - such as having a hiring advantage for companies using Defold. Learning Lua through Defold is also useful as many other game development tools also use Lua.


# Defold History

Defold is a ready for production, and 100% free cross platform game engine and editor. The editor works with Windows / Mac / Linux and it supports targets for iOS / Android / HTML5 / Windows / Mac / Linux with more possible in the future. It is a full 3D engine under the hood with specialization for 2D games. The engine is in C, and runs interpreted Lua, which is the language you will use to code your Defold project for the most part. On most target platforms, LuaJIT is used, which makes the Lua code nearly as fast as native code would be. Over the years of its development, Defold has had many major additions and changes.

The Defold team (Defold AB based in Stockholm, Sweden) started the project in 2009 with the goal of making a tool that allowed professional workflow, but that which was simple to use, and could be used to create complex features - with the ability to collaborate and be productive at its core. A strong focus from the start was on performance, being light weight, and having high reliability. Defold was envisioned with 2D as being the first class priority, although the engine is still a 3D engine and can make 3D games. It took three years from project start to reach Alpha. Defold is currently in late Open Beta.

Defold.com (primary domain) was registered on May 26, 2010. The secondary domain, Defold.se, was registered on March 26, 2011, and is used for some of the Defold services.

The first site for the Defold Editor was live in 2012. Back then, when it was in Closed Beta, Defold was offered for a subscription fee depending on team size / number of projects. For the next few years, Defold continued to be in Beta and was actively developed.

In 2014, King purchased Defold, and in 2015 plans previously made were put into motion to release Defold as a fully free game engine. Their goals with doing this were first to improve Defold by sharing it with a community, second to show the world the technology, and third to be able to hire more developers already familiar with the technology. King uses Defold as one of their three internal game engines (one other major one is for their private use only and is called “Fiction Factory” an older, more 3d focused, C++ cross platform engine (iOS, Android, HTML5, PC, OS X) which powers Candy Crush, Pet Rescue, Farm Heroes, Bubble Witch Saga, and more), and has produced the hit game Blossom Blast Saga with it. The Defold engine team remains separate from the King game or other engine teams. Currently the Defold development team is about \~12 people according to King jobs listings.

Now Defold is released (but still will remain in Beta for a while like Gmail was), and available for any developer to use. Its community is growing, and more games are being made and published which use it. The future is bright for Defold and developers who use it!


# Editor Tour

A guided tour through the features of the Defold Editor.

## Splash

![](https://59336108-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LHnmfJK3HDz-s0f74qO%2F-LHsFcgZ8r5kkDH2cply%2F-LHsHpNHM6HQb69m2V97%2FSplash_2018-07-20%2008_24_13.png?alt=media\&token=cf21e1a0-62ae-4e79-8840-57ead7a09a78)

When you first launch Defold you will see a splash screen as the editor loads. Images of games made with Defold are periodically showcased here. Maybe one day your game will be!

## Launcher

![The editor launcher gives you a long list of recent projects to pick from. Convenient!](https://59336108-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LHnmfJK3HDz-s0f74qO%2F-LHsFcgZ8r5kkDH2cply%2F-LHsI7ssHi1W3rLQibwx%2FLauncher-2018-07-20%2008_19_35.png?alt=media\&token=806d1aa2-99a2-4df3-a391-985a1a1e125c)

After the splash, you will see the launcher. Here you can open one of your recent projects, open any project from your computer, create a new project based on a template, and import from your Defold dashboard in the cloud.

![](https://59336108-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LHnmfJK3HDz-s0f74qO%2F-LHsFcgZ8r5kkDH2cply%2F-LHsIdX1Swqa97usCsf8%2FCreate_2018-07-20%2008_28_06-Window.png?alt=media\&token=d040370e-b050-4edf-b5f5-4da73d147793)

When creating a new project from the launcher, you can pick from various templates or starter projects either based on official tutorials or samples.

![](https://59336108-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LHnmfJK3HDz-s0f74qO%2F-LHsFcgZ8r5kkDH2cply%2F-LHsJQFxkOgMV5Z7-cgq%2FImport-2018-07-20%2008_31_28.png?alt=media\&token=961d7827-b6b4-4a7a-937e-439211167aed)

To import projects from the Defold cloud you must have created an account on Defold.com and created a project on your dashboard there. Using the Defold cloud is not required to make games with Defold. You can easily use your own Git hosting for your projects.

## Main Editor

![](https://59336108-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LHnmfJK3HDz-s0f74qO%2F-LHsO9p1up3OXmcZcgJ2%2F-LHsOFWFXM9siOMbvU0d%2FEditor-2018-07-20%2008_52_10-Window.png?alt=media\&token=a2fd0325-b363-4908-89d3-166fa61ccc52)

Once you've created from a template or loaded a project the main editor will open.&#x20;

### Assets

On the left is the **Assets** panel. These are the files that are inside of your project folder. The **builtins** folder is a special **read only** library that is included in all Defold projects with some essential defaults an empty project needs such as default shader materials. You can import other libraries too, but you cannot omit the **builtins**. Read only means you can't edit these files, you must make copies of them if you wish to use them as a base to make a custom version.

![Browse through the builtins folder so you know what's in there.](https://59336108-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LHnmfJK3HDz-s0f74qO%2F-LHsTDSa1DdNP8FGzTHE%2F-LHsTIH6QTcyBi8kNkL_%2Fbuiltins%202018-07-20%2009_14_40-Window.png?alt=media\&token=e0394650-ac82-4acc-babb-6bf309775439)

### Changed Files

On the bottom left is the **Changed Files**. This will show you any file modifications since your last git commit. If you use the editor's own git features or your own git setup the changed files will show here as long as you have a git repository setup. You can tell there is no git repository setup when no changed files history shows up, but also by the fact there is no .git folder in your project's home directory.

![No .git folder means no git version control.](https://59336108-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LHnmfJK3HDz-s0f74qO%2F-LHsO9p1up3OXmcZcgJ2%2F-LHsPeXWo4rbQ8kMEWBy%2Fno%20git%202018-07-20%2008_58_07-Window.png?alt=media\&token=e23e3c4e-6788-454d-bcdc-b7194c29fd3f)

![Example of a project with a .git folder](https://59336108-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LHnmfJK3HDz-s0f74qO%2F-LHsO9p1up3OXmcZcgJ2%2F-LHsQ0MoSjtEmjPpb8c_%2F2018-07-20%2008_59_57-Window.png?alt=media\&token=4ffbce15-f602-4ec7-a09a-746220445ec3)

**.git** is used for git version control, **.internal** is used by the editor, and the **build** folder is for temporary files while building or bundling. You may occasionally need to delete your .internal or build folders if instructed. These folders should not be saved to your git version control, and you should be careful to not include them in any zips of your project as they are not needed and only add extra space.

### Outline

![The hero GO has a sprite component.](https://59336108-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LHnmfJK3HDz-s0f74qO%2F-LHsUvPzMhmCuzw1IVkk%2F-LHsWpfhP75tNsHXOeQc%2Foutline%202018-07-20%2009_30_11-Window.png?alt=media\&token=986ddae3-69d3-46d6-9593-1a5963270007)

The outline panel shows a contextual tree of resources depending on what you have open in the editor. If you have a collection open then you'll likely see a list of **Game Objects (GO)** with their associated **Components**.

### Properties

![](https://59336108-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LHnmfJK3HDz-s0f74qO%2F-LHsUvPzMhmCuzw1IVkk%2F-LHsXb_IUpNQsnYXwRDO%2Fproperties%202018-07-20%2009_33_18-Window.png?alt=media\&token=4acc32c8-30dd-4f3e-806a-87414c8d8921)

The properties panel shows contextual information based on what is selected in the **Outline**. Sometimes this information can be edited other times it's read only and only there to be useful information for you.

### Console

The console shows information when you build your project from **Project->Build**. When you **print()** or **pprint()** this will show up in the console. You can load a copy of the Defold engine onto a mobile device such as an Android phone, select it as a target with **Project->Target**, then when you build the information from the Android phone's copy of the engine running will be shown in your local console.

![Starting and stopping an empty project.](https://59336108-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LHnmfJK3HDz-s0f74qO%2F-LHsUvPzMhmCuzw1IVkk%2F-LHsW-EYb1vVGQI9YDAx%2Fconsole%202018-07-20%2009_26_36-Window.png?alt=media\&token=ae008de1-71db-40f3-a9a5-8cfd83ec9d0c)

### Curve Editor

### Build Errors

### Search Results

### Scene Editor / Viewport


# File Formats

A list of all file types related to working with Defold.

**Animation Set (\*.animationset)**: Used for model animations. You can add one animation set to another if you have some animations which are shared between models. To use an animationset you define it as the animation file in the properties for an open model file.

**Atlas (\*.atlas)**: Texture atlases are methods of optimization which decrease texture space, and decrease load time. When your game’s textures are loaded into memory, due to the way older graphics hardware works (some newer graphics hardware handles texture memory better), they will always take up memory rounded up to the nearest power of 2 in each dimension. 128x256, 128x128, 256x256, 256x512, 512x512, 1024x1024, … When you have hundreds or even thousands of textures your game can end up wasting a large amount of memory without optimization - the difference in space which each of the textures actually takes vs its container size in memory. Texture atlas technology attempts to solve this problem by combining multiple textures into a single texture so that the memory your game takes is more optimized and less wasted. By using texture atlases, your game’s loading time is also reduced. It’s easy to understand - if every texture is a filesystem call when it is loaded, with hundreds of images, there is significant OS overhead with all of the load calls, which increases loading time. When you create an atlas file you will then want to add images to it, which must be within your project’s file structure. You can define the atlas texture’s margin, if it has extruded borders (useful for tiles to prevent color bleeding), and if it has inner padding (along with margin is useful to prevent texture color bleeding). Generally you will want to create multiple atlases with images defined in them that logically go together so that you only keep textures in memory that a currently necessary. Keep images which are always loaded while your game is running in their own image atlases referenced in your main collection. Put images which are loaded in and out as your game changes screens or levels in their own atlas files referenced in sub-collections.

**Camera (\*.camera)**: Cameras are how your game knows what to render onto the screen. Remember that even though Defold has been optimized for 2d game projects it is still a 3d game engine under the hood. Just like any 3d engine, you can have multiple cameras in your scenes which have different purposes. The “Camera Editor” allows you to change a camera’s aspect ratio, field of view (fov - expressed in degrees), near z (the z distance where a camera begins to draw), far z (the z distance where a camera no longer draws objects), and a flag to set to 1 to automatically set the aspect ratio based on your game project’s screen size settings. You do not technically need camera files for rendering, but they can be useful to for example place as a child component to a parent game object so that your camera follows a game object. As of this writing, it is better to use the [Orthographic](https://github.com/britzl/defold-orthographic) or [RenderCam](https://github.com/rgrams/rendercam) extensions rather than the builtin cameras. **You should be using one or either of these most likely!**

**Collection (\*.collection)**: Collections are hierarchies of game objects. Their editor is called the “Scene Editor” and allows editing collection contents within what first appears to be a flat 2d space, but is actually a 3d space. You can rotate the viewport camera by holding alt and left click while dragging the mouse pointer.

**Collection Factory (\*.collectionfactory)**: Collection factories can spawn collections which are pre-made, and used as blueprints, templates, or prefabs. Every Collection Factory File must have a “Prototype” collection defined inside of it. Collection Factories are related to Collection Proxies with some important differences. The Collections associated with Collection Factories are loaded into memory when its parent collection is loaded. Collection Factories are for creating multiple objects based on the prototype. The Collections associated with Collection Proxies are not loaded when its parent collection is loaded, they are loaded only when told to load, and load asynchronously - meaning when you call a Collection Proxy to load it loads on its own thread, and doesn’t cause your game to lag while loading, but you may still need to wait some time before a large collection loads. Collection Proxies are for arbitrarily loading external collections as their own independent “worlds” - you can use them to manage the different screens in your game project. If you wish you could add multiple game objects to each other inside of a .go file then you should be using collections instead and then spawning them using a collection factory. GOs can reference  each other by name when inside of a collection. This means if you have a "head" and "body" GO  you can address each "head" and "body" as such in the scripts of these GOs if they are inside of a collection, which means you do not need dynamic addressing for these cases. When you use collectionfactory.create() to create a collection based on a collection factory it returns a table of addresses of all of the GOs within that were just created.

**Collection Proxy (\*.collectionproxy)**: You define collections within collection proxies which you can then async load / unload as the contents of the defined collections are needed. These are often used for switching screens in games. The current best screen manager is [Monarch](https://github.com/britzl/monarch). **Use Monarch!**

**Collision Object (\*.collisionobject)**: Collision Objects are used within the physics systems built into Defold. You place Collision Objects as child components of parent Game Objects. More on Collision Objects later in this chapter, and in the Physics chapter.

**Cubemap (\*.cubemap)**: Cubemaps are used as a type of texture useful for different kinds of things such as baked world reflections or sky boxes. Search Google for “cube mapping” for more information. **These are currently not functional.**&#x20;

**Factory (\*.factory)**: A Factory is like a Collection Factory but for Game Objects. You define a Game Object prototype inside of the Factory, and then can communicate with the Factory to create new Game Objects based on the prototype. It’s up to you to keep track of and manage the created Game Objects - when you create a GO with factory.create() the return value is the address of the GO, which can then be stored in a table as a list of addresses to manage.&#x20;

**Font (\*.font)**: Defold has great Font support. It supports creating bitmap fonts and distance field type fonts based on ttf font files. Distance field type fonts enable drawing great looking font glyphs at most sizes with keeping glyphs looking crisp. But they still have some gotchas, such as needing to generate a large enough glyph size, and some shapes still not looking right depending on the font you use. You may need to adjust the builtin distance field font material's fragment program to reduce smoothing if your fonts look blurry when scaled down. It is possible to use bitmap fonts, and for them to be scaled nearest neighbor, but you'll need to [create a copy of the builtin fonts and set a sampler](https://read.bookofdefold.com/defold-a-z/defold-tips/pixel-art-assets). View this video for a demonstration on distance field fonts: <https://www.youtube.com/watch?v=CGZRHJvJYIg> You can also use BMFonts generated by the [BMFont](http://www.angelcode.com/products/bmfont/) tool (or any bitmap font generation tool that supports the BMFont format)[ this link shows an example of using BMFont fonts.](https://github.com/subsoap/defold-bmfont-example)

**Fragment Program (\*.fp)**: Fragment Programs (or Fragment Shaders) allow you to make graphical manipulations to your existing game textures to, for example, add borders, desaturate colors, or most any kind of effect you can think of. You can for example use [DefBlend](https://github.com/subsoap/defblend) to shade your sprites with certain colors with different Photoshop like blending modes.

**Game Object (\*.go)**: Game Objects are an important building block of your projects. You can create Game Object Files external to Collections, which can then be easily imported into Collections, and when you modify the Game Object File its changes will be reflected in all of the Collections which have imported it. Game Objects created inside of Collections are unique to those Collections. If you want to be able to parent GOs to each other in your prefabs then you will want to put them inside Collections and then use a Collection Factory to spawn those assets.

**GUI (\*.gui)***:* A GUI File allows you to build interfaces for your game projects. GUIs by default are rendered on their own render predicate tag layer in the builtin render script - on top of everything else. By default too, GUIs are rendered in a way that is more resolution and aspect ratio agnostic. GUIs ignore Z distance completely and do not use it for render ordering - instead they rely on relative order and parenting in the GUI file itself. If you have multiple .gui files inside of a scene then you can set each file's render order in each gui's gui\_script file with gui.set\_render\_order(). This is usually used when you want a popup GUI above a game HUD GUI for example. You may want to define render order "layers" inside of a module which each gui\_script can reference that way you can easily change the value of each type in a single place if necessary.

**GUI Script (\*.gui\_script)**: GUI Scripts are special kinds of scripts meant for GUI objects only. The .gui\_script files have specific GUI related API access that normal scripts cannot use.

**Input Binding (\*.input\_binding*****)**:* Defold supports many input methods: keyboard key events, mouse, text, touch, gamepad. You must define input bindings to keywords and then wait for the input which is associated action keyword to make actions. This is useful because you can define multiple inputs to the same keyword, and then only keep track of that single keyword. For example, you can define mouse left click, and touch to the same keyword, and then input for both are tracked with less code. Input is covered more in a later chapter. Light File (.light): This is deprecated and should not be used. It will be replaced in the future. It is still possible to create “lights” in scenes, but takes extra work and is not in standard Defold currently. [This link is for a .input\_binding with all possible options defined](https://github.com/subsoap/definput/blob/master/definput/all.input_binding).

**Label (\*.label)**: A Label allows you to attach text to Game Objects as components. This allows an easy, direct way to associate nametags with minions which follow the minions around for example.

**Lua Module (\*.lua)**: Lua modules are different to GUI Scripts, Render Scripts, or Game Object Scripts (or just Scripts). You are always still coding in the Lua programming language, but every type of script has a different preset behavior and scope of available features to access. Generally you import Lua modules into other scripts to take advantage of their features in your project. There are many Lua libraries which are very useful with game development.&#x20;

**Material (\*.material)**: Every visible object whether it be a sprite component of a game object, a font, or a model - all need a material set to it which defines how it is rendered. Inside of a material you can define its tags, which is used in the render script to render groups of objects, the vertex and fragment shaders, which define how the object which uses the material is rendered. You can also define default materials which you may want a material shader program to be able to access, and set the the sampler, which allows you to change how whatever it is you are rendering is filtered (nearest neighbor - good for keeping hard pixel edges when scaling pixel art, or linear- good for smoothing when scaling). In many cases, you will need to copy a builtin material into your project to make a custom version of it.&#x20;

**Model (\*.model)**: A model file is a 3d object container where you define a mesh (currently only .dae files are supported), a 3d material, and textures for the material to use. You can also define a skeleton and, animationset, and default animation if you wish to animate your models.

**Particle FX (\*.particlefx)**: Defold has very good and efficient particles support. Particles are rendered on their own tag layer by default above game object sprites. If you wish particles to appear below game objects you could for example make a copy of the builtin material used by particles, give it a different tag name (or give it the "tile" tag so that it renders along with sprites - although this may cause more drawcalls), associate this new material with the particles you wish to draw below game objects, and then duplicate the particle tag in the render script so that the second tag is rendered before the game objects are. You can make multiple layers of game objects with this method too - you cannot otherwise mingle particles and game objects based on z distance ordering. Particle FX is currently only for 2D particle effects and does not function well in 3D space.

**Render (\*.render)**: Your Render file defines the location of your Render Script, which determines how your game is rendered. Tags are applied to materials, and you render objects with material based on the tags they have to render predicates. Rendering every tag is like an individual layer of paint, which can be made up of layer objects of its own, put on top of each other.

**Render Script (\*.render\_script)**: The easiest way to create a new Render Script is to duplicate the one found in the builtins folder. You are more likely going to want to modify the builtin one than to create a new one from scratch. You will most likely want to use Orthographic or RenderCam community modules, or base a custom render script off those available in these projects.

**Script File (\*.script)**: If you create a new Script you will see that it is pre-made with several functions. If you add the script as a component to a Game Object which is part of an active Collection then some of these functions will be called automatically during the lifetime of your game and the Game Objects it is associated with. The **init** function is called when the associated Game Object first initializes. The **final** function is called when your game is about to quit, the collection the GO is in is about to be disabled, or the GO is deleted with go.delete() - to give your GOs a chance to do any final tasks, such as saving user data, before ending or letting other objects know it has been deleted. The **update** function is called every time your game updates - you can choose to increase or lower the update rate - a dt (delta time) argument is passed to the update function of a collection loaded through a collection proxy which allows you to modify your game’s simulation more reliably based on the real world time difference between the last update. The **on\_message** function is for inspecting messages sent to the Game Object’s script - message passing is very useful, but has a cost and so should be wisely in the correct situations. Sometimes it's better to share data with Lua modules. The **on\_input** function is for detecting, and using user input so that your game can react to player input to, for example, be able to move a hero around with a keyboard or touch a monster with a touch screen to attack it. Generally you only one to detect user input in a few scripts, then make that data accessible to other scripts through Lua modules. The **on\_reload** function is used with the hot code reloading functionality of Defold - hot code reloading is very useful for development and debugging, and you should certainly use it - the on\_reload function allows you to make special considerations to account for when reloading your game’s code.

**Sound (\*.sound)**: Defold currently only supports .wav and .ogg for sound. A good practice is to use WAV for short sound effects, and OGG for music or longer audio clips. If you need special audio features check the [community asset portal](https://www.defold.com/community/assets/) as it has several useful options.

**Spine Model (\*.spinemodel)**: The Spine Model File is for defining information related to Spine Models created with the Spine application by Esoteric Software, which is a commercial, 2d puppet animation software. If you know games such as Dragon’s Crown this is the kind of tool that is used to make animations for games like that. It is really great software, and some very amazing effects are possible to create with it. Instead of rendering many frames of an animation to flat images you create parts of a body, and then animate those parts. In game, these parts are moved, and rotated based on the Spine animation date generated, which allows for much more efficient and smaller file sized games with great looking animated characters and doodads. You can also make Spine animations with the software Dragon Bones. You are allowed to use this without buying Spine as the Defold team wrote their own Spine runtime although you should certainly buy Spine if you are a professional to ensure that the official software can survive being developed. Not all newer features of Spine are supported in Defold's Spine runtime.

**Spine Scene (\*.spinescene)**: Before you can define a Spine Scene in a Spine Model, you must first create the Spine Scene and define the location of a spine\_json file, which is the animation data generated by the Spine application, and you must create an Atlas file in Defold, which has all of the images used in your Spine animation. You can make many different spine animations, and then put all of their image parts into the same Atlases to be more efficient if it makes sense to do this. The sample\_rate is by default at 30.0 but this is only how often the data of the spine model is simulated - it will not make your spine animations look bad - you can raise it if you need to, but try some animations first at this default sample rate. For some objects, you may even lower this as they don’t need to be sampled as often.

**Sprite (\*.sprite)***:* It is more common to add Sprite Files directly as components to Game Objects, but you can still create them as single files too. After creating, you define the Atlas image from which you wish to grab a sprite image from by selecting the Default Animation once you have set the right Atlas. You can change the default material if you wish, and set the Sprite’s blending mode to be normal (Alpha), Add (additive - useful for making bright, shiny effects), or Multiply (useful in some situations, but you will probably use it rarely). If you create Animation Groups in your Atlases then Sprites can use this animation data to display flip book style frame by frame animations.&#x20;

**Texture Profiles (\*.texture\_profiles)**: You can define different texture compression for different sets of textures depending on which platforms you are targeting. This can enable you to enable very high texture compression on mobile targets as final binary size is very important. Keep in mind that if you have compression active it can greatly increase the time your game takes to bundle so only enable it while testing that / releasing a build. Defold supports WebP compression, which has significantly better compression than other formats. You may find that by using WebP compassion your game’s final binary is half the size. **Use WebP!**

**Tile Map (\*.tilemap)**: Tile Map files define information such as size of tile area, tile layers, and what tiles, from a Tile Source File, are set for each slot in a layer's grid. You can create level layouts in programs such as [Tiled](https://www.mapeditor.org/), and then export .tilemap files, or export .lua files, and import the .lua file into your in game .tilemap template along with any other metadata you wish to use in .lua layout files which are not possible in standard .tilemap files. For games with big, complex tilemaps either creating your own tile map editor inside of the Defold engine, or using Tiled is a very good idea.

**Tile Source (\*.tilesource)**: The Tile Source file defines the location of the image you would like to get tiles from, tile sizes, and has built in features for extruding tile edges (important to compensate for texture bleeding - you nearly always want this to be set to 2 for tiles).

**Vertex Program (\*.vp)**: Vertex programs (or Vertex Shaders) are part of the GLSL ES shader technology which Defold uses and defines the manipulation of vertex geometry. A Vertex Program is used along with a Fragment Program to define how your objects are rendered. Vertex Programs or Vertex Shaders handle individual vertices of objects. Most of your objects in Defold will be flat, 2d images, but even these have basic vertex geometry. Most likely you will not need to edit the builtin VPs.

**More file formats which are possible to create but not on the default Assets list. You can find samples of these in the builtins folder.**

**Display Profiles (\*.display\_profiles)**: In the Display Profiles File you will define the sizes of displays you wish to target for GUI layouts. The builtin Display Profile default.display\_profile has two Layouts for Portrait and Landscape at widescreen style sizes. With the use of a custom Display Profile, you can make a list of specific screen sizes you wish to build GUI layouts for, and then Defold can automatically pick the closets match when the game is ran on a device. Generally though the built in Landscape and Portrait profiles may be enough for you. To use these layouts you must add them to your GUI files as layouts and then set each layout active while you position the nodes within your GUIs.

**Gamepads File (\*.gamepads)**: A built in one can be found in the builtins/input folder. This file defines mappings and dead zones for specific gamepad models. A dead zone is the area on sticks where input is ignored. Unique mappings based on gamepad model is important to define because of variation of gamepad design and differences of how gamepads map with their driver compared to button position on the physical gamepad. If you make a game which is often played with gamepads you will most likely have complaints from people with rarer gamepad models. You can find gamepad related files on sites like Github which include lists of mappings / dead zone listings other people have already made for most popular models - the builtin file only includes a few. Defold does not currently support multiple gamepads at once; however, you can still have one gamepad and one keyboard input for example, and other more advanced setups, such as using mobile devices as gamepads, are currently possible.

**You may also find references to .texture and .mesh, which are both used internally. There is also .emitter which is used by the ParticleFX files.**


# game.project

Description of all features related to the game.project master project file.

**Note: this is old text still and needs to be updated for latest features.**

The game.project file is the main project file of your project. In it, you enter various important configuration files. You can modify the file directly with a text editor or use the built in Project Editor. If you modify this file directly with a text editor it will not be populated with default values, and you will need to add it all by hand. There are only a few values which can be modified for this file which are not exposed in the Project Editor. The Project Editor does show default values - if a value has not been changed from its default value then Defold will not bother to save that value in the game.project file - once you do change a value even if you change it back to its default it will then begin to be included in the game.project file and be visible in the text if edited directly. When editing files in the Project Editor you must change the input away from the last input you edited to be able to save the most recent changes.

If you edit your game.project file to include additional properties they will be accessible depending on where you place them. You can access these values via sys.get\_config(). For example, print(sys.get\_config(“project.title”)). You can create most any custom group, with most any custom contents. Do note that your game.project file is accessible as plain text so you should not put anything sensitive into it, only useful config information. It would be possible for users to modify your game.project to, for example, bootstrap into a collection you never intended to be the bootstrap. If you wish to you can fix this by having a global value check that is only set when your primary Collection is the actual bootstrap.

You may want to add your Publisher and AppName as custom values, and then use these values when saving your player save data instead of hard coding it deeper into your source. To add custom values, you must edit the game.project file in plain text mode (Open As -> Text).

If you press the icon to the left of text boxes it will revert the values of the fields to default values. Oddly these default values are not the same as the values within the blank project.

project - General project settings. title: The title of your app. Displayed in the titlebar area for desktop builds. When doing iOS and Android builds this is the label used below your app’s icon - when making builds you can quickly modify this, or if you use a custom plist and manifest update the label there. CFBundleDisplayName for iOS/plist, for Android look for the first android:label and customize the value of that - both will by default be what you have set project.title to when you bundle your apps, but because these labels need to be shorter for mobile builds you may want to pick a shorter name vs desktop builds where it can be longer. If you don’t shorten this label for mobile builds it will simply be truncated, sometimes with a … where it has been cut off. version: As you release builds publicly, you can increase this version number. Inside of your game, you can grab this value so that you can display it to your users, or use it for comparison, such as checking client version with latest version available to download. Use: sys.get\_config(“project.version”)

write\_log: If true (1) then the Defold game engine will write logs as the app is ran. These logs can be useful for debugging purposes. A “log.txt” file is created in the root directory of the app. For iOS, you can access logs from iTunes -> Apps -> Files Sharing. For Android, look in the external storage. Use one of the many good Android apps, such as AirDroid, which allows you to remotely access the file system. On Android too, while running the development engine, you can find logs at the following location: /mnt/sdcard/Android/data/com.defold.dmengine/files/log.txt

compress\_archive: If true (1) then archives will be compressed when bundling. Android archives will always be compressed due to the way the platform works. You will generally want this on.

dependencies: This is a comma separated list of Defold hosted library dependency URLs. If you wish to use this feature then the library data must be hosted on the Defold servers as a project, and you must have permission to access it. If you create a library, you can find its proper URL to link to on the online Defold dashboard page for each project. An alternative to this feature is to use git submodules directly, but this takes more to setup.

custom\_resources: (not exposed in Project Editor but should be): Comma separated list of resources you wish to include in your project. You can list folders or specific files. Note that you should not include the leading slash when specifying folders. Including custom resources is necessary when you wish to arbitrarily run Lua files which you do not know the names of before compiling your project, such as RPG related scripted events.

display - Resolution and display settings. Currently Defold does not have any graphics throttling in place, and relies entirely on your system’s vsync. Sometimes when your graphics card drivers are updated or out of date things can go wrong. If your game runs too quickly on your desktop you may need to go into your graphics card settings and force vsync on.

width, height: The width and height of your project. You may use these values if you use custom rendering scripts.

high\_dpi: If true (1) then support for high-dpi screens will be enabled on Windows and Mac. If your computer has a high-dpi screen you will want to enable this option. samples: A whole number value greater than 0 will enabled super sampling for your project. Your project will be drawn at 2 \* x size, and then scaled down. This feature can greatly impact performance. It is meant to remove or smooth jagged edges. Don’t turn this feature on unless your target hardware can handle it as you currently cannot toggle it at runtime. In general, leave it off (0).

fullscreen: If true (1) enables fullscreen for desktop targets. Currently there is a bug with desktop fullscreen in that the native screen size is not used, and instead a default smaller size is used, leading to bad quality image. There also currently no ability to toggle fullscreen as runtime, or change resolution. Hopefully this improves in the future. update\_frequency: How often your game goes through its update loops. Valid values are 60, 30, 20, 15, 12, 10, 6, 5, 4, 3, 2, 1

variable\_dt: This, if set to true (1), allows the update frequency to be at a variable rate, and instead of maintaining a constant delta time passed to update loops as an argument, it allows updates as often as possible. Depending on your project you may want this checked or unchecked. Generally it is better to have a fixed rate if your game is using physics simulations (if dt becomes inconsistent then your simulation results can vary where if the dt was consistent then the results would be the same every time) but otherwise it's generally better to have variable delta timing on, and to not rely on a fixed delta time in your scripts.

display\_profiles: Defines the location of your .display\_profiles file for your project, which contains the various sizes of screen size layouts in whatever proportions you wish to support. If you edit the location directly you must include the c at the end for the eventual compiled version.

dynamic\_orientation: If set to true (1) then when you change your device’s orientation the project will automatically select the best fitting layout for that size and orientation. Note that the iOS development engine does not respect this setting value and always supports dynamic orientation; however, the release build does respect this value.

physics - Settings. type: Your project can either use 2D or 3D physics. Capsule Shapes are only functional with 3D physics enabled; however, with 3D physics enabled there are other considerations you must make for your project too. You can also compose capsule like shapes (good for certain platforms) out of 2 circles and a rectangle.

gravity\_y: y-axis gravity. Default value is -10, which moves physics objects, which are modified by gravity, to move downward. debug: If true (1) then physics objects will have their geometry drawn. Otherwise physics objects (spheres, rectangles, capsules, and so on) are invisible. Turn this on to better visualize and debug your game’s physics.

debug\_alpha: This value can be from 0-1. Making the value closer to 1 makes it more visible, closer to 0 more invisible.

world\_count: The maximum allowed number of physics worlds. If you have physics simulations happening inside of a collection loaded via a collection proxy then that is an independent world. You should carefully load and unload your collections so that you do not have more physics worlds active at once than you really need. Default max is 4, but this is more of a buffer for loading/unloading and you should try to use as few as possible at once.

gravity\_x: x-axis world gravity.

gravity\_z: z-axis world gravity.

scale: Value can be from 0.01 to 1. Defines scale of physics worlds relative to game world. Adjust this value to fix the scaling for your project.

debug\_scale: If you have debug enabled then, depending on your setup, you will be able to visibly see unit objects such as triads (the x,y,z origin arrows) and normals (a ray which is perpendicular to another line). This value defines the scale of these units.

max\_collisions: Max concurrent collisions that will be reported.

max\_contacts: Max concurrent contact points that will be reported.

contact\_impulse\_limit: If set to a value higher than 0 then any contact impulses which are lower than the value will be ignored.

bootstrap - initial settings passed to Defold’s game engine. main\_collection: The main starting point for your project. Note that when editing this value in the Project Editor it will automatically append a c at the end so as to point to the compiled version of the collection file. For example, /main/main.collectionc - you must point to the compiled version too if you edit directly. The same is true for other files which are linked to in the same way.

render: The render file to use - not the render script (which is defined in the render file). You can define multiple types of behaviors in your render script so only one is necessary.

graphics - Settings. default\_texture\_min\_filter: Default filter to use when min (minification) filtering. Set to either linear or nearest (good for pixel art games).

default\_texture\_mag\_filter: Default filter to use when mag (magnification) filtering. Set to either linear or nearest. These two min/mag are used when rendering images in the running game engine. If you are making a pixel art game then you will need to edit some other areas where there is filtering, such as with fonts, so that they use linear filtering as not all respect these default values.

max\_debug\_vertices: When drawing visual debug information, for physics and other objects, this setting determines the maximum allowed.

texture\_profiles: Define the location of your .texture\_profiles file. This does not point to a c / compiled version. Your .texture\_profiles file determines how different folders of image files are processed for different platforms when you bundle your game. Keep in mind that the default .texture\_profiles does not use the WebP format as support for it was only recently added. It’s a very good idea to use this format in your own projects as it will greatly reduce your bundled file size.

sound - Settings. gain: The default gain in linear scale generally from 1 to 0. Read the chapter on sounds for more information.

max\_sound\_data: The maximum number of unique sound files allowed.

max\_sound\_buffers: Maximum number of unique sounds loaded at once. Buffers hold sound data.

max\_sound\_sources: Maximum number of concurrently playing sounds.

max\_sound\_instances: The maximum number of sound components allowed active at once.

resources - Loading and resource management settings for HTML5 builds. http\_cache: If true (1) then resources will be cached locally (saved) and reloaded from cache instead of from the server when needed. Add a ?version=number or some kind of tag to force refresh with this option enabled.

uri: Defines where to find the game.project config file.

max\_resources: The maximum number of unique resources allowed to be loaded at a time. Fonts, for example, count as two resources. input - Settings.

repeat\_delay: How long in seconds before treating an input, which is pressed, as a repeating, held down input.

repeat\_interval: Once an input is treated as a repeated input, how often it counts as an event. Lower to have faster intervals. If you do not want a delay between events then don't use action.repeated which this is for.

gamepads: File references to a .gamepadsc file. The .gamepad files includes information on various .gamepad models and how you wish to support them. game\_binding: File reference to your .input\_binding file’s compiled version .input\_bindingc.

sprite - Settings. max\_count: Maximum number of sprite components allowed at once.

subpixels: While false (0), sprites are forced to be aligned to pixels. While true (1), sprites are no longer forced to align with pixels. This option is checked by default, and so the default behavior is to not snap align sprites to the pixel grid.

collection - Settings. max\_instances: Maximum number of instances of objects / components allowed at once.

collection\_proxy - Settings. max\_count: Maximum number of collection proxies allowed at once while the engine is running.

collectionfactory - Settings. max\_count: Maximum number of collection factories allowed at once.

factory - Game Object Factory Settings. max\_count: Maximum number of factories allowed at once.

ios - Settings. appicon\*: Various sizes of pre-made icons sizes which iOS will use when showing your app’s icon in different screens / devices. You can use or buy <https://iconverticons.com/online/> to quickly generate all of the image sizes you need.

launchimage\*: These images are the hardware launch image shown at the start of your game. iOS first displays this image, and then once your app is loaded switches to your app. Apple suggests that you keep the launch image and the very first thing you display to your users the same. This design is meant to make apps look like they always launch instantly upon being opened. You must specify launch image files of each appropriate size for your game to display properly while testing on iOS!

pre\_rendered\_icons: If true (1) will disable the overlay which iOS adds to icons otherwise. If you do not disable this option then your final icon will have an extra gloss layer added on top by iOS.

bundle\_identifier: Generally this is in the format of com.company.product.version - it is a unique identifier of your app, and is in this way so that no other app in the world will have the same identifier. The first part of the identifier is generally based on your primary web-site domain, and it’s only possible for one company to own a unique domain so this in the best case should ensure uniqueness.

infoplist: If you wish to use a custom Info.plist file you can define one here. You can duplicate the standard infoplist included with Defold, and modify it to your needs. Remember that as Defold updates are released you may need to manually update your custom infoplist file so that all features work.

android - Settings. appicon\*: Pre-made icon images of various sizes which are used in different areas of the Android OS.

pushicon\*: Pre-made icon images of various sizes which are shown on the user receiving a push notification for the game app.

push\_field\_title: Specifies which field in the payload JSON to be used as the text title by default.

push\_field\_text: Specifies which field in the payload JSON to be used as the text body by default.

version\_code: Must be an integer. This is an internal number which must increase as you release builds and public them to the Android markets. A higher number determines that a build is more recent. This is not shown to users anywhere. Simply increase it by 1 each new version.

package: The unique package identifier generally in the form of com.company.app

gcm\_sender\_id: Google Cloud Messaging Sender ID. When you set up your app in the Google Play Developer Console you can get this ID from your app’s Services & APIs tab. This must be set to enable push notifications for Android on Google Play.

manifest: If you wish you can define a custom manifest file. The best practice is to bundle your Android application once, and then take the generated manifest from within it. Then customize it as you need. As new versions of Defold are released, you may need to redo this in order to get most recent changes which the Defold engine needs.

iap\_provider: This can be set to either “Amazon” or “GooglePlay” depending on which store you are building for. Defold supports the Amazon 2.0 store API. Defold will default to assuming “GooglePlay”.

input\_method: The default value is KeyEvent, which represents the older style of input for Android devices, and is default only to prevent breakage for older Defold projects. You should absolutely always change this value to HiddenInputField as it does a better job of handling popular software keyboards. The KeyEvent is the default only so as to not break older Defold projects.

osx - Mac OS X Settings. app\_icon: The .icns icon file used for the Mac OS X .app file generated. You can use the site <https://iconverticons.com/online/> to generate a .icns file from a .png file. You can use up to a 1024x1024 image and it will generate all of the sizes.

infoplist: Like with iOS apps you can use custom Info.plist files. If you wish to use a custom infoplist first bundle your app for Mac OS X, and then right click on the app -> Show Package Contents -> Contents -> Copy and paste the Info.plist file there into your Defold project’s folder, then define that within your game.project file. bundle\_identifier: Unique bundle identifier generally in the form of com.company.app for example: com.apple.itunes

windows - Settings app\_icon: The .ico file used when you make Windows build bundles. This file is used by the main .exe file as its icon. Again you can use the site <https://iconverticons.com/online/> to generate your .ico from a .png file. The site will automatically generate the correct sizes based off your source image as long as you upload a large enough image. 1024x1024 or 512x512 would be fine.

html5 - Settings. set\_custom\_heap\_size: If true (1) a custom heap size will be set.

custom\_heap\_size: Custom heap size expressed in bytes. The default value is shown as 0 in the Project Editor, but this should not be used. The true default heap size is 256MB of memory - 268435456 Bytes. You most likely will not need to increase this value, and instead more likely will want to decrease this value when optimizing your game so that your project prepares a smaller heap size. include\_dev\_tool: If true (1) then when you bundle HTML5 builds memory tracking tools will be included.

htmlfile, cssfile: For convenience, you can define custom .html and .css files for HTML5 builds. You should make your custom versions based off the versions made when you bundle your HTML5 app as these files will not be processed at all only included in the ultimate bundle.

splash\_image: You can define a custom splash screen image, which is loaded by the browser, and shown while your application data is being loaded in the background. By default, a progress bar is shown too. All of this can be customized, and is covered in the later chapter Releasing on HTML5.

archive\_location\_prefix: Allows you to define an alternative location to host your archive file, such as hosting it on a CDN. For example, “<http://mygreatcdn.com/games/my_game/“>

archive\_location\_suffix: As you update your HTML5 game, you may need to ensure that the updated version, and not the cached version is downloaded. You can add a suffix to the end of your archive location URI in order to force the user’s client to download the newer version. For example, “?build=5”

particle\_fx - ParticleFX Settings. max\_count: The maximum number of ParticleFX instances allowed.

max\_particle\_count: The maximum number of single particles allowed over all Particle FX instances.

iap - In App Purchase Settings. auto\_finish\_transactions: If true (1) then IAP transactions will be auto finished after they have been initiated and did not error. If you do not have this set to true then you must handling finalizing transactions yourself. For example: “iap.finish(self, transaction)” see later chapter on IAP for more information on handling IAP transactions properly.

network - Settings http\_timeout: How long to wait in seconds before timing out HTTP requests. You can also define custom http timeouts in seconds with every http.request call. See later chapter on HTTP Requests.

library - When this project is used as a library for another project. include\_dirs: Space separated list of directories which will be included by any projects which include this project as a library through Defold’s systems.

script - Settings. shared\_state: If true (1) state will be shared between all Lua scripts. By default, Defold keeps unique context between the different script types: Game Object scripts, GUI scripts, and the Render script. Rather than enable shared state, it’s generally better to access shared data instead through included Lua modules. Having shared\_state temporarily enabled can be useful with debugging.

tracking - Defold application tracking settings. app\_id: A unique App ID for your Defold project can be found on its dashboard page. If you do not define an App ID no analytics tracking will take place. If you do enter your App ID, and then open your app, it will send basic usage data to the Defold servers, which you can then view on your Defold dashboard for the project. Usage data is very useful when making decisions for your project’s future. The Defold team plans to improve the Defold Analytics to include features such as custom events. So you could, for example, view the number of times your users have completed a specific level, or how far they went through your tutorial before giving up - this kind of data can give you a highly valuable insight into what you need to improve to keep your users happy and playing.


# Defold Tips


# Anchored GUIs

Do you want groups of GUI elements to be anchored to a corner of your game's screen? You'll need to do something which may not be obvious to you at first to make the GUI elements look right.

When you first attempt to anchor GUI elements to an area to the screen you may do it simply by setting each GUI node to have an X and Y anchor and a pivot. But if you scale the screen you may notice some issues with spacing.

![Unscaled Window](https://59336108-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LHnmfJK3HDz-s0f74qO%2F-LJLGsonuhEWLq_04RSr%2F-LJLIzU0pkojETuJJEpd%2F2018-08-07%2014_32_54-AnchoredGUIs.png?alt=media\&token=2331e2c4-c346-48e1-8ce3-f52f8609ea01)

![Scaled Window](https://59336108-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LHnmfJK3HDz-s0f74qO%2F-LJLGsonuhEWLq_04RSr%2F-LJLJ21ghgghP7XfNkIj%2F2018-08-07%2014_32_46-AnchoredGUIs.png?alt=media\&token=19de6cdb-72c4-4e53-802a-bf3d3946aa74)

As can be seen in the "Scaled Window" image above, the spacing between the nodes is inconsistent with the amount of scaling.&#x20;

The fix for this is easy!

For each area of the screen you wish to anchor nodes to, you must create a parent anchor GUI node.&#x20;

Create a box node. Set its size mode to manual, and set its size to 0,0,0. This will make it invisible.

![](https://59336108-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LHnmfJK3HDz-s0f74qO%2F-LJLGsonuhEWLq_04RSr%2F-LJLJfNUpfqXgj6CnD2R%2F2018-08-07%2014_36_51-Window.png?alt=media\&token=cf6c9d62-ea1d-4429-bbe9-6c6735c332f1)

Then set the anchor box node to have the anchor type you want. In this case X anchor left, Y anchor top.

![](https://59336108-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LHnmfJK3HDz-s0f74qO%2F-LJLGsonuhEWLq_04RSr%2F-LJLKdUxvFZ-42Gu3vro%2F2018-08-07%2014_41_26-Window.png?alt=media\&token=2fc5d0c7-6e79-43dd-bfb4-46d0afcef227)

Now you can move the box node to the area of the screen you wish to anchor other GUIs to.

![](https://59336108-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LHnmfJK3HDz-s0f74qO%2F-LJLGsonuhEWLq_04RSr%2F-LJLK5RzrW9RrRUtKUg3%2F2018-08-07%2014_39_02-Defold%20Editor%202.0%20-%20AnchoredGUIs.png?alt=media\&token=3d8299fa-4b0f-4854-a991-e12f8ec8d87c)

Then parent the other elements to this anchor GUI. You'll need to update their positions as they will now be relative to the anchor GUI.

![](https://59336108-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LHnmfJK3HDz-s0f74qO%2F-LJLLkmcdiDUsx2SBBLA%2F-LJLLpRcfDVEyYDFLWoJ%2F2018-08-07%2014_46_34-Defold%20Editor%202.0%20-%20AnchoredGUIs.png?alt=media\&token=4bf8bb11-71dd-4dd7-bbd4-d916c25ea3d6)

Now when you scale the window the GUI elements will look to be spaced more consistently.

![](https://59336108-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LHnmfJK3HDz-s0f74qO%2F-LJLGsonuhEWLq_04RSr%2F-LJLKpYPOBA9mhdQkQeO%2F2018-08-07%2014_41_59-AnchoredGUIs.png?alt=media\&token=06694f97-2961-4998-a9bd-0bc8120dedd8)

You should generally follow this example when anchoring elements to areas of the screen as even in less extreme scaling situations the spacing can look off without this.&#x20;

Using anchor GUIs can be useful for general GUI organization as well.


# GUIs for Window Size

Reference your game's window size when editing a collection.

Currently the live version of the editor does not show you the size of your game window set in your game.project file.

You can create a blank .gui file, add it to your collection, and then you'll be able to see the size of your game's window. This can help you with placement for some kinds of setups.

![](https://59336108-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LHnmfJK3HDz-s0f74qO%2F-LJMJlGdKQepJ7lXfENY%2F-LJMKX1qXB2BqxoXn319%2F2018-08-07%2019_20_22-Defold%20Editor%202.0%20-%20LaserExample.png?alt=media\&token=2f34af28-7dcf-48a6-9a50-723e951f2569)


# Pixel Art Assets


# Lua Tips


# Lua Tables

Learn useful information about Lua Tables!

**WIP**

Tables are a very important part of working with Lua code within Defold. Tables are simple to use, powerful, and flexible enough to make the features you need.

### Table Basics

{% embed url="<https://repl.it/@pkeod/TableBasics>" %}


# About math.random()

When you call math.random() without setting a seed you will get the same values each time every time you run your game. This is due to the way "random" values are generated. Generally you would set the seed to os.time() to make the "random" generation based on the current timestamp of the user, which functionally makes your random generation look to actually be random each time your game is ran, but would still generate the same random numbers each time if you used the same timestamp.

There is another issue however - the first few values generated by math.random() are usually the same no matter what. This is due to the way the builtin Lua RNG method generates numbers. To compensate this, you should always dispose of the initial values generated.

```lua
math.randomseed(os.time()) -- sets seed to the current time
math.random();math.random();math.random(); -- discards first few RNG numbers
print(math.random(), math.random(), math.random()) -- some random numbers between 0 and 1
print(math.random(0,1), math.random(0,1), math.random(0,1)) -- either 0 or 1 randomly
```

{% embed url="<https://repl.it/@pkeod/MathRandomExample>" %}


# Randomly 1 or -1

```lua
math.random(1,2) * 2 - 3
```

The above code can be used to get a random value of either 1 or -1.

1 \* 2 = 2 - 3 = -1

2 \* 2 = 4 - 3 = 1

Getting 1 or -1 can be useful for setting a value to be randomly negative or positive when multiplied by the random value. This can be useful for example for setting a direction randomly.

{% embed url="<https://repl.it/@pkeod/Randomly1or-1>" %}


# Lua Modules

How to create and use Lua modules.

Lua modules are useful for sharing functions and data between your scripts.&#x20;

To be able to share data between scripts, make sure you have "shared state" checked in your game.project file.

You can create a Lua module by right clicking on the asset panel and going New -> Lua Module you can then name this file and create it.

This is just a .lua file which can be created with other tools as well.

The default Lua module is blank with some comments only.

The standard pattern for a Lua module file is as follows:

{% code title="mymodule.lua" %}

```lua
local M = {}

return M
```

{% endcode %}

The standard way to include a Lua module in another script is as follows:

```lua
local mymodule = require("mymodule")
```

If you had your mymodule.lua file within a utils folder then your include would be:

```lua
local mymodule = require("utils.mymodule")
```

We will edit our Lua module to add a function and a variable.

{% code title="mymodule.lua" %}

```lua
local M = {}
M.secret = 777

-- you can get and set the M.secret value outside of the module

function M.hello_world()
    print("Hello World Defold!")
end

-- you could call M.hello_world() here once too
-- if you wanted any function to be called once for your module
-- such as an init function which checks to see if it
-- has already been initialized or not

-- you can also define local functions here
-- local functions in a module are private to that module

return M
```

{% endcode %}

Then in a script we can include and use the module's function:

{% code title="main.script" %}

```lua
local mymodule = require("utils.mymodule")

function init(self)
	print(mymodule.secret)
	mymodule.secret = 25
	print(mymodule.secret)
	mymodule.hello_world()
end

```

{% endcode %}

```
DEBUG:SCRIPT: 777
DEBUG:SCRIPT: 25
DEBUG:SCRIPT: Hello World Defold!
```

{% file src="/files/-LJPfu6aRNEw5yySiLa7" %}

If you look through the source of assets published on the community portal most of them are Lua modules which follow this similar pattern.

If you wish to share your module then you'll want to give it a catchy name, then put it inside of a folder with that name. For example "log/log.lua" see here <https://github.com/subsoap/log>

Then in the game.project file you would define the "log" folder as a include dir in the library area. See Log's setup for an example of this.

Sharing modules on Github is currently the most popular way of sharing modules. Again, see how others are done and copy them. There are still many resources which have no Defold version so there is still opportunity for you to contribute to the community! When you do publish something make sure you use a license which has as much freedom for its users as possible if you want people to actually use it. If you want to put your work into the public domain like I generally do then you can use the **Creative Commons Zero v1.0 Universal** license.


# Global Scope

If you do not define your variables locally then they will be available globally within your scripts. This can be very dangerous, can cause difficult to debug bugs so use with care. It can be better to share data between scripts with a Lua module rather than to put data into the global scope for example.

Sometimes you do want to put functions / modules / data into the global scope. It's as easy as not putting local before your definitions. For example, you might want to use the [log module](https://github.com/subsoap/log) and to have it able to be used in all of your scripts without needing to require it in every script. To do so, you would require it once in your main entrypoint. For example, in the main.script of your main.collection.

```lua
log = require("log.log") -- log is global!
```

It's also possible to replace some tables within the global scope at runtime - such as replacing the builtin print function. Know that it's possible but use it with care as you can break the way the engine is meant to work if you're not careful!

If you don't want to mess with the global scope then always remember to add local before every definition you make in your scripts.


# Running Projects

R unning Your Projects You can launch your game application at any time by going to Project -> Build. This will by default build for your local OS, and then launch immediately. Projects built in this way are always in debug mode and not release mode.

If you are using Defold’s library system then you may need to get the latest version of your library files before making a build. Project -> Fetch Libraries will do this for you. Defold does not grab the latest version of libraries for you otherwise. Libraries need not be hosted on official Defold servers, can can be fetched from, for example, publish GitHub hosted git repositories too.

To test your app on other devices, such as on iOS or Android devices, you will need to setup the Defold development app on your device. Once you do, you will be able to select Project -> Target, and change it to your device. Then, when you make new builds, with the test device selected, it will have new build bundles uploaded to it and then ran - as long as you have the development app open and ready to accept new builds. If you hot reload files while having an active running build those resources will hot reload on the target devices.

While the Defold editor is running, it will do target discovery. If you click Project -> Target Discovery Log you will be able to see the text log of this service.

If you know the IP address of your local area network device which is running the engine you can manully enter its IP

For Android, navigate to <http://d.defold.com/> on your Android device, and expand the version number of the same build as your Defold Editor’s current version. Look for “dmengine.apk” and download this to your device. Once opened, you should be able to see that Android device as an option on the Project -> Target list as long as your computer, where the Defold Editor is running on, and the Android device are on the same local network. The “AirDroid” app is a useful app to use for development as it allows remote management of your device’s filesystem. You can bundle apks and upload them to your Android device with this app. You may need to enable remote sources to install APKs directly. If you wish to test features such a IAP then you must sign your apk properly, set it up properly with Google Play Developer Console, and upload it to the Google Play store as a beta build. The developer portal for Google Play allows for uploading and downloading test builds from its service. Check the later chapter on Android for more instructions.

For iOS testing, you must be on an OS X device to make the signed build, you must first be signed up as an iOS developer, create a provisioning profile for your app (which has your test devices enabled), go to Project-> Sign iOS Executable…, select code signing identity (you may first need to set this up with Xcode)(choose iPhone Distribution option), select your provisioning profile file after having downloaded it (create for adhoc distribution), then click Sign and Upload. You will then need to go to the Defold Dashboard on the Settings tabfor your project and download the app listed there. This will download the Defold Engine app, which, once open, will then be able to have builds pushed to it once it as selected as Project Target. Check the later chapter for iOS for more instructions.

If you have the development app open and it says “Waiting for connection…”, but you can’t see the device on the target list, you can try to close and re-open the Defold Editor, close and re-open the app, or wait longer for it to show up. You can reuse the same dev apps for multiple Defold projects, but if your Defold Editor updates then you will need to go through the same processes to get new development apps on your device (you will be warned of version mismatch if you try with older versions).

If you wish to distribute your Android/iOS game so that others can test it there are more considerations necessary. See the later chapters on distributing for Android and iOS. With apps running, and launched with this method, you are able to do hot code reloading. Go to Edit -> Reload Resources when you have a script open that you wish to hot reload. Hot code reloading can sometimes break your game, which is why the “on\_reload(self)” function exists to compensate for any problems. Using hot code reloading can be much faster than waiting for the entire project to rebuild and relaunch so use it! Besides scripts, you can also hot-reload shaders, and some other resource types such as Atlases, Game Objects, GUI files, but not Collections.

If you create many kinds of files or components, such as Collection Proxies, and do not properly define them then when you go to run your project there will be errors preventing you from doing so. Only create files that need full definitions when you are ready to use them. Generally when you go to run your project, while having incomplete entries, related errors will appear.


# Bundling Projects

When you need to test builds on devices, or your project is ready to release to the public, you will want to make platform specific build bundles of your project. Before you do, make sure you have the correct settings for each target platform setup in your game.project file. Defold will attempt to use builtin defaults where it can, but for some targets you will need to setup certain files such as certificates, provisioning profiles, and, in the case of iOS, launch screen images to properly run.

To make bundled builds go to Project -> Bundle -> and then pick the platform which you intend to make a build for.

For each platform, you’ll be shown a dialog box to confirm more information.

By checking “Release mode” your build will have less of the debug features enabled (as of this writing, if you are using a Native Extension this release mode checkbox does not work, you must also use an appmanifest file to specify a true release mode build). When publishing builds publicly this is generally an option you want enabled. By checking “Generate build report” a report.html file will be made which details all of the drive space usage of all of the resources of your project. Use this information to adjust compression of your assets so that you can reduce the final size of your bundled game binary.

It is possible to make bundled builds using command line tools. Check the later part of this chapter for information on this.

When you make games your game data is packed. For most users, your game assets including images and scripts won’t be accessible, but for power users it’s always possible for them to access these files no matter what engine or tool you use to make games. Keep this in mind, and don’t put any sensitive files into your game project. Assume that eventually anyone motivated enough will be able to get into it.


# Releasing Projects


# Command Line Tools


# Debugging Projects

### Debugging Tools

todo

### Web Profiler

So long as you are running a debug build / using an appmanifest which does not strip profiling, you you use the web profiler to inspect your running project. This is done simply by running the project and going to <http://localhost:8001/> in your browser. (**todo** test with other non-localhost targets)

You will see a page where you can capture frame data from the engine. You can also inspect the sizes of all resources currently being used in your project.&#x20;

Clicking the **Capture** button to get data from a fresh frame.

By using the web profiler, you can get a clue as to what is taking the most processing during each frame. If your game is running slow this is where you can go to see why. The example images below are for an empty project.

![](https://59336108-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LHnmfJK3HDz-s0f74qO%2F-LKNJ4JLdjaafpwkSDTW%2F-LKNKFPM0ydwz9DAwiAP%2F2018-08-20%2000_21_35-Window.png?alt=media\&token=0e198ef9-512a-49b3-8b16-1e60cfbd6709)

![](https://59336108-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LHnmfJK3HDz-s0f74qO%2F-LKNJ4JLdjaafpwkSDTW%2F-LKNKIXgVHP5QftunpKw%2F2018-08-20%2000_21_47-Dynamo%20Profiler.png?alt=media\&token=83d33618-54ce-4eb0-8387-776569df45b9)

**todo** explain all of the options in the list.


# Make Games Now!

The **Dive into Defold** section will guide you through making several full games using Defold. You do not need to read any other section first before you begin this section. You must **follow along** and not simply read. By following along, you will be able to learn more quickly and remember what you've read long term.

**Notice:** Currently examples are being put up. Later on step by step tutorials will be put up for each example. You can still learn valuable insights by reading the source of examples.

You will need to download Defold first and make sure it runs. Defold has an auto-update feature so you can easily get up to date from any other version.

**Linux** <https://www.defold.com/download/editor2/Defold-x86_64-linux.zip>

**Mac** <https://www.defold.com/download/editor2/Defold-x86_64-darwin.dmg>

**Win** <https://www.defold.com/download/editor2/Defold-x86_64-win32.zip>


# Avoider - Action

Avoid a wave of enemies for as long as possible.

![](https://59336108-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LHnmfJK3HDz-s0f74qO%2F-LJPqvb13xwnbzmzwJCZ%2F-LJPrXn9o_jHGtvIa4zT%2F2018-08-08%2011_47_46-Window.png?alt=media\&token=325c344d-0761-43e5-9b06-b6c2ab6e454b)

The features of this game are:

* 2D action game.
* Player attempts to survive as long as possible. Best high score listed.
* Player controls a yellow smile face character with wasd or arrow keys. Player character can loop around the game board, but enemies cannot.
* Enemies spawn in from the middle and are ghosts for a few seconds before they can harm the player.

Demo: <https://www.bookofdefold.com/dive-into-defold/avoider/>

{% file src="/files/-LJPrbWOnrJGesJj7uXG" %}


# Asteroids - Action

WIP

![](https://59336108-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LHnmfJK3HDz-s0f74qO%2F-LJRWaPG3CA8utKv0IFp%2F-LJRWd6Khaelz8bMF3TR%2F2018-08-08%2019_23_40-Window.png?alt=media\&token=13e2fb3f-446d-466b-85fc-8e0479cc3335)


# Level Editor - Tool

The basics for creating a level editor in the Defold engine.

Making your own custom level editors can be useful. Depending on the type of game you are making there may be no other tool, such as Tiled, which enables you to make level layouts quickly.


# Learn Programming

### **For Absolute Beginners**&#x20;

Defold is an excellent tool for first time creators to use to learn programming. It enables you to get into making games without being overwhelmed, and is still capable of advanced usage. Above all else, don’t ever get discouraged, don’t allow yourself to get overwhelmed. Take breaks when you need to, but always keep coming back. Break projects down into individual tasks, and focus only on single problems one at a time. Give yourself a bullet point list of very small goals to accomplish every time you work. If you face a problem that you don’t understand do a search to try to find answers (site:defold.com ...), and ask questions. Search first. Know that there are no dumb questions (although if you keep asking questions which have already been answered / keep asking questions which reading the manuals once through would answer it can get annoying). The community will be happy to answer any questions as best as it can. If something is not clear in a thread where a question was already answered then ask for more clarity.

### Deliberate Practice&#x20;

A good way to learn is to do. Read chapters in this book, and attempt to implement the features discussed on your own. When you see code do not copy and paste ever. Instead write code out on your own. Think about what each bit of code might do. You will sometimes make mistakes with typing example code, but this is OK. Making mistakes and learning from them can help you to learn and remember long term.

If your goal is to master the features of Defold, to be able to make any kind of game you wish to with Defold, then it is in your interest to work with Defold daily. Don’t go a day without opening the Defold Editor and working on something. Keep a list of features you wish to implement, and do one at a time. Always have a specific goal before you start each day. Learn new things every day. Ask questions in the community forum. Search for answers in the official docs. Pick specific problems you want to solve, and tackle those small and focused problems for the day. Break your larger goals into small lists of specific tasks, and only focus on those small, focused tasks until they are done.

Take notes, and consider writing tutorials of your own, because teaching can also be a great way to solidify your knowledge. Anyone with the desire to can make games, and with Defold you can make better games faster.

### Coding Tips

Don’t try to be smart when writing code. Have you ever written code in the past, and then came back to it sometime later and wondered how it even works? This shouldn’t happen. You should write code as simple as possible, and on as many lines as is needed to make each step have perfect clarity. Anyone should be able to look at a line of code and understand how it works, how it transforms data.

Use math instead of conditional statements (if then else …) when you can. This requires understanding more math, which you should endeavor to learn. Mathematical methods can be clearer, be more flexible, and be less likely to be buggy than long lists of conditional statements.

Avoid duplicate function calls. If you have a long list of a repeated function call consider a rework. Transform the data instead, and then call the function call a single time at the end of the block of code.

Don’t create Lua tables when you don’t need to - such as with return statements. Lua supports returning multiple values, which can then be assigned to multiple variables. Creating Lua tables has a cost (memory / garbage collection), and so should be avoided when it’s not necessary.

Don’t allow yourself to go into feature creep. Only code features you immediately need. Avoid building tools - especially for projects where you don’t have a genuinely fun prototype yet. Use tools by others as much as you can to increase your productivity. Defold is this kind of tool - it has so much built in that enables you to get to making the actual game faster.

Keep your code clean and tidy. Leave it better than how you found it. Avoid duplicating functionality all over your code.

Spend your time really learning the features of Lua: tables, metatables , coroutines, modules as a start.

Explore the library of available Lua modules published on the community portal, and make examples with integrate the features into Defold projects. There is a great amount of work done by others that is freely available for you to use, and you should use these resources if they enable you to make your games better.

Ask others to review your code. You may feel shy, insecure about your code. You don’t want others to think less of you for possibly doing things the hard way or in a dumb way. This is normal. Everyone feels this way even if they won't admit it. You don’t have to throw your code into the world. You can find mentors who you can trust who can help you to improve your code quality. The most important thing is that you are getting code reviews done as it will help you to learn through the mistakes others have made and learned from before. Even less experienced coders can be useful for doing reviews - we all don’t know everything, and they may have some insights which you, as a more experienced coder, don’t. If someone is harsh about your code don’t take it personally, and don’t attack them.

Your code may be honestly trash, but someone being harsh is talking about the probably naively written code and not you. Learn, move on, and do better.

Offer to review the code of others. You can learn new things, and help share your own learning and problem solving insights.


# Game Business

### General Gamedev Tips

Explore the Defold editor fully. Create every kind of file, open its editor, and interact with it. Understanding the relationship between the different kinds of tools available to you is important to being productive.

Learn Lua. Practice every day making examples that target some kind of problem that you wish to solve.

Learn the Defold API. Begin with reading the entire API and what each part does, and then begin to make examples using each part of the API. Do not go a day without studying and practicing. If you wish to you could make a thread on the official Defold forums documenting what you have learned that day. This can help you solidify your knowledge, and potentially help others if you run into problems which can then become searchable.

Your ultimate goal with learning Lua and the Defold API is to not need to reference documentation while working. You should have as much of what is useful memorized, which, in the case of Lua and Defold, is the majority. Use tools such as <https://www.defold.com/community/projects/78498/> to help you quickly look up features.

Make flashcards and study them every day. The Anki software is free, and can help you with automatic spaced repetition. Once you really learn new concepts, tools, functions, then make flashcards to keep that in your long term memory. If you learn something new, and then don’t use it for a few months you may forget it, but if you stay diligent with studying you will reach mastery sooner. Flash cards are for long term memorization of what you already understand. Don't create flash cards for concepts which you do not yet understand.

Use source control. By using source control, you can maintain a historical record of your projects, and be able to peek back in time, or revert to older code without worry while you work. Defold has built in source control where you can sync your project to Defold’s git servers. This is provided for free, but you can also use other private hosting such as Bitbucket. If you don’t use source control at all then start and stay using it. If you don't use source control you will eventually regret this.

You can still make games before you reach mastery level, and you should. Try to make an example of as many older games which inspire you. If you need ideas ask your friends what games they remember being fun, and then show you the progress of you remaking those ideas.

Stay motivated, but understand that discipline is extremely valuable when you can’t seem to get the motivation. Cultivating willpower is done through doing small tasks, denying yourself small rewards in order to be able to do larger tasks, and deny yourself larger rewards and temptations. The more you practice discipline and willpower the better you will get at staying focused and getting your work done.

Break your projects into bite sized tasks. Try to not dwell on the bigger picture, because thinking about how much work you still need to do can completely overwhelm and demotivate you, and cause you to not want to do any work at all. So instead only focus on one task, and break that further into smaller chunks. Then make yourself focus on only those small tasks, and repeat this process daily. Over time, everything adds up, and using this method you can maintain productivity more reliably.

Know that nothing is truly original - everything is a remix. Chasing originality is the wrong idea to have. Remixing good ideas in new, fresh ways is a much better practice than trying to be completely original. Gain inspiration from everywhere, and use it to make better products. It's easier and often better to build on what already works first then evolve it into its own new thing.

There are no dumb questions. Of course you should search the forums (use site:defold.com search term in Google to search the forums and manuals at the same time) to answers to your questions, but if you can’t find answers and feel stuck then you should create a topic and ask. If you have concerns ask.

Defold takes the hard work out of many elements of game development. But make no mistake that making games, making good games is still time consuming and hard work. You must accept this, and give yourself enough time to get to a mastery level.

Success favors perseverance. You must be willing to fail over and over in order to have a chance to succeed. Some people are more lucky than others by doing the right thing at the right time without thinking about it. You can be smart by making your attempts relevant to what is working now. Many people are seen as overnight successes, because they “became somebody” suddenly when so long they were not seen as anybody, but the years of work and failure is rarely shown. Failure means doing things wrong in order to learn how to do them right. It means improvement. Failure is not necessary to being successful, but you should still not allow fear of failure from preventing you from attempting in the first place, and continue to make attempts as many times as it takes for you to reach your goals.

Never become complacent. You may reach great success, but maintaining it still takes work. Don’t rest on your laurels. If you have great opportunity then take it. If you’ve made a good IP of a game that people like don’t immediately jump to making something completely different. It may not feel great to keep working on the same project so long, but if people like it and are buying it then strongly consider making more of it.

Don’t take on too much at once either, don’t try to do everything. Do one thing at a time, and finish it. Don’t leave projects unfinished. Resist the temptation to work on what’s new and fun. This is something nearly every game developer struggles with. We’re excited, and interested in so many things, but getting distracted is bad, and not putting in the work work to finish what you started is a bad habit to cultivate. After some point, of working on new projects, the honeymoon period fades, and it begins to become real work. This is when having discipline and willpower matters.

Be willing to cut. If gameplay mechanics are not actually fun then cut them. Part of the polishing process is removing things which do not add to the whole to create a new whole that has higher total value even with less content.

Sometimes simple features can be the most compelling. Recognize these, and make room for them in your projects. Empires have been built on taking simple mechanics, and refining them to be extremely compelling games which have garnered hundreds of millions of downloads.

Subdue your gamer / artist / developer ego. People like different things. Some people like super simple mechanics which you may feel you can’t even begin to understand the appeal of. A reaction I see from many dev when they talk about games they think of as being lesser is to over emphasize their disgust. Acting this out does you no good. Reality is that you need to make money, and you need to serve sizable audiences that actually buy things, want things, are willing to watch ads to get. As a commercial developer, it’s in your interest to get to know your audiences that you choose to serve, and have a willingness to make what they want without letting your personal preferences as a gamer get in the way of delivering a quality product that people enjoy. It’s mostly about money and that’s OK, but it’s also about fulfilling the needs and desires of real people. There is a ton of opportunity in the world. Be honest with yourself with what people actually want, and deliver the best example of that product to them.

Do what you can on your own. Be willing to learn new things. Don’t rush to hire people when you can do it yourself. At the same time, recognize that more successful teams are made up of people who specialize on specific tasks. Still, it’s entirely possible to do everything, or most everything on your own with well scoped projects, and still create hits. Avoid hiring full time people for work that you know is only short term. Pay people based on contracts, and make sure you use good contracts so that you only pay people when work is completed - don’t accept excuses - work with professionals. When you do grow your team grow it slowly. Higher exceptional people who can directly impact your team’s ability to produce great games and pay them well.

Be careful with how you spend your time and your money. Don’t spend money just because you are flush with cash. If you get some success, don’t share the news with friends and family. You will find that people will begin to expect things from you (for you to pay - don’t - everyone can pay their fair share), ask things from you (if you loan money to friends or family it can end the relationship - they may avoid you until they can pay you back, and they may never pay you back), and some may even begin to resent you or feel you didn’t earn it and attack you. These are pretty normal things to happen especially with people who come from poverty. You may even begin to feel you didn’t earn it, and feel like you just got lucky. Well, maybe you did do the right thing and the right time, but never forget how much you have worked to get what is yours. It’s your success, and you don’t owe anyone else anything. Do what’s in your best interest first always.

Be careful with partnerships. If you can afford to you should prefer to be the owner and hire others. If you must partner with others then make sure the terms are clearly laid out and documented. Being the one willing to sell your share to others is an easier situation than being the buyer.

Be willing to work for others. Many of us have a strong, independent spirit, but if you lack experience, then you should strongly consider waiting to go indie. Find a good employer who can give you stability, and work super hard to become an indispensable employee. Learn as much as you can, push yourself as much as you can.

When hiring programmers make sure that they sign contracts which state that the work they do for you is entirely owned by you. This may seem like it’s not necessary. After all, if you are paying for it don’t you own it? For the entire rights to the work, not necessarily, and that’s why you should make it absolutely clear in a contract.

Be careful with non-compete contracts both when hiring and working for others. You don’t want to be legally obligated to not work on certain kinds of work for so long after leaving a job. And, when employing, even if you do get someone to sign a non-compete that doesn’t mean it will “protect you”. The truth is that even if someone begins to work on a project similar to what you produce it’s unlikely to eat into your company’s own profits. The gaming industry is growing, and what’s more likely to happen is the work they do brining in more customers into the market, which means more potential for you. My advice is don’t bother. Same with non-disclosure agreements. Most of the time they are a pain without any gain. Just don’t share work with people you don’t trust, and if they do break your trust then they are doing you a favor by telling you to not trust them again. There are kinds of contracts which are very important, such as distribution agreements. Read everything before you sign.

Trademarks are useful, but they can also be costly to maintain (it’s your job to watch for the incorrect use by others, and warn people to stop infringing on them). If you publish a mega hit: absolutely yes try to get it trademarked, but don’t spend time and money getting everything trademarked before it even makes its first sale. Don’t try to trademark common words. Especially single words. Don’t try to block other developers from using single or common words in their own game. The game developer community is extremely hostile to people who try this. What do you trademark? The full name of your game only, and the logo.

Patent offices are notorious for allowing patents of so many absurd things. Don’t patent game mechanics. You will spend time and money to file the paperwork, you may or may not get it approved (it’s a gamble pure and simple), and you’ll have to spend more money and time if you really wish to defend it in court. Unless your plan is to get money from and shut down others who are making similar things (only terrible people who hate games would do this), there is little profit in patenting game mechanics. There is a ton of bad karma if you do.

Know that well made projects can result in products that can produce long term, passive income. This requires paying attention to the market, and having a willingness to make games which are more likely to have long term consistency rather than what’s hot right now.

Sometimes projects have to die and can’t be finished. These kinds of projects are where you can no longer see how they could be fun - what sounded good on paper just isn’t working in practice. Sometimes markets can shift too, and you can be left with a project that no longer is commercially viable. You must make the decision to cut your losses (avoid sunk cost fallacy), or cut the scope of the project down until it can be released.

If you are making and finishing projects that does not mean you have to release them. What matters is that you don’t foster a habit where you leave work unfinished, and to follow through with what you start. The reality of the world is that people are shallow creatures who will judge you for work that doesn’t quite hit the mark, and try to get closer to you for your success. A strategy that seems to work is to only publish your best work, and to not reveal anything about what you are working on until it’s finished. Work to be smarter, but stay humble. Don’t let anything get to your head else you may alienate the people who really matter while surrounding yourself with narcissists. Helping others is great for community, and can help you learn or to solidify knowledge, but you should also make sure you prioritize what matters in your work and not allow distractions to consume too much time.

Always act professionally when dealing with other professionals and customers. If someone acts like a troll, don’t act like a troll back. Don’t point out their behavior to others, don’t signal boost people who may be doing you wrong. Do report credible threats to law enforcement. Don’t try to get others to change their ways directly. Instead "kill them with kindness", and unwavering professionalism. Don’t block - instead you should mute, and ignore. It’s better to never react at all than to show a reaction when you think or feel you or what you have made are being attacked. If you must react, do it privately, or in an offline journal. Some people may be having a bad day, and may become converted to a close ally, or a super loyal fan if you don’t attack back. There are trolls out there, and they quickly lose interest when they realize they can't get any satisfying reaction out of you. Simply put: don’t burn bridges, don’t feed the trolls, don't help people to make yourself into their enemy.

Don’t take customer or press reviews personally. In some situations, it’s good customer service to respond to reviews (for example, to help them fix a technical problem), but not always. It’s better to do and not say. Sometimes reviews by press, especially games press you enjoyed personally, can upset you. Here is what you need to realize about games press: most of them are not gaming enthuists and never were gamers, most are jaded people with uselsss liberal arts degrees who hate video games and hate gamers. The only people whose opinions should matter to you are your direct cusomters who happily pay you money for what you make.

Many people say they wish companies would communicate more, but that doesn’t mean making promises you can’t keep. It is better to not publish release dates than to miss them. Promotion, marketing, building hype is important, but letting people down is very bad. Under promise, over deliver.

It’s OK to hint at a Game 2 in a Game 1, but if you do you should be prepared to work on it immediately, and release it as soon as possible after Game 1. If you’re not prepared to put everything into making a Game 2 after a Game 1, don’t hint at Game 2. Even if you don’t make any hints, if your game is popular people will constantly ask you if there will be a Game 2. Especially if there is a story narrative in your game. Let them know your policy is to not publish release dates or information for unfinished games, and instruct them to sign up for your newsletter so that they can be notified of any news.

When making a Game 2 it is better to make improvements than to redo every part of it from scratch. Don’t try to reinvent what already works, focus on what didn’t work well in the first game and fix that. For example, is there something that people seem to complain about in a very strongly negative way frequently? Fix that first.

Just because people complain about things does not mean you are right to “fix” them. Some game design elements which cause pain are also a reason for why people play. Take random loot for example - people may complain that loot drops are so low, but at the same time if you make them super high then getting loot feels effortless and less rewarding. Players working through pain and to complete their goals can both make people rage quit, and give people a great sense of accomplishment when they succeed. Balancing this is important, and it’s also important to recognize these kinds of features and not just make changes to shut complainers up when you may also be making changes that rob other players of enjoyment.

Iteration is important, but starting projects over from scratch is very bad. Finish what you started first, then make the next full iteration. Game developers are notorious for restarting projects from scratch over and over again when they could have finished and released several full games in succession.

If you don’t have a newsletter - start one immediately (Sendy.co + Linode is good for cheap self hosting), and begin to encourage people to sign up to get news. Try to at least send a few newsletters a year to keep your list warm even if you don’t have real news. Having a list of people’s e-mails can be long term much more valuable than having many Facebook likes or Twitter followers. E-mail does not appear to be going away any time soon, but those social media sites may collapse and shutdown overnight. Still, don’t disregard social media for marketing, but also always keep a newsletter.

Be aware of complying with COPPA. Read the rules, and follow them even if you do not live in the US. If you distribute apps in the US then you must follow COPPA. <https://www.ftc.gov/tips-advice/business-center/guidance/complying-coppa-frequently-asked-questions>

If you are making games not just as a hobby, but as a way to do a profession then you must be brutally honest with yourself as to what various markets want, and what you on your own, or with a small team can produce to meet market demand. Don’t make games no one wants or never asked for. Pay attention to what the market is buying, and playing. There is true opportunity everywhere, but it may take humility to truly see. If you are too proud, have too much hubris then may become blind to opportunity.

Defold might not be the right tool for you and the projects you may want to make. Even if you feel excited about learning and using Defold you should keep and open mind, and maintain a factual perspective of what tools you have available to you. For example, making 3d games with Defold is possible, but it will take extra work compared to other tools such as Stingray, Lumberyard, Unity, or Unreal. If you need a feature now for your project that Defold doesn’t have yet you should strongly consider other tools - the right tool for the job.

Don’t take things for granted. Ask questions. Understand why you are doing something, why you are using something. What does it solve? What does it help you to do? What value does it add? Is it risky? Should I be focusing elsewhere? Why does this problem need this solution? Why should this project be made with Defold?

Try to not waste time. Ask yourself if what you are doing actually matters, actually contributes to your major life goals, and is not just an ultimately time wasting distraction. There is a ton of potential and opportunity in the world, and you only have so much time in your life to go after it.


# Useful Software


# Lasers

Draw lines / lasers.

You can draw lasers / lines easily in Defold. You will need to place the laser/line segments in an atlas with edges extruded at 2.

![](https://59336108-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LHnmfJK3HDz-s0f74qO%2F-LJMLL7X9gyCR8jr-Tl5%2F-LJMLtGYPUveG-ACyFHE%2F2018-08-07%2019_26_31-Untitled-1%20%40%201070%25%20\(Group%201%2C%20RGB_8\)%20_.png?alt=media\&token=2db4d151-0d4f-434a-b124-d8ae66def769)

Your segments need to have a width of 1. Then place their sprites on a .go so that their left side is at x of 0. This may require you to place them at x of 0.5 like in this example.

The important functions used in this example are dist2d to get the distances between two 2d points - this is used to determine how far to stretch the laser which is done through setting the x scale of the sprite's go, angle\_of\_vector\_between\_two\_points which returns the radian angle between two 2d points, and vmath.quat\_rotation\_z which returns a quaternion of the rotation around the z axis based on the previously generated radian value.&#x20;

![](https://59336108-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LHnmfJK3HDz-s0f74qO%2F-LJMLL7X9gyCR8jr-Tl5%2F-LJMLbjWfU4I-msmP_EW%2F2018-08-07%2019_25_17-LaserExample.png?alt=media\&token=d9c6fd6f-d9eb-4ac0-a1ce-52e0934fd42e)

{% code title="laser.script" %}

```lua
local function dist2d(x1, y1, x2, y2)
	return ((x2-x1)^2+(y2-y1)^2)^0.5
end

local function angle_of_vector_between_two_points(x1,y1, x2,y2) 
	return math.atan2(y2-y1, x2-x1) 
end

function init(self)
	msg.post(".", "acquire_input_focus")
	self.position = go.get_position()
	self.target_position = go.get_position()
	self.scale = go.get_scale()
	go.animate(".", "scale.y", go.PLAYBACK_LOOP_PINGPONG, 1.5, go.EASING_INOUTSINE, 1.2 + math.random(30) * 0.01)
end

function update(self, dt)
	local distance = dist2d(self.position.x, self.position.y, self.target_position.x, self.target_position.y)
	self.scale.x = distance
	go.set_scale(self.scale)
	local direction = angle_of_vector_between_two_points(self.position.x, self.position.y, self.target_position.x, self.target_position.y)
	local rotation = vmath.quat_rotation_z(direction)
	go.set_rotation(rotation)
end

function on_input(self, action_id, action)
	if action.x ~= nil then
		self.target_position.x = action.x
		self.target_position.y = action.y
	end
end


```

{% endcode %}

{% file src="/files/-LJMLWCteZl\_adSkjvl2" %}


