# Question
Title: How can I offset a direction when raycasting?
I'm trying to figure out how I can best offset a direction when raycasting.

So let's say I have an object and I want to cast a ray from my mouse position to said object, that's easily done with (for example):

```
// "obj" being the transform of the object I'm raycasting to.
Vector2 mPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 dir = (Vector2)obj.position - mPosition;
Debug.DrawRay(mPosition, dir, Color.green);

```

But what if I want the direction to always be slightly offset to the right of the object from the mouse position? And I mean not just to the right of the object itself, but to the right from where the mouse is.

I hope I'm making any sense. Here are some pictures to try and make it a little more clear: (Pretend the line is the ray and the circle is the object)

I want to offset the ray so that when my mouse is under the circle, it goes to the right of it, like this:

However, when I move my mouse to the left of the object, the ray should instead go like this:

Meaning the ray will always cast to the right of the object from where the mouse is.

The reason I want to do this is because I'm trying to raycast to the corners of objects, but also see what's past them:

I need to use offset rays to just barely miss the corners and allow them to continue on and see if there's a wall behind them like on the picture above. I'm offsetting my rays in the picture above, but the way I'm doing it isn't the best and I'm trying to find the proper way of doing it.

# Answer
> 4 votes
The X/Y Problem strikes again!

> I'm trying to figure out how I can best **offset a direction**..I want the direction to always be slightly offset to the right of the object from the mouse position? And I mean not just to the right of the object itself, but to the right from where the mouse is.

This is complicated, messy, and error prone. How much offset is *juuuuuust enough* to miss while not unduly changing the resulting hit on the wall behind? What if we have two corners at similar angles, with just a narrow wedge in between, so our offset from one corner hits the other corner and vice versa, and we miss the gap entirely? :o

> I need to **determine where my ray hits a wall on the far side of a corner**, for the purpose of determining the polygonal area visible / illuminated from my ray origin.

This is your real problem. Not offsetting rays. Offsetting rays was just a guess at the solution, and I'd argue it's not the best solution we have within our reach.

So, moral of the story: always ask about *the problem you're trying to solve*, not about the kludge that might help you solve it.

---

To fire a ray that continues past the corner of the object and out the other side to detect the next hit, just use a RaycastAll query (specifically the non-allocating version for efficiency). Something like this:

```
// Make this conservatively large so you don't overflow it.
RaycastHit2D[] _hits = new RaycastHit2D[10];

RaycastHit2D RaycastPastCorner(Vector2 cornerPosition, Vector2 rayOrigin) {
     int hitCount = Physics2D.RaycastNonAlloc(
                      rayOrigin,
                      cornerPosition - rayOrigin,
                      _hits,
                      maxRayRange,
                      raycastLayers);

     // If we hit nothing past the corner, return a miss.
     if(hitCount < 2)
         return default(RaycastHit2D);

     // Otherwise, return the first hit past the corner.
     // (If needed, you can inspect these hits and skip forward by some tolerance)
     return _hits[1];
}

```

There we go, no fudge factor offsets required. Much cleaner and less error-prone!

# Answer
> 0 votes
You can rotate it around the Y axis a bit. E.g. 10 degrees:

```
direction = Quaternion.Euler(0, 10, 0) * direction;

```

# Answer
> 0 votes
To rotate a 2d vector (x, y) by a angle A to form a new vector (x2, y2):

```
x2 = x * cos(A) - y * sin(A);
y2 = x * sin(A) + y * cos(A);

```

(A mathematical discussion of why is here if you want it)

Because you want to rotate in both directions, you can simply form vectors with the angles +0.0001 and -0.0001 to get the rays either side of your central ray. Almost every implementation of cos and sin works with Radians so you won't need to perform a conversion.

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


# Question
Title: Path finding in grid for objects that occupy more than one tile
In a grid-based game I am working on, I want to add objects that occupy more than one tile of the grid. Are there any algorithms or techniques to find paths for this kind of objects?

# Answer
> 5 votes
In general you'll be adapting existing pathfinding algorithms to be width-sensitive. Primarily that means adapting A\*, though since your game is grid-based you may find the algorithm for solving fat mazes helpful.

For A\*, the most basic solution is to simply add an assertion for width to your calculations, according to your movement rules. However, this will make a mess of your pathfinding code and slows down pathfinding for any regular-sized entities.

Alternatively, you can consider your grid to be a node-based pathfinding network, and for your larger entities you could create a secondary network which accounts for their size, and use that for movement and pathfinding. This has the benefit of allowing you to tailor your pathfinding for larger entities so that it behaves as expected, but means creating multiple maps for each scene and holding them in memory, which may impact games on mobile platforms.

If neither of those methods suits your purposes, you could look for inspiration in navigation mesh pathfinding algorithms, which are inherently width-aware.

# Answer
> 6 votes
One option would be to calculate a second grid that takes the object's size into account by "painting" it onto the grid, like so. Here's the original grid:

```
#########
#..b....#
#.#.....#
#.####..#
#.......#
#.......#
#..#.#..#
#a.#.#..#
#########

```

We want to see if a 2x2 object can get from `a` to `b`. We calculate a second grid where every time we have a wall (`#`), we add walls above and to the left of it (`x`), turning each single wall segment into a 2x2 one. Now it looks like:

```
xxxxxxxxxx
x#########
x#xxb...x#
x#x#xxx.x#
x#x####.x#
x#......x#
x#.xxxx.x#
x#.x#x#.x#
x#ax#x#xx#
x#########

```

We can then pathfind on this grid by treating the object as 1x1 since the grid itself takes their size into account.

# Answer
> 2 votes
You can extend munificent's answer to store a single supporting grid, which rather than storing passability for each different object size, it stores a distance field recording the number of half-tile widths between this location and the closest barrier. (Or alternatively, the width of the largest object that can be centered on this tile without hitting anything)

