# Question
Title: How would I go about coloring marching cubes terrain?
I'm making a game with marching cubes terrain (I know very original idea) and I don't exactly know how to color it. I have a system to do it, I just need to know how to interpolate it where it's not all smoothed out.

I just want flat colors, I think it boils down to this function (this is this guys code http://www.paulbourke.net/geometry/polygonise/):

```
glm::vec3 VertexInterp(const float& isolevel,const glm::vec3& p1,const glm::vec3& p2, const float& valp1, const float& valp2) {
    float mu;
    glm::vec3 p;

    if (ABS(isolevel-valp1) < 0.00001)
        return(p1);
    if (ABS(isolevel-valp2) < 0.00001)
        return(p2);
    if (ABS(valp1-valp2) < 0.00001)
        return(p1);
    mu = (isolevel - valp1) / (valp2 - valp1);
    p.x = p1.x + mu * (p2.x - p1.x);
    p.y = p1.y + mu * (p2.y - p1.y);
    p.z = p1.z + mu * (p2.z - p1.z);

    return p;
}

```

So if anyone could help me implement a flatter or smoother variant of that function it would be very much appreciated (I know all the rest of the things I need to do I just need help with this)

# Answer
Once I have generated all of the triangles, I weld the vertices, and get face and vertex normals.

Once that's done, I stuff the vertex data (including position, colour) into a buffer and call glDrawArrays.

Here are some codes:

```
void get_vertices_and_normals_from_triangles(vector<triangle> &t, vector<vec3> &fn, vector<vec3> &v, vector<vec3> &vn)
{
    fn.clear();
    v.clear();
    vn.clear();

    if(0 == t.size())
        return;

    cout << "Triangles: " << t.size() << endl;

    cout << "Welding vertices" << endl;

    // Insert unique vertices into set.
    set<indexed_vertex_3> vertex_set;

    for(vector<triangle>::const_iterator i = t.begin(); i != t.end(); i++)
    {
        vertex_set.insert(i->vertex[0]);
        vertex_set.insert(i->vertex[1]);
        vertex_set.insert(i->vertex[2]);
    }

    cout << "Vertices: " << vertex_set.size() << endl;

    cout << "Generating vertex indices" << endl;

    vector<indexed_vertex_3> vv;

    // Add indices to the vertices.
    for(set<indexed_vertex_3>::const_iterator i = vertex_set.begin(); i != vertex_set.end(); i++)
    {
        size_t index = vv.size();
        vv.push_back(*i);
        vv[index].index = index;
    }

    for (size_t i = 0; i < vv.size(); i++)
    {
        vec3 vv_element(vv[i].x, vv[i].y, vv[i].z);
        v.push_back(vv_element);
    }

    vertex_set.clear();

    // Re-insert modifies vertices into set.
    for(vector<indexed_vertex_3>::const_iterator i = vv.begin(); i != vv.end(); i++)
        vertex_set.insert(*i);

    cout << "Assigning vertex indices to triangles" << endl;

    // Find the three vertices for each triangle, by index.
    set<indexed_vertex_3>::iterator find_iter;

    for(vector<triangle>::iterator i = t.begin(); i != t.end(); i++)
    {
        find_iter = vertex_set.find(i->vertex[0]);
        i->vertex[0].index = find_iter->index;

        find_iter = vertex_set.find(i->vertex[1]);
        i->vertex[1].index = find_iter->index;

        find_iter = vertex_set.find(i->vertex[2]);
        i->vertex[2].index = find_iter->index;
    }

    vertex_set.clear();

    cout << "Calculating normals" << endl;
    fn.resize(t.size());
    vn.resize(v.size());

    for(size_t i = 0; i < t.size(); i++)
    {
        vec3 v0;// = t[i].vertex[1] - t[i].vertex[0];
        v0.x = t[i].vertex[1].x - t[i].vertex[0].x;
        v0.y = t[i].vertex[1].y - t[i].vertex[0].y;
        v0.z = t[i].vertex[1].z - t[i].vertex[0].z;

        vec3 v1;// = t[i].vertex[2] - t[i].vertex[0];
        v1.x = t[i].vertex[2].x - t[i].vertex[0].x;
        v1.y = t[i].vertex[2].y - t[i].vertex[0].y;
        v1.z = t[i].vertex[2].z - t[i].vertex[0].z;

        fn[i] = cross(v0, v1);
        fn[i] = normalize(fn[i]);

        vn[t[i].vertex[0].index] = vn[t[i].vertex[0].index] + fn[i];
        vn[t[i].vertex[1].index] = vn[t[i].vertex[1].index] + fn[i];
        vn[t[i].vertex[2].index] = vn[t[i].vertex[2].index] + fn[i];
    }

    for (size_t i = 0; i < vn.size(); i++)
        vn[i] = normalize(vn[i]);
}

bool read_triangles_from_binary_stereo_lithography_file(vector<triangle> &triangles, const char *const file_name)
{
    triangles.clear();

    // Write to file.
    ifstream in(file_name, ios_base::binary);

    if(in.fail())
        return false;

    const size_t header_size = 80;
    vector<char> buffer(header_size, 0);
    unsigned int num_triangles = 0; // Must be 4-byte unsigned int.
    indexed_vertex_3 normal;

    // Read header.
    in.read(reinterpret_cast<char *>(&(buffer[0])), header_size);

    if(header_size != in.gcount())
        return false;

    // Read number of triangles.
    in.read(reinterpret_cast<char *>(&num_triangles), sizeof(unsigned int));

    if(sizeof(unsigned int) != in.gcount())
        return false;

    triangles.resize(num_triangles);

    // Enough bytes for twelve 4-byte floats plus one 2-byte integer, per triangle.
    const size_t data_size = (12*sizeof(float) + sizeof(short unsigned int)) * num_triangles;
    buffer.resize(data_size, 0);

    in.read(reinterpret_cast<char *>(&buffer[0]), data_size);

    if(data_size != in.gcount())
        return false;

    // Use a pointer to assist with the copying.
    // Should probably use std::copy() instead, but memcpy() does the trick, so whatever...
    char *cp = &buffer[0];

    for(vector<triangle>::iterator i = triangles.begin(); i != triangles.end(); i++)
    {
        // Skip face normal.
        cp += 3*sizeof(float);

        // Get vertices.
        memcpy(&i->vertex[0].x, cp, sizeof(float)); cp += sizeof(float);
        memcpy(&i->vertex[0].y, cp, sizeof(float)); cp += sizeof(float);
        memcpy(&i->vertex[0].z, cp, sizeof(float)); cp += sizeof(float);
        memcpy(&i->vertex[1].x, cp, sizeof(float)); cp += sizeof(float);
        memcpy(&i->vertex[1].y, cp, sizeof(float)); cp += sizeof(float);
        memcpy(&i->vertex[1].z, cp, sizeof(float)); cp += sizeof(float);
        memcpy(&i->vertex[2].x, cp, sizeof(float)); cp += sizeof(float);
        memcpy(&i->vertex[2].y, cp, sizeof(float)); cp += sizeof(float);
        memcpy(&i->vertex[2].z, cp, sizeof(float)); cp += sizeof(float);

        // Skip attribute.
        cp += sizeof(short unsigned int);
    }

    in.close();

    return true;
}

```

where:

```
void draw_mesh(void)
{
    glUseProgram(render.get_program());

    glUniformMatrix4fv(uniforms.render.proj_matrix, 1, GL_FALSE, &main_camera.projection_mat[0][0]);
    glUniformMatrix4fv(uniforms.render.mv_matrix, 1, GL_FALSE, &main_camera.view_mat[0][0]);
    glUniform1f(uniforms.render.shading_level, 1.0f);

    vector<float> vertex_data;

    for (size_t i = 0; i < triangles.size(); i++)
    {
        vec3 colour(0.0f, 0.8f, 1.0f);

        size_t v0_index = triangles[i].vertex[0].index;
        size_t v1_index = triangles[i].vertex[1].index;
        size_t v2_index = triangles[i].vertex[2].index;

        vec3 v0_fn(vertex_normals[v0_index].x, vertex_normals[v0_index].y, vertex_normals[v0_index].z);
        vec3 v1_fn(vertex_normals[v1_index].x, vertex_normals[v1_index].y, vertex_normals[v1_index].z);
        vec3 v2_fn(vertex_normals[v2_index].x, vertex_normals[v2_index].y, vertex_normals[v2_index].z);

        vec3 v0(triangles[i].vertex[0].x, triangles[i].vertex[0].y, triangles[i].vertex[0].z);
        vec3 v1(triangles[i].vertex[1].x, triangles[i].vertex[1].y, triangles[i].vertex[1].z);
        vec3 v2(triangles[i].vertex[2].x, triangles[i].vertex[2].y, triangles[i].vertex[2].z);

        vertex_data.push_back(v0.x);
        vertex_data.push_back(v0.y);
        vertex_data.push_back(v0.z);
        vertex_data.push_back(v0_fn.x);
        vertex_data.push_back(v0_fn.y);
        vertex_data.push_back(v0_fn.z);
        vertex_data.push_back(colour.x);
        vertex_data.push_back(colour.y);
        vertex_data.push_back(colour.z);

        vertex_data.push_back(v1.x);
        vertex_data.push_back(v1.y);
        vertex_data.push_back(v1.z);
        vertex_data.push_back(v1_fn.x);
        vertex_data.push_back(v1_fn.y);
        vertex_data.push_back(v1_fn.z);
        vertex_data.push_back(colour.x);
        vertex_data.push_back(colour.y);
        vertex_data.push_back(colour.z);

        vertex_data.push_back(v2.x);
        vertex_data.push_back(v2.y);
        vertex_data.push_back(v2.z);
        vertex_data.push_back(v2_fn.x);
        vertex_data.push_back(v2_fn.y);
        vertex_data.push_back(v2_fn.z);
        vertex_data.push_back(colour.x);
        vertex_data.push_back(colour.y);
        vertex_data.push_back(colour.z);
    }

    GLuint components_per_vertex = 9;
    const GLuint components_per_normal = 3;
    GLuint components_per_position = 3;
    const GLuint components_per_colour = 3;

    GLuint triangle_buffer;

    glGenBuffers(1, &triangle_buffer);

    GLuint num_vertices = static_cast<GLuint>(vertex_data.size()) / components_per_vertex;

    glBindBuffer(GL_ARRAY_BUFFER, triangle_buffer);
    glBufferData(GL_ARRAY_BUFFER, vertex_data.size() * sizeof(GLfloat), &vertex_data[0], GL_DYNAMIC_DRAW);

    glEnableVertexAttribArray(glGetAttribLocation(render.get_program(), "position"));
    glVertexAttribPointer(glGetAttribLocation(render.get_program(), "position"),
        components_per_position,
        GL_FLOAT,
        GL_FALSE,
        components_per_vertex * sizeof(GLfloat),
        NULL);

    glEnableVertexAttribArray(glGetAttribLocation(render.get_program(), "normal"));
    glVertexAttribPointer(glGetAttribLocation(render.get_program(), "normal"),
        components_per_normal,
        GL_FLOAT,
        GL_TRUE,
        components_per_vertex * sizeof(GLfloat),
        (const GLvoid*)(components_per_position * sizeof(GLfloat)));

    glEnableVertexAttribArray(glGetAttribLocation(render.get_program(), "colour"));
    glVertexAttribPointer(glGetAttribLocation(render.get_program(), "colour"),
        components_per_colour,
        GL_FLOAT,
        GL_TRUE,
        components_per_vertex * sizeof(GLfloat),
        (const GLvoid*)(components_per_normal * sizeof(GLfloat) + components_per_position * sizeof(GLfloat)));

    glDrawArrays(GL_TRIANGLES, 0, num_vertices);

    glDeleteBuffers(1, &triangle_buffer);
}

```

Hopefully this will help.
> 1 votes

---
Tags: c++, terrain-rendering, glm, marching-cubes
---


# Question
Title: How can i add to the waypoints multiple objects to move between the waypoints?
```
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class Waypoints : MonoBehaviour
{
    public GameObject objToMove;
    public LineRenderer lineRenderer;
    public float speed;
    public bool go = false;
    public bool moveToFirstPositionOnStart = false;
    public float rotSpeed;
    public bool random = false;
    public int currentCurvedLinePointIndex;

    private Vector3[] pos;
    private int index = 0;
    private bool goForward = true;
    private List<GameObject> curvedLinePoints = new List<GameObject>();
    private int numofposbetweenpoints;
    private bool getPositions = false;

    // Start is called before the first frame update
    void Start()
    {
        var parent = GameObject.Find("Moving Object Parent");
        objToMove = Instantiate(objToMove, parent.transform);
        objToMove.name = "Platfrom";

        curvedLinePoints = GameObject.FindGameObjectsWithTag("Curved Line Point").ToList();

        if (curvedLinePoints != null && curvedLinePoints.Count > 0)
        {
            //objToMove.transform.rotation = curvedLinePoints[1].transform.rotation;
        }
    }

    Vector3[] GetLinePointsInWorldSpace()
    {
        var positions = new Vector3[lineRenderer.positionCount];
        //Get the positions which are shown in the inspector
        lineRenderer.GetPositions(positions);

        //the points returned are in world space
        return positions;
    }

    // Update is called once per frame
    void Update()
    {
        if (lineRenderer.positionCount > 0 && getPositions == false && CurvedLineRenderer.linesSet)
        {
            pos = GetLinePointsInWorldSpace();

            numofposbetweenpoints = curvedLinePoints.Count;

            if (moveToFirstPositionOnStart == true)
            {
                //objToMove.transform.position = pos[index];
            }

            getPositions = true;
        }

        if (go == true && lineRenderer.positionCount > 0 && CurvedLineRenderer.linesSet)
        {
            pos = GetLinePointsInWorldSpace();
            Move();
        }
    }

    int counter = 0;
    int c = 1;
    void Move()
    {
        Vector3 newPos = objToMove.transform.position;
        float distanceToTravel = speed * Time.deltaTime;

        bool stillTraveling = true;
        while (stillTraveling)
        {
            Vector3 oldPos = newPos;

            newPos = Vector3.MoveTowards(oldPos, pos[index], distanceToTravel);

            distanceToTravel -= Vector3.Distance(newPos, oldPos);
            if (newPos == pos[index]) // Vector3 comparison is approximate so this is ok
            {
                // when you hit a waypoint:
                if (goForward)
                {
                    bool atLastOne = index >= pos.Length - 1;
                    if (!atLastOne)
                    {
                        index++;
                        counter++;
                        if (counter == numofposbetweenpoints)
                        {
                            c++;

                            counter = 0;
                        }
                        if (c == curvedLinePoints.Count - 1)
                        {
                            c = 0;
                        }
                    }
                    else { index--; goForward = false; }
                }
                else
                { // going backwards:
                    bool atFirstOne = index <= 0;
                    if (!atFirstOne)
                    {
                        index--;

                        counter++;
                        if (counter == numofposbetweenpoints)
                        {
                            c++;

                            counter = 0;
                        }
                        if (c == curvedLinePoints.Count - 1)
                        {
                            c = 0;
                        }
                    }
                    else { index++; goForward = true; }
                }
            }
            else
            {
                stillTraveling = false;
            }
        }

        objToMove.transform.position = newPos;
    }
}

```

Now it's working fine with the single object the variable objToMove but I want to turn the variable either to a List or to Array like objsToMove and then using some timer or a coroutine to fire each X seconds for example every 3 seconds to start moving the next objToMove between the waypoints from the List/Array.

# Answer
> 0 votes
Your approach is conceptually backwards. Waypoints should generally be defined in a basic data structure, and objects that want to follow the waypoints should reference the set of waypoints. Objects move themselves while following waypoints; waypoints do not move objects.

Here's a simple example:

```
public class Waypoints : MonoBehaviour {
    //with this approach, you use GameObjects to represent your waypoints
    //(they can be empty if you want the waypoint to be invisible)
    [SerializeField] private List<Transform> waypoints;

    public int Count => waypoints.Count;
    public Vector3 GetWaypoint(int index) {
        return waypoints[index].position;
    }
}

public class WaypointFollower : MonoBehaviour {
    [SerializeField] private Waypoints waypoints;
    [SerializeField] private float speed = 5f;

    private int waypointIndex = 0;

    void Update() {
        Vector3 waypoint = waypoints.GetWaypoint(waypointIndex);
        //movement
        float distance = speed * Time.deltaTime;
        transform.position = Vector3.MoveTowards(transform.position, waypoint, distance);

        //check if we've reached the waypoint
        float threshold = .5f; //how close is considered having reached the waypoint
        if (Vector3.Distance(transform.position, waypoint) < threshold) {
            //wraps back to 0 when we reach last waypoint
            waypointIndex = (waypointIndex + 1) % waypoints.Count;
        }
    }
}

```

This way, any number of moving objects can independently follow the waypoints. The waypoints do not have to know about or manage state for any of the moving objects; those objects can manage their own state.

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


# Question
Title: Game loop architecture using WPF(MVVM) and C#
Could i get some suggestions on how to implement a game loop whilst using WPF(MVVM) and C#, I am a professional developer and understand the technology well.

The game loop usually contains a Init(), Render() and Update().

I know how to implement the Init() and Update(), but i would like ideas of how the render() fits in, using data binding the Render will happen on update(). Should forget the Render method or suppress the bindings and force them with a render?

Hope that makes sense :)

