# Question
Title: I have imported a FBX model. It has predefined Transform values in Imported Object setting in the Inspector. How can I change those transform values?
*what my problem is:*

I imported FBX models, when I click those objects from Project tab, I see the values of Transform are different and can't be changed (The Transform values under Imported Object section in the Inspector tab). These Transform values belong to the FBX object instead of a GameObject from the Hierarchy. And it seems it is predefined and I could not find a way to change them.

*Here is how it looks:*

*How it should look like:*

*Why is it a problem:*

Because I spawn (Instantiate) their prefabs during gameplay but even though the values of the Transform (position) in their prefab is 0 and even the code is correct, those 2 objects spawn to different locations because of this predefined Transform values. (And even though their GameObjects' Transform is correct after spawning)

*Why it occurs:*

I did not create the FBX models so I do not know how they exported. (I'm trying to work for a studio and they wanted me to create a mini prototype game.) After models sended to me, I put them to the Assets folder of Unity. I also tried to import them from the *Import new Asset...* settings from the Assets tab but it also did not solve the issue. So I don't know how to change those settings.

*Other things I tried to solve the issue:*

I imported the FBX files to Blender, thinking that if I re-export them maybe the transform values look right when I reimport them to Unity. And it did but all the materials gone when I imported them to Blender and I can't access or find materials either in Blender or Unity. So I contacted the person who sent me the models and told them to change the transform values from the program which the models created, and then export them as FBX and send me. But they said I need to look the import settings in Unity again. No import settings occur when I import them. And the import settings of the Transform can't be changed.

So I have no clue how to change the Transform values of the Imported Object (making the position zero of that Transform)

I also tried to change those values from script but looks like it is not possible. Any help is appreciated.

Much thanks \<3

**P.S.**

The local pivot of the prefab of the object (the first screenshot in this question) which has the wrong transform values in fbx: (Object name is V11):

And below is from the other object, local pivot of the prefab of the object (the second screenshot in this question) which has the correct transform values in fbx: (Object name is V12):

# Answer
I tried to find the Freeze Transforms option but could not find it. I imported the fbx objects to Blender and just re-exported them. It looks like the transform values corrected but all the materials gone just after importing them to Blender. So all models look they do not have materials.

And I realized that I can extract the embedded materials of the old models (the ones which have wrong transform values) so I extracted those materials in unity **(expand the fbx model and right click the material (you can select all the materials with shift click and then right click))** and placed those materials to the new models which have correct transform values. And that's how I solved the problem. I hope it helps for someone who is having the same issue.

**Expanding the fbx model (in Unity, under project tab):**
> 2 votes

# Answer
I believe you have to open it in a 3D modelling software (such as Blender or Maya), and do action "Freeze Transforms"
> 0 votes

---
Tags: unity, transformation, fbx, import
---


# Question
Title: How to render picture-in-picture effect with libGDX camera
libGDX cameras are mostly used for layered rendering with different "world unit size," but I wonder is there a way of showing the view of for example a libGDX Orthographic camera in the corner of screen - lets say showing what a drone's camera sees from ground?

Here's an example:

How can I achieve such effect?

# Answer
> 2 votes
You can render the drones view to a `FrameBuffer`, and then draw that `FrameBuffer` onto your main screen.

This is often referred to as *render to texture*.

FrameBuffers in libGDX

---
Tags: libgdx, rendering, camera, viewport
---


# Question
Title: How to smoothly transition between two images in a image component?
I have a state machine responsible for transitioning between different images, corresponding to player actions. I want to make the image a part of UI, but my main question is how do I transition between two images.Will using Lerp work in this situation? For reference I want to transition it like in powerpoint animation or windows image slideshow.

# Answer
> 1 votes
The easiest non-programer way to do this would be to use an animation to animate the transparency between two image components.

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


# Question
Title: How to implement movement with move speed in a multiplayer game?
I'm developing a MMO RPG using Rust and bevy both in the client and the server, which means that I'm using ECS on both sides. My game is tile based, so each tile is a point in my map in the server, like this:

I am trying to implement a movement system which works with a movement speed, but all the calculations are being done in the server and it works fine, my problem here is in the client. The problem is that, when the user clicks to move in the screen, I am sending a message to the server to set a path to that destination, and since during the path things can occur, like, players walking through or enemies, I'm sending one tile per time that the player should move after the amount of time based on the move speed. So let's say that the player can move 1 tile per second, if I set a path that has 10 tiles, it will take 10 seconds to walk.

The problem happens that sometimes in the client, the player ends up with a transform that is not aligned with the tile, like if it is losing some pixels during the walk animation. At first I thought the server is sending messages faster than the client expects and it starts moving from a point in the middle of the way to other tile, so every time the server sends a message to walk to a direction, I store that in a queue and only starts the next move once the first is done. But this didn't solve the issue and I've been trying to figure this out for days now and I just don't know how to do this.

Each frame I update the translation a little bit based on the move speed, but at the end the translation must be a multiple of 32 since my game is all 32x32 pixels. I will put some code here, but I think the problem is not the code but the way that I'm doing things, so I would like a new idea.

```
for (mut transform, entity, moving, mut sprite, movement, mut direction, mut moves) in
    query.iter_mut()
{
    let mut should_move = false;

    if let Some(moving) = moving {
        if (transform.translation.x < moving.final_destination.translation.x - 2.
            && moving.x_move > 0.)
            || (transform.translation.x > moving.final_destination.translation.x + 2.
                && moving.x_move < 0.)
            || (moving.y_move > 0.0
                && transform.translation.y > moving.final_destination.translation.y + 2.)
            || (moving.y_move < 0.0
                && transform.translation.y < moving.final_destination.translation.y - 2.)
        {
            let constant = 32. / ((1. / movement.0 as f32) * 200.);

            transform.translation = transform.translation.add(Vec3::new(
                moving.x_move * constant,
                -moving.y_move * constant,
                0.0,
            ));
        } else {
            if sprite.index % 3 == 0 {
                sprite.index += 1;
            } else if sprite.index % 3 == 2 {
                sprite.index -= 1;
            }

            transform.translation.y = moving.final_destination.translation.y;
            transform.translation.x = moving.final_destination.translation.x;

            for (entity, t) in destination_query.iter() {
                if t.translation.x == transform.translation.x
                    && t.translation.y + 10.0 == transform.translation.y
                {
                    commands.entity(entity).despawn_recursive();
                }
            }

            should_move = true;
        }
    } else {
        should_move = true;
    }

    if should_move {
        if moves.0.len() > 0 {
            let m = moves.0.remove(0);

            commands.entity(entity).insert(m.clone());

            if m.x_move > 0.0 {
                *direction = Direction::Right;
                sprite.index = 7;
            } else if m.x_move < 0.0 {
                *direction = Direction::Left;
                sprite.index = 4;
            } else if m.y_move < 0.0 {
                *direction = Direction::Up;
                sprite.index = 10;
            } else {
                *direction = Direction::Down;
                sprite.index = 1;
            }

            commands
                .entity(entity)
                .insert(AnimationTimer(Timer::from_seconds(
                    0.06 / movement.0 as f32,
                    TimerMode::Repeating,
                )));
        } else {
            commands.entity(entity).remove::<Moving>();
            commands.entity(entity).remove::<AnimationTimer>();
        }
    }
}

```

Basically when I receive the message from the server, I add to the `Moves` component the next move, so the `Moves` component is actually the queue. Then I check if it's moving already, if so, update the translation based on the move speed until reaches the final translation, which should be the next tile. This is the part that doesn't work. The bottom part of the code is just updating the sprite and getting the next move from the queue.

And to show what I mean that it loses some pixels during the animation, look the image below, the skeleton has the right alignment to the tile, see that the player is just a little bit off to the left?

This doesn't happen all the time, but happens very often, like 50% of the times, but I still can't figure why this is happening.

# Answer
Typically in a server authoritative game simulation the server would send or replicate the state of the object and the client would simulate to achieve that state.

So for example here might be some flow:

1. client sends message to move to a position
2. server receives message and begins moving the object
3. server replicates the authoritative position of the object
4. the client now simulates movement using the same speed that the server uses to move the client to that position
5. the server continually sends updates about the next position and the client continually moves to achieve that state.

There are of course many types of variations to this, such as both client/server doing simulation at the same time, and then the client upon receiving a server update works to correct it's simulation to match.
> 1 votes

---
Tags: movement, entity-component-system, rust, bevy
---


# Question
Title: Showing something different on screen to what is seen in Oculus
I was tasked with creating a demo for something involving VR. They want people to use the VR headset, but they also want to visualize some of the calculations that go on behind the scene to the audience.

To that end, I was asked to have the computer screen show something different to what the VR is showing.

The difference would be the addition of objects from a layer that isn't included in the `OVRCameraRig`'s left and right cameras' culling mask.

I've tried messing a bit with the code in the `OVRCameraRig` script to make sure all 3 cameras (left, right, and center) are enabled, but that didn't work (and I'm hoping there's a simpler solution than debugging that script to try and make that work)

I've also tried adding a camera as a child of `LeftEyeAnchor` with its culling mask set only to the additional layer I want to overlay, its target set to `Left eye`, and `Clear Flags` set to `Depth only`, but that led to the right eye getting nothing and the left eye getting the object I don't want to be seen on the VR goggles.

Is there a way for me to either get the overlay to only show up on the screen or create another window that will show everything *without a 3rd camera that repeats everything already done with the other cameras*? (That is, I worry that adding a 3rd camera with its culling mask set to "everything" and having that displayed on another screen would drop the FPS)

# Answer
You probably had the "almost" there solution with the child of LeftEyeAnchor.

Did you check this out first: https://docs.unity3d.com/Manual/MultiDisplay.html

You will want to add an additional camera for displaying it's view on a separate display altogether.

The parenting to the VR objects in the scene might be causing you headache if the scripts are expecting camera's in that game hierarchy to be used for the VR headset and are modifying properties or something. If that is the case you can always just add a Follow MonoBehavior to your camera to move with the other camera's but not be a child of them.
> 1 votes

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


title: Discounts on In-App Purchases

text:
# Question
Title: Discounts on In-App Purchases
A client asked me about implementing In-App Purchase discounts on the Apple App Store and Google Play. For example, putting an item that's normally $7.99 on sale for $5.99.

I've primarily been working on desktop games for the last couple of years so my memory is rusty, but from some quick research it sounds like neither the App Store or Google Play supports IAP discounts of this nature for consumable or non-consumable items (though there can be discounts for things like subscriptions or pay-up-front apps).

I can think of several possible alternate approaches:

1. Create multiple IAP items for the same product, at different prices, and control which one is active at at time. So for example, BOOSTER\_PACK costs $7.99 and BOOSTER\_PACK\_ONSALE costs $5.99, but only one of these two products shows up in the store at a given time. *However*, this seems like it's circumventing the rules and would probably cause the IAP to be rejected (on the App Store at least).
2. If the game uses a premium currency model, IAP currency packs come with bonus currency during the sale. So for example, $5 normally gives you 50 gems, but during the sale, you get an extra 15 gems for free with the $5 pack. This might also be seen as circumventing the rules.
3. If the game uses the premium currency model (where the player can buy a currency like Gems with real money, and then spend Gems on in-game items), the price of buying in-game items with virtual currency can be reduced (so for example, $5 always gives you 50 gems, but during a sale, an item that normally costs 50 gems might instead cost 35 gems). This seems like the safest approach because any given IAP pack always has the same price and gives you the same item(s).

Are there any other strategies I'm not thinking of for offering discounts on IAP?

# Answer
> 1 votes
Solution 1 is what you want.

When you say only one shows up in the store at a time, that is entirely up to your code to display the items you want to sell. The IAP setup in the store has nothing to do with what you provide in app to purchase other than linking the price point to an identifier and your portal sales reports.

BOOSTER\_PACK BOOSTER\_PACK\_OFFER\_1

In our game we simply have ITEM\_999, ITEM\_599. and we manage the actual sales reports internally for the consumable items that are purchased. It makes the store setup easier, but does involve better bookkeeping internally in our system.

---
Tags: mobile, appstore, in-app-purchase
---


# Question
Title: Collisions in other sides on pong in python
Im trying to create pong in python, so far Ive set up correct collisions on the right paddle but upon just trying to reverse the code to work with the other side it refuses to work, simply glitching and holding the ball in its axis somehow, anyone know how to help?\`

```
from processing import *

ball = {
    'x': 50,
    'y': 50,
    'velocity_x': 3,
    'velocity_y': 3,
    'radius': 10
}
width = 550
height = 400

paddle1 = {
    'x': width - 20,
    'y': 160,
    'width': 15,
    'height': 100,
    'velocity': 5,
    'move': 0
}
paddle2 = {
    'x': width - 545 ,
    'y': 160,
    'width': 15,
    'height': 100,
    'velocity': 5,
    'move': 0
}
score = 0
def setup():
    # set the size of the canvas
    size(width, height)

def draw():
    # clear the previous frame by setting the background color of the canvas
    background(0, 0, 0)

def drawPaddle1():
    fill(0, 0, 255)
    rect(paddle1['x'], paddle1['y'], paddle1['width'], paddle1['height'])

def drawPaddle2():
    fill(0, 255, 255)
    rect(paddle2['x'], paddle2['y'], paddle2['width'], paddle2['height'])

def checkCollisions1():
    global score
    if ball['y'] >= paddle1['y'] and ball['y'] <= paddle1['y'] + paddle1['height']:
        if ball['x'] + ball['radius'] >= paddle1['x']:
            ball['velocity_x'] = -ball['velocity_x']
            ball['x'] = paddle1['x'] - ball['radius']

def checkCollisions2():
    global score
    if ball['x'] >= paddle2['x'] and ball['x'] <= paddle2['x'] + paddle2['width']:
        if ball['x'] + ball['radius'] >= paddle2['x']:
            ball['velocity_x'] = +ball['velocity_x']
            ball['x']
            ball['x'] = paddle2['x'] + ball['radius']

def drawBall():
    fill(255, 255, 255)
    ellipse(ball['x'], ball['y'], 2 * ball['radius'], 2 * ball['radius'])

def moveBall():
    ball['x'] = ball['x'] + ball['velocity_x']
    ball['y'] = ball['y'] + ball['velocity_y']
    if ball['y'] + ball['radius'] >= height or ball['y'] - ball['radius'] <= 0:
        ball['velocity_y'] = -ball['velocity_y']
    if ball['x'] + ball['radius'] >= width or ball['x'] - ball['radius'] <= 0:
        ball['velocity_x'] = -ball['velocity_x']

def draw():
    # clear the previous frame
    background(0, 0, 0)
    fill(255, 255, 255)

    drawBall()
    moveBall()
    drawPaddle1()
    drawPaddle2()
    checkCollisions1()
    checkCollisions2()

run()`

```

# Answer
I've noticed a few wrong things on the collision lines:

```
def checkCollisions1():
    global score
    if ball['y'] >= paddle1['y'] and ball['y'] <= paddle1['y'] + paddle1['height']:
        if ball['x'] + ball['radius'] >= paddle1['x']:
            ball['velocity_x'] = -ball['velocity_x']
            ball['x'] = paddle1['x'] - ball['radius']

def checkCollisions2():
    global score
    if ball['x'] >= paddle2['x'] and ball['x'] <= paddle2['x'] + paddle2['width']:
        if ball['x'] + ball['radius'] >= paddle2['x']:
            ball['velocity_x'] = +ball['velocity_x']
            ball['x']
            ball['x'] = paddle2['x'] + ball['radius']

```

First, on `checkCollisions1`, you check if `ball['x'] + ball['radius'] >= paddle1['x']:` and if that's true, you set the ball's position like this: `ball['x'] = paddle1['x'] - ball['radius']`. This is not wrong, if the ball moves on the X axis every frame without having its speed ever hit 0. But if for some reason that function runs twice without the ball moving on the X axis, it will trigger collision twice.

You mentioned the first collision works properly, so that's probably not a big issue, but something worth being aware of. One suggested solution is changing the if condition to use `>` instead of `>=`, so that when collision happens, the ball will be placed in a position where collision can no longer happen, unless one of the two objects moves closer to each other.

On the second collision there are a number of things wrong. Firstly, on the first `if` condition, you check the ball's and paddle's X axis, contrary to the first collision where you check the Y axis first.

First collision:

```
if ball['y'] >= paddle1['y'] and ball['y'] <= paddle1['y'] + paddle1['height']:

```

Second collision:

```
if ball['x'] >= paddle2['x'] and ball['x'] <= paddle2['x'] + paddle2['width']:

```

This is not enough, as it's the same as the first collision, so you need to change a little bit of the code like this:

```
if ball['x'] <= paddle2['x'] and ball['x'] >= paddle2['x'] - paddle2['width']:

```

This seems to be an error as on the next line you check the ball's X and paddle's X again, so they should be changed to the Y axis, and `width` should change to `height`.

On the next line, I can't tell if it was a copy-paste error, or it's a syntax error (I have limited knowledge on python), but this line seems wrong:

```
ball['x']

```

That's all I found from a quick look, let me know if the problem still occurs.
> 1 votes

# Answer
Your collision2 function is wrong it should be:

```
def checkCollisions2():
  global score
  if ball['y'] >= paddle2['y'] and ball['y'] <= paddle2['y'] + paddle2['height']:
    if ball['x'] - ball['radius'] <= paddle2['x'] + paddle2['width']:
        ball['velocity_x'] = -ball['velocity_x']
        ball['x'] = paddle2['x'] + paddle2['width'] + ball['radius']

```
> 0 votes

---
Tags: collision-detection, python
---


# Question
Title: Calculating LookAt position from rotation and translation matrix
I was wondering if it was possible to calculate a lookat position from the translation and rotation matrices (aka the building blocks of my view matrix). I need the lookAt position to implement a special type of frustum culling, but my program does not use the lookat position, so I was looking for a simple solution to calculate it.

# Answer
> 0 votes
Your view matrix is the inverse of the object's camera transformation, and the inverse of a rotation matrix is just its transpose, so the 3rd row is your camera's local forward vector.

Add some multiple `d` of the third row of your view matrix to your camera position to get a point `d` units in front of your camera along its forward axis.

(This is equivalent to multiplying the vector `(0, 0, d, 1)` by the camera's transformation matrix, or the inverse of the view matrix, just skipping redundant ops for the zero terms)

Using that as a look-at point will give the same result as your current camera orientation, since your camera is already looking at it.

Some APIs treat negative `d` values as "in front" of the camera, while others say that's behind and positive is in front, so flip the sign on `d` if you initially get the wrong answer.

---
Tags: camera, matrix, view, frustum-culling
---


# Question
Title: What are Unity's problems with garbage collection
I've been asked this in interviews before and I can never seem to find a definite answer. I know Unity's garbage collection isn't great, but if you were to ask this question in an interview, what would you expect to hear?

# Answer
> 2 votes
I have no idea what answer is expected but if I'm asked on an interview I would say the "problem" is that GC requires freezing of the state of the program but games are usually very dynamic. This makes those freezes much easier to spot with games where there are constant movements on the screen (stuttering).

Until recently GC used by Unity was not incremental, meaning it must do all its job in single game freeze. And that may make those freezes long enough to be noticed.

Now there is an option for incremental GC (i.e. staged GC, freezes more often for shorter times) but it must be profiled if it brings improvement for the current game. Incremental GC have this problem of the state of the game changing between GC stages which can force the GC to re-analyse the changed state over and over from scratch and ultimately be slower than the non-incremental one.

# Answer
> 1 votes
Based on the documentation for memory management & garbage collection:

Allocating managed memory is time-consuming for the CPU, so memory management (including garbage collection) impacts runtime performance. At an extreme, garbage collection can prevent the CPU from doing other work until it completes. Note: I take this to mean "completes some task". As others have noted, the GC is incremental, but while it might not need to stop everything to solve everything (see prior versions of memory management for details), it may still need to consume CPU time in a way that is noticeable.

Unity's memory management can lead to memory fragmentation, meaning the available & allocated blocks of memory are interspersed. Basically, "gaps" of available memory form as garbage collection releases memory that's no longer needed. As a result you can have situations where sufficient amount of memory available in the managed heap for some allocation, but it is only available in the "gaps" between allocated objects that are still in use. In that case the managed heap can't find a large enough single block of contiguous memory to perform the assignment. Here's an illustration:

`A` shows the allocation that we want to make `B` shows available memory: a block from a previously deallocated `string`, a block from a previously deallocated `int[]` & a free block.

If the garbage collector runs & cannot find enough contiguous space, it expands the heaps. Expansion is platform-dependent, so it's not a learn it once apply it everywhere sort of thing - you should consider each separately. The typical expansion is double the amount of the previous expansion.

Eventually Unity releases empty portions of the managed heap back to the operating system, but it doesn't do so at reliable intervals.

Summarizing:

* Memory management & garbage collection require CPU time.
* Garbage collection can lead to fragmentation.
* Fragmentation can lead to not having enough *continuous* memory.
* Lack of continuous memory triggers expansion.
* Expansion rules vary by platform.
* Memory isn't returned back to the OS at predictable intervals.

# Answer
> -1 votes
Garbage collection in Unity refers to the .NET GC. There is no "problem" with GC other than what you would expect to find with the pros and cons of a GC, and you can read about .NET GC on the web easily.

What they are probably expecting to hear, is that Unity does not do a garbage collection cycle until you call LoadScene and switch to another scene. LoadAdditive does not call GC.

---
Tags: unity
---


# Question
Title: Viewing a List of A Custom Class inside of Unity Inspector
I have a Script with a custom class, which I've attached to a Unity GameObject:

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

[Serializable, Inspectable]
public class listOfBlends : MonoBehaviour
{
    [Inspectable]
    public List<individualBlend> blendList;

 }

    public class individualBlend
{
    [Inspectable]
    public List<String> feemText;
    [Inspectable]
    public List<NeemData> listOfNeemsInBlend;
    public Boolean blendCompleted;
}

```

I'd like to be able to view this List inside of Unity, but the Inspector just shows me a List with items... and each item says, "No Inspector for 'Individual Blend'."

I'd like to be able to view the Individual Blends inside of the Inspector. I've been researching Custom Editors, but am struggling with the learning curve... any advice on how to make the Individual Blends fully viewable in the Inspector? Thank you!!

# Answer
Unity uses the serializer to power its inspector views, so be sure to put the `[System.Serializable]` attribute on any type you want to display in the inspector that doesn't descend from `UnityEngine` classes like `MonoBehaviour` or `ScriptableObject`.

Here, the `[Serializable]` should be above `public class IndividualBlend` (type names start with an uppercase letter in standard C# nomenclature), not above `public class ListOfBlends : MonoBehaviour` (`MonoBehaciour` types are already serializable by default).
> 1 votes

---
Tags: unity
---


# Question
Title: ECS - Components that access other components
This question is about how to design my ECS system.

I have the following components:

* Position
* Gravity

Gravity needs to access Position.

Is there a better design that does not introduce this dependancy?

Position doesn't have any behaviour, it's just accessed by a bunch of things. Should it even be a component? What about other data only components?

# Answer
> 4 votes
> Position doesn't have any behaviour, it's just accessed by a bunch of things. Should it even be a component?

Just data without behavior is pretty much the definition of a component in ECS.

> I have the components Position and Gravity. Gravity needs to access Position.

No, it doesn't. In an idiomatic ECS architecture, components don't have dependencies because they don't contain any logic. Components are just dumb data. All the logic is in the systems.

The Gravity *System*, however, is a different story. It needs access to the Gravity component **and** the Position component of all entities which have both these components. Systems which implement interactions between two components are pretty common in ECS architectures. Such systems of course depend on both of those components. The ECS architecture is responsible for providing such systems with access to all the component-tuples that are relevant for them.

---
Tags: entity-component-system
---


# Question
Title: Clamp GameObject into isometric camera viewport
I'm using this code to move an object into an isometric projection, as viewed by an orthographic camera tilted with Euler angles (30, 45, 0)

```
[SerializeField] private Camera cam;
[SerializeField] private Transform target;
[SerializeField] private float speed;

private Vector3 forward, right;

private void Start()
{
    forward = cam.transform.forward;
    forward.y = 0;
    forward = Vector3.Normalize(forward);
    right = Quaternion.Euler(0, 90, 0) * forward;
}

private void Update()
{
    if (Input.GetKey(KeyCode.Mouse0))
    {
        var righMovement = right * speed * Time.deltaTime * (Input.GetAxis("Mouse X"));
        var upMovement = forward * speed * Time.deltaTime * (Input.GetAxis("Mouse Y"));

        if (righMovement != Vector3.zero && upMovement != Vector3.zero)
                target.forward = Vector3.Normalize(righMovement + upMovement);

            lastPosition += new Vector3
            {
                x = righMovement.x + upMovement.x,
                y = righMovement.y + upMovement.y,
                z = righMovement.z + upMovement.z
            };

            target.position = lastPosition;

            //target.position = Clamp(lastPosition);
        }
    }
}

```

At same time I want to clamp that object based on the screen size to avoid moving the target when it is off screen, so I made this:

```
private Vector3 Clamp(Vector3 position)
{
    var w2p = Camera.main.WorldToViewportPoint(position);

    w2p.x = Mathf.Clamp(w2p.x, .2f, .8f);
    w2p.y = Mathf.Clamp(w2p.y, .2f, .8f);

    return Camera.main.ViewportToWorldPoint(w2p)
}

```

But I'm getting some weird behaviours, the X axis clamp is fine, but Z is not working at all, and Y is not behaving correctly when moving. It's quite probable I'm doing this in the wrong way. How should it be?

# Answer
> 0 votes
https://docs.unity3d.com/Manual/FrustumSizeAtDistance.html

all you need is this link. in perspective we dont have axact bound but we have bounds in distance. you have to calculate camera distance from you object and calculate bound on that distance.

if its in 3d you can calculate using below:

```
 public static class CameraExtensions
 {
     public static Bounds OrthographicBounds(this Camera camera)
     {
         float screenAspect = (float)Screen.width / (float)Screen.height;
         float cameraHeight = camera.orthographicSize * 2;
         Bounds bounds = new Bounds(
             camera.transform.position,
             new Vector3(cameraHeight * screenAspect, cameraHeight, 0));
         return bounds;
     }
 }

```

you can follow this thread for more info:

https://answers.unity.com/questions/501893/calculating-2d-camera-bounds.html

# Answer
> 0 votes
For any point on screen, there's a whole line of points in your world that map to that point.

Your current code is choosing the one that maintains the same depth from the camera, which may or may not be what you want.

An alternative would be to try to maintain the same height (y) in the world. That code would look like this:

```
private Vector3 Clamp(Vector3 worldPosition)
{
    // Cache this to avoid repeated searches.
    var camera = Camera.main;

    var viewportPoint = camera.WorldToViewportPoint(worldPosition);

    viewportPoint.x = Mathf.Clamp(viewportPoint.x, .2f, .8f);
    viewportPoint.y = Mathf.Clamp(viewportPoint.y, .2f, .8f);

    var ray = camera.ViewportPointToRay(viewportPoint);

    // Compute the distance along the ray where it crosses our y plane.
    float d = (position.y - ray.origin.y)/ray.direction.y;

    // Return that intersection point.
    return ray.GetPoint(d);
}

```

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


title: Scroll UI Image

text:
# Question
Title: Scroll UI Image
Currently, I am scrolling a UI `RawImage` using the following:

```
[SerializeField] private RawImage _imageToScroll;
[SerializeField] private float _x, _y;
// Update is called once per frame
void Update()
{
    _imageToScroll.uvRect = new Rect(_imageToScroll.uvRect.position + new Vector2(_x, _y) * Time.deltaTime, _imageToScroll.uvRect.size);
}

```

However, I'd like to use a regular `Image`, rather than `RawImage`. The reason I'd like to switch to using a regular Image is because I need to tile an image to fill the dialogue box below:

From what I can tell, RawImage doesn't seem to allow for tiling the way Image does. Is there a similar and simple way to accomplish this scrolling effect with `Image`?

# Answer
> 1 votes
You can do this with RawImage just fine.

* In your Project folder, select the texture that you want to tile.

+ Set its Wrap Mode to Repeat.
* Then select your RawImage.

+ Set its UV Rect W and H parameters to the number of tile repeats you want, horizontally and vertically.

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


# Question
Title: How to change the alpha of a tilemap if the player is in it in Unity
I'm working on a 2D game and would like to have it so when I'm entering a building, the roof fades away. This is my current attempt, I'd just like to know how to set the alpha of a tilemap through c#.

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

public class RoofTransparency : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

    }

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

    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        Debug.Log("Inside building");

        tilemap.color = color(0, 255, 0);
    }

    void OnTriggerExit2D(Collider2D other)
    {
        Debug.Log("Outside building");
    }
}

```

# Answer
> 0 votes
This will work for what you need. If you wanted to have it on like the grass layer but make your roof layer transparent just do this to the code.

```
public class RoofTransparency : MonoBehaviour
{

     Tilemap m_Renderer;

     // Start is called before the first frame update
     void Start()
     {
         //Grabs the Tilemap Component
         m_Renderer = GetComponentInParent<Tilemap>();
     }

     private void OnTriggerEnter2D(Collider2D other)
     {
         Debug.Log("Player has entered the trigger");

         //Turns object invisible when the player enters its collider space
         if (other.gameObject.tag == "Player")
         {
             m_Renderer.color = new Color(1f, 1f, 1f, 0.0f);
         }
     }

     private void OnTriggerExit2D(Collider2D other)
     {
         Debug.Log("Player has exited the trigger");

         //Turns object visible when player enters its collider space
         if (other.gameObject.tag == "Player")
         {
             m_Renderer.color = new Color(1f, 1f, 1f, 1f);
         }
     }
}

```

---
Tags: unity, c#, collision-detection, tilemap, transparency
---


# Question
Title: UI Scaling issues only with QHD and 4k UHD
I have a card game, where I'd like to be able to zoom in on a card if it's right clicked. I coded to make sure that if the zoomed card would go over a screen boundary, instead we would anchor it such that the full card is displayed. I initially hardcoded everything for 1920x1080 resolution, then I wanted to get it to work for an arbitrary resolution. The logic seems to work for all resolutions except for `QHD` and `4k UHD`.

I feel like I have a fundamental misunderstanding of resolutions, or I'm missing something with either how `RectTransform` scaling works, or how the units for width/height correspond to resolutions, or how the interaction between `Canvas` and `CanvasScaler` work with resolutions. The math seems simple, but it's not working for these resolutions, so I'm obviously missing something.

For reference:

```
using UnityEngine;
using UnityEngine.EventSystems;

public class Zoomable : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    private GameObject _popOutCard;
    private bool _enabled;

    // Works for all resolutions except QHD and 4k UHD.
    // Calculations: Card Dimensions are 150 x 200.
    // So, if we're, for example, scaling by a factor of 2, the zoomed cards are 300 x 400.
    // We're using the (x,y) coordinates of the cursor.
    // So for 1920 x 1080, for example:
    // To display a zoomed card, its center with respect to x can never be less than 155 (300/2, with an offset of 5).
    // The same logic is applied to the other 3 boundaries.

    private const int _offset = 5;
    private const int _cardHeightHalfed = 100;
    private const int _cardWidthHalfed = 75;

    private float _topBoundary;
    private float _bottomBoundary;
    private float _leftBoundary;
    private float _rightBoundary;

    [SerializeField]
    private float _scaleFactor = 2.5f;

    private Transform _canvasTransform;

    void Awake()
    {
        // We're mixing ints and floats here, but it's fine.
        _canvasTransform = transform.root;
        _topBoundary = Screen.height - _scaleFactor * _cardHeightHalfed - _offset;
        _bottomBoundary =_scaleFactor * _cardHeightHalfed + _offset;
        _leftBoundary = _scaleFactor * _cardWidthHalfed + _offset;
        _rightBoundary = Screen.width - _scaleFactor * _cardWidthHalfed - _offset;
        var resolution = Screen.currentResolution;

        Debug.Log($"Resolution height: {resolution.height}, resolution width: {resolution.width}");
        Debug.Log($"Screen height: {Screen.height}, resolution width: {Screen.width}");
    }
    public void OnPointerDown(PointerEventData eventData)
    {
        if (eventData.button == PointerEventData.InputButton.Right)
        {
            ZoomPopOut();
        }
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        Debug.Log("OnPointerUp called");
        if (_enabled)
        {
            OnZoomPopOutExit();
        }
    }

    private void ZoomPopOut()
    {
        float xPosition = Input.mousePosition.x;
        float yPosition = Input.mousePosition.y;
        Debug.Log($"x position: {xPosition}, y position: {yPosition}");

        float popOutXPosition = xPosition;
        float popOutYPosition = yPosition;

        if (xPosition < _leftBoundary)
        {
            popOutXPosition = _leftBoundary;
        }

        if (xPosition > _rightBoundary)
        {
            popOutXPosition = _rightBoundary;
        }

        if (yPosition < _bottomBoundary)
        {
            popOutYPosition = _bottomBoundary;
        }

        if (yPosition > _topBoundary)
        {
            popOutYPosition = _topBoundary;
        }

        Debug.Log($"Pop out x position: {popOutXPosition}, pop out y position: {popOutYPosition}");

        _popOutCard = Instantiate(gameObject, new Vector2(popOutXPosition, popOutYPosition), Quaternion.identity);
        _popOutCard.transform.SetParent(_canvasTransform);
        _popOutCard.transform.SetAsLastSibling();

        RectTransform rect = _popOutCard.GetComponent<RectTransform>();
        rect.localScale = new Vector3(_scaleFactor, _scaleFactor, _scaleFactor);
        _enabled = true;
    }

    private void OnZoomPopOutExit()
    {
        Debug.Log("OnZoomPopOutExit() called");
        _enabled = false;
        Destroy(_popOutCard);
    }
}

```

# Answer
> 1 votes
Try something like this:

```
RectTransformUtility.ScreenPointToLocalPointInRectangle(
    (RectTransform)_canvasTransform,
    new Vector2(popOutXPosition, popOutYPosition),
    null, // If not using Screen Space - Overlay, provide a camera here.
    out var convertedPosition
);

// Set the parent first.
_popOutCard = Instantiate(gameObject, _canvasTransform);

// THEN set the position WITHIN that parent.
_popOutCard.transform.localPosition = convertedPosition;

// For some UI setups you may prefer to use anchoredPosition.

_popOutCard.transform.localScale = Vector3.one * _scaleFactor;
_enabled = true;

```

# Answer
> 1 votes
I didn't realize that I needed to map from screen space (mouse coordinates) to canvas space in my original code. After learning about `RectTransformUtility.ScreenPointToLocalPointInRectangle` and realizing that `Instantiate` always anchors to the center of the canvas, I also realized that I should modify the border calculations to account for the anchoring, and move the constraining borders code to after the screen space to canvas space mapping.

using UnityEngine;
using UnityEngine.EventSystems;

public class Zoomable : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    private GameObject _popOutCard;
    private bool _enabled;

    // Mouse Coordinates are given in screen space.
    // We then map those coordinates to canvas space, which is set to
    // 1920 x 1080.
    // Calculations: Card Dimensions are 150 x 200.
    // So, if we're, for example, scaling by a factor of 2, the zoomed cards are 300 x 400.
    // So for 1920 x 1080:
    // To display a zoomed card, its center with respect to x can never be less than 155 (300/2, with an offset of 5) away
    // from a left/right boundary.
    // The same logic is applied to the top/bottom boundaries.
    // Since the anchoring of the popOutCard with respect to the canvas is centered, i.e. (0,0) is the center of the canvas
    // we need to account for that when calculating the boundaries in Awake.

    private const int _offset = 5;
    private const int _cardHeightHalfed = 100;
    private const int _cardWidthHalfed = 75;
    private const int _canvasHeightHalfed = 540;
    private const int _canvasWidthHalfed = 960;

    private float _topBoundaryCanvas;
    private float _bottomBoundaryCanvas;
    private float _leftBoundaryCanvas;
    private float _rightBoundaryCanvas;

    [SerializeField]
    private float _scaleFactor = 2.5f;

    private Transform _canvasTransform;

    void Awake()
    {
        _canvasTransform = transform.root;

        // We're mixing ints and floats here, but it's fine.
        _topBoundaryCanvas = (_canvasHeightHalfed - _scaleFactor * _cardHeightHalfed - _offset);
        _bottomBoundaryCanvas = (_canvasHeightHalfed - _scaleFactor * _cardHeightHalfed - _offset)*-1;
        _leftBoundaryCanvas = (_canvasWidthHalfed - _scaleFactor * _cardWidthHalfed + _offset)*-1;
        _rightBoundaryCanvas = _canvasWidthHalfed - _scaleFactor * _cardWidthHalfed - _offset;
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        if (eventData.button == PointerEventData.InputButton.Right)
        {
            ZoomPopOut();
        }
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        Debug.Log("OnPointerUp called");
        if (_enabled)
        {
            OnZoomPopOutExit();
        }
    }

    private void ZoomPopOut()
    {
        float xPosition = Input.mousePosition.x;
        float yPosition = Input.mousePosition.y;
        Debug.Log($"x position: {xPosition}, y position: {yPosition}");

        Vector2 convertedPosition;
        RectTransformUtility.ScreenPointToLocalPointInRectangle((RectTransform)_canvasTransform,
                                                                new Vector2(xPosition, yPosition),
                                                                null,
                                                                out convertedPosition);

        Debug.Log($"Pop out x position: {convertedPosition.x}, pop out y position: {convertedPosition.y} in canvas space");

        if (convertedPosition.x < _leftBoundaryCanvas)
        {
            convertedPosition.x = _leftBoundaryCanvas;
        }

        if (convertedPosition.x > _rightBoundaryCanvas)
        {
            convertedPosition.x = _rightBoundaryCanvas;
        }

        if (convertedPosition.y < _bottomBoundaryCanvas)
        {
            convertedPosition.y = _bottomBoundaryCanvas;
        }

        if (convertedPosition.y > _topBoundaryCanvas)
        {
            convertedPosition.y = _topBoundaryCanvas;
        }

        Debug.Log($"Pop out x constrained: {convertedPosition.x}, pop out y constrained: {convertedPosition.y} in canvas space");

        _popOutCard = Instantiate(gameObject, _canvasTransform);
        _popOutCard.transform.localPosition = convertedPosition;
        _popOutCard.transform.localScale = Vector3.one * _scaleFactor;
        _enabled = true;
    }

    private void OnZoomPopOutExit()
    {
        Debug.Log("OnZoomPopOutExit() called");
        _enabled = false;
        Destroy(_popOutCard);
    }
}

```

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


# Question
Title: How can I make objects spawn at random positions on the terrain?
I want to spawn some objects like trees etc. on my terrain randomly.

I use the script below:

```
public GameObject Tree;

public GameObject Stone;

public GameObject MetalOre;

private float xMinimum, xMaximum, zMinimum, zMaximum;

public int Tele;

public Vector3 yPos;

private void Start()
{
    GameObject terrainObj = GameObject.Find("Terrain");
    Terrain terrain = terrainObj.GetComponent<Terrain>();

    xMinimum = -3f;
    zMinimum = -43f;
    xMaximum = xMinimum + 62f;
    zMaximum = zMinimum + 40f;

    float xRand = Random.Range(xMinimum, xMaximum);
    float zRand = Random.Range(zMinimum, zMaximum);

    Vector3 yPos = new Vector3(xRand, 0, zRand);

    yPos.y = terrain.SampleHeight(yPos) + terrain.GetPosition().y;

    for (int i = 0; i < Tele; i++)
    {
        GameObject TreeObj = Instantiate(Tree, yPos, Quaternion.identity);
        GameObject StoneObj = Instantiate(Stone, yPos, Quaternion.identity);
        GameObject MetalOreObj = Instantiate(MetalOre, yPos, Quaternion.identity);
    }
}

```

The problem is that all of these objects spawn at one place, like this:

I know why is that happening (that's because all of the game objects get the same position, I guess), but I don't know how to fix it.

# Answer
> 1 votes
First, refactor your random position-choosing code to a helper function:

```
// Packing X & Z together like this just means fewer arguments to type per call.
Vector3 GetRandomPointOnTerrain(Terrain terrain, Vector2 minXZ, Vector2 maxXZ)
{
    var point = new Vector3(Random.Range(minXZ.x, maxXZ.x),
                            0,
                            Random.Range(minXZ.y, maxXZ.y));

    point.y = terrain.SampleHeight(point) + terrain.GetPosition().y;

    return point;
}

```

Then call this function once for each object to spawn:

```
private void Start()
{
    // If you have just one terrain, searching by type is faster
    // and more reliable than searching by name plus a GetComponent.
    var terrain = FindObjectOfType<Terrain>();

    var minXZ = new Vector2(-3f, -43f);
    var maxXZ = minXZ + new Vector2(62f, 40f);

    for (int i = 0; i < Tele; i++)
    {
        var TreeObj = Instantiate(
            Tree,
            GetRandomPointOnTerrain(terrain, minXZ, maxXZ),
            Quaternion.identity);

        var StoneObj = Instantiate(
            Stone,
            GetRandomPointOnTerrain(terrain, minXZ, maxXZ),
            Quaternion.identity);

        var MetalOreObj = Instantiate(
            MetalOre,
            GetRandomPointOnTerrain(terrain, minXZ, maxXZ),
            Quaternion.identity);
    }
}

```

Note that because each of these points is chosen independently, there's a chance that the same or very nearby positions will be chosen for two objects, leading to penetration. Some existing Q&A goes into more detail about strategies to avoid that, so I won't cover it here.

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


# Question
Title: How do I contain two rigid bodies with a relative position, while ignoring rotation?
This question is physics engine agnostic (could be Box2D, Bullet, whatever).

I have two rigid bodies, each with a single fixture/shape. One is a sphere, and one is a box.

I'd like the box to rotate independently of the sphere, but I'd like the relative position of both to remain fixed. So for example, if the sphere rolls, the box would move with its position but not rotate. Likewise if the box hits something I'd like the sphere to also respond to the impact.

Is there a simple way of achieving this?

# Answer
> 0 votes
This would be done with a joint constraint.

In Bullet, if you want rotation in a single plane, it's the Hinge Constraint. For rotation in any direction, it's the Point to Point Constraint.

In PhysX, the single plane version is a Revolute Joint, while the any-rotation version is a Spherical Joint.

In Box2D, it's a Revolute Joint (since there's only one plane to consider in 2D, there's no distinguishing between a hinge and a ball-and-socket style joint here).

Engines using these libraries might rename these constraints for internal naming consistency. For instance, in Unity, even though it uses PhysX/Box2D under the hood, it renames them to HingeJoint and HingeJoint2D respectively.

---
Tags: physics, joints
---


# Question
Title: How to debug Unity/mono code on Linux/VsCode
I am new to Unity and I have been fighting with VSCode and debugging.

I am trying to attach a debugger to Unity to test some code that run in the editor without running the app ( kind of Unity extension debug )

Apparently there was an VsCode extension for this this but has been deprecated

Any idea how to make it work ?

# Answer
1. Install this extension: https://marketplace.visualstudio.com/items?itemName=ms-vscode.mono-debug
2. Create a **launch.json** file in `<your Unity project dir>/.vscode/launch.json` with this content

```
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Unity Editor",
            "type": "unity",
            "request": "launch"
        }
    ]
}
```
3. In Unity click in the bottom right the debug icon
4. In VsCode `Run -> Start Debugging`

Enjoy
> 0 votes

---
Tags: unity, debugging, linux, visual-studio-code
---


# Question
Title: Unity 2D animated tiles library: IsSelected variable not working or not present within RuleTileEditor.cs
I have just tried downloading a library which will allow me to add animated tiles to unity. I have been following this tutorial:http://shadowpeakstudios.com/2018/10/22/unity-tutorial-animated-tiles/

It told me to download this library in order to work the animated tiles: https://github.com/Unity-Technologies/2d-extras

After this the tutorial told me to unzip the library and place it into my assets folder. It loaded into my assets folder and then got the following error:

```
Assets\2d-extras-master\2d-extras-master\Editor\Tiles\RuleTile\RuleTileEditor.cs(277,26): error
CS1061: 'ReorderableList' does not contain a definition for 'IsSelected' and no accessible extension
method 'IsSelected' accepting a first argument of type 'ReorderableList' could be found (are you
missing a using directive or an assembly reference?)