* A wall tile has a distance of -1 (the center of this tile is inside the bulk of the wall).
* A tile adjacent to a wall on at least one side has a distance of 1 (one half a tile separates the center of this tile from the edge of the closest wall)
* A tile with no adjacent walls, that's adjacent to a tile that's adjacent to a wall, has a distance of 3 (one full tile width to reach its neighbour's center, and one half tile from there to the wall)

You can populate this grid by initializing the map to an integer larger than your map size in empty spaces, and -1 at wall sites. Then iteratively set each tile \> 0 to the minimum of its neighbours plus two.

Now inside your pathfinding algorithm, you replace

```
if (!IsPassable(PassabilityMap[x, y])) continue;

```

with

```
if (DistanceToObstacleMap[x, y] < pathfindingAgent.size) continue;

```

Now you can handle pathfinding for any size of unit with a single map, and storing / checking passability remains comparable in cost to the one-bool-per-tile case.

---
Tags: algorithm, tiles, path-finding, grid
---


# Question
Title: How do i find the circumsphere of a tetrahedron?
I'm looking for the most minimized equation to find the **center coordinates** and the **radius** of a **tetrahedron circumsphere** given four 3D points.

What I found on the internet mainly deal with the circum sphere of a flat 3D triangle, or some rough mathematical definitions, or some very single case such as regular tetrahedrons. Anyway I managed to find the equation below but I missed something :

```
    ->  ->      ->
let d1, d2, and d3 three vectors of any face of the triangle :

    | d1x  d1y  d1z |   | x |   | d1^2 |
2 * | d2x  d2y  d2z | * | y | = | d2^2 |
    | d3x  d3y  d3z |   | z |   | d3^2 |

```

My knowledge in this field has its limits but I think I can handle matrices and vector operations. But is the right part of the equation the square of the norm of each vectors ? (which are into a vector). Is the equation valid ? Is it just the writer who lazely forgot to write |d1|^2 ? Or Is it a common way to define some mathematical property.

PS : It's for a Delaunay Triangulation implementation. The equation (number 9) is in the following link : https://www2.mps.mpg.de/homes/daly/CSDS/t4h/tetra.htm

# Answer
While this is an ancient thread, I thought it may be nice for posterity to have a bit to reference. The source of the formula is from Geometric Tools for Computer Graphics by Philip J. Schneider and David H. Eberly. Something to note, according to the text

> The tetrahedron V0, V1, V2, V3 is ordered so that it is isomorphic to the canonical one (0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1) .

As I understand isomorphism, there can be several different meanings when used in geometry. If he means isomorphic with regard to graph theory, then the following code should behave correctly, as the topology of any tetrahedron is the same (K4, a complete graph). I tested the results of the function against wolfram alpha using various permutations in the ordering of the canonical vertices, and I saw no difference in the outcome. If the ordering proves to be a problem, I suggest examining the normal of the triangle formed by the vertices V1,V2,V3 upon input to this function, and treating the points like a half-space with a dot-product test to figure out if that triangle is facing the right way. If it's not, a simple `std::swap` of any two of the triangle's vertices will reverse the direction of the normal and you may continue. But like I said, I saw no difference with various permutations.

Here is the translated code without using matrices to avoid any implementation confusion, it's fairly straight-forward;

```
void Circumsphere(const Vec3& v0, const Vec3& v1, const Vec3& v2, const Vec3& v3, Vec3* center, float* radius)
{
  //Create the rows of our "unrolled" 3x3 matrix
  Vec3 Row1 = v1 - v0;
  float sqLength1 = length2(Row1);
  Vec3 Row2 = v2 - v0;
  float sqLength2 = length2(Row2);
  Vec3 Row3 = v3 - v0;
  float sqLength3 = length2(Row3);

  //Compute the determinant of said matrix
  const float determinant =   Row1.x * (Row2.y * Row3.z - Row3.y * Row2.z)
                            - Row2.x * (Row1.y * Row3.z - Row3.y * Row1.z)
                            + Row3.x * (Row1.y * Row2.z - Row2.y * Row1.z);

  // Compute the volume of the tetrahedron, and precompute a scalar quantity for re-use in the formula
  const float volume = determinant / 6.f;
  const float iTwelveVolume = 1.f / (volume * 12.f);

  center->x = v0.x + iTwelveVolume * ( ( Row2.y * Row3.z - Row3.y * Row2.z) * sqLength1 - (Row1.y * Row3.z - Row3.y * Row1.z) * sqLength2 + (Row1.y * Row2.z - Row2.y * Row1.z) * sqLength3 );
  center->y = v0.y + iTwelveVolume * (-( Row2.x * Row3.z - Row3.x * Row2.z) * sqLength1 + (Row1.x * Row3.z - Row3.x * Row1.z) * sqLength2 - (Row1.x * Row2.z - Row2.x * Row1.z) * sqLength3 );
  center->z = v0.z + iTwelveVolume * ( ( Row2.x * Row3.y - Row3.x * Row2.y) * sqLength1 - (Row1.x * Row3.y - Row3.x * Row1.y) * sqLength2 + (Row1.x * Row2.y - Row2.x * Row1.y) * sqLength3 );

  //Once we know the center, the radius is clearly the distance to any vertex
  *radius = length(*center - v0);
}

```
> 2 votes

---
Tags: 3d, sphere
---


# Question
Title: How to cut a desired shape out of a mesh?
I want the player to be able to cut a hole through a wall, similar to what's shown in this video

I know for the fact that it's really difficult to achieve, so I was wondering how I can cut a shape out of a simple mesh at run time (or even cut a shape out of a 2D sprite).

# Answer
> 3 votes
I have done this for automated medical CAD procedures as well as game engines, and will attempt to provide adequate information in order for you to accomplish this task on your own, but I will not be able to provide the script for you as **this is a non-trivial task that requires a good deal of computational geometry and problem-solving**. What you're asking is quite complicated and it is for this reason you have not seen this mechanic in most games.

**Hurdles and strategies**

1. **Non-Convex collision detection** \- Say your user were to cut a hole in the middle of a wall. Not terribly complicated to do by itself, but we'll get to that. They now have presumably two pieces of geometry. The inner piece, assuming your user made a clean triangle, is a convex object meaning a straight line cannot cross through more than two points on the surface. This is the best-case scenario, as modern collision detection algorithms are quite fast because they rely on certain mathematical principals which only apply to convex shapes. As for your second shape, which is a large box with a gaping hole in the middle, it is no longer convex. In fact, it's horribly non-convex. While there are solutions to non-convex collision detection via hand-crafted collider-hierarchies (as sometimes seen with ragdolls) or through automated procedures such as HACD or V-HACD, neither of them are easy to implement. Fortunately, it appears as though someone has attempted to port V-HACD to unity. Having not used it, I can't say whether their implementation works or not. I can say that typically HACD is something you would precompute and package the output with your game. That being said, the problem becomes significantly easier in 2D if that's a viable option for you and may be something to take a look at.
2. If collisions are not a problem for you, you're off to a great start. Next comes **graphics**. You will need to be familiar with UV coordinates and clipping algorithms. To slice a wall, the resulting geometry will need to retain the UV coordinates. I suggest familiarizing yourself with algorithms such as the Sutherland-Hodgman clipping algorithm, which has been around since 1974 and is still used today for various procedures. The meat and potatoes though, using half-planes or half-spaces to determine the side of a plane in which a point resides, will be the primary functional tool used throughout the procedure. It can not only slice the topology, but you can even slice vertex attributes (like UV coordinates) at the same time in one go.
3. **Geodesic Pathfinding and Topological Data Structures** \- This is where it gets *even messier*. Unity (to my knowledge) does not natively employ a dynamic mesh data structure which will allow you to easily accomplish this task, which means that every destructible mesh will need to be converted to a traversable graph structure, sliced, and then converted back to the format in which unity expects to pass to the renderer. If your slicing does not occur in one fell swoop, i.e. a slow laser cutting the wall instead of a cookie-cutter stamping out a shape all at once, then you will have to do this **every frame**. Presumably, your data structure would persist through each frame, and you will have to tell unity to drop the current mesh for the newly-sliced version. I'm not familiar with unity's graphics implementation, but as far as vertex buffer objects and index buffer objects go, there is a fair amount of overhead involved with uploading new meshes to the GPU. The lag-time when transferring data from the CPU to the GPU is one of the worst unavoidable bottlenecks in graphics, something which a lot of smart people spend a lot of time strategizing over. This is why most meshes are uploaded once at the beginning of a level.

So on to the data structure and algorithm;

**The Data Structure**

A popular data structure used in topological deformation and slicing procedures is called a **Half-Edge Mesh, also known as a Doubly Connected Edge List**. It's by no means the best graph for all scenarios, but it's a thoroughly tested structure that I've personally employed to accomplish similar tasks and can speak to its versatility. If this was your own engine and not unity, I would suggest moving your collider geometry implementation toward this as it supports non-triangulated surfaces and can be used to optimize certain collision detection algorithms.  (image courtesy of wikipedia commons)

As a high-level overview, it's simply a directed graph made up by a doubly-linked list of vertices and edges with the caveat being each physical edge on the geometry is represented by **two** edges in the graph, known as twin edges. Each of these edges owns 1 vertex (usually represented by an index instead of the physical point), and has a pointer to the next edge, previous edge, and its twin-edge which traverses an adjacent face in the opposite direction. This is the big feature of half-edge graphs, allowing one to iterate an entire polygon face by simply walking the next pointer until you're back where you started. This is essential to the procedure, as it allows us to preserve the winding order of the vertices as they must always be uploaded to the GPU in the same way. Otherwise, you get a big gaping triangular hole wherever the winding order was flipped. I advise looking for existing implementations in Unity for this, as the helper functions you will need to write (such as inserting a vertex) will take a lot of white-board planning and diagramming to get right.

So now, assuming you've successfully converted your mesh into a half-edge data structure, you can now traverse the surface of the mesh and you're ready to try your hand at geodesic pathfinding. To begin, you would use raycasts or some other method involving your mechanic to somehow pull topological information such as which face of the geometry was hit, in order to find a starting point. If you plan on drawing, I suggest saving these points and converting them into a Catmull-Rom splines because if your user is raycasting each frame, you will need to have a path to follow and splines are a simple way of providing "infinite" precision (because it is an implicit curve), instead of limiting yourself to wherever the user happened to be pointing that frame.

Begin by inserting a point into the geometry at the first spot your user hit. You will need to have some sort of triangulation utility handy, iterative algorithms like Bowyer-Watson or the Earcut Algorithm. This is where the problem-solving actually starts, as you will need to get your hands dirty to implement a rag-tag Constrained Delaunay Triangulation (referred to as CDT) or just a simple constrained triangulation (which there isn't much information on, as almost everyone needs Delaunay triangles, though we do not) which is quite literally a field of study in and of itself. You'll notice in the illustrations provided by Wikipedia on the Bowyer-Watson algorithm that at each iterative insertion, the order in which they are added *tend* to be preserved via an edge connecting each new vertex at each step. Another hint I can give you from the result of my own experimentation, is that if you look at any convex non-triangulated half-edge diagram, they can be instantly triangulated by connecting from the "head" of an edge, to the tail of the previous edge. i.e.

```
HalfEdge* edge = face.edges[0];

        while(!edge->IsTriangle())
            edge = ConnectEdges(edge, edge->prev);

```

Take that for what you will and roll with it cause it only gets worse from here.

Now you have inserted and triangulated your face, next comes traversing the graph. I suggest precalculating the inward-facing normal of each edge, essentially if you were to rotate each edge's direction 90 degrees to face the center of the triangle, that's the direction you want. Treat that like a half-plane like I mentioned earlier with the sutherland-hodgeman clipping algorithm. You want to continue inserting and triangulating occasionally until the point drawn by your player crosses the edge of a triangle, at which point the sign of the dot product will switch from positive to negative as the dot product with a plane represents the signed-distance of the point from that plane. Split that triangle at the clipped point, inserting it into your graph, and continue on to the next triangle.

Now while all that's going on, if you're in 3D you need your trusty helper functions to be silently creating "internal" edges (literally meant for the inside of the polyhedra, as we are treating it like a solid object which suddenly gains a new internal surface) each time you add your new half-edge pairs to the graph, and make sure they connect with one another, as you will eventually need to triangulate that surface when the procedure is complete.

That about covers it as far as down-and-dirty geodesic pathfinding goes, the rest of the procedure boils down to your mechanics and how you wish to start and stop the process. Ideally, the ends should connect (the spline simplifies this) so that you can easily create your new shapes without thinking much about it. That only leaves conversion back to renderable geometry, which I will leave up to you.

Aside from this, you may want to consider a high-density voxel object approach, which I have no experience with, but have seen it employed for destructible environments using marching cubes or dual contours to smooth the mesh and make it appear like you're not using voxels (as seen in games such as No-Man's Sky).

My point here is that it is possible, but you have to *really want it* and be willing to put in an enormous amount of time and research. I'll leave you with a few other pertinent white papers and final words of wisdom to mull over.

* Debug drawing will be your BEST FRIEND.
* Consider writing a quick function to export your graph to a wavefront obj at any step, particularly for the triangulation to ensure you aren't accidentally flipping winding order, and again after you split the mesh into two parts. The internal edges are TRICKY to get right.
* Visual Studio can be used to quickly open and view .obj files and can even detect changes to those files so you don't have to open them again
* Use a whiteboard to draw the Half-Edge diagrams with labels, doing it in your head is an easy way to drive yourself insane. I still have occasional triangle-related nightmares.

http://www.dainf.ct.utfpr.edu.br/~murilo/public/CAD-slicing.pdf https://pdfs.semanticscholar.org/8bad/3d8fb0577d05adb2d5b4b993b90c4e63ec9f.pdf https://www.ntu.edu.sg/home/asjfcai/Euro10\_Geodesic.pdf

# Answer
> 2 votes
i dont think there is anyone that can tell you how this exactly works. there should be lots of elements to make this happen but i can give some guessing.

1) if you look for cutting for that is in **metal gear rising** the sward works like a plane equation with borders. you can make a calculation for vertices Up and Down of that plane. then do a capping algorithm to cover cut. but certainly lots of other things should be handled to make it work properly.

2) it seems in your example, there is a plane with a fence texture over it. maybe on shooting the lazer gun, it raycasts and only removes the nearest polygun and after that a calculation that seperated polygons did make a whole new model, so just adding something like rigidbody and make it fall.

3) in image processing there are region detection algorithms. maybe another binary image is calculated in hidden mode that whole page is white and when lazer is being shot to it, pixels turn to black. so after that close region can be calculated.

remember what is say is based on guessing and there is much distance from implementation.

---
Tags: unity, 3d-meshes, mesh
---


# Question
Title: How to make a smooth projectile in roblox?
I am trying to make a projectile (Energy ball) for my game. I am using body velocities, but the issue is is that it seems laggy. I shoot it then half a second through flight it seems to stop in mid air for a quarter of a second then continue. This only happens the first minute of playing.

Here is my code:

```
local Motion = Instance.new("BodyVelocity", Ball)
Motion.Velocity = ((MouseClickLocation - Player.Character.HumanoidRootPart.Position).Unit*100)

```

Why is the described behavior happening and how can I make it never happen?

# Answer
It is a lot more complicated than that. As the ball travels out far enough away from the player, the network ownership changes from the client to the server. This produces very short, laggy moments. Don't ask me why this happens. All I know is that this can be fixed like this: (I am assuming your using a client activated remote event)

```
--Where ever you try to put the Motion in, replace that with this
Ball:SetNetworkOwner(Player --[[arg from OnServerEvent]])
RemoteEvent:FireClient(Player, Ball --[[so the client knows what to add the velocity to]])

--In the local script
RemoteEvent.OnClientEvent:Connect(function(Ball)
    local Velocity = Instance.new(BodyVelocity, Ball)
    Velocity.MaxForce = Vector3.new(math.huge, math.huge, math.huge)
    Velocity.Velocity = game.Players.LocalPlayer.Character.PrimaryPart-game.Players.LocalPlayer:GetMouse().Hit.P
end)

```
> 0 votes

---
Tags: physics, performance, projectile-physics, lag, roblox
---


# Question
Title: How to draw the editor's camera position in play mode Unreal?
The blue camera that is drawn for the CameraComponent in the editor.

My intended usage is that when playing a third person template, ejecting from the pawn and then selecting it, will show the Camera debug asset instead of just the camera boom.

So in the above picture of the editor mode, the camera attached to the pawn is visible.

