# Question
Title: how to access base UnityEngine function of object form other class
I want to know is it possible to access functions of object like Start, Update,OncollisionEnter of other objects class in another class. if the answer is yes please tell me how can i do that.

Thank you fr helping

# Answer
> 1 votes
Your question is bit unclear, if you are asking to get access in a way that you can execute it by yourself like other common methods, then I would ask why you want so, if you can implement your own methods?

But if you are asking to get notified if `Start`,`OnCollisionEnter` of other script is called, then you are actually want to *listen* those specific events. For that purpose I'd recommend to implement `delegate`.

Here is the short example for `delegate` implementation.

```
// Class AA

public delegate void OnAAMessagesDelegate(string methodName);
public static event OnAAMessagesDelegate OnAAMessagesListener;

void Start()
{
    if (OnAAMessagesListener != null)
        OnAAMessagesListener("Start");
}

void OnCollisionEnter(Collision collision)
{
    if (OnAAMessagesListener != null)
        OnAAMessagesListener("OnCollisionEnter");
}

```

Now you can listen that delegates in other class

```
// Class BB

void OnEnable()
{
    AA.OnAAMessagesListener += OnAAMessages;
}

void OnDisable()
{
    AA.OnAAMessagesListener -= OnAAMessages;
}

// Signature should be same as delegate's signature
void OnAAMessages(string methodName)
{
    switch (methodName){
    case "Start":
        Debug.Log("AA's Start called");
        break;
    case "OnCollisionEnter":
        Debug.Log("AA's OnCollisionEntercalled");
        break;
    }
}

```

# Answer
> 1 votes
You might have noticed that the Unity event methods are usually declared as private, so they can not be called directly from the outside. Then how does the Unity Engine itself call those methods?

By using the SendMessage function. This method uses introspection to call the named method in all components which derive from `MonoBehaviour`, no matter how its visibility is declared. You can use that method, too. There is a caveat, though: It will call the method on *all* components, but maybe you only want to call it on one.

Another thing you can do when the method is implemented in a script you control is declare the event handler method as `public`. It can then be called directly. The visibility on the event handler does not interfere with Unity's own event management.

---
Tags: unity, unityscript
---


# Question
Title: How can I take a screenshot of a certain part of the screen in PyGame?
I need to for my pixel art tool that I'm making to help myself make games.

# Answer
You can do this using `pygame.image.save(Surface, filename)`, which you can read more about here.

Below is a simple function that will save a portion of the display as an image.

```
def Capture(display,name,pos,size): # (pygame Surface, String, tuple, tuple)
    image = pygame.Surface(size)  # Create image surface
    image.blit(display,(0,0),(pos,size))  # Blit portion of the display to the image
    pygame.image.save(image,name)  # Save the image to the disk

```

What this function does is created a pygame surface named image. Then the area `(pos,size)` is blitted to image at its origin. Finally, `pygame.image.save(Surface, filename)` will be called and save image to the disk.

For example, if we want to save a 100x100 image named "Capture.png" at the pos 50x50 on the display, name would equal "Capture.png", pos would equal (50,50), and size would equal (100,100), and the function call would look as such:

```
Capture(display,"Capture.png",(50,50),(100,100))

```
> 1 votes

---
Tags: python, pygame
---


title: Why doesn't pyglet window respond?

text:
# Question
Title: Why doesn't pyglet window respond?
I use the following code in the python command line interpreter, but the window doesn't respond.

```
import pyglet
window = pyglet.window.Window()

```

A white window with python icon into left-upper corner appears but then it basically hangs. Windows task manager shows that this window is not responding. However the Python command prompt works well. No errors or warning messages get displayed.

# Answer
You need to add an event loop for your window. The following code is directly from a pyglet quickstart tutorial.

You basically need a function that gets called periodically. After that you can then just ask pyglet to run the application. Here's a basic draw function:

```
@window.event
def on_draw():
    window.clear()

```

and then just call `pyglet.app.run()` to start the app.
> 1 votes

---
Tags: pyglet
---


title: Stamina Bar refuses to go back up

text:
# Question
Title: Stamina Bar refuses to go back up
I am creating a very simple script for my stamina bar to go down when I press M, but when I am not pressing M, for the bar to go back up slowly back to 100.The bar goes down fine when I press M, however, while the bar does go down, it refuses to go back up.

Attached is the code:

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

public class StaminaBar : MonoBehaviour {
    public Scrollbar StaminaGUIBar;
    public float Stamina;

    void Start()
    {
        Stamina = 100;
    }

    void Update()
    {
        Debug.Log(Stamina);
        if (Input.GetKey(KeyCode.M))
        {
            Stamina -= 5;
            StaminaGUIBar.size = Stamina /100f;
            Refuel();
        }
    }

    public void Refuel()
    {
        while (Stamina < 100)
        {
            Stamina += 5f;
            StaminaGUIBar.size = Stamina * 100f;

            if (Stamina >= 100)
            {
                break;
            }
        }
    }
}

```

Any Ideas

# Answer
> 1 votes
`Refuel` is only being called when M is down. Additionally, your while loop will be run in a single shot, and so will fail to bring the fuel back "slowly" anyway. A similar problem exists with your rate of depletion, as it will only run over 20 frames (.33 seconds @ 60FPS) before it's fully depleted. Maybe you want something like this?

```
public class StaminaBar : MonoBehaviour {
    public Scrollbar StaminaGUIBar;
    public float Stamina;

    void Start()
    {
        Stamina = 100f;
    }

    void Update()
    {
        Debug.Log(Stamina);
        if (Input.GetKey(KeyCode.M))
        {
            // deplete Stamina at a rate of 5 units per second
            Stamina -= 5f * Time.deltaTime;
            StaminaGUIBar.size = Stamina / 100f;
        }
        else if(Stamina < 100f)
        {
            Refuel();
        }
    }

    public void Refuel()
    {
        Stamina = Mathf.Min(100f, Stamina + 5f * Time.deltaTime);
        StaminaGUIBar.size = Stamina / 100f;
    }
}

```

# Answer
> 0 votes
I think your call to Refuel() is in the wrong place. It's currently in the if statement so your only refilling while M is held down.

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


# Question
Title: Shall we create our game engine in this case?
Although my friend and I are not interested in game development, we like creating tools. We would really like to give life to our own game engine, however, we don't want to put effort into something useless. Develop something what can be used by smaller or "medium-sized" companies. It's not about the most modern graphics and technologies. Something like WoW's engine 10 years ago or GTA III's would be a dream.

So, is it possible that 2 (assuming) experienced programmers can create something like that?

# Answer
> Although my friend and I are **not interested in game development** \[...\].

You have your answer: *don't do it*.

To build a game engine, you have to know how to create games. And you'll have to create games with your engine to prove that it can work well (in a single genre or in many genres, as @Philipp mentions in his answer) and display what cool stuff you can achieve with it. You'll not only have to be interested in it, **you'll have to be passionate about it**.

Thus the logical conclusion is: chose another type of project.

---

On a broader side of the answer, if you're interested in tool development, however, there are a couple of paths you could explore:

* create an external tool that fills a need (like Tiled, a map editor for 2d games)
* create a plug-in for an already existing engine that adds features to it (e.g. an AI module for Unity)
> 6 votes

# Answer
To estimate the market potential of your engine, you might want to look at what else there is on the market. When you are going for a general-purpose game engine, then you will be competing with engines like Unity, Cryengine or Unreal Engine which are all available in a price range which is very affordable to the target demographic you mentioned.

Don't take it personal, but I doubt that a two-person team could create anything which can compete on that market.

When you say "Well, these are 3d engines, let's do something simpler and stick to 2d" (relevant again due to the smartphone gaming boom): That market is covered as well. There are Clickteam Fusion and Game Maker for example.

However, what *could* work is when you create an engine designed for a very specific game genre. There is, for example, RPGMaker which is a game engine especially made for creating 2d JRPG's. It is a far less ambitious project than a general purpose engine, but still has a large userbase because the one thing it does, it does extremely well (and that for over 20 years now).

When you find a different genre without a specialized engine yet, then you might find a market niche which you can fill even with just a two-person team.
> 4 votes

---
Tags: business
---


title: Trying to make a 2D Spring

text:
# Question
Title: Trying to make a 2D Spring
Still a Beginner at Unity 5 and this time I am trying to make a Spring.

The spring would act as you'd expect. Something comes in with a direction and force, so you bounce it the opposite direction of the way it came in. Something like this:

But for some reason my player object doesn't interact with my Spring. It goes right through it as if they are on separate layers.

As you see above it falls right through. Now here is my setup:

Finally the Spring Script:

```
using UnityEngine;
using System.Collections;

public class BounceOnContact : MonoBehaviour
{
    void OnCollisionEnter2D(Collision2D collisionInfo)
    {
        Rigidbody2D rBody = collisionInfo.collider.GetComponent<Rigidbody2D>();
        Vector2 vel = rBody.velocity;
        float mag = vel.magnitude;
        rBody.AddForce(Vector2.Reflect(vel, collisionInfo.contacts[0].normal) * mag, ForceMode2D.Impulse);
    }
}

