# Question
Title: Adding multiple materials to a single mesh in three.js
I've been doing some reading and can't seem to figure out a good way to do this..

I have a simple globe with a material on it like so:

```
const earthGeomerty = new THREE.SphereGeometry( 4, 48, 48 );
const earthDiffuse = loader.load('assets/drought_earth_texture.png');
const earthSpec = loader.load('assets/drought_earth_texture_bump.png');

const material = new THREE.MeshPhongMaterial( {
    specular: 0xffffff,
    map: earthDiffuse,
    specularMap: earthSpec,
    normalScale: new THREE.Vector2( 1, 1 ),
    shininess: 5,
    transparent: true,
    depthTest: true,
    depthWrite: false,
    polygonOffset: true,
    polygonOffsetFactor: - 4,
    wireframe: false
} );

```

and I apply this material to my `earthGeometry` like so:

```
const sphere = new THREE.Mesh( earthGeomerty, material );

```

but now I want to add an atmospheric glow, which I found a nice extension for and created like so:

```
const atmosphereMaterial = THREEx.createAtmosphereMaterial();

```

but after doing a ton of reading I'm unsure of how to use *both* `material` and `atmosphereMaterial` to my single `sphere` mesh.

Any help? Thanks!

# Answer
> 3 votes
You can have multiple materials in one mesh in Three.js. Supply an array of materials to the Mesh constructor instead of a single material. You then also have to specify vertex groups in the geometry. If you want, you can specify the groups to contain the same vertices, only different material index.

It is also possible to define multiple meshes using the same geometry, but unique materials. You can organize the meshes as children of a `THREE.Group`.

# Answer
> 2 votes
First there's a problem with your code, you should use callbacks when using a TextureLoader, and with multiple textures you should use Promises, with your code you are not waiting for textures to load and your material will not work.

*But after doing a ton of reading I'm unsure of how to use both material and atmosphereMaterial to my single sphere mesh.*

In short you can't add two materials to the same mesh using Three.js, materials are coupled vertex fragment shaders and geometries are arrays of vector positions.

You can use a custom material using ShaderMaterial so you can create a custom shader that combine the two effects, then you can apply the material to a mesh.

Or you can simply use two meshes and bind them to a parent Object3D.

Something like this:

```
var earthObj = new THREE.Object3D();

var sphereMesh = new THREE.Mesh(geometry, material);

earthObj.add(sphereMesh);

var atmosphereMaterial = THREEx.createAtmosphereMaterial();

earthObj.add(atmosphereMaterial);

```

It is important to know that child meshes will get the origin from their parents. Every translation, rotation is intended related to the parent mesh position, which make a lot of sense for building complex objects with multiple meshes.

I made an example a while ago about using multiple textures and multiple meshes.

---
Tags: webgl, three.js
---


title: How to support Surface pens in Unity?

text:
# Question
Title: How to support Surface pens in Unity?
Our game works great with touch or mouse, but the Surface pen doesn't seem to register as a pointing device at all. How can we support the pen in Unity in a native build?

This question on the Unity Answers site suggests we could build it as a UWP app, but that means restricting ourselves to a very limited subset of the .NET framework (specifically, we lose a lot of the Serialization libraries).

# Answer
On my SP3 the pen works with https://docs.unity3d.com/ScriptReference/Input-mousePosition.html and returns a Vector3 with x, y and 0z co-ordinates. I'm using Unity 5.6 on Linux but if the pen doesn't show up as touch input in Windows I would assume it has the same behavior.
> 2 votes

---
Tags: unity, input
---


# Question
Title: How can I make my game wait a number of seconds before the player respawns?
I want to add some particle effects for when I die so the player appears to explode upon death, but I am not totally sure how I can stop the player from respawning long enough for this effect to carry out. I currently have some code that just reloads the scene when you die, but I was fiddling with the idea of some way to make the script wait a number of second before executing the respawn method. I saw something in another post on the unity forums about a coroutine, but I am not sure how to make that work as I am pretty new to coding. Any help is greatly appreciated.

# Answer
> 0 votes
If you put your "respawn" logic into some method, you can then call it delayed like this: `Invoke("respawnMethodName", 5);`, in this case a method named `respawnMethodName` will be called after 5 seconds.

You can find documentation on `Invoke` here.

# Answer
> 0 votes
I don't know how you implemented the respawn mechanic, but if you make it a separate function, you can just call an Invoke with a set amount of seconds so that the method will be called at a later time.

Example usage:

```
public class ExampleClass : MonoBehaviour {
    void OnDestroy() {
        Invoke("RespawnPlayer", 10); //this will call the method after 10 seconds
    }

    void RespawnPlayer()
    {
        //input what you normally do when you respawn a player.
    }
}

```

If you don't destroy your player object, then you can just call the method right after the "player death" situation. It's essentially the same thing.

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


# Question
Title: Blur Shader: Can I use one Framebuffer for the horizontal and vertical pass?
I have set up my blur shader with the following header:

```
#version 400
in vec2 texCoord;

uniform sampler2D u_texture;
uniform vec2 resolution;
uniform float radius;
uniform vec2 dir;

layout (location = 0) out vec4 out_color;
void main() { *some code*; out_color = vec4(*some code*); }

```

The vertical pass is working well but I would like to use the same Framebuffer for both passes.

My idea was to create Color **Attachment1** and Color **Attachment2**. In the first pass, **Attachment1** is the target (out\_color) attachment. Now I want the second pass to bind **Attachment1** to the sampler2D (u\_texture) and write the resulting pixels (out\_color) into **Attachment2**.

If there is any possibility to read from one **Attachment** and write to another, please let me know.

Thanks in advance!

# Answer
Well, I tried a bit with glDrawBuffers and found a working solution.

Before the second pass starts, I simply switched the shader output:

```
layout (location = 0) out vec4 out_color;

```

to the second attachment (**Attachment2**) simply by writing:

```
GL.DrawBuffer(DrawBufferMode.ColorAttachment2);

```

This line of code will change the target of the 1st shader output (layout location = 0) so that it writes to **Attachment2**. Also, I restore the DrawBuffer after the second pass, so the first pass won't have any problems.
> 2 votes

---
Tags: opengl, shaders, glsl, blur
---


title: Obstacle avoidance in Bezier Curves

text:
# Question
Title: Obstacle avoidance in Bezier Curves
I use an A\* algorithm to find a path voiding obstacles. On obtaining the path it would be a good idea to reduce the number of points. Then I would like to typically do a spline interpolation or Bezier Curves to find a smooth path but is it not possible that post smoothening my character bumps into an obstacle? If not possible then why and if it is possible, then how do I avoid it?

# Answer
Do as we all do: play with splines running between adjacent path cells, and see how it works. This is really totally down to personal interpretation. Then adapt your parameters from there. The primary issue is moving around corners. If the curve is too gradual, such that the entity bumps into inner corners during its arc, then strengthen the control point (move it outward) on the outer edge of the arc; this will sharpen the corner to some degree. OTOH, If the curve is too sharp, you're not much better off than where you are at the moment, and you probably need to move the control point back inward.

You can slightly bevel the corners of walls in your game, if all you are worried about is how this *looks*.

TL;DR Experiment and Adapt. That's a large part of the fun of game development.
> 1 votes

---
Tags: path-finding, beziers
---


# Question
Title: How to apply dual joystick on player movement that contain multiple sprite movement scripts?
I got my player movement script, joystick movement script, and keyboard movement script. The question is I have no idea how to change the keyboard movement script to the virtual joystick script. The main solution I face is my player character has 4 views which is left, right, front, back and 3 states which is idle, dead, and walking. I want my joystick movement input same as the keyboard movement as below. I got some error in my code which is

> "Find is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. "

Can someone teach me why I am getting this error?

```
using UnityEngine;
using System.Collections;

public class TaoistMovement : MonoBehaviour
{
    enum DirectionEnum
    {
        forward,
        back,
        left,
        right,
        // leftidle,
        // rightidle,
        // backidle,
        frontidle
    }

    float MoveSpeed = 4.5f ;

    public string charactersname = "taoistmoveobject";
    public string charactername = "taoist";

    // change the string to your parameter

    string charactersfrontwalk = "FrontWalk";
    string charactersbackwalk = "BackWalk";
    string charactersleftwalk = "LeftWalk";
    string charactersrightwalk = "RightWalk";
    string charactersfrontidle = "FrontIdle";
    string charactersbackidle = "BackIdle";
    string charactersrightidle = "RightIdle";
    string charactersleftidle = "LeftIdle";

    GameObject characters = GameObject.Find("taoistmoveobject");
    GameObject anim = GameObject.Find("taoist");

    Animator theAnimator;
    DirectionEnum currentDirection1;
    // DirectionEnum currentDirection2;
    // DirectionEnum currentDirection3;
    // DirectionEnum currentDirection4;

    void Awake()
    {
        theAnimator = anim.GetComponent<Animator>();
        currentDirection1 = DirectionEnum.frontidle;
        // currentDirection2 = DirectionEnum.rightidle;
        // currentDirection3 = DirectionEnum.backidle;
        // currentDirection4 = DirectionEnum.frontidle;
    }

    void Update()
    {
        characters.transform.localPosition = new Vector3(characters.transform.localPosition.x + 0.05f * MoveSpeed, characters.transform.localPosition.y, characters.transform.localPosition.z);
    }

    public void updateDirection(float h, float v)
    {
        if (h != 0)
        {
            if (h > 0)
            {
                changeDirection(DirectionEnum.left);

            }
            else
            {
                changeDirection(DirectionEnum.right);

            }

        }
        else if (v != 0)
        {
            if (h > 0)
            {
                changeDirection(DirectionEnum.forward);
            }
            else
            {
                changeDirection(DirectionEnum.back);
            }

        }
        else
        {
            // changeDirection(DirectionEnum.rightidle);
            // changeDirection(DirectionEnum.backidle);
            changeDirection(DirectionEnum.frontidle);
        }
    }

private void changeDirection(DirectionEnum dir)
{
    if (dir == DirectionEnum.left)
        theAnimator.SetBool(charactersleftwalk, true);
    else if (dir == DirectionEnum.right)
        theAnimator.SetBool(charactersrightwalk, true);
    else if (dir == DirectionEnum.forward)
        theAnimator.SetBool(charactersfrontwalk, true);
    else if (dir == DirectionEnum.back)
        theAnimator.SetBool(charactersbackwalk, true);
    else if (dir == DirectionEnum.frontidle)
        theAnimator.SetBool(charactersfrontidle, true);

}

```

This is the left joystick

```
public class JoystickMove : MonoBehaviour ,IDragHandler,IEndDragHandler
{

    public static JoystickMove instance=null;

    public float _speed=6f;

    [Tooltip("the joystick radius ")]
    public float R=50f;

    private float _r;

    private Vector2 centerPos;

    private float _h;
    private float _v;

    public float H {
        get{return _h;}
    }
    public float V {
        get{return _v;}
    }

    void Awake() {

        if(instance!=null) {
            Destroy(this.gameObject);
        } else {
            instance=this;
        }

    }
    void Start() {

        _r=1f*Screen.width/960f*R; //this to calculate the scale of screen

        centerPos=GetComponent<RectTransform>().position;

    }

    void SetHAndF(Vector2 pos){ // Horizontall and Vertical axes

        Vector2 diff=pos-centerPos;
        float distance=diff.magnitude;

        if(distance>_r) {
            pos=centerPos+diff/distance*_r;
        }
        GetComponent<RectTransform>().position=pos;

        Vector2 move=pos-centerPos;

        _h=move.x;
        _v=move.y;

    }

    public void OnDrag(PointerEventData data)
    {

        Vector2 newPos =new Vector2(data.position.x-30f,data.position.y-30f);

        SetHAndF(newPos);

    }

    public void OnEndDrag(PointerEventData data){

        Debug.Log("End Drag"+centerPos);
        GetComponent<RectTransform>().position=centerPos;
        SetHAndF(centerPos);

    }

}

```

This is the rotate class joystick

```
  using UnityEngine;
  using System.Collections;
  using UnityEngine.EventSystems;

public class JoystickRotate : JoystickMove
{

    public static JoystickRotate instance=null;

    void Awake(){

        if(instance!=null){
            Destroy(this.gameObject);
        }else{
            instance=this;
        }

    }

```

this is for fire

```
    public class JoystickFire :  MonoBehaviour,IPointerDownHandler,IPointerUpHandler
    {

        public static JoystickFire instance=null;

        private bool _fire=false;
        public bool Fire{
            get{return _fire;}
        }

        void Awake(){

            if(instance!=null){
                Destroy(this.gameObject);
            } else {
                instance=this;
            }

        }

        public void OnPointerDown(PointerEventData data){
            _fire=true;
        }

        public void OnPointerUp(PointerEventData data){
            _fire=false;
        }
    }

```

# Answer
The error is because you are using `GameObject.Find` in the constructor section of your class:

```
GameObject characters = GameObject.Find("taoistmoveobject");
GameObject anim = GameObject.Find("taoist");

```

You should have:

```
GameObject characters;
GameObject anim;

```

And then in Awake():

```
characters = GameObject.Find("taoistmoveobject");
anim = GameObject.Find("taoist");

```
> 1 votes

# Answer
I read your code again and it looks like what you want is to update your animation based on the value received from the joysticks?

From what I see, you only have 4 directions. The first thing you should do is translate the analogical values from the stick into a direction that you can use to chose between your 4 animations. The easiest way to do this is to discard one of the inputs that you receive and use the sign of the one you keep to determine the direction. For example, if h = 0.2 and v = -0.8, you'll have direction = (0, -0.8) which means vertical negative.

When you have your direction, you can set the correct Boolean on the animator and move your character accordingly. Instead of a lot of Boolean, you should consider an `enum` to switch between directions.

Here is some code to show how you could do this. It is poorly written but it is clear I think.

```
  enum DirectionEnum {
    forward,
    back,
    left,
    right,
    idle
  }

  Animator theAnimator;
  DirectionEnum currentDirection;

  void Awake()
  {
    theAnimator = theanim.GetComponent<Animator>();
    currentDirection = idle;
  }

  void Update()
  {
    character.transform.localPosition = returnSpeedForCurrentDirection();
  }

  public void updateDirection(float h, float v)
  {
    if(h != 0)
    {
      if(h > 0)
        changeDirection(DirectionEnum.left);
      else
        changeDirection(DirectionEnum.right);
    }
    else if(v != 0)
    {
      if(h > 0)
        changeDirection(DirectionEnum.forward);
      else
        changeDirection(DirectionEnum.back);
    }
    else
    {
      changeDirection(DirectionEnum.idle);
    }
  }

  private void changeDirection(DirectionEnum dir)
  {
    theAnimator.SetBool(currentDirection, false);
    currentDirection = dir;
    theAnimator.SetBool(currentDirection, true);
  }

  private Vector3 returnSpeedForCurrentDirection()
  {
    //Compute your speed depending on the current direction
  }

```
> 0 votes

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


# Question
Title: How to open two Animator views in Unity?
How can I open two Animator views in Unity editor?

What I tried so far is to lock an Animator view and go to Window=\>Animator.

That did not help.

# Answer
Unfortunately, some Unity windows are bound to a single instance. Animator is one of those. So, as short as the answer is, as of at least Unity 5.6.1, you cannot have multiple Animator tabs open.
> 3 votes

# Answer
Like this:

Right click on an existing tab (Game, Scene, doesn't matter) and go to "add tab." Add a new Animation tab. You can have as many as you'd like. When I first read your question I was like "what, really? only one?" and did this immediately out of habit and had no trouble. Then re-read your question. Window -\> Animation jumps to the first animation tab open, creating it if there isn't one.

However, this only works for the types listed in this menu. For other windows (such as the Asset Store, Anima**tor**, Profiler, Sprite Packer, Services, Lighting...) you can only have *one.* There is no ability to create a second tab of that type. For most of these (Profiler comes to mind) there's no *need* to have more than one. For the others, it might be a technical restriction (you can have two Inspector tabs, for instance, but they'd always show the same information...so I don't know why that one's supported in multiple).
> 1 votes

---
Tags: unity
---


# Question
Title: How to convert non-discreate data for discreate pathfinding?
I have a list of entities that looks like `[{x,y,width,height}, {x,y,width,height}, ...]`. This list is non-discreate, It doesn't follow a grid. entities can be positioned at floats like `x:2.345`

Most path finding solutions I've found like **A\*** expect a discrete grid to perform the calculations.

I've looked at **Theta\*** as a solution it supports non-discreate pathfinding on a navigation mesh.

Either way I need to convert this entity data into a Grid or Navigation Mesh. This is probably a common task but new for me. I'm doing this in Javascript and would appreciate any examples in that language.

also some entities will be moving in realtime and will effect future path generation of other entities.

# Answer
> 4 votes
new answer:

In the real world, since this field is not densely populated, simply tell the characters to move in the desired direction and once they approach an obstacle, to go clockwise or counter-clockwise around it (depending on which way is shorter).

To improve on this, you can walk the characters towards corners instead:

In the general case, you would send rays from the corners of the black rects like so:

The circles will be the vertices of the graph and the lines, the edges. Once the line hits the border of the stage, you need to recursively keep searching to the left and the right. I did not put it in the sketch but you also need to cast edges inwards. This however is the general case (which is hard could the field might be very densely populated).

Please note doing this pseudo-boolean operations on a 2d-mesh to get the desired navmesh or graph could be expansive so it's not something you want to do if your game worlds modifies itself in real time. It is more of a tool that could be used in advance. I strongly suggest going for the first approach if possible as it's much much faster.

old answer:

They don't expect a discrete grid, they expect a graph. You need to form a graph, perhaps by embedding your input in a navmesh.

Also, please consider caching paths by computing them "offline" (not during runtime) in advance to offload that process as it could get taxing, depending on the complexity of the graph.

# Answer
> 3 votes
I would consider generating waypoint graphs instead. They're easy to work with, they give optimal paths, and are generally fast enough for reasonably small environments.

The optimal path will be a series of line segments, and each vertex in the path will either be the origin, the destination, or a vertex of one of your obstacles. So although your environment isn't discreet, you only really need to consider this discreet set of vertices.

So, you can build a waypoint graph with a node for the origin, a node for the destination, and a node for each vertex of each obstacle. Two nodes should have an edge between them iff the line segment between the nodes does not intersect any obstacles. The weight of the edge should be the length of this line segment.

If you have dynamic obstacles, a new graph will need to be regenerated repeatedly. If this turns out to be too slow, a number of optimizations are possible, but the best approach depends on how many static vs dynamic obstacles you have and how often the dynamic ones move.

Once you have this graph, you can run any pathfinding algorithm on it. A\* is an option - it's usually used with grids, but all it requires is a graph and a distance heuristic. Since each node in your graph has spacial coordinates associated with it, you can use the usual distance heuristics (e.g., Euclidean distance if you allow movement in any direction).

Note that I've assumed your agents can fit though arbitrarily small spaces. If that isn't the case, we need to offset waypoints away from obstacles based on the agents' size, and use rectangles instead of line segments when checking if two nodes are connected.

# Answer
> 0 votes
I want to post my own answer that I eventually went for with this

Steering Behaviors: http://www.red3d.com/cwr/steer/

Essentially each frame you calculate a movement "force" on an entity. The force can take into account other entities positions. So in my case the moving entities would take a "Seek force" to move towards a destination and along their way they would apply an "avoid force" to any of the non-discrete entities and move around them.

---
Tags: vector, path-finding, data-structure, navmesh
---


# Question
Title: Unreal engine for just 2d game development
I am very much interested in game development. But my pc seems to be not up to the mark for downloading UE4. These are the specs of my crappy pc:

* Processor: Intel Core 2 Duo e7500 2.93 ghz
* Ram: 4 gb DDR2
* Graphics : Nvidia Geforce Gt 730 Gddr5

Before doing big stuff like upgrading pc, I want to try with 2d game development, which doesn't require a high rig. So is there a way to download UE4 on such low pc. By the way, I prefer UE4 because of some features like node programming, and other extensive features.

# Answer
From the UE4 FAQ section :

> What are Unreal Engine 4's system requirements? For developing with UE4, we recommend a desktop PC with Windows 7 64-bit or a Mac with Mac OS X 10.9.2 or later, 8 GB RAM and a quad-core Intel or AMD processor, and a DX11 compatible video card. UE4 will run on desktops and laptops below these recommendations, but performance may be limited.

So in reality you do not cover the recommended specs, but absolutely nothing is stopping you from downloading it and trying the engine.
> 3 votes

# Answer
Basically, your computer specs doesn't cover the BASIC specs to run the program. Also, Unreal engine doesn't support 2D style games, but it supports platforming through some coding and camera positioning.

If you want to develop 2D games, I recommend the engines GameMaker:Studio and Godot. Both are easy to use but you'll be writing some code and you'll need some learning, because these engines work with "their own language", so to speak.

If you never coded anything, GameMaker:Studio is the one for you, because it supports a drag and drop feature to develop your stuff.

Again, if you really want the Unreal Engine, step up your pc specs.
> 1 votes

# Answer
Do you want to make games or LEARN to make games? Consider this very deeply and come up with a polished answer. Unreal Engine is a nice tool, but it does not always serve it's purpose. I, as a code-oriented developer try to avoid UE4 in any possible way, because it forces the user to think in a very specific way, and that is totally opposing to what I believe game development should be about: (theoretically) unlimited freedom of choice.

In regards to your question: Here's how I see it: Do you want to be able to make any possible game? Then you need a very wide skill set that is not bound to any specific interface or API. If you want to learn 2D graphics then pick up SDL/SFML/OpenGL/(whatever) books and start learning. There is nothing more satisfying than beginning at the very bottom and working your way up to the top: you'll never fear the learning curve, or the entry bar again. Try to explore every little nook and cranny of this infinite field and see what's getting you excited. As a matter of fact, most companies in game-dev avoid UE4 because, while being a very useful multi-tool, it also fixes the way developers can do their work.

On the other hand, UE4 will give an experienced developer a tool set that will increase their productivity A LOT. However, UE4 does come with a very steep learning curve, especially for developers.

As an example, consider that in UE4 you can't use the C++ Standard library in the way you might be accustomed. You need to either create your own algorithms and data structures or use the built-in functionality, such as the TMap or the TArray, which you need to study very closely before you are able to build anything with them. You might say that you can avoid coding completely, by using Blueprints, but you should be aware that Blueprints bring a powerful performance overhead: they are meant to be an interface between designers and programmers, not a programming tool.

TL;DR: UE4 is a next-gen game engine that has a high hardware impact even though you only want to use part of it's functionality(that is, you get the whole minimal package at all times), and has a very steep learning curve especially if you're a programmer. Before doing anything with UE4, I recommend you try to learn with a 2D wrapper for OpenGL or DirectX. Try SDL, or SFML. Or you could go for OpenGL directly(it's very satisfying to climb the initial learning curve and draw your first 3D cube that spins around in the post 3.3 standard).

I hope you'll consider what I mentioned above and won't stop pursuing the elevation of your creativity and experience.
> 0 votes

---
Tags: 2d, unreal-4
---


title: Finite State Machine for player states

text:
# Question
Title: Finite State Machine for player states
I have a state machine for a game I am developing. The player can be in four states, depending on button clicks, and some game elements (being in thin air, or standing on the ground). I am just wondering if I should use arrows between all the possible states changes? All states in this diagram need to go through the `Idle` state, but in the game, you could easily go from `Walking` to `Jumping` by pressing the "jump"-button whilst walking. The same applies for the `Jump` state to the `Falling` state. After a jump, the player immediately transfers to the `Falling` state. Is this something I need to put in the finit state machine diagram? The diagram might end up messy with extra arrows, and I would like to avoid it, but if this diagram was meant for a thesis or in lecture I want the diagram to be correct.

I am sorry if this question is too opinion based.

# Answer
For every way your state could change, you need an arrow (with an condition and a priority). If you always would have to go back to the idle state, your conditions would have to be really good. Imagine the player state of jump is just dependent of pressing the jump button, then you either could jump forever (caused by the idle return state depending on no button pressed), or you could not jump while walking.

Also think of hybrid states like moving while falling or jumping, if needed. The priorities might not be that important, only if two possible state changes could happen at the same time.
> 1 votes

# Answer
PSquall got it right. Just to add on to that, if this is for a thesis or lecture you want to look at using UML state machine diagrams to model the machine. Also you could have your jump state transition into falling once the peak of the jump is reached, and falling back into idle once you're back on the ground. If youre interested i also wrote a small article on planning out and writing a simple state machine like what you have there using cocos2d-x, but the theory stuff should be transferable.

For anything serious you'll end up with many more states and hybrid states, and you'd also want to consider states like getting hit or being stunned. There's also such a thing as concurrent state machines which amounts to two or more machines linked together running side by side so you can logically separate certain things like what you're doing and what is happening to you or what you're carrying.
> 2 votes

---
Tags: architecture, documentation
---


# Question
Title: How to build repetition into a game that won't ruin the experience
I am building an Educational technology (Edtech) game that attempts to follow the format of an adventure RPG while teaching foreign languages.

Obviously, EdTech games must actually **teach**, which requires repetition for mastery. Especially foreign languages which requires a lot of practice to master. But, the game's goal is for the story line and game world to be immersive to the point the player is hooked in. Repetition often destroys the immersive aspect and linearity of a story.

What are some strategies to ensure the necessary repetition is happening such that a student retains the information, but also has fun playing along with the story? Are there any?

# Answer
## What kind of mechanic to focus on?

You need to decide how you will fit Planning, Practice and Improvisation in the game:

* Planning. This is the stage of the game where the player is building the strategy. This often happens in the player’s head (rarely you layout the strategy in the game, although some games do that). Yet, the game needs to support it. For example, by letting the player browse the inventory deciding what to equip, what to sell, etc. In card games, this is where you build your deck. Some games let you see what collectible you do not have, and may even give you clue on where to find them. All before you go into…
* Practice. This is the stage of the game where the player is trying to execute something by memory. This usually takes the form of a scenario where the player has to do a series of step in the right order and timing to progress. How easy it is to recover from a mistake will be the measure of unforgiveness of your game. Which brings us to…
* Improvisation. This is the stage of the game where you need to react to whatever the game throws at you, perhaps trying to stay close to a plan, but without one unique solution. It is in this stage where emergent gameplay is your best ally.

We have to cross this with the way people learn:

* Some people learn by experimenting. They will learn better in *improvisation* by trial and error.
* Some people learn better by example. They need to see how to do it first, as a form of *planning* for what they will do.
* Some people learn better by theory. They need to understand how everything works and what to do on every case. They learn better if you let them study on their own. I will put that on *planning* too.
* Some people learn better by instruction. They need somebody telling them what to do. I consider this *practice*.

You give these tools to the wrong person, and they hate it (so make them optional if you have them):

* Going into the game without some form of tutorial is unfair.
* Having to sit while the game does the demonstration is boring.
* Having to read in game text to understand the game is unintuitive and frustrating.
* Getting instructions of what to do at every step is annoying.

*These are anecdotal. I am unaware of any study or reference material on the matter. Ern.. Egoraptor!*

Considering that the player might be looking for this game to learn languages, I would say this player would not benefit from reading or from a bunch of instructions. That is selection bias. Thus, I suggest a game that focuses on *improvisation* and *planning*, and not much practice.

A game that focuses on *improvisation* and *planning*, is a game where you can pick your tools, consider weights, do some tradeoffs, and then go to an area where you don’t know what is coming for you and you got to work out with what you got and what you may get on the site.

For the player, a game the focuses on *improvisation* and *planning* can be rewarding when:

* They conquered the area, which is an accomplishment
* They satisfy their curiosity by trying different strategies and seeing how they play out
* They gain mastery on what tools to keep and how to use them

**Note**: This is based on what "Archivers" and "Explorers" find engaging according to Bartle taxonomy. I also considered the motivational theory presented in the book Drive: The Surprising Truth About What Motivates Us.

*Just to be clear, I have been talking about what to focus on, not what to have and not have in the game.*

---

## The repetitive temptation

It is tempting to make a game focuses in practice for learning languages. Tempting because you start on the premise that you need repetition. Yet, in actuality, communicating is not a repetitive skill. Unless you are preparing for a recital or something like that, languages is more akin to improvisation. If you want to be able to have a conversation, you need to be able to understand and respond to whatever the other person “throws” at you.

**Note**: If you believe that you can teach languages by simply teaching a person what to respond to each prompt. Then you believe that the person in the Chinese Room knows Chinese.

That does not mean that practice has no didactic value. It is great for rhythm games, for example. A great example is singing games, where you actually develop the skill to sing.

**Note**: In general, we want the player to enjoy every part of the game. You may still get the player to do the not funny, repetitive, boring things... for example by Classical conditioning or my emulating a Skinner Box. Do not do that.

---

Be wary of random encounters. Being an RPG it is very easy to build the repetition mechanic in random encounters in the game. So that you “battle” by having to remember the thing that you are supposed to be learning. The problem many fall in the trap of designing random encounters as a means to a goal, and not to be engaging... if you focus on practice, that is what you would be doing.

**Note**: See Intrinsic vs Extrinsic - Designing Good Rewards in Games - Extra Credits.

I once tried a couple RPG games that were supposed to teach me some other language, and they fail to engage me because of that. The general description of these games is as follows:

You have to go from town to town because reasons and then enemies pop out in the journey – and you hate this because you want to get to the next town – and each enemy is a symbol, a word, or a phrase and you have to translate it, spell it or something like that to defeat it.

**Note**: Project LRN is an example that went this route. Certainly, it has been useful for some people. Yet, its lack of popularity - at least in its current form - supports the hypothesis that this is a bad idea.

*Do not do that. That is my suggestion.*

---

## Engaging the player

What you should aim for is to take the player to *the zone*, I mean, to a semi meditative state where the player can perform the actions by reflex. You can archive this by:

* Having a well stablished set of predictable mechanics.
* Having random elements that challenge the player.
* Steadily increase the difficulty (by increasing the speed).

This framework can lead to mechanics akin to the classic arcade games, but it can also lead to mechanics akin to modern sandbox and open world games. I would say it is more appropriate to pay attention to what I am not saying.

* When I say well stablished predictable mechanics, I am not saying that you should copy from other games (you can, but that is not what I am saying). Instead, I am saying that you should provide an environment where the player can safely test how the game works, and seamlessly move to an environment with real risk. Do that in such way that for the moment the player struggles, it is not because of lack of understanding or predictability of the mechanics.
* When I say to have random elements, I do not mean to say to make the consequences of the actions of the player are unpredictable. The player needs to know what went wrong when something goes wrong. Instead, have random elements (such as obstacles, enemies or loot) pop at a safe distance, letting the player some time to react.
* When I say increase the difficulty, I do not mean to make the enemies more dangerous or complex. I mean require the player to react faster. That could be more obstacles or faster enemies.

**Note**: I am suggesting to increase speed, not because other ways to adjust difficulty are wrong, but because we aim for the moment where the player can respond without having to ponder (or looking up in a dictionary or something like that).

If that does not make sense, think about the game Tetris and read those points again.

---

## Try using emotions

To teach languages you need to teach association. If want the player to understand text in another language, you have to give it context. If you can provide images and audio cues, much better. There is something even better yet: associate them with an emotion. Moreover, I do not mean an emotion of the characters of the game, but an emotion of the player!

As game designer, you can create genuine emotions. in the player (for example of joy, surprise, fear, loss, anger, and disappointment, etc... intentionally or not). You do not have to try to explore the whole spectrum (that is up to you), yet you need to recognize when you game creates these reaction and act on that. Either by taking advantage or by changing them to something different.

One good way to archive emotional experiences for the player is to archive immersion. Getting immersion is relatively easy. The first tool is audio and graphics, yet, if you have enjoyed any text only adventure game, you know you do not need those. It is more important to invite curiosity, if the player wants to explore the game, then the player is willing to suspend its disbelief.

*By the way, fill the negative space. If you give the player an option, be it intentionally on a dialog tree, accidentally as a corner in a maze, or unconsciously as climbing on top of a tree or not, make it feel meaningful.*

Not breaking the immersion is harder… you need to leverage mechanical transference and affordance as much as you can. Not only from the real world to the game, but also from other games to your game. Also, being your objective to teach, leverage skill transference and affordance from your game to the real world.

If you can put the playable character in the situation where it needs to learn what the player needs to learn, without braking the immersion by reminding the player that this game is an educative one, you have succeeded.

**Note**: See "How Games Move Us: Emotion by Design" by Katherine Isbister

Sure, you cannot teach everything this way, and you cannot really test player knowledge without removing the language from the cues. Yet, this is what will make the game memorable in the end, and it is what will allow the player to access those memories, making the learning experience long lasting.

---

## Teach by not trying

Consider the Simlish language (from The Sims series). It evolved across various games. The developers did not mean for it to represent any real language. It does not matter if you do not understand it. In fact, the developers improvised most of it. Yet, it is consistent! People have built dictionaries out of the thing!

There are plenty of examples where the developers of a video game create some cipher (**warning: TVTropes link**) or crease some artificial grammar and odd symbols to write some fictional language, and somebody somewhere figure it out.

Discovering what something is or means in the game can be rewarding in and out of itself. Certainly not every player will have this experience; most will get to know by third party. Which is good! Because this means there is also a social aspect to the game that exists outside of the game itself.

**Note**: There are tips, tricks, cheats, walkthroughs, reviews, guides, let's play, etc... Where do I point you to justify the claim that people share information about games... Ern... Arqade!

Therefore, do not be afraid to leave thing hidden or unexplained in the game, as long as the players have the tools to figure them out and some reward for doing so (Addendum: For example, if they want a reward they will look up a word in another language, if want that often enough, they better memorize them).

---

## Look at what works

I advise to look at Duolingo, which does a lot of gamification for language learning. Look at it with the lenses of game designer, deconstruct it into mechanics, and look how you may adapt them or improve upon them.

Addendum: You know what else works...? Games in another language that are easy enough to get into. In particular if, they have a social component. If the game can get the player hooked without using words, and then turn out you need to know some words to get good at the game... you are going to learn. Moreover, the game was not even trying to teach you another language.
> 8 votes

# Answer
Look at some early examples of repetitive yet fun video games:

https://en.wikipedia.org/wiki/Snake\_(video\_game)

https://en.wikipedia.org/wiki/Asteroids\_(video\_game)

https://en.wikipedia.org/wiki/Tetris

https://en.wikipedia.org/wiki/Pac-Man

All of these are very, very repetitive, yet there will be very few readers in this forum who spent less than 10 hours combined playing these games.

There are 2 concepts these games use besides repetition:

* Gradually increasing difficulty
* A sense of progress (Highscores, Levels)

In an educational RPG, the most common minigame is combat, but there are plenty of opportunities for other minigames as well. If you're wondering how to merge language and combat, I'll refer you to one of the games I "used" to learn English, which merges repetition, gradually increasing difficulty, and a sense of progress masterfully.
> 1 votes

# Answer
Repetition can be used to enhance the experience rather than destroy it. The key is whether it helps the core mechanics of the game. People like adventure RPGs because uncovering and experiencing a story is a naturally fun activity. Therefore, you should use repetition to help players uncover the story. This already exists in many RPGs. Think about when you enter a village in an RPG and everyone you talk to keeps mentioning a certain house/person/activity. This is a gentle nudge to the player for what he or she should try next. Each person says something slightly different, but they are close enough together that they build off one another. Even though a player will be hearing almost the same words over and over again, there is still satisfaction in talking to everyone, because that is how you get the full story.

Transferring this over to teaching foreign languages, you could use a similar approach. Players will be motivated to learn the language because all the NPCs keep using certain words. More repetition = more importance. Learning the meaning of these words means unlocking the secrets of this world.

The danger of boredom comes in when repetition does *not* support the core mechanics of discovery. For example, having an NPC recite the exact same speech every time you enter a new area would distract from the experience rather than help. Players want to learn new things about the area, and the repetition in this case keeps that from happening.
> 1 votes

---
Tags: game-design, game-mechanics, education, storyboard, educational-games
---


title: Dynamic frame rate in Unity

text:
# Question
Title: Dynamic frame rate in Unity
I'm developing a 3D visualization tool based on Unity, targeting WebGL. The user rarely interacts with the 3D scene and when he does it's only about adjusting the camera like rotating or zooming the view. I disabled vSync (`QualitySettings.vSyncCount`) and locked the frame rate to 30 (`Application.targetFrameRate`) to reduce the CPU usage at least a bit while still having an acceptable level of responsiveness when the user moves the camera around. With 30 fps I get a CPU usage of around 30%. Considering lower-end hardware this seems still too high.

In order to further decrease CPU usage, I introduced two 'modes':

* Interactive: runs with 30 fps
* Idle: runs with 10 fps

I wrote some lines of code to switch between those modes depending on user interaction. So when an input is detected, the application uses more fps and after a certain amount of time without any interaction, the application uses less fps again. It works pretty well so far: The app uses 30% in interactive mode and 8% to 10% of the CPU while in idle mode.

Setting the idle frame rate to 1, CPU usage is reduced to 1.5% while in idle mode. This is really great. But as expected there's a problem. Basically I locked all the `Update()` methods to be called only once per second. When the user interacts with the camera, the event will be processed with an expected delay of something around one second.

**Now the question:** How can I detect user input immediately while having the application run with a low frame rate and also immediately apply a new frame rate (say 30) without any noticeable delay?

Originally I wanted to have some sort of on-demand rendering. I've read some posts about how people render to a texture to reduce rendering cost in less interactive scenes. But setting the frame rate dynamically seems like a cleaner solution in my opinion. I also tried to use the `FixedUpdate()` method to check for inputs and switch to interactive mode, but that didn't work either.

**Note** Also worth mentioning, this approach produces errors in the browser, indicating that the application frame rate should be 0 (not in terms of Unity's target frame rate but as in *'let the browser handle the frame rate'*). While this might be a different question it's still related to this topic. Maybe someone has an answer for that as well!

---

# Edit 1

As mentioned in the comments below, Unity provides the callbacks `MonoBehaviour.OnApplicationPause` and `MonoBehaviour.OnApplicationFocus` to detect whether the application is about to receive or lose focus.

**However, the problem is this:** My application nearly never loses focus. While this is a nice additional optimization it doesn't really help me too much. My problem is that the app is idle most of the time while **also** having focus. It's really just the user staring at the window most of the time.

Just to make some more sense: I'm targeting WebGL. Unity's sole purpose is to visualize some stuff while the user mainly interacts with some HTML controls. In the rare case he wants to interact with the 3D scene, I want to set the frame rate to say 30. The idea is *"I don't re-render the scene too often as long as you don't interact"*.

To emphasize: In my most relevant use case the application never loses focus. This means, the only reliable indicator to determine when to switch between frame rate profiles is based on user input.

Sorry if I wasn't too clear about that :)

---

# Edit 2

I posted this topic on the Unity Feedback Page. If you're interested, check it out and leave a vote. Maybe this request gets enough attention to get supported by the Unity developers.

# Answer
I think render to texture is still your best bet. If you took a "screenshot" of what the camera sees and just display that texture the rendering cost should be cheap even at 30fps.
> 7 votes

# Answer
So I thought about this, what if you were to just stop the camera from rendering again(Not disabling the camera) when the user is stationary? That way you could still have a frequent calls to the `Update` function so that user input is still responsive but the device wouldn't have a high resource consumption. After a quick search I found this. I haven't tried it yet, it's just an idea you could tryout.
> 1 votes

---
Tags: unity, performance, frame-rate
---


# Question
Title: How to convert Texture2DContent to Texture2D in custom ContentTypeReader
I'm trying to implement a custom ContentPipeline extension that writes a Surface object with a Texture2D member.

My input file is an xml with fields for all of my Surfaces and their members. In the xml, my Surface's Texture2D is represented by a path to an image file. In my ContentProcessor, I want to load the Texture2D from the image file path, then write that texture data straight into my object's xnb with the rest of a Surface's members.

Right now, I've got the ContentTypeWriter writing a different ("CompiledSurface") object with a Texture2DContent member. The Texture2DContent is created in the ContentProcessor using BuildAndLoadAsset(string path).

My importer, processor, and writer all seem to be doing their jobs. But in my ContentTypeReader, I can't figure out how to convert the Texture2DContent back to a Texture2D in order to create my runtime object.

Any help is much appreciated.

```
class Surface
{
    protected Rectangle bounding_box;
    protected Texture2D texture;
    ...
}

class CompiledSurface
{
    public Texture2DContent texture;
    public int x;
    public int y;
    ...
}

```

# Answer
> 0 votes
I've got it! An extremely simplified example:

Loaded each Texture2D in custom ContentProcessor like this...

```
// Create external ref to texture source file (.bmp, .png, etc)
ExternalReference<Texture2DContent> tex_ref = new ExternalReference<Texture2DContent>(path_to_image_file);

// Build & Load texture
Texture2DContent texture_content = context.BuildAndLoadAsset<Texture2DContent, Texture2DContent>(tex_ref, "TextureProcessor");

```

Then serialized Texture2DContent in custom ContentTypeWriter like this...

```
// Write as Texture2DContent
output.WriteObject(texture_content);

```

Conversion happens during de-serialization, in custom ContentTypeReader...

```
// But read back as Texture2D
Texture2D texture = input.ReadObject<Texture2D>();

```

---
Tags: xna, monogame, xna-content-pipeline
---


# Question
Title: How to create a grid movement like the oldschool snake game?
I got 2 problems with the game,

1. I don't know how make my GameObject (snake head) move based in a grid for some reason I don't know it moves freely on the screen.
2. The tail keep instantiating above the head not behind... I tried many things and did not work and didn't find an answer in the forum that helps me.

Now I'm back to the begin and looking if someone can help me.

This is the code I use to generate a grid. If anyone could help me with some code, I appreciate it.

```
public class LevelManagerTest : MonoBehaviour
{

    public GameObject tile;
    [SerializeField]
    private Transform gridParent;
    [SerializeField]
    public Transform[,] Grid;

    private GameObject[,] grid = new GameObject[12, 7];

    public float TileSize
    {
        get { return tile.GetComponent<SpriteRenderer>().sprite.bounds.size.x; }
    }

    void Start()
    {
        CreateLevel();
    }

    private void CreateLevel()
    {
         Vector3 worldStart = Camera.main.ScreenToWorldPoint(new Vector3(0, Screen.height));

        for (int y = 0; y < 7; y++)
        {
            for (int x = 0; x < 12; x++)
            {
                PlaceTile(x, y, worldStart);
                grid[x, y] = tile;
            }
        }
    }

    private void PlaceTile(int x, int y, Vector3 worldStart)
    {
        // creates a new tile and makes a reference to that file in new tile variable
        GameObject newTile = Instantiate(tile, gridParent);

        //uses the new tile reference and change the position of the tile
        newTile.transform.position = new Vector3(worldStart.x + (TileSize * x), worldStart.y - (TileSize * y), 0);
    }
}

```

# Answer
> 3 votes
You have handled the process of creating grids. Tile based movement is a bit more complex than normal 2D or 3D movement. You can find some headlines of the implementation but obviously I cannot provide you the whole code for the game.

For the movement of the snake, you can create speed variable with using `Vector2.Up`, `Vector2.Down`, `Vector2.Left`, `Vector2.Right`. For moving the snakes body, you can use `Coroutine` class of Unity. The main idea behind the movement is that translate the position of the head of snake directly into the next cell, wait for some duration and then start to move again, something like following:

```
void Start()
    {
        coroutine = Move(Vector2.Up);
        StartCoroutine(coroutine);
    }

    private IEnumerator Move(Vector2 direction)
    {
       transform.position += direction;
       //Wait time is the duration between snakes' moves
       yield return new WaitForSeconds(waitTime);
    }

```

The coroutine won't stop executing unless you call `StopCoroutine()`

After correctly implementing only head's movement, you should implement the body parts of the snake with the following logic:

Keep a reference for each block part of the snake in a list When you start moving, move the head towards direction, but other body parts must move towards the lower indexed body parts direction. For example;

```
bodyPartsArray[0].position += Vector2.Up;
   for(int i = 1; i < bodyPartsArray.Count; i++){
   bodyPartsArray[i].position = bodyPartsArray[i-1].position;
}

```

Finally, for instantiating a new body part for the tail, you must append `bodyPartsArray`, and position the new body part **to the opposite of last body part's movement vector.** (You can calculate that vector like this **before you add the new body part**:

```
//Subtract the last part's position from the previous one
Vector2 newPartsDirection = bodyPartsArray[bodyPartsArray.Count - 1] - bodyPartsArray[bodyPartsArray.Count - 2];

//Add the direction to the last part's position
Vector2 newPartsPos = bodyPartsArray[bodyPartsArray.Count - 1] + newPartsDirection;

```

Saying again, these are the key parts that you have asked, not the entire code or project. But I hope this would be a guideline for you, to implement the features that you wanted.

# Answer
> 0 votes
Once you have a grid, have your snake's head's position be in grid units. Move the snakes head in tile units. Then move the actual GameObject to the grid units times their width. Ex: Snake head is at (5,5) on a grid made of 1 unit wide squares, set its position to (5,5) ie: 5 grid units * 1 unity unit.

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


title: Unity accordion UI

text:
# Question
Title: Unity accordion UI
I downloaded the accordion from the unity forums and I'm trying to add a button to it. issue is with the vertical layout group. when any UI element is added the layout will automatically go vertical and scale accordingly. i fixed it by adding a layout element on the button and ticking the ignore layout option. However this generates another issue. when the UI is folded (accordion is folded) the buttons scale down and show. See image below  these buttons are inside section 1. and when it's opened they show up as i want.  Any idea on how to fix this?

# Answer
You can achieve this by adding a layout holder for your buttons that has a horizontal group layout. Note that if you want a custom group layout you will probably have to write it yourself. This screenshot shows how I set up the element.

From there you can play with the preffered width and height of the layout element component of each button.

Hope this helps :)
> 1 votes

---
Tags: unity, c#, gui, ui-design
---


title: Bounce once on a collision

text:
# Question
Title: Bounce once on a collision
I have BoxCollider2D and EdgeCollider2D how can I make the BoxCollider2D bounce only from the EdgeCollider2D and only once?

# Answer
> 1 votes
Add a tag to the Edge Collider game object, write a script to detect collision and check for this tag, then have 2 Boolean variables (e.g. played, collided) set to false at start, if collision with Edge Collider is detected and 'played' is false, set the 'collided' boolean to true.

In `Update()` check if the 'collided' boolean is true, if so then add a bounce and set it to false and set 'played' to true.

Add the script to Box Collider.

It would be something like this-\>

```
private bool played = false;
private bool collided = false;

void FixedUpdate(){
      if(collided){
          GetComponent<Rigidbody2D>().AddForce(transform.up * FORCE MULTIPLIER);
          collided = false;
          played = true;
      }
   }

void OnCollisionEnter(Collision col){
  if(col.CompareTag("EdgeCol") && !played){
     collided = true;
 }
 }

```

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


# Question
Title: How to create seamless and coherent voxel terrain using simplex noise 2D?
I'm using the simplex noise 2d plugin for unreal engine 4, which can also be understood by most programmers. I have already implemented chunk generation and dual-chunk noise elevation. However, each chunk has a unique heightmap and this results in jagged voxel terrains. Pseudo code:

```
//Chunk.cpp
for(int chunkWidth = 0; chunkWidth <= 10; chunkWidth++){
   for(int chunkHeight = 0; chunkHeight <= 10; chunkHeight++){
      noiseX = ((chunkWidth / 10) - 0.5) * Frequency;
      noiseY = ((chunkHeight / 10) - 0.5) * Frequency;
      Elevation = SimplexNoise2D(noiseX, noiseY) * 100;
      ChunkLoc = getActorLocation(self);
      SpawnMeshAtLoc(ChunkLoc.x + chunkWidth, ChunkLoc.y + chunkHeight, Elevation);
   }
}

```

I have another variable available: chunk2DCoord(2D vector coordinate for each chunk)

# Answer
I solved this problem by changing the parameters of this function. The iteration caused this problem. The x and y values of the noise function should encompass the values of a voxel's world position.

USimplexNoise::SimplexNoise2D(VoxelWorldLocation.x, VoxelWorldLocation.y);
> 2 votes

---
Tags: c++, voxels, unreal-4
---


title: Tile-wide extent tracing on a grid

text:
# Question
Title: Tile-wide extent tracing on a grid
I'm currently working on A\* pathfinding on a grid and I'm looking to smooth the generated path, while also considering the extent of the character moving along it. I'm using a grid for the pathfinding, however character movement is free roaming, not strict tile to tile movement.

To achieve a smoother, more efficient path, I'm doing line traces on a grid to determine if there is unwalkable tiles between tiles to shave off unecessary corners.

However, because a line trace is zero extent, it doesn't consider the extent of the character and gives bad results (not returning unwalkable tiles just missed by the line, causing unwanted collisions).

So what I'm looking for is rather than a line algorithm that determines the tiles under it, I'm looking for one that determines the tiles under a tile-wide extent line. Here is an image to help visualize my problem!

Does anyone have any ideas? I've been working with Bresenham's line and other alternatives but I haven't yet figured out how to nail this specific problem.

# Answer
How about if you draw a line from every corner of the 'tile' you are on to every corner of the tile you want to go to. You can probably even optimize this to 3 lines instead of four. Wouldn't this correctly detect all the tiles on the path?

As for smoother paths, check articles about 'steering behaviour' especially those combining it with A\* for example these links:
> 1 votes

# Answer
I've just implemented this algorithm for a game of mine a couple of days ago! (-8

Here's my idea in a picture form:

Note that the algorithm works with rectangles of any size. it's based on the fact that one corner of the rectangle *always* collides first with any grid line. This means that you can only trace one ray, and get all intersections you need.

Here's the algorithm step-by-step:

1. Choose the "forward" corner of your rectangle. For example, in the picture the tracing direction lies in the upper-right quadrant, so we choose upper-right corner.
2. Trace the (zero-width) ray from this corner to your destination. You would need to iterate over all intersections of your ray with grid lines.
3. For all intersections of the ray with grid lines, place your rectangle at the intersection point. Its side would lie exactly along a grid line, touching a number of grid cells. These are the tiles that your rectangle collides with at this point!

There are some edge cases here, like when the ray is exactly vertical/horizontal, or when it hits a corner exactly, but they're not difficult.
> 0 votes

# Answer
This procedure is an adaption of bresenham, which solves origial question.

```
final int cols = 64;
final int rows = 64;
color tiles = new color[cols*rows];

void squaretrace(int x1, int y1, int x2, int y2, color c) {
  if (x1==x2 && y1==y2) {
    tiles[x1+y1*cols] += c;
  } else {
    // make sure y1 is less or equal to y2
    if (y2 < y1) {
      int t = x1;
      x1 = x2;
      x2 = t;
      t = y1;
      y1 = y2;
      y2 = t;
    }
    // along y-axis
    if (x1==x2) {
      for(int y = y1; y <= y2; y++){
        tiles[x1 + y * cols] += c;
      }
    }
    // along x-axis
    else if (y1==y2) {
      int xLo, xHi;
      if(x1 < x2){
        xLo = x1;
        xHi = x2;
      }
      else{
        xLo = x2;
        xHi = x1;
      }
      for(int x = xLo; x <= xHi; x++){
        tiles[x + y1 * cols] += c;
      }
    }
    // northeast
    else if (x1 < x2) {
      // NW and SE corner
      int dx = x2 - x1;
      int dy = y2 - y1;
      int m = 8;
      int k = (1<<m) * dx / dy;

      int minx = x1 << m;
      int maxx = (x1+1) << m;

      for (int y = y1; y <= y2; y++) {
        int xLo = minx >> m;
        if (y!=y1) minx += k;
        if (y<y2) maxx += k;
        int xHi = (maxx-1) >> m;
        for (int x = xLo; x <= xHi; x++) {
          tiles[x+y*cols] += c;
        }
        tiles[xLo+y*cols] += c;
        tiles[xHi+y*cols] += c;
      }
    }
    // northwest
    else {
      // NW and SE corner
      int dx = x2 - x1;
      int dy = y2 - y1;
      int m = 8;
      int k = (1<<m) * dx / dy;

      int minx = x1 << m;
      int maxx = (x1+1) << m;

      for (int y = y1; y <= y2; y++) {

        if (y<y2) minx += k;
        int xLo = minx >> m;
        int xHi = (maxx-1) >> m;
        if (y!=y1) maxx += k;

        for (int x = xLo; x <= xHi; x++) {
          tiles[x+y*cols] += c;
        }
        tiles[xLo+y*cols] += c;
        tiles[xHi+y*cols] += c;
      }
    }
  }
}

```
> 0 votes

---
Tags: tiles, path-finding
---


# Question
Title: How to calculate the vector direction to point , so the object will move to
i like to be able to calculate the vector values from object A to destination position. For Example in this image object A to destination B . What will be the x/y positions all the way until it reach distention B. where the x,y origin is in bottom left side

# Answer
If you just want the the vector from 'A' to 'B' thats 'C = TargetPos - StartPos = B - A', no matter how they are orientated.

If you want a function to return a position on this line between, that's 'pos(x) = StartPos + (TargetPos - StartPos) * x = A + C * x', where either x is a number between 0 ( lower you would have a point further away from B) or 1 (higher means you went through B and got further).

Most of the time your 'C' gets normalized, so still points in the same direction, but has 'length = 1', so `C_n = C / Length of C`. . In that case x should be between 0 and 'Lenght of C'.
> 1 votes

---
Tags: movement, vector
---


# Question
Title: Move object towards the center of coordinating system
I would like to move a object towards Vector2(0, 0), but every time I use this script, the object always goes down, instead of going towards the center of the coordinate system.

```
        void Update()
         {
    //Object rotation
             if (!Input.GetMouseButtonDown(0))
             {
                 _angle += speed * Time.deltaTime;
                 var offset = new Vector2(Mathf.Sin(_angle), Mathf.Cos(_angle)) * radius;
                 transform.position = _centre + offset;
             } else
             {
//Moving object towards center
                 rb.transform.position = Vector2.MoveTowards(transform.position, Vector2.zero, speed * Time.deltaTime);
             }

```

# Answer
Your objects rigidbody is being affected by gravity. Either set the rigidbody's type to **Kinematic** in the inspector, or set the gravity to zero from **Edit** --\> **Project Settings** --\> **Physics2D** --\> Gravity

**Note**:I assume you are working on 2D. Hope this helps!
> 0 votes

---
Tags: unity, 2d, vector, coordinates
---


# Question
Title: What causes undefined geometry to be drawn?
I am currently using the polygonSpriteBatch of libgdx to draw triangles, rectangles and a concave polygon as border. After adding the concave polygon for the colored borders everything seems to break and random geometry appears (sometimes even with a gradient).

Some Examples

Here you can see on the left everything looks good and after drawing the additional rectangle with its border and removing the other borders you can still see some weird red regions. This is even more extreme. On the left part of the concave polygon is drawn with a different color, and after it despawns (on the right) there is still part of it left and other triangles not created by me are drawn.

I am quite confident that all convex polygons are defined in counter-clockwise ordering.

In the past I had trouble with providing the correct TextureRegion and it still doesn't feel like my current implementation is how it should be, but it worked for simple rectangles and triangles. Currently I have a (3px)\*(3px) Region and all polygon vertices are between (0f,0f) and (3f,3f).

Because I define all triangles of the polygons myself the short array given to the PolygonRegion for a rectangle looks like this: (0, 1, 2, 3, 4, 5) and the corresponding Vector2 polygon array like this: ((0.0, 3.0), (0.0, 0.0), (3.0, 0.0), (0.0, 3.0), (3.0, 0.0), (3.0, 3.0))

I experienced even more artifacts when executing this on android and for some reason drawing a small rectangle for each vertice (for debugging) fixed some of the artifacts above.

This is quite a complex problem but I hope somebody knows what could cause such a behaviour.

# Answer
> 1 votes
I fixed it, the problem was the missing `/2` in this function:

```
public static short[] getDefaultTriangles(float[] polygon) {
    short[] triangles = new short[polygon.length/2];
    for (short i = 0; i < triangles.length; i++) {
        triangles[i] = i;
    }

    return triangles;
}

```

Which resulted in my triangle arrays having the same length as my polygon arrays.

---
Tags: libgdx, opengl-es2
---


# Question
Title: Is there any way in game maker to pass argument parameters to strings executed via the execute_string() function of version 8.0 (pre-studio)?
**Last I checked, the game I'm modding was compiled\* using Game Maker 8.0**

So for a little set up, here is my situation. There's a game out there which has a box in which you can enter a string and it executes it. I decided to try and mod the game through use of this cheat box along with some other objects which execute strings and whatnot.

In general, this is all essentially powered by the built-in function 'execute\_string'. My main problem is that as far as I know one cannot pass arguments to these executed strings, which is essential to anything complicated\** I might wish to do.

I know there is a similar function called execute\_script which allows for argument parameters to be passed into the code being executed. However, adding scripts as rescources is one of the many things that get "flushed" out of memory when saving/loading using the default save system. I am definitely not interested in reloading code from files on the fly and I don't want to make my own save system (which would still require code to be loaded from files) as I would prefer to basically have to use a save file and a few 3D model/image files to send the mod to anyone else who might be interested in it. I could also send the raw source, but regardless I don't want a lot of unstable resource manipulation.

> So basically, is there a way for me to pass arguments into the code being executed with "execute\_string" without having to implement my own function stack memory space and do the pushing and popping of arguments manually?

---

\*The game was made many years ago in game maker 6.0. I believe it was recompiled for efficiency purposes.

\**For instance, a very common technique to make some more complicated enemies or buildings is to make your own dynamic memory allocator using an array as a virtual memory space and use the interfaces of raw memory allocation to build lists and trees or whatever else you need. That is definitely something which requires a *lot* of different function calls.

# Answer
**Here is a different answer, which might be more inclined towards what you wanted.**

Read. The. Documentation.

From The GM 8.0 Docs/Game Maker Language/Changing Rescources/Scripts

> execute\_string(str,arg0,arg1,...) Execute the piece of code in the string str with the indicated arguments.

I'm just going to point out the need to whenever one does programming and wants to do something that might just be an unknown feature... to read the documentation. That's what it is for.
> 2 votes

# Answer
**Here is a *potential* solution:**

Before any functions you wish to call:

```
FUNCTION_STACK[RECURSION_LEVEL+1,0] = arg_0;
FUNCTION_STACK[RECURSION_LEVEL+1,1] = arg_1;
....
FUNCTION_STACK[RECURSION_LEVEL+1,n] = arg_n;

```

At the beginning of any "functions" you wish to call, do the following:

```
RECURSION_LEVEL += 1;
//arguments found in "FUNCTION_STACK[RECURSION_LEVEL,__]"

```

When the function ends do the following:

```
RETURN_VALUES[RECURSION_LEVEL-1] = return value;

```

This is a pretty weird solution, but it should emulate the idea of calling user-defined functions.
> 0 votes

---
Tags: game-maker
---


title: Collison detection trouble. (c++ SDL2)

text:
# Question
Title: Collison detection trouble. (c++ SDL2)
I have a small trouble with my collsion detection system, ill show it on images. im checking the detection by using that logic with example when moving to the right:

```
obj.x+obj.w+obj.mov > block.x
obj.x+obj.w+obj.mov < block.x+block.w
and
(
    obj.y <= block.y
    obj.y+obj.h >= block.y
    or
    obj.y <= block.y+block.h
    obj.y+obj.h >= block.y+block.h
)

```

when object size and block size are equal, the problem appears

the 3 blocks are detected

1 = is the trouble maker

2 = isnt making much problem, since its on same axis

3 = is working

the 1 block is detected since its within Y + H area of the block (

it happens when the object is sticked with 0 pixel distance.

im using motion based on min(mov,dist) \[dist is Y distance between object and block\] function and when it tries to move to the right, it gets moved like that

because min(mov,dist) will become negative when getting distance to object 1 instead of 3, making it buggy

im asking if its possible to prevent block 1 (block 2 optionaly) when that situation happens. (or atleast change the logic)

# Answer
> 2 votes
i have solved it, logic should look like this

```
     obj.x+obj.w+obj.mov > block.x
     obj.x+obj.w+obj.mov < block.x+block.w
    and
    (
        obj.y <= block.y
        obj.y+obj.h >= block.y
        or
        obj.y <= block.y+block.h
        obj.y+obj.h >= block.y+block.h
    )
    and
     obj.y != block.y+block.h
    and
     obj.y+obj.h != block.y

```

# Answer
> 3 votes
At a glance, your code is doing what it's supposed to, which is detecting collisions (distance between 2 edges \<= 0).

It sounds like you want to detect *intersections* instead, which is two AABB's overlapping. In which case, change:

```
and
(
    obj.y <= block.y
    obj.y+obj.h >= block.y
    or
    obj.y <= block.y+block.h
    obj.y+obj.h >= block.y+block.h
)

```

To:

```
and
(
    obj.y < block.y
    obj.y+obj.h > block.y
    or
    obj.y < block.y+block.h
    obj.y+obj.h > block.y+block.h
)

```

---
Tags: c++, collision-detection, sdl2, logic
---


# Question
Title: Why don't game companies buy 3D models of cars from the respective car manufacturers?
My friend is working in a game company in India. They are developing 3D car models for racing games for other companies. They create their own car models right from the beginning.

I asked my friend "why are game companies not buying 3D models of cars from the respective car manufacturers? Why they are outsourcing it to other 3D modeling companies or creating on their own?"

He doesn't know the answer... So I am asking here.

# Answer
> 1 votes
Every company is likely to have slightly different reasons to want to build their own 3D models of cars. One reason they will all likely have in common at some level of priority is that the design of a car is something covered by intellectual property rights in most places, and that means that the game developer must obtain the legal rights to use the car designs in a game.

That is potentially a very involved legal process (getting in touch with the right people at the car company, negotiating licensing deals, making sure the deal covers all the important rights each party would need to obtain, et cetera). This tends to be extremely expensive both to pursue, and then ultimately to execute on (to pay for the license).

It's thus not likely to be considered extremely important to have real life cars in a game, since it's usually not something that constitutes a "killer feature" and the cost to get there doesn't usually balance out the payoff.

Other reasons a company may want to simply build their own models (including reasons why the deal might fall through) could be:

* the game company might have the *money* on hand to pay for the aforementioned legal processing, but they might not have the *time* to wait for it to happen
* no deal may be available that satisfies the game company's needs; for example, the car company may only be willing to offer a license for three years, after which point the developer must cease use of the cars, thus potentially forcing the developer to stop selling the game at the end of the license agreement (for reference, consider how Alan Wake was recently pulled from Steam due to expiration of some music rights)
* getting a licensing deal with one car manufacturer may prevent (financially or legally) getting a deal with another manufacturer
* the 3D models car manufacturers have on-hand may only be extremely high-resolution CAD models or some such, suitable for their needs, but quite unsuitable for the needs of a high-performance game; the game company will thus need to employ artists to streamline those models for in-game use, and they may be hamstrung by legal clauses in the contract regarding how much they can modify the art
* the game's setting may not lend itself to having real-world cars in it anyway

Note that in the case of your friend's company, which is doing outsourcing work for *other* companies, it may be even harder or more expensive to obtain rights to use the car models (to build appropriately game-ready models). That's because your friend's company probably needs to obtain both the rights to *use* the car designs *and* to redistribute those designs and licensing to other studios. That's a powerful right that many car companies, indeed may companies in general, are unwilling to part with cheaply or at all.

---
Tags: licensing
---


# Question
Title: When should I acquire game objects with dependency injection, find-with-tag, or singletons?
This is sort of a best practice/efficiency kind of question, and I haven't really seen any other question talking about these three things together.

Essentially, Dependency Injection, Find with Tag (like the Unity function), and Singletons are all ways of acquiring globally required game objects (like for instance, a sound manager or the player object).

For each, in which case does it make sense to use one over another? (I'm aware it's quite an open question, but I am looking for aspects which typify the situations in which you might use one over another).

Why is each better or worse for doing the job of acquiring a globally required object?

Are there any other methods of doing this not mentioned here?

# Answer
**Dependency injection**, in some form, is almost always the solution I would reach for first. DI approaches to providing access to objects have some clear benefits:

* they are usually fast: the consuming code is directly given a reference to the dependencies and can usually cache those references, so no further lookups need to be done in the consuming code.
* they are self-documenting: the dependencies of the consuming code are clearly listed in the code itself as part of the structure of the code, which usually makes it obvious when you've broken something via a refactor, and helps indicate to a future reader of the code what that code is supposed to have jurisdiction over (and by exclusion, what that code should *not* be able to do).
* they do away with the assumption of globality of the dependency objects: DI approaches, unlike your other two cited methods (usually), don't assume that there is one global version of some dependency, which can give the consuming code some flexibility for future expansion or for isolation (in the case of unit tests, for example).

An oft-cited downside to DI approaches is that they involve passing "some thing" to "every other thing." This can be a downside, especially when refactoring large existing codebases that rely on some other method of access to dependencies. However, on balance it is also usually a strong indicator of a potential design flaw (the fact that "everything" depends on some object is an implication that code may not be well-factored).

I tend to use DI approaches to pass around dependencies in game code: giving certain systems access to other systems, or certain objects access to sibling objects (e.g., rendering components that depend on reading data from physical components get a reference to the corresponding component via the constructor).

**Singletons** are about enforcing the existence of a single object and providing global access to it. They have the advantage of being easy to use, and easy to proliferate: if you need to access some object at some point in the code, you don't have to worry about plumbing a reference to that object all the way through from where it originates to where you need it.

On the other hand, one could argue that that ease creates problems: by not having to think about how to get an object to where you want to use it, you don't have to think about whether or not that is creating a bad, overly-coupled design. Further, any such dependency is harder to find, as it's buried randomly in the consuming code where-ever somebody chose to access to the singleton, and isn't always apparent by simply browsing the interface of that consuming code.

Finally, depending on the language you are using and the method you are using to implement a singleton, they can have some technical issues since they are a global object: multithreaded access can present some issues that in some cases cannot be solved except by taking a lot of locks, and initialization order of the object can require some careful planning in languages like C++ which have interesting static object initialization ordering caveats.

I would generally never recommend a singleton, personally, and do not use them.

**Find-via-tag** (or in general, lookup via some well-known identifier) is an interesting middle-of-the-road approach. Depending on how the lookup is done, it could be more costly than the simple direct access usually offered by DI solutions. Depending on the implementation of the backing storage for the objects, it may not be possible for consuming code to cache the looked-up reference, thus requiring constant re-fetches.

It is also possible for lookups to fail, since they are generally done at runtime, and thus it is harder to verify the compile-time correctness of any consuming code. Such code often requires more protection and error-checking scaffolding to ensure robustness; removing an object entirely from the code base *may* not immediately present a compile-time error in code that looked up that object at runtime, if the code is only checking for existence of that object and not actually calling any methods or whatever on that object's interface.

But find-via-tag can be used as an bridging mechanism allowing it to steal some advantages from the other two approaches. For example, an "object locator" object could be passed via DI to consuming code, which then uses it to look up the specific objects it needs. This gives you a place to insertion some isolation into the code, freeing you from assumptions that there is one instance of every dependency object, but also retains some of the ease-of-use of a singleton.

I often use this approach in editor framework code to provide a service-locator object that can be used for plugins or modules to request access to the editor services (transaction or undo service, notification service, et cetera).
> 3 votes

---
Tags: architecture, software-engineering, oop, dependency-injection
---


# Question
Title: What is Google Play Services Multiplayer?
This question might be off-topic, i don't know where should i ask it.

What's the difference between Google Play Real-Time Multiplayer, Google Play Turn-Based Multiplayer and sockets?

# Answer
Google Play's Real Time and Turn-Based multiplayer provide a high-level framework supporting real-time or turn-based multiplayer in your game, respectively. They offer you ways to perform peer-matching and invitation and state updating, as well as providing a pipeline upon which you can build the actual game-specific networking on, if you want.

"Sockets," on the other hand, are a low-level networking concept that allow you to open connections to other devices and transmit arbitrary data back and forth.

Google's services are built *on top of* sockets, and are thus higher-level and easier to use. If you eschew them in favor of using lower-level sockets APIs, you'll be doing a lot more work yourself to re-implement everything Google's services are providing for you.
> 0 votes

---
Tags: android, networking, multiplayer, google-play-services
---


# Question
Title: Why can I sometimes access Static objects' elements and sometimes not?
I'm making a game in Unity and I learned to make my Player object static for reference by other objects quickly and easily. So I have a "public static Player player." I remember when I first made this and began referencing it, some scripts were telling me that I could not access certain things without a local instantiation. So I made a Player p and set it equal to Player.player and it then allowed me to reference its functions and variables. It seemed like I could have some kind of access like reading not writing or just accessing variables but not function calls without a local reference, but I later found I could access anything without the local reference. I was then able to get rid of the local references completely in scripts that were originally not able to access the elements without it. I have no idea what changed. Now, however, I'm making a static SaveData object and I'm running into the same issue. Things I'm accessing with Player.player is not working with my SaveData.saveData. What is going on? What could possibly be different? When can I and can't I access this stuff without a local reference?

# Answer
> 1 votes
You might be confusing the concepts of **Access** (who is allowed access data) and **Allocation** (where is data stored in memory). I hope the following explanation clears things up for you!

# Access

Access refers to *who is allowed to access objects of an object*. You can specify this for both data ("who can read/write a variable?") and functions ("who can execute this function?") You will use three keywords for this:

* **Public**: any other object can see this variable/function
* **Protected**: only the object itself and derived classes can see this variable/function
* **Private**: only the object itself can see this variable/function

Here's an example to grasp the concept:

```
class Enemy {
private:
    unsigned int m_id;
protected:
    unsigned int m_health;
public:
    void DamageMe(unsigned int damage_amount);
};

```

Let's say you have a class called *Enemy* that represents an enemy in your game. You want to give each enemy a unique ID, so you can retrieve it later. This ID is assigned upon creation via the constructor, and you never want it to change! Therefore, you mark it as **private**. This way, only the enemy class can initialize the ID, and it can not be messed up by derived classes or other classes.

Additionally, you want to store the enemy's health. We don't want any other object to go change the enemy's health willy-nillily, as we wanna be sure to trigger the right animations, and invincibility frames when the enemy gets hit. However, if we later decide to implement a more specific enemy that derives from the *Enemy* class, it should be able to modify its health. You might for example create `class HealingEnemy : public Enemy` that heals itself up from time to time. Therefore, we mark it as **protected**. This way only the class itself and its derivatives can change the variable.

Finally, we want to be able to damage the enemy. We do this via a clean function, so that we can take care of animations and invincibility frames. We want any other game object to be able to cause damage to the enemy. Therefore we mark the function as **public**. This means any object that has a reference to the variable can execute the member function.

# Allocation

Allocation refers to where data is stored in memory. There are two options:

* **Member/Local**: the data / function applies individually to each instance of the class
* **Static**: the data / function is shared among all individuals of the class

Here's an example to grasp this:

```
class Enemy {
    unsigned int m_health;
    static unsigned int number_of_enemies_created;

    void DamageMe(unsigned int damage_amount);
    static unsigned int GetNumberOfEnemies();
};

```

Let's say we create 3 instances of the class Enemy. We want each of these to individually store their health. After all, if we punch one enemy in the face for 5 damage, we don't want the health of the others to change. Therefore we use a **local/member variable** (no keyword used to specify this). By typing `my_enemy_1.m_health` we will get the health of that specific Enemy instance. Notice that we use a specific instance of Enemy to access this variable to specify which enemy we want to retrieve the health of.

Additionally, we want to keep count of how many enemies we have created. This number doesn't really belong to a specific instance of the Enemy class. It's a property of the class itself. Therefore we use a **static variable** (using the *static* keyword). By typing `Enemy::number_of_enemies_created` we get the total number of enemies. Notice that we don't specify a specific instance name to access this variable! We use the class to access this static variable.

Similarly, we can mark functions as local (no keyword) or static (static keyword). We want the function `DamageMe` to apply to one specific enemy, not all enemies at once! In contrary, `GetNumberOfEnemies` applies across all instances of the Enemy class, therefore we mark it as a static function. Calls to these functions would look like this: `my_enemy_1.DamageMe(5);` and `Enemy::GetNumberOfEnemies();`. Once again, notice how we use a specific instance's name in the local case, and the class name in the static case.

# Where access problems can occur

From the information you've given, I can really see what exactly is going on. There's one problem that causes access problems that often occurs when using static functions/variables. You cannot access local/member properties from a static function!

Let's say you are implementing the `void DamageMe(unsigned int damage_amount);` function:

```
void DamageMe(unsigned int damage_amount) {
    m_health -= damage_amount;
    if (m_health <= 0) { number_of_enemies--; }
}

```

This will work just fine. As DamageMe is a local/member function, it is executed on a specific instance of the Enemy class (e.g. *my\_enemy\_1*). The compiler therefore knows whose "m\_health" to reduce. Additionally, if the enemy dies, we can reduce the *number\_of\_enemies* counter by one, as it is a property of the class, there is only one of this variable.

Now let's say we implement `static unsigned int GetNumberOfEnemies();` like this:

```
static unsigned int GetNumberOfEnemies() {
    PrintMessage("My health is: " + m_health);
    return number_of_enemies;
}

```

Your compiler will violently complain reading this. We are trying to print the enemy's health, and then we return the total number of enemies. This last part is fine. We can retrieve a static variable in a static function, as there is only one copy of the *number\_of\_enemies* variable. When we try to retrieve *m\_health*, things go wrong. The compiler has no way of knowing what instance of Enemy you are trying to read the health of. After all, its a static function (and it is called as Enemy::GetNumberOfEnemies()). There might not even be an instance of enemy yet!

I suspect that this is what is going wrong in your code. To fix it, consider whether you really need your Player class to be static. Maybe there is a different way to retrieve it. For example you could have a different object keep track of all player instances in the game world with an interface such as:

```
class PlayerTracker {
    static std::vector<Player*> m_players;
    static void RegisterPlayer(Player* player);
    static Player* GetPlayer(unsigned int id);
    static std::vector<Player*> GetAllPlayers();
}

```

You could even add all of these functions to your player class and keep the Player class members itself non-static. Hope this helps!

# Answer
> 0 votes
Okay, I figured it out. I knew the right way to do it but it turns out I wasn't actually doing it the way I knew to do it. The problem was that I was trying to reference the non-static elements directly rather than going through the static element within it. For example, I was trying to reference SaveData.someArray\[i\] rather than SaveData.saveData.someArray\[i\]. No one could have known that of course, especially since I claimed I was doing it right in the question. I'll mark the other answer as right since it does hold all the correct information.

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


title: SpriteKit and Swift or Objective-C

text:
# Question
Title: SpriteKit and Swift or Objective-C
As a newbie to iOS programming, I'm wondering which of these would be more conducive to the type of game I want to program. I've been tasked to program an iOS game for my company. They asked me to do this after learning I was studying some Swift on my own time.

The game will be a turn-based strategy game consisting of a map with irregular areas/polygons and player pieces that can be moved on the map. I'll need to be able to detect when a piece moves into different areas and restrict a piece to moving only a certain number of areas per turn.

Can this be accomplished in straight Swift/Spritekit?

# Answer
> 0 votes
The graphical part can be achieved in SpriteKit very easily. To detect/restrict movement you can use Apple's Gameplay Kit, which is "generic" in the sense that it can be used with any graphic SDK, let is be SpriteKit or any other graphic library available in Swift.

You may want to check: Path finding in Gameplay Kit.

---
Tags: ios, objective-c, spritekit, swift
---


# Question
Title: How do I play local user-provided audio files on an Android or iOS device?
I'd like to allow a user to select a path to local audio files, in Android and iOS devices. Is there a way I could provide a list of available songs, in Android or iOS devices, so the user could pick and play them?

# Answer
May be an issue due to security considerations on the devices. You can certainly try using System.IO.Directory and System.IO.File to look around, but you'll need to adjust the 'root' paths for the different devices. IOS and Android don't share the same directory structure, and I very much doubt iOS will let you look around much at all.

You could try using the **www** class to load a *file:* (local file) URL - such as *file:/storage/media/musictrack.mp3*. I've known that technique to work in Windows, and according to the post below it can also work on Android. Again, iOS may be an issue - how do you copy an MP3 file to an iOS device without iTunes?

http://answers.unity3d.com/questions/334907/how-to-www-a-file-on-android.html
> 0 votes

---
Tags: unity, android, ios
---


# Question
Title: How are these physics formulas translated to this code?
So how exactly does something like \\$v\_f = v\_i +a\*t\\$ translate to something like `self.vel += self.acc` in code? or \\$d=v\_i\*t+\frac{a\*t^2}{2}\\$ translating to `self.pos += self.vel + 0.5 * self.acc` there seems to be variables missing, and summations happening that aren't part of the formulas.

# Answer
> 1 votes
The formulas you're showing translate like that because some values are implicit, which removes the need to explicitly use other values. Read on!

Let's recap what these formulas are, based on where you have most likely picked the original images:

\\$v\_f = v\_i +a\*t\\$ and \\$d=v\_i\*t+\frac{a\*t^2}{2}\\$

where

* **vf** indicates the **final velocity** of the object;
* **vi** indicates the **initial velocity** of the object;
* **a** stands for the **acceleration** of the object;
* **t** stands for the **time** for which the object moved;
* **d** stands for the **displacement** of the object.

And let's see how they are implemented in the tutorial you've linked to:

```
self.vel += self.acc
self.pos += self.vel + 0.5 * self.acc

```

Finally, let's compare these implementations using the formulas:

```
vf = vi + a
d = vi + 0.5 * a

```

What's missing? The references to `t` (time).

It is because, in this particular situation, the time is assumed to be constant (a frame rate of 60Hz, each frame lasting 1/60th of a second). The tutorial is using pygame. Without going into the details, pygame allows to throttle the frame-rate to a desired frequency, and that's what is done in the tutorial. So all the explicit references to time are removed because they're implicit in the other parameters. The acceleration in that tutorial *units per 1/60th of a second* and not *units per second*.

This can be done when using a fixed time step, that is, when each frame is expected to have the same duration. Some 3rd party game infrastructure support this (pygame is an example, Unity too, with the FixedUpdate method), while others don't (e.g. the Update method of Unity). In this case, the "delta time" is passed to the Update method and this value should be used with the 'normal' formula to manage the displacement of objects.

As per DMGregory's comment, this can add confusion, specially when the code is not well documented. You should generally use 'standard' units such as meter per seconds, kilometer per hour, radians per seconds, rotations per minut and such, until you're at the point where you have to manage the value on a per-frame basis.

---
Tags: physics, mathematics
---


# Question
Title: How to detect when object A In point B place
i have object which is moving to points in the screen each time the point ( call it B)
is moving to different place and object A follow its direction . Im using Linear interpolation and simple pythagoras equation to find the vector to point B
what i have problem now is to find the location where object A should stop when it In point B place point B its just x/y location . point b can be any where on the screen

# Answer
Unless you're running on extremely slow hardware or dealing with incredibly fast objects, checking per-frame should be fine as long as you aren't looking for an **exact** hit.

It's best to check the distance between A & B, then see when the point is within the radius. For example, if object 'B' is 3 units wide, check if the line between 'A' and 'B' is less than 1.5 units long. That would indicate a collision.

If you're using a 3D engine such as Unity, you can handle this using colliders.

If you MUST check for collisions 'between frames' calculate the line of the objects travel between where the object currently is, and where it *will* be (ie compare each new set of interpolated points with the previous set), and see if that line would have passed through a sphere or box centered around point B.

This is easier for 2D than 3D, but it can be done - see https://stackoverflow.com/questions/5883169/intersection-between-a-line-and-a-sphere for some examples.

Again, if you're using a 3D engine such as Unity, you can handle this using colliders and Physics.Raycast.
> 1 votes

---
Tags: vector, objects
---