# Question
Title: GenerateProjectFile error Referenced directory [...] does not exist
I am following this tutorial to install Unreal Engine 4.22 from GitHub on Windows. I forked the project and cloned it on my computer. I've executed `Setup.bat` and everything went fine, but when I execute `GenerateProjectFiles.bat` I get all these errors:

```
PS D:\software\UnrealEngine> .\GenerateProjectFiles.bat
Setting up Unreal Engine 4 project files...
Binding IntelliSense data...
D:\software\UnrealEngine\Engine\Source\ThirdParty\IntelTBB\IntelTBB.Build.cs: warning: Referenced directory 'D:\software\UnrealEngine\Engine\Source\ThirdParty\IntelTBB\IntelTBB-4.4u3\Include' does not exist.
D:\software\UnrealEngine\Engine\Source\ThirdParty\DirectShow\DirectShow.Build.cs: warning: Referenced directory 'D:\software\UnrealEngine\Engine\Source\ThirdParty\DirectShow\DirectShow-1.0.0\Lib\Win64\vs2015' does not exist.
D:\software\UnrealEngine\Engine\Source\ThirdParty\Ogg\UEOgg.Build.cs: warning: Referenced directory 'D:\software\UnrealEngine\Engine\Source\ThirdParty\Ogg\libogg-1.2.2\lib\Win64\VS2015' does not exist.
D:\software\UnrealEngine\Engine\Source\ThirdParty\Vorbis\Vorbis.Build.cs: warning: Referenced directory 'D:\software\UnrealEngine\Engine\Source\ThirdParty\Vorbis\libvorbis-1.3.2\Lib\win64\VS2015' does not exist.
D:\software\UnrealEngine\Engine\Source\ThirdParty\Vorbis\VorbisFile.Build.cs: warning: Referenced directory 'D:\software\UnrealEngine\Engine\Source\ThirdParty\Vorbis\libvorbis-1.3.2\Lib\win64\VS2015' does not exist.
D:\software\UnrealEngine\Engine\Source\ThirdParty\OpenSSL\OpenSSL.Build.cs: warning: Referenced directory 'D:\software\UnrealEngine\Engine\Source\ThirdParty\OpenSSL\1.1.1\include\Win64\VS2015' does not exist.
D:\software\UnrealEngine\Engine\Source\ThirdParty\OpenSSL\OpenSSL.Build.cs: warning: Referenced directory 'D:\software\UnrealEngine\Engine\Source\ThirdParty\OpenSSL\1.1.1\lib\Win64\VS2015\Release' does not exist.
D:\software\UnrealEngine\Engine\Source\ThirdParty\Kiss_FFT\Kiss_FFT.Build.cs: warning: Referenced directory 'D:\software\UnrealEngine\Engine\Source\ThirdParty\Kiss_FFT\kiss_fft129\lib\x64\VS2015\Release' does not exist.
D:\software\UnrealEngine\Engine\Source\ThirdParty\VHACD\VHACD.Build.cs: warning: Referenced directory 'D:\software\UnrealEngine\Engine\Source\ThirdParty\VHACD\lib\Win64\VS2015' does not exist.
D:\software\UnrealEngine\Engine\Plugins\Experimental\ProxyLODPlugin\Source\ThirdParty\OpenVDB.Build.cs: warning: Referenced directory 'D:\software\UnrealEngine\Engine\Source\ThirdParty\IntelTBB\IntelTBB-4.4u3\include' does not exist.
D:\software\UnrealEngine\Engine\Source\ThirdParty\Qualcomm\TextureConverter\QualcommTextureConverter.build.cs: warning: Referenced directory 'D:\software\UnrealEngine\Engine\Source\ThirdParty\Qualcomm\TextureConverter\Lib\vs2015\x64' does not exist.
Binding IntelliSense data... 0%ImportError: No module named site
Python SDK not found
D:\software\UnrealEngine\Engine\Plugins\Runtime\LeapMotion\Source\LeapMotion\LeapMotion.Build.cs: warning: Referenced directory 'D:\software\UnrealEngine\Engine\Source\ThirdParty\Leap\Include' does not exist.
D:\software\UnrealEngine\Engine\Plugins\Runtime\nDisplay\Source\DisplayCluster\DisplayCluster.Build.cs: warning: Referenced directory 'D:\software\UnrealEngine\Engine\Plugins\Runtime\nDisplay\ThirdParty\VRPN\Include' does not exist.
Binding IntelliSense data... 100%
Writing project files... 100%
PS D:\software\UnrealEngine>

```

At the end of this command it creates a UE4.sln (but no UE4.v12.suo file) but when I try to compile the project on Visual Studio 2019 I get plenty of errors that are quite reminiscent of the ones above, so I assume the problem comes from the generation of the project files.

How can I fix this problem?

Thank you for your help.

# Answer
> 1 votes
Python3 needs to be installed and add `python.exe` to Environment Variables of OS.

---
Tags: unreal-4, installer
---


# Question
Title: How do I access a struct that resides within a struct in blueprints?
I have a struct: "`FOuterStruct`"

This is defined in code such that it contains another struct type:

```
Struct OuterStruct
{
    UPROPERTY(...)
        FInnerStruct memberStruct;
}

```

Now.

When I break an `FOuterStruct` apart within blueprints, I do not get the `FInnerStruct` as a pin on the resultant node.

How am I to edit/access this `FInnerStruct`?

# Answer
You can try like this.
Define Struct:

```
USTRUCT(BlueprintType)
struct MYRROJ_API FMyStruct
{
    GENERATED_USTRUCT_BODY()

    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Test")
        int32 Test;

    FMyStruct()
    {

    }
};

```

Usage:

```
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly)
    FMyStruct Test;

```
> 2 votes

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


# Question
Title: Unity "Text Mesh Pro UGUI" component rewrites my text! Make it stop?
I'm having this terribly annoying problem where my text is being overwritten by Unity. This Happens regardless of whether I am using tags or not.

Here is what I want to appear (more or less, I don't think this example is using the tag):

And here is what happens when I try to include a monospace tag:

Since you might not see it here, the text I inputed is

```
<mspace=64px>A</mspace>

```

This works FINE for regular TMP objects, which the other 3 are (and are using). I am trying to implement dropdown (and left, and up, and right) menus.

You can see that Unity overwrites it as "Option A", like it has a clue what I'm doing. What can I do?

# Answer
This has nothing to do with the tag that you are using.

For dropdown fields, the text of the label is overwritten by the dropdown component based on the selected option. In order to set the text of that label, you should go to the dropdown component and set the text of the selected option (Option A) like so:

Or unlink the Label from the dropdown component, but it is likely that you want it to be linked sinse you are using the DropDown component for a reason I suppose.
> 1 votes

---
Tags: unity, gui, text, ui-design, game-component
---


title: SpriteRenderer not Rendering Sprite

text:
# Question
Title: SpriteRenderer not Rendering Sprite
Edit: I've slightly edited this question because I've found the symptom for my problem, but not why the actions I've noticed cause the issue.

I have what appears (via the inspector) to be two identical 2D objects containing only a transform and a Sprite Renderer.

One was created by dragging a png from a folder onto the screen, and it displays normally.

The other was created by going to the hierarchy and right click \> 2D Object \> Sprite, and dragging the desired picture into the object's 'Sprite' Field.

Both objects appear in the development view, but only the first one appears in the game view. Why does the second object not appear?

All other settings for Unity (environment, camera, etc) are the default for a 2D project.

Here are the inspectors for...

The sprite that is displaying:

The sprite that is not displaying:

And my Camera:

# Answer
From what I see of the values you're using, it appears that `New Sprite` object is actually **BEHIND** and not aligned with the camera. So the camera can't see it, and display it. It'd explain why you can see it in the Scene view but not in the Game view.
> 1 votes

---
Tags: unity, 2d
---


# Question
Title: Unity 2D Rotating Cannon to Mouse Position Inaccuracy Issue
I am trying to rotate a 2D cannon to clicked mouse position and having accuracy issue. It's working but the angle seems to be losing more and more accuracy when I move the mouse to further up or down position.

Here's my code,

```
void Update()
{
        if (Input.GetMouseButtonDown(0))
        {
                // display a test cannon ball on mouse location
                Vector2 BallPos = MainCam.ScreenToWorldPoint(Input.mousePosition);
                TestBall.transform.position = BallPos;

                var p2 = MainCam.ScreenToViewportPoint(Input.mousePosition);
                var p1 = MainCam.WorldToViewportPoint(Cannon.transform.position);
                var p3 = p2 - p1;

                var angle = Mathf.Atan2(p3.y, p3.x) * Mathf.Rad2Deg;
                RotAngle = Quaternion.AngleAxis(angle, Vector3.forward);
                Cannon.transform.rotation = RotAngle;
        }
}

```

And attached screenshot below,

# Answer
From what I understand the fact to compute your angle on Viewport space messes everything up due to origins. If you do your computation on Screen space everything will work just fine.

Update your code with this:

```
            var p2 = Input.mousePosition + Vector3.forward * transform.position.z;
            var p1 = Camera.main.WorldToScreenPoint(transform.position);

```
> 1 votes

---
Tags: unity, 2d, rotation
---


# Question
Title: How to import camera from Blender into Unity3D
I have a few cameras in Blender to export to Unity3D. They're exported as empty `GameObject`s, and that's what is expected. The idea is to have the main camera be a child of one of the camera empty `GameObject`s.

In Blender, for the world, +Y is forward, +Z is up. But the camera is -Z is forward, +Y is up. In Blender, I have to set the camera's rotation to (90, 0, 0) just to have the camera not face down. But it the camera doesn't face the same direction as the camera in Blender.

I tried rotating the camera game objects by Y+180 so that the camera faces +Z, parent the camera `GameObject`, then zero out its position and rotation.

**How can I have a 1:1 export from Blender to Unity3D for camera objects?**

**Edit**: I am exporting FBX binary 7.4 files.

**Edit**: Here is a table:

```
 Blender RotXYZ     Unity global RotXYZ    Expected rotation
( 0,  0,  0)        (  0, -90,  90)        ( 90,   0,   0)
(90,  0,  0)        (  0, -90,   0)        (  0,   0,   0)
( 0, 90,  0)        ( 90, 180,   0)        (  0, -90, -90)
( 0,  0, 90)        (  0, 180,  90)        ( 90, -90,   0)

```

If I input any of the `Blender RotXYZ` values into Blender's camera rotation, export the FBX, I get the corresponding value in the `Unity global RotXYZ` column. But `Expected rotation` is what it should be.

**Edit**: Here is a poorly drawn image of what I'm seeing when I export from Blender to Unity.

**Edit**: I'm seeing inside `fbx_utils.py` (FBX exporter) that the camera gets rotated to have +X be the camera's forward direction.

# Answer
> 2 votes
Blender is a right handed coordinate system but you can export .obj and .fbx with whatever "up" vector you want. Selecting Y+ as your Up vector when you export your .fbx files should result in the orientation you're looking for.

Link to a more detailed post about the blender coordinate system on the blender stack exchange

# Answer
> 0 votes
Okay! I figured it out.

In Blender's FBX exporter, set options *Up=Z*, *Forward=Y*.

```
M = Matrix.Rotation(math.pi / 2.0, 4, 'Y')
R = Matrix.Rotation(math.pi, 4, 'Z')
obj.matrix_local = (R * obj.matrix_local) * M.inverted()

```

Rotate the camera around the Z-axis by 180 degrees (matrix `R`). Since Blender's FBX exporter rotates the camera so that +X is the camera's forward direction, we need to apply the inverse of that rotation (matrix `M`) so that it's canceled out on export.

On Unity's side, rotate the empty game object by -90 degrees on the X-axis, then 180 degrees on the Y axis.

The only problem I'm having now is Blender not taking into account the changes made to `matrix_local` before exporting.

# Answer
> 0 votes
Export fbx from blender with scale 0.08. Make sure to export the camera only. Import your fbx asset in your Unity project. You have to add an animator to the camera. Editing the animator, you drag and drop your motion fbx. Press DEL to remove the first of the two animations. Magically your camera is responding your animation.

---
Tags: unity, camera, blender, quaternion, export
---


# Question
Title: How to setup a public github unity repo with paid assets?
From what I gathered (like in this thread or here) I am allowed to push my own game code on github and choose a license, as long as I avoid putting assets I do not own. I want to make it public to be able to show it (to potential employers for instance) but I cannot make it open source as I plan to use paid assets (like DoozyUI).

I can avoid pushing the asset itself on the repo (with .gitignore for instance). **Should I prevent gameobjects created with this package to be pushed as well ?** That would make the game unusable, even with the rights to use the package...

Once that is settled, **Is it ok to push it to github without license ?**

Specifically, I do not know if objects generated by a paid asset are still considered that asset or not...

**Edit:** I asked the question directly to DoozyUI support, which quickly responded :

> You can upload your project, without the Doozy folder. Thus excluding our source code from being shared. Also, unsert a disclaimer letting anyone know that DoozyUI is required to be installed (before getting your files) for the project to work.
> **You can share any GameObject (or prefabs) you create**, but they will not work if DoozyUI is not installed due to missing references (scripts). Once Doozy is installed, they will work as expected. Thus anyone who has the system will be able to see/use your project.

# Answer
i already answered this question here: How can I open source my Unity project when I use third party assets?

you cant publish your project except you exclude those paid assets out of your project.
> 3 votes

---
Tags: unity, licensing, open-source, git
---


# Question
Title: Unity - Level complete progress bar stops at 75%
I am trying to build a progress bar that indicates the completion of the current level from 0 to 100% (or from 0 to 1 in probability). I found this example:

https://stackoverflow.com/questions/34960494/distance-from-start-point-to-end-point-in-percentage-in-update

It works, but my progress bar stops at about 75% when i reach the target position and then it drops down. This is my code:

```
public GameObject player;
public GameObject target;
public Text scoreText;

private float startDistance;
private float currentDistance;

private void Start()
{
    this.startDistance = Vector3.Distance(player.transform.position, target.transform.position);
}

private void Update()
{
    this.currentDistance = Vector3.Distance(player.transform.position, target.transform.position);
    float percentage = 1 - (currentDistance / startDistance);
    transform.localScale = new Vector3(percentage, 1f, 1f);

    this.scoreText.text = string.Format("Score: {0}%", Mathf.Round(percentage * 100f));
    Debug.Log("Percentage Completed: " + (percentage));
}

```

The player moves by himself towards the target position at constant speed without acceleration. The player can move its character left or right in order to avoid obstacles. This doesn't change the player's speed, it just maneuvers the direction. Maneuvering, I realized the progress sometimes goes beyond 75% and sometimes below. Why is this happening? How to make the progress simply reach 100% when I reach the target position?

# Answer
> 0 votes
My target element was an empty game object that had children of cubes where the progress went to around 75% and stopped. Then I created a cube that had children of cubes and the progress worked fine. I don't know why is this the case but seems like an empty game object and a cube react differently.

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


# Question
Title: How do I avoid "too" lucky / unlucky streaks in random number generation?
I'm currently dealing with a multiplayer combat system where the damage dealt by the players is always multiplied by a random factor between 0.8 and 1.2.

In theory, a truly random RNG may eventually yield the same number many times (see the Tetris dilemma). This could result in a match where player is *always* making very high damage while the other always makes very low damage.

What can I do to make sure this doesn't happen? Are some RNGs better than others at avoiding repetition?

# Answer
> 27 votes
You can solve it the same way Tetris does, by making a preset list of damage results and shuffling.

Let's say you know the player is going to deal 0.8x to 1.2x damage with a linear distribution. Take the list \[0.8, 0.9, 1.0, 1.1, 1.2\]. Shuffle it randomly, so you get e.g. \[1.2, 1.0, 0.8, 0.9, 1.1\].

The first time the player deals damage, they deal 1.2x. Then 1x. Then, etc, to 1.1x. *Only when the array is empty* should you generate and shuffle a new array.

In practice, you'll probably want do this to 4+ arrays at once (e.g. start with \[0.8,0.8,0.8,0.8,0.9,0.9,0.9,0.9,...\]). Otherwise the period of the sequence is low enough that players can figure out whether their next hit is "good" or not. (Although that can also add more strategy to the combat, as in Dragon Quest IX's Hoimi table, which people figured out how to probe by looking at healing numbers and tweak until you're guaranteed a rare drop.)

# Answer
> 5 votes
I actually wrote some code to do this. The gist of it is using statistics to correct unlucky streaks. The way you can do this is to keep track of how many times the event has occurred and use that to bias the number generated by the PRNG.

Firstly, how do we keep track of the percentage of events? The naive way of doing this would be to keep all numbers ever generated in memory and average them out: which would work but is horribly inefficient. After a little thinking I came up with the following (which is basically a cumulative moving average).

Take the following PRNG samples (where we proc if the sample is \>= 0.5):

```
Values: 0.1, 0.5, 0.9, 0.4, 0.8
Events: 0  , 1  , 1  , 0  , 1
Percentage: 60%

```

Notice that each value contributes to 1/5 of the final result. Let's look at it another way:

```
Values: 0.1, 0.5
Events: 0  , 1

```

Notice that the `0` contributes to 50% of the value and the `1` contributes 50% of the value. Taken slightly further:

```
Values: [0.1, 0.5], 0.9
Events: [0  , 1  ], 1

```

Now the first values contribute 66% of the value and the last 33%. We can basically distil this down to the following process:

```
result = // 0 or 1 depending on the result of the event that was just generated
new_samples = samples + 1

average = (average * samples / new_samples) + (result * 1 / new_samples)
// Essentially:
average = (average * samples / new_samples) + (result / new_samples)

// You might want to limit this to, say, 100.
// Leaving it to carry on increasing can lead to unfairness
// if the game draws on forever.
samples = new_samples

```

Now we need to bias the result of the value sampled from the PRNG, because we are going for a percentage chance here things are a lot easier (versus, say, random amounts of damage in a RTS). This is going to be hard to explain because it 'just occurred to me'. If the average is lower it means that we need to increase the chance of the event occurring and visa-versa. So some examples

```
average = 0.1
desired = 0.5
corrected_chance = 83%

average = 0.2
desired = 0.5
corrected_chance = 71%

average = 0.5
desired = 0.5
corrected_change = 50%

```

Now what 'occurred to me' is that in the first example 83% was just "0.5 out of 0.6" (in other words "0.5 out of 0.5 plus 0.1"). In random event terms that means either:

```
procced = (sample * 0.6) > 0.1
// or
procced = (sample * 0.6) <= 0.5

```

So in order to generate an event you would basically use the following code:

```
total = average + desired
sample = rng_sample() * total // where the RNG provides a value between 0 and 1
procced = sample <= desired

```

And therefore you get the code that I put in the gist. I am pretty sure this all can be used in the random damage case scenario, but I haven't taken the time to figure that out.

*Disclaimer:* This is all home-grown statistics, I have no education in the field. My unit tests do pass though.

# Answer
> 3 votes
What you are asking for is actually the opposite of most PRNGs, a non-linear distribution. Just put in some kind of diminishing returns logic in your rules, Assuming that everything over 1.0x is a "critical hit" of some kind, just say that each round your chances of getting a crit go up by X, until you get one at which point they reset to Y. You then do two rolls each round, one to determine crit or not, and then another for the actual magnitude.

# Answer
> 2 votes
Sid Meier had an excellent speech on GDC 2010 just about this topic and Civilization games. Link. In essence - perceived randomness is not the same as true randomness. To make things feel fair you need to analyze previous results and pay attention to players psychology.

Avoid streaks of bad luck at all costs (if previous two turns were unlucky next one should be guaranteed to be lucky). Player should be always luckier than AI opponent.

# Answer
> 0 votes
# Use a shifting bias

The base generator uses a uniform distribution between \\$0\\$ and \\$1\\$ to generate \\$r\\$. Initially set a bias value, \\$b\\$, to \\$0\\$.

The overall distribution will be biased by the following formula:

\\$ r^{\exp (-b)} \\$

The effect here is that when \\$b\\$ is positive, the resulting number will be biased toward \\$1\\$. When \\$b\\$ is negative, the resulting number will be biased toward \\$0\\$.

Take this number and scale it appropriately to the desired range.

Each time a player rolls favorably, subtract from the bias. Each time the player rolls unfavorably, add to the bias. The amount changed could be scaled by how (un)favorable the roll is or could be a flat amount (or a combination). You will need to adjust specific values to fit the feel you are going for.

---
Tags: algorithm, multiplayer, random
---


# Question
Title: Move a ball horizontally left and right but restricting forwards and backwards motion unity 2d
I am trying to develop an endless runner where there is a sphere as the player and it is moving left and right following the position of a finger on a touch screen. However, when I try to do this I cannot get the player to lock on the Y-axis. I want a constant force that speeds up overtime which I have using the constant force 2d supplied by unity. I have two versions of code, the first follows the finger but the player is able to move up and down as well:

```
using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour
{
    public GameObject character;
    public float speed = 500.0f;

    void Start()
    {
        Input.multiTouchEnabled = false;
    }

    void Update()
    {
        if (Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Moved)
        {
            Vector2 target = Camera.main.ScreenToWorldPoint(
                              new Vector2(Input.mousePosition.x, Input.mousePosition.y));
            character.transform.Translate(Vector3.MoveTowards(character.transform.position,
                              target, speed * Time.deltaTime) - character.transform.position);
    }
}

```

The second code I have allows the player to move left and right by tapping rather than following but is still sloppy:

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

public class PlayerMovement : MonoBehaviour
{
    public Rigidbody2D rb;

    public float sidewaysForce = 500f;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        {
            foreach (Touch touch in Input.touches)
            {
                if (touch.position.x < Screen.width / 2)
                {
                    rb.velocity = new Vector2(sidewaysForce * -1, rb.velocity.y);
                }
                if (touch.position.x > Screen.width / 2)
                {
                    rb.velocity = new Vector2(sidewaysForce * +1, rb.velocity.y);
                }
            }
        }
    }
}

```

Any help on this would be awesome Thanks!!!

# Answer
in 2d horizon is X axis. for restriction you can simple put a restricting object or read borders of your camera.assume you have a minX and minY empty objects. so you will have:

```
    [SerializeField] private Transform minX;
    [SerializeField] private Transform maxX;
void Update()
{
  if (transform.position.x < minX.position.x) { transform.position = new Vector3(minX.position.x,transform.position.y,transform.position.z); }
  if (transform.position.x > maxX.position.x) { transform.position = new Vector3(maxX.position.x, transform.position.y, transform.position.z); }
}

```
> 0 votes

---
Tags: unity, movement
---


# Question
Title: Instantiate creates a clone in wrong position
I have this prefab with this transform:

And then using this code to create a clone (the prefab is assigned to a public property of a script, which I assign using the editor, which is the e.Weapon):

```
Instantiate(e.Weapon, new Vector3(0f, 0f, 0f), Quaternion.identity, rightHand.transform);

```

I am parenting it to my character's right hand. But whenever the clone gets created, it has different position than the one I have in my code. It appears like this:

Any idea why this is happening?

# Answer
First guess: It sounds like you have a parent gameObject and you instantiate it in world space \[0, 0, 0\]. Then your position would of course be something else than \[0, 0, 0\] because the inspector would show the local position to its parent, not world position. The Instantiate method has overloads with a Boolean for spawning objects in world position. However I'd assume the Instantiate method would use local space for the vector anyway, given that it allows you to assign a parent. Have a look into that.

Another guess: You set the position somewhere else by code upon Awake() or Start() of a script on the instantiated item. In this case look into all scripts attached to it.
> 2 votes

---
Tags: unity
---


title: Moving cars on a tiled map

text:
# Question
Title: Moving cars on a tiled map
I'm writing a game which is situated on a **tiled map**. I have a PlayState on which there's a Board which cosists of Fields.

My Board is an **isometric map** of a city, where each tile is a kind of road. Depending on the type of the road, there's a different texture of a car (if we go up/ down or left/ right) + on some tiles a car will take more than one texture (because it turns).

I don't know what's the correct idea of putting a car into the game. Should a class Car be part of Field? Probably not because there are moments in which the car is on **more than one field**. So maybe a part of Board? But the texture of a car **depends on the type of the road** that it is on. What is more, I must deal with the fact that once a car is on a field, it moves in the boundaries of it - so should I insert some **coordinates of a field** itself?

Could someone write a pseudocode of classes Board and Field with the necessary variables? And explain how I should deal with car's movements? I'm working in Java's Libgdx if it matters.

# Answer
> 0 votes
Firstly, I believe that there are some conditions needed for the car to appear on the field, and also i assume that you will want to have more than one car in the future.

I believe it's a bad idea to put all logic into the field objects, the only reason to do so would be performance reasons. But since you have a clear separation of concerns in your case, I would make a Car class containing the cars logic: reference to the Field object that the car is visible at, coordinates within this field, direction the car is pointing towards (based on which you would change textures) etc. Store the cars in an array-like structure and on render just iterate over it, rendering cars whenever needed.

I would continue with this simple architecture while adding houses, dogs, cows and whatever else you would need to place on the board. If the performance matters, consider storing all of the references to the particular field in one data structure (dictionary of lists?), and then iterate only over Fields, checking this structure for each field to find all elements that the selected one relates to.

Note that I have no experience with making games in Java, and this is just a simple tip following the Keep-It-Single-Stupid rule.

# Answer
> 0 votes
I am not going to write the pseudo code for you, but I can tell you what I would have done creating the game.

Keep the `Car` and the `Field` as different classes. The `Field` can have zero or more instances of a `Car`. Either use an Array of cars, or a map of cars, where the carId is the key. It is totally up to you.

If the texture of the car is field dependent, you can simply have a method in your `Car`-object, e.g `setTexture()`, and the `Field` can call that method on all the cars in its array (or map). The car itself can change the texture based on a direction-property. If the car is moving up, left, right or down, set the direction, and render the correct texture.

I would still use x, and y coordinates to defined your map, in a traditional 2D-way, no isometric thinking here, you can just transform all the points to fit the isometric grid in rendering. If you think about it, an isometric grid is just a 2D-grid. Here is an article I stumbled upon while looking around on the internet, that might be useful: https://gamedevelopment.tutsplus.com/tutorials/creating-isometric-worlds-a-primer-for-game-developers--gamedev-6511. Here is a picture from the same article

---
Tags: libgdx, architecture, isometric
---


# Question
Title: I want to clamp each instance of the same prefab to the y axis only
I instantiated the prefab "paddle" twice then I tried clamping it to the y-axis only; using Mathf.Clamp, however, the min and max values end up being applied to both instances of "paddle" and hence they can move in the x-axis

ok so I'm trying to make a 2d mobile pong game, I have a prefab "paddle" which are the rackets/bats which the balls collide with.

I instantiated the same prefab twice one on each side of the screen :

```
Paddle paddle1 = Instantiate(Paddle) as Paddle;
Paddle paddle2 = Instantiate(Paddle) as Paddle;
paddle2.Init(true); //right paddle
paddle1.Init(false); //left paddle

```

Now i want each of the paddles to only be able to move in the y axis (UP And DOWN).

So I tried clamping them with:

```
var poss = transform.position;
poss.x =  Mathf.Clamp(transform.position.x, -1.0f, 1.0f);
transform.position = poss;

```

However, this caused the left paddle to still be able to move to the right and the right paddle to be able to the left( I don't want them to move in the axis at all).

This is the file GameManager.cs:

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

public class GameManager: MonoBehaviour
{
    public Ball Ball;

    public Paddle Paddle;

    public static Vector2 topRight;
    public static Vector2 bottomLeft;

    // Start is called before the first frame update
    void Start()
    {
        bottomLeft = Camera.main.ScreenToWorldPoint(new Vector2 (0,0));
        topRight = Camera.main.ScreenToWorldPoint(new Vector2
        (Screen.width,Screen.height));

        Instantiate(Ball);

        //Paddle paddle1 = Instantiate(Paddle) as Paddle;
        Paddle paddle1 = Instantiate(Paddle) as Paddle;
        Paddle paddle2 = Instantiate(Paddle) as Paddle;
        paddle2.Init(true); //right paddle
        paddle1.Init(false); //left paddle
    }

    void Update()
    {

    }

}

```

This is the file paddle.cs:

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

public class Paddle : MonoBehaviour
{
    Rigidbody2D rb;
    float directionY;
    float speed;
    float height;

    float distance;
    string input;
    bool isRight;

    // Start is called before the first frame update
    void Start()
    {
        height = transform.localScale.y;
        speed=5f;
    }

    public void Init(bool isRightPaddle)
    {
        isRight = isRightPaddle;
        Vector2 pos = Vector2.zero;

        if(isRightPaddle)
        {
            //Place paddle on the right of the screen
            pos = new Vector2(GameManager.topRight.x, 0);
            pos -= Vector2.right * transform.localScale.x; //Move a bit to the left
        }
        else
        {
            //Place paddle on the left of the screen
            pos = new Vector2(GameManager.bottomLeft.x, 0);
            pos += Vector2.right * transform.localScale.x; //Move a bit to the right
        }

        //Update this paddle's position
        transform.position = pos;
    }

    void Update()
    {
        var poss = transform.position;
        poss.x =  Mathf.Clamp(transform.position.x, -8.0f, 8.0f);
        transform.position = poss;
    }
}

```

I expect each paddle to not be able to move in the x axis. Only in the y axis

c# unity3d mobile

# Answer
> 1 votes
TL;DR: you are updating the x position value while you want to update the y value.

Please have a look at this part of your code:

```
        var poss = transform.position;
        poss.x =  Mathf.Clamp(transform.position.x, -8.0f, 8.0f);
        transform.position = poss;

```

What you're doing here is telling Unity:

> At every frame, (line 1) I want you to get the position of my transform, (line 2) update and clamp the x value of my position to be contained between -8.0 and 8.0 but don't touch any other values, (line 3) set the position with the clamped x value as the new position of my transform.

This code will let your paddle moving on x (left / right) from -8.0 to 8.0 values. In Unity, by default, left/right axis is x, up/down is y, and forward/back is z. If you want your paddle to only move on Y when you press up and down arrow, you just have to only update the Y value of their `transform.position` and clamp it to the min / max values you need while forcing the default x and z values that you need.

---
Tags: unity, 2d, mobile
---


# Question
Title: Unreal MouseWheelAxis negative axis does not work
Would like to avoid using separate action mappings i.e. `MouseWheelUp` and `MouseWheelDown` for a system I'm developing.

I noticed `MouseWheelAxis` and put that as my axis event. This only works on the forward movement of the mouse wheel, and not on the backwards, as stated. (presumably because the scale is set to +1.0)

Why?

And how can I get around this?

# Answer
> 1 votes
It's not possible to assign the mouse wheel scrolling action to a regular axis mapping as you would do with two different keys.

The only option available is using MouseWheelUp to scale +1.0 (or what you need) and MouseWheelDown to scale -1.0.

This is by design and is not considered a bug.

---

Edit based on my own tests and from new comments.

I'm not sure why you're only seeing result when the wheel moves forward.

I went into the input settings and added a new axis event based on mouse wheel axis:

Then went into the level blueprint and set up a simple chain for getting to a print string:

And finally, ran the program, scrolling the mouse wheel back and forth:

As you can see, I'm getting 1.0 and -1.0 results so can't say why you're not seeing the same.

Please note that I'm using engine version 4.22 for this. Based on previous research, I didn't think this was possible so it may be a new feature added on a later version of the engine.

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


# Question
Title: Unreal Engine: Object Reference is not compatible with pawn Object Reference
Hello I am a beginner Unreal Engine developer learning with Blueprint and I am trying to take an imported FBX model and put a pawn control on it. Below is what I am trying to do. By the way, FbxScene\_Test\_Character is an actor.

What can I do to get around this error? Do I need to add extra information?

# Answer
> 2 votes
You can only `Possess` a `Pawn`, and `FbxScene_Test_Character` isn't one (it's probably a skeletal mesh actor).

Place a pawn subclass (such as `ACharacter`) in your scene, and in the properties for that character, assign the imported skeletal mesh. You can then use the placed character actor as an input for the `Possess` node.

See "Setting up a Character" for more details.

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


title: WoW attack speed calculation

text:
# Question
Title: WoW attack speed calculation
Reading up on attack speed calculations for World of Warcraft I noticed that the formula for attack speed is:

> Attack\_speed = "current attack speed" / (("Percent increase or decrease" / 100) + 1 )

So with a weapon of speed 1.8 and activating a 40% attack speed buff for example we would have:

> Attack\_speed = 1.8 / ( (40 / 100) + 1 ) = 1.2857

So I am just wondering why is there a +1 in the formula. Logically I would assume that one would calculate the attack speed like this:

> Attack\_speed = 1.8 - (1.8 * (40 / 100)) = 1.08

Which is just subtracting the 40% of 1.8 from 1.8, which is how one would normally calculate a percentage in math. Is this just by design or is there some logic to this?

# Answer
Let's look at your particular suggestion for a formula and what range of values it is able to handle:

```
attack_speed = 1.8 - (1.8 * (x / 100))

```

What if x is larger than 100? Now you have a *negative attack speed*. What is that even supposed to mean mechanics-wise?

Adding a 1 when calculating a divisor ensures that the division will always reduce the value and never increase it.

Without the +1, the divisor could in some cases be between 0.0 and 1.0. If you divide by a number in that range, the value increases. But the designer who came up with the attack speed modification mechanic likely intended it to only ever reduce attack speed and never increase it. So the +1 is added to avoid this edge-case.

Only under the premise, of course, that the rest of the term can not be negative. However, that edge-case is easy to rule out by introducing the general rule that "No stat can ever be negative". This is a constraint which is pretty easy to enforce, pretty easy to remember for anyone involved in the design and development process of the game and it also rules out a lot of other edge-cases which would otherwise require special handling.
> 8 votes

# Answer
The +1 is in there because `Attack_speed` is actually a cooldown stat, where half as much `Attack_speed` makes you attack twice as fast. If you have a "+100% increase" to your attack speed with the WoW formula, you get outputs like `Attack_speed = 1.8 / ( (100 / 100) + 1 ) = 0.9`. Similarly, if you have a "-99% decrease" to your attack speed with the WoW formula, you get outputs like `Attack_speed = 1.8 / ( (-99 / 100) + 1 ) = 180`, so you attack 100 times less often.

From a balance perspective, this means that stacking bonuses to attack speed linearly scales your total DPS: two +100% bonuses to attack speed only triple your DPS, whereas with your suggested formula one +50% bonus to attack speed would double your DPS, while adding another one would send it all the way to insanity.
> 2 votes

# Answer
I was not involved in the development of WoW, but reading the first formula, I'd say that they added 1 to prevent the case (that may happen a lot with very low level / unnequipped characters) of division by zero. If the "Percent increase or decrease" value is 0, you'll end up with "current attack speed" being divided by zero. In the "+1" version the only case that could give a division by zero would be to have a 100% decrease of speed (that would give `(-100/100)+1 = -1+1 = 0`).
> 1 votes

---
Tags: mathematics, game-mechanics
---


title: Random Zelda-style map generation

text:
# Question
Title: Random Zelda-style map generation
Im trying to randomly generate a map of rooms connected by doors, and I've succeeded in generating one using this code:

```
public void generate(GameContainer gc) {
        rooms = new ArrayList<Room>();
        startingRoom = new Room(0);
        startingRoom.setPosition(viewport.getCenterX(), viewport.getCenterY());
        lastRoom = startingRoom;
        rooms.add(startingRoom);
        int roomsize = 25;

        for (int i = 0; i <= (1000 + Math.random() * 4000); i++) {
            Room room = new Room(i + 1);
            int direction = (int) (Math.random() * (4));

            switch (direction) {
                case 0:
                    room.setPosition(lastRoom.x, lastRoom.y - roomsize);
                    break;
                case 1:
                    room.setPosition(lastRoom.x, lastRoom.y + roomsize);
                    break;
                case 2:
                    room.setPosition(lastRoom.x + roomsize, lastRoom.y);
                    break;
                case 3:
                    room.setPosition(lastRoom.x - roomsize, lastRoom.y);
                    break;
                default:
                    room.setPosition(lastRoom.x, lastRoom.y - roomsize);
                    break;
            }
            rooms.add(room);
            lastRoom = room;
        }
    }

```

However, this doesnt allow me to find out which doors the given room has. I need to be able to figure that out so that I can place the doors in the correct places so that they can be used to adjoin rooms. Is this sort of "smart map" possible with my current algorithm, or should I start over? What steps can I take to get this working?

I'm using Slick2d and Java for this

Thanks.

# Answer
> 1 votes
I think that this question is quite open-ended, since there are a few pieces of code you'll need before you can link the rooms properly and how you code that up depends a lot on how things make sense to you.

Having said that, I can make a few recommendations to help you go in the right direction.

First of all, if the room sizes are constant I'd recommend making a higher level coordinate system for the rooms. Something that would look like this:

```
 _____ _____ _____ _____ _____
|     |     |     |     |     |
|-2,-1|-1,-1| 0,-1| 1,-1| 2,-1|
|_____|_____|_____|_____|_____|
|     |     |     |     |     |
|-2,0 |-1,0 | 0,0 | 1,0 | 2,0 |
|_____|_____|_____|_____|_____|
|     |     |     |     |     |
|-2,1 |-1,1 | 0,1 | 1,1 | 2,1 |
|_____|_____|_____|_____|_____|

```

The idea being that when you're making room (0,0) you ask rooms (-1,0) (0,-1) (1,0) and (0,1) where the adjoining doors are. If you need screen coords, it should be easy enough to add a GetScreenCoords method or a transform matrix if you're into those.

Next you'll want to be able to query the list of rooms. Going through all of the rooms in your list (up to 5000!) just to find the neighbouring rooms will get costly. For a quick way to get things up and running, I'd recommend using a `HashMap<coord, Room> rooms` instead. This way when you're making room (0,0) you ask for existing neighbouring rooms you simply ask for `rooms.get((1,0))` etc. and to add your newly generated room at (0,0) you'd do `rooms.put((0,0), newroom)` If this becomes too slow, it might be worth looking at sorted lists. Perhaps a sorted list(x) of sorted lists(y).

Finally you'll need to add some way to get the door position from the neighbouring rooms. A new method like `int GetSouthDoor()` should do the trick.

I'm sure there will be a lot more work for you to code a full solution. I hope this will help you get started.

# Answer
> 2 votes
Two things:

1) In your comment, you say you want something like the Binding of Isaac. That game has doors in the middle of each piece, guaranteeing that they line up. If you follow suit, then it only comes down to deciding what kind of door to connect them with (open, locked, bowall, etc).

2) Your code appears to start at one location and procedurally generate new tiles off in one direction. In your switch statement, however, you're not accounting for the direction you're coming *from*. If you continue with that algorithm, consider keeping track of the last placement as well, so that the tiles don't overwrite each other.

# Answer
> 0 votes
# Use a maze generation algorithm

Use a modified form of Prim's Algorithm to create a basic maze of 20 rooms or so. Choose two rooms to be start and end rooms, ensuring the end is always reachable. Block off random doors with different door types and randomly add doors where two adjacent rooms are not connected (with low probability)

---
Tags: java, maps, random, procedural-generation
---


# Question
Title: apk is fine, but when building aab for google play submission google play services dont start when i download it
So I have a game on app store, I added Google play services

Now when I do an apk build and test it works great really happy with it.

But when I then tick the box for aab ( this is what Google store want uploaded ) it builds it, I upload it, it rolls out but the Google play stuff fails to work, leaderboard and sign in.

When I extract the apk on my Mac from the aab and install that it works great again.

What am I doing wrong? Is there a way to check logs of running app? On a device

I have tried

7 different versions of unity (currently on 2019.2.9f1) Changing the min version of Android API to 21 I exported it as a Gradle project and tried building it like that, again test great on device but play services fail when downloading it from the google play store.

It's using the IL2CPP scripting backend.

Any ideas at this stage are welcome

# Answer
so after you upload it, google resigns it and gives you a new cert to I had to take this and put it in my google play services API.
> 1 votes

---
Tags: unity, android, google-play-services, il2cpp
---


# Question
Title: Mesh Triangulation that is inside<->outside aware
am working on an algorithm for **procedural generation of 3D meshes** for caves in a side-scroller game.

The algorithm nicely computes contours and also points inside the caves that are supposed to be anchor points for the mesh. A sample for this can be seen in the following image:

The idea is that each of those anchor points has a distance to the view-pane depending on their distance to the contour. This way the caves have a roughly spherical shape in 3D.

This is also the reason I added those anchor points because having triangles from wall-to-wall would not enable me to have actual 3D caves.

---

However, the problem now is how to make the triangles. I found a nice implementation of the Delaunay triangulation algorithm. However that yields me the following mesh:

Obviously **this algorithm is not aware of what's inside my cave** and what is not and thus forms triangles completely outside of the caves. Pruning those outliers does not yield good results because then the contours of the caves are interrupted.

I have heard of "ear cut" algorithms that can work with concave shapes like my outlines. However those are not compatible with the anchor points I require.

**What I'd need is a triangulation algorithm that allows me either to add anchor points inside the figure, or that allows me to limit the maximal length of vertices thus computing anchor points on its own.**

Is such an algorithm known?

Huge thanks!

# Answer
You can compute the centroid of the triangles that make your mesh and cull them if they are outside your original boundary.

Reference
> 1 votes

# Answer
You have the solution in your last line "that allows me to limit the maximal length of vertices" If you have the code which is generating the good mesh, except for the outside zones, you can add a line to check triangle's size as it is written by the meshing code.

You can alternatively write a brief function which fetches your triangle point arrays, and checks every triangle size in the model. You can either rewrite a new mesh with new vertex indices, or you can go cheap, and resize triangles that are too big, so that all three points are the same point.

Triangles can occupy an infinitely small point in space, and it makes them invisible to the graphics card. you can rewrite the big ones small else erase and re-index them, either in the triangle checking stage of your meshing code, or in a mesh editing function afterwards. for a mesh of that size, it would take about 1 frame of time.
> 0 votes

---
Tags: mesh, triangulation, delaunay-triangulation
---


title: unity check color on collision Enter2d

text:
# Question
Title: unity check color on collision Enter2d
So I am trying to figure out how to check the color of my sprite on collision 2d. I change my colors of sprites like this:

```
Color newColor = new Color(0.68f, 0.63f, 0.76f);
                    m_spriteRenderer.color = newColor;

```

and on the other script I have the OnCollision2d Function:

```
private void OnCollisionEnter2D(Collision2D col)
    {
        Destroy(col.gameObject);
    }

```

acording to the color I want to delete the sprite or just add points.

Thanks,

# Answer
> 0 votes
Use this method in your monobehavior class:

```
void OnCollisionEnter(Collision other)
{
    //Colors are written as 4 normalized values: (Red,Green,Blue,Alpha)
    if (other.GetComponent<SpriteRenderer>().color == (1,0,0,1)) //alt: Color.red
    {
        Destroy(gameObject);
    {
}

```

Let me know if that doesn't do it for some reason. This IF statement should automatically return false (do nothing) if something with a collider hits the game object this script is attached to, but doesn't have a SpriteRenderer component in the first place.

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


# Question
Title: Do I need licenses to make 3D models of guns for my game?
I think a same question has been asked 2 years ago but I would like an answer for my specific situation.

I'm working on an indie project, which is a low-poly style FPS game and it contains several firearms modeled by myself. I'm considering to change and remove details from my guns so people can still recognize the weapon, while it is not exactly the same as the original one. I would name it something like "Combat Rifle", "Auto Pistol", etc.

Also, I'm not living in the US or Europe so is there any (international) legal action that could be taken against me?

# Answer
> 0 votes
Disclaimer: I'm **not** a lawyer.

If the guns you are making are "abstract enough" to not be a specific model, then you don't need any license. Guns are recognised internationally and not really tied to a specific company.

Having said that, it's worth being aware of some of the consequences of having guns in your game:

* Your game cannot target primarily children. In a lot of countries, anything made for children cannot have any reference to guns.
* Your game might get different rating on different countries, which might limit the number of people that can download it. Some countries have issues with violence in video games, and might even ban one that is too violent.

At the end of the day, you are making something for entertainment. Nobody will (realistically) sue you because you made a video game with guns. The worst that can happen is your game not being playable in some countries (depending on the amount of violence).

If you are too worried and you want your game to have as big market as possible, things you can do include:

* Make the guns be more "fantasy-like" so it's not easy to tie them with real life ones. Games like "Halo" has done that to some degree.
* Limit the amount of blood that is shown. Some games go as far as to show other graphical elements, like "dust" instead of blood. One example that comes to mind is "Tekken".

However rules of how to control the rating are not concrete. It's all about how a game feels when you play it.

---
Tags: licensing
---


# Question
Title: Unity: White outline around seams in my character, make it stop!
so once upon a time I made a really cool character for my game project and he looked great. Then at some unspecific point in time, my character's UV seams got these awful white outlines around them:

I assumed the problem was that during some texture revision, I didn't paint past the island seams, so I compared the texture file with an image of the UV output, but in fact I did paint past the seams, so that isn't the problem. I have heard that this may have something to do with antialiasing, but I don't want to turn that off if I can fix the problem another way. Also, notice that the enemy character in the above gif does not suffer from the same problem.

What could be causing this? How can I fix it?

# Answer
Lines around texture seems aren't usually caused by anti aliasing, since that's only doing multiple passes per fragment. If it isn't visible without anti aliasing, it won't be visible after either.

Texture problems are instead usually caused by mipmapping. It can make the seams a lot more imprecise.
> 3 votes

---
Tags: unity, textures, rendering, uv-mapping, image-processing
---


# Question
Title: How to get position of next object that closest to player,when player is move forward to nearest every time?
I have a scene that looks like the following picture:

The `Player` has a `RigidBody2D` and all the `step`s have a `BoxCollider2D`. All steps are tagged with a 'step' `tag`.

I would like to let the player move to the next `step`, every time the user `presses a key`. In this case, I'll need to get the `position` of the `next step` that is the closest to the player, every time the player moves to the next position.

I have tried the following so far:

```
using UnityEngine;
using System.Linq;

public class Box : MonoBehaviour
{
    //the rigidbody of the box
    private Rigidbody2D player2D;

    // Start is called before the first frame update
    void Start()
    {
        player2D = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Vector2 targetPosition = GetNextTargetTransform(player2D.position );

            //here set trajectory to move from current position to target position
            Vector2 trajectory = SetTrajectory(player2D, targetPosition);
            player2D.AddForce(trajectory, ForceMode2D.Impulse);

            //after reach the position update player position to current position
            //player2D.position = targetPosition;
        }
    }

    public Vector2 GetNextTargetTransform(Vector2 player2Dposition)
    {
        GameObject[] step = GameObject.FindGameObjectsWithTag("step");

        //here is the code to get the nearest object using LinQ
        var nearest = step.OrderBy(t => Vector2.Distance(player2Dposition, t.transform.position)).FirstOrDefault();

        Transform nearestPosition = nearest.transform;
        Vector2 targetPosition = new Vector2(nearestPosition.position.x, nearestPosition.position.y);

        return targetPosition;
    }
}

```

I am able to get the position of the first step when a button is pressed, but when I press the key again, I am unable to get the position of the next step (and thus remain on the first position).

I've added `player2D.position = targetPosition;` after `AddForce(...)` and the player will directly appear on the first step and move to the next one, which is not the result I want.

**Question**

How do I get the position of the nearest `step`, every time the player moves to a new step?

# Answer
At the beginning of your game you could create a list of Steps (it would contain either the transforms or the colliders of all the steps of the scene). Every time the player presses down, you run through your list of Steps and try to find the closest one (using `Vector3.Distance` between player position and step position, it should be easy to determine the closest one). The trick here is to save what Step you're one. So every time the player jumps on a new step you save it as the current step in a variable contained on your player. Now everytime you want to find the closest step you run through your list of step comparing the distance of the player and excluding the one you have saved.
> 1 votes

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


# Question
Title: Godot Animation only playing First Frame
I have tried checking if it is already playing, stopping animations before and putting it in a separate function. Whenever I jump it should play 4 Frames of my animated sprite. But it only plays first.

const FLOOR = Vector2(0,-1)
const SPEED = 500
const GRAVITY = 20
const JUMP = -600

func _physics_process(delta):
    pos.y += GRAVITY
    if Input.is_action_pressed("ui_right"):
        pos.x = SPEED
        $Sprite.play("Run")
        $Sprite.flip_h = false
    elif Input.is_action_pressed("ui_left"):
        pos.x = -SPEED
        $Sprite.play("Run")
        $Sprite.flip_h = true
    else:
        pos.x = 0
        $Sprite.play("Idle")
    if is_on_floor():
        if Input.is_action_just_pressed("ui_up"):
            pos.y = JUMP
    else:
        if pos.y < 0:
            $Sprite.play("Jump")
        else:
            $Sprite.play("Fall")
    pos = move_and_slide(pos,FLOOR)
```

# Answer
> 0 votes
You're telling your sprite to switch animations every frame while jumping, so it never gets past the first frame. Take a look at what code executes when `is_on_floor()` is `true` and `pos.y < 0`. You first try to play "Idle" (or "Run", if a direction key is pressed). *Then* you try to play "Jump", which starts at the first frame. On the next loop, you switch to "Idle" again, then back to "Jump" (resetting to the first frame).

Try to restructure your code so you are only calling `play` on one animation each loop.

---
Tags: animation, sprites, godot, gdscript
---


# Question
Title: How do I add a Rigid body and a box collider component to a Texture2D?
I am making a snake game. I'm basing it on a basic tutorial game, which does no collision detection, wall checking or different levels.

All snake head, piece, food, even the background is made of `Texture2D`. I want the head of the snake to detects 2D collisions with them, but `Rect.contains` isn't working. I'd prefer to detect collisions by `onTriggerEnter()` for which I need to add `BoxCollider` to my `snakeHead`.

# Answer
> 0 votes
To get onTriggerEnter events, you need to set the **Is Trigger** flag to true.

# Answer
> 3 votes
There should be an object that holds your texture and to that object you could add a collider.

# Answer
> 1 votes
If your game is 2D, you can use Rigidbody2D and BoxCollider2D. It will give you a performance boost, and will ignore Z position differences.

To get `OnTriggerEnter` or `OnTriggerEnter2D`, you need to check the *"Is Trigger"* checkbox in collider settings. Please note that doing so will remove your ability to make rigidbody respond collisions.

# Answer
> 0 votes
As you have already added "2D collisions", then you can't add "BoxCollider" because it is a 3D object. You have to add the components of the same type. Meaning, if you are going to use the 3D object like "BoxCollider", then you have to add a 3D collision not 2D collision. That means you have to add "Shpare collider" instead of 2D collider.

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


# Question
Title: What physics settings do I need to apply to make the pool game realistic?
I want to create a pool game using Unity.

1. I added the spheres as playballs and cubes as the walls.
2. I added a rigidbody to all objects and Im able to do some basic collisions like in a pool game.

My Question is:

What physics settings do I need to apply to make the pool game realistic?

Right now, it's a bit weird. The ball does not bounce off the walls realistically and also the ball to ball collisions are not ok.

Any suggestions?

# Answer
> 2 votes
Late, I know, but I think the big piece that you are missing is Physics Materials - they are what give the colliding objects their behaviors, in this case their bounciness.

# Answer
> 1 votes
You should look at this tutorial video https://unity3d.com/learn/tutorials/projects/roll-a-ball/moving-the-player

And maybe the entire Unity tutorial on Roll a ball

For making the balls bounce of the wall and from each other, on collision detection you should add a force based on momentum of ball(s).

# Answer
> 1 votes
Add physics material to your balls and walls. Then set the bounciness as per your requirement. Now the **most important thing**: `Go to edit > project setting > Physics > Bounce Threshold` and set it to zero(0). This will solve your problem. Now your balls sticks to the wall and bounces off at any speed.

Lets me know if it works for you. If you want I can share my project for your reference.

---
Tags: unity, 3d, billiards
---


# Question
Title: How to add a collision function to a game
Ive tried a few things but i cant get a working function if player collides with object set speed to 0( stop moving)

ive tried to use the function under "game over " and change the things to make speedx=0 and speedy=0 but i couldnt format it correctly.

https://www.w3schools.com/graphics/game\_obstacles.asp

my code:

```
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
    border:4px solid #d3d3d3;
    background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<script>

var myGamePiece;
var endGoalPiece;

function startGame() {
    myGameArea.start();
    myGamePiece = new component(30, 30, "red", 0, 0);
    endGoalPiece = new component(30, 30, "black", 450, 240);
    myObstacle = new component(10, 200, "green", 300, 120);
}

var myGameArea = {
    canvas : document.createElement("canvas"),
    start : function() {
        this.canvas.width = 480;
        this.canvas.height = 270;
        this.context = this.canvas.getContext("2d");
        document.body.insertBefore(this.canvas, document.body.childNodes[0]);
        this.interval = setInterval(updateGameArea, 20);
        window.addEventListener('keydown', function (e) {
            myGameArea.key = e.keyCode;
        })
        window.addEventListener('keyup', function (e) {
            myGameArea.key = false;
        })
    },
    clear : function(){
        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    }
}

function component(width, height, color, x, y) {
    this.gamearea = myGameArea;
    this.width = width;
    this.height = height;
    this.speedX = 0;
    this.speedY = 0;
    this.x = x;
    this.y = y;
    this.update = function() {
        ctx = myGameArea.context;
        ctx.fillStyle = color;
        ctx.fillRect(this.x, this.y, this.width, this.height);
    }
    this.newPos = function() {
        this.x += this.speedX;
        this.y += this.speedY;
    }
}

function updateGameArea() {
    myGameArea.clear();
    myGamePiece.speedX = 0;
    myGamePiece.speedY = 0;
    if (myGameArea.key && myGameArea.key == 37) {myGamePiece.speedX = -1; }//left
    if (myGameArea.key && myGameArea.key == 39) {myGamePiece.speedX = 1; }//right
    if (myGameArea.key && myGameArea.key == 38) {myGamePiece.speedY = -1; }//up
    if (myGameArea.key && myGameArea.key == 40) {myGamePiece.speedY = 1; }// down
    myObstacle.update();
    endGoalPiece.update();
    myGamePiece.newPos();
    myGamePiece.update();
}
</script>
<p>use the arrow keys on you keyboard to move the red square.</p>
</body>
</html>

```

https://jsfiddle.net/tmanrocks999/e6w9br2s/178/

I expect when the player hits the obstacle for them to stop moving. but at the moment they go through it/ i have 1 && that prevents it from going past the x location of obstacle but that doesn't work right

# Answer
So for collision detection and game development in general I suggest you start off with https://developer.mozilla.org/en-US/docs/Games/Techniques or https://www.w3schools.com/graphics/game\_intro.asp

The way you would do this is add a collision method in your component class like so:

```
 this.collison = function(rect2) {
      let rect1 = this;
      if (rect1.x < rect2.x + rect2.width &&
     rect1.x + rect1.width > rect2.x &&
     rect1.y < rect2.y + rect2.height &&
     rect1.y + rect1.height > rect2.y) {
      //credits to https://developer.mozilla.org/en-US/docs/Games/Techniques/2D_collision_detection
      this.color = "yellow";
      //check which side (x) the rect is touching
      if(rect1.x <= rect2.x) {
        rect1.x = rect2.x - 30;
      }
      if(rect1.x >= rect2.x) {
        rect1.x = rect2.x + rect2.width;
      }

    } else {
      this.color = "red";
    }
 }

```

Here's the updated JSFiddle: https://jsfiddle.net/mero789y/nvbcu7ja/1/
> 1 votes

---
Tags: javascript, html
---


# Question
Title: How to get an Unreal Engine 4 Level to sync using Git Source Control?
Hello Game Development Stack Exchange,

I and a couple of collaborators are working on an Unreal Engine project, we do not share a common network, which meant that using a local network storage to hold the data wasn't plausible.

I discovered that Unreal Engine allows Source Control through Git services, so I created a private repository on GitLab that all Collaborators have access to.

Inside of Unreal Engine, I created a Project with the Minimal C++ with Starter Content, edited the 'Minimal\_Default' map a little bit, inserted some new assets, placed them on the map. Made sure all my needed asset information was being checked-in to Source Control, saved everything, then Submitted to Source Control, named the commit, then committed locally.

Now outside of Unreal Engine, using TortoiseGit for Windows I pushed the commit to the GitLab repository, all the necessary files were uploaded. However, when I cloned the same repository to another machine, and opening (with the same exact engine version), the 'Minimal\_Default' map was the original, not the updated one. The assets I imported are inside of the Content Browser, but the assets are not placed around the level as I did to the commit.

So, my question states, how do I get the 'Minimal\_Default' level to be committed and opened when the Git repo is cloned? Am I missing something in Unreal Engine, Pushing, or something else?

All help would be greatly appreciated.

Sincerely, Shejan Shuza

# Answer
> 1 votes
Remember to stage the changes of the map inside your commit

Even if Sourcetree is marking your files as modified (checked-in) you still have to add your file inside your commit (aka stage the modified file).

Also after you commit some changes, you need to push them to the remote (usually origin).

A complete workflow would look like this:

* Make sure your file is tracked/ added
* Change your file
* Save it
* Add to staging area
* Write your commit message
* Commit locally
* Push to remote

Others have to fetch the origin and pull to get your changes.

If this does not solve your problem, please do share a photo of the commit itself, so we can see what's going on.

# Answer
> 1 votes
I has a similar issue.

**To duplicate the problem:**

1. Create a clean `git clone` of my Unreal (v4.23) project onto a Windows 2010 machine.
2. Browse to the `*.uproject` file, right-click, Generate Visual Studio project files.
3. Open the resulting `*.sln` file using Visual Studio 2019 (v16.3.3).
4. Build the project's default configuration via Build / Build Solution.
5. Run via Debug / Start Without Debugging.

**Observed vs. expected:**

* The project editor ran, but showed the default "minimal default" starter content map without my changes, whereas I expected to see what I'd pushed into git. All else looked fine, e.g. my classes, materials, blueprints, etc. were all there.

**To fix:**

1. Run `git status` in your cloned repository. In my case, there were differences under the `Content/StarterContent` directory, specifically with the `Maps/Minimal_Default.umap` and some `Architecture/*.uasset` files I'd changed.
2. Use git's suggestion for discarding changes in the working directory, e.g. `git checkout -- <file>...` listing each unexpectedly modified file.

I ran through the duplication steps again, this time checking the git status after each one. At least in my case, the culprit was duplication step 5. The git status was clean until I ran the project.

Hope that helps someone who was about to punt their keyboard. Alas, mine wasn't so lucky.

---
Tags: unreal-4, assets, version-control, git
---


# Question
Title: Why does the object rotate to a random direction when I start dragging?
I'm trying to do drag to rotate sort of thing, so far the code is fine. However when starting to drag (left clicking first), the object rotate to a random direction first which looks odd.

here is my code :

```
public Camera cam;
public float smoothAngle, dragPower = .3f;
public bool isRadial = true;
float angle, angleOld, angleDelta, angleRef;
Vector2 mousePosOld, mousePosDelta = Vector2.zero;

void Update()
{
  Vector2 mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
  if (Input.GetMouseButton(0))
  {
    mousePosDelta = mousePos - mousePosOld;
    float rotX = (mousePosDelta.magnitude / Time.deltaTime)
                  * dragPower
                  * -Mathf.Sign(mousePos.y)
                  * Mathf.Sign(Vector2.Dot(Vector2.right, mousePosDelta));

    transform.Rotate(Vector3.forward, rotX);

    mousePosOld = mousePos;
    angleDelta = Mathf.DeltaAngle(angleOld, transform.localEulerAngles.z);
    angleOld = transform.localEulerAngles.z;
  }
  else
  {
    transform.RotateAround(transform.position, transform.forward, angleDelta);
    angleDelta = Mathf.SmoothDampAngle(angleDelta, 0, ref angleRef, smoothAngle);
  }
}

```

this is the effect :

# Answer
It looks like there is garbage in your `mousePosOld` variable when you first detect a click (through `if (Input.GetMouseButton(0))`): it seems you use an uninitialized value for it (most likely (0, 0)) for the first click, or the value you got from the last time you had mouse-down.

Assuming you'll not get a mouse click event on the first frame, you could update the `mousePosOld` before leaving the function.

It also looks like you could keep `mousePosDelta` local to the function; here is an example:

```
public Camera cam;
public float smoothAngle, dragPower = .3f;
public bool isRadial = true;
float angle, angleOld, angleDelta, angleRef;
Vector2 mousePosOld;

void Update()
{
  Vector2 mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
  if (Input.GetMouseButton(0))
  {
    Vector2 mousePosDelta = mousePos - mousePosOld;
    float rotX = (mousePosDelta.magnitude / Time.deltaTime)
                  * dragPower
                  * -Mathf.Sign(mousePos.y)
                  * Mathf.Sign(Vector2.Dot(Vector2.right, mousePosDelta));

    transform.Rotate(Vector3.forward, rotX);

    angleDelta = Mathf.DeltaAngle(angleOld, transform.localEulerAngles.z);
    angleOld = transform.localEulerAngles.z;
  }
  else
  {
    transform.RotateAround(transform.position, transform.forward, angleDelta);
    angleDelta = Mathf.SmoothDampAngle(angleDelta, 0, ref angleRef, smoothAngle);
  }

  mousePosOld = mousePos;
}

```
> 3 votes

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


# Question
Title: SerializedProperty to UnityEvent in a Custom Editor
I am making a Custom Editor for a type that includes a UnityEvent property.

I'm currently facing an issue in converting a SerializedProperty to get that UnityEvent.

Here is how I declare the event in the type I want to edit with this custom editor:

```
public class SomeComponent : MonoBehaviour {

    public UnityEngine.Events.UnityEvent EventToAdd;

    //...
}

```

And this is my Editor script

```
[CustomEditor(typeof(SomeComponent))]
public SomeComponentEditor : Editor {

    private SerializedProperty _Events;
    private void OnEnable()
    {
        _Events = serializedObject.FindProperty("EventToAdd");
    }

    public override void OnInspectorGUI()
    {
        TwitchTVGui TGUI = (TwitchTVGui)target;

        this.serializedObject.Update();
        EditorGUILayout.PropertyField(serializedObject.FindProperty("EventToAdd"), true);

        this.serializedObject.ApplyModifiedProperties();
    }
}

```

And then I need to get the UnityEvent out of the serializedObject \_Events somehow

# Answer
Huh, I literally just had this problem and found this code over here, but it basically boils down to needing just this:

```
[Serializable] public class CustomEvent : UnityEvent { }

public CustomEvent myEvent = new CustomEvent();

```

Rename the class and field as you see fit. If you're going to use the same event in multiple script files, make it its own script, but having a micro-class for each one is fine too (it distinguishes that `OnWidgetDoX` and `OnWidgetDoY` are different events).
> 1 votes

# Answer
If I understand correctly, you are trying to serialize events so that they will show up in the inspector. You do not need to do that yourself.

Instead, just use `UnityEngine.Events.UnityEvent`, and it will be available in the inspector for you. This is simply a wrapper around standard C#.

```
public UnityEvent MyEvent;

```
> 0 votes

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


title: Detect collision on explosion

text:
# Question
Title: Detect collision on explosion
I am creating spells for my game.

The collision with a normal fireball works just fine, what I am trying to achieve is to have the `player_2` getting hit when the green explosion happens.

How can I achieve that? I tried adding explosion force with very high values just for testing purposes, but I could not make it work.

Below you can check a demonstration of what I am trying to do, and a piece of the code I tried.

```
this.spellPrefab.GetComponent<Rigidbody>().AddExplosionForce
            (configuration.ExplosionForce,
            spellPrefab.transform.position,
            500,
            0f,
            ForceMode.Impulse);

```

# Answer
You can view the particle system settings in the inspector and check on the collision box and specify what it should collide with.

The first spell that hits normally is because the two collide. The second spell needs to have collision added to the particles since the transform is not actually near the enemy to perform a typical collision.
> 2 votes

---
Tags: unity, c#, collision-detection, physics
---


title: How can I scale my window in SDL 1.2?

text:
# Question
Title: How can I scale my window in SDL 1.2?
I'm trying to scale my window, for example from 440\*420 to 320\*240.

How can I easily do this?

# Answer
> 1 votes
It's been a while since I last used SDL 1.2, but from what I remember there are two options.

First, SDL by default works in software mode. If you're not using OpenGL, then you'd have to grab the screen buffer SDL\_Surface and scale it to your window's size (probably SDL\_Image has a function to do that).

Second option is if you're using OpenGL. After resizing the window, you have to change the projection matrix, and the viewport. Projection matrix defines how much the user sees, viewport scales it to the window. If you set matrix as if the window is 320x240, and set the viewport to 440\*420 (window size), your rendered scene will be warped to match the window/viewport.

---
Tags: c++, sdl
---


title: Models /textures/music corrupted!

text:
# Question
Title: Models /textures/music corrupted!
I'm making a 3d rpg game. Everything seems to work on other computer. But when I open my game in my computer, the polygons gets crazy everywhere filled with random polygons. Textures will get rainbow effects and distorted music plays backs. Everything is corrupted, even the collision detection.

I think I have memory corruption but other games are ok...
I'm using the FreeGlut library.
Very basic obj loader and the Windows OS original playsound library. Compiler: Visual Studio 2017...

# Answer
> -1 votes
I fixed by changing special characters : üĞI to uGi

---
Tags: c++, glut
---


# Question
Title: How can I create a templated function to add components to their necessary containers using an ECS system?
I had implemented a basic ECS system and was then informed that it should be changed as each system should not directly store their required components.

I have created a `ComponentManager` which will own all of the registered components, and I would like to keep all of the different components in their own containers

```
class ComponentManager
{

    template <typename T> T& AddComponent(Entity entity)
    {
        //...
    }

    std::vector<2DRenderComponent>  m_renderComponents;
    std::vector<TransformComponent> m_transformComponents;
};

```

I could create a different function for each component type but I would like to get familiar with using templates for tasks like this. It will also make it a little easier further down the line when I try to do more complex tasks.

Could anyone point me in the right direction as to how I would achieve something like this, whilst keeping the components isolated from each other?

My usage would be something like the code below

```
Entity entity = entityManager->CreateEntity();
TransformComponent& transformComponent = componentManager->AddComponent<TransformComponent>(entity);

```

When I call `AddComponent` with a `TransformComponent`, how do I add it to the correct container (`m_transformComponents`). If I have to change the structure slightly to get this to work, i.e a map of types to vectors that is fine. Any guidance on this is appreciated.

---

So after looking into the entt framework, the functionality there is what I want to achieve, on a much smaller scale. Code example of how it functions (https://github.com/skypjack/entt#code-example)

I've done some digging into how they register components through what they describe as a `registry` (https://github.com/skypjack/entt/blob/master/src/entt/entity/registry.hpp).

From what I can gather after looking they identify component containers by ids but I'm confused as to what it is doing so if someone could help me to understand this it would be appreciated.

First entry point when we want to add a component to a given entity

```
template<typename Component, typename... Args>
decltype(auto) assign(const entity_type entity, [[maybe_unused]] Args &&... args) {
    ENTT_ASSERT(valid(entity));
    return assure<Component>()->assign(*this, entity, std::forward<Args>(args)...);
}

```

assure() is called to obtain the correct pool for the component being added

```
template<typename Component>
const pool_type<Component> * assure() const {
    const auto ctype = to_integer(type<Component>());

    //....
}

```

type function - this returns what I can see to be an enum? But how is the function constructing and returning an enum like it does. When I try this in a separate application it fails to compile

```
    ENTT_OPAQUE_TYPE(component, ENTT_ID_TYPE) //enum is created from this macro, along with the to_integer function

//macro
#define ENTT_OPAQUE_TYPE(clazz, type)\
    enum class clazz: type {};\
    constexpr auto to_integer(const clazz id) ENTT_NOEXCEPT {\
        return std::underlying_type_t<clazz>(id);\
    }

template<typename Component>
static component type() ENTT_NOEXCEPT {
    return component{runtime_type<Component, component_family>()}; //how is this compiling?
}

```

runtime\_type function - `ENTT_ID_TYPE` is defined as `std::uint32_t`

```
#define ENTT_ID_TYPE std::uint32_t

    template<typename Type, typename Family>
    static ENTT_ID_TYPE runtime_type() ENTT_NOEXCEPT {
        if constexpr(is_named_type_v<Type>) {
            return named_type_traits<Type>::value;
           //this looks like it returns a hashed string of the type name as std::uint32_t
        } else {
            return Family::template type<Type>;
        }
    }

```

# Answer
First of all, i don't know how the entt-Framework works. I recognize most of its functions, but some i dont really understand what they do. I try to explain what i did the first time around and also try explain, what problems i had. Maybe that helps what my way of thinking was.

Second, i just make some easy assumptions, that can be changed by your liking, but might require big changes in the structure themself.

* For simplicity sake, entities are just an ID and carry no information or functions other than that
* Components are only carrier for information, not functions.
* Components are all derived by a `BaseComponent`. That makes things a lot easier.
* Every component class has a static variable `COMPONENT_ID`for unique class identification. (I simply used Integer, but you can use what you want)
* You only need one system to hold all components.
* Entities can only have one of every component.

Ok, now to the real meat. First off all your `ComponentSystem`needs a way to register new `Components`. For that your system needs a way of saving what type of Components are registered and a way to save them. I also will mostly reside to comments or pseudocode, as its completly depends on your style of coding and using of variables.

For that, your system needs some sort of `Container<ComponentBase>`, that gets created for every type of component class you register. Then create a `Map<COMPONENT_ID, Container<ComponentBase*>` That was a problem for me, as i created my own Container for that. Luckily Stack Overflow helped me there.
With that map your `ComponentSystem` can keep track what components already have been regiestered. But just for convenience you should add a counter, what number the next registered `COMPONENT_ID`will be. Then you can implement your register-function:

```
    //register Components and return reference to them (Pre-Init Phase)
    template<class TComponent>
    void registerComponent() {
        //set COMPONENT_ID of the TComponent to a new and unused

    ... //Create Buffer for your TComponent and map it to your Map<COMPONENT_ID, Container<ComponentBase*>
    };

```

As you can see, i changed it from my original implementation, as you dont really need to get the `COMPONENT_ID`. The Systems working with the distinct components can just check the static COMPONENT\_ID on the components themselfs.

The components your engine start with should be registered by some sort of Pre-Loop Init-System, so all your starting systems dont try to register those aswell.

Now you could start adding Components to Entities:

```
//add a Component to an entity
template <class TComponent>
bool addComponent(EntityId entityId, TComponent component){
   //check if component is registered
   if(!mapOfComponentContainer.contains(component.getCOMPONENT_ID()){
      return false;
   } else {
      ComponentContainer* container = mapOfComponentContainers.get(component.getCOMPONENT_ID);
      //check if entitiy already has component of that type
      if(container->getPos(entityId) != null){
         return false;
      }
      //add component at entitiy Id as position
      container.add(component, entityId);
   }
}

```

I just wrote that on the fly, so i dont really now if there is any universe or compiler, that just can interpret that as i wrote it.

But that are basically the basics. Your system should add a way to return the component lists, or certain component constellation (as your `RenderSystem` will likely need a `PositionComponent`and a `GraphicComponent`at least).
Also you should add a way to get a single componente of an Entity, for editing, and a way to delete them. Also note, that this way is not in any way the optimal way of doing things. It may be slow, slughish or stupid. Just take it as it is as help to understand. There are so many ways to optimize this, so you should easily find a way to make things better (Pools, Contagious Memory etc.)
> 1 votes

---
Tags: c++, entity-component-system
---


# Question
Title: Godot: how to use _draw to draw textures at an angle
So simple question that I just can't find an answer to, how do I use Godot's \_draw function to draw textures rotated at an angle (more specifically how do I get them turned completely 90° onto their side).

# Answer
> 5 votes
You can use `draw_set_transform` to set the position, rotation, and scale of all following draw calls:

```
extends Control

func _draw():
    var icon = preload("res://icon.png")
    draw_texture(icon, Vector2(0, 0))
    draw_set_transform(Vector2(100, 100), PI / 2.0, Vector2(1, 1))
    draw_texture(icon, Vector2(0, 0))
    draw_set_transform(Vector2(200, 200), PI, Vector2(2, 2))
    draw_texture(icon, Vector2(0, 0))

```

However, as @TomTsagk hinted in the comments, `_draw` is only necessary if you have custom needs. In general, building your UI out of `Control` components will give you more out-of-the-box functionality. For example, you could use a `TextureRect` to draw a texture in your UI, which has a `set_rotation` method.

---
Tags: godot
---


# Question
Title: When drawing text, numbers appear as D1 or NumPad1 rather than just numbers
Been writing a class for a main menu, there's a play button and when pressed it goes to a window that asks for coordinates, sadly when writing with the keys and using the numbers the output is either D1, D2, D3... and so on, or NumPad1, NumPad2... and such. What I want is for the output to be just the number itself rather than the key name.

```
    private string Coordinates = string.Empty;
    private SpriteFont font;

    private Keys[] lastPressedKeys = new Keys[5];
    public void GetKeys()
    {
        KeyboardState kbState = Keyboard.GetState();

        Keys[] pressedKeys = kbState.GetPressedKeys();

        foreach (Keys key in lastPressedKeys)
        {
            if (!pressedKeys.Contains(key))
            {
                //key is no longer pressed
                OnKeyUp(key);
            }

        }
        foreach (Keys key in pressedKeys)
        {
            if (!lastPressedKeys.Contains(key))
            {
                OnKeyDown(key);
            }
        }
        lastPressedKeys = pressedKeys;
    }
    public void OnKeyUp(Keys key)
    {

    }

    public void OnKeyDown(Keys key)
    {
        KeyboardState kbState = Keyboard.GetState();

        if (key == Keys.Back && Coordinates.Length > 0)
        {
            Coordinates = Coordinates.Remove(Coordinates.Length - 1);
        }
        else
        {

            Coordinates += key.ToString();

        }

    }

```

Here's the whole class https://pastebin.com/ZJqXx0zc

is there something wrong with using ToString? Or should I be using something different for numbers?

# Answer
> 2 votes
Since the `Keys` class is an enum, `ToString` simply converts the names into strings. Enums can't have names, like `1`, `2`, etc., so they were named as `D1`, `D2`, and so on.

The built-in `KeyboardState` class isn't a good way to manage text input for multiple reasons (including this one, and the fact, that it doesn't support foreign characters, such as `ő`, `ö`, `á`, `é`, etc. or even special characters, such as `˛`, `˘` or `°`). You need to use something different, like this one.

# Answer
> 1 votes
I used this code:

string key = e.KeyCode.ToString();

if (key.Length \> 1) key = key.Replace("NumPad", "").Replace("D", "");

---
Tags: c#, xna-4.0
---


title: Selected enemy off camera

text:
# Question
Title: Selected enemy off camera
I'm facing a problem with a game I'm making. Currently I can select an enemy and mark it as shown on the image:

But now I want to show the position of the selected enemy on the screen when it's off camera. So my questions are:

1. How do I know when an enemy is off camera.
2. How can I show in GUI an arrow on the edge of the screen that points to the position of that enemy. Perhaps something related to what I did to point towards the crosshair?

```
Vector3 positionOnScreen = Camera.main.ScreenToWorldPoint(mousePos + Vector3.forward * range);
Vector3 targetDir = positionOnScreen - transform.position;

```

Thanks!

# Answer
1. You can easily know if a world point is visible by a given camera using Camera.WorldToViewportPoint. This will return a `Vector2` that represents the position of your object in the viewport. A viewport goes from \[0,0\] (bottom left) to \[1,1\] (top right). If the returned value has a component lower than 0 or higher than 1 it means that the object is offscreen (or partially offscreen).
2. As Seyed Morteza Kamali suggested in his comment, you can point the position of your object using basic intersection

---

About the second point the solution is all about linear function (y = ax + b).

            Vector2 a = viewport_pos; // viewport position of your offscreen item
            Vector2 b = target_viewport_pos; // viewport position of the target (in your case 0.5;0.5 for the

            if (b.x == a.x || a.y == b.y) return;

            // y = px + d
            float p = (b.y - a.y) / (b.x - a.x);
            float d = a.y - p * a.x;

            float new_vy;
            float new_vx;

            // Check the axis with the biggest difference to define on which side of the screen you should display the arrow.
            float diff_x = a.x - b.x;
            float diff_y = a.y - b.y;

            // Display the arrow on the left/right sides
            if (diff_x > diff_y)
            {
                new_vx = viewport_pos.x < 0 ? 0f : 1f;
                new_vy = new_vx * p + d;
            }
            else // Display the arrow on the top/down sides
            {
                new_vy = viewport_pos.y < 0 ? 0f : 1f;
                new_vx = (new_vy - d) / p;
            }

            // This is the position of your arrow.
            Vector3 new_pos = Camera.main.ViewportToWorldPoint(new Vector3(new_vx, new_vy));
```

> 3 votes

---
Tags: unity, camera, gui
---


title: Unity - character is not moving

text:
# Question
Title: Unity - character is not moving
**What I'm trying to do**

I have a character - prefab. For this prefab I have one animation (idle), which works fine - I hit "Play" button and my character is in idle state. What I want is to try to move this character without implementing an animation (for now, only for test). So I wrote two scripts - one is the "engine" for movement and one is the controller for the character itself.

**What is wrong**

The thing is, that my character is not moving at all. I tried to debug the keyboards in the console and that works fine, so I assume that the inputs are good. I checked that twice in the Project Settings. I tried with two Unity versions and also I tried to start whole new project only with cubes, because I thought that maybe is something wrong with my character. That doesn't work either.

**MovementMotor.cs**

```
using UnityEngine;

public class MovementMotor : MonoBehaviour
{
    public float gravityMultiplier = 1f;
    public float lerpTime = 10f;

    [HideInInspector]
    public CharacterController characterController;

    private Vector3 moveDirection = Vector3.zero;
    private Vector3 targetDirection = Vector3.zero;
    private float fallVelocity = 0f;

    public float distanceToGround = 0.1f;

    private bool isGrounded;
    private Collider myCollider;

    void Awake()
    {
        characterController = GetComponent<CharacterController>();
        myCollider = GetComponent<Collider>();
    }

    void Start()
    {
        distanceToGround = myCollider.bounds.extents.y;
    }

    void Update()
    {
        isGrounded = OnGroundCheck();
        moveDirection = Vector3.Lerp(moveDirection, targetDirection, Time.deltaTime * lerpTime);
        moveDirection.y = fallVelocity;

        characterController.Move(moveDirection * Time.deltaTime);

        if (!isGrounded)
        {
            fallVelocity -= 90f * gravityMultiplier * Time.deltaTime;
        }
    }

    public bool OnGroundCheck()
    {
        RaycastHit hit;

        if (characterController.isGrounded)
        {
            return true;
        }

        if (Physics.Raycast(myCollider.bounds.center, -Vector3.up, out hit, distanceToGround + 0.1f))
        {
            return true;
        }
        return false;
    }

    public void Move(Vector3 direction)
    {
        targetDirection = direction;
    }

    public void Stop()
    {
        moveDirection = Vector3.zero;
        targetDirection = Vector3.zero;
    }

    public void Jump(float jumpPower)
    {
        if (isGrounded)
        {
            fallVelocity = jumpPower;
        }
    }
}

```

**CharacterMovement.cs**

```
using UnityEngine;

public class CharacterMovement : MonoBehaviour
{
    private MovementMotor motor;

    public float moveMagnitude = 0.05f;
    public float speed = 0.7f;
    public float speedMoveWhileAttack = 0.1f;
    public float speedAttack = 1.5f;
    public float turnSpeed = 10f;
    public float jumpPower = 20f;

    private float speedMoveMultiplier = 1f;

    private Vector3 direction;
    private Animator animator;
    private Camera mainCamera;

    private string PARAMETER_STATE = "State";

    void Awake()
    {
        motor = GetComponent<MovementMotor>();
        animator = GetComponent<Animator>();
    }

    void Start()
    {
        animator.applyRootMotion = false;
        mainCamera = Camera.main;
    }

    void Update()
    {

    }

    private Vector3 MoveDirection
    {
        get
        {
            return direction;
        }

        set
        {
            direction = value * speedMoveMultiplier;

            if (direction.magnitude > 0.1f)
            {
                var newRotation = Quaternion.LookRotation(direction);
                transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, Time.deltaTime * turnSpeed);
            }
            direction *= speed * (Vector3.Dot(transform.forward, direction) + 1f) * 5f;
            motor.Move(direction);

            // AnimationMove(motor.characterController.velocity.magnitude * 0.1f);
        }
    }

    void Moving(Vector3 direction, float multiplier)
    {
        speedMoveMultiplier = 1 * multiplier;
        MoveDirection = direction;
    }

    void Jump()
    {
        motor.Jump(jumpPower);
    }

    void MovementAndJumping()
    {
        Vector3 moveInput = Vector3.zero;
        Vector3 forward = Quaternion.AngleAxis(-90, Vector3.up) * mainCamera.transform.right;

        moveInput += forward * Input.GetAxis("Vertical");
        moveInput += mainCamera.transform.right * Input.GetAxis("Horizontal");

        moveInput.Normalize();
        Moving(moveInput.normalized, 1f);

        if (Input.GetKey(KeyCode.Space))
        {
            Jump();
        }
    }
}

```

**Question**

Does the problem lies within the code or maybe I should look somewhere else?

Unity version: 2019.2.9f1

System: MacOS Mojave 10.14.6

# Answer
Currently, in **MovementMotor.cs** `moveDirection` is always zero unless `distanceToGround` is greater than `0.1f`. This is because in **CharacterMovement.cs** `MovementAndJumping()` is never called. Calling this Method in `Update()` should fix the problem.

**CharacterMovement.cs**

```
void Update()
{
    MovementAndJumping();
}

```
> 1 votes

---
Tags: unity, character
---


title: Load scenes inactive

text:
# Question
Title: Load scenes inactive
When I call `SceneManager.LoadScene()` it will set the loaded scene as active. Can I load scenes at the game startup and just call `SceneManager.SetActiveScene()` during gameplay?

If so, is there a way to iterate through all the scenes in the *Build Settings* and load them? Mine don't have a build index assigned to them until I have called `LoadScene()`.

# Answer
i think what you are looking for is **async** loading. async loading, just loads you scene in background and shows(runs) you scene anytime you want.

https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.LoadSceneAsync.html Smooth loading screen between scenes
> 2 votes

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


# Question
Title: How to figure out what's moving my GameObject?
I have a GameObject as part of a complex scene with a handful of interconnected parts, that's moving when it shouldn't be. I've tried running under the debugger and setting breakpoints on all of the script points that are supposed to move its Transform, and ensured that none of them are firing. There seems to be some "spooky action at a distance" going on, some rogue script doing something I don't want it to be doing, but I can't for the life of me figure out where it is.

What I'd really like is some way to set a "breakpoint" on the object's Transform that will break me into the debugger when it gets moved by any script, but that doesn't appear to be supported. Is there any way to figure out exactly what it is that's moving my object around when it shouldn't be?

(And before anyone says "trial and error, disable components and see when it stops moving," I already know exactly which component to disable to make it stop moving. Unfortunately, that isn't helping track down the problem because the movement isn't coming directly from that component's MonoBehaviour script.)

# Answer
Replace all instances of `transform.position =` and `transform.localPosition =` with a custom extension method:

```
public static class ExtensionMethods {

    public static void SetPosition (this Transform transform, Vector3 position) {
        if (transform.gameObject.name == "foo") {
            Debug.Log("foo is being moved!");
        }
        transform.position = position;
    }

    public static void SetLocalPosition (this Transform transform, Vector3 localPosition) {
        if (transform.gameObject.name == "foo") {
            Debug.Log("foo is being moved!");
        }
        transform.localPosition = localPosition;
    }

}

```

You can then call `transform.SetPosition()` or `transform.SetLocalPosition()`.

So `transform.position = somePosition;` would be replaced with `transform.SetPosition(somePosition);`, and you'll get a stack trace from `Debug.Log` within.
> 1 votes

---
Tags: unity, debugging
---


# Question
Title: How to render 3d object as 2d with different angles
I wanted to make a ship as a 3d object and import it with an atlas file to my 2d libgdx project with different angles like I saw it by another game.

And I was wondering if there is a specific software which should be prefered to make those things.

Where can I create the 3d objects and export them into a big png + atlas file?

# Answer
> -1 votes
You can use my script for converting 3d 3dsmax animations to spritesheets Link: https://github.com/kalevski/maxSpriter

---
Tags: java, libgdx
---