# Question
Title: A* algorithm: need help fixing path that come in contact with obstacle
I am using A\* as a pathfinding technique for my AI; it works fine until it gets close to an obstacle (in my case rocks). Right now it just continues the loop if it finds a neighbor thats a rock. It should not actually do this. It should check it.

Allowed Moves: FORWARD,LEFT,RIGHT (LEFT & RIGHT at diagonals) turns are basically two phases: FORWARD, turn face then FORWARD (counts as one move with no additional cost)

The AI should know to turn left or right on the rock in the direction of the goal while also taking other rocks into account.

The line that checks for rocks is: `if(at == 1 || at == 2) continue;`

I guess you could use the neighborlist to check the sides of the ship.

**However it shouldn't always check it. Only when it comes in contact with a rock**

Scenario 1: (ship should turn left (one move) once then continue on path)

Scenario 2: (ship should either turn left or right twice (two moves) to unblock itself)

Scenario 3: (ship should turn left or right depending on which path is shorter: doing two lefts will hit rock twice but distance is shorter than if it went right by 1 tile)

In each of these scenarios the face of the ship is the only thing that changes; unless its a forward move into the rock then there is no change. If right/left were used in any other situation (regular tiles) it would change position also.

```
public class AStarSearch {

    private ServerContext context;
    private List<AStarNode> openList;
    private List<AStarNode> closedList;

    private double ORTHOGONAL_COST = 1.0;
    private double DIAGONAL_COST = ORTHOGONAL_COST * Math.sqrt(2.0);

    public AStarSearch(ServerContext context) {
        this.context = context;
    }

    private Comparator<AStarNode> nodeSorter = new Comparator<AStarNode>() {

        @Override
        public int compare(AStarNode n0, AStarNode n1) {
            if(n1.fCost < n0.fCost) return 1;
            if(n1.fCost > n0.fCost) return -1;
            return 0;
        }

    };

    public List<AStarNode> findPath(Player bot, Position goal){
        openList = new ArrayList<AStarNode>();
        closedList = new ArrayList<AStarNode>();
        List<AStarNode> neighbors = new ArrayList<AStarNode>();
        AStarNode current = new AStarNode(bot, bot.getFace(), MoveType.NONE, null, 0, bot.distance(goal));
        openList.add(current);

        while(openList.size() > 0) {
            Collections.sort(openList, nodeSorter);
            current = openList.get(0);
            if(current.position.equals(goal)) {
                List<AStarNode> path = new ArrayList<AStarNode>();
                while(current.parent != null) {
                    path.add(current);
                    current = current.parent;
                }
                openList.clear();
                closedList.clear();
                Collections.reverse(path);
                return path;
            }
            openList.remove(current);
            closedList.add(current);

            int x = current.position.getX();
            int y = current.position.getY();
            switch (current.face) {
                case NORTH:
                    neighbors.add(new AStarNode(new Position(x, y), VesselFace.NORTH, MoveType.NONE,current,0,0));
                    neighbors.add(new AStarNode(new Position(x, y+1), VesselFace.NORTH, MoveType.FORWARD,current,0,0));
                    neighbors.add(new AStarNode(new Position(x-1, y+1), VesselFace.WEST, MoveType.LEFT,current,0,0));
                    neighbors.add(new AStarNode(new Position(x+1, y+1), VesselFace.EAST, MoveType.RIGHT,current,0,0));
                    break;
                case EAST:
                    neighbors.add(new AStarNode(new Position(x, y), VesselFace.EAST, MoveType.NONE,current,0,0));
                    neighbors.add(new AStarNode(new Position(x+1, y), VesselFace.EAST, MoveType.FORWARD,current,0,0));
                    neighbors.add(new AStarNode(new Position(x+1, y+1), VesselFace.NORTH, MoveType.LEFT,current,0,0));
                    neighbors.add(new AStarNode(new Position(x+1, y-1), VesselFace.SOUTH, MoveType.RIGHT,current,0,0));
                    break;
                case SOUTH:
                    neighbors.add(new AStarNode(new Position(x, y), VesselFace.SOUTH, MoveType.NONE,current,0,0));
                    neighbors.add(new AStarNode(new Position(x, y-1), VesselFace.SOUTH, MoveType.FORWARD,current,0,0));
                    neighbors.add(new AStarNode(new Position(x-1, y-1), VesselFace.WEST, MoveType.RIGHT,current,0,0));
                    neighbors.add(new AStarNode(new Position(x+1, y-1), VesselFace.EAST, MoveType.LEFT,current,0,0));
                    break;
                case WEST:
                    neighbors.add(new AStarNode(new Position(x, y), VesselFace.WEST, MoveType.NONE,current,0,0));
                    neighbors.add(new AStarNode(new Position(x-1, y), VesselFace.WEST, MoveType.FORWARD,current,0,0));
                    neighbors.add(new AStarNode(new Position(x-1, y+1), VesselFace.NORTH, MoveType.RIGHT,current,0,0));
                    neighbors.add(new AStarNode(new Position(x-1, y-1), VesselFace.SOUTH, MoveType.LEFT,current,0,0));
                    break;
            }
            for(AStarNode neighborNode : neighbors) {
                // Compute the cost to get *to* the action tile.
                double costToReach = current.position.distance(neighborNode.position);

                int at = context.getMap().getTile(neighborNode.position.getX(), neighborNode.position.getY());
                if(at == 1 || at == 2) continue; // this is the line where it checks if tile is rock or not

                double gCost = current.gCost + costToReach;
                double hCost = heuristicDistance(neighborNode.position,goal);
                AStarNode node = new AStarNode(neighborNode.position, neighborNode.face,neighborNode.move, current, gCost, hCost);
                if(positionInList(closedList, neighborNode.position) && gCost >= node.gCost) continue;
                if(!positionInList(openList, neighborNode.position) || gCost < node.gCost) openList.add(node);
            }
        }
        closedList.clear();
        return null;
    }

    private double getActionCost(Position node, int currentTile) {
        if(currentTile > 3 && currentTile < 11) {
            return 0.2;
        }else {
            return 1;
        }
    }

    private double heuristicDistance(Position current, Position goal) {
        int xDifference = Math.abs(goal.getX() - current.getX());
        int yDifference = Math.abs(goal.getY() - current.getY());

        int diagonal = Math.min(xDifference, yDifference);
        int orthogonal = xDifference + yDifference - 2 * diagonal;

        return orthogonal * ORTHOGONAL_COST + diagonal * DIAGONAL_COST;
    }

    private boolean positionInList(List<AStarNode> list, Position position) {
        for(AStarNode n : list) {
            if(n.position.equals(position)) return true;
        }
        return false;
    }

}

```

AStarNode:

```
public class AStarNode {

    public Position position;
    public VesselFace face;
    public MoveType move;
    public AStarNode parent;
    public double fCost, gCost, hCost;

    public AStarNode(Position position, VesselFace face, MoveType move, AStarNode parent, double gCost, double hCost) {
        this.position = position;
        this.face = face;
        this.move = move;
        this.parent = parent;
        this.gCost = gCost;
        this.hCost = hCost;
        this.fCost = this.gCost + this.hCost;
    }

}

```

There will be no additional cost of running into a rock as long as its a shorter route. Also, if a ship tries to turn left or right from its current position; but there is a rock at that tile it will move up one tile and changes its direction.

The overall question/goal: How do I fix my current code to account for these situations; please provide an implementation or instructions.

# Answer
I'll show you how I'd tackle this in C#, since it's the language I'm most familiar with and I'm less likely to make silly syntax errors. Java syntax is very similar, so you should be able to translate the strategy to your code smoothly enough.

I'd start by defining some data types to manipulate ship positions and headings. Nothing too exciting here.

```
public enum Direction {
    North,
    East,
    South,
    West
}

public static Direction TurnRight(Direction direction) {
    return (Direction)(((int)direction + 1) & 3);
}

public static Direction TurnLeft(Direction direction) {
    return (Direction)(((int)direction + 3) & 3);
}

public static Vector2Int ToOffset(Direction direction) {
    switch(direction) {
        case Direction.North: return Vector2Int.up;
        case Direction.East: return Vector2Int.right;
        case Direction.South: return Vector2Int.down;
        case Direction.West: return Vector2Int.left;
    }
    throw new System.ArgumentException($"Invalid direction {direction}");
}

public struct ShipTransform {
    public readonly Vector2Int position;
    public readonly Direction heading;

    public ShipTransform(Vector2Int position, Direction heading) {
        this.position = position;
        this.heading = heading;
    }
}

```

Then I'd set up the map functions to compute what happens for special effect tiles...

```
public class Map {

    // I'll elide the map storage - you can use whatever format you like there.

    public bool IsBlocked(Vector2Int position, Direction travelDirection) {
        // TODO: Return true if there is a ship here that's not moving out of the way.

        switch(GetTileTypeAt(position)) {
            case TileType.Rock: return true;
            case TileType.WhirlpoolNE: return travelDirection == Direction.West;
            case TileType.WhirlpoolSE: return travelDirection == Direction.North;
            case TileType.WhirlpoolSW: return travelDirection == Direction.East;
            case TileType.WhirlpoolNW: return travelDirection == Direction.South;
            default: return false;
        }
    }

    public bool ProcessTileEffect(ShipTransform transform, out ShipTransform result) {

        var tileType = GetTileTypeAt(transform.position);
        switch (tileType) {
            case TileType.WindNorth:    result = ProcessWind(transform, Direction.North);
                                        return true;
            case TileType.WindEast:     result = ProcessWind(transform, Direction.East);
                                        return true;
            case TileType.WindSouth:    result = ProcessWind(transform, Direction.South);
                                        return true;
            case TileType.WindWest:     result = ProcessWind(transform, Direction.West);
                                        return true;
            case TileType.WhirlpoolNE:  result = ProcessWhirlpool(transform, transform.position - Vector2Int.one);
                                        return true;
            case TileType.WhirlpoolNW:  result = ProcessWhirlpool(transform, transform.position + Vector2Int.down);
                                        return true;
            case TileType.WhirlpoolSE:  result = ProcessWhirlpool(transform, transform.position + Vector2Int.left);
                                        return true;
            case TileType.WhirlpoolSW:  result = ProcessWhirlpool(transform, transform.position);
                                        return true;
            default:                    result = transform;
                                        return false;
        }
    }

    ShipTransform ProcessWhirlpool(ShipTransform transform, Vector2Int whirlpoolCorner) {
        Vector2Int position = 2 * whirlpoolCorner + Vector2Int.one - transform.position;
        return new ShipTransform(position, TurnRight(transform.heading));
    }

    ShipTransform ProcessWind(ShipTransform transform, Direction windDirection) {
        var position = transform.position + ToOffset(windDirection);

        if (IsBlocked(position, windDirection))
            return transform;

        return new ShipTransform(position, transform.heading);
    }
}

```