# Answer
> 2 votes
With WPF, the UI ( or render I guess ) thread is kind of special. It'll try and run every 60th of a second. All of your View-\>ViewModel bound property read/writes are sort of banked up and updated on the UI thread. So you can alter a property a ton of times on a background thread but it will be updated on the UI thread. Command bindings ( like a button click bound to a command ) will happen on the UI thread so dealing with those on the same thread will block the UI update. Starting views and closing views can only be done on the UI thread.

I've not done much in the way of interactive 'gamey' stuff using WPF but I have done 3d scenes with moving camera's. The way I did this was to have an update thread which updated properties which were bound to the UI objects ( like position, orientation ). There was no UI thread specific things to do really. Apart from allocating the geometry and hooking it into the visual tree.

So WPF isn't really set up to work in a way you may be used too. But you could probably get something close by using a BackgroundWorker.

The BackgroundWorker class has a RunWorkerComplete method https://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker(v=vs.110).aspx. This allows you to start a background worker task and then update any UI specific stuff when its complete. And so I guess with some clever timing this would effectively give you an update & render hook which you may find to be more game loop familiar.

# Answer
> 0 votes
I guess the `CompositionTarget.Rendering` event fits your bill. You can attach a method to the `Rendering` event like this:

```
CompositionTarget.Rendering += Loop;

```

The `Loop` function can then update the properties of an element, in this example an element positioned on a Canvas:

```
private void Loop(object sender, EventArgs e)
{
    LeftPos++;
    Canvas.SetLeft(ball, LeftPos);
}

```

Mircosoft API Documentation: compositiontarget.rendering

(This stackoverflow answer pointed me in the right direction.)

---
Tags: c#, architecture, game-loop, wpf
---


# Question
Title: In Pong, how do you calculate the ball's direction when it bounces off the paddle?
I'm trying to wrap my head around this very Hello World-y problem in game development. I've created a TicTacToe game in XNA so I guess the next step would be a Breakout clone.

Keep in mind that I have **no** knowledge on game programming or even what maths I should apply to where. That's why I'm asking this question.

---

To the question: How can I determine where the ball should bounce when it hits the paddle at the bottom of the screen?

I'd imagine it would be something like:

1. Capture speed and angle from incoming ball.
2. Detect where it touched the bar (far left, far right, center) and according to that give it a higher speed if it touched the outer areas.
3. This is where I'm stuck. Hehe.

Any insights? I realize this is not a straightforward answer type question, but I'm sure it's one everyone faces at some point.

I'm reading the book *Linear Algebra* that was recommended on this website, but I still have no idea if I should apply it here.

# Answer
Here's the relevant logic I used on the pong on my homepage: (please go play it before reading, so that you know the effect I'm achieving with the following code)

Essentially, when the ball collides with the paddle, its direction is completely disregarded; it is given a new direction according to how far from the center of the paddle it collided. If the ball hits the paddle right in the center, it is sent away exactly horizontal; if it hits right on the edge, it flies off at an extreme angle (75 degrees). And it always travels at a constant speed.

```
var relativeIntersectY = (paddle1Y+(PADDLEHEIGHT/2)) - intersectY;

```

Take the middle Y value of the paddle, and subtract the Y intersection of the ball. If the paddle is 10 pixels high, this number will be between -5 and 5. I call this the "relative intersect" because it is in "paddle space" now, the ball's intersection relative to the middle of the paddle.

```
var normalizedRelativeIntersectionY = (relativeIntersectY/(PADDLEHEIGHT/2));
var bounceAngle = normalizedRelativeIntersectionY * MAXBOUNCEANGLE;

```

Take the relative intersection and divide it by half the paddle height. Now our -5 to 5 number is a decimal from -1 to 1; it's *normalized*. Then multiply it by the maximum angle by which you want the ball to bounce. I set it to 5\*Pi/12 radians (75 degrees).

