title: Spell casting in a Turn based game

text:
# Question
Title: Spell casting in a Turn based game
I'm trying to make a start on a Spell/Skill system similar to a Moba or MMO from my project where you would press the skill button and see what type of targeting it has then aim (either in an area or at a target) and then "fire" the skill but I am coming really unstuck rather soon into it.

Please also bare in mind I am not asking how to implement X Spell from Y Game I'm looking to understand the structure of a typical spell in a MOBA/MMO not the spells behavior.

I'll try to describe the flow I'm aiming for

1. Player presses Skill Button One - for simplicity's sake a Standard Fireball
2. Cursor Changes to show targeting,

-if it was an Aoe it would show the aoe, now this part stays like this until the Player casts or cancels.
3. The Player casts (left click) - spell is spawned targeting stuff goes away.
4. The Player cancels (right click) - everything reverts targeting stuff goes away.

This may seem like a really simple problem for some but I am really struggling with **step 2**

I have no code to show as every time I try something I find something fundamentally wrong with it, I'm repeatedly writing awful code because I can't find a starting point for this, in short - 'I don't get it'.

Would I use a state-machine and if-so where? Would it not get gradually more complex each with every new spell type? I'm a fan of doing this in a component based style but that right now is irrelevant if I can't understand the basic concept of it.

Apologies, I don't have the technical vocabulary to ask this is in a straight forward, concise way. If code is really necessary I can copy in my last attempt but I believe that would just lead people to think I want to fix the un-fixable.

edit: Added EntitySKillUser and Base\_Skill

EntitySkillUser

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

public class EntitySkillUser : MonoBehaviour
{
    public GameObject target = null;
    public Skill[] skills;

    private Transform castLocation;
    private Projector projector;

    private void Start()
    {
        castLocation = transform.Find("castLocation");
        projector = castLocation.gameObject.GetComponent<Projector>();

        projector.enabled = false;
        //set up a dummy spell
        skills = new Skill[1];
        skills[0] = new Skill("Test", 2, 5, TargetType.SINGLE);
    }

    void Update ()
    {
        ///problem here only works when Imholding the button down - yes I know about getButtonDown and getButton
        //I want this to go into "targeting" mode when the buttons pressed wait for a left click to confirm THEN cast
        //
        if (InputManager.AbilityButtonOne())
        {
            if (target == null)
            {
                //how do I set each unqie targeting type for each spell without having to do something like this for each in the EntitySkillUser
                projector.enabled = true;

                Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                RaycastHit hit;
                LayerMask layerMask = LayerMask.NameToLayer("Terrain");

                int layer = (1 << layerMask);

                //set projectorposition
                if (Physics.Raycast(ray, out hit, Mathf.Infinity, layer))
                {
                    Vector3 pos = new Vector3(hit.transform.position.x, 6f, hit.transform.position.z);
                    projector.transform.position = pos;

                }
                RaycastHit hitTwo;

                if (Physics.Raycast(ray, out hitTwo, Mathf.Infinity))
                {

                    if (Input.GetMouseButton(0))
                    {
                        //set target
                        if (hitTwo.collider.GetComponent<Enemy>())
                        {
                            target = hitTwo.collider.gameObject;
                        }
                    }
                    else if (Input.GetMouseButtonDown(1))
                    {
                        //cancel
                    }

                }

            }
            else
            {
                Debug.Log("have target "  + target.name );
            }

        }

    }

}

```

Base\_Skill

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

public class Base_Skill
{
    public string name;
    public int apCost;
    public int range;
    public TargetType targetType;

    public Base_Skill(string name, int apCost, int range, TargetType targetType)
    {
        this.name = name;
        this.apCost = apCost;
        this.range = range;
        this.targetType = targetType;
    }
}

public enum TargetType
{
    SINGLE,
    AOE,
    MULTI
}

```

# Answer
> 3 votes
Sounds like a perfect fit for an event-driven system i.e. the observer design patten. This will allow you to decouple all of the individual components that you need. Each component would then subscribe to an event and react accordingly.

When a skill is clicked, an event is broadcast i.e. `SkillClicked`. This message would encapsulate all the information required by each individual system to progress the action i.e. `CursorManager` could change the cursor when a `SkillClicked` is fired, `SpellManager` could start a cast timer and your UI could display a cast bar.

The benefit to this is that it is extensible, you can add more components as you need and then enable their behaviour by simply subscribing to the correct event. A basic example implementation is below in implemented .Net Framework 4.6.1, I haven't tested it in Unity, so you may need to change the syntax of various parts (I'm unsure off the top of my head whether it is supported in Mono).

If i'm not mistaken, Unity has built in support for events that you can extend, but I haven't used it enough myself to be sure.

```
public static class SkillClicked : EventArgs
{
    public string SkillName { get; }
    public SkillType Type { get; }

    public SkillClicked(string skillName, SkillType type)
    {
        SkillName = skillName;
        Type = type;
    }

    public enum SkillType
    {
        AoE = 0,
        Targeted = 1
        //etc..
    }
}

public static class EventManager
{
    public static EventHandler<SkillClicked> SkillClicked { get; set; }
}

public class CursorManager
{
    public CursorManager()
    {
        EventManager.SkillClicked += OnSkillClick;
    }

    private void OnSkillClick(object sender, SkillClicked e)
    {
        switch (e.Type)
        {
            case SkillType.AoE:
                //set cursor to AoE
                break;
            case SkillType.Targeted:
                //set cursor to Targeted
                break;
        }
    }
}

public class SpellManager
{
    public SpellManager()
    {
        EventManager.SkillClicked += OnSkillClick;
    }

    private void OnSkillClick(object sender, SkillClicked e)
    {
        if(e.SkillName == "Fireball")
            //start casting fireball
    }
}

```

Once these manager classes are constructed in some `Init()` method, you need only publish a `SkillClicked` event, for the correct behaviour to be invoked.

Hope this helps.

**EDIT:** If you need any further information regarding events and the observer pattern or other useful design patterns, I highly recommend you take a look at GameProgrammingPatterns

# Answer
> 2 votes
You're kinda stepping into territory I know well and have a lot of confidence with here :)

Were I to implement this, it's all about what code gets authority.

If the spell itself controls the cursor behaviour then what happens when your cursor needs to change otherwise? you'd need to control it in *another* place, and that can't step on what the spell is telling it to do.
You'd have one section of code saying it needs to be the "You can't walk here" icon, and another saying "area of effect blast template" and somewhere something needs to decide which one takes precedence.
Displaying what the character will do when you click is the primary function of the Cursor icon.

The best solution is almost always to centralise a given piece of functionality.
In an ideal world, you'd have a CursorController which talks to your game-state and decides what the best cursor for the situation is.
This cursor-controller can be folded into your existing input manager without too much trouble.

What you need to do is something like an extended if/else statement, you've got a bunch of nested logic to do and a Switch-Case wouldn't be complex enough.

```
//SpellManager - The central class that manages the update-loops of spells and tracks their data.
//GetCurrentSpell() - a method to retrieve the spell the caster has readied to fire
//MySpell - The individual spell the caster has readied to fire,
//    MySpell is managed by SpellManager and is a Spell class.
//    It contains the data and internal logic of a spell, such as its damage, mana cost, cursor icon, visual effects data and so on.
//SetCursor(arg) - Sets the mouse cursor icon, if the argument input is the same as the one it last set to, then it won't make any changes

If(SpellManager.HasSpellReady()){
  MySpell = SpellManager.GetCurrentSpell();
  Icon = MySpell.GetCursorIcon();
  if(MySpell.IsAOE()){
    AOE = MySpell.GetAOE();
    //Build the AOE overlay using the icon and aoe values
  }
  SetCursor(Icon);// Set your mouse cursor to the one assigned by the spell.
}else{
  SetCursor("Default_Cursor_Icon");
// You can also include logic here for displaying other information,
// such as showing the interaction-state of the selected character.

}

```

Whether you run this code continuously off your main execution loop or trigger it whenever you see a change in the position of your mouse, or any other system is up to you. I favour the second one. There are probably more computationally efficient systems out there for deciding when to update this but it'll work just fine.

# Answer
> 0 votes
Not sure how your project is organised, but in theory one way to do this is to include something like `target_type` to your spells. Each spell, similar to how you save its damage and mana cost, save it's target type as well.

You have a variety of choises of what value to give to it. You can give it a value that represents it's AoE range, with 0 being "single target" (special case). Or you can create an enum, with values `single_target` and `AoE_target`, although that may have restrictions on defining range, but you can also add values like `allies_only` (for healing skills) and `enemies_only` (for aggressive ones).

So the logic goes: click on skill/press key -\> get that skill's data, based on that skill's `target_type` -\> change cursor depending on it

This is one of the ways to do it, I'm sure there are more than enough other ways that may even work better, but it's a start.

# Answer
> 0 votes
Representing your input system with a state machine seems to be the way to go here. I don't see why it would get "gradually more complex each with every new spell type", because most of the spell-specific logic could be encapsulated in the object representing the spell being cast. The state machine itself could be largely spell-agnostic.

The only thing the "pick target" state needs to know about the current spell is the `TargetType`. When the player picked a valid target, then the state just needs to pass target and spell on to the "cast spell" state. What the spell actually does is of no concern for the pick target state.

The "cast spell" state wouldn't need to know much about the Spell either. It would just call methods from the spell object. The spell object itself would manage its own execution and call back to the "cast spell" state when it is done. What I would do is have a method `public abstract void Execute(GameObject target, PickTargetState callbackState)` in my Spell base class. The implementation would then do what the spell is supposed to do and then call `callbackState.SpellFinished()` when it is done. The method `SpellFinished()` of `PickTargetState.SpellFinishded()` would then switch to the next state.

# Answer
> 0 votes
Since you are using Unity I would recommend letting the engine essentially run itself, thats what we had done the last time something like this was needed for a game jam.

In essence, you let the spell deal with its own things, including the rendering and the casting. Your spell could have a simple interface along the lines of Aimfor(point x) where you pass in the point the mouse is pointing at and the spell itself can descide what to render an how to do so since it is the only thing that really knows what to do in this case. It would also possess a second method in the interface Cast(point x) which makes the spell class spawn a new object. This new object then simply has a collider that it uses to detect if/to who it should apply effects and performs the actions it needs.

Using this technique its very easy to add new spells as you only need to define the spell itself as your input manager will know which spell should be used and manage it simply from there

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


# Question
Title: Converting code to work in godot with sliders
I have some Fragmentarium code that I would like to convert so it will work in Godot anyone have any ideas how I can do this?

The code is below:

```
#include "Progressive2D.frag"

#group Spiral
uniform int StripesNum; slider[1,10,100]
uniform int StripesAng; slider[-180,45,180]
uniform float StripesThinkness; slider[0,0.5,1]
uniform float CenterHole; slider[0,0.125,1]
uniform float OuterHole; slider[0,0.825,1]

const float pi = 3.141592653589793;

vec2 cLog(vec2 z)
{
return vec2(log(length(z)), atan(z.y, z.x));
}

vec3 color(vec2 p)
{
float t = radians(float(StripesAng));
float c = cos(t);
float s = sin(t);
mat2 m = mat2(c, -s, s, c);
vec2 q = m * cLog(p);
return vec3(float
( mod(float(StripesNum) * q.y / (sqrt(2.0) * pi), 1.0) < StripesThinkness
|| length(p) < CenterHole
|| length(p) > OuterHole
));

}

```

