# Question
Title: Implementing a build queue in a browser based game
I need to be able to execute certain events at a given time in my game, for example, say the player "Builds a building" this building should take 15mins to process. Implementing this seems straightforward enough, simply enter the event into the database and execute the event when the time comes for it to be completed.

However, it is my understanding that i would need a script that is running permanently on the server and continually checks the event database for delayed events to execute and process them as needed. My question is, is this the right approach or should i be tackling the "event que" differently?

Some of the events that will be processed can effect many different players so they would need to happen in real time, as opposed to be lazy loaded.

You can see similar such event queues in browser games such as travian, grepolis etc.

Update - If i was to implement a purely lazy load method, are there any flaws in the following pseudo code?

```
    ## upon player_x pages load

## start a loop that will only exit once all needed events have been processed

## check for any events initiated by player_x that are overdue

## get event and lock it for processing

    ## does this event involve another players object?

        ## if it does, then lets check if said object also has any events that should happen before this event

            ## if it has, then lets process one of those events instead, and loop again once processed

            ## if it doesnt have any previous events, then we're free to process this event, do it

## loop till all overdue events for player_x's object are done

```

# Answer
I faced a similar problem before and, given your needs, I'd go for a slightly variation of your pseudo-code.

Considering that you could have events issued by other player but which can be needed for stats purpose, for example if I open the "Most resource ladder" I want to see the data up to date for every player, not only me, and stuff like this, I prefer to elaborate events belonging to every players when somebody opens a page, so you will have the "game world" synchronized every time.

Now somebody could say "The first player logging in will have to wait for a ton of events elaboration", but that's not completely true. In fact if you have such a huge amount of events, it means you have lots of players, which means lots of connections, which means that the elaboration load will spread over those connections. If you have fewer connections, they must be generating fewer events, so the load still is not too heavy.

An addition to this strategy could be creating your "event executor" as an independent script, called by users when they load a page, and also called by a cron set like every 15 or 30 minutes, so you can thin the queue even if nobody logs for a while. This way you are sure that the first logging player must at most wait for events expired in the last 15 minutes.

I found this solution pretty smooth in my projects, I hope it can also suit yours.
> 4 votes

# Answer
It's not uncommon to put in a cron script that invokes a PHP script or whatnot every minute or so.

If you need finer granularity, you need a running event processor.

You can also use a message queue service to submit delayed events that invokes an HTTP script when necessary. Batch processing events will be better for power consumption, though. It's easier to go the cron route, which is compatible with most cheap PHP/MySQL web hosts.
> 1 votes

# Answer
> However, it is my understanding that i would need a script that is running permanently on the server and continually checks the event database for delayed events to execute and process them as needed. My question is, is this the right approach or should i be tackling the "event que" differently?

**Assuming your game is only played through player prompts/observation** (more on that later), there are simpler ways of doing this.

Assume I am building a house, and it is currently Jan 1, 2019 at 00:00 precisely. If you were to store the building's status as a history table, the game could register two statuses already:

```
 Player | Building | Status   | Timestamp
=================================================
 Flater | House    | Building | 01/01/2019 00:00
 Flater | House    | Built    | 01/01/2019 00:15

```

Note that the second line is *in the future*. But when you fetch the item's current status, you use a query similar to:

```
SELECT TOP 1 Status
FROM BuildingStatusHistory
WHERE Timestamp <= GETDATE()   -- GETDATE() give you the current date and time
ORDER BY Timestamp DESC

```

What you will notice is that when I refresh the page before 00:15, the query will return "Building". But when I query the page at 00:15 (or later), the same query will return "Built", even though we did not actually change the database since then.

If you want to show a progress bar, you can do this based on three values:

* The timestamp of the most recent (already active) status = left side of the progress bar
* The current time = progress of the progress bar
* The timestamp of the *next* event (that is not yet active) = right side of the bar

---

**Assuming your game is only played through player prompts/observation**

What I mean by this is that the game is played through player observation:

* The player sends a web request for information
* The backend runs a query on the DB
* The player receives the information they need

If your game is expected to e.g. send out emails to the player when their house is built, that's different. Then, you need some agent that sends that email *precisely* at 00:15 when the house is built, and this means you either need an always-online component, *or* (if it's acceptable for your use case) you used a scheduled service that regularly polls the database to see if there are actions that need to be taken (which means your players may have to wait for their email a bit longer).
> 0 votes

---
Tags: browser-based-games
---


# Question
Title: How can I handle scripting-like tasks in my ECS?
So I have been getting more and more into ECS architecture, and I am having a bit of trouble wrapping my head around how to handle custom actions/callbacks.

For instance, let’s say I want to have a concept of a button in my game. One button opens a door. Another button drains the water out of a room. Another button opens a door, and deactivates all the cameras on this level.

With a data-driven ECS, I am struggling to figure out how one would handle this kind of diverse, specific behavior short of writing a massive enum with a case for each specific action.

---

My ECS is a pure data-driven one: entities are indexes to components, components are just data, and systems are implicit: they are just anything which operates on entities/components.

# Answer
> 3 votes
I'd recommend solving this in pretty much the usual way: with a scripting language. (This could be a text-based language like LUA, a nodegraph based visual scripting tool, pre-digested bytecode, etc.)

ECS exists to help make the things you do hundreds, thousands, or even more times each frame execute as efficiently as possible.

But one-off level scripts like this are not that kind of thing, almost by definition. You'll usually have only a few dozen to deal with, and many will be event-driven like the button example, rather than updating continually. So it's totally OK that they're not componentized — as long as you're careful not to do anything hideously wasteful in these scripts, they shouldn't be a major drain on your framerate.

I'd recommend having one of your ECS systems be your scripting engine. The data it operates on are virtual machine state vectors, representing the current state of execution of each custom script. When this system updates, it runs your scripting virtual machine to tick these scripts forward a frame, doing whatever custom stuff they want to do.

Your buttons, as part of their data, can specify a script entry point that should be fired when they're interacted with. Your button interaction system processes the interaction, and if it needs to call a new script it logs a message for the scripting system, saying "spin up a new VM state at this entry point and start executing it" (optionally with a few IDs pre-populated on the stack so you can refer to which button was pressed & who pressed it)

The scripting system, when its turn comes in the update order, picks up that message and starts executing the script. If it finishes in one frame it can immediately recycle the VM state for the next script to be called. Otherwise the script can yield to resume later (to control staged transitions over time and the like), and the system can keep its state on the back burner to resume on next frame's update.

This gives you the flexibility to combine high-performance, data-oriented components and systems for the stuff you do uniformly/frequently, with flexible/designer-friendly scripts for the stuff that's more one-off or needs frequent adjustment as your game's design evolves.

If you find you're doing something complex & heavyweight enough or frequently enough in one of these scripts that it is impacting performance, then that's a good candidate to pull it out and make it into its own component(s)/system(s) in native code - something you can do incrementally as needed, as you learn more about your game's performance characteristics.

# Answer
> 0 votes
It is a simple question of how you handle your scripting, how your ECS arcitecture is designed and so on.

In a date-driven ECS, so only data in your entities without any functions, these functions are 'outsourced' to your systems. Your Entities have a graphics component, so the graphic system works with those components. Same with physics components.

So, if your entity got for example an interaction component, this component could hold a reference to a script file in a dedicated script system. Now, when you interact with that Entity, your gamerule system or whatever gets the information to call the referenced script via the script system.

Now to stick to your examples, your component may need aditional information in addition to the script reference:

* To Open a door, your corresponding interaction component would also need to hold the reference to the door entity
* clearing out water of a room would either need the reference to the room, the tiles, maybe the water are some entities themselfs

Of course this highly depends on your arcitectures. Maybe you got an event system, that could call your scripts. Your entities could be created by scripts themself and so on.

---
Tags: architecture, entity-component-system
---


# Question
Title: How do you create a VR game for a personal VR headset you're making?
If you were to create a whole new VR headset and want to put a game on it, how would you? I know that you you could use Unity and UE4 to create games but those are for stuff like the Rift and Vive. I might be mistaken, but does anybody know the answer to my question?

# Answer
Actually, OpenVR (used by both Unity and UE4) is an open platform. If you implement it on your side of things (i.e. the headset), you can use both editors.
> 7 votes

---
Tags: virtual-reality, oculus
---


# Question
Title: Multiple layers processing mouse input, instead of only the top layer clicked
Rectangles are grouped and attached to a "layer" extending Stage.
Each layer is added to a multiplexer in a Screen extension.

There are 2 layers:

* Top has the 1 big rectangle & group members (smaller colored rectangles)
* Bottom has the 2 big rectangles & their members

The 3 big rectangles are all the same size & color (turns yellow if it detects the mouse is over it, for debugging purposes)

When you click on it, it brings its **group** to the front of its **layer**.

The problem is that both the top layer and bottom layer are processing the input, though grouping and drawing stuff works fine.

In the screenshot, only the top-most big rectangle should be yellow at the cursor's position:

# Answer
> 1 votes
Assuming that you're using some kind of `Event`, you should mark that the Event as "handled" to prevent it being propagated further.

You can do this in the Actor by calling `Event.handle()`.

If you are using the Stage methods, you should also be able to do this by returning `true` from (eg) `Stage.mouseMoved`. This will indicate that the input has been processed and does not need to be sent to other objects.

---
Tags: libgdx, input, mouse
---


title: Draw a grid of tiles

text:
# Question
Title: Draw a grid of tiles
I've made a tiledrawer, which takes a list of sprites, and then randomly picks one of those sprites, and draws it in a 2D grid.

This works, but I have a feeling I'm not doing it the right way. When the camera moves over the area, the tiles look choppy.

My code for the generator:

```
public GameObject tileType;
public Sprite[] sprites;
private Grid grid;
public int gridRadius = 100;

// Start is called before the first frame update
void Start()
{
    if (sprites == null || sprites.Length == 0)
    {
        return;
    }
    var tileSize = 0.5f;
    var tileScale = 1.56f;

    var half = gridRadius / 2;
    var beginX = half * tileSize * -1;
    var beginY = half * tileSize * -1;

    var beginOffset = new Vector3(beginX, beginY, 0);

    grid = GameObject.FindObjectOfType<Grid>();
    var offset = new Vector3(0.25f, 0.25f, 0) + beginOffset;

    for (int x = 0; x < gridRadius; x++)
    {
        for (int y = 0; y < gridRadius; y++)
        {
            var tileOffset = offset + new Vector3(tileSize * x, tileSize * y, 0);

            var tile = Instantiate(tileType, transform.position + tileOffset, Quaternion.identity, grid.transform);
            tile.transform.rotation = transform.rotation;

            var renderer = tile.GetComponent<SpriteRenderer>();
            tile.transform.localScale = new Vector3(1.5f, 1.5f, 0);
            renderer.transform.localScale = new Vector3(tileScale, tileScale, 0);
            renderer.sprite = RandomSprite();
        }
    }

}

private Sprite RandomSprite()
{
    var rand = Random.Range(0, sprites.Length - 1);
    return sprites[rand];
}

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

}

```

