# Question
Title: How to move objects across a canvas with consistent speed on different screen resolutions?
I am making a rhythm game in Unity. I have been using Transform.Translate for moving images on a canvas as the music notes. However, I cannot consistently use this method on different screen widths. The notes move the same amount each frame.

I want to use interpolation for my music notes. I want to have the notes reach the center of the canvas at the same time despite the width of the screen. How can I write such a script?

# Answer
If you want to **l**inearly int**erp**olate between two values, the jargon for that is "**lerp**". The basic idea is you pass a lerp function two values and a number between 0 and 1 that specifies how far between the two you want the current position to be. In this way you can control when a moving object hits the target by controlling when the value between 0 and 1 hits 1.

Here's an official Unity article on lerping.

After adapting examples from there to your particular use case where at least two notes need to hit the same place at the same time I get this:

```
Vector3 noteAStart = new Vector3 (...);
Vector3 noteBStart = new Vector3 (...); // choose these however you like
Vector3 center = new Vector3 (...); // calculate the center of the screen here.

Vector3 noteACurrent = Vector3.Lerp (noteAStart, center, progress);
Vector3 noteBCurrent = Vector3.Lerp (noteBStart, center, progress);

```

You can then set your notes' positions directly to `noteACurrent` and `noteBCurrent`, which will be change based on the current value of `progress`. So, if we can figure out what to set `progress` to each frame, then we're set. But how do we do that?

First, we need to know how long we want the animation to take. Let's assume we want it to take half a second.

Well, assuming the game runs at exactly 60 frames per second, the most straight-forward way would be to just increment progress by 1/30th each time, so we get to 1 after exactly 30 frames.

```
const float PROGRESS_PER_UPDATE = 1.0 / 30.0;
//...
progress += PROGRESS_PER_UPDATE;

```

However, `Update` does not necessarily get called exactly 60 frames per second, depending on the system load. Depending on your timing needs the occasional lag may be both noticeable and highly undesirable.

One way to deal with this is to factor in the time that the last frame took, (the `Time.deltaTime`,) into the interpolation, by doing something like this:

```
progress += Time.deltaTime / DESIRED_DURATION_IN_SECONDS;

```

But this approach can produce undesirable results if `Time.deltaTime` is ever significantly larger than it usually is, depending on what other code is triggered by progress reaching or exceeding `1.0`. You also may want to clamp `progress` to be at most `1.0`, depending on how far things move in a frame.

Another method which Unity has built-in for you, is to use FixedUpdate instead which attempts to provide a more consistent time step, allowing you to just use a constant amount of progress per frame. It is still true that ultimately a system with sufficiently heavy load, (say several other heavy programs are running in the background besides just your game,) will need to skip some frames, and/or call the method at a different frequency, some of the time. In practice this is likely not an issue.

If the way Unity deals with the an overloaded machine ever does become an issue, it would be possible to keep track of the actual elapsed time yourself, and react accordingly. You could even set up your own loop that handles heavy load the way you want to, but this is much more complicated, particularly making such a loop play nice with Unity's expectations.

# Worked example regarding screen sizes

Let's assume that you've got a `progress` variable which is changing at the desired rate, based on one of the above methods.

At some point your game will need to read the screen dimensions from The `Screen` class.

You can get the center position of the screen like so:

```
var center = new Vector3(Screen.width * 0.5, Screen.height * 0.5, 0.0);

```

(Since most screens have even dimensions, there is no center pixel. This gives a pixel that is as close as possible to the center. You can add `0.5` as appropriate to talk about the actual center of the screen if desired, but this is probably unnecessary complication.)

I don't know how you have been setting your notes' positions so far, but if you want you can set them based on the screen size as well, by multiplying by the appropriate dimension. For example:

```
new Vector3(Screen.width * 0.125, Screen.height * 0.125, 0.0)

```

creates a position near one corner of the screen, and

```
new Vector3(Screen.width * 0.875, Screen.height * 0.875, 0.0)

```

creates one near the opposite corner. Here's the example from above with all the `...` parts filled in:

```
Vector3 noteAStart = new Vector3 (Screen.width * 0.125, Screen.height * 0.125, 0.0);
Vector3 noteBStart = new Vector3 (Screen.width * 0.875, Screen.height * 0.875, 0.0); // choose these however you like
Vector3 center = new Vector3 (Screen.width * 0.5, Screen.height * 0.5, 0.0); // calculate the center of the screen here.

Vector3 noteACurrent = Vector3.Lerp (noteAStart, center, progress);
Vector3 noteBCurrent = Vector3.Lerp (noteBStart, center, progress);

```
> 1 votes

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


# Question
Title: Using Part of prefab as script parameter
I'm trying add a weapon to Eithan - the third person character. So I want to take his hand, which is part of the prefab Eithan (the weapon location) and use it in the my Player.cs script to Instantiate the weapon. I created a parameter in the script for the hand: \[SerializeField\] GameObject weaponSocket; and I tried to Instantiate the weapon like this like this: Instantiate(weaponPrefab, weaponSocket.Transform);, but I just cant drag the hand to the parameter.

Anyone knows how to do this correctly?

Thank you!

Images: Player script:

```
public class Player : MonoBehaviour, IDamageable {

[SerializeField] Weapon weaponInuse;
[SerializeField] GameObject weaponSocket;

GameObject currentTarget;
CameraRaycaster cameraRaycaster;

// Use this for initialization
void start ()
{
   PutWeaponInHand();
}

private void PutWeaponInHand()
{
   var weaponPrefab = weaponInUse.GetWeaponPrefab();
   var weapon = Instantiate(weaponPrefab, weaponsocket. transform);
   weapon.transform.localPosition = weaponInUse.gripTransform.localPosition;
|  weapon.transform.localRotation = weaponInUse.gripTransform.localRotation;

```

Trying to drag the left hand to the parameter (indicated by red arrows):

# Answer
What you can do is to use the method FindGameObjectsWithTag. Add a special tag to your hand and use this:

```
GameObject hand = FindGameObjectsWithTag("HandTag")[0];

```

Here is the documentation: https://docs.unity3d.com/ScriptReference/GameObject.FindGameObjectsWithTag.html
> -2 votes

---
Tags: unity, prefabs, scriptable-object
---


# Question
Title: Does animation have internal "update"-cycle where I can make calculations between steps?
I am new to Unity and not game developer at all, so sorry if this question might be stupid. I have an animation in my project. Is there some points where Unity calculates/recalculates the next position of animated character? Is there some function like for example "OnAnimationSample()"? I want to make calculations between theese points. I didn't found anything in the documentation and hope that someone more experienced than me know some way to tackle, although the task is quite peculiar.

I am programming a simulation environment for robots. There is a need to take screenshots at certain events happening by means of raycasting (gathering img data for CNN). The robot has various physical specification like for example speed. I don't want the environment depends on speed of the robot, so I am planning to make calculations and screenshots constatly for example in between two animation "milestones". That will slow fps and overall game down, but I don't mind since I need only right data at right step. For example suppose there are exist such points in the Unity, when before taking any movement the Unity calculates the next state of the object being animated. I want to stuff my calculation and such, that next animation step won't start until all is done.

I hope that explained not so tricky. Say if the explanation is obscure I will try my best again.

# Answer
> 1 votes
From what I have understood from your question you are trying to perform certain calculations based on animation state so here is few approaches:

1. You could have a script inherited from StateMachineBehaviour instead of Monobehavoir and attach it to animation states. For further details check out unity's documentations https://docs.unity3d.com/ScriptReference/StateMachineBehaviour.html
2. You could have animation events marked on animation frames and invoke those events as per your need. For further details check this out https://docs.unity3d.com/Manual/script-AnimationWindowEvent.html#:~:text=To%20add%20an%20Animation%20Event,mouse%20to%20reposition%20the%20Event.

# Answer
> 1 votes
If you want to perform some calculation before the animation system and the physics engine operate on the object, then the right event for that is FixedUpdate.

For more information when Unity executes which event, check out this diagram about the order of execution in Unity.

---
Tags: unity, animation
---


# Question
Title: Material looks different on programatically generated mesh compared to resized default cube mesh
I've written some code that generates a mesh from some 2D nodes, generating both triangles and vertices. It seems to have worked pretty well, since I get a solid mesh without any weird rendering artefacts:

As you can already see in the preview, I am experiencing some problems with lighting and materials, despite the triangles and vertices being completely valid and wound correctly.

This is probably shown best by comparing this with a mesh created via right click \> 3D Object \> Cube, with the exact same material assigned as the programmatic mesh:

I have tried calling `RecalculateNormals()` on the mesh, but this doesn't help.

I'm really stuck trying to work out what's going on, so any help is very much appreciated.

**Edit:**

In lieu of the code, here are the vertices and triangles that I'm using in this mesh:

```
Vertices: [(0.5, 0.0, 0.5), (0.5, 0.0, -0.5), (-0.5, 0.0, -0.5), (-0.5, 0.0, 0.5), (0.5, -0.5, 0.5), (0.5, -0.5, -0.5), (-0.5, -0.5, -0.5), (-0.5, -0.5, 0.5)]

Triangles: [(3, 0, 1), (3, 1, 2), (5, 4, 7), (6, 5, 7), (0, 4, 5), (5, 1, 0), (1, 5, 6), (6, 2, 1), (2, 6, 7), (7, 3, 2), (3, 7, 4), (4, 0, 3)]

```

For @Phillip:

```
Mesh editing = Instantiate(new Mesh());

Vector3[] vertices;
int[] triangles;
GenerateVertices(out vertices);
GenerateTriangles(in vertices, out triangles);

editing.Clear();
editing.vertices = vertices;
editing.triangles = triangles;
editing.RecalculateNormals();

```

# Answer
There are a couple things missing from your mesh generation code:

1. You forgot to set any uv (texture) coordinates for all corners of your triangless. You might wonder why you need those when your material doesn't even have a texture. The reason is that the Global Illumination engine requires UV coordinates for calculating its lightmaps, even for shaders which don't use textures.
2. You forgot to calculate a secondary uv map with Unwrapping.GenerateSecondaryUVSet(mesh) which is also required for some shaders.
3. You called RecalculateNormals() but you didn't call RecalculateTangents(). This is usually only required for materials which use a normal map, but it usually doesn't hurt to do it anyway in case you later decide to apply one which does.
4. You forgot to call RecalculateBounds(). This is likely unrelated to the problem, but might cause other problems later related to culling.
> 1 votes

---
Tags: unity, c#, 3d-meshes, materials
---


# Question
Title: Which Terrain LOD algorithm should I use for super large terrain?
My game needs a terrain, the requirements are:

1. Freely Zoom in & zoom out, like GoogleEarth. Max resolution when zooming in ~100 meter, Max range when zooming out ~2000km (a whole country scale).
2. Freely fly over to any direction with any height; Freely rotate camera; Framerate should not a bottleneck for all those basic camera movement.
3. Support large heightmap data. I got mine real world elevation data from NASA with 7.5arc resolution, around 30k * 15k for a whole country.
4. Also I need to consider the spherical earth surface curvature other than using a planar map. But this should be easy if I just map each vertex into spherical coordinates. I am not build the whole planetary LOD so it's not even a problem.

I noticed there are many different LOD algorithm out there. For example:

* **ROAM**: very classic algorithm, most done on CPU;
* **Geomipmapping**: store the whole heightmap with best resolution as vertex buffer, with different LOD in vertex index. Then determine LOD and draw range in vertex index at runtime.
* **CDLOD**:
* **Geo Clipmapping**: I am feeling excited about this one since it claims to load all 200k * 100k US heightmap into video card memory and compressed ~300M, it seems to meet all my requirements. see source paper. And this is paper in 2004 and think about the video card at that time!

That's pretty much all I know about terrain LOD. I am not familiar recently study/research in this area. Is **Geo clipmapping** my best option? What else algorithms are also useful to consider?

# Answer
Forget about ROAM. That's the pre-3DFX era of SW rasterizers. I mean, if you're bored, it's a fun exercise, but it's useless in today's era of thousands of shaders units...

I would very strongly recommend **Chunked LOD** (Geomipmapping) because:

* it's super simple to implement - literally, one day is all it takes to create 3 different Index Buffers (High/Medium/Low Detail)
* it will serve as a reference implementation for further LOD schemes you will implement later

The single greatest issue with Chunked LOD is that it retains HighDetail on the border. So, while your base terrain chunk is, for example, 33x33 vertices, and your low detail would have only 7x7 on the inside of the chunk, the borders would be 33 vertices, which is much more than the ~90% of your chunk area.

This is why I would propose to first experiment a bit with your target data set:

* see if you can get away with completely without the high-detail border
* this will introduce cracks on the boundary (say, high-med or med-low) in distance, but only you can tell, if that's acceptable for your application or not.
* cracks visibility is exacerbated by the viewing angle. If you are only viewing terrain head on at zero angle (like, landing on the planet), you will not see any cracks. Opposite extreme is a first-person view, which will make every single one of them very visible against background.

I have alleviated the problem myself by creating additional sets of Index Buffers:

* have all combinations of hi/med/low on all 4 sides
* at run-time, based on actual LODs on the boundary, I then choose a correct Index Buffer
* this is only a slight complication that shouldn't take more than 1 day to implement, so well worth it

Once you've done the above, you can now implement a quadtree-style LOD where each base chunk will get progressively larger:

* 33x33
* 65x65
* 129x129 This will allow you to stop wasting vertices at the borders and relieve CPU from processing thousands of vertex batches. Which, again, depends on your target HW requirements. Perhaps you can start with 129x129, and just use 257x257 and 513x513 - we don't know your target HW specs...
> 1 votes

---
Tags: terrain, mesh, gpu, level-of-detail, open-world
---


# Question
Title: How to load 3D modells when they are necessary
I'm working on a 3D game engine, currently I load ALL of my 3D modells into the memory when my game starts, but obviusly there will be hundreds of 3D modells, so somehow I should unload them when they are out of the range, and load them again when the player is going to go near them.

What is the best way to do this ?

# Answer
> 0 votes
It also depends on the engine you're using, but for example:

In Unreal Engine 4, you use something called "Level Streaming" where you open a level that you want to remain persistent (meaning, a level that is always loaded) and add sub-levels to it that load when certain events are triggered. These sub-levels work in a similar way to layers in say, Photoshop. You can hold any amount of 3D models, animations, post processing, etc on each "layer" (sub-level).

I'm sure other engines have similar functionality but possibly under a different name.

# Answer
> 0 votes
There are many strategies to do this, I'll just list the most common the ways people have done them in the past and you can then use this as a jumping off point for more research.

## Scene files

Define a scene (or level) file which specifies where and what is inside the level, you can then use this list to load data as it's needed and unload when you switch to a different scene. Sometimes you want multiple scenes in the world and could potentially have to maintain multiple lists of assets, it all really depends on the requirements of the game your trying to build.

## Distance based loading

Some engines have implemented systems where they know what items are around the player and thereby know what resources are required by those objects. Then they look at where the player is and how far away those objects are and load whatever is closest to them that can fit into memory. These types of systems are usually needed when there is a LOD system which is hitting memory constraints.

---
Tags: opengl, java, 3d, 3d-meshes, memory-efficiency
---


# Question
Title: How to set C++ language standard for VS2019 in an Unreal project?
I am trying to a simple thing, just like that, in a header file;

```
#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;

```

And IntelliSense goes: `namespace std has no member filesystem`.

Okay no worries, it's an easy fix. Just set the C++ language standard in the propery pages...

Well, it turns out it isn't, it's not an option in Unreal VS project. Tried typing in search bar, View -\> Property pages, but no luck.

Okay let's try doing the whole thing in a console project first.

Same message from IntelliSense as before.

Ok, no worries, I found this.

I found my settings under: Project \> projectname Properties

And voila, the console app works.

Let's try it in the Unreal project.

Well, well... My options are limited here.

I had a look around in the project settings as well:

How do I get this filesystem header work with my project?

# Answer
> 3 votes
Okay, found the solution here.

```
CppStandard = CppStandardVersion.Cpp17;

```

I added this to my myproject.Build.cs

---
Tags: c++, unreal-4, visual-studio, filesystem
---


# Question
Title: Camera stacking for first-person view weapon in Universal Render Pipeline
I just added URP to my project then upgraded the materials to URP and now it's not rendering the environment anymore

I found the problem is that I have 2 cameras which are stacking on each other: one with a priority of 1 and the other 0 . The camera that has higher priority is blocking the lower priority camera.

How can I fix that? I want to render the higher priority camera on top of the lower priority one.

# Answer
> 0 votes
I was overlaying cameras on each other in the SRP so, in order to make it work in URP, I just had to Stack them properly link to documentation

---
Tags: unity, rendering, camera, first-person-shooter
---


title: Which image effect is this?

text:
# Question
Title: Which image effect is this?
This is a screenshot from RE7. I have once seen the same image effect in Unity, but I don't remember the name:

I'm not talking about AA or DOF here, I mean this grainy / greenish thing, I don't know how to describe it...

At first I thought the name was something like "Anisotrophic filtering", but that didn't bring up anything that looked like it.

Can anybody tell me the name of the effect that I see here?

Edit: It can be seen in the start screen of this video, too: https://www.youtube.com/embed/aaN3MNb9ij0?feature=oembed

Both screenshots look pretty similar to me, so I guess it's the same effect?

Edit 2:

The pixels seem to shift into red / blue the closer they get to the edge of the screens.

I have drawn red arrows to region where this effect is very visible to me. These pixels appear as "shifted" to me.

I think this effect is more visible at the edge of the screen.

Thank you.