Here's the animation of the code working in Fragmentarium

Here's the animation of moire patterns, I'm trying to recreate this in Godot so I can animate multiple copies of spirals turning at different rates (along with using sliders to adjust variables) to produce different moire patterns.

Note: // Progressive2D.frag This is a utlity / include for the program to set up anti-aliased 2D rendering. Progressive2D.frag code location

# Answer
> 0 votes
This code is apparently a fragment shader code. You can use shaders in godot, since it have its own shading language. It's just a bit different from another shading languages, so I think you can learn it fast.

EDIT:

I achieved a similar result with Godot 3. In a scene, insert a sprite, then create a new ImageTexture or simple load any image. After that, create a new ShaderMaterial for Sprite, then create a new Shader for the ShaderMaterial and insert this shader code:

```
shader_type canvas_item;

// group Spiral
uniform float StripesNum = 9; //slider[1,10,100]
uniform float StripesAng = 45; //slider[-180,45,180]
uniform float StripesThinkness = 0.5; //slider[0,0.5,1]
uniform float CenterHole = 0.125; //slider[0,0.125,1]
uniform float OuterHole = 1; //slider[0,0.825,1]

vec2 cLog(vec2 z){
    return vec2(log(length(z)), atan(z.y, z.x));
}

void fragment(){
    float pi = 3.141592653589793;

    vec2 p = UV.xy - vec2(0.5, 0.5); // correct to the center of texture
    float t = radians(StripesAng);
    float c = cos(t);
    float s = sin(t);
    mat2 m = mat2(vec2(c, -s), vec2(s, c));
    vec2 q = m * cLog(p);

    float color = float(mod(StripesNum * q.y / (sqrt(2.0) * pi), 1.0) < StripesThinkness
        || length(p) < CenterHole
        || length(p) > OuterHole
    );

    COLOR = vec4(vec3(color),1);
}

```

The result was the following:

Note the uniform variables: their values can be changed via GDScript with the method `set_shader_param` from `ShaderMaterial`.

---
Tags: animation, python, scripting, godot
---


# Question
Title: What is a good strategy to recruit test players for a chess app?
We developed a chess app for iMessage and we would like to have people try it out and tell us their opinions.

Do you know a good strategy to give away free promo codes for the pro version of our new game?

# Answer
> 8 votes
Go to where your audience is.

You have a chess app, so I would recommend to find some online **communities** of chess players. Read their community guidelines, FAQs and a bit of their content to make sure that discussing your app is on-topic in the community. Read it carefully: unwelcome advertising is annoying and creates more damage than value. For example, definitely do not do this as a question here or on any other stackexchange site! When you see nothing which hints that talking about your app might be unwelcome, just create a thread where you introduce yourself, ask them if they would like to give you some feedback about your chess app, post a few codes and the promise to give a private code to anyone who contacts you privately.

Also do your research and check if there are any **influencers** around you could collaborate with. Are there any YouTubers, bloggers, news websites, social media personalities or similar who have a non-negligible reach in the chess community and regularly talk about chess apps? Find a way to contact them directly, give them a promo code and ask if they would like to post about it. The relationship between developers and influencers is beneficial for both sides. They get to report about something which isn't available to the general public yet and you get free promotion. So don't be shy. The worst they can do is ignore you.

Also use the reach of **your own social media presence** (you *do* have a social media presence, do you?). Dropping a few codes in a public post will likely burn out quickly. But you could at least announce that you are starting a closed beta and anyone who asks you nicely will get a code. **Check if anyone talks about your game on social media**. When they have some reach, consider sending them a code, too.

# Answer
> 4 votes
At a very high level, a possible cycle for finding users goes something like this:

1. Identify your target audience. (Note this step is not trivial & can be much more difficult to do than it sounds).
2. List places &/or communication channels where you expect a worthwhile amount of your target audience to be. Look for options that either have a high % of potential users (I.E. most people there would be interested) or that have a large enough over quantity (I.E. most people on Facebook might not play chess, but thousands of chess players also happen to be on Facebook).
3. Restrict your list from item 2 to places that permit solicitation.
4. Solicit users.
5. Invite the users to participate in the process of finding users. That is to say, try to get some of them to repeat the steps listed here in the hopes of discovering previously unknown users.

---
Tags: marketing, playtesting
---


# Question
Title: Is there a way to duplicate the windows desktop zooming in SDL to make low res pixels look like stylyzed cartoon art?
When you hit the Win key and numpad plus key at the same time it opens the desktop magnifying glass and the effect of this on low res pixel art is to make it look like super cool stylized cartoon art. I want the game to look like this all the time. Is there a way to do this permanent i SDL or DirectX or OpenGL?

How I have achieved this image is to run the game in a small windows and have the windows 10 magnifying glass hoover over it and I hit print screen. And I want the game to look like this all the time in full screen.

Ps. This is the Gradius 3 ship that I use for place holder graphics for question asking purposes.

# Answer
> -1 votes
You could achieve this by using a viewport: https://wiki.libsdl.org/SDL\_RenderSetViewport

You define a rectangle somewhere in your scene which will then fill the window. You can update where the rectangle is as your player moves around.

---
Tags: sdl, windows
---


# Question
Title: In a game such as Star Wars Galaxies, Planetside, and Warcraft how would server-side collision/terrain navigation work?
I'm trying to learn some advanced topics in multiplayer networking for fun and education, specifically how server-side collision/terrain navigation works in MMOs and/or any online game.

Personally, I have a nice little test server where I can move two units around a plane and they can collide with one another, no big issue, then I started to think about real terrain. Features such as mountains, rivers, cliffs, etc.

I know that a map can be chunked out and I could use spatial partitioning to narrow my collision detection down to small chunks, however, I'm a bit stumped if the server and client would be running the exact same physics calculations (gravity, physics, etc).

I'm assuming the server would need to have an exact duplicate of the map-data that the player is seeing client side to perform the appropriate collision/terrain calculations to make sure nothing nefarious is going on - such as a way to prevent map hacks and hiding in walls/mountains.

This is all assuming the player has direct control over the movement/direction of their character ala WoW/SWG/Planetside, and not like a MOBA/RTS game.

My question boils down to this (as I know implementation details vary) what does the server-side need in order to properly keep track of players in a varied terrain world?

# Answer
> what does the server-side need in order to properly keep track of players in a varied terrain world?

The same things a single-player game would need to do this. The server in a client-server relationship generally only differs from a single-player game in that it has to deal with sending information to clients periodically (which comes with a raft of scaling problems, of course). Conceptually things work mostly the same.

Thus, the server would keep authoritative information on the locations of all player's collision capsules (or however collision is represented, but capsules are common). The server would also need all the other collision primitives near the players, however those are represented, and the collision information for the terrain (typically a height map or one such converted to a triangle mesh).

Essentially the server needs to keep the entire physics world around, at least near the players, to be able to authoritatively simulate the world and handle player collisions.

This is where scale can become an issue relative to a single player game, because a single player game will generally only need to keep the immediate area around one player in memory, whereas a server may need to keep many such areas. Depending on the scale of the game this will involve more aggressive optimizations, more expensive hardware, or actually splitting the simulation up into discrete chunks with boundaries between them (such as "map travel" points) so multiple server processes across multiple pieces of hardware can bear the load.

---

It is true that the client and the server generally have exact copies of the map and collision data. This lets clients do local simulation and interpolation of the game state while they wait for authoritative updates from the server; this hides latency.

This itself doesn't really prevent map hacks. The real major roadblock to map hacks and such is simply having the server keep a tight rein over the information it sends to any one client. Generally, it is not necessary to send the position of *every entity* on the map to any one client. A client only needs to know about stuff it can see nearby, as determined by the server. If the server instead just sends *everything*, any enterprising hacker can modify the client to produce a "wall hack" using that information.
> 1 votes

---
Tags: 3d, multiplayer, terrain, client-server
---


title: Light and shadows like Diablo

text:
# Question
Title: Light and shadows like Diablo
I wanted to have shadows in my game and thought the way they were implemented in Diablo was good enough. Any hints on how to produce a similar outcome?

# Answer
The environment lighting demonstrated in your screenshots is largely tile-based. The effect is particularly notable along the diagonal just to the right of the enemies in the screenshot.

In such a system, the map is divided into tiles (which may or may not be the same tiles used to actually build the visuals of the map) and each tile has a base light level. Players and other objects have "light" values that are then added to this base light level to determine how bright or dim to shade any given tile. These light values generally decay in some fashion, per tile, in a radius around the object. For example, if the player has a light value of "3" and is standing at the center of a room, the player might impart light value bonuses as follows to the surrounding tiles:

```
+1 +1 +1 +1 +1
+1 +2 +2 +2 +1
+1 +2 +3 +2 +1
+1 +2 +2 +2 +1
+1 +1 +1 +1 +1

```

For additional realism, objects like walls can be marked as such to block or occlude the proliferation of the light pattern above.

---

As for the object shadows (those "cast" by the creatures), those can just be built in to the character's sprite. You can see this in the one demon at the bottom right of the fire column. It's shadow is clipping *over* the fire, and the fire itself does not impact its shadow at all. It does impact the environmental light as above, but not the creature's own shadow.
> 3 votes

---
Tags: 2d, lighting, shadows
---


# Question
Title: How can I detect whether a point is moving in a circle?
I want to detect if my GameObject (`Vector3 Point`) being dragged by the player's finger is moving in a circular fashion.

I thought I could save the last 5 points every 10 frames and join them by lines. Then I'd project them into a "defined" plane. From there, I can form the perpendicular bisectors of those line segments - to check where they are intersecting.

If every intersection point is very nearby - the finger is swiping in a circle!

Now I only need to check if the intersection point is close.

How can I check if they intersect? Or is there a better way to solve this?

Here's my code so far:

```
public LinkedList<Vector3> FingertipPoints;
public Transform Fingertip;

private void Start()
{
    FingertipPoints = new LinkedList<Vector3>();

    FingertipPoints.AddFirst(new Vector3(0, 0, 0));
    FingertipPoints.AddLast(new Vector3(0, 0, 0));
    FingertipPoints.AddLast(new Vector3(0, 0, 0));
    FingertipPoints.AddLast(new Vector3(0, 0, 0));
    FingertipPoints.AddLast(new Vector3(0, 0, 0));
}

[Range(1,60)]
public int FramesPerCheck = 10; // 6checks per sec
private int Frame;
// Update is called once per frame
void LateUpdate()
{
    Frame++;
    if (FramesPerCheck == Frame)
    {
        Frame = 0;
        FingertipPoints.RemoveLast();
        FingertipPoints.AddFirst(Fingertip.position);
    }

    //Get the Direction Vectors
    Vector3 V1 = FingertipPoints.First.Value - FingertipPoints.First.Next.Value;
    Vector3 V2 = FingertipPoints.First.Next.Value - FingertipPoints.First.Next.Next.Value;
    Vector3 V3 = FingertipPoints.First.Next.Next.Value - FingertipPoints.First.Next.Next.Next.Value;
    Vector3 V4 = FingertipPoints.First.Next.Next.Next.Value - FingertipPoints.Last.Value;

    //Project them on a plane
    V1 = Vector3.ProjectOnPlane(V1, Fingertip.forward);
    V2 = Vector3.ProjectOnPlane(V2, Fingertip.forward);
    V3 = Vector3.ProjectOnPlane(V3, Fingertip.forward);
    V4 = Vector3.ProjectOnPlane(V4, Fingertip.forward);

    //Get the Perpendicular Vectors (is this even right?)
    Vector3 C1 = Vector3.Cross(V1, Fingertip.forward);
    Vector3 C2 = Vector3.Cross(V1, Fingertip.forward);
    Vector3 C3 = Vector3.Cross(V1, Fingertip.forward);
    Vector3 C4 = Vector3.Cross(V1, Fingertip.forward);

    //???
    //How to check if they intersect nearby??
    //

}

```