```

I'm not really sure what I'm missing. The player object should hit my spring right?

# Answer
> 1 votes
Your Spring object's `BoxCollider2D` has the Is Trigger box checked, which means that you need to check for collisions with `OnTriggerEnter2D`, rather than `OnCollisionEnter2D`.

---
Tags: c#, 2d, unity
---


title: An algorithm for forming unit groups

text:
# Question
Title: An algorithm for forming unit groups
Currently in my game engine when a user selects a large number of units and commands them to a target each unit finds its own path using Jump Point Search. The performance of this is generally OK. What I dislike is that over longer distances all the paths tend to converge so that the units end up competing to reach the path's nodes.

My solution to this is to group the units together and create a path from the unit closest to the centre of the group. I then use steering behaviours / flocking to sensibly navigate the group along the path to the target.

The problem I am struggling with now is that the user may select many units which aren't physically grouped together. Some may be very far away from each other, others may be close but separated by walls, etc. It is not really possible to create one path for such a group.

What I need is an algorithm that can create discrete physical groups from a larger set of units like in the image above. I'm at a loss as to where to start with this. I had thought of maybe using some sort of brushfire algorithm, adding units to the group as they're discovered and stopping at walls or too much empty space. I'd rather not reinvent the wheel though and would appreciate any help anyone can give me.

# Answer
You are looking for a clustering algorithm. It is a very vast research area because it is used in statistics (Wikipedia has at least 36 articles describing algorithms).

My suggestion would be single-linkage clustering. Here is how it goes:

* start with N clusters, each containing 1 unit
* repeat:
    + find the two closest points that are not in the same cluster (use your in-game distance, taking walls into account)
    + if the distance between these points is small enough, merge these clusters
    + if the distance is too large, you’re done

One remark: you may see some of the above algorithms being described as “slow” or “inefficient”. While this is true for their usual purpose (*i.e.* when dealing with millions of statistical data points), in your case (a few dozen units) I think you’re better off with the simplest algorithm you can find.
> 3 votes

---
Tags: path-finding
---


# Question
Title: Oscillating an object left and right based on it's current orientation
I'm currently implementing a fire animation in HTML5 Canvas using the phone's accelerometer.

Regardless of the phones orientation, the triangles for the fire move upward. So you can spin your phone around to what ever degree you wish, and the triangles will move towards the sky.

My issue is trying to implement an oscillation left and right for these triangles. Before I had the accelerometer hooked up, I just applied an oscillation to the x axis and everything worked fine. Now however because the triangles are moving in what ever direction up is, I need to somehow apply the oscillation to both axis depending on what the orientation of the phone is.

Could anyone help me out?

I'm using JS for this.

Thanks.

# Answer
> 1 votes
If I were going to do it, I'd use (a very small subset of) vector math.

First, generate the desired deflection in "device-space". The following diagram uses two slerps. You can think of this as "starting at" UP and then pulling away from it, towards REFERENCE by +- 10%. Reference is calculated by "starting at" FLATREFERENCE and moving toward UP.

If you spin FLATREFERENCE around UP (a flat circle) and keep final slerp constant at 0, a spiral of triangles is produced along the perimeter of a cone, where the radius of the cone is set by REFERENCE. If you also vary final slerp randomly, then the cone's interior is filled. If FLATREFERENCE is fixed and final slerp varies randomly, a directional "spread" of triangles is produced ranging from -REFERENCE to +REFERENCE.

After you compute your normalized random direction (by any means), rotate it in 3D-space according to your accelerometer input. An "accelerometer", in this context, refers to both the physical device and the software/firmware that reads it and converts it into a convenient format - likely a "down" vector or Euler angles. You can use vector math again to just rotate the randomized vector by the accelerometer's rotation. World-Space "UP" is locked to Accelerometer-Space "UN-FORWARD".

---
Tags: physics, javascript
---


# Question
Title: What do you call the Call-of-Duty-style health system?
In games like Call of Duty (and many, many other FPSs), there is no visible health bar; instead, as the player takes damage, their vision is slowly obscured by blood that seeps in from the edges. As they heal, the blood clears.

This has become a very prevalent mechanic in modern shooters, but I'm not sure if there is a definitive name for it.

I vaguely remember it being called the "blood barrel" in the game adaptation of 007: Quantum of Solace, but I never actually played that game, I only glanced through the manual a while ago. Also, Quantum of Solace came out after Call of Duty 2 (the first game I know that used this mechanic), so "blood barrel" probably isn't the original term.

This mechanic is very common, so I imagine there must be some term for it.

# Answer
The mechanic of having a player's health be represented through some *other* abstraction than a bar or counter is common, but doesn't really have a specific *standard* term. We just label it as what it is, in English: a health system without an obvious bar. There's lots of different ways you could slice it, depending on the specific aspect of it you're trying to convey as important.

For example, if the important thing is that there's no easy-to-read discrete indicator of your health as a percentage or value, you may say it's an "opaque" or "obscured" health by system.

If the important thing is the visual effect you replace the discrete readout with, you might come up with a visceral name like "blood barrel" (which, I have to say, is not a term I've ever heard before for the concept in the industry).

If you think the important thing is to be going for "realism" (questionable) by making it hard to tell precisely how close one is to death, you might call it a "realistic" health system.

Generally the importance is probably with the "no UI" aspect, so you'll most often find variations on that theme. "Distraction-free," "in-world," "UI-less," "immersive" (also questionable, as your eyes are not a camera lens as they are in that screenshot). And so on.

---

To address some comments:

> Isn't the most important aspect of this system the fact that there are no medkits or health packs to pick up?

Based on the original text of the question, no, because a system where health can't be restored by consumables is orthogonal from one where the feedback about your current health state is communicated without discrete bars or graphs, as in the screenshot and descriptions posted by the OP.

Similarly,

> this type of health system is well (perhaps even universally) known as "regenerating health".

Yes, a system where your health regenerates *is* fairly universally known as a "regenerating health" system, but that doesn't appear to be what the asker is talking about. The description and screenshot illustrates the mechanic where blood smears (or similar fuzzy metrics) convey how close the player is to death, and don't speak of regeneration *specifically* (just healing, which is more general).
> 4 votes

---
Tags: game-mechanics, terminology
---


# Question
Title: Correct order of entity updates and collision detection
I'm trying to simulate a number of units walking in a single file. My update loop looks like this:

```
for each unit:
    n = compute next position
    if n is empty then move to n

```

If I start the loop from the foremost unit, it moves first and leaves its current position to the unit behind it. When the loop finishes every unit will be moved one step. However if I start the loop from some other unit, it can't move since its next position is occupied by the unit in front of him. So, in the worst case it would take n-1 ticks for a unit to move one step (where n is the number of units in front of it).

I tried changing my update like this:

```
for each unit:
    save current position to p
    n = compute next position
    move to n

detect colliding units and move them back to their p positions

```

In this case the units move fine, as long as we have a single group. But another problem arises when the group collides head-first into another group. In this case, the foremost units will collide and they need to be moved back, but their previous positions will be occupied (by the units behind them) and they also need be moved back. This method also needs too many iterations.

How do RTS games tackle this problem? Is there a standard approach?

# Answer
Although not for an RTS, I looked at a similar problem and came up with an idea:

For each unit A, check if it's colliding with the *old* location of other units B. If it is, then in B, remember that A needs it to move.

Now if B is unable to move, you can go back and mark A as being unable to move. A in turn might cause other units to be unable to move, so you recursively go through and mark all the units that are unable to move.

Unfortunately I never did finish that implementation because I moved to another project, so I don't know if this algorithm runs into any issues.
> 0 votes

---
Tags: movement, game-mechanics, game-loop, rts, simulations
---


# Question
Title: Error CS1061: doesn't contain a definition for `transfrom' and no extension method `transfrom' of type `PlayerControl' could be found
I tried finding a solution, but I couldn't find one.

I'm getting the error:

> GameManager.cs(15,46): error CS1061: Type `PlayerControl' does not contain a definition for`transfrom' and no extension method `transfrom' of type`PlayerControl' could be found

So here is under this is GameManager class.

```
public class GameManager : MonoBehaviour {

public Transform platformGenerator;
private Vector3 platformStartPoint;

public PlayerControl thePlayer;
private Vector3 playerStartPoint;

// Use this for initialization
void Start () {
    platformStartPoint = platformGenerator.position;
    playerStartPoint = thePlayer.transfrom.position;
}

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

}
}

```

Under here is part of the PlayerControl class.

```
public class PlayerControl : MonoBehaviour {

public float moveSpeed;
public float speedMultiplier;

public float speedIncreaseMilestone;
private float speedMilestoneCount;

public float jumpForce;

private Rigidbody2D myRigidbody;

public bool grounded;
public LayerMask whatIsGround;
public Transform groundCheck;
public float groundCheckRadius;

//private Collider2D myCollider;

private Animator myAnimator;

```

I'm trying to do it, but it says this when I hover over thePlayer.**transform**.position; "Error CS0117: 'PlayerControl' does not contain a definition for 'transform'"

# Answer
> 2 votes
You have a typo in your code.

`transfrom` should be `transform`.

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


# Question
Title: Using XNA to create an isometric tileset?
In XNA, how can I take any given texture, then render it so that it fits completely into a 64x31 (or 32x15) isometric tile such that it tessellates perfectly? My goal is to give various textures to my game, then have it generate an isometric tileset from the given textures, thus requiring pixel-perfect accuracy.

I have tried to use an orthogonal projection, which has good (but imperfect) results, but always ends up making odd-width textures instead, such as 61x29; no amount of adjusting the camera position or target or orthagonal settings seems to correct this, textures always end up with 1, 3, or 5 pixels on the top or bottom of the tile:

How can I correct this behavior, or is there a better way I can create multiple isometric tiles easily?

Edit: Before anyone asks, I'm not trying to clip or mask anything when I render it. I'm trying to preserve as much of the texture as possible and push it cleanly into a specific space.

# Answer
To keep things simple, I'd do the following:

We assume as a starting point something like your target tile shape at the top - a 1-bit bitmap which I assume tesselates correctly - if not, get the tesselation working first.