# Answer
I'm really not sure what you are referring to, as I don't see any effect that looks grainy or greenish in the screenshots or clips (other than a few green objects on the desk, but I'm sure that's not what you're referring to).

As far as effects I see:

From the RE7 screenshot

* The only obvious visual effect in the RE screenshot (aside from DOF) is a blood smear in the top-left corner of the image (which is red and not grainy).

From the Unity HQ Abandoned School video:

* Bloom \- Creates a glow around bright parts of the image; can also be combined with a lens dirt texture to create the look of a dirty lens. Bloom is visible around the sun/sky in the external shots, and I think there's lens dirt in the shot of the desk with lamp, though they are also using a particle effect to simulate dust in the air. There's also some mild lens dirt or lens flare in a few other shots
* Chromatic aberration: A few shots might have very mild chromatic aberration. It's hard to describe this effect and I suggest doing an image search for it.
* Color grading: Adjusts the color tone of the image, such as saturation, tint, and contrast. Some shots look like they might use color grading to achieve a more stylized look (e.g. adding a little sepia, reducing black levels).
* Vignette: darkens the edges of the image. I believe this effect is applied uniformly on every shot.

Regarding the green, these are the parts of the desk image that Photoshop thinks have some green (determined by increasing the saturation "Greens" in the Hue/Saturation window by 100).

Here's the image with the same range of green completely desaturated. On my calibrated monitor the difference from the original image is barely noticeable. If it still looks very green to you, that suggests to me that your monitor isn't calibrated correctly.

As for the RE7 image, if I put it into Photoshop and raise the saturation of "greens" by 100, the image doesn't change at all; in other words, in contains no green at all.

EDIT: Here's an example of Chromatic Aberration
> 2 votes

# Answer
Well, I'll share my opinion with you. I am not sure where you are pointing exactly but from the comments and your post I feel like slight **hue rotation** effect could give you this kind of results.
> 1 votes

---
Tags: unity, image-effects
---


# Question
Title: How to change a sprite via script at runtime when using an animator?
I am making a simple 2D shooter.

I have my character's body and head as different objects, as I want him to look up/down regardless of the movement. So, I basically use the following script:

```
public class PlayerHead : MonoBehaviour
{
    public static PlayerHead instance;
    public SpriteRenderer theSR;
    public Sprite netural, down, up;

    private void Start()
    {
        instance = this;

    }
    public void Up()
    {
        theSR.sprite = up;
    }

    public void Down()
    {
        theSR.sprite = down;
    }

    public void Netural()
    {
        theSR.sprite = netural;
    }

}

```

However, the head is also used in the player animations:

This is because head must move with the body during the idle animation (breathing and moving up&down slowly).

I suspect that because of this animation, the sprite of the head is somehow fixed. It does not change in runtime even though I change it manually inside Unity.

How can I make the Animator let me change the sprite?

# Answer
> 1 votes
Thanks to DM Gregory's comment, I have understood and solved the issue.

Since I am using the Head object in animator, the sprite is updated in every frame. Therefore, even I change it in one frame, it goes back to default in the next one.

This is the right way to do it:

```
public class PlayerHead : MonoBehaviour
{
    public static PlayerHead instance;
    public SpriteRenderer theSR;
    public Sprite netural, down, up;
    public Sprite current;

    private void Start()
    {
        instance = this;

    }

    private void LateUpdate()
    {
        theSR.sprite = current;
    }

    public void Up()
    {
        current = up;
    }

    public void Down()
    {
        current = down;
    }

    public void Netural()
    {
        current = netural;
    }

}

```

It is importan to use `LateUpdate()` method because the animations are updated between `Update()` and `LateUpdate()`.

Credit goes to DMGregory.

---
Tags: unity, 2d, animation, sprites
---


# Question
Title: Volumetric lighting not working when building and running game
I have a volumetric lighting system implemented into Unity and when I am making the game and run it in the Unity editor the volumetric lighting shows up. When I build it and run it though it doesn't.

I think this is caused because it has not exported the script with the volumetric lighting so I exported it again and it still didn't show. I dont know what is up. Any suggestions would be appreciated.

In Unity with the thing working:

Unity built game:

# Answer
> 1 votes
I built the game with console and looked for errors. It said a 3 shaders were missing and told me to make sure it is included in "always include shaders" in ProjectSettings/Graphics. So I changed the size from 8 to 11 and added the 3 shaders and "voilà," which in french means and then I found out. Now my game looks much better!

---
Tags: unity, lighting, build-process, export
---


# Question
Title: Why does the script stop working after respawning?
I have a flying enemy that follows the player:

```
public class MoveTowardsPlayer : MonoBehaviour
{
    public float moveSpeed, sightDistance;
    public Rigidbody2D theRB;
    public Transform target;
    private void Start()
    {
        theRB = GetComponent<Rigidbody2D>();
    }
    private void Update()
    {
        Vector3 targetDir = target.position - transform.position;
        targetDir = targetDir.normalized;
        float dist = Vector3.Distance(target.position, transform.position);
        if (dist < sightDistance)
            theRB.velocity = targetDir * moveSpeed;
    }

}

```

And here is what happens when the enemy dies, and then respawns:

```
  public void Die()
    {
        Instantiate(enemyDieEffect, transform.position, transform.rotation);
        gameObject.SetActive(false);
    }

    public void Respawn()
    {
        gameObject.transform.position = initialPosition;
        gameObject.SetActive(true);
        currentHealth = maxHealth;
    }

```

The enemy respawns if the player dies and goes back to the last checkpoint.

Interestingly, if the player dies before reaching any checkpoint, the `MoveTowardsPlayer` scripts still works after respawning. It only stops working after any of the checkpoints are reached.

For the sake of completeness, here is the Checkpoint script, which has absolutely nothing to do with the enemies:

```
public class Checkpoint : MonoBehaviour
{
    private Animator animator;
    public bool isReached;

    // Start is called before the first frame update
    void Start()
    {
        isReached = false;
        animator = GetComponent<Animator>();
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            CheckpointController.instance.DeactivateCheckpoints();
            animator.SetBool("isActive", true);
            CheckpointController.instance.SetSpawnPoint(transform.position);
        }
    }

    public void ResetCheckpoint()
    {
        animator.SetBool("isActive", false);
    }
}

```

# Answer
> Interestingly, if the player dies before reaching any checkpoint, the MoveTowardsPlayer scripts still works after respawning. It only stops working after any of the checkpoints are reached.

Presumably your problem code is this:

```
if (dist < sightDistance) theRB.velocity = targetDir * moveSpeed;

```

When you respawn the enemy, you move it back to its original position. When you respawn the player after they reach a checkpoint, they are moved back to the checkpoint. I'm guessing the enemy spawnpoint is too far from the checkpoint and enemy can't "see" the player any more.

---

As an aside, it is very bad practice to put public variables in your classes. It's much safer/cleaner/easier to debug when you use private/protected variables and access them from other classes using properties. If you need the fields to appear in the inspector, you can use the `[SerializeField]` attribute:

```
//bad
public float moveSpeed;

//good
[SerializeField] private float moveSpeed;
public float MoveSpeed { get => moveSpeed; set => moveSpeed = value; }

```
> 2 votes

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


# Question
Title: Unity2D Sprite gone / not visible when flipped using Vector3.x
I have create game object with code

```
using UnityEngine;
using System.Collections;

public class CharacterBehaviour : MonoBehaviour {

private bool facingRight = true;
private float moveDirection = 0;
private Rigidbody2D theRigidbody2D = null;

void Start ()
{
    theRigidbody2D = GetComponent<Rigidbody2D>();
}

void Update ()
{
    moveDirection = Input.GetAxis("Horizontal");
}

void FixedUpdate()
{
    theRigidbody2D.velocity = new Vector2(moveDirection * 5, theRigidbody2D.velocity.y);

    if (moveDirection > 0 && !facingRight)
        Flip();
    else if (moveDirection < 0 && facingRight)
        Flip();

}

void Flip()
{
    facingRight = !facingRight;
    Vector3 scale = transform.localScale;
    scale.x *= -1;
    transform.localScale = scale;
}
}

```

and using the material as shown below

In game while not facing left / while the game object is facing right :

But while the game object is not facing right / while the game object is facing left :

\*The camera is follow the game object, so that's why i surround the camera with yellow rectangle

the question is, how can i fix this ? how can i fix the sprite to not gone even facing left state, or maybe any suggestion / method to do this ?

---

**EDIT \[ HOW TO SOLVE THIS \]**

From the answer below, Fuzzy Logic told me to create 2-sided mesh / rectangle, or in this case maybe the sprite, but i have a problem there, then i try to create 2-sided shader from the orignal "Legacy Shaders/Transparent/Bumped Specular" and rename to "Legacy Shaders/Transparent/Bumped Specular 2 sided" with just adding a line of code:

```
Cull Off

```

after

```
SubShader {
    LOD 400

```

If you need full of shader code, you can download it here.

# Answer
> 2 votes
You need to flip the texture, not the object. Sprite/Plane meshes are one-sided so if you flip the actual object, you are seeing the back of it, which is transparent.

Edit: You could also make your mesh two-sided. But Unity doesn't provide a flat, 2-sided rectangle. You will have to make it, either in a modelling program or with code.

# Answer
> -1 votes
One way I can try to assist in the resolution (given I am fairly new to programming) is to just use an animation of the character flipped the other way, in my case my character is just a square moving through space so its easier for me, if not then my appologies.

---
Tags: 2d, sprites, unity, materials
---


# Question
Title: How to calculate a direction that will turn a parent so that a locally-rotated child is faced in a given direction?
Imagine an old sailing ship with cannons: they're pointed out at 90° angles from the ship's hull, so in order to fire them, you have to turn the whole ship so that the cannons are pointed at the target. I'm hoping to figure how to calculate "where to point the ship so that the cannons are aimed correctly," but for any possible cannon-angle (not just 90°) in 3D space.

I'm an experienced dev but a total 3D newb, so this vector stuff is wrinkling my brain. This is what I have right now, calculated from the child's (cannon's) gameObject:

`Vector3 directionToAim = (transform.localRotation * (transform.position - target.position)).normalized;`

It's working for side-facing weapons (like the sailing ship), but for forward-facing weapons it turns the parent in the opposite direction, directly away from the target. If I invert it to (target.position - transform.position) the forward-facing weapons work fine, but the side-facing weapons face the opposite way.

Also, my vague understanding is that it's better to use Quaternions for this, rather than Vector3, is that right? Can someone help me grasp how these parent/child rotations can be calculated?

# Answer
Your answer leaves out the step of actually applying the direction-to-aim to the parent. Depending on how you use `directionToAim`, the parent (ship) might roll (stop being upright).

A slightly simpler solution, which is immune to roll in most cases:

```
//Get the rotation we would apply to the child to make it look at the target
Quaternion rotation = Quaternion.LookRotation(target.position - child.position, Vector3.up);
//Apply this rotation to the parent's rotation (rotate the parent so that the child faces the target)
parent.rotation = rotation * Quaternion.Inverse(child.localRotation);

```
> 1 votes

# Answer
Apparently I needed to invert the quaternion localRotation. The final answer looks like this:

```
Vector3 targetDirection = (target.position - transform.position).normalized;
Vector3 directionToAim = Quaternion.Inverse(transform.localRotation) * targetDirection;

```

Hope it helps anyone else wrestling with this!
> 0 votes

# Answer
You can first determine the direction of the aim.

Vector3 mainDirection = ship.transform.position - aim.position;

Then you can calculate the angle between cannons vector and the mainDirection vector. And this will be the angle that ship should be rotated in order to make cannons point in the correct direction.
> -3 votes

---
Tags: unity, 3d, rotation, quaternion
---


# Question
Title: How to get Unreal find headers needed for my code to work?
I am trying to open a dialog to select files under UE4, using OpenFileDialog.

I added this to my build.cs

```
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "DesktopPlatform" });

```

In my header:

```
#include "IDesktopPlatform.h"
#include <Developer\DesktopPlatform\Private\Windows\DesktopPlatformWindows.h>

```

Second line suggested by IntelliSense...

I am adding dummy values to my code to start with:

```
void AFileDialogOpenerActor::OpenFileDialog() {
    FString defaultFile = "";
    FString fileTypes = "";
    TArray<FString> outFileNames;
    uint32 flags = 1;
    FDesktopPlatformWindows fpl;
    fpl.OpenFileDialog(0, dialogName,defaultPath, defaultFile, fileTypes,flags, outFileNames);
}

```

When I try to compile, I get these linker error messages:

If I replace the above includes in the header to these:

```
#include "IDesktopPlatform.h"
#include "DesktopPlatformWindows.h"

```

In message log:

```
cannot open include file: "DesktopPlatformWindows.h" no such file or directory

```

If I play around with these includes, I get a mixture of these messages.(Either a linking error, either no such file, or the bunch of linking error messages) I took a look at containing folders of the headers and they are indeed there and public.

# Answer
After some searching I found this:

I my header I changed the includes to this:

```
#include "DesktopPlatform/Public/IDesktopPlatform.h"
#include "DesktopPlatform/Public/DesktopPlatformModule.h"

```

In the cpp:

```
IDesktopPlatform* fpl = FDesktopPlatformModule::Get();
fpl->OpenFileDialog(0, dialogName, defaultPath, defaultFile, fileTypes, flags, outFileNames);

```

It looks like, I only needed a path to that header...
> 1 votes

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


# Question
Title: Is it a bad idea to store all textures in linear color-space?
I am wondering about the performance behind color-space conversions for textures during reading.

If a project decides to go with a linear workflow, as in, when doing any sort of color manipulation, like lighting, they operate on within the linear color-space, is there any good reason to not store all texture assets in the linear color-space?

My understanding is that when loading textures which are stored in sRGB, the GPU can do the conversion to linear for you very quickly. Is that cost completely negligible? Why not just store all the textures in that form?

The only reason I can think against this is that you may want to store the textures in a color-space that looks like the one you intend to display to (if you're going to display to sRGB then you should store the textures in sRGB). In that case, why not master the texture as sRGB but then store them on disk already converted to linear colorspace?

# Answer
You would need a higher bit-depth to achieve the same quality if you store the textures in linear. See https://en.wikipedia.org/wiki/Gamma\_correction#Explanation.

Is the cost of the conversion completely negligible? I don't know but I've read that it is very cheap on current GPUs. You could try profiling to find out.
> 1 votes

---
Tags: performance, color
---


# Question
Title: Making pickup objects with gravity that won't push the player on collision
I am trying to create pickups, that appear after an enemy dies, and that the player can pick up, but I am running into some issues.

First of all, I want the pickups to be affected by gravity, so I need a rigidbody2d and a boxcollider2d (non-trigger), so this works.

Now, if I want to collect the pickups on contact, I need to make the layers for the loot and the player get in contact, so that they can interact.

Now, of course, I do not want to push the pickups around. I want to actually pick them up when I touch them, but the collider is not a trigger so I thought I would use OnCollisionEnter to handle this.

```
        void OnCollisionEnter2D(Collision2D other)
        {
            var loot = other.gameObject.GetComponent<ILoot>();

            loot?.PickUp(gameObject); // Destroys also the pickup
        }

```

While this works, I am still using a non-trigger collider, which means that there are some physics effects that are not desired. For instance, when I "jump" onto the pickups.

Notice the subtle, but still present, slowdown in the fall, when the player enters in touch with the pickups?

How could I solve this issue??

# Answer
Set the pickup to be on a layer that interacts with the ground only, not the player character.

Give your player character a child object that represents their collection radius. Give it a trigger collider, and set just this child object to be on a layer that interacts with the pickups, leaving the root of your player character on its original layer.

Now your player character will get `OnTriggerEnter2D` messages when they walk close enough for their child trigger collider to touch the pickups' solid colliders, but your player can still pass through the pickups because they don't interact with the player's solid collider.

As a bonus, you can use this child object to precisely control the pick-up radius independent of your character's normal collision size, or implement buffs like magnetically attracting pickups from further away.
> 3 votes

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


title: Unity data sampling rate

text:
# Question
Title: Unity data sampling rate
I'm using the Unity as a physic simulation and I want to gather the data of object position from it. So I put my code about random the force and apply to that object. Also the part that Write the data into .csv format file. The sampling rate that I need is about 360Hz then i decided to set the FixedUpdate to 1/360 ~= 0.002777778. But once i use the DateTime to measure the sampling rate, The unity give the number of points(In my understanding is the number of time date FixedUpdate() have been run because file writing is also in FixedUpdate(). The sampling rate kinda jump between 210 to 410. Please correct me if i'm wrong using this way.

\[#Note : I don't care about the low framerate because i just need the position from unity's Physx\]

Here's my Time settings.

Here's my code to get the current time.

```
void Start()
{
...
DateTime startTime = DateTime.UtcNow;
DateTime currentTime = DateTime.UtcNow;
...
}

void FixedUpdate(){
...
WriteData()
PhysicsUpdate()
...
currentTime = DateTime.Utc.Now
print("#N Data : " + t + ", Elapsed time : " + (currentTime - startTime));

```

Here's my results that show the jumping of sampling rate : The sampling rate each passing second periods are 223, 395, 392, 362 (This should close to 360 Data points)     Thank you.

# Answer
A common misunderstanding about FixedUpdate is that it runs with a regular rhythm in real time / wall time. ie. that Unity is watching the clock like a hawk, and when the real-time moment for the next FixedUpdate comes around, it puts everything on hold and immediately runs FixedUpdate on that exact moment, then waits for the next moment again.

This is not what this method promises.

Unity runs FixedUpdate with a regular rhythm in *game time*. At the start of each frame, Unity measures how much game time should have elapsed since last frame, and runs FixedUpdate and the physics step back-to-back some number of times to catch up, advancing the game time in fixed increments with each step.

So, from the perspective of game time, FixedUpdate occurs with perfect regularity. That's how it lets us create consistent game simulations.

From the perspective of the player, who sees the end result after all the catch-up has been done for the frame, the result is a pretty good illusion of consistent frequency. They might observe a judder due to "loose change" time (a bit of extra time has elapsed since the last FixedUpdate, but not enough to run the next FixedUpdate), but this is usually fixable with interpolation. They can also observe slowdown/lag, if the hardware is overloaded and not able to run the updates fast enough for game time to keep pace with real time. This affects the play experience, but not the underlying consistency of the simulation, which still maintains its exact regular frequency in game time.

But you're counting your FixedUpdates with respect to wall time. In wall time, FixedUpdates occur in bursts, generally *after* their "scheduled time", as the engine plays catch-up at the start of each frame to reach where the simulation should be for the next frame. Especially if your frames are running long because you're asking Unity to do hundreds of physics steps per second, the exact time when those steps are computed will have less and less correlation with the matching wall clock time.

If only the simulation log output matters, then you don't care about when those calculations happened in real time. You just need to know when it occurred within the simulation timeline. So you should be measuring `Time.time` instead of `DateTime.Utc.Now`. Or, if 32-bit floating point precision isn't enough for you, you can make your own timer variable that you increment by your fixed timestep in `FixedUpdate`, to measure your simulation time at any precision you like.
> 2 votes

---
Tags: unity, c#, physics-engine, time
---


# Question
Title: Some UI button script not working in apk build!
There are a lot of posts regarding this problem in various website and even in this one but no one has given a feasible solution to this problem. I have a button that has a custom sprite. I also have a custom script attached to that button which when pressed down (`IPOINTER DOWN`) changes the color of particular sprite renderer. All this works in pc but not on apk build. Why? I have two canvas, so I thought there might be raycasting issues, so I disabled one but still no luck. The buttons are in world space in canvas. So, I thought I might not use a canvas but `IPointer` only works on clickable UI elements.

The scene looks like this, star is the clickable button and the borders are a sprite(district).

The script attached to the button is:

```
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;// Required when using Event data.

public class OnHighlighted : MonoBehaviour, IPointerClickHandler, IPointerDownHandler// required interface when using the OnPointerEnter method.
{
    // HoldByeach button

    private GameObject correspondingImage;

    void Start ()
    {
        correspondingImage = GameObject.Find(gameObject.name);
    }

    public void OnPointerClick(PointerEventData pointerEventData)
    {
        GetComponent<Image>().color = new Color32 (36,53,53,255);
        correspondingImage.GetComponent<SpriteRenderer>().color= new Color32 (36,53,53,255);
    }

    public void OnPointerDown(PointerEventData pointerEventData)
    {
        GetComponent<Image>().color = new Color32 (47,255,0,255);
        correspondingImage.GetComponent<SpriteRenderer>().color = new Color32 (47,255,0,255);
    }
}

```

# Answer
In your `Start()` function you do this:

```
correspondingImage = GameObject.Find(gameObject.name);

```

First of all, `GameObject.Find()` is extremely sloppy and you should never use it. Second, this tells the script to find the GameObject with the same name as the GameObject that the script is attached to. This makes no sense, as it's likely to return the same GameObject, which you already have a reference to.

```
void Start() {
    correspondingImage = GameObject.Find(gameObject.name);
    print(correspondingImage == gameObject); //should print "true"
}

```

The exception is if you have multiple GameObjects in the scene with the same name; if you do, you definitely should not be trying to find them with `GameObject.Find()`! It's possible that the one that is found in the Editor is not the same as the one that is found in the Android build.

You should use direct references to your objects when possible:

```
[SerializeField] SpriteRenderer correspondingImage; //we can set this from the inspector

void Start() {
    Assert.IsNotNull(correspondingImage);
}

```

This will improve performance, because Unity doesn't have to search the scene for a particular object, and also is less likely to break.
> 0 votes

---
Tags: unity, ui-design
---


# Question
Title: Update Project Version, or other Project Settings, from command line
### Is it possible to update UE4 Project Settings from command line?

More specifically I would love to be able to update the following Project Settings attributes from command line using, for instance, `RunUAT.bat`

* Project \> Description \> `Project Version`
* Platform \> Android \> `Store Version`
* Platform \> Android \> `Version Display Name`
* Platform \> IOS \> `Version Info`

I have checked the unreal documentation without finding anything, and looked through the documentation for ue4 cli, also without any luck.

I have already tried to read the `Config/DefaultEditor.ini` file (and other INI files) using various tools, but apparently the INI format used by UE4 is somehow different than what the parsers I have tested accepts. (`+`-icons for indicating array elements and so on)

Am I missing something obvious? Or is this not normal to do?

---

Running from Windows, MacOS, or Linux (whichever will work)

# Answer
> 2 votes
You could write your own script to update the files. Here is a python example to update lines in the DefaultGame.ini

```
import fileinput
import sys

defaultGameFilePath = 'Config/DefaultGame.ini'
stagingDirectory = 'path/you/want'

for line in fileinput.input(defaultGameFilePath, inplace=True):

    key = line.strip().split("=", 1)[0]

    if key == "StagingDirectory":
        print(key + "=(Path=\"" + stagingDirectory + "\")")
    else:
        print('{}'.format(line), end='')

```

This will not modify arrays +/-, you will have to extend the script for that. I also had trouble using third party ini packages. Unreal ini files do seem to have their own unconventional format.

---
Tags: unreal-4
---


# Question
Title: How to make camera move with the player in 3D Libgdx
Iam trying to create a 3D game in Libgdx, so I created a 3d World with physics, and added just a small terrain and capulse (the Player) .

I want to make the game first person, so I created a player class and managed to move the player (Capulse) by joystick.

Like this :-

```
@Override
    public void create() {
        // load enviroment
        environment = new Environment();
        environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
        environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
        // setup camera
        cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        cam.position.set(10f, 10f, 10f);
        cam.lookAt(0, 0, 0);
        cam.near = 0.001f;
        cam.far = 3000f;
        cam.update();
        // setup controller for camera
        camController = new CameraInputController(cam);
        Gdx.input.setInputProcessor(camController);
        // load the models
        assets = new AssetManager();
        assets.load("ground_stairs.g3db", Model.class);
        assets.load("gathering_node.g3db", Model.class);
        loading = true;
        modelBatch = new ModelBatch();

        // setup bulletphysics
        Bullet.init();
        collisionConfig = new btDefaultCollisionConfiguration();
        dispatcher = new btCollisionDispatcher(collisionConfig);
        broadphase = new btDbvtBroadphase();
        constraintSolver = new btSequentialImpulseConstraintSolver();
        dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, constraintSolver, collisionConfig);
        dynamicsWorld.setGravity(new Vector3(0, -10f, 0));
        contactListener = new MyContactListener();
        loadPlayer();

    }

    private void loadPlayer() {

        // setup player/camera movement
        pc = new PlayerController(instances,cam,dynamicsWorld);
    }

    private void doneLoading() {
        loading = false;
        onDoneLoadingStatic("ground_stairs.g3db", GROUND);
        onDoneLoadingStatic("gathering_node.g3db", GATHERING_NODE);
        gatheringNode = instances.get(instances.size() - 1);
    }

    public btRigidBody onDoneLoadingStatic(String fileName, int id) {
        Model model = assets.get(fileName, Model.class);
        ModelInstance instance = new ModelInstance(model);
        instances.add(instance);

        btBvhTriangleMeshShape shape = new btBvhTriangleMeshShape(instance.model.meshParts);
        btRigidBody body = new btRigidBody(0, null, shape, new Vector3(0, 0, 0));
        body.proceedToTransform(instance.transform);
        // set id to find with collision detection
        body.setUserValue(id);
        dynamicsWorld.addRigidBody(body);

        return body;
    }

    @Override
    public void render() {
        if (loading && assets.update()) {
            doneLoading();
        }
        camController.update();

        pc.update();

        final float delta = Math.min(1f / 30f, Gdx.graphics.getDeltaTime());
        dynamicsWorld.stepSimulation(delta, 5, 1f / 60f);

        Gdx.gl20.glClearColor(0, 0.5f, 1, 1);
        Gdx.gl20.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
        modelBatch.begin(cam);
        modelBatch.render(instances, environment);
        modelBatch.end();
    }

    @Override
    public void dispose() {
        modelBatch.dispose();
    }

    private class MyContactListener extends ContactListener {

        @Override
        public void onContactStarted(int userValue0, int userValue1) {
            if (userValue0 == PLAYER && userValue1 == GATHERING_NODE) {
                ((ColorAttribute) gatheringNode.materials.first().get(ColorAttribute.Diffuse)).color.set(Color.RED);
            }
            if (userValue0 == PLAYER && userValue1 == GROUND) {
                PlayerController.canJump = true;
            }
        }

        @Override
        public void onContactEnded(int userValue0, int userValue1) {
            if (userValue0 == PLAYER && userValue1 == GATHERING_NODE) {
                ((ColorAttribute) gatheringNode.materials.first().get(ColorAttribute.Diffuse)).color.set(Color.BLUE);
            }
        }
    }
}

PlayerController

public class PlayerController
 {
    private btRigidBody playerBody;
    private ModelInstance player;
    private float speed = 1f;
    public static boolean canJump = true;
    private PerspectiveCamera cam;
    private List<ModelInstance> instances = new ArrayList<ModelInstance>();
    private static final int PLAYER = 1;
    public static float xposition;
    public static float yposition;
    private btDynamicsWorld dynamicsWorld;
    public static float angleX;

    public PlayerController(List<ModelInstance> instances,PerspectiveCamera cam,btDynamicsWorld dynamicWorld) {
        this.instances = instances;
        this.cam = cam;
        this.dynamicsWorld = dynamicWorld;

        player = new ModelInstance(new ModelBuilder()
                                   .createCapsule(0.25f, 3, 10, new Material(ColorAttribute.createAmbient(Color.BLACK)), Usage.Normal | Usage.Position)
                                   );
        player.transform.translate(5, 7, 0);
        instances.add(player);
        // load player rigid body
        btCapsuleShape playerShape = new btCapsuleShape(0.25f, 2.5f);
        float mass = 10;
        Vector3 localInertia = new Vector3();
        playerShape.calculateLocalInertia(mass, localInertia);
        playerBody = new btRigidBody(mass, null, playerShape, localInertia);
        playerBody.proceedToTransform(player.transform);
        playerBody.setCollisionFlags(playerBody.getCollisionFlags() | btCollisionObject.CollisionFlags.CF_CUSTOM_MATERIAL_CALLBACK);
        // set id to find with collision detection
        playerBody.setUserValue(PLAYER);
        dynamicsWorld.addRigidBody(playerBody);

    }

    public void update() {
        // make sure to activate the player body so bullet doesnt put it to sleep
        playerBody.activate();
        // prevent the capsule from falling over
        playerBody.setAngularFactor(new Vector3(0, 0, 0));
        playerBody.getWorldTransform(player.transform);

        Vector3 velocity = new Vector3(0, playerBody.getLinearVelocity().y, 0);
        velocity.x = xposition;
        velocity.z = yposition;
        player.transform.rotate(Vector3.Y,angleX);

        cam.update();

        playerBody.setLinearVelocity(velocity);

    }
}

```

And this is the output :-

Now I want the camera to be at the top of the player (the Capulse) , and move with the player, so I added this

```
cam.position.add(velocity);

```

In update method in PlayerController

And this the output : just a blue screen So, my question how to make the camera move we it the player like first person?

# Answer
Solved : I added this line in update method of player controller

```
cam.position.set(player.transform.getTranslation(new Vector3()));

```

Now the camera move with the player, but I can't now make it rotate with the player.
> 0 votes

---
Tags: java, libgdx, android, first-person-shooter
---


# Question
Title: Unity - movement code overriding rigidbody mass?
Unity noob here...

I have a basic movement script, but whatever I set the objects mass at it still falls the same speed, floating down off ramps instead of sticking to the floor.

I saw some posts referencing that the movement translate can override the rigidbodys downward velocity. Well I tried several code adjusts but I couldn't get it to work correctly.

```
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");

// this code is to keep movement direction when switching to alternate camera
if (Input.GetButtonDown("Horizontal") || Input.GetButtonDown("Vertical")) {
    viewForward = Vector3.Scale(Camera.main.transform.forward, new Vector3(1, 0, 1)).normalized;
    viewRight = Vector3.Scale(Camera.main.transform.right, new Vector3(1, 0, 1)).normalized;
    viewRight = new Vector3(viewForward.z, 0f, viewForward.x * -1f);
    }

moveDirection = v * viewForward + h * viewRight;
if (moveDirection != Vector3.zero) {
    // moveDirection.y = rb.velocity <-- not working
    transform.position += moveDirection * Time.deltaTime * moveSpeed;
    transform.rotation = Quaternion.LookRotation(moveDirection);
    }

```

Could someone point out what I'm doing wrong?

# Answer
> whatever I set the objects mass at it still falls the same speed

That's how gravity works. Gravity is a constant rate of acceleration and is not affected by mass. In real life, rate of descent may be slowed by air resistance.

I don't fully understand what you're trying to do with your movement code (move object relative to the camera?), but it doesn't seem like the cleanest way to do what you want. Does the object fall as expected if you aren't giving any horizontal or vertical input?

You might want to reorganize it like this:

```
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");

// this code is to keep movement direction when switching to alternate camera
if (Input.GetButtonDown("Horizontal") || Input.GetButtonDown("Vertical")) {
    viewForward = Vector3.Scale(Camera.main.transform.forward, new Vector3(1, 0, 1)).normalized;
    viewRight = Vector3.Scale(Camera.main.transform.right, new Vector3(1, 0, 1)).normalized;
    viewRight = new Vector3(viewForward.z, 0f, viewForward.x * -1f);

    moveDirection = v * viewForward + h * viewRight;
    if (moveDirection != Vector3.zero) {
        // moveDirection.y = rb.velocity <-- not working
        transform.position += moveDirection * Time.deltaTime * moveSpeed;
        transform.rotation = Quaternion.LookRotation(moveDirection);
    }
}

```
> 0 votes

# Answer
The mass doesn't affect the speed that has the object when it's falling, but if you want to increase or decrease the air resistance, you have to modify the parameters "Drag" and "Angular Drag" of the rigidbody.

A higher value of this parameters, means, a high air resistance, also, if you want the object to fall with more speed, you can add force downwards at the object, like this:

```
float force = 100f;
rigidbody.AddForce(-Vector3.up * force);

```
> 0 votes

---
Tags: unity, rigidbody
---


# Question
Title: What is transmitted over the network during multiplayer first person shooter games?
In games like Half-Life 2, Team Fortress 2 etc, when you play against other players online, your local game communicates with a game server.

If you've built one of these games, what sort of information is sent by your local game to the game server, and what sort of information is sent to you by the game server?

I recall reading that in Team Fortress 2, the computer tracks the trajectory of every projectile including every bullet, rocket. It seems like that would generate a tsunami of messages, yet my game works reasonably well over distinctly average broadband.

I've noticed gaps in the magician's curtain when severe lag occurs. Sometimes other players "teleport"; they're not where I think they are. Other times, I can peer around a corner and be killed when there's no-one there; except shortly after I see the other victorious player.

So roughly, what is being communicated over the network to create the illusion of real time?

I'm generally interested in simulation games but have never built one. I'm just trying to get a feel for how it's done.

Let's start with

* The position x, y, z, speed, and direction of every player.
* Player switches weapon
* Player fires/stop firing.

# Answer
> 1 votes
I have not implemented a network strategy myself, but I have already read some related texts and thought about network solutions for my game engine project. So maybe I can give you a small overview.

> I recall reading that in Team Fortress 2, the computer tracks the trajectory of every projectile including every bullet, rocket. It seems like that would generate a tsunami of messages, ...

It isn't really necessary to update everything every frame of your game loop. Many things can be omitted. For example: For a bullet, all you need to know to describe it's movement is the time and direction it was fired and some additional data that influences the trajectory like initial movement speed and external forces (gravity, drag, etc.). With this information, every computer can calculate the current position on its own. They might come to slightly different results due to different time steps, floating-point errors or hardware, but as long as they do not have relevant impacts on the worlds state (hitting a player/destroyable object, change environment states, etc.) it doesn't really matter if the point of impact varies by 2cm between 2 computers. So you just need to sync those projectiles that might affect the game world's global state and only in the time range where this is going to happen.

It is not really that much different for player movements. The player just hits a button at a certain time to trigger an action. It is not like the player is actually controlling every limp himself. His computer calculates the resulting animation state and movements which can be recalculated on every other computer that has the same information. So you just need to know at which time another player performs which action and you computer can more or less predict his movement and animations in the next frames.

Another optimization is to just let the server send data to a player that is actually relevant for him. Something a player can't see and that can't affect him doesn't need to be synchronized. So the server can decide based on the player's location and viewing direction what is relevant for him.

> I've noticed gaps in the magician's curtain when severe lag occurs. Sometimes other players "teleport"; they're not where I think they are. Other times, I can peer around a corner and be killed when there's no-one there; except shortly after I see the other victorious player.

Due to the network latency, all the updates you get from the server arrive usually "too late". You get the information about what another player did a certain amount of milliseconds ago. However, your computer can predict what he is probably doing "now" from that information. There are some techniques to avoid jumps in movements and animations due to getting updates too late.

For example, if you get the information that a player changed his movement 100ms ago and your computer mispredicted it, instead of instantaneously moving him to the correct position you can just speed up his movement into the correct direction so that his position on your computer will be synchronized again a few frames later. Usually, you won't notice the slightly increased speed. Of course, if the latency gets too high (lag), you can't hide such mispredictions anymore and it is probably better to just resync everything with a big jump even though I have seen games where everything turns into turbo mode for a short time.

> If you've built one of these games, what sort of information is sent by your local game to the game server, and what sort of information is sent to you by the game server?

A player only needs to send changes in his direct actions to the server (movements, firing, using stuff). He might send additional data on how his computer predicts the outcome of his actions (who/what did he hit), but this depends on how your network system handles latency related conflicts. The server, on the other hand, only needs to send data to a player that does affect him and what he sees, and that invalidates previous updates the client got.

**Conclusion**

Generally, you only need to update the state of moveable objects over the network if their behavior changes in a way a computer can't predict with the information he has. For example changes in animation state, velocity, movement direction, etc. Additionally, you only need to update the data if it is relevant for the client.

You might also perform resyncs for every object from time to time to avoid obvious jumps due to the accumulation of small prediction errors, but depending on the object and your game this can be done at very low frequencies so that it doesn't affect the network traffic significantly.

# Answer
> 0 votes
It's less a matter of what data is passed, though that which can be made deterministic would be better so, and more a matter of how often that data must be passed.

Michael Abrash talks a bit about perceptual latency reduction:

http://www.jagregory.com/abrash-black-book/#how-we-spent-our-summer-vacation-after-shipping-quake

In the subsection on QuakeWorld.

From personal experience playing HL2DM with another player sitting at my desk, only the larger sub-set of physical objects align, instance to instance. The scrap is primarily for glitz and appears to be randomly perturbed client-side.

On TF2, I doubt very much they are tracking each bullet in any literal sense(rockets are another story). I suspect the bullet is spawned with a directional vector and length(this would be shared over network), and any dynamic object that intersects over a short life-span can be hit-detected. Think laser logic.

In the long run, and the biggest data hog, the real problem is with cheat protection and prevention. Even with a total client-side data set being passed to server, the server would still have to have a complicated rule-set by which it determines the feasible viability of any given client-side state in relativity to the game state as a whole. In this day and age bandwidth is hardly as expensive as server-side processing cycles.

On a final note, and academically interesting, if not directly to your question, Korean shooters, Gunz by MAIET, for example, seem to pass almost nothing to server, and very rarely. They are almost unchanged in behavior by a 120ping. This is self evidently achieved in two ways: One, the other player-characters are, for all intents and purposes, AIs that are bound to the approximate location determined by the opposing-player client, targeting the antagonistic-player avatar that is being targeted, using the correct weapon, and not dead; Point two, player health is extremely fuzzy and plentiful, allowing for a whole lot of slop. That isn't to say these games can't be fun, just apples and oranges to the precision tournament-shooters of old.

Dave Oshry discusses the relative failure that is DuskWorld as well as the laggy hit-detection of the modern-shooter: https://www.youtube.com/watch?v=-FoFXPrEphM

---
Tags: physics, networking, client-server, synchronization
---


title: My HTML canvas keep flickering

text:
# Question
Title: My HTML canvas keep flickering
I'm trying to create a game in HTML canvas, but somehow it keeps flickering, I've taken a look at the tutorial and I perceived that my code is more or less similar. Can anybody help me fix this?

```
var canvas = document.getElementById("screen");
var ctx = canvas.getContext("2d");
var pwidth = 16;
var pheight = 16;
var cwidth = 12;
var cheight = 12;
var mariox = 16;
var marioy = 120;
var tiles;
var marioSprite;

function drawMarioSprite(){
    marioSprite = new Image();
    marioSprite.src = 'file:///C:/Users/User/Desktop/img/characters.gif';
    marioSprite.addEventListener('load', e => {
    ctx.drawImage(marioSprite, 276, 44, pwidth, pheight, mariox, marioy, cwidth, cheight);
    //pic x and y, pic width and height, canvas x and y, canvas width and height
    });
}//drawMarioSprite() end

//draw floor
function draw() {
    tiles = new Image();
    tiles.src = 'file:///C:/Users/User/Desktop/img/tiles.png';
    tiles.addEventListener('load', e => {
        drawTiles();
    });
}
function drawTiles(){
    for (let x = 0; x < 25; x++){
        for (let y = 11; y < 13; y++){
                ctx.drawImage(tiles, 0, 32, pwidth, pheight, x*12, y*12, cwidth, cheight);
        }
    }
}//drawTiles() end

function clear(){
    ctx.clearRect(0, 0, canvas.width, canvas.height);
}
function component(){
    drawMarioSprite();
    draw();
}
function level1(){
    console.log('level1');
    clear();
    component();
}

var inter = setInterval(level1, 1000);

```

# Answer
> 1 votes
Two things need to be improved in your code:

1. Preload images
2. Use `requestAnimationFrame` instead of `setInterval`

Demo:

```
console.clear();
const INTERVAL = 16; //16 ms animation interval
const src = "https://www.c00lsch00l.eu/Games/AA/BulletOrbRed.png";
var CTX = document.getElementById("myCanvas").getContext("2d");
console.log(CTX);
var frame = {
  start: null,
  delta: null,
  count: 0
};

var img = new Image();
img.onload = function () {
  run(test.bind(null, CTX, img));
};
img.src = src;

function run(func) {
  if (!frame.start) frame.start = performance.now();
  frame.delta = performance.now() - frame.start;
  if (frame.delta >= INTERVAL) {
    func.call();
    frame.start = null; //reset
    frame.count++;
  }
  //for this example the loop will be repeated only 100 time
  if (frame.count < 100) requestAnimationFrame(run.bind(null, func));
  //without counting limit
  //requestAnimationFrame(run.bind(null, func));
}

function test(CTX, img) {
  //simple function for demonstration
  // avoid using console in animation loop, except for debugging
  // console operations are very slow
  console.log(`${frame.count}`);
  draw(CTX, img);
}
function draw(CTX, img) {
  CTX.clearRect(0, 0, CTX.canvas.width, CTX.canvas.height);
  CTX.drawImage(img, frame.count, frame.count);
}
```

```
 <canvas id="myCanvas" width="200" height="200"></canvas>
```

It's a very simple example; first we waited that image was loaded. Then the function run was executed, providing a simple animation, and a a count of frame in the console. Together with code comments this should provide some basis for further learning.

# Answer
> 0 votes
While Lovro's answer is solid, it's worth adding, having had this problem myself, that almost nothing will fix that kind of brute-force tile blitting behavior if there are too many pixels being pushed.

I once resorted to a software rasterizer so that I could blit the whole image in one call(mostly worked :) ).

I think most 2D Canvas games still use static backgrounds for this reason(dirty rectangles and what).

---
Tags: javascript, html-canvas, html
---


# Question
Title: How can I change the default New Project directory in Godot Engine?
When I go to create a new project in Godot Engine (version 3.2) my Project Path is always the original default directory, no matter what path I last used. There doesn't appear to be any configuration inside the Project List window. How can I change the default project path for new projects?

# Answer
This setting is inside the project editor, so you'll first need to create or open a project. Then:

1. From the toolbar, open Editor Settings

2. In the sidebar of Editor Settings, go to Filesystem → Directories. From there you'll be able to set the **Default Project Path** to whatever you'd like:
> 12 votes

---
Tags: godot
---


# Question
Title: Why do I get "UObject" has no member "BeginPlay" errors?
I loaded up UE4 to work on a new project. I created two C++ classes, one for a bullet, one for a cannon. Upon loading into Visual Studio 2015 I immediately get the error:

> "UObject" has no member "BeginPlay"

Keep in mind I have not written a single line of code. This error just popped up. I have not written a single comment, a single variable, I don't even get to enter some white space so that I have room for new code. I just get the error. I tried remaking the project with different settings (like a blank project, third person, et cetera) and I keep getting that error.

# Answer
> 4 votes
> "UObject" has no member "BeginPlay"

That's because `UObject` *doesn't* have a `BeginPlay` member. `BeginPlay` comes from `AActor`.

It sounds like your bullet class just tries to inherit `UObject` directly, instead of `AActor`. If you want to make an actor subclass, your class needs to look like:

```
UCLASS()
class ABullet : public AActor {
  ...
}

```

Then you can implement `BeginPlay`, and call it on instances of your `ABullet`. User-error or possibly a bug in the C++ class creator in Unreal could have generated the type with the wrong base class as well, as it sounds like you didn't manually type it in.

---

Getting the error "immediately" suggests it's an error by the Intellisense parser, which... isn't really well suited to Unreal's massive codebase. It will often produce false positives and as such you may want to consider disabling the Intellisense feature that tries to pre-emptively pop-up errors and provide red squiggly underlines.

Unreal's unity compilation module will generally cause the headers for `AActor` to be pulled in for you, but if you're not using the unity builds or if Intellisense still refuses to co-operate (since it will not understand the unity builds) you can sometimes appease it by explicitly adding an `#include "AActor.h"` to the top of the file.

# Answer
> 1 votes
This is a weird intellisense bug that in my case started happening when I added this include to my header file:

```
#include "PhysicsEngine/PhysicsHandleComponent.h"

```

What fixed it was a mix of 3 things I believe:

1. I deleted extra blank lines between my last include statement and my first line of code so that there is only ONE blank line between them. I changed from this:
to this:
2. I deleted spaces at the end of include statements. Sometimes when you copy paste include statements from the Unreal docs it adds extra spaces or new lines at the end, just make sure you delete those.
3. I reordered the include statements in my file. You might have to keep tweaking the order of your include statements until it gets fixed since I couldn't find a specific pattern that fixed it. The only thing I can say is make sure that `generated.h"` is at the bottom, and if you use `CoreMinimal.h` make sure it's at the top. Then tweak the order of what's in between.

In my case it was just an intellisense problem though so you would still be able to compile without errors if it's the same cause.

In this thread other people seem to also experience the issue being caused by the include statements

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


title: GameObject LookAt not aligning properly

text:
# Question
Title: GameObject LookAt not aligning properly
I have a celestial sphere with a plane in the centre and spheres (stars) aligned around the centre with a fixed radius.

In order to show the stars visible from a certain latitude and longitude from Earth, I need to rotate the plane accordingly.

To rotate the plane properly, I converted the latitude and longitude into 3D vectors, then utilised the `LookAt()` method to point the plane at this vector.

The following is the code which calculated the vectors from the coordinates, and utilises the `LookAt()` Method:

```
public void positionLand(double latitude, double longitude)
{
    double latitude_rad = (math.PI / 180) * latitude;
    double longitude_rad = (math.PI / 180) * longitude;

    Vector3 markerPositioning = new Vector3();
    markerPositioning.x = (float)-((math.cos(latitude_rad)) * (math.cos(longitude_rad)));
    markerPositioning.y = (float)((math.cos(latitude_rad)) * (math.sin(longitude_rad)));
    markerPositioning.z = (float)((math.sin(latitude_rad)));

    groundPlane.transform.LookAt(markerPositioning);
}

```

To test if this would work, I used the coordinates of London, UK, latitude: 51.509865 and longitude: -0.118092. And this was the result:

With the `LookAt()` method changed to the following: `groundPlane.transform.LookAt(markerPositioning, Vector3.forward);`

This is the result:

Replacing `groundPlane.transform.LookAt(markerPositioning);` with `groundPlane.transform.up = markerPositioning;` results in the following:

As you can see, the plane is not properly rotating. Initially, I thought maybe the `LookAt()` method is using the incorrect forward vector of the plane gameobject, but this isn't the case as there is no connection between the way the plane rotated and the coordinates of London as the plane is near vertical at 89 degrees.

What am I doing wrong and how can I fix this?

# Answer
Your spherical coordinate functions are written for a z-up coordinate system. Unity is a y-up coordinate system.

You want something more like this (assuming the prime meridian faces z+):

```
normal.x = - Mathf.Cos(latitude_rad) * Mathf.Sin(longitude_rad);
normal.y =   Mathf.Sin(latitude_rad);
normal.z =   Mathf.Cos(latitude_rad) * Mathf.Cos(longitude_rad);

transform.up = normal;

```

Or, as a one-liner, letting Unity handle the trig for you:

```
transform.localEulerAngles = new Vector3(90f - latitude_deg, -longitude_deg, 0);

```
> 0 votes

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


# Question
Title: Game Physics: Calculating a collision response using the Separating Axis Theorem?
I am working on a project in which I have implemented the Separating Axis Theorem to detect collisions between objects. My current collision response is an object that contains whether it is overlapping and what the minimum translation vector (MTV) is.

I then take the MTV and add it to the linear velocity of the object we're testing. This all works fine. However, I want to add rotational forces to the object based on the collision. For this, I imagine we will need two things:

* The Minimum Translation Vector, which represents the force
* A contact point, which is the point at which the MTV-force gets applied to the object

However, I have been struggling with calculating the contact point for the past two/three days. I haven't been able to find good resources on this, unfortunately.

How would I go about calculating a suitable collision response as I described? Thank you very much!

# Answer
> 1 votes
I will assume this question is about 3D SAT which I find has alot less resources than 2D..

I have been struggling with this for the past week. I have face contacts down but not Edge cases.

When you are testing your various axes keep track of which has the minimum overlap, that is your contact normal and penetration depth.

Contact points are where it gets interesting, depending on how you have the Axes to test setup you can determine what *type* of collision has occured (i.e Face to Vertex, Edge to Edge).

When you are testing the face normals of Object A and Object B and one of them happen to be the axis with the minimum depth penetration, that is a Face contact. If it is one of the edge pairs axes that has the minimum depth penetration, it is an Edge contact.

To find the Contact point for a Face contact I used an algorithm that tests if a point is inside a cube (which is easier than it sounds if you have the dimensions of a cube on hand). The algorithm is as follows:

1. Calculate the vector from a worldspace vertex of Object A to the center position (should also be worldspace) of Object B.
2. if the Dot product of that Vector with 3 Face Normals of Object B is within the range of the size of the Object B, then that vertex is inside of B and thus is a contact point.
3. Loop through the rest of the verticies of Object A.

I recommend you do the same algorithm for Object B since there can be contact points from both objects in some situations. (Also this algorithm can be optimized, meaning you dont have to test all 8 verticies of a Cube but I'll leave that for you cause I'm still ironing that out lol.)

When it comes to the actual collision response, theres even less resources out there on that I find. I recommend looking at Ian Millington Game Physics Book edition 2 for his flavor of collision response.

I hope this helps in anyway! P.S if anyone knows how to do edge cases let me know, That is a battle im currently undergoing.

edit: wow this was asked 4 years ago. Well I hope you found a solution before this.

---
Tags: collision-detection, physics, collision-resolution, separating-axis-theorem, torque
---


# Question
Title: How do you prevent your JavaScript / HTML5 web game from being copied or altered?
I'm in the middle of planning a game built using JavaScript and HTML5.

I'm having trouble understanding how you could prevent someone from simply copying the JavaScript from the web server and either making their own game with it (not my biggest concern), or substituting their own JavaScript functions and dashing any hope for reliable clients in the wild if the game was to eventually support multiplayer.

Can anything be done to prevent just anybody from reading the JavaScript?

If not, should all game processing be taking place on a server somewhere with the client's only responsibilities being capturing user input and drawing graphics?

# Answer
Keep all your game data and logics on the server. Part of the game which is on the client side can be copied using appropriate tools anyway (even if it's in Flash or Java), so just accept it and don't care too much about it.

To keep your javascript less copyable, because of bad readability, you can minify it. That's a good practice anyway as it makes the gaming site download faster.
> 49 votes

# Answer
> how you could prevent someone from simply copying the JavaScript from the web server and either making their own game with it (not my biggest concern)

This is where the law helps. In practice this doesn't seem to happen very often.

> or substituting their own JavaScript functions and dashing any hope for reliable clients in the wild if the game was to eventually support multiplayer.

There are no reliable clients in the wild, for exactly this sort of reason. Give up on this dream now. :)
> 12 votes

# Answer
Just as everyone else has recommended; keep as much code as possible server-side.

A method I have used to deal with code copying is a bit odd, but it has worked well so far.

* Server-side, generate unique id and store it for later.
* Server-side, add unique id in script element during html rendering.
* Client-side, create a WebSocket connection and pass the unique id to the server.
* Server-side, match id against current list.
* If match is not found, close connection.
* If match *is* found, replace message handler with your "proper" one and discard id.
* Stream your secret code to client as JSON, {"func":"function(){dostuff();}"}
* Client-side, watch for messages, if they contain "func", eval it.

Now your secret code is executing client-side and won't show up in view-source or inspectors/consoles. There is still ways to get at the code, but it's quite a bit more difficult.
> 8 votes

# Answer
The only way to be reasonably certain that your game code will be secure is to build a client/server type of game and put as much code as you can on the server. And of course, make that server secure!

The main issue is that if code is running on my computer, I can inspect it, decompile it, and figure out how it works. This is true for JavaScript, Flash, C++, anything else. In fact, in MMO development (which is where the bulk of my professional experience is) the assumption from the very beginning is that the client is compromised: whatever you have written for the client is already in the hands of whoever wants it, malicious or not.

Minifying code does provide a tiny amount of protection against people who are too lazy to unminify it using one of the many tools out there. (But production code *should* be minified to reduce its data footprint.)

But if you're in a situation where, say, your boss wants some kind of code protection, you can google "Javascript obfuscator" -- there's a lot of free and for-pay software out there that makes JS at least about as impervious to decompiling as Flash is.
> 3 votes

# Answer
Aside from all this talk of code obfuscation, be sure to put a very clear copyright declaration at the top of each file and make it obvious that the license doesn't allow for alteration or commercial usage. This gives you legal recourse if someone does try to copy it. If you aren't willing to go to court over it, then this whole question is mostly academic.
> 3 votes

# Answer
I think if you make your game multi-player, which entails keeping your game logic in the server you would probably make it at least less appealing to steal. You can't trust the client really. As someone has already mentioned, there are tools for even compiled languages like Java and Flash, that can reverse engineer the text of the code from the byte code.
> 0 votes

# Answer
I think people caught on this problem are looking at it wrong. Don’t look at how code has been protected - your game engine isn’t your game. You should be protecting data - look at how websites, Netflix, and Spotify protect themselves from scrapers.

On the server side, you need to monitor the resources people are requesting. You can look for two things that would be suspicious:

1 - Requesting resources in an order that doesn’t make sense in my game. IE, if you have a set of level data and a set of enemy data, where it would be expected that levels are retrieved then enemies for that level, it wouldn’t make sense if you saw back to back requests from an account for level data without requests for enemy data in-between. Or if that level sequence doesn’t make sense - IE, if level 3 has to be visited before level 2, but you see them access 1, 2, 3.

2 - Requesting resources too quickly. It wouldn’t make sense for a request for level 2’s data to come just a second after the request for level 1’s data.

If either behavior is detected on the server side, you can block their account from making further requests and pop up a bug report form on the client end. If your piracy detection system has a bug, then it’s proper to ask for details - you’ll review and unblock their account if it turns out you were wrong. If you’re right, then they’re stuck with an uneasy feeling that you’re onto them and might stop trying.

You can further monitor for if you’re ending up with a lot of accounts getting blocked in a certain part of the world - might indicate someone really determined to steal the data (without even bothering to play the game properly.)

Someone determined to steal the game could still do a proper 100% play through, capturing every single data packet, but the more value your game offers, the harder it’d be for them to accomplish.
> 0 votes

# Answer
You need to use a Javascript Minifier. There are many options available feel free to find one that you like. To save you some research here's one you could try Yahoo Minifier. I haven't run that myself but I assume it will do what you need. The goal is to 1) reduce file size and 2) obfuscate code. This is accomplished by removing all whitespace, comments, and replacing variable names with shorter, nonsensical ones.

Most web applications today have a significant amount of Javascript and use tools such as these to try to protect their IP. As others have said you should always ask, "Can I do this on the server?" for important or sensitive operations, but I believe this should offer some protection.
> -1 votes

# Answer
Use Google closure compiler http://code.google.com/closure/compiler/ It is not just a js minimizer ;)

What are the benefits of using Closure Compiler?

1. Efficiency. The Closure Compiler reduces the size of your JavaScript files and makes them more efficient, helping your application to load faster and reducing your bandwidth needs.
2. Code checking. The Closure Compiler provides warnings for illegal JavaScript and warnings for potentially dangerous operations, helping you to produce JavaScript that is less buggy and and easier to maintain.1.
> -1 votes

# Answer
Or you could use something like Game Maker HTML5 to create your game which will obfusicate the code for you. That means that it will make the code unreadable to humans. And it'll be near impossible to edit.
> -1 votes

# Answer
Anything proprietary should be kept server-side. Client side you only provide enough for it to facilitate their use of the game.
> -1 votes

# Answer
Putting everything on the server could have performance issue and not really using all the potential of the web as we know it today.

You can write your code in c++ and compile it to binaries.

Native Client (NaCl).

See https://stackoverflow.com/questions/9018537/how-to-run-c-programs-on-the-web-inside-a-browser
> -1 votes

---
Tags: html5, javascript, client-server
---


# Question
Title: Why doesn't Unity keep keydown states between scenes, and how can I change that?
So basically, when my scene in Unity changes and I'm holding down, say, Right or Left, when the scene resets, my player (and Unity) doesn't even recognize that I'm **still** holding that button, until I lift my finger and put it back.

Any thoughts?

Sorry for any broken English or anything, I'm running off two hours of sleep.

# Answer
Using this in my dataHolder that persists between scenes I continuously got space key was pressed logged in the console.

```
 void Update () {
        if (Input.GetKey("space"))
            print("space key was pressed");
    }

```

The trick here is to make sure the instance of the script that handles button presses persists between scene loads.
> 4 votes

# Answer
I'm coming to this very late, but I ran into a similar issue. From what I tested, Unity seems to preserve keystates between scenes unless multiple keys are down, in which case it loses the first key to be pressed when a new scene is loaded. This is actually a super easy fix: Instead of using Input.GetKey(), you can use OnGUI() and use a boolean to detect if a certain key is down. Unity seems to handle this better, and the boolean will be preserved (provided that the script you're using persists). I'm not sure if this was the exact issue you were facing, but this is one way to fix it :)
> 1 votes

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


# Question
Title: Can open source games be published on Steam?
Many free and open source software licenses have conditions in them that ban bundling it with proprietary modules, although, in case of the GPL at least, there are some exceptions for drivers and necessary libraries.

Can open source games be published on Steam without violating the licenses?

I know there are some free software available on Steam, such as Blender (using the GNU General Public License), the Godot engine (using the MIT license), and SuperTuxKart (which is currently in Steam Greenlight).

What permissive license is best for publishing on Steam?

# Answer
> 9 votes
Can open source games be published without violating the license? Yes; because open source games *have* been published, and Steam allows it.

Simutrans is a simulation game that is offered through Steam, and advertises itself as open source. It may very well be the only open source game that has currently been published; There is actually a search filter to look for open source games, but games are tagged by the community, so it is not an exclusive list. Warsow is another such game that is currently in Steam Greenlight, but has been published through other means.

*Pikalek* has brought up one very big example of open source games being available through Steam; many of the older Doom, Quake and Wolfenstein games are available through the Steam store, despite using open source licenses.

---

While I can not personally comment on why we do not see *many* open source games, on Steam, I found a comment on Reddit that offers some sound reasoning as to why we do not see many, and other complications that may arise:

> Because to put something on Steam there have to be some person who may represent project in relations with Valve and many open source project don't have such people.
>
> Technically license of open source games allow anybody to put their compiled code and assets on Steam even to sell them, but there is open question about trademarks. E.g even if trademark not registered ownership of project name technically belongs it's original creators so likely Valve not going to accept project to Steam if it's use same name, but not submitted by actual developers.
>
> Other question that many open source games licensed under GPL and it's make it harder to use Steam integration as Steamworks SDK is proprietary and can't be linked with GPL'd game executable. In same time Valve don't provide easy way to use Steam-only features (as far as I aware WebAPI it's not exactly what can be used in game).
>
> <sub>\- **SxxxX** (posted 16/2/2015 and quoted as written) @ **/r/Linux\_Gaming : Why are many (free and) open source games not on Steam?**</sub>

# Answer
> 4 votes
To answer your question "**What permissive license is best for publishing on Steam?**", the answer is: What license you chose for your work does not matter.

When you release your work under a license, you still have full ownership of your work. You are not subject to your own license, because you're not licensing your work from yourself, you own it.\* There's nothing that stops you from releasing your code under any number of licenses, unless you sign an exclusive contract. Steam doesn't require titles on Steam to be exclusives, so there's no issue there.

To clarify: I'm talking about your ownership of your work. If you release someone else's work, you are subject to their terms.

\*You can give away ownership of your work, but that is something very different from making it available under a license.

# Answer
> 0 votes
By what I understand from other answers, if you own all the code, then you are fine. If there are multiple devlopers/contributors, make sure everyone agrees or say outright that you are going to do so.

---
Tags: licensing, open-source, steam
---


# Question
Title: Why is my player spinning after a collision?
I've made a very simple 2D top down prototype with Unity. This is the code I use for the player:

```
public class PlayerTurnsController : MonoBehaviour
{
    private Rigidbody2D m_rb;
    public float Speed;

    Vector2 m_movement;

    void Start()
    {
        m_rb = GetComponent<Rigidbody2D>();
    }

    private void Update()
    {
        var moveHorizontal = Input.GetAxis("Horizontal");
        var moveVertical = Input.GetAxis("Vertical");
        m_movement = new Vector2(moveHorizontal, moveVertical);
    }

    void FixedUpdate()
    {
        m_rb.MovePosition(m_rb.position + m_movement * Speed * Time.fixedDeltaTime);
    }
}

```

At the start and while moving everything seems OK. But when I bump into some Colliders, the player sprite starts spinning when it should just stop (not pressing any button anymore)

I already tried:

* To set the rotation only when the m\_Movement-Vector is \> 0.1f. But this didn't change anything.

# Answer
With the help of DMGregory I solved my problem.

The way I chose is to set "Freeze Rotation Z" of the Regidbody 2D via the inspector.

An other way is to increase the angularDrag of the Regidbody 2D via the inspector to e.g. 10.

This works too:

```
void Start()
{
    m_rb = GetComponent<Rigidbody2D>();
    m_rb.freezeRotation = true;
}

```

Also does:

```
void FixedUpdate()
{
    m_rb.MovePosition(m_rb.position + m_movement * Speed * Time.fixedDeltaTime);
    m_rb.angularVelocity = 0;
}

```

Im not sure which method is the best or which one to use when, but for the moment I chose "Freeze Rotation Z" = true in the inspector.
> 0 votes

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