# Question
Title: How to make player move into next level in pygame
When my player reaches at the end of the map, I want it to enter to the next level. I've created the first level and it all works fine. All I want to do is that when player finishes 1st level I want to load another map on which it can move forward. But I'm not able to understand how to do it.

Here is piece of my code:

```
def runGame(theGame):

    theGame.clock.tick(FPS)

    # This function consists code for Events
    theGame.events()
    # This function consists code from enemy hit events
    theGame.hit_or_not()
    # This function consists code for player movements
    theGame.movements()
    # This function consists code for drawing the sprites over the screen
    theGame.redrawGameWindow()

def readyGame(run, gameOver):
    game = Game()

    while run:
        runGame(game)

        keys = pygame.key.get_pressed()

        if keys[pygame.K_x]:
            game = Game()
        elif keys[pygame.K_ESCAPE]:
            run = False
        pygame.event.pump()

        if gameOver:
            runGame(game)

readyGame(True, False)

```

Here is my whole code which is responsible for my 1st level please kindly check it - https://pastebin.com/zMFetAd6 (Game Class)

Do I have to create another class for 2nd level like I did for the 1st level?

Can anyone please help me out in this issue? Thanks in advance!

# Answer
runGame can return a value as it is a function. Let's have it return `True` if a player completes the level. I'm assuming you already have a check for that in one of your other functions.

Your Game class can take arguments by adding them to its `__init__` method. Let's add a "level" argument and set the default to 0.

```
def __init__(self, level):
    if level == 0:
        # existing code for level 1 here
    elif level == 1:
        # code for level 2 here.

    # code that applies to all levels here.

```

Now all we have to do is create a new variable called level.

```
def readyGame(run, gameOver):
    level = 0
    game = Game(level)

    while run:
        if runGame(game) is True:
            print("Next level")
            level = level + 1
            game = Game(level)

        ...

```

From a pure code quality perspective, there are some things I might change about this implementation, but this will get you up and running.

In response to your comment:

```
class Game(pygame.sprite.Sprite):

    def __init__(self, level):  # add level parameter here
        super().__init__()
        self.clock = pygame.time.Clock()
        # This part stays the same for every level
        #   so I am cutting it out to save space

        if level == 1:
            self.hero = thePlayer(45, 625, 40, 40)

            self.enemy = # enemies for level 1
            self.platform = # platforms for level 1
        elif level == 2:
            self.hero = thePlayer(45, 625, 40, 40)

            self.enemy = # enemies for level 2
            self.platform = # platforms for level 2
        elif level == 3:
            # and so on

        self.facing = 0
        self.landed = True
        self.enterGame = pygame.image.load('startorclose.png')

        self.showMenu = pygame.image.load('MainMenu.png')
        self.stopScreen = False
        self.gameOver = False

```

This doesn't fit your code exactly because it seems like you'd have the the menu show up every time. But in short all you're adding is a new argument to `__init__` in the Game class and a `if` blocks here and there for the levels.

Your code has a lot of little issues so I'll leave you to hash it out and learn from the experience. Keep working and posting questions.
> 1 votes

---
Tags: python, pygame
---


# Question
Title: (Tiled) Background stops being rendered in libGDX
I'm using Tiled and I created my background as an image in a Tile Layer. When I load the map in LibGDX, it shows fine. However when the camera moves, the whole background dissapears.

The problem is solved if I add the background as an Image Layer.

Any idea what's causing the problem in the Tile Layer?

# Answer
> 0 votes
Likely libgdx optimizes the rendering process by rendering only those tiles that are within your viewport. Your background tile is very large, but libgdx may be assuming that all tiles match with the grid size of your map. Then, as soon as that small area is outside of the view, it stops rendering the entire tile.

I guess you could just use an image layer instead, since this solves your problem? Another solution would be to place your background image as multiple tiles.

---
Tags: libgdx, rendering, tiled
---


# Question
Title: SmothStop Function doesn't work as expected
i'm trying to create a smothstop function i need it to control time variable on my lerp function used to move character and so on...what i have is this

```
    private float SmothStop(float t)
{
    return  1 - (1 - t * t * t * t * t);

}

```

problem here is that will start slow then accelerate... same as smothstart function.. that i already tested and work on that way.. so.. what i'm missing up?

# Answer
Look what happens when we multiply through the parentheses here:

```
  1 - (1 - t * t * t * t * t)
= 1 - 1 + t * t * t * t * t
= t * t * t * t * t

```

So you just re-wrote SmoothStart in disguise.

It looks like what you want is:

```
float s = 1f - t;

return 1 - s * s * s * s * s;

```

When t is close to 1, s is close to zero. Raising to the 5th power creates a shallow slope around `s = 0` (`t = 1`), and a steep slope around `s = 1` (`t = 0`). Subtracting from 1 ensures the function is still increasing from 0 to 1 as t increases from 0 to 1.
> 0 votes

---
Tags: unity, mathematics, curves
---


# Question
Title: Why is 90 FPS recommended for Virtual Reality games?
### Origin of the question

I have recently finished an internship at a (small) game development company which is working on a Virtual Reality game that is also used in medical rehabilitation. From what I have heard and read online, you generally want to achieve at least 90 FPS in a VR game because otherwise the player can get motion sickness or dizzyness, etc.

I am aware that not everyone is getting sick but from what I have read, you still want to aim for that 90 FPS to be sure, although I am unable to find the exact reason for this number. (it feels like an industry standard)

### Questions

"Why is 90 FPS an industry standard when developing a VR game?" and "Why can people get sick when playing on lower frame rates?"

When searching online, I keep reading about 'studies' that show that people will be more likely to feel sick or dizzy when playing a VR game below 90 FPS but I never see the actual reason (source) as to why that is.

I can only make assumptions based on what I know already but I would like to know the exact reason (or as much of a reason as possible) and hopefully a **source** as to why 90 FPS is chosen (and not 80 or 100) and what causes some people to become sick from lower framerates.

*sidenote: I am referring to VR games for devices as the 'Vive', 'Rift', etc. (as there are also VR Simulations for pilots, etc. which also have elements such as simulated movement that can impact sickness)*

# Answer
I'm going to start by answering your second question, which has a more concrete answer.

# Why can people get sick when playing on lower frame rates?

**In the real world, when you turn your head one direction, objects move across your field of view in the other direction.** Consider the drawing below. When the person turns their head to the left, the tree is visible in their right field of view, and vice versa. Your brain expects this to happen whenever you move your head. The response time of your visual system is low enough that we can consider this to be instantaneous.

Imagine that someone has a stick mounted on their head holding a photograph of a tree in front of their face. In this situation, when the person turns their head left and right, the tree always remains in the center of their field of view, as shown below.

Now imagine if we put a screen on the stick instead of a static photograph. **If we can change what is displayed on the screen when the person turns their head, then we can make the image of the tree behave as if it were an actual tree**, moving across the field of view in the opposite direction of the turning head, as in the drawing below. This is basically how VR headsets work.

However, the visual system is finely tuned to this behavior and knows that it should happen pretty much instantly any time you move your head. **If VR frame rates are too low, your head can turn faster than the image can keep up.**

When your brain detects this discrepancy between the image it sees and the movement of your head, it thinks, "Hmm, something is poisoning my nervous system; I should get rid of whatever I just ate." This is the nausea and discomfort some people feel in VR, which is exacerbated by low frame rates.

# Why is 90 FPS an industry standard when developing a VR game?

**Because people tend to feel sick when the frame rate is below 90 FPS.**

This is not a magic number; 89 FPS would be fine. I'm sure some neuroscience articles have identified the maximum amount of time that your brain will tolerate between frames, but VR developers most likely just pushed the frame rate higher until most people weren't feeling sick, as suggested in the comments. Also mentioned in the comments is the fact that a 90 FPS VR display will work well in conjunction with a 60 FPS monitor, since usually both are active at the same time.

Unfortunately I was not able to find any authoritative study demonstrating the 90 FPS "standard." However, some articles do mention the 90 FPS figure. If you are really curious, you may have to do some digging. If so, here are some places to start:

Temporal Resolution Multiplexing: Exploiting the limitations of spatio-temporal vision for more efficient VR rendering.

The Problem of Persistence with Rotating Displays.
> 5 votes

---
Tags: virtual-reality
---


# Question
Title: SDL Memory leak with TTF_Font and surface
I am creating 2D game with SDL2, and I have a problem with my label class. Every time I construct new label I have a memory leak, and I don't know what I do wrong! For example, I want to refresh every time the fps label on my game, I have a memory leak since the old texture seems that doesn't deletes. Here is the code of the Label class. Tell me please where I am wrong!

```
namespace se {

class WidgetLabel : public Widget {
public:
    WidgetLabel(std::shared_ptr<Display> t_display,const Vector2i& t_possition, const std::string& t_text, const int t_fontSize = 25, const Color& t_color = Color(255,255,255,255));
    WidgetLabel(const WidgetLabel& rhs) = delete;
    WidgetLabel& operator =(const WidgetLabel& rhs) = delete;
    ~WidgetLabel();
    void render();
    void update();
    void setBlendMode(SDL_BlendMode t_blending);
    void setAlphaMode(Uint8 t_alpha);

    void setPossition(const Vector2i& t_possitions);
    void setPossitionX(const int t_x);
    void setPossitionY(const int t_y);
    const Vector2i getPossition() const;
    void setFontPath(const std::string& t_path);
    void setText(const std::string& t_string);
    const Vector2i getResolution() const;
    int getWidth() const;
    int getHeight() const;

private:

    std::shared_ptr<Display>    m_display;
    TTF_Font                    *m_font;
    SDL_Surface                 *m_surface;
    SDL_Texture                 *m_texture;

    int                         m_width;
    int                         m_height;
    int                         m_possitionX;
    int                         m_possitionY;

    std::string                 m_text;
    int                         m_fontSize;
    std::string                 m_fontPath;
    Color                       m_color;

    void createSurface();

};

```

}