When I say "choppy", I mean the tiles sometimes generates lines between them, sometimes not, even though there is not space between them.

What is the right way of drawing a grid of tiles, from a list of sprites?

# Answer
In my opinion there are a couple different things this could be.This is one of those things that will just require some general troubleshooting to figure out. But these are three things I would try.
**1 Texture**
It could just be that the image isn't tile-able. It looks like you are picking a random sprite from an array of sprites so maybe certain sprites tile well with others but not in certain scenarios.
**2 Compression**
Could be as simple as needing to adjust the sprite compression settings on the sprite importer. Sometimes unity's compression algorithms leave images with unexpected artifacts.
**3 Too much scaling**
This isn't so much a cause of the problem but its a problem that should be addressed.I don't think you should be playing around with scaling like that in script unless you have a very good reason. It seems like when I have written or seen code similar to this it is because there is import settings that need to change or scaling issues further up the line. If you need to scale you must compartmentalize(i.e. animation) where when you are done scaling an object you should reset it back to its original scale or vector3.one.One last note I will make about this is the tile size/ scale shouldn't be hard coded. You will probably end up regretting this in the future.
Let me know if any of these helped.
> 1 votes

---
Tags: unity
---


# Question
Title: Video feedback effect with recursive RenderTextures in Unity 2018.3
I have a project where I'm playing with a video feedback effect by rendering a camera to a RenderTexture and pointing the camera at a quad displaying that RenderTexture.

This works great normally, but when trying out HDRP, LWRP, (and upgrading materials) or upgrading the entire project to 2018.3, the RenderTexture just stops working and shows black. I also tried with a completely new project and just had a camera, a quad, and a cube. That also didn't work.

Is there any obvious reason this wouldn't be working? I spent a while trying out various settings but couldn't find anything that had any effect, so I really don't even know where to start.

# Answer
> 0 votes
I wasn't able to find out exactly what changed in the Unity rendering that caused this to stop working, but I did create a simple workaround. This post talks about some low-level rendering changes, but I don't understand them enough to know if they're related. **Note:** this won't work if you use the new Lightweight or High-Definition Render Pipelines, because they don't support OnRenderImage(), but the built-in render pipeline still does for now.

The workaround is actually simpler than my original implementation. Just attach this script to any camera and assign a rendertexture to it and the same rendertexture to a quad the camera is pointed at. I added the if statement to enable a frame delay effect, it isn't necessary for the script to work.

```
public class FeedbackTexture : MonoBehaviour
{
    public RenderTexture rt;
    [Range(0,5)] public int frameDelay;

    void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        if (frameDelay == 0 || Time.frameCount % frameDelay == 0) { Graphics.Blit(source, rt); }
        Graphics.Blit(source, destination);
    }
}

```

---
Tags: unity, rendering, camera, graphic-effects, rendertexture
---


# Question
Title: How to generate a random path on a 2d Grid
I want to create a random path in a 2d grid given a start point at the bottom row and an end point at the top of the row. I do not want the shortest path, or even the longest. Instead, I want a random path that can go up, down, left and right, but one that does not intersect itself.

I've been researching this question for days and cannot find anything that helps me solve the issue. I've read this questions Simplest way to generate a random path, however, the answer provided does not allow for the path to go backwards.

Some solutions I've thought of

1. On every row select a random point, then travel to each of these points. This does not allow for moving backwards because I would continue to move up in the rows.
2. Start the the beginning point, select a random point next, and so on until I reach the goal. This does not work because I can end up trapping myself and reaching a dead end.

How can I achieve this?

# Answer
> 8 votes
One common way to solve this type of problem is to still use a shortest path algorithm like A\* that takes into account traversal costs. We just lie to it about what's "shortest" ;)

Here we assign our costs for moving into each cell pseudorandomly — effectively making an invisible terrain of hills and valleys, fast roads and slow marshes for the algorithm to navigate. The path will meander to favour the low-cost cells and avoid crossing high-cost barriers, but since these obstacles exist only in the pathfinder, it looks to the player like it turned a corner for no reason.

By using a different seed for each pathfinding query, we can avoid each path settling into the same fast routes, and instead taking completely uncorrelated meanders.

This also lets you finely control the kinds of shapes you get from the paths, by tuning the scale and magnitudes of the pseudorandom cost features — getting big sweeping curves or little fractal zig-zags depending on how you choose to generate this imaginary landscape.

# Answer
> 0 votes
If performance is not an issue, you can just choose a point out of the set of points from which a path to the end exists. Essentially it's like your second option, but after each step you check from which neighbours there's still a path to the end point, and choosing a random point out of the set of valid points.

---
Tags: 2d, path-finding
---


title: Variable number of light sources

text:
# Question
Title: Variable number of light sources
I'm going to be writing a very simple renderer, mainly for learning purposes (using OpengGL). I've been wondering about how to implement support for dynamic number of light sources. Two solutions that come to my mind are:

1. Define an upper limit for each kid of light source (point, directional etc) and pass an array of lights in an uniform.
2. Write a shader for each of the light source type, iterate over each light in the scene and invoke it's appropriate shader, giving it as input the gBuffer with positions, normals and etc. This seems inefficient for me, as we will loop `n` times through the fragments in the framebuffer, where `n` is the number of lights.

Are there any more solutions?

# Answer
The Doom 3 engine used your option 2, but obviously with a forward rather than deferred renderer. The basic workflow looked like this:

* Clear the scene to black.
* Do a Z-only pre-pass.
* For each light in the scene:
    + Do stencil shadows.
    + Turn on additive blending - glBlendFunc (GL\_ONE, GL\_ONE);
    + Render objects hit by that light.

The Doom 3 source code was released under the GNU GPL and can be viewed as a working example of one way of doing this. The subsequent Doom 3 BFG Edition - a slightly cleaned-up and modernised variant - was also released, and both may be downloaded from id Software's Github:

You may also be interested in the following overview of the Doom 3 renderer: http://fabiensanglard.net/doom3/renderer.php
> 1 votes

---
Tags: opengl, shaders, lighting
---


# Question
Title: How can I handle the difficulty level between co-op and single player?
I'm working on an action-adventure game, and I was considering adding a co-op option. What I'm trying to decide is if when another player joins the game, if the game should get harder. On the one hand, I don't want the game to just get easier. On the other hand, I don't want to break continuity by making enemies suddenly stronger, eg I was able to take this down it two hits before, why does it take four all of the sudden.

I do not want there to be an "AI co-op" that comes with you in single player, I think that would make the game worse since it would detract from player agency.

How can I handle this? How can I keep the game challenging when a second player joins in?

# Answer
> 2 votes
It all depends on the gameplay of your game, but it all comes down to this: If multiple players make the player team stronger, then the enemies have to be stronger as well, to balance this.

Although not a video game, this is how Dungeon and Dragons do it. I don't have the Dungeon Master's Guide with me, but I recall it mentions something like this:

> For each player of a specific level, add the XP value together. There are different values for Easy, Medium, Hard and Deadly encounters. Using this you can get the party XP for each difficulty.
>
> When making a monster encounter, add the XP of all monsters and multiply it with some specific values, depending on the amount of monsters. So the more monsters on an encounter, the higher the multiplier value. This is the Encounter XP.
>
> Compare the Encounter XP with each difficulty's Party XP. To find if the encounter is Easy, Medium, Hard or Deadly.

This means that more players means more party XP, means that more difficult encounters are now easier. If you didn't do that, all encounters would just get easier, which could potentially make the game easier.

However, this is not a rule. There are games where having more players could make the game more difficult, because maybe all players have to survive, so if even one of them dies, the team dies. So make your choice depending on your game, just make sure the game has *roughly* the same amount of challenge.

# Answer
> 2 votes
First of all, figure out how having multiple players effects the core mechanics of the game if everything stays the same as single player.

* Your player "team" now has twice as much damage and health, abilities.
* Your player "team" can now be in two places at once - e.g. easily solving puzzles which may have required an object placed on a switch to open a door.

However, the players now also have a few potential downsides - do they now have to share equipment, boosts, health kits, gold, xp etc? If so, this can make things quite a lot more difficult. You also need to be careful that you keep the two players reasonably balanced in terms of power, or it can be pretty frustrating for one of them.

There are lots and lots (and lots!) of games to take inspiration from here in terms of how to balance this out.

The most basic (and probably boring) is to simply scale the enemies so they have twice as much health and damage.

A more interesting variation is to have more enemies - twice as much may be more than your engine can handle, or difficult in other ways. So you could take some balance of difficulty/numbers to compensate.

Another step forward would be to add new abilities, enemies as well as health/numbers.

Really good co-op games tend to add new puzzles, elements when more players are present - but this requires a lot more work from your side. I'd suggest starting with some simple scaling out of damage/health/numbers to start with (it's the easiest to implement) and then playtest it. Is it more fun? Tweak those proportions around and see. If it still feels lacking, you may need to look at more involved options.

---
Tags: game-design, multiplayer
---


# Question
Title: how do I tile this generated terrain infinitely around the player?
i made a script that instantiates cubes with for loops and perlin noise. is there any way i can tile this infinitely around the player? here is the script for the generation of one tile

```
public GameObject grass;
public int mapSizeX = 50;
public int mapSizeZ = 50;

public float heightScale = 20f;
public float detailScale = 20f;

float seed;
// Use this for initialization
void Start()
{
    //if (instance == null)
    //   instance = this;
    for (int x = 0; x < mapSizeX; x++)
    {
        for (int z = 0; z < mapSizeZ; z++)
        {
            int y = (int)(Mathf.PerlinNoise((x + seed) / detailScale, (z + seed) / detailScale) * heightScale);

            GameObject g = Instantiate(grass) as GameObject;
            g.transform.position = new Vector3(x, y , z);
            g.transform.SetParent(this.transform);
        }
    }
}

```

# Answer
Well, you could instantiate an infinite number of cubes, but that would require an infinite amount of time and consume an infinite amount of memory. So this is not going to work. You have to set a range limit around the player.

But what if the player moves towards the end of that range?

In that case you simply use your map generation function again to spawn new cubes in the newly discovered areas and destroy those in the areas left behind.
> 1 votes