Create a `Tuple<float, float> array[64][31]` reflecting the target pixels. Each such array cell is a UV coordinate (0.0-\>1.0 exclusive range) into any existing image you'd like to project into isometric space. For cells that aren't part of the tile, just use e.g. `Float.MaxValue` for x and y (and remember to check for those and skip them when processing - see below). For all valid cells, read on.

Populating valid cells is a matter of using a mapping formula from iso to ortho space, i.e. "for some isometric \[x,y\], what is the corresponding \[x,y\] in ortho space?" - this allows you to get the texel you want at the position you want it in the iso tile. There are plenty of posts around on isometric conversion formulae, see for example this answer. The end result is essentially that you will map every isometric-space tuple to an image-space UV coordinate.

Once you've populated this conversion array with the mappings, you could write a nice wrapper function that uses the mappings for any tile that wants to populate itself from an image:

```
tile = new Tile();
tile.FromImage("/images/myimage.jpg");

```

...which will run through the isometric array tuples and pull the corresponding coordinates from the named image, and possibly apply some smoothing / subtexel sampling.
> 0 votes

---
Tags: xna, isometric
---


# Question
Title: How to refresh Unreal Editor Viewport when dragging a spinbox (FModeToolkit)?
The viewport of my custom EdMode does not update while I drag a spinbox (which is in a custom FModeToolkit). In fact, MyCustomEdMode::Render() is not even called (while the spinbox).

How can I refresh the viewport while dragging?

# Answer
> 0 votes
The `MyCustomEdMode::::DrawHUD(FEditorViewportClient* ViewportClient, FViewport* Viewport, const FSceneView* View, FCanvas* Canvas)` function gives access to the `FEditorViewportClient` which must be invalidated.

In the spinbox onValueChange callback there must be `ViewportClient->Invalidate();`.

---
Tags: gui, viewport, unreal
---


# Question
Title: How to implement specific custom events in an Event Condition Action (ECA) game system?
A while ago I implemented a simple event-condition-action system for my game trying to emulate the Warcaft 3 trigger system (in a small scale, of course):

So far, it works fine, but there is something I have not been able to implement yet. It is the specific events or conditioned events (I don't know if there is a proper name for them). Following the example of the picture, a set of actions are performed if that event is triggered and matches the condition specified PLUS another condition within the event.

Every time I have worked with event systems, events (understanding them as event types) are non-mutable strings, ints, enums or any type of unique ids that allow subscription/mapping/etc. so someone else is notified. The way the system of the picture works clashes with what I know, as the event type can be "edited". What I mean is that, from my point of view, it seems there are two type of events in the example: "A unit dies" and "A unit owned by player 12 dies". But I'm almost sure it's not how it works.

Do systems like this one keep the same "constant event structure" as I conceive it and have an inner condition layer checking for that specific event? Do they work in a completely different way that I'm unaware? How, then?

# Answer
> 3 votes
The event "A unit owned by player 12 dies" implies the "A unit dies" event. So there is no reason to have two different events.

You should only need a single "Unit death" event, but have that event include all the relevant information like which unit exactly got killed and what killed it.

You can then have the event receivers inspect that information about the event to decide whether or not to act on it:

```
HandleUnitDeathEvent(UnitDeathEvent event) {
    if (event.killedUnit == this.target) {
         if (event.killer == this) {
             say("Wohooo!");
         } else {
             say ("Hey, " + event.killer.name + "! Stop killstealing!");
         }
    }
    if (event.killedUnit == this) {
         say("Dammit, not again!");
    }
    if (event.killedUnit.type == "Kobold") {
         say("I like seeing kobolds getting killed.");
    }
}

```

Or you could have your event dispatcher system implement the filtering to only forward those events which are relevant to a specific receiver.

---
Tags: architecture, events
---


# Question
Title: How does this point2LineDist() method works?
I was browsing Wolf3D JS port and bump into that method :

```
/**
 * @description calculates distance between a point (x, y) and a line.
 * @memberOf Wolf.Math
 * @param {number} x X coord of point
 * @param {number} y Y coord of point
 * @param {number} a Line angle in degrees
 * @returns {number} Distance
 */
function point2LineDist(x, y, a) {
    return Math.abs( (x * SinTable[a] - y * CosTable[a]) >> 0);
}

```

I think I understand what it does. It gives shortest distance (green on picture) between a line (from angle) and a (x, y) point.

What is not clear to me is how it works. I know a little bit of trigonometry, but I am not able to figure out which trigonometry identity or formula it use. The binary shift is (I think) a quick way to convert a float to an int.

# Answer
The direction vector of the red line is `(CosTable[a], SinTable[a])`. It is a unit vector.

Now consider the green line on your drawing. The vector along this line pointing towards `(x, y)` is orthogonal to the direction vector, and its value is `(SinTable[a], -CosTable[a])`. It is a unit vector, too.

From there, the distance between point `(x, y)` and the red line, which is the length of the green line, is the dot product between vector `(x, y)` and the orthogonal vector. This is where the formula comes from. The `abs()` call is here because one must account for direction vectors pointing in the other direction.
> 1 votes

---
Tags: 2d, mathematics, javascript, trigonometry
---


# Question
Title: Unity error after adding skybox material
So I added the night material from the fantasy skybox asset I download from the asset store and the rest of my objects turned white for some reason I figured it was just a glitch like the light baking and it would be okay when I deployed my project

Well I saved and built my project as usual and the objects all turn pink as if their materials did not exist and every time I go to play the game I receive the following error

'Assets/Build/ParcoreBeast\_Data/Managed/Assembly-CSharp.dll' shouldn't be queried by IsAssemblyCompatible, missing IsInternalOrCompiledAssembly check ? UnityEditorInternal.InternalEditorUtility:GetMonoIslands() UnityEditor.SyncVS:SyncVisualStudioProjectIfItAlreadyExists()

How do I fix this?

# Answer
This happens when you create a build of your project and save that build in your assets. If you move the build from the assets then the error should go away.
> 0 votes

# Answer
Deleting Library file might solve the problem
> -1 votes

---
Tags: unity
---


title: Character ability power balance

text:
# Question
Title: Character ability power balance
I'm making a game where the player controls a character. This character starts off bland & weak. But over the course of playing the game, picks up abilities which the character uses as attacks/magic/damage dealers during battles. There are many different types of abilities/powers. I want to allow the player to level up these abilities through whatever means I come up with (haven't done that yet).

How do I balance ability ATTACK power (damage dealt) for instance? I'm sure there's some kind of abstract way of approaching this but it's eluding me. I want to make sure that if I make a super overpowered ability that there is another ability out there that can at least counter act it.

So the question: how do I approach ability power upgrade balancing when designing my game? Is it an algorithm? Can it be done linearly? So that there is always an awesome new strong ability waiting around the corner for the player character?

# Answer
> 37 votes
In any game where you have character leveling, you need to decide on a **power curve**.

This is a mathematical function which maps game progress to character strength. This curve can be linear, polynomial or even exponential. The flatter the curve, the less progress your player will feel, but the easier it is to balance because early-game content still stays relevant until the late-game.

Design your content in a way that while the player progresses through your game, you hand out powerups in a way that their characters power stays on that curve. Simultaneously you increase the power level of any opponents and other challenges the player faces to be around that power curve. At the beginning of the game, where the player is still learning your game mechanics, you want the opponents to be below the curve. But in the end, when the player has mastered your mechanics, you want the opponents to be above the curve to provide a challenge. How far below or above the curve depends on how hard it is to learn your game mechanics and how much power potential they have when mastered.

That means there can be an awesome powerup around the next corner, but only when you make sure that all future enemy encounters are even stronger to compensate for the increased power of the player-character.

Example:

Let's say your game has 10 levels, and you decided on a polynomial power curve which is `10 * (level ^ 1.2)`. This means you would hand out powerups in each level so that the player ends up with approximately this amount of attack on each level:

```
1   10
2   23
3   37
4   53
5   69
6   86
7   103
8   121
9   140
10  158

```

A spreadsheet application like Excel is very useful for calculating such tables.

This table also tells you how many hit points the enemies on each level should have, which would be a multiple of these values (the value of that multiplier depends on how many hits on average you want an enemy to take before they go down). Again, stay slightly below that curve on earlier levels and slightly above on later levels when you design enemy encounters.

***"But what if I want my game to be a fluent experience not separated into levels?"*** \- then still separate it into levels, just don't tell the player where one level ends and another level begins.

***"But what if my game is an open world game and I want to let the player explore it in any order they like?"*** \- then either have the player progress very little, have them progress horizontally (give them new abilities which open up alternative strategies but aren't actually more powerful), or make sure that when the player gets stronger, the whole world adapts and becomes more challenging.

# Answer
> 11 votes
@Philipp gave a great answer. Another concept to take into consideration is the idea of average threat level. It is perfectly acceptable for certain foes to have stats dramatically greater than what your curve predicts – so long as their other stats are lowered in proportion to the increase. For instance take pixies armed with envenomed needles. They are extremely fast and small, represented by a high dexterity stat (or speed if that is what you wish to call it) and a corresponding raise in evasion. However, this means players will likely miss them more often, so you should lower their hit-points in proportion to the change. So if the player is only supposed to be required to attack a foe x times to kill it, and the pixy has a 50% miss chance, you can give it approximately half the health of your average foe. Likewise giving the pixy an attack that grants a status effect can make up for it having a low attack power.

This allows you to make your enemies more unique and will make the game less boring. Rather than the goblin, the golem, and the giant all being the same except for the number of wounds they can take, you can push certain features of theirs in one direction and reduce the others accordingly to keep it within your target challenge level.

Also, while it is usually preferable to keep the ATR relatively even (bosses should always have something neat that surprises even the best prepared players), it never hurts to shake things up a bit. Take Diablo 3’s treasure goblins for example. Weak in every way, yet drops amazing loot. It only contributes to the dungeon’s difficulty by convincing otherwise intelligent players that it’s a good idea to go running headfirst into unknown territory because “otherwise the little bugger is going to get away with the loot!” Yet no one complains about them, because it is an unexpected and refreshing challenge that brings its own reward.

Another example I love is the earth dragon from “Golden Sun: The Lost Age.” Its stats are pretty high, it regenerates an insane amount every turn and it can’t actually be killed in a fair fight (I tried for kicks once). This is dealt with when the player figures out that there is an entire area inside that mountain dedicated to weakening the dragon and stripping it of its regeneration. Sometimes it is great idea to make foes absurdly overpowered (by the numbers) and then introduce other variables like volatile terrain or legendary, boss-specific weapons. The key thing I have learned about this is to keep it fun.

---
Tags: rpg, character, balance, progression
---


title: Unity List spawner problem ? C#

text:
# Question
Title: Unity List spawner problem ? C#
I have four spawners in my scene that spawns four enemies. My problem is when I try to add game objects to the list it works but only for one spawner.

My code

```
if (Score.levelNum >=2 ){
  germtype.Remove(pupplegerm);
  germtype.Add(blackgerm);
  germtype.Add(blackgerm);
}
else if(Score.levelNum >=3 ){
  germtype.Remove(bluegerm);
  germtype.Add(greengerm);
  germtype.Add(greengerm);
}

```

I want to add a new enemy / germ each time the player moves up a level. I have green germ and black germ stored in a variable.

# Answer
> 1 votes
Remove the `else` from the other conditions, as only the first condition triggers. That is because something greater than or equal to three is also greater than two.

---
Tags: unity, c#, software-engineering
---


# Question
Title: How to access a variable from another script in Unity c#
I need to access a variable from another script in Unity, but I can't figure it out. Script:

```
public class move : MonoBehaviour {
public float speed;
// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    transform.position += Vector3.left * Time.deltaTime * speed;
}

}

```

I want to access the variable speed in another script, but I can't. Any help will be appreciated :)

# Answer
If both scripts are on the same `GameObject`, you can use this

```
gameObject.GetComponent<move>().speed

```

This will access the given variable, in this case `speed`.

---

If the scripts are on different GameObjects you can do this :

```
GameObject.Find("nameOfObjectYourScriptIsOn").GetComponent<move>().speed

```

and you should have access to the variable `speed`.

**Note : You need to replace `nameOfObjectYourScriptIsOn` with the name of the `GameObject` you have attached the `move` script to.**
> 6 votes

# Answer
Basically it is somehow different in Unity. In Unity most of the work and scripts are attached to any `GameObject` to make it work through `MonoBehaviour`. In other words you cannot be able to execute `Monobehaviour`'s messages like `Start`, `Update` if that script is not attached to any `GameObject`.

So the way would be change little bit. You must have to get the very same instance that is dropped to any `GameObject` otherwise you may get no error but also get no change.

For this purpose I second the first part of Biix's answer, if you have both scripts attached to same `GameObject` then you can use `GetComponent`

```
// In script other than move
move _move = GetComponent<move>();
_move.speed = 10;

```

But if scripts are attached to two different `GameObject`s then you can use `FindObjectOfType`, by this you don't have to worry about the name of the `GameObject` on which your script is attached.

```
// In script other than move and also on different Game Object
move _move = FindObjectOfType<move>();
_move.speed = 10;

```
> 3 votes

# Answer
What you need are getters and setters. Basically it is a way of getting and/or setting variables in classes (or scripts in this case) from external code. There are many ways that you can do this:

**Automatic get and set**

By changing the code to the code below you are making the variable available to the outside classes (public get;) but those classes can't change the variable. Which you might want so you don't change it be accident.

```
[SerializeField]
private float InspectSpeed;

public float speed { get; private set; }

void Start () {
    speed = InspectSpeed;
}

```

So you might notice this is a lot of code, Yes.... It is. While automatic setters and getters are awesome for variables you want to share between classes/scripts the inspector won't allow you to use them (which is why i assume speed is public) so I added an extra float which is visible to the inspector. Since this is then not the same as speed you need to set it at startup.

To then access the speed variable you simply get it from the instance of the class:

```
move.speed;
//note you won't be able to change the variable as the setter is private

```

**Manual getter**

You could just add a method which has a return value of float which then always returns the variable of speed. When every you need speed just call the method

```
Public float getSpeed(){
    return speed;
}

```

so from another script/class you would call:

```
move.getSpeed();
//returns the speed

```

**Making the variable public (not recommended)**

You have already done this in the code sample that you provided. You declared the speed variable as public meaning that all scripts can just call the variable from anywhere. I suspect you did this to make it visible in the inspector (we have all done it at some point :)).

The problem with this is that as you add more and more variables to scrips that you want to be changeable in the inspector it becomes harder and harder to work with the code as you add more scripts. This is because when you need to call methods in other classes or scrips it will show every public variable as well as all the other public methods that you have. Sooner or later you will have 2 variable of the same name at which point it will be vary confusing which variable you are getting if you are getting data of the same name from multiple sources.

To fix this make every variable private and add "\[Serializable\]" above it which will prevent other classes/scripts from seeing it but the inspector will still be able to interact with it.

And just for the completion of this point you access the speed variable like this:

```
move.speed;

```

This should cover everything, if it doesn't work for whatever reason comment bellow :)
> 1 votes

# Answer
I guess you are being down-voted for the question being simple to find online but a way that I have been using is the following:

```
public class TargetGameObject : MonoBehavior {

    public Move move;
    int vel = 0;
    ....

    void Update(){
        vel += move.speed;
    }
    //Use move.speed however you want once the game object is linked in the inspector.

```

You link the item in the GameObject inspector by dragging the GameObject with your move script attached. I would also recommend using camel-case for all class names. It is just good practice.

The other answers will work as well such as using FindObjectByName, GameObject.Find, etc but searching through all GameObjects if you have a fairly large game can be intensive on performance.
> 1 votes

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


# Question
Title: Opengl occlusion culling huge performance drop
Hello I tried to implement occlusiong culling to my engine in opengl using java & lwjgl. Occlusion works but... performance drop is huge I mean from 60-70 fps to 3-6 fps. Here is my question what I'am doing wrong ? Here is my code:

```
                    //this code is after frustrum culling if object passed

                    glColorMask(false, false, false, false);
                    glDepthMask(false);

                    glBeginQuery(GL_SAMPLES_PASSED, query_id);
                    //renderable is cube not normal object
                    renderable.render();
                    glEndQuery(GL_SAMPLES_PASSED);

                    int iSamplesPassed = GL15.glGetQueryObjecti(query_id, GL15.GL_QUERY_RESULT);
                    if(iSamplesPassed == 0) {
                        //object is not visible don't render it
                        renderable.setVisible(false);
                    }
                    glColorMask(true, true, true, true);
                    glDepthMask(true);

```

query\_id is simply:

```
query_id = glGenQueries(); //it is called only once on start

```

I look on some examples and I don't see any diffrences in code. Only diffrence is their and my framerate.

# Answer
You are **stalling the GL pipeline** with the `glGetQueryObjecti()` call. The pipeline helps OpenGL render fast because it lets you call new functions while the previous ones are still executing. In some cases however, such as when you do a `glGet*()` call, it needs to wait for all the previous calls to finish before returning the result. A pipeline stall is so bad that, as you are yourself experiencing, it’s a lot slower to wait for the occlusion query to return than to actually render the object. And this happens for each and every object you draw. This defeats the purpose of a pipeline and needs to be addressed.

One solution could be to send `N` queries in parallel, then call `glGetQueryObjecti` `N` times. This will divide the number of slowdowns by `N`. Another solution is to ask whether the query has actually finished, using `GL_GET_QUERY_AVAILABLE`, and if it hasn’t, just render the primitive (because, as established, it’s faster to render the object than to wait for the query result). This will get rid of the stalls, at the expense of a few unnecessary draw calls. You could have a look at Listings 12.3 and 12.4 in the *OpenGL Superbible book* for a combination of both methods.
> 6 votes

---
Tags: opengl, culling
---


# Question
Title: Is it possible to use mipmaps with dynamic textures in Dirext 11?
I was trying create a texture with `D3D11_USAGE_DYNAMIC` and `MipLevels` equal to 0 (to create all the mip levels). However, the texture failed to be created. Is it possible to use mipmaps with dynamic textures?

# Answer
> 2 votes
If you create the device with `D3D11_CREATE_DEVICE_DEBUG`, you should see the following error:

> D3D11 ERROR: ID3D11Device::CreateTexture2D: A D3D11\_USAGE\_DYNAMIC Resource must have MipLevels equal to 1. \[ STATE\_CREATION ERROR #102: CREATETEXTURE2D\_INVALIDMIPLEVELS\]

which is pretty self explanatory.

Use `USAGE_DEFAULT` and `UpdateSubresource()`, instead.

This is a decent summary of the options you have:

https://eatplayhate.me/2013/09/29/d3d11-texture-update-costs/

---
Tags: directx, directx11
---


# Question
Title: How to mark a variable as prefab independent?
I am making a game that has a symmetrical level design. Each player own a portion of the map and each portion is the same. As such, I placed the portion as a prefab so that when I apply the prefab, every other portion gets changed as well.

On the prefab there is a script. This script contains a variable called playerId. I dont want this variable to change to prefab default when I apply the prefab. Is there an attribute tag I can use to do this? As far as I am aware, Unity's transform.position doesnt get affected by the prefab defaults.

# Answer
> 1 votes
I don't know of any such attribute. The special behavior of `transform` in regards to prefabs appears to be hardcoded. But I could think of two workarounds.

1. Abuse the `name` of the game-object to store that information, which is not synchronized between prefab instances either when you apply/revert. A quite hackish solution, though.
2. Move the scripts with the player-Id's to separate game-objects which have no prefab-connection and reference the prefab-instances from them.

# Answer
> -2 votes
Make singletone which will have list of playerIds .When prefab gets spawned ,let script in prefab fetch Playerid from it.

---
Tags: unity
---


# Question
Title: MonoGame creates a copy of song files in XNBs location
I'm having a problem. I've been adding `.wma` files to the Content Pipeline app to be used as my game's background music. But today when I opened the `solution/project/content/bin/music` folder I spotted the following:

So am I forced to ship the `.wma` files with the actual XNBs when I distribute my game? No other asset gets copied like this so how do I prevent songs from being copied as well?

If I delete the `.wma` files manually then the next time I build the project they get automatically added again :/

# Answer
That is the way the content pipeline works. If you look at other games that use XNA or MonoGame, you may see wma files in their content directories where they're installed. I believe it's the same for mp3 format.

If you want to make it harder for people to copy your music, you can convert them to wav files and then process them through the pipeline. You could also try using XACT to build a wavebank instead, which may further obscure your audio files.

The bottom line, though, is that by distributing your game, you're also distributing your music (albeit packaged in different format). So if they really want to copy it, they'll find a way. They probably can just use the code in MonoGame's source that processes the x\*b files.
> 1 votes

---
Tags: c#, monogame, assets
---


title: Existing game to virtual reality game?

text:
# Question
Title: Existing game to virtual reality game?
What kind of existing game can be taken as a good source for a 'virtual reality' game, specifically, the one you can play with any 3D VR glasses?

Why do you think this particular game or these games can be adjusted well in the new realm?

Thank you for your thoughts.

# Answer
> 1 votes
Racing games are a good waypoint for VR. You don´t have to move, all you need to do is sit and grab a wheel, so the immersion is a lot better than, for example, a shooter.

I am talking about simulation racing games, LFS, for example, not arcades like Gran Turismo or Need For Speed, those games are fine too, but we want immersion and Virtual REALITY.

**Update**: I just found a video showing LFS on VR.

---
Tags: 3d, virtual-reality
---


# Question
Title: Convert Mouse Coords into Isometric Tile ID
Using GameMaker Language, I'm basing off their Adavnced Examples. How can i convert the current mouse position into a tile position?

The mouse coordinates are 0,0 from top-left

This is the function when it draws. I think this is what needs reversing. I'm tragically bad at Maths, so I'm sorry in advance.

```
/// DrawLevel()
var xx,yy,destx,desty, base_x,base_y,current_row_x,current_row_y,tile,o,sp, m,h,offy, tileset;

TileRowDX = 68;
TileRowDY = 34;
TileColumnDX = -68;
TileColumnDY = 34;

MapX = 0;
MapY = 0;
MapDrawX = 11;
MapDrawY = 11;

/// Draw the complete isometric level
tileset = global.tiles;

// End point in map drawing (map coordinates)
destx = MapX+MapDrawX;
desty = MapY+MapDrawY;

// Start drawing position - center in the middle of the screen - and just above a little
base_x = surface_get_width(application_surface)/2;
base_y = 150;

// X and Y loop to print all cells.
for( xx=destx-1;xx>=MapX;xx--) {
    current_row_x = base_x;
    current_row_y = base_y;
    for( yy=MapY;yy<desty;yy++)
    {
        // First draw the column of tiles in this cell, bottom to top.
        offy=0;
        for(var h=0;h<global.mapMaxLayers;h++){
            m = Map[h];         // get 2D map grid from level array (Z axis)
            tile = m[# xx,yy];  // get tile from 2D grid (x,y axis)
            if( tile>=0 ){
                // if we have a tile, then draw it.
                draw_sprite(tileset,tile,current_row_x,current_row_y-offy);
            }
            offy+=27;
        }

        // Next, get the object in this cell, and draw it on top.
        // If allowing height for the player, you'd need to add on 27 for each block up.
        o = Objects[# xx,yy];
        if( o!=0 ){
            // Get the object sprite to draw (could also do frames etc)
            sp=o.Sprite;

            // get a 0 to 1 value into the isometric cell.
            var dx = (1.0/15.0) * ((o.x&15));
            var dy = (1.0/15.0) * ((o.y&15));

            // Move to top left of Isometrix grid cell
            var ox = current_row_x - TileRowDX;
            var oy = current_row_y - TileRowDY;

            // Now convert into an isometric offset on X and Y
            ox = ox + (dy*TileRowDX);                   //Y axis first
            oy = oy + (dy*TileRowDY);
            ox = ox - (dx*TileColumnDX);                // now X axis
            oy = oy - (dx*TileColumnDY);

            // and draw this sprite
            draw_sprite(sp,0,ox,oy);

        }

        // Move down and right
        current_row_x += TileRowDX;
        current_row_y += TileRowDY;
    }
    // Back up to top, and move left and down.
    base_x += TileColumnDX;
    base_y += TileColumnDY;

}

```

I'm sure this is just mostly a mathematics question!

# Answer
> 1 votes
```
isoX = cartX - cartY;
isoY = (cartX + cartY) / 2;

```

I don't know game maker's langauge, so I can only give you a pseudocode.

This only works correctly, if your "north" is facing to the top right direction

If you don't have objects, then you maybe need to create 2 separate methods to get tge X and the Y coordinate.

---
Tags: mathematics, isometric, game-maker
---


title: Choosing AI strategy

text:
# Question
Title: Choosing AI strategy
How would I choose to design an AI that would know the rules of the game, however not know the game world before hand?

Given fx. a Sokoban game, I could teach it using Reinforcement Learning to play a map optimally. However as soon as I change the map but not the game rules, all it has learn is discarded. So what would be the tactic to make this work in the area of AIs being able to find a near optimal solution in an arbitrary board setting?

# Answer
> 1 votes
The stuff the computer scientists call "Artificial Intelligence" is quite different than what game developers mean when they speak about "Artificial Intelligence".

Neural networks and reinforced learning are a quite obscure technique when it comes to game AI (still not completely unheard of, though). Most game AIs are implemented by rule engines or minmax tree searches.

A rule-based AI analyzes the situation and makes decisions based on a set of preset rules (like in a platformer (`if (player is in front of me) then fire bullet` or in a 4x strategy game `if (enemy_military_power / my_military_power) < diplomatic_relationship_score) then declare war`). This usually results in an AI which can play very complex games in a way which is not really that great because it often has several glaring weaknesses a crafty player can find and exploit, but is usually at least able to entertain the player until they figured it out.

A minmax tree-search based AI checks all possible moves it could possibly make and several possible moves it could make afterwards and then picks the move order which leads to the best outcome by applying a rating function. This doesn't work well for all games. It only really works well on games without randomness or information hiding. It can also become quite computation-intense when there is a large number of possible moves. But on those games where it does work, such an AI can reach terrific AI strength on par with players with years or even decades of experience (like in Chess, for example).

Considering that Sokoban is a game where no randomness or information hiding involved and the number of possible moves at any given time is rather limited, it leads itself well to a minmax-AI. You only need to evaluate the chest-pushes the character can legally make from the positions it can currently reach without pushing a chest, because moving around usually has no consequences so it isn't actually a move. A rating function could simply look at how many chests are on a target-field. But in fact the number of moves is so small that simply brute-forcing all possible move-sequences until they either lead to a configuration you already had or to the solution might actually be viable.

---
Tags: ai, reinforcement-learning
---


title: Dijkstra's Algorithm - Infinite loop

text:
# Question
Title: Dijkstra's Algorithm - Infinite loop
While running Dijkstra's Algorithm to assign a direction to every tile and when an object land on the tile, follow the direction to a goal. I encountered an infinite loop (or I think it is). The following is my code:

```
while (openList.Count > 0)
    {
        Debug.Log("Running alg");
        failsafe++;
        if (failsafe > 1000) { break; }

        Tile currentTile = openList[0];
        openList.Remove(currentTile);
        closedList.Add(currentTile);

        List<Tile> neighbours = GetNeighbours(currentTile.localX, currentTile.localY, grid);

        foreach (var neighbour in neighbours)
        {
            if (!closedList.Contains(neighbour))
            {
                neighbour.parentX = currentTile.localX;
                neighbour.parentY = currentTile.localY;
                openList.Add(neighbour);
            }
        }
    }

```

Under these conditions, the failsafe triggered and broke the loop. The grid is a 11x11 grid and as such by my understanding should have never reached 1000 cycles.

When the failsafe triggers, it explored 9 tiles away from the goal and the rest are unexplored.

What am I doing wrong here?

# Answer
> 2 votes
Aw, what the heck. I'm pretty sure this question belongs on Stack Overflow but my inner algorithm geek won't let this go without showing a classic breadth-first search implementation...

```
void FindShortestHopcountPaths(Tilemap map, Tile start)
{
    foreach(Tile tile in map.GetTiles())
       tile.visited = false;

    start.parent = start;
    start.visited = true;
    start.hopCount = 0;

    var queue = new Queue<Tile>();
    queue.Enqueue(start);

    while(queue.Count > 0)
    {
         var parent = queue.Dequeue();
         foreach(Tile child in parent.Neighbours)
         {
             if(child.visited)
                 continue;

             child.visited = true;
             child.parent = parent;
             child.hopCount = parent.hopCount + 1;

             queue.Enqueue(child);
         }
    }
}

```

By the way, if you like geeking out over algorithms like this, there's a fantastic free course online where I learned pretty much everything I know. :)

# Answer
> 0 votes
Your current algorithm is not dijkstra. Instead it's breadth first floodfill with a buggy loop elimination. Dijkstra implies that you sort the open list according tot he cost of the tile.

Fixing the loop check requires something like:

```
if (!closedList.Exists(n => (n.localX == currentTile.localX &&
                             n.localY == currentTile.localY)))
{
    if (!openList.Exists(n => (n.localX == currentTile.localX &&
                                 n.localY == currentTile.localY)))
    {//also check the open list
        neighbour.parentX = currentTile.localX;
        neighbour.parentY = currentTile.localY;
        openList.Add(neighbour);
    }
}

```

Adding the sorting requires that you keep a cost field in each Tile that is defaulted to the max value;

```
foreach (var neighbour in neighbours)
{
    if (!closedList.Exists(n => (n.localX == currentTile.localX &&
                                 n.localY == currentTile.localY)))
    {
        if (!openList.Exists(n => (n.localX == currentTile.localX &&
                                     n.localY == currentTile.localY)))
        {//new value
            neighbour.cost = currentTile.cost + currentTile.traverselCost;
            neighbour.parentX = currentTile.localX;
            neighbour.parentY = currentTile.localY;
            openList.Add(neighbour);
        }
        else
        {
            auto newCost = currentTile.cost + currentTile.traverselCost;
            if(newCost < neighbour.cost){
                neighbour.cost = newCost;
                neighbour.parentX = currentTile.localX;
                neighbour.parentY = currentTile.localY;
            }
        }
    }
}
openList.sort((x, y) =>{return x.cost.CompareTo(y.cost);} );

```

---
Tags: algorithm, path-finding, dijkstra
---


title: Password-less player identification

text:
# Question
Title: Password-less player identification
I'm working on the server side part of my game (develop your village/farm) and trying to build user identification system. I'd like to have a password-less mechanism: user downloads my app from the store, run it and that's all. He doesn't have to type any login or password. The game connects with the server requesting new player creation so he can start playing as soon as he opens the app.

I assume that this process is connected with GameCenter/GooglePlayGames. A game retrieves player ID from those services and then use it for future requests (saving user progress, game specific data - like village/farm facilities' positions, other information on my server). Is it a valid and safe assumption? If not can ask you to describe how it works/should be done?

I have some doubts regarding security? Single PlayerID seems to be quite weak solution, isn't it?

**Edit:**

I didn't mention it but I would like to move my progress from one device to another also without creation of any account with login and password.

# Answer
For my game *LowDown: A Social Experiment*, I did this:

The first time a user submits a number to a contest, there's a CAPTCHA to filter out bots. The server assigns the user a UserID, which is just the next index in the database table. It also assigns an invisible password (I call this a key; it's a randomly generated string). The client saves both the ID and the key.

Future logins are sent using the ID and the key, and is sent encrypted via string concatenation and hash. It concats the userID, the key, the contest id, and the user's entries into a string and hashes it. The hash of the string plus the submission are sent, and the server verifies that the submitted data results in the sent hash. This is to (hopefully) verify that the submission is coming from an actual client, not a bot.

This means the user can only log in from that device, since the keys are hidden from her. If she wants to log in from another device, she can register the account. This involves giving the server an email address and desired password. From then on, the user can log in from any device provided they log in with the email address and password.

This system reduces new-user friction to a minimum, yet allows them to log on through other devices if they really want to.
> 1 votes

# Answer
There is a concept in security called two-factor authentication - where you authenticate two aspects of the user. Often this comes in the form of a password and device code.

I bring this up because if you don't want a password you can just use the device code portion of these techniques and if you properly implement it you have the same level of security that a password offers if you allow your users to stay logged in with a cookie. You need to be aware of and accept that level of risk. (All login systems have some amount of risk of being defeated.)

Specifically that could mean using gamecenter/googleplaygames as a means to verify the device account - however this carries with it the risk that a player will lose their game if they lose their gamecenter account.

Alternately you can send them an email with a code and link and if they click that link you give them a cookie and use that cookie to keep them logged in. If performed correctly, this is fine. Please do research into how to do this properly.

You can simply start a new game by giving them a cookie with a random code, if you want. Their game will be lost if the clear their cookies or if they move to a new device - but games like Cookie Clicker and other browser games have successfully used just that.

You need to match your techniques to the security of the game. If the game is light and free - having no security scheme could be acceptable. If the game has a monthly fee, micro-transactions with a wallet of currency, transferable items that could be stolen off the account and/or a high level of competitive play with tracked scores that might make an account desirable to own - you'll probably want device codes, passwords with enforced lengths and complexity and optional or even required cryto-keys like RSA or DUO; with account recovery tools like second email addresses, text message recovery or a staff of people verifying scans of photo ids such as Blizzard has.

Match the security of your game to the features of the game.
> 0 votes

---
Tags: client-server, google-play-services, game-center, authentication
---


# Question
Title: How to handle focus on a custom actor in Unreal Engine?
I created a custom actor, placed it on my scene and selected it.

When I press "F" to focus on it, the camera zoom back very far from the scene, probably because I didn't implement the method supposed to return the bounding box of my actor.

How can I do that?

**Update**

I implemented a custom component which delegates all drawing functions to an internal `ULineBatchComponent` member. I unregistered this `ULineBatchComponent` member. The custom component is not even attached to the actor root component.

But its bounding box is still taken into account when focusing on the actor.

*UPBLineBatchComponent.h*

```
UCLASS()
class UPBLineBatchComponent : public UObject
{
    GENERATED_UCLASS_BODY()
public:
    virtual FBoxSphereBounds CalcBounds(const FTransform& LocalToWorld) const;
    void SetTransform(const FTransform &Transform);
    virtual void DrawLine(...);
    virtual void DrawPoint(...);
    void Flush();
    ULineBatchComponent* LineBatchComponent;
    FBox LocalBounds;
};

```

*UPBLineBatchComponent.cpp*

```
UPBLineBatchComponent::UPBLineBatchComponent( const FObjectInitializer& ObjectInitializer )
        : Super( ObjectInitializer )
{
    LineBatchComponent = CreateDefaultSubobject<ULineBatchComponent>(TEXT("LineBatcher"));
    LineBatchComponent->UnregisterComponent();
    LocalBounds = FBox(0);
    LineBatchComponent->Bounds = FBoxSphereBounds(EForceInit::ForceInitToZero);
}

FBoxSphereBounds UPBLineBatchComponent::CalcBounds(const FTransform& LocalToWorld) const
{
    LineBatchComponent->Bounds = FBoxSphereBounds(LocalBounds.TransformBy(LocalToWorld));
    return FBoxSphereBounds(LocalBounds.TransformBy(LocalToWorld));
}

void UPBLineBatchComponent::SetTransform(const FTransform& Transform)
{
    LocalBounds = LocalBounds.TransformBy(Transform);
    LineBatchComponent->Bounds = FBoxSphereBounds(LocalBounds);

    bool bDirty = false;
    for (FBatchedLine& Line : LineBatchComponent->BatchedLines)
    {
        Line.Start = Transform.TransformPosition(Line.Start);
        Line.End = Transform.TransformPosition(Line.End);
        bDirty = true;
    }

    for (FBatchedPoint& Point : LineBatchComponent->BatchedPoints)
    {
        Point.Position = Transform.TransformPosition(Point.Position);
        bDirty = true;
    }

    for (FBatchedMesh& Mesh : LineBatchComponent->BatchedMeshes)
    {
        for (FVector& Vert : Mesh.MeshVerts)
        {
            Vert = Transform.TransformPosition(Vert);
            bDirty = true;
        }
    }

    if (bDirty)
    {
        LineBatchComponent->MarkRenderStateDirty();
    }
}

void UPBLineBatchComponent::DrawLine(const FVector &Start, const FVector &End, const FLinearColor &Color, uint8 DepthPriority, float Thickness, float LifeTime)
{
    LineBatchComponent->DrawLine(Start, End, Color, DepthPriority, Thickness, LifeTime);
    LocalBounds += Start;
    LocalBounds += End;
    LineBatchComponent->Bounds = FBoxSphereBounds(LocalBounds);
}

void UPBLineBatchComponent::DrawPoint(const FVector &Position, const FLinearColor &Color, float PointSize, uint8 DepthPriority, float LifeTime)
{
    LineBatchComponent->DrawPoint(Position, Color, PointSize, DepthPriority, LifeTime);
    LocalBounds += Position;
    LineBatchComponent->Bounds = FBoxSphereBounds(LocalBounds);
}

void UPBLineBatchComponent::Flush()
{
    LineBatchComponent->Flush();
    LocalBounds = FBox(0);
    LineBatchComponent->Bounds = FBoxSphereBounds(EForceInit::ForceInitToZero);
}

```

**Update 2**

If I use

```
LineBatchComponent = NewObject<ULineBatchComponent>();

```

instead of

```
LineBatchComponent = CreateDefaultSubobject<ULineBatchComponent>(TEXT("LineBatcher"));

```

I can focus properly on the actor, but I can't see the lines anymore.

# Answer
> 2 votes
I've never experienced the problem you're describing with any custom actor types. You shouldn't need to do anything explicitly, or implement any methods, yourself.

The "focus" command is handled in EditorServer.cpp (the link requires access to Epic's private Unreal Engine GitHub, which can be obtained by registering an account with Epic); specifically `UEditorEngine::MoveViewportCamerasToActor`.

This method computes a bounding box for the viewable region based on the bounding boxes of the individual selected actors and their components.

Based on your problem description, it is likely that your actor, or one of its components, has an improperly initialized or overly-large bounding box assigned. The other possibility would be that your actor has *no* components, and is configured such that all other code paths computing the bounding box are skipped (certain types of actors, et cetera), resulting in a zero box.

However the subsequent call that actually focuses the viewport on a box will early-out if given a zero box, so it's quite likely the case is the first one: one of your actor's components has an overly-large or malformed non-zero bounding box.

---
Tags: selection, unreal
---


title: Solving for velocity in the x/y/z axes?

text:
# Question
Title: Solving for velocity in the x/y/z axes?
In a 3D environment I have an object with a displacement *x* that I know I need to traverse in a given time interval. I have the object's heading and elevation and I want to figure out the distance the object needs to travel on the x/y/z axis to move *x* units in the given direction. How can I calculate this? Are there two distinct ways to calculate it (using trigonometry or linear algebra)? Which way is the best in what scenarios?

EDIT: To clarify, I will make an analogy to a simple 2D scenario that is similar to the 3D scenario I'm working with. Let's say the object has an angle of 35 degrees from the x-axis. Making a right triangle, let's say we know that the hypotenuse (or displacement of the object) is 10 units. Now to figure out the x and y deltas to get from the object's current position to the object's new position 10 units away at a 35 degree angle, you simply do:

```
x = 10 * cos(35)
y = 10 * sin(35)

```

I simply need to solve the same problem except in 3 dimensions.

# Answer
Ok, I think I get what you're asking now...

If you have the 3D position of the target object (`B`) and your own position (`A`), the vector `B - A` is the 3D displacement to the target.

If you only have a bearing and an elevation to the target, you can get a vector that points at it but you can't determine how far away it is with only those angles. The components for that vector would be: `x = cos(bearing) * cos(elevation); y = sin(bearing) * cos(elevation); z = sin(elevation);` You may need to convert between degrees and radians and may need to add a constant to your bearing and/or elevation to properly line them up with the world axes.

If you have the bearing, elevation, and distance, multiply the vector components above by that distance.
> 3 votes

# Answer
accoring to your changes I can assume you have two angles, one that I call theta which is just like the one you have in 2d plane and has some value between `-pi -> +pi`. and you have a second angle called (let's call this one phi) and it has some value between `-pi/2 -> pi/2`. you can see in the picture what are these angles exactly specifying.

using these 2 angles you can compute normal 3d vector using this formula :

```
 x = cos(theta) * cos(phi);
 y = sin(theta) * cos(phi);
 z = sin(phi);

```
> 2 votes

# Answer
Things simplify considerably if you're willing to use quaternions.

In this case you have to simply store a "direction" unit vector(**D**) and an "upside" unit vector(**U**). Optionally you can store the "right" unit vector that points to the right direction (**R**) or you can compute doing the cross product (**D x U**).

When you want to change your pitch or bearing or orientation you simply have to construct a quaternion using the right vector and multiply the other two for that quaternion.

With this strategy you can store a "direction" vector that even points where you are going and rotate without the problem you may encounter if you touch some nasty rotation pole.

**\[EDIT\]**

Quaternions are 4-tuple of real numbers that represent a real part and the coefficients for tree orthogonal imaginary parts **i**, **j**, **k**. A quaterion may be write as (s,**v**) where s is the real part and **v** is the imaginary 3D vector.

A point in 3D (**p**) may be represented as the quaternion (0,**p**) and the rotation of θ rads about the **r** unit vector is: **q** = (s,**v**) where s = cos(θ/2) and **v** is **r**·sin(θ/2).

now **p\*** = **q** · **p** · **q'** is the rotated point where **q'** is the inverse of **q**.

The inversion of a unit quaternion equals its conjugate so **q'** = (s, -**v**)

The quaternion multiplication shows a little complexity: while the a quaternion can be written as **q** = w + x **i** +y **j** +z **k** thus **p** · **q** is a simple polinomial multiplication, there are the relations so:

we can say that a multiplication between quaternion can be written as:

this lead us to the conclusion that if **q1** is the vector **Q** = \[W1, X1, Y1, Z1\] then

so **q1** · **q2** = **Q** · **A** in term of matrix multiplications.

You can see that a rotation using a quaternion involves **32** multiplications and **24** sums Vs the **9** multiplications and **6** sums for the rotation using the standard matrix rotations.

This difference is due to the fact that a fourth dimension is used to avoid the pole problem that often makes the matrix rotation unviable: the euclideans matrix rotations is not faster, it simply compute less things and you pay this if you pass through a pole.
> 0 votes

# Answer
If you don't want do deal with some nasty trig functions, try parametrizing the movements on each axis. For example, imagine an object moving in a vector (variably scaled) of \<1,2,3\> for 2 seconds at 3 meters per second. Define the units of each axis as one meter. x=t y=2t z=3t Continue time to find where the object would be at t seconds. To find velocity, differentiate each parametric for a velocity vector. For a projectile, z would usually be something like -9.8t^2+t+20 and that projectile's velocity vector would be scalars for x and y and a linear with t for z. I personally like this better because differentiation is more intuitive, but 3D polars are good for some things too
> 0 votes

---
Tags: 3d, physics, projectile-physics
---


# Question
Title: What is the difference between transform.translate and rigidbody.velocity?
I've been tying to understand what the difference between these two methods of moving a rigid body are. Both seem to move the object at a constant rate and both operate on a RigidBody. So what's the difference between the two and when should one be used over the other?

# Answer
> 16 votes
`transform.translate` is not going to utilize the physics system (doesn't look for collisions when moving, ignores any current velocity, etc.), nor will it nessesarily be smooth movement (since you can translate as far as you like). This is essentially setting a new location for the entire object, relative to the current position. This would be how you should move objects if you don't want to use physics. Either because the object doesn't have physics, or you want to ignore physics (like teleporting).

`rigidbody.velocity` uses the physics system, and will be mostly smooth (except for extreme velocities). This is more like telling the objects which direction to move, instead of telling them what position be at. Movement here will consider the physics world around it. If you set a velocity towards a solid wall, the physics system will attempt to make that move, and adjust the velocity based on the collision with the wall. In many cases, you're more likely to leave the velocity alone and adjust the object's acceleration instead, likely by applying a force.

# Answer
> 3 votes
They do rather different things, but can be used to achieve the same results.

Setting the body's `velocity` sets its speed and direction. As long as the body is being updated by the physics system, it's velocity will be (effectively) added to its position in order to arrive at a new position for the frame. This causes the object to move at constant speed over time *until* you change the velocity to something else, or to zero.

The `Translate` method of the `Transform` type adjusts the translation stored in the body's transformation matrix by adding the provided translation to it. This causes the object to move instantly to the new position, once, ignoring the physics system. This will *not* cause the object to move over time unless you constantly call it every frame.

Use the one that makes the most sense for the semantics you want when interacting with the object. If you just want to position it once (or occasionally) and leave it there, using `translate` is fine. If you want it to move constantly, and nicely interact with other physical objects, setting `velocity` is probably less work overall than manually translating it every frame yourself.

# Answer
> 0 votes
The difference starts to matter when you have your rigidbodies collide with each other.

Changing the transform "teleports" the object to a different location without giving it any kinetic energy. It won't interact with any objects on the way. But moving an object by giving it a velocity means that it will push other objects out of the way, which accelerates the other objects and decelerates the object itself.

---
Tags: unity
---


# Question
Title: How to align the corner of the camera with x= 0, y=0?
I need put Main Camera's bottom left corner at starting position 0, 0 (x, y) so all of its coordinates will be positive coordinates. I thought to put the pivot at the bottom left corner but I don't know if it is possible. I thought to adjust it manually, but it displays non-positive, non-integers.

I chose the aspect ratio 16:9 but if I choose the 4:3 proportions, it becomes right:

So, what is the best way to align/put the camera at position 0, 0 at bottom left corner?

# Answer
> 1 votes
If you want the camera to be at 0,0, you set its position to be 0,0. If you want to align the bottom left corner of the camera with 0,0, you need a little math.

It's not required to be an integer coordinate. It can easily be a decimal, depending on the field of view or the size of the projection, and the aspect ratio of the view. For your first image, using 16:9 aspect ratio, the x value would indeed be 8.88 and the y value would be 5.0. With a orthographic size of 5, and an aspect ratio of 16:9. Since the Y dimension is smaller, it'll always equal the orthographic size. The X value is calculated using the aspect ratio:

```
X=(16/9)*5 = 8.88
Y=5

```

Ideally, you'd calculate this in a script that automatically positions the camera. in the `Start()` method.

I suspect you're trying to use Unity in a way that might be standard with other engines, which is why you're finding this to be strange or difficult. Consider your approach and how it fits with how Unity is typically used.

# Answer
> 2 votes
The position shown there is the position of the pivot, which is, as you can see in the image, where the camera's gizmos are - in your case the "scale" gizmos which come out of the camera itself. not where your circle is.

The reason you are seeing these numbers is because of the camera's "size" parameter. This parameter (used for orthogonal cameras) says how many unity units will be from the middle of the screen to the top of the screen (and of course from the middle to the bottom). In your first image, the size is set to 5. Notice how there are five horizontal lines between the y = 0 horizontal line and the camera object. This is also why the camera's y position is 5. You aligned the bottom edge with y = 0, and the screen middle is 5 units above that, therefore it's at y = 5. The reason it's 5.01 and not 5 exactly, is because you didn't align it 100% correctly, the corner you circled is actually at (0, 0.01).

On your second image, the size parameter is set to 6. You aligned the bottom edge with the y = 0 horizontal line, meaning the screen's middle (and thus position) will be at y = 6.

The reason the first image doesn't translate to a clean integer is because of the aspect ratio. 16/9 = X/Y, here you know that the middle of the screen is (in the first case) 5 units above the y = 0 horizontal line (because of the size parameter). 16/9 = X/5 =\> solve for X =\> X = 8.88888...

In the second case though, you selected 6 as your camera's size, and so 4/3 = X/Y =\> 4/3 = X/6 =\> solve for X =\> X = 8. That's why it's a clean integer.

In Unity, by default, the constant axis for orthogonal cameras is the vertical axis. This means that if you change the aspect ratio, the width of your camera's view will change, but the height will remain constant. Knowing this, you can do what you want to. It will however require a small script. You can technically stick this on any GameObject, but you may as well stick it in a script on your camera.

```
void Start(){
    float aspectRatio = Camera.main.aspect; //(width divided by height)
    float camSize = Camera.main.orthographicSize; //The size value mentioned earlier
    float correctPositionX = aspectRatio * camSize;
    Camera.main.transform.position = new Vector3(correctPositionX, camSize, 0);
}

```

---
Tags: camera, unity
---


# Question
Title: How do game engines like Unity and Game Maker exports to other platforms?
From what I understand, if you want to export a Unity or GameMaker game from the editor, the game needs to be compiled to create an executable. I thought that to produce a Windows executable, you needed to be on Windows. How does Unity and GameMaker compile to Mac and Linux, if the engine is running on Windows? Likewise, How do they export to Android and iOS? Do they use the NDK for Android? What about WebGL?

How does the export actually work? Do they use a cross-platform framework written in some programming language, and when you do things with the editor it generates code using that programming language and framework, so that when you export, that code gets compiled? For WebGL, since the UnityScript code doesn't get compiled, can we see the .js files with the code?

# Answer
> 3 votes
> But I thought to produce a Windows executable you needed to be on Windows.

Not true; cross-compilation is a thing. This is essentially a compiler that runs on architecture A but produces executables for architecture B, and it's basically the only way to compile for (for examples) consoles, which don't generally have compilers that run on the console itself.

Similarly, tools like Unity which support deployment to platforms like iOS that generally require specialized development environments will usually defer to the specialized development environments in question. For example, by creating Xcode project files representing the game (even if they're only temporary) and invoking the Xcode build tools to get the executable signed and bundled appropriately.

It's not magic, and they're generally not using any kind of clever totally-platform-agnostic language or tools. Just a bunch of specialized ones for the task or tasks at hand, wrapped up behind a homogenized interface so it *looks* like magic.

# Answer
> 0 votes
There's a thing called IL (Interpreted Language), which is what unity compiles into. From this, it can then be compiled into C++, which most platforms support. For WebGL, Emscripten is used. (Source).

---
Tags: unity, game-maker, export
---


title: Updating code to include states

text:
# Question
Title: Updating code to include states
**The Problem**

I am having a problem in that I am finding it hard to understand how to update my current code so that it uses states. I am creating a game, the game has a menu, each page in the game will be a different state but I am unsure how to implement this in my current code.

Here is the menu I have created, below I have drawn what I am trying to explain.

**The Question** Would it be possible if somebody could, using my code below, help me understand how I can update it to include different states?

**The Code**

```
<div style id="canvas">
        <canvas id="myCanvas" style="border:5px solid #410b11" height="320" width="480">
            <p>Your browser does not support HTML5!</p>
        </canvas>
    </div>

        <script type="text/javascript">

            //Referencing the canvas
            var canvas = document.getElementById("myCanvas");
            var context = canvas.getContext("2d");
            var width = canvas.getAttribute('width');
            var height = canvas.getAttribute('height');

            //Finding the position of the mouse
            var mouseX;
            var mouseY;

            //Images
            var bgImage = new Image();
            var logoImage = new Image();
            var playImage = new Image();
            var instructImage = new Image();
            var settingsImage = new Image();
            var aboutImage = new Image();
            var peaceImage = new Image();

            var backgroundY = 0;
            var speed = 1;

            //Arrays below used for mouse over function
            var buttonX = [130,110,130,160];
            var buttonY = [100,140,180,220];
            var buttonWidth = [96,260,182,160];
            var buttonHeight = [40,40,40,40];

            var peaceX = [0,0];
            var peaceY = [0,0];
            var peaceWidth = 35;
            var peaceHeight = 35;

            var peaceVisible = false;
            var peaceSize = peaceWidth;
            var peaceRotate = 0;

            var frames = 30;
            var timerId = 0;
            var fadeId = 0;
            var time = 0.0;

            peaceImage.src = "Images/peace.png";
            bgImage.onload = function(){
                context.drawImage(bgImage, 0, backgroundY);
            };
            bgImage.src = "Images/background.png";
            logoImage.onload = function(){
                context.drawImage(logoImage, 50, -10);
            }
            logoImage.src = "Images/logo.png";
            playImage.onload = function(){
                context.drawImage(playImage, buttonX[0], buttonY[0]);
            }
            playImage.src = "Images/play.png";
            instructImage.onload = function(){
                context.drawImage(instructImage, buttonX[1], buttonY[1]);
            }
            instructImage.src = "Images/instructions.png";
            settingsImage.onload = function(){
                context.drawImage(settingsImage, buttonX[2], buttonY[2]);
            }
            settingsImage.src = "Images/settings.png";
            aboutImage.onload = function(){
                context.drawImage(aboutImage, buttonX[3], buttonY[3]);
            }
            aboutImage.src = "Images/about.png";

            timerId = setInterval("update()", 1000/frames);

            canvas.addEventListener("mousemove", checkPos);
            canvas.addEventListener("mouseup", checkClick);

            function update() {
                clear();
                move();
                draw();
            }
            function clear() {
                context.clearRect(0, 0, width, height);
            }
            function move(){
                backgroundY -= speed;
                if(backgroundY == -1 * height){
                    backgroundY = 0;
                }
                if(peaceSize == peaceWidth){
                    peaceRotate = -1;
                }
                if(peaceSize == 0){
                    peaceRotate = 1;
                }
                peaceSize += peaceRotate;
            }

            function draw(){

                context.drawImage(bgImage, 0, backgroundY);
                context.drawImage(logoImage, 50,-10);
                context.drawImage(playImage, buttonX[1], buttonY[0]);
                context.drawImage(instructImage, buttonX[2], buttonY[1]);
                context.drawImage(settingsImage, buttonX[2], buttonY[2]);
                context.drawImage(aboutImage, buttonX[3], buttonY[3]);
                    if(peaceVisible == true){
                    context.drawImage(peaceImage, peaceX[0] - (peaceSize/2), peaceY[0], peaceSize, peaceHeight);
                    context.drawImage(peaceImage, peaceX[2] - (peaceSize/2), peaceY[2], peaceSize, peaceHeight);
                }
            }

            function checkPos(mouseEvent){
                if(mouseEvent.pageX || mouseEvent.pageY == 0){
                    mouseX = mouseEvent.pageX - this.offsetLeft;
                    mouseY = mouseEvent.pageY - this.offsetTop;
                }else if(mouseEvent.offsetX || mouseEvent.offsetY == 0){
                    mouseX = mouseEvent.offsetX;
                    mouseY = mouseEvent.offsetY;
                }
                for(i = 0; i < buttonX.length; i++){
                    if(mouseX > buttonX[i] && mouseX < buttonX[i] + buttonWidth[i]){
                        if(mouseY > buttonY[i] && mouseY < buttonY[i] + buttonHeight[i]){
                            peaceVisible = true;
                            peaceX[0] = buttonX[i] - (peaceWidth/2) - 2;
                            peaceY[0] = buttonY[i] + 2;
                            peaceX[1] = buttonX[i] + buttonWidth[i] + (peaceWidth/2);
                            peaceY[1] = buttonY[i] + 2;
                        }
                    }else{
                        peaceVisible = false;
                    }
                }
            }
            function checkClick(mouseEvent){
                for(i = 0; i < buttonX.length; i++){
                    if(mouseX > buttonX[i] && mouseX < buttonX[i] + buttonWidth[i]){
                        if(mouseY > buttonY[i] && mouseY < buttonY[i] + buttonHeight[i]){
                            fadeId = setInterval("fadeOut()", 1000/frames);
                            clearInterval(timerId);
                            canvas.removeEventListener("mousemove", checkPos);
                            canvas.removeEventListener("mouseup", checkClick);
                        }
                    }
                }
            }
            function fadeOut(){
                context.fillStyle = "rgba(0,0,0, 0.2)";
                context.fillRect (0, 0, width, height);
                time += 0.1;
                if(time >= 2){
                    clearInterval(fadeId);
                    time = 0;
                    timerId = setInterval("update()", 1000/frames);
                    canvas.addEventListener("mousemove", checkPos);
                    canvas.addEventListener("mouseup", checkClick);
                }
            }
</script>

```

# Answer
> 1 votes
A state is intended to help your program determine what situation it has found itself in. To implement a simple state machine, all you really need is a simple variable. For example `var state = 1;`. What I'd suggest you do is update the `draw()` function to include a switch-case statement. This function should be responsible for everything that has to do with screen output - no other function should do any drawing to the canvas. The idea is that you set everything up via variables (including state machines) before this function is called. Then you call it, and the frame is done. This function will first clear your canvas and then completely redraw the UI based on what state it's in. So for example:

```
var state = 1;
function DrawUI(){
    context.clearRect(0, 0, canvas.width, canvas.height); //Clear canvas
    switch(state){
        case 1:
            //draw main menu
            break;
        case 2:
            //draw play menu
            break;
        case 3:
            //draw settings menu
            break;
        default:
            alert("Unknown state: "+state);
            break;
    }
}

function ClickedOnPlayButton(){
    state = 2;
    DrawUI();
}

function ClickedOnSettingsButton(){
    state = 3;
    DrawUI();
}

```

---
Tags: javascript, software-engineering, html5, html-canvas
---