```
namespace se {

WidgetLabel::WidgetLabel(std::shared_ptr<Display> t_display,const Vector2i& t_possition, const std::string& t_text, const int t_fontSize, const Color& t_color) :
m_display(t_display),
m_surface(nullptr),
m_texture(nullptr),
m_width(0),
m_height(0),
m_possitionX(t_possition.getX()),
m_possitionY(t_possition.getY()),
m_text(t_text),
m_fontSize(t_fontSize),
m_fontPath("assets/fonts/serif.ttf"),
m_color(t_color)

{

    m_font = TTF_OpenFont(m_fontPath.c_str(), t_fontSize);

    if (m_font == nullptr) {
        std::cerr << "Faild to load SDL Font! Error: " << TTF_GetError() << '\n';
    }

    int imgflags = IMG_INIT_PNG;
    if ( !( IMG_Init(imgflags) & imgflags)) {
        std::cerr << "Couldn't not initialize sdl image" << '\n';
    }

    createSurface();

}

WidgetLabel::~WidgetLabel()
{
    SDL_DestroyTexture(m_texture);
    m_texture = nullptr;
}

void WidgetLabel::render()
{
    SDL_Rect rect_ = { m_possitionX, m_possitionY, m_width, m_height};
    SDL_RenderCopyEx(m_display->getRenderer(), m_texture, nullptr, &rect_, 0.0, nullptr, SDL_FLIP_NONE);
}
void WidgetLabel::setPossition(const Vector2i &t_possitions)
{
    m_possitionX = t_possitions.getX();
    m_possitionY = t_possitions.getY();
}

void WidgetLabel::setPossitionX(const int t_x)
{
    m_possitionX = t_x;
}
void WidgetLabel::setPossitionY(const int t_y)
{
    m_possitionY = t_y;
}
const Vector2i WidgetLabel::getPossition() const
{
    return Vector2i(m_possitionX, m_possitionY);
}

void WidgetLabel::setFontPath(const std::string &t_path)
{
    m_fontPath = t_path;
}
void WidgetLabel::setText(const std::string &t_string)
{
    m_text = t_string;
    createSurface();
}
void WidgetLabel::createSurface()
{

    m_surface = TTF_RenderText_Blended(m_font, m_text.c_str(), m_color);

    if ( m_surface == nullptr ) {
        std::cerr << "Unable to render text surface! Error: " << TTF_GetError() << '\n';
    } else {

        m_texture = SDL_CreateTextureFromSurface(m_display->getRenderer(), m_surface);

        if ( m_texture == nullptr ) {
            std::cerr << "Unable to create texture from renderer text! Error: " << SDL_GetError() << '\n';
        } else {

            m_width = m_surface->w;
            m_height = m_surface->h;

        }

        SDL_FreeSurface(m_surface);
        m_surface = nullptr;
    }

}
const Vector2i WidgetLabel::getResolution() const
{
    return Vector2i(m_width, m_height);
}

int WidgetLabel::getWidth() const
{
    return m_width;
}

int WidgetLabel::getHeight() const
{
    return m_height;
}
void WidgetLabel::update()
{

}

void WidgetLabel::setBlendMode(SDL_BlendMode t_blending)
{
    SDL_SetTextureBlendMode(m_texture, t_blending);
}

void WidgetLabel::setAlphaMode(Uint8 t_alpha)
{
    SDL_SetTextureAlphaMod(m_texture, t_alpha);
}

```

}

The render and update function called in main game loop. The shared pointer with t\_display, is just the passed renderer .

# Answer
> 0 votes
Upon first glance, it looks like you call `TTF_OpenFont` to create your font in your label constructor, but you do not call `TTF_CloseFont` in the destructor. You should.

You also call `createSurface` in both the constructor and `setText`. When called from `setText`, `createSurface` will immediately allocate a new `m_surface` and `m_texture`, causing you to lose the things they were previously pointing at (and thus, leak them).

If you're going to use that model, you probably need `createSurface` to first check if the texture is non-null, and if so, release it prior to creating a new one. It's not clear that `m_surface` needs to be member at all since it appears you only create it for `createSurface` and always release it before the function ends. It may simplify your code if you can just make that surface a temporary local.

# Answer
> -1 votes
I had the same problem but I have no memory leak now steady a steady line

so in my update drawing the renderer // SDL\_Surface\* surface is in my header and gets deleted on the ~destructor

```
if (surface == NULL) {
    surface = TTF_RenderText_Solid(getFont(), getText(), getColor());
    setMessage(SDL_CreateTextureFromSurface(getRender(), surface));
}

SDL_RenderCopy(getRender(), getMessage(), NULL, getMousePosition());

if (surface != NULL)
{
    SDL_BlitSurface(surface, NULL, surface, NULL);
    //SDL_FreeSurface(surface); // dont destroy

}
else
{
    // report error
}

```

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


# Question
Title: How do I fix the "Failed to recompile android resource files." build issue?
I've tried similar solutions I found on this website, nothing worked. There are thee errors that pop up... been banging my head for quite a while now, please help!

Also note: I updated my JDK using the download link (next to the browse option in the external preferences). Then linked it to this file, which I am lead to believe is the correct file. C:/Program Files/Java/jdk-9

1. ```
Failed to compile resources with the following parameters:
-bootclasspath "C:/NVPACK/android-sdk-windows\platforms\android-24\android.jar" -d "C:\Users\Dylan\Desktop\ContentCreater\Repo\DoodlePlanes\DoodlePlanes\DoodlePlanes\Temp\StagingArea\bin\classes" -source 1.6 -target 1.6 -encoding UTF-8 "com\android\vending\billing\R.java" "com\SoloDeveloperStudio\DoodlePlane\R.java" "com\unity\purchasing\R.java" "com\unity\purchasing\googleplay\R.java"
warning: [options] source value 1.6 is obsolete and will be removed in a future release
warning: [options] target value 1.6 is obsolete and will be removed in a future release
warning: [options] To suppress warnings about obsolete options, use -Xlint:-options.
3 warnings

UnityEditor.HostView:OnGUI()

```
2. ```
UnityException: Resource compilation failed!
Failed to recompile android resource files. See the Console for details.
UnityEditor.Android.PostProcessor.CancelPostProcess.AbortBuild (System.String title, System.String message, System.Exception ex)
UnityEditor.Android.PostProcessor.CancelPostProcess.AbortBuild (System.String title, System.String message)
UnityEditor.Android.PostProcessor.CancelPostProcess.AbortBuildPointToConsole (System.String title, System.String message)
UnityEditor.Android.PostProcessor.Tasks.BuildResources.CompileResources (UnityEditor.Android.PostProcessor.PostProcessorContext context)
UnityEditor.Android.PostProcessor.Tasks.BuildResources.Execute (UnityEditor.Android.PostProcessor.PostProcessorContext context)
UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context)
UnityEditor.Android.PostProcessAndroidPlayer.PostProcess (BuildTarget target, System.String stagingAreaData, System.String stagingArea, System.String playerPackage, System.String installPath, System.String companyName, System.String productName, BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.BuildReporting.BuildReport report)
UnityEditor.Android.AndroidBuildPostprocessor.PostProcess (BuildPostProcessArgs args)
UnityEditor.PostprocessBuildPlayer.Postprocess (BuildTargetGroup targetGroup, BuildTarget target, System.String installPath, System.String companyName, System.String productName, Int32 width, Int32 height, BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.BuildReporting.BuildReport report) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/PostprocessBuildPlayer.cs:263)
UnityEditor.HostView:OnGUI()

```
3. ```
UnityEditor.BuildPlayerWindow+BuildMethodException: Build failed with errors.
  at UnityEditor.BuildPlayerWindow+DefaultBuildMethods.BuildPlayer (BuildPlayerOptions options) [0x001b9] in C:\buildslave\unity\build\Editor\Mono\BuildPlayerWindowBuildMethods.cs:162
  at UnityEditor.BuildPlayerWindow.CallBuildMethods (Boolean askForBuildLocation, BuildOptions defaultBuildOptions) [0x00050] in C:\buildslave\unity\build\Editor\Mono\BuildPlayerWindowBuildMethods.cs:83
UnityEditor.HostView:OnGUI()

```

# Answer
> 1 votes
use jdk 8 because 9 is not compatible or change your package name it might help you. in my case when i changed the package name then it works fine.

# Answer
> -1 votes
it worked thx all.

for me jdk path was the point.i changed the path to 1.8.25 folder.

and change the target API and minimum lv to 26,19 in androidManifast 파일.

only two files in the asset\>plugin\>android.

---
Tags: unity, android, build-process
---


# Question
Title: Unity Placing a UI on top of Cinemachine
I have cinemachine set up. I just need to place the UI on top of it. I can easily manage to make the canvas appear when there's only the main camera alone. However with Cinemachine, it appears that the virtual camera prevents the loading screen to be seen. The canvas in my hierarchy is named `loadingPanel` which is disabled until I trigger an event. Everything in the hierarchy has their layers set to `Default`, except canvas (`UI`) and the player (`Player`)

**I can trigger the event and set `loadingPanel` to active as well as load the next level but I can't see the loading screen. I could only see my tilemap/level before I switch to the next scene. I need to see my canvas / user interface.**

This is my hierarchy

Inspector

How do I see the `loadingPanel` when cinemachine is present?

# Answer
> 2 votes
I forgot to come back. Setting the Canvas panel back to `Overlay` mode did the trick.

Credits to DMGregory

---
Tags: unity, 2d, user-interface, cinemachine
---


# Question
Title: How do I add a random number of points to my score stored in Player Preferences?
My problem is the value I get from Random.Range is not stored, but I get another value instead.

* In level 1 I press the "claim" button to store a randomly-chosen score
* In level 2 I retrieve the level 1 score using player preferences.
* When I press the "claim" button again in level 2 I want to add the new random score to the score from level 1.

How can I do this?

Here is the code I'm using currently:

```
playermanager.cs

 internal static int pointsAdd;

 void Start()
 {
       PlayerManager.pointsAdd = PlayerPrefs.GetInt("score");
 }

 void FixedUpdate()
 {
        creditsText.text = PlayerPrefs.GetInt("score").ToString();
 }

 public void GetClaim()
 {
        PlayerManager.pointsAdd = PlayerPrefs.GetInt("score");
        Debug.Log("pointadd" + PlayerManager.pointsAdd);

        PlayerManager.pointsAdd =  Random.Range(20, 40);
        Debug.Log("Your Point is:" + PlayerManager.pointsAdd);
        Debug.Log("random.range" + Random.Range(20, 40));

        PlayerPrefs.SetInt("score", PlayerManager.pointsAdd);

        creditsText.text = ("" + PlayerManager.pointsAdd);
 }

```

Output:

# Answer
There are several problems with this code.

1. `pointsAdd` is serving as a total score, not an addition, so you should name it appropriately: `totalScore`
2. Since you're loading it from Player Prefs in each scene anyway, it does not need to be `static`.
3. `FixedUpdate` is not the correct time to update a text string. It might get called multiple times per frame, but your text can only be seen once per frame, so the extra setting is just producing unnecessary string garbage.

In fact, you only need to set your text when your score *changes*.
4. You are assigning a new value to your score with `=`, instead of adding to it with `+=`
5. You seem to be calling `Random.Range` twice as though you expect the same value each time. `Random.Range` will return a new randomly selected value each time you call it.

Try this instead:

```
public class ScoreManager {

    public Text creditsText;
    int totalScore;

    // Set the text whenever the score changes, and ONLY when the score changes.
    void SetScore(int newScore, bool save = true) {
        totalScore = newScore;
        creditsText.text = totalScore.ToString();
        if(save)
            PlayerPrefs.SetInt("score", totalScore);
    }

    void Start() {
        SetScore(PlayerPrefs.GetInt("score"), false);
    }

    public void GetClaim() {
        int addition = Random.Range(20, 40);

        Debug.LogFormat("Adding {0} points to the current score {1} to get {2}",
              addition,
              totalScore,
              addition + totalScore
        );

        SetScore(totalScore + addition);
    }
}

```