# Answer
In theory you need to check the player location each frame and max render distance you’d set for yourself, if players location is bigger then your render radius, you add tiles based on he’s axis he moves at and delete those that are out of range
> 0 votes

# Answer
You have to keep your map somewhere (Array, file, class,...) Then you create a tile grid that contain a fixed number of tile. This grid could be a 2 dimensions array. Then each time the player move you update your tile grid with the actual tile the player should see. If you have a 10x10 tile grid = 100 tiles you select the 100 tiles around the players. You pick the needed tile in your map Container and add them to the tile grid. Then you render only the tile from the tile grid. If between 2 render cycle the player don't move you don't need to update the grid.
> 0 votes

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


title: Random range issues

text:
# Question
Title: Random range issues
i tried to make a random spawn system, but when i tried to start it, it spawns more than 1 prefab, which is not intended as i wanted to spawn only one by one.

tried some method to prevent from spawning non stop, but can't really make it to spawn only one.

EDIT: deleted the random range in the start section, it works as intended at the beginning, however when i enabled the same script in the prefab( based on the gameobject listed), it just spawn endlessly, script for these gameobject will be added, and since they are pretty much the same thing, i'll only attach one of them.

```
  public GameObject Tap, Up, Down, Left, Right;
int WhatToSpawn;
public bool isFree=false;
public bool destroyed=false;

// Use this for initialization
void Start () {
    isFree = true;
    destroyed = true;

}

// Update is called once per frame
void Update()
{
    if (isFree && destroyed)
    {
        destroyed = false;
        isFree = false;
        WhatToSpawn = Random.Range(1, 6);

        switch (WhatToSpawn)
        {
            case 1:
                Instantiate(Tap, Tap.transform.position, Tap.transform.rotation);
                break;
            case 2:
                Instantiate(Up, Up.transform.position, Up.transform.rotation);
                break;
            case 3:
                Instantiate(Down, Down.transform.position, Down.transform.rotation);
                break;
            case 4:
                Instantiate(Left, Left.transform.position, Left.transform.rotation);
                break;
            case 5:
                Instantiate(Right, Right.transform.position, Right.transform.rotation);
                break;
        }
    }

}

```

Here's the another script that is made for gameobject, i tried to make conditions that the script will spawn random stuff when destroy but failed to.

```
    private Swipe swipe;
private SpawnManager spawn;

private void Awake()
{
    swipe = GetComponent<Swipe>();
    spawn = GetComponent<SpawnManager>();
}

// Update is called once per frame
void Update () {
    if (swipe.Tap)
    {
        Debug.Log("Passed!");
        spawn.isFree = true;
        Destroy(gameObject);
        spawn.destroyed = true;
    }
    else
    {if (swipe.SwipeLeft || swipe.SwipeDown || swipe.SwipeRight || swipe.SwipeUp)
        {
            Debug.Log("Failed...");
            spawn.isFree = true;
            Destroy(gameObject);
            spawn.destroyed = true;
        }
    }

}

```

# Answer
> -1 votes
remove line from start line to prevent start loop upon spawn also you might have to place the codes seperately

---
Tags: unity, random
---


# Question
Title: Why does gameObject.transform.eulerAngles = new Vector3... work?
Apparently gameObject.transform.eulerAngles is accessing a copy, so changing it shouldn't do anything, and in fact using .Set doesn't work. But why does =new Vector3 (..) work?

EDIT: Given the answers - I think I should update the question. What seems inconsistent to me, is the fact that "new Vector3" works as a setter the way I would want it to, but not using "new" and .Set doesn't. It doesn't seem very intuitive that "new" is understood as "ah, he's trying to set this property of a property" that way want - the choice of word doesn't seem very intuitive at least.

I suppose it makes sense in the ".Set" case - you might want to intentionally use the .Set of the Vector3 returned. Essentially, it might be useful to interpret A.B.Set as (A.B).Set, as this is the "natural" way to interpret it, as opposed to some other "ordering" (which could symbolically be expressed as A.(SetB) or something like that).

But in the other case - I don't know why omitting "new" doesn't work. It would seem like a natural choice to interpret (A.B.C)= as "he wants to set the property" - what else could be intended by this? I can't think of a reason why someone would want it to do something else than what happens when you add "new" - i.e. assuming that A.B gives you the copy of the property B of A, and assuming it's not some sort of simple object like a Vector3, why would you want to set this copy of the property to something? In what scenario could that be a useful, efficient way of doing something?

But thinking about it again, I suppose the reason might be the same as with .Set -the code A.B.C= is simply understood as ((A.B).C)=, because that's the most natural, basic way to interpret it, is that right?

# Answer
'All of what I write here is an assumption, based on the API. Take it with a grain of salt.

I assume that eulerAngles is a property that encapsulates more than basic setter logic. Essentially, assume that

```
foo.eulerAngles = new Vector3(x, y, z);

```

is translated by the compiler into a method

```
foo.setEulerAngles(new Vector3(x, y, z));

```

now, assuming there's some internal state of the transform from which the eulerAngles' property is derived - I assume it's the 'rotation' quaternion. Then the setEulerAngles method rotates 'rotation' using quaternion mathematics, by converting the given vector to a quaternion.

By the same logic, the getter 'eulerAngles' is compiled to

```
public Vector3 getEulerAngles() {
  return rotation.eulerAngles;
}

```
> 2 votes

# Answer
As @DMGregory points out in a comment, you seem to assume a premise that if *getting* from `gameObject.transform.eulerAngles` accesses and returns a copy, then *writting* to it must write to a copy, in which case there would be no meaningful changes being done to the root data.

Both parts of that premise are wrong. Despite breaking the naming convention most people use in C#, `eulerAngles` is a property, not a variable. And in C#, properties, including ones made to act as getters and setters, can implement completely independent logic.

---

Specifically, in this case, the property *returns* a copy in *reading/getting* inherently, as it is just a proxy to the underlying `Transform.rotation`, which is a `Quaternion`, not a `Vector3`. Therefore a new `Vector3` is returned simply as part of the process of conversion.

And for *writing*, the same proxy happens in reverse. The property converts the given `Vector3` representing euler angles to a `Quaternion`, using `Quaternion.Euler(Vector3)`, and then writes the result to `Transform.rotation`:

> public Vector3 eulerAngles { get { return rotation.eulerAngles; } **set { rotation = Quaternion.Euler(value); }** }

**From the official Unity source-code reference**
> 2 votes

# Answer
The other answers are correct, it's a property that returns a copy when you get it, but when you set it, converts the value to a quaternion.

I believe this is the right part of the reference source:

```
        public Vector3 eulerAngles { get { return rotation.eulerAngles; } set { rotation = Quaternion.Euler(value); } }

```
> 1 votes

# Answer
Good question! I would guess youre accessing not a copy, but a prop with its setter routing to the real value stored inside a database withing unity.

Vector3.Set would indeed just set the value of the local prop this way, while

= new Vec3(..) would make use of the setter of the prop (wich implementation details i couldnt find)

Edit:

I think so because ive heard that unity's implementation relies on an entityComponentSystem and inside the metaData of unity's Transform comopnent we can see that eulerAngles is an undefined prop and Set(x, y, z) a delegate/action or something, maybe to obscure the implementation
> 0 votes

---
Tags: unity
---


title: High performance screenshots in LWRP

text:
# Question
Title: High performance screenshots in LWRP
I'm trying to capture some screenshots for my game. They need to be saved as jpgs to a folder, latency is not an issue, I don't care if it happens over 10 seconds. My number one priority is to keep the game at a steady framerate.

Some things I've tried:

Some metrics from my testing:

* ScreenCapture.CaptureScreenshot is ~200ms.
* ReadPixels() is 40-70ms.
* Texture.Apply() is ~5ms.
* EncodeToJPG() is 35-50ms.
* File.WriteAllBytes() is \<1ms.

Also posted this question here and here:

# Answer
> 1 votes
There's two separate parts to this question. First is how to record screenshots without hitting your framerate too much, and second is how to capture screenshots *at all* in the new render pipelines. The first part is way easier, so let's get that out of the way first.

## Capturing screenshots/GIFs during gameplay

You said you wanted these screenshots for bug testing, and that it would be even better to have video. Luckily, there's already a plugin for exactly this! I found Moments Recorder and have used it in my own project already and the quality is great. Key features:

* Runs a constant buffer so hitting a button exports the last x seconds, which is ideal for catching hard-to-reproduce bugs
* Encoding runs in a separate thread, so it shouldn't affect your framerate much
* Customizable resolution/quality, so you can reduce resolution or thread priority if it's slowing things down
* Well-commented source code makes it easy to modify

My project was very poorly coded at the time and barely made 15fps, with randomized colors that are terrible for GIF encoding, but I saw no major additional slowdown when exporting a GIF. I should note the comments in the code for GIF encoding do say it could tank the framerate for high resolution, but if you find that's the case, then it gives plenty of options to play with to speed things up. Otherwise you can try to modify it to just export jpgs.

Here's an example of it in my editor:

The moments recorder uses System.Threading, but you could also look into the Unity Jobs system for multithreading your own solution, which could potentially be safer/faster/easier. I haven't tried it, and it's still in preview, so it may still be slower. Either way, it's a good example of how to separate out the capturing/saving code if you write your own solution.

Also, if you want to record video clips while in the editor, Unity has an official Asset Store plugin for that.

## Capturing screenshots in LWRP

This is a huge pain in the ass and I've been looking through solutions for a while. I'm still learning this stuff so I may have missed an obvious or easier solution. Also, all my testing has been very haphazard so I may be mixing up solutions and results, and I've crashed Unity a few times. **Follow at your own risk.**

**Option 1** You said `ScreenCapture.CaptureScreenshot()` was taking 200ms, but have you tried `CaptureScreenshotAsTexture()`? It seems like that should be a lot faster and you could split off the file conversion/writing into a separate thread. I tried testing this both by modifying the Moments Recorder.cs and in a separate simple script, but I'm not getting any screenshot output at all and no errors, so I'm not sure what's going on there. If that method is working for you, that could be the fastest/easiest solution.

**Option 2:** This thread shows a way to capture an image from a camera in the new render pipelines, but the script linked doesn't show where/how it's called. Another post in the replies uses `RenderPipeline.beginCameraRendering`, so I modified the Moments recorder to use this callback and replaced the `OnRenderImage` method, but calling it at the beginning of camera rendering gives inconsistent/unhelpful results. It looks like it's moved out of experimental and a `endCameraRendering` event is added in 2019.1, but I don't have time to upgrade and test it. That might be the ideal solution. To do that with Moments, change the OnRenderImage() method in Recorder.cs to the following:

```
void CaptureCamera(Camera _camera)
    {
        if (State != RecorderState.Recording)
        {
            return;
        }

        m_Time += Time.unscaledDeltaTime;

        if (m_Time >= m_TimePerFrame)
        {
            // Limit the amount of frames stored in memory
            if (m_Frames.Count >= m_MaxFrameCount)
                m_RecycledRenderTexture = m_Frames.Dequeue();

            m_Time -= m_TimePerFrame;

            // Frame data
            RenderTexture rt = m_RecycledRenderTexture;
            m_RecycledRenderTexture = null;

            if (rt == null)
            {
                rt = new RenderTexture(m_Width, m_Height, 0, RenderTextureFormat.ARGB32);
                rt.wrapMode = TextureWrapMode.Clamp;
                rt.filterMode = FilterMode.Bilinear;
                rt.anisoLevel = 0;
            }

            _camera.targetTexture = rt;
            _camera.Render();
            _camera.targetTexture = null;

            m_Frames.Enqueue(rt);
        }
    }

```

Then add this in `Init()`

```
cam = GetComponent<Camera>(); //don't forget to create the cam var somewhere
RenderPipeline.EndCameraRendering(GetComponent<Camera>());
RenderPipeline.endCameraRendering += CaptureCamera;

```

**Option 3: works in 2018.3, easy but weird results** If you can't upgrade to 2019.x then this might work. I got this version working, but the resulting gif is washed out for some reason. Possibly shaders aren't being applied, not sure.

Modifying Recorder.cs in Moments, rename `OnRenderImage` to `Update()` or `LateUpdate()` and get rid of all the `Graphics.Blit` calls. Then at the end just throw this in:

```
Graphics.Blit(ScreenCapture.CaptureScreenshotAsTexture(), rt);
m_Frames.Enqueue(rt);

```

# Answer
> 3 votes
## For capturing video instead:

I found a github repo that can export mp4s using ffmpeg at runtime: https://github.com/keijiro/FFmpegOut

I had to make some modifications to make it save the last few seconds on demand, instead of a continuous recording. Specifically:

* Don't send each frame to the FFmpeg binaries as they come. Instead, save them in memory until further notice.
* Have a max number of frames to be saved in memory. When this number is exceeded, remove the oldest saved frame. (I actually calculated the approximate memory usage per frame and used this to dynamically set the max number of frames based on the max amount of ram I can budget to the recorder)
* When it's time to export the last few seconds of gameplay, send the entire queue to FFmpeg all at once. By this time, all the data is in a byte array already and so it can be multithreaded - important to ensure the main thread isn't blocked.

The final result of this was a steady 150 fps while recording at 1080p.

# Answer
> 0 votes
My response is based on taking screenshots in pure C++/OpenGL - I have no experience with Unity.

Most of the time needed for screenshots is for compression and saving the image.

Reducing the quality of saved image should decrease the time. Another option is to grab the screen pixels, and let another thread do the compression and saving.

If we're not speaking about 4K resolution, saving raw (BMP) images should be faster than JPEG/PNG (unless you're writing to a floppy).

**Update:** I took a look into Unity's API. If I were to add screenshot feature to Unity game, it would probably look like that:

1. Read screen's pixels: https://docs.unity3d.com/ScriptReference/Texture2D.ReadPixels.html
2. Launch separate thread (is it possible?)
3. Encode and save to file on separate thread https://answers.unity.com/questions/332335/saving-a-texture2d-as-a-png.html

Screenshots in C++ (SFML):

```
// Create texture
sf::Texture texture;
texture.create(windowSize.x, windowSize.y);
// Move window's pixels to texture
texture.update(window);
// VRAM -> RAM
sf::Image screenshot=texture.copyToImage();
// Encode+save to HDD
screenshot.saveToFile(ss.str().c_str());

```

# Answer
> 0 votes
You should look into https://docs.unity3d.com/ScriptReference/Graphics.Blit.html.

Graphics.Blit is unity's API for copying from one texture to another. If you render your scene into a render texture (Which I assume the lightweight pipeline can do, correct me if I'm wrong), then blit that render texture using the scriptable pipeline API. Then render the render texture to the screen. And as crueltear has said save processing for another thread.

---
Tags: unity, performance, screenshot
---


# Question
Title: XNA: Classes with Texture2D to be treated as one
**Summarised Problem:**

I have an `Animation` class that I want to be able to treat as a `Texture2D` field when need be. I do not want to inherit from the class or its parents. I'd rather not create a parent class of both the animation class and a 'container' for a `Texture2D`, though that may be the only way to achieve what I want.

**Code:**

```
public class Animation : IComponent
{
  public Texture2D texture => frames[currentFrame];

  public Texture2D[] frames;
  public byte currentFrame { get; protected set; }
  /// <summary>
  /// Frame time in milliseconds;
  /// </summary>
  public ushort interval;
  public bool looping;
  public bool animate;

  protected ushort progress;

  /// <param name="interval">Time until frame is succeeded.</param>
  /// <param name="loop">Whether to loop frames.</param>
  /// <param name="start">Whether to start cycling through frames.</param>
  public Animation(Texture2D[] frames, ushort interval, bool loop, bool start)
  {
    this.frames = frames;
    currentFrame = 0;
    this.interval = interval;
    looping = loop;
    animate = start;
  }

  public void Update(ushort milliseconds)
  {
    if (looping)
      currentFrame = (byte)((progress += milliseconds) % interval % frames.Length);
    else
      currentFrame = (byte)((progress += milliseconds) % interval);
    progress %= interval;
  }
}

```

It's an extremely simple class that is subject to change. Its purpose is to stand in for a `Texture2D` for external handling of spreadsheets and whatnot. It is going to be used in an ECS but probably not as a component as I have it now.

So, for instance, I'd like to be able to put it as a stand in for a `Texture2D` in draw calls (can be done with the 'texture' property it has) and also be kept in the same field and be cast to treat it as the animation class again.

If anyone thinks there's a much superior implementation of this please let me know.

If there's a way I could do something like this that would be perfect:
`spriteBatch.Draw(Anim as Texture2D, Vector2.Zero, Color.White);`

# Answer
After coming across many unrelated and somewhat-related stackoverflow/gamedev questions I managed to find what I was looking for.

I didn't fully understand the "Is-a" vs "Has-a." I knew I didn't want inheritance but didn't want to encapsulate a Texture2D just for the sake of another class to inherit from without any extra usefulness to come of that encapsulation (Seems messy and unnecessary to me). The solution most often would take the form of a sprite class:

```
public class Sprite
{
    public Texture2D texture;
    public float depth;
    public float scale; // Or a Vector2
    public Color mask;
    // etc, etc

    public Sprite(/* stuff */)
    {
        // do more stuff
    }
}

```

I didn't actually go with this in the end, I went with having an abstarct "Graphic" class containing vital info to draw a texture, but not the texture itself and inheriting classes would be drawn in there own way via an extension to `SpriteBatch.Draw` (This was good for Sprite vs Spritesheet vs Animations and such)

One thing I just came across and inspired me to make this is the way to cast your object to another outside of of the class's inheritance tree. Done quite simply as follows:

```
static public implicit operator Texture2D(Sprite s)
{
    return s.texture;
}

```

Use as follows:

```
Texture2D texure = (Texture2D)spriteinstance

```

You can go backwards too if one had extra info or you were happy to settle for default variables (Could be easily worked around).
> 0 votes

# Answer
You can either just extend Texture2D, which would allow you to cast it down to a Texture2D if you want or (in my opinion preferably) extend the spriteBatch with a draw that accepts Animations.

To be honest, I wouldn't do either of these. The same draw method doesn't give enough information to the animation, e.g. when did it start? How long should it be?
> 1 votes

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


# Question
Title: How can I debug a black screen when testing on a device?
I have made an Android game with Unity. But, when I opened my game, I see a black screen and a closed game.

It works on a tablet but does not work on mobile phones. I tested it on 2 mobile phones.

On the first phone I installed it on, I see nothing but a black screen and closed game.

On the second one, it installed once and worked, but when I uninstalled it and tried to install it again, I get the black screen and closed game.

What can I do to help me find out what is going on?

# Answer
It's hard to answer that without any logs. You can use LogCat for that. If you don't have Android Studio installed, go ahead and install it. Once that is done head over to C:\Users\YOUR\_NAME\AppData\Local\Android\Sdk\tools and start the monitor.bat as an administrator. Allow debug mode on your phone and plug it into your PC via USB. Your device should be shown in the monitor window, click on it, if you don't receive any messages yet. You can see the messages in logcat now in the bottom left corner when you open the tab "LogCat".

Start the unity game and once it crashed, disconnect the device from the USB-port. Then go through the logs and look for a fatal crash messages (red). Copy the whole log and show it here.
> 1 votes

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


title: DirectX depth/order render issue

text:
# Question
Title: DirectX depth/order render issue
I have what appears to be a depth or order rendering problem which I have never seen happen before. My terrain and water are rendered with my displacement shader, and at the moment all other models are rendered with my standard shader, and I am using deferred rendering. Now, as you can see in the images, I have a sphere that is half cut off, as though d3d thinks that the water is somehow in front of the sphere, which it is not. If I move down to water level, you can see the whole sphere. If I render the same sphere with my displacement shader, there is no problem at all. If I go into my displacement shader class, and cut out the hull and domain shader stages, then the terrain and water start to do the weird z buffer issue that the sphere is having. Is there something conceptual anyone can think of without me having to post hundreds of lines of code? However, happy to post code if needed.

Thank you

**UPDATE:** I've narrowed it down to the domain shader - the line that physically changes the output triangles' position. When I comment out this line, it solves the problem, although then I have no tessellation. Do I need to do some kind of manual depth writing after changes the position?

Domain Shader:

```
cbuffer cbDomainInfo
{
    float3 g_vEyePosition;
    float _padding;
};

struct PatchTess
{
    float flEdges[ 3 ] : SV_TessFactor;
    float flInside : SV_InsideTessFactor;
};

struct DomainInput
{
    float4 vPosition    : POSITION;
    float2 vTexcoord    : TEXCOORD0;
    float3 vNormal      : NORMAL;
    float3 vViewVec     : TEXCOORD1;
    float flAlpha       : ALPHA;
};

struct DomainOutput
{
    float4 vPosition    : SV_POSITION;
    float2 vTexcoord    : TEXCOORD0;
    float3 vNormal      : NORMAL;
    float3 vViewVec     : TEXCOORD1;
    float flAlpha       : ALPHA;
};

Texture2D g_texDispMap;
SamplerState g_samSampler;

[ domain( "tri" ) ]
DomainOutput DS( PatchTess input, float3 uvwCoord : SV_DomainLocation, const OutputPatch<DomainInput, 3> patch )
{
    DomainOutput output;

    output.vPosition = uvwCoord.x * patch[ 0 ].vPosition + uvwCoord.y * patch[ 1 ].vPosition + uvwCoord.z * patch[ 2 ].vPosition;
    output.vNormal = uvwCoord.x * patch[ 0 ].vNormal + uvwCoord.y * patch[ 1 ].vNormal + uvwCoord.z * patch[ 2 ].vNormal;
    output.vTexcoord = uvwCoord.x * patch[ 0 ].vTexcoord + uvwCoord.y * patch[ 1 ].vTexcoord + uvwCoord.z * patch[ 2 ].vTexcoord;
    output.vViewVec = uvwCoord.x * patch[ 0 ].vViewVec + uvwCoord.y * patch[ 1 ].vViewVec + uvwCoord.z * patch[ 2 ].vViewVec;
    output.flAlpha = uvwCoord.x * patch[ 0 ].flAlpha + uvwCoord.y * patch[ 1 ].flAlpha + uvwCoord.z * patch[ 2 ].flAlpha;

    output.vNormal = normalize( output.vNormal );

    float flMipInterval = 20.f;
    float flMipLevel = clamp( ( distance( output.vPosition, float4( g_vEyePosition, 1.f ) - flMipInterval ) ) / flMipInterval, 0.f, 6.f );

    float flHeightMap = g_texDispMap.SampleLevel( g_samSampler, output.vTexcoord, flMipLevel ).r;

    //TODO: Pass in height scale via cbuffer
    //This next line causes the problem:
    output.vPosition += float4( ( 20.f *( flHeightMap - 1.f ) ) * output.vNormal, 1.f );

    return output;
}

```

# Answer
> 0 votes
DMGregory was right - setting the w coordinate to 1.f was causing the problem. I was able to fix it by changing it to 0.f, or alternatively only changing output.vPosition.xyz. If anyone has an explanation as to perhaps why this is I'd be interested to hear about it.

Thanks to DMGregory and ErnieDingo for the help.

---
Tags: c++, directx11, deferred-rendering
---


# Question
Title: How can I show tilemap coordinates in-game in Unity?
I have a game that uses a tile map, and I'd like to draw numbers representing positions on the tile map while playing the game. This would, for example, let me easily write down a note that I want to make changes at a specific coordinate.

I've written a script which grabs the `Tilemap` object and assigns it to a variable called `m_map`, and then:

```
void OnGUI()
{
    for (int x = -15; x < 15; ++x)
    {
        for (int y = -15; y < 15; ++y)
        {
            //if (GetTile(x, y) == null) continue;

            if (Camera.main != null)
            {
                Vector3 coord = m_map.GetCellCenterWorld(new Vector3Int(x, y, 0));

                Vector3 screenCoord = Camera.main.WorldToScreenPoint(coord);

                GUI.Label(new Rect(screenCoord.x, screenCoord.y, 200, 200), string.Format("{0},{1}", x, y));
            }
        }
    }
}

```

However, this does not produce the results I would expect. The Y-axis is inverted, for example, and X-axis seems to be off by a cell or two. Moving the camera along the Y-axis also causes the labels to move away from the tiles they are supposedly numbering, which means it definitely isn't correct.

It seems I must have made some bad assumption about one of these coordinate systems, but I can't figure out what.

# Answer
> 1 votes
If I remember correctly, the tile coordinates are based on the lower-left corner of the tile, so if you called this method on (1,1) you might expect that to be within tile (0,0) but it's the next one up and over. That may be accounting for some of your coordinates being off. More importantly, your loop is creating a Vector3 starting at (-15,-15) but that's relative to the world, not the camera's position. So if the camera is at (40,40) you're trying to line up coordinates with tiles that are offscreen. Also keep in mind how many tiles are on screen and the spacing of the labels will change with the zoom level so you'd want to orient your labels in world space, not in relation to the camera.

(Minor note while we're here, `Camera.main` is just a shortcut for FindGameObjectsWithTag, and you're doing that 900 times per frame, which is very slow considering there shouldn't be a reason for the camera to become null mid-loop.)

I'm not 100% clear on what your goal is. Are you just trying to get references for development? Or are you trying to have the tile coordinates display in the game, on the tiles?

If you're just looking for references during development, try this:

```
Vector3 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
SomeMethod(m_grid.WorldToCell(worldPoint));

```

SomeMethod can just update a text box on screen so you have a constant display of what cell your cursor is on, or you can have it save the cell when you click, or whatever you like.

From there the answer will depend on exactly what you want to do and how you want it to look, but here's a place to start. This will give you the coordinates of the bottom-left and top-right tiles on screen, regardless of camera size or position:

```
bottomLeft = _grid.WorldToCell(mainCamera.ViewportToWorldPoint(new Vector3(0, 0, 0))),
topRight = _grid.WorldToCell(mainCamera.ViewportToWorldPoint(new Vector3(1, 1, 0)))

```

You could use that to find a start and end point for your loop and your code might work fine as is from there.

If you want the tiles to display their coordinates during the game, or even in development, it would probably be possible to create a scriptable tile that displays coordinates based on where it is and have those on a separate tilemap underneath or over your main tilemap. Although I'm not sure how you'd render text to a tile. Your OnGUI method should be perfectly fine to start though.

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


# Question
Title: Unity, errors when using Quaternion.Euler to copy rotations
In the game I'm creating I have a square that rotates around a parent point, I want the square to always aim upright however (think of a rotating platform). What I've done is simply use `child.transform.rotation = Quaternion.Euler(0.0f, 0.0f, -gameObject.transform.rotation.z)` This rotates the child object in the opposite direction so that they're always aiming in the right direction. Except it doesn't, there is some error that piles up with bigger rotations. For example at 90º the child object will be rotated -90.77 instead which is very noticeable given that the game has a grid of sorts and when objects are not aligned to it they instantly pop out.

So my question is, is there any way to avoid this error?

# Answer
> 2 votes
`transform.rotation` is not an Euler angle triplet. It is a quaternion. So its z component is not a rotation angle that you can pipe through `Quaternion.Euler` meaningfully.

If you want to apply only the roll of one object to another, you can do something like this:

```
child.transform.rotation = Quaternion.LookRotation(Vector3.forward, transform.up);

```

This forms a rotation whose forward direction maps to world forward (so 0 pitch / yaw), and whose up direction is as close as possible to parallel to your reference object's up vector when using roll alone.

Or to roll it in the opposite direction, take the `Quaternion.Inverse` of the above.

---
Tags: unity, quaternion
---


# Question
Title: Most efficient way to get the closest point to a 3d rectangle
I have a 3D rectangle, with 4 points (x,y,z) And I have a player, who can be anywere (inside the rectangle, outside, not even in the plane, in the corner...).

I would like to get the closest point in that rectangle, to my player. The most efficient way

I have already a struct who can say the closest point to a line:

```
public struct ExtLine
{
    public readonly Vector3 A;
    public readonly Vector3 B;
    public readonly Vector3 Delta;
    public bool noGravityBorders;//if I want to return true only if player is in the boundary

    public ExtLine(Vector3 a, Vector3 b, bool _noGravityBorders)
    {
        A = a;
        B = b;
        Delta = b - a;
        noGravityBorders = _noGravityBorders;
    }

    public Vector3 PointAt(double t) => A + (float)t * Delta;
    public double LengthSquared => Delta.sqrMagnitude;
    public double LengthLine => Delta.magnitude;

    public Vector3 ClosestPointTo(Vector3 p)
    {
        //The normalized "distance" from a to your closest point
        double distance = Project(p);

        if (distance < 0)     //Check if P projection is over vectorAB
        {
            if (noGravityBorders)
                return (ExtUtilityFunction.GetNullVector()); //an extention who give me an "null vector", not useful here
            return A;
        }
        else if (distance > 1)
        {
            if (noGravityBorders)
                return (ExtUtilityFunction.GetNullVector());
            return B;
        }
        else
        {
            return A + Delta * (float)distance;
        }
    }

    public double GetLenght()
    {
        return (LengthLine);
    }

    public double Project(Vector3 p) => Vector3.DotProduct(Delta, p - A) / LengthSquared;
}
```

And a struct who can say the closest point to a plane:

```
public struct ExtPlane
{
    public Vector3 Point;
    public Vector3 Direction;

    public ExtPlane(Vector3 point, Vector3 direction)
    {
        Point = point;
        Direction = direction;
    }

    public bool IsAbove(Vector3 q) => Vector3.DotProduct(q - Point, Direction) > 0;

    public Vector3 Project(Vector3 randomPointInPlane, Vector3 normalPlane, Vector3 pointToProject)
    {
        Vector3 v = pointToProject - randomPointInPlane;
        Vector3 d = Vector3.Project(v, normalPlane.normalized);
        Vector3 projectedPoint = pointToProject - d;
        return (projectedPoint);
    }
}
```

How can I manage to find my point ? Thanks for help !

# Answer
> 4 votes
This is actually a pretty simple problem if you first rotate the rectangle so it lies flat and at right angles on one plane, and also apply the same rotation to the player location. Now, everything can be done with Cartesian coordinates to determine the closest point. In Cartesian space, it's trivial to find the point on the rectangle, then reverse the rotation to get your final answer.

Here's a basic illustration of how this works...

Let's say you rotate the rectangle so it lies flat on the Z plane, so you're working just with X and Y. Given that and looking only at the player location in X and Y (ignoring Z), the player will either be inside the rectangle, or outside the rectangle.

If inside, the point on the rectangle is simply the player X, Y coordinates on the rectangle.

If outside, it's also surprisingly trivial as well. Rather than answer the outside case, I'm going to point you to https://math.stackexchange.com/questions/356792/how-to-find-nearest-point-on-line-of-rectangle-from-anywhere which has a nice, extremely simple answer to that problem.

Here's a key illustration from the above linked Math stack answer, which shows how for a point outside the rectangle, it's either a simple line to an edge, or one of the corners, depending on the point location...

Now with the closest point on the rectangle located in Cartesian coordinates, you reverse the rotation on that point to find the desired point on the rectangle in 3D space.

The only thing I've left you as a challenge is to compute the rotational transformation needed for your rectangle. I'm going to say though that defining a plane (to work out the needed rotation) with 4 points is going to be a problem, because you'll never have enough precision to ever have 4 points truly lying on a flat plane (unless it's already flat on X, Y, or Z). The best thing would be for you to pick 3 of the points on the rectangle to define a triangle, then compute the normal from them (and from there the rotation).