```
ballVx = BALLSPEED*Math.cos(bounceAngle);
ballVy = BALLSPEED*-Math.sin(bounceAngle);

```

Finally, calculate new ball velocities, using simple trigonometry.

This might not quite be the effect you're going for, or you might want to also determine a speed by multiplying the normalized relative intersection by a max speed; this would make the ball go faster if it hits near the edge of a paddle, or slower if it hits near the center.

---

> I'd possibly like some code on what a vector would look like or how I could save the variable of the vector the balls has (speed and direction).

A vector contains both speed and direction, implicitly. I store my vector as a "vx" and "vy"; that is, the speed in the x direction and the speed in the y direction. If you haven't taken an introductory course in physics this might seem somewhat foreign to you.

The reason I do this is because it reduces the per-frame calculations necessary; every frame, you just do `x += vx * time;` and `y += vy * time;` where time is the time since last frame, in milliseconds (therefore the velocities are in pixels per millisecond).

---

Regarding implementing the ability to curve the ball:

First of all, you'd need to know the paddle's velocity at the time the ball hits; which means you'd need to keep track of the paddle's history, so that you can know one or more of the paddle's past positions so that you can compare them to its current position to see if it moved. (change in position / change in time = velocity; so you need 2 or more positions, and the times of those positions)

You now also need to track an angular velocity of the ball, which practically represents the curve along which it is traveling, but is equivalent to the real-world spin of the ball. Similar to how you would interpolate the bounce angle from the relative position of the ball on collision with the paddle, you would also need to interpolate this angular velocity (or spin) from the velocity of the paddle on collision. Rather than simply setting the spin like you do with the bounce angle, you might want to add or subtract to the ball's existing spin, because that tends to work well in games (the player can notice the ball is spinning, and cause it to spin even more wildly, or counter the spin in an attempt to make it travel straight).

Note, however, that while this is the most common sense and probably easiest way to implement it, the actual physics of a bounce doesn't rely solely on the velocity of the object it hits; an object with no angular velocity (no spin) which hits a surface at an angle, will have a spin imparted upon it. This might lead to a better game mechanic, so you may want to look into this, but I'm not certain of the physics behind it so I'm not going to try to explain it.
> 38 votes

# Answer
It has been a while since I've done this, but I think I've got this right.

Given a perfect collision, the angle of reflection is equal to the angle of incidence.

You know the normal of your paddle (presuming a flat surface): N You know your original position of your ball (at the beginning of your timestep): P You know your new position of the ball (at the end of the timestep): P' You know your point of collision: C Assuming that you calculated that the segment P -\> P' passes through your paddle, your new reflected postion (P'') would be:

P' + 2 * (N * (P' dot -N) )

The N * (P' dot -N) subexpression calculates the depth along the normal of collision the ball traveled. The minus sign is to correct for the fact we're checking for depth opposite the direction of the normal.

The P' + 2 * the part of the subexpression moves the ball back above the plane of collision by 2 times the depth of the collision.

If you want a less than perfect collision, change the factor 2 to be (1 + (1-k)) where k is your coefficient of friction. A perfect collision has a k value of 0, causing the reflection angle to be exactly that of the incoming angle. A k value of 1 causes a collision where the ball would stay on the surface of the plane of collision.

Your new velocity vector, V'', direction would be P'' - C. Normalize it and multiply by your incoming velocity and your resultant velocity magnitude would be the same, but in the new direction. You can monkey with that velocity by multiplying it by a coefficient, l, that would either increase (l \> 1) or decrease (l \< 1) the resulting velocity.

To summarize:

P'' = P' + (1-k) * (N\*(P dot -N)) V'' = l * V * ((P'' - C) / |P''-C|)

Where k and l are coefficients of your choosing.
> 9 votes

# Answer
The reflection can either be done "right" or done "easy."

The "right" way is to compute vectors perpendicular to the walls. In 2D that's pretty easy and you could probably just hard code them. Then, the reflection step essentially leaves the "parallel" component of the motion intact and reverses the "perpendicular" component. There's probably detailed information on the web for this, maybe at MathWorld even.

The "easy" way is to just negate the X or Y motion when you hit a wall. If you hit the side walls, you'd negate X. If you hit the top you negate Y. If you want to speed the ball up, just increase whatever you want; you can speed it up in its current direction by multiplying both the X and Y speeds or you can speed up only on one axis.
> 6 votes

# Answer
I'm making an arkanoid-ish game myself too and I think the solution on how the ball should behave when hitting the paddle is quite simpler and faster than getting into the sin/cos approach... it works fine for the purposes of a game like this. Here's what I do:

* Of course, since the ball speed increases in time I interpolate the before/after x,y steps to keep accurate collision detection, looping through all "stepX" and "stepY" which are calculated dividing each speed component by the modulus of the vector formed by the current and future ball positions.
* If a collision against the paddle occurs I divide the Y speed by 20. This "20" is the most convenient value I found to get my resulting maximum angle when the ball hits on the sides of the paddle, but you can change it to whatever your needs are, just play with some values and choose the better for you. By dividing, let's say a speed of 5, which is my initial game speed by this number (20), I get a "rebound factor" of 0.25. This calculation keeps my angles quite proportional when the speed increases in time up to my maximum speed value which, for example, could be 15 (in that case: 15/20 = 0.75). Considering that my paddle x, y coords are midhandled (x and y represent the center of the paddle), I then multiply this result by the difference between the ball position and the paddle position. The greater the difference, the greatear the resulting angle. Besides, using a midhandled padlle, you get the correct sign for the x increment depending on the side the ball hits without having to worry about calculating the center. In pseudo-code:

For n = 0 to modulus ...

if collision\_detected then speedX = -(speedY / 20 ) * (paddleX - ballX); speedY = -speedY;
exit; end if

...

x = x + stepX; y = y + stepY;

end for

Remeber, always try to keep things SIMPLE. I hope it helps!
> 5 votes

# Answer
The paddle in Breakout, when it follows the style you're describing is usually modelled as a curved surface. The angle of incidence changes based on where on the paddle it hits. On the dead center the tangent line to the curve is absolutely horizontal, and the ball reflects as expected. As you move off the center, the tangent to the curve becomes increasingly angled, and the ball reflects differently as a result.

The key point is that the angle of reflection, not the ball speed, is what changes. The ball speed generally just increases slowly over time.
> 4 votes

# Answer
Nolan Bushnell gave a keynote at SIEGE this past weekend and talked about a similar issue with the original pong. You don't have to do alot of complicated calculations. If you hit on towards the left portion of hte panel, send the ball left. Do the same for the right side.

To start off with you can make the angle for the left and right sides 45 degrees. Once you finish the game you could if you want go back and make this more complicated but make this as simple as you can to begin with.
> 4 votes

# Answer
Breakout is a classic beginners work for starting to dive into the world of physics based game programming. Basically the ball has a bounce motion when it hits on the wall. As somebody above suggested the angle of incidence is equal to the angle of reflection. But when you consider the ball hitting the paddle. The logic is divided into 3 sections. 1.) The ball hitting the center portion of the paddle. 2.) The ball hitting the leftward portion of the paddle. 3.) The ball hitting the rightward position of the paddle.

When you consider the center portion: You need not differ the bounce effect of that which is applied when hitting the ball. The ball just gets deflected normally.But, when either direction is hit, the case is different.

When the ball is hit on the leftward side, ie consider the ball coming from the leftward side of the screen and you are coming with the paddle from the right side. Then when you hit the ball with the leftward portion, the ball should reflect to the direction it came from .ie.leftwards with the same angle it came from. Same is the case vice versa. In the rightward portion also the same thing applies.

This movement of the ball towards the leftward or rightward direction when it is being hit makes it more believable.

Hope you got the idea,at least logic wise.Thank you
> 4 votes

# Answer
Imagine you calculate the distance between the center of the paddle and the point where the ball Y hit and call it `d`. Let's suppose `d` has a positive value when the ball hit above the center of the paddle. You can now add `d * -0.1` to the Y velocity of your ball and it will start changing direction. Here is an example in javascript that can be easily translated into c#!

```
var canvas = document.querySelector('canvas');
var resize = function () {
  canvas.width = innerWidth;
  canvas.height = innerHeight;
};
resize();
var ctx = canvas.getContext('2d');
var ball = {
  size: 3,
  x: 1,
  y: canvas.height/2,
  vx: 2,
  vy: 0
};
var paddle = {
  height: 40,
  width: 3,
  x: canvas.width/2,
  y: canvas.height/2
};
addEventListener('mousemove', function (e) {
  paddle.y = e.clientY - (paddle.height/2);
});
var loop = function () {
  resize();
  ball.x += ball.vx;
  ball.y += ball.vy;
  if (ball.x > canvas.width || ball.x < 0) ball.vx *= -1; // horiz wall hit
  if (ball.y > canvas.height || ball.y < 0) ball.vy *= -1; // vert wall hit
  if (ball.x >= paddle.x && ball.x <= paddle.x + paddle.width && ball.y >= paddle.y && ball.y <= paddle.y + paddle.height) {
    // paddle hit
    var paddleCenter = paddle.y + (paddle.height/2);
    var d = paddleCenter - ball.y;
    ball.vy += d * -0.1; // here's the trick
    ball.vx *= -1;
  }
  ctx.fillRect(ball.x,ball.y,ball.size,ball.size);
  ctx.fillRect(paddle.x,paddle.y,paddle.width,paddle.height);
  requestAnimationFrame(loop);
};
loop();
```

```
body {overflow: hidden; margin: 0}
canvas {width: 100vw; height: 100vh}
```

```
<canvas></canvas>
```
> 3 votes

# Answer
Hi I have been recently tried to make a ball game and figured out a solution for this. So what I did: The paddle is moving while we are playing the game. My coordinate system is left as it is, the top-left point of the canvas is 0,0. The paddle is moving in this coordinate system. The x axis points from 0 to canvas width, and y axis is pointing on 0 to canvas Height. I created a paddle with fix size 100 width and 20 height. And then I draw an imagined circle around it. When the ball hits the paddle I compute paddle's Centerpoint

```
double paddleCenter=Squash.paddle.getXpos()+Squash.paddle.getPaddleWidth()/2;

```

Then I subtract the center from the ball's current position this way the coordinate system will be at the center of the paddle, ballCenter is the point where the ball hit the paddle (-(paddlewidth+r)..0..(paddlewidth+r)) this is nothing but rescaling the hitting point on the paddle

```
double x0 = ballCenterX-paddleCenter;

```

compute the circle's intersection point with the help of the ball's hitting point (x0) this is a recomputation , we ask for the y coordinate on the circle with the x0 already known coordinate and there was needed a flip for the y axis