Note that the player can easily modify the PlayerPrefs storage to give themselves whatever score they want, so you should not use this score storage method for anything that affects fairness in multiplayer, monetization, or other systems you don't want hacked.
> 1 votes

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


# Question
Title: How to move the arrow markers 1 unit only?
I'm new to learning C#. How can I move an arrow one unit at a time?

Here's the code I'm using now:

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

public class ArrowMovement : MonoBehaviour
{
    float directX;
    float directY;

    public float moveSpeed = 5f;

    private Rigidbody rb;

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

    }

    private void FixedUpdate()
    {
        float h = Input.GetAxis("Horizontal") * 100;
        float v = Input.GetAxis("Vertical") * 100;

        Vector3 vel = rb.velocity;
        vel.x = h;
        vel.z = v;
        rb.velocity = vel;
    }
}

```

I just know how to do basic move

# Answer
> 1 votes
I am assuming your 3D models are in 1 unit scale as per unity.

`Input.GetAxis` will give you float values. Use `Input.GetKeyDown("Key")` instead.

Let's suppose you want to move up so you can use:

```
if (Input.GetKeyDown(KeyCode.UpArrow))
{
    transform.position += Vector3.Up;
}

```

`Vector3.Up` is Shorthand for writing Vector3(0, 1, 0) and 1 represent 1 unit. For more detail on representation of 3D vectors and points. click here.

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


# Question
Title: How to make a sphere bounce while it is moving forwards Unity
I am trying to make a sphere that I have moving forwards also bounce at the same time. Here is what I have tried.

Adding a physic material to the sphere and setting the material with a friction combine of minimum, setting the bounce combine to the maximum.

Setting the collision detection on the rigidbody of the sphere to continuous.

After trying all of this, it all resulted in when the sphere hits the other gameobject just sitting there and moving forwards without bouncing. Here is the code that I have for moving the sphere.

```
public float forceMulti = 50f;

private Rigidbody rb;

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

// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{
    rb.velocity = transform.forward * Time.deltaTime * forceMulti;
}

```

If there is a way to make the sphere bounce through code while it is moving forwards that would be great and I would really appreciate the suggestions.

Thanks.

# Answer
Don't directly set the velocity of the rigidbody if you want other physics behaviors. Use rb.AddForce instead.
> 0 votes

# Answer
If your player don't change height in the game then how about simply animating the sphere to bounce while moving forward? no need to go complex.
> 0 votes

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


title: How to 9 slice meshes?

text:
# Question
Title: How to 9 slice meshes?
So let us assume I have a 3D model of a window and I would like to stretch it like a 9 sliced sprite. How would you go by doing 9 slice on meshes? All I found online was about quads. What about more complicated meshes?

# Answer
> 1 votes
As far as I know, this is not as popular as 9-slicing images, so it doesn't come with popular engines.

Having said that, you can always do this manually. Editing a mesh is easier than editing an image, so it's not difficult to separate a mesh into 9 pieces (like you would an image) and either scale the in-between meshes, or tile them, or a combination of both. You don't have to mess with shaders or anything complicated, just the basic transformations of a 3D object are enough.

The process is the same as when using an image, and maybe you can do a "27-slice" if you want the same effect on 3D.

---
Tags: unity
---


title: Wobble the y(up) axis of a circle

text:
# Question
Title: Wobble the y(up) axis of a circle
I wrote a script that moves a game object(w/ trail render) in a circular motion via the sin/cos functions

```
x = center.x + Mathf.Sin(t) * r;
z = center.z + Mathf.Cos(t) * r;
position = new Vector3(x, 0, z);

```

i would like to know how to tweak the y axis to wobble/tilt it like a spinning coin as it slows down.

what kind of math would i apply to do that? I applied x to y which tilts it, but it remains that way instead of moving its high/low ends around

# Answer
> 2 votes
First of all, you need to lift one side up. You can do this pretty easily by just setting the y axis to the sine of t:

```
x = center.x + Mathf.Sin(t) * r;
y = Mathf.Sin(t) * height;  // Height is the maximum height the coin reaches
z = center.z + Mathf.Cos(t) * r;
position = new Vector3(x, y, z);

```

However, this will make the coin stay in place as you seem to have noticed. To make the high end move around, add the current time (not the same as `t`) to `t`. You can use `Time.time` in Unity:

```
x = center.x + Mathf.Sin(t) * r;
y = Mathf.Sin(t + Time.time) * height;  // Height is the maximum height the coin reaches
z = center.z + Mathf.Cos(t) * r;
position = new Vector3(x, y, z);

```

2D example in JavaScript:

```
let ctx = c.getContext("2d");

let time = 0;
setInterval(() => {
  ctx.clearRect(0, 0, 500, 500);
  for (let t = 0; t < 30; t++) {
    let x = Math.sin(t / 15 * Math.PI);
    let y = Math.sin(t / 15 * Math.PI + Date.now() / 1000 * 3);
    ctx.fillRect(x * 150 + 250, y * 75 + 250, 10, 10);
  }

  time += 0.016;
}, 16);
```

```
<canvas id="c" width="500" height="500"></canvas>
```

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


# Question
Title: How do I apply angular velocity vector after a collision?
I'm writing a small 3D physics engine, and I am trying to get the angular velocity vector of two shapes, specifically two cubes.

For deeper understanding I have divide the motion to linear and angular motion.

For the angular motion I have done a few steps.

I calculated the inertia tensor matrix which is 3x3 so I could get the torque as follows:

$$\tau=I\alpha \\ \begin{bmatrix} \tau\_x \\ \tau\_y \\ \tau\_z \end{bmatrix} = \begin{bmatrix} I\_{xx} & I\_{xy} & I\_{xz} \\ I\_{xy} & I\_{yy} & I\_{yz} \\ I\_{xz} & I\_{yz} & I\_{zz} \end{bmatrix} \begin{bmatrix} \alpha\_x \\ \alpha\_y \\ \alpha\_z \end{bmatrix} \\ \tau\_x = I\_{xx}\alpha\_x+I\_{xy}\alpha\_y+I\_{xz}\alpha\_z \\ \tau\_y = I\_{xy}\alpha\_x+I\_{yy}\alpha\_y+I\_{yz}\alpha\_z \\ \tau\_z = I\_{xz}\alpha\_x+I\_{yz}\alpha\_y+I\_{zz}\alpha\_z $$

And for calculating the matrix I have used: $$I= \begin{bmatrix} m(y^2+z^2) & -mxy & -mxz \\ -mxy & m(x^2+z^2) & -myz \\ -mxz & -myz & m(x^2+y^2) \end{bmatrix} $$

Using the formulas described here, I could get the impulse and the final angular velocities for all shapes as follows:

Impulse: \\$j= -(1+e) \frac{(v\_a-v\_b)•n + (r\_a×n)•\omega a - (r\_b×n)•\omega\_b}{ 1/m\_a+1/m\_b+(r\_a×n)•(\[I\_a\]^{-1}(r\_a×n))+(r\_b×n)•(\[I\_b\]^{-1}(r\_b×n))}\\$
Final velocity of object a:\\$\vec V\_{af} =Vai-J/Ma\\$
Final velocity of object b:\\$\vec V\_{bf} =Vbi-J/Mb\\$
Final angular velocity of object a:\\$w\_{af}=wai-\[Ia\]^{-1}(J x ra) \\$
Final angular velocity of object b:\\$w\_{bf}=wbi-\[Ib\]^{-1}(J x rb) \\$

So my question is: how could I calculate the rotational angular which each object should rotate and for how long it should last?

# Answer
The angular velocity vector you've computed using the method you've shown gives you two things:

* The direction the vector points is the axis of rotation
* The magnitude of the vector is the speed of rotation (typically in radians per second)

So, to rotate the object, you can take:

```
// Separate axis and speed into separate variables.
float angularSpeed = angularVelocity.Length;
Vector3 axis = angularVelocity / angularSpeed;

// Compute how far the object rotates in the time
// duration of the current simulation step.
float angularIncrement = angularSpeed * deltaTime;

```

Then construct a rotation matrix from the axis and angle, or a quaternion like so:

```
Quaternion rotationIncrement;
rotationIncrement.xyz = Sin(angularIncrement/2f) * axis;
rotationIncrement.w = Cos(angularIncrement/2f);

```

This lets you rotate the objects frame-by-frame according to their angular velocities.

As for "how long" to rotate them, in Newtonian physics, "an object in motion tends to stay in motion," so they'll keep spinning this way like a gyroscope or an asteroid tumbling in space until another collision or force acts on them to cancel the spin.

In games, we'll often simulate friction by applying a damping to the angular velocity, multiplying it by a constant less than one each frame so that the rotation will eventually slow to \[low enough to round down to\] nothing.
> 6 votes

---
Tags: physics, collision-resolution
---


title: 2d array with empty elements

text:
# Question
Title: 2d array with empty elements
I am working on a game with a number of different grid components. Each grid would be about 15 squares wide by 15 squares tall. Each of the squares may either contain an item or not.

Is there any way to create this array and only include the components that have a value. Example (for a 5x5 array):

```
[
   [5,3, , ,3],
   [ ,1,0,2,2],
   [ , , , , ],
   [5, , ,2, ],
   [ , , , ,1]
]

```

Is there any way to do this in JavaScript or should I just add a bunch of *NULL* values to the array?

A simplified version of this, might be an *Xs and Os* game. Before the game starts all squares are empty. Over time, some of the grid may have either Xs or Os in specific squares.

# Answer
If you want the map to appear as close as possible to what you've written above, without a lot of `null`s to type out and clutter reading, you could define a helper variable first:

```
var _ = null;

var tileMap = [
  [5,3,_,_,3],
  [_,1,0,2,2],
  [_,_,_,_,_],
  [5,_,_,2,_],
  [_,_,_,_,1]
];