Yet when in play mode. Ejecting from the pawn and selecting the pawn shows only the camera boom (the red line) and not the camera 'debug asset' used in the editor.

# Answer
> 0 votes
Edited with the correct answer:

I am starting with a fresh third person template project, and moving from there.

1. Select the ThirdPersonCharacter in the Editor Viewport
2. Click the blue Edit Blueprint button under the Details panel (below the World Outliner) and select Add or Edit Script, which opens the blueprint editor
3. If it's not already visible, click the Window tab at the top and make sure there is a checkmark near Components.
4. Select the FollowCamera component, which should open up the Details page on the right
5. Scroll down the details panel to the Events section, and click the big green plus sign next to On Component Activated
6. On the background next to the event node that was just added to the blueprint editor, right-click to open the context menu, and in there type Hidden.
7. Select the item labeled "Set Hidden In Game (FollowCamera)" and adjust the nodes so you can see it.
8. Drag the white bar with the Exec tooltip from the "On Component Activated" event over to the input for the "Set Hidden In Game" node.
9. Tick the lower right checkbox located in the "Set Hidden in Game" node labeled "Propagate to Children". The check box above it should remain unticked.
10. Save, compile and test your game. It should now display the blue camera when ejecting from the pawn.

Here is a picture of the configured nodes.

Thank you for the learning experience. I worked for Epic Games on the unreal engine geometry team and never once got the opportunity to play with the engine.

---
Tags: camera, unreal
---


# Question
Title: Unity - change only z axis rotation to 0
I have a child where I want the `rotation` to work like `(parentRot, parentRot, 0)`.

So first I set its `localRotation` to 0, meaning it will get the parents rotation: `child.localRotation = Quaternion.identity;`

But how can I make sure the world rotation (not local) value of the z axis stays at 0?

# Answer
Here's another way to think of it:

First, we figure out which direction in the parent space points toward world "up":

```
Vector3 parentSpaceUp = transform.parent.InverseTransformDirection(Vector3.up);

```

Then we orient ourselves to point forward in the parent's local coordinate, while aligning our own up vector as close as possible to this vertical:

```
transform.localRotation = Quaternion.LookRotation(Vector3.forward, parentSpaceUp);

```

Wherever possible, I like to use direction vectors and quaternions over Euler angles, both to avoid unnecessary trig functions, and also to make sure the code doesn't exhibit bugs at edge cases where the Euler angles wrap around.
> 1 votes

# Answer
I have no idea what you're trying to do, but this does precisely what you described.

```
public class AxisLock : MonoBehaviour
{
    void Update()
    {

        Vector3 target;
        target.x = transform.parent.eulerAngles.x;
        target.y = transform.parent.eulerAngles.y;
        target.z = 0;
        transform.rotation = Quaternion.Euler(target);
    }
}

```
> 0 votes

---
Tags: unity, unityscript
---


# Question
Title: How does the deployment of server look like
I´m kinda new to these networking stuff, but basically managed to finish server to handle client requests(wan´t it to handle connections to game and help the clients update the game and stuff). I got it working on my localhost (sending files/packets on same PC is working already - i just launch server app and then client app). However, I still wonder how it works in real, if I want to access my server from global network. I understand that I need a hosting. So to sumarize my thoughts:

1. Find hosting - As the server,client or engine code is in C++, do I have to look for hostings specifically for C++ applications?
2. Now the server works this way: I set up IP+port, that clients use for their connection. Launch the server so now its accessible. How do I launch the server application when on hosting? Is there some kind of interface, for example if I want to relaunch the application(called for example server.exe).
3. As I said - clients need to know servers IP and port. So the hosting will give me IP+port that will be accessible for my clients (and I use this IP also on my server)?

I know these questions are kinda basic, but networking is new world for me and deployment of the networked stuff is also a part of it, so would like to understand the proccess.

# Answer
This is what I know about Servers. I have my own Server, but never cared about single Application hosting. There also could be other possibilities.

1. It is not important that it's C++. It is important, for which operating system you compile it. There are good chances, that your server code **could** be platform independent. (Did you use any Windows libraries?) There are hosting Services where you pay for CPU and RAM usage and others where you have your own server with fixed CPU and RAM and fixed price. You can choose between Linux and Windows Servers.
2. The Interface depends on the Service you use. If it's some service for gameservers or something similar, there is probably a nice web interface. If it's a so called root server where you have total control over the Server, chances are, you will do everything via command line. (There are probably also root servers with GUI-Webinterfaces?)
3. IP + Port: Think of the Server as an other Computer. It has a static IP. If you don't change the Server, your Clients know the IP as it will stay the same. The Port is more interesting. If you have your own root Server, select the port you like. The application hosting services probably give you a Port. (never used such services)

I hope this helped a bit.
> 1 votes

---
Tags: c++, networking, client-server, server, hosting
---


# Question
Title: What´s wrong with my Frustum Culling implementation?
I´m struggling with a weird problem since hours. Ive implemented frustum culling with the help of online articles and a book. The problem is that the objects are not culled correctly. I´m using Spheres, they are scaled correctly - I just dont know what´s wrong!

Ill just show you some code:

First my frustum is just an array of six planes, and a plane is just a Vector4 with x,y,z and w!

Check if sphere is inside frustum. Maybe the problem lies here:

```
bool Frustum::checkSphere(const PrimitiveSphere& sphere, const WorldPoint& were) const noexcept {

    const auto pos = were.position + sphere.center;
    for (const auto& plane : planes) {

        const float radius = sphere.radius * were.scale.unitMagnitude(); //unit magnitude is just x + y + z / 3
        const float dist =
            plane.x * pos.x +
            plane.y * pos.y +
            plane.z * pos.z + plane.w;
        if (dist < -radius)
            return false;
    }
    return true;
}

```

Build my frustum each frame from ViewProjectionMatrix

```
void Frustum::fromViewProj(const float* const vp) noexcept {

    const float xw = vp[3];
    const float yw = vp[7];
    const float zw = vp[11];
    const float ww = vp[15];

    const float xz = vp[2];
    const float yz = vp[6];
    const float zz = vp[10];
    const float wz = vp[14];

    PrimitivePlane& near = planes[0];
    PrimitivePlane& far = planes[1];
    PrimitivePlane& left = planes[2];
    PrimitivePlane& right = planes[3];
    PrimitivePlane& top = planes[4];
    PrimitivePlane& bottom = planes[5];

    near.x = xw - xz;
    near.y = yw - yz;
    near.z = zw - zz;
    near.w = ww - wz;

    far.x = xw + xz;
    far.y = yw + yz;
    far.z = zw + zz;
    far.w = ww + wz;

    const float xx = vp[0];
    const float yx = vp[4];
    const float zx = vp[8];
    const float wx = vp[12];

    left.x = xw - xx;
    left.y = yw - yx;
    left.z = zw - zx;
    left.w = ww - wx;

    right.x = xw + xx;
    right.y = yw + yx;
    right.z = zw + zx;
    right.w = ww + wx;

    const float xy = vp[1];
    const float yy = vp[5];
    const float zy = vp[9];
    const float wy = vp[13];

    top.x = xw + xy;
    top.y = yw + yy;
    top.z = zw + zy;
    top.w = ww + wy;

    bottom.x = xw - xy;
    bottom.y = yw - yy;
    bottom.z = zw - zy;
    bottom.w = ww - wy;

    for (auto& plane : planes)
        plane.normalize();
}

```

Now the problem is, the draw calls are the same if all the orbs are in my frustum or only 5. But when I rotate my camera slowly a bit the drawcalls are decreasing a bit. WTF? Just look for yourself (the red rect marks the drawcalls):

Does anybody have an idea what it could be? Or is my code okay and the problem is somewere else? :/

# Answer
You seem to have implemented a basic frustum culling. But unfortunately, frustum culling is an inaccurate method for large objects in view frustum. Its only culling objects completely outside the bounds and including everything which is either intersecting or inside. This introduces some false positives i.e. objects that are not in your practical view but are intersecting the frustum (intersecting with near and far plane) regardless. Prune these scenarios based on your practical viewing range to fix the problem.

You can find some really good illustration and the solution about it in the following posts- https://cesium.com/blog/2017/02/02/tighter-frustum-culling-and-why-you-may-want-to-disregard-it by Austin Eng at Cesium and http://www.iquilezles.org/www/articles/frustumcorrect/frustumcorrect.htm by Inigo Quilez.
> -1 votes

---
Tags: mathematics, bounding-boxes, frustum, frustum-culling, bounding-spheres
---


# Question
Title: (Game Maker Studio)How to make an alarm that starts & loops in the step event?
I'm making an enemy object where the enemy will go on a specific path to patrol.Then he will stop at a certain point to look around for the player.

