title: Input-like Paper-io.io Unreal Engine

text:
# Question
Title: Input-like Paper-io.io Unreal Engine
I'm making a copy of the game "Paper-io.io" as an exercise, since i'm new to Unreal Engine and C++. Actually i'm having trouble making the Pawn/Player move like it should in the real game. When the game begins the Player moves in a way that could be forward, backward, left, right, whatever (it is randomly choosen) without pressing any button (WASD). If the Player doesn't press any button in the meanwhile, he'll end to hit a wall, so when he press a button/key that is not the direction the player is going, will turn and will go to that way until he'll press another button to turn that is not the opposite one, because he cannot go backward if he is going forward, and same happens if he goes left can't go right, and so on. Any idea? So far, i tried to use BindAction but the attached method will be called just on press/release button/whatever.

this is just an example of what i've done but as i said, it is not called everyframe:

```
void APlayerTile::MoveX()
{
    FVector NewLocation = FVector(PlayerLocation.X, PlayerLocation.Y - Speed, 26.0f);
    this->SetActorLocation(NewLocation);
    PlayerLocation = NewLocation;
}

```

# Answer
> 3 votes
For people who've not played paper.io, it operates like Snake. In order to achieve this type of movement, you need to separate your every-frame movement from player input.

In order to do this, you'll need to store which direction your pawn should currently be moving in. You can do so in whichever way strikes your fancy -- an enum, vector, ect. In your player input actions, like the MoveX example you've given, THAT is what should be changed. Based on the input action, set that variable to the new direction.

Now you'll need to use another Pawn method, Tick. The Tick method is the one that's called every single frame. Inside of Tick, you'll want to move the pawn in the direction indicated by the variable you've stored. This way, your pawn moves every frame, and every time the player presses a button to change direction, the pawn will react and change direction.

Basic code sample by popular request!:

```
//inside PlayerTile.h
enum EMovementDirection {
  UP,
  DOWN,
  LEFT,
  RIGHT
  }

  private EMovementDirection CurrentMovementDirection;

  //inside PlayerTile.cpp

void APlayerTile::MoveRight() //Add more for other directions
{
    if (CurrentMovementDirection != EMovementDirection::LEFT)
        CurrentMovementDirection = EMovementDirection::RIGHT;
}

void APlayerTile::Tick(float DeltaTime)  //This block happens every frame
{
    FVector CurrentLoc = this->GetActorLocation();

    if (CurrentMovementDirection == EMovementDirection::LEFT)
        this->SetActorLocation(CurrentLoc + FVector(CurrentLoc.X, CurrentLoc.Y - (Speed * DeltaTime), CurrentLoc.Z));
    //etc for other directions
}

```

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


# Question
Title: What edition of VS is installed by Unity and what are its capabilities?
My brother just installed Unity on my desktop, and it seems like it installed Visual Studio 2017 as well.

I was planning to install Visual Studio before this, so I was wondering what kind of version is this edition of VS? Is this like a bare-bones version? Does it work like a standalone version without lacking features? Can I use it just as a regular IDE to program in?

I typically program in C++, and I never used Unity before, so I'm not sure if this version of VS is only suited for Unity.

# Answer
> so I was wondering what kind of version is this edition of VS?

It's most likely VS 2017 Community Edition if Unity is the 2017 version. AFAIK Unity 5 uses VS 2015, so that could be it too. You'd have to open it and see the version text at startup or in help / about section.

> Is this like a barebones version? Does it work like a standalone version without lacking features?

No. The Unity API is in there and it can be attached to Unity to work with it. Other than that it does what a standard VS 2017 does.

> Can I use it just as a regular IDE to program in?

Yep, there shouldn't be anything in there that would stop you from doing that.

> I typically program in C++, and I never used Unity before, so I'm not sure if this version of VS is only suited for Unity.

It's not *just* for Unity, but still, you might need some additional stuff for C++ programming. The C# programming bit should work as expected and it did as far as I could see.
> 2 votes

# Answer
The version of Visual Studio Community Edition which comes with Unity is pretty barebone. It only includes the core components and the package for Unity game development. So in that state it can not be used for much more than Unity scripting.

However, you can easily install the packages for many other programming language. Simply try to create a new project and in the selector for a project template click on "Open Visual Studio Installer". You can then download and install the C++ package. You will then have C++ project templates available.
> 1 votes

---
Tags: unity, c++, visual-studio
---


# Question
Title: Java - LibGDX low fps on completely empty project
I started working on a really really small prototype and when I ran the application i noticed the FPS was only half of what it's supposed to be at. FPS stays at around 30-31 instead of 60 - even when I literally erased all code from running sitting with an empty project it's still 30. I even tried to import an old project which used to work fine with high fps but it also runs at 30.

I also tried importing a LWJGL project and it worked fine with 60 FPS.

I've tried restarting my computer as well and other games run fine on my computer. Note that I've developed in LibGDX for quite a long time and never encountered this before - any help is appreciated!

# Answer
> 1 votes
The program was running slow because of a graphics driver that had stopped working. A reinstall got things back up running again! If you're in the same position as me, do what Alexandre suggested and check your nVidia settings. Also make sure that your current graphics driver is working. I noticed mine was broken when I tried to enter my settings by right-clicking the desktop and going into the "AMD Radeon Settings" and was met with an error.

To reinstall download "DDU", a display driver uninstaller. Disable all of your anti-vrius/anti-malware etc and run the program. It will create a system restore point and uninstall the graphics driver. Then download the driver again manually from the internet and things should be working!

Don't forget to enable the anti-virus again when you're done!

---
Tags: java, libgdx
---


title: Rotating a gameworld using quaternion

text:
# Question
Title: Rotating a gameworld using quaternion
I'm a hobbyist programmer at best and I had an idea I wanted to test in Unity, I wanted to rotate the game world around 90 degrees, to this end I've been learning a tiny bit about quaternions, in this simple test I have a empty game object at position 0,0,0 and 2 cubes placed so only one will be in the foreground at once (both children of the empty game object). I simply want to rotate the parent object on a mouse up like so.

```
if (Input.GetMouseButtonUp(0)) {

        Quaternion newrot = Quaternion.Euler (0,90,0);
        transform.rotation = Quaternion.Slerp (transform.rotation,newrot,0.05f);

    }
}

```

The problem I am having is that this does not do the rotation in a single click and never reaches 90 degrees, it only ever tends towards 90 (for fun I decided to click for 2 minutes and only got up to 89.99999 ... well you get the picture).

Can someone tell me what I am doing wrong and if there is a better way of doing this?

# Answer
It looks like you're treating the Slerp method like you're starting a tween. "Start a new tween animation from here to there at this speed, okay... Go!" - with the expectation that it will carry out its work in parallel over the subsequent frames.

Slerp isn't that kind of method. It's just a math function that takes some inputs and gives you an output, exactly once, the frame that you call it, and never again until you explicitly call it again.

You can build your own tweening routine if you like. It would look something like this:

```
[Tooltip("Rotation speed in degrees per second")]
public float rotationSpeed = 180f;

Coroutine _turn;
Quaternion _targetRotation = Quaternion.identity;

void Update() {

     // Using "Button" instead of "MouseButton" lets you or the
     // player re-map this turn control without changing code.
    if(Input.GetButtonUp("Turn")) {

          // Increment our destination rotation by another 90 degrees.
          _targetRotation *= Quaternion.Euler(0,90,0);

          // If our tweening routine is already running, it'll handle this.
          // Otherwise, we'll start an instance of it.
          if(_turn != null)
              _turn = StartCoroutine(TurnToTarget());
    }
}

IEnumerator TurnToTarget() {

    // Like a lot of floating point, waiting for exact equality here can
    // let us get stuck. So we'll wait till we're "close enough".
    while(Quaternion.Dot(transform.rotation, _targetRotation) < 0.9999f) {

         // Rotate towards the target at a controlled rate over time.
         transform.rotation = Quaternion.RotateTowards(
                                     transform.rotation,
                                     _targetRotation,
                                     rotationSpeed * Time.deltaTime);

         // Let the game run another frame before we loop again.
         yield return null;
    }

    // Snap our rotation exactly to the target,
    // in case we still had a few decimals off.
    transform.rotation = _targetRotation;

    // Mark the rotation action as complete.
    _turn = null;
}

```

Note here I'm using the convenience method RotateTowards to get a controlled rotation speed. You can do this yourself with Slerp, taking on the speed adjustment math yourself. You can also use different easing functions to vary the speed of rotation over time, rather than keeping it exactly uniform.
> 1 votes

# Answer
*I'm not able to test it right now (I'm on my phone).*

---

I think what is happening is that this happens because each time you ask it to go from the current transform to the target transform, you specify the same percentage related to he scale (t).

Think of the "trick" question asking how long it would take to a ball that you drop to stop bouncing if each bounce is half the height of the preceding one. (Answer: it will never stop.)

To use the slerp method, you have to fix the starting and the end value, and make the t value change. (In your case, you make the end and the t value fixed and the start only changes.)

I suggest you take a closer look at the Quaternion.Slerp documentation. You'll notice they make the t value evolve with time.
> 0 votes

---
Tags: unity, c#, rotation, quaternion
---


title: Animation with drawImage vs canvas

text:
# Question
Title: Animation with drawImage vs canvas
I have a canvas that draws the letter 'a' with a box:

```
 var cxt = document.getElementById('someCanvas').getContext('2d');
 cxt.strokeRect(someX, someY, someWidth, someHeight);
 cxt.fillText('a', someX, someY);

```

if I want to animate this to move and not leave the previous drawn canvas behind, I will need **clearRect** and re-draw it again:

```
 cxt.clearRect(someX, someY, someWidth, someHeight);
 //cxt.strokeRect..
 //cxt.fillText..

```

However, with drawImage, I can just increment its x/y without needing to clear/re-draw it again:

```
 cxt.drawImage(src, someX, someY);

```

I was wondering, would there be any performance difference of these two methods if I wanted more letters/others? Does **drawImage** clear itself the same way as **clearRect**?

# Answer
> 1 votes
`drawImage` doesn't clear the canvas. It would make drawing the same image multiple times impossible. You probably think this, because images with borders around the main parts of it "clear" (or rather overwrite) the already drawn ones.

Here's a demo just so you see it in action

---
Tags: javascript, html5
---


# Question
Title: Cannot modify a value type return value of `UnityEngine.Transform.position'. Consider storing the value in a temporary variable
I'm getting the following error

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

with this code:

```
transform.position = new Vector3(target.position.x, transform.position.y, target.position.z);
Vector3 desiredPosition = new Vector3(transform.position.x , target.position.y, transform.position.y );
Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
transform.position += smoothedPosition;

```

# Answer
> 0 votes
If you want to modify the `transform.position` property, you have to modify the `transform.position` property: it's values are effectively read-only. This is due to the fact that Unity Vectors themselves are *value types* and not instanced objects. What you're trying to do is similar to doing `4 += 1` which makes no sense.

```
Vector3 pos = transform.position;
pos.x = target.transform.position.x;
transform.position = pos;

```

# Answer
> 0 votes
You can only store whole vectors to gameObject.transform.position

Position is read-only in all other contexts.

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


title: Blood splatters on a terrain

text:
# Question
Title: Blood splatters on a terrain
I am trying to create blood effects, where the characters being killed are on an uneven terrain. The simple way is to instantiate a prefab with texture, which uses a plane mesh, on the raycast hit point. But, in this case, this looks quite odd as the terrain has height variance within the bounds of the plane of the blood splatter prefab.

I tried using the projector in Unity, but the issue with using that is that the projector shaders are very simple. In particular, I don't want them to blend into the terrain texture, and wanted to add specularity (to make it look like a liquid).

What is my best option?

# Answer
What you're looking for is a decal system.

I don't know quite how they work in the general sense of "how do you make a decal system" (and each system might be built in different ways) but the *way* it works from a usability standpoint is exactly what you want: textures overlaid on a target surface conforming to its contours. They're generally fast and inexpensive (on system resources) the same way particle systems are, which is why they're used for detail in all sorts of ways (those bits of paper trash on the street in Half Life and Left 4 Dead? Those are also decals).

There's quite a few decal systems available on the asset store and I'm pretty sure I've worked with this one before. It might fill your needs, or one of the others might work better, do a little research.
> 1 votes

# Answer
I am no expert with projectors as I haven't used them a lot myself, but however to achieve what you seek, especially at the uneven terrain part, you'd want to use a projector or at least something similar. While decals can do a lot a projector will achieve the same effect with less efforts. That is where projectors dominate. The material used for the projector can use a shader you like to for example use the standard specular shader with modified values.

You might want to write your own shader with shaderlab or CG depending on what you prefer. But I honestly think that a projector will achieve what you are looking for. By creating a material with the texture and shader you like you can modify a lot values to make each of them look unique.

Projector tutorial: http://talarian.blogspot.nl/p/unity-tutorial.html

Unity docs for projector: https://docs.unity3d.com/Manual/class-Projector.html
> 0 votes

---
Tags: unity, 3d, terrain
---


title: UE4 Navmesh precision

text:
# Question
Title: UE4 Navmesh precision
I'm trying to make my very tiny man pathfind his way through a map of a school but the navmash won't recognize some of the hallways cause they are very narrow like this.

So as you can see the man can fit but the navmesh says no so can anyone help and keep in mind that i am very new to unreal engine so please make your explanation easy to understand.

# Answer
A Navmesh is generated according to so-called "Nav Agents".

These Nav Agents are located in your Project Settings under the "Navigation System" Settings. There you can create a new Agent or edit existing ones.

To make your Navmesh go through narrow corridors, you need to change the "Nav Agent Radius". Keep in mind that if your Nav Agent Radius is smaller than your AI's Collision, the AI will probably get stuck!
> 2 votes

---
Tags: path-finding, unreal-4, navmesh
---


title: Add Lerp on only the Y axis

text:
# Question
Title: Add Lerp on only the Y axis
I want my camera to be smooth on only the Y axis.How do I do that it?

Current code:

```
public Transform target;
public float smoothSpeed = 0.3f;
public float offsetX = 1f;
public float offsetY = 1f;
public float offsetZ = 1f;

void FixedUpdate ()
{
    Vector3 pos = transform.position;
    pos.x = target.position.x;
    pos.y = target.position.y;
    pos.z = target.position.z;
    Vector3 positionz = pos.z;

    Vector3 smoothedPosition = Vector3.Lerp(transform.position, pos, smoothSpeed);
    transform.position = smoothedPosition;
}

```

# Answer
> 1 votes
Just lerp only the y component.

Don't be afraid to just try stuff like this yourself — it's a lot faster to muck with a few formulas and see what they do than wait for an answer from a stranger. ;)

```
Vector3 pos = target.position;

pos.y = Mathf.Lerp(transform.position.y, pos.y, sharpness);

transform.position = pos;

```

Note that to get consistent behaviour under varying framerates, you'll need to adjust the sharpness parameter as explained here.

---
Tags: unity, camera, transformation, lerp
---


title: How can I make a player swims in libgdx

text:
# Question
Title: How can I make a player swims in libgdx
I'm creating a Java game similar to Mario Bros. I'm using Tiled Map Editor to create the map, inside the map there is water. I want to make my character swims inside water, for instance, changing the animation and make it floats. But, my character just sinks. I don't know how to implement these things inside my program, although, I succeed with collision.

Can anyone help me please?

# Answer
You could have a `boolean inWater;` for your player and every update it checks if he is colliding with a water tile. Then in your `update` / `tick` method where you calculate your logic you just base your logic on the `inWater` variable.

For example:

```
if(inWater) {
    gravity = -0.5f;
} else if(!inWater) {
    gravity = -0.9f;
}

```

Same goes for your animations. When applying the current animation check the `inWater` variable and if it is `true`, set the `moveLeft` and `moveRight` animations to `swimRight` and `swimLeft` etc.

And to get the tile, just do what you do for collision, but instead apply it to check for water.

This is a really simple way of doing it, but googling a little won't hurt you.
> 1 votes

---
Tags: java, libgdx, collision-detection
---


# Question
Title: Ledge Detection with Plane Intersection?
i am working on a ledge climb system and I am currently refactoring it to make it more reliable.

I am tracing with a sphere towards infront of my character. If it found something, I trace downwards. However, with steeper angles, this produces non-reliable results.

I searched the Web a lot and it looks like that a Plane Intersection algorithm seems the best method, however I am not sure how to implement this.

My idea was to first trace towards the wall again and define a plane out of the point and the hitnormal. Then I trace downwards again and do the same. I then use the cross-product of both normals to retrieve the direction of the Plane Intersection.

And now I am lost on how to go further. I am not sure how to implement the actual plane intersection in Blueprints.

I want to avoid using traces alone because I want to have small cracks that need to be grabbed without any additional collision hints etc.

Does someone have a clue for me how to implement this? (Not a genius in maths, some tips would be nice though)

# Answer
For ledges, I would trace both horizontal and vertical rays.

Something like shown in this movie by Tim Dawson:
> 0 votes

---
Tags: mathematics, unreal-4, blueprints
---


# Question
Title: Is it possible to copyleft license a game engine and still allow users to sell games made with it?
I have recently been studying and working on implementing my own game engine. I am interested in making my work open source so that others may use and modify it freely. However, I also want to make sure any modified or improved versions of my engine would also be free to use or modify. This led me to believe a copyleft license would be most appropriate. However, despite wanting all future versions and modifications to the engine source code to be open source, I want people to be able to sell or profit off the *games* made with the engine. In other words, while the source code of the engine for the sake of the engine itself should remain open source, anything made with the engine for the sake of being played should be allowed to be closed source. Is there an appropriate license for this?

The reason I include the architecture tag is to also ask: If no simple license exists, then is there a way to architect my engine such that what I want to accomplish with licensing is possible? For instance, if my engine uses a scripting language with some entity component system written in the engine's compiled code, then maybe the scripts (which a gameplay programmer using my engine would write to dictate game logic) would be allowed to be closed source? But then anyone playing the game would still require the compiled engine in order to run said scripts. I do not know if this particular example could work, but it is just to give an idea of what I am getting at.

# Answer
You will want the GNU Lesser General Public License, or LGPL.

This enables commercial games to use your engine, and keep the game's source code closed.

It would also make sure that improvements to the engine would make it back to you.

Note that the game will have to make available dynamically linked executables. They can ship static linked binaries to customers, but not if there is no way for the customer to obtain an improved engine library and used it with the game by downloading a dynamically linked binary.

So if they ship statically linked game, they should also provide a link for downloading a game that is dynamically linked to your engine. This should not be much of an obstacle for the game developer.

For choosing an Open Source license, refer to https://choosealicense.com/
> 5 votes

# Answer
In addition to LGPL (which permits closed source code to link the your open source code), you also have the option of releasing code under more than one license.

You could also create your own license, though I would strongly recommend working with / contracting such things to those who are well versed in such matters. A software license is essentially a contract & you should treat it accordingly.

Ultimately, the specifics of which license (or combination of licenses) is most appropriate depends on a mixture your desired business, your target market & your personal / professional stance on the licenses themselves.
> 1 votes

---
Tags: architecture, licensing
---


# Question
Title: How to add clickable text link in Game Maker Studio 2?
I was wondering if anybody knew how to add text, that when clicked, would take you to another website in Game Maker Studio 2.

# Answer
> 3 votes
Create a new object.

Create event:

```
text = "your text";
link = "url";
font = your_font;

draw_set_font(font);
var width = string_width(text);
var height = string_height(text);

var offset = 5;
left = x - offset;
top = y - offset;
right = left + width - 1 + offset;
bottom = top + height - 1 + offset;

```

Global Mouse Left Pressed:

```
if point_in_rectangle(mouse_x, mouse_y, left, top, right, bottom)
{
    url_open(link);
}

```

Draw event:

```
draw_set_halign(fa_left);
draw_set_valign(fa_top);
draw_set_font(font);
draw_text(x, y, text);

```

---
Tags: game-maker
---


# Question
Title: How to randomize Motion/animation without create a state for each animation?
I'm using Animator and state for animating my charachter.

So, i've (example) an Idle state, associated to an Idle motion animation , and a Death State, associated to a Death animation.

But I've 5 possible animation for death so i would like to randomize death animation without create a state for each animation.

My State "Death" has a "Motion" variable. I would like to change at runtime this "motion" variable. Is it possible ?

Thanks

# Answer
> 1 votes
Quoting from Unity forums:

> In 5.0 we introduced StateMachine Transition which can be used to generate random animation from a list see this blog for an example http://blogs.unity3d.com/2014/06/26/shiny-new-animation-features-in-unity-5-0/
>
> in 4.x you can emulate this by creating a sub statemachine, with a first state that act like a selector; put a small clip(a few frame only) in this state that blend corrrectly to all your other random state, for each transition make sure that you don't have an exit time, you want to change as fast as possible from this selector state to your random state.

---
Tags: unity, animation
---


# Question
Title: Best data structure to store large amount of data
I am making a minecraft kind of game. In which I have 100s of objects and their crafting recipe.

Now I want to store them inside the program, ie I cannot load external files. Everything must be inside class for now. In future I might be able to use databases, once the game gets more traction.

All these objects will have addition properties like shootable,purchase cost,etc etc.

Some also have array property like

```
{ research1: unlocks{ object1:50%, object2:100% }},

{ research2: unlocks{ object1:50% }}.

```

But all these objects will be constant with an exception of "locked" boolean.

If I do a huge database I'll also have to search data using filters on they keys like we do on sql. Example: "Give me all Researches that are unlocked and that unlocks object1"

What will be the best datastructure to store them? Thanks.

# Answer
100s of objects is not a large amount of data for current machines (computers, phones, consoles).
For only 100s of objects with different properties, you could save them as a comma-separated-values file (.csv) that can be opened and edited with Excel or similar worksheet software.
You can write run-time queries that will take a negligible time to loop around the list of objects and find the ones with the correct properties.
If you want to speed up the loading/saving of this array of data, you can try to serialize it in a binary format instead of the text-based .csv format.

For the properties of variable size (the arrays you mentioned) , if you decide the biggest possible number of items, you can hard-code this in the serialization and leave the unused array items as "empty".
If there is no limit... then you need a field to store the number of items, and then fields to store this data. You cannot use a simple flat format such as .csv in that case (unless you store arrays in different files referred to by some identifiers).
> 2 votes

---
Tags: algorithm, data-structure, databases
---


# Question
Title: AddForce doesn't work anymore when Acceleration is added
Everything worked fine until I added acceleration on the x axis..now when I try to jump it just lifts up very little from the ground in a weird way and then it slowly sinks down like having 0 gravity. Here is the code I'm using:

```
public class PlayerMovement : MonoBehaviour {

    public float baseSpeed = 10f;
    public float maxSpeed = 10f;
    public float timeFromZeroToMax = 10f;
    public float jumpSpeed = 10f;
    public Collider coll;

    float accelRatePerSecond;
    float forwardVelocity;
    Rigidbody rb;

    void Awake () {
        rb = GetComponent<Rigidbody>();
        coll = GetComponent<Collider>();

        accelRatePerSecond = maxSpeed / timeFromZeroToMax;
        forwardVelocity = 0f;
    }

    void FixedUpdate() {

        transform.Translate(transform.right * baseSpeed * Time.deltaTime);
        forwardVelocity += accelRatePerSecond * Time.deltaTime;
        forwardVelocity = Mathf.Min(forwardVelocity, maxSpeed);

        if (isGrounded() && Input.GetKeyDown("w"))
        {
            rb.AddForce(transform.up * jumpSpeed * Time.deltaTime, ForceMode.Impulse);
        }

    }
    void LateUpdate()
    {
        rb.velocity = transform.right * forwardVelocity;
    }
    bool isGrounded()
    {
        return Physics.Raycast(transform.position, Vector3.down, coll.bounds.extents.y + 0.1f);
    }
}

```

# Answer
Let's just walk through one frame step by step as an exercise.

First, FixedUpdate:

* We translate the object rightward by our `baseSpeed` (no effect on velocity)
* We increase the `forwardVelocity` by `accelRatePerSecond` but don't yet use it. For our purposes let's say we were already at `maxSpeed` since the previous frame to keep the numbers simple.
* We jump by adding an upward force.

Let's say the rigidbody velocity is now (10, 5, 0)

Then, in LateUpdate:

* We set velocity to `forwardVelocity * transform.right`

Our rigidbody velocity is now (10, 0, 0) \<-- our y component is gone now.

So what happened to our upward velocity from the jump, or downward velocity from the fall? We told the physics engine to throw it out and use **only** the `forwardVelocity * transform.right`, stomping whatever other velocity it might have accumulated earlier in the frame. This almost certainly not what you want to do.

Instead, you might want to consider applying your velocity solely to the x component while keeping the y component unchanged, or treating this step as an acceleration/deceleration to a target speed along the ground direction when `isGrounded` is true (this would let the object get an assist from gravity when going downhill, for example).

There are a number of other physics mistakes in this code:

* As a general rule, don't use both Rigidbody physics and Transform position/translation/rotation on the same object. This periodically rips control away from the physics engine and can cause excess processing for the physics to catch up to this out-of-band modification (from the physics engine's point of view, the object just teleported), produce implausible reactions from other physics objects, and will disable interpolation/extrapolation if you're using it.

Instead, commit to one or the other. Either steer your object using the Rigidbody exclusively (using velocity, AddForce, or MovePosition), or skip the Rigidbody and go pure Transform manipulation if you don't need the physics engine's collision checks.
* Applying Time.deltaTime to an Impulse is not meaningful. An impulse represents an instantaneous change to the object's motion, not an influence that is sustained over a duration. And you don't want the intensity of the player's jump to vary based on the fixed timestep you choose.

Given that you're passing a speed as an input here, it looks like you want `rb.AddForce(transformn.up * jumpSpeed, ForceMode.velocityChange)` instead
* Applying continuous Physics effects (not instantaneous reactions) in LateUpdate rather than FixedUpdate can mean they trigger with an uneven frequency relative to the physics step. You might sometimes go 0, 1, 2, or 3 physics steps integrating the motion of the object between these velocity updates, which can give your motion an uneven and stuttering look. Generally, any continuous physics effects should go in FixedUpdate to ensure they're processed in lockstep with the other physics simulation.
> 0 votes

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


# Question
Title: Find an infinite loop in a very big project in Unity
How can I find an infinite loop in a very big project in Unity?

I tried to use breakpoints in MonoDevelop and debug, but I was not able to track the loop. I tried to put `Debug.Log()` in a few places and it did not help as well.

So, are there are any other ways of doing it?

It is possible that the loop is not a problem, but I think it is very unlikely. The problem is that when I perform some actions the Unity Editor just stucks and becomes unresponsive at all and I should disable it through the task manager.

# Answer
There's a paid ($15) asset called Panic Button that can help you track this down.

You import it into your project, then run. Once Unity locks up in an infinite loop, hit `Shift+Esc` to break out of it and get a stack trace of exactly where execution was stuck. This also resumes editing without crashing, so you don't lose unsaved work.

I don't have any affiliation with the creator, but I can confirm it performs as advertised and doesn't introduce undesirable side-effects into the project. For the price of the coffee I'd have burned through tracking down a few of these issues, I'd personally say it's worthwhile. ;)
> 2 votes

---
Tags: unity, debugging
---


# Question
Title: Getting "Non-invocable member 'items.item' cannot be used like a method." when invoking a class
I have my item class (items.cs) not attached to any gameObjects, I want to use items for all items in my game so I can use arrays as inventories.

I have Stone.cs which is attached to a gameObject. On the line `inv = items.item(100f, "Stone", "Rock used for building");` I get a compiler error `Non-invocable member 'items.item' cannot be used like a method.` I am confused by this as I copied it from the Unity class tutorial, just splitting creating the item to another script.

**items.cs**

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

public class items : MonoBehaviour{
    public class item{
        public float iQuan;
        public string iName;
        public string iDesc;

        public item(float iQ, string iN, string iD){
                iQuan = iQ;
                iName = iN;
                iDesc = iD;
        }

    }
}

```

**Stone.cs**

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Stone : MonoBehaviour {
    // Use this for initialization
    public items.item inv;
    public float iMax;
    public float iCur;
    void Start () {
        inv = items.item(100f, "Stone", "Rock used for building");
    }

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

    }
}

```

# Answer
> 2 votes
`item` is not a method. It's an object. If you want to create an instance of item, then you need to use the `new` keyword:

```
items.item inv = new items.item(...)

```

Also, the first letter of class names should be uppercase, something like

```
Items.Item inv = new Items.Item(...)

```

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


title: How to export from Blender to unity3d

text:
# Question
Title: How to export from Blender to unity3d
I have a simple object created from PLANE, in BLENDER version 2.72, where I edged the edges to the height. How do I correctly export the model to Unity3d I have version 4.7 to make all walls visible? Figure 2. Sorry for the wrong English. Thanks for your advice

Picture 1 in Blender

object export .obj in unity

# Answer
Unity automatically converts blender to unity meshes/objects.

You're probably having issue with normals here.

In edit mode select all faces and hit ctrl+n then pick which direction you want the face to be.

Before:

After selecting all and hitting ctrl+n

After togeling inside

Notice how the faces are lighter? It's a quick indication of which face the normal is pointing at.

The normals can be shown by enabling one of the options for normals in the right properties of the 3D view ( if it isn't showing up, just hit n )

> I have version 4.7

That's ancient tho, any reason you're not using unity 2017?
> 1 votes

---
Tags: unity, blender, export
---


# Question
Title: Rectangles render with gaps in between them (Box2D)
Right now I create my boxes where 1 meter is 85 pixels. Gravity is 10. And

```
                        fixtureDef.restitution = 0.1f;
            fixtureDef.friction = 0.5f;
            fixtureDef.density = 1.0f;

```

The problem I'm having is illustrated in the image I have provided:

As you can see, there is a small gap between many, but not all the crates. What could cause this?

Thanks

# Answer
> 8 votes
I guess that's some issue in box2d, there is such a bug to increase performance. since more accuracy needs much more computational power. to fix that issue I guess you only need reduce box physical sizes (for example you can create a 84px\*84px rectangle for a 86px\*86px image). you can also fade the pixels in the edges to get better results.

# Answer
> 0 votes
Just wanted to say that Ali is right, Box2D has a macro on this - I'll paste it here:

```
/// The radius of the polygon/edge shape skin. This should not be modified. Making
/// this smaller means polygons will have an insufficient buffer for continuous collision.
/// Making it larger may create artifacts for vertex collision.
#define b2_polygonRadius        (2.0f * b2_linearSlop)

```

This value is assigned to a new b2PolygonShape's m\_radius field in the constructor. Subtracting this value from your body during creation is a trivial solution to resolve the gap glitch:

```
    b2PolygonShape polygon;
    polygon.SetAsBox(width*0.5-polygon.m_radius, height*0.5-polygon.m_radius, b2Vec2(offsetX, offsetY), angle);
    fixture.shape = &polygon;

```

# Answer
> 0 votes
This is also documented in the manual http://box2d.org/manual.pdf :

> 4.2 Shapes
>
> Polygons inherit a radius from b2Shape. The radius creates a skin around the polygon. The skin is used in stacking scenarios to keep polygons slightly separated. This allows continuous collision to work against the core polygon.
>
> The polygon skin helps prevent tunneling by keeping the polygons separated. This results in small gaps between the shapes. Your visual representation can be larger than the polygon to hide any gaps.

I have found that I can get better looking results simply by scaling up the scene, which makes the gaps look smaller, as it appears that the skin has a fixed width.

Related: https://stackoverflow.com/questions/7705095/webgl-box2d-drawing-issue-gap-between-bodies

---
Tags: c++, box2d
---


# Question
Title: How to place an object at the mouse position?
How can I place a object to position where I clicked in just x,y axis not in z, I am trying to achieve it with

```
Vector3 mousepos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
object.transform.position = new Vector3(mousepos,mousepos);

```

but it does not seem to work, in fact the object doesn't even move.

# Answer
You need to reference the value, not the entire vector.

```
 Vector3 mousepos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
 object.transform.position = new Vector3(mousepos.x,mousepos.y,0);

```
> -1 votes

---
Tags: unity
---


# Question
Title: What does the green arrow in Unitys MonoDevelop mean?
What does the green arrow in Unitys MonoDevelop mean? It comes up while I am debugging my code:

# Answer
The green arrow in MonoDevelop shows the line in your code the game is currently executing. You can read more about this, and debugging using MonoDevelop in general here.
> 2 votes

---
Tags: unity, monodevelop
---


# Question
Title: Performance problems with quadtree for dynamic objects
I´ve implemented a quadtree spatial partitioning to my game engine as I wanted to try it and see how it affects the performance checks. The results were great (instead of hundreds collision checks only for cursor I was suddenly having just about 10%), however I faced performance problems (not caused by the number of collision checks but by the spatial structure itself \[or my implementation\]) :

**1.** At first I was inserting items every frame and at the end of the frame the quadtree was cleared and so on. I realised this slowed down the performance more than 2-3 times.

**2.** Of cource the next step was to try to make the quadtree dynamic by not clearing it but by checking the moving objects from the quadtree. However this process is also not trivial as I can have a multiple nodes containing the same object (if it doesnt fit to any of the children I "broadcast" and check neighbour nodes so it can be visible in more than 1 node) and I ended up by digging through the entire quadtree again.

How did you solve these problems with the quadtrees? I´ve read that some of the engines use multiple spatial structures to divide work for **static/dynamic** objects, I would use quadtree for static structure but what would be suitable for dynamic? Also I think I "hurt" myself when I want to make as generic solution as possible so I dont have to change the spatial structures of my game engine no matter what type of game I´m creating with it at the time.

# Answer
I'd echo Bram and use a grid and actually just for all objects, static and dynamic (though you might store static objects in a separate grid *instance*, but same data structure for both). You can tune the crap out of it.
> 3 votes

# Answer
How deep are your quadtrees? How many elements do you tolerate in a leaf node before you subdivide?

How are your entities spread out through the world? If it is extremely uneven, with just a few big clumps here and there, I can see how quadtrees would help.

But if it is better spread out than that, I would use a grid instead of a quadtree.

A grid is much easier to keep updated than a tree. You could dynamically move objects from cell to cell, but because assignment to a cell is so cheap, reconstruction from scratch works too.

You can typically afford busy cells in a grid. It increases the collisions test of course, for those cells, but you still get the easy wins of not testing against remote objects.

If you decide to use a grid, you can either do the grid for dynamic objects only, or use it for static objects too. You will get fewer collision tests if you keep the quadtree for static objects. This is because a quadtree can be more precise in spatially subdividing your world.

But you will have to weigh the reduction in collision tests against the increased complexity of your code due to maintaining two data structures. Personally, I would choose simplicity over performance. Especially if the performance with a grid is "good enough." It's wasteful to code a quadtree indexing before determining that you actually need it, I think.

I would also chose grid-only approach if you need to test dynamic versus static objects. You mentioned you test the cursor against dynamic/static, in which case both a grid and a tree would be less problematic.

Let me conclude with one draw-back for the grid approach: if you want fine-grain subdivision you will be using a lot more memory than a quadtree would require. So determine your constraints: are you short on memory? Are the collision tests dragging down the fluid experience?
> 1 votes

---
Tags: c++, architecture, performance, software-engineering, spatial-partitioning
---


title: Height Maps for story driven terrain

text:
# Question
Title: Height Maps for story driven terrain
We are developing an indie story driven adventure game and our writer is writing specific geography into her story. Is there any information on how to create height maps for specific geography? I have googled and there is nothing specific I can find on controlling the painting to create a very specific geography. I have taken the common sense approach of black being nothing and pure white being the tallest points however our results have been negligible thus far.

# Answer
A good introduction tutorial on procedural terrain can be found at the Red Blob Games blog.

You will also find that at some point, height maps will not cut it any more. There will be no overhangs, no caves, no bridges or tunnels possible with a height map.

But depending on your needs, you could stick with a height map.

From the same author, there is also this map generator, which is not a height map, but can help you get some ideas for controlling terrain features like rivers and such.
> 1 votes

---
Tags: terrain, level-design, heightmap
---


# Question
Title: Lunar Lander calculating gravity, acceleration and collision in GameMaker
I've already asked this on the GameMaker forums but had no response so far.

I'm making a little Lunar Lander game as my first foray in to GameMaker, I'm wanting to have the ship land and take off again too. I'm new to scripting and programming in general and I'm having trouble with acceleration, in particular with gravity.

Basically I need to:

* Be constantly pulled downwards to simulate gravity up to a maximum speed (terminal velocity)
* Activate thrusters to accelerate my ship towards its current direction
* Turn the ship left and right, therefore adjusting my current direction
* Land on surfaces (I've been accomplishing the collision by setting my gravity to 0) and then take off again (thereby activating gravity again)

The problem:

* I can't figure out a natural, correct way to accelerate the ship with gravity up to its terminal velocity
* I also can't figure out how to add the ship's thrust to gravity (i.e. if I'm facing downwards and firing the thrusters I should be going faster than if I wasn't firing the thrusters). As gravity is only pulling me down in the y direction and the thrust of the ship could be a force pushing me in any direction (according to my ship's angle) this is tricky (for me...).
* The whole thing doesn't feel like particularly smooth motion

An example of my code is as follows:

```
direction = image_angle

fallSpeed += grav

if fallSpeed > 2
{
fallSpeed = 2
}

y += fallSpeed

motion_add(direction,shipThrust)

if keyboard_check(ord('W')) and speed < maxSpeed
{
   shipThrust += 2/room_speed
}
else
{
    shipThrust -= 2/room_speed
}

if shipThrust > 20/room_speed
{
shipThrust = 20/room_speed
}

if shipThrust < 0
{
shipThrust = 0
}

if place_meeting(x,y,oGround)
{
    fallSpeed = 0
    grav = 0
}
else
{
    grav = 0.2
}

if keyboard_check(ord('A'))
{
    image_angle += 3
}

if keyboard_check(ord('D'))
{
    image_angle -= 3
}

speed = max(speed -0.1,0)

```

Some of that code is probably (read: clearly...) wrong and I figure I need an overall 'speed' value of the ship that I then affect with my two forces (gravity and thrust) but I can't for the life of me figure out how to do it. Any help is appreciated, thanks! :)

# Answer
I'm unfamiliar with game-maker and its' syntax so I'll leave that part up to you.

This psuedo-code should get you close:

```
If (W) acceleration++;
If (S) acceleration--;
clamp(acceleration, min, max);
velocity += normalizedDirection * acceleration * deltaTime;
If (!landed) velocity += gravity * deltaTime;
clamp(velocity, min, max);
position += velocity * deltaTime;
if (position.y > 0) //If not on the ground
  landed = false; //Take off
else if (!landed) //Otherwise, if we haven't landed yet
{
  position.y = 0; //Ignore physics and snap ship to terrain
  acceleration = 0; //Cut the engines
  velocity = 0; //Thud
  landed = true; //Don't apply gravity until we've taken off again
  rotation = 0; //Fix bad landings??
}

```

Gravity is an acceleration in WorldUnits/Second/Second
Velocity is in WorldUnits/Second

You'll also need to wrap the rotation keys in an 'If (!landed)' so you cant turn while 'landed'.
> 0 votes

# Answer
As I mentioned in my comment a terminal velocity is a result of drag on an object limiting the maximum velocity. This means that in order to have a smooth approach of the terminal velocity drag needs to be included somewhere in your game (of course this is not strictly physical as a small moon is unlikely to have an atmosphere to cause drag, I am going to ignore this point for now).

This question on the physics stack exchange details how it is possible to include drag (it also includes some Python code detailing how to simulate it). For pseudo code I would suggest,

```
if(W){
    thrusterAcceleration = direction * thrusterPower;
}
else{
    thrusterAccleration = (0,0);
}

finalAcceleration =  thrusterAcceleration - gravity
    - drag * velocity * (velocity.normalised);