```
> 1 votes

---
Tags: javascript, tilemap
---


# Question
Title: Why the value of float xAxis = -Gdx.input.getAccelerometerY(); is given a accelerometer of y axis?
I am learning game development from the udacity course "https://classroom.udacity.com/courses/ud405/lessons/5389263706/concepts/53853441090923"

I am stuck with one statement in the code about Accelerometer. The code initialized the xAxis variable to"-Gdx.input.getAccelerometerY()" and "yAxis = Gdx.input.getAccelerometerX()"

Can anyone explain what getAccelerometerY and getAccelerometerX does actually?

# Answer
The accelerometer is a thing in mobile devices that can detect when the phone is being moved. If you're on desktop or HTML, these methods always return 0. If you're on android or IOS, these methods return the acceleration on the three different axes of X, Y, and Z. (https://www.mathworks.com/help/supportpkg/android/ref/accelerometer.html explains the axes pretty well.)

For example, if you put the phone face-up on a table, getAccelerometerZ() returns -9.81 because the acceleration due to gravity on the Z axis is 9.81m/s^2 down.
> 0 votes

---
Tags: libgdx, accelerometer
---


# Question
Title: In 2D, how can I improve character rotation using raycasts when dealing with sharp/convex edges?
**Edit:**

After making some edits to my `polygon collider` (based on @Alex F's suggestion), I can indeed confirm that sharp, convex corners are causing the buggy rotation. For now I've decided to only rotate my character if its moving, so standing on a corner when `velocity.x = 0` won't cause my collider to rotate rapidly. However, this seems like a band-aid fix, and I'm still wondering if there's a better way to handle these edges. Resuming movement after idling on a corner still causes some buggy behavior, and I'm concerned that this will compound once my rotations become more complicated or frequent:

**Original question:**

I'm quite inexperienced with `quaternions` and rotating, so I'm not entirely sure if this issue has to do with my code, the collisions shown in this question, or my game design.

What I'm trying to achieve is "smooth" rotation of my character's collider based on the normal of the current surface. I've been creating a custom raycast controller in 2D from the ground up, and already know how to find all kinds of information from rays, such as the current angle of a sloped surface. My controller is coming along quite nicely, and rotation is one of the last things I'd like to tackle. It should be able to handle sloped `box colliders`, but also irregular ground shapes that require something like a `polygon collider`.

I've been somewhat successful, having learned that I shouldn't set my character's z-rotation directly, but instead update my entire `transform.rotation` with a method like `Quaternion.Lerp`. This has worked generally well, but I'm running into issues on irregular ground, and on corners.

Notice the smooth transition from flat to sloped surfaces, but that my collider rotates rapidly when the raycast hits a corner:

Movement is still somewhat smooth on irregular terrain, but there is a noticeable shakiness at times. Sometimes my character's collider rotates rapidly as well (end of gif):

I suspect that the shakiness on the irregular terrain is just my collider getting "caught" on the many edges that the `polygon collider` creates. I just don't know if this is happening because I could be doing something differently in my code, or if I need to edit the `polygon collider`, or is caused by something else entirely. Perhaps raycasting isn't the best way to achieve my desired behavior.

```
[SerializeField]
private float speed = 5;
[SerializeField]
private float gravity = -20;
[SerializeField]
private LayerMask collisionMask;

private BoxCollider2D boxCollider;
private Vector2 velocity;
private Vector2 groundNormal;

private void Awake()
{
    boxCollider = GetComponent<BoxCollider2D>();
}

private void Update()
{
    float playerInput = Input.GetAxisRaw("Horizontal");

    velocity.x = playerInput * speed;
    velocity.y += gravity * Time.deltaTime;

    MoveCharacter(velocity * Time.deltaTime);
}

private void MoveCharacter(Vector2 velocity)
{
    //Rotate the character
    Quaternion targetRotation = Quaternion.FromToRotation(Vector2.up, groundNormal);
    transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, 0.5f);

    groundNormal = Vector2.zero;

    CollideBelow(ref velocity);
    transform.Translate(velocity);
}

private void CollideBelow(ref Vector2 deltaMovement)
{
    float rayLength = 1;
    Vector2 rayOrigin = transform.position;

    RaycastHit2D hit = Physics2D.Raycast(rayOrigin, -transform.up, rayLength, collisionMask);
    Debug.DrawRay(rayOrigin, -transform.up * rayLength, Color.red);

    if (hit)
    {
        velocity.y = 0;
        deltaMovement.y = -(hit.distance - boxCollider.size.y * 0.5f);

        groundNormal = hit.normal;
    }
}

```

# Answer
> 0 votes
I don't know if raycasting is the *best* way to do what you want, but it certainly looks like it works. I think the problem is just lack of detail on the track; if you **rounded the sharp corners** of your track, it looks like it would work perfectly.

# Answer
> 0 votes
You can add a circle2D collider as a trigger (and just make sure it's slightly bigger than the square), then do something like this to get the groundNormal:

```
// cache reference to the circle2D trigger in Awake. I'll call it trigger

void OnTriggerStay2D(Collider2D other) {
    groundNormal = -trigger.Distance(other).normal;
}

```

I haven't tested how this would work in your case, but I'm using literally the above code for a circular character, and groundNormal transitions very smoothly over corners, so I think it should work for you.

# Answer
> -1 votes
I think on the edge, it takes much more than one raycast (example: 1 bottom left, 1 bottom right ...), because the raycast hesitates to give you between two normal ground

ps: sorry for my english

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


title: object changing position when scaled

text:
# Question
Title: object changing position when scaled
These are my matrices. when i move the pivot point to one unit in x and if the scaling is set to 1 than everthing works fine.

the pivot point has moved to one unit and the cube has stayed in its position.

But when i first scale the object to 0.5 and than move the pivot point than the cube follows the pivot point , which should not be he case as i am only moving pivot point.

Please help me with this , how can i keep the cube in position.

```
 glm::mat4x4 Container::GetPositionMatrix()
  {
     // posx  is the x position of the object.
     // posy  is the y position of the object.
    // posz  is the y position of the object.
       glm::mat4 TransformationPosition = glm::translate(glm::mat4x4(1.0),
       glm::vec3(posx , posy   , posz ));
      return TransformationPosition;
   }

```

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

```
 glm::mat4x4 Container::GetRotationMatrix()
 {
      //  posx  is the x positon of the object
      // pivotx is the x position on the pivot point
      // rotx is the x rotation of the object
      glm::vec3 pivotVector(posx - pivotx, posy - pivoty, posz - pivotz);
      glm::mat4 TransPivot = glm::translate(glm::mat4x4(1.0f), pivotVector);
      glm::mat4 TransPivotInverse = glm::translate(glm::mat4x4(1.0f),
      glm::vec3( -pivotVector.x , -pivotVector.y , -pivotVector.z));
      glm::mat4 TransformationRotation(1.0);
      TransformationRotation = glm::rotate(TransformationRotation,
      glm::radians(rotx ), glm::vec3(1.0, 0.0, 0.0));
      TransformationRotation = glm::rotate(TransformationRotation,
     glm::radians(roty ), glm::vec3(0.0, 1.0, 0.0));
     TransformationRotation = glm::rotate(TransformationRotation,
     glm::radians(rotz  ), glm::vec3(0.0, 0.0, 1.0));
     return  TransPivotInverse * TransformationRotation * TransPivot;
  }

```

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

```
  glm::mat4x4 Container::GetScalingMatrix()
      {

      //  posx  is the x positon of the object
      // pivotx is the x  position on the pivot point
      // scax is the x scaling of the object
      glm::vec3 pivotVector(posx - pivotx, posy - pivoty, posz - pivotz);
      glm::mat4 TransPivot = glm::translate(glm::mat4x4(1.0f), pivotVector);
      glm::mat4 TransPivotInverse = glm::translate(glm::mat4x4(1.0f),
      glm::vec3(-pivotVector.x, -pivotVector.y, -pivotVector.z));
      glm::mat4 TransformationScale = glm::scale(glm::mat4x4(1.0 ) ,
      glm::vec3(scax, scay, scaz));
      return  TransPivotInverse * TransformationScale  * TransPivot;

```

}

```
 final matrix

 TransformationPosition * TransformationRotation  * TransformationScaling

```

# Answer
> 0 votes
Scale pivoting is certainly supposed to translate your object, as demonstrated here.

But, in the reference video you linked, did you notice that when you move pivot point, position of the object changes as well? You should do the same thing when you move pivot in your application, by subtracting difference to the object's position in order to compensate.

This is how to find difference:

```
glm::vec3 difference = position - pivot * scale;

```

---
Tags: opengl, glsl
---


title: objects disappear before time

text:
# Question
Title: objects disappear before time
I created a little pool in order to better manage my enemies, to which, an enemySpawner object calls to retrieve a clone and show it on screen

```
public class ObjectPool : MonoBehaviour
{
    public static ObjectPool current;
    public GameObject objectForPool;
    public int poolAmmount = 20;
    public bool growth = true;

    List<GameObject> objectsForPool;

    void Awake()
    {
        current = this;
    }

    // Use this for initialization
    void Start ()
    {
        objectsForPool = new List<GameObject>();

        for (int i = 0; i < poolAmmount; i++)
        {
            GameObject obj = Instantiate(objectForPool);
            obj.SetActive(false);
            objectsForPool.Add(obj);
        }
    }

    public GameObject GetPooledObject()
    {
        for (int i = 0; i < objectsForPool.Count; i++)
        {
            if (!objectsForPool[i].activeInHierarchy)
            {
                return objectsForPool[i];
            }
        }
        if (growth)
        {
            GameObject obj = Instantiate(objectForPool);
            objectsForPool.Add(obj);
            return obj;
        }
        return null;
    }

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

    }
}

```

The call(EnemySpawner update)

```
void Update ()
{
    transform.position = new Vector3(transform.position.x + (speed * Time.deltaTime), 0, transform.position.z);
    if (transform.position.x <= boundary.xMin || transform.position.x >= boundary.xMax)
        speed *= -1;

    if (Time.time > nextSpawn)
    {
        nextSpawn = Time.time + spawnRate;

        GameObject clone = GetComponent<ObjectPool>().GetPooledObject();
        if (clone == null || clone.activeInHierarchy) return;
        clone.GetComponent<EnemyMovement>().SetPlayerShip(playerShip);
        clone.transform.position = transform.position;
        clone.transform.rotation = transform.rotation;
        clone.GetComponent<Health>().RestoreHealth();
        clone.SetActive(true);
    }
}

```

The problem here is, that my enemies are being deactivated on mid trajectory

https://youtu.be/ZGHC6wwGX1E

I know my issue is in my pooling, but I can't figure out what I'm doing wrong

# Answer
> 1 votes
Well, finally realized my mistake

I followed Unity tutorial on object pooling

https://unity3d.com/es/learn/tutorials/topics/scripting/object-pooling

And, event though it works wonders on bullets, not so much on enemies.

I'm pooling the enemies, just, trying to keep a good memory management from the begginning, and every object pooled had this `killScript`

```
public class KillBox : MonoBehaviour
{

    void OnEnable() => Invoke("Destroy", 2f);

    void Destroy() => gameObject.SetActive(false);

    private void OnDisable() => CancelInvoke();

}

```

This is the only place the `SetActive(false)` is ever called, so your mention of looking for this piece of code made me realize that, this is invoked 2 seconds after the object is pooled and activated. Changing this from 2 to 10 made that the enemies never dissapeared... like, never, and I had a kill box to set them innactive when reached, but the killbox logic wasn't ther, so I just needed to adjust this

```
public class KillBox : MonoBehaviour
{
    void OnTriggerExit(Collider other)
    {
        switch (other.gameObject.name)
        {
            case "Bullet":
                Debug.Log("A bullet reached the killbox");
                other.gameObject.transform.parent.gameObject.SetActive(false);
                break;
            case "Enemy(Clone)":
                Debug.Log("An Enemy reached the killbox");
                other.gameObject.SetActive(false);
                break;
            default:
                Debug.Log($"{other.gameObject.name} reached the killbox");
                break;
        }
    }
}