Then I'd make a data structure to represent an A\* node - with a few convenience methods to make it easier to compute neighbouring nodes I want frequently:

```
public struct MoveState {
    public readonly ShipTransform transform;
    public readonly int gCost;
    public float hCost;

    public MoveState(ShipTransform transform, int cost) {
        this.transform = transform;
        gCost = cost;
        hCost = 0;  // Our parent will fill this in later.
    }

    public MoveState SpendMove() {
        return new MoveState(transform, gCost+1);
    }

    public MoveState MoveForward() {
        return new MoveState(
            new ShipTransform(transform.position + ToOffset(transform.heading), transform.heading),
            gCost);
    }

    public MoveState Turn(Direction direction) {
        return new MoveState(
            new ShipTransform(transform.position, direction),
            gCost);
    }
}

```

Now we can make a method that enumerates the moves we can make from a given position:

```
public static void FindMoves(MoveState start, List<MoveState> outcomes, Map map, int moveBudget) {
    outcomes.Clear();

    // If we have no moves left, return with an empty list.
    if (start.gCost >= moveBudget)
        return;

    // Add "wait" move (or move that cannot be completed).
    var here = start.SpendMove();
    outcomes.Add(here);

    // First, we'll try moving in our current heading.
    var forward = here.MoveForward();

    if (map.IsBlocked(forward.transform.position, forward.transform.heading)) {
        // If we're facing a barrier, we can only turn in-place.
        outcomes.Add(here.Turn(TurnLeft(here.transform.heading)));
        outcomes.Add(here.Turn(TurnRight(here.transform.heading)));
    } else {
        // Otherwise, we can move forward into the tile in front of us.
        outcomes.Add(forward);

        // And we can turn into the tiles left or right of it...
        var turned = forward.Turn(TurnLeft(here.transform.heading));
        var advanced = turned.MoveForward();
        if (map.IsBlocked(advanced.transform.position, advanced.transform.heading)) {
            // If that tile is blocked, we just turn our facing direction.
            outcomes.Add(turned);
        } else {
            // Otherwise, we move into the tile diagonal to our original.
            outcomes.Add(advanced);
        }

        // Repeat for a right turn.
        turned = forward.Turn(TurnRight(here.transform.heading));
        advanced = turned.MoveForward();
        if (map.IsBlocked(advanced.transform.position, advanced.transform.heading)) {
            outcomes.Add(advanced);
        } else {
            outcomes.Add(turned);
        }
    }

    // After we've moved, then the map takes a turn and can move us.
    for (int i = 0; i < outcomes.Count; i++) {
        // If we're on a tile that moves us, replace the outcome with that move.
        if (map.ProcessTileEffect(outcomes[i].transform, out ShipTransform result)) {
            outcomes[i] = new MoveState(result, outcomes[i].moveBudget);
        }
    }

    // Done!
}

```

Note that nowhere in here does the algorithm consider what the AI "should" do per se. It only exhaustively enumerates the set of things that *could* happen.

Also notice here that the `gCost` only ever increments by 1 - because every move exhausts exactly one movement action slot, whether it's orthogonal or diagonal or a "wait".
> 1 votes

---
Tags: java, game-design, ai, path-finding
---


# Question
Title: Unable to create a blueprint containing multiple actors
I'm having some trouble in Unreal 4.23. According to the documentation, if I select a bunch of Actors and hit the Blueprints button in the toolbar, I should get an option to "Convert Selection To Blueprint Class," which then gives me a choice of three options of what to do with the different objects before creating the blueprint. Instead, I get "Convert Selected Components To Blueprint Class," the dialog asking me what to do with the objects does not show up -- it goes straight to the one asking where to save the blueprint -- and the blueprint it generates is a mess: textures get changed, the names of the actors are lost, and all of the objects are "dropped on the ground" rather than being positioned where they had been relative to each other!

The objects in question are a character (Skeletal Mesh) and several sub-objects representing the character's clothing (also skeletal meshes, attached to the character as sub-objects in the World Outliner hierarchy.) I basically want to do the same thing you can do in Unity: take this character and save it as a prefab so I can make copies of it easily in different maps. From researching the documentation and various forum posts, it seems like making them into a Blueprint using the Harvest Components option is the best way to do that, but that option is never showing up! This problem persists even after closing and restarting Unreal.

Anyone have any idea why the editor is not behaving as documented, and what I can do about it?

(And yes, I know about Prefabricator. This is supposed to be for Marketplace content, though, where third-party dependencies are discouraged.)

# Answer
You cannot create a Blueprint that holds multiple actors in the same way the level does in World Outliner. Unreal is different than Unity in that the hierarchy stuff in the level is not the same as the hierarchy stuff within an Actor. Blueprints are (usually) subclasses of the C++ classes UObject, AActor, or UComponent. An Actor has a set of Components, which have an offset if they are subclass of USceneComponent. What the editor is trying to do here is combine all the components of each Actor in the selection into one Actor, and it appears something in the process is failing. There are quite a few edge cases not handled by this process, especially in 4.23.

You can use a SubActor component to get MOST of what you are talking about here; from what I recall, it's basically a nicely-pieced-together setup that does Actor::AttachToComponent for you.

I recommend changing all your clothing actors into skeletal mesh components that are all applied to your character, but default to invisible.

If you just want to manually copy it into different maps, selecting then right-click copy/paste in World Outliner might work.
> 2 votes

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


# Question
Title: Android multitouch: How to detect movement on non-primary pointer / finger?
How does one go about detecting a secondary/non-primary finger moving?

There is:

ACTION\_DOWN and ACTION\_UP to detect a primary finger pressing the screen / leaving the screen

ACTION\_POINTER\_DOWN and ACTION\_POINTER\_UP for subsequent fingers pressing / leaving the screen

But there is no ACTION\_POINTER\_MOVE for monitoring and responding to subsequent fingers moving.