# Answer
The idea sounds interesting, but it might be too complicated. Depending on the type of steering mechanic used in your game, you could restrict the input so that circular motion is easy to control for the player (e.g. by simple left/right joystick/button input to go left/right on a circular arc). That would detection also make much easier.

If you use free motion, which makes it harder to steer the object on a circlar path, the detection must also be more general. A problem I do see with your idea above, is that the "normal rays" do only intersect in one single point if the motion is perfect circle. Otherwise you'll get multiple different intersection points... However, you could average the resulting intersection points of all the ray pairs to get an estimate I guess. If they are close together, and all on the same side of the input line segments, then the center/radius of a circle can be calculated/estimated to match the input approximately.

**Geometry: Line-Line / Ray Intersection** You'll find lots of tutorials and examples on the webs and also here Stack Overflow on how to do this. (If I remember correctly, there's also something in Unity called a Ray2D, maybe that can be used somehow too.)

Oh, but wait, I think I get it now: you want to detect if a touch motion path can be approximated with a circular arc: **Circular gesture detection**? - **In that case, this detection method seems to be very promising!**

Edit: Related topic: Simple circular gesture detection
> 1 votes

---
Tags: unity, vector, input, geometry, touch
---


# Question
Title: Multiple image objects extracted from spritesheets or one-two object for all?
Let's say I want to make a 2D game and I'll use a spritesheet containing all of the animation frames and a texture-atlas for static sprites such as walls, non-animated decorations...etc.

Should I create separate image objects for all the static sprites and for all animation-rows or should I just pass the on-texture-atlas (or on-spritesheet) coordinates for them?

Which solution, or "direction" is considered elegant in game-development?

Thanks for the help! :)

# Some pseudocode:

**Separate image objects:**

```
Class StaticSprite {
  Image texture;

  // ...

  public Image getImage() {
     // ...
  }

  public static final CheckedWall cw = new CheckedWall( -- checked wall grid extracted from the texture-atlas -- )
  public static final WoodWall ww = new WoodWall( -- wood wall grid extracted from the texture...
}

```

**Or:**

```
class StaticSprite {
 int texX, texY, size;

 // ...

 public Image getImage() {
    // gives the part of the spritesheet
 }

 public static final WoodWall ww = new WoodWall( -- coordinates for the texture-atlas -- )
}

```

Assuming that the spritesheet is accessible for all these sprite-related classes.

# Answer
> 0 votes
Most of the time you should go for a hybrid approach, seperating by character\tileset\what have you.

This way you dont have to load up a giant file, which would be much slower if you dont load the full game graphics all at once, and would use up less memory at once.

---
Tags: game-design, sprites, performance, spritesheet
---


title: Unity OnCollision2D not working

text:
# Question
Title: Unity OnCollision2D not working
I'm new to Unity and C# (though I'm experienced in python) and I am trying to make a pong clone, I've spent ages googling and trying to fix this issue but for some reason my OnCollisionEnter2D won't work

My paddle hit method:

```
public void PaddleHit(Collision2D col)
{

    float y = WhereBallHitPaddle(transform.position,
        col.transform.position,
        col.collider.bounds.size.y);

    Vector2 dir = new Vector2();

    //determing direction to left or right depending on the paddle

    if (col.gameObject.name == "Player1")
    {
        dir = new Vector2(1, y).normalized;
    }
    if (col.gameObject.name == "Player2")
    {
        dir = new Vector2(-1, y).normalized;
    }

    rb.velocity = dir * speed;

    //play ball paddle collision sound
    SoundManager.Instance.PlayOneShot
        (SoundManager.Instance.ballpaddle);

}

```

When I run the game the ball moves, then when it comes into contact with a paddle it just stops moving, and if it comes into contact with a wall it bounces off, but at no point does it trigger the OnCollisionEnter2D. (I think my codes indents aren't showing properly here but it is all indented correctly, there are no compile errors or anything).

# Answer
You don't pass a Collision2D object to your paddle, instead as other people have suggested, do something like this:

```
void OnCollisionEnter2D(Collision2D collision)
{
    //put code here
    Debug.Log("Hello World");
}

```
> 2 votes

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


# Question
Title: Accessing a UI Image that is a child of a GameObject?
I'm sure there is a very simple solution to this issue. I am creating a UI for a 2D RPG in Unity.

I have a Canvas with a two GameObjects:

DialogManager & MenuManager

The Dialog Manager has a child "DialogBox" which is a UI Image.

And the Menu Manager has three children for each part of the menu, so: three UI Images.

How the heck do I access these UI Images in a script attached to a different gameObject? Since they're technically not gameObjects, I can't just use the old gameObject.Find(). I've seen some things about Transforms and Children, but I just can't wrap my head around it.

# Answer
They aren't technically GameObjects, but are attached to GameObjects, and all GameObjects have by default a Transform. So, what you could do, in scripting, is to use a Transform's method called GetChild(index), receives an index of the child you want to retreive. Now, you may have the parents' references as Canvas, Image, etc., but all Components have a reference to their GameObject and Transform, so you can easily call that method:

```
public class Example : MonoBehaviour
{
    Image imageChild;

    void Awake()
    {
        imageChild = transform.GetChild(2).GetComponent<Image>(); /// Give me the third child, and give me its Image component
    }
}

```

If what you want is to retreive all the components in your children, then GetComponentsInChildren is what you are looking for:

```
public class Example : MonoBehaviour
{
    public Sprite spriteToAssign;

    void Awake()
    {
        Image[] childrenImages = GetComponentsInChildren<Image>();

        foreach(Image childImage in childrenImages)
        {
            childImage.sprite = spriteToAssign;
        }
    }
}

```

A way more easier and fast approach, would be to also have a public collection (array or list) of Images, and you assign them on the Inspector. As easy as this:

```
public class Example : MonoBehaviour
{
    public Image[] childImages;
    public Sprite spriteToAssign;

    void Start()
    {
        foreach(Image image in childImages)
        {
            image.sprite = spriteToAssign;
        }
    }
}

```

Hope it helps.
> 2 votes

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


# Question
Title: How can I rotate childrens nodes with parent node in cocos2dx?
Consider the following code...

```
cocos2d::Node* parent = cocos2d::Node::create();
cocos2d::Node* child = cocos2d::Node::create();
parent->addChild(child);
parent->rotate(-90.0f); // But its not affecting the child position

```

When I am rotating the parent node by an angle, It's not affecting the child node position. How can I get it right? Please help. Thanks.

# Answer
Use `setRotation()` method instead of `rotate()`
> -1 votes

---
Tags: c++, transformation, cocos2d-x, tree
---


# Question
Title: How can I draw Polyline and detect its collision with other objects?
The idea is to draw trace of moving Actor and if some other Actor intersect it, some function would be called.

I've been searching for solution to this problem in Intersector class, but it seems to me that the only way to do what I want is to implement my polyline as a Polygon and find intersections, but its totally inelegant. I'm sure there should be some smart way to do this.

# Answer
Well, the best way I could solve this problem is to create a `Group` of `Actors`, that are `Sprites` with `Polygon` bounds.

So `CollidablePolyline` class takes array of floats as vertices (just like `Polyline` class) and then draw textured polyline on stage.

```
class CollidablePolyline(vertices: Array<Float>): Group() {

    init {
        for (i in 0 until vertices.size-2 step 2) {
            val startPoint = Vector2(vertices[i], vertices[i+1])
            val endPoint = Vector2(vertices[i+2], vertices[i+3])
            addActor(CollidableLine(startPoint, endPoint))
        }
    }
}

class CollidableLine(p0: Vector2, p1: Vector2): Actor() {

    private var thickness = 15f

    private var pixmap = Pixmap(1, 1, Pixmap.Format.RGBA8888)
    private var texture = Texture(pixmap)
    private var sprite = Sprite(texture)
    private var bounds = Polygon()

    init {
        val distance = p0.dst(p1)
        setSize(distance, thickness)
        setOrigin(0f, height / 2f)
        setPosition(p0.x, p0.y - height / 2)
        val w = p1.x - p0.x
        val h = p1.y - p0.y
        rotation = MathUtils.radiansToDegrees * MathUtils.atan2(h, w)
        pixmap.setColor(0f, 0f, 0f, 1f)
        pixmap.fill()
        texture.draw(pixmap, 0, 0)
        sprite.setSize(width, height)
        sprite.setOrigin(originX, originY)
        sprite.rotation = rotation
        sprite.setOriginBasedPosition(p0.x, p0.y)
        bounds.vertices = floatArrayOf(p0.x, p0.y - height / 2, p0.x, p0.y + height / 2, p1.x, p1.y + height / 2, p1.x, p1.y - height / 2)
        bounds.setOrigin(originX, originY)
        bounds.rotation = rotation
    }

    override fun draw(batch: Batch?, parentAlpha: Float) {
        sprite.draw(batch)
    }
}

```

So now you can use `bounds` to detect intersection of each line in the polyline.

Moreover, `CollidableLine` class allows to change thickness and color (just change color of a `Pixmap` and `texture.draw(pixmap)` after that) of line.
> 0 votes

# Answer
Essentially you're looking for a Collision algorithm.

What you described is the "simplest" method of doing this (keeping track of all actor's and checking the intersection of the Polygons during each meaningful game tick.) There are a number of methods in their Maths library that can handle this for convex polygons.

Another option is to use an actual Physics library like Box2d to handle collisions and provide the collision methods; this has the bonus of simplifying a lot of logic on the side of smaller/faster actor movements.
> 0 votes

---
Tags: libgdx, intersection, kotlin
---


# Question
Title: How should I store and load structures for 2d tile based game?
I am working on structure generation for my 2d tile based game. Structures can be anything from houses, castles, dungeons, mazes etc.

Structures are pre-defined, meaning I defined the width/height of the structure and wrote every single tile that should be placed for each coordinate.

Structure "template":

```
public class Structure
{
    private int width;
    private int height;

    private int[,] element;

    public Structure(int _w, int _h, int[,] _e)
    {
        width = _w;
        height = _h;
        element = _e;
    }
}

```

Creating a new structure:

```
// 0 = air

// 1 = wall

// 2 = door

Structure house = new Structure(4, 4,
{

{1, 1, 1, 1},

{1, 0, 0, 1},

{1, 0, 0, 1},

{1, 2, 1, 1}

});

```

This works fine for small amounts of structures. However, having tens/hundreds of structures in code is not only mess, but taking memory unnecessarily since structure generation gets called rarily. So how should I store that data?

1) Should I make a file for each structure and load from it?

2) Should I dump all structures in 1 file?