# Answer
> 0 votes
Let \\$\vec{n}\\$ be a normalized normal vector of the plane (say, the cross-product of \\$\vec{DA}\\$ and \\$\vec{DC}\\$ divided by its length).

Let \\$Q = P - (\vec{DP}\cdot \vec{n}) \vec{n}\\$. (I.e., \\$Q\\$ is the projection of \\$P\\$ into the plane of \\$ABCD\\$. You seem to have a function for this already. The only missing part is to make sure that \\$Q\\$ belongs to the rectangle.)

Let \\$x=(\vec{DQ}\cdot \vec{DC})/|DC|^2\\$ and \\$y=(\vec{DQ}\cdot \vec{DA})/|DA|^2\\$. (That means, we find the place of \\$Q\\$ in a coordinate system in the rectangle that has its origin in \\$D\\$ and \\$(1,0)\\$ and \\$(0,1)\\$ in \\$C\\$ and \\$A\\$, respectively.) If \\$x\>1\\$ or \\$x\<0\\$, set \\$x=1\\$ or \\$x=0\\$, respectively; the same for \\$y\\$.

The point \\$D + x\vec{DC} + y\vec{DA}\\$ is the point you are looking for.

(Admittedly, this answer still leaves open the question of "most efficient way".)

**Edit:** In order to make this somewhat more efficient: The first step is unnecessary (the following steps would ignore the component perpendicular to the plane anyway); and it is possible to compute the projections (probably the most expensive parts of the algorithm) only when necessary.

Let \\$a= \vec{DP}\cdot \vec{DC}\\$. If \\$a\<0\\$, let \\$\vec{x}=\vec{0}\\$. Else if \\$a\>l\_c\\$, where \\$l\_c=\vec{DC}\cdot\vec{DC}\\$, let \\$\vec{x}=\vec{DC}\\$. Else let \\$\vec{x}\\$ be the projection of \\$\vec{DP}\\$ in the direction of \\$\vec{DC}\\$ (like above, e.g. as \\$\frac{a}{l\_c}\\, \vec{DC}\\$.).

Let \\$b= \vec{DP}\cdot \vec{DA}\\$. If \\$b\<0\\$, let \\$\vec{y}=\vec{0}\\$. Else if \\$b\>\vec{DA}\cdot\vec{DA}\\$, let \\$\vec{y}=\vec{DA}\\$. Else let \\$\vec{y}\\$ be the projection of \\$\vec{DP}\\$ in the direction of \\$\vec{DA}\\$.

The solution is \\$D+\vec{x}+\vec{y}\\$.

While this is certainly more efficient than my first attempt (source: count the operations of each type), on which it is based, I still cannot say how close it is to the 'most efficient' algorithm (if such exists) - and am looking forward to reading another answer that addresses this question (ideally comparing with all other possible algorithms and not only examples given here).

---
Tags: c#, 3d, algorithm, geometry, optimization
---


# Question
Title: Create a instance of a C++ class within a blueprint
I'd like to create an instance of a C++ class in a blueprint. That's my current approach, but the instance is *None*. Why?

# Answer
I'd tried to get the class by an instance which is not instantiated.

Fix:
> 1 votes

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


# Question
Title: Play games services leaderboard does not work all the time
I am trying to login into play services. I got it working. But there were duplicate game objects created. So I added do not destroy on load and now the play services work the first time I access it.

But when I go to play game scene, end the game and come back to main menu, I can not seem to load the leaderboards.

```
public class PlayServices : MonoBehaviour {

public static PlayServices services;

private void Awake()
{
    if(services != null)
    {
        Destroy(gameObject);
    }
    else
    {
        services = this;
        DontDestroyOnLoad(gameObject);
    }
}

// Use this for initialization
private void Start () {
    PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder().Build();

    PlayGamesPlatform.InitializeInstance(config);
    // recommended for debugging:
    PlayGamesPlatform.DebugLogEnabled = true;
    // Activate the Google Play Games platform
    PlayGamesPlatform.Activate();
    SignIn();
}

```

# Answer
> 0 votes
Are you sure that the whole setup for the platform and sign-in-process is only called once? Add a debug log and make sure. Things can get weird, if you try to initialize google play services multiple times.

---
Tags: unity, c#, android, google-play-services
---


# Question
Title: Why doesn't my SpriteRenderer's color change when setting .color = new Color(166, 33, 33)?
I need to change the color of my `SpriteRenderer`, and so I looked up how to do it and come up with this code:

```
spaceOne.GetComponent<SpriteRenderer>().color = new Color(166, 33, 33);

```

(In case you are wondering, yes I checked that 'spaceOne' is correctly linked to a `GameObject`.)

This should change the color, but it doesn't. As I was writing this, I found that replacing `new Color(166, 33, 33);` with `Color.red;` actually does change it to red.

So now I am wondering, why does the `new Color(166, 33, 33);` code not work, and how can I fix it?

P.S. I made sure that it wasn't something simple, like it being RGBA rather than RGB, but no, it still doesn't work with `new Color(166, 33, 33, 255);`.

# Answer
> 5 votes
The `color` component of a `SpriteRenderer` defaults to white. The `Color` type is a four-component, RGBA, floating point representation of a color. The range of each component of that type is 0.0 to 1.0.

In your code, you're passing integers for each component, and all of them are greater than one. The documentation doesn't specify what happens if you do this, but there's a good chance it just clamps them to 1. So you're essentially just setting the color to white (which it already was), and thus seeing no results.

Try dividing all your components by 255.0f:

```
spaceOne.GetComponent<SpriteRenderer>().color = new Color(
  166.0f / 255.0f,
  33.0f / 255.0f,
  33.0f / 255.0f
);

```

# Answer
> -3 votes
I experienced the same Problem, but found an other solution:

`spaceOne.GetComponent<SpriteRenderer>().color = new Color(
 166.0f,
 33.0f,
 33.0f,
 1
);`

i forget the alpha chanel

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


# Question
Title: DirectoryNotFoundException for an existing file path on Unity startup
I'm not sure why this error appears in my console when I start up my Unity editor but it is stopping me from running any Unity projects by pressing the play button.

I have tried re-installing Unity, checking out the file at the specified file path destination and searched my local Unity folders for any relevant files that are calling for a file path search.

**I want to know which file is responsible for specifying/assigning the file path causing the error.**

The error message is pasted below with a screenshot of the Unity editor (with the error message in its console) and a screenshot of the specified file in the file path:

*Error message*

DirectoryNotFoundException: Could not find a part of the path "F:\Computer Science\Aston University Work\Final Year (for real)\Game Development\Labs\LabSeven\Workspaces\labSeven\_Home\_Vers\Library\PackageCache\com.unity.analytics@3.2.2\Tests\Editor\Unity.Analytics.StandardEvents\Unity.Analytics.StandardEvents.EditorTests.asmdef" System.IO.FileStream..ctor (System.String path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, System.Int32 bufferSize, System.Boolean anonymous, System.IO.FileOptions options) (at :0) System.IO.FileStream..ctor (System.String path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, System.Int32 bufferSize, System.IO.FileOptions options, System.String msgPath, System.Boolean bFromProxy, System.Boolean useLongPath, System.Boolean checkHost) (at :0) (wrapper remoting-invoke-with-check) System.IO.FileStream..ctor(string,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare,int,System.IO.FileOptions,string,bool,bool,bool) System.IO.StreamReader..ctor (System.String path, System.Text.Encoding encoding, System.Boolean detectEncodingFromByteOrderMarks, System.Int32 bufferSize, System.Boolean checkHost) (at :0) System.IO.StreamReader..ctor (System.String path, System.Text.Encoding encoding, System.Boolean detectEncodingFromByteOrderMarks, System.Int32 bufferSize) (at :0) System.IO.StreamReader..ctor (System.String path, System.Boolean detectEncodingFromByteOrderMarks) (at :0) System.IO.StreamReader..ctor (System.String path) (at :0) (wrapper remoting-invoke-with-check) System.IO.StreamReader..ctor(string) System.IO.File.ReadAllText (System.String path) (at :0) UnityEditor.Scripting.ScriptCompilation.EditorCompilation.LoadCustomScriptAssemblyFromJson (System.String path) (at C:/buildslave/unity/build/Editor/Mono/Scripting/ScriptCompilation/EditorCompilation.cs:463) UnityEditor.Scripting.ScriptCompilation.EditorCompilation.SetAllCustomScriptAssemblyJsons (System.String\[\] paths) (at C:/buildslave/unity/build/Editor/Mono/Scripting/ScriptCompilation/EditorCompilation.cs:681) UnityEditor.Scripting.ScriptCompilation.EditorCompilationInterface:SetAllCustomScriptAssemblyJsons(String\[\])

*Screen shots*

Many thanks in advance.

# Answer
Thanks to TehMightyPotato, the answer is quite straightforward. Make sure the file path for the project is less than 265 characters/bits and the error should not occur.
> 1 votes

---
Tags: unity, filestream
---


# Question
Title: Baking details to a low poly model asset - used on enviroment or “world” geometry?
Usually for the game objects a high poly model is prepared, to then transfer the details onto a low poly model, so that it can be rendered in realtime.

Is this workflow always used, with any object?

I imagine this is used for the polygonal models of the characters in general, but what about the rest?

I'm especially interested in the environment, like a snowy mountain for example. I do not think this high-poly to low poly detail baking workflow is appropriate for this case.

# Answer
Yes, there are usually multiple models of different detail for the same Objects. \[in open world games for sure\].

One Example is PUBG where - if your PC sucks - houses are at first only rendered as vaguely housy looking boxes, then replaced with the real full-detail object.

And that is where your assumption is wrong: usually there are no high-detail models just for development, these are all shipped to be rendered in live. The players PC will pick which "level" he can do and render that.

For the environment, that is up to the engine, some just don't render anything after a certain range (Planetside 2) and make a fog after that, others do in fact lower the poly count on distant objects.
> 1 votes

# Answer
While user125108 is correct that games will often have multiple levels of detail for environment assets and terrain, I think they may have overlooked a key part of your question:

> Usually for the game objects a high poly model is prepared, to then transfer the details on a low poly model, so that it can be rendered in real time.

It sounds like you're talking about normal map baking, where an artist sculpts highly detailed geometry, then bakes the surface detail to a normal map that can give the appearance of similarly fine shading details even on a lower-poly model.

That particular workflow can be used across a wide range of game assets, including characters, props, and even whole chunks of buildings.