```

Does anyone perhaps know why this error is occuring.

# Answer
1. Open Unity
2. On top of Unity window, you will see your version number. Will look something like, Unity 2020.3.8f1
3. Go to: https://github.com/Unity-Technologies/2d-extras
4. On Unity 2d Extras Github, check to see if your Unity version above matches the current branch. If you're unsure, do Control + F and search the word Branches to find the branches link on Github, click this. This will take you to all the branches of 2d extras.
5. Select the branch that matches your Unity Version. Ex: If my version is 2020.3, I would select the 2020.3 branch. Click the blue link to your branch.
6. Click the green code button on top right of the branch page, download zip.
7. Extract the zip folder once downloaded.
8. Open your Unity project, go to Window -\> Package Manager.
9. Click the + in package manager, select Add package from disk.
10. Locate your unzipped folder for 2d extras and select the package.json inside it, click open.
11. The package will load into your project... *fingers crossed* error-free.
12. Rejoice.

---

Note: If this helped, give this an upvote. If this didn't work, you most likely downloaded the incorrect version from Github. Also, make sure you deleted the prior 2d extras package from your Unity project that was giving you errors if you had one as this could cause file conflictions.
> 4 votes

# Answer
You are most likely on an Unity version where their `ReorderableList` no longer provides the `IsSelected` method. Looking at the GitHub repository it seems that there are different branches for different versions of Unity. For an example the branch "2020.3" no longer seems to contain a reference to `IsSelected`, so you need to change to an appropriate branch of the repository that works with your version of Unity.
> 0 votes

# Answer
I've replaced this \> if (list.index != 0)

with this \> if (list.index != 0)

and it worked for my project.
> -1 votes

---
Tags: unity, c#, 2d, tiles
---


title: Facilitator UI on desktop screen for VR

text:
# Question
Title: Facilitator UI on desktop screen for VR
Hey and thanks in advance for any help/pointers

The solution is probably straight forward but i am still a little inexperienced (while creating quite a few different VR unity projects mostly study related, i never really build anything so the editor allowed for some shortcuts. see below).

I am currently developing for Windows mixed reality with unity. I am struggling to figure out how to make a (possibly secondary) application window run on the desktop that can be used during facilitated VR-experiences to change settings and generally provide facilitator input to the application while the participant would just perceive the VR world.

*Edit: I have a similar project that is developed with Steam\_vr library / Open\_VR that works exactly as expected and portrayed by the unity editor; i.e. the desktop will shows the ingame footage + the screenspace overlay UI (which is interactable).Nevertheless quite a few features where implemented with the MixedRealityToolkit so I'd prefer to stick with that. And was wondering if there is a way to achieve the same/similar behavior with it.*

Now with MRTK everything works straight forward when running from unity editor just making a canvas screenspace will prevent it from showing in vr while it can still be interacted with. the problem is that the facilitators themselves are a third party and having a build would just make their handling of the solution much easier. Not to mention performance gains from building and cleaning the project(?).

it will probably come down to creating a secondary window that runs on the desktop since my understanding is that uwp with MRTK just runs in the wmr portal rather than a separate app; and that the WMR portal simply copies the Headset render to the desktop. But i am completely blank on how to achieve this and was hoping that someone might have struggled with this before. But i couldn't really find anything. I'd prefer not to have to resolve to Networking, and will attempt to convert to Steam\_VR /OpenVR in the meantime..

# Answer
Sorry to bring this back up but I just had the exact same issue and after hours of digging and testing different things I realized it had to do with a setting on the Event System GO. In short, the Pointer Behavior should be set to "All Pointer As Is" if you're planning on listening to Mice input and VR controllers at the same time. Here is an official link to the options descriptions from the Unity documentation.
> 0 votes

---
Tags: unity, gui, virtual-reality, steam-vr, universal-windows
---


title: Pack 4 textures into one channel

text:
# Question
Title: Pack 4 textures into one channel
Can I pack 4 grayscale textures into one channel by converting the textures into uints and packing them?

```
uint b1 = (t1.r * 255 & mask1) << 0;
uint b2 = (t2.r * 255 & mask2) << 8;
uint b3 = (t3.r * 255 & mask3) << 16;
uint b4 = (t4.r * 255 & mask4) << 24;
t.r = b1 | b2 | b3 | b4;