3) What file format should I use for this?

4) Does Unity provide some data containers that can be easily accessed and read from?

5) How is this usually done?

# Answer
> 0 votes
Maps don't belong into code. They belong into files which get loaded at runtime.

What you need is a WYSIWYG map editor which allows you to edit maps on the fly. If you build it right into your game, you can use the C# serialization system to turn the data in your `class Structure` to a file. Alternatively, you can use the method `AssetDatabase.CreateAsset` to turn an object in the running game into a persistent prefab asset which you can then use in your project. But keep in mind that the AssetDatabase class is in the UnityEditor namespace, so you can only use it while testing your game in the editor. It won't work if you build your game.

If you would like to edit your structure files with an external map editor like tiled or just use a text editor, then you need to invent your own file format. There isn't really a standard for this.

# Answer
> 0 votes
This would likely depend on how detailed you want your structures. Is it just going to be the tile positioning? Or are you going to want things like name, type and the like for what I presume to be your world generator to know about?

If just the tile positioning, then I would just dump to and from a csv file, and write your own import/export code (export because it is a hell of a lot easier to create in unity itself then dump to file, than define each structure manually, especially if the structure is 100 X 100 castle or cathedral). Each line is a row, and then store the data split by commas (or other separating character). String.Split method is what to use here.

Alternatively, there is JSON, which Unity has an implementation for serializing. There is one problem with this; Unity JSON does not support multidimensional arrays. Which means you'll need to figure out a different way of storing tile data, and write code to convert it to the array. A possible way to do this could be (note, untested):

```
[Serializable]
public class Structure
{
    public int Width;

    public int Height;

    public string Name;

    public List<Tile> Tiles;

    public int GetTile(int x, int y)
    {
        var tile = Tiles.FirstOrDefault(x => x.Location == new Vector2(x, y);
        if (tile != null)
            return tile.Type;

        return 0;
    }
}

[Serializable]
public class Tile
{
    public Vector2 Location;

    public int Type;
}

```

An advantage with the above implementation is you don't need to store air tiles in the files.

Anything with \[Serializable\] can in theory be serialized, and also displayed in the editor. In reality, anything that cannot be displayed in the editor cannot be displayed.

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


title: jMonkeyEngine ignores keyboard input

text:
# Question
Title: jMonkeyEngine ignores keyboard input
Created a game login form using the Nifty GUI. The interface reacts to the movement and clicking of the mouse, but ignores the input in the text fields. Whether the program is looking for a click handler, instead of typing, or I don’t know what. What could be the case and how to fix it?

**Interface/screen.xml:**

```
<?xml version="1.0" encoding="UTF-8"?>
<nifty xmlns="http://nifty-gui.lessvoid.com/nifty-gui" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://raw.githubusercontent.com/void256/nifty-gui/1.4/nifty-core/src/main/resources/nifty.xsd
https://raw.githubusercontent.com/void256/nifty-gui/1.4/nifty-core/src/main/resources/nifty.xsd">
    <useStyles filename="nifty-default-styles.xml"/>
    <useControls filename="nifty-default-controls.xml"/>
    <screen id="start" controller="mygame.LoginScreen">
        <layer id="background" childLayout="center">
            <image filename="Interface/start-background.jpg"></image>
        </layer>
        <layer id="foreground" childLayout="center">
            <panel id="panel" height="25%" width="75%" align="center" childLayout="horizontal">
                <panel id="panel_left" height="100%" width="25%" align="left" childLayout="vertical">
                    <text text="E-mail:" font="Interface/Fonts/Default.fnt"/>
                    <text text="Password:" font="Interface/Fonts/Default.fnt"/>
                </panel>
                <panel id="panel_center" height="100%" width="50%" align="center" childLayout="vertical">
                    <control name="textfield" maxLength="50" font="Interface/Fonts/Default.fnt"/>
                    <control name="textfield" maxLength="100" passwordChar="*" font="Interface/Fonts/Default.fnt"/>
                </panel>
                <panel id="panel_right" height="100%" width="25%" align="right" childLayout="vertical">

                </panel>
            </panel>
        </layer>
    </screen>
    <screen id="hud" controller="de.lessvoid.nifty.screen.DefaultScreenController">

    </screen>
</nifty>

```

**src/mygame/Main.java:**

```
package mygame;

import com.jme3.app.SimpleApplication;
import com.jme3.renderer.RenderManager;
import com.jme3.niftygui.NiftyJmeDisplay;
import de.lessvoid.nifty.Nifty;

public class Main extends SimpleApplication {

    public static void main(String[] args) {
        Main app = new Main();
        app.start();
    }
    public String driver = "org.apache.derby.jdbc.EmbeddedDriver";
    public Nifty nifty = null;
    @Override
    public void simpleInitApp() {
        NiftyJmeDisplay niftyDisplay = NiftyJmeDisplay.newNiftyJmeDisplay(assetManager, inputManager, audioRenderer, guiViewPort);
        nifty = niftyDisplay.getNifty();
        nifty.fromXml("Interface/screen.xml", "start");
        guiViewPort.addProcessor(niftyDisplay);
        inputManager.beginInput();
        flyCam.setDragToRotate(true);
    }

    @Override
    public void simpleUpdate(float tpf) {
        //TODO: add update code
        nifty.update();
        inputManager.update(tpf);
    }
}

```

**src/mygame/LoginScreen.java:**

```
package mygame;

import com.jme3.app.Application;
import com.jme3.app.state.BaseAppState;
import de.lessvoid.nifty.Nifty;
import de.lessvoid.nifty.screen.Screen;
import de.lessvoid.nifty.screen.ScreenController;

public class LoginScreen extends BaseAppState implements ScreenController {

    @Override
    protected void initialize(Application app) {

    }

    @Override
    protected void cleanup(Application app) {

    }

    @Override
    protected void onEnable() {

    }

    @Override
    protected void onDisable() {

    }
    @Override
    public void update(float tpf) {

    }

    @Override
    public void bind(Nifty nifty, Screen screen) {

    }

    @Override
    public void onStartScreen() {

    }

    @Override
    public void onEndScreen() {

    }
}

```

# Answer
> 0 votes
The error was in XML. Interactive interface elements without an id remain static. Need not so:

```
<control name="textfield" maxLength="50" font="Interface/Fonts/Default.fnt"/>
<control name="textfield" maxLength="100" passwordChar="*" font="Interface/Fonts/Default.fnt"/>

```

Well right:

```
<control id="mail" name="textfield" maxLength="50" font="Interface/Fonts/Default.fnt"/>
<control id="password" name="textfield" maxLength="100" passwordChar="*" font="Interface/Fonts/Default.fnt"/>

```

Then the fields are activated.

---
Tags: java, gui, jmonkeyengine, nifty-gui
---


# Question
Title: Convert Canvas Space point to local space of a rotated rect?
I got a quite tricky problem:

I have my mouse position and my rectangle position in canvas space(screen space but with adjusted scaling). Now I want my mouse position converted to local space of the rectangle. Problem is, the rectangle can be rotated. Without rotation its quite simple and works nicely.

Heres a graphic for better demonstration:

Edit3: Got it finally working. I messed up with a minus in the calculation instead of using a +. Also the hierarchy of the image in unity was incorrect. Lastly I had to change the rotation from CCW to CW(Thanks unity for using CCW in your UI...). This is my final solution:

Code Unity C#:

```
    var mapRect = MapContentTransform.rect;

    // Canvas Space Map Center
    var mapPositionCenter = CanvasRectTransform.InverseTransformPoint(MapContentTransform.position);
    mapPositionCenter.x += CanvasRectTransform.rect.width / 2.0f;
    mapPositionCenter.y += CanvasRectTransform.rect.height / 2.0f;
    // Mouse Position in Canvas Space
    Vector2 mousePositionCanvasSpace = CalculateScreenspacePositionCanvasSpace(new Vector2(Input.mousePosition.x, Input.mousePosition.y));

    // Rotation angle of the Map in Radians
    float theta = -(MapContentTransform.eulerAngles.z - 360.0f) * Mathf.Deg2Rad;

    var rotatedX = ((mousePositionCanvasSpace.x - mapPositionCenter.x) * Mathf.Cos(theta) -
                   (mousePositionCanvasSpace.y - mapPositionCenter.y) * Mathf.Sin(theta)) + mapRect.width / 2.0f;

    var rotatedY = ((mousePositionCanvasSpace.y - mapPositionCenter.y) * Mathf.Cos(theta) +
                   (mousePositionCanvasSpace.x - mapPositionCenter.x) * Mathf.Sin(theta)) + mapRect.height / 2.0f;

```

Thank you Kyy13!

# Answer
> 1 votes
```
// let <x ,y > be the position of the mouse in canvas space coordinates
// let <x',y'> be the position of the mouse in local space coordinates
// let <x0,y0> be the origin of local space in canvas space coordinates
// let sx be the ratio of canvas space to local space coordiantes in the x direction
// let sy be the ratio of canvas space to local space coordinates in the y direction
// let theta be the CW rotation of local space with respect to canvas space

x' = (x-x0)*sx*cos(theta) - (y-y0)*sy*sin(theta)
y' = (y-y0)*sy*cos(theta) + (x-x0)*sx*sin(theta)

// to specify the center of the local space bounding rectangle instead of the origin <x0,y0>,
// we need to express <x0,y0> in terms of <xc,yc>

// let <xc,yc> be the center of the local space bounding rectangle in canvas space coordinates
// let halfw be half the width of the local space bounding rectangle
// let halfh be half the height of the local space bounding rectangle

x0 = xc - halfw*cos(theta) - halfh*sin(theta)
y0 = yc - halfh*cos(theta) + halfw*sin(theta)

// if you want positive theta to represent CCW rotation,
// then we need to replace theta with -theta,
// and we can use the following properties to reduce the equations
// cos(-x) = cos(x)
// sin(-x) = -sin(x)
// the new equations are:

x0 = xc - halfw*cos(theta) + halfh*sin(theta)
y0 = yc - halfh*cos(theta) - halfw*sin(theta)

x' = (x-x0)*sx*cos(theta) + (y-y0)*sy*sin(theta)
y' = (y-y0)*sy*cos(theta) - (x-x0)*sx*sin(theta)

```

HTML5 example