For extremely large models though - like the terrain mesh - this type of workflow is not typically used. Instead, we texture these assets with tiling albedo texture & normal maps, interpolating between multiple texture sets where we need a smooth change in the surface material. This lets us add detail to a practically unlimited amount of geographic area, with a modestly-sized amount of shared texture data.
> 0 votes

---
Tags: normal-mapping, asset-workflow
---


# Question
Title: How to manage server "view" of game board when it is shared by clients?
I'm currently creating a simultaneous turn based card game in which two players play cards in three lanes to determine who wins points in these lanes.

I've been struggling this past week trying to think of a good way to handle my game board on the nodejs server. The problem I'm having is that the game board consists of 3 lanes and 5 rows in a 2D array (I.E. indexs 0,0 to 2,4). When Player A plays a card to 0,0 on their screen it goes to 0,0 on the server, the problem then comes Player B plays a card in 0,0 locally but it translates to 2,4 on the server.

My question is, is there a better server game board pattern that enables a cleaner structure than to specifically make a playerA and B on my server and have a playerId tied to every call to know whether or not to invert the co-ordinates? If there is no better way, is it better to do the conversion on the client or server side? I.E. after matchmaking will the server tell each client if they are playerA or B or will the server just keep track of it?

Also, less important, but if in the future I wanted to add new gamemodes that support x number more players how will this pattern scale upwards?

# Answer
> 0 votes
If you want to eventually scale up to `n` players, then I think you'll want to abandon the idea that each player sends & receives input relative to their own local coordinate system.

Rather, all players should agree on one standard coordinate system. If you ask all players what card is at coordinates (2, 4), they should all give you the same answer.

This coordinate system is completely arbitrary. You could choose to use player 1's view of the table, or any other perspective you like.

What differs between players is their *view* of that universal table coordinate system. Think of this as the position of their camera around the shared table. You can represent this as a matrix that transforms the universal table coordinates into their local screen coordinates.

Each player can keep track of their own table-to-screen matrix as purely local information, without complicating the server logic.

When the player provides input on the screen, you multiply it by the inverse of the table-to-screen matrix to get the corresponding position in the universal table coordinates. That's what you send to the server.

The server can do its computations purely in this universal coordinate system, with every player speaking to it in the same geometric language, and it can send the same update to every player in this same language.

When the player receives data from the server in universal table coordinates, they can update their board state in that same internal representation. Then, when positioning & orienting display objects on screen, they use the table-to-screen matrix to find the corresponding pixel positions for their viewpoint.

---
Tags: unity, c#, client-server, node.js, typescript
---


# Question
Title: Show Sprites on Overlap (Shader Graph) [2D]
I have a character sprite mesh and mesh renderer (The black wavy box). I am hoping to be able to overlay the black box onto the character covering the sprites but I am not sure how to do that.

I looked at this question : Unity: How do I only show parts of objects that overlap \[2D\]

But this works more as a cover that you can see through. I am hoping to have the variable black mask the sprites of the character but I cant seem to layer these correctly. Is there a way to do this using the LWRP and shader graph?

The over arching idea is to use this as a damage marker. Moving the black box up or down depending on the health lost.

# Answer
> 1 votes
This is a little trickier to achieve than it looks, because each part of a sprite - by the time it reaches the GPU - is just a lone triangle that knows nothing about the other triangles in the scene, including the positions & sizes of other sprites.

So, we have to fake it a little. We can assign a new material to our sprite renderers for the character's sprite(s) (this will also work if you have a multi sprite character like a Spine / Puppet 2D animated character), using a shader like the one below:

```
Shader "Unlit/WorldspaceBlend"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        // Add a texture field for our overlay image.
        _Overlay("Overlay", 2D) = "white" {}
        _Color("Tint", Color) = (1,1,1,1)
    }
    SubShader
    {
        // Duplicate normal sprite shader behaviours.
        // (I skipped implementing pixel snap / split alpha though)
        Tags
        {
            "Queue" = "Transparent"
            "IgnoreProjector" = "True"
            "RenderType" = "Transparent"
            "PreviewType" = "Plane"
            "CanUseSpriteAtlas" = "True"
        }

        Cull Off
        Lighting Off
        ZWrite Off
        Blend One OneMinusSrcAlpha

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float4 color : COLOR;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float4 vertex : SV_POSITION;
                fixed4 color : COLOR;
                float2 uv : TEXCOORD0;
                float2 overlayUV : TEXCOORD1;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;

            fixed4 _Color;

            // Allow sampling from the overlay image.
            sampler2D _Overlay;
            float4 _Overlay_ST;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                o.color = v.color * _Color;

                // Compute what part of the overlay image we should sample.
                float2 worldPos = mul(unity_ObjectToWorld, v.vertex).xy;
                o.overlayUV = (worldPos - _Overlay_ST.zw)/_Overlay_ST.xy;

                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col = tex2D(_MainTex, i.uv) * i.color;

                // Sample our overlay image.
                fixed4 overlay = tex2D(_Overlay, i.overlayUV);
                // Blend it with our base image.
                fixed4 output = lerp(col, overlay, overlay.a);
                output.a = col.a;
                // Convert to pre-multiplied alpha, as used by sprite shaders.
                output.rgb *= output.a;

                return output;
            }
            ENDCG
        }
    }
}

```

This imitates the standard sprite shader, but adds an "Overlay" texture field you can assign in the material inspector for your black zigzag.

The material's scaling & transform parameters for this texture will determine how large & where it's drawn in worldspace. So, you'll want to add a script that sets the following each frame:

```
Vector4 overlayAlignment = character.transform.position + overlayOffset;

material.SetTextureOffset("_Overlay", overlayAlignment);

```

You can then vary the `overlayOffset` vector to slide your overlay texture around relative to the character's position.

---
Tags: unity, 2d, shaders, mesh, unity-shader-graph
---


# Question
Title: How can I create a mesh with Blender which changes mid game?
Take a situation where on the first half the player fights an enemy and after a cutscene, the player cuts off the hand of the enemy. How can I show him without his hand after this moment (when modeling it with the hands in Blender in a single skeletal mesh)? Do I have to make another skeletal mesh but without the hand? Similar to how in Assassin's Creed Origins where at the end of the snake quest after the cutscene Bayek losses his ring finger and remains without it all game. But in my case, the entire hand is removed.

# Answer
There are a few approaches.

If the hand mesh can be separated from the rest of the body, you could make a unique animation where the hand is detached and out of view, such as behind the camera (if this is a first-person animation).

If the hand cannot be removed from the arm (in the case of a continuous mesh), perhaps you can animate the hand's scale down to 0, and maybe translate it up into the wrist if it looks funny. Some games have used effects like this for 'headshots' that blow off characters heads, scaling it down to a finite point such that only the neck is visible.

Then there is the solution you mentioned, where you swap it out with an entirely different model where the hand is missing.
> 2 votes

---
Tags: blender
---


title: Props or blocks?

text:
# Question
Title: Props or blocks?
I was wondering what would be best if I was to create a really big map with many items or decorations. Currently I'm working on a library for a GMod/Garry's Mod Server and I wanted to add a lot of shelves. Perhaps with a variety of different looking shelves like one shelf with red books another one with yellow and another one with blue and green and some with everything mixed together.

So I was wondering what would be the best for the performance. I mean many small objects usually tend to need a lot of rendering but if it's best to set a model as `prop_static` that would also be great.

The other shelves I found are all `prop_dynamics` or `prop_physic` but `prop_static` would be good enough for me.

The main question is "What's best, (in regards of server performance) Prop or Block?"

# Answer
> 0 votes
Setting the func\_detail for many blocks help with the performance and compiling time. Check here for more: https://www.reddit.com/r/hammer/comments/3gdjxv/portal\_flow\_vvis\_taking\_forever/ http://www.tophattwaffle.com/hammer-tutorial-v2-series-6-basic-optimization/ https://www.tophattwaffle.com/hammer-tutorial-v2-series-21-optimization/

---
Tags: hammer, garrys-mod
---


# Question
Title: Spawn prefabs from list one by one when trigger is touched
I am trying to spawn one gameobject from a list of gameobjects each time I touch the trigger with the controller.

But when I do this, all the game objects from the list spawn together at the same time. I couldn't figure out how to solve this problem and make them spawn one at a time instead, where the next touch spawns the next object in the list, and so on.

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

public class Trigger : MonoBehaviour
{

    public Transform spawnPoint;
    //public GameObject Prefab;
    public List<GameObject> items = new List<GameObject>();

    void OnTriggerEnter(Collider other)
    {
        //GameObject Prefab = new GameObject("prefab");

        for (int i = 0; i < items.Count; i++)
        {
            Instantiate(items[i], spawnPoint.position, spawnPoint.rotation);
            Debug.Log("Hello World" +i);
        }

    }

}

```

# Answer
Assuming you want to spawn one GameObject per touch, you could store the spawnIndex outside the method, and increment it by one each time you spawn.

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

public class Trigger : MonoBehaviour
{
  public Transform spawnPoint; //public GameObject Prefab;
  public List items = new List();
  private int spawnIndex = 0;

  void OnTriggerEnter(Collider other)
  {
    //GameObject Prefab = new GameObject("prefab");
    int i = spawnIndex++ % items.Count;
    // int i = Random.Range(0, items.Count); // for random each time
    Instantiate(items[i], spawnPoint.position, spawnPoint.rotation);
    Debug.Log("Hello World" + i);
  }
}

```
> 1 votes

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


title: How to change the KEYSTORE securely?

text:
# Question
Title: How to change the KEYSTORE securely?
I'm wanting to release a free version of an app to which I've already made a paid version.

I simply copied the project to another folder:

The project is initially the same as the paid application when finalized. I want to simply delete a few phases and put a link that takes the application paid in the Google Store (this I know how to do);

Turns out there is something called a keystore.

I would like to know if only thing I have to do is create a **file.keystore** in the directory with different name, rename the Filename (before **Password**) and click the generate button (below **Country**).

OBS - Obviously I will make a backup copy of the paid version **file.keystore**.

# Answer
> 0 votes
First I changed the first field (**filename**).

Then I clicked on button **generate**.

The program has created a new key in a different location than where I put the keys.

Just copy or move the key to the place of your choice.

Be very careful not to create a new key without having made a copy of the previous one. Otherwise, **you may be unable to update your game in the Play Store**.

---
Tags: android, game-maker, version-control
---


# Question
Title: Photon2 Unity2D How to send float with RPC
I have big problem in my code .. I want to spawn obstacle exactly on the same position as on the server is spawned so I made rpc Method and tried to pass random variable of float , but when i run the game obstacles are spawned on the diffrent position. I am loosing a lot of time to get it done but I still can not find solution.