```

"mask#" is a uint with 1s for #th byte and 0s for all other bytes. "t#" is a grayscale texture. "t" is the texture we are packing into.

My main concern is that t.r is a float, and I'm not allowed to access the bits.

# Answer
> 0 votes
maybe this work? I'm not test it.

```
    byte mask1 = 0;//0~4
    byte mask2 = 0;//0~4
    byte mask3 = 0;//0~4
    byte mask4 = 0;//0~4

    byte maskCombine = (byte)((mask1) & (mask2 << 2) & (mask3 << 4) & (mask4 << 6));
    Color32[] colors = new Color32[4];
    colors[0].r = maskCombine;
    Texture2D t = null;
    t.SetPixels32(colors,0);

```

shader:

```
half alpha = mask.r;
half mask1 = step(0.25 , alpha-0.75);// here get 0 or 1
half mask2 = step(0.25 , alpha-0.5);
half mask3 = step(0.25 , alpha-0.25);
half mask4 = step(0.25 , alpha);

```

# Answer
> 0 votes
Simply cast the floats to `uint` after multiply. `float` is only good to 21 bits, so use an `uint32` type as the output:

```
uint b1 = (uint(t1.r * 255) & oxFF);
uint b2 = (uint(t2.r * 255) & 0xFF) << 8;
uint b3 = (uint(t3.r * 255) & 0xFF) << 16;
uint b4 = (uint(t4.r * 255) & oxFF) << 24;
uint packed = b1 | b2 | b3 | b4;
Tex.rgba = packed;