I planned to make him change his sprite direction every 2 seconds(Enemies vision's for another day)but i seems to stuck here.I want the alarm to start as soon as he stops in the middle of the path,but i don't know how to activate the alarm in the step event.

Any ideas ?

# Answer
> 0 votes
Normally, setting an alarm is just about giving `Alarm[0]` a value it needs to count down. But in the Step Event, it would reset the value constantly. So it needs a statement where it only goes through setting the alarm once.

What I use is a switch statement with a new variable for each behavior it does. which I prefer to call them 'states'.

For example, in the Create event, you'll define a state. and write down the meaning next to it.

```
state = 0; //0 = walking, 1 = running.

```

It's also fine to use Enums for this once you're familiar with it. But I prefer ints to get started.

Then, in the Step Event:

```
switch (state)
{
   case 0: //walking
   {
      //walks around.
      break;
   }
   case 1:
   {
      //looks around
      break;
   }
}

```

Then, for example in the Alarm\[0\] event (Which triggers once the alarm reaches 0):

```
switch (state)
{
   case 0: //walking
   {
      alarm[0] = 2; //example of new value
      state = 1;
      break;
   }
   case 1:
   {
      alarm[0] = 2; //example of new value
      state = 2;
      break;
   }
}

```

Personally, I prefer custom variables to define counters and timers, as you can write these out in the step event completely, which I could try to explain later.

Hope it helps you out.

# Answer
> -1 votes
Yes; using a custom counter was the way to go. I looked it up, and made my own counter.

Create:

```
sprar[0] = sprscout;
sprar[1] = sprscout_up;
sprar[2] = sprscout_down;

spcounter = 0;

```

Step:

```
 switch(state){
     case 0: spd = 0;
     counter += 1;
     if(counter >= room_speed*3){
        spcounter ++;
        sprite_index = sprar[spcounter];
     } break;
}

```

The sprite changes to up after 3 seconds, and then down immediately. The error occurs right after the sprite changes into the last sprite of the array:

> FATAL ERROR in action number 1 of Step Event0 for object obj\_EBase: Push :: Execution Error - Variable Index \[0,3\] out of range \[1,3\] - -1.sprar(100019,3) at gml\_Object\_obj\_EBase\_StepNormalEvent\_1 (line 8) - sprite\_index = sprar\[spcounter\];

Can you look into this for me ?

---
Tags: game-maker
---


title: How to make changes to Pawn.cpp Unreal?

text:
# Question
Title: How to make changes to Pawn.cpp Unreal?
I am trying to figure out a problem related to CableComponents.

As part of my learning and problem identification I'm trying to place some UE\_LOGs/Debug Messages within Pawn.cpp and CableComponent.cpp

These changes are not reflected when the c++ code is compiled within unreal. which is consistent with Unreal only building project code.

So My question is, how can I make these changes to the source code and have them be used?

Alternatively, is there a better way to do what I'm trying to do?

**The reason i'm trying to do this**

* I'm trying to figure out how often the dynamic data of UCableComponent is recalculated compared to the rendering update of APawn.

# Answer
If you make changes to the code of the Unreal Engine you have to recompile the Unreal Engine. See the documentation to find out how to do this.
> 0 votes

---
Tags: c++, unreal, source-code
---


title: How to resolve a collision in 2D game?

text:
# Question
Title: How to resolve a collision in 2D game?
At the moment I have built a custom Vector2 class and have a character object that has an acceleration vector (modified by vector forces), a velocity, and a position as well as bounding boxes for every entity within the scene.

Right now my physics works quite well and the character falls and moves with gravity and player input and is able to detect when it collides with another rectangle bounding box shown here:

```
 void
    PhysicsEngine::TimeStepProcess(float deltaTime,
        Entity* character, std::vector<Walls*> walls,
        double screenWidth, double screenHeight,
        int timeStep)
    {
        double processedDeltaTime = deltaTime / timeStep;

        //Process entire physics engine multiple times per step with
        //a smaller deltaTime for more accuracy
        for (int i = 0; i < timeStep; ++i) {
            //Add forces back per frame
            ComputeForceAndTorque(character);
            //ApplyForce(character, gravity);
            ApplyForce(character, character->GetForce());

            //Calculate and resolve collisions
            ResolveCollisions(character, walls, processedDeltaTime);

            //Set angular acceleration
            angularAcceleration = character->GetTorque() / character->GetIntertia();

            //Add Velocity per frame for linear and angular
            Vector2::ScaleMult(*character->GetVelocity(), *linearAcceleration, processedDeltaTime, Vector2::ADDITON);
            *character->GetAngularVelocity() += angularAcceleration * processedDeltaTime;

            //Add displacement per frame for linear and angular
            Vector2::ScaleMult(*character->GetPos(), *character->GetVelocity(), processedDeltaTime, Vector2::ADDITON);
            *character->GetAngle() += *character->GetAngularVelocity() * processedDeltaTime;

            //Add friction
            CalculateFriction(character, processedDeltaTime);

            //Clear forces per frame
            Vector2::ScaleMult(*linearAcceleration, *linearAcceleration, 0, Vector2::EQUAL);
        }

        //Log
        LogCurrent(character);
    }

```

With the collision being detected quite accurately here:

```
void
PhysicsEngine::ResolveCollisions(Entity* character, std::vector<Walls*> walls, double deltaTime)
{
    double minDistanceFromObject = 1; //pixels

    //Iterate through all walls
    vector<Walls*>::iterator wallIter;
    for (wallIter = walls.begin(); wallIter != walls.end(); ++wallIter) {
        //Broad
        if (character->GetCollisionBox()->CheckCollision((*wallIter)->GetCollisionBox())) {
            //Resolve collision
        }
    }
}

//Does this rectangle contain other rectangle
bool
Rectangle::CheckCollision(Rectangle* other) {
    //The sides of the rectangles
    int leftA, leftB;
    int rightA, rightB;
    int topA, topB;
    int bottomA, bottomB;

    //Calculate the sides of rectangle A
    leftA   = static_cast<int>(this->X());
    rightA  = static_cast<int>(this->X() + this->W());
    topA    = static_cast<int>(this->Y());
    bottomA = static_cast<int>(this->Y() + this->H());

    //Calculate the sides of rectangle B
    leftB   = static_cast<int>(other->X());
    rightB  = static_cast<int>(other->X() + other->W());
    topB    = static_cast<int>(other->Y());
    bottomB = static_cast<int>(other->Y() + other->H());

    //If any of the sides from rectangle A are outside of B
    //Then there is no possible way the two boxes are colliding
    if (bottomA <= topB) {
        return false;
    }
    if (topA >= bottomB) {
        return false;
    }
    if (rightA <= leftB) {
        return false;
    }
    if (leftA >= rightB) {
        return false;
    }

    //If none of the sides of the primary rectangle are outside of other
    //Then there must be a collision of some sort
    return true;
}

```

But my vector math is quite shaky and I have no idea how to resolve these collisions and stop the character moving through surfaces. I want to be able to walk along floors and collide with any surfaces realistically. I have now been trying to accomplish this for over a week and have gone through at least 20-30 posts, comments, articles and questions about this and cannot understand how it works or how to implement it.

Can someone please help me with the coding aspect of this?

# Answer
> 0 votes
I get this question a lot at my school's physics club. As an immediate answer, check out the source code from Box2D-lite, which is an educational engine designed **exactly** for this purpose, and is provided by Erin Catto, one of the makers of Box2D. According to him, he recently updated his box2d lite implementation. What you'll find in here is the result of an incredible amount of research and planning rolled up into a small, easy to follow codebase. While you're reading that, I highly encourage you to examine the following presentations which outline the mathematical details pertaining to your question, as I could not explain it all in one go.

Having tried collision resolution before, I can tell you what happens when trying to solve the problem of resolution on your own using kinematic equations alongside the collision equations; you will wind up with tolerable results at first, but you will find that your boxes **do not stack**, and multibody collisions are a nightmare, and when you get to apply the rotational aspects of collision resolution it will get even harder.

This is why I recommend these resources first; the task of realtime rigid body simulation in games is a non-trivial problem, and there are many many ways of going about solving them. There are tried and true methods such as sequential impulse solvers (which I believe Erin Catto came up with and demonstrates in his engine) or projected gauss-siedel solvers which are industry standards when it comes to this. Currently PhysX, for example, employes a mysterious solver that we're all waiting for documentation on called the Temporal Gauss-Sidel solver, which appears to have made some stability improvements.

Resources:

Here is the file containing the code you're looking for, but the setup for an iterative solver like this requires a bit of extra design in addition to what you've got. Most importantly caching contacts so they persist over frames is tricky, but for most comprehensive implementations, it's a must.

http://box2d.org/files/GDC2006/GDC2006\_Catto\_Erin\_PhysicsTutorial.ppt

http://www.chrishecker.com/images/e/e7/Gdmphys3.pdf

https://www.toptal.com/game/video-game-physics-part-iii-constrained-rigid-body-simulation

http://box2d.org/files/GDC2011/GDC2011\_Catto\_Erin\_Soft\_Constraints.pdf

http://web.archive.org/web/20180115094936/https://www.randygaul.net/2013/03/27/game-physics-engine-part-1-impulse-resolution/

http://twvideo01.ubm-us.net/o1/vault/gdc2013/slides/822403Gregorius\_Dirk\_TheSeparatingAxisTest.pdf

http://box2d.org/files/GDC2013/GDC13\_vandenBergen\_Gino\_Physics\_Tut.pdf

https://gamedevelopment.tutsplus.com/tutorials/how-to-create-a-custom-2d-physics-engine-friction-scene-and-jump-table--gamedev-7756

http://box2d.org/files/GDC2013/Tonge\_Richard\_PhysicsForGame.pdf

http://box2d.org/files/GDC2005/IterativeDynamics.pdf

(i believe Erwin Coumans did a lot of work regarding Featherstone, possibly with Rockstar games in developing their fabulous ragdoll implementation alongside the Euphoria engine) http://box2d.org/files/GDC2014/ErwinCoumans\_ExploringMLCPSolversAndFeatherstone.pdf

# Answer
> 0 votes
In particular, for as simple as a possible solution, I could just use this code and make sure that the second object has 0 velocity and infinite mass or has a restitution coefficient of 0.

```
// j = -(1 + epsilon) * N dot Vrel
// -------------------------------
//        invM_1 + invM_2
void Manifold::ApplyImpulse( void )
{
  Vec2 rv = B->m_velocity - A->m_velocity;
  real contactVel = Vec2::DotProduct( rv, normal );

  // Do not resolve if velocities are separating
  if(contactVel > 0)
    return;

  // Calculate restitution
  real e = std::min(A->m_material.restitution, B->m_material.restitution);

  // Calculate impulse scalar
  real j = -(1.0f + e) * contactVel;
  j /= A->m_massdata.inv_mass + B->m_massdata.inv_mass;

  // Apply impulse
  Vec2 impulse = j * normal;
  A->m_velocity -= A->m_massdata.inv_mass * impulse;
  B->m_velocity += B->m_massdata.inv_mass * impulse;
}

```

---
Tags: c++, collision-resolution, sdl2
---


title: Box2D Weird collision behavior

text:
# Question
Title: Box2D Weird collision behavior
I'll let the gif speak first.  As you can see, the small cube just kinda floats there like it has a forcefield. This weird glitch only happens with small cubes, smaller than 60 pixels for some reason. It's 32x32. And I have no clue why this happens, at all. I've debugged and debugged, but I am at my end.

Box class

```
//Header
class Box
{
public:
    Box(const std::string& _textureName, int _x, int _y, int _width, int _height, SDL_Renderer* _renderer, b2World* _world);

    void draw(SDL_Renderer* _render) const;
    void update();
private:
    SDL_Texture* m_image;
    SDL_Rect m_bounds{};

    b2PolygonShape m_polygon;
    b2FixtureDef m_fixture;
    b2BodyDef m_bodyDef;
    b2Body* m_body;
};

//CPP
Box::Box(const std::string& _textureName, int _x, int _y, int _width, int _height, SDL_Renderer* _renderer, b2World* _world) : m_image(IMG_LoadTexture(_renderer, _textureName.c_str()))
{
    SDL_QueryTexture(m_image, nullptr, nullptr, nullptr, nullptr);

    m_bounds.x = _x;
    m_bounds.y = _y;
    m_bounds.w = _width;
    m_bounds.h = _height;

    m_bodyDef.type = b2_dynamicBody;
    m_bodyDef.position.Set(_x / World::PPM, _y / World::PPM);
    m_body = _world->CreateBody(&m_bodyDef);

    m_polygon.SetAsBox((_width / World::PPM) / 2.0f, (_height / World::PPM) / 2.0f);

    m_fixture.shape = &m_polygon;
    m_fixture.density = 1.0f;
    m_fixture.friction = 0.3f;

    m_body->CreateFixture(&m_fixture);
}

void Box::draw(SDL_Renderer* _render) const
{
    SDL_Point center;
    center.x = m_bounds.w - (m_bounds.w / 2);
    center.y = m_bounds.h - (m_bounds.h / 2);

    const auto angle = (180 * m_body->GetAngle()) / M_PI;

    SDL_RenderCopyEx(_render, m_image, nullptr, &m_bounds, angle, &center, SDL_FLIP_NONE);
}

void Box::update()
{
    m_bounds.x = m_body->GetPosition().x * World::PPM;
    m_bounds.y = m_body->GetPosition().y * World::PPM;
}

```

World class

```
//Header
class World
{
public:
    static constexpr float PPM = 32.0f;
    static constexpr int VELOCITY_ITERATIONS = 5;
    static constexpr int POSITION_ITERATIONS = 8;

    World();

    void update();
    void render(SDL_Renderer* m_renderer);

    void createBox(const std::string& _textureName, int _x, int _y, int _width, int _height, SDL_Renderer* _renderer);
private:
    float m_timeStep;

    b2World m_world;
    b2BodyDef m_groundBodyDef;
    b2Body* m_groundBody;

    std::vector<Box*> m_boxes{};
};

//CPP
World::World() : m_world(b2Vec2(0.0f, 9.8)), m_timeStep(1.0f / 60.0f)
{
    m_groundBodyDef.position.Set(400.0f / PPM, 590.0f / PPM);
    m_groundBody = m_world.CreateBody(&m_groundBodyDef);

    b2PolygonShape groundBox;
    groundBox.SetAsBox(400.0f / PPM, 20.0f / PPM);
    m_groundBody->CreateFixture(&groundBox, 2.0f);
}

void World::update()
{
    m_world.Step(m_timeStep, VELOCITY_ITERATIONS, POSITION_ITERATIONS);
    for (auto box : m_boxes)
    {
        box->update();
    }
}

void World::render(SDL_Renderer* m_renderer)
{
    for(auto box : m_boxes)
    {
        box->draw(m_renderer);
    }
}

void World::createBox(const std::string& _textureName, int _x, int _y, int _width, int _height, SDL_Renderer* _renderer)
{
    m_boxes.push_back(new Box(_textureName, _x, _y, _width, _height, _renderer, &m_world));
}

```

If anybody has any idea why this might happen, please let me know. Thank you.

# Answer
Problem solved: the error was in drawing the boxes all along. The way Box2D returns positions is by returning the center of an object, and not the upper-left corner. So all I had to do was deduct half the width and height from my texture's position to draw it in the right spot.

```
    m_bounds.x = m_body->GetPosition().x * World::PPM;
    m_bounds.y = m_body->GetPosition().y * World::PPM;

```

becomes

```
    m_bounds.x = m_body->GetPosition().x * World::PPM - (m_bounds.w / 2.0f);
    m_bounds.y = m_body->GetPosition().y * World::PPM - (m_bounds.h / 2.0f);

```
> 1 votes

---
Tags: c++, collision-detection, box2d, sdl2
---


# Question
Title: How do I efficiently determine what objects are visible to a camera?
I want to call the rendering methods of only the game objects that are visible. How can I efficiently determine which objects or tiles are within the camera's rendered region?

# Answer
You are talking about tiles, therefore i'm assuming you are talking about a 2d game.

You need to have the camera position in the world like so:

```
int cameraX = 0;
int cameraY = 0;

```

You also need to have the camera size, which is usually the same as your viewport size:

```
int cameraWidth = viewportWidth;
int cameraHeight = viewPortHeight;

```

Then you can find out if a quad is inside the camera by using simple AABB collision check:

```
public boolean isInsideCamera(int x, int y, int width, int height) {
    if(x < cameraX + cameraWidth && x > cameraX) {
        if(y < cameraY + cameraHeight && y > cameraY) {
            return true;
        }
    }
    return false;
}

```

NOTE: The above example only works if the quad is completly inside camera. For proper AABB intersection, try here: What is the fastest way to work out 2D bounding box intersection?
> 1 votes

# Answer
If the tiles are stored in a linear way( sorted so that the top left tile is first and the bottom right is last, or some other reasonable order ), you can access the array / list by an index that describes tiles that only lay within the screen bounds. This will be a bit faster than doing a bounds check every tile.

```
Tile[,] tiles = new Tile[x,y];

```

We can now access the tiles in this way:

```
for( int x = camera.x / tileWidth; x < ( camera.x + camera.width ) / tileWidth; x++ )
{
    for( int y = cameray / tileHight; y < ( camera.y + camera.height ) / tileHeight; y++ )
    {
        // Access the tiles that are in the screen here.
    }
}

```

I believe this may be the fastest way we could do it. If the tiles aren't in an array, however, you can use the bounds checking method described by Lasse. If that's not fast enough, you could use a quadtree. This data structure allows use to quickly check where things are in the world.

Read about it here: http://en.wikipedia.org/wiki/Quadtree

It's a pretty simple structure to create and helps in far more than just object culling.
> 1 votes

# Answer
Your question doesn't specify 2d or 3d but if it's 2d the best way would probably be to use a spatial hash map. Essentially a spatial hashmap stores objects in buckets like a usual hashmap, but instead of storing based on a hash it stores based on it's position in space. Objects that span multiple buckets are placed in every bucket they overlap. so because things that are near each other are stored in the same bucket you can just pass in a position and get the objects near it. Check out this article on spatial hash maps for more info: https://www.gamedev.net/articles/programming/general-and-gameplay-programming/spatial-hashing-r2697/
> 0 votes

# Answer
You could always start with frustrum culling as it's quite simple to implement and fairly straight forward via extracting the information you already need to compute (your model view projection matrix). It doesn't account for objects which may be blocking your view, but it would provide the correct geometric approach. If a vertex passes your frustrum culling, it is guaranteed in your field of view.

Also, the **SIMPLEST** test would be to get the signed distance from the object in question to the plane formed by your camera's position and view direction. Obviously, if the dot product is negative with all vertices, then it's in the opposite direction and can't be seen.

Otherwise, I recommend using a balanced bounding-volume hierarchy.
> 0 votes

---
Tags: rendering, camera, optimization
---


# Question
Title: The camera goes up and down when following a rolling sphere
I have this `CameraController` script attached to my camera, to follow a sphere that moves using WSAD.

```
public class CameraController : MonoBehaviour
{

    public GameObject player;

    private Vector3 offset;
    // Start is called before the first frame update
    void Start()
    {
        offset = transform.position - player.transform.position;
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        transform.position = player.transform.position + offset;
    }
}

```

It follows the object fine, but it bounces up and down on the Y axis when it's moving, and I don't know how to stop the camera from doing it.

# Answer
You could just lock the height of the camera to a value. This should stop bouncing.

```
public GameObject player;
float height;

private Vector3 offset;
// Start is called before the first frame update
void Start()
{
    offset = transform.position - player.transform.position;
    height = transform.position.y;
}

// Update is called once per frame
void FixedUpdate()
{
    transform.position = player.transform.position + offset;
    transform.position.y = height;
}

```

I hope this might help you
> 0 votes

# Answer
i dont know how your ball is controlled but i assumed it is controlled by rigidBody physics. its obvious that for something that is controlled by physics you have some noisy jittery moves. your code works like attaching or childing camera to ball without deriving rotation. so camera will have the same jittey moves.

best solution is to lerp camera to wanted position instead of stick it to exact position. your update callback will be like this:

```
float speed=0.1f;
 void FixedUpdate()
    {
        transform.position = Vector3.MoveTowards(transform.position ,player.transform.position + offset,speed);
    }

```
> 0 votes

---
Tags: unity, camera, movement, sphere, axis
---


# Question
Title: Converting a table into a formula / equation
I need help to figure out the formula / equation or at least the growth rate based on this table. All I can see is that the base stat is 12 as STAT2 = 2 x base and STAT3 = 5 x base.

# Answer
I tried to figure this out by creating an MS Excel spreadsheet and experimenting with different formulas until I found one which works.

A formula which approximates the values in that table very closely seems to be `a + b * (level / 10)²` with the following values for a and b:

```
        a    b
STAT1  12   10
STAT2  24   20
STAT3  60   50

```

It is not an *exact* fit. the results for level 100 are 1012, 2024 and 5060 respectively. But this is likely close enough for your purpose.

If the table comes from a different game and you want to clone it, then you shouldn't try to copy them too closely anyway in order to avoid copyright problems.

If this is a table from your own game and you are trying to reverse-engineer it because the knowledge how to create it was lost, then a 0.06% deviation is unlikely to turn your game balance upside down. (but on the other hand, I know absolutely nothing about your game mechanics, so I can't be *completely* certain about that)
> 5 votes

# Answer
The best fit I found was via cubic fit (least squares). the last two stats were almost spot on entirely, and the first one was only about 99.98% fit or something which yielded the following results:

```

// let x represent the level, and y represent the corresponding stat's output

// Stat1: y = -3.99983×10^-6 x^3 + 0.100512 x^2 - 0.00664512 x + 11.5483
// Stat2: y = -1.57334×10^-8 x^3 + 0.200103 x^2 + 0.00463321 x + 23.5259
// Stat3: y =  0.0000107514 x^3 + 0.498893 x^2 + 0.0373237 x + 59.5811

```

if you round the resulting y quantity to its nearest integer, you will find the results extremely accurate.
> 0 votes

---
Tags: mathematics, rpg
---


# Question
Title: What should the Z coordinate be after transformed by the projection matrix?
I'm working on an OpenGL 1.x implementation for the Sega Dreamcast. Because the Dreamcast didn't have any hardware T&L the entire vertex transformation pipeline has to be done in software.

What also has to be done in software is clipping to the near-Z plane as failure to clip results in the polygon being dropped entirely from rendering by the hardware.

I'm having some trouble getting the transform -\> clip -\> perspective divide process working correctly and basically I can sum up the problem as follows:

* I transform polygon vertices by the modelview and projection matrices
* I clip each polygon against the W = 0.000001 plane
* This results in new vertices on the near plane with a W of 0.000001, but a Z which is *twice the near plane distance*
* At perspective divide vertex.z /= vertex.w results in an extreme value because we're dividing a Z value (e.g. 0.2) by 0.000001

Something seems very wrong here. The projection matrix is being generated in the same way as described in the glFrustum docs.

So my question is, if I have a coordinate on the near plane, should its Z value be zero after transform by the projection matrix or should it be the near-z distance, or something else?

After clipping polygons to the W = 0.000001 plane, should the generated Z coordinates be -0.000001?

*Update:*

Here is the projection matrix as calculated by: `gluPerspective(45.0f, 640.0f / 480.0f, 0.44f, 100.0f);`

```
1.810660 0.000000 0.000000 0.000000
0.000000 2.414213 0.000000 0.000000
0.000000 0.000000 -1.008839 -0.883889
0.000000 0.000000 -1.000000 0.000000

```

Does this look correct? It's the value in the right-hand column I'm not sure about...

# Answer
Well that looks right to me. your projection matrix should be bringing you into normalized device coordinates which range from \[-1,1\], correct? The Z value should represent your depth and is used by the depth buffer, if I'm not mistaken. If you're in 2D using 4x4 matrices, I would imagine you should expect to see 0 in every Z output, as that zero should cancel out any final results, and if you aren't then I would certainly track down where that Z value is creeping from.

https://www.scratchapixel.com/lessons/3d-basic-rendering/perspective-and-orthographic-projection-matrix
> 1 votes

---
Tags: opengl, matrix, transformation
---


# Question
Title: Light position is always on the origin point therefore the diffuse and specular do not work
I am newbie to opengl. I did the tutorial by learnopengl. I have a strange problem when I was trying to do the light effect (ambient, diffuse and specular). For the diffuse, the effect appears on an incorrect surface, and it seems like the light position is always local on the origin point even if I change its position (the right cube position and the light position as the image shows):

I also tried to add the specular in a fragment shader but it also only appears on the left surface of the cube (the green arrow, that surface should not be lightened because now the vector is parallel the surface, so theoretically that surface should be black). I have passed the light position and camera position to the fragment shader of the cube (also the light fragment shader):

```
        glm::vec3 lightPos(0.0f, 2.5f, 3.0f);
        cubeShader->use();
        cubeShader->setVec3("lightPos", lightPos);
        cubeShader->setVec3("cameraPos", secondCamera->Position);

```

and the fragment shader is, as simply as the tutorial's example:

```
    out vec4 FragColor;
    in vec3 Normal;
    in vec3 FragPos;
    in vec3 lightPos;
    uniform vec3 cameraPos;
    uniform vec3 lightColor;
    uniform vec3 objectColor;
    void main()
    {

        //ambient CONDITION
        float ambientStrength = 0.1;
        vec3 ambient = ambientStrength * lightColor;
        //diffuse CONDITION
        vec3 norm = normalize(Normal);
        vec3 lightDirection = normalize(lightPos - FragPos);
        float diff = max(dot(norm, lightDirection), 0.0);
        vec3 diffuse =  diff* lightColor;
        //specular CONDITON
        float specularStrength = 0.5;
        vec3 viewDirection = normalize(cameraPos- FragPos);
        vec3 reflectDirection = reflect(-1.0 * lightDirection, norm);
        float spec = pow(max(dot(viewDirection, reflectDirection), 0.0), 32);
        vec3 specular = specularStrength * spec * lightColor;
        //Result
        vec3 Result = (ambient + diffuse + specular) * objectColor;
        FragColor = vec4(Result, 1.0f);
}

```

Even when I add the specular, the specular appears on the incorrect surface. I found this answer, and I thought the cause might be the transformation of the model from camera to world space by using inverse and transpose:

However I did this in my vertex shader:

```
    layout (location = 0) in vec3 aPos;
    layout (location = 1) in vec3 aNormal;
    out vec3 Normal;
    out vec3 FragPos;
    uniform mat4 model;
    uniform mat4 view;
    uniform mat4 projection;
    uniform vec3 cPosition[10];

    void main()
    {
    vec3 newPosition = cPosition[gl_InstanceID];
    gl_Position =  projection * view  * model * vec4(aPos + newPosition,1.0);
    FragPos = vec3(model * vec4(aPos +newPosition,1.0));
    Normal = mat3(transpose(inverse(model))) * aNormal;
    }

```

So, in summary, the problem is that when the light position changes, the effect will not change because it is only controlled by the "ghost" light which is located on the origin point. Could you guys please tell me, why there is a light on the origin? Thanks!

# Answer
I believe you may be experiencing what happens when you use quantities belonging to distinctly different spaces. I have a number of questions for you which will hopefully lead you to your answer.

First, why are you using the inverse transpose of your model matrix to transform your normal? assuming your model matrix is your ObjectSpace =\> WorldSpace transformation, and your normal should be in object space, simply multiplying your normal by your Model matrix should map your normal into World Space.

Second, what's the deal with newPosition? It's not clear to me what this is for, but you appear to be translating your ObjectSpace quantities, which means your pipeline from ObjectSpace =\> ModelSpace =\> ViewSpace =\> NDC coordinates is no longer valid, as your ObjectSpace vertex is no longer centered at the origin? gl\_Position should be the MVP * SomeVertexPosition in Object space, which converts it to NDC.

You may want to get in the habit of including a prefix for your shader variables which could help you denote which space each variable is in. When you move on to a more complicated phong implementation, you will have to deal with tangent space as well. I'm not sure if it's a comon practice, but labeling my spaces and labeling my matrices in a XSpaceToXSpace fashion certainly helps me keep track of where each variable is supposed to go, as well as help me track down the bugs quicker. You just see the names don't match up, and voila your hour-long bug hunt is cut short. I'll give you an example from one of my vertex shaders

```
  // deal with position and normal in world space
  WorldPosition = ModelMatrix * vec4(vPosition, 1);

  //convert TBN vectors to view space
  WorldNormal = normalize(ModelMatrix * vec4(vNormal, 0));
  WorldTangent = normalize(ModelMatrix * vec4(vTangent,0.f));
  WorldBitangent = normalize(ModelMatrix * vec4(vBitangent,0.f));

  mat4 WorldToTangent;
  WorldToTangent[0] = WorldTangent;
  WorldToTangent[1] = WorldBitangent;
  WorldToTangent[2] = WorldNormal;
  WorldToTangent[3] = vec4(0.f,0.f,0.f,1.f);

  //because we orthonormalized, TBN will now be our TangentToWorld (the transpose of an orthogonal matrix is equivalent to its inverse)
  if (Material.NormalMapTextureEnabled)
    TBN = mat4(transpose(mat3(WorldToTangent)), vec4(0,0,0,1));;
  else
    TBN = mat4(1.f);

  //Use TBN to convert world-space light positions and directions into tangent space
  for (int i=0;i<LightCount;++i)
    setLightDirection(i);

  ViewVector = Material.NormalMapTextureEnabled ? TBN * vec4(Camera.Position - WorldPosition.xyz, 0) :vec4(Camera.Position - WorldPosition.xyz, 0) ;
  CameraPosition = Material.NormalMapTextureEnabled ? TBN * vec4(Camera.Position, 1.f) : vec4(Camera.Position, 1.f);

...

  gl_Position = ModelViewProjectionMatrix * vec4(vPosition, 1);

```
> 1 votes

---
Tags: opengl, lighting
---


title: How to correct obtain HWND from SDL2?

text:
# Question
Title: How to correct obtain HWND from SDL2?
I use Urho3D which uses SDL2 as a window system. I want create another window as GUI and make it child for main window of Urho3D.

What I did is:

```
// insde virtual void Start() // Urho3D app
SDL_Window * sdlw = context->GetSubsystem<Graphics>()->GetWindow();
int width = context->GetSubsystem<Graphics>()->GetWidth();
int height = context->GetSubsystem<Graphics>()->GetHeight();
HWND mw = SDLWindows::GetWindowHWND(sdlw);
wpfC = WPFI::CreateWPFControl(0, 0, width, height);
HWND www = SetParent(wpfC, mw); // SetParent is windows function
if (www == NULL)
{
    std::cout << "------------------------------\n"
        << "www = NULL\n"
        << GetLastError() << "\n"
        << "------------------------------\n";
}

```

---

```
HWND SDLWindows::GetWindowHWND(SDL_Window * wnd)
{
    SDL_SysWMinfo sysInfo;
    SDL_VERSION(&sysInfo.version);
    SDL_GetWindowWMInfo(wnd, &sysInfo);
    return sysInfo.info.win.window;
}

```

---

I got `Invalid window handle (1400) Error on SetParent()`.

I am not sure if I am doing it right, but I am sure that my `wpfC` is ok because I have another test project where it is working but instead SDL window I use win32 Window.

I think `SDL_GetWindowWMInfo()` give me a wrong handle.

Question is how to obtain `HWND` from `SDL_Window` correctly and be sure that it is right `HWND`?

If it is not possible do it that way, is there another way how to create child window from `HWND` inside main SDL2 window?

# Answer
I found solution for Invalid window handle.

I edit source code of Urho3D engine and create function

```
void *GetSDLWindowHWND()
HWND hWnd = static_cast<HWND>(context->GetSubsystem<Graphics>()->GetSDLWindowHWND());

```

after that, SetParent() function working and my window child is displayed in Urho3D main window.
> 1 votes

---
Tags: c++, sdl2, urho3d
---


title: Mapping noise to sphere surface

text:
# Question
Title: Mapping noise to sphere surface
I'm attempting to create a sphere with terrain (aka planet). I managed to procedurally create an icosahedron, and I am able to subdivide it (yay), but now I'm stuck on terrain.

My current idea was to create a Perlin like "3D Noise Field" and sample density where each of the spheres vertices fall (as a height-map value). this way i should be able to tweak the noise (add octaves, etc) to roughen the "NoiseField" and thus the spheres surface.

pseudo example and result:

```
public void Terrain(float Scale)
{
    if (Scale < 0.01) return;

    List<Vector3> terrain = new List<Vector3>();
    for ( int i = 0; i < surface.vertices.Count; i++)
    {
        Vector3 vert = sphere.verts[i];
        Vector3 direction = vert.normalized;
        Vector3 newpoint = vert * Sample3DNoise(direction, Scale);
        terrain.Add(newpoint);
    }

    //this line replaces the original shape!
    surface.vertices = terrain;

    Debug.Log("terrain Update");
}

public float Sample3DNoise(Vector3 point, float scale)
{
    //Vector3 direction = point.normalized;

    float u = point.normalized.x * scale;
    float v = point.normalized.y * scale;
    float w = point.normalized.z * scale;

    //poor attempt at 3d noise field
    //PerlinNoise(float, float );
    float x = Mathf.PerlinNoise(u , 0f);
    float y = Mathf.PerlinNoise(0f, v);
    float z = Mathf.PerlinNoise(u , v);

    //the average of the coords, returns "density at this point"
    return (x + y + z) / 3;
}

```

edit:

so while it appears i was able to achieve this, it's is clearly not the "terrain on surface of sphere" look I was aiming for. Any suggestions on how can I change the "noise field" so my surface is more planet like? or how else can i achieve this?

# Answer
the answer was simple enough

```
Vector3 vector = original[i] + ((normal * noise) * amplitude);

```

basically i want to take the "original vert" and add "some noise in the correct direction" and scale by amplitude.

i ended up changing quite a bit of the project, but if anyone's curious it pretty much breaks down too...

```
    public void UpdateNoise(/* int layer,*/ float amplitude, float period)//, float frequency)
{
    List<Vector3> original  = Octaves[Octaves.Count - 2];//input verts
    List<Vector3> octave    = new List<Vector3>();

    for ( int i = 0; i < original.Count; i++)
    {
        Vector3 normal = original[i].normalized;
        float u = (normal.x * period);
        float v = (normal.y * period);
        float noise = Mathf.PerlinNoise(u, v);
        Vector3 vector = original[i] + ((normal * noise) * amplitude);

        octave.Add(vector);
    }
    this.vertices = octave;//output verts
    //Octaves[Octaves.Count - 1] = octave;
}

```
> 2 votes

# Answer
It seems to me that if you want more of a planetary terrain effect, you would add the modifier to the original vert instead of multiplying them and change your scale value to a number that is a small percentage of the sphere's radius. Good luck.
> 1 votes

---
Tags: terrain, perlin-noise, procedural
---


# Question
Title: In Unity, Is it possible to get gameobjects from non-open Scene?
Sorry for my english mistakes,I treid my best to make myself easy to be understood.

On Unity 2017.1 + C#.

I am trying to make UnitTest to check the potential errors in the scenes. and when I want to get the gameObjects from the two deifferent scenes, I can only get the scene which is open currently in the editor.

How to solve this problem? Or This is impossible to be done in Unity mechanism?

**Two Secens I have:**

**Scene1 hierarchy:**

**Scene2 hierarchy:**

**Code:**

**Result: Only get the open scene's infomation**

---

## My Final Solution

Thanks for the help, you guys help me make progress.

This is the feedback of my work. When I tried to solve my problems with the instruction, I ran into some obstacle.

So, I followed the suggestion of the error message.

And **the result is pleasant**.

The possible reason I can not get the same result at the begining, It may be because the different test mode(playMode/EditMode)

I will let myself take a break now and not dig deeper at this moment.

Thanks for your help and wish my dicovery can help someone too.

# Answer
You are trying to get scene information before loading the scene try this it worked for me.

```
        [Test]
        public void Test_loadScene()
        {

            SceneManager.LoadScene(0);
            Scene scen_1 = SceneManager.GetSceneByBuildIndex(0);
            SceneManager.LoadScene(1);
            Scene scen_2 = SceneManager.GetSceneByBuildIndex(1);

            Debug.Log("Scene 1 name: " + scen_1.name);
            Debug.Log("Scene 2 name: " + scen_2.name);
        }

```

**Result:**

**Debug:**

**Make sure both scene are added to "Scene in build"**
> 1 votes

# Answer
Hey there I see you are a new contributor. First off let me say that you can paste code directly in your question and that is desired. Secondly Have you tried loading both scenes before performing the test with :

```
SceneManager.LoadScene("scene_name", LoadSceneMode.Additive);

```
> 1 votes

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


title: Trademarks - a couple of questions

text:
# Question
Title: Trademarks - a couple of questions
I got a couple of questions about game trademarks.

* When should I submit a trademark for my game if I see that this is a serious project?
* Where do I submit a trademark request? Does it have to be local (In my country)?
* What do I need to be ready to submit a trademark request?

Thanks!

# Answer
> 3 votes
The answer to your 3 questions is subject to the laws that are applied in your country, also a trademark is a different concept if compared to a registered IP or a registered copyright, and there are also other possible options.

Each country has its own law and usually its own patent office, also do not assume that a registered IP is protected worldwide, this is a political issue and can also affect your distribution strategy.

# Answer
> 4 votes
1. I suggest that you contact someone who is able to perform a trademark analysis of the name that you've chosen. It is important to know if the name you have chosen is protected in the corresponding trademark classes about 6-8 months before you launch the game. It is sometimes easy for the board members, investors or the owners to decide for a name that they consider to be "Final" where I have to tell them that the name they've chosen is extremely difficult to protect.
2. It depends on which countries you are interested in protecting your trademark in. The most economical and secure way is to start in one country and then use trademark priority to expand your trademark protection to other countries.
3. You need to know the name you want to protect, if it is protectable and in which classes you will be active in. Generally for games, it is class 9 but depending on the game, it might be more classes.

---
Tags: trademark
---


# Question
Title: Does Unity animation event send a message to every object which owns it?
I made game objects A, B. And each has animator, and it has the same animation. And they are inherited class of Base class.

I trigger animation on A object, and the animation has callback and invoke it when the animation ends. The callback sets bool value true.

My expectation was, the callback will only change bool value in A. But bool value in B was changed. Is this natural?

```
public class BaseClass
{
    public bool triggered;
}

public class A : BaseClass
{
    public void OnAnimEnd()
    {
        triggered = true;
    }
}

public class B : BaseClass
{
    public void OnAnimEnd()
    {
        triggered = true;
    }
}

```

# Answer
> 1 votes
An animation triggered on instance X should not affect instance Y, whether they're the same class or different classes doesn't matter.

---
Tags: unity, animation
---


title: Is 2048 a registered trademark?

text:
# Question
Title: Is 2048 a registered trademark?
It looks like 2048 is a registered trademark of Ketchapp (obviously not the original author of 2048): https://trademarks.justia.com/865/87/2048-86587551.html . How applicable is this trademark and why are there still dozens of clones of 2048 on both Apple/Google Play store?

# Answer
In the US, a trademark is a word, phrase, symbol, design, or combination thereof that helps consumers identify a particular product.

If you register a trademark, you have legal grounds to prevent others from unpermitted use of your trademark with their product. For instance, Nintendo has trademarked *Super Mario Bros.* If someone attempted to market a game using that trademark, Nintendo would be in a strong position to litigate.

However, Nintendo's Super Mario Bros. trademark does not prevent other from making platformer video games with powerups, modifiable terrain, princess rescuing plots and so forth.

As such, trademark is only relevant to clones if:

* The original game has a trademark **AND**
* The clone is attempting to make use the trademark (I.E. use it as part of their branding) without permission.

As the question of whether or not Ketchapp can 'apply' their trademark, it depends on the context. It would appear they haven't successfully maintained control of 2048 as a trademark. Furthermore, it appears that 2048 is now used to describe a general category of game. Such generalization sometimes dilutes a trademark.

That being said, the Google Play Store is not exactly the same as a courtroom. Presently, here's what the Google Play Developer Policy Center states about trademark:

> We don’t allow apps that infringe on others’ trademarks. A trademark is a word, symbol, or combination that identifies the source of a good or service. Once acquired, a trademark gives the owner exclusive rights to the trademark usage with respect to certain goods or services.
>
> Trademark infringement is improper or unauthorized use of an identical or similar trademark in a way that is likely to cause confusion as to the source of that product. If your app uses another party’s trademarks in a way that is likely to cause confusion, your app may be suspended.

Initially, results would depend on whether or not Google agreed with Ketchapp's claims. Results beyond that might further depend on any legal developments in court (Google doesn't agree, so Ketchapp files a motion, Google does agree & some other dev files a motion when their app gets removed, etc). Further speculation is likely to be better suited to the Law Stack Exchange or actual legal council.
> 6 votes

# Answer
The trademark "2048" is protected in class 9 for "games" by a few different companies. The most known one is Ubisoft who has registered the name in. 2015 in both the EU and in the US.

With a trademark protection, you are able to act on infringing apps or games in all app-stores. Without a trademark protection, it is very difficult to enforce any game with a similar name.
> 1 votes

---
Tags: trademark
---


title: Resize window in D3D12

text:
# Question
Title: Resize window in D3D12
I am trying to implement the d3d12 window resizing function. First, I delete all the buffers referenced by SwapChain, and then run SwapChain :: ResizeBuffers. At this point I get the error:

```
D3D12 ERROR: ID3D12Resource1::<final-release>: CORRUPTION: An ID3D12Resource object (0x000002323B7029A0:'Unnamed Object') is referenced by GPU operations in-flight on Command Queue (0x000002323B6BFD00:'Command queue'). It is not safe to final-release objects that may have GPU operations pending. This can result in application instability. [ EXECUTION ERROR #921: OBJECT_DELETED_WHILE_STILL_IN_USE]
Exception thrown at 0x00007FF89004A839 (KernelBase.dll) in dx12_buffers_learn.exe: 0x0000087D (parameters: 0x0000000000000000, 0x000000712E99AE80, 0x0000023238E800D0).
Unhandled exception at 0x00007FF89004A839 (KernelBase.dll) in dx12_buffers_learn.exe: 0xC000041D:

```

This is the code of the procedure for changing sizes of window:

```
bool resize(int w, int h)
{
    if (device && swapChain && commandAllocator[frameIndex])
    {
        WaitForPreviousFrame();
        if (FAILED(commandAllocator[frameIndex]->Reset())) return false;
        if (FAILED(commandList->Reset(commandAllocator[frameIndex].Get(), nullptr))) return false;
        for (int i(0); i < frameBufferCount; i++)
            renderTargets[i].Reset();
        if (FAILED(swapChain->ResizeBuffers(frameBufferCount, w, h, backBufferFormat, NULL))) return false;
        frameIndex = 0;
        if (!createBackBuffer()) return false;
        createViewport();
        createScissor();
        if (FAILED(commandList->Close())) return false;
        vector<ID3D12CommandList*> cmdsLists = { commandList.Get() };
        commandQueue->ExecuteCommandLists(cmdsLists.size(), cmdsLists.data());
    }
    return true;
}

```

I put together a minimal self sufficient example for modeling the problem that described above:

```
#include <windows.h>
#include <d3d12.h>
#include <dxgi1_4.h>
#include "d3dx12.h"
#include <wrl.h>
#include <vector>
#pragma comment(lib, "dxgi.lib")
#pragma comment(lib, "d3d12.lib")
using namespace std;
using Microsoft::WRL::ComPtr;

void updateSize();
bool InitializeWindow(HINSTANCE hInstance);
bool resize(int w, int h);
void mainloop();
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
bool InitD3D();
void UpdatePipeline();
void Render();
void WaitForPreviousFrame();
bool createBackBuffer();
void createViewport();
void createScissor();

HWND hwnd = nullptr;
int widthClient = 900;
int heightClient = 650;
int startWidth;
int startHeight;
int widthWindow;
int heightWindow;
int frameBufferCount = 3;
ComPtr<IDXGIFactory4> dxgiFactory;
DXGI_FORMAT backBufferFormat = DXGI_FORMAT_R8G8B8A8_UNORM;
ComPtr < ID3D12Device> device;
ComPtr<IDXGISwapChain3> swapChain;
ComPtr < ID3D12CommandQueue> commandQueue;
ComPtr < ID3D12DescriptorHeap> rtvDescriptorHeap;
vector< ComPtr<ID3D12Resource>> renderTargets;
vector< ComPtr<ID3D12CommandAllocator>> commandAllocator;
ComPtr < ID3D12GraphicsCommandList> commandList;
vector< ComPtr<ID3D12Fence>> fence;
HANDLE fenceEvent = nullptr;
vector<unsigned long long> fenceValue;
int frameIndex = 0;
int rtvDescriptorSize = -1;
D3D12_VIEWPORT viewport;
D3D12_RECT scissorRect;
bool vsync = false;
float color[] = { 0.53f, 0.53f, 0.53f, 1.f };

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
    if (!InitializeWindow(hInstance)) return -1;
    if (!InitD3D()) return -1;
    mainloop();
    WaitForPreviousFrame();
    return 0;
}

void updateSize()
{
    RECT windowRect;
    GetClientRect(hwnd, &windowRect);
    widthClient = windowRect.right;
    heightClient = windowRect.bottom;
    startWidth = windowRect.left;
    startHeight = windowRect.top;
    GetWindowRect(hwnd, &windowRect);
    widthWindow = windowRect.right - windowRect.left;
    heightWindow = windowRect.bottom - windowRect.top;
}

bool InitializeWindow(HINSTANCE hInstance)
{
    WNDCLASSEX wc;
    ZeroMemory(&wc, sizeof(wc));
    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = WndProc;
    wc.hInstance = hInstance;
    wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
    wc.lpszClassName = L"dx12_className";
    wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
    if (!RegisterClassEx(&wc)) return false;
    if(!(hwnd = CreateWindowEx(NULL, L"dx12_className", L"DX12 Render Triangles", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, widthClient, heightClient, NULL, NULL, hInstance, NULL))) return false;
    updateSize();
    ShowWindow(hwnd, SW_SHOW);
    UpdateWindow(hwnd);
    return true;
}

void mainloop()
{
    MSG msg = {};
    while (true)
        if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            if (msg.message == WM_QUIT)
                break;
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
        else
            Render();
}

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch (msg)
    {
    case WM_DESTROY: // x button on top right corner of window was pressed
        PostQuitMessage(0);
        return 0;
    case WM_SIZE:
        updateSize();
        if (!resize(widthWindow, heightWindow))
        {
            DestroyWindow(hwnd);
            return 0;
        }
        break;
    }
    return DefWindowProc(hwnd, msg, wParam, lParam);
}

bool InitD3D()
{
    // init
    renderTargets.resize(frameBufferCount);
    commandAllocator.resize(frameBufferCount);
    fence.resize(frameBufferCount);
    fenceValue = { 0,0,0 };
    // debug
    ComPtr<ID3D12Debug> debugController;
    if (FAILED(D3D12GetDebugInterface(IID_PPV_ARGS(&debugController)))) return false;
    debugController->EnableDebugLayer();
    // dxgi factory
    if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(dxgiFactory.GetAddressOf())))) return false;
    // device
    if (FAILED(D3D12CreateDevice(nullptr, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(device.GetAddressOf())))) return false;
    // queue
    D3D12_COMMAND_QUEUE_DESC cqDesc = {};
    cqDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
    cqDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
    if (FAILED(device->CreateCommandQueue(&cqDesc, IID_PPV_ARGS(commandQueue.GetAddressOf())))) return false;
    commandQueue->SetName(L"Command queue");
    // swap chain
    DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {};
    swapChainDesc.Format = backBufferFormat;
    swapChainDesc.Stereo = FALSE;
    swapChainDesc.SampleDesc.Count = 1;
    swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    swapChainDesc.BufferCount = frameBufferCount;
    swapChainDesc.Scaling = DXGI_SCALING_NONE;
    swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
    swapChainDesc.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED;
    ComPtr<IDXGISwapChain1> tempSwapChain;
    if (FAILED(dxgiFactory->CreateSwapChainForHwnd(commandQueue.Get(), hwnd, &swapChainDesc, nullptr, nullptr, tempSwapChain.GetAddressOf()))) return false;
    if(!(swapChain = static_cast<IDXGISwapChain3*>(tempSwapChain.Get()))) return false;
    frameIndex = swapChain->GetCurrentBackBufferIndex();
    DXGI_RGBA swapChainBkColor = { color[0], color[1], color[2], color[3] };
    if (FAILED(swapChain->SetBackgroundColor(&swapChainBkColor))) return false;
    // back buffers
    if (!createBackBuffer()) return false;
    // viewport
    createViewport();
    // scissor
    createScissor();
    // allocators
    for (int i = 0; i < frameBufferCount; i++)
        if (FAILED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(commandAllocator[i].GetAddressOf())))) return false;
    // list
    if (FAILED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, commandAllocator[frameIndex].Get(), NULL, IID_PPV_ARGS(commandList.GetAddressOf())))) return false;
    // fence
    for (int i = 0; i < frameBufferCount; i++)
        if (FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(fence[i].GetAddressOf())))) return false;
    if(!(fenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr))) return false;
    // closed list
    commandList->Close();
    vector<ID3D12CommandList*> cmdsLists = { commandList.Get() };
    commandQueue->ExecuteCommandLists(cmdsLists.size(), cmdsLists.data());
    return true;
}

bool resize(int w, int h)
{
    if (device && swapChain && commandAllocator[frameIndex])
    {
        WaitForPreviousFrame();
        if (FAILED(commandAllocator[frameIndex]->Reset())) return false;
        if (FAILED(commandList->Reset(commandAllocator[frameIndex].Get(), nullptr))) return false;
        for (int i(0); i < frameBufferCount; i++)
            renderTargets[i].Reset();
        if (FAILED(swapChain->ResizeBuffers(frameBufferCount, w, h, backBufferFormat, NULL))) return false;
        frameIndex = 0;
        if (!createBackBuffer()) return false;
        createViewport();
        createScissor();
        if (FAILED(commandList->Close())) return false;
        vector<ID3D12CommandList*> cmdsLists = { commandList.Get() };
        commandQueue->ExecuteCommandLists(cmdsLists.size(), cmdsLists.data());
    }
    return true;
}

void UpdatePipeline()
{
    WaitForPreviousFrame();
    commandAllocator[frameIndex]->Reset();
    commandList->Reset(commandAllocator[frameIndex].Get(), nullptr);
    commandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(renderTargets[frameIndex].Get(), D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET));
    CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHandle(rtvDescriptorHeap->GetCPUDescriptorHandleForHeapStart(), frameIndex, rtvDescriptorSize);
    commandList->ClearRenderTargetView(rtvHandle, color, 0, nullptr);
    commandList->RSSetViewports(1, &viewport);
    commandList->RSSetScissorRects(1, &scissorRect);
    commandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(renderTargets[frameIndex].Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT));
    commandList->Close();
}

void Render()
{
    UpdatePipeline();
    vector<ID3D12CommandList*> ppCommandLists = { commandList.Get() };
    commandQueue->ExecuteCommandLists(ppCommandLists.size(), ppCommandLists.data());
    commandQueue->Signal(fence[frameIndex].Get(), fenceValue[frameIndex]);
    swapChain->Present(vsync ? 1 : 0, 0);
}

void WaitForPreviousFrame()
{
    frameIndex = swapChain->GetCurrentBackBufferIndex();
    if (fence[frameIndex]->GetCompletedValue() < fenceValue[frameIndex])
    {
        fence[frameIndex]->SetEventOnCompletion(fenceValue[frameIndex], fenceEvent);
        WaitForSingleObject(fenceEvent, INFINITE);
    }
    fenceValue[frameIndex]++;
}

bool createBackBuffer()
{
    D3D12_DESCRIPTOR_HEAP_DESC rtvHeapDesc = {};
    rtvHeapDesc.NumDescriptors = frameBufferCount;
    rtvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
    rtvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
    if (FAILED(device->CreateDescriptorHeap(&rtvHeapDesc, IID_PPV_ARGS(rtvDescriptorHeap.GetAddressOf()))))
        return false;
    rtvDescriptorSize = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
    CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHandle(rtvDescriptorHeap->GetCPUDescriptorHandleForHeapStart());
    for (int i = 0; i < frameBufferCount; i++)
    {
        if (FAILED(swapChain->GetBuffer(i, IID_PPV_ARGS(renderTargets[i].GetAddressOf()))))
            return false;
        device->CreateRenderTargetView(renderTargets[i].Get(), nullptr, rtvHandle);
        rtvHandle.Offset(1, rtvDescriptorSize);
    }
    return true;
}

void createViewport()
{
    viewport.TopLeftX = 0;
    viewport.TopLeftY = 0;
    viewport.Width = widthClient;
    viewport.Height = heightClient;
    viewport.MinDepth = 0.0f;
    viewport.MaxDepth = 1.0f;
}

void createScissor()
{
    scissorRect.left = 0;
    scissorRect.top = 0;
    scissorRect.right = widthClient;
    scissorRect.bottom = heightClient;
}

```

Tell me how to fix this problem.

**UPD1**

I set my RTV names and text error replace:

```
D3D12 ERROR: ID3D12Resource1::<final-release>: CORRUPTION: An ID3D12Resource object (0x000001E405CEB230:'back buffer #1')...

D3D12 ERROR: ID3D12Resource1::<final-release>: CORRUPTION: An ID3D12Resource object (0x0000022F37904B10:'back buffer #3')

```

RTV number is always random.

# Answer
I have to wait for my GPU to idle before I can resize.

This code make wait GPU:

```
void flushGpu()
{
    for (int i = 0; i < frameBufferCount; i++)
    {
        uint64_t fenceValueForSignal = ++fenceValue[i];
        commandQueue->Signal(fence[i].Get(), fenceValueForSignal);
        if (fence[i]->GetCompletedValue() < fenceValue[i])
        {
            fence[i]->SetEventOnCompletion(fenceValueForSignal, fenceEvent);
            WaitForSingleObject(fenceEvent, INFINITE);
        }
    }
    frameIndex = 0;
    // Thank you gamedev
}

```
> 2 votes

---
Tags: directx, directx12, dxgi
---


# Question
Title: How to reapply force applied to one object to another object
Edit: While I wasn't able to make the code work completely, I believe my question has been sufficiently answered.

I want to make two objects move, react to collisions and other stuff as if they were one.

For example, Objects A and B are entangled.

When Object C rams into Object A and starts moving with it, Object B should start moving with it. When Object B hits a wall, Object A should act like it also hit a wall.

I tried changing position/speed every frame, but this only works when done in one direction.

Now, I want all forces applied to any of the objects to also apply to the other objects entangled to it.

EDIT: The next step is making the thing work with one of the objects moving along a different axis(e.g. the opposite direction of the others) and at a different scale (e.g. speed is proportional to size). So fixed joints, while a working solution for the simplified version of the problem, don't work for me.

UPDATE: Here's the code so far, trying to figure out how to send the other object spinning in the same way as the first one, not sure how to set the position for the force(s?) applied

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

[RequireComponent(typeof(Rigidbody))]
public class EEScript : MonoBehaviour
{
    public List<GameObject> activeObjects;

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

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

    private void OnCollisionStay(Collision collision)
    {
        OnCollisionEnter(collision);
    }

    private void OnCollisionEnter(Collision collision)
    {
        Rigidbody rigidbody = gameObject.GetComponent<Rigidbody>();
        foreach (GameObject obj in activeObjects)
        {
            Rigidbody rb = obj.GetComponent<Rigidbody>();
            if (rb is null || rb.gameObject==gameObject) continue;
            Debug.Log(collision.gameObject.name+"->"+obj.name);

            for (int i = 0; i < collision.contactCount; i++)
            {
                ContactPoint co = collision.GetContact(i);
                Vector3 relativePoint = co.point - rigidbody.centerOfMass;
                Vector3 normal = co.normal;
                Vector3 impulse = collision.impulse;
                if (Vector3.Dot(normal, impulse) < 0f) impulse *= -1;
                rb.AddForceAtPosition(impulse, relativePoint + rb.centerOfMass, ForceMode.Impulse);
            }
        }
    }
}

```

# Answer
> 0 votes
One thing you could do is, when one object experiences an impulse due to collision, apply it to the other too:

```
public Rigidbody[] entangledBodies;

void OnCollisionEnter(Collision collision) {
    // Unity sends the same impulse value to both participants in a collision,
    // even though one gets impulsed in the opposite direction. So which are we?
    Vector3 impulse = collision.impulse;
    if(Vector3.Dot(impulse, collision.GetContact(0).normal) < 0f)
        impulse *= -1f;

    // Transmit this impulse to all bodies entangled with this one.
    foreach(var body in entangledBodies)
        body.AddForce(impulse, ForceMode.Impulse);
}

```

If this is in 2D, you won't have a simple total impulse property available, but you can compute it yourself as shown in this answer.

To add torques, you'll need to iterate through the actual contact points in the collision manifold and add forces at the corresponding points of your entangled bodies.

# Answer
> 0 votes
Make one object a child of the other object or make both objects children of the same object. Add a rigidbody component to the parent object, but keep collider on both objects.

---
Tags: unity, physics, physics-engine
---


# Question
Title: Using DualShock 4 motion sensor in Unreal engine (windows)
Anyone know how to access the gyro/accelerometer values from a DualShock 4 controller in the Unreal engine (under windows)? Are there any plugins that do this? Does raw input work?

# Answer
> -1 votes
There is a plugin indeed, but it's closed source. You need to be a registered PS4 dev to get it.

---
Tags: unreal, controllers, motion-control
---