Also, if I log *event.getActionIndex();* it always returns '0' regardless of how many fingers are touching the screen (I'm guessing because \*ACTION\_MOVE\* is only interested in the primary finger). So how is it possible test the subsequent fingers?

**Code**

```
case MotionEvent.ACTION_MOVE:{
         int pointerId = event.getPointerId(pointerIndex);

        //Finger slid to left button so set sprite left
            if (event.getY(pointerIndex)>=renderer.leftButton("top") && event.getX(pointerIndex)<=renderer.leftButton("right")){
                renderer.setSpriteState('l', true);
                renderer.setSpriteState('r', false);

        }

            //Finger slide to the right button so set sprite right
            else
                if (event.getY(pointerIndex)>=renderer.rightButton("top") && event.getX(pointerIndex)>renderer.rightButton("left") && event.getX(pointerIndex)<=renderer.rightButton("right")){
                    renderer.setSpriteState('l', false);
                    renderer.setSpriteState('r', true);

            }
            break;

```

# Answer
> 6 votes
The ACTION\_MOVE event provides data for multiple fingers.

You can use event.getPointerCount() to find out how many fingers are touching the screen. Then you can loop through the pointers to get data for each one.

Example:

```
case MotionEvent.ACTION_MOVE:
    int count = event.getPointerCount();
    for (int i = 0; i < count; i++) {
        x[i] = event.getX(i);
        y[i] = event.getY(i);
    }

```

This will give you the x and y values for all of the different touch events.

# Answer
> 1 votes
You can get the effective pointer index of moving finger by checking which pointer changed:

```
private final int MAX_POINTER = 5; // 5 different touch pointers supported on most devices
private float mLastTouchPositionX[];
private float mLastTouchPositionY[];

@Override
public boolean onTouchEvent(MotionEvent aEvent)
int tActionIndex = aEvent.getActionIndex();
int tPointerCount = aEvent.getPointerCount();
    /*
     * Check which pointer changed on move
     */
    if (tMaskedAction == MotionEvent.ACTION_MOVE) {
        for (int i = 0; i < tPointerCount && i < MAX_POINTER; i++) {
            if (mLastTouchPositionX[i] != aEvent.getX(i) || mLastTouchPositionY[i] != aEvent.getY(i)) {
                mLastTouchPositionX[i] = aEvent.getX(i);
                mLastTouchPositionY[i] = aEvent.getY(i);
                // Found new action index
                tActionIndex = i;
                break;
            }
        }
    }
...
}

```

# Answer
> 0 votes
Neither of the proposed solutions are entirely correct (or at the very least, are misleading), since instead of keeping track of the actual finger/pointer id, they are only regarding that move event's index within the `MotionEvent` object, which may vary depending on the number of fingers on the screen.

For example: if the user presses the screen with one finger, and then a second, then that second finger's 'x' position is read by calling `event.getX(1)`. Once the first finger is released, the second finger's position will now be read via `event.getX(0)`, since that `event` object's internal position array is now only one item long. In the above solutions, this means that the position data from the second finger will start being written to a different location in the `mLastTouchPositionX[]` array, once the user releases the first finger.

In order to keep track of a finger throughout its lifespan, you must call `event.getPointerId(i)` (as mentioned by OP and in one of the comments) - this will identify which finger the movement data in the aforementioned `event` object's position array at index 'i' is associated with. Working example:

```
for (int i = 0; i < tPointerCount; i++) {
    int tempPointInd = event.getPointerId(i);
    if (mLastTouchX[tempPointInd] != event.getX(i) || mLastTouchY[tempPointInd] != event.getY(i)) {
        mLastTouchX[tempPointInd] = event.getX(i);
        mLastTouchY[tempPointInd] = event.getY(i);
        tActionIndex = tempPointInd;
        break;
    }
}

```

---
Tags: android, touch, multitouch
---


title: 2D isometric game with 3D prefabs

text:
# Question
Title: 2D isometric game with 3D prefabs
Is it possible to have a **2D isometric** game in Unity, but also have **3D prefabs** in the scene?

Will that work or should I make the game in **3D** with an **isometric** camera?

# Answer
Of course. Unity allows you to combine 2D sprites and 3D meshes in the same scene without any problems.

The only thing that's separate are the 2D and 3D collision systems. 2D colliders won't interact with 3D colliders and vice versa, but you can attach 2D colliders to meshes or 3D colliders to sprites if you want to.

So you might want to decide early whether you want 2D or 3D physics in your game.
> 0 votes

---
Tags: unity
---


title: Generate a wave noise map

text:
# Question
Title: Generate a wave noise map
How can we generate the wave-like texture like this

The author(RujiK) says in reply he used the texture generator(http://www.kitfox.com/projects/perlinNoiseMaker/index.html), but no matter how I tweak the parameters, it looks quite different from the original version

# Answer
I don't think you can make it with that generator alone, but you can use it as a starting point. It looks like the sparseness comes from adjusting the cutoff values - you just take regular noise, and make all pixels below certain gray level black, and all pixels above a different (higher) gray level white.

Some noise generators will allow you to adjust this, but you can also simulate it in an image processing program, like Photoshop - or maybe code it yourself as a shader. For example, start with this:

Note that I used only 2 levels of noise; your source image doesn't seem to have many levels mixed in. Now apply the Levels filter (left image), or alternatively, the Curves filter (right):

Play with the cutoff values until you get something like this:

Adjust vertical tiling:

Now you can apply a color ramp to it, to map the grayscale values to a color gradient:

Obtaining something like this:

Again, you can tweak the cutoff parameters to adjust the result to your liking. Here's how it looks with slightly larger cutoffs on both sides:
> 2 votes

# Answer
I believe RujiK has generated a perlin-noise texture. Then they set a tiling on this texture to be unproportional on X axis/width which stretches it out.

For this effect it doesn't necessary need to have a colour, but I believe colour was added afterwards in some editing software. White - reddish, dark - blueish.

I have used `Groovy` effect to better display the values of white and black. But you would generate a texture without it and make some modifications to make white values whiteish and black values blackish to differentiate more.

These were my settings
> 0 votes

---
Tags: graphics, perlin-noise
---


# Question
Title: How to get the correct Input direction based on the camera angle to use in a rootmotion based third person controller
I move my character based on the rootmotion of their animation using a blend tree that uses 2D Freeform Cartesian input (Vertical, Horizontal)

if Vertical = 1, the character moves forward based on the direction **he is facing**

if Horizontal = 1, the character turns right based on the direction **he is facing**

and the rest of the system follows, here is the current Blend Tree:

Currently, if i press forward, the character move forward no matter where the camera is facing:

But in this example, what i want is for the character to slightly make a turn left to face the camera direction and then start walking forward:

When working on a game that moves the character by code (without rootmotion), something like this would solve the issue:

```
_inputAxis = new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0);
_inputCam = Quaternion.Euler(0, _cam.transform.eulerAngles.y, 0) * _inputAxis;

```

And then use **\_inputCam** to move the character, but for some reason this isn't working, and these two variables are always equal to each other, what am i doing wrong ? also if there is a "standard" solution for this problem (am sure it is) please link it (doesn't matter if its Unity or not as long as the code is readable)

Thanks!

# Answer
> 1 votes
You have two steps here.

1. Convert your controller-relative input into a desired direction in the world, based on the camera perspective.
2. Convert your desired direction in the world to a steering direction, based on the object orientation.

The code you've shown is one way to do step 1.

Myself, I like to use a different version that can also handle slopes:

```
Vector3 CameraRelativeFlatten(Vector3 input, Vector3 localUp)
{
    Transform cam = Camera.main.transform; // You can cache this to save a search.

    Quaternion flatten = Quaternion.LookRotation(
                                        -localUp,
                                        cam.forward
                                   )
                                    * Quaternion.Euler(-90f, 0, 0);

    return flatten * input;
}

```

We can use that to do step 1 like so:

```
// If you want to handle slopes, use the character's up vector,
// or a terrain normal you get from a raycast here instead.
Vector3 groundNormal = Vector3.up;

Vector3 controllerSpaceInput = new Vector3(Input.GetAxis("Horizontal"),
                                           0f,
                                           Input.GetAxis("Vertical"));

Vector3 worldSpaceInput = CameraRelativeFlatten(input, groundNormal);

```

Now that we have an arrow in the world pointing where we want to go, we want to look at that from the character's point of view - to know whether it's pointing left or right based on which way they're facing. That's step 2:

```
Vector3 localSpaceInput = characterTransform.InverseTransformDirection(worldSpaceInput);

```

Now `localSpaceInput.x` contains the amount of input pointing to your character's right, and `localSpaceInput.z` contains the amount pointing directly ahead in their forward direction.

---
Tags: unity, camera, third-person-view, animation-controller
---


# Question
Title: Rendering tiles at a larger size for a detailed look
I'm trying to make my 32-bit tiled map become more "zoomed" in. However, I experience an error that I can't resolve. Firstly, I followed this post on how to render the tiles larger.

**This is my code** *(close to identical to the code in the other post)*:

```
class TiledMap:
    def __init__(self, filename):
        tm = pytmx.load_pygame(filename, pixelalpha=True)
        self.width = tm.width * tm.tilewidth
        self.height = tm.height * tm.tileheight

        self.tmxdata = tm

    def render(self,surface):
        ti = self.tmxdata.get_tile_image_by_gid
        for layer in self.tmxdata.visible_layers:
            if isinstance(layer,pytmx.TiledTileLayer):
                for x,y,gid in layer:
                    tile = ti(gid)
                    tile = pg.transform.scale(tile,(64,64))       <---------- Line that gives Error
                    if tile:
                        surface.blit(tile,(x * 64, y * 64))

    def make_map(self):
        temp_surface = pg.Surface((self.width, self.height))
        self.render(temp_surface)
        return temp_surface

```

The error that is produced is:

```
tile = pg.transform.scale(tile,(64,64))
TypeError: argument 1 must be pygame.Surface, not None

```

I'm suspecting that some tile that its trying to render simply is empty. I've tried a separate smaller map but the issue persists. Is it the tileset? They've all been processed through the program Tiled where they were initially part of one png. If anyone knows a possible solutions I'll gladly try one. Or any other methods that could make it more zoomed in...

# Answer
> 1 votes
The solution in my case was simple, check if the tile is 'None'. If yes, then pass it, but if not, transform it to a larger size. This is the full code that should be used:

```
class TiledMap:
    def __init__(self, filename):
        tm = pytmx.load_pygame(filename, pixelalpha=True)
        self.width = tm.width * tm.tilewidth
        self.height = tm.height * tm.tileheight

        self.tmxdata = tm

    def render(self,surface):
        ti = self.tmxdata.get_tile_image_by_gid
        for layer in self.tmxdata.visible_layers:
            if isinstance(layer,pytmx.TiledTileLayer):
                for x,y,gid in layer:

                    tile = ti(gid)
                    if not tile == None:                     <---- This is the change
                        tile = pg.transform.scale(tile,(64,64))
                        if tile:
                            surface.blit(tile,(x * 64, y * 64))

    def make_map(self):
        temp_surface = pg.Surface((self.width, self.height))
        self.render(temp_surface)
        return temp_surface

```

This solution worked for me. Although, i did notice i have to change the camera class as it still limits itself to the 32-bit size.

---
Tags: rendering, tilemap, tiles, pygame, image-processing
---


# Question
Title: Why the enemy is flipping constantly when it collides with an obstacle?
I'm making a 2D platformer with Unity. I have an enemy patrol that shoots bullet. The enemy is working fine until it reaches to a point that should be turn around. (when collides with an obstacle or is near the ledges) The problem is that the enemy flips rapidly in this situation. Also it only shoots to the right despite its facing direction. I'm pretty sure that the problem is from either the bullet or the pistol script because the enemy completely works when the pistol game object is disabled. My goal is to make the enemy flip at those points like before while it shoots the bullets in its facing direction.

Enemy script:

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

public class Enemy : PhysicsObject
{
    [Header("Attributes")]
    private int direction = 1;
    [SerializeField] private float maxSpeed;
    [SerializeField] private LayerMask rayCastLayerMask; //Which layer do we want the raycast to interact with?
    [SerializeField] private Vector2 rayCastOffset; //Offset from the center of the raycast origin
    [SerializeField] private float rayCastLength = 2;
    bool isFacingLeft;

    [Header("References")]
    private RaycastHit2D rightLedgeRaycastHit;
    private RaycastHit2D leftLedgeRaycastHit;
    private RaycastHit2D rightWallRaycastHit;
    private RaycastHit2D leftWallRaycastHit;

    void Update()
    {
        targetVelocity = new Vector2(maxSpeed * direction, 0);

        if (targetVelocity.x < -.01)
        {
            transform.localScale = new Vector2(-1, 1);
            isFacingLeft = true;
        }
        else if (targetVelocity.x > .01)
        {
            transform.localScale = new Vector2(1, 1);
            isFacingLeft = false;
        }

        //Check for right ledge!
        rightLedgeRaycastHit = Physics2D.Raycast(new Vector2(transform.position.x + rayCastOffset.x, transform.position.y + rayCastOffset.y), Vector2.down, rayCastLength);
        Debug.DrawRay(new Vector2(transform.position.x + rayCastOffset.x, transform.position.y + rayCastOffset.y), Vector2.down * rayCastLength, Color.blue);
        if (rightLedgeRaycastHit.collider == null) direction = -1;

        //Check for left ledge!
        leftLedgeRaycastHit = Physics2D.Raycast(new Vector2(transform.position.x - rayCastOffset.x, transform.position.y + rayCastOffset.y), Vector2.down, rayCastLength);
        Debug.DrawRay(new Vector2(transform.position.x - rayCastOffset.x, transform.position.y + rayCastOffset.y), Vector2.down * rayCastLength, Color.green);
        if (leftLedgeRaycastHit.collider == null) direction = 1;

        //Check for right wall!
        rightWallRaycastHit = Physics2D.Raycast(new Vector2(transform.position.x, transform.position.y), Vector2.right, rayCastLength, rayCastLayerMask);
        Debug.DrawRay(new Vector2(transform.position.x, transform.position.y), Vector2.right * rayCastLength, Color.red);
        if (rightWallRaycastHit.collider != null) direction = -1;

        //Check for left wall!
        leftWallRaycastHit = Physics2D.Raycast(new Vector2(transform.position.x, transform.position.y), Vector2.left, rayCastLength, rayCastLayerMask);
        Debug.DrawRay(new Vector2(transform.position.x, transform.position.y), Vector2.left * rayCastLength, Color.magenta);
        if (leftWallRaycastHit.collider != null) direction = 1;
    }
}

```

Pistol script:

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

public class Pistol : MonoBehaviour
{
    [SerializeField] GameObject bullet;
    [SerializeField] Transform bulletSpawnPos;
    private bool IsShooting;

   [SerializeField] private float shootDelay = .5f;
    private bool isFacingLeft;

    void Start()
    {
        InvokeRepeating("Shoot",4f, shootDelay);
        Rigidbody2D rb = GetComponent<Rigidbody2D>();

    }

    void Update()
    {
       if (IsShooting) return;
        IsShooting = true;
        GameObject b = Instantiate(bullet);
        b.GetComponent<Bullet>().StartShoot(isFacingLeft);
        b.transform.position = bulletSpawnPos.transform.position;

        Invoke("ResetShoot", shootDelay);
    }

   void ResetShoot()
   {
      IsShooting = false;
    }
}

```

Bullet script:

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

public class Bullet : MonoBehaviour
{
    [SerializeField] float speed;
    [SerializeField] int damage;
    float timeToDestroy = 3;

    public void StartShoot(bool isFacingLeft)
    {
        Rigidbody2D rb = GetComponent<Rigidbody2D>();

        if (isFacingLeft)
        {
            rb.velocity = new Vector2(-speed, 0);
        }
        else
        {
            rb.velocity = new Vector2(speed, 0);
        }

        Destroy(gameObject, timeToDestroy);
    }
}

```

# Answer
> 0 votes
Your pistol and your enemy each have their own `isFacingLeft` bool currently. Pistol gets never updated with the value and just uses the default one. So you need to be able to get the `isFacingLeft` from your Enemy script in the Pistol script. You could either

* Have a getter for it
* Make it public

A getter is better since the logic on when it is true or false is handled in Enemy already and we do not want other scripts be able to change the value.

Add this code to your Enemy script

```
public bool IsFacingLeft() {
    return isFacingLeft;
}

```

Updated pistol script

```
private Enemy _enemy;
void Start()
{
    //Getting once a reference to the enemy that is holding the pistol, you
    //could as well assign this in the editor if you make it public
    _enemy = GetComponent<Enemy>();
    InvokeRepeating("Shoot", 4f, shootDelay);
}

void Shoot() {
    GameObject b = Instantiate(bullet);
    b.GetComponent<Bullet>().StartShoot(_enemy.IsFacingLeft());
    b.transform.position = bulletSpawnPos.transform.position;
}

```

The old Update code in Pistol is not needed anymore. There are no changes to the Bullet script.

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


# Question
Title: What is the best approach to minimise the lag caused by ping when spawning predictable entities?
When the client clicks it spawns a unit on the client-side which moves in a predetermined path, it also emits an event to the server which indicates that the client has spawned a unit. Once received the server then spawns a unit and updates it.

Both the client and server's update loop occurs 60 times a second, every 5 iterations the server emits the new state to the client which is then applied.

This works fine for very low ping however when the ping increases the unit that is spawned moves for a while and then snaps back to the position it was spawned (because the server has only just received the event and emitted the new state).

What are the ways I can deal with this?

# Answer
> 0 votes
For something like this, it's useful to use an authoritative server model.

When your client spawns an entity - they don't. They're *requesting that the server spawn an entity*.

That entity doesn't become real until the server says so. Once you get a response back from the server saying "entity X spawned at time Y moving along path Z" you can realize that entity and match it perfectly with this and future messages from the server, without any conflict between your local simulation and a delayed version from the server.

Now this just leaves the problem of how to fill the milliseconds between the request and the response. If you just do nothing, the game looks laggy - the player doesn't know if the game "heard" their input, and might spam the button or yell at the screen for it to react.

So, we provide immediate feedback on the client - say a flashy "summoning" visual and sound effect that shows their input has been accepted and acted upon (and can help hide a "pop" of the unit appearing out of nowhere). Make this effect or animation long enough to cover a typical round-trip-time, and the player won't perceive a delay between their command and the action taking place, and you get smooth, consistent behaviour from there.

The visual effect should be something you can fast-forward or play while the unit is already in motion on other clients, since from their perspective, the command to summon the unit and the appearance of the unit in motion arrive in the same message from the server.

---
Tags: 2d, javascript, client-server
---


# Question
Title: How to create a Decisecond(0.1second) function that can use in the code?
I create a circular object and pivot the minute and second pointer on the middle of the object as below.  Below is the code I use.

```
using System;
using UnityEngine;

public class Pivot_minute : MonoBehaviour
{
    long x;

    void Update()
    { //1complete revolution for minute pointer=3600000millisecond
        x = DateTime.Now.Minute*60*1000+DateTime.Now.Second*1000+DateTime.Now.Millisecond;
        transform.eulerAngles = new Vector3(0, 0, -(x*0.0001f));

    }
}

using System;
using UnityEngine;

public class Pivot_second : MonoBehaviour
{
    long x;

    void Update()
    {// 1 complete revolution for second pointer=60000millisecond,then x millisecond=x/60000*360degree
        x = (DateTime.Now.Second*1000+DateTime.Now.Millisecond);
        transform.eulerAngles = new Vector3(0, 0, -x*0.006f);
    }
}

```

As tested, taking the millisecond precision is definitely showing a smoother pointer movement(not discrete movement) compare to the code below using "second" accuracy as calculation.

```
using System;
using UnityEngine;

public class Pivot_second : MonoBehaviour
{
    int x;

    void Update()
    {// 1 complete revolution for second pointer=60 second, then x second= x/60*360 degree
        x = (DateTime.Now.Second);
        transform.eulerAngles = new Vector3(0, 0, -x*6);

    }
}

```

Now I want to test the Decisecond(0.1second) accuracy to find out at this precision, can I still distinguish between the discrete movement and continuous movement of the pointer? Search through internet and so far do not have any luck.

# Answer
> 0 votes
```
using System;
using UnityEngine;

  public class NewBehaviourScript : MonoBehaviour
 {
   long y;
   long x;
   long z;
   void Update()
   {
    y = DateTime.Now.Millisecond;
    if(y<500)
    {
        x = 0;
    }

    if(y>500&&y<999)
    {
        x = 500;
    }

    z = (DateTime.Now.Second * 1000 + x);
    transform.eulerAngles = new Vector3(0, 0, -z * 0.006f);
}

```

}

Thank for the idea, got it already just define the roundup boundary using if statement, then can define any precision I want in between second and millisecond.

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


# Question
Title: Is it possible to render / project / flatten a 3d model onto a 2d plane in Unity?
If I have a 3d Object (character) could I use a renderer / shader / camera mode to essentially render the 3d object as a 2d sprite?

Not looking for a full tutorial on this one, I realize its a large question; just looking for a direction to head in.

My thought on this one is that it would be easier to create a 3d model and move it to a position for a book-style game. The character could be posed in a number of different positions. I'd add some sort of outline and Cel shader and outline to get the affect, but in order to get it to view properly on my otherwise 2d game, I would need it to be in a panel or something that could have a "Sorting Layer" added to it.

# Answer
You might want to check out RenderTextures. These are 2D textures that you can display on models / sprites or in the UI, but that you can also render into, changing their contents on the fly.

You can create a new render texture with a fixed resolution and format in your Assets folder, or construct one in script if you need to have a flexible resolution at runtime (say, based on the user's display size or quality settings)

The Camera component has a Target parameter you can set to point at a Render Texture, so that whatever the camera sees gets drawn into the texture, instead of onto the screen. Use this in conjunction with Layers and layer masks on the cameras, so that only this to-texture camera can see your 3D model, and other cameras don't try to render it.

Now you can use this render texture as the texture for any material in your game (including a sprite material, or you can make a sprite from a region of the render texture), or supply it to a RawImage component in the UI to draw it as part of a menu.
> 2 votes

---
Tags: unity
---


title: Save Script Doesn't Save Item Variables

text:
# Question
Title: Save Script Doesn't Save Item Variables
I've been working on an RPG videogame, and I have been trying to implement a Save button into my game, which is supposed to save the player's itemAmount variable, which is in another script, called ItemInformation. I retrieve the itemAmount variable at Start() by getting the script from the itemHolder GameObject. I plan to use this script in multiple GameObjects, because I use the same variable (itemAmount) with different values in different GameObjects. For some reason, I don't receive any errors or warnings in the Console. Here is my script to the Saving System:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

public class InventorySave : MonoBehaviour
{
    // Public variables for inventory and health
    private GameObject itemHolder;
    private ItemInformation myItemAmount;

    // Initiates before the first frame
    void Start()
    {
        // Gets components for the player variables
        itemHolder = transform.gameObject;
        myItemAmount = itemHolder.GetComponent<ItemInformation>();
    }

    // Function that will be called when player saves game from pause menu
    public void SaveGame()
    {
        // Creates file to store variables
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Create(Application.persistentDataPath + "/SaveData.dat");
        SaveData data = new SaveData();

        // Gets the player data
        data.itemSave = myItemAmount.itemAmount;

        // Writes player data to file and encrypts it
        bf.Serialize(file, data);
        file.Close();
    }
}

// Holds data that is to be saved
[Serializable]
class SaveData
{
    // Variables for save file
    public int itemSave;
}

```

# Answer
> 0 votes
Don’t worry I fixed the problem. I just forgot to implement a Load System!

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


title: Unity 3D mirror, sync player spawn name

text:
# Question
Title: Unity 3D mirror, sync player spawn name
I am using Mirror for doing my little multi-player car racing project which I want to rename the game object automatically after the NetworkManager auto create the game object.

Here is my NetworkManager code:

```
using System.Collections.Generic;
using UnityEngine;
using Mirror;
public class MyNetworkManager : NetworkManager
{
    public List<GameObject> spawnPos;

    public override void OnServerAddPlayer(NetworkConnection conn)
    {
        Transform start = spawnPos[numPlayers].transform;
        GameObject player = Instantiate(playerPrefab, start.position, start.rotation);
        player.name = "car_" + (numPlayers + 1).ToString();
        NetworkServer.AddPlayerForConnection(conn, player);
    }

}

```

This NetworkManager works good in the Host PC. However, when the client connecting to the host, the name showing in the inspector on client PC is still like car(Clone).

Does anyone know how to deal with this problem?

Thank you for your help.

# Answer
You can use a syncVar for the player name.

```
[SyncVar]
public string playerName;

```

You have to set the playerName on the server. The clients will automatically get notified of the changes to playerName.
> 1 votes

# Answer
welcome to the GameDev Stack Exchange. It looks like your code currently only runs server side which is pretty normal for most projects when initially creating players and setting up the scene. This should keep your server up to date with the latest information, however it does not send these updates to clients.

Usually when setting shared variables you need to plan for sending updates to 1.) the server, 2.) clients already in game, 3.) new clients joining the game. Most online tutorials will help you with the first 2 but the 3rd case is usually the most difficult (you can do this by either resetting all player names when someone joins or by using \[TargetRpc\]).