```
double y0 = -Math.sqrt(paddleRadius*paddleRadius-x0*x0);

```

compute the derivate of the normal equation of the circle which is defined around the paddle with radis paddleRadius f(x,y)=x^2+y^2-r^2

```
double normalX=2*x0;
double normalY=2*y0;

```

normalize the N vector, to get a unit vector for the surface normal

```
double normalizer=Math.sqrt(normalX*normalX + normalY*normalY);
normalX=normalX/normalizer;
normalY=normalY/normalizer;

```

now we have the normalized (unit) surface normals for the paddle. Compute the new direction with these surface normals, this will be computed with the help of the reflection vector formula: new\_direction=old\_direction-2\*dot(N,old\_direction)\*N, but instead with the surface normal pointing always upwards, the normal's will be changing from point to point where the ball hits the paddle

```
double eta=2; //this is the constant which gives now perfect reflection but with different normal vectors, for now this set to 2, to give perfect reflection
double dotprod=vX*normalX+vY*normalY;
vX=vX-eta*dotprod*normalX;//compute the reflection and get the new direction on the x direction
vY=-vY;//y direction is remain the same (but inverted), as we just want to have a change in the x direction

```

I've published my solution to this problem. For more details and for the complete game you can see my github repository:

https://github.com/zoli333/BricksGame

written in java with eclipse. There is another solution for this commented out in Ball.java, where the rescaling not happen I don't move the coordinate coordinate system to the paddle's center point, instead I compute all of these above from the topleft 0,0 coordinate system relative to the paddle's center point. This works also.
> 1 votes

# Answer
based on @Ricket's answer, I solved it basically with Pythagorean theorem. You want the size of the final vector to be 1, so you can multiply it to have your final ball speed. Following Python code:

At first, u take the intersect of the paddle-(bar) and the ball. So it's the X vector.

```
relativeIntersectX = (self.bar_x + (self.bar_width/2)) - self.ball_x

```

Then you normalize it. So it is value between -1 and 1.

```
normalizedIntersect = (relativeIntersectX/(self.bar_width/2))

```

So, the ball\_vx (x-velocity) is basically the vector itself. Velocity is any positive number based on, how fast you want the ball.

```
self.ballvx = -normalizedIntersect*self.velocity

```

The ball\_vy is just expressed from the formula *vx^2 + vy^2 = 1*.

```
self.ballvy = -math.sqrt(1-normalizedIntersect**2)*self.velocity

```

You might want to care about special cases, so you just go something like this.

```
if normalizedIntersect > 0.95:
     normalizedIntersect = 0.95
elif normalizedIntersect < -0.95:
     normalizedIntersect = -0.95

```
> 1 votes

# Answer
this will help http://www-classes.usc.edu/engr/ee-s/477p/s00/pong.html you simply invert x and y depending on where it hits the screen. if its going up, and hits the top, it inverts the y velocity while keeping the x velocity
> 0 votes

---
Tags: xna, c#, 2d, mathematics, physics
---


# Question
Title: How can I add one OPENGL page to another when ENTER key is pressed?
I created one GLUT project which has my project's introduction page. When I pressed ENTER key, it should redirect to my front page of project which I created as another project.

# Answer
> 0 votes
With glutKeyboardFunc() we can detect keystrokes and do a system call to start the program.

```
void keyboard(unsigned char c, int x, int y) {
    if (c == 13) {
        system("C:\\Users\\Folder\\program.exe");
        exit(0);
    }
}

glutKeyboardFunc(keyboard);

```

---
Tags: opengl, glut
---


title: Spawn point not working on unity

text:
# Question
Title: Spawn point not working on unity
I have two `GameObjects` set down. One is named `Spawn Point`, and it is set at the beginning of my level, and `Death Point`, set down at about 0,-40,0. My code tries to see if the character is below the `Death Point` area and moves the player to the spawn point. I feel that the answer is so simple, that I could look it up, but I looked it up, and I didn't see it.

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

public class death : MonoBehaviour
{
    public GameObject spawnPoint;
    public GameObject deathPoint;
    // Start is called before the first frame update

    // Update is called once per frame
    void Update()
    {
       Vector3 playerPos = transform.position;
        if(playerPos.y < deathPoint.transform.position.y) {
            transform.position = spawnPoint.transform.position;
        }
    }
}