```

This way, enemies are respawned whenever they are inactive, either by the killBox, or when hit by a bullet

# Answer
> -1 votes
I could not read all your post, but I think just call SetActive(false) is not good idea. PooledObject have to be return to pool for reusing.

I love this site. I also recommend to read this. If you don't have time, see ObjectPool, PooledObject class only:)

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


# Question
Title: Are there .NET bindings for Autodesk's FBX SDK?
I'm writing a tool in C# that needs to open FBX files (and the XNA content pipeline isn't a suitable solution). I note that Autodesk only provides it's FBX SDK as a C++ class library.

Before I write it myself I thought I'd ask if anyone knows of existing .NET bindings for this SDK?

# Answer
> 4 votes
Unfortunately, I don't think there are any -- I've never stumbled across them, at least. There's definitely a niche there if you can write a C# wrapper that can be distributed (not sure what the FBX SDK license terms are, though, they may make that cumbersome).

# Answer
> 0 votes
Check out Max.NET.

> Max.NET is a .NET CLR wrapper for 3d Studio Max's (3dsmax) software development kit (SDK). It allows developers to write tools for 3dsmax in a managed and reflective environment using any of the common .NET languages such as C#, VB.net, J#, and C++/CLI. Moreover it provides access to all of the classes and their members accessible to normal unmanaged SDK.

According to Scriptspot, the homepage link for Max.NET is here, so use that if the above link goes dead.

# Answer
> 0 votes
Shameless plug: I maintain FbxSharp, A pure C# library for loading FBX files. It's not a wrapper, though. It's an attempt to re-implement the functionality of the FBX SDK in pure C#, so a consumer wouldn't have to bother with interop. At present it's workable, but only covers a subset of the features and versions of the FBX SDK.

# Answer
> 0 votes
I have been using this for a long time.. https://archive.codeplex.com/?p=fbx

Sooner or later this will be too old to use. It only works writes 2009 (6100) version of FBX but its a built DLL ready to use. It reads 2015 with no problems. Just put it in your projects directory and make sure its being copied to the output location. Also.. Make sure you include it with any setup projects! Here's a link to the DLL and A lot of code. Its in VB.net but can easily be converted to C#. This code is from a App I wrote and has a lot of subs and functions you will never need. It does show how to build instanced objects and materials and also non-instanced. http://tnmshouse.com/FBX\_Wrapper/

Why am I doing this? Because its very hard to get any help with FBX and how to work with it. This code is sloppy but has a lot you can use. It has NOTHING about animations although the FBX wrapper apparently can work with them.

---
Tags: c#, .net, importing, fbx
---


# Question
Title: Monogame - Collision not working and invisible walls
I have recently been experimenting with Monogame and XNA (moving from Gamemaker) and decided to work on a simple collision system. Problem is shown in the GIF.

## Main Collision

Each entity (Quick name for anything with properties) has some parameters. Those are:

```
    public Vector2 Position;
    public Vector2 Origin;
    public Vector2 Velocity;
    public Vector2 Speed;
    public Color Color = Color.White;
    public Rectangle Rectangle
    {
        get
        {
            return new Rectangle((int)Position.X, (int)Position.Y, _texture.Width, _texture.Height);
        }

    }

```

I used blocks just to check how collision works on multiple objects next to each other. This is not about optimisation right now. As you can see, there is an invisible wall coming to the right of each vertical block. I can add multiples just to demonstrate:

Now let's get to the collision code. I wanted to do something similar like in GMS2 and check if the box of sprite is going to overlap any other entity in the game at set postition. Since I need to know in the future, which side will be touched, I wrote my code in Entity class like this:

```
    protected bool IsTouchingLeft(Vector2 pos, Entity entity)
    {
        return pos.X + _texture.Width >= entity.Rectangle.Left &&
               pos.X <= entity.Rectangle.Left &&
               pos.Y + _texture.Height >= entity.Rectangle.Top &&
               pos.Y <= entity.Rectangle.Bottom;
    }
    protected bool IsTouchingRight(Vector2 pos, Entity entity)
    {
        return pos.X >= entity.Rectangle.Right &&
               pos.X + _texture.Width >= entity.Rectangle.Right &&
               pos.Y + _texture.Height >= entity.Rectangle.Top &&
               pos.Y <= entity.Rectangle.Bottom;
    }
    protected bool IsTouchingTop(Vector2 pos, Entity entity)
    {
        return pos.X <= entity.Rectangle.Right &&
               pos.X + _texture.Width >= entity.Rectangle.Left &&
               pos.Y + _texture.Height >= entity.Rectangle.Top &&
               pos.Y <= entity.Rectangle.Top;
    }
    protected bool IsTouchingBottom(Vector2 pos, Entity entity)
    {
        return pos.X <= entity.Rectangle.Right &&
               pos.X + _texture.Width >= entity.Rectangle.Left &&
               pos.Y <= entity.Rectangle.Bottom &&
               pos.Y + _texture.Height >= entity.Rectangle.Bottom;
    }

```

For these functions I use two variables, the position at which collision is going to happen and Entity that it should collide with.

And to make everything simple when I just need to know, if it's going to collide at all, I added a PlaceMeeting function.

```
    protected bool PlaceMeeting(Vector2 pos, Entity entity)
    {
        return IsTouchingLeft(pos, entity) ||
               IsTouchingRight(pos, entity) ||
               IsTouchingTop(pos, entity) ||
               IsTouchingBottom(pos, entity);
    }

```

It just checks if there wil be any collision at a set point with a set Entity. ( if you've used GMS, you know what I want to do )

Now Let's go to the movement script. Player is a child of Entity class and has few new variables.

```
    private Vector2 move;
    private float grav = 0.3f;
    private Int32 input_left;
    private Int32 input_right;
    private bool input_up;

```

Input is taken like this:

```
        input_left = Convert.ToInt32(Keyboard.GetState().IsKeyDown(Keys.A));
        input_right = Convert.ToInt32(Keyboard.GetState().IsKeyDown(Keys.D));
        input_up = Keyboard.GetState().IsKeyDown(Keys.Space);

```

Horizontal input is set in such way because of simpler movement. Here is Move() Function.

```
    private void Move()
    {
        move.X = (input_right - input_left);
        Velocity.X = move.X * speed.X;
        Velocity.Y += grav;
        if (input_up)
            Velocity.Y = speed.Y;
    }

```

And the the code Player Collision code:

```
        foreach (var entity in entities) //Looks at all entities created
        {
            if (entity == this) //If it is player, don't check collision
                continue;

            //Horizontal Collision
            if (PlaceMeeting(new Vector2(Position.X + Velocity.X, Position.Y), entity))
            {
                while (!PlaceMeeting(new Vector2(Position.X + Math.Sign(Velocity.X), Position.Y), entity))
                {
                    Position.X += Math.Sign(Velocity.X);
                }
                Velocity.X = 0;
            }
            //Vertical Collision
            if (PlaceMeeting(new Vector2(Position.X, Position.Y + Velocity.Y), entity)) // checking if it's going to collide in 1 step
            {
                while (!PlaceMeeting(new Vector2(Position.X, Position.Y + Math.Sign(Velocity.Y)), entity))// checking if it's not going to collide in 1 pixel
                {
                    Position.Y += Math.Sign(Velocity.Y); // incrementing pixel By pixel until it's going to collide in 1 pixel
                }
                Velocity.Y = 0; //stoping the player
            }
        }

```

And then I Increment the position with Velocity.

```
Position += Velocity;

```

I tried different collision methods and this is how they work out and look like:

## Other Collision One

In the Player Class I used this collision code instead:

```
            if (this.Velocity.X > 0 && IsTouchingLeft(Position + Velocity, entity))
                this.Velocity.X = 0;
            if (this.Velocity.X < 0 && IsTouchingRight(Position + Velocity, entity))
                this.Velocity.X = 0;
            //Vertical Collision
            if (this.Velocity.Y > 0 && IsTouchingTop(Position + Velocity, entity))
                this.Velocity.Y = 0;
            if (this.Velocity.Y < 0 && IsTouchingBottom(Position + Velocity, entity))
                this.Velocity.Y = 0;

```

I basically couldn't move Left when in the right of vertical blocks.

## Other Collision 2

I also tried using this strange code with Rectangle.Intersects()

```
            //Horizontal Collision
            var xRect = new Rectangle((int)Position.X+ (int)Velocity.X, (int)Position.Y, _texture.Width, _texture.Height);
            if (xRect.Intersects(entity.Rectangle))
            {
                xRect = new Rectangle((int)Position.X + Math.Sign(Velocity.X), (int)Position.Y, _texture.Width, _texture.Height);
                while (!xRect.Intersects(entity.Rectangle))
                {
                    Position.X += Math.Sign(Velocity.X);
                }
                this.Velocity.X = 0;

            }
            //Vertical Collision
            var yRect = new Rectangle((int)Position.X, (int)Position.Y + (int)Velocity.Y, _texture.Width, _texture.Height);
            if (yRect.Intersects(entity.Rectangle))
            {
                yRect = new Rectangle((int)Position.X, (int)Position.Y + Math.Sign(Velocity.Y), _texture.Width, _texture.Height);
                while (!yRect.Intersects(entity.Rectangle))
                {
                    Position.Y += Math.Sign(Velocity.Y);
                }
                this.Velocity.Y = 0;

            }

```

This made my program to unresponsive - why? What can I do to prevent it from becoming unresponsive?

I will post the full code of each class: Game1.cs Entity.cs Player.cs Block.cs

# Answer
> 0 votes
You should check if your `IsTouchingLeft`and `isTouchingRight` are working as intended.

I've noticed that in your `IsTouchingRight`, You're doing:

```
pos.X + _texture.Width >= entity.Rectangle.Right

```

However, that's not yet the opposite of this code in your `IsTouchingLeft`

```
pos.X + _texture.Width >= entity.Rectangle.Left

```

Because it's still calculating if it's x-position is greater (more to the right) than the rectangle's x-position, but you're almost there.

You should change the `>=` into `<=` or `<` of the line in `IsTouchingRight`, and try testing around in that section:

```
pos.X + _texture.Width <= entity.Rectangle.Right