```

If `float`s were used there would be round trip loss in b1 and the lsb bit of b2, by `Ceil(log2(ReverseBitOrder(b1)) + Ceil(log2(b4)))` bits.

Make sure you use an uncompressed format without mip maps for perfect channel recovery.

So make `Tex` an integer format: convert the textures to use GL\_RGBA32 instead of GL\_RGBA32F for OpenGL or DXGI\_FORMAT\_R8G8B8A8\_UINT instead of DXGI\_FORMAT\_R8G8B8A8\_UNORM for Windows depending on platform.

---
Tags: unity, shaders, textures, hlsl
---


# Question
Title: How to export ONLY animation clips from Blender to Unity to organise them in different files
When you start with the Unity 3rd person template, you see the animations (actions) being neatly organized as separate files:

I know how to export a model with the mesh, materials, and actions:  But how do I do it like in that Unity template (only actions)?

I'd like to be able to work independently on materials, actions, and meshes.

I tried to export only the armature and all actions (all one), but the animation is not playing in preview, nor in play mode. Even weirder, it got stuck on some pose which is not even a part of exported animation.

What kind of worked for me, was creating a simple cube, parenting it to the armature, and exporting the armature with that cube.

But this is a hack, which doesn't feel right.

# Answer
> 2 votes
Had this same exact problem yesterday. Turns out all you need to do to fix it is toggle the "Preserve hierarchy" import option on the animations asset in Unity.

Apparently, this behaviour is because when you import an asset that has a single object (the armature, in this case), unity just makes the armature the root of the hierarchy. When you have multiple objects (the armature and a mesh), neither of them can be the root, so a separate root is created that both objects are parented to. Net result is the armature+mesh asset has a different hierarchy than the armature asset, so the animations are no longer compatible.

"Preserve hierarchy" forces the importer to create a root object even if there is only one thing in the asset, so it works again.

---
Tags: unity, animation, blender, export, asset-workflow
---


title: Remove transparency from second camera

text:
# Question
Title: Remove transparency from second camera
I have a scene with two cameras. The goal is to

* display the content of one (little) camera ontop of the content of the other camera (fills the entire screen)

Current problem:

* the content of the little camera has some transparency

I'm not sure how to get rid off the tranparency (I'm somewhat new to Unity). Here is some picture:

**Context**

* Unity 2021.3.3f1

# Answer
> 0 votes
Turns out

* the "camera" component has a field "Target Texture".
* Looking for the GameObject with the corresponding texture
* I found that it had a "Raw Image" attached to it with some transparency.
* Removing that transparency solved my problem

---
Tags: unity, camera
---


# Question
Title: Adding custom made class through name and not component
I'm trying to make an editor window to ease my workflow of creating enemies. Most parts work fine apart from creating a class and adding it.

```
    void SaveAndCreate()
    {
       string guid = AssetDatabase.CreateFolder("Assets/Scripts/Enemies/EnemyTypes", enemyData.EnemyName);
        string newFolderPath = AssetDatabase.GUIDToAssetPath(guid);
        TextAsset templateTextFile = AssetDatabase.LoadAssetAtPath("Assets/CharacterTemplate.txt", typeof(TextAsset)) as TextAsset;

        string contents = "";
        if (templateTextFile != null)
        {
            contents = templateTextFile.text;
            contents = contents.Replace("CUSTOMCLASS_", enemyData.EnemyName.Replace(" ", ""));
        }
        using (StreamWriter sw = new StreamWriter(string.Format(newFolderPath + "/{0}.cs", new object[] { enemyData.EnemyName.Replace(" ", "") })))
        {
            sw.Write(contents);
        }

        objToCreate = new GameObject(enemyData.EnemyName);
        objToCreate.name = enemyData.EnemyName;
needToAttach = true
    }