```

A big thank you in adavance.

# Answer
Well, there is nothing wrong with your code. So, if it does not work, there must be some other reason. When this happens I would add some Debug.Log() calls and check what is going on. In a case like this, I would add one line at the beginning of the Update().

```
void Update()
{
    Debug.Log("p: " + transform.position.ToString()
        + ", d: " + deathPoint.transform.position.ToString());

```

If you don't get any messages in the console the object is probably disabled. Make sure there is a checkbox in front of the script title in the Editor.

I would also add a second line inside the if-statement to check if it ever evaluates to true.

```
    if (playerPos.y < deathPoint.transform.position.y)
    {
        Debug.Log("Is below!");

```

If this never evaluates to true:

1. The fields have other game objects assigned to them than expected.
2. Some other script is interfering. If you can - disable other scripts that might alter the position of the character.
3. If you are using physics (rigid bodies and colliders), make sure there isn't a collider on the deathPoint and your player is simply stopped by it before your script evaluates the position.

(Sorry if parts of my answer are too simple for you, then ignore those.)
> 1 votes

---
Tags: unity
---


# Question
Title: What is the difference between OpenGL, SDL, DirectX, GLFW, GLUE?
I'm aware that *OpenGL* and *DirectX* are somehow programmed into my graphics card drivers initially, and I can use *GLFW*, *SDL* etc. to get access to those and manipulate them, by creating kind of different graphics objects.

Analogy:

**OpenGL** \- programming language

**SDL** \- framework

Please, correct me where i'm wrong.

# Answer
Both OpenGL and DirectX are **API**s. They serve as an interface between the GPU and the programming language.

GLFW, GLUE, and SDL (not SLD) are both frameworks with different goals. GLFW and GLUE is just a way to setup a window easily with OpenGL and DirectX, while SDL also provides some basic drawing functionality. Both if these three uses OpenGL, DirectX API's as a foundation.

Basically, APIs are the lowest level and frameworks are above them and on top are the engine's
> 4 votes

# Answer
'glue' is sticky stuff. glu is a deprecated utility library for the old OpenGL fixed function pipeline (am ready for correction if it has been updated since back in the day).

OpenGL and DirectX (and Vulkan, Metal, ....) are graphics APIs. They offer a programming interface to the render pipeline of graphics cards. DirectX has a bit more than graphics, but is MS Windows specific. OpenGL and Vulkan are available on other platforms as well.

GLFW and SDL offer a platform independent interface to windowing and user event handling, SDL with more functionality than GLFW. Use them if you don't want to do all the window functions like sizing, resolution, user keystrokes, mouse or joystick movements, contexts in case of OpenGL by yourself and platform dependently, which can be very tedious.

What's missing in the 'toolchain' are loader libraries (GLEW belongs to that) to obtain all the function pointers and macros of the chosen API. Often they are just header files, for example for Vulkan, or glad (replacing glew) for OpenGL.

My suggestion to the OP would be to just get started. The questions will be answered automatically then.
> 1 votes

---
Tags: opengl, graphics, sdl, glfw, glew
---


title: Run a Script at Game Startup in Unity

text:
# Question
Title: Run a Script at Game Startup in Unity
I have a script that runs when the game is loading. That script sets the resolution, fullscreen, and loads other screen and important settings and applies them. I have the script attached to a `gameObject` in the main screen that have some game and scene scripts.

The problem is that everytime you return to the main scene, that script runs again causing several bugs.

Is there a way to run a script only at game startup?

# Answer
> 1 votes
I wouldn't know a better way than the way you already do: By attaching it to a gameObject in your first scene and putting your setup code in `Start()`.

As possible workarounds for the problems you encounter I would recommend:

* Create an initialization scene which runs even before your main screen. The purpose of that scene is to run any initialization code and then load your main screen scene. You can also use that scene as a loading screen for the game.
* Add a variable `private static bool initialized` to your initialization script. Then wrap the whole code of its Start method into `if (!initialized)` and end that code with `initialized = true`.

# Answer
> 6 votes
There is the `[RuntimeInitializeOnLoadMethod]` attribute. Excerpting from the documentation:

> Allow a runtime class method to be initialized when a game is loaded at runtime without action from the user.
>
> Methods marked `[RuntimeInitializeOnLoadMethod]` are invoked after the game has been loaded. This is after the `Awake` method has been invoked.
>
> **Note:** The execution order of methods marked `[RuntimeInitializeOnLoadMethod]` is not guaranteed.

```
// Create a non-MonoBehaviour class which displays
// messages when a game is loaded.
using UnityEngine;

class MyClass
{
    [RuntimeInitializeOnLoadMethod]
    static void OnRuntimeMethodLoad()
    {
        Debug.Log("After Scene is loaded and game is running");
    }
}

```

The advantage of this approach is that the method will be called no matter what scene you start up in, and you don't need a specific object in that scene to handle this in `Awake` or `Start`. (And you also don't need to keep track of a flag to skip re-doing that work if play later returns to the same scene)

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


# Question
Title: Can I reset the `[DisallowMultipleComponent]` attribute in child classes in Unity somehow?
Can I reset the `[DisallowMultipleComponent]` attribute in child classes in Unity somehow?

I want to create my base class:

```
[DisallowMultipleComponent]
public class MyCompanyClass : Monobehaviour {}

```

I want all my component scripts to inherit from the `MyCompanyClass`. So, I will be able to add only one instance of my component script to a game object at a time. I need it for most of my classes. But for some classes I still want to preserve the ability to add a few class instances to a game object, while still inheriting from the `MyCompanyClass` (because I am going to put some custom behavior into it, which is going to be used by all my component scripts).

So, I was trying to search for something like `[AllowMultipleComponent]`, but found nothing. Is there maybe another way to achieve what I want?

# Answer
> 2 votes
I can think of a couple of ways to achieve that. You can either: Write some **boilerplate code** to check whether a Component is present multiple times or not at runtime (boring and error-prone). Or, you can play around with **inheritance and interfaces** (which is Vaillancourt's good proposed solution, plus an extra by me).

The latter method grants in-editor and debugging feedback. You can also extend one of the methods above to include additional in-editor support, such as warning messages and stuff, but that's up to you (I'm not into UnityEditor scripting that much).

## Combine `[DisallowMultipleComponent]` and inheritance

This method requires you to have a base class (`MyCompanyClass`) with all properties and functions you need. Then, another class (`MyCompanyClassOneInstance`) extends the base class, therefore inheriting all non-`private` properties and functions. Besides, it has the class attribute `[DisallowMultipleComponent]` that applies to all subclasses as well. Here's a (very bad) schema of inheritance and sample class code:

*MyCompanyClass.cs*:

```
using UnityEngine;

public class MyCompanyClass : MonoBehaviour { ... }

```

*MyCompanyClassOneInstance.cs*:

```
using UnityEngine;

[DisallowMultipleComponent]
public class MyCompanyClassOneInstance : MyCompanyClass { ... }

```

Every script that extends `MyCompanyClass` will behave as a regular `MonoBehaviour`; those that extend `MyCompanyClassOneInstance` will do the same but cannot be more than one per `GameObject`. If you need `private` properties to be available to subclasses, use the `protected` modifier instead.

## Extending with interfaces

Another problem that may arise is different classes are considered different types. You can solve it with interfaces: if `MyCompanyClass` implements the interface `IMyCompany`, it is considered an object of either type (with some code tweaks). Then:

*IMyCompany.cs*:

```
interface IMyCompany
{
    void Fun1();
    void Fun2();
    ...
}

```

*MyCompanyClass.cs*:

```
using UnityEngine;

public class MyCompanyClass: MonoBehaviour, IMyCompany
{
    public void Fun1() { ... }
    public void Fun2() { ... }
}

```

*MyCompanyClassOneInstance.cs*:

```
using UnityEngine;

[DisallowMultipleComponent]
public class MyCompanyClassOneInstance : MyCompanyClass
{
    // Fun1() and Fun2() already implemented in MyCompanyClass
}

```

This way you can operate on `MyCompanyClass` and `MyCompanyClassOneInstance` components regardless of their actual type and just reference them by their interface type:

```
IMyCompany component1 = FindObjectOfType<MyCompanyClass>();
IMyCompany component2 = FindObjectOfType<MyCompanyClassOneInstance>();
component1.Fun1();
component2.Fun2();

```

---
Tags: unity
---


# Question
Title: Get world object transform relative to another object (potential parent)
I'm attempting to parent a bullethole decal to a dynamic object. I've figured out how to set the correct position for the bullethole object so that it shows at the correct position of the dynamic object, but once that dynamic object is rotated, parenting new bulletholes are skewed because I'm not compensating for the rotation of the dynamic object (the child object, bullethole decal in this case, is translated relative to the parent, which is why I'm attempting to remove the initial rotation of the parent object to get the actual rotation for the child). I've probably done a terrible job of explaining this...so here is a video of what I'm working on (note that the bulletholes that are added to the barrel before it is moved stay where they should be, and it's only after the barrel is rotated that new bulletholes become skewed)

So I believe I know what needs to happen, I'm just not sure how to go about implementing it. I need to compensate for the rotation of the barrel at the time the bullethole is parented to it, setting the rotation of the bullethole to this value. Possibly an easy question to answer for someone with experience working with quaternions.

```
if (raycast.hasHit())
{
    auto hitPoint = vel::helpers::functions::bulletToGlmVec3(raycast.m_hitPointWorld);

    bulletObject->currentPositionFromScreen = hitPoint;
    bulletObject->disposeOnNextTick = true;

    auto normal = vel::helpers::functions::bulletToGlmVec3(raycast.m_hitNormalWorld);
    float nrmDot = glm::dot(normal, glm::vec3(0.0f, 1.0f, 0.0f));

    auto bulletHoleAdjustmentValue = this->currentBulletHoleIndex == 0 ? 0.00001f : 0.00001f + (0.00001f * this->currentBulletHoleIndex);
    auto bulletHolePosition = hitPoint + (normal * glm::vec3(bulletHoleAdjustmentValue, bulletHoleAdjustmentValue, bulletHoleAdjustmentValue));

    auto bulletHoleActor = this->bulletHoleQueue.at(this->currentBulletHoleIndex);

    if (this->currentBulletHoleIndex < (this->bulletHoleQueueSize - 1))
        this->currentBulletHoleIndex++;
    else
        this->currentBulletHoleIndex = 0;

    bulletHoleActor->getTransform().setTranslation(bulletHolePosition);

    if (nrmDot < 1.0f && nrmDot > -1.0f)
        bulletHoleActor->getTransform().setRotation(glm::toQuat(glm::transpose(glm::lookAt(hitPoint, bulletHolePosition, glm::vec3(0.0f, 1.0f, 0.0f)))));
    else
        bulletHoleActor->getTransform().setRotation(90.0f, glm::vec3(1.0f, 0.0f, 0.0f));

    bulletHoleActor->setVisible(true);

    // if physics object has a user pointer, parent bullethole actor to the actor which that value represents
    if (raycast.m_collisionObject->getUserPointer() != nullptr)
    {
        auto dynamicActor = (vel::scene::stage::Actor*)raycast.m_collisionObject->getUserPointer();

        bulletHolePosition =  bulletHolePosition - dynamicActor->getTransform().getTranslation();
        bulletHoleActor->getTransform().setTranslation(bulletHolePosition);

        // Was thinking below would work, but it does not for some reason?
        //auto newRotation = bulletHoleActor->getTransform().getRotation() * glm::inverse(dynamicActor->getTransform().getRotation());
        //bulletHoleActor->getTransform().setRotation(newRotation);

        bulletHoleActor->setParentActor(dynamicActor);
    }

}

```

# Answer
> 0 votes
Alright, figured this out. I needed to put the child object into the coordinate system of it's parent, before parenting it. This was accomplished by multiplying the inverse matrix of the parent by the matrix of the child, and applying the resulting matrix to the child. Below are the changes I made to my code to accomplish this:

```
// if physics object has a user pointer, parent bullethole actor to the actor which that value represents
if (raycast.m_collisionObject->getUserPointer() != nullptr)
{
    auto dynamicActor = (vel::scene::stage::Actor*)raycast.m_collisionObject->getUserPointer();

    // get inverse of dynamicActor transformation matrix
    glm::mat4 invDAM = glm::inverse(dynamicActor->getTransform().getMatrix());
    glm::mat4 newBulletHoleMatrix = invDAM * bulletHoleActor->getTransform().getMatrix();

    // now decompose and assign each element to bulletHoleActor since my Transform class generates matrix from the individual components
    // and i don't currently have functionality to assign a new matrix and have these elements automatically update
    glm::vec3       translation;
    glm::quat       rotation;
    glm::vec3       scale;
    glm::vec3       skew;
    glm::vec4       perspective;
    glm::decompose(newBulletHoleMatrix, scale, rotation, translation, skew, perspective);
    rotation = glm::conjugate(rotation);

    bulletHoleActor->getTransform().setScale(scale);
    bulletHoleActor->getTransform().setRotation(rotation);
    bulletHoleActor->getTransform().setTranslation(translation);

    bulletHoleActor->setParentActor(dynamicActor);
}

```

---
Tags: transformation, quaternion, glm
---


# Question
Title: Given its direction, and another vector that begins at the same point, how can I find the magnitude of that vector using only vector math?
I've solved this using the law of sines, but I was wondering if there's a way to do this with just vector math.

Here's a diagram that will hopefully help illustrate what I'm trying to do:

Given `vector a` and the direction of `b`, how can I find the magnitude of `b`? Both vectors share a common origin point. The white line is just supposed to show that both vectors will extend to the same position on either the x or y axis.

# Answer
Given an initial vector \\$\vec b\\$ of arbitrary length, we can calculate two scale factors that will bring it to the same horizontal or vertical offset as our reference vector \\$\vec a\\$:

$$s\_x = \frac {a\_x} {b\_x}\\ s\_y = \frac {a\_y} {b\_y}$$

Choose \\$s\_x\\$ if you want both vectors to arrive at the same vertical line (same horizontal offset), or \\$s\_y\\$ if you want both vectors to arrive at the same horizontal line. Or you could select whichever of the two is the finite positive number closest to zero, breaking ties arbitrarily.

Let's say I choose \\$s\_x\\$, then my new modified vector is:

$$\vec b^\prime\ = s\_x \vec b\ = \begin{bmatrix}s\_x b\_x\\ s\_x b\_y\end{bmatrix}= \begin{bmatrix}\frac{a\_x}{b\_x} b\_x\\ \frac{a\_x}{b\_x} b\_y\end{bmatrix}=\begin{bmatrix}a\_x\\ \frac{a\_x}{b\_x} b\_y\end{bmatrix}$$

The magnitude of this vector is just:

$$||\vec b ^\prime|| = s\_x ||\vec b||$$
> 1 votes

# Answer
Fundamentally, you have a right-angle triangle

Your vector `a` is (conveniently) the adjacent side

You want to know the length of the hypotenuse which is coincident with `b`.

`θ` is the angle between your two vectors which we can get by calculating their dot product.

So I can't see any simpler option than

```
magnitude(a)/cos(dot(a, b))

```

Note that in your question, you alternate which vector is extended and which is attached to a right-angle. The above assumes you know `a` and want to find the magnitude of `b`.
> 1 votes

---
Tags: mathematics, vector, linear-algebra
---


# Question
Title: Intantiating objects across multiple container pages
I have this script here that generates buttons based on an array and a serialized grid transform

```
public void InitializeUI()
{
    LevelItem[] levelItemsArray = LevelSystemManager.Instance.LevelData.levelItemArray;
    for (int i = 0; i < levelItemsArray.Length; i++)
    {
        if (i % n == 0) // sets it to 15
        {
            LevelButtonScript levelButton = Instantiate(levelBtnPrefab, levelBtnGridHolder);
            levelButton.SetLevelButton(levelItemsArray[i], i, i == LevelSystemManager.Instance.LevelData.lastUnlockedLevel);
            var page = GameObject.FindObjectOfType<UI.Pagination.PagedRect>();
            page.AddPageUsingTemplate();
        }
    }
}

```

Now what I'm trying to do is make that array instantiate a new page (calling the `page.AddPageUsingTemplate()` function which is from another script) once for every 15 items of the array.

I have 75 levels and want to instantiate the buttons on a new game object which has a grid layout group, so it would be 15 buttons on each grid with 5 pages/grids in total.

I do indeed get 5 pages when I run this code, but since the transform is only set to the first one the buttons don't get placed on the other pages.

How can I place buttons after the first 15 on the following pages?

# Answer
First, I'd update your `AddPageUsingTemplate` function to return a reference to the container that should be used to add buttons to the newly-spawned page. Something like this:

```
[SerializeField] Page newPageTemplate;

public RectTransform AddPageUsingTemplate() {
    var newPage = Instantiate(NewPageTemplate);
    return (RectTransform)newPage.transform;
}

```

Then we can use this to update our "current page" as we make our buttons:

```
LevelItem[] levelItemsArray = LevelSystemManager.Instance.LevelData.levelItemArray;

// Cache the initial container as our first page.
RectTransform currentPage = levelBtnGridHolder;
int buttonsPerPage = 15;

// Do this once, not repeatedly in the loop.
var page = GameObject.FindObjectOfType<UI.Pagination.PagedRect>();

for (int i = 0; i < levelItemsArray.Length; i++)
{
    // Every 15 buttons, start a new page, and save it as our current page.
    if (i % buttonsPerPage == 0)
    {
        currentPage = page.AddPageUsingTemplate();
    }

    // Add button to the current/newly-created page.
    LevelButtonScript levelButton = Instantiate(levelBtnPrefab, lurrentPage;
    levelButton.SetLevelButton(levelItemsArray[i], i, i == LevelSystemManager.Instance.LevelData.lastUnlockedLevel);
}

```
> 0 votes

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


title: Pathing for pipe style layout

text:
# Question
Title: Pathing for pipe style layout
I've been trying to think of ways to approach doing a pipe style game like the one pictured below, but am coming up short.

The pic is from Star Trek Elite Force 2, the hacking minigame part. I've never played the game, but found this particular part via a search.

The player must click on to turn each pipe section and get a path between the blue nodes, while not connecting to any red nodes.

I assumed the way to create the pipe route is to begin from the end node and generate a path towards the starting node, then obscure the path with branches. But on trying this, the path is very obvious (pic added below), so I'm looking for other ideas.

Does anyone have any pointers to set me in the right direction?

# Answer
First, we can use a technique Squirrel Eiserloh calls "Perlin Routes" to get a more meandering, less obvious initial path.

Assign a random cost to every edge between two cells in your grid. You can do this either in a pre-process, or use a hash/noise function that maps an edge location to a (consistent) pseudorandom cost on demand. Using a 2D noise function with a few octaves gives you control over how many big detours you get, and how many smaller wiggles along the way.

Now run A\* between your start and goal tiles, using these traversal costs. Sometimes there will be high cost wall blocking the most direct path, forcing A\* to detour around it. The result is a more organic-looking, zig-zaggy path that can sometimes make U-turns or other deviations to obfuscate its aim. Mark the cells crossed by this path as part of the solution.

Now re-randomize your costs (or shift your noise/hash seed), and do it again. You'll get another chaotic path. Mark any cells it crosses that aren't already on the main path "decoy" cells.

Repeat as many times as you like to create your desired density of decoy paths. If you're using a noise function, you can choose to re-randomize only the higher octaves, leaving the base octave unchanged, so that your decoy paths mostly follow the same broad arc as the main path, but differ in the details.

Next we can add some elaboration. Look through all the empty cells that are adjacent to either a solution cell or a decoy cell, and mark some of them as decoys with some probability. Maybe higher if they're touching multiple decoy cells, lower if they're touching just one (dead ends).

Repeat that step as many times as you like to fuzz-out the paths with distractions.

Now you can go assign actual tile shapes to each tile. First, do the solution tiles, initially giving them the shape that matches the solution path through that tile. Then you can add side branches to them with some probability (eg. turning a corner or straightaway into a 3-way junction), as long as that addition doesn't connect them to a hazard.

You can do the same with your decoy paths, but periodically insert a random tile shape instead so it's not guaranteed to actually connect. Just test that doing this does not inadvertently connect a hazard to the solution path.

The remaining decoy tiles you can fill randomly, again subject to the constraint that they should not connect the solution path to a hazard.

Lastly, randomly rotate all of the tiles and verify that the start and goal are not connected.

Approaching it this way, you can get alternative solutions (multiple orientations of the solution tiles that work, or ways to use "decoy" tiles to shortcut the solution), but for many styles of puzzle this is a positive feature. And you can guarantee that even without these coincidental solutions, your puzzle will have at least one valid solution.
> 1 votes

---
Tags: path-finding
---


# Question
Title: Cubic Voxel Game, Calculate What Chunks are in the Player's View, using 3D chunks?
I need to calculate what chunks are in the player's view, meaning I need the 3D positions (the bottom, back, left corner in world space) of each chunk that is in the player's view. I'm not worried about culling, this is mainly to prioritize the generation of new chunks that are in the player's view.

These are 3D chunks, meaning unlike Minecraft, the world is infinite in all directions, including up and down. The chunks are 32x32x32 right now.

The way I am doing it now is I will look at a giant cube of chunks around the player and then do the same exact thing but around points that are cast out in front of the player's camera. This works, but it is fairly slow, I have to check every chunk if it already exists in two different dictionaries before adding it to the right one because my algorithm isn't perfect and sometimes it checks the same position twice, and then after all of that I only use a few of the closest chunk positions because if I used them all it would continue generating those chunks even after the player has moved miles away from it.

So it would be great if I could figure out a fast way to create a list of all the chunk's positions that are in the player's view with no duplicates. Any ideas at all are very welcome! Thank you.

This is my current algorithm:

```
void CheckForNewChunksAroundMultiplePoints(Vector3 playerCameraPosition, Vector3 playerCameraForward, int startingRenDist, int renderDistIncrement) // checks the surroundings as well as the player's view
{
    Vector3Int chunkPosition = positionToChunkPosition(Vector3Int.CeilToInt(playerCameraPosition));
    chunksToGenerateHash.Clear();

    // checking the surroundings of the player
    Vector3Int startingPos = chunkPosition + new Vector3Int(-surroundRenderDistanceG * chunkRowSize, -surroundRenderDistanceG * chunkRowSize, -surroundRenderDistanceG * chunkRowSize); // the bottom, back, left point of the area we check, a cube of (surroundRenderDistanceG * 2) chunks cubed, or (that * chunkRowSize) voxels cubed
    int surroundRenderRowSize = surroundRenderDistanceG * 2;

    for (int x = 0; x < surroundRenderRowSize; x++) // x
    {
        for (int z = 0; z < surroundRenderRowSize; z++) // z
        {
            for (int y = 0; y < surroundRenderRowSize; y++) // y
            {
                Vector3Int chunkToCheck = startingPos + new Vector3Int(x * chunkRowSize, y * chunkRowSize, z * chunkRowSize);

                if (!visibleChunksDictionary.ContainsKey(chunkToCheck))
                {
                    if (!chunksToGenerateHash.Contains(chunkToCheck))
                    {
                        chunksToGenerateHash.Add(chunkToCheck); // to be generated later
                    }
                }
            }
        }
    }

    // checking the surroundings of points cast out from the player's view
    Vector3[] points = GetPointsAlongPlayersView(playerCameraPosition, playerCameraForward, startingRenDist, renderDistIncrement, 3);
    for (int i = 0; i < viewPoints; i++)
    {
        chunkPosition = positionToChunkPosition(Vector3Int.CeilToInt(points[i]));

        int chunksRenderDistance = startingRenDist + (renderDistIncrement * i);
        int chunksRenderRowSize = chunksRenderDistance * 2;

        startingPos = chunkPosition + new Vector3Int(-chunksRenderDistance * chunkRowSize, -chunksRenderDistance * chunkRowSize, -chunksRenderDistance * chunkRowSize);

        for (int x = 0; x < chunksRenderRowSize; x++) // x
        {
            for (int z = 0; z < chunksRenderRowSize; z++) // z
            {
                for (int y = 0; y < chunksRenderRowSize; y++) // y
                {
                    Vector3Int chunkToCheck = startingPos + new Vector3Int(x * chunkRowSize, y * chunkRowSize, z * chunkRowSize);

                    if (!visibleChunksDictionary.ContainsKey(chunkToCheck))
                    {
                        if (!chunksToGenerateHash.Contains(chunkToCheck))
                        {
                            chunksToGenerateHash.Add(chunkToCheck); // to be generated later
                        }
                    }
                }
            }
        }
    }
}

```

# Answer
I haven't built a voxel game before, so this is theoretical, but I think this is a good starting direction:

Unity has a function `GeometryUtility.TestPlanesAABB()` that can be used to check if a bounding box is inside or overlapping a plane array. One of the main uses for this is in determining what is within the camera's view frustum and thus potentially visible to the camera.

Basic use would be like this:

```
var frustumPlanes = GeometryUtility.CalculateFrustumPlanes(Camera.main);
foreach (var chunk in chunks) {
    if (GeometryUtility.TestPlanesAABB(frustumPlanes, chunk.Bounds)) {
        GenerateChunk(chunk);
    }
}

```

Obviously it's not practical to check against every possible chunk in the world, but you could easily filter chunks by distance from the player. You don't have to store the bounds for every single chunk; since all chunks are the same size you can easily calculate the bounds dynamically.
> 0 votes

# Answer
I later looked up an implementation of this algorithm so I could do it on another thread, I didn't even know it existed and it is actually fairly simple! My implementation still uses a Unity function `Plane.GetSide(point)` but it's thread safe. It just tells you if a point is on the positive side of a plane.

```
    foreach (plane in frustumPlanes)
    {
        int inCount = 8;

        foreach (corner in corners)
        {
            if (!plane.GetSide(corner)) // the Unity function, returns true if the point is on the positive side of the plane
            {
                inCount -= 1;
            }
        }
        if (inCount <= 0)
        {
            return false;
        }
    }
    return true;

```

Implemented like this:

```
bool ChunkIsInFrustum(Vector3Int chunk)
{
    for (int i = 0; i < 6; i++)
    {
        bool chunkInFrustum = false;
        for (int j = 0; j < 8; j++)
        {
            if (frustumPlanes[i].GetSide(chunk + cornersOffsets[j]))
            {
                chunkInFrustum = true;
                break;
            }
        }
        if (!chunkInFrustum)
        {
            return false;
        }
    }
    return true;
}

```
> 1 votes

---
Tags: unity, voxels, frustum
---


# Question
Title: Problems with collisions (using vector of instances)
I wrote a for loop to check every instance of the class Wall, only the the last instance in the vector properly works

hybrid.h

```
 void reactTo(Player* other)
 {
     if (react)
     {
         if ((other->back<front && other->front > front) && (other->y > foot && other->y < head))
         {
             other->goAhead[0] = false;
         }
         else
         {
             other->goAhead[0] = true;

             if ((other->front >= back) && other->back < back && other->y > foot && other->y < head)
             {
                 other->goAhead[1] = false;
             }
             else
             {
                 other->goAhead[1] = true;
             }
         }
     }
     if (other->foot <= head && other->head >= head && other->x > back && other->x < front)
     {
         other->goAhead[2] = false;
     }
     else
     {
         other->goAhead[2] = true;
         if ((other->head >= foot) && other->foot < foot && foot && other->x > back && other->x < front)
         {
             other->goAhead[3] = false;
         }
         else
         {
             other->goAhead[3] = true;
         }
     }
     if (other->front > back && other->back <= front && other->head < head && other->foot > foot)
     {
         R = 0;
     }
     else
     {
         R = 1;
     }
 }

```

source.cpp

#include"hybrid/hybrid.h"

int main()
{
   setWindowSize(1500, 600);

   makeSequenceWall();//push back 5 Wall constructor

   Player p(300, 300,30,30,0.5,0,1,0);
   //------------
   slWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "HYBRID", false);
   while (!slShouldClose())
   {
               //----------
       p.move();
       p.render();//render the player

       for (int i = 0; i != 5; i++)//check the collision
       {
           wallSeq.at(i).reactTo(&p);
       }

       for (itr = wallSeq.begin(); itr != wallSeq.end();itr++)//render the wall
       {
           itr->render();
       }

       slRender();

   }
   slClose();
   return 0;
}

```

# Answer
> only the the last instance in the vector properly works

Yes, it looks like `void reactTo(Player* other)` only really takes into consideration stuff that happens with "this wall": it will overwrite in the player whatever happened with the "previous wall" that was checked.

You probably need to "reset" the data in your player at the beginning of each frame, then in your wall-check code, check *also* what happened with the previous wall checks (e.g. check if `other->goAhead[X]` has already been set to `false`, and if it has, don't set it to `true`). Or maybe set everything to `true` (`goAhead[X] = true;`) at the beginning of each frame, and only toggle the values to `false` if they must (i.e. don't set them to `true` in the collision-checking function).
> 1 votes

---
Tags: c++
---


title: Play and Pause State

text:
# Question
Title: Play and Pause State
## Problem

i want to implement a pause state and with a simple conditional inside the update of PlayState is very very simple. However i think that the pause has to be another state in the StateMachine so i dont know how to call that PauseState and then resume the Play State without calling the init again, i mean, i dont want to start the PlayState from zero

## Code

Main

```
 gStateMachine = StateMachine {
        ['title'] = function() return TitleScreenState() end,
        ['countdown'] = function() return CountdownState() end,
        ['play'] = function() return PlayState() end,
        ['score'] = function() return ScoreState() end,
        ['pause'] = function() return PauseState() end,
    }
    gStateMachine:change('title')

```

StateMachine

```
function StateMachine:init(states)
    self.empty = {
        render = function() end,
        update = function() end,
        enter = function() end,
        exit = function() end
    }
    self.states = states or {} -- [name] -> [function that returns states]
    self.current = self.empty
end

function StateMachine:change(stateName, enterParams)
    assert(self.states[stateName]) -- state must exist!
    self.current:exit()
    self.current = self.states[stateName]()
    self.current:enter(enterParams)
end

```

PlaysState

```
 if love.keyboard.wasPressed('p') then
        self.paused = not self.paused //Here i pause the game
    end

```

---

## Resume

Basically I want to make it more pro, and I understand that the correct way to do it according to the design patterns of video games is to incorporate a GameState that is PauseState.

My problem as I was telling you before is that when I make a change state from PlayState to PauseState, and then return to PlayState, the PlayState:init is called again, and I simply want its update not to be called and then resume correctly.

What I want to do is correct ?, Is there any way to do it right ?, I imagine something like stacking the States then Push and Pull them, but I do not know if it is correct

# Answer
In resume we want to keep the status of GameState when we go to PauseState, imagine like they are instances so, like i said in the question we can work with an array and push or pop, however in that case we just want to integrate the pause state with this characteristics, i develop something more specific for that with an auxiliar to keep the status

StateMachine definition

```
function StateMachine:init(states)
...
    self.puaseState = self.empty
end

```

Pause Function

```
function StateMachine:statePause(stateName)
    assert(self.states[stateName])
    self.pauseState = self.current
    self.current = self.states[stateName]()
    self.current:enter()
end

```

Resume Function

```
function StateMachine:stateUnPause()
    self.current = self.pauseState
    self.pauseState = self.empty
    self.current:enter()
end

```
> 0 votes

---
Tags: lua, love2d, game-state, pausing
---


# Question
Title: How to project a vector onto a plane, but not along plane normal?
In 3d space, is there any way to project a vector onto a plane, but alongside the UP vector (0,1,0) instead of the plane normal? If so, then how do I do that and what is it called?

# Answer
> 1 votes
Given a plane with normal vector \\$\vec n\\$ and any arbitrary point \\$\vec p\\$ on that plane, then for any other point \\$\vec p^\prime\\$ in that plane the following equation holds:

$$\vec n \cdot \vec p ^ \prime = \vec n \cdot \vec p$$

Now let's take your off-plane point \\$\vec q = (q\_x, q\_y, q\_z)\\$. We're going to slide it along the y axis to a new point \\$\vec q ^\prime = (q\_x, y, q\_z)\\$ so that it lies in that plane. That means...

$$\begin{align}\vec n \cdot \vec q^\prime &= \vec n \cdot \vec p\\ n\_x q\_x + n\_y y + n\_z q\_z &= \vec n \cdot \vec p\\ n\_y y &= \vec n \cdot \vec p - n\_x q\_x - n\_z q\_z\\ y &= \frac {\vec n \cdot \vec p - n\_x q\_x - n\_z q\_z} {n\_y} \end{align}$$

So, substitute your normal, point on plane, and x/z coordinates of your off-plane point \\$ \vec q\\$, and you'll get the new y coordinate that will project it vertically onto this plane.

---
Tags: 3d, mathematics
---


# Question
Title: Snapping to z or x rotation values with Quaternion.Lerp
My player is a cube. I want to restrict/prevent its rotation around *global* y axis. I am doing this using Quaternior.Lerp since I do not want to completely constraint rotation around y axis, I just want it to quickly snap back to original rotation after a small angular displacement. The problem I have is that every time the cube flips to the side around x or z axis, the local y axis is not parallel to the global y axis anymore and I need to select new local axis and restrict/prevent cube's rotation around the new axis. My way of trying to resolve this problem was the following:

1. Constantly keep track of which side of the cube is "at the bottom". I do this by figuring out which side center has lowest y position value;
2. Based on that, figure out which local axis is the closest to being parallel to the global y axis;
3. Use Quaternion.Lerp to interpolate from the current rotation to new rotation. Each time, two of the axis values stay the same, while the third one is being set to the closest 90° angle from the current value (e.g., for x axis: `Mathf.Round(transform.rotation.eulerAngles.x / 90) * 90`)

I wrote a method named `autoCorrectRotation(Vector3 rotation)` that I call in `FixedUpdate()` as `autoCorrectRotation(transform.eulerAngles);`.

Here is that method:

```
private void autoCorrectRotation(Vector3 rotation)
    {
        float eulerXX = rotation.x;
        float eulerYY = rotation.y;
        float eulerZZ = rotation.z;

        // Create 6 normal vectors for 6 sides of the cube
        Vector3 vectorDown = Quaternion.Euler(eulerXX, eulerYY, eulerZZ) * Vector3.down;
        Vector3 vectorRight = Quaternion.Euler(eulerXX, eulerYY, eulerZZ) * Vector3.right;
        Vector3 vectorUp = Quaternion.Euler(eulerXX, eulerYY, eulerZZ) * Vector3.up;
        Vector3 vectorLeft = Quaternion.Euler(eulerXX, eulerYY, eulerZZ) * Vector3.left;
        Vector3 vectorForward = Quaternion.Euler(eulerXX, eulerYY, eulerZZ) * Vector3.forward;
        Vector3 vectorBack = Quaternion.Euler(eulerXX, eulerYY, eulerZZ) * Vector3.back;

        List<Vector3> cubeNormalVectorAllA = new List<Vector3>();
        cubeNormalVectorAllA.Add(vectorDown);
        cubeNormalVectorAllA.Add(vectorRight);
        cubeNormalVectorAllA.Add(vectorUp);
        cubeNormalVectorAllA.Add(vectorLeft);
        cubeNormalVectorAllA.Add(vectorForward);
        cubeNormalVectorAllA.Add(vectorBack);

        // Sort normal vectors by ascending y value
        cubeNormalVectorAllA.Sort((a, b) => a.y.CompareTo(b.y));

        Vector3 vectorLowestY = cubeNormalVectorAllA[0];

        // Restrict the movement based on which side is "at the bottom"
        if (vectorLowestY == vectorDown || vectorLowestY == vectorUp)
        {
            transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(transform.rotation.eulerAngles.x, Mathf.Round(transform.rotation.eulerAngles.y / 90) * 90, transform.rotation.eulerAngles.z), 1f);
            Debug.Log(gameObject.tag + ": DOWN or UP");
        }
        else if (vectorLowestY == vectorLeft || vectorLowestY == vectorRight)
        {
            transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(Mathf.Round(transform.rotation.eulerAngles.x / 90) * 90, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z), 1f);
            Debug.Log(gameObject.tag + ": LEFT or RIGHT");
        }
        else if (vectorLowestY == vectorForward || vectorLowestY == vectorBack)
        {
            transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, Mathf.Round(transform.rotation.eulerAngles.z / 90) * 90), 1f);

            Debug.Log(gameObject.tag + ": FORWARD or BACKWARD");
        }

    }

```

This works exactly as I wanted only in the first case, where local y and global y are parallel, meaning when either one of original top and bottom sides of the cube are on the bottom. As soon as any of the other 4 sides are on the bottom and the rotation needs to be restricted/prevented for x or z axis, the Quaternion.Lerp does not work. Some laggy/jittering movement is present, but the rotation is not snapping to the closest 90° angle.

Any ideas on what could be wrong or if there is some other way to achieve what I want?

# Answer
> 0 votes
I achieved the movement I wanted by using

```
transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(transform.rotation.eulerAngles.x, Mathf.Round(transform.rotation.eulerAngles.y / 90) * 90, transform.rotation.eulerAngles.z), 1f);

```

in all 3 `if` sentences, insted of just in the first one. Here is a video of the resulting movement. This also brought some unwated side effects like spinning or jittery movement when going over corners, so I am still looking for the solutions for the same logic of movement. That is: you must be able to roll "to the side" when going over the edges, but no arbitrary spining around y axis is allowed.

Edit: The whole script now becomes a single line:

```
transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(transform.rotation.eulerAngles.x, Mathf.Round(transform.rotation.eulerAngles.y / 90) * 90, transform.rotation.eulerAngles.z), 1f);

```

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


# Question
Title: Procedurally generated mesh makes weird shapes
I'm developping a procedural terrain generator in Unity 2020.3, using Sebastian Lague's tutorials and knowledge i've gathered through college projects. The heightmap looks just fine, and i had no issues in 2D, but upon generating the Meshes, i'm getting these weird stairs-like shapes: https://i.stack.imgur.com/xGOdf.png

Debugging that kind of issue has proven quite hard and i spent a few hours not understanding what's wrong already. Displaying the values of my heightmap does not show any issue, values are what i would expect from perlin noise.

I need help understanding what's wrong.

For reference, the noise generation function:

```
public static float[,] GenerateNoise(int width, int height, int octaves, float persistance, float lacunarity, float scale, Vector2 offset, float redistribution, int seed,
                                        bool islandMode, float waterCoefficient, float warping1, float warping2
    ) {
        float[,] results = new float[width, height];
        float begin = Time.realtimeSinceStartup;

        //seed to have the possibility to recreate a noisemap
        System.Random randomGenerator = new System.Random(seed);
        //random offset
        Vector2[] octaveOffsets = new Vector2[octaves];
        for(int i = 0; i < octaves; i++)
        {
            float offsetX = randomGenerator.Next(-100000, 100000) + offset.x;
            float offsetY = randomGenerator.Next(-100000, 100000) + offset.y;
            octaveOffsets[i] = new Vector2(offsetX, offsetY);
        }

        for (float y = 0; y < width; y++) {
            for (float x = 0; x < height; x++) {
                // Initial values
                float amplitude = 1;
                float frequency = 1;
                float noiseValue = 0;

                // the FBM algorithm to generate layers
                for (int i = 0; i < octaves; i++) {
                    float xCoord = x / width * scale * frequency + octaveOffsets[i].x;
                    float yCoord = y / height * scale * frequency + octaveOffsets[i].y;

                    //warping reusing code from https://www.iquilezles.org/www/articles/warp/warp.htm
                    //add 1st level of warping
                    Vector2 q = new Vector2(Mathf.PerlinNoise(xCoord, yCoord),
                                            Mathf.PerlinNoise(xCoord + 5.2f, yCoord + 1.3f));

                    //second level of warping
                    Vector2 r = new Vector2(Mathf.PerlinNoise(xCoord + warping1 * q.x + 1.7f, yCoord + warping1 * q.y + 9.2f),
                                            Mathf.PerlinNoise(xCoord + warping1 * q.x + 5.2f, yCoord + warping1 * q.y + 1.3f));

                    noiseValue += Mathf.PerlinNoise(xCoord + warping2 * r.x, yCoord + warping2 * r.y) * amplitude;

                    frequency *= lacunarity;
                    amplitude *= persistance;
                }

                //redistribution to allow creation of flat areas if need be
                float finalValue = Mathf.Pow(noiseValue, redistribution);
                //create an island shape by lowering noise value the further you are from the middle of the map
                if (islandMode)
                    finalValue = finalValue - Vector2.Distance(new Vector2(x, y), new Vector2(width / 2, height / 2)) / (width * waterCoefficient);
                results[(int) x, (int) y] = finalValue;
            }
        }

        Debug.Log("time to generate heightmap: " + (Time.realtimeSinceStartup - begin));
        return results;
    }

```

And the Mesh generation function:

public static Mesh GenerateMesh(float[,] noisemap, float minHeight, float maxHeight, int width, int height, float pointsPerUnit) {
        float begin = Time.realtimeSinceStartup;
        Mesh mesh = new Mesh();
        mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;
        int nx = noisemap.GetLength(1);
        int ny = noisemap.GetLength(0);

        Vector3[] vertices = new Vector3[nx * ny];
        //calculate vertices
        for (int y = 0; y < ny; y++)
        {
            //only write the point if he is not at the end of a line (as it would not have a point to its right)
            for (int x = 0; x < nx; x++)
            {
                vertices[y * nx + x] = new Vector3((float) x / pointsPerUnit, noisemap[x, y] * maxHeight, (float) y / pointsPerUnit);
            }
        }

        Vector2[] uvs = new Vector2[vertices.Length];
        for (int i = 0; i < uvs.Length; i++)
        {
            uvs[i] = new Vector2(vertices[i].x / width, vertices[i].z / height);
        }

        List<int> triangles = new List<int>();
        //skips the first line as it has to points above
        for (int y = 1; y < ny; y++)
        {
            //only write the point if he is not at the end of a line (as it would not have a point to its right)
            for (int x = 0; x < nx - 1; x++)
            {
                int current = y * nx + x; // the "number" of the current point in a "1D" fashion
                //write current, diagonal, above and current, right, diagonal
                int above = current - ny; //the point above the current
                int rDiagonal = above + 1; //the point in the right diagonal of the current
                int right = current + 1;//the point to the right of the current

                triangles.Add(current);
                triangles.Add(rDiagonal);
                triangles.Add(above);

                triangles.Add(current);
                triangles.Add(right);
                triangles.Add(rDiagonal);
            }
        }

        mesh.SetVertices(vertices);
        mesh.triangles = triangles.ToArray();
        mesh.SetUVs(0, uvs);
        mesh.RecalculateNormals();
        Debug.Log("time to generate mesh: " + (Time.realtimeSinceStartup - begin));
        return mesh;
    }
```

# Answer
> 1 votes
It looks like your offset range is relatively large in relation to the float number format. Floats have about 23 bits for actual number data, the rest being for the exponent and sign. At extreme offset values around 100000, you'll only have about 4-5 bits worth of precision left for the fractional part between integer values. This can very easily cause stepping issues like this, and it also makes sense that it is occurring in only one direction -- only one of your randomized offsets happened to be a big number.

I do like that you have an offset step, though. This is instrumental in reducing origin-biased patterns where the same parts of the noise add together at different frequencies, especially when you can't use different seeds, and a lot of people don't account for it.

To mitigate the problem, you could reduce the offset range by a few orders of magnitude. This should correct it in your implementation as it is, but it isn't the solution I would go with. It would be better to replace the noise function entirely, for two reasons:

1. Mathf.PerlinNoise isn't a very good noise function. Being the unmitigated Perlin algorithm of its namesake, it creates significant feature direction bias along 45 and 90 degree angles relative to the coordinate space. This means you'll only get mountains and coastlines that follow these directions -- something that's ideally supposed be unbiased. It's also 2D-only, meaning it isn't possible to do a domain-rotation trick to produce good 2D results from 3D. Take it with a grain of salt when tutorials recommend you to use this function, because this compromise is entirely unnecessary in most applications. It's better to import a library that support a good Simplex-type noise implementation, or a 3D Perlin which you can domain-rotate if you ensure to apply the rotation. It's Unity's fault for including this function in isolation - thereby influencing people to use it, and tutorial writers' faults for not understanding and conveying the issue, but it's also easy to solve for yourself and import a library.
2. You can support much larger coordinates and bigger maps, without worrying about issues like this, if you pick a noise library that supports doubles instead of floats.
3. (EDIT) Most libraries also support seeding noise the "right" way, rather than randomizing offsets in an unseedable function.

I would take FastNoiseLite (drop the `FastNoiseLite.cs` file into your project) and do one of the following.

* For 2D Simplex-type noise, `setNoiseType(FastNoiseLite.NoiseType.OpenSimplex2)` (default), and use `GetNoise(x, y)`
* For domain-rotated 3D Perlin, do `setRotationType3D(FastNoiseLite.RotationType3D.ImproveXYPlanes)`, `setNoiseType(FastNoiseLite.NoiseType.Perlin)`, and only use `GetNoise(x, y, 0)` not `GetNoise(x, y)`. You can also:
    + Do `setRotationType3D(FastNoiseLite.RotationType3D.ImproveXZPlanes)` and `GetNoise(x, 0, z)`
    + Use this to improve Value and ValueCubic which have similar problems as Perlin when unrotated or used in 2D
    + Use this on the 3D Simplex-type noise to further improve their results.
    + Actually use the third coordinate, such as for 3D noise in a mostly-2D world. Use your vertical coordinate in place of the previously-unused one, for best results.

This library can also do the fractal summation for you, by setting the fractal type to `FBm`, so you can completely offload that stage. You can still do it yourself though, by leaving this set to `None`.

Important usage details:

* It handles frequency scaling internally, with frequency set to `0.01` by default. You can either embrace this, or call `SetFrequency(1)` to continue doing it how you were.
* Its range is **-1 to 1** not 0 to 1. So if you are going to use the `Mathf.Pow` function to curve the value range, or just need the values to match what you've come to expect, then you can rescale to 0 to 1 range by doing `value = value * 0.5f + 0.5f`.

To use doubles rather than floats, there is a configuration option at the top of the `FastNoiseLite.cs` file.

Final note: I see your island falloff uses vector distance. It is better to use a squared distance based falloff curve, in order to avoid a sharp point in the middle. Replace your `finalValue = finalValue - Vector2.Distance(new Vector2(x, y), new Vector2(width / 2, height / 2)) / (width * waterCoefficient);` line with `finalValue = finalValue - (new Vector2(x, y) - new Vector2(width / 2, height / 2)).sqrMagnitude * (1.0f / (width * width * waterCoefficient));` It's also more efficient because it avoids the square root call.

---
Tags: unity, procedural-generation, mesh
---


# Question
Title: How do I program procedural generation with objects that must fit together in specific ways?
I'm working on a game where I have to procedurally generate a large open room building. I'm using Unity, but I think this applies to any engine. The room is made up of different wall segments. What makes this difficult for me is the ends of the segments have to join with a similar end of another segment. There are 2 types of ends. Flat and angled. The purpose of the angled ends is to create an outside corner. Meaning for example a flat wall then turns into a hallway it would use angled ends to make the transition.

The method I tried initially was to define each segment type and what the follow up modules could be. Meaning SegmentA can be followed by: SegmentB, SegmentC, and SegmentD. Then I would randomly select which of those to add and place it, then move on and repeat. It works ok, but I feel like there is a better way to do it. It's pretty unwieldy and is kind of prone to bugs. I also run into issues trying to close the loop and return to the original segment.

# Answer
> 0 votes
DMGregory was correct with his answer. Using the bitmasking worked well for me. I used this a reference. tutsplus My method was to define each segment by the resulting bit number. I used an array of bits since I had to reorder them depending on the rotation.

# Answer
> 0 votes
> the ends of the segments have to join with a similar end of another segment

Corner pieces could be much simpler: 1 mesh for a wall, 1 mesh for a corner.

---

> I also run into issues trying to close the loop and return to the original segment.

Loop generation is hard and scales with degrees of freedom in the model. The rule of thumb is to start with a loop if you want a loop.

For example, you may start with a square made from many segments, move the points around to your taste while avoiding collisions, then "materialize" resulting scheme into a scene.

---
Tags: unity, c#, procedural-generation
---