Here is the code

```
   [PunRPC]
    void RPC_SpawnColumn(Vector3 position)
    {
        // Instantiate(prefab, position, Quaternion.identity);
        Debug.Log("THIS IS SPAWNYPOSITION" + spawnYPosition);

        Instantiate(prefab, new Vector2(9, spawnYPosition), Quaternion.identity);

    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        //print("Are we here");
        if (collision.GetComponent<ColumnsMultiplayer>() != null)
        {

            print("Or are we here");
            if (SpawnOnce)
            {
                spawnYPosition = Random.Range(-3.36f, 2.98f);

                photonView.RPC("RPC_SpawnColumn", RpcTarget.Others,new Vector3(9, spawnYPosition));  // this is

            }
                //SpawnColumn();

            SpawnOnce = false;

        }
    }
```

Thank you so much for reading post.

Edit: I need to send spawnYPosition from method two to method one and spawn it with same position of spawnYPosition in the second method.

# Answer
> 0 votes
It looks like you might need a refresher on function arguments.

When you define a function like this:

```
void RPC_SpawnColumn(Vector3 position)

```

You're saying "I will accept as input a `Vector3` value, and I will call that value `position` inside the body of this method" - this `position` variable is called an argument to the function, and you can use it like other variables inside its body.

Now, when you call the function (remotely) like this:

```
photonView.RPC("RPC_SpawnColumn", RpcTarget.Others, new Vector3(9, spawnYPosition));

```

You're saying "Call the function, and pass it the value `(9, spawnYPosition, 0)` to use as the `position` argument"

So, inside the body of `RPC_SpawnColumn`, if you want the value of `spawnYPosition` which you passed as the y coordinate of the `position` argument, you can get it by reading `position.y`.

So it looks like you want to change this line, which makes up a new vector with whatever value we have in `spawnYPosition` locally:

```
Instantiate(prefab, new Vector2(9, spawnYPosition), Quaternion.identity);

```

to this line, which uses the `position` that was sent to us via the RPC call (including `spawnYPosition` in the y component):

```
Instantiate(prefab, position, Quaternion.identity);

```

---
Tags: unity, photon
---


title: Unity2d Camara smooth zoom issue

text:
# Question
Title: Unity2d Camara smooth zoom issue
want to know that how mathf.movetowards works, i tried to play around it and have some issues. i want to make the camera moves from player to target places along with zooming upon triggered and vise versa, while smooth follow(camera changes target) works, smooth zooming doesn't work. i place the movetowards code to ontriggerenter/exit, but it doesn't work as intended as it only zoom for frames. However, if i place it at update side, the zooming doesn't work at al.

code provided for more infomation.

```
public class Disable : MonoBehaviour {
GameObject player;
GameObject Camera;
public Transform placeHolder;
public float smoothTime = 2f;
public float adjustSize;
public float originalSize = 6.5f;
public float targetOrtho;

public Vector3 velocity;

void Awake()
{
    player = GameObject.FindGameObjectWithTag("Player");
    Camera = GameObject.FindGameObjectWithTag("MainCamera");

}
private void Start()
{
    targetOrtho = originalSize;
}

void Update()
{
    Camera.GetComponent<Camera>().orthographicSize = Mathf.MoveTowards(Camera.GetComponent<Camera>().orthographicSize, targetOrtho, smoothTime * Time.deltaTime); //doesn't work

}

void OnTriggerEnter2D(Collider2D other)
{
    if (other.gameObject == player)
    {

        Camera.GetComponent<Camera2DFollow>().target = placeHolder;
       targetOrtho = adjustSize;
       //Camera.GetComponent<Camera>().orthographicSize = adjustSize; //works but only changes the size without smooth
       //Camera.GetComponent<Camera>().orthographicSize = Mathf.MoveTowards(Camera.GetComponent<Camera>().orthographicSize, adjustSize, smoothTime * Time.deltaTime); //works but only did for a few frames( not completely)

    }
}

void OnTriggerExit2D(Collider2D other)
{

    Camera.GetComponent<Camera2DFollow>().target = null;
    targetOrtho = originalSize;
    //Camera.GetComponent<Camera>().orthographicSize = originalSize; //works but only changes the size without smooth
    //Camera.GetComponent<Camera>().orthographicSize = Mathf.MoveTowards(Camera.GetComponent<Camera>().orthographicSize, originalSize, smoothTime * Time.deltaTime); //works but only did for a few frames (not completely)
}

```

# Answer
> want to know that how mathf.movetowards works

Anytime you want to know how part of Unity's C# API works, you can look it up in the published source code:

```
// Moves a value /current/ towards /target/.
static public float MoveTowards(float current, float target, float maxDelta)
{
    if (Mathf.Abs(target - current) <= maxDelta)
        return target;
    return current + Mathf.Sign(target - current) * maxDelta;
}

```

As you can see, `MoveTowards` is just a math function: it takes in some numbers, and returns a computed number.

It does not have any knowledge about what you want to do with that number. It doesn't receive a reference to any object that you want it to update, which is why you have to assign the return value yourself:

```
Camera.GetComponent<Camera>().orthographicSize = Mathf.MoveTowards(...

```

This assignment happens exactly once: the frame when this line of code is run. It does not kick off a background process that will keep updating the object frame over frame. If that's the behaviour you want, then it's your job to write that code:

```
Coroutine zoomTween;

IEnumerator ZoomCoroutine(Camera camera, float targetSize, float duration) {
    float startSize = camera.orthographicSize;

    for(float t = 0f; t < duration; t += Time.deltaTime) {
        float blend = t/duration;
        // A SmoothStep rather than a Lerp might look good here too.
        camera.orthographicSize = Mathf.Lerp(startSize, targetSize, blend);

        // Wait one frame, then resume.
        yield return null;
    }

    // Finish up our transition, and mark our work done.
    camera.orthographicSize = targetSize;
    zoomTween = null;
}

void ZoomTo(Camera camera, float targetSize, float duration) {
    // Check if we're already in a zoom transition, and stop it to ensure we don't double-up.
    if(zoomTween != null)
        StopCoroutine(zoomTween);

    // Kick off a new zoom transition that can keep going on future frames.
    zoomTween = StartCoroutine(ZoomCoroutine(camera, targetSize, duration));
}

```

Then when you want to change zoom, you just call `ZoomTo()` with your desired parameters.
> 1 votes

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


title: glOrthof not being applied

text:
# Question
Title: glOrthof not being applied
I have had a problem with OpenGL where glOrthof is not being applied, leading to my frame having the default 1:1:1 ratio. Here is the code initializing it:

```
    public void reshape(GLAutoDrawable glAutoDrawable, int i, int i1, int i2, int i3) {
        GL2 gl=glAutoDrawable.getGL().getGL2();
        if(window.getWidth()!=screenWidth||window.getHeight()!=screenHeight)window.setSize(screenWidth,screenHeight);
        unitsTall=window.getHeight()/(window.getWidth()/unitsTall);
        gl.glMatrixMode(GL2.GL_PROJECTION);
        gl.glLoadIdentity();
        gl.glOrthof(0.0f, unitsWide, 0.0f, unitsTall, 0.0f, 1.0f);
        gl.glMatrixMode(GL2.GL_MODELVIEW);
    }

```

unitsWide is equal to 100. Here is the code for drawing the rectangle:

```
    public static void drawRect(float x,float y,float width,float height){
        GL2 gl=Render.getGL2();
        gl.glRotatef(-rotation,0,0,1);//Rotation needed to be reversed
        gl.glColor4f(red,green,blue,alpha);
        gl.glBegin(GL2.GL_QUADS);
        gl.glVertex2f(x,y);
        gl.glVertex2f(x+width,y);
        gl.glVertex2f(x+width,y+height);
        gl.glVertex2f(x,y+height);
        gl.glEnd();
        gl.glFlush();
        gl.glRotatef(rotation,0,0,1);
    }

```

The "Render" class is the class with all of the main methods for OpenGL. Here is the code that I used for drawing the rectangle:

```
Graphics.drawRect(0,0,0.5f,1);

```

Finally, here is a screenshot of what it looks like when this code executes:

I have looked around and have not found any other problems like this. Please tell me what I might be doing wrong.

# Answer
> 1 votes
```
unitsTall=window.getHeight()/(window.getWidth()/unitsTall

```

You probably intend to divide by unitsWide here; if you check the value of unitsTall in your debugger you'll likely find that it's 0, so you're actually getting a division by 0, which is messing up your matrix.

---
Tags: opengl, java, jogl
---


# Question
Title: Why Unity3D 2018 UI looks bad and very sharpy?
I update my project from Unity 2017.1.1 to 2018.3.9 and almost everything is OK except UIs. All of UIs like Images,Buttons,texts,text mesh pro, sprites and others looks very sharpy and pixel pixel ...

please see the attached image :

Unity3D 2017 before update :

Unity3D 2018 after update :

why this happens ? and how can I solve this problem ?

# Answer
> 4 votes
We just need to change Scale and layout to 100% in windows setting panel .

And in advanced scaling setting I turn on "Let Windows try to fix apps so they're not blurry" .

After that Unity UI problem is gone.

---
Tags: unity, sprites, gui, text
---


title: Timer breaks after changing scenes

text:
# Question
Title: Timer breaks after changing scenes
I am using this script below to move an animation in unity with no root-motion. It simply walks across the terrain.

I have timer attached also so the animation doesn't start to walk for 60 seconds. This works fine in the scene when played…but when I navigate into this scene from another home scene the timer delay doesn't work as I guess it has been triggered already and has already reached the 60 second mark? I have tried using `DontDestroyOnLoad` but this just recreates the animation in the home scene also.

I'm trying to keep the code as simple as possible and maybe add to the code below to fix it:

```
void Update ()
{
    if (Time.time > 60)
    {
        transform.Translate (0, 0, Time.deltaTime);
    }
}

```

# Answer
`Time.time` returns the number of seconds since the start of the game. "Start of the game" refers to the moment the game was launched, not the moment the current scene was loaded.

If you want this movement to start 60 seconds after a scene has loaded, use `Time.timeSinceLevelLoad` instead. This returns the time in seconds since the last level has been loaded. In other words, it starts counting up from 0 every time a scene is loaded.

```
void Update ()
{
    if (Time.timeSinceLevelLoad > 60)
    {
        transform.Translate (0, 0, Time.deltaTime);
    }
}

```
> 3 votes

---
Tags: unity, timer, scene
---