```

Through this im creating the folders and class that i need which uses inheritance from a Monobehaviour. The objects name is the class, so if im making a "Dog" enemy the class that gets generated is "Dog.cs" which inherits from "Animals.cs". Now my issue lies with actually adding that class.

```
        //_go.AddComponent(Type.GetType(enemyData.EnemyName + ".cs"));//
        String ScriptName = objToCreate.name;
        Type MyScriptType = Type.GetType(ScriptName + "UnityEngine ,Assembly-CSharp");

        objToCreate.AddComponent(MyScriptType);
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
needToAttach = false;

```

As you can see i have tried a few things but since adding components through string is obsolete i cannot! I get this error "AddComponent asking for invalid type". So my question is is there any way for this to happen? I generate the dog.cs through script, create the prefab and assign to it through its name. This way i want to create enemies easy and adding all the necessary components automatically and not having to create each class on my own and assign in the editor. Thank you!

I should note that if i create another GUI button that assigns it , it works. But i do want it to work with the same button. In current setup the function to add the new component is in Update with this code. needToAttach is a bool to check when it needs and i updated the above to include it!

```
        if (EditorApplication.isCompiling) { return; }
        if (needToAttach)
        {
           // AddClass();
        }

```

# Answer
> 0 votes
Because the newly generated script is not recompiled, it is not added to the assembly.

Your expected behavior is:

1. Generate some new `.cs` script while in editor script running.
2. Recompile
3. Add the compiled monobehavior class to the specified gameobject.

This cannot be done in the same operation, even using coroutines to wait for the compilation to finish is useless. Operating on another GUI button works because the entire assembly has been recompiled.

You can use UnityEditor.Callbacks.DidReloadScripts to be notified that the script recompilation is complete, and to do so at this time. Also, you don't want to trigger this function every time you recompile, so we need to make sure that `adding component after compilation` is triggered by `generating scripts`.

However, due to recompilation, all the context have been destroyed, and things like global variables cannot be used to save marks. We need a persistent storage method that does not rely on memory. e.g. EditorPrefs.

```
void SaveAndCreate()
{
    //Create scripts...
    EditorPrefs.SetBool("CreateMark", true);
}