```

A little tip: I would've drawn the results of these booleans in the game (using Drawstring()) so I have up-to-date information whether the values are intentional at that moment. that way I know the values without having to use breakpoints. Of course you should only leave them there for testing purposes.

---
Tags: c#, xna, collision-detection, movement, monogame
---


# Question
Title: "Unfortunately game has stopped" error on Android device
In Unity 2018.4.3f1, I am able to build my APK successfully, but when I try to launch it on my mobile device, it shows: "Unfortunately game has stopped".

I don't know the problem is. Here are the project settings I'm using:

# Answer
> 1 votes
In your project open the Plugins folder and open the Android folder.

Open up the android manifest and remove any lines written in the manifest that you are not using such as facebook sdk or another plugin you no longer use ect..

Save it / Rebuild and it should open up fine after that.

**-*edited to improve answer* -**

if the apk builds fine with no 'logcat or build player errors' and then you have issues after deployment.

The game instantly crashes before you even see the splash screen.

Normally these types of errors occur during the initialization of the android manifest file. Most likely due to something that was included within it that you are no longer using such as the 'facebook sdk' or another 'plugin' that has been deleted from the project but is still referenced inside the manifest file or something else along those lines.

After removing those from the file it will no longer hang and should boot up normally.

---
Tags: unity, android, debugging
---


# Question
Title: LIBGDX - Artifacts when scaling background image
I've got a problem with libgdx.

First off, im working with libgdx and box2d on a little physics game.

Im using the aproach mentioned in this answer and thereby setting my camera to some smallish numbers and it worked out fine so far.

Now I've ran into following problem. When drawing my background (1920x1080) I am experiencing artifacts ingame and I am not sure where they are coming from.

I tried linear and nearest Filtering on the Texture with no differing results and I scale the image once via

```
beachSprite.setScale(camera.viewportWidth/Gdx.graphics.getWidth(), camera.viewportHeight/Gdx.graphics.getHeight());

```

This is what the background image looks when opening it With a regular image viewer:

And this is what it looks like ingame:

Oddly enough, there seem to appear no artifacts with smaller images, like the player character, or they are just too small to notice.

Thanks in advance for any help.

# Answer
I was under the wrong impression that the default filter for libgdx is Linear Filtering, so I never actually tried setting it manually. Setting it for the texture solved it for me.

```
beachTexture.setFilter(TextureFilter.Linear, TextureFilter.Linear);

```
> 1 votes

---
Tags: java, libgdx, box2d, image
---


# Question
Title: How to render grid properly, especially over distance?
I'm drawing a grid, pretty much like one can see in the Unity editor itself or any 3D-editor, many 3D-related applications and some games. But it doesn't look pretty in my case.

I put a few random objects to make perspective more readable.

Please also see it full-size for clearer view on the artifacts at a distance.

## How grid is rendered

* Whole grid is one big plane.
* There is texture representing one cell.
* The cell is multiplicated by tiling.

### How there are different line thicknesses on the picture?

It's just 3 planes (each with one grid) with different settings on top of each other. I could leave only one, but 3 grids demonstrate my problem better.

### Additional details:

* Mipmap is disabled (grid cells disappear very soon over distance when it's enabled).
* Trilinear filtration and maximum aniso are set (looks worse otherwise).

## My guess

I think over distance lines get to be thinner than a pixel, especially under shallow angle (hence “verticals” lines look better than “horizontal”.

## Conclusion

Grid rendering is obviously done many times before me, so I presume it should be pretty much wide knowledge how to draw them prettily. I tried to google it, but any query formulation I tried led only to completely unrelated stuff. I have a bit of ideas what I can try, but I believe it would be reinventing the wheel.

P.S.: I'm using Unity engine, but I believe the engine is irrelevant.

---

Plane simple blurring suggested by user29244 and Thebluefish really makes huge difference:  Biggest lines are too blurry now, but it's irrelevant, because easy to fix. Note that I had to **enable** mipmaping if you're trying to reproduce it.

# Answer
You can't avoid this problem, you can try super sampling to make it less jarring ... but high frequency + high contrast works very bad in quantisize space. I go around this with a very small bit of blurring on the texture, it's counter intuitive but then you have more chance than a pixel pick a blur value and make the line looks antialiased on the texture, assuming you never get close enough that the pixel ratio to texel ration sell the trick.

More: https://elementalray.wordpress.com/tag/artifact/
> 2 votes

# Answer
The way you draw them, you have big cells that contain 10x10 small cells. Would it be acceptable to draw only the big cells when they're at a certain distance from the camera? That would be one possibility. Another would be to actually draw lines, like in a wireframe mesh. They are always exactly one pixel wide. That's all the ideas i have right now.
> 1 votes

# Answer
For this kind of thing, it depends on what your goals is. If you're looking to ensure that lines are 1 pixel wide, then you could draw the grid using lines instead of textured triangles:

However with ensuring that lines are 1 pixel wide, when they're so far away that the individual grid spaces are less than 1px, it will look like a solid:

With your existing solution, you may be able to get better results by setting the texture filtering to Anisotropic with an appropriate ratio.

Another option would be to sub-divide your grid into smaller grid spaces. Using either mipmapping or different textures, you could separate your grid texture into 3 different grid sizes based off distance:

* level 1 - 10x10
* level 2 - 5x5
* level 3 - 1x1

Alternatively, manually blurring the line would be another option. It should make the line "wider" without it being too thick.

Finally, a custom shader could do the trick. You could develop a shader that samples the lines appropriately depending on distance from the camera. This option would give you the most fine-tuned approach, though it is much more complex to setup for newer developers.
> 1 votes

# Answer
This might be a bit overkill for this specific problem, but might want to have a look at Humus's Phone-wire anti-aliasing:

http://www.humus.name/index.php?page=3D&ID=89

> The idea is to adjust the radius of the wire to make sure it does not get smaller than a pixel wide. If the wire's radius would make it smaller than a pixel, it clamps the width to a pixel and instead fades with an alpha value corresponding to the radius reduction ratio. For example, if the wire is deemed to be half a pixel large at current distance, it clamps width to a full pixel and sets coverage to 0.5 instead. While the technique solves the problem of aliasing due to thin geometry, it does not address the general problem of jaggies; however, your regular MSAA will take care of that. With both enabled you get a very natural looking wire at any distance.
>
> A similar approach could likely be used on other aliasing prone geometry based on thin geometry, such as antenna towers, pipes and railings.

If you could apply it to your problem, I believe it would solve it in the best way possible.

(I realize that the question is old and the original poster has probably moved on by now, but it might be of use to someone else reading this.)
> 1 votes

---
Tags: 3d, textures, shaders, rendering
---


title: Problem with progress bar visibility

text:
# Question
Title: Problem with progress bar visibility
I have a code with several elements. One of these elements I would like you to initiate hidden.

So I did, set for the progress bar to start hidden. It started to go wrong when and I was calling its visibility (bind) the same stopped starting hidden.

**I did a test with this problematic progress bar and another one created on time:**

**The progress bar that has the visibility setting function appears even if I set it to start hidden:**

**As I said, I believe that this strange behavior is due solely and exclusively to the fact that there is such a function:**

**Even though I have created a boolean variable that imposes a condition, the bar insists on appearing:**

**The variable quoted initiates by default as false:**

I thought the blame could be on the return knot, but as you can see in the fourth image, even putting "hidden", the progress bar appears anyway.

# Answer
Shortly after asking the question I was able to solve my problem and somehow find out the reason for it.

When you create a function to set the visibility of the progress bar. By all indications, their visibility by default becomes true. Regardless of which option you select in the box (you can see this box in the first image of the question, circled in green).

**Code:**

With this code, the bar appears in the game.

As seen also in the question (image 3), the variable I created starts being false. And by the code it ends up that the commands go nowhere. As you could see, if you do not have code the default value becomes what counts.

Soon the progress bar is visible.

**Thus, it is clear the need for you to have to define when the bar will or will not be visible:**
> 0 votes

---
Tags: unreal-4, hud
---


# Question
Title: Modifying z axis position of a canvas and adapting it to camera
I have a camera with y rotation of 0.

And i have a canvas with position value of `(0f,76.29f,41.82f)`. The size value of the canvas is `(194.1f,307.8f)`. I want to modify the z value of the canvas to -10.

```
public Canvas textcanvas;
void Start () {
textcanvas.anchoredPosition = new Vector3 (0f, 24.5f, -10f);
}

```

But i get an error "error CS1061: Type `UnityEngine.Canvas' does not contain a definition for`anchoredPosition' and no extension method `anchoredPosition' of type`UnityEngine.Canvas' could be found. Are you missing an assembly reference?"

Also, when i succeed moving the canvas, does the size of it adapting to the camera automatically?

# Answer
`((RectTransform)textcanvas.transform).anchoredPosition`

The problem here is a very basic one: `Canvas` objects aren't `Transforms`. Transform objects are the only ones that contain position information, so you can't modify the position of the canvas by calling `textcanvas.anchoredPosition` because it doesn't exist there, you need to access the canvas's Transform: `textcanvas.transform.anchoredPosition`

However this won't work either, not directly, because there are two Transform classes:

* Transform (for most GameObjects)
* RectTransform (for most UI objects) which extends Transform

So we have to cast from one to the other, as the `GameObject.Transform` property is of type `Transform`, not `RectTransform` and `anchoredPosition` is a property of `RectTransform` and not `Transform`. Hence the final solution:

`((RectTransform)textcanvas.transform).anchoredPosition`
> 1 votes

# Answer
If you want the canvas to appear in front of a camera, you need to change the Canvas component to "Render Mode: Screen Space (Camera)" or "World Space" and then drag your camera into the canvas component.

If you want your menu to appear "transformed" I find the easiest thing to do is make an empty object under your canvas (I called it MenuTransform), and then place all your UI elements as children of that (like the panel in this example). Then, you can transform all the elements at once.
> 1 votes

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


# Question
Title: Should I scale gravity for small objects?
If I am working with objects that are small in real life, but in the Unity world they are scaled larger, should I increase the Gravity with the scale of the objects?

For example, if an object of size one would actually be 10 cm across, would gravity scaled to be 10x make the object behave more like a small object would in real life.

I know objects fall at the same rate, but the rate is the same so small objects fall more in proportion to their size don't they?

# Answer
The Unity default gravity of 9.81 units / second² assumes that one unit is one meter and the game takes place on Earth.

If these assumptions are not true, you would theoretically have to adjust it accordingly. If one unit in your game is actually just 10cm, then you would have to increase gravity to 98.1 in order to be physically correct.

But the question is: Do you actually *want* the gravity in your game to be physically correct? Human intuition often has a wrong idea of how gravity acts on objects which are very large or very small. People intuitively expect that a humanoid character grown to the size of a skyscraper or shrunk to the size of an ant would move and fall just like a regular sized person in regular gravity, even though that would not be the case.

So keeping the gravity at the default value might actually *feel* more correct to your players even though it is not. And besides, even games which are actually meant to have a realistic scale and realistic physics sometimes adjust the gravity. Because even though 9.81 m/s² is correct in theory, it might still feel wrong in the context of a particular game. Sometimes gravity is changed globally, sometimes just for specific objects (the jumping mechanics of player-characters in particular rarely obey the laws of physics). The only way to find the perfect gravity value for *your* game is rigorous playtesting.

I am looking forward to playing your game.
> 4 votes

