# Question
Title: Find the coordinates between two points based on third
You can see two points in this picture. Points are surrounded by collider which is set to trigger. Points can either be `Vector3` or `Vector2`, shouldn't make any difference.

I need to get the coords on gray line if mouse enters the trigger, at the exact point where mouse and gray line form 90 degree angle. Gray line is just an straight line between 2 points.

All the data:

* left point coords
* right point coords
* mouse coords

Is it possible with the data I have and how?

---

# Answer
It is possible with the data you have. Let's call the line segment vw and the point p:

```
vec2 projection_point(vec2 v, vec2 w, vec2 p) {
  const float l2 = length_squared(v, w);  // i.e. |w-v|^2 -  avoid a sqrt
  // Consider the line extending the segment, parameterized as v + t (w - v).
  // We find projection of point p onto the line.
  // It falls where t = [(p-v) . (w-v)] / |w-v|^2
  // We clamp t from [0,1] to handle points outside the segment vw.
  const float t = max(0, min(1, dot(p - v, w - v) / l2));
  return v + t * (w - v);  // Projection point that falls on the segment
}

```

This function returns the nearest point on the line segment.

The above code is derived from here: https://stackoverflow.com/questions/849211/shortest-distance-between-a-point-and-a-line-segment
> 2 votes

# Answer
Here's an answer in C#.

```
public Vector3 NearestPointOnSegment(Vector3 start, Vector3 end, Vector3 point) {
    Vector3 dir = (end - start);
    dir.Normalize();

    Vector3 v = point - start;
    float dist = Vector3.Dot(v, dir);
    return start + dir * dist;
}

```

This can be unsafe if there's a chance point could be off the segment. If that's the case and you need to return the closest point on segment anyway, use clamp to either return `start` or `end`:

```
public Vector3 NearestPointOnSegment(Vector3 start, Vector3 end, Vector3 point) {
    Vector3 dir = (end - start);
    dir.Normalize();

    Vector3 v = point - start;
    float dist = Vector3.Dot(v, dir);

    // magnitude takes square root which could be expensive
    // use previous method if your usecase allows
    float length = dir.magnitude;
    dist = Mathf.Clamp(dist, 0f, length);

    pointOnLine = start + dir * dist;
}

```
> 0 votes

---
Tags: unity
---


# Question
Title: Need help with my on collision restart program
I tried using the program

```
using UnityEngine;

private void OnTriggerEnter(Collider other)
{
    if (other.tag == "setting_object_tag")
    {
        Application.LoadLevel(Application.loadedLevel);
    }
}

```

But the `OnTriggerEnter` command came up with an error saying "a namespace cannot directly contain members such as fields or methods".

And the `Application.LoadLevel(Application.loadedLevel);` program had an error saying "application.loadedLevel is obsolete, use sceneManager to determine what scenes have been loaded".

# Answer
The C# programming language requires that every method is wrapped in a class. In order to add such a class as a behaviour to a Unity game object, it needs to be a class which inherits from `MonoBehaviour`. Your script file should look like this:

```
using UnityEngine;

public class RestartOnCollision : MonoBehaviour
{

    private void OnTriggerEnter(Collider other)
    {
        if (other.tag == "setting_object_tag")
        {
            Application.LoadLevel(Application.loadedLevel);
        }
    }
}

```

Note that a script file needs to be named like the class it contains. So in this case, the script should be saved as `RestartOnCollision.cs`.

Regarding the second message: "application.loadedLevel is obsolete, use sceneManager to determine what scenes have been loaded": This is just a warning, not an error. `Application.LoadLevel` still works as you would expect it. However, in a new project you should use `SceneManager.LoadScene` instead.

By the way `setting_object_tag` is a really strange tag name. Did you add a tag with that name to the player (or whatever object you want to cause a level restart if it enters this trigger)?
> 3 votes

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


# Question
Title: why my shader is black in the game mode?
I used this useful blending modes It's good but it just work in Editor mode. what is the problem?!

```
Shader "CodeCorsair/BlendModesFX"
{
    Properties
    {
        _MainTex ("Base (RGB) Trans (A)", 2D) = "white" {}

        // This here gives hints to the shader to do pixel-time tricks
        _BlendMode("BlendMode", Range(0, 16)) = 0 // 0 is standard blend

        [HideInInspector] _BlendOp1("__op1", Float) = 0.0
        [HideInInspector] _BlendSrc1("__src1", Float) = 1.0
        [HideInInspector] _BlendDst1("__dst1", Float) = 0.0
        [HideInInspector] _BlendSrcAlpha1("__src_alpha1", Float) = 1.0
        [HideInInspector] _BlendDstAlpha1("__dst_alpha1", Float) = 0.0
    }

    SubShader
    {

    //  Tags{ "Queue" = "Transparent" "IgnoreProjector" = "True" "RenderType" = "Transparent" }
    //ZWrite Off Lighting Off Cull Off Fog{ Mode Off }
    //LOD 110
        Pass
        {
            BlendOp[_BlendOp1]
            Blend[_BlendSrc1][_BlendDst1],[_BlendSrcAlpha1][_BlendDstAlpha1]

            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma fragmentoption ARB_precision_hint_fastest
            #include "UnityCG.cginc"

            sampler2D _MainTex;
            float _BlendMode;

            struct vin
            {
                float4 vertex : POSITION;
                float2 texcoord : TEXCOORD0;
                float4 color : COLOR;
            };

            struct v2f
            {
                float4 vertex : POSITION;
                float2 texcoord : TEXCOORD0;
                float4 color : COLOR;
            };

            v2f vert(vin v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.texcoord = v.texcoord;
                o.color = v.color;
                return o;
            }

            fixed4 frag(v2f i) : COLOR
            {
                float4 color = tex2D(_MainTex, i.texcoord);
                color.rgb = 1.0 - (1.0 / max(0.001, color.rgb * color.a + 1.0 - color.a)); // max to avoid infinity

                return color;
            }

            ENDCG
        }
    }
}

```

when I used Transparent Queue I had this result:

# Answer
Try adding the `uniform` keyword before the below lines:

```
sampler2D _MainTex;
float _BlendMode;

```

changes to:

```
uniform sampler2D _MainTex;
uniform float _BlendMode;

```
> -1 votes

---
Tags: unity, shaders
---


# Question
Title: Difference between unity scripting backend IL2CPP and Mono2x
**IL2CPP** is a Unity-developed scripting back-end which you can use as an alternative to Mono when building projects for some platforms. Note - IL2CPP is only available when building for the following platforms:

* Android AppleTV, iOS\*, Nintendo 3DS, Nintendo Switch, Playstation 4 Playstation Vita, WebGL\* ,Windows Store, Xbox One

I have a project(unity 5.2) which has switched for Android deployment. I tried to switch my scripting backed from `Mono2x` to `IL2CPP` and its showing me that

> IL2CPP on Andriod is experimental and unsupported

So, my simple question is that if it is still not supported then why the option has included, what is the fundamental difference between IL2CPP and Mono2x. **Why I switched to IL2CPP** scripting backend ? what are its **pros and cons**?

I have also checked in unity 5.5.2 there is not IL2CPP option in windows platform deployment.

# Answer
> 25 votes
**Information is based on Unity version 2018.2:**

Quoting the Unity manual on IL2CPP:

> IL2CPP (**Intermediate Language To C++**) is a Unity-developed scripting backend which you can use as an alternative to Mono when building projects for various platforms. IL2CPP (**An ahead-of-time (AOT) compiler)** supports debugging of managed code in the same way as the Mono scripting backend.
>
> When building a project using IL2CPP, Unity converts IL code from scripts and assemblies to C++, before creating a native binary file (.exe, apk, .xap, for example) for your chosen platform. Some of the uses for IL2CPP include increasing the performance, security, and platform compatibility of your Unity projects.

Quoting the Unity tutorial on IL2CPP & Mono:

> Each Scripting Backend has benefits and drawbacks that should influence your decision on which is the right choice for your situation:
>
> **IL2CPP:**
>
> * Code generation is heavily improved compared to Mono.
> * Debugging Script code in C++ from top to bottom is possible.
> * You can enable Engine code stripping to reduce code size.
> * Build times are longer than with Mono.
> * Only supports Ahead of Time (AOT) compilation.
>
> **Mono:**
>
> * Faster build times than IL2CPP.
> * Supports more managed libraries due to Just In Time compilation (JIT).
> * Supports runtime code execution.
> * Must ship managed assemblies (.dll files that mono- or .net produce).

**Important Points:**

> * The default Target Architecture in the Android Player Settings are armv7 and x86 with the IL2CPP and Mono Scripting Backend.

* Mono is not supported on UWP (Universal Windows Platform) or iOS 11 and above. The default Architecture in the iOS Player Settings are armv7 and arm64 with the IL2CPP Scripting Backend.
* UWP build only support IL2CPP and .NET, The .NET scripting backend (Deprecated ) uses Microsoft’s .NET to power scripting.

# Answer
> 4 votes
> IL2CPP is a Unity-developed scripting back-end which you can use as an alternative to Mono when building projects for some platforms. When you choose to build a project using IL2CPP, Unity converts IL code (sometimes called CIL - Intermediate Language or Common Intermediate Language) from scripts and assemblies into C++ code, before creating a native binary file (.exe, apk, .xap, for example) for your chosen platform. Some of the uses for IL2CPP include increasing the performance, security, and platform compatibility of your Unity projects.
>
> Source

IL2CPP is a supposedly equivalent\* execution platform that is faster than mono. In this context "experimental" places a strong emphasis on the word **"supposedly"** in the previous sentence.

Experimental features are released for the same reason beta software is released publicly: The software is good enough to use, and the developers want bug reports and other feedback from a wide range of users so they can get to the point where the software is ready or the actual release.

---

\*IL2CPP doesn't work for code that is used purely through reflection, which will happen when using reflection, serialization, or generics on classes that are never called directly and thus stripped from the build. The same restriction currently applies to Mono on platforms that use Ahead of Time compile restrictions.

---
Tags: unity, c#, mono, il2cpp
---


# Question
Title: Tools or techniques for UV unwrapping/texturing terrain with features such as roads?
I'm trying to create a map similar to Outset island in Loz: Wind Waker. Here is an example of what I'm trying to create:

As you can see, the roads more or less have dedicated tris. However, when I look at the UV data, it looks like a complete mess:

For reference, this is the texture without any overlays:

I have no idea how to go about creating a similar effect in my own game -- are there any tools I can use? What is this technique called?

# Answer
It's UV-mapping. There are no rules to say it has to be neat, it is just preferred and encouraged by most to have a neat UV layout.

UV-mapping is about making a part of a texture show on a certain part of the mesh. We can use seams to help position parts of the layout neatly. In your example I don't think any seams have been used and probably no effort has been made to make a neat layout.

UV's use a repeating coordinate system, the layout that appears outside of the image will still use the same image, you will find the matching texture if you tile the image.

While we usually try to avoid stretching the layout, a simple texture can hide stretching, in this case, the patch of green at the top you can see has been repeated using different scales to get some variation.

At the end of the day, it is about the texture on the model looking good, not what the UV layout looks like.
> 1 votes

---
Tags: unity, textures, blender, uv-mapping, texture-atlas
---


# Question
Title: shooting bullets without players being able to cheat
I'm working on a multiplayer game and for bullets that players shoot I was wondering what is the right way to do it:

when a player press a key It send the key code to server and:
**a.** server starts moving the bullet and sends the bullet location to clients
**b.** server tells the clients to generate a bullet and move it in angle x, with speed of x for duration of x

well the second way makes more sense but I'm worried about players being able to cheat in the second way. So How should I do this without players being able to cheat?

# Answer
> 3 votes
The bullet may not actually matter. The safest way to design such a system is giving full authority to the server. This means that only the server simulates critical events, such as damage or death.

The bullet and shooting effects may just be for show on the client. The downside of this is that it may produce some odd effects in laggy environments, but the end user shouldn't be playing a shooter in a laggy environment anyway.

It's also worth considering that the user will expect immediate feedback when they shoot a gun. So it makes sense for that client to create their own shooting and bullet effects. But everyone else's projectiles are created only on the server's instructions.

Client validates the conditions for shooting locally, and if they are fine it will create the bullet and play the shooting animation. At the same time it sends a request to the server, which then validates again. If everything is fine the server relays the shooting command to everyone. If anyone is subsequently damaged by the projectile, the server alone makes that decision and informs all of the clients of the outcome.

Keep in mind you'll need to integrate prediction for this sort of solution to be satisfying.

# Answer
> 0 votes
These options aren't mutually exclusive. Both the server and the clients can be simulating the bullet (that way it can continue to move correctly even if there's a delayed/dropped packet from the server).

The only question is which simulation has the final authority when we claim the bullet hit or missed someone.

To fairly adjudicate that, the server needs to simulate the bullet and report when it hits something. If the server says you got hit, everyone's simulation has to update to include the effects of that hit.

---
Tags: multiplayer, anti-cheat
---


# Question
Title: Implementing a Deferred Renderer (Basic Understanding)
I am trying to implement a Deferred Renderer in Direct3D11. I am fairly new to this. I already bought a book: Practical Rendering & Computation with Direct3D 11. However, this book doesnt answer many of my questions.

The Book just says "Call one of the Draw Commands to execute the Pipeline"

In the context of a deferred Renderer I would like to know How I can actually render the different GBuffers, merge them and put actual Lighting to my scene. Let's say my GBuffers should represent Diffuse, Specular and Normals. I understand that Vertex Shaders have Constant Buffers that represent my Camera through Matrices. Vertices get Transformed in shaders into ViewSpace. How Do I get my Diffuse/Specular/Normal information out of that?

Do I have to execute the Rendering Pipeline for every GBuffer? Technically do I just need to transform my vertices once in a VS and just execute my different GBuffer PS? The Context Object offers functions like "OMSetRenderTarget". The OutputMerger however is the last stage of the Pipeline, not the first...

The Book itself just calls "Present(0,0)" exactly once and doesnt explain how you actually put things together.

Sorry, quite a lot of different questions :(

# Answer
> 2 votes
In short, there's nothing super special about a deferred renderer when it comes to drawing the initial scene. You just submit your triangles via VBs/IBs, state, and the `Draw*` functions like any other Direct3D 11 application. The difference is that for a deferred renderer you use special shaders that write position, normal, and surface information to the render target instead of shaded final pixels, -and- you typically do this with multiple render targets bound.

If you are that new to DirectX 11, you should probably start with classic forward rendering first. Take a look at DirectX Tool Kit.

After that, additional passes with the g-buffer are effectively the same as classic full-screen post-processing, namely you just set up a pixel shader and bind your gbuffer as a texture, you bind another buffer as your render target, and then you draw a full-screen quad to fire it off. With Direct3D Hardware Feature Level 10.0 or better, you can use some tricks to make this easier. See FullScreenQuad.

> Note that modern games typically use hybrid techniques known as forward+ rendering rather than deferred these days. See this article

---
Tags: directx11, deferred-rendering
---


# Question
Title: Would it be worth designing games in which the fighting is suspended so your enemies can get some sleep?
I think one way to motivate kids to get more sleep at night would be to design a series of video games in which the monsters/creatures/aliens, etc., will automatically stop attacking your character between the hours of say 11:00pm - 7:00am.

At 11:00pm, they will cease fighting, will lay down and fall asleep. At 7:00am, they will wake up and resume attacking your character. If you attack them while they are sleeping, you will lose major points or you will instantly die.

Also, you will need to instruct your character to go to sleep during this same period, or your character will be very sleepy when the game resumes and will not perform well.

This particular time period would need to be hard coded into the game so it cannot be changed. So, at 11:00pm in New York City the enemies in the game will go to sleep, and the same thing happens in the game at 11:00pm in Los Angeles, and so forth in all the time zones around the world.

Would it be worth adding this feature to video games or would most kids just refuse to play them?

# Answer
I understand where you are coming from. There are some games around with some questionable design decision which encourage the player to focus their whole life around the game. Among these are PvP mechanics which allow players to take advantage of players who don't log in that frequently, timed events which fall into times where players are usually asleep, challenges with a real-time time limit of several days which can only be completed when the player plays many hours each day or other mechanics and design decisions which discourage the player from quitting the game any time they want. Such game mechanics have some serious ethical problems. Especially if paired with pay-to-win microtransactions. But if these are a problem in your game, then you should first consider some solutions which address these mechanics directly.

I think that it is obvious that adding a "crippled mode" to your game which is solely designed to make the player quit playing is not making your game any more enjoyable. If you just want to prevent the player from playing, you could achieve that goal in a far more straight-forward manner which requires far less development resources on your behalf: Just kick them out of your game and prevent the game from starting until 7am. This is a feature you could develop within *minutes* of development time.

Now the question is whether you as a game designer have the moral responsibility (or in fact the moral right) to tell your players when to go do bed. You are not their parent. Some of your players might not even be children anymore. And besides, your game alone won't convince the players to do this. When they don't feel like going to bed, they will just play a different game. There are more than enough games available on the market, after all.
> 5 votes

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


# Question
Title: How do I determine distance of a point within a ProBuilder mesh?
As in the title, I have an effect prepped for my game which applies certain derived parameters to a post-processing effect after the player enters a boundary I created with ProBuilder. Finding how far inside the bound the player is; that is, how far the player would have to travel, at minimum, to leave it; would help me scale this effect. It is not an axis-aligned boundary, and its sloped shape is fairly important. Having the effect go full-on on crossing the boundary would be jarring to the player.

I'm tempted to resort to traditional edge testing with this, but I would like to highlight that it will be done at least once per frame on multiple objects, so I would like to keep it as simple, and non-home-rolled, as possible.

The other possibility would be to keep track of time exposed and scale it by that; but this isn't ideal and I'm seriously curious as to whether a penetration-depth-testing method exists out-of-box.

---

A requested image of my setup:  It is laterally symmetric, and that is unlikely to ever need to change. However, future volumes are likely to have varying angles and heights. Depth is more-or-less irrelevant, as while I'm using 3D, this game has the physics of a 2D platformer; so you can consider it to have infinite depth if you need to. As you can see on the right, I've added almost nothing to it, other than the MagneticField.cs custom script (which does not even reference the mesh, only whether it's been crossed) and a debug class, TriangleReport.cs, that I'm working on right now.

One thought I had was to get triangles for the top, bottom, left, and right edges, use them to define planes, and then determine the distance from those planes; but if you've got something better I am all ears!

# Answer
So this is what I've got going. On account of the inquiries of @DMGregory, I managed to file down exactly what I needed to test for. It's likely that I'll do something a little different, but this seems to work:

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

[RequireComponent(typeof(MeshFilter))]
public class TriangleReport : MonoBehaviour {

GameManager manager;

Mesh mesh;

int[] triangles;
Vector3[] vertices;
Vector3[] normals;

Plane Left, Right, Top, Bottom;

void Awake() {
    manager = GameObject.Find("/Game Manager").GetComponent<GameManager>();
}

///<summary>
///I will only ever need to worry about the top, bottom, left, and right of the mesh bounds, which will be z-axis aligned.
///That said, I can compare the normals of the triangles to the Left/Up/Right/Down normals and find the ones that best fit. Since
///one triangle defines a plane, this will be all I need to simply do a minimum of plane distances.
///</summary>
void Start () {
    mesh = GetComponent<MeshFilter>().mesh;
    triangles = mesh.triangles;
    normals = mesh.normals;
    vertices = mesh.vertices;

    Vector3[] RightVerts = GetFaceAligned(vertices, triangles, normals, Vector3.right);
    Vector3[] LeftVerts = GetFaceAligned(vertices, triangles, normals, Vector3.left);
    Vector3[] TopVerts = GetFaceAligned(vertices, triangles, normals, Vector3.up);
    Vector3[] BottomVerts = GetFaceAligned(vertices, triangles, normals, Vector3.down);

    //Get normal of the triangle via a cross product (either direction will do)
    Vector3 NormalRight = Vector3.Cross(RightVerts[1] - RightVerts[0], RightVerts[2] - RightVerts[0]).normalized;
    Vector3 NormalLeft = Vector3.Cross(LeftVerts[1] - LeftVerts[0], LeftVerts[2] - LeftVerts[0]).normalized;
    Vector3 NormalTop = Vector3.Cross(TopVerts[1] - TopVerts[0], TopVerts[2] - TopVerts[0]).normalized;
    Vector3 NormalBottom = Vector3.Cross(BottomVerts[1] - BottomVerts[0], BottomVerts[2] - BottomVerts[0]).normalized;

    Right = new Plane(RightVerts[0], NormalRight);
    Left = new Plane(LeftVerts[0], NormalLeft);
    Top = new Plane(TopVerts[0], NormalTop);
    Bottom = new Plane(BottomVerts[0], NormalBottom);
}

///<summary>
///Find the triangle that best matches the provided normal, and return it
///</summary>
Vector3[] GetFaceAligned(Vector3[] vertices, int[] triangles, Vector3[] normals, Vector3 bestNormal) {
    int winner = -1;
    float winningDot = System.Single.NegativeInfinity;

    for(int i = 0; i < triangles.Length; i += 3) {
        Vector3 normal = (normals[triangles[i]] + normals[triangles[i+1]] + normals[triangles[i+2]])/3f;
        float dot = Vector3.Dot(normal, bestNormal);

        if(dot > winningDot) {
            winningDot = dot;
            winner = i;
        }
    }

    return new Vector3[3]{
        vertices[triangles[winner]],
        vertices[triangles[winner + 1]],
        vertices[triangles[winner + 2]]
    };
}

// Update is called once per frame
void OnTriggerStay (Collider c) {
    Vector3 pos = transform.InverseTransformPoint(manager.robot.transform.position);
    float distance = Mathf.Min(Bottom.GetDistanceToPoint(pos),
        Mathf.Min(Top.GetDistanceToPoint(pos),
        Mathf.Min(Left.GetDistanceToPoint(pos),
        Right.GetDistanceToPoint(pos))));
    Debug.Log(distance);
}
}

```

That said, what I do is compare each triangle's effective normal to the direction I'm looking for, and select the one that has the highest (and most congruent) dot product. This would be the one that "best" faces that direction.

Since all a plane needs is three vertices and a normal, and in this instance either normal would work, all I have to do to get a plane is take the cross product of two vectors along the triangle.

Plane has a convenient `GetDistanceToPoint` method which will provide the distance to a Vector3 to me. To determine the shortest path out, or at least, its length, all I have to do is take the minimum.

Looking back, there is easily a better way to find the minimum of four items... but this works well as a P.o.C.

@DMGregory also pointed out that I'm effectively, at least in this instance, trying to find the distance to the edge of a 2D trapezoid; but this might not always be true for this project. (We'll see.) I hope this helps someone.
> 0 votes

---
Tags: unity, 3d, mesh, meshcollider, depth
---


# Question
Title: Text Adventure - Engine actions based on dialogues
Building forward my text adventure i stumbled upon how to actually drive the actions that can be caused by dialogs. I wrote the dialogues and the logic around handling them already, but i'm missing a key about how to turn a dialogue into an 'engine' specific action (like spawn item, drop, buy, sell).

My game is absolutely based on JSON therefore even dialogues are stored there:

An *Option* is what a player can choose by typing one of the defined *Keywords* for currently displayed dialogue.

*Response* is what a player sees when option is chosen

*Goto* is where the dialogue goes next after an option is chosen

*Script* is nothing more fancy than a list of strings with integers that get mapped into a `std::map<std::string,int>` and later passed for the execution. Think of it as of flags.

Let's look at the example below - where you could buy something from inn keeper.

In above situation, you can talk to the keeper and choose:

* "1" to buy item "1"
* "2" to buy item "2"
* "back" to get back to previous dialogue (with a goto)

Let's say i want to choose option "1" and it boils down to the design now.

How would you turn that "1" into a real engine action of buying an item?

What i did.

As you might have seen i have defined a *Script* within the option of the dialogue, this would be just a map (string to int) of attributes passed to an interpreter.

Then the interpreter executes that based on 'action\_type' - which is defined in json, mandatory and describes type of action like here:

Some questions then:

1) Is it the valid approach to write my own interpreter - maybe i can use it somewhere else? or i should start thinking about external scripts - which actually require me to focus on adding library and learning it, instead of doing the game itself.

2) Which class should be really responsible for actually executing the script with the data passed from dialogue.

Dialog class itself ?

```
std::string CDialogue::Process(const std::vector<std::string>& rvArguments)

```

Npc class handling talk action ?

```
void CEntityNPC::HandleTalk(CEntity *pFromWho, const std::vector<std::string>& rvArguments)

```

Command class that handles talk command?

```
void CCommandTalk::Execute(CEntity *pPlayer,const std::vector<std::string>& rvArguments)

```

3) Maybe you can think of a different way to handle this situation? Basically a translation of a text(json) data into a game logic.

# Answer
> 2 votes
Brief context: I work on a fairly large LDMud with mostly (but not entirely) hard-coded objects subclassed from a few primary blueprints. I spend some of my time trying to improve our long-term maintainability by refactoring *common* patterns out of the "content" objects and into the core.

1. You probably don't want to write an interpreter at this scale unless you want to learn how to write an interpreter. I'm not exactly sure what you mean when you say external scripts here, and I'm also skeptical that your scale would make it worth picking up a library unless it's reasonably small/simple/focused.

I would spend some time pondering what you like about JSON, why you want to structure the game around it, and (briefly) getting a sense of what text-game libraries might be real options for you. If you embed executable scripts in JSON, code and content will no longer be separate, and you'll lose all of the advantages of code in the process.
2. I'm not sure there's a silver-bullet answer here, but I'd probably try to abstract command-handling out into parts so that a number of different entities could handle the command, and then start out with doing it on the NPC. It seems like trying to do all of this work in a dialogue or command class could lead to a lot of complexity accumulating in one place. On the NPC class, you'd be able to have a Vendor or ShopKeeper subclass, for example, if the dialogue needs of the tavern-keeper are sharply divergent from the town drunk.

I think this gives you a little wiggle room to focus on implementing instances of this functionality in the short run, until you have a better idea of whether it can all collapse into a single common pattern.

Consider (just pseudocode/concepts here):

* Any user input goes through a command router that checks the first word against a temporary command mapping and passes it on to the correct object/function.
* Individual objects register their intent to handle a given command word, adding it to the temporary command mapping.
* Give every object you suspect might eventually care a chance to register commands. Make a dedicated method for this setup/init work, and this method a call on each object you think might eventually want to register a command in a well-defined order. This isn't too sophisticated. A decent order is: everything the player is holding, everything in the room with them, the room itself, and a general command handler. Think something like `register_command(name, json_command_description)`.
* If anything changes, clear this temporary command map and give everyone a new chance to register.
* When the user actually enters a command, the handler might do something like: `registered_object->command_name(user_input, json_command_description)` or `registered_object->do_command(name, user_input, json_command_description)`

This standard process for registering and handling commands will free you up to move any specific command around fairly easily, so you can write the command on the most specific object it makes sense on and move it towards the core (generalizing, parameterizing, and pushing messages/paramters out into JSON) later. It also means the JSON command descriptions can differ circumstantially in the beginning, so that common structural patterns emerge from real use.

---
Tags: c++, architecture, text-based
---


# Question
Title: How to randomly create a fair maze for a multiplayer game?
I am creating a 2d multiplayer RTS game which happens inside a maze. I have used Growing Tree algorithm to randomly generate the maze. I thought that the maze would be **fair** for each team as long as each team's shortest path to solving the maze is equal to the other team. I made sure of that by making a rule in my game which dictates that each team start point is the other team's finish point and vice versa, so the shortest path would always be equal for both teams. but in practice, I noticed something else.

this question sprang up on me when I was trying to make the resulting perfect maze to a non-perfect maze using this solution, specifically @tobias-k answer.

> if you already have a maze with a single path form start to goal, use this variant:
>
> * Do a Breadth First Search from both the start and the goal, and for each cell in the maze record the number of steps that cell is away from both the start and the goal.
> * Subdivide the maze by putting all cells that are closer to the start into the start set and all cells that are closer to the goal into the goal set.
> * Remove a wall between the two regions to add an additional path from start to goal.
>
> The generated paths might have (maybe even substantial) parts in common, but they should be unique loop-free paths from start to goal. Here's an illustration of the first case:
>
> the result of seperating the maze according to each cell distance from start or end point

However, when I use BFS to calculate all distances from my start and finish point, and before removing a wall to create a non-perfect maze, I mostly get something like this:

in this picture, 336 cells are closer to team Red start point and only 105 are closer to Team Blue start point. Even removing a wall (or more than just one wall) between these two sections does not help the situation.

My game is about collecting the treasures that are randomly spread throughout the maze and getting out before the other team exits the maze, this resulting mazes are totally unfair because it gives one team the higher chance of reaching more treasures in the maze sooner compared to the other team.

**so my qustions are:**

1. Does the mentioned results of growing tree maze generator means that the maze is not fair for a multiplayer game (for simplicity lets just imagine the game happens between two players)?
2. Do I need to change my maze generator to something that produces a uniform texture, like Wilson's or Aldous-Broder Algorithm? (this is based on algorithms introduced by Astrolog

# Answer
> 2 votes
Interesting question, a really simple solution would be to create half a maze and mirroring it. If you don't want a perfect symmetrical maze then I don't have a solid solution for you but I have some thoughts about the steps to take to make it fair for both teams. First creating the perfect maze.

* Carving out the maze step by step for both the red team and the blue team simultaneously should fix the issue of more/less cells closer and thus having more options to choose from for one team making it harder to solve. There are still cases where one team has no more room of carving out walls because the other team has "cut off" an area. You could implement a "switching" patter where the team without cells left can "steal" cells from the other team.
* Another much simpler approach would be to randomly pick a common end point for both teams then have both teams walk away from it randomly but in a different pattern. If you use an equal amount of steps in a perfect maze this should also give an equal amount. Team could end up very close together but you can have a check for this in place and regenerate if necessary.

However, when you start from a imperfect maze or randomly remove walls the problem will get a lot harder to solve. So once you have placed the teams fairly in the perfect maze you could do the following.

* You should not carve into the other teams area unless both cells have the same amount of distance from there starting point.
* Second you should carve only into similar patterns otherwise one player would get a bigger loop, making it unfair.

This should be possible with the growing tree maze algorithm, I mostly used recursive backtracking for my mazes and mostly based my experience on that.

---
Tags: algorithm, multiplayer, graph, maze
---


# Question
Title: How much time would it take to make a sprite-based isometric game with customizable characters?
I've never been good with 3-d models, but I can do sprites. I was hoping I could perhaps make a 2-d isometric game that acts like 3-d. Something like Don't Starve is what I have in mind.

Here's the kind of features I would like to include in games:

1. Rotatable camera. Don't Starve is obviously sprite-based, but you can rotate the camera. The effect may not look that great, but it allows the game to work like it has 3-d graphics when it doesn't.
2. Customizable character. You choose what your character looks like, such as their clothing, hair style, skin color, maybe their face. The issue is, I also want my characters to be animated. I know the number of sprites I'd have to make for that would be huge, but I figured I could shorten the process with things like palette swapping and reversing sprites. Could I have the game procedurally generate a sprite from multiple parts that are all animated? Or would I have to have every single possible combination pre-rendered? Yeah, I'd still have to make a huge number either way, but I can still cut corners where I can.

And yes, I know having both of these things would require me to create an insane number of sprites, but I'd still like to attempt it, if its possible. Also, I'd like to avoid a pixelated look, if that's doable. And yes, I know that would make creating sprites even more laborious, but gimp makes drawing clean lines rather easy, so I'm not too worried about it.

How long would it take me to create each sprite? With that, I could figure out how long it would take me to craft all of them, if I calculate how many sprites I would need per character.

And yes, thinking about the logistics of it all is immense. Animated, customizable characters in game with a rotating camera, meaning that even static objects would need multiple sprites. And no, I don't intend to include camera pitch. Obviously, I'm pushing the boundaries of what I can do as-is.

# Answer
Yes, you can create a character from multiple animated parts and layer them over each other at runtime. This is a very common technique. Changing the color tint at runtime is usually not that difficulty either with most graphic frameworks. If you have any issues with this, feel free to post a new question where you tell us what technology stack you are using, how you load and draw your sprites and how exactly you want your recoloring algorithm to work.

But how long it will take to crete all these character parts and animate them is impossible to say. It depends on:

* How skilled you are at pixel art
* What level of quality you want to achieve
* How many different animations you want to create
* How many phases you want these animations to have
* How many character parts you want

These five factors are multiplied with each other, so it is impossible to give you an estimation without knowing anything about them.

I would recommend you to make a list of objects and animations you need, create your first sprite animation and extrapolate.
> 1 votes

---
Tags: graphics, time-management
---


# Question
Title: How can I implement a scrolling text ticker?
How can I implement a right-to-left scrolling text ticker in libGDX (like stock tickers)?

# Answer
> 0 votes
Assuming that you can draw a `string` on the screen, to implement a ticker, you can simply draw only part of the `string`. For example:

```
string myString = "My large text to display";

```

When you are drawing it, simply draw part of it depending on a value you update every frame:

```
int strPointer = 0;
string myTickerString = "";

void update() {
    strPointer++;
    myTickerString = myString.Substring(strPointer, MAX_STRING_SIZE);
}

```

Now `myTickerString` will contain part of your original string, that every frame loses one letter and displays the rest of the string with a maximum size of `MAX_STRING_SIZE` (The size you choose).

Please note I'm not very familiar with libgdx, but this method should work with any library. For this reason the code is C#/Pseudocode. Also note you can add some delay to how quickly the text scrolls, by tweaking how often `strPointer` increments itself.

---
Tags: libgdx, text, scrolling
---


# Question
Title: Determine if ray hits an edge of a model in Unity 3D
How can i determine if a ray was hitting an edge of a mesh?

The figure below shows what I want to achieve:

Any ideas?

# Answer
> 1 votes
Adjacency information like this isn't needed for most stuff we do with meshes in games, so unfortunately the out-of-the-box representations don't make it easy to access.

The simplest way to do this, especially if you have only a few, simple meshes that need this, is to hand-place a narrow capsule collider along each edge you want to detect with raycasts this way, then fire your raycast against the physics layer containing these edge mark-up shapes.

---

If you want to automatically detect these edges, I'd recommend applying a pre-processing step to help accelerate the queries. You can do this at edit time or in-game when you load a mesh that needs this metadata.

1. Iterate over all the mesh's vertices and build a lookup table that associates vertices in the same position with a shared index.
2. Prepare an associative map edges, keyed by the shared indices of the two vertices it joins (always put the lower index first, so you get the same key regardless of order)
3. Iterate over all the mesh's triangles and compute a face normal for each one by averaging its vertex normals. Use the edge map to store a reference to this triangle and its normal associated with each edge of the triangle.
4. When you find two triangles that share an edge, check the angle between their face normals. If it's less than some threshold you choose, we can call this an internal edge and ignore it. If it's greater, then we call this a sharp edge and mark it up for raycast hits as follows. (You could also take into account whether it's a smooth-shaded edge or creased, if you choose)
5. Build an associative map of crease edges. This will be again be keyed by vertex indices, but we'll use their original indices this time, not the shared alias as we used before. And we'll list them in the key in the order in which they appear consecutively when we wind around the triangle, so the two triangles meeting at an edge give opposite orders (assuming manifold geometry).
6. We add our newly-discovered sharp edge to this final map. The value we store with this key is a `float` tolerance range, computed as the maximum tolerance distance you choose for your raycasts (how far from the edge can we hit and still call it an "edge hit"?) divided by the length of the altitude of the parent triangle measured from this edge to the opposite vertex.

Okay, that was exhaustive. But now we can keep this final map structure for each mesh, and throw away the intermediate structures we built along the way.

Now when we get a candidate raycast hit, we can get its triangle index property, and use that to check whether any of the three edges of the triangle are in the mesh's sharp edge map. If so, we get the hit's barycentric coordinate property, and check whether the weight for the opposite vertex is less than the tolerance value we stored in our map for that edge. If so, then we have struck within our tolerance distance of a sharp edge! :D

---

Okay, so that was a lot of work. One last strategy we could try is somewhat empirical:

When you get a candidate raycast hit, get the triangle normal. Using this, you can predict an expected depth for subsequent raycasts fired from slightly offset positions (as if you were hitting a flat plane). Fire a few such raycasts in the same direction as your original, from positions slightly offset from the first hit. If the depth of any of these raycasts is much larger than the prediction, then you've grazed past an edge, and you can treat the original hit as an edge hit.

---
Tags: unity, raycasting
---


# Question
Title: First Person Shooter Character in Unity - Meshes Clipping When Close to Body?
I am working on a game character using Unity. I'd like it to be playable in 3rd Person and 1st Person depending on what the user chooses (switchable in game whenever ideally).

I've worked on and read many examples all using different techiniques (some don't have any mesh for the player and just have a gun; others have no gun at all, just aiming; some use basic geometry only like cylinder and sphere bullet and dont really work when i try using high-poly human like etc).

So I am trying my own ideas and feel like maybe it's impossible for me to make a properly decent game character :\[

Here is exactly what I have so far:

a) Mixamo 'Passive\_Marker\_Man' with idle-rifle-aiming animation.

b) SetIKPosition/Weight for each hand to specific transforms on the gun object.

c) Guns 'butt'/base is the gun objects pivot/origin.

d) The gun is spawned at a transform i made near the models right shoulder

e) Added child object Sphere to player 10 units forward on Z axis

f) Mouse movement on Y moves gun/sphere up and down; mouse X rotates entire player object left/right.

g) SetLookAtPosition IK also done to make head always look at sphere (gun is also always pointed at sphere)

h) camera is set to a position between the two eyes on every frame, and is set to lookAt the sphere.

......When i view this from a 3rd Person perspective it looks pretty good, the guys eyes follow his guns aim, which is pointing nicely at the sphere 10m away.

But if I view it in 1st Person, I can see inside the gun and parts are chopped off etc (aka clipping????)

So am I going about this all the wrong way. It felt so right at some points but now I can't imagine how to stop this kind of thing from ruining the character.

# Answer
The way this is often done is to render in two passes:

* first, render your scene with your normal near & far planes.
* next, clear the depth buffer, and render your character's visible first-person limbs/tools using a very close near & far plane.

That way you can tune the near plane close enough to not clip the limbs, without damaging the depth precision you have available for rendering a large scene.

It also has the benefit that if you walk so close to a wall that your arm/tool would clip into it, the arm/tool is instead rendered on top (strictly incorrect, but looks better than seeing the geometry intersect).

Note that many games will also use a custom set of models & animations for this limb pass in the first-person view, allowing them to play with the positions, angles, and even scale of the limbs so it "looks right" from a first person perspective, even if it departs from what looks realistic from a third-person view.

---

In Unity, you can do this by...

* setting aside a Layer for your first-person models. Assign those objects to this first-person layer.
* set your main camera's Culling Mask to render everything *except* this first-person layer.
* duplicate your camera, and make the clone a child of your original camera.

+ This child camera doesn't need any of the extra components like AudioListener, so you can remove those.
    + The child camera's culling mask should render *only* the first-person layer.
    + The child camera's near & far clipping planes should be set very close.
    + The child camera's Clear Flags should be set to Depth
    + The child camera's Depth should be set to 1 so it renders after the default camera.
> 3 votes

---
Tags: unity, 3d, character, first-person-shooter
---


# Question
Title: How can I color single triangles with a color palette?
My primary goal is to have a lowpoly rendering style, so that each triangle has its own homogeneous color on all its fragments, meaning color is not interpolated between vertex.

I have my indices buffer with 4 values: 3 integers indicating the vertex index, and one ubyte indicating the color index from a 1D texture, which is just an array of 256 24bits colors in a vec3.

Is it possible to do this with opengl3.3 in core profile?

Do I need glVertexAttribDivisor? I'm not sure I really understand what it does exactly.

I've also heard about flat shading, but I don't know exactly how I could do it. I could also set a color per vertex, but triangles would share vertices, so it doesn't seem like a solution.

# Answer
> 1 votes
glVertexAttribDivisor wouldn't help you: it is used to specify an attribute per model instance.

If you draw 10 instances of a house model of 1000 vertices, then you can use the divisor to set a value (for tranform, colour, etc.) per instance.

If I were you, I would draw my geometry non-instanced, thus use glDrawArrays() instead of glDrawElements().

You would have to flatten the model by removing the indexing.

Once you have that, you can simply supply the same colour to each of the three vertices of each triangle.

In your case, you would give the same 1D texture coordinate for each vertex, as you are using a texture as your colour palette.

Make sure you set the sampling to GL\_NEAREST so that your texture sample doesn't get interpolated.

---
Tags: opengl, shaders, index-buffer
---


# Question
Title: ScreenToWorldPoint and ViewportToWorldPoint
I'm currently following tutorials on Youtube to learn howto use Unity. My code runs perfectly as per the tutorial, but i just have some questions regarding the code, with regards to screenToWorldPoint & viewportToWorldPoint.

The purpose of the code is for a 2D platformer, where the character's arms will rotate and face where the mouse cursor is.

Code:

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

public class ArmRotation : MonoBehaviour {

    public int rotationOffset = 0;

    // Update is called once per frame
    void Update () {
        Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position; //Gets the difference between
        difference.Normalize(); //Normalizing the vector

        float rotateZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.Euler(0f, 0f, rotateZ + rotationOffset);
    }
}

```

I've done some googling and am aware of the difference between screenToWorldPoint and viewportToWorldPoint as per the answer here https://answers.unity.com/questions/168156/screen-vs-viewport-what-is-the-difference.html

Where

1. Screen: from \[0,0\] to \[Screen.width, Screen.height\]
2. Viewport: from \[0,0\] to \[1,1\]

**Questions:**

1. **Why do we have to calculate the difference between the position of the mouse cursor and the position of the character's arm** instead of just setting the following: . `Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition);`
I've tried setting it to the position of the mouse cursor instead of using the difference between the arm & the cursor and while the code still works and the arm is still able to rotate, it is a little "off" from the direction of the cursor. E.g A little higher than where the cursor is. Why does using the difference solve this issue?
2. **Why do we call difference.Normalize() ?** To my understanding, Normalize returns a vector between 0 & 1.However, Mathf.Atan2 returns the angle in radians whose Tan is calculated by y/x. As such, calling Normalize and returning a vector to a value between 0 & 1 makes no difference because the value calculated will be the same between a un-normalised and normalised vector since the proportions are the same?
3. When i use ViewportToWorldPoint instead of ScreenToWorldPoint, i do not use Normalize because to my understanding, the Vector returned by ViewportToWorldPoint should already be within 0 & 1, hance we do not have to normalise it. However, when i test the code out in play mode,the arm barely rotates. **Why is this so?**

I would appreciate any help or pointers in the right directions.

Thanks!

EDIT: I had a look at the manual and realise that Normalize() returns a vector with the same direction, but magnitude 1, but i'm still just as confused

# Answer
# Because if you don't, it'll be wrong.

Imagine putting the mouse DIRECTLY over the character and then 1 pixel to the right (we want a non-zero vector before we normalize to avoid weirdness with trying to deal with a zero-length vector).

We'll say that this happens at 300 pixels from the left and 120 pixels from the top of the screen. Values aren't important other than to walk through both scenarios and see what happens.

So here's your code:

```
    Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position; //Gets the difference between
    difference.Normalize(); //Normalizing the vector

    float rotateZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
    transform.rotation = Quaternion.Euler(0f, 0f, rotateZ + rotationOffset);

```

We don't need to know what (300,120) works out to after transforming it to a world point, as we said it's "1 pixel to the right" of the character. Subtracting off the character's position leaves us with `(x,0)` where `x` is that tiny fraction of a unit that corresponds to 1 pixel. Then `difference.Normalize();` is called, giving us `(1,0)` (because Normalize gives us a unit vector with the same heading, which in our case was +1 to the right, or positive X).

Then we get to calculate `rotateZ`, which on the vector of `(1,0)` ends up being `0.099 radians` (or 0.0017 degrees).

`Quaternion.Euler(0f, 0f, rotateZ + rotationOffset)` ends up being some rotation equal to `(0,0,0.099)` as rotationOffset is `0`. Functionally this is pretty much `(0,0,0)` (rounding errors using le Google calculator) and the arm will end up pointing to the right.

### Now what happens if we don't subtract?

Well, we'd end up normalizing `(300,120)` instead, which is in the neighborhood of `(0.928, 0.371)`. That gets plugged into Atan and we get `0.38` (21 degrees). That's almost a quarter of the way to vertical! Our character would be pointing too high. And this gets even worse if we move our mouse to be 100 pixels to the right (he should point in the same direction, right?)

`(400,120)` normalizes to `(0.958,0.287)` which Atans to `0.29 radians`. His arm *moves down* pointing lower. Not a lot lower, but it still *moved.* At the far right of the screen `(1000,120)` the rotation is `0.119 radians`.

### What about on his left?

Oh boy. So if we move 2 pixels to the left of our original position, so our mouse is 1 pixel to the *left* instead of 1 pixel to the *right* the arm's rotation (when not subtracting) works out to be...

`0.38 radians`

Wait what?

Yep. Exactly the same (plus or minus a few thousandths). Now your mouse is to the left and your character is pointing to the right.

Remember how `(300,120)` normalized to `(0.928, 0.371)`? Well `(298,120)` normalizes to pretty much the same value: `(0.927, 0.373)` and you wanted him to flip around a full 180 degrees!

The only way we can do that is by subtracting off the character's location:

`toWorld(298,120) - pos` would then result in `(-x,0)` and normalize to `(-1,0)` and be `3.14 radians` (180 degrees).
> 2 votes

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


# Question
Title: Jumping to land x pixels ahead while not really moving (2D)
The player object in my game has its x-axis locked. It can only jump on Y. It's the ground that constantly moves to the left so that it appears like the player is moving to the right.

The ground is moving left at a speed of 240 pixels per second.

Whenever the player falls and hits the ground, I want it to jump so that it hits the ground again when it has gone 180 pixels to the left.

So, it should jump, the ground should get to move 180 pixels and then the player should hit the ground at that moment and jump. Then repeat. 180 pixels each time.

Oh and, the jump height may be variable. Specifically, there will be two jumps: a small jump and a big jump. Both need to land after the ground has moved 180 pixels.

I'm bad at math, so I can't figure it out. I would appreciate any help!

# Answer
If your ground scrolls at

```
groundSpeed = 240 // pixels per second

```

And you want your jump to cover

```
jumpDistance = 180 // pixels

```

Then your jump needs to last

```
jumpDuration = jumpDistance / groundSpeed = 180 / 240 = 0.75 // seconds

```

Let's say arbitrarily that you want the jump to take a parabolic arc. If we track the time since the jump started, and the height the player was at then, we can set:

```
currentHeight = startingHeight
              + jumpHeight
              * (1 - 4 * (timeSinceJumpStart / jumpDuration - 0.5)^2)

```

This gives you a parabolic height that hits `startingHeight` at `timeSinceJumpStart == 0` and at `timeSinceJumpStart == jumpDuration`, and hits a maximum altitude of `startingHeight + jumpHeight` in between.

Note that doing it this way, when you do your high jump, you're also effectively increasing gravity - to bring you down faster even though you had more upward velocity to carry you.
> 4 votes

---
Tags: 2d, physics, mathematics, game-maker
---


# Question
Title: Do I need a database to support a sign-in system to associate a player with their save/highscore data?
I am making a 2d game with Unity, and in my game I want to add a username and a password for each player, so that when the player signs in, they will get all the data about what they played until the moment they signed in (like their highscore and so on)

So my question is: do I need to use a database like sqlite, or could this be done with Unity without needing an external database?

# Answer
> 1 votes
Definitely do not need a database. You can store this information in a text file, or the PlayerPrefs.

The app would keep a list of player account names and passwords, and when a user tries to log in, search for the combination in the list.

https://docs.unity3d.com/ScriptReference/PlayerPrefs.html

# Answer
> 0 votes
Are you talking about local user accounts and scoreboards stored on the device? Then an SQL database would likely be overkill. You can store small amounts of data using the PlayerPrefs class. Note that if you want to store passwords (although I am not sure why you would do that for local player profiles) then you should make sure they are properly hashed. The contents of the PlayerPrefs class is stored in plaintext somewhere on the device (where exactly depends on the platform).

If you want global user accounts and scoreboards, then you won't just need a database but also an application server in front of it which prevents people from writing junk into it.

I'm looking forward to playing your game.

# Answer
> 0 votes
it depends of the game, if you will make an online game you should consider use a database to store user data, user credential, achievements, items in inventory, pending quest or complete quests.

of your game wont have online features, then is not recommended, you can use any text file or other formats depending what is better and suits your game like, .json, .yaml, .properties, .INI.

i ussually use .INI files.

# Answer
> 0 votes
Simple answer to the question as written: Define database.

The minimal viable database accessed from C# is `Dictionary`, although some may argue that it is `List`, `Array`, or `Object`. These classes can be used from within Unity, and they can be serialized to and from a file on disk.

While we sometimes call libraries like SQLite databases, in reality they are just software libraries. Libraries almost always give you plenty of features you don't need, along with some features you do need, solutions to problems you never knew existed, and generally a lot of correctness. For example, any decent database library doesn't destroy your file if the application crashes while it was still writing to the file.

You could certainly argue either way in your case: use a `Dictionary` and serialize it to a file (simpler), or use SQLite (likely more correct). Both options are "correct".

---
Tags: unity, databases, authentication
---


title: Rotate player to vector3 point?

text:
# Question
Title: Rotate player to vector3 point?
I want my player object rotate to face vector3 point on terrain.

```
public Vector3 RocketPointer;
public Transform pointer,Player;
public bool rocket_, button_move;

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

    if (button_move == true)
    {
        Ray mouseRay = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit mousePoint;

        if (Physics.Raycast(mouseRay, out mousePoint, 100))
        {
            RocketPointer = mousePoint.point;
            pointer.transform.position = RocketPointer;
        }

        if (button_move == true && Input.GetMouseButtonDown(0))
        {
        // rotate player object to face rocketpointer point
            rocket_ = true;
            button_move = false;
        }

    }

    if (button_move == false && Input.GetMouseButtonUp(0))
    {
        rocket_ = false;
    }

}

public void move_button() // UI button
{
    button_move = !button_move;
}

```

# Answer
> 1 votes
There is a handy convenience method for this: `Transform.LookAt`.

Assuming `player` is your player game object:

```
player.transform.LookAt(RocketPointer);

```

---
Tags: unity, rotate
---


# Question
Title: Publishing a game on Steam. Who's name to put in dev info, do I need a company?
I'm currently paying a game dev to create me a game that I can publish on Steam.

Should I put the devs name or mine for the dev info on Steam?

Do I need a legitimate company in the UK to sell a game on Steam?

# Answer
There are separate fields for publisher and developer on Steam, so I would advice that you put the actual developer's name in the developer field and your name in the publisher field. However, if you have a deal with the developer that they give full rights to the game to you and are not supposed to have their name anywhere after that, obviously do not put their name on Steam.

IANAL, but as far as I know, you do not *need* to have a legal company setup, you *can* publish as an individual. Whether or not you want to do that is for you to decide. A company can protect you from financial liabilities for an example.
> 2 votes

---
Tags: steam, publishing
---


title: Correct way of combining A* and funnel

text:
# Question
Title: Correct way of combining A* and funnel
I implemented a pathfinding algorithm like this:

* There is a mesh of triangles that defines the area the player can walk.
* An A\* algorithm is used for finding a path from the start triangle to the end triangle.
* A funnel algorithm is used for optimizing the path returned by A\*.

The result looks like this:

* The red lines mark the triangles of the mesh.
* The blue lines are the path returned by A\*. The path connects the centres of the triangles that are found.
* The green lines are the path returned by the funnel algorithm.

In the screenshot above, it can be clearly seen that the green path is not optimal. The optimal path would be a straight line from start to end.

The blue path causes the problem. Since A\* just uses the centres of the triangle as a heuristic to determine the length of the path from one triangle to the next, it thinks the best way would be to go through the three triangles below rather than the single triangle above. The blue path is then passed to the funnel algorithm, which only "sees" the triangles connected by the blue path; it cannot find the optimal path, because it is given the wrong set of triangles to work with.

So, I suppose the bug is caused by the heuristic of A\* failing to determine the correct length. How to improve this? What is a better heuristic than just measuring the distances of the centres of the triangles?

Here's the main loop of the A\* algorithm:

```
while ((pCurrent = removeOpenTriangWithLowestEstimatedScore()) != nullptr)
{
    if (pCurrent == pGoal)
    {
        break;
    }

    m_mapClosed[pCurrent] = true;

    for (const CTriangle *pNeigh : pCurrent->neighboursConst())
    {
        ASSERT (pNeigh != nullptr);

        if (isInClosedSet (pNeigh))
        {
            continue; // the neighbour has already been evaluated
        }

        if (!pNeigh->enabled())
        {
            m_mapClosed[pNeigh] = true;
            continue;  // the neighbour is disabled
        }

        auto itNeigh = findInOpenSet (pNeigh);

        if (itNeigh == m_lstOpen.end())
        {
            // Add pNeigh to the open set.
            tas.pT = pNeigh;
            tas.dScore = DBL_MAX;
            m_lstOpen.push_back (tas);
            itNeigh = m_lstOpen.end();
            itNeigh--;
        }

        // Estimate the distance from the neighbour to the goal.

        double dNeighToGoal = pNeigh->distanceOfCentres (*pGoal);

        if (dNeighToGoal < dNearestDist)
        {
            dNearestDist = dNeighToGoal;
            pNearestTriangle = pNeigh;
        }

        // Compute the actual score from start to the neighbour.

        double dScore = actualScore (pCurrent) + pCurrent->distanceOfCentres (*pNeigh);

        if (dScore >= actualScore (pNeigh))
        {
            continue; // this is not a better path
        }

        // This path is the best until now. Record it!

        m_mapCameFrom[pNeigh] = pCurrent;
        m_mapActualScore[pNeigh] = dScore;

        updateEstimatedScore (itNeigh, pNeigh, dScore + dNeighToGoal);
    }
}

```

And here's the main loop of the funnel algorithm:

```
for (it++; it != lstTriangles.end(); pPrev = *(it++))
{
    const CTriangle *pT = *it;
    ASSERT (pT != nullptr);
    ASSERT (pPrev != nullptr);

    getOrderedVertices (*pT, *pPrev, ptA, ptB, ptC);

    // ptA is the new vertex, ptB and ptC are shared by pPrev.

    if (isTurnedAway (ptApex, ptA, ptB))
    {
        ptApex = ptB;
        vecResult.push_back (ptApex);
    }
    else if (isTurnedAway (ptApex, ptC, ptA))
    {
        ptApex = ptC;
        vecResult.push_back (ptApex);
    }
}

```

# Answer
> Since A\* just uses the centres of the triangle as a heuristic to determine the length of the path from one triangle to the next...

You don't have to implement A\* this way. You can use discretized polygon-to-polygon distances to accumulate your path length `g`, but use the Euclidean distance to your actual destination point (not the center of its containing polygon) for your heuristic estimate `h`. This remains an admissible heuristic, because it never over-estimates the length of the shortest path to the destination.

(Since your polygons are convex, you can also treat the cost of the final leg as the distance to the final border edge plus the straight line distance from there to the destination, rather than going via the polygon's center)

Doing it this way, A\* will prefer to explore the upper triangle first, because even though the polygon-to-polygon chain distances are the same on the upper or lower path, the heuristic value is smaller on the upper route.
> 2 votes

---
Tags: c++, path-finding, dijkstra
---


# Question
Title: Why can't i change the background color in Phaser?
what is wrong with my code? i'm using game.stage.backgroundColor but the screen remains black.

main.js:

```
var demo = demo || {};

demo.game = new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.AUTO, '');

demo.game.state.add('state1', demo.state1);
demo.game.state.add('state2', demo.state2);

demo.game.state.start('state1');

```

state1.js:

```
var demo = demo || {};

demo.state1 = function() {};

demo.state1.prototype = {
    preload: function() {

    },
    create: function() {
        game.stage.backgroundColor = "#4488AA";
    },
    update: function() {

    }
};

```

# Answer
> 4 votes
So, I did some tinkering with Phaser, and found the following code to work. Basically it seems like your issue was that the state doesn't know what the variable `game` is. That created an issue. The issue wasn't in setting the color, the issue was that code never got called. Anyways, here's the code that worked for me.

```
var demo = demo || {};

var stateOne = function(game) {
}
stateOne.prototype = {
    create: function() {
        this.game.stage.backgroundColor = "#FF00FF";
    },
}

demo.game = new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.AUTO, "");
demo.game.state.add("stateOne", stateOne);
demo.game.state.start("stateOne");

```

As a disclaimer I should probably mention that I am not very experienced in JavaScript, so if you feel like some part is not necessary, feel free the point that out (or just remove it, you know it better).

# Answer
> 3 votes
If you want to change the background color for the whole game, it´s easier to just set it in the game config. You can even use transparency:

```
const config = {
  ...
  transparent: true
  ...
};
const game = new Phaser.Game(config);

```

...and with a color:

```
const config = {
  ...
  transparent: true,
  backgroundColor: 'rgba(255,110,110,0.5)',
  ...
};
const game = new Phaser.Game(config);

```

---
Tags: javascript, phaser
---


# Question
Title: Changing text through a cursor hover trigger
In my game I have several house groups (see image below), I want to show a specific message when the mouse hovers a specific house group.

For some reason, this only works on the first switch case (house) but fails on the second switch (house2). The default case doesn't work either. I verified that the case house2 is found by the engine. By not working I mean the text does not appear.

Do you have any idea about the problem?

Code:

```
public class MouseIsOver : MonoBehaviour {

    private Image TipImage;
    private Text textObject;
    public string text;
    private bool displayInfo;

    void Start ()
    {
        TipImage = GameObject.Find("realtyInformation").GetComponent<Image>();
        textObject = GameObject.Find("realtyInformationText").GetComponent<Text>();
        TipImage.enabled = false;
    }
    void Update();
    {
        Display();
    }

    void Display ()
    {
        if (displayInfo)
        {
            switch (text.ToLower())
            {
                case "house":
                    textObject.text = "house text1";
                    break;
                case "house2":
                    textObject.text = "house text2";
                    break;
                default:
                    textObject.text = "Click on the building";
                    break;
            }

        }
        else
        {
            TipImage.enabled = false;
            textObject.text = "";
        }
        TipImage.enabled = true;
    }

    private void OnMouseOver()
    {
        displayInfo = true;
    }

    private void OnMouseExit()
    {
        displayInfo = false;
    }
}

```

# Answer
> 1 votes
The trouble here is that you have multiple hoverable objects, each independently trying to take complete control of the text field. So whichever one happens to run last in the update order will win, even if it's not currently hovered.

Let's say "house2" is currently under the mouse, and updates before "house".

"house2"'s `displayInfo` is `true` so it sets `textObject.text = "house text2"`

Next "house" updates. Its `displayInfo` is `false` so it sets `textObject.text = ""`, erasing the text that "house2" had set.

Instead, you'll want to keep responsibility for updating the text in one place. eg.

```
public class TipDisplay : MonoBehaviour {

    public static TipDisplay instance { get; private set; }

    public Text text;
    GameObject selected;

    void Awake() {
         instance = this;
    }

    public void SetTip(string tip, GameObject selected) {
         this.selected = selected;
         text.text = tip;
    }

    public void ClearTip(GameObject unselect) {
         if(unselect == selected) {
              selected = null;
         }
    }

   void Update() {
        if(selected == null)
             text.text = "";
   }
}

```

Put this on your text field and wire up the reference to the text component.

Now your individual hoverables can just signal when they become hovered / not hovered:

```
void OnMouseEnter() {
    TipDisplay.instance.SetTip(myTipText, gameObject);
}

void OnMouseExit() {
    TipDisplay.instance.ClearTip(gameObject);
}

```

Passing the game object we're selecting/deselecting helps guarantee that we don't accidentally clear somebody else's tip if the calls happen in a different order than we expect.

# Answer
> 0 votes
Your `Display()` method isn't being called from anywhere (well, it is, but in a static block that runs once), either you have left out the `void Update()` in your question, or you have a bug there.

Second, I wouldn't use a switch block on a string. I would just put the desired display text in the `text` field and display it directly.

Third, you have `TipImage.enabled = true;` at the end of your `Display()` method, meaning that the tooltip will always display. You need to move that line inside your `if (displayInfo)` block.

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


# Question
Title: How to set default pose of model from Blender? (Exported as FBX)
I have a model that has lots of animation clips(actions).

Before export as FBX, I set the pose to named "default" pose and exported as FBX like this.

But in Unity, it's changed to first animation clip in animation list in Blender!

I try to fix it, but there is nothing I can do. I can't change the order of animations in Blender and Unity either.

This wasn't first time, I had same issues before but I just ignored because it's fine in game play, but I really want to fix it this time.

What I want is set "default" pose in edit mode in Unity(not play mode). How do I set "default" pose as default, not first animation clip in the list?

Using Blender 2.78, and Unity 2017.3.0f3.

# Answer
As Sidar said, change name of "Default" clip to "\_Default" should be work. It's not complete solution, might be fix for now.
> 0 votes

# Answer
You should Know that Unity takes the "default pose" from the first frame of the first animation.

Also Unity classifies them as they are in blender:

\[Solution\] 1 - Always create an Idle Animation and set the "default pose" in the first frame, and rename it to be the first animation.

or

2 - set "default pose" on the first frame of your first animation(action) in blender, so Unity can understand that's the default pose.

(don't forgit to Reimport the .FBX in Unity after making changes)
> 2 votes

---
Tags: unity, animation, blender
---


# Question
Title: How do I calculate the total XP to reach a particular level, when each level takes 10% more?
How do I calculate the amount of XP for a level where the first level is 110, and each level after is 10% more than the last. Preferably to do without a loop because the levels will have to be infinite and will need to be quickly calculated.

in js using a loop:

```
var xptest=110;
var lastLevel = 110;
for (var level = 2; xptest <= Number.MAX_SAFE_INTEGER || level < 100; level++) {

    lastLevel*=1.1;
    lastLevel = Math.round(lastLevel *1.1)
    xptest+= lastLevel;

    console.log('LEVEL',level,'('+lastLevel+' / '+xptest+')');
}

```

# Answer
> 4 votes
Let's work through some cases, given \\$baseXP = 110\\$ and \\$increase = 1.1\\$:

$$\begin{align} targetXP(1) &= baseXP\\ targetXP(2) &= baseXP + baseXP \cdot increase\\ targetXP(3) &= baseXP + baseXP \cdot increase + baseXP\cdot increase^2\\ ...\\ targetXP(n) &= baseXP + baseXP \cdot increase + ... + baseXP \cdot increase ^ {n-1}\\ \end{align}$$

If we multiply \\$targetXP(n)\\$ by \\$increase\\$, we find that all it does is shift the terms down one:

$$\begin{align}targetXP(n)&\cdot increase\\ &= baseXP \cdot increase + baseXP \cdot increase^2 + ...+ baseXP \cdot increase^n\end{align}$$

So if we subtract the original from this shifted version, all the terms except the first and last will cancel out, and we get...

$$\begin{align} targetXP(n) \cdot increase - targetXP(n) &= baseXP \cdot increase^n - baseXP\\ targetXP(n) \cdot (increase - 1) &= baseXP \cdot (increase^n - 1)\\ targetXP(n) &= baseXP \cdot \frac {1 - increase^n} {1 - increase}\end{align}$$

This is what's called a Geometric Series - you can read more about the math behind this here.

# Answer
> 2 votes
You're correct to want to use a technique which is more professional and elegant than a brute force loop! \[;)

$$XP\_{next} = XP\_{initial} (1 + Rate\_{level})^{Level\_{current}}$$

This is the compound interest formula. "Rate\_level" is rate per level.

So, you're level five and you want to know the XP for level six:

$$\begin{align} NextLevel = 110(1+0.10)^5\\ = 110(1.10)^5\\ = 110 \times 1.61051\\ = 177.1561\\ \end{align}$$

Rounded down is 177xp.

To find what level you're currently at based on your current experience points:

$$Level\_{current} = log\_{(1+Rate\_{initial})}\left(\frac{XP\_{current}}{XP\_{initial}}\right)$$

10% is quite a steep progression curve, but it sounds like you know what you're doing and that you want it that way. If this were a D&D style RPG I would lean more toward 195% to 210% per level progression, which would imply a relatively limited number of levels.

Good luck.

---
Tags: mathematics, javascript
---


# Question
Title: Using ShaderGraph for UI elements with transparency
I am trying to design some UI elements using shader graph. In this case specifically a life bar that is transparent where empty.

For a normal life bar with a filled and empty color I got it working without much issue. I created my shader using an unlit model, and set it to a material. I set the material on a raw image, and then added it to a canvas.

Now I want to create a life bar with transparency. It I make the shader transparent, I just get a black box. If I make it opaque I can see the shader, but the transparent (alpha blended) sections of the image are just black. I cannot find any settings to fix this. The shader looks fine outside of UI with the transparency working.

Is there a way to make raw images on a shader graph support transparency even if it is just yes/no per pixel transparency?
Is a raw image the correct way to use a shader on UI?

# Answer
> 0 votes
# You're looking for Alpha Cutoff

*Or alpha test.*

There are some builtin shaders that do this, but the general idea is to check the alpha value of the texture (which goes from 0% to 100% from one side to the other) and compare that value with a float property (driven by your player's HP). If it's less, output 0. If it's more, output 1.

It tends to leave a jagged edge, though, which is one of the reasons I created these shaders a number of years ago. It treats that boundary a little more fuzzily so that any imperfections in the texture are blurred out, as well as allowing for edges that aren't completely hard. I tend to get the best results with a blend value of about `0.02`; small enough that some blurring occurs, but not so strongly that the data precision (i.e. the readability of the graphic) is lost. $2 asset is $2 because that's the lowest non-free price and anyone with understanding of HSLS can create the included shaders themselves in about an hour.

I'm not sure how ShaderGraph would handle this, if there's already a builtin function for it (I'd be surprised if there wasn't), but creating it manually with a few nodes should be easy enough now that you know what the process is.

---
Tags: unity, shaders, unity-shader-graph
---


# Question
Title: How to make shake effect on camera in LibGDX?
I want to shake my OrhographicCamera on some event (i.e. click on the keyboard). How can I do that?

# Answer
This is a good example:

Create a Rumble class to manage the shaking:

```
public class Rumble {
    private static float time = 0;
    private static float currentTime = 0;
    private static float power = 0;
    private static float currentPower = 0;
    private static Random random;
    private static Vector3 pos = new Vector3();

    public static void rumble(float rumblePower, float rumbleLength) {
        random = new Random();
        power = rumblePower;
        time = rumbleLength;
        currentTime = 0;
    }

    public static Vector3 tick(float delta) {
        if (currentTime <= time) {
            currentPower = power * ((time - currentTime) / time);

            pos.x = (random.nextFloat() - 0.5f) * 2 * currentPower;
            pos.y = (random.nextFloat() - 0.5f) * 2 * currentPower;

            currentTime += delta;
        } else {
            time = 0;
        }
        return pos;
    }

    public static float getRumbleTimeLeft() {
        return time;
    }

    public static Vector3 getPos() {
        return pos;
    }
}

```

To start Rumble call:

```
Rumble.rumble(1, .2f);

```

And in the `render` method:

```
if (Rumble.getRumbleTimeLeft() > 0){
    Rumble.tick(Gdx.graphics.getDeltaTime());
    camera.translate(Rumble.getPos());
}

```

The example is from this tutorial:
https://carelesslabs.wordpress.com/2017/08/14/making-a-libgdx-roguelike-survival-game-part-9-screen-shake-inventory-gamedev/
> 2 votes

# Answer
My approach to this problem is to create a child class of an `OrthographicCamera()` and add some functionality to its `update()` method.

```
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.OrthographicCamera
import java.util.Random

class ShakyCamera: OrthographicCamera() {

    private lateinit var samples: FloatArray

    private var timer = 0f
    private var duration = 0f

    private var amplitude = 0
    private var frequency = 0
    private var isFading = true

    private var shake = false

    private fun ClosedRange<Int>.random() = Random().nextInt((endInclusive + 1) - start) +  start

    fun shake(time: Float = 1f, amp: Int = 10, freq: Int = 35, fade: Boolean = true) {
        shake = true
        timer = 0f
        duration = time
        amplitude = amp
        frequency = freq
        isFading = fade
        samples = FloatArray(frequency)
        for (i in 0 until frequency) {
//            samples[i] = Random().nextFloat() * 2f - 1f
            samples[i] = (-1..1).random().toFloat() // only 3 variants (-1, 0, 1) and same visible effect as function above, lol
        }
    }

    override fun update() {
        if (shake) {
            if (timer > duration) shake = false
            val dt = Gdx.graphics.deltaTime
            timer += dt
            if (duration > 0) {
                duration -= dt
                val shakeTime = timer * frequency
                val first = shakeTime.toInt()
                val second = (first + 1) % frequency
                val third = (first + 2) % frequency
                val deltaT = shakeTime - shakeTime.toInt()
                val deltaX = samples[first] * deltaT + samples[second] * (1f - deltaT)
                val deltaY = samples[second] * deltaT + samples[third] * (1f - deltaT)

                position.x += deltaX * amplitude * if (isFading) Math.min(duration, 1f) else 1f
                position.y += deltaY * amplitude * if (isFading) Math.min(duration, 1f) else 1f
            }
        }
            super.update()
    }
}

```

Make an object in your main class (add it to the Stage if you need):

```
    private val camera = ShakyCamera()
    private val stage = Stage(FillViewport(1280, 720, camera), batch)

```

Then call shake fuction when you need it (i.e. when you click a key):

```
handler = object: InputAdapter() {
        override fun keyDown(keycode: Int): Boolean {
            when (keycode) {
                Input.Keys.S -> camera.shake()
            }
            return true
        }
    }

```
> 1 votes

---
Tags: libgdx, kotlin
---


title: Unity3d Move player with UI buttons

text:
# Question
Title: Unity3d Move player with UI buttons
I'm trying to move the player based on UI buttons. I found this topic which covers the button listener: https://forum.unity.com/threads/touch-and-hold-a-button-on-new-ui.266065/#post-1944748

Now I know when the button is being pressed, but how can I "connect" those two scripts to make the player move?

I have this script to the player which was moving without using button.

```
public class player : MonoBehaviour {
     Rigidbody m_Rigidbody;
     public float m_Speed;

     // Use this for initialization
     void Start () {
         m_Rigidbody = GetComponent<Rigidbody>();
         //Set the speed of the GameObject
     }

     // Update is called once per frame
     void Update () {
         /* OLD -> WITHOUT BUTTON

         float x = Input.GetAxis("Horizontal");
         float y = Input.GetAxis("Vertical");

         x = -x;

         m_Rigidbody.velocity = new Vector2( x * m_Speed,  y * m_Speed);
         */
     }
 }

 public class scrLeftButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler {

     // Use this for initialization
     void Start () {

     }

     // Update is called once per frame
     void Update () {
         if (!isPressed) {
             return;
         }
     }

     bool isPressed = false;

     public void OnPointerDown(PointerEventData eventData){
         isPressed = true;
     }

     public void OnPointerUp(PointerEventData eventData){
         isPressed = false;
     }
 }

```

# Answer
```
// Class names should have their first letter capitalized
public class Player : MonoBehaviour
{
     public float movementSpeed;
     private Rigidbody rigidbody;
     public PlayerButton LeftButton; // Drag & drop the left button object
     public PlayerButton RightButton; // Drag & drop the right button object;
     public PlayerButton UpButton; // Drag & drop the up button object;
     public PlayerButton DownButton; // Drag & drop the down button object;

     // Use this for initialization
     void Start ()
     {
         rigidbody = GetComponent<Rigidbody>();
     }

     // FixedUpdate must be used when you manipulate the physics components
     void FixedUpdate ()
     {
         Vector2 velocity = Vector2.zero ;
         if( RightButton.IsPressed ) velocity.x += movementSpeed ;
         if( LeftButton.IsPressed )  velocity.x -= movementSpeed ;
         if( UpButton.IsPressed )    velocity.y += movementSpeed ;
         if( DownButton.IsPressed )  velocity.y -= movementSpeed ;

        rigidbody.velocity = velocity * Time.fixedDeltaTime;
     }

 // Attach this script to your 4 buttons.
 public class PlayerButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler
 {
     // Define a property so that other classes can know whether the button is pressed
     public bool IsPressed
     {
         get ;
         private set ;
     }

     public void OnPointerDown(PointerEventData eventData)
     {
         IsPressed = true;
     }

     public void OnPointerUp(PointerEventData eventData)
     {
         IsPressed = false;
     }

     public void OnPointerExit(PointerEventData eventData)
     {
         IsPressed = false;
     }
 }

```
> 1 votes

# Answer
This is your old way of moving the character:

```
// Update is called once per frame
void Update () {
     float x = Input.GetAxis("Horizontal");
     float y = Input.GetAxis("Vertical");

     x = -x;

     m_Rigidbody.velocity = new Vector2( x * m_Speed,  y * m_Speed);
 }

```

If you want to replace that with UI buttons, simply set the value of `x` and `y` based on the buttons. For example, when the right arrow is pressed, you could set `x` to `1.0` and for left arrow `-1.0`. Do the same for `y`.

One way to do this, is to give a reference of each button to the player, then you could do something like:

```
// Initialise to no button pressed
float x = 0;

// If a button is pressed, change x's value
if (myLeftArrow.IsPressed())
    x = -1;

```
> 0 votes

---
Tags: unity, movement, rigidbody
---


# Question
Title: How to return reference from BlueprintImplementableEvent?
I've got a C++ component and I want to have function which will be implemented in Blueprint like this:

```
UFUNCTION(BlueprintImplementableEvent)
Stats& GetStats();

```

But this doesn't compile, I get the following error:

> overload function differs only by return type from

and Unreal generates function inside .gen.cpp looking like this:

```
Stats Component::GetStats()
{
// ...
}

```

Stats is USTRUCT

# Answer
```
//////////////////////////////////////////////
//By reference
//////////////////////////////////////////////
//.h
UFUNCTION(BlueprintCallable)
    void GetStats(const FStats& stats);

//.cpp
void YOURCLASS::GetStats(const FStats& stats)
{
    stats = FStats();
}

//////////////////////////////////////////////
//Copy
//////////////////////////////////////////////
//.h
UFUNCTION(BlueprintCallable)
    FStats GetStats();

//.cpp
FStats YOURCLASS::GetStats()
{
    return FStats();
}

```
> 1 votes

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


title: How to synchronize moving hazards?

text:
# Question
Title: How to synchronize moving hazards?
I am trying to implement a saw blade hazard in my platformer. The saw blade simply moves from point A to point B, and back, at constant velocity. (Let's assume all saw blades move at the same velocity.)

I currently achieve this using my engine's built-in tweening functionality, which allows me to specify a start position, end position, and duration of the tween.

I start the object at position A, tween to position B, then tween it back to A.

This works well enough, but it limits what I can do with level design. There is no way for me to start the saw blades at intermediate points, which means I can't really design interesting patterns with them, for example, getting them to pass some intermediate point at the same time in their cycles.

Ideally, I'd like to be able to set the terminal points, duration of a cycle, as well as the *initial configuration* of the saw blades. This would allow me to start them at a pattern I want to repeat, and simply let them run.

So, my question is: **How can I set up my moving hazards so that I can easily achieve and experiment with different patterns and synchronizations?**

I work in Godot 3.0, but I don't think that matters. I am looking for general advice about how to set up moving hazards so that they can be synced in reliable yet highly customizable ways.

# Answer
You can set the time of the tween with its `seek` method to start at an intermediate point, e.g.:

```
tween.seek(.5)  # Set it to 0.5 seconds.

```

---

Also, a `Path2D` and a `PathFollow2D` would give you more flexibility, since you could add more points to the paths and make them curvy easily. Just make the path cyclic and set the `loop` property of the PathFollow2D to `true` and your object will move back and forth.

The object that you want to move has to be a child node of `PathFollow2D` which has to be a child of `Path2D`.

```
extends Path2D

var speed = 500

func _ready():
    set_physics_process(true)
    $PathFollow2D.offset = 200  # Change the initial offset.

func _physics_process(delta):
    # Change the offset or unit_offset to move the PathFollow and its children.
    $PathFollow2D.offset += speed * delta

```

To change the `offset` you can also use a Tween node.
> 2 votes

---
Tags: 2d, physics, movement, platformer, godot
---


# Question
Title: How to split sprites into multiple pieces, like in image below
Or how it should be called? I will change color programmatically. Sorry for my English.

# Answer
As far as I understand you, you want to split your colored image into several black–white images, of which each indicates the pixels of one specific color. And that in an automated fashion.

As TomTsagk already commented, you might just use an image manipulation program. For instance, I know that GIMP has a scripting facility where you can write scripts to automated image processing. Or you use more specialized tools like `convert` as part of ImageMagick, which is included in many Linux distributions. For example, the following command creates a black–white image `out.png` which highlights the color with the hex triplet `#abcdef` from the image `in.png`:

```
convert "in.png" -fill black +opaque "#abcdef" -fill white -opaque "#abcdef" "out.png"

```

---

If you want instead to create these images at runtime, you can write a simple function given that you can access the pixels of your image like an array. In this case, you might just allocate a second array for your output image, and use something like the following C++ code to generate the black–white image:

```
void highlight(Color theColor, Color* in, Color* out, size_t size) {
  for (int i = 0; i < size; i++) {
    if (in[i] == theColor) {
      out[i] = Color::White;
    } else {
      out[i] = Color::Black;
    }
  }
}

```

---

Finally, if you just want to use this in an (e.g. OpenGL) shader to alternate your output, (e.g. draw all but the specified color) you might use something like the following GLSL Fragment Shader code:

```
uniform sampler2D image; // The input image
uniform vec3 theColor;   // The color to highligh/discard, given as RGB color vector
in vec2 tc;              // The texture coordinate calculated in the Vertex shader
out vec4 outColor;       // The output color of this Fragment shader

void main() {
  vec3 color = texture(image, textureCoordinate).rgb;
  if (color == theColor) {
    discard; // Do not output anything
  } else {
    outColor = color; // output the color from the image
  }
}

```
> 1 votes

---
Tags: sprites, spritesheet
---


# Question
Title: moving object while being snapped to another one lwjgl
hi now I want to move an object(cube) while being snapped to the surface of another one (sphere) with the same surface of the cube how can i achieve this in lwjgl here is a diagram. to describe my point  thanks in advance ☺

# Answer
> 0 votes
This problem of course requires a logical system and algorithm. Since I do not know a lot about your Game Engine I can give you only a small glance of a solution.

At first you need the Surface of the Object A the Object B should stick to. If your Object A is like a terrain (in form of a grid) you can get the current 3 nearest vertices to Object B and "interpolate" between them. To do that you can use a barry centric method. I have this one in my Tools class:

```
public static float barryCentric(Vector3f p1, Vector3f p2, Vector3f p3, Vector2f pos) {
    float d = (p2.z - p3.z) * (p1.x - p3.x) + (p3.x - p2.x) * (p1.z - p3.z);
    float l1 = ((p2.z - p3.z) * (pos.x - p3.x) + (p3.x - p2.x) * (pos.y - p3.z))/d;
    float l2 = ((p3.z - p1.z) * (pos.x - p3.x) + (p1.x - p3.x) * (pos.y - p3.z))/d;
    float l3 = 1.0f - l1 - l2;
return l1 * p1.y + l2 * p2.y + l3 * p3.y;

```

p1, p2 and p3 are the positions of the vertices. pos is the x and z coordinate of the "sticking point" of your Object B. It then returns the y coordinate to make your object stick.

If your object is unfortunaly not always under the player (so that the player like in your diagram must "stick" to it even sideways) you need a more complex algorythm.

You could rotate both objects so that Object B is above Object A (

```
pseudo-code:
if B is left of surface of A
rotate both 90 degree around center of A
if B is under surface of A
rotate both 180 degree around center of A
...

```

) adjust the y coordinate of A with the barry centric method and rotate them back. This is just one simple solutions, perhaps there a dozen better or simpler solutions, so just try whats in your mind.

I hope i have helped at least a little bit :) Sorry for my english, its late

---
Tags: java, lwjgl, lwjgl3
---


# Question
Title: Rigidbody slows down when its going up a slope. What can I do?
I am using unity and I am creating a 3d topdown game. There is no jump feature. The input handling supports only x and z axis player movement. Climbing slopes or falling from gaps is something I want to happen without certain input.

So, I have a rigidbody which I move by directly setting its velocity. When it goes up a slope it slows down.

I would like it to keep the same speed.

Now I do it like this:

```
    void Update(){
moveInput = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
}

void FixedUpdate(){

MyRB.velocity = moveInput.normalized * runSpeed
}

```

I am using a capsule collider on the rigidbody and a box collider for the slope. The physics materials of the colliders are the default/none (not changed).

# Answer
It entirely depends on how you're moving your rigidbody. If you're manually updating the position each frame (using Translate or movePosition, not AddForce), you can apply a physics material to your sphere collider and set the friction somewhere at or slightly below 1. This allows your rigidbody to grip the sloped surface a bit better.
> 0 votes

---
Tags: unity, rigidbody
---


# Question
Title: Why is my spherecast returning an incorrect hit on mesh collider?
I have a mesh collider that is largely a flat plane facing up. Any SphereCast against that surface should return a normal of Vector3(0, 1, 0), but that isn't always happening. When near an edge on the mesh, the cast will penetrate the face and register the hit against the edge as if it was a corner when it's really just a polygon edge on a flat surface This is giving me inaccurate hit points and normals.

Hopefully the image above is interpretable. The light blue circle is where the SphereCast should stop and the pink circle is where it seems to be stopping. Instead of hitting the face (horizontal black line) and returning the proper normal (green line), it's ignoring the face and hitting the tri's edge (diagonal black line) and returning a lerped normal (red line) as if it were a corner.

Is the SphereCast that inaccurate against mesh colliders, or am I doing something wrong? Is there anything I can do to fix this?

---

Edit: I've added a screenshot to illustrate exactly what's happening. The black line/sphere are the cast, the green line is what the normal should be, the red line is the normal the SphereCast is returning. The normals differ by as much as 0.05m. The mesh is the default plane mesh. It seems like when the cast hits near a polygon edge, it snaps to the edge, giving an incorrect hit point and normal.

# Answer
Interesting to see what does `Physics.SphereCastAll` returns and see weather intersection (green vector) with horizontal line (horizontal black line) is detected at all.

Results shall be like as shown bellow

But when sphere is touching/overlapping surfaces result will be like

This is because:

> For colliders that overlap the sphere at the start of the sweep, RaycastHit.normal is set opposite to the direction of the sweep, RaycastHit.distance is set to zero, and the zero vector gets returned in RaycastHit.point. You might want to check whether this is the case in your particular query and perform additional queries to refine the result. Passing a zero radius results in undefined output and doesn't always behave the same as Physics.Raycast.
> 1 votes

---
Tags: unity, collision-detection, 3d-meshes, raycasting, normals
---