```
<!DOCTYPE html>
<html>
<body>

<!-- main window -->
<canvas id = "canvas" width = "300" height = "300"></canvas>

<!-- local rectangle space -->
<canvas id = "rect" width = "100" height = "50"></canvas>

<script>
    // get object handles
    var canvas = document.getElementById("canvas");
    var canvas_rect = document.getElementById("rect");
    var ctx = canvas.getContext('2d');
    var ctx_rect = canvas_rect.getContext('2d');

    // set origin to lower left
    ctx.translate(0, canvas.height);
    ctx.scale(1, -1);
    ctx_rect.translate(0, canvas_rect.height);
    ctx_rect.scale(1, -1);

    // inner rect param
    var x0 = 120;
    var y0 = 120;
    var theta = Math.PI/5;
    var sx = 1;
    var sy = 1;

    /* functions */

    // update images
    function render(coord)
    {
        // fill canvas with color
        ctx.fillStyle = "#CCCCCC";
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx_rect.fillStyle = "#666666";
        ctx_rect.fillRect(0, 0, canvas_rect.width, canvas_rect.height);
        ctx.fillStyle = "#000000";
        ctx_rect.fillStyle = "#000000";

        // draw local rect on canvas
        ctx.beginPath();
        ctx.moveTo(x0,y0);
        ctx.lineTo(x0 + canvas_rect.width * Math.cos(theta), y0 - canvas_rect.width * Math.sin(theta));
        ctx.lineTo(x0 + canvas_rect.width * Math.cos(theta), y0 - canvas_rect.width * Math.sin(theta));
        ctx.lineTo(x0 + canvas_rect.width * Math.cos(theta) + canvas_rect.height * Math.sin(theta), y0 - canvas_rect.width * Math.sin(theta) + canvas_rect.height * Math.cos(theta));
        ctx.lineTo(x0 + canvas_rect.height * Math.sin(theta), y0 + canvas_rect.height * Math.cos(theta));
        ctx.lineTo(x0,y0);
        ctx.stroke();

        // draw coordinate on canvas
        drawCoord(coord, ctx);

        // coordinate in local rectangle space
        var c_rect = canvas2rect(coord[0], coord[1]);

        // draw coordinate in local space
        drawCoord(c_rect, ctx_rect);
    }

    // get coordinate when mouse is moved
    canvas.onmousemove = function(e)
    {
        var rect = e.target.getBoundingClientRect();
        render([e.clientX - rect.left, canvas.height - e.clientY + rect.top]);
    }

    // draw coordinate
    function drawCoord(coord, context)
    {
        context.fillRect(coord[0],coord[1],4,4);
    }

    // canvas coordinates to rect coordinates
    function canvas2rect(x, y)
    {
        var xPrime = (x - x0) * sx * Math.cos(theta) - (y - y0) * sy * Math.sin(theta);
        var yPrime = (y - y0) * sy * Math.cos(theta) + (x - x0) * sx * Math.sin(theta);
        return [xPrime, yPrime];
    }

</script>
</body>
</html>

```

---
Tags: unity, mathematics, coordinates
---


# Question
Title: Rotation of a matrix with unequal rows and columns
I have this simple matrix class which has a `char**` array for storing the data. The data array gets initialized like this:

```
data = new char*[cols];
  for (int x = 0; x < cols; x++)
    data[x] = new char[rows];

```

Is it possible to rotate this kind of matrix when its let's say 3x2? So that the rotation will result in this (or counter clockwise works as well)

```
a b
c d    ->    e c a
e f          f d b

```

Got some kind of atable here which shows where certain elements move when the matrix is rotated, but cannot get it working in code (those numbers around a&b are the x and y indexes):

```
  0                               0
0 a              0 1            0 b
1 b     ->     0 b a     ->     1 a
   (0,0)->(1,0)     (0,0)->(0,0)
   (1,0)->(0,0)     (1,0)->(0,1)

```

I'm currently rotating with these methods (they rotate clockwise):

```
void Matrix::reverseCols() {
  for (int x = 0; x < cols; x++)
    for (int y = 0, i = cols - 1; y < i; y++, i--)
      std::swap(data[y][x], data[i][x]);
}

void Matrix::transpose() {
  for (int y = 0; y < rows; y++)
    for (int x = y; x < cols; x++)
      std::swap(data[y][x], data[x][y]);
}

```