# Answer
I dont't think there is an objectively correct answer to your question, in the sense that it is up to how you feel it should feel. It is ok and not uncommon to tweak the gravity scale as well as any other physics parameter of your game engine in order to provide a more satisfactory game experience.

To make a small example, say that your small object is a rock and you want to throw it. Perhaps with gravity scale set to 1 the throw will not look so cool or fast, but if you increase the gravity scale it will have a faster fall, simulating an heavier object. On the other hand, if the object that is falling is a feather, you should reduce the gravity scale to have a slower fall. It's an iterative process: try different values until you find the one that fits the effect you were looking for.
> 0 votes

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


# Question
Title: How do I make my rigid body rotate a fixed angle value each time I click the movement keys
Ive tried some experiments with the character rotation, but I dont want it to rotate when he touches something, but I also need to unfreeze the Z axis rotation or else the character doesnt rotate when I press a key. My code is this right now, each time I press play (with the Z axis unfreeze) the character just turns like 10 degrees each time I press a key and he is still interacting with objetcs, I dunno what I can do and I might need some help :/

```
public float speed = 2f;
private Rigidbody rb;
private float midJump = 1;
private Rigidbody rB;

//Character Movement

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

    float moveHorizontal = Input.GetAxis("Horizontal");
    float moveVertical = Input.GetAxis("Vertical");

    Vector3 movement = new Vector3(moveHorizontal, 0f, moveVertical);

    rb.AddForce(movement * speed);

//Character Jump

    if (midJump == 1 && Input.GetKeyDown(KeyCode.Space))
    {
        rb.velocity = new Vector3(0, 45, 0);
        midJump = 2;
    }

//Character Rotation

    else if (rb.velocity.y == 0.0)
        midJump = 1;

    {
        if (Input.GetKeyDown(KeyCode.D))
            rb.AddRelativeTorque(new Vector3(0, 0, 90));
        rb.angularVelocity = Vector3.zero;

        if (Input.GetKeyDown(KeyCode.A))
            rb.AddRelativeTorque(new Vector3(0, 0, -90));
        rb.angularVelocity = Vector3.zero;

        if (Input.GetKeyDown(KeyCode.S))
            rb.AddRelativeTorque(new Vector3(0, 0, 180));
        rb.angularVelocity = Vector3.zero;

        if (Input.GetKeyDown(KeyCode.W))
            rb.AddRelativeTorque(new Vector3(0, 0, 0));
        rb.angularVelocity = Vector3.zero;
    }

}

```

# Answer
If you don't want your player's rotation to be affected by physics collisions, then freeze the Z-axis rotation and use one of these properties/functions which change the direction directly instead of indirectly through torgue:

All these different ways do basically the same thing, but have subtle differences. For more information about what these differences are and whether or not they are relevant to your particular game, check out the relevant documentation behind the links.
> 1 votes

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


# Question
Title: How do I ignore 1 axis on vector 3 reset to 0,0,0?
coding noob 3D artist here. I'm trying to create a scrolling parallax background with 3D objects, I have it set so that when it scrolls off screen, it resets it's position off screen on the opposite side so it repeats. However, If I want to have multiple depths to these background objects, it needs to not reset that objects position in the Z axis, or when it loops once it'll just overlap the other objects. How can I tell it to ignore the Z axis on resets? Here's what I have so far.

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

public class BGSLIDE : MonoBehaviour
{
    public float speed = 2.0f;
    public Transform cube;
    public CC player;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        cube.position += new Vector3(speed*player.velocity.x, 0, 0);
       if (cube.position.x > 10)
        {
            cube.position = new Vector3(-10,0,0);
        }
       if (cube.position.x < -10)
        {
            cube.position = new Vector3(10,0,0);
        }

    }

}

```

# Answer
> 1 votes
It's simple, you can just read `z` of that position and pass it as a parameter when creating `Vector3` for new position:

```
void Update () {
    var p = cube.position;
    cube.position = new Vector3 (
        Mathf.Clamp (p.x + speed * player.velocity.x, -10, 10)
        0,
        p.z
    );
}

```

Note the `Clamp` call. It does the same as your two conditions, but shorter.

---
Tags: unity, parallax-scrolling
---


# Question
Title: How do I make the turning of my character smooth?
I'm pretty sure I need to use the `Quaternion.Lerp` although I don't know how, my character already rotates but it's instantly, which is pretty unrealistic and not smooth. I'm extremely new with Unity (I just started 2 days ago), so I think asking here is a good idea since I will get help from people with experience:

```
private Rigidbody rb;

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

void Update()
{
    //Character Rotation
    {
        if (Input.GetKey(KeyCode.D))
            rb.transform.rotation = Quaternion.Euler(0, 90, 0);

        if (Input.GetKey(KeyCode.A))
            rb.transform.rotation = Quaternion.Euler(0, -90, 0);

        if (Input.GetKey(KeyCode.W))
            rb.transform.rotation = Quaternion.Euler(0, 0, 0);

        if (Input.GetKey(KeyCode.S))
            rb.transform.rotation = Quaternion.Euler(0, 180, 0);
    }
}

```

# Answer
> 3 votes
Create a private variable for the desired rotation. This variable represents the direction the object is supposed to face, but might not yet face towards. Have key input change the value of that variable.

Then use `Quaternion.RotateTowards` in your update-function to gradually change the actual rotation towards the desired rotation

```
public float turnSpeed = 200.0f; // adjust to taste in inspector

private Rigidbody rb;
private Quaternion desiredRotation = Quaternion.Euler(0, 90, 0);

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

void Update() {
    //Character Rotation
    {
        if (Input.GetKey(KeyCode.D))
            desiredRotation = Quaternion.Euler(0, 90, 0);

        if (Input.GetKey(KeyCode.A))
            desiredRotation = Quaternion.Euler(0, -90, 0);

        if (Input.GetKey(KeyCode.W))
            desiredRotation = Quaternion.Euler(0, 0, 0);

        if (Input.GetKey(KeyCode.S))
            desiredRotation = Quaternion.Euler(0, 180, 0);
    }

    rb.transform.rotation = Quaternion.RotateTowards(
           rb.transform.rotation,
           desiredRotation,
           turnSpeed * Time.deltaTime );
}

```

And by the way, it might be a good idea to not constantly recreate the quaternions but to put them into constants. This improves performance (although only to a negligible amount in this use-case) and makes the code more readable:

```
private static readonly Quaternion ROTATION_NORTH = Quaternion.Euler(0, 0, 0);
private static readonly Quaternion ROTATION_EAST = Quaternion.Euler(0, 90, 0);
private static readonly Quaternion ROTATION_SOUTH = Quaternion.Euler(0, 180, 0);
private static readonly Quaternion ROTATION_WEST = Quaternion.Euler(0, -90, 0);

/*...*/

if (Input.GetKey(KeyCode.D))
   desiredRotation = ROTATION_EAST;

if (Input.GetKey(KeyCode.A))
   desiredRotation = ROTATION_WEST;

if (Input.GetKey(KeyCode.W))
   desiredRotation = ROTATION_NORTH;

if (Input.GetKey(KeyCode.S))
   desiredRotation = ROTATION_SOUTH;