[UnityEditor.Callbacks.DidReloadScripts]
static void OnScriptsReloaded ()
{
    var mark = EditorPrefs.GetBool("CreateMark");//default value is false.
    if (mark){
        //Add components...
        EditorPrefs.SetBool("CreateMark", false);
    }
}

```

---
Tags: unity
---


# Question
Title: Implementing Runescape-style stat-based conditional buffs within an ECS
## Prologue

I'm quite new to data oriented programming and my goal is to implement a Runescape-style stats & damage mechanic in a data oriented styme.

This is quite a complex topic (Runescape-Mechanics) and I haven't found any ECS-related sources on that topic yet.

In the following example, we see a bunch of items which modify the wearer's stats based on a few conditions.

This happens in two different variants, either for the damage calculation only, or as a buff.

* Brine sabre and Brackish blade increase damage against crabs.

or
* Silverlight and Darklight increase ability damage by a scaling of 25-124% against most demons. The exact damage bonus is based on your base Attack and Strength, and the monster's base Defence.

## The problem

Such RPG systems are very complex. There different damage types, different resistances, and other stats.

Having a strong OOP background and no real experience in DOP, I can't find a suitable architecture to fill those needs.

In my current approach, every stat is a component. Items and Buffs are structs. A item "buffs" its owner and the buff modifies his stats. This works so far, but I have no idea how I could realise the damage calculation, while still keeping it as flexible as it is in Runescape.

This little example would just be able to buff the stats... not deal, receive or modify the damage itself.

```
// The stats

public struct Health{
  float max;
  float value;
}

public struct MeleeDamage{
  float base;
  float value;
}

public struct MeleeResistence{
  float base;
  float value;
}

// Item & Buffs
public struct Item{
  string name;
  int amount;
  bool equippable;
  List<Buff> buffs;
}

public struct Buff{
  string name;
  float duration;
  Condition applicable;
  ToBuff stat;
  float value;
}

```

It's also important that an entity can also deal damage to multiple other entities in one frame.

How would you implement such a complex mechanic? Any examples are appreciated!

# Answer
Here's one way to approach it.

First throw all your base stats into one component as follows:

```
public struct BaseStats {
    float maxHp = 100;
    float meleeDmg = 40;
    float meleeResistance = 20;
    ...
}

```

This `BaseStat` component is complimented by a `StatModifier` component with multiplier and offset modifiers for each stat:

```
public struct StatModifier {
    float maxHPMult = 1.0;
    float maxHPOffset = 0.0;

    float meleeDmgMult = 1.0;
    float meleeDmgOffset = 0.0;

    float meleeResistanceMult = 1.0;
    float meleeResistanceOffset = 0.0;

    ...
}

```

Your player entity will have both of these components attached and each stat is evaluated in a System using the following equation:

```
stat = (base * multiplier) + offset;

```

All equip-able items will also have a `StatModifer`, and when that item is equipped the on the player, its stat multipliers and offsets are added to the player's `StatModifier`.

---

So say you have a ring item that:

* adds +50 health
* increases melee damage by 10%
* reduces melee resistance by 5%

Its `StatModifier` component would be implemented as follows:

```
public struct StatModifier {
    float maxHPMult = 0.0;
    float maxHPOffset = 50.0;

    float meleeDmgMult = 0.1;
    float meleeDmgOffset = 0.0;

    float meleeResistanceMult = -0.05;
    float meleeResistanceOffset = 0.0;

    ...
}

```

With the ring equipped the player entity's `StatModifier` component is updated with the following values:

```
  playerStatModifier.maxHPMult == 1.0 // unchanged
  playerStatModifier.maxHpOffset == 50 // 0.0 + 50.0

  playerStatModifier.meleeDmgMult = 1.1 // (1.0 + 0.1) up 10%
  playerStatModifier.meleeDmgOffset = 0.0 // unchanged

  playerStatModifier.meleeResistanceMult = 0.95 // (1.0 - 0.05) down 5%
  playerStatModifier.meleeResistanceOffset = 0.0 // unchanged

```

The cool thing about this setup is that the player's `StatModifier` component acts as an accumulator, allowing you to easily stack status effects as items are removed and added.
> 2 votes

# Answer
My main systems aren't really ECS, but the stat system I came up with is fairly self-contained and consists of just a few components.

The idea behind my system is to have stats stack in all kinds of ways, additive, multiplicative, and a mix of both. Specifically, here's one scenario that I wanted to enable.

A character has its "own" 100 HP (for example), wears an item that gives it an additional 10 HP, and then uses an ability giving it a +20% HP boost. This will then result in the character having (100 + 10) + 20% = 132 HP.

If now this character receives another effect that gives it an additional 50 HP (not 50%), it should have 182 HP.

If this character instead wears an additional item that gives it a 20% HP boost (not an ability effect), then its HP should be

> 100 + 10 + 20 (20% of 100) = 130, and then 20% from the ability on top of that (156).

I accomplish this using a sort of a hierarchy, an order of stats to be applied.

I also refer to stats by string values - which has all kinds of useful effects, like being able to add any arbitrary stats without messing with the code, or being able to refer to these stats easily in data, without coding complex object factories or switch statements.

The first piece is the `StatBonus` object. It contains the name of the stat it affects, the flat amount (+10 HP) and the multiplier (+10% HP), as well as which *stat order* it belongs to.

In my project, I have defined a few such obvious orders:

`Template`, these are the absolute base stats for a character of a specific kind (class, species, whatever). Those aren't meant to be altered but there's nothing in the code that says that they cannot be, of course.

`Character`, these are stats that this specific character has in addition to the base stats, but are still an innate part of the character. This includes stat upgrades from levelling up, permanent effects from completing quests, player-assigned stats (some games, instead or in addition to increasing your stats on level-up, give you a small amount of "points" to assign to stats as you please).

`Equip`, these are bonuses obtained from equipment worn by the character. Those are directly referring to the corresponding `StatBonus` objects attached to the equipment `Item`s, which makes stat recalculation on equipping/unequipping items trivial.

`Socket`, those could be a part of the previous order, but I find it easier to calculate item modifications separately - since under the hood these modifications carry their own `StatBonus` objects and are intended to be swappable, so a modification that gets removed from an equipment piece turns back into an `InventoryItem` and takes its associated `StatBonus`es along.

`Effect`, any stat modifications done by an ability effect. This means that an effect that increases a stat will then synergise with equipment and any other boosts above it.

The last item, `Count`, is added to simplify the iteration process. I can freely add other stat orders before it and they will be automatically included in the process.

```
public class StatBonus : ICloneable
{
    public float FlatValue;
    public float Multiplier;
    public string Type;
    public string Description;
    public StatOrder Order;
    public enum StatOrder
    {
        Template,Character,Equip,Socket,Effect,Count
    }