An easy way to take care of this is using the \[SyncVar\] property which will send regular updates to every client/server about property updates. This can be helpful if a variable is constantly changing but as @DMGregory suggests, can be overkill in most cases. Usually in this scenario you will need to tell the server to let clients know the name has changed and that they should update their local version of the players name to match the new players name

Below is roughly what I would do to try an keep names synchronized (you may need to fiddle with it because like most code on StackExchanges, it isn't really properly tested and is just there to give you an idea of how to solve the problem). This may seem like a lot of code, but the idea is that by updating the players name only when needed you can keep your network connection free for sending more important updates like player positions.

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

public class MyNetworkManager : NetworkManager
{
    public List<GameObject> spawnPos;

    public override void OnServerAddPlayer(NetworkConnection conn)
    {
        Transform start = spawnPos[numPlayers].transform;
        GameObject player = Instantiate(playerPrefab, start.position, start.rotation);

        NetworkServer.AddPlayerForConnection(conn, player);

        int playerId = PlayerManager.Instance.players.Count() - 1;
        string name = "car_" + playerId.ToString();
        PlayerManager.Instance.SetPlayerName(playerId, name);
    }
}

public class PlayerManager : NetworkBehaviour
{
    public PlayerManager Instance; // Quick and dirty singleton, you can find better implementations later
    public List<Player> players = new List<Player>();

    public void Awake()
    {
        Instance = this;
    }

    // Call this when you want to change a players name
    public void SetPlayerName(int playerId, string name)
    {
        CmdSetPlayerName(playerId, name);
    }

    // Tell server name to let people know a name has changed
    [Command]
    private void CmdSetPlayerName(int playerId, string name)
    {
        players[playerId].SetPlayerName(name); // update my player name value
        RpcSetPlayerName(playerId, name); // tell clients to update value
    }

    // tell client to update their own copy of the players name
    [ClientRpc]
    private void RpcSetPlayerName(int playerId, string name)
    {
        players[playerId].SetPlayerName(name); // update my player name value
    }
}

public class Player : MonoBehaviour
{
    private void Awake()
    {
        PlayerManager.players.Add(this);
    }

    // Actually update players name.
    public void SetPlayerName(string name)
    {
        gameObject.name = name;
    }
}

```
> 1 votes

---
Tags: unity, networking, spawning, mirror-networking
---


title: Rotate around moving object

text:
# Question
Title: Rotate around moving object
I'm using the function Transform.RotateAround in order to make my player rotate around objects in my game, it's the main feature.

The thing is, when I'm making my levels harder and make the objects (that the player rotates around) dynamic and add some movement on the X & Y axis, the rotation movement is inconsistent, obviously, since the function recalculates each frame a different pivot to rotate around, the player distance from the object changes and not staying static throughout the rotation cycles.

The question is, is there a way to get around this and make the player rotate around the object in a static, permanent distance from the object even though it's moving?

Maybe by predicting the movement of the object or somehow "diffusing" the effect of the object movement..?

Any comment would be helpful.

Thanks in advance!

# Answer
You can store your current pivot object, direction from it, and distance away in member variables.

Overwrite these values when you start rotating around a new pivot, but then keep the distance variable fixed at that value for future updates.

In your Update (or LateUpdate, if you want to be sure this runs after any Update scripts or animations that move your pivot objects around), rotate your direction, scale it by your distance, and add it to the pivot position to find your new location relative to it.

Here's one way that could look:

```
public class RotateAround : MonoBehaviour {

    public float rotationSpeed = 90f;

    Transform _pivot;
    Vector3 _offsetDirection;
    float _distance;

    public void SetPivot(Transform pivot) {
        if (pivot != null) {
            _pivot = pivot;
            _offsetDirection = transform.position - pivot.position;
            _distance = _offsetDirection.magnitude;
        } else {
            _pivot = null;
        }
    }

    void Update() {
        if (_pivot == null) return;

        Quaternion rotate = Quaternion.Euler(0, 0, rotationSpeed * Time.deltaTime);

        _offsetDirection = (rotate * _offsetDirection).normalized;

        transform.position = _pivot.position + _offset * _distance;
    }
}

```
> 0 votes

---
Tags: unity
---


# Question
Title: Method to make character roam map isn't working
I'm an absolute beginner in Unreal Engine, so sorry for any strange mistakes, formatting, etc. I'm trying to make a game for a project where an enemy chases the player through a maze when it spots the player, but when there's no player it roams around the maze. I have the following blueprint:

Every time I run it, it has varying outcomes. Sometimes the enemy will move around a few times, then randomly stop. It won't return a fail message or move. Other times, it will send a single fail message as soon as the program is run, then not return anything else. And other times, it won't send anything at all or move and just stand there. It'll also sometimes simply turn ~95 degrees to the left then stop.

There's also the issue that the enemy takes the same path every trial, even though it's supposed to choose a random point and move to it.

The enemy easily chases the player through the maze and won't get stuck anywhere, but for some reason the enemy stops moving when it's executing the roam method.

I tried adjusting the radius in the `GetRandomPointInNavigableRadius` part, but that didn't affect anything. I also tried making the character smaller in case it was getting stuck on certain turns, but that also didn't affect it. Removing the delay made it work a few times, but then it went back to not working after a few trials.

Here's the rest of the code for reference:

and a picture of the maze:

and the enemy's width relative to the maze path:

Thank you for any help!

# Answer
By the looks of it, your character is causing its own problems with navigation. The lack of green underneath suggests that it is blocking the NavMesh.

In the Blueprint, select the Capsule then in the details panel, search for Navigation.

One of the options is "Can affect navigation". Uncheck this and you should see the area under your AI go green and it should be free to move.
> 1 votes

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


# Question
Title: Can't Create High Definition Render Pipeline Asset in Unity (Create > Rendering Doesn't Exist)
I've upgraded my project to Unity version 2019.3.0a11. It complains and can't load scripts, mostly because it can't seem to load the original HDRPipeline. I want to make graphics display properly.

In Unity's instructions, they say to go to Assets \> Create \> Rendering and click High Definition Render Pipeline Asset and create this in the `Assets` folder. Problem is, Assets \> Create \> *Rendering* doesn't exist.

* I'm in Assets/Settings
* I upgraded the High Definition RP, Post Processing, and Core RP Packages
* Restarted Unity many times
* Searched for a suitable asset

Here is what the package manager says:

There is an exception thrown in Unity about `Shader error in HDRP/Lit: failed to open source file: 'Packages/com.unity.render-pipelines.core/ShaderLibrary/Version.hlsl' at /…/Library/PackageCache/com.unity.render-pipelines.high-definition@7.0.0/Runtime/ShaderLibrary/ShaderVariables.hlsl …`

In fact, there is a whole wall of exceptions:

# Answer
The solution has been to completely remove all packages in the Package Manager that were awaiting download. Then, I removed High Definition RP and the Core RP Library. After restarting, I added the High Definition RP package back (minus the Core RP Library), and the menu item appeared.
> 2 votes

# Answer
I upgraded my project into 2019.2.6 version from 5.2.1 & my game play graphics didn't display properly. I used Cleared Baked Data in the lighting setting as shown below:

After that, my game play graphics display properly.
> 1 votes

---
Tags: unity, shaders
---


# Question
Title: Is there any different between these 2 command?
I came across this question on stackoverflow https://stackoverflow.com/questions/17147553/int-num-new-int-what-happens-when-this-line-executes . Wonder if there is any difference for sprite and spriteRender in unity between both of these commands `sprite y=new sprite()` and `sprite y;` or `SpriteRenderer x=new SpriteRenderer()` and `SpriteRenderer x;`? I tested in unity, both commands also generate the same option to attach game object, so do both have the same meaning as well?

# Answer
> 0 votes
In Unity components can't be created with `new`, so such command as `SpriteRenderer x = new SpriteRenderer();` must be avoided. In this particular case you will get `x` initialzied with `null`.

And input box for attaching gameObject is generated for every `public` component in class.

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


# Question
Title: How can I make Unity run fast when it's not focused?
I'm using Unity3D. I have an automated test suite that takes 1-2 minutes to run. When Unity has focus, these tests seem to run at least 2x as fast as when Unity is in the background. But, it's very boring to stare at a progress bar for 1-2 minutes while I wait for the tests to complete. The whole reason I want to put it in the background is so I can do something else while these tests are running, but because it slows down the tests to 2-4 minutes, doing so makes me even less efficient.

**Is there a way to have Unity run as fast as it does when it's focused, even when it's not focused?**

This could be a Windows 10 question more than a Unity question. Maybe there's a way to set the Unity process as "high priority" or something.

# Answer
> 1 votes
I would try using the command line flags `-batchmode -nographics` see command line flags and make sure framerate is uncapped: somewhere write `if (Application.isBatchMode) { Application.targetFrameRate = -1; }`

If you don't need physics, you can "turn off" physics with `Time.fixedDeltaTime = 10;` to save some CPU (raycasts will still work).

---
Tags: unity, windows
---


title: How to Make Saving System Serializable

text:
# Question
Title: How to Make Saving System Serializable
Hello I’ve been working on a save/load system for my RPG inventory, and I was wondering whether there was a way to make the script use Serialization instead of PlayerPrefs, because I want the player to be able to access their save file. The main issue I run into with this code is how it mixes up the same variable in different itemHolders, causing duplication. Also, I heard that PlayerPrefs is better used for settings or preferences. Here’s my script:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

public class ItemInformation : MonoBehaviour
{
    // These are the assets for the item to change
    public Text nameText;
    public Text descriptionText;
    public Text regenText;
    public Text amountText;

    // This is the identifier for each item
    public string identifier;

    // These are the variables that change with the different items
    public string itemName;
    public string itemDescription;
    public float itemRegeneration;
    public int itemAmount;

    // Starts on awake
    void Awake()
    {
        // Function to change the object's information and such
        nameText.text = itemName;
        descriptionText.text = itemDescription;
        regenText.text = "HEALS " + itemRegeneration + "HP";

        // Loads game data
        LoadDataIfNeeded();
    }

    void Update()
    {
        amountText.text = "HAVE:" + itemAmount;
    }

    private void SaveData()
    {
        string jsonString = JsonUtility.ToJson(this);
        PlayerPrefs.SetString(identifier, jsonString);

        // Creates file to store variables
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Create(Application.persistentDataPath + "/InvData.dat");
        SaveData data = new SaveData();

        // Gets the player data
        data.itemSave = myItemAmount.itemAmount;

        // Writes player data to file and encrypts it
        bf.Serialize(file, data);
        file.Close();
    }

    public void LoadDataIfNeeded()
    {
        if (PlayerPrefs.HasKey(identifier))
        {
            string jsonInstance = PlayerPrefs.GetString(identifier);
            JsonUtility.FromJsonOverwrite(jsonInstance, this);

            // Extracts the data from the binary file and reads it
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Open(Application.persistentDataPath + "/InvData.dat", FileMode.Open);
            SaveData data = (SaveData)bf.Deserialize(file);
            file.Close();
            myItemAmount.itemAmount = data.itemSave;
        }
        else
        {
            SaveData();
        }
    }
}

// Holds data that is to be saved
[Serializable]
class SaveData
{
    // Variables for save file
    public int itemSave;
}

```

# Answer
1. Don't make this a MonoBehaviour. You don't want to mix actual serialized fields and save data. The references won't serialize right. (If you do need to save references to assets, you'll need to figure out the Addressables system, but you don't need that here.)
2. Have one root object that points to the entire set of save data. That way it all goes into the same file.

Here's the gist of the pattern I usually use.

```
try {
    // avoid collisions with other persistent files
    string saveFolder = Path.Combine(Application.persistentDataPath, "SaveData");
    Directory.CreateDirectory(saveFolder);

    string path = Path.Combine(saveFolder, filename);
    using (var file = new File(path, FileMode.Create)) {
        string jsonString = JsonUtility.ToJson(this);
        file.Write(jsonString);
    }
    return true;
}
catch (Exception e) { // IO can throw all sorts of weird exceptions, for instance Path.Combine can throw ArgumentException
    Debug.LogError("Failed to write save data.");
    Debug.LogException(e);
    return false;
}

```
> 0 votes

# Answer
Here is a basic example for converting an Item/ Spell/ YouKnowWhat to an json string that you could later save plainly if you want user be able to easily edit it (or as binary file if you want to make it harder for them). I'm using a Spell as example.

First we have a helper for loading and saving. The annotation above From and To allows you to execute the methods from the editor.

```
public class JSONHelper : MonoBehaviour
{
    public Inventory myInventory;
    public string json;

    [ContextMenu("ToJSON")]
    public void FromClassToJson()
    {
        json = JsonUtility.ToJson(myInventory);
        Debug.Log(json);
    }

    [ContextMenu("FromJSON")]
    public void FromJsonToClass()
    {
        myInventory = JsonUtility.FromJson<Inventory>(json);
    }
}

```

Now we need an actual Inventory that we can save.

```
[Serializable]
public class Inventory
{
    public Item[] items;
}

[Serializable]
public class Item
{
    public string itemName;
    public ItemType itemType;
    public int amount;
}

```

The example uses a custom ItemType to show that it does not just need to be strings or ints but can be a class as well.

```
[Serializable]
public class ItemType
{
    public EquipSlot slot;
    public Category itemCategory;
}

```

And enums, enums are great for things you use often (they kinda a string) but you can't spell them wrong.

```
public enum Category
{
    WEAPON, QUEST_ITEM, CONSUMABLE, ARMOR
}

public enum EquipSlot
{
    HEAD, SHOULDER, CHEST, ARM, LEG
}

```

Here is an example how an Inventory would look like in json with the helper

{"items":\[{"itemName":"Sturdy Helm","itemType":{"slot":0,"itemCategory":3},"amount":1},{"itemName":"Broken Shild","itemType":{"slot":3,"itemCategory":3},"amount":1},{"itemName":"Old Sock","itemType":{"slot":4,"itemCategory":3},"amount":2}\]}

Enums are identified by an int value internally that's why you see `"slot":0`. Don't worry about that, the parsing from json is giving you the `HEAD` back. This just gives a brief example, how you structure your item or what counts as an item is something you need to figure out based on the needs of your game.
> 3 votes

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


# Question
Title: What's the maths behind checking line of sight
I understand in unity there is Phsyics.LineCast(Vector A, VectorB). What's the maths behind doing that, the only thing i can think of is going along the line at small intervals and seeing whether it collides with an object or setting the line as a cuboid with a small width and height but depth equal to vector1-vector2 but then that would be non-axis aligned cuboid collision which seems pretty expensive.

Could anyone help me on this?

EDIT: I just want to know how to draw a line between two objects and see whether another object obstructs that line. That's it. Yes this is in DirectX.

# Answer
The math behind `Physics.LineCast(A, B)` is what we call a **ray intersection test**.

We take `A` to be the origin of the ray, `B-A` to be the direction of the ray, and look for potential intersections along the line `P(t) = A + (B-A)*t` for `0 <=t <= 1` (or other equivalent formations that differ only in details)

For many shapes, we have a closed-form formula we can apply to find the specific `t` value where the ray hits it, if it does at all. If there's no such value of `t`, or the intersection happens at `t < 0` or `t > 1`, then there's no intersection with our line segment.

Different shapes will use different formulas:

So this gives us a simple algorithm: loop over all the collision shapes in your scene, apply the corresponding ray intersection formula for each one, and keep the lowest value of `t` you find in the range 0...1.

This will give you *correct* results, but it's not *fast*. We waste a lot of time evaluating the formula on objects nowhere near the ray, or on distant objects likely to be occluded by something closer.

So we apply an acceleration structure to help us zero in on just the shapes worth checking, ideally in roughly front-to-back order. That lets us keep the correctness, while making the test much cheaper/faster.

There are a lot of forms this could take, depending on your needs:

* We could divide your world into a grid of cells, and store collision shapes in each cell they overlap.

Then we can march the ray through this grid (kind of like Bresenham's line algorithm), so that we visit each cell in front-to back order.

For each cell we visit, we run the intersection formulas on just the shapes in that cell, skipping any cells our ray doesn't touch.
* We could group objects into a bounding volume hierarchy, and test our ray only against the bounding volume of the root node of that tree. If we find a hit, we test against the bounding volume of its children, and recurse this way until we narrow in on the intersecting objects to run the fine-grained formula on.

We usually use a very simple shape for the bounding volumes, so that test is fast, letting us quickly discard large swaths of the scene.

For all these approaches, it's important to know when to stop. The first hit you found isn't necessarily the nearest hit - it could be that the next object you check has a closer hit point. We can again use a bounding volume to estimate the closest possible hit on an object, and stop our search once the closest possible estimate is further away than the closest hit we've found, guaranteeing that we do indeed have the closest result now.
> 1 votes

# Answer
Figured it out, thanks to everyone who actually tried to help instead of just asking me why i needed to do this.

Use z=mx+c. sub in the two objects positions to work out m and c. Then sub in z and x values to see if it collides with other objects in the scene.
> -1 votes

---
Tags: c++, collision-detection, physics, directx, physics-engine
---


title: glUniformMatrix4fv OpenTK equivalent

text:
# Question
Title: glUniformMatrix4fv OpenTK equivalent
Very simple and quick question which surprisingly I couldn't find an answer to over the internet: what is the equivalent of glUniformMatrixfv for opentk? I've browsed all the 7 overloads of GL.UniformMatrix4 and none of them seems correct to me and/or I have found any example usage for.

E.g. if I have a

`Matrix4[] matrices;`

variable (properly initialized etc..) that I want to map on a

`mat4 matrices[2];`

in glsl, which GL.UniformMatrix4 overload should I use?

P.S. Using OpenTK.Next NuGet package version 1.1.1616.8959

# Answer
According to GL spec:

```
void glUniformMatrix4fv(GLint location,
                        GLsizei count,
                        GLboolean transpose,
                        const GLfloat *value);

*location*
Specifies the location of the uniform value to be modified.

*count*
Specifies the number of matrices that are to be modified.
This should be 1 if the targeted uniform variable is not an array of matrices,
and 1 or more if it is an array of matrices.

*transpose*
Specifies whether to transpose the matrix
as the values are loaded into the uniform variable. Must be GL_FALSE.

*value*
Specifies a pointer to an array of count values
that will be used to update the specified uniform variable.

```

So in my opinion (I've never used OpenTK before) you can use the following function:

```
static unsafe void OpenTK.Graphics.OpenGL4.GL.UniformMatrix4(Int32 location,
                                                             Int32 count,
                                                             bool transpose,
                                                             Double * value)

```

Which has the same parameters as the C++ equivalent. Just pass the proper parameters to this function and everything should be ok:

```
OpenTK.Graphics.OpenGL4.GL.UniformMatrix4(matrices_location,
                                          2        /* count - 2 matrices */,
                                          false    /* transpose */,
                                          matrices /* ref, pointer */);

```
> 1 votes

# Answer
This isn't necessarily the best way to do it, but you could just unroll the matrix in a for loop that adds each element to a `float[]`.

```
private float[] Matrix4ToArray(Matrix4 matrix)
{
    float[] data = new float[16];
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 4; j++) {
            data[i*4+j] = matrix[i, j];

        }
    }
    return data;
}

```

Copying the data as a block would be cheaper, or something like a member access function to the underlying data on the OpenTK API side, but I couldn't find any, and the above worked well enough for my needs.
> 0 votes

---
Tags: opengl, glsl, opentk
---


# Question
Title: Are there any serious advantages for C++ compared to C?
so I know a little bit about C (read like a few university level textbooks on it, I am not an experienced programmer or anything) and now I would like to learn the ropes of the Unreal engine to fidle with it an make my first 3D game :P (I know it's a huge step easier said than done but I just want to go with it)

My question is about how wise would it be to stuck with what I already know and built upon it?

Will I hit soon some nasty walls while trying to make things work using C should I instead use C++ or will I be fine? In other words does C++ will make my life easier or can do things I wouldn't be able to do with C or that I needed serious puzzlesovling skills and much bigger hardware level knowledge in order to overcome them while using C?

Long story short should I invest more time expanding what I know in C or should I start learning C++ instead which would save me time and bring me the most comfort?

# Answer
> 1 votes
If you want to accomplish anything in Unreal through code, then you have to use some object-oriented features. The way you implement game mechanics is by creating C++ classes which inherit from the standard classes provided by the engine and override virtual methods with your own code. And any of the engine features you want to access in your code are also accessed through objects. So you can not really use Unreal using only C features. You need a basic understanding of classes, objects and inheritance.

That being said, you don't really need to understand that much about the finer intricacies of C++ to make use of Unreal. The engine API handles a lot of the nitty gritty details of the C++ language for you. Also, the Unreal engine got a very powerful visual scripting system (called "Blueprints") which allows you to implement most game mechanics without writing any code at all. There are Unreal Engine games which use visual scripting for everything and do not contain a single line of code. Not that this is always a good idea, but it is certainly possible.

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


# Question
Title: Fastest 3D collision detection between two oriented bounding boxes (OBBs)
I am at the point in my game where I need to add a collision system. I tried jBullet, and while it did work, it wasn't what I was looking for. I just want a simple way to test if two oriented bounding box (OBB) trees are colliding.

I was going to do collision by using the tree. Make an AABB for broadphase, then if that passes test if each OBB in tree collide with the other tree.

I did find a few things on the internet, but I couldn't understand them completely. What I am asking for is a website or resource that explains 3D OBB collisions well?

I learned that GJK is faster than SAT, and it appears to be able to tell me how far the boxes penetrate each other. I found some GJK stuff, but they were not boxes; instead, more complex and confusing things.

I just want to be able to make an OBB from 3 vectors: center, size, and rotation of each axis. Then be able to test collisions with those. Thank you in advance for anything you post.

# Answer
> 1 votes
You mentioned using GJK, but that you stepped away from it because they were using things that are more complicated than boxes. Might I suggest that you stepped away too soon? Because GJK uses support maps, you can use GJK for any convex shape, including OBBs, for which a support mapping is defined. So, if you know how to define the support function for an OBB, you can use GJK without worry.

Not only can this help you for OBBs, but it will also be easy to expand the system to work with any two convex shapes for future projects, or if this project develops to require it.

## Calculating a Support for an OBB

Given an input direction \\$d\\$ (converted to the OBB's local space), one way to calculate a support for an OBB would be to define a ray from the center of the OBB in the direction \\$d\\$. The support mapping could simply calculate which face the ray intersects and return any point on that face.

Another, simpler (but likely slightly more expensive) method would be to just take the dot product of \\$d\\$ (converted to the OBB's local space) with each of the eight corners of the OBB, and return the corner that yielded the largest dot product.

(Note that this method actually works for any convex shape that you define as a discrete collection of vertices. Something like a sphere or a capsule would require special operations to handle the smooth, curved surfaces.)

```
Vector3f d = /*OBB space direction*/;
Vector3f[] corners = /*The corners of the OBB in OBB space*/;

float maxDot = Float.NEGATIVE_INFINITY;
int maxDotIndex = -1;

for(int i = 0; i < corners.length; i++) {
    dot = Vector3f.dot(corners[i], d);
    if(dot > maxDot) {
        maxDot = dot;
        maxDotIndex = i;
    }
}

return globalPositionOf(corners[maxIndex]);

```

From there, it's just vanilla GJK. Since we've defined a support function for an OBB, you can just learn GJK from the articles you were reading without having to worry about the complicated shapes at all. Some additional articles on GJK that helped me when I was learning it are here and here, and a working implementation of GJK can be found here.

# Answer
> 0 votes
I saw the link in your comment that showed the character with the OBBs that were arraigned around the mesh. Sometimes that can be done with bounding spheres and then there is no orientation issues and a sphere test is usually faster.

Your character, if showing the bounding structures like in your link would look more like the Michelin man.

# Answer
> 0 votes
Here is an actual working example of an AABB, which is directly from my game engine:

```
using System;
using OpenTK;
using OpenTK.Graphics.OpenGL;

namespace GrimoireEngine.Framework.Maths
{
    public struct BoundingBox : IEquatable<BoundingBox>
    {
        public Vector3 Min;
        public Vector3 Max;

        public const int CornerCount = 8;

        public static Vector3 MaxVector3
        {
            get
            {
                return new Vector3(float.MaxValue);
            }
        }

        public static Vector3 MinVector3
        {
            get
            {
                return new Vector3(float.MinValue);
            }
        }

        public static BoundingBox Identity
        {
            get
            {
                return new BoundingBox(Vector3.Zero, Vector3.One);
            }
        }

        public static BoundingBox Zero
        {
            get
            {
                return new BoundingBox();
            }
        }

        public BoundingBox(Vector3 min, Vector3 max)
        {
            Min = min;
            Max = max;
        }

        public BoundingBox(
            float minX, float minY, float minZ,
            float maxX, float maxY, float maxZ)
            : this(
                new Vector3(minX, minY, minZ),
                new Vector3(maxX, maxY, maxZ))
        { }

        public bool Collides(BoundingBox box)
        {
            if (box.Max.X < Min.X
                || box.Min.X > Max.X
                || box.Max.Y < Min.Y
                || box.Min.Y > Max.Y
                || box.Max.Z < Min.Z
                || box.Min.Z > Max.Z)
            {
                return false;
            }
            if (box.Min.X >= Min.X
                && box.Max.X <= Max.X
                && box.Min.Y >= Min.Y
                && box.Max.Y <= Max.Y
                && box.Min.Z >= Min.Z
                && box.Max.Z <= Max.Z)
            {
                return true;
            }
            return true;
        }

        public ContainmentType Contains(BoundingBox box)
        {
            if (box.Max.X < Min.X
                || box.Min.X > Max.X
                || box.Max.Y < Min.Y
                || box.Min.Y > Max.Y
                || box.Max.Z < Min.Z
                || box.Min.Z > Max.Z)
            {
                return ContainmentType.Disjoint;
            }
            if (box.Min.X >= Min.X
                && box.Max.X <= Max.X
                && box.Min.Y >= Min.Y
                && box.Max.Y <= Max.Y
                && box.Min.Z >= Min.Z
                && box.Max.Z <= Max.Z)
            {
                return ContainmentType.Contains;
            }
            return ContainmentType.Intersects;
        }

        public bool Collides(BoundingFrustum frustum)
        {
            int i;
            bool contained;
            Vector3[] corners = frustum.GetCorners();
            for (i = 0; i < corners.Length; i++)
            {
                if (corners[i].X < Min.X
                    || corners[i].X > Max.X
                    || corners[i].Y < Min.Y
                    || corners[i].Y > Max.Y
                    || corners[i].Z < Min.Z
                    || corners[i].Z > Max.Z)
                {
                    contained = false;
                }
                else if (corners[i].X == Min.X
                         || corners[i].X == Max.X
                         || corners[i].Y == Min.Y
                         || corners[i].Y == Max.Y
                         || corners[i].Z == Min.Z
                         || corners[i].Z == Max.Z)
                {
                    contained = true;
                }
                else
                {
                    contained = true;
                }
                if (contained == false)
                {
                    break;
                }
            }
            if (i == corners.Length)
            {
                return true;
            }
            if (i != 0)
            {
                return true;
            }
            i++;
            for (; i < corners.Length; i++)
            {
                if (corners[i].X < Min.X
                    || corners[i].X > Max.X
                    || corners[i].Y < Min.Y
                    || corners[i].Y > Max.Y
                    || corners[i].Z < Min.Z
                    || corners[i].Z > Max.Z)
                {
                    contained = false;
                }
                else if (corners[i].X == Min.X
                         || corners[i].X == Max.X
                         || corners[i].Y == Min.Y
                         || corners[i].Y == Max.Y
                         || corners[i].Z == Min.Z
                         || corners[i].Z == Max.Z)
                {
                    contained = true;
                }
                else
                {
                    contained = true;
                }
                if (contained != true)
                {
                    return true;
                }
            }
            return true;
        }

        public ContainmentType Contains(BoundingFrustum frustum)
        {
            int i;
            ContainmentType contained;
            Vector3[] corners = frustum.GetCorners();
            for (i = 0; i < corners.Length; i++)
            {
                if (corners[i].X < Min.X
                    || corners[i].X > Max.X
                    || corners[i].Y < Min.Y
                    || corners[i].Y > Max.Y
                    || corners[i].Z < Min.Z
                    || corners[i].Z > Max.Z)
                {
                    contained = ContainmentType.Disjoint;
                }
                else if (corners[i].X == Min.X
                         || corners[i].X == Max.X
                         || corners[i].Y == Min.Y
                         || corners[i].Y == Max.Y
                         || corners[i].Z == Min.Z
                         || corners[i].Z == Max.Z)
                {
                    contained = ContainmentType.Intersects;
                }
                else
                {
                    contained = ContainmentType.Contains;
                }
                if (contained == ContainmentType.Disjoint)
                {
                    break;
                }
            }
            if (i == corners.Length)
            {
                return ContainmentType.Contains;
            }
            if (i != 0)
            {
                return ContainmentType.Intersects;
            }
            i++;
            for (; i < corners.Length; i++)
            {
                if (corners[i].X < Min.X
                    || corners[i].X > Max.X
                    || corners[i].Y < Min.Y
                    || corners[i].Y > Max.Y
                    || corners[i].Z < Min.Z
                    || corners[i].Z > Max.Z)
                {
                    contained = ContainmentType.Disjoint;
                }
                else if (corners[i].X == Min.X
                         || corners[i].X == Max.X
                         || corners[i].Y == Min.Y
                         || corners[i].Y == Max.Y
                         || corners[i].Z == Min.Z
                         || corners[i].Z == Max.Z)
                {
                    contained = ContainmentType.Intersects;
                }
                else
                {
                    contained = ContainmentType.Contains;
                }
                if (contained != ContainmentType.Contains)
                {
                    return ContainmentType.Intersects;
                }
            }
            return ContainmentType.Contains;
        }

        public bool Collides(BoundingSphere sphere)
        {
            if (sphere.Center.X - Min.X >= sphere.Radius
                && sphere.Center.Y - Min.Y >= sphere.Radius
                && sphere.Center.Z - Min.Z >= sphere.Radius
                && Max.X - sphere.Center.X >= sphere.Radius
                && Max.Y - sphere.Center.Y >= sphere.Radius
                && Max.Z - sphere.Center.Z >= sphere.Radius)
            {
                return true;
            }
            double dmin = 0;
            double e = sphere.Center.X - Min.X;
            if (e < 0)
            {
                if (e < -sphere.Radius)
                {
                    return false;
                }
                dmin += e * e;
            }
            else
            {
                e = sphere.Center.X - Max.X;
                if (e > 0)
                {
                    if (e > sphere.Radius)
                    {
                        return false;
                    }
                    dmin += e * e;
                }
            }
            e = sphere.Center.Y - Min.Y;
            if (e < 0)
            {
                if (e < -sphere.Radius)
                {
                    return false;
                }
                dmin += e * e;
            }
            else
            {
                e = sphere.Center.Y - Max.Y;
                if (e > 0)
                {
                    if (e > sphere.Radius)
                    {
                        return false;
                    }
                    dmin += e * e;
                }
            }
            e = sphere.Center.Z - Min.Z;
            if (e < 0)
            {
                if (e < -sphere.Radius)
                {
                    return false;
                }
                dmin += e * e;
            }
            else
            {
                e = sphere.Center.Z - Max.Z;
                if (e > 0)
                {
                    if (e > sphere.Radius)
                    {
                        return false;
                    }
                    dmin += e * e;
                }
            }
            return dmin <= sphere.Radius * sphere.Radius;
        }

        public ContainmentType Contains(BoundingSphere sphere)
        {
            if (sphere.Center.X - Min.X >= sphere.Radius
                && sphere.Center.Y - Min.Y >= sphere.Radius
                && sphere.Center.Z - Min.Z >= sphere.Radius
                && Max.X - sphere.Center.X >= sphere.Radius
                && Max.Y - sphere.Center.Y >= sphere.Radius
                && Max.Z - sphere.Center.Z >= sphere.Radius)
            {
                return ContainmentType.Contains;
            }
            double dmin = 0;
            double e = sphere.Center.X - Min.X;
            if (e < 0)
            {
                if (e < -sphere.Radius)
                {
                    return ContainmentType.Disjoint;
                }
                dmin += e * e;
            }
            else
            {
                e = sphere.Center.X - Max.X;
                if (e > 0)
                {
                    if (e > sphere.Radius)
                    {
                        return ContainmentType.Disjoint;
                    }
                    dmin += e * e;
                }
            }
            e = sphere.Center.Y - Min.Y;
            if (e < 0)
            {
                if (e < -sphere.Radius)
                {
                    return ContainmentType.Disjoint;
                }
                dmin += e * e;
            }
            else
            {
                e = sphere.Center.Y - Max.Y;
                if (e > 0)
                {
                    if (e > sphere.Radius)
                    {
                        return ContainmentType.Disjoint;
                    }
                    dmin += e * e;
                }
            }
            e = sphere.Center.Z - Min.Z;
            if (e < 0)
            {
                if (e < -sphere.Radius)
                {
                    return ContainmentType.Disjoint;
                }
                dmin += e * e;
            }
            else
            {
                e = sphere.Center.Z - Max.Z;
                if (e > 0)
                {
                    if (e > sphere.Radius)
                    {
                        return ContainmentType.Disjoint;
                    }
                    dmin += e * e;
                }
            }
            return dmin <= sphere.Radius * sphere.Radius ? ContainmentType.Intersects : ContainmentType.Disjoint;
        }

        public bool Collides(Vector3 point)
        {
            if (point.X < Min.X
                || point.X > Max.X
                || point.Y < Min.Y
                || point.Y > Max.Y
                || point.Z < Min.Z
                || point.Z > Max.Z)
            {
                return false;
            }
            if (point.X == Min.X
                || point.X == Max.X
                || point.Y == Min.Y
                || point.Y == Max.Y
                || point.Z == Min.Z
                || point.Z == Max.Z)
            {
                return true;
            }
            return true;
        }

        public ContainmentType Contains(Vector3 point)
        {
            ContainmentType result;
            if (point.X < Min.X
                || point.X > Max.X
                || point.Y < Min.Y
                || point.Y > Max.Y
                || point.Z < Min.Z
                || point.Z > Max.Z)
            {
                result = ContainmentType.Disjoint;
            }
            else if (point.X == Min.X
                     || point.X == Max.X
                     || point.Y == Min.Y
                     || point.Y == Max.Y
                     || point.Z == Min.Z
                     || point.Z == Max.Z)
            {
                result = ContainmentType.Intersects;
            }
            else
            {
                result = ContainmentType.Contains;
            }
            return result;
        }

        public bool Equals(BoundingBox other)
        {
            return (Min == other.Min) && (Max == other.Max);
        }

        public override bool Equals(object obj)
        {
            return (obj is BoundingBox) && Equals((BoundingBox)obj);
        }

        public Vector3[] GetCorners()
        {
            return new[] {
                new Vector3(Min.X, Max.Y, Max.Z),
                new Vector3(Max.X, Max.Y, Max.Z),
                new Vector3(Max.X, Min.Y, Max.Z),
                new Vector3(Min.X, Min.Y, Max.Z),
                new Vector3(Min.X, Max.Y, Min.Z),
                new Vector3(Max.X, Max.Y, Min.Z),
                new Vector3(Max.X, Min.Y, Min.Z),
                new Vector3(Min.X, Min.Y, Min.Z)
            };
        }

        public override int GetHashCode()
        {
            return Min.GetHashCode() + Max.GetHashCode();
        }

        public bool Intersects(BoundingBox box)
        {
            if ((Max.X >= box.Min.X) && (Min.X <= box.Max.X))
            {
                if ((Max.Y < box.Min.Y) || (Min.Y > box.Max.Y))
                {
                    return false;
                }
                return (Max.Z >= box.Min.Z) && (Min.Z <= box.Max.Z);
            }
            return false;
        }

        public bool Intersects(BoundingFrustum frustum)
        {
            return frustum.Intersects(this);
        }

        public bool Intersects(BoundingSphere sphere)
        {
            if (sphere.Center.X - Min.X > sphere.Radius
                && sphere.Center.Y - Min.Y > sphere.Radius
                && sphere.Center.Z - Min.Z > sphere.Radius
                && Max.X - sphere.Center.X > sphere.Radius
                && Max.Y - sphere.Center.Y > sphere.Radius
                && Max.Z - sphere.Center.Z > sphere.Radius)
            {
                return true;
            }
            double dmin = 0;
            if (sphere.Center.X - Min.X <= sphere.Radius)
            {
                dmin += (sphere.Center.X - Min.X) * (sphere.Center.X - Min.X);
            }
            else if (Max.X - sphere.Center.X <= sphere.Radius)
            {
                dmin += (sphere.Center.X - Max.X) * (sphere.Center.X - Max.X);
            }
            if (sphere.Center.Y - Min.Y <= sphere.Radius)
            {
                dmin += (sphere.Center.Y - Min.Y) * (sphere.Center.Y - Min.Y);
            }
            else if (Max.Y - sphere.Center.Y <= sphere.Radius)
            {
                dmin += (sphere.Center.Y - Max.Y) * (sphere.Center.Y - Max.Y);
            }
            if (sphere.Center.Z - Min.Z <= sphere.Radius)
            {
                dmin += (sphere.Center.Z - Min.Z) * (sphere.Center.Z - Min.Z);
            }
            else if (Max.Z - sphere.Center.Z <= sphere.Radius)
            {
                dmin += (sphere.Center.Z - Max.Z) * (sphere.Center.Z - Max.Z);
            }
            return dmin <= sphere.Radius * sphere.Radius;
        }

        public PlaneIntersectionType Intersects(Plane plane)
        {
            Vector3 positiveVertex;
            Vector3 negativeVertex;
            if (plane.Normal.X >= 0)
            {
                positiveVertex.X = Max.X;
                negativeVertex.X = Min.X;
            }
            else
            {
                positiveVertex.X = Min.X;
                negativeVertex.X = Max.X;
            }
            if (plane.Normal.Y >= 0)
            {
                positiveVertex.Y = Max.Y;
                negativeVertex.Y = Min.Y;
            }
            else
            {
                positiveVertex.Y = Min.Y;
                negativeVertex.Y = Max.Y;
            }
            if (plane.Normal.Z >= 0)
            {
                positiveVertex.Z = Max.Z;
                negativeVertex.Z = Min.Z;
            }
            else
            {
                positiveVertex.Z = Min.Z;
                negativeVertex.Z = Max.Z;
            }
            float distance = plane.Normal.X * negativeVertex.X + plane.Normal.Y * negativeVertex.Y + plane.Normal.Z * negativeVertex.Z + plane.D;
            if (distance > 0)
            {
                return PlaneIntersectionType.Front;
            }
            distance = plane.Normal.X * positiveVertex.X + plane.Normal.Y * positiveVertex.Y + plane.Normal.Z * positiveVertex.Z + plane.D;
            if (distance < 0)
            {
                return PlaneIntersectionType.Back;
            }
            return PlaneIntersectionType.Intersecting;
        }

        public float? Intersects(Ray ray)
        {
            return ray.Intersects(this);
        }

        public static bool operator ==(BoundingBox a, BoundingBox b)
        {
            return a.Equals(b);
        }

        public static bool operator !=(BoundingBox a, BoundingBox b)
        {
            return !a.Equals(b);
        }

        public override string ToString()
        {
            return "{{Min:" + Min + " Max:" + Max + "}}";
        }

        public void DrawImmediate()
        {
            GL.Begin(PrimitiveType.LineLoop);
            GL.Vertex3(Max.X, Max.Y, Min.Z);
            GL.Vertex3(Min.X, Max.Y, Min.Z);
            GL.Vertex3(Min.X, Min.Y, Min.Z);
            GL.Vertex3(Max.X, Min.Y, Min.Z);
            GL.End();
            GL.Begin(PrimitiveType.LineLoop);
            GL.Vertex3(Max.X, Min.Y, Max.Z);
            GL.Vertex3(Max.X, Max.Y, Max.Z);
            GL.Vertex3(Min.X, Max.Y, Max.Z);
            GL.Vertex3(Min.X, Min.Y, Max.Z);
            GL.End();
            GL.Begin(PrimitiveType.LineLoop);
            GL.Vertex3(Max.X, Max.Y, Min.Z);
            GL.Vertex3(Max.X, Max.Y, Max.Z);
            GL.Vertex3(Min.X, Max.Y, Max.Z);
            GL.Vertex3(Min.X, Max.Y, Min.Z);
            GL.End();
            GL.Begin(PrimitiveType.LineLoop);
            GL.Vertex3(Max.X, Min.Y, Max.Z);
            GL.Vertex3(Min.X, Min.Y, Max.Z);
            GL.Vertex3(Min.X, Min.Y, Min.Z);
            GL.Vertex3(Max.X, Min.Y, Min.Z);
            GL.End();
        }
    }
}

```

Just remove the other Bounding type methods.

# Answer
> -2 votes
Molly Rocket is forever your friend.

http://mollyrocket.com/849

But it sounds like you are misunderstanding the general use of a bounding box. You don't really use it for a physics collision system. Especially when it can be terribly inefficient for that sort of use.

Perhaps you are thinking of a Scene Graph's collision query? Where you check if an object is entering a QuadTree, or an Octree, and you quickly rebuild your graph.

---
Tags: java, collision-detection, lwjgl
---


# Question
Title: Display musical symbol (unicode) in Text component not working?
I downloaded and specified to use a unicode font that supports musical symbols (Musica), but when I set the text value of the Text component to "" nothing is displayed? I tried using the unicode code point with \U as well. What is going wrong?

(I could not get TextMesh Pro working either with that symbol.)

# Answer
How I did to display it with TMPro.TextMeshProUGUI:

Followed https://stackoverflow.com/a/13215070/3021108: `ttx -t cmap Musica.ttf` to get the unicode codes in it.

I clicked on `Window > TextMeshPro > Font Asset Creator`. Then I added the codes into Font Assert by using Unicode Range (Hex).

After I had added them it turned out the range was:

```
20-7E,A0,A4,A6-A7,AC,B0-B1,B6-B7,D7,F7,2002-200D,2012-2014,2016,2022,2212,2219,25CC,2669-266F,1D000-1D0F5,1D100-1D126,1D129-1D1E8,1D200-1D245,FD158-FD159,FD173-FD17A,FD1E0-FD20F

```

The characters look very pixly right now but at least they are not empty.

I did not get it working with Text component, maybe someone else can answer how to do that.
> 1 votes

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