```

# Answer
> 0 votes
From a technical perspective, `Quaternion.Lerp` is what you want. From a gameplay perspective, you are taking the wrong approach.

Control your character's movement via its position, so that you have good controls. Then animate the character separately, without using physics. (Unless you are using root motion, but that's a different conversation.)

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


# Question
Title: How do I link a GameObject activated state to a UI button being held?
How do I go about this functionality: When a user taps and still holds onto a UI button, a GameObject will be set active, when they release the UI button, the GameObject will be deactivated.

# Answer
> 0 votes
Add the event trigger component, then add the pointerDown and pointerUp events, then create a script with 2 public methods of type void, and respectively reference them in the pointerDown and pointerUp events, one should contain the functionality that will happen if the user presses and holds(attached to the pointerDown event), while the other should contain the functionality that will happen if the user lets go of the button(attached to the pointerUp event).

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


# Question
Title: How can I exclude an object from receiving shadows?
I would like to make it so that a certain object is being excluded from receiving shadows.

While it itself should cast shadows onto other objects, it should not receive shadows from other objects.

How can I achieve this?

I'm using HDRP.

Seemingly, the option not to receive shadows is not present when using HDRP.

The MeshRenderer looks like this:

# Answer
> 0 votes
The Unity bug support told me that this can be achieved by using HDRP Light Layers and pointed me to this for a start:

https://forum.unity.com/threads/light-layers-in-hdrp.619609/

---
Tags: unity
---


# Question
Title: Is deferred rendering/shading possible with OpenGL ES 2.0 ?
I asked this on StackOverflow, but it might make more sense here:

Has anyone implemented deferred rendering/shading under OpenGL ES 2.0? It doesn't support MRTs, so with only one color buffer, it's not something that can be implemented in the "usual" manner.

Specifically, I'm exploring on iPad, iPhone4 (maaaybe iPhone 3gs), and Android. On the GLESView app on iPad/iPhone4/iPhone3gs, the GL\_OES\_RGB8\_RGBA8 extension is present, and I haven't looked too deeply yet, but with 8bits/channel, this idea is interesting: http://www.gamedev.net/topic/562138-opengl-es-20-and-deferred-shading/

Any other ideas? Is it even worth doing, performance-wise?

# Answer
> 16 votes
Yes, it is possible. However, it isn't particularly worthwhile.

First, unless you have access to the NV\_draw\_buffers extension (as the name implies, it is NVIDIA-only. So unless you're running on Tegra, you don't have it), framebuffer objects under ES 2.0 can only render to *one* image at a time. So to generate your G-buffers, you will need to render your scene multiple times, thus taking away one of the advantages of deferred rendering.

Second, bandwidth on mobile platforms is not the same as you would get even on mid-grade GPUs. And bandwidth is critical to making deferred rendering (for many lights) worthwhile. Without that bandwidth, the light passes are really going to hurt, performance-wise.

Third, PowerVR hardware is really not designed for this kind of thing. It optimizes rendering with its tile-based rendering hardware. So deferred rendering on top of that would be less helpful than in a traditional scan-conversion architecture.

# Answer
> 6 votes
The main problem is Fillrate. On mobile GPUs, your fill rate is low that you can't do Deferred shading in realtime at native resolution.

On iPhone 4 & iPad 1, fillrate is just ridiculous. The only device IOS with good fillrate is iPad 2, but i doubt there is enough... On android, only Tegra devices have the GL\_NV\_draw\_buffers to use MRT but fillrate is very low too. The Mali 400 seems to have the best fillrate. If you want cry, just try to fill a color rectangle at fullscreen resolution 4 times... Many devices can't do it 60 fps.

On desktop GPUs, you have 10 times (or more) fillrate as mobile gpus. Don't forget that mobile GPUs use the same memory as CPU and you don't have dedicated memory.

There are some examples in WebGL (same API) so that isn't a limitation of the API.

# Answer
> 1 votes
Really you have to consider what is the absolute minimum you need for a deferred renderer. If you fall back to deferred lighting it reduces the amount of data that needs to be stored in the GBuffer, and really it's a helluva lot cheaper than rendering half the scene 3 time or more to support a low amount of lights.

I would go for the following GBuffer format:

* Reuse the depth buffer for the lighting pass, not sure how widely this is supported on mobile devices, but it's a free depth texture.
* A single GBuffer texture, inside it I would store: Normal U, Normal V, Param 0, Param 1. Lambert-Azimuthal encoding looks really nice for normals and compresses them down into just two components, relatively cheap to encode and decode as well.
* Two parameters for lighting variables is a lot, could use one as an enumeration for multiple lighting functions if the hardware does well with dynamic branching.

Deferred lighting is similar to deferred rendering, except you render the scene twice:

1. Render Geometry Depth, Normals, and Lighting Parameters into the GBuffer.
2. Render Lights into the accumulation buffer.
3. Render Geometry with material shaders, composite your lighting here as well. If your good with working out reverse operators of lighting equations you can do a LOT of really cool things with this step.
4. Do any post-processing you can afford, be sure to abuse the depth and normal textures to death here for efficiency sake.

About storing the lighting results. I've become fond of storing diffuse color and specular luminance so that the accumulation buffer only needs to be a standard 32-bit color texture. You can estimate the specular color by calculating chroma of diffuse color and combining that with specular luminance.

The most important part however is going to be using the depth-stencil buffer to it's fullest, ensure that your not rendering any of the lighting code where it's not needed. I'd even go so far as to add some discard statements into the fragment shaders on terms that will drop light visibility below the device's displayable range (1e-3 is usually a safe cutoff).

# Answer
> 1 votes
Consider deferred lighting. In a nutshell, deferred lighting is a technique that uses a reduced version of deferred shading to calculate a screenspace lightmap. In a second pass, the geometry is rendered again using the screenspace lightmap as lighting information.

This technique is used to reduce the size of the G-Buffer, since fewer attributes are needed. It also buys you the advantage, that the G-Buffer and the screenspace lightmap can be of lower resolution than the screen.

I had implemented a strict GLES 2.0 based renderer (although an experimental one), and I managed to boil the G-Buffer down to one RGBA texture (yes, I used a texture2D instead of a renderbuffer). It contained the screen space normal map + the depth buffer in the alpha channel (which was compressed using a logarithm, as far as I remember).

The position attributes (called ***world*** here) can be calculated during the lighting pass using the fact, that in a perspectivic projection, *.xy* is devided by *.z*, so that:

$$xy\_{frustum}=xy\_{world}/z\_{world}$$

I approximated the position attribute's *xy* by doing:

$$xy\_{world}=xy\_{frustum}\*z\_{world}$$

Note: I had to do further adjustments depending on the projection matrix' settings.

Also worth noting is, that I was capable to omit the *.z* component of the normal vectors, since i could reconstruct *.z* from *.xy* since the normal vector is normalized so that:

$$ \sqrt{x^2+y^2+z^2}=1\\ x^2+y^2+z^2=1\\ z^2=1-(x^2+y^2)\\ z=\sqrt{1-(x^2+y^2)} $$

Using this technique, i was capable to free up another channel in my RGBA G-Buffer and used this to store the screen space specular-map (or glossiness, if you will).

# Answer
> 0 votes
Yes, it is absolutely possible. Fill rate is not such a problem because mobile graphics chips are designed to deal with very high resolution screens. In fact, deferred rendering helps with this because your lighting calculation is independent from scene complexity, so overdraw doesn't cause a slowdown. Here is my implementation on a fourth generation iPad: http://www.youtube.com/watch?v=K4X1oF6b4V8

If you want four times the performance, just half the resolution of the texture you render to. I can't really see any different with 3D graphics on a retina screen, anyways.

Mobile graphics chips are extremely good at deferred rendering because of the way they handle render-to-texture. Unlike PC graphics cards, which typically incur a huge performance hit when you start rendering to a texture instead of a window context, mobile graphics are designed to do this with no performance hit. So you get the scalability of a deferred renderer, without the initial performance penalty you experience on a desktop graphics card.

At the time of my implementation, OpenGLES was missing render to multiple targets, so I had to draw the screen color and normal in separate passes. This may be fixed in more recent versions of OpenGLES, but don't know if the solutions are available yet in consumer mobile hardware.

---
Tags: android, ios, opengl-es2
---


# Question
Title: Do I have to credit the author of a free asset from the asset store?
Am sure that some people have been asked this question, and my researches yields a no, but I want to know from here. Do I have to credit the owner of a free asset that I used for my project from the unity asset store? Example: if I download a model from the unity asset store and use it in a game design, do I have to give credits to the person that provided the model on the asset store? Like this: https://assetstore.unity.com/packages/3d/characters/humanoids/scifi-robots-113422

# Answer
> 7 votes
*I'm assuming that by "free asset", you mean an asset available on the unity Asset Store that is shown when filtering by "free" (resulting in something like this).*

---

Maybe.

It will depend on the asset. For instance:

* if you get the "Unity-Chan!" Model, you'll have to display somewhere the *"license logo or the license sign separately"* as specified by the “Unity-Chan” License Terms and Conditions;
* if you get the Standard Assets provided by unity, you'll have to dig, find, read and understand the actual license, where there is no mention that you must credit the author;
* if you get the SciFi Robots, you'll find no license on the Asset Store page, and no readme and no license.txt in the package. I'm not exactly sure what license apply here, so I'll suggest you ask the author what are the terms of use of their asset before you commit to it.

It's unfortunate that the Asset Store page does not provide a clear "license" section. Until they add this, I'm afraid you'll have to search and ask for each asset.

---
Tags: unity, assets, licensing
---


# Question
Title: How can I recreate the Darwin Project's Particle?
I want to recreate electronic particle in Darwin Project.but I don't know how can I use vfx graph to make this effect.I upload this effect in youtube you can see in the link below:

Darwin Project Electronic Particle Effect Youtube

# Condensation

# Answer
> 2 votes
This is what I came up with after an hour of playing around. It doesn't look exactly like the effect from the video, but it's a start which could easily be tweaked to get pretty close (seen from the side, not from below):

I did this by creating a VFX graph and controlling some of its parameters with a timeline.

# The VFX Graph

Let's first look at my VFX graph. First the "Spawn" and "Initialization" sections:

The initialization node spawns the particles in an AABox with a height of 0 - or in other words a rectangular plane aligned to the floor. The spawn rate is controlled by a parameter. I am multiplying the parameter by a constant, so I can have that parameter in a handy range between 0 and 1 in the timeline while I can control the general density through that multiplication factor.

The parameter has the **Exposed** checkmark enabled. This is important, because it makes it possible to control that value from something outside of the particle effect, like a C# script or like in this case a timeline asset.

Now for the Update section:

The update-node is based on "Conforms to Sphere". This causes all the spawned particles to get "sucked into" a spherical shape. The height of the sphere is the second parameter I exposed. I again used a multiplication node for better control over the maximum height without having to fiddle with it in the timeline.

I also added a dash of turbulence for flavor (to make the whole particle field look a bit more random).

A screenshot of my output-node isn't worth inlining. It's almost unchanged from the official template, just with the color changed from yellow/orange to cyan/blue.

# The Timeline

Now for the interesting part:

I created a timeline-asset for my particle effect. Then I added the two parameters of my VFX to the timeline:

1. go into "record" mode for that timeline clip (the red circle right of "New VFX")
2. open the inspector of the VFX object
3. Right-click on each of the "Parameters" and select "Add Key"
4. Switch off record mode

Now you have the green curve to edit the spawn rate over time and the red curve to edit the sphere height over time.

Here I set the spawn rate to only spawn particles during the first 5 seconds, with its peak at 2.5 seconds.

The altitude of the sphere is set to slowly raise over the first 5 seconds, then smash down in a parabolic curve.

# What next?

What you could do next is make the sphere explode after it reached the ground position. You can simply do that by adding another parameter which controls the attraction force and stick force of the "Conforms to Sphere" node and adding it to the timeline. Set that curve to quickly switch from positive to negative the moment the sphere hits the ground. This should cause the particle cloud to explode.

I am looking forward to seeing some awesome particle effects in your game.

# Download

I tweaked the effect a bit more and added the explosion effect as described above. I also added a floor collider to make sure none of the particles from the explosion go to waste. The floor collider is controlled by a bool variable and is only active during the second phase so it doesn't get in the way of the spawned particles.

Here is the asset pack with the VFXGraph, timeline and a prefab which combines them.

---
Tags: unity, particles, special-effects, vfxgraph
---


# Question
Title: Is it legal to develop a game using software which is unavailable in my region due to legal reasons?
I was wondering: what would happen if I published a game while the software I used is not available in my area?

I was planning to make a game using Unity Personal, and it just happened that it's not available in my area (Syria). Should I keep looking for alternatives or is it okay to publish it since I could download the software?

Here's the text that appears when I try accessing either unity.com or unity3d.com without a VPN connection:

> Access Denied
>
> You don't have permission to access "http://unity3d.com/" on this server. Reference #18.c7581002.1562292126.1b42107

# Answer
Unity is not being made available to you due to trade restrictions:

> Unity Technologies is listed and incorporated as a business in the U.S. This means that as a company, we must abide by the legal sanctions implemented by the U.S Government.
>
> This means that some countries do not have access to the Unity sites. Currently countries on this list include Iran, Cuba, Syria, Sudan and North Korea.
>
> Unfortunately, if you are a developer in any of the above countries there is not anything that can be done regarding your access to Unity. It is however, important to keep up to date with any changes that may be made by the U.S Government in relation to these sanctions.

Next, there's the matter of the Unity Software Additional Terms:

> **7. Export Law.**
> You agree to comply fully with all export laws and regulations to ensure that neither the Unity Software nor any technical data related thereto nor any direct product thereof are exported or re-exported directly or indirectly in violation of, or used for any purposes prohibited by, such laws and regulations.

Since your access is being restricted due to trade restrictions & they have disclosed the nature of the situation, my read is that your use of Unity would also violate their ToS, which means that you could be subject to the following from the Unity Terms of Service

> **7. Termination And Account Cancellation**
> Unity will have the right in its sole discretion, and without prior notice to you, to suspend or disable your Unity Account or terminate the Agreement and/or your right or ability to access or use any of the Services if: (a) you breach this Agreement; ...

As such, if you are using Unity when you are legally not permitted to do so, they can pull your account & products. They likely have some obligation to take action and that's a relatively easy solution for them to take which allows them to avoid some significant legal problems for being non-compliant.

There may be additional legal ramifications as well; for that you would need to consult with a lawyer. Ultimately, I can't tell you whether or not it's okay for you publish with Unity. All I can provide is my informed opinion & that is to do so would violate their terms of service and place your work in jeopardy. I wouldn't willing use such a strategy with my own work.
> 13 votes

---
Tags: unity, legal
---