    public object Clone()
    {
        return this.MemberwiseClone();
    }
}

```

Note how this has no references to anything else in my codebase, this is 100% drop-in ready for any project. The actual class is very barebones, I have added a `Clone` method that is handy sometimes, for example, when creating things (items, characters etc), as well as a `Description` \- that's mostly there for convenience and is not necessary. The rest should be self explanatory, there is the flat value, the percentage value and a string to refer to the stat affected.

If tomorrow I decide to add a new stat, I don't really need to do anything - I can add it to anything and it will just work, and checking for a non-existing stat will just default to zero.

To receive the final value of a specific stat, I then only need to find all `StatBonuses` that apply to that stat, and calculate each order and apply in that order.

Here's a pair of functions I use. Again, there are no references specific to anything in my code (except for the `StatBonus` class from above, of course). All this needs is a `List<StatBonus>` to iterate over.

```
public float CalculateStage(float input,List<StatBonus> Bonuses,StatBonus.StatOrder Stage)
    {
        float result = 0;

        List<StatBonus> stage = Bonuses.FindAll(s => s.Order == Stage).ToList();
        float flats = stage.Sum(s => s.FlatValue);
        float multis = stage.Sum(s => s.Multiplier);
        result = (input + flats) * (1 + multis);
        return result;
    }