Should I keep it like this or should I go with a one-dimensional array and calculate the index when accessing the data by a method? And should I initialize the data array by columns (like I'm doing right now) or rows?

Wouldn't really bother doing this, but while learning C++ I want to build an console window engine and test it with a Tetris clone.

Thanks!

# Answer
Using a linear matrix rather than a multidimensional array,

(Click here to run this)

```
#include <iostream>
#include <cassert>

using namespace std;

template<typename T>
void printMatrix(T data, const int cols, const int rows)
{
    for(int j = 0; j < rows; ++j)
    {
        for(int i = 0; i < cols; ++i)
        {
            cout << data[j * cols + i] << '\t';
        }
        cout << '\n';
    }

}

/*
rotate src matrix 90 degrees clockwise and store in dest
Assumes dest has sufficient space.
*/
template<typename T>
void rotateMatrix(T dest, T src, int cols, int rows)
{
    /*
    rotate -
    y' = x
    x' = -y
    */

    // one loop, but costs a mod and a div
    for(int i = 0; i < rows * cols; ++i)
    {
        // source coordinates
        int x = i % cols;
        int y = i / cols;
        // destination coordinates
        int x1 = (rows - 1) - y;
        int y1 = x;

        dest[y1 * rows + x1] = src[y * cols + x];
    }

}

// or, if you'd prefer a nested loop to division:
template<typename T>
void rotateMatrixLoop(T dest, T src, int cols, int rows)
{
    for(int j=0; j < rows; ++j)
    {
        int dx = (rows - 1) - j;
        for(int i = 0; i < cols; ++i)
        {
            int dy = i;
            dest[dy * rows + dx] = src[j * cols + i];
            // for a 2d Array, you'd just
            // dest[dy][dx] = src[j][i];
        }

    }

}

// pointlessly optimized version
template<typename T>
void rotateMatrixSilly(T dest, T src, int cols, int rows)
{
    int srcOffset = 0;
    for(int j=0; j < rows; ++j)
    {
        int destOffset = rows - 1 - j;
        for(int i = 0; i < cols; ++i)
        {
            dest[destOffset =+ rows] = src[srcOffset++];
        }

    }

}

int main()
{
    int cols = 2;
    int rows = 3;
    char source[] {
        'a', 'b',
        'c', 'd',
        'e', 'f',

    };
    char dest[sizeof(source) / sizeof(source[0])];
    int destRows = cols;
    int destCols = rows;

    cout << "Original matrix:\n";
    printMatrix(source,cols,rows);

    cout << "Rotated matrix with division:\n";
    rotateMatrix(dest, source, cols, rows);
    printMatrix(dest, destCols, destRows);

    cout << "Rotated matrix with nested loop\n";
    rotateMatrixLoop(dest, source, cols, rows);
    printMatrix(dest, destCols, destRows);

    cout << "Slightly optimized rotation...\n";
    rotateMatrixSilly(dest, source, cols, rows);
    printMatrix(dest, destCols, destRows);

    return 0;
}

```

You could do this in place with a little more work, and changing it to use a multidimensional array as in your original sample is trivial. I templated the rotate and print functions which may not be necessary in your implementation; but hey, why not.
> 1 votes

# Answer
Depending on what your matrix should be able to do, you should simplify your matrices you calculate with. If you have a 2x3 Matrix, fill the missing row with zeros, then invert/transpose and then remove the column you added.

If you can't use 0 for that, use null for that and just move the values from one coordinate to another.

Edit: To fill up the elements in your Matrix, you can simply use null values. Convert your char\* array into a complete matrix (n x n), then traverse/invert/rotate, then create a new 2d char\* array with the null-values removed. E.G.:

```
a b c        a  b    c                    e    d   a    e d a     e d a
d       =>   d null null  (rotate R) =>   f   null b => f   b OR  f b
e f          e  f   null                 null null c        c     c

```

The Problem is, what happens if elements are not the next element in a row after the rotation (in my example the c and b. You either have a 2d array with Rows then Coloumns, or Coloumns then Rows.

This depens on what you want and there is no general answer (as this is in math not stictly defined)

If you have no rows with empty elements, n x m matrix, its simple, as you get a m x n matrix instead with no elements left out. If n \> m, add x Coloumns till n + Y = m, if m \> n add rows Y. Then rotate and remove either Y rows or coloumn (always the last ones).

```
a b                        a b 0               e c a     e c a
c d  (add coloumn of 0s)=> c d 0 (rotate R) => f d b =>  f d b
e f                        e f 0               0 0 0

```
> 0 votes

# Answer
After many hours of behind the computer, I've seem to get it working. The full code rotation code (keep in mind, that the `char**` data array gets initialized column by column):

```
void Matrix::rotate(int amt) {
  for (int i = 0; i < amt; i++) {
    int cols = this->cols, rows = this->rows;
    int size = (cols > rows) ? cols : rows;

    char** oldData = this->data;

    char** data = new char*[size];
    for (int x = 0; x < size; x++) {
      data[x] = new char[size];
      for (int y = 0; y < size; y++)
        data[x][y] = ' ';
    }

    this->cols = size;
    this->rows = size;

    for (int x = 0; x < cols; x++)
      for (int y = 0; y < rows; y++)
        data[x][y] = oldData[x][y];

    this->data = data;

    transpose();
    reverseCols();

    char** newData = new char*[rows];
    for (int x = 0; x < rows; x++) {
      newData[x] = new char[cols];
      for (int y = 0; y < cols; y++)
        newData[x][y] = ' ';
    }

    if (cols > rows) {
      //Remove enough columns from the left
      int diff = cols - rows;
      for (int x = 0; x < rows; x++)
        for (int y = 0; y < cols; y++)
          newData[x][y] = this->data[x + diff][y];
    } else {
      //Remove enough bottom rows
      for (int x = 0; x < rows; x++)
        for (int y = 0; y < cols; y++)
          newData[x][y] = this->data[x][y];
    }

    this->data = newData;
    this->cols = rows;
    this->rows = cols;
}

void Matrix::reverseCols() {
  for (int x = 0; x < cols; x++)
    for (int y = 0, i = cols - 1; y < i; y++, i--)
      std::swap(data[y][x], data[i][x]);
}

void Matrix::transpose() {
  for (int y = 0; y < rows; y++)
    for (int x = y; x < cols; x++)
      std::swap(data[y][x], data[x][y]);
}

```

I'm pretty sure that it's not the most optimal way to do this, but it works as it should.

Special thanks to @PSquall for pointing out to change the matrix to a N x N matrix!
> 0 votes

---
Tags: c++, matrix
---


title: 2D Grid based movement inherent issue

text:
# Question
Title: 2D Grid based movement inherent issue
I have a 2D grid based movement. To move, I stop key inputs until the character has reached a tile. Because of this, if you make a new directional input midway from one tile to another tile, nothing will happen as the unit has not reached the tile yet.

This seems like a fundamental challenge for grid based movement and I am wondering how people generally handle it, if they handle it at all.

One solution I had was to make the tile sizes smaller (From 32x32 to 16x16) so that the distance between each tile was smaller, but I don't really want to use 16x16.

Thanks

# Answer
> 1 votes
One way to solve this is to use an action queue.

You have a queue of actions, that you execute every time the unit is idle.

When the user presses button, you enqueue the action "Move Left" and then in your units update logic you dequeue the action and perform it.

This way the player can keep adding actions and the unit will keep executing them.

For basic player control logic, you would probably not allow a player to constantly add new actions, and rather only let him add an action if there are no other actions queued up currently.

This system works both for player control, but also for AI control. It's generally very flexible and can be expanded on greatly. If you understand how stacks work, they might offer some other interesting advantages. For instance, you could enqueue a pathfinder action that will pop itself off and replace itself with the necessary moves to reach it's destination.

# Answer
> 0 votes
To solve this you simply need to remember the last input that was given during the transition. Once you reach the end of the move, then you perform the action that is remembered. However if the user simply holds the button down as he moves it should requeue the action until the end of the movement, in case the user was not intending to more further than the next tile.

---
Tags: grid
---


# Question
Title: Public value null after assigning it from a different script
Hello I am a beginner in Unity and still currently exploring with scripts. So I ran into a problem.

In FetchAndAssign.cs Script

```
    void Start(){

         GameObject theEdge = GameObject.Find("Edge2");
         StallComponentAdder edge = theEdge.GetComponent<StallComponentAdder>();
         edge._id = _id;

    }

```

In StallComponentAdder.cs Script where it is attached to Edge2 GameObject

```
    public string _id;

    void Start () {
         string storeID = _id;
         print(storeID);
    }

```

When I try to print the storeID it won't print anything, why is that so?

# Answer
> 2 votes
The problem you’re running into is likely due to an incorrect script execution order. The `Start` method on all scripts with the same priority which are loaded at the same time are executed in an arbitrary order. Your `FetchAndAssign.Start` is probably running after`StallComponentAdder.Start`.

You can address this by either adjusting the script execution order to ensure that `StallComponentAdder` is run later, or you could change Start inside of `FetchAndAssign` to use `Awake` instead, which runs before `Start`.

# Answer
> 1 votes
Others have answered this already, but it's caused due to execution order - the start of your adder is called before the assign.

Personally, I'd recommend doing the opposite - instead of setting it through the parent (findandassign), find and get the data through the adder, and set it internally. this way, if the data isn't yet set, you know immediately, and don't assume it is set. Now I can't see your code, so there's likely a reason you do it this way.

If that's the case, I'd suggest using Awake() over Start(). if it helps, Awake is more of a "After Initializing," and Start is more of a "Before First Update." You cannot tell what order things will be initialized in, and similarly, you can't tell what order everything will set itself before the first update. however, you are guaranteed that everything declared statically in a scene will be initialized during Awake, and everything will have called Awake before any one of them run Start. this means that you can set data in findAndAssign's Awake(), and it will be guaranteed to be set before anything runs Start().

Quick disclaimer: any class declared during runtime will still follow these rules, (Initialize -\> Awake -\> Start (if enabled)) but when during the frame they do so is more complicated.

# Answer
> 0 votes
Start() of StallComponentAdder is called earlier than Start() of FetchAndAssign script. You could do something like this:

FetchAndAssign.cs

```
void Start(){
     GameObject theEdge = GameObject.Find("Edge2");
     StallComponentAdder edge = theEdge.GetComponent<StallComponentAdder>();
     edge._id = _id; //assign
     edge.StartAlt(); //call
}

```

StallComponentAdder.cs

```
public string _id;

public void StartAlt () {
     string storeID = _id;
     print(storeID);
}

```

So that you know that StartAlt() is 100% called after \_id is assigned :) hope this helps.

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


# Question
Title: Are constantly growing (in dimensional size) GameObjects a problem?
It's possible the following is fundamental to Unity, and not a problem?

I am using an example of a WheelJoint2D/Car from the Ray Wenderlich tutorials. Note from the pic below, the top level game object called "Car". It has children of "Body" which contains the wheel joints and the wheels (attached to the wheel joints). The top level "Car" GameObject is placed in the scene (here at X=6.4).

Now we run the game for a short time, and the car rolls forward as expected. From the inspector, we would see that X position of the Body and the wheels has changed, but note that the Car game object's X position has not changed:

So, in reality the game object "Car" has grown in the X-dimension. Granted this growth seemingly has nothing to do with physics simulation (as all the rigidbodies and joints are moving along as expected). One interesting side affect is that this growth might make scaling the parent object problematic.

But it seems that if this were an infinite runner, you would have an ever increasingly wide "Car" object. On the surface this seems undesirable, but is it really? And if so, how would you mitigate this (given that this game object hierarchy seems to be the prescribed way of using the wheel joints).

# Answer
While large colliders or large renderer bounds can be a problem (ie. big *stuff*), large position offsets (with big *nothing* in between) are generally not a problem until you start running into floating point precision loss.

Unity doesn't ever need to do anything in particular with the span of space between a container object's local `0,0,0` point and a child object's position (or the span between the positions of two child objects moving in opposite directions) so this offset itself doesn't introduce more processing load. They don't make the containing object's transform "bigger" because transforms don't have a size (only *stuff* like renderers or physics colliders do); transforms are just rotations/shifts/scales to apply to their contained objects.

To deal with floating point precision issues in an infinite runner to to ever-increasing *positions*, you'll want to either move the world toward the player character (who stays close to zero), or periodically re-center everything so you stay in the higher-precision range. This doesn't really relate to how big something is though, just how far it is from the world origin.
> 1 votes

---
Tags: unity, coordinates, gameobject
---


# Question
Title: How do I get from orthographic to perspective?
I programmed a cube in java and calculated the x y and z position for it's rotation on the x,y and z axis but I'm finding it hard to display the z axis i've been trying to change the distance of the vectors with higher z values to be closer to the middle of the Screen or the (0,0) point but am finding this rather hard any tips? Thank you.

here's the code:

```
public class vert {
 //screen position
 int x;
 int y;
 int z;
 //real rot position
 int xr;
 int yr;
 int zr;

 public void rotate(int xpos,int ypos,int zpos,int rotx,int roty,int rotz) {

    //x,y
    //calculate the new rotation
    double rx1 = Math.toDegrees(Math.atan2(ypos,xpos)) + rotx;
    //calculate the hypotenuse
    double hypx1 = Math.sqrt(xpos * xpos + ypos * ypos);
    //calculate x1
    double posx1 = Math.cos(Math.toRadians(rx1)) * hypx1;
    int tointx1 = (int) Math.round(posx1);
    int x1 = tointx1;
    //calculate y1
    double posy1 = Math.sin(Math.toRadians(rx1)) * hypx1;
    int tointy1 = (int) Math.rint(posy1);
    int y1 = tointy1;

    //x,z
    //calculate the new rotation
    double ry2 = Math.toDegrees(Math.atan2(zpos,x1)) + roty;
    //calculate the hypotenuse
    double hypy2 = Math.sqrt(x1 * x1 + zpos * zpos);
    //calculate x final
    double posx2 = Math.cos(Math.toRadians(ry2)) * hypy2;
    int tointx2 = (int) Math.round(posx2);
    int x2 = tointx2;
        //calculate z1
    double posz2 = Math.sin(Math.toRadians(ry2)) * hypy2;
    int tointz2 = (int) Math.rint(posz2);
    int z1 = tointz2;

    //y,z
    //calculate the new rotation
    double rz3 = Math.toDegrees(Math.atan2(z1,y1)) + rotz;
    //calculate the hypotenuse
    double hypz3 = Math.sqrt(y1 * y1 + z1 * z1);
    //calculate y final
    double posy3 = Math.cos(Math.toRadians(rz3)) * hypz3;
    int tointy3 = (int) Math.round(posy3);
    int y2 = tointy3;
    //calculate z final
    double posz3 = Math.sin(Math.toRadians(rz3)) * hypz3;
    int tointz3 = (int) Math.rint(posz3);
    int z2 = tointz3;

    xr = x2;
    yr = y2;
    zr = z2 + 128;
 }

 public void perspective() {

    double pers = Screen.camfocallenght / zr;
    x = (int) Math.rint(xr * pers) + Screen.x;
    y = (int) Math.rint(yr * pers) + Screen.y;
 }
}

```

And here's the code that draws the cube onto screen:

```
import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JComponent;
import javax.swing.JFrame;

public class Screen extends JComponent{

private static final long serialVersionUID = 1L;

static int height = 400;
static int width = 600;

static double camfocallenght = 100;

static int y = height / 2;
static int x = width / 2;

int movex = 0;
int movey = 0;
int movez = -100;

int a = 0;
int b = 0;
int c = 0;

vert[] v = new vert[12];

public void paint(Graphics g) {

    v[0] = new vert();
    v[0].rotate(movex + 45,movey + -45,movez + 45, a, b, c);
    v[1] = new vert();
    v[1].rotate(movex + 45,movey + 45,movez + 45, a, b, c);
    v[2] = new vert();
    v[2].rotate(movex + -45,movey + 45,movez + 45, a, b, c);
    v[3] = new vert();
    v[3].rotate(movex + -45,movey + -45,movez + 45, a, b, c);

    v[4] = new vert();
    v[4].rotate(movex + 45,movey + -45,movez + -45, a, b, c);
    v[5] = new vert();
    v[5].rotate(movex + 45,movey + 45,movez + -45, a, b, c);
    v[6] = new vert();
    v[6].rotate(movex + -45,movey + 45,movez + -45, a, b, c);
    v[7] = new vert();
    v[7].rotate(movex + -45,movey + -45,movez + -45, a, b, c);

    v[0].perspective();
    v[1].perspective();
    v[2].perspective();
    v[3].perspective();
    v[4].perspective();
    v[5].perspective();
    v[6].perspective();
    v[7].perspective();

    g.setColor(Color.green);

    g.drawLine( v[4].x, v[4].y, v[5].x, v[5].y);
    g.drawLine( v[6].x, v[6].y, v[7].x, v[7].y);
    g.drawLine( v[5].x, v[5].y, v[6].x, v[6].y);
    g.drawLine( v[7].x, v[7].y, v[4].x, v[4].y);

    g.setColor(Color.RED);

    g.drawLine(v[0].x, v[0].y, v[4].x, v[4].y);
    g.drawLine(v[1].x, v[1].y, v[5].x, v[5].y);
    g.drawLine(v[2].x, v[2].y, v[6].x, v[6].y);
    g.drawLine(v[3].x, v[3].y, v[7].x, v[7].y);

    g.setColor(Color.CYAN);

    g.drawLine( v[0].x, v[0].y, v[1].x, v[1].y);
    g.drawLine( v[2].x, v[2].y, v[3].x, v[3].y);
    g.drawLine( v[1].x, v[1].y, v[2].x, v[2].y);
    g.drawLine( v[3].x, v[3].y, v[0].x, v[0].y);

    String ShowZ = Integer.toString(v[1].xr);
    String Show4 = Integer.toString(v[4].x);
    String Showb = Integer.toString(b);

    g.drawString("x rotation:", 0, 10);
    g.drawString(Showb, 0, 22);
    g.drawString("z pos of vert 1:", 0, 30);
    g.drawString(ShowZ, 0, 42);
    g.drawString("x pos of vert 1 with perspective:", 0, 50);
    g.drawString(Show4, 0, 62);

    //a++;
    b++;
    //c++;

    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
 }

 public static void main(String[] args) {
    JFrame frame = new JFrame("Draw Line");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setSize(width, height);
    frame.setVisible(true);
    frame.getContentPane().add(new Screen());
    while (true) {
        frame.getContentPane().repaint();
    }
 }
}

```

# Answer
You just need to divide the x and y components by z. If you want to put the vanishing point "farther", then make the z component smaller (e.g. divide it by a constant). If you want to make the fov larger, then increase it by a constant.
> 1 votes

# Answer
You will get a lot more of readability if you use matrices for this, then to find the new position of the vector, you just multiply the vector by the matrix.

This question is a bit old, but if you meant how to find the on-screen position based on the world position, then you need to multiply the world position by the perspective matrix:

```
mat4 perspective = mat4_perspective_fov(fov, width, height, near, far);
onscreen_pos = vec4_multiply_mat4(world_pos, perspective);

```

If you meant how to make a transition from orthographic to perspective (and vice-versa), you can linear interpolate two projection matrices:

```
mat4 perspective = mat4_perspective_fov(fov, width, height, near, far);
mat4 orthographic = mat4_ortho(left, right, bottom, top, near, far);
mat4 interpolated = mat4_lerp(perspective, ortho, 0.5);
onscreen_pos = vec4_multiply_mat4(world_pos, interpolated);

```

Then you will have a middle ground (`0.5`) between an orthographic and perspective projection.
> 1 votes

---
Tags: java, 3d, rendering, perspective
---


title: Unity: Player Gets Stuck Between Tiles

text:
# Question
Title: Unity: Player Gets Stuck Between Tiles
I am creating an endless game, which constantly spawns tiles. The problem is that after a few tiles the player gets stuck on random tile and stops moving. I noticed this problem even when i was designing a level, where when I align two tiles side by side, the player gets stuck on the junction of these two tiles. I am including a video link to my problem. Please help me and please try to be in detail because i very very new to Unity.

Video for the problem im facing. https://photos.app.goo.gl/JrCPWkGclUA2UiMy1

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

public class TileManager : MonoBehaviour {

public GameObject[] tiles;
private Transform player;
private float SpawnLocationZ = -30.0f;
private float tileLength = 36;
private float amountOfTilesOnScreen = 5;
private float SafeZone = 45;
private List<GameObject> activeTiles;
private int lastPrefabIndex = 0;
private bool StartCompleted = false;
// Use this for initialization
void Start () {
    activeTiles = new List<GameObject>();
    player = GameObject.FindGameObjectWithTag("Player").transform;
    for(int i =0; i<amountOfTilesOnScreen; i++){
        Debug.Log("Start Method");
        SpawnTile(-1);
    }

}

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

    if((player.transform.position.z -SafeZone > (SpawnLocationZ - amountOfTilesOnScreen * tileLength))){
        Debug.Log("started");
        SpawnTile(0);
        DeleteTile();
    }
}

void SpawnTile( int prefabIndex){
    if(prefabIndex == -1){
        GameObject gor;
        gor = Instantiate(tiles[0]) as GameObject;
        gor.transform.SetParent(transform);
        gor.transform.position = Vector3.forward * SpawnLocationZ;
        SpawnLocationZ += tileLength;
        activeTiles.Add(gor);
    }else{
    GameObject go;
    go = Instantiate(tiles[Randome()]) as GameObject;
    go.transform.SetParent(transform);
    go.transform.position = Vector3.forward * SpawnLocationZ;
    SpawnLocationZ += tileLength;
    activeTiles.Add(go);
    }
}

void DeleteTile(){
    Destroy(activeTiles[0]);
    activeTiles.RemoveAt(0);
}

private int Randome(){
    if(tiles.Length <=1){
        return 0;
    }
    int randomIndex = lastPrefabIndex;
    while(randomIndex == lastPrefabIndex){
        randomIndex = Random.Range(0, tiles.Length);
    }
    lastPrefabIndex = randomIndex;
    return randomIndex;
}
 }

```

# Answer
> 2 votes
In many situations, depending on how collision works in your game, you can use the Sphere Colliders or Capsule Colliders instead of the box Colliders. This will let the character slider over Box Colliders without catching.

---
Tags: unity, physics, tiles, tilemap, spawning
---


title: Sync a file across multiple devices

text:
# Question
Title: Sync a file across multiple devices
How can a file be synced across multiple devices? I am able to store the data locally using binary serialization, but the user should have the ability to access it on any device at any time.

Is this done automatically by the operating system? If the user logs into an Android phone using a Google account, would local data created by the application appear on every device that Google account is logged into or would I need to implement this functionality myself?

I have considered using a remote database, but I am not so sure that is the best option. My target platforms are Windows Universal, Android, and iOS.

The closest topic I found when I researched this is "Remote Settings" and "binary serialization", but neither help in my case.

# Answer
Have you considered saving/loading data into/from XML (or Json) ? It can easily be read from a remote source as TextAsset and parsed.

This Unify snippet is a good starting point to save/load your data as an XML text file (either from/into the Resources/ folder, from the persistent DataPath or from a remote source using www.text): Saving and Loading Data: XmlSerializer

Then for your remote server, i guess the Firebase Storage free plan should be more than enough, they provide a great Unity documentation for Cloud Storage.
> 1 votes

---
Tags: unity, synchronization
---


# Question
Title: Difference between Unity's Renderer.sharedMaterial and Renderer.sharedMaterials
What are the difference between **Renderer.sharedMaterial** and **Renderer.sharedMaterials** in Unity?

# Answer
**Renderer.sharedMaterial** returns first material used by a Renderer or null if Renderer has no materials. If there\`re multiple materials, first one in that array will be returned.

**Renderer.sharedMaterials** returns all (1, 2, ...) materials used by a Renderer as array or null if Renderer has no materials.
> 2 votes

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


# Question
Title: How can I add a [MenuItem] to the context menu shown when right-clicking a specific asset type in the Unity Editor?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Linq;
using System.IO;
using System.Text.RegularExpressions;

public class Test : Editor
{
    [MenuItem("Assets/Testing")]
    private static void Init()
    {

    }
}

```

When I right click on the Assets I will see the "Testing" item defined above in the context menu.

But I want to see this "Testing" option only if I right click on a script file (.cs or .js)

For example if I have a script file at Assets \> Test \> Test.cs, only when I right mouse click on Test.cs should the context menu show the new Testing option.

How can I do this?

# Answer
Short answer - you can\`t "hide context menu options".

But you can disable certain menuitems with "Validation" methods. This system adds new validation method to already existing context menu, this method must return bool, true == enabled, false == disabled. Also in `MenuItem` attribute you must pass `true` as second parameter to mark that method as validator, MenuItem path must be the same as original method.

For your example with scripts you must compare current selection object with `MonoScript` type which represents C# scripts in Unity.

```
[MenuItem("Assets/Do Something")]
private static void DoSomething() {
    Debug.Log("You did something!");
}

[MenuItem("Assets/Do Something", true)]
private static bool DoSomethingValidation() {
    return Selection.activeObject.GetType() == typeof(MonoScript);
}

```
> 2 votes

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


title: Tiledata management

text:
# Question
Title: Tiledata management
I've been trying to create a grid-based open world game. In order to do that I've decided to create a personal map editor. The problem I've encountered is handling data because of the actual data size. For example if I were to have a 2.000x2.000 world, I'd have a total of 4.000.000 grid cells (tiles).

Now then, if we assume that each cell *can* hold the following:

1. ground image,
2. an add-on on top of that image (something like a flower, or any type of decoration),
3. a wall or anything like that, a box, a tree, etc
4. an add-on on top of a wall (a torch, spiderweb, etc)

And if we assume that each of those takes up to 8 bits (basically that id takes a stored ID from 0 - 255) it would take a total of 2.000\*2.000\*32 bits of data, which is equivalent to 125 megabytes to store a map of that size. Now then, the size itself isn't a problem if I were to have only 1 floor (you can look at floors as z-axis). But what if I wanted to have several floors? The size would be equivalent to 125\*floor megabytes which gets ridiculous over time.

My question would be, what do you think would be the best way to store this type of data, or tiledata in general when working with maps which have enormous size?

# Answer
> 2.000\*2.000\*32 bits of data, which is equivalent to 125 megabytes

First, let's use the correct units. You want to talk about **mebibytes**, not megabytes, as mebibytes is to a power of 2 value, proper to use with octal systems (which is what we use).

Second, 2000×2000×4 results in 15.26 MiB. Small value.

Now, the real problem:

> But what if I wanted to have several floors?

Let's say you have 128 floors. The result of 2000×2000×4×128 will be 1.91 GiB. Quite big, uh?

This might be a problem depending on how your game plays. What some games do is only load a part of the map from disk. This is what Minecraft does, for example. When the player moves, part of the map is unloaded and other part of the map is loaded. This is the best approach if your game doesn't require to simulate the NPCs outside of the player radius.

But, what if the NPCs must be simulated even if outside of the player radius? Well, then the option is really to have the whole map loaded. If you are offering such vast open world to your players, I don't think they will complain about requiring some minimum GiB of RAM to run your game.
> 2 votes

---
Tags: architecture, game-maker, data-structure
---


title: Best way to mask 2D sprites in XNA?

text:
# Question
Title: Best way to mask 2D sprites in XNA?
I currently am trying to mask some sprites. Rather than explaining it in words, I've made up some example pictures:

The area to mask (in white)

Now, the red sprite that needs to be cropped.

The final result.

Now, I'm aware that in XNA you can do two things to accomplish this:

1. Use the Stencil Buffer.
2. Use a Pixel Shader.

I have tried to do a pixel shader, which essentially did this:

```
float4 main(float2 texCoord : TEXCOORD0) : COLOR0
{
    float4 tex = tex2D(BaseTexture, texCoord);
    float4 bitMask = tex2D(MaskTexture, texCoord);

    if (bitMask.a > 0)
    {
        return float4(tex.r, tex.g, tex.b, tex.a);
    }
    else
    {
        return float4(0, 0, 0, 0);
    }
}

```

This seems to crop the images (albeit, not correct once the image starts to move), but my problem is that the images are constantly moving (they aren't static), so this cropping needs to be dynamic.

Is there a way I could alter the shader code to take into account it's position?

---

Alternatively, I've read about using the Stencil Buffer, but most of the samples seem to hinge on using a rendertarget, which I really don't want to do. (I'm already using 3 or 4 for the rest of the game, and adding another one on top of it seems overkill)

The only tutorial I've found that *doesn't* use Rendertargets is one from Shawn Hargreaves' blog over here. The issue with that one, though is that it's for XNA 3.1, and doesn't seem to translate well to XNA 4.0.

It seems to me that the pixel shader is the way to go, but I'm unsure of how to get the positioning correct. I believe I would have to change my onscreen coordinates (something like 500, 500) to be between 0 and 1 for the shader coordinates. My only problem is trying to work out how to correctly use the transformed coordinates.

Thanks in advance for any help!

# Answer
> 14 votes
You can use your pixel shader approach but it is incomplete.

You will also need to add some parameters to it that inform the pixel shader where you want your stencil to be located.

```
sampler BaseTexture : register(s0);
sampler MaskTexture : register(s1) {
    addressU = Clamp;
    addressV = Clamp;
};

//All of these variables are pixel values
//Feel free to replace with float2 variables
float MaskLocationX;
float MaskLocationY;
float MaskWidth;
float MaskHeight;
float BaseTextureLocationX;  //This is where your texture is to be drawn
float BaseTextureLocationY;  //texCoord is different, it is the current pixel
float BaseTextureWidth;
float BaseTextureHeight;

float4 main(float2 texCoord : TEXCOORD0) : COLOR0
{
    //We need to calculate where in terms of percentage to sample from the MaskTexture
    float maskPixelX = texCoord.x * BaseTextureWidth + BaseTextureLocationX;
    float maskPixelY = texCoord.y * BaseTextureHeight + BaseTextureLocationY;
    float2 maskCoord = float2((maskPixelX - MaskLocationX) / MaskWidth, (maskPixelY - MaskLocationY) / MaskHeight);
    float4 bitMask = tex2D(MaskTexture, maskCoord);

    float4 tex = tex2D(BaseTexture, texCoord);

    //It is a good idea to avoid conditional statements in a pixel shader if you can use math instead.
    return tex * (bitMask.a);
    //Alternate calculation to invert the mask, you could make this a parameter too if you wanted
    //return tex * (1.0 - bitMask.a);
}

```

In your C# code you pass in variables to the pixel shader prior to the `SpriteBatch.Draw` call like this:

```
maskEffect.Parameters["MaskWidth"].SetValue(800);
maskEffect.Parameters["MaskHeight"].SetValue(600);

```

# Answer
> 19 votes
The first step is to tell the graphics card we need the stencil buffer. To do this when you create GraphicsDeviceManager we set the PreferredDepthStencilFormat to DepthFormat.Depth24Stencil8 so there is actually a stencil to write to.

```
graphics = new GraphicsDeviceManager(this) {
    PreferredDepthStencilFormat = DepthFormat.Depth24Stencil8
};

```

The AlphaTestEffect is used to set the coordinate system and filter the pixels with alpha that pass the alpha test. We are not going to set any filters and set the coordinate system to the view port.

```
var m = Matrix.CreateOrthographicOffCenter(0,
    graphics.GraphicsDevice.PresentationParameters.BackBufferWidth,
    graphics.GraphicsDevice.PresentationParameters.BackBufferHeight,
    0, 0, 1
);
var a = new AlphaTestEffect(graphics.GraphicsDevice) {
    Projection = m
};

```

Next we need to set up two DepthStencilStates. These states dictate when the SpriteBatch renders to the stencil and when the SpriteBatch renders to the BackBuffer. We are primarily interested in two variables StencilFunction and StencilPass.

* StencilFunction dictates when the SpriteBatch will draw individual pixels and when they will be ignored.
* StencilPass dictates when drawn pixels pixels effect the Stencil.

For the first DepthStencilState we set StencilFunction to CompareFunction. This causes the StencilTest to succeed and when the StencilTest the SpriteBatch renders that pixel. StencilPass is set to StencilOperation. Replace meaning that when the StencilTest succeed that pixel will written to the StencilBuffer with the value of the ReferenceStencil.

```
var s1 = new DepthStencilState {
    StencilEnable = true,
    StencilFunction = CompareFunction.Always,
    StencilPass = StencilOperation.Replace,
    ReferenceStencil = 1,
    DepthBufferEnable = false,
};

```

In summary the StencilTest always passes, the image is drawn to screen normally, and for pixels drawn to the screen a value of 1 is stored in the StencilBuffer.

The second DepthStencilState is slightly more complicated. This time we want to only draw to the screen when the value in the StencilBuffer is. To achieve this we set the StencilFunction to CompareFunction.LessEqual and the ReferenceStencil to 1. This means that when the value in the stencil buffer is 1 the StencilTest will succeed. Setting StencilPass to StencilOperation. Keep causes the StencilBuffer not to update. This allows us to draw multiple times using the same mask.

```
var s2 = new DepthStencilState {
    StencilEnable = true,
    StencilFunction = CompareFunction.LessEqual,
    StencilPass = StencilOperation.Keep,
    ReferenceStencil = 1,
    DepthBufferEnable = false,
};

```

In summary the StencilTest only passes when the StencilBuffer is less than 1 (the alpha pixels from the mask) and does not effect the StencilBuffer.

Now that we have our DepthStencilStates set up. We can actually draw using a mask. Simply draw the mask using the first DepthStencilState. This will effect both the BackBuffer and the StencilBuffer. Now that the stencil buffer has a value of 0 where you mask had transparency and 1 where it contained color we can use StencilBuffer to mask later images.

```
spriteBatch.Begin(SpriteSortMode.Immediate, null, null, s1, null, a);
spriteBatch.Draw(huh, Vector2.Zero, Color.White); //The mask
spriteBatch.End();

```

The second SpriteBatch uses the second DepthStencilStates. No matter what you draw, only the pixels where the StencilBuffer is set to 1 will pass the stencil test and be drawn to the screen.

```
spriteBatch.Begin(SpriteSortMode.Immediate, null, null, s2, null, a);
spriteBatch.Draw(color, Vector2.Zero, Color.White); //The background
spriteBatch.End();

```

Below is the entirety of the code in the Draw method, don't forget to set PreferredDepthStencilFormat = DepthFormat.Depth24Stencil8 in the game constructor.

```
GraphicsDevice.Clear(ClearOptions.Target
    | ClearOptions.Stencil, Color.Transparent, 0, 0);

var m = Matrix.CreateOrthographicOffCenter(0,
    graphics.GraphicsDevice.PresentationParameters.BackBufferWidth,
    graphics.GraphicsDevice.PresentationParameters.BackBufferHeight,
    0, 0, 1
);

var a = new AlphaTestEffect(graphics.GraphicsDevice) {
    Projection = m
};

var s1 = new DepthStencilState {
    StencilEnable = true,
    StencilFunction = CompareFunction.Always,
    StencilPass = StencilOperation.Replace,
    ReferenceStencil = 1,
    DepthBufferEnable = false,
};

var s2 = new DepthStencilState {
    StencilEnable = true,
    StencilFunction = CompareFunction.LessEqual,
    StencilPass = StencilOperation.Keep,
    ReferenceStencil = 1,
    DepthBufferEnable = false,
};

spriteBatch.Begin(SpriteSortMode.Immediate, null, null, s1, null, a);
spriteBatch.Draw(huh, Vector2.Zero, Color.White); //The mask
spriteBatch.End();

spriteBatch.Begin(SpriteSortMode.Immediate, null, null, s2, null, a);
spriteBatch.Draw(color, Vector2.Zero, Color.White); //The background
spriteBatch.End();

```

# Answer
> 0 votes
In the answer above, some weird things happened when I did exactly as is explained.

The only thing I needed was the both `DepthStencilStates`.

```
var s1 = new DepthStencilState {
    StencilEnable = true,
    StencilFunction = CompareFunction.Always,
    StencilPass = StencilOperation.Replace,
    ReferenceStencil = 1,
    DepthBufferEnable = false,
};

var s2 = new DepthStencilState {
    StencilEnable = true,
    StencilFunction = CompareFunction.LessEqual,
    StencilPass = StencilOperation.Keep,
    ReferenceStencil = 1,
    DepthBufferEnable = false,
};

```

And the draws without the `AlphaTestEffect`.

```
spriteBatch.Begin(SpriteSortMode.Immediate, null, null, s1, null, null);
spriteBatch.Draw(huh, Vector2.Zero, Color.White); //The mask
spriteBatch.End();

spriteBatch.Begin(SpriteSortMode.Immediate, null, null, s2, null, null);
spriteBatch.Draw(color, Vector2.Zero, Color.White); //The background
spriteBatch.End();

```

And everything was fine like expected.

---
Tags: xna, 2d, hlsl, masking
---


title: How do I make a JS game downloadable?

text:
# Question
Title: How do I make a JS game downloadable?
I can put the HTML and JavaScript together in the same `.html` file, but the images need to be separate files. The only solution that comes to my mind is to give to the user a `.zip` folder.

This is not pretty though... How else can I do this?

# Answer
> 21 votes
You can embed images in the HTML document using the dataurl-syntax which allows to put the base64 representation of the binary image data as the src-attribute of an image. This also works on any other kind of media file.

```
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAIAAAACUFjqAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAALEgAACxIB0t1+/AAAAAd0SU1FB9EFBAoYMhVvMQIAAAAtSURBVHicY/z//z8DHoBH+v///yy4FDEyMjIwMDDhM3lgpaEuh7gTEzDiDxYA9HEPDF90e5YAAAAASUVORK5CYII=">

```

When you use CSS stylesheets, you can create these completely procedural in JavaScript.

# Answer
> 30 votes
Just putting all the files into a .zip file isn't a viable solution because most web-applications need a web-server so that they can access resources via HTTP-requests. On some systems you can access files via the `file://` URI-scheme, but that's not guaranteed to work everywhere because of security-reasons and will fail for things such as AJAX requests.

It might work for a very simple app where you have most resources inline but this really isn't the approach I'd recommend to anybody. There are alternatives though, such as:

### Build a native application

You can package your web-application as a native app using Node-Webkit. You can even use this to add native desktop features (such as local save-games) to your game.

This isn't a "*package and done*" approach though.. you'll probably have to rewrite portions of your application and write different loaders (eg. with a desktop app you'll rather load the files via filesystem, whereas you use HTTP-Requests in a browser/online-game).

### Use HTML5 features to allow offline access of your app

If your primary goal is to allow the player to play your game offline, then you can also use application-cache to allow offline access of your app. This is a feature that works in most modern browsers. The added benefit is that the user doesn't have to download anything and can just use a bookmark to play your game even when offline.

For resources that are being loaded asynchronously (AJAX) you'll also have to implement separate loading mechanisms. You could make use of local-storage to save these resources for offline use.

# Answer
> 7 votes
For a Chrome-based solution to make the game run offline and enjoy some native functionality, you can consider making a Chrome App.

This way, you can distribute it in Chrome Web Store for added visibility, you can enjoy some powerful APIs, and make it look more like a standalone app.

The downside is, of course, requiring Chrome.

# Answer
> 0 votes
Well it depends on how much work you really want to put into it. Using the current set of Web APIs you can:

* Create a **Progressive Web App** (PWA) (Sadly PWAs are only for mobile phones and Chrome OS, but I've heard that Chrome for Desktop will soon have support for it soon. For now, it hides behind a flag) since the old Application Cache is now deprecated
* **Convert** everything into **text** (images and audio). And either encourage the user to save the web page as is (using `Cmd+S` or `Ctrl+S` in browser) or cache the page as a PWA. Just know that, on mobile, dataURIs don't perform very well.
* You can create a Chrome App, but that won't work on any Chrome version that isn't running on Chrome OS. This means it's better for you to create an extension instead
* Most games come under 10 MB, with that said you can cache all your game's data into the local storage. How you do this is up to you: you can do the above (convert everything to text), use Blob api, etc. Though I highly discourage this, as some mobile phones could clear your whole game from memory. Which means you have to check that everything is ok (if your code is still in memory), which means longer load times and also could crash the user phone. If you do choose to go down this path though, you'll definitely benefit from using LocalForage
* Using Electron or NW.js, you can use your html, css, and js to create a desktop app. Similar methods can be used to create mobile apps as well (using something like Cordova or a Cordova dependant like PhoneGap). You'd do this and allow the user to download the full game if they wanted to.
* If you still want to continue with a `zip` file, checkout JSZip. I have no idea how you can use it, but I'm sure someone can come up with a good idea (maybe zip your file and then convert the binary data to string and place it inline into the html).
* This weird hack allows you to load any textual data as something known as a data block. This is just another tool you can use to embed assets into an html file.

---
Tags: javascript, html5, distribution
---