# Question
Title: Are loading screens more important than they appear to be?
I am creating a game in Unity that is really low poly and uses few resources on mobile. It runs quite fast on old, low end phones so the new, high end phones have no problems running it. There are no load times between scenes which makes the game load each scene instantly, yet this gives a sense of simplicity and that the game is really cheap.

So here is my question: would the implementation of a "fake" loading screen give the player the feeling that the game is complex and create that transition between scenes? Or should I stick with the fact that everyone hates loading screens and therefore should leave the game as it is? What other options could I use to convey the feeling to the user of complexity despite the low graphics?

# Answer
It seems like you lack some form of **transition** between one scene and the next. Moving the player from one UI context to another instantaneously can feel quite jarring. Also, not giving the player any chance to breathe between levels can create a problematic pacing. Both could be what you perceive as a certain "cheapness".

A loading screen is one form of transition, but artificially adding a pointless loading bar which actually does nothing would be quite ridiculous. There are many other forms of transition graphic effects you can use to mentally remove the player from one context and put them into another. Just some examples:

* Fade to black, like DisturbedNeo suggests
* Do some form of wipe transition. This can also be combined with fade-to-black to do a wipe-transition to black and then another wipe-transition from black to the next level. The combination with black might be easier to do because it doesn't require both scenes to be loaded at the same time.
* Zooming in and out again
* Blurring and unblurring
* When entering/leaving a menu, animate that menu to visually move into/off the screen
* When switching between levels:
    + pause the game to have the player-character perform an animation
    + show a level statistics screen and have the player click/tap a "next" button
> 4 votes

# Answer
Loading screens exist as a feedback mechanism to let the player know that the game is loading things and hasn't simply frozen or otherwise crashed. If your loading times are basically non-existent, there's no reason to have a loading screen anywhere, especially if your app doesn't actually need them. People complain a lot about long loading times (See Super Smash Bros. Brawl for a good example), so I think it would be detrimental to artificially cause that.

A much better system, assuming you can't create something seamless with a loading time of 0, is to have a **Fade To Black** in place. Say you're playing a game, and you have a nice looking menu with a slightly animated background, what looks best to you:

1) *No transition* \- You select "New Game", the animated background freezes for about half a second, then the game starts.

2) *Loading Screen* \- You select "New Game", the screen changes to a loading screen that takes a few seconds to "Load", then the game starts.

3) *Fade Transition* \- You select "New Game", the screen fades to black, hiding everything from view. The screen then fades back in, and when it does, the game has already loaded and everything is running smoothly.

The fade transition works because, unlike the other options, it doesn't break the player's ***Immersion***, which is very important, but it can also be adjusted to fit slightly longer load times simply with a slightly slower / longer fade.

I'm sure there are a million ways in which you can achieve a seemingly seamless transition, but I find that the **Fade To Black** is simple and easy to implement whilst still being very effective.
> 2 votes

# Answer
Remove loading screens altogether if the response time is less than 1 second is a good rule of thumb, since if it is longer and you don't have loading screens, the user will think "what is happening", but if the response is less than a second, they probably wont notice. Otherwise, a loading screen gives sense of progression and that the game is actually working. If the user thinks the game isn't actually doing anything, it will frustrate them.
> 0 votes

---
Tags: unity, game-design
---


# Question
Title: How can I use ARB_debug_output with SDL on Windows?
I'm trying to port a small GL program that I've been working on from Linux to Windows. I have the following:

```
window_ = SDL_CreateWindow(...);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
glContext_ = SDL_GL_CreateContext(window_);
glewInit();
if (GLEW_ARB_debug_output)
{
    glDebugMessageCallbackARB(&DebugCallback, nullptr);
}

```

I was surprised to find out that `GLEW_ARB_debug_output` evaluates to false. Could it be that `ARB_debug_output` not supported on Windows, with the latest drivers for my video card (an older Radeon HD540v)? Am I doing anything wrong? I thought this extension was rather old, and it would probably be supported everywhere by now.

**Update:** I added my SDL initialization code, as I needed to pass `SDL_GL_CONTEXT_DEBUG_FLAG`. Unfortunately, `ARB_debug_output` is still not supported.

**Update:** After initializing the context with the debug flag through SDL, I manually queried the available extensions (bypassing GLEW) and `ARB_debug_output` is not available! Again, could this not be supported on my implementation?

# Answer
`ARB_debug_output` requires, I believe, the context to have been created with WGL\_CONTEXT\_DEBUG\_BIT\_ARB via `wglCreateContextAttribs`. That function is itself an extension, which means that GLEW probably cannot properly acquire the function pointers to the `GLEW_ARB_debug_output` functions because it will not have made use of that extension function to set the debug bit on the context.

You will probably need to manually set up the extension function pointers for `GLEW_ARB_debug_output` (like we had to do in the dark ages) after creating a context with `wglCreateContextAttribs`.

This chicken-and-egg issue with GLEW was noticed back in 2011 or so (`ARB_debug_output` is from 2010), but GLEW's change log doesn't make an obvious mention of a solution beyond mentioning when it acquired `ARB_debug_output` support.
> 3 votes

# Answer
### There are a couple of important things to note here:

1. AMD did not always implement `ARB_debug_output`. Technically, `ARB_debug_output` is an improved version of AMD's original extension: `AMD_debug_output`. Older AMD drivers lagged behind NV in adopting the ARB'ified version of AMD's own extension.

* Now here is where things get really funny: `GL_KHR_debug` is yet another improvement on the ARB extension. There are theoretically implementations of OpenGL that support neither AMD nor ARB's debug output but do support `KHR_debug`. At its core (no pun intended), however, the KHR extension re-uses the same function names, enums and constants (but without the ARB suffix).
2. This extension is generally only listed if you query the extension string while you are running in a debug context.

* More importantly, GLEW is rather stupid when it comes to querying extensions by name and uses `glGetString (GL_EXTENSIONS)`, which is invalid in core contexts. The macros such as `GLEW_ARB_debug_output` reflect whether the extension is listed in the extensions string (which GLEW may not even be capable of querying if you are using a core context).

### I would suggest you initialize GLEW this way instead:

```
/**
 * Tells GLEW not to use the extension string.
 *
 *   Instead, it determines if an extension is supported by actually trying to load it.
**/
glewExperimental = GL_TRUE;
glewInit ();

if (glDebugMessageCallbackARB != NULL) {
  // Debug Output is supported, hooray!
}

```

---

By the way, the extension `GL_KHR_debug` has one other benefit that `GL_ARB_debug_output` does not. You can look for this extension by name (assuming you properly query the extension string) whether you have a debug context or not. A non-debug context created by an implementation of OpenGL that supports debug output is guaranteed to list this extension, whereas it may not list `GL_ARB_debug_output`.
> 1 votes

# Answer
Your code *should* work as it is.

In general, all you need to do is set the debug flag before creating the context and then query the extension.

The code I'm currently using (SDL+GLEW; error checking omitted for brevity):

```
// Get the current context flags and add the debug flag
// (so we don't accidentally reset any default flags)
int contextFlags = 0;
SDL_GL_GetAttribute(SDL_GL_CONTEXT_FLAGS, &contextFlags);
contextFlags |= SDL_GL_CONTEXT_DEBUG_FLAG;
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, contextFlags);

// Create window and context
SDL_Window* window = SDL_CreateWindow(...);
void* context = SDL_GL_CreateContext(window);

// Init GLEW
glewInit();

// Set debug callback function
if (GLEW_ARB_debug_output) {
    glDebugMessageCallbackARB(&DebugCallbackARB, nullptr);
}
else if (GLEW_AMD_debug_output) {
    glDebugMessageCallbackAMD(&DebugCallbackAMD, nullptr);
}

```

So, the only real difference I can see is that you don't check for `GLEW_AMD_debug_output`. I have actually never tried this on a system which didn't have `GLEW_ARB_debug_output` set, so I'd be interested to hear if this fixes it for you (if this is still relevant after 2.5 years).

Note that the callback functions have slightly different signatures:

```
void DebugCallbackARB(GLenum source,
                      GLenum type,
                      GLuint id,
                      GLenum severity,
                      GLsizei length,
                      const GLchar* message,
                      const GLvoid* userParam);

void DebugCallbackAMD(GLuint id,
                      GLenum category,
                      GLenum severity,
                      GLsizei length,
                      const GLchar* message,
                      GLvoid* userParam);

```
> 1 votes

---
Tags: opengl, windows, glew
---


# Question
Title: Unity - Check if sprite is within range around player
I need to know if a sprite is within range (circle or square doesn't matter) around the player. If the sprite is, let's say, 100 blocks away from the player, I will disable it. This wouldn't be too much of an issue, just compare positions and you're done. However, my game is a tile based game and I want the world to be as big as possible, which will result in millions of sprites.

I could also add a overlapcicle2D, but the problem is this these objects can't have a collider, since they could be walkable.

So how can I check if the millions of sprites are in range of the player, without lowering performance?

Alternatively, I could add occlusion culling. But how do you do this with sprites?

# Answer
You may not need to include Occlusion Culling for a 2D game in Unity.

Unity has a thing called *FrustumCulling* that hides any object not in view of the camera. In a 3D game, this isn't always ideal because the frustum doesn't account for distance, meaning that the game would still do things like render rooms behind doors that you can't technically see. However, in a 2D game, you don't need to worry about that, because it's 2D, there's literally no distance to worry about. So, assuming that "100 blocks away from your player" actually means "Outside of the camera view", they're possibly already being culled anyway.
> 1 votes

# Answer
If you're simply trying to minimize resource impact, @DisturbedNeo is right on the money. If there are other reasons you'd like to do this, you could always use a VERY large collider and check for objects inside of it that meet a certain tag criteria.
> 0 votes

---
Tags: unity, 2d, culling, occlusion, tiles
---


title: Access a Private GameObject in Unity

text:
# Question
Title: Access a Private GameObject in Unity
Hope you bear with me, I'm a beginner! Maybe I should've paid better attention to the tutorials but they all seem to use public variables/game objects that we can then drag into using the Unity Editor. However, if I have a private Game Object, how can I reference that programatically? I have the following:

```
private GameObject menuCanvas;

void Start()
{
menuCanvas = GameObject.Find("menuCanvas");
menuCanvas.SetActive(false);
}

```

Where the menuCanvas is named such in the Unity editor. However, I usually get the following error:

"The variable menuCanvas of myScript has not been assigned."

myScript is attached to a different GameObject in the scene, but not attached to menuCanvas. What am I doing wrong? Thanks for the help!

Edit: another question - which is generally better to use?

Edit 2: Hi guys, I figured it out. I had to move some code around to the Awake() function, so it looked like this:

```
private GameObject menuCanvas;

void Awake()
{
menuCanvas = GameObject.Find("menuCanvas");
}

void Start()
{
menuCanvas.SetActive(false);
}

```

And that worked. I realized that myScript was attached to multiple objects, which would cause the menuCanvas to be set inactive more than once (but it could not be referenced inactive).

S. Tarık Çetin's answer worked just as well! Thanks for the help

Edit 3: As Jesse Williams answered, an `internal` definition keeps the variable hidden from the editor, but it can still be assigned via code.

# Answer
Normally Unity serializes only public fields, to prevent confusion in inspector. But you can force Unity to serialize private fields by adding `[SerializeField]` before the decleration.

So this should do the trick:

```
[SerializeField] private GameObject menuCanvas;

```

Then you can assign it in inspector.

---

For the question in your edit: It is always better to use private variables unless you have a reason to do otherwise. If you want to expose something to public use, best option is to use *properties*.
> 2 votes

# Answer
If you want to have Unity serialize your data you can use the approach in S. Tarık Çetin answer and mark private members with `[SerializeField]`.

EDIT: Actually this really exposes the variable as S. Tarık Çetin said. So you are good with this approach. But I think this was not your main concern.

What you are trying can not work that way because the command `GameObject.Find(string name)` finds a game object with this name and returns it (see Unity Documentation for GameObject.Find). So you have to set the name via the inspector or the "name" variable that every GameObject has.

EDIT: Not relevant anymore, but this approach gives you the ability to use properties instead of variables in the inspector. A long with a lot more like custom user interfaces (buttons etc.).

If you want to access a private variable via the inspector you have to write a separate editor class: Unity Documentation for Custom Editors.

For your example:

```
using UnityEngine;

public class ExampleClass : MonoBehaviour
{
     [SerializeField]
     private GameObject menuCanvas;

     public GameObject MenuCanvas
     {
         get { return menuCanvas; }
         set { menuCanvas = value; }
     }

     ...
}

```

And then your second class:

```
using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(ExampleClass))]
public class ExampleClassEditor : Editor
{
    public override void OnInspectorGUI()
    {
        // render the rest of the GUI
        base.OnInspectorGUI();

        // cast the internal reference
        var obj = (ExampleClass)target;

        // create an entry in the inspector
        obj.MenuCanvas = (GameObject)EditorGUILayout.ObjectField("Menu Canvas", obj.MenuCanvas, typeof(GameObject), true);
}

```

The editor class has to be in a subfolder namend "Editor".

In tutorials you usually just want to get something going so this dual-class approach is dropped for just a `public`.
> 0 votes

# Answer
I may be missing the point of the question, but if scope is an issue, and you need to access the variable from another script or another scope, but don't want the inspector objects visible, you can initialize it as `internal` rather than `public`. It will behave as a public variable, but not show in the inspector.
> 0 votes

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


# Question
Title: Unity error converting quaternion to euler rotation
When I try to run my game in unity, it comes up with the error:

```
No appropriate version of 'UnityEngine.Quaternion.Euler' for the argument list '(UnityEngine.Quaternion)' was found.

```

When using the update code in (written in javascript):

```
transform.Rotate(Quaternion.Euler(transform.rotation * Quaternion.Inverse(GameObject.Find("Main Camera").transform.rotation)));

```

Any help would be appreciated.

# Answer
> 0 votes
`Quaternion.Euler` creates a Quaternion from three euler angles either by parameter list of floats or a Vector3 of the angles, not from a Quaternion (see docs):

```
public static Quaternion Euler(float x, float y, float z);

```

OR

```
public static Quaternion Euler(Vector3 euler);

```

Did you mean to write:

```
transform.Rotate((transform.rotation * Quaternion.Inverse(GameObject.Find("Main Camera").transform.rotation)).eulerAngles);

```

eulerAngles

---
Tags: javascript, unity
---


title: UE4 - openGL context

text:
# Question
Title: UE4 - openGL context
Is there a way to get an openGL context to do my drawings in UE4?

I'd like to use some shaders before the loading of a scene (kind of an intro thingy), but I couldn't find anything related to get an openGL context.

# Answer
It's not an appropriate answer, but you can do this... You may go deep inside UE4 source code, rewrite the things you need; since it has free access it's possible. But it will hurt, promise you.
> -1 votes

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


# Question
Title: Legally possible to re-create/remake an old game?
Recently I started remaking an old game on Unity. Basically I want to remake an old RPG that was released for Playstation 1. I'm not ripping anything from the old game, all the assets are being created by me. I'm creating everything from the scratch, music, 3D models, gameplay however I will keep the (copyrighted ?) names, I will try to create the characters and maps/levels as they were in the original version of Playstation 1 but with better graphics.

I'm not planning on selling it or adding in on a platform like Steam (for obvious reasons, copyrights etc), just giving it for free. But I wanna know when I will finish the development, can I share the game on public with other people so they can download it?

Can the company that made the original game sue me/fine me because of copyrights reasons even though I'm not planning on selling for money?

tl;dr Remake an non-profit game of PS1 from the scratch, can the company that holds the copyrights of the game sue me/fine me?

# Answer
> 0 votes
You can't keep the real names nor the same level structure with improved graphics. That will be a partial remake of a game and that is forbidden by law, even if you are not charging money for the game. You can however copy the style and make it very similar without infringing copyright. Take banjo kazooie and it's rebirth from the same developer Yookay Laylee, or the most recent mighty number 9 which is from the same creator from megaman. Both games keep the same gameplay and core features from their originals; however, feature new characters, new levels and completely different assets. For further proof you can see that in both examples I mentioned, the creators of the original game are the ones that created this different "remakes" and yet they can't use the same assets they created years ago.

---
Tags: legal, copyright
---


# Question
Title: Faces on 3D model not rendering in the correct
I seem to be having trouble with rendering models in monogame. I'm trying to draw several cubes, in a minecraft style world. It's a simple .obj file, nothing special. But... for whatever reason, both the top and the bottom are rendering over the sides, as can be seen here in these four cubes.

My code is simple as can be, so I can't imagine the problem is directly the fault of this:

```
public static void DrawModel(Model model, Matrix modelspace, Texture2D texture)
    {

        foreach (ModelMesh mesh in model.Meshes)
        {
            foreach (BasicEffect effect in mesh.Effects)
            {

                //effect.EnableDefaultLighting();
                effect.TextureEnabled = true;
                effect.Texture = texture;
                effect.World = modelspace;
                effect.View = Cameraworks.ActiveCamera.View;
                effect.Projection = Cameraworks.ActiveCamera.Projection;
            }

            mesh.Draw();
        }

    }

```

How do I fix this?

# Answer
> 0 votes
It turns out, it was because of a previous SpriteBatch call causing the GraphicsDevice settings to be changed. Putting this code in before my model drawing code executed fixed it, and now it draws correctly.

```
GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;

```

---
Tags: rendering, monogame, models
---


# Question
Title: In PhaserJS, how do I get a clicked Physics.P2 body's data?
I have a sprite with `Phaser.Physics.P2` enabled, using a custom shape loaded with `loadPolygon()` from a `.json` file. I have also activated its **debug** and **debugBody** properties, so I can see the custom shape:

How could I collect the shape data information when I click on the debug shape?

For example, if I were to click the head of the sprite, can I get the polygon information from the click event?

# Answer
> 1 votes
You could take a look at how phaser debug works: https://github.com/photonstorm/phaser/blob/v2.4.2/src/physics/p2/BodyDebug.js

On line 90 you have the 'draw' function that shows you how phaser draw the shapes.

If you take a look at the last part of the function you can have a way to get the verts of the polygons of each shape:

```
verts = [];
vrot = p2.vec2.create();

for (j = _j = 0, _ref1 = child.vertices.length; 0 <= _ref1 ? _j < _ref1 : _j > _ref1; j = 0 <= _ref1 ? ++_j : --_j)
{
    v = child.vertices[j];
    p2.vec2.rotate(vrot, v, angle);
    verts.push([(vrot[0] + offset[0]) * this.ppu, -(vrot[1] + offset[1]) * this.ppu]);
}

this.drawConvex(sprite, verts, child.triangles, lineColor, color, lw, this.settings.debugPolygons, [offset[0] * this.ppu, -offset[1] * this.ppu]);

```

So what you can do is, on click event, get the X and Y of the click and then, create a polygon for each shape (modifying the code from above) and for each polygon, check if it contains the position of the click.

---
Tags: 2d, physics, phaser, selection
---


# Question
Title: add physics to a group or container body in phaser
I'm developing a HTML5 Phaser game. In this game I do have a Group which I would like to behavior as a physics body (arcade-physics).

It is a character with a lot of moving parts (sprites) inside this group. In this case the group acts like a container for the sprites.

However I only able do add physics behavior to a sprite.

```
game.physics.arcade.enable(mySprite); // works good!

```

Doing the same to a group does not works. it only add physics to children sprites

```
game.physics.arcade.enable(myroup) // does no works
myGroup.body.(...)  // body is undefined

```

I would like to create a "virtual" body to this group, mannually set dimensions for it (body.setSize) and add all my sprites inside it. Is that possible in any another way?

# Answer
I think you can't do it.

Phaser groups doesn't have body: http://phaser.io/docs/2.4.4/Phaser.Group

But you can use setAll method to set properties to all sprites of a group: http://phaser.io/docs/2.4.4/Phaser.Group.html#setAll

Otherwise, if you want more complex objects you could try another type of physics (P2) and make complex bodies with polygons.
> 2 votes

---
Tags: physics, javascript, sprites, phaser, body
---


# Question
Title: why the camera won't rotate around my object?
im new to unity scripting, and now am building upon "Roll a Ball" example in unity training. I wanted to make the camera rotate around the ball in the scene in Y axis, when mouse is moved, and watched some tutorials on it, and eventually wrote the code below. but it doesn't rotate around the ball. instead it does a simple rotate in place. camera still moves with the ball though. what am i doing wrong?

```
public class CameraController : MonoBehaviour {

    public GameObject Player;
    private Vector3 offset;

    public float moveSpeed;
    private Vector3 point;

    void Start () {
        offset = transform.position - Player.transform.position;

        point = Player.transform.position;
        transform.LookAt(point);
    }

    void Update()
    {
        float mouseMovement = Input.GetAxis("Mouse X");

        transform.RotateAround(point, new Vector3(0f, mouseMovement, 0f) , moveSpeed * Time.deltaTime);
    }

    void LateUpdate()
    {
        transform.position = Player.transform.position + offset;

    }
}

```

# Answer
Your problem comes from setting the position of the camera in late update. Change your LateUpdate code to something like this and remove the code from Update

```
 void LateUpdate()
    {
        offset = Quaternion.AngleAxis(Input.GetAxis("Mouse X") * turnSpeed, Vector3.up) * offset;
        transform.position = player.position + offset;
        transform.LookAt(player.position);
    }

```
> 3 votes

---
Tags: unity, c#, camera, rotate
---


# Question
Title: Unable to save player data in a binary file within Update() method
I'm trying to save player life within a binary file in Application.persistenceDataPath. I've written a method to store the player life:

```
  public void SaveLife()
     {
         BinaryFormatter bf = new BinaryFormatter ();
         FileStream file = File.Open (Application.persistentDataPath + "/playerInfo.dat", FileMode.Open);
         PlayerData data = new PlayerData ();
         data.savedLife = life;
         bf.Serialize (file, data);
         file.Close ();
     }

```

The problem is that when the SaveLife() is called OnApplicationQuit it works. Instead, if I call it within an Update() method of a class, it doesn't work.

The Update() method is called when a certain event is triggered:

```
void Update()
{
    if (life < 20)
    {
        if (//certain event is triggered)
        {
            SaveLife();
        }

        lifeTimer -= Time.deltaTime;
        if (lifeTimer <= 0)
        {
            ResetLife ();
        }
    }

}

```

The container class for the data is

```
[Serializable]
 class PlayerData
 {
     public int savedLife;
 }

```

What could be the problem?

# Answer
> 1 votes
The problem was caused by another `SaveTime()` method in the same script that was writing to the same file "playerInfo.dat".

```
public void SaveTime()
{
    BinaryFormatter bf = new BinaryFormatter ();
    FileStream file = File.Open (Application.persistentDataPath + "/playerInfo.dat", FileMode.Open);
    PlayerData data = new PlayerData ();
    data.savedTime = DateTime.Now;
    bf.Serialize (file, data);
    file.Close ();
}

```

Since in `SaveTime()` I was instantiating again `Player data`, this seems to cause the old `Player data` created by `Update()` to be substituted.

I solved the problem by instantiating `Player date` only once in the main body of the script.

---
Tags: unity, binary
---


# Question
Title: FBX animation works in 3DSMax but not with Assimp
I have an FBX file that represent a **plane with an animation of the gear opening**. In my editor 3DSMax or in the Unity editor, the file and animation seem good, but when I use Open 3D Model(*the official viewer of Assimp*) or when I call the FBX file simply in an application, to see what the file will look like with the use of Assimp, I got some issues.

The object seems normal at the beginning, but when I try to launch the animation, **all my animated elements are going crazy**.

*Here's what it looks like* :

Here's my FBX FILE

Do you have experience something similar ? Does it come from my file or a parameter in Assimp ?

I am beginning to think that there is a problem with how Assimp handles pivot points, looks like objects are rotating using a different pivot point in Unity/open3mod.

# Answer
> 1 votes
I had the same issue when I was attempting to make a model for a UAV in Blender and import it to unreal engine. I think I recall as a solution I just redid my bone weights and it fixed the problem. Then i rotated the model to go the direction I wanted to in unreal.

# Answer
> 0 votes
Typically you need to zero out any transforms before you export into an exchange format or else it's bound to go totally crazy on the other end.

That could be the issue.

It could also be a bug in the exporter or in how assimp reads it. File formats like FBX are very complicated and this is very common.

If you export the animation/skeleton separately it's also important that you export the exact same things (same selections) and make selections of nodes in the same way or it will also probably fail.

In short it could be many things and it is very hard to diagnose it exactly without sitting on your computer and/or looking at the file contents themselves.

---
Tags: unity, 3d, 3dsmax, fbx, assimp
---


# Question
Title: How can I detect handedness of normal maps in a shader?
I've implemented normal maps into my game renderer using the formulas by Christian Schuler.

It works OK with most normal maps but some not so much since in some the Y component (green) is reversed. Apparently there is no real standard here and Maya does it one way and Max does it the other way.

I'd like to be able to look at a normal map's values and somehow determine which scheme is being used, if that's possible.

Also, though I have not actually seen any, some normal maps appear to use only two channels and the third channel is left blank and calculated at runtime. Ideally I would be able to detect those, too. I figure maybe the Z channel is all zeros? I am not sure that would save any space though so maybe it is some other scheme.

Seems like an obvious desire, but I don't see any references to this. but then, maybe it's not really possible.

# Answer
> 2 votes
There's no good way to detect different data formats from each other in shader code.

In general you should always give the same kind of data to your shaders. You need to pre-process your data before drawing with it. Pick one format and convert all data to that, and then write your shaders to use that format.

One other way is to detect the format before you start drawing and then use separate shader made for that spesific format.

---
Tags: geometry, normal-mapping
---


title: Bukkit Scheduler not in main Class

text:
# Question
Title: Bukkit Scheduler not in main Class
I want to make an Repeating Task whisch isn't in the main Class. ("Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {},20,20);")

But it says that it can't resolve the method.

# Answer
Instead of the `this` you need to pass an instance of the main class to the method. You can achieve this by using the constructor. When you create the Listener class (wich shouldn't be named listener BTW) you need to pass the instance of the main class to it.

```
//Listener class
<Main class> instance;
public Listener(<Main class> instance) {
    this.instance = instance;
}

Bukkit.getScheduler().scheduleSyncRepeatingTask(instance, new Runnable() {...});

//Somewhere in the main class
Listener listener = new Listener(this);

```

Make sure to use `this` when you pass the instance of the main class to the listener, because if you use `new <Main class name>()` it will throw an exception.
> 0 votes

---
Tags: java, minecraft-modding, bukkit
---


# Question
Title: How can I consistently map mouse movements to camera rotation?
I am writing a OpenGL game engine and also an editor for the engine. In my editor, I can import 3D models from FBX/Collada as a scene graph. Now I want to implement the option for the user to rotate and the camera in the viewport using mouse.

I found many links to rotate the camera by some angle based on the delta x and delta y of the mouse. This is fine. But my problem is selecting the axis for rotation.

For example, if the user moves the mouse in the x axis, I am changing the camera's local rotation angle along y axis (the up axis). But this is not always working. In case if the camera node's parent node is rotated 90 degree in the x axis, when I change the camera's local y axis rotation angle, the scene is rotating in wrong direction. So in this case I have to rotate the camera's z axis angle.

This is my problem. So how can I ensure the camera always finally rotate left and right (whatever the parent nodes' angles are rotated) when the user moves the mouse horizontally?

Also I want to mention that when the user moves mouse up and down, I want the camera to rotate up and down always.

# Answer
> 1 votes
The problem you are experiencing is called `Gimbal Lock`.
There are some ways to circumvent this problem. One possibility is to use Quaternions. There are plenty of resources on the web about them so I won't go to deep into the details here.
Quaternions are fast but not very intuitive for a 3D editor. But it is possible to convert Euler angles to Quaternions. There even is a Wikipedia article here. Quaternions also enable you to interpolate between two orientations which is very hard when working with Euler only.

Some resources to get you started:
I also liked this article which contains some nice examples how to work with Quaternions: OpenGL Tutorial 17 : Rotations
This one from gamedev.net has some nice explanations and examples too: Gamedev.net Quaternion Powers

I hope this helps you to get started.

---
Tags: opengl, 3d
---


# Question
Title: How to test an android game made in Unreal Engine 4
I have made a android game in unreal engine 4 version 4.12.4 and I want to test it on a real android device and i do have an android tablet but i don't know how to get the exported project onto the tablet for testing so can someone tell me please?

# Answer
> 1 votes
Pressuming you have the android sdk installed:

Put your phone into developer mode plug it into the computer, and enable adb

Open command prompt and navigate to the adb folder inside the sdk

```
adb devices

```

after this type:

```
adb install apkname.apk

```

or the other way enable allow installs from unkown sources put the apk on your phone navigate to it and then open it and install it that way but the first option is easy enough to make an install script for when you update it.

**Hope this helps**

Jordan

---
Tags: android, unreal-4, testing, unreal
---


# Question
Title: Implementing an interaction system that can perform different tasks dependant on the object you are trying to interact with?
In No Mans Sky there are objects to interact with in the world and the result of the interaction changes depending on the object. For example, if you interact with a plant it will give you resources but if you interact with the save point it will save the game. I was wondering if it would be efficient to add an 'Action' class that had different methods for each different action (save(), grab resources(gameObject)), then call each action depending on what object you are interacting with...

Another possible solution I came up with is to have a base class of 'Action' and have each action as a script that inherits from this class, then attach them as a component to the interactable objects. Then have the interaction system check if it has an 'Action' script and perform that action if required.

I am just wondering if any of my solutions would be effective, or if there is a much simpler way around this problem that I am missing.

# Answer
I would implement this with an abstract base class `Interactable` which inherits from MonoBehaviour and has an abstract method `public abstract void Interact(Player player)`.

Any object the player can interact with would then have a component which extends that abstract base-class and provides an object-specific interaction method.

To call that method form the player-class, use:

```
Interactable interactable = otherObject.GetComponent<Interactable>();
if (interactable != null) interactable.Interact(this);

```

GetComponent also returns components which inherit from the provided class, so it will give you any component which extends Interactable.

Another option is to use Unity messages. When the player tries to interact with an object, call `otherObject.SendMessage("Interact", this)` to send an "Interact" message to all components of the object. This will call a method "Interact" on any component of that object which has one. The nice thing about this is that you can have any number of components on an object which handle interactions.
> 1 votes

# Answer
The Command Pattern seems like it would be useful here. First I'd classify the various types of interactions, associating each interaction with a command slot on your desired object. With this setup you can add command instances to and remove command instances from these slots on the object based on the state of the game. This approach is pretty flexible and dynamic as you can swap out commands so that the object can respond in different ways to a given type of interaction.
> 0 votes

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


title: Isometric map black screen

text:
# Question
Title: Isometric map black screen
I am trying to create an isometric map and I am very new to it. Please see the attached example map. While rendering it I've noticed that when my actor reaches the edges of the map the player can see the black screen after it which is not very nice. I wonder what are the best practices of dealing with it ? Do I need to show the black screen where the map ends, if not then what's the best way to avoid/hide it?

# Answer
There are several options:

1. Have a non-scrolling background image which is more attractive than just pure black. This might make the game appear a bit more abstract. (example from Disgaea D2)
2. Add a decorative border which looks as if the game takes place on a tabletop or similar (Example from Rings of Power)
3. Design your maps with a non-reachable border region which is so wide that the player never moves close enough to the border to actually see it. This might be the most immersive solution but also the one which takes the most work because your maps need to be far larger. It also requires that the camera is bound to the player's position and that you can always come up with plausible obstacles to limit the player's movement.
4. Have the map loop around so there is no actual border the player can reach. This only feels plausible with very large maps which represent the surface of a complete planet.
5. Just stop scrolling when the player reaches the edge of the map (doesn't work well with a diamond-shaped map but works well with a square one).
> 2 votes

# Answer
There are multiple ways to solve this issue.

The first way to solve this would be to use procedural generation and simply create more terrain on the fly when the player reaches the edge of the map. Depending on what you currently have, this could be pretty hard to achieve.

The second would be to add walls to the map, so the player can't reach the edge of it. These don't need to be invisible walls, like some games do it (even AAA games). You can simply include some rocks or bergs there.

The third (and arguably the hardest) method would be to make the game world loop around, so if you reach one of the side of the world you see the other one, kind of like on a real globe.
> 0 votes

---
Tags: unity, libgdx, tilemap, maps, isometric
---


# Question
Title: Can I set the origin of the texture to its center in OpenGL?
I want "texture2D(texture, vec2(0,0))" to fetch the pixel at the center of the texture and "texture2D(texture, vec2(-1,-1))" to fetch a pixel from the corner of the texture. I don't want to calculate from (-1,+1) to (0,+1) like s\*.5+.5 I don't want that.

Is there some command that I can use to configure the hardware that way?

# Answer
Not really.

In older, non-modern versions of OpenGL you can use `glMatrixMode` to activate the `GL_TEXTURE` matrix stack, and then push a scale and/or translation matrix that offsets accordingly. UV coordinates will be multiplied by the texture matrix prior to resolution.

But those functions are deprecated in modern OpenGL, because it's trivial to do them in a shader by offsetting the values you pass to `texture2D` directly. There is no facility to implicitly offset the texture origin in modern OpenGL.
> 1 votes

---
Tags: opengl
---


# Question
Title: Distance between the player and another object Unity
Edit: I want to find the distance between the player another object. How do I do that?

this is what I tried:

```
public GameObject other;

void Update()
{

    float dist = Vector3.Distance(other.transform.position, transform.position);

    print("distance " + dist)

}

```

which didn't seem to work

# Answer
> 2 votes
To achieve that task, you can use BoxCollider2D or PolygonCollider2D. Attach it to both objects, but make it 5 pixels larger for the first object.

Then write code, that kills the object, in the OnTriggerEnter2D / OnCollisionEnter2D event handlers.

To destroy the object you can use method Object.Destroy, just pass the desired gameObject reference to it.

Here's the reference materials: BoxCollider2D

Also, you can cast rays of limited length, how to do so described in the following link:

How to cast ray2d in Unity

Also, I strongly advice you to learn through this section and watch all the materials, because what you've asked is really basic question, you should at least watch the tutorials in the learn section on Unity site, so you won't ask the questions like this in the future.

Here it is, please watch it

# Answer
> 0 votes
You can measure squared distances:

```
var sqrMagn = (target.position - transform.position).sqrMagnitude;

if(sqrMagn <= squaredTriggerDistance)
{
    Destroy(gameObject);
}

```

Change `squaredTriggerDistance` to a value you want.

---
Tags: unity
---


# Question
Title: How to design the AI for a board game like Risk?
I am about to develop a web game that is similar to board games like Risk, and iOS games like Lux and Strategery. I am curious to know what the concept behind the AI for such games should be like.

I know it's going to involve a lot of move calculations and and calculating all possible options. But can someone elaborate on this please? I am actually a web programmer who usually develop websites and program logic to them, so game development is something new to me.

Also, my boss would like to implement different difficulty levels for the AI. What are the principles behind something like this? Would the difficulty level correspond with how many steps/turns ahead the AI would calculate for each movement? (Like easiest difficulty would be the AI only calculating all possible moves for this turn, whereas in the next level of difficulty, the AI would calculate all possible moves for this turn and the next turn?)

Thanks!

# Answer
i don't know about Risk but i had developed a Chinese Chess game few years ago. I think you can try Minimax which the game calculate every possible decisions and each decision will branch out a node for all the players until a certain depths within reasonable time. I think it is suitable for most turn based games. For 'difficulty' your game will randomized the node paths based on success rate of the paths, higher difficulty will give more 'weight' to the higher success rate paths. Also, you might want to limit the depths of the calculation, easier = less depth, harder = deeper depths.
> 6 votes

# Answer
*Risk* has too many potential moves and too many potential outcomes per move to have a Chess-like AI be effective. You don't need to consider every possible move, and you don't need to do look-ahead.

I would suggest you get some playtesters, or at least one or two smart gamers to help. If you're really just taking the *Risk* rules, or some sub-set of them, then you can borrow the known strategies for such games. Make an "expert machine" heuristic computerized opponent, by figuring out how a player would play, and program routines for that. You can have a variety of considerations and apply them based on the situation and various rules, and some random numbers to keep things unpredictable. Things like moving armies to the "front line" provinces, and towards prime target provinces. Favor moves that don't expose your territory as much, complete objectives, and have some threshold for leaving some troops on the front rather than burning down to single armies on the fronts. You can have difficulty levels by reducing the number and/or likelihood of the opponent applying some of the strategies. i.e. the Easy opponent may tend to only leave one or two armies on his fronts.

Program a simple opponent and then let your playtesters try it and suggest strategies for you to add to the AI.

Note that just because you don't do look-ahead, doesn't mean your AI can't have long-terms goals. They probably should, such as what continents and opponents to concentrate effort towards, especially if the game has a lot of multi-turn movement to gets troops to fronts.
> 2 votes

---
Tags: game-design, ai, web, turn-based, strategy
---


# Question
Title: How do I implement wander behavior in GDX AI?
So I follow the original gdx-ai documentation and created 2 circles to test Steering behavior.

The image shows arrival behaviour but I am still quite lost about how they work.

Screen class:

```
public void show() {
        pCircle = new ShapeRenderer();
        pCircle.setProjectionMatrix(mCamera.combined);
        sCircle = new SteeringCircle(pCircle, 15, 128*5, 128, Color.BLUE);

        target = new SteeringCircle(pCircle, 15, 128,128*3 , Color.CYAN);
        /*
        Wander<Vector2> wanderSB = new Wander<Vector2>(sCircle);
        wanderSB.setEnabled(true);
        wanderSB.setTarget(target);*/
        Arrive<Vector2> arriveSB = new Arrive<Vector2>(sCircle, target).setTimeToTarget(0.1f).setArrivalTolerance(10f).setDecelerationRadius(25f);

        sCircle.setBehavior(arriveSB);
}

   @Override
    public void render(float delta) {

        Gdx.gl.glClearColor(63 / 255f, 128 / 255f, 70 / 255f, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        mCamera.update();
        mTiledMapRenderer.setView(mCamera);

        mTiledMapRenderer.render();

        sCircle.update(delta);
        sCircle.render();

        target.render();

        mBatch.setProjectionMatrix(mCamera.combined);

        mBatch.begin();
        mBatch.draw(img, 128, 0);

        mBatch.end();

    }

```

SteeringCircle class:

```
   public SteeringCircle(ShapeRenderer circle ,float boundingRadius, float x, float y, Color color) {
        pCircle = circle;
        mColor = color;
        this.position = newVector();
        this.position.x = x;
        this.position.y = y;
        this.boundingRadius = boundingRadius;
        this.maxLinearSpeed = 50;
        this.maxLinearAcceleration = 5000;
        this.linearVelocity = new Vector2(15,15);
        this.maxAngularSpeed = 30;
        this.maxLinearAcceleration = 5;

        this.tagged = false;

        this.steeringOutput = new SteeringAcceleration<Vector2>(new Vector2());

    }

@Override
    public Location<Vector2> newLocation() {

        return null;
    }

public void update (float delta) {
        if (steeringBehavior != null) {
            // Calculate steering acceleration
            steeringBehavior.calculateSteering(steeringOutput);

            // Apply steering acceleration to move this agent
            applySteering(steeringOutput, delta);
        }
    }

    private void applySteering (SteeringAcceleration<Vector2> steering, float time) {
        // Update position and linear velocity. Velocity is trimmed to maximum speed
        this.position.mulAdd(linearVelocity, time);
        this.linearVelocity.mulAdd(steering.linear, time).limit(this.getMaxLinearSpeed());

        // Update orientation and angular velocity
        if (independentFacing) {
            this.orientation += angularVelocity * time;
            this.angularVelocity += steering.angular * time;
        } else {
            // For non-independent facing we have to align orientation to linear velocity
            float newOrientation = calculateOrientationFromLinearVelocity(this);
            if (newOrientation != this.orientation) {
                this.angularVelocity = (newOrientation - this.orientation) * time;
                this.orientation = newOrientation;
            }
        }
    }

```
1. For the arrival behaviour, the blue circle will move from the original position towards the Cyan circle and comes back to the circle back and forth. I thought the blue circle is supposed to stop when arriving the cyan circle which it didn't. How can I make it stop at arrival? what's wrong with the codes?
2. For the wander behaviour, the blue circle just moves north-east direction and never goes back to the cyan circle. I thought it will wander around but it didn't. Any advice on what is needed to change to make the wander behaviour happens?

Also, does anyone know what should Location returns? Isn't Vector2 position already has the location?

# Answer
> 0 votes
I think that experimenting with different values for your parameters should fix the issue. Specifically the zero threshhold and deceleration radius. If your deceleration radius is too short the dynamic body won't have enough time to slow down to a speed within the zero threshhold and will overshoot the target. Try playing with the demo that's provided with the test code.

---
Tags: libgdx, ai
---


# Question
Title: Game loop with fixed timestep gives strange result
So I've read the famous article at http://www.koonsolo.com/news/dewitters-gameloop/comment-page-2/#comments which describes different methods of implementing a game loop. I've tried to implement the final method that is described in the article in Javascript (ignoring interpolation for the time being):

```
var Timer = {
        pastTime : 0,
        currentTime : 0,
        started : false,
        //starts the timer
        start: function(){
            if(!this.started){
                this.started = true;
                this.pastTime = new Date().getTime();
            }
        },
        //gets the time in MILLSECONDS
        getTime: function(){
            return new Date().getTime() - this.pastTime;
        },
        //stops the timer but does not reset it (i.e. getTime() can still be
          called to get the time between start() and end())
        end: function(){
            if(this.started){
                this.currentTime = new Date().getTime();
                this.started = false;
                return this.currentTime - this.pastTime;
            }
        },
        //resets the timer
        reset: function(){
            this.pastTime = 0;
            this.currentTime = 0;
            this.started = false;
}

var maxFrameSkip = 5;
var nextTick = new Date().getTime();
var TICKS_PER_SECOND = 25;
var tickTimeMillis = 1000 / TICKS_PER_SECOND;

var ticksPerSecondReal = 0;
var ticksCounter = 0;

var timer = Object.create(Timer);

var loops = 0;

 function gameLoop(){
    loops = 0;

    timer.start();

    while(new Date().getTime() > nextTick && loops < maxFrameSkip){
        update();
        ticksCounter++;
        nextTick += tickTimeMillis;
        loops++;
    }

    draw();

    if(timer.getTime() >= 1000){
        ticksPerSecondReal = ticksCounter;
        ticksCounter = 0;
        timer.reset();
    }

    console.log(ticksPerSecondReal);

    window.requestAnimationFrame(gameLoop);
}

 gameLoop();

```

So the problem that I'm having is that the console.log(ticksPerSecondReal) should always be giving me 25 because that's the constant ticks per second that I want and have set up. What I end up getting is an alternating number that is 25 and 26. So periodically (~1 second) it will be 25 and then 26 and then 25 and so on. And sometimes (much less frequently) it will even give a result of 27. It keeps switching back and forth when it should be constant at 25. What is the issue here?

# Answer
Not sure i (bother to :-)) understand your code, but i'd like to point out that accumulated time will never be accurate on the long term. If it is crucial that you have consumed exactly 2500 frames in 100 seconds, you likely cannot rely on exact sum of the individual frames.

Instead you must make it "absolute". If you require 25 ms per frame, you know for sure that the trigger times for the 20 first frames are

```
0 0.04 0.08 0.12 0.16 0.2 0.24 0.28 0.32 0.36 0.4 0.44 0.48 0.52 0.56 0.6 0.64 0.68 0.72 0.76

```

Do not expect the sum of your frame times to be an exact multiple of 0.04 any longer after 1000 frames, after always having delayed the loop cycle relatively. It will diverge.

Instead implement a system where you always check the clock time (DateTime, whatever) against a pre-generated "next trigger time". Ie. if your next frame is the 11th frame, calculate 11\*0.04 (which is 0.44) and sit somewhere and compare current time against 0.44. When current time exceeds 0.44, paint the frame, and then next time sit and wait for currenttime to exceed 0.48. And so on.

n\*0.04 will be an accurate value even if n is 100000.
> 1 votes

# Answer
You should move the call of `timer.start()` to be before your call of `gameLoop()`. You should also make a call to it right after the call of `timer.reset()`.
> 0 votes

---
Tags: javascript, game-loop, fixed-timestep
---


# Question
Title: Unity / How to add a shader to a material via c# script?
I found already some things - but those seem not quite what I need. (perhaps outdated functions?)

https://docs.unity3d.com/ScriptReference/Material-shader.html

here, it seems you can add a shader to a renderer:

```
using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    public Shader shader1;
    public Shader shader2;
    public Renderer rend;
    void Start() {
        rend = GetComponent<Renderer>();
        shader1 = Shader.Find("Diffuse");
        shader2 = Shader.Find("Transparent/Diffuse");
    }
    void Update() {
        if (Input.GetButtonDown("Jump"))
            if (rend.material.shader == shader1)
                rend.material.shader = shader2;
            else
                rend.material.shader = shader1;

    }
}

```

well - i dont have a renderer. i only have a material.

and there is no "material.setShader" , only a material.setTexture"

sooo can anyone solve this mystery of how to add a shader to a material via script?

# Answer
If you already have a reference to the material and the shader then you just need to do this: `myMaterial.shader = myShader;` There's nothing more to it than that.

The Unity Material API says that the `shader` property is `public` so you can just use `=` instead of finding some "set" method. There is an explicit "set" and "get" function for textures on materials because they can have more than one so they're identified with a name or id.

In your example with the renderer, it's just getting the material from the renderer and doing the same exact thing I mentioned above. This code...

```
rend.material.shader = myShader;

```

has the same results as this code...

```
Material myMaterial = rend.material;
myMaterial.shader = myShader;

```
> 2 votes

---
Tags: unity, shaders
---


# Question
Title: Control Entity Moving Speed Without Using a Delay Function
In a Tetris game I'm trying to make (using C++/SDL), I need to control the falling speed of, say, one block. I have successfully done this by incramenting its `y` value then setting `SDL_Delay(200)`. So every 200 ms, the block moves down one unit. However, using `SDL_Delay` lags the whole game, and using the controls to move the block around gets delayed as well. I need to control the falling speed in a way that nothing gets delayed except the falling of the block. How can I achieve this? Thanks.

# Answer
> 2 votes
You need to implement some sort of a timer. A basic implementation could work like the following: start by calculating the next time when a block should move, which might look something like `nextMoveTime = SDL_GetTicks() + 200;`. Then, each frame/update cycle, you would check if enough time has passed and if so, move the block. So something simple like `if (SDL_GetTicks() >= nextMoveTime) block->Move();`. If you wanted to keep the block moving, you would then recalculate `nextMoveTime`.

---
Tags: movement, sdl
---


title: LibGDX Image Outline Help

text:
# Question
Title: LibGDX Image Outline Help
As I was working on some art for my project, I decided that I should add an outline around some objects.

So I tried my method; which was to create a second image slightly larger than the first, make it all black, then draw it with a slight offset to the original image.

For a little bit, everything was fine and dandy, but then I went and tried it on some different shaped images, and everything went downhill.

Here are the images for the first outline, the good one:

And then when I tried something irregular, this happened:

So hopefully you can see my problem, but if the image is to small, then I can try describe it. Ok, when I draw an "outline" around my image, it turns out normal. Yet, when I try draw an outline around my more irregular image, the outline doesn't reach all the edges of the image. Only some are visible.

What I want is to be able to have the outline all the way around the edges of the image, like the first image.

Is there a better way to draw outlines? Or is this the best way, if so, what am I doing wrong to get this outcome?

Any help is appreciated,

Thanks!

# Answer
> 1 votes
If you're going to use two images anyways, why don't you simply just have one image without an outline and one with an outline and just swap between them?

As for other methods of drawing an outline, it can be done using multiple methods. If you're going to draw an outline on simple textures (let's say a square) use a `ShapeRenderer` (docs & tutorial) and do something like this (pseudo, kinda).

```
//Create a variable
ShapeRenderer shapeRenderer = new ShapeRenderer(); //New shape renderer.

//Then in your render method AFTER rendering your image.
shapeRenderer.setProjectionMatrix(camera.combined); //The combined matrix from your camera object.
shapeRenderer.begin(ShapeType.Line); //We wish to draw simple lines only.
shapeRenderer.setColor(Color.BLACK); //Any color you want.
shapeRenderer.rect(image.x, image.y, image.width, image.height); //Draw a rectangle around our image.
shapeRenderer.end(); //Stop the renderer.

```

This will draw a box outline on your image. If you want the box to not obscure any part of your image you just have to offset the co-ordinates and increase the size of the box by one pixel.

For drawing pixel perfect borders you should look into the `Pixmap` class (tutorial | docs) or OpenGL shaders (tutorial | use google and SO for help).

Using one of these methods you can decide what pixels are non-transparent, and then paint the neighboring pixels black.

---
Tags: java, libgdx, rendering, art, outline
---


# Question
Title: How does atan2 work when getting angle of a vector?
I know that `atan2` gives me the absolute angle of any vector. But it doesn't give a value from `0` to `360` degrees. Instead, it gives a value (if I'm not mistaken), between `0` and 180, or between `0` and `-180`. For example, instead of giving angle `270`, it will say `-90`.

This is a little confusing for me. Let me try to describe how I *think* this works, and please tell me if I'm correct. Actually, I'll draw it.

Is this correct? I'm having a little trouble understanding this. Thanks

# Answer
From the Wikipedia page:

It is returning the shortest angle of rotation from the positive x direction to the point, where a positive angle indicates the counter-clockwise direction. Therefore it makes sense that it would only return values between 0 and 180, since anything greater than 180 can be 'better' approached by a smaller angle in the opposite direction.

Returning -90 instead of 270 also makes sense now, since moving 90 degrees clockwise is less than moving 270 degrees counter-clockwise to reach the same point. This also suggests that your interpretation has mixed up the positive and negative 90 degree directions but is otherwise fine.
> 8 votes

# Answer
The referenced Wikipedia article provides the logic of the `atan2` function, which has been optimized computationally (it works faster than implementing the statement explicitly). To convert to 0-to-360 degree values, first you must adjust the range of `atan2` results, then convert to degrees, shown here as a vectorized operation in pseudo-code:

```
rad = atan2(y,x)
rad[rad < 0] = rad[rad < 0] + 2*pi
deg = rad*(180/pi)

```

Hope that is helpful.
> 1 votes

# Answer
Just to answer you question simply: arctangent function atan2(y,x) uses the sign of BOTH parameters to determine the quadrant of the angle in the range -PI to +PI (-180 deg to +180 deg). If you want degrees in the range 0 to 360 do this:

```
struct vector {double x, double y}; // define a 2D vector
vector vec{ 3.0,2.0 }; // sets x and y values
const double convertRadiansToDegrees = 180.0 / 3.14159265359;

double resultInDegrees = atan2(vec.y, vec.x) * convertRadiansToDegrees + 180.0; // 0 to 360 degrees

```

Note that there is a faster but less accurate version for floats and not doubles called atan2f(y,x);
> 1 votes

# Answer
The following example isn't using vectors but rather simple `unit-circle` implemented on javascript: https://github.com/Drooids/unit-circle.

More particularly below this line: https://github.com/Drooids/unit-circle/blob/e608e67ed52db89025e0fc4c6900fddcdab01608/unit-circle.js#L391
> 0 votes

---
Tags: mathematics, vector, geometry
---


# Question
Title: How do I convert gravity from pixels per frame² into Unity's Rigidbody2D gravity scale parameter?
I'm learning Unity2D by trying to make a Mega Man clone. The first thing I'm trying to do is to replicate the original series physics. It differs from game to game, but I'm leaning towards something like Mega Man 3. I found this post (#3 and #8) where the game physics is described in detail and started to "translate" it to Unity. So, for instance, it says that Mega Man moves at 1.3 pixels per frame in MM3. Since I'm working with 60FPS, I multiply it by 60 and get 78 pixels per second, and use it as my character's walking speed, i.e., its horizontal velocity. Is that correct?

My real question, however, is about the following: "Rock jumps at 4.875 pixels per frame with a gravity of 0.25 pixels per frame per frame.". As I understand it, Mega Man's initial jump speed should be 4.875 pixels per frame, i.e., 292.5 pixels per second. Considering that I'm using a Rigidbody2D of mass=1, does it mean that I should use `addForce(0, 292.5)`? Also, how can I "translate" the 0.25 pixels per frame² gravity? My first thought would be to multiply 0.25 by 60\*60 to get pixels per s², but it gives me 900 and the character does not even get off the ground. **How do I convert gravity from pixels per frame² into Unity's Rigidbody2D gravity scale parameter?**

Edit: this is a learning attempt, I'm not building a MM engine. So, for now, I want to understand this specific issue. I'm not new to MM gamedev and already did this before without a physics engine. I'm new to Unity and want to learn how to do it this way.

# Answer
There's going to be some variation in how you approach this, depending on whether you're going for "pixel-perfect retro re-creation" or "playable prototype to learn about making platformers." You don't need perfect precision to make something fun, so there's nothing wrong with taking a simpler route, especially in your early work. As I go through the steps below I'll call out extra things you'll want to think about if you want to push toward pixel-perfection, but you can also safely skip these and still get something that feels good to play.

## Step 1: Decide on your unit scale

Mega Man 3 used 16x16 tiles, so you'll probably find it convenient to consider this "one unit" for the purposes of laying out your levels. You could also halve this value if you want both tile corners and tile centers to sit on integer coordinates - this is really a matter of taste.

(I'd recommend against using 1 pixel = 1 unit though - generally you want your unit to be in the ballpark of the size of the player avatar, since a lot of engine tools & systems assume you're working in this kind of scale range)

If you want your game to render pixel-perfect across multiple resolutions, you may want to use two or more unit scales for your graphics, selecting the best fit for the current resolution as described in this article on pixel-perfect rendering in Unity. To keep gameplay consistent, you'll still want to pick one canonical unit scale for calculating your metrics & movement in **Step 4**.

## Step 2: Configure your Pixels Per Unit import settings

This is found in the Inspector when selecting any image you've imported into your project with `TextureType: Sprite (2D and UI)`

Set this to your unit scale value (eg. 16 if using 16-pixel tiles, or the appropriate variant for each asset if you're using multiple sizes as touched on above)

Once you do this for each Sprite asset you're using, each tile will automatically size itself to 1 unit when you add it to your scene (and other shapes/sizes of sprites like characters will size themselves proportionately)

## Step 3: Configure your camera size

Using the formula:

```
Orthographic camera size = (screen height in source pixels) / (pixels per unit * 2)

```

So, if you want to emulate a standard NES resolution of 240 pixels vertically (including overscan), with 16 pixels per unit, you'd set your camera size to `(240)/(16*2)= 7.5`

If you want to crop in further to mimic the fact that old CRTs only displayed part of the image, you could use `224/(16*2) = 7`

To get a pixel perfect look you need to be careful how this is scaled to the player's screen, which typically has way more pixels than a retro-style game. If you notice rippling artifacts in your sprites it's because your viewport size isn't an integer multiple of your "retro" resolution. Again, the pixel-perfect rendering article linked above has tips on how to crop or pad your display to get this lined up neatly, if you want to go all the way with it.

## Step 4: Tune your gameplay metrics & speeds

Now we can use this value to translate our measurements into gameplay units:

```
Jump speed in pixels per frame    =   4.875   p/f
...times 60 frames per second     = 292.5     p/s
...divided by 16 pixels per unit  =  18.28125 u/s

Acceleration in pixels per frame² =   0.25    p/f²
...times (60 frames per second)²  = 900.0     p/s²
...divided by 16 pixels per unit  =  56.25    u/s²

```

## Step 5: Using Unity Physics

Unity's Box2D physics system is a lot more complex than the logic used in classic platformers, so as others have pointed out above, if you want to truly duplicate older mechanics then the way to do it is to write your own custom physics handling - that's beyond the scope of this answer.

**But** if purity of reproduction isn't your goal and you just want to get something playable and fun, using Unity's built-in physics may help you get up and running faster, and can be tuned to give a similar feel, so that's what I'll describe here.

You'll find there's a lot of negativity out there about these physics engines, but most of it comes from the fact that they're very easy to use *wrong*. With a little care we can tame them to get the kind of results we want.

There are three main parts to this:

**A) FixedUpdate**

If your reference game's physics update at 60 fps, then you'll want to go into `Project Settings -> Time` and set `Fixed Timestep` to 1/60 = 0.01666...

This will ensure that things like gravity and collisions are integrated at the expected time resolution. Note that if your rendering framerate is very close to 60, this can cause a beat frequency between the physics rate and the display rate, but for a 2D game you'll typically be running well above 60 fps anyway. There are ways to address this if you find noticeable artifacts.

Get in the habit of putting any movement logic in `FixedUpdate()` methods. This will ensure they run as often as the physics step, no matter what happens to the rendering framerate, helping you get consistent gameplay across different devices and levels of load.

**B) Applying your forces and velocities**

Applying the gravity acceleration is straightforward. If everything is using the same gravity, you can go to `Project Settings -> Physics 2D` and put the value we calculated above into Y, negated. (ie. `X: 0 Y: -56.25`). Then you can leave the `gravityScale` on each object at its default value of 1.

Some old games used different gravity values per character/object, or for different phases of the jump. In a case like that you'd probably want to zero-out the gravity globally or by setting `rigidbody2D.gravityScale = 0` on the objects that need custom gravity, then apply it yourself at the end of every `FixedUpdate` with:

```
rigidbody2D.velocity += Vector2.down * gravity * Time.deltaTime;

```

To kick your character into the air with a given initial velocity, you'd use something like this:

```
Vector2 velocity = rigidbody2D.velocity;
// You can also add to the current vertical velocity instead of replacing it,
// if you want the jump to adapt to running up/downhill or jumping off a moving platform.
velocity.y = jumpVelocity;
ridigbody2D.velocity = velocity;

```

That should give you a good starting point. Test it out and see how it works.You may find the jump arc in Unity deviates slightly from your target, due to differences in when gravity is applied (eg. between steps or continuously over the course of each step) - if you find that's the case, comment below with the metrics you're seeing and we can work out the appropriate compensating factors.

**C) Disable unwanted physics effects**

Create a new `Physics2D Material` from the Assets menu and set its Friction to 0. Use this on any player colliders so contact with the ground doesn't sap a portion of the velocity value you want.

On the player Rigidbody2D, check FreezeRotation Z under Constraints so your character doesn't roll around. Keep Linear Drag at its default of zero for the same reason as the friction - it'll be up to your control script to stop the player when you want them stopped. ;)
> 1 votes

---
Tags: 2d, physics, unity, jumping
---


# Question
Title: Using angle_difference to calculate shortest turn to target [Gamemaker]
I've tried, but I *cannot* understand `angle_difference`.

I have an object, `oTurretDetTurret`, which turns to face its `Target`, which lies at the angle `DirectionOfTarget` from it.

It does this by updating its `direction` thus:

`direction = direction + SpinDirection`

`SpinDirection` can be either +3 or -3, meaning it can turn in either direction at a rate of 3 degrees per step.

What determines the direction it turns in is the angle between its current `direction` and the \`DirectionToTarget. **I want the turret to turn in the direction with the shortest number of degrees to travel.**

I've been using this:

```
if angle_difference(direction, DirectionToTarget) > 0 {
direction = direction + 3
} else if angle_difference(direction, DirectionToTarget <= 0 {
direction = direction - 3
}

```

However, in game this just means that the turret faces the opposite direction to its target at all times, oscillating back and forth slightly.

In my understanding, `angle_difference` returns the *smaller* of the two angles between two directions.

For example, if the turret's `direction` is 300 degrees and the `DirectionToTarget` is 90 degrees, `angle_difference` should return +150, the smaller of the two angles, and thus my above code should move the turret counter-clockwise towards 90 degrees.

Can anybody help me?

# Answer
angle\_difference is calculated with atan2 function which returns -PI to +PI (-180 deg to +180 deg). That is useful because if angle\_difference \> 0 you know it is clockwise from you and \< 0 counterclockwise. your else if statement with \<= should only be \<, which is causing your oscillation.
> 1 votes

# Answer
I think probably your directToTarget is off by 180 degrees somehow. Maybe post that code. That could explain why your turret is always pointing away from the target. The next thing to consider is the oscillation. This is probably happening because you increment by 3 even if the difference between the angle and the desired angle is only 1 - so you'll get some overshoot over and over again. So instead, write in some logic that basically says **if difference is more than 3, increment by 3, else increment by the difference**
> 0 votes

---
Tags: game-maker, angles
---


# Question
Title: AS3 ScaleX is moving object across screen
I am trying to make an HP bar for my game. I have the code here

```
private var hpBar:Sprite = new Sprite();
private function drawHPBar(s:Stage):void{
    hpBar.graphics.beginFill(0xFF1717); //Medium Red
    hpBar.graphics.drawRect(620, 165, 152, 22);
    hpBar.graphics.endFill();
    s.addChild(hpBar);
    s.addEventListener(KeyboardEvent.KEY_DOWN, displayKey);
}

private function displayKey(e:KeyboardEvent):void{
    hpBar.scaleX -= 0.02;
}`

```

But when the hpBar.scaleX is decreased, the object shrinks and at the same time, moves left across the screen(stage). I am so confused because I saw videos on youtube about the scaleX and they don't seem to have a problem.

# Answer
> 0 votes
I found the problem. Finally!!

I had to set the X and Y manually, and leave the X and Y blank when I created a rectangle.

Here's an example:

```
        hpBar.x = 620;
        hpBar.y = 165;
        hpBar.graphics.beginFill(0xFF1717); //Medium Red
        hpBar.graphics.drawRect(0, 0, 152, 22);

```

Now, when the scaleX is changed, it will no longer move across the screen.

---
Tags: actionscript-3
---


# Question
Title: What is the design rationale behind melee retaliations in turn-based games?
I've seen quite a lot of turn-based games in which melee attacks on another unit cause the attacked units to also damage the attacking unit, while ranged attacks do not suffer from this "retaliation" mechanic.

Examples include the Heroes of Might and Magic series, the Civilization series, the new King's Bounty series, and more.

Is there a specific design reason for this? What's the rationale behind giving the attacked unit an extra attack, which doesn't cost it its turn? And why are ranged attacks excluded from retaliation?

# Answer
> 71 votes
**Melee counter-attack is an easy way to make ranged attacks valuable.**

Do you build and use units that have strong melee attacks but die more easily because they're in melee or do you use units with weaker ranged attacks that live longer because they can stay out of melee?

**Melee counter-attack reduces otherwise over-whelming attacker advantage.**

In a game like HoMM, having a large stack of powerful attackers you'll be able to kill many other stacks in the game with a single attack. Melee counter-attack means that even defenders that you roll over still whittle away at your offensive stack, reducing its offensive power over time (unless you expend resources replenishing the stack).

**Melee counter-attack reduces the benefit of taking the first turn.**

Continued from above, melee-counterattack means that it matters less which player attacks first, as both players' units will get a chance to attack no matter the outcome. The first attacker will no longer be able to eliminate the opponent's strongest attacker in the first turn without consequences (well, except for ranged attackers, but that plays back into the first point). This reduces the first-turn advantage to mostly being about picking the battlefield positioning, which is more strategically interesting in a tactical game.

**Melee counter-attack is "easy".**

This is a two-parter that is predicated on accepting the prior three points. Basically, assuming you want the additional strategic impact provided by melee-counterattack in the first place, it's just easier to use melee-counterattack than to come up with a different solution.

Melee counter-attack is widely understood and easy to incorporate into a game's design. It's easy to teach to new players which makes the game more appealing to a wider playerbase. It requires little additional/special artwork or animations. It requires little additional code.

In short, if you accept the previous three points, using melee-counterattack to achieve them is just probably far easier overall than using something else.

**Melee-counterattack is a composable design.**

What I mean by "composable" is that since counter-attack is such a simple rule, there are many ways to combine it with other rules to get a combinatoric growth in strategic depth without requiring much extra work. For instance, make a defender unit that does 2x damage on a counter-attack, or make an offensive unit that does 1/2x damage on a counter-attack. You'll frequently find this element in simpler designs: you can combine simple rules far more effectively than you can combine complex rules, and the result is often equally simple and easy to understand.

**Melee-counterattack provides some counter-balance to unit counts.**

This one is specific to other game details. An example again would be HoMM: a single unit on the battlefield is actually a stack of creatures rather than a single creature. Bigger stacks have more power. Without counter-attack, it becomes much easier for multiple small stacks to overwhelm a single large stack, even though the large stack possibly represents more overall individual creatures. The counter-attack evens out the economy of attack actions with the smaller stacks; 5 small stacks ganging up on a larger stack do not get 5x as many attacks, possibly nulling out the supposed numeric superiority of the larger stack.

This is rather subjective as its quite arguable whether you'd want to encourage the player to have many smaller stacks or fewer larger stacks.

# Answer
> 15 votes
It's a basic question of a certain type of "realism". It's hard to imagine getting a melee hit in on an enemy and them not getting involved at all, because you have to very close to them to hit with with something like an axe. It makes sense that the unit getting attacked gets a swing in.

Ranged attackers can't get hit by the melee units they attack because it makes sense. Imagine you have a sword and someone shoots an arrow at you; they're too far away for you to hit them with the sword.

Some games, like Duelyst, let ranged attackers get a counter-attack in when being attacked by ranged attackers.

# Answer
> 15 votes
I am currently developing a turn-based strategy game.

There are (overly simplified) two kinds of units in the game: sturdy melee damage sponges and fragile ranged damage dealers. The player is supposed to position the first in a way which prevents the opponent from attacking the second. However, that usually means that the melee units will receive the first hit from the enemy attackers and lose some health. That makes this tactic feel wrong, even though it is objectively right.

However, when I made the player's melee units retaliate against enemy melee attacks, this perception changed. Seeing the units strike back suddenly made it feel rewarding to allow the opponent to attack them.

Adding a retaliation to the *opponents* melee units also had an interesting effect on the players behavior. The player felt punished for attacking the enemies damage sponges in melee, so they learned to prefer to attack the non-retaliating damage dealers when having the option. This greatly helped to teach the players an important tactical concept they needed to understand to master the game: Attack the damage dealers first.

# Answer
> 4 votes
I think the rationale is pretty simple. A melee or a close quarters attack is a immediate threat to your survival fail to counter and your dead, or running for your life.

Going into a melee is a two way street, you might get the first blow, but the other will counter attack or die. Nobody in their sane minds would be standing in place when they get attacked. Same kind of rationale happens in modern games where small arms fire begets small arms fire. Simply you must retaliate or be overrun by the enemy. Your not a wall after all.

Ranged attacks while deadly do not cause the threat of being overrun. And you might not be equipped with weapons that can fire back. Second arranging for a massed arrow or artillery barrage takes time to organize. The line need to turn, guns need to be re-positioned and loaded etc. So doing an attack is much more deliberate than close quarters fighting.

Immediacy of modern hand guns and armor weapons to me seems also the reason close quarters shooting in modern era does counter because its much more immediate. Artillery has the same problem as arrows. However, some games do launch counter artillery strikes. So the more modern you are the more likely it is that artillery should counter attack.

**TL;DR** Its simply modeling the fact that you have time for many attacks in a turn but only time to prepare for one attack.

---

Alternatives to model turns like this. If you model turns so that movement comes first and than all attacks are pooled, then your stationary could sidestep this design for anything other than pure hand to hand combat. In hand to hand your inevitably locked to the enemy which would need some additional rules to be resolved.

# Answer
> 4 votes
You add additional depth by mixing 2 existing systems.

System 1: Combat can be initiated from either side, winner is determined by stats and luck.

System 2: Only the one initiating combat deals damage.

Retaliations are just a variation of the first system. Both systems make sense on their own. "Attacker deals all the damage" has been used since chess, so it's more than a thousand years old. I don't know when "the winner determined by stats and luck" first appeared, but I'd be surprised if it isn't also at least several hundred years old.

The reason the both are combined is that it's sometimes a more interesting experience to work with both systems instead of just one of them. Both systems on their own have disadvantages\*, and these disadvantages can be mitigated by mixing them.

The reason for the way of them being combined being by using the first system for melee and the second system for ranged is that this way the combined system is somewhat intuitive and therefore easy to explain to the player.

---

\*The first system limits the effects good tactics can achieve, because damage is always an equal trade in numbers. The second system puts an emphasis on tactics-micromanagement, and a single piece being in a slightly different place can result in a massive difference to the outcome.

# Answer
> 3 votes
It gives turn based games a component of "realtime"-realism. In real battle you seldom can attack an enemies army without him fighting back at all, especially at close range.

This is why everything in civ counterattacks everything in range in civ.

Bowmen will counterattack other bownman.

In some games the counterattack even happens before the damage is applied, so both armies deal damage at "the same time", this means if 2 equally powerful armies attack each other noone comes out ahead. (Ignoring possible attacker or terrain bonuses)

This gives the player a more realistic and intuitive sense of the battle. It's also more fair sometimes. If a player can loose his army without dealing any damage that can seem/be very unfair on occasions. Especially if the realistic intuition of the player tells him "common, how can they die without doing anything? those guys are attacking from right next to them"

# Answer
> 1 votes
The number one reason is to make the game fun and challenging.

It:

1. makes the attacker think twice about attacking if they're low on health (why would a low health unit be able to 'kill' a full health unit?)
2. can represent a bit what happens in real life: in a fight, fighter A might want to hit fighter B, but this opens an opportunity to counter attack: e.g. fighter A kicks fighter B, fighter B knows fighter A is now slightly off-balance so they may want to grab the standing leg, or something like it.

Ranged attackers are typically used as big-damage/wimp: they stay far so that they don't get attacked. That's why they don't suffer that penalty.

# Answer
> 1 votes
Melee retaliation is both to simulate the danger of attacking an enemy at hand-to-hand range, as well as to compensate for the inevitable buffs that melee attacks receive related to ranged attacks.

Ranged attacks are significantly more tactically advantageous than melee attacks. They are also much easier to accomplish, depending on what ranges are valid, whereas melee attacks may require you to be right next to your opponent. And so very often ranged attacks will be given large accuracy penalties and do much less damage, whereas melee attacks will tend to do much more damage. (Other common ranged penalties include making ranged units generally weaker, or giving a defense penalty to a unit when it is in ranged mode, or even making a unit immobile in ranged mode.)

Because of this skewing of damage towards melee attacks, melee can become imbalanced, killing opponents too quickly. This is especially a problem in a turn based game, where multiple enemies could melee attack on their turn before the defender has gotten his, and the defender will be killed without having had a chance to do anything.

By giving melee retaliation attacks, you introduce a smaller scale version of turn-taking, allowing the inactive team a chance to do something.

Note that the retaliatory attacks may need to be limited, or else an entire army could fall to one sufficiently strong unit in a single turn. Or that may be desirable as well.

Retaliation attacks in general allow for more balanced turn taking than you would get without them. In a 20v20 battle, it's problematic if all 20 on one side get their turn before their 20 opponents. This gives an enormous advantage to the team that goes first. Retaliation reduces the significance of this problem. (Another way to avoid this problem is to use an initiative system where you interleave the members from both teams, and neither team has an entire "turn" to themselves.)

---
Tags: game-design, turn-based
---


title: Space Based Physics

text:
# Question
Title: Space Based Physics
How would I go about about adding space-based physics like orbital mechanics into a game engine like Unreal Engine 4 or Unity 5? The goal is to generate celestial bodies procedurally: first black holes, start around those black holes, then planetary systems around those stars, then in every instance calculate the needed velocity to make stable orbits(the system would calculate the best orbit and have cases for star systems with multiple suns) them data in the format time: position will be stored in an array for each celestial body and the body will then be rendered there when needed.

# Answer
> 1 votes
I'm actually working on a 2D project similar to what your doing, definitely less complex in scope though.

I am also a beginner at this but can give you what I've learned so far.

You're going to need to figure out your gravity mechanics first, universe generation is easier and will have to come second.

Since I'm assuming you're making a game and not a simulation, you're going to probably use two-body gravity not n-body, the more bodies effecting each other at once the more processing time youre going to be eating. You're going to have to decide how complex you want it.

If you use Unity, you're going to want to put your physics updates in

```
FixedUpdate()

```

and you will have to write your own gravity. Using Unity's rigidbody and rigidbody.addforce() will lead to problems since unity caps rigidbody velocity.

You're going to need to scale things down a lot too.

It will also probably be best to keep your black holes, Suns, planets, and moons on the rails, once you have an orbital path calculated once just move it along that path without calculating gravity anymore. (This lets you draw the orbital path without running math constantly)

I'm on mobile at the moment but when I get a chance I'll edit this to include some links to resources and some code I've done to go from the 2 state vectors to the 6 orbital elements, but hopefully someone else will be able to help you out more, I suggest you keep the space exploration stack exchange in mind as well.

Edit 1... Here are some very useful PDFs that show you how to calculate the orbital elements, then convert them back at a specific t time. I have only used the first one in my project.

State vectors to orbital elements

Orbital elements back to state vectors at given time

Edit 2... (I won't have my code until I get home) For your forces, you're going to need torque, and velocity, I'm still using Unity's addTorque() because I'm in 2D but you may want your own. As for velocity, do not use Unity's addForce(). Store velocity as a vector3 and move the position of your object by that vector each time step. You can add any velocity changes to that vector. I'll be able to get some code on gravity and the orbital elements this evening.

You're going to need to pick a scale and stick to it, as seen in my questions on space exploration losing track of the units and not converting values properly leads to problems.

Edit 3...

Here is my code for gravity:

```
public Vector3 Gravity(Vector3 pos1, float m1, Vector3 pos2, float m2) {
    //Relative distance vector
    Vector3 dvec = (pos2 - pos1);

    //Relative distance
    float d = dvec.magnitude;

    //Direction of force
    Vector3 dnorm = dvec.normalized;

    //Distance Squared
    float dsqrd = Mathf.Pow(d, 2);

    //Mass of both bodies
    float M = m1 + m2;

    //Gavitational pull
    float g = World.G * M / dsqrd;

    //Acceleration due to gravity vector
    Vector3 f = dnorm * g;

    return f;
}

```

Edit 4...

And finally, here is my huge script that finds a bunch of sciency stuff for gravity. Some of it you will ignore, I can't confirm all of it is 100% correct, but you can use it as a resource as I suffered through it myself and wouldn't wish the same torture on my worst enemy

```
public OrbitData CalculateOrbitalData(Vector3 pos1, Vector3 vel1, float m1, Body body) {
    if (body == null) {
        return new OrbitData();
    }

    Vector3 pos2 = body.position;
    Vector3 vel2 = body.velocity;
    float m2 = body.mass;

    //Relative Position Vector
    Vector3 r = pos1 - pos2;

    //Distance between bodies
    float rmag = r.magnitude;

    //Relative Velocity Vector
    Vector3 v = vel1 - vel2;

    //Velocity Magnitude
    float v1 = vel1.magnitude;

    //Relative Velocity Magnitude
    float vm = v.magnitude;

    //Specific Angular Momentum
    Vector3 h = Vector3.Cross(r, v);

    //Standard Gravitational Parameter
    float µ = World.G * m2;

    //Eccentricity Vector
    Vector3 evec = (Vector3.Cross(v, h) / µ) - (r / Vector3.Magnitude(r));

    //Eccentricity
    float e = Vector3.Magnitude(evec);

    //Vector to Ascending Node
    Vector3 n = new Vector3(-h.x, h.z, 0);

    //True Anomaly
    float ta = Mathf.Acos((Vector3.Dot(evec, r)) / (e * Vector3.Magnitude(r)));
    if (Vector3.Dot(r, v) < 0)
        ta = (2 * Mathf.PI) - ta;

    //Longitude of Ascending Node (2D)
    float Ω = 0;

    //Inclination (2D)
    float i = 0;

    //Argument of Periapsis
    float ω = Mathf.Atan2(evec.y, evec.x);
    float ωdegrees = ω * (180 / Mathf.PI);
    if (e == 0) {
        ω = 0;
        ωdegrees = 0;
    }

    //Eccentric Anomaly
    //float E = 2 * Mathf.Atan2(Mathf.Tan(ta / 2), Mathf.Sqrt((1 + e) / (1 - e)));
    float E = 2 * Mathf.Atan(Mathf.Tan(ta / 2) / Mathf.Sqrt((1 + e) / (1 - e)));

    //Mean Anomaly
    float M = E - (e * Mathf.Sin(E));

    //Semi-Major Axis
    float a = 1 / ((2 / Vector3.Magnitude(r)) - (Mathf.Pow(Vector3.Magnitude(v), 2) / µ));

    //Apoapsis
    float ap = a * (1 + e);

    //Periapsis
    float pe = a * (1 - e);

    //Orbital Period
    float T = (2 * Mathf.PI) * Mathf.Sqrt(Mathf.Pow(a, 3) / µ) / 60;
    float fT = T * 1.205f;

    //Mean motion
    float m = (2 * Mathf.PI) / fT;

    //Time since apoapsis
    float tsa = Mathf.Sqrt(Mathf.Pow(a, 3) / µ) * ((E + Mathf.PI) - e * Mathf.Sin((E + Mathf.PI))) / 60 * 1.205f;

    //Time to apoapsis
    float tta = fT - tsa;

    //Time since periapsis
    float tsp = tsa - fT / 2;
    if (tsp < 0)
        tsp = fT / 2 + tsa;

    //Time to periapsis
    float ttp = tta - fT / 2;
    if (ttp < 0)
        ttp = fT / 2 + tta;

    //Perifocal distance
    float rp = (Vector3.Dot(h, h) / µ) / e + 1;

    //Prograde rotation angle
    float pr = 0;
    if (vel1 != Vector3.zero) pr = Quaternion.AngleAxis(Mathf.Atan2(vel1.y, vel1.x) * Mathf.Rad2Deg, Vector3.forward).eulerAngles.z - 90;

    //Retrograde rotation angle
    float rr = pr + 180;

    //Counterclockwise forward rotation angle
    float ccwR = 0;
    float rad = 0;
    Vector2 offset = transform.position - body.transform.position;
    if (offset.x != 0) rad = (Mathf.Atan(offset.y / offset.x));
    if (offset.x < 0) rad += Mathf.PI;
    ccwR = rad * (180 / Mathf.PI);

    //Clockwise forward rotation angle
    float cwR = ccwR + 180;

    //Up rotation angle
    float uR = cwR + 90;

    //Down rotation angle
    float dR = cwR - 90;

    //circularize dV
    float circ_dV = Mathf.Sqrt(µ / ap) - Mathf.Sqrt((pe * µ) / (ap * (pe + ap) / 2));

    //circularize burn tick count
    float circ_btt = circ_dV / forwardThrust;

    //Circularize burn time
    float circ_bt = circ_btt / (1 / World.timeStep);

    return new OrbitData(m1, pos1, v1, vel1, m2, vel2.magnitude, vel2, pos2, World.G,
        r, v, rmag, h, µ, evec, e, n, ta, Ω, i, ω, ωdegrees, E, M, a, ap, tsa, tta,
        pe, tsp, ttp, orbit.forcedApoapsisPosition, orbit.forcedPeriapsisPosition,
        T, fT, rp, pr, rr, cwR, ccwR, uR, dR, circ_dV, circ_btt, circ_bt);
}

```

---
Tags: physics
---


title: Linear Gradient with angle formula

text:
# Question
Title: Linear Gradient with angle formula
How can I generate a linear gradient along a vector?

Here is the function I'm looking for:

```
function CreateGradient(x,y, x1,y1,x2,y2) {
    // x and y are the point in our image we are looking to create the  color for in grayscale
    // x1,y1,x2,y2 is the vector in which the linear gradient should run
    // Can be in any language
}

```

What I have so far (that doesn't work):

```
var width = 2.0;
var offset = 0;

var convX = ((x / RES) * width - width/2) - offset;
var convY = ((y / RES) * width - width/2) - offset;

var angle = Math.atan(y1-y2, x1-x2);

var rx = Math.cos(angle);
var ry = Math.sin(angle);

var here = convX * rx + convY * ry;
var start = x1 * rx + y1 * ry;
var end = x2 * rx + y2 * ry;

var lerpValue = (start - here) / (start - end);

var val = lerp(0,255,clamp(lerpValue,0.0,1.0));

```

`RES` is the total resolution of the picture. `val` in the value (0-255) which represents the R G and B values of the pixel.

Edit: I have it now thanks code for the future:

```
var x1 = 0;
var y1 = 0;
var x2 = 255;
var y2 = 255;

var dx = x2-x1;
var dy = y2-y1;

var rx = x-x1;
var ry = y-y1;

var t = ((rx*dx) +(ry*dy)) / ((dx*dx) + (dy*dy));

return lerp(0,255,t);

```

# Answer
It looks an introduction to linear algebra is in order, or more precisely the dot product:

```
dot(a, b) = |a| |b| cos(Theta)

```

Why is it helpful? Because of its relation to the scalar/vector projection, the length of projection of vector **a** onto vector **b** is

```
lenPA = |a| cos(theta)

```

or more practically, derived from dot product definition:

```
lenPA = (a . b) / |b|

```

and when you know how far the current coordinate is projected onto the line between gradient's step1 and step2, all you have to do is to normalize it:

```
t = lenPA / |b|
color = lerp(color1, color2, t)

```

where **a** is relative position of fragment xy to the gradient step1 and **b** is non-normalized gradient (direction) going from step1 to step2.
copy/paste code (for shadertoy):

```
vec2 step1 = vec2(200, 200);
vec2 step2 = vec2(400, 400);

vec4 color1 = vec4(0.0,0.5,1.0,1.0);
vec4 color2 = vec4(1.0,5.0,0.0,1.0);

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    //----constant, can pre compute------
    vec2 gDrirection = step2 - step1;
    float lenSq = dot(gDrirection, gDrirection);//len(gDrirection)^2
    //-----------------------------------
    vec2 relCoords = fragCoord - step1;
    float t = dot (relCoords, gDrirection) /  lenSq;
    fragColor = mix(color1, color2, t); //mix = lerp
}

```
> 4 votes

# Answer
is this what you want ?

```
    float endPercent = curLength / totalLength;                                                         // Calculates the percent of colour at the ending point of the line to be used in current pixel
    float startPercent = 1 - (curLength / totalLength);                                                 // Calculates the percent of colour at the starting point of the line to be used in current pixel

    float a = Math.abs(end.getColour().getAInInt() * endPercent + start.getColour().getAInInt() * startPercent);    //Interpolating alpha
    float r = Math.abs(end.getColour().getRInInt() * endPercent + start.getColour().getRInInt() * startPercent);    //Interpolating red
    float g = Math.abs(end.getColour().getGInInt() * endPercent + start.getColour().getGInInt() * startPercent);    //Interpolating green
    float b = Math.abs(end.getColour().getBInInt() * endPercent + start.getColour().getBInInt() * startPercent);    //Interpolating blue

    return new PixelData(a, b, g, r);                                                                   // returing the intepolated value

```
> 2 votes

---
Tags: procedural-generation, heightmap, procedural
---