public float CalculateStat(string statname)
    {
        float result = 0;
        List<StatBonus> stats = StatBonuses.FindAll(s => s.Type == statname).ToList();
        if (stats.Count < 1)
            return 0;
        for(int i=0;i<(int)StatBonus.StatOrder.Count;i++)
        {
            result=CalculateStage(result,stats,(StatBonus.StatOrder)i);
        }

```

Here, the `CalculateStat` function iterates over all stat orders (here called "stages" and calls the `CalculateStage` function on each.

The `CalculateStage` function simply finds all `StatBonus`es matching the correct stat and the order and spits out the result. This function takes the `input` param, this is used as the result of the previous stages calculated. I also made this function take the `List<StatBonus>` as a parameter in case I need it elsewhere, and should probably do that to the `CalculateStat` function as well, as right now it is referring to a `StatBonuses` member (which is a `List<StatBonus>`, of course) of the class it is residing in. Moving that to a parameter as well will make this fully portable and just called from the main class as needed.

Returning to the very beginning, the example of a character with

> 100 HP, an item adding 10 HP and another adding 20% HP, and an effect granting further 20%

will be calculated in this order:

`Template` receives 0 as a starting value and returns 100.

`Character` returns 100 as there's nothing to add (in this example).

`Equip` receives 100 and returns 130 (10 HP flat and 20% of 100 of `input`)

`Effect` receives 130 and returns the final value of 156, having applied a 20% increase to the previous value of 130.
> 0 votes

---
Tags: unity, c#, entity-component-system, data-oriented, effect-modifier
---


# Question
Title: Make Niagara System effect visible only on specific Render Target
I’m new to UE and don’t really know how to approach my problem, perhaps that’s why I couldn’t google a solution for it. So here’s what I want to achieve:

I need a Niagara System effect to be only visible on the video camera. In other words, players cannot see the effect by looking at it directly, but if they use a video camera (in-game object) then the effect is visible on the camera display.

The video camera is implemented with a Material created from a Render Target put on the camera’s mesh. The camera can be picked up by the player and carried around, so the player can see the environment through it. I can think of two ways to solve my issue: either make NS effect invisible for eyes but somehow detectable by the camera or add the effect directly on the Render Target so I don’t have to deal with the effect’s invisibility. None of these ideas brings me anywhere.

I imagine I’m not the first to implement this, so there must be rather a straightforward solution. If somebody could describe how this can be done at least on a high level so I can figure out the details, it would be highly appreciated. If the trick is impossible with Niagara System, doing it with particles or even static meshes would be an option for me.

# Answer
I used a `sceneCapture2D` to capture the effect, and then set the value of `bVisibleInSceneCaptureOnly` to TRUE for my Niagara System:
> 0 votes

---
Tags: unreal, unreal-5, rendertargets, visibility-determination, multiple-render-targets
---


# Question
Title: Why is my negamax algorithm returning negative infinity scores?
I'm currently in the process of writing my own chess engine in java and am having a little trouble with negamax. I've opted for negamax since its easier on the eyes and reduces the number of lines of code. My specific problem is that after making a move (me) the negamax algorithm returns scores of -Infinity and so the moves the AI is making seems illogical.

The problem only happens when I return beta if score\>=beta instead of returning score. Here is my function:

```
private int Search(int side, int depth, int alpha, int beta, long bitBoard, long[][][] allPieces, HashMap<Integer, Pair> pieceInfoTable,boolean allowNull){
    int turn;
    if (side == 1) {
        turn = 0;
    } else {
        turn = 1;
    }
    long hash = zobrist.getZobristHash(allPieces,pieceInfoTable, turn);

    if (zobristMap.containsKey(hash)) {
        int storedDepth = zobristMap.get(hash).getDepth();
        int score = zobristMap.get(hash).getScore();
        NodeType nodeType = zobristMap.get(hash).getNodeType();
        if (storedDepth >= depth) {
            if(nodeType == NodeType.PV){
                return score;
            }
            if(nodeType == NodeType.CUT_OFF_NODE){
                alpha = Math.max(alpha,score);
            }else if(nodeType == NodeType.ALL_NODE){
                beta = Math.min(beta,score);
            }
            if(score >= beta){
                return score;
            }
        }
    }
    MoveTable moveTable = new MoveTable();
    MoveGenerator.updateMoveMoves(bitBoard, moveTable, turn, allPieces);
    if (depth <= 0) {
        int score;
        int quiescenceDepth = 1;
        if(moveTable.pieceCaptureMoves.size() > 0){
            score = quiescenceSearch(side, alpha, beta, quiescenceDepth, bitBoard, allPieces, turn, pieceInfoTable);
        }
        else {
            score = Rating.rate(allPieces, bitBoard,pieceInfoTable);
        }

        NodeType nodeType = getNodeType(score, beta, alpha);
        zobristMap.put(hash,new TranspositionTableEntry(score, depth,nodeType));

        return score;
    }

    int terminal = terminalCheck(turn, side, bitBoard, allPieces,pieceInfoTable,moveTable);

    if(terminal != 0){
        NodeType nodeType = getNodeType(terminal, beta, alpha);
        zobristMap.put(hash,new TranspositionTableEntry(terminal, depth,nodeType));
        return terminal;
    }

    int value;
    int R=2;
    int x = Integer.MIN_VALUE;

    if(depth-R-1 >= 0&&allowNull&&!inCheck(turn,bitBoard,allPieces)){
        x = -Search(-side, depth - 1 - R, -beta,-beta+1, bitBoard, allPieces,pieceInfoTable,false);
        if(x >= beta){
            return beta;
        }
    }

    int bestSoFar = Integer.MIN_VALUE;
    moveOrdering(bitBoard, allPieces,moveTable, turn,pieceInfoTable);
    for(Move move : moveTable.pieceMoves){

        int pieceTile = move.getPieceTile();

        int targetTile = move.getTargetTile();
        if (BoardAnalyser.checkIfValidMove(pieceTile, targetTile, bitBoard, allPieces, turn,pieceInfoTable)) {

            int capFlag = Utils.getCaptureFlag(bitBoard, targetTile);

            Pair[] z = {null};
            bitBoard = Utils.makeMove_test(pieceTile, targetTile, bitBoard, z, turn, allPieces,pieceInfoTable);

            value = -Search(-side, depth - 1, -beta, -alpha, bitBoard, allPieces,pieceInfoTable,true);
            bitBoard = Utils.unmakeMove_test(pieceTile, targetTile, bitBoard, capFlag, z, turn, allPieces,pieceInfoTable);

            if(value > bestSoFar){
                bestSoFar = value;
            }
            if(bestSoFar >= beta){
                history[pieceTile][targetTile][turn] += depth*depth;
                zobristMap.put(hash,new TranspositionTableEntry(bestSoFar, depth,NodeType.CUT_OFF_NODE));
                return beta;
            }
            if(bestSoFar > alpha){
                alpha = value;
            }
        }
    }
    NodeType nodeType = getNodeType(bestSoFar, beta, alpha);
    zobristMap.put(hash,new TranspositionTableEntry(bestSoFar, depth,nodeType));
    return bestSoFar;
}

```

I'd appreciate any help/tips that I can get on this issue. If you require more information (code/explanation) then I'd be happy to help you help me :)

Thank you!

# Answer
> 1 votes
I'm not sure if this is what's wrong, but beware that:
`(-Integer.MIN_VALUE) == Integer.MIN_VALUE`

Because of that I'd suggest using a different integer to represent negative infinity (e.g. -1000000000).

See the Stack Overflow post why does the negative of integer min value give the same value for more information.

# Answer
> 0 votes
I cant recall exactly what I did. But the biggest change I made was with the evaluation function. I wasn't returning a score respective to the game perspective.

Initially I just returned (sumWhite - sumBlack) but replaced that with:

```
/*currentScore -> return val -> enemside perspective
 * score >0 white winning
 * if turn = 1 return score (bad for black) x -> x -> -x
 * if turn = -1 return -score (good for white) x ->-x -> x
 *
 * score < 0 black winning
 * if turn = 1 return score (good for black) -x -> -x -> x
 * if turn = -1 return -score (bad for white) -x-> x -> -x
 */
int score = sumWhite-sumBlack;
if(score != 0){
    if(turn == 1){

        return score;
    }
    if(turn == -1){

        return -score;
    }
}

```

---
Tags: java, algorithm, chess
---


# Question
Title: Character sinks into ground when switching animations
I originally posted this question on the unity forums, but no one answered my question.
Here it is:

Hello, I have been game developing since May and today I finally figured out how animations work in unity! But as with everything new in developing, I have problems. Let me just be straight with you. I have absolutely no idea what just happened. I have a gif you what happens. Why does the character sink like that? Here is my gif and animation image

I don't have any scripts or parameters for testing purposes. I just let it switch automatically. Here are my options for the transition:

# Answer
> 2 votes
Just change rig of the animation to humanoid from generic

---
Tags: unity, animation, character
---


title: Problems with rotating Child Objects

text:
# Question
Title: Problems with rotating Child Objects
I'm writing a Transform script for a Monogame project and I'm trying for a few days now to fix the Rotate method of this script, but without success.

Currently, the Parent transform only rotates around itself and also its Children does not translate around the specified Point (the Parent), only around themselves and with a lot of imprecision. When tested in other scenarios, the RotatePoint method is working correctly, but not when used in the Rotate method written below.

```
public class Tranform
{
    public Vector2 Position
    {
        get { return new Vector2 (x, y); }
        set { return x = value.X; y = value.Y; }
    }

    public float Rotation
    {
        get { return rotation;  }
        set { rotation = value; }
    }

    public void Rotate(float degrees)
    {
        this.rotation += degrees;

        if (rotation >= 360) rotation = 0;
        if (rotation <= -360) rotation = 0;

        foreach (var child in this.Children)
        {
            child.Position = RotatePoint(child.Position, this.Position, degrees);
            child.Rotate(degrees);
        }
    }

    public override void Update(GameTime time)
    {
        if (Keyboard.GetState().IsKeyDown(Keys.A))
        {
            Translate(-1, 0);
            Rotate(-1 * (float)time.ElapsedGameTime.TotalMilliseconds);
        }

        if (Keyboard.GetState().IsKeyDown(Keys.D))
        {
            Translate(1, 0);
            Rotate(1 * (float)time.ElapsedGameTime.TotalMilliseconds);
        }
    }

    public override void Render(SpriteBatch sprite_batch)
    {
        sprite_batch.Draw(pixel, this.Position, this.Boundaries, Color.White, MathHelper.ToRadians (this.Rotation), this.Origin, 1, SpriteEffects.None, 0);
    }

    public Vector2 RotatePoint(Vector2 point, Vector2 origin, float degrees)
    {
        float radians = MathHelper.ToRadians(degrees);

        Vector2 rotation_origin = new Vector2(point.X - origin.X, point.Y - origin.Y);

        double radius = Math.Sqrt(rotation_origin.X * rotation_origin.X + rotation_origin.Y * rotation_origin.Y);

        float x = (float)((radius * Math.Cos(radians)) + origin.X);
        float y = (float)((radius * Math.Sin(radians)) + origin.Y);

        return new Vector2(x, y);
    }
}

```

I'm creating the objects like this:

```
var parent = new Tranform();

parent.Position = new Vector2(0, 0);
parent.Scale = new Vector2(100, 100);
parent.Origin = new Vector2(50, 50);

child.SetParent(parent);

```

# Answer
In this version of the question, you are doubling the positional rotation when drawing. The origin of rotation in the `Draw()` call needs to be the origin of the local rotation of the sprite, normally the center of the sprite texture (pixel).

I would move the `Translate();` calls to their own keyboard keys. Rotations and translations should be kept separate on inputs, unless you want nautilus shell like movements. If the child and parent objects are of the same type, all objects will move uniformly.

The position of the rotation is already adjusted for the parent rotation offset.

Imagine a Ferris Wheel. The origin of the wheel is in the center. Each of the cabins is translated by the radius and angle from the rotation of the origin, but each cabin has its own local rotation, loosely fixed to world up by gravity.

`Boundaries` is the source rectangle within the `pixel` texture in texture space, not the boundaries of the object in world space. This parameter allows for the use of texture atlases(sprite sheets).

You still cannot rotate rectangles, directly. The Draw handles rotations, but it is not usually helpful for collisions.

```

// int >> 1 is a much faster version of int / 2 ,it only works with integers.

// DrawOrigin = new Vector2(pixel.Width >> 1, pixel.Heigth >> 1);
DrawOrigin = new Vector2(Boundaries.Width >> 1, Boundaries.Heigth >> 1);

// Remove the Boundaries, if not needed.
sprite_batch.Draw(pixel, Position - DrawOrigin, Boundaries, Color.White, MathHelper.ToRadians(Rotation), DrawOrigin, 1, SpriteEffects.None, 0);

```

Also, due the inverted nature of the Y axis the Sin needs to be negated for proper positive counter clockwise rotation angles:

```
// Added a minus before the Sin call, to correct the "Y up is negative"
 float y = (float)((radius * -Math.Sin(radians)) + origin.Y);

```
> 0 votes

---
Tags: c#, 2d, mathematics, monogame, transformation
---


# Question
Title: Generating 'Specially' shaped rooms for a Dungeon
I've made a fairly simple dungeon generator but now I want to expand on it so that I can procedurally generate a dungeon with irregular shaped rooms. I don't just want any old crazy shapes popping up though, I want to be able to have room types that follow a certain pattern but ultimately have random sizes. I just don't have a clue how to generate rooms that aren't just square.

I have an idea of how to merge squares together to make rooms comprised of other rooms, but I'm more interested in how to get hexagon and octagon shaped rooms, or doughnut-like rooms. My code for generating square rooms is:

```
    public static char[,] GetSquareRoom(int width, int height)
    {
        char[,] roomLayout_Square;

        roomLayout_Square = new char[width, height];

        for (int x = 0; x < roomLayout_Square.GetLength(0); x++)
            for (int y = 0; y < roomLayout_Square.GetLength(1); y++)
                if (x == 0 || y == 0 || x == width - 1 || y == height - 1)
                    roomLayout_Square[x, y] = '#';
                else
                    roomLayout_Square[x, y] = '.';

        return roomLayout_Square;
    }

```

**I would like to create more functions like this that will accept a few variables so I can create specific variations of these room-types, so I can input specific number and randomly generated values alike.**

:)

# Answer
> 4 votes
You can create a room that is in the shape of a regular convex polygon with arbitrary sides, size and rotation.
Steps:

1. Draw walls by picking pairs of points around a circle and linearly interpolating between them. The number of pairs should equal the number of sides of the shape. You will need to use trig for this.
2. Create a floor by filling the shape using some sort of fill algorithm.

You can then create a doughnut shaped room by subtracting a smaller generated room from the center of a larger generated room. You should keep the walls of the smaller generated room though.

Since I found this interesting I went ahead and tried implementing it myself. **I would recommend not looking at my code until you have tried to write it yourself though.**

```
public static char[,] RegConvexPolyRoom(int sides, double radius, double rotation)
{
    // convert the rotation degrees to radians.
    rotation *= Math.PI / 180.0;

    // make an array size that is sure to fit the room.
    int roomSize = (int) Math.Ceiling(radius*2) + 1;

    char[,] room = new char[roomSize, roomSize];

    // first we must create the walls of the room.
    double rchange = (Math.PI * 2.0) / sides;
    for (double r = 0; r < Math.PI * 2; r += rchange)
    {
        // define first point.
        double p1_x = radius + Math.Cos(r + rotation) * radius;
        double p1_y = radius + Math.Sin(r + rotation) * radius;

        // define second point (rotated 1 iteration further).
        double p2_x = radius + Math.Cos(r + rotation + rchange) * radius;
        double p2_y = radius + Math.Sin(r + rotation + rchange) * radius;

        // get distance between the two points.
        double len = Math.Sqrt(Math.Pow(p2_x - p1_x, 2) + Math.Pow(p2_y - p1_y, 2));

        // linearly interpolate between the two points and place walls between them.
        for (double i = 0; i < 1; i += 1.0 / len)
        {
            int place_x = (int) Math.Round((1 - i) * p1_x + i * p2_x);
            int place_y = (int) Math.Round((1 - i) * p1_y + i * p2_y);

            room[place_y, place_x] = '#';
        }
    }

    // now we have to fill the room with a floor.
    // this is done using something similar to a scanline algorithm.
    for (int scan = 0; scan < roomSize; scan++)
    {
        int left_x = -1;
        int right_x = -1;
        bool spaceDetected = false;

        for (int i = 0; i < roomSize; i++)
        {
            if (room[scan, i] == '#')
            {
                if (!spaceDetected)
                    left_x = i;
                else
                {
                    right_x = i;
                    break;
                }
            }
            else if (left_x != -1)
                spaceDetected = true;
        }

        if (right_x != -1)
        {
            for (int i = left_x + 1; i < right_x; i++)
            {
                room[scan, i] = '.';
            }
        }
    }

    return room;
}

```

Here is a hexagonal room generated with the above method:

```
     ##############
     #.............#
    #..............#
    #...............#
   #................#
   #.................#
  #...................#
 ##...................#
 #.....................#
#.......................#
#.......................#
#.......................#
 #.....................#
  #...................##
   #..................#
   #.................#
    #...............##
    #...............#
     #..............#
     #.............#
      ##############

```

# Answer
> 3 votes
If anyone is coming across this and wants to make non-regular, square dungeon rooms, you can still use Quintin's answer just adapted a bit.

You will move along the circumference of a circle until you reach 360 degrees(2 pi radians), back to the starting point. (you can use either radians or degrees, I will use degrees for readability. Keep in mind math functions use radians. convert with degrees * pi/180)

Create a loop starting at 0 degrees around the circle and stopping at 360 degrees. Each loop you will do the following:

1. Generate a random degree amount and increment the total degrees by it. Use whatever range you want, smaller values = more circular and more corners, larger = more boxy.
2. Use x = radius * cos(angle) and y = radius * sin(angle) to get an x,y position (relative to the center of your circle/room). If you are using degrees you need to convert degrees to radian with degrees * pi/180
3. Fill in the walls from the previous position to the new one.
4. Set the previous position to the new one and move on to next iteration

Filling in the walls from the previous to new position is simple. Get the difference from previous to new position with new - previous (that order). Then you can draw the x wall and the y wall by moving that distance along the respective axis.

And that's it. You may need to do one final wall filling from the last position to the very first position.

Here is an example room I made with a tile based map. The random degree change range was 20 to 90 degrees, with a radius of 10 (tiles).

And here is a circle overlay to show how the points along a circle's circumference are used to make the room:

---
Tags: xna, algorithm, procedural-generation, roguelikes
---