velocity += finalAcceleration * deltaTime;
position += velocicty * deltaTime;

```

to update your position vector. Note here I have used vectors, i.e. some struct or class with an `x` and `y` component. If you require a solution without these I can post some psuedo code later (note the above linked question has a solution with `x` and `y` separate).

You may need to play around with the constants `drag`, `gravity` and `thrusterPower` as often what appears good in games is not the actual true values. An example is Super Mario (example stolen from this answer here) which has different value of gravity for different cases;

> * When jumping regularly, Mario experienced a gravity of 67.82 m/s^2 (6.9 times Earth gravity). Here he had a push-off velocity of 17.36 m/s.
> * When high-jumping, Mario experienced a gravity of 34.79 m/s^2 (3.5 times Earth gravity). Here he had a push-off velocity of 15.21 m/s.
> * When falling off a ledge, Mario experienced a gravity of 55.88 m/s^2 (5.7 times Earth gravity).
> * As for running, Mario seemed to follow a perfectly constant run velocity pattern (as is expected, really). When walking, he moved at a speed of about 3.7 m/s, and when running, moved at a speed of about 9.1 m/s.
> 0 votes

# Answer
My answer involves the use of GameMaker's Physics Engine, which may not be the right answer for everyone.

To initiate the physics system: 1) check the "use physics" check-box for all relevant object, including the ship and the ground, which can be built from rectangular box(es). 2) check the "use physics" option in all relevant rooms. 3) adjust the gravity to the desired amount in the room setting. 4) assign sprites to all physical objects, and in the object menu, create a suitable physics fixture.

The ways in which the questioner's requirements can be fulfilled:

1)Gravity and terminal velocity: These can be fulfilled first by the automatic acceleration created by the gravity setting. Terminal velocity can be achieved by this code:

```
if phy_speed_y>10
{
    phy_speed_y=10
}

```

where 10 is the terminal velocity you allow.

2)Thruster: draw your ship with the sprite pointing to the right. Do these in your "w-pressed" event:

```
NetForce=10
XForce=NetForce*cos(degtorad(image_angle))
YForce=-NetForce*sin(degtorad(image_angle))
physics_apply_force (x,y,XForce,YForce)

```

This will apply a force to the ship, or whatever is running this code from its origin point, if you want to be more sophisticated, you can replace the "x" and "y" in the "physics\_apply\_force" command with a specific point (like the thruster's coordinate)

3)adjusting current direction:

Without physics: simply add or subtract from your image angle with your key presses, except you need to run this code at the end of every step:

```
phy_rotation=-image angle

```

With physics:

```
physics_apply_torque(10)

```

where "10" is replaced by the desired amount of torque. I believe negative torque turns you clockwise.

4) Land on surfaces: if you do not have very many objects, in the events for the ship and the ground, add this event: "collision". when you add this, the system will ask you which object do you want the current object to collide with, choose "ship" is you are doing ground, choose "ground" if you are doing ship. Then, add some placeholder scripts in the collision events so game maker doesn't automatically delete them as empty events.

If your ship has the right geometry, it should be possible to make it land like a normal object would. If you want to make sure that it has landed on the proper side, simply check the angle it is pointing at when it lands on the place where you want it to be.

If you are dealing with many colliding objects, create a parent object and add a collision event to it, with itself.
> 0 votes

# Answer
Rather than spell out implementation, I'd like to suggest you view the many open source versions of this on GitHub. Here's a simple one in Python, and you should be able to work out the details to translate to GameMaker...

https://github.com/cp4k/PyLander

You can also just search GitHub for Lunar Lander game code at https://github.com/search?utf8=%E2%9C%93&q=lunar+lander

Also, as I mentioned in a comment, there is no terminal velocity in space - only when there is an atmosphere. If you do want your game to work in an atmosphere, I'd say don't worry about it for version 1. Get it to work without, and then figure out how to add it later.

If you are in general worried about the spacecraft going too fast when accelerating, consider it will just crash soon enough and not get that fast.
> 0 votes

---
Tags: collision-resolution, game-maker, physics
---


# Question
Title: Copyright/property rights to using the Certificate 18 movie logo on your game or artwork without permission?
Ok so I have been making a game recently just for fun and might be making it available for download. I have done it in the past with ERSB (or whatever it called) and they give the official age rating of the game

But I want to use the Certificate 18 movie logo that has been used for decades , on my games title screen. With some kind of tagline such as "This is not for kids!"

Is that legal? or is it in breach of any kind of law?

Sorry if this is off-topic, I did a search but can't find the answer anywhere. I figured you knowledgable beauties would know the answer!!

# Answer
> 2 votes
Legally, the short answer is no, you cannot just use them. Using their labelling suggest that they have vetted & rated your product, which is presently not the case. They regulate usage their labeling in an attempt to achieve the following:

> BBFC age ratings (text and symbols) are identifiable, understandable, trusted and consistent in their application and meaning.
>
> Using them allows viewers to make safe, informed decisions about the content they choose for themselves and their family.
>
> In order for them to retain their value to the public, BBFC age ratings must be used in a consistent and correct fashion.

Additionally, their classification guidelines state:

> With a few limited exceptions we do not classify video games.

Details of how and where BBFC symbols can be used are covered in their licensing agreement; if you want to get into particulars about it, you should either read through with a lawyer &/or contact them as described on their other uses page.

---
Tags: copyright, trademark, intellectual-property
---


title: How to move player on unity3D?

text:
# Question
Title: How to move player on unity3D?
I checked the input settings. I added a speed value. I also added Time.deltaTime, but the body is not moving.

```
using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

    public float speed;
    private Rigidbody rb;

    void Start () {
        rb = GetComponent<Rigidbody>();
    }

    void FixedUpdate () {
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");
        Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
        rb.AddForce(movement * speed);
    }
}

```

# Answer
You should multiple speed and deltatime

```
rb.AddForce = (time.DeltaTime * speed * movement)

```
> -2 votes

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


# Question
Title: You've killed the enemy you needed to get across. Now you have to die and retry?
I am designing enemies for a platformer, and want to have enemies which the player utilises to get through levels.

I like the idea of jumping on enemies to platform across gaps, but it's problematic if they die. It feels really bad to put the player in an unwinnable state, having killed their means to platform across a level. It just feels messed up to be like, 'You've killed the enemy you needed to get across. Now you have to die and retry'.

What are some ways of fixing that problematic game state?

# Answer
Just have them **respawn**

Have an enemy spawner which will either spawn enemies that fall to their own deaths or just respawn the enemy once you killed it (e.g. drop it out of a pipe like in the original Mario Bros).
> 116 votes

# Answer
When you are designing a game, you are in control, don't forget that.

If you have enemies that can be killed which are crucial to traversing the level, why are they able to die in the first place? There is no reason to kill them if you have to start over if you do so.

Perhaps allowing you to 'stun' but not kill them, still allowing you to use them to platform is a good solution.

On another note, Super Metroid is what this problem reminds me of, the game had these turtle-like enemies that move left and right. They could not be killed, using an ice-beam you could freeze them, this allowed you to jump on top of them and use them to reach higher areas.
> 47 votes

# Answer
Have the killing of the enemy initiate another way to cross. The way that happens depends upon the specifics of your game.

If your game is fast paced, maybe killing the enemy makes a platform appear that now makes the jump possible.

Perhaps the enemy drops an item that gives a one-time-use double-jump mechanic.

Perhaps the enemy drops items that now let the player compete the level in an entirely different way.
> 12 votes

# Answer
You could design an alternative route with less reward.

Killing the enemy to drop down a level and walk to the goal = easy.

Jumping on the enemy, up or across to next level and get reward, walk to goal = skills.

Jumping on enemy without pause, so you also catch that weird mech-bird-thing before it flies away, get reward, walk to goal = super mad skills.

There is then intensive to play the game well, instead of lazily, but it also becomes more ... inebriation friendly!
> 7 votes

# Answer
The decision really depends on the tone of the game.

* If the game is one of those hard-as-nails type, let the player wander around in their failure. I Wanna Be The Guy et al. have a reset button that loads the last save, and you typically encounter a lot of similar situations where you need to use it.
* If the narrative requires it, show a message that *some enemies are better left undefeated* and offer an option to retry.
* In other cases, have the stage loop, either via resurrection, respawning, enemy reciprocation, or leaving to another clone of the room.

Think about what the player will expect, having played up until this point and do that. Or don't, twists are sometimes good too.
> 5 votes

# Answer
If possible, put the player on a strict timer mechanic that will kill them if they screw it up.

Some examples; the platform they are standing on collapses, the game screen moves to the right and will push them into the pit, water rises up and drowns them, etc.

This denies them the ability to hang around in the "trapped" state because it will move to a "dead" state in a few seconds max. (This was a pretty common way to do it for old NES platform games)
> 5 votes

---
Tags: game-design, game-mechanics
---


title: Polymorphism vs cache-friendliness

text:
# Question
Title: Polymorphism vs cache-friendliness
How can we combine inheritance-based polymorphism with spatial cache friendly data structures? In a simple game engine we usually have some base Entity class which is inherited from to implement the various distinct game entities. These entities are then stored by pointer in a large array of some kind, which is iterated over for updating, rendering and so on.

However this leads to bad performance because entities will be randomly scattered throughout memory. One way I thought of to fix this problem is to have a separate array for each entity type, for example:

```
Goblin goblins[100];
Human humans[100];
Demon demons[100];
Entity* entities[300];

```

My question is: Is there a more elegant solution than that? The separate arrays approach requires rewriting the core functions of the engine itself every time I want to add or remove an entity type in the game implementation. I'm looking for a general solution which doesn't care about what the subclassed entity types are as long as they inherit from a common ancestor.

# Answer
> 2 votes
I wouldn't do that, as you'd complicate things unnecessarily. Keep a single generic list of entities and compact toward the beginning of the array every so often. That way you will get far fewer cache misses (unlikely you'll eliminate them altogether unless you make your dataset sufficiently small). It's also bad form to type various species as you have there; you should just be using `Entity`, composed of components describing differences between the species. *Favour composition over inheritance*.

Compaction means updating entity indices *everywhere* in memory; otherwise you face broken links.

Look into cache-oblivious algorithms to understand how to achieve best cache performance, but note that not every problem is suited to eliminating cache misses entirely. Key is to *minimise* them.

P.S. If you haven't wrapped your head around implementing Entity-Component Systems yet, you'd do well not to worry about optimising cache any time too soon. Work on the basics first - long road.

# Answer
> 1 votes
If the costs of dynamic dispatch/indirect function calls and optimization barriers are genuinely too great and exhibit a tendency to degrade spatial locality, then the straightforward solution is model your design at a less granular level.

---
Tags: c++, performance, inheritance
---


# Question
Title: How to access Maya Bonus Tools 2012 in Maya 2014
I have been trying to use the paint geometry tool for Maya 2014 but it isnt showing up. I downloaded Bonus Tools 2012 and installed it. Where can I find this tool in Maya 2014?

# Answer
In Maya 2014 you go to Modify -\> Paint Scripts Tool \[Options\] -\> Setup. Enter "geometryPaint" under 'Tool setup cmd:' and there you have it!
> 1 votes

# Answer
paint geometry tool for higher Maya versions, e.g. 2017: run the script inside the mel console(you can drag and drop the script line from the mel console to a shelf, too) to get the legacy paint geometry tool (from maya bonus tools 2012):

ScriptPaintTool; artUserPaintCtx -e -tsc "geometryPaint" `currentCtx`;
> 0 votes

---
Tags: geometry, tools, maya
---


# Question
Title: Optimal batching for 2D objects with transparency
I have a collection of 2d objects with transparency. Each object has a depth value to determine draw order and a material. I'm trying to batch them in an optimal way to minimize draw calls. Assume that objects with the same material can be batched together in a single draw call.

A naive way of batching is to sort all objects by depth first, then sort by material if the depth values are the same. Consider the following set of objects with 'z' representing depth and the color of the object representing its material. In the right set, blue objects have been translated along x such that they don't overlap with red.

Sorting by \[depth,material\] results in the sorted object list: { Red, Blue, Red, Blue } for both the left and right set of objects. Either left or right would result in 4 draw calls (objects of the same material need to be adjacent in the sorted list to be batched)

However if you look at the objects on the right, its clear you can use two draw calls because there's no overlap. The ordering based on depth doesn't matter if the blue and red objects don't overlap in between a given batch's depth range. This would also hold true if you had a red object with (z \> 4) or (z \< 2) anywhere in the right set.

So, assuming each object has a material that can be compared, a depth value, and a bounding box (lets say each object is an axis aligned quad), what is an efficient way to get a list of draw objects with both a correct ordering for transparency and optimal groupings based on material?

Also just to note, I don't have instancing support so that's not an option here.

# Answer
If batching is a bottleneck then you might want to sort them by depth and material and also perform a bounds check to see if they overlap. But you're probably going to spend way more time in sorting and checking than just plain sorting and having a less performant batching.

I guess your mileage may vary but if you're writing a generic batcher I'd stick to simple sorting and ignore the bounds check.
> 1 votes

---
Tags: c++, opengl-es2, transparency, sorting, batching
---


# Question
Title: Should a system be able to render things? (ECS)
I'm currently building an entity component system and I just have one question... Should a system be allowed to render things to the screen?

For example, should I make a SpriteComponent that contains a Sprite, and then create a SpriteRenderSystem that renders the sprite to the screen? Or should rendering entities be managed by something else entirely?

The reason I ask is because I've read in many forums that allowing a system to render is a bad idea. But I just don't understand why this is; If game objects in my game are represented using the ECS, how else would I go about rendering objects to the screen?

# Answer
This might not be the best approach, but it works for me:

The *ECS* is used for logical storage and operations *only* (or almost only).

The design I use is aiming to separate these two concerns as much as possible. Naturally somehow you need to be able to tell any rendering code how to render a given entity, I do that using a component on my entities that stores a graphical representation of the entity. This representation could be a simple sprite, a whole spritesheet, a bunch of triangles, and so forth.

To decide what I render, my ECS has a *Camera-System*. This system has a certain box in world-space it *sees*. Any entities that are located in that box and have a representation-component are picked up by the Camera-System, batched and queued for rendering.

The renderer runs, in my case, on another thread and picks up a snapshot of all cameras every frame - then renders it.
> 1 votes

# Answer
You're overthinking this. There is no definitive *"good"* or *"bad"*, just what **works**. I've always used a `SpriteComponent` and a `SpriteRenderingSystem`. It's the most simple and straight-forward way and it has worked for all of my games. If you feel like it's not the correct thing to do then change it to be whatever you want / need. Just do whatever feels right and whatever **works** and it will be fine in the end.
> 1 votes

---
Tags: c#, entity-system, component-based
---


# Question
Title: How can I rotate RigidBody and not violate physics?
I'm trying to create a game that we have a falling ball and an spinning object that spin based on user mouse position. user should rotate the object and hit the ball on time to throw the ball into sky. The problem is that if user move his finger too fast. the game object moves too fast and goes past through the ball. This is my code so far:

```
 void Update () {
         if (Input.GetMouseButtonDown(0)) {
             startPos = Input.mousePosition.x;
             startRot = obj.transform.localEulerAngles;
             lastDist = 0;
         }

         if (Input.GetMouseButton(0)) {
             float dist = Input.mousePosition.x - startPos;

             obj.MoveRotation(Quaternion.Euler(startRot + new Vector3(0, 0, -dist)));

             for (int i = 0; i < obj.transform.childCount; i++)
                 obj.transform.GetChild(i).GetComponent<Rigidbody>().MoveRotation(Quaternion.Euler(startRot + new Vector3(0, 0, -dist)));
         }
 }

```

How can I achieve this behavior for my game. The user should be able to spin the game object as fast as possible.

Thanks in advance.

# Answer
These kinds of issues arise when the speed of the interaction is faster than the resolution of the Physics engine. Essentially the object has passed completely through the other object in the moments between when the physics engine was paying attention to them.

Increase the Physics run rate in the Physics settings.
> 1 votes

---
Tags: unity, collision-detection, rotation, rigidbody
---


# Question
Title: How should I arrange storage for components referenced in a quad tree?
I like the Unity's entity-component-system approach, I'm working on something similar. However I'm not sure where and how I should store the components.

An easy answer would be: *"store the components in the corresponding system"* \- this is logical (who else is interested in the component if not the handler system?), and cache-friendly (continuous memory, so iterating through the collection would/could cause less cache miss).

However there are two major problems with this approach. Actually it's only one which generates the other. The generated problem is the simpler, I start with that:

A `Behaviour` (aka. custom user script) component can be added to the `GameObject` (aka. entity). The `Behaviour` must be able to get other components which are added to this object (similar to Unity's MonoBehaviour). However the object is not storing any component directly, so we have to query the component from the corresponding system. In a simple world, this query can be done only once after the required component is created, because its address won't change until its actually removed. This way, the `Behaviour` component can query other components in its constructor/init function and everyone is happy. But what if the other component's address can change? Actually this is the root cause of this problem and it's generated by the next one:

Storing components in an array can be a good thing because it's memory(bus) friendly. However it's not ideal in some cases, eg. when I have a spatial partitioner tree (QuadTree right now). I have two choices:

**1)**

I can keep the "global" continuous array representation and store pointers only in the QuadTree. However, this way when I query the components which belongs to a QuadTree node and iterate on the result, cache misses are introduced (jumping back and forth in the memory).

```
// pseudo-code

// "global" storage
pool<RigidBody> rigidBodies;
pool<Mesh> meshes;
// etc.

QuadTreeNode
{
    // only pointers to the "global" array elements
    vector<RigidBody*> rigidBodies;
    vector<Mesh*> meshes;
}

```

**2)**

I can use node-based component array which means the iteration is more cache-friendly. But when the component has to be moved to a different QuadTree node, it must be removed from the current node and must be copied to the new one. This means the component's memory address is changed which also generates my first problem (cannot query only once, because the address can change).

```
// pseudo-code

// not-partitioned components
pool<Behavior>

QuadTreeNode
{
    // these are not pointers, but the actual data
    pool<RigidBody> rigidBodies;
    pool<Mesh> meshes;
}

```

I probably pick the *1st* solution, because the cache-miss is probably less noticable than the constant remove-copy and query operations (at least for "moving" components).

However, I'm interested in any better representation/storage of the components which is both cache-friendly and operation-friendly.

# Answer
> 0 votes
I'd suggest the first solution but use indices instead of pointers. Pointers will still be invalidated if you resize/realloc the array (or `std::vector` in C++) unless you used unrolled blocks with division/modulo (or right shift and bitwise AND) for random-access plus they take twice as much memory on 64-bit which will also more incur more cache misses if you sequentially access a massive array of 64-bit pointers as opposed to 32-bit indices, e.g.

However, you can make quad-tree traversal more cache-friendly if you can afford a radix sort here and there by radix sorting the indices it stores at the leaves periodically if the quad-tree has changed a lot.

---
Tags: architecture, entity-system, optimization
---


# Question
Title: Efficiently Handling Entity-Interactions in a Tile-Based World
I've been programming Roguelike games lately and there's a common problem I always run into. I can't seem to find a satisfactory solution for handling Monster-Monster interactions.

For the intents and purposes of this question, let's assume my Game-Map just is an array of bytes.

```
struct Map{
 unsigned char tiles[100][100];
};

```

Now, I've got Monsters, which have an X and a Y position.

```
struct Monster{
 unsigned int x, y;
};

```

Handling Monster-Map interactions is trivial. For example, if a monster wants to move to the left, I just have to check if `tiles[x - 1][y]` is a passable tile. This is very nice because no-matter how large the map is, I **only have to check one tile**.

But here's where I run into problems. What if a monster wants to breath fire onto a tile to the left. To ignite any monster that might be on the tile, I'd have to iterate through **every monster in the entire world**, checking if it's `x, y` matches the coordinates of the tile. This is not-so-nice, as the cost of breathing fire **scales linearly** with the amount of monsters in the world. If only there were a way to **access monsters using tile-coordinates**...

Which leads me to one solution. Tiles could hold a **pointer to a monster**. When a monster moves to a tile, it sets the previous tile's pointer to a `nullptr` and sets the current tile's pointer to `this`.

```
struct Map{
 unsigned char tiles[100][100];
 Monster* resident;
};

```

Now, when a monster breaths fire, it just ignites whatever monster is on that tile by using the tile's monster-pointer. Now the cost of breathing fire is **constant**, and the cost of moving is **constant**. Perfect!

## But...

Now a tile is 9 bytes instead of 1 byte. `sizeof(map)` has more-than **octoupled**! Ouch!

My question is: What other solutions could be used to solve this problem? Maybe one's that meet in the middle on memory usage vs. number of operations.

# Answer
**You have 3 major options:**

**1:** Implement some kind of sorting or data structure.

For example: Keep monsters in a list/array (Something you are probably already doing) and sort them by `x` and `y`. This would enable you to perform a binary search (Which has O(log n) performance) for locating a monster at a given tile. However, this introduces the need to sort the list once per game tick(Sorting is O(n log n)). This means that if there are a small number of monsters that need to breath fire, the performance will almost certainly be worse. This would only help performance if they are a very large number of monsters that need to breath fire (Probably somewhere in the hundreds to thousands).

Although that was just an example algorithm, the same general characteristics will hold true. In short, complex algorithms will only save time if there are a large number of monsters.

**2:** Simply go through the list of monsters (O(n)). This is simple and likely to be quick enough in almost all cases.

**3:** Use the pointer system you suggested. Although this increases the size of the map considerably, it is unlikely to cause any problems unless your map is extremely large. This system lets you handle both small and large numbers of monsters simply and efficiently. Basically, the size increase is probably irrelevant and this is possibly the best option overall.
> 6 votes

# Answer
**Why this is overkill**

Although you've probably heard the phrase *premature optimisation is the root of all evil*, it took a while for me to fully grasp its meaning.

Consider a game that runs two procedures (A and B) every game loop. Procedure A takes 10,000 cycles to perform its task. But really it only needs 100 cycles. It could be 100x faster, how wasteful!

Procedure B takes 1,000,000 cycles to perform its task. But really it only needs 500,000. It could be 2x faster, it doesn't seem very wasteful.

If we optimise procedure A, we save 9,900 cycles. If we optimise procedure B we save 500,000 cycles. So optimising procedure B is the wise choice. But if we follow our intuition it will probably tell us to optimise the "wasteful" or "inefficient" procedure - procedure A!

**But let's do it anyway**

Of course, you will never learn *how* to write an efficient algorithm if you do not take opportunities to practice. And in some instances (depending on how much you deviate from the typical roguelike, or how constrained your hardware is) you might legitimately need to optimise this.

So, here are some options:

1. **Restrict active monsters to those on/near screen.** Any monsters that are far enough offscreen are either completely "frozen" or just wander around. Monsters that are active are kept in a list.

**Pros:** Not only is the list of monsters much shorter, but you can also save work on the actions of "inactive" monsters.

**Cons:** Potential loss of realism, especially if the user can cast a spell to view the entire map, etc.
2. **Chunk by chunk basis.** Divide the map into chunks of (say) 16x16 tiles, and for each chunk keep a list of monsters within the chunk. Like the previous option this considerably restricts the number of monsters that needs to be checked.
3. **Have monster list permanently sorted by x co-ordinate.** For example, if you wanted to check the (x-1, y) tile, you would simply go backwards in the monsters list until you found a monster whose x co-ordinate was x-2 or lower. To check the (x,y-1) tile you would have to go backwards *and* forwards until you hit different x co-ordinates. Intuitively this might seem like it would cut the list from *n* to *√n*, but actually because monsters are quite sparse it will cut it even further.
4. **Keep monster info in the tiles themselves.** Since a pointer to a `Monster` is 8 bytes, if you can cram all the monster information into a comparable amount of storage then you might as well do so. For instance, if you use `unsigned char`s for the monster type and health, you would only use 3 bytes per tile (probably 4 if compiler adds padding). For example:

```
struct Tile {
    unsigned char terrain;
    unsigned char monster_type; //if ==0 then there is no monster here
    unsigned char monster_health;
}
struct Map {
    Tile tiles[100][100];
};

```
5. **Implement some kind of space partitioning trees.** As discussed in this question, you could use Quad-trees or BSP. The main advantage of these over simple chunking (AKA grid system) is that when there are large regions devoid of objects, less space is taken up in the data structure. (The extreme example is space-travel games where there are lots of objects in some areas but others are very very empty.) I don't see any advantage for the typical roguelike. But you can implement it to learn something.
6. **Integrate with pathfinding algorithm.** Your procedural generation probably knows about the rooms and corridors it creates. This can be used to implement efficient pathfinding (e.g. to have enemies home in on the player): by considering the graphs of rooms/corridors and doors, only a few nodes need to be considered, rather than all the tiles. Then, you would need to keep track of which room each monster is in, so you could only consider monsters in the same room. I don't see much point to this aside from coding practice.

By the way, a very very easy optimisation you can do is to not search through your monster list if you know the target tile is empty.

Have fun!
> 0 votes

# Answer
I am also working on a (somewhat/partially) roguelike game, though in C# (using Monogame), not C++. What I am doing is storing all my map objects (monsters, stairs, traps, the player, other NPCs, etc.) in a 2D array of lists.

```
public List<MapObject>[,] MapObjects;

```

This allows there to be more than one map object on one tile (e.g. a flying monster on a trap). The last object in the list is almost always the one that will be interacted with by other objects. It also makes rendering the objects easier if the map is larger than the screen.
> 0 votes

# Answer
What sort of machine are you targeting? If your pointers are 8 bytes (64-bit machine), I'm extremely confused with you saying "ouch", since 9 bytes per tile is *teeny* with a 64-bit addressing space, and actually with padding for proper alignment, it'll tend to be 16 bytes per tile:

```
struct Tile
{
    Monster* monster;
    unsigned char value;
    // 7 bytes padding for proper alignment of 'monster' field
    // assuming 64-bit pointers
};

```

... unless you use a parallel array (SoA rep):

```
struct Map
{
    unsigned char tiles[100][100];
    Monster* tile_monsters[100][100];
};

```

... at which point you can avoid the padding. Still, with 100x100 (10,000) tiles, that's less than `80 kilobytes` for these pointers. That said, I'll just give you the benefit of the doubt and assume this actually matters on the hardware you're targeting or maybe your real example has a hundred million tiles.

**Just Partition One Dimension**

In that case, what I recommend is store a singly-linked list pointer inside your monsters to the next monster in the same *row* of tiles:

```
struct Monster
{
    // Next monster on the same row of tiles or NULL if we're
    // at the end of the list.
    Monster* next_row_monster;

    // Monster position on map.
    int x, y;
};

```

Now for your map, you can store a pointer to the first monster for each *row* of tiles:

```
struct Map
{
    unsigned char tiles[100][100];

    // Points to first monster on a row of tiles or NULL if there are
    // no monsters for a given row (for a given Y position).
    Monster* row_monster[100];
};

```

Now you've cut the map memory overhead down to 1/100th, though it does introduce a pointer to each monster. I'm assuming you have way less monsters than there are tiles for the entire map.

**Why Use 8 Bytes For Monster Positions?**

That said, if you're this concerned about memory use, you're wasting a lot of memory by storing *two integers* (which I assume to be 32-bit) for each monster position. You can just use one:

```
struct Monster
{
    // Next monster on the same row of tiles or NULL if we're
    // at the end of the list.
    Monster* next_row_monster;

    // Monster position on map. To get the x and y values, use:
    //   y = tile / map_width;
    //   x = tile % map_width;
    unsigned int tile;

    // 4 bytes of padding to align 'next_row_monster'.
};

```

... or two 16-bit integers, though that limits the maximum width and height of your map as opposed to using the above method which only limits the total number of cells you can have to a little over 4 billion tiles.

However, as we can see we end up getting 4 bytes of padding again for alignment which brings us to the question, why even use pointers?

**Why Use 64-Bit Pointers?**

How about 32-bit indices?

```
struct Monster
{
    // Index to next monster on the same row of tiles or -1 if we're
    // at the end of the list.
    int next_row_monster;

    // Monster position on map. To get the x and y values, use:
    //   y = tile / map_width;
    //   x = tile % map_width;
    unsigned int tile;

    // No more padding!
};

struct Map
{
    unsigned char tiles[100][100];

    // Indexes the first monster on a row of tiles or -1 if there are
    // no monsters for a given row (for a given Y position).
    int row_monster[100];

    // Array of all monsters in the map.
    Monster monster[num_monsters];
};

```

**Just 400 Bytes More instead of 80,000! 0.5% Memory Use!**

Voila, now you've made it so you only need 400 bytes more than what you started with assuming 100x100 tiles. We didn't increase the memory use of monsters at all since we squashed down the two ints for `x` and `y` into one integer.

With this, when you are checking to see if a monster is on a given tile, you only need to look through the monsters on the same row. You can even *radix sort* the monsters for a given row (using `x` as key) if it gets really crowded and cache the results to an array of monster indices at which point you can do a *binary search* to find a monster at a particular X coordinate on a given row.

And there we have it. We solved your whole problem by just requiring `400 bytes` more in total as opposed to `80,000 bytes`, using only 0.5% of the memory of your proposed solution!

If you can afford to use another 400 bytes, then you store two indices per grid row and partition the monsters to the left half of a row separately away from monsters on the right half of a row, and so on (choosing the appropriate memory/processing trade-off to accelerate searches).

**4-Color DOS Days!**

That said, I haven't needed to squash memory usage down this much in almost 30 years. This is an interesting and fun question making me relive the old glory days of DOS programming with 4-color CGA graphics. I wish there were more like these -- fun stuff! Though this question kind of gave me a mid-life crisis. I miss programming back in the 80s. I actually think programming is harder these days with all the fancy 3D stuff everyone is doing and all the APIs you gotta learn and having to deal with multi-tasking environments. The tools and hardware are absolutely superior, but I miss the old days. Things were simpler back then.

Here is some music from the late 70s and 80s: https://youtu.be/h7LmxEsme94

And some good programming music: https://www.youtube.com/watch?v=ZzQ3eBerHfM
> 0 votes

---
Tags: c++, tiles, optimization, roguelikes
---


# Question
Title: Art style for a character that has frequent visual changes during gameplay
I'm creating a game with a bodybuilding/fitness theme. The camera will almost always be focused on an inclined front view of a character who will be evolving very frequently during the game as the player 'levels up' the musculature of each part of the character such as arms, legs, chest, etc.

I've been doing some research trying to figure out the most economical yet effective way to incorporate this visual mechanic of letting individual parts of a character independently increase in size and detail and have come up somewhat short, most likely due to my complete lack of experience when it comes to art (my experience is mostly in programming).

I was thinking 2D would be best for this game, however maybe this one character should be in 3D? Would a low poly style fit these requirements, or should I look towards something akin to sprites or hand drawings? The games interactivity will be purely through menus so that doesn't need to be taken into account when dealing with the problem of this character. I would like this character to have some animations, of course, however I'm not sure if that fits the scope of this single question.

# Answer
If you're comfortable with 3D modeling, I would recommend looking into blend shapes. They're often used for e.g. customizing faces in RPGs, and should fit your use case quite nicely.

In a nutshell, blend shapes allow you to morph (part of) a shape into another, on top of, say, bone animations. You could create two or three versions of each body part and seamlessly interpolate between them.

(See here for an example or here for Unity's (limited) documentation on the subject.)
> 0 votes

---
Tags: unity, art, clicker
---


# Question
Title: How to make a string[] from the words of a file in Unity?
I have .txt file containing all the English words separated by line breaks.

I want to turn them to a string\[\] so I can easily pick a random one from them.

The way I would do that in normal C# is the File.ReadAllLines(path) function in the System.IO namespace.

But, I don't think that I can use System.IO with Unity so the alternative that I could come up with is the TextAsset class which I can use to reference an imported text asset and get its text property as a string.

But, if I have a giant string how can I simply split it up into individual words and store them as a string\[\]?

# Answer
> 3 votes
You can split a string into substrings with `String.Split`.

When you don't have any whitepsaces in that textfile but line breaks (as in no words with spaces in them) you can use

```
string[] words = yourTextAsset.text.Split();

```

When you do have whitespaces, use the solution from this stackoverflow question:

```
string[] words = yourTextAsset.text.Split(
    new[] { "\r\n", "\r", "\n" },
    StringSplitOptions.None
);

```

(or instead of that hardcoded array with all kinds of line separator flavors, figure out which one is used in your text file)

---
Tags: unity, c#, text, file
---


# Question
Title: How to position objects responsively in SDL?
I have an SDL window using SDL\_WINDOW\_FULLSCREEN\_DESKTOP (as opposed to SDL\_WINDOW\_FULLSCREEN, which doesn't work properly)

When I try to place stuff on the screen, it is placed in the wrong location on Fullscreen mode rather than windowed mode. Since fullscreen and windowed seem to have different proportions/placements, I'm wondering what the best way is to accurately place images on the screen in both windowed and fullscreen mode.

I need to "convert" or "adapt" placement from windowed to fullscreen, so it looks right when fullscreen is toggled.

# Answer
So the first step is to calculate positions using the size of the window. You probably want to use percentages to define the position of an object inside the window. That should result in relatively responsive UI design.

However, there's a small catch here. If you keep the origin of the object that you want to position in the top-left, you might end up with objects not fitting inside the window, and positioning in general can be a big pain.

A nice and generic way to fix this would be to add an anchor vector, that describes where the object's origin is. The vector values should be in the range \[0, 1\], where 0 is top/left and 1 is bottom/right.

So, if `pos` is the percentage position inside the window, and `origin` is the anchor position as described above, the final render position can be calculated as `result = pos * windowSize - origin * objectSize;` (component wise vector multiplication).

So centering an object would mean setting both `pos` and `origin` to `vec2(0.5, 0.5)`.
> 1 votes

---
Tags: c++, sdl2, fullscreen
---


# Question
Title: How to optimize two-pass operations on an array with Unity Coroutines
I am working on simulating vacuum decompression in a 2D top down environment. I have 2 2-dimensional arrays: one that stores the pressure at a location, and one that stores the vector of fluid flow.

The algorithm looks likes this:

```
private void Flow()
{
    Diffuse();
    Vectorize();
}

private void Vectorize()
{
    for(int x=0;x<xRange;x++)
    {
        for(int y=0;y<yRange;y++)
        {
            float myPressure= pressure[x,y];
            [...]
            Vector2 flowVector=calculate_the_resultant_vector_from_the_pressure_differentials //O(1) op
            [...]
            vector[x,y]=flowVector;
        }
    }
}

private void Diffuse()
{
    for(int x=0;x<xRange;x++)
    {
        for(int y=0;y<yRange;y++)
        {
            float myPressure= pressure[x,y];
            [...]
            float newPressure=calculate_the_new_pressure_from_the_pressure_differentials //O(1) op
            [...]
            pressure[x,y]=newPressure;
        }
    }
}

```

The problem is that as the area of the simulation space increases, the performance continues to drop off as the iteration steps block the update loop.

I want to convert these to Coroutines in such a way that both yield but more or less maintain a lockstep appearance. Since flow is dependent on pressure differential, and pressure differential is partially dependent on flow, if an order has to be enforced, then Diffuse should take precedence.

My initial attempt followed the following form:

```
IEnumerable Flow()
{
    StartCoroutine(Diffuse());
    yield return null;
    StartCoroutine(Vectorize());
}

IEnumerable Vectorize()
{
    for(int x=0;x<xRange;x++)
    {
        for(int y=0;y<yRange;y++)
        {
            float myPressure= pressure[x,y];
            [...]
            Vector2 flowVector=calculate_the_resultant_vector_from_the_pressure_differentials //O(1) op
            [...]
            vector[x,y]=flowVector;
            yield return null;
        }
    }
}

IEnumerable Diffuse()
{
    for(int x=0;x<xRange;x++)
    {
        for(int y=0;y<yRange;y++)
        {
            float myPressure= pressure[x,y];
            [...]
            float newPressure=calculate_the_new_pressure_from_the_pressure_differentials //O(1) op
            [...]
            pressure[x,y]=newPressure;
            yield return null;
        }
    }
}

```

This tended to cause a jittery simulation. Even on a small 20x20 simulation field, there was noticeable difference between the first and second solutions.

Are there any tricks to coroutines that will allow a more lockstep simulation that scales well? Any suggestions on optimization is welcomed as well.

# Answer
You seem to be aware of this but I just want to make it clear, the best solution for these kinds of problems is usually to spread calculations over multiple frames. This is especially true when frame perfect data representation is not necessary.

---

Now to answer your actual problem:

Coroutines are still executed sequentially, so you don't need to worry about lock step as long they both yield after the same number of iterations.

Whenever you call yield return null, you're telling your function to wait until the next frame to resume. This can cause things to slow down, since you're waiting a frame for every iteration in your double for.

When I've tackled similar problems, I usually follow a pattern like so

```
IEnumerator Control(){
   while(flag){
      yield return SpinLock(method);
   }
}

IEnumerator SpinLock(){
   StartCoroutine(method);
   StartCoroutine(method2);
   while(running1 && running2){yield return null}
}

```

This control block executes a coroutine, and doesn't launch another until the current completes. The launched runs its two Coroutines and waits for both two complete. They're both operating on the same chunks of data, but since they sleep at the same count, one doesn't get ahead of the other.

As for the other methods, I'd do something like this:

```
int perFrame;
IEnumerator doWork(){
    int counter = 0;
    runningX = true;

    for(int x = 0; x < stuff; x++){
        for(int y = 0; y < stuff2; y++){
            doStuff()

            //yields for next frame.
            //you can make this a fraction of the total, or a magic number, both have their uses.
            if(counter > perFrame) {counter = 0; yield return null;}
            counter++;
        }
    }

    runningX = false;
}

```

This tells the function to do up to perFrame calculations, then rests. Since the function that calls it isn't waiting, both functions should do the same amount of calculations (in sequence), wait for end of frame, then resume on the next frame.

You can choose to work with the mixed dirty/clean data, or you can update your utilized matrix every iteration

---

If those 2D arrays are just data, you may be able to use actual threads in your Vectorize and Diffuse methods to take advantage of parallelism. The implementation should mostly be the same.
> 2 votes

---
Tags: unity, optimization
---


# Question
Title: Virtual Reality without source code access is it possible
Hey is it possible to make a pc game that has no access to source code to the community support virtual reality.... I need answers tonight.......

More in depth I need to know how to make a game that has no access to the source code make it support virtual reality so this means i have no source code of that game example game "fear pc from monilith" it has no source code to the community so how do you do it......

# Answer
> Can I run third-party games on a VR device without access to the game's source code?

There are already tools out there (like VorpX) that can intercept low-level rendering calls and replace them with modified rendering calls to show a VR-display-compatible image. I haven't personally tried them out, and it seems like the VR quality can vary between games, but the answer to "is it possible" should be **yes**.
> 2 votes

---
Tags: c++
---


title: Declare a struct in a function

text:
# Question
Title: Declare a struct in a function
I am creating a game that sometimes crashes and i am asking if this could be the cause. Take this code:

```
struct SDL_FloatRect
{
    float x, y;
    float w, h;
};

void random_func()
{
    SDL_FloatRect rect;
}

int main()
{
    ...
    while(1)
    {
        ...
        random_func();
        ...
    }
}

```

As you can see.. there is a rect created every frame. I sometimes create them for satisfying some functions parameters (for example a function parameter is of type SDL\_Rect but i have only x and y). I don't know if this causes memory leak Or something like.. (But i know that at the end of a function, variables get destroyed) Thanks

# Answer
> 1 votes
This does not leak because the rect memory is allocated on stack (in opposite to heap allocation) so it is deallocated when the random\_func returns.

The information you have provided is not enough to diagnose the crash. A crash dump or some more code would be helpful.

---
Tags: c++, sdl2
---