# Question
Title: How do you solve where the camera should be on a bezier curve depending on player? (camera on rail)
I am writing a game where I require a camera on rail; That is, the camera's path is fixed and follows a bezier curve. However, I cannot find any resources online for solving the closest point on a bezier curve closest to another arbitrary point, despite being something that should be common.

A good example of a game that does it very well is the original Crash Bandicoot trilogy.

So how do you do it? Or am I overthinking the problem?

# Answer
> 2 votes
I could not find anything on this subject so I invented my own algorithm which works by iterating over and over again to find more precise results. The higher you set the iteration count, the more precise it will be.

hope this helps anyone who has the same problem

```
public Vector3 GetPointClosestTo(Vector3 p, out float result, out int curve) {
// an optimized algorithm i invented which finds the closest point on a bezier to another arbitrary P point
// this algorithm is iteration based, meaning that the more iterations your perform, the more precise the results will be
// it is optimized to be fast but this particular implemention is not necessarily as fast as it could be, and the code is certainly not pretty
// optimizing this is left as an exercise to the viewer

// points is a vector3 array which defines the anchors and control points of the current bezier curve in the following format
// [anchor, control, control] * n, [anchor]
// where n is as many bezier curves which this spline defines. it pieces multiple bezier curves together, although the algorithm could be adapted for single curves that are alone

// 1. first we find the closest anchor and the corresponding curves that this anchor touches
int acount = CurveCount + 1; // number of anchors
Vector3[] anchors = new Vector3[acount];
for (int i = 0; i < acount; i++) {
    anchors[i] = transform.TransformPoint(points[i * 3]);
}

Vector3 closest;
int index;
GetClosestVector(anchors, p, out closest, out index);

float[] ts;
int[] indices;

// 2. we setup our dataset
bool fleft = false; // far left
bool fright = false; // far right
if (index == 0) {
    ts = new[] {0f, 0.5f};
    indices = new[] {index * 3};
    fleft = true;
} else if (index == anchors.Length - 1) {
    ts = new[] {0.5f, 1f};
    indices = new[] {(index - 1) * 3};
    fright = true;
} else {
    ts = new[] {0.5f, 1f, 0f, 0.5f};
    indices = new[] {(index + -1) * 3, (index + 0) * 3};
}

// 20 should be good enough for most cases, increase for better precision????????
const int iterations = 20;
float ot = result = 0f;
curve = 0;

for (int i = 0; i < iterations; i++) {
    float t0, t2;

    if (ts.Length > 2) {
        t0 = ts[0];
        t2 = ts[3]; // if we're still on an anchor point, then it's a 2-curve
    } else {
        t0 = ts[0];
        t2 = ts[1];
    }

    int i0 = indices[0]; // left index
    int i2 = indices[0];
    if (indices.Length > 1)
        i2 = indices[1];

    // calculate left/right focal points
    Vector3 v0 = transform.TransformPoint(Bezier.GetPoint(points[i0], points[i0 + 1], points[i0 + 2], points[i0 + 3], t0));
    Vector3 v2 = transform.TransformPoint(Bezier.GetPoint(points[i2], points[i2 + 1], points[i2 + 2], points[i2 + 3], t2));

    // test left/right focal points against the center focal
    Vector3[] test = {v0, closest, v2};
    float[] tmapping = {t0, ot, t2};
    GetClosestVector(test, p, out closest, out index);

    result = ot = tmapping[index];
    curve = i0;

    // update
    if (index != 1) { // shift focal point to the left/right && increase focality
        float hf = Math.Min(t0, t2) * 0.5f;
        if (fleft) // left-most anchor
            hf = t2 * 0.5f;
        else if (fright) // right-most anchor
            hf = (t2 - t0) * 0.5f;

        float t = t0;
        if (index == 2)
            t = t2;

        ts[0] = t - hf;
        ts[1] = t + hf;

        Array.Resize(ref ts, 2);

        if (index == 2 && indices.Length > 1)
            indices[0] = indices[1];
        Array.Resize(ref indices, 1);
    } else { // increase focality
        float hf;

        if (ts.Length > 2) { // we're still on the 2-curve anchor
            hf = t2 * 0.5f;
            ts[0] = t0 + hf; // compress >> o
            ts[3] = t2 - hf; // compress o <<
        } else { // we're working on a single curve now
            hf = (t2 - t0) * 0.25f; // WTFFFF

            ts[0] = t0 + hf; // push >> o
            if (!fright)
                ts[1] = t2 - hf; // push o <<
        }
    }
}

curve /= 3;

return closest;
}

private void GetClosestVector(Vector3[] vectors, Vector3 p, out Vector3 closest, out int index) {
float dist = 9999999999f;
closest = Vector3.zero;
index = 0;

for (int i = 0; i < vectors.Length; i++) {
    Vector3 v = vectors[i];
    float d = Vector3.Distance(v, p);
    if (d < dist) {
        dist = d;
        closest = v;
        index = i;
    }
}
}

```

# Answer
> 1 votes
Assuming a character goes from A to B and you want to follow that with a beizer curved camera. You have a Beizer Curve parameterized with normalized time B(t). "time" in this case doesn't have to be real time, but just some normalized value that tells the function B, how far along the curve you are, such that it can calculate the correct point. So what you need to do is just alter the what t is here to being the players position compared to A and B. Something along the lines of this pseodo code:

```
Vector3 pathVector = B - A; //Path from A to B
Vector3 playerOnPathVector = Project(PlayerPos, PathVector); //Project the players position vector on to the pathvector
Vector3 t = Normalize(PlayerOnPathVector, PathVector); //normalize value (0-1)

```

In a game like crash where you normally go along one of the aligned axis, it is immidiately apparent that this would work. However, it will also work in more complicated scenarios where path is not axis aligned.

Note that this assumes that you always go closer to B along the path, if you have some detour on your way to the endpoint t would become lower, and thus go back on the beizer curve. If you have segments where you go further away from B, just split up the paths to have intermediate start and endpoints.

If you look at my beautiful paint art below, you can see as the player approaches I0, t would increase, but when going to I1, t would start to decline again. This can be prevented by making these intermediate points that in combination will make t increase along the path.

---
Tags: unity, 3d, camera, curves, beziers
---


title: zoom to cursor calculation

text:
# Question
Title: zoom to cursor calculation
I want to be able to zoom in and out of the map using the scroll wheel. I want to zoom towards the cursor like Google Maps does, but I'm completely lost on how to calculate the movements.

So far, all I have is the resizing, but I now need to change the map position.

What I have: map `x` and `y`; map `width` and `height`; cursor `x` and `y`.

Any help would be most welcome.

# Answer
> 13 votes
Assuming that your *map\_x* and *map\_y* mean the top left corner of the screen area over your map in map coordinates and *map width* and *map height* are the dimensions of your map at the actual zoom level again in map coordinates (not screen coordinates), first, calculate your zoom ratio:

```
zoom_x = screen_width / map_width;

```

Let's assume the aspect ratio does not change: *zoom\_x* = *zoom\_y* = *zoom*; If you want to change the zoom to *next\_zoom*, first find the coords of the new screen over your map:

```
new_map_width = screen_width / next_zoom

new_map_height = screen_height / next_zoom

```

We need to find the change in both values and distribute these depending on the mouse position on the screen. If the mouse position would be in the exact center screen position, then this change would be evenly divided between the top-bottom and left-right sides. Since the mouse is at an arbitrary position, we need to find the ratios for the height and width changes for the sides.

Let's assume that the screen dimensions are *screen\_max\_width* and *screen\_max\_height*; The new coordinates of your screen (dimensions *new\_map\_width*, *new\_map\_height*) over your map are:

```
new_map_x = map_x - (cursor_x / screen_max_width * (new_map_width - map_width))
new_map_y = map_y - (cursor_y / screen_max_height * (new_map_height - map_height))

```

To convert any map coordinate to a screen coordinate:

```
screen_x = map_x * zoom

```

and to convert back:

```
map_x = screen_x / zoom

```

# Answer
> 6 votes
I couldn't figure out what Konrad's variables were supposed to mean in my game (map width? My map is infinite, so... that's the same as the screen width then maybe? It didn't work out), so I figured it out from scratch. The way I figured:

(TL;DR: read only the **bold** parts.)

* When zooming, **some pixels drop off the screen (zooming in) or newly become visible on the screen (zooming out). This number of pixels determines the maximum amount by which you want to shift your view**. For example, if you have a view of 800px wide and you have your cursor at 200px, then you want 25% of the new pixels to appear left of the cursor and 75% to the right.
* To **calculate the ratio of pixels that should drop off on the left vs. the right**, one has to look from the center and see how far off to the side it is. In the example, the middle is at 400px, so the cursor being at 200px means you're at -25% (`-0.25`). On the far right (cursor at 800px), you would be at +50% (`0.5`).
* `view_width / 2` gives us the center and `mouse_x - (view_width / 2)` gives us the difference, in pixels. To get the (float) ratio, you need to divide that difference by the total again, i.e.
**`side_ratio = (mouse_x - (view_width / 2)) / view_width`**
* To find the number of pixels that will drop off the side, you want to find the difference between the two zoom levels.
* The part of the view visible on the current zoom level is `view_width * zoom` where `zoom` is `1.0` for no zoom or `0.5` for having everything at half size (zoomed out).
* The number of pixels newly visible is therefore:
**`pixels_difference = (view_width / old_zoom) - (view_width / new_zoom)`**
* Finally, multiply the two together:
**`view_x_offset += pixels_difference * side_ratio`**
* Apply the same to your Y axis, using `view_height` and `mouse_y` instead.

Full code to scroll upon mouse wheel for Phaser 3:

```
function create() { // called upon scene creation
    document.addEventListener('wheel', function(scroll_event) {
        handle_scroll(scroll_event);
        scroll_event.preventDefault();
        return false;
    }, false);
}

function handle_scroll(scroll_event) {
    var cam = sceneMain.cameras.cameras[0];

    var oldzoom = cam.zoom;
    var newzoom = oldzoom * (scroll_event.deltaY > 0 ? 1.1 : 0.9); // deltaY>0 means we scrolled down

    var mouse_x = scroll_event.clientX;
    var mouse_y = scroll_event.clientY;

    var pixels_difference_w = (view_width / oldzoom) - (view_width / newzoom);
    var side_ratio_x = (mouse_x - (view_width / 2)) / view_width;
    cam.scrollX += pixels_difference_w * side_ratio_x;

    var pixels_difference_h = (view_height / oldzoom) - (view_height / newzoom);
    var side_ratio_h = (mouse_y - (view_height / 2)) / view_height;
    cam.scrollY += pixels_difference_h * side_ratio_h;

    cam.setZoom(newzoom);
}

```

(The code is copied from my game, but I changed some of the structure and edited most variable names to match the explanation, so while I tested my code, please let me know if I introduced any mistakes in this example.)

# Answer
> 2 votes
Or for people using XNA when the system is flipped.

First calculate the mouse cursor in the world. Since the mouse position system in XNA is flipped subtract the mouse Y from the height of the screen.

```
var mouseinWorld = new Vector2(
    (cursor.X * oldZoomLevel) - world.X,
    ((cursor.Y - screen.Height) * oldZoomLevel) + world.Y));

```

Now change your zoomlevel.

Next is to calculate the new world location.

```
var newX = (cursor.X * newZoomLevel) - mouseinWorld.X;
var newY = mouseinWorld.Y - ((cursor.Y - screen.Height) * newZoomLevel)

```

Now update the world location with the newly calculated coordinates.

```
world = new Vector2(newX, newY)

```

---
Tags: gui, maps
---


# Question
Title: Why when I do an isometric projection do I get a "dimmetric" view?
First of all I would like to apologize for my poor English. It is not my native language.

I have some doubts about isometric projection that perhaps I do not know how to describe them and I would like to appeal to your knowledge to evacuate them.

I am introducing in the area of video games, doing some research, and testing some concepts.

I am following the article on wikipedia: https://en.wikipedia.org/wiki/Isometric\_projection

And the help given in this question: Rendering models in isometric view

My intention is to achieve an isometric view of a 3D world. Where (x, y, z) will be (width, length, height) of it.

X axis: horizontal: -x to the left, + x to the right.

Y axis: vertical: + and up, -y down

Z axis: + z towards the screen, -z away from the screen

This world with such an arrangement of axes is projected isometrically.

Therefore following the previous links I have made a rotation/projection matrix with the angles (-35.264º, 45º) = (atan(-1/sqrt(2), PI/4) on the X and Z axis:

M = Rx(atan(-1/sqrt(2)) * Rz(PI/4)

Where Rx and Rz are the matrices of rotations on the x and z axes respectively. With this I get the following results (rounded to 5 decimal places):

$$\begin{pmatrix} 0.70711 & -0.70711 & 0.0\\ 0.57735 & 0.57735 & 0.57735\\ -0.40825 & -0.40825 & 0.81650\end{pmatrix}$$

Now suppose I have a 1x1x1 cube whose centroid is at the origin (0,0,0). When doing the multiplication: M * V

Where V is a column matrix with the coordinates of the 8 points of the cube $$\begin{pmatrix} -0.5&0.5&-0.5&-0.5&0.5&0.5&-0.5&-0.5\\ -0.5&0.5&0.5&-0.5&-0.5&0.5&0.5&-0.5\\ -0.5&-0.5&-0.5&-0.5&0.5&0.5&0.5&0.5\end{pmatrix}$$

Instead of getting an isometry, I'm getting a dimetry! I see this when I measure the angles between the axes. And they give me 130º, 100º, 130º. When the theory says that it should get 120º, 120º, 120º. The result is:

$$\begin{pmatrix} 0.70711&0.0&-0.70711&0.0&0.70711&0.0&-0.70711&0.0\\ -0.28868&0.28868&-0.28868&-0.86603&0.28868&0.86603&0.28868&-0.28868\\ -0.40825&-0.8165&-0.40825&0.0&0.40825&0.0&0.40825&0.8165\end{pmatrix}$$

As my equipment is broken and the computer I am using is borrowed, I do not have my working tools to thoroughly test this. And I have relied on Excel and graphing by hand. At the time of drawing, and measuring the angles between the axes formed with the protractor I obtain that:

Angle XY: 100º

Angle XZ: 130º

Angle YZ: 130º

So the angle between the horizontal and X, or Y is 40º instead of being 30º

What am I doing wrong? Has the rounding of decimals in M been so marked that there is this difference in the projection?

**EDIT** I am attaching a photo of the resulting Viso matrix. Please excuse the poor quality of the photo, but I do not have good lighting and the camera is not entirely good.

Maybe it is not my best graph, but it is quite noticeable that the angles are not 120º as the theory indicates.

**EDIT 2:**

Continuing with my calculations, I decided to calculate the matrix in Wolfram Alpha to check if I was doing the steps well.

The calculated rotation / projection matrix does not differ from the one I explained previously, if we consider the rounding of decimals to 5 decimals. You can see the exact matrix at this link.

And then I proceeded to calculate the angle between the unit vectors x and y, to be surprised that it is approximately 101.5º. When making my graph, I have screwed up for only 1.5º

Now, if the angle is calculated considering the 3 dimensions of the vectors x and y, it obtains as expected 90º

This makes me uneasy since, I am following exactly the angles indicated in the sources that I have already cited previously.

What am I doing wrong?

**EDIT 3:**

In a basic test, trying to make the angles between the axes be 120º, I found that with a rotation angle of 60º instead of 35,264º, I achieved a very good approximation. But I will have to check my calculations well. And don't trust too much what the transporter says.

Any help I will be very grateful

**EDIT 4 - 2020-04-26** (and possible self-response) **:**

I have set out to analyze what was happening in my calculations and rotations. I have come to an answer to this, although I am not completely sure, I have a 1% doubt and that is enough for me not to answer my own question.

Everything seems to be due to a particularity of how I am facing the design of my world (which at least for me, is natural and appropriate). My 3D world is oriented so that the axes are:

x-axis: width of the world

y-axis: Long of the world

z-axis: height of the world

And the orientation is such that:

x: horizontal

y: vertical

z: perpendicular

This is the logical representation of the world.

The theoretical development indicates that the isometric projection is obtained by making two rotations (atan(1/sqrt(2), pi/4) on the axes (x,z).

But since my z axis is rotated with respect to x by 90º (pi/2) instead of applying atan(1/sqrt(2)), it must be the complementary angle of this: acos(1 /sqr(3)).

Furthermore, the angle must be negative to obtain a view from the top. Otherwise you get a view from the bottom to the top.

Therefore the angle sought is -cos(1/sqrt(3)), which is approximately -54.7356º.

With this new angle when applying the combined rotation Rx\*Rz we obtain the correct matrix.

And now you can see a correct symmetrical projection instead of an "approximate" dimetry. The calculations of the angle between the unit axes can be made and they will be able to verify that the angles will indeed be 90º between them. In a similar way, it can be verified that if we take columns of this matrix as vectors the coordinates (x, y) and measure the angle between them and it will effectively be 120º.

You can use the widget in Wolfram Alpha in case you want to check the latter.

The development I made to get to this angle is much longer. What I exposed here is the short story.

I wasn't testing silly angles. Instead I went in the opposite direction, starting from what the resulting matrix should look like, and analyzing what values meet the conditions of the angles for an orthogonality, as well as the projection (x, y) being 120º.

At my first impression, it was a mere coincidence that the final angle for rotation in Rx () is the complement of atan(1/sqrt(2))

If the reasoning that I have carried out is sufficient to finish the topic, and if it turns out to be interesting for others, I can explain the analytical procedure of how this famous angle is reached. For this instead of editing, I will give a formal answer to my question.

I think a good time has passed, and to tell the truth I am a little disappointed because this has become a monologue. And my intention is that someone else could explain to me what was wrong. It must be that my question is not attractive enough, or that such an exhaustive and detailed description of my problem is boring.

# Answer
> 1 votes
Well I think too much time has passed and I don't want to extend this too much. Perhaps what I asked was so silly and absurd that I didn't deserve to spend some time on it, or that it's complex enough that nobody dared to comment.

Whatever the reasons for the lack of participation, it doesn't matter anymore. I am able to answer myself.

As I said before, the correct angle for my case is -acos(1/sqrt(3)). I explain here how to get to this one.

We have a rotation/projection matrix that combines two rotations: one on the x axis and one on the z axis:

M = Rx(?)\*Rz(45º)

This multiplication will produce a matrix that takes the following form:

$$\begin{pmatrix} a & -a & 0.0\\ b & b & c\\ d & d & e\end{pmatrix}$$

A few things must also be accomplished:

1. The angle between the column vectors must be 90º to guarantee orthogonality
2. In turn, the vectors \[a, b\] and \[-a, b\] must have an angle of 120º
3. Similarly, the angle between vectors \[a, b\] and \[0, -c\] must also be 120º
4. By colorary of point 2, We have that the angle between \[a, b\] and the x axis must be 30º

The value of a can be obtained directly by the multiplication of matrices, and by the characteristics of these is that it is reduced to: a = sin(pi/4) = 1/sqrt(2)

By trigonometry we know that those 30º indicated in point 4 respond to:

tan(30º) = b/a

So that:

b = a * tan(30º) = a * tan(pi/6)

b = 1/sqrt(2) * tan(pi/6) = 1/sqrt(6)

On the other hand, by the multiplication of matrices b must meet:

b = cos(?) * a

From this expression we can obtain the angle we were looking for by replacing the values that we previously had:

cos(?) = (1/sqrt(6))/(1/sqrt(2)) = 1/sqrt(3)

? = acos(1/sqrt(3))

Also since the direction of rotation is inverse, due to the particularity in how the coordinate system of my world was thought:

Angle = -acos(1/sqrt(3)) aprox. -54.74º

Values for c, d, e are obtained by matrix multiplication:

c = -sin(angle) = -sin(-acos(1/sqrt(3))) = sqrt(2/3)

d = sin(angle) * a = sin(-acos(1/sqrt(3))) * (1/sqrt(2)) = -1/sqrt(3)

e = cos(angle) = cos(-acos(1/sqrt(3))) = 1/sqrt(3)

Orthogonality properties are guaranteed by the multiplication of matrices Rx()Rz()

And since we have "forced" the angle between \[a, b\] and \[-a, b\] to be 120º and that between \[a, b\] and the x-axis there is 30º, it is to be expected that the angle between the 3 projected axes exist 120º.

It can be verified by calculating that: AngleBetween (\[a, b\], \[0, -c\]) = 120º

This answer complements and reinforces the 4th edition that he had made. In this edition another aspect is explained, perhaps from a "more geometric" point of view such as, and why this angle is obtained and not the theoretical one of 35.264º

I think this may serve others who are in the same situation or in which their coordinate systems are different from the theoretical one expected to apply the isometric projection with the angles (atan(1/sqrt(2)), pi/4) to Rx() and Rz().

Thank you to all who stopped to read all this.

---
Tags: 3d, mathematics, isometric, projection
---


title: How to map texture across whole face?

text:
# Question
Title: How to map texture across whole face?
I'm trying to map a texture to a square face in OpenGL 3.2, but the texture gets tiled in the upper right corner. I've tried changing the uv coordinates, vertices and shaders, but nothing seems to have the desired effect. Sorry if it's a lot of code, I've done my best to extract only the relevant parts. Please explain your answer and include any relevant questions or documentation, so I can understand why this is happening.

**What my code does:**

**What I'm trying to do:**

**object.vs**

```
#version 150 core

precision mediump float;

in vec2 vertex_texture_coord;
in vec3 vertex_normal;
in vec3 vertex_position;

out vec3 position;
out vec3 normal;
out vec4 color;
out vec2 texture_coord;

uniform mat4 transform;
uniform mat4 model;
uniform vec4 self_color;

void main()
{
    gl_Position = transform * vec4(vertex_position, 1.0);
    position = vec3(model * vec4(vertex_position, 1.0));
    normal = normalize(mat3(transpose(inverse(model))) * vertex_normal);
    color = self_color;
    texture_coord = vertex_texture_coord;
}

```

**object.fs**

```
#version 150 core

precision mediump float;

out vec4 fragment_color;

in vec3 position;
in vec3 normal;
in vec4 color;
in vec2 texture_coord;

uniform vec3 light_color;
uniform vec3 light_position;
uniform sampler2D textureObj;
uniform int texture_mode;

void main()
{
    // ambient
    float ambientStrength = 0.1;
    vec3 ambient = ambientStrength * light_color;

    vec3 light_direction = normalize(light_position - position);
    float diff = max(dot(normal, light_direction), 0.0);
    vec3 diffuse = diff * light_color;
    vec4 result = vec4(ambient + diffuse, 1.0) * color;
    if (texture_mode == 0) {
        fragment_color = result;
    } else {
        vec4 tex_color = texture(textureObj, texture_coord);
        if(tex_color.a == 0.0)
            discard;
        fragment_color = tex_color;
    }
}

```

**square.obj**

```
# Blender v2.80 (sub 75) OBJ File: 'square.blend'
# www.blender.org
mtllib square.mtl
o Cube
v 1.000000 1.000000 0.000000
v 1.000000 -1.000000 0.000000
v -1.000000 1.000000 0.000000
v -1.000000 -1.000000 0.000000
vt 0 0
vt 0 1
vt 1 1
vt 1 0
vn 0.0000 0.0000 1.0000
usemtl Material
f 4/1/1 3/2/1 1/3/1 2/4/1

```

**viewer.py**

```
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GL import shaders
import glm
from pywavefront import Wavefront
import numpy as np
from PIL import Image
from os.path import dirname, realpath, join
from ast import literal_eval
from screeninfo import get_monitors

try:
    from ctypes import windll
    """prevents stretching on windows"""
    windll.user32.SetProcessDPIAware()
except:
    pass

screen = get_monitors()[0]

dir_path = dirname(realpath(__file__))
uv_test_png = join(dir_path, 'uv_test.png')
square_obj = join(dir_path, 'square.obj')

with open(join(dir_path, 'object.fs'), 'r') as shader_file:
    object_fs = shader_file.read()
    shader_file.close()
with open(join(dir_path, 'object.vs'), 'r') as shader_file:
    object_vs = shader_file.read()
    shader_file.close()

def dedup_and_index(sequence):
    sequence_ref = {}
    new_sequence = []
    indices = [i for i in range(len(sequence))]
    for i, vertex in enumerate(list(sequence)):
        strung = str(list(vertex))
        if strung in sequence_ref:
            indices[i] = sequence_ref[strung]
        else:
            indices[i] = len(sequence_ref)
            sequence_ref[strung] = indices[i]
    for i in sequence_ref.keys():
        new_sequence.append(literal_eval(i))
    return indices, new_sequence

class Obj:
    def __init__(self, scene, v_shader, f_shader, texture=None):
        """Loads a Wavefront OBJ file. """
        self.vertex_info = [] # unique combinations of position, normal and color
        self.model = glm.mat4()
        self.position = np.array([0, 0, 0], np.float32)
        self.light = self
        self.light.color = (0, 0, 0)
        self.light.position = (0, 0, 0)
        self.shader = None
        self.vertex_shader = v_shader
        self.fragment_shader = f_shader
        self.texture_mode = 0
        self.texture = texture
        self.translated = glm.mat4()
        self.rotated = glm.mat4()
        self.scaled = glm.mat4()

        scene = Wavefront(scene)
        scene.parse()
        for material in scene.materials.values():
            vertex_format = 0
            for i in material.vertex_format:
                if i.isdigit():
                    vertex_format += int(i)
            vertices = np.array(material.vertices, np.float32).reshape(len(material.vertices) // vertex_format, vertex_format)
            indices, vertex_info = dedup_and_index(vertices)
            self.color = material.diffuse
        self.indices = np.array(indices, np.int32)
        self.vertex_info = np.array(vertex_info, np.float32)

    def generate(self):
        self.VAO, self.VBO, self.EBO = GLuint(), GLuint(), GLuint()
        self.VAO = glGenVertexArrays(1)
        glBindVertexArray(self.VAO)
        self.VBO = glGenBuffers(1)
        self.EBO = glGenBuffers(1)

        glBindBuffer(GL_ARRAY_BUFFER, self.VBO)
        glBufferData(GL_ARRAY_BUFFER, self.vertex_info, GL_STATIC_DRAW)

        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.EBO)
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, self.indices, GL_STATIC_DRAW)

        glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 32, None)
        glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 32, ctypes.c_void_p(8))
        glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 32, ctypes.c_void_p(20))
        glEnableVertexAttribArray(0)
        glEnableVertexAttribArray(1)
        glEnableVertexAttribArray(2)

        glBindVertexArray(0)
        self.set_texture(self.texture_mode)

    def compile_shader(self):
        vertex_shader = shaders.compileShader(self.vertex_shader, GL_VERTEX_SHADER)
        fragment_shader = shaders.compileShader(self.fragment_shader, GL_FRAGMENT_SHADER)
        self.shader = shaders.compileProgram(vertex_shader, fragment_shader)
        self.uniforms = {}
        for name in ('model', 'transform', 'self_color', 'light_color', 'light_position', 'texture_mode'):
            self.uniforms[name] = glGetUniformLocation(self.shader, name)

    def use_shader(self):
        if self.shader == None:
            self.compile_shader()

        shaders.glUseProgram(self.shader)

        glUniformMatrix4fv(self.uniforms['model'], 1, False, np.array(self.model))
        glUniformMatrix4fv(self.uniforms['transform'], 1, False, np.array(self.model))
        glUniform4f(self.uniforms['self_color'], *self.color)
        glUniform3f(self.uniforms['light_color'], *self.light.color[:3])
        glUniform3f(self.uniforms['light_position'], *self.light.position[:3])
        glUniform1i(self.uniforms['texture_mode'], self.texture_mode)

    def set_texture(self, setting):
        self.texture_mode = setting
        if self.texture_mode:
            self.apply_texture()

    def apply_texture(self):
        if isinstance(self.texture, Image.Image):
            texture = self.texture
        else:
            texture = Image.open(self.texture)
        texture_data = np.flipud(np.asarray(texture)).tobytes()

        self.tex_id = glGenTextures(1)
        glBindTexture(GL_TEXTURE_2D, self.tex_id)
        glTexImage2D(GL_TEXTURE_2D, 0, 4, *texture.size, 0, GL_RGBA, GL_UNSIGNED_BYTE, texture_data)
        glGenerateMipmap(GL_TEXTURE_2D)

    def draw(self):
        self.use_shader()
        glBindVertexArray(self.VAO)
        if self.texture_mode:
            glBindTexture(GL_TEXTURE_2D, self.tex_id)
        glDrawElements(GL_TRIANGLES, len(self.indices), GL_UNSIGNED_INT, None)

def main():
    pygame.init()
    display = (screen.width, screen.height)
    pygame.display.set_mode(display, FULLSCREEN|DOUBLEBUF|OPENGL)
    glEnable(GL_DEPTH_TEST)
    # glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)

    square = Obj(square_obj, object_vs, object_fs, uv_test_png)
    square.generate()
    square.set_texture(1)

    while True:
        for event in pygame.event.get():
            if (event.type == KEYDOWN and event.key == K_ESCAPE) or event.type == QUIT:
                raise SystemExit
        square.draw()

        pygame.display.flip()
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
        pygame.time.wait(10)

if __name__ == '__main__':
    main()

```

# Answer
> 0 votes
In hindsight, it's kind of amazing the previous code worked at all. I had removed the layout qualifiers in `object.vs` when I changed the version directive from 330 core. Since that syntax isn't supported in 150, I needed to specify locations with `glGetAttribLocation`.

This is some example C++ code that helped me find the solution.

And documentation for `glGetAttribLocation`. (I've always found Khronos' own documentation somewhat obtuse)

Obj.generate() in **viewer.py**:

```
# glGetAttribLocation needs a shader program to reference
self.compile_shader()

vertex_texture_coord = glGetAttribLocation(self.shader, b'vertex_texture_coord')
vertex_normal = glGetAttribLocation(self.shader, b'vertex_normal')
vertex_position = glGetAttribLocation(self.shader, b'vertex_position')

# make sure it's positive since return value of -1 is an error
if vertex_texture_coord >= 0:
    glVertexAttribPointer(vertex_texture_coord, 2, GL_FLOAT, GL_FALSE, 32, None)
    glEnableVertexAttribArray(vertex_texture_coord)
if vertex_normal >= 0:
    glVertexAttribPointer(vertex_normal, 3, GL_FLOAT, GL_FALSE, 32, ctypes.c_void_p(8))
    glEnableVertexAttribArray(vertex_normal)
if vertex_position >= 0:
    glVertexAttribPointer(vertex_position, 3, GL_FLOAT, GL_FALSE, 32, ctypes.c_void_p(20))
    glEnableVertexAttribArray(vertex_position)

```

---
Tags: opengl, textures, glsl, python
---


# Question
Title: Best way to generate a sports schedule with restrictions, byes and rest days
I have created a schedule generator to match games to calendar dates with some restrictions, after some review it does not run in an usable time.

The schedule is for a 2 conference, 4 divisions, 6 teams league with two byes (not on the first 4 or last 4 weeks), teams that play in the same stadium cannot play at home in the same day.

It's a 24 week season, each team plays 10 division games(5 at home, 5 away), 6 games against a division in the conference (3 home, 3 away), 6 games against a division in another conference (3 home, 3 away) and 2 more games against the teams in your conference that had the same standing as you last year in the conference division you didn't play against.

When you play a different division if you play at home, next time you face that division you will play away and vice-versa.

My approach was to create all the games, handpick the restrictions first and then just randomly try to fit all the games until I get a working schedule. Also tried a depth first solution without success.

Are there any solutions out there that allow to calculate this schedule in at most 1 hour? Preference would be almost instantly, don't know if it's possible.

# Answer
> 2 votes
Basically what you are doing can (but does not necessarily have to) be described as a scheduling problem from the field of optimization/operations research. You can define the scheduling task as an mathematical optimization problem and than use a solver (= a software for solving optimization problems) to get many feasible solutions.

Of course there might also be other ways of doing this. I can just tell you that for example the German Basketball League (BBL) and the National Football League in the US (NFL) are doing it like this. They use the commercial solver **Gurobi** for generating feasible schedules. Here you can read about these case studies:

Of course, you can also use free solvers (see here). The method you are using (some kind of a brute force approach) is quite inefficient for large-scale optimization problems.

---
Tags: c#, algorithm
---


# Question
Title: NULL REFERENCE EXCEPTION Object reference not set to an instance of an object
So I have 3 scripts:

* first for my player `movementscript`
* second for my speed powerup `speedscript`
* third for my obstacle `box` script i

I'm trying to get the component of box script in speed script, to get the function 'added' (which is in box script) into speed script but it keeps giving me nullreferenceexception error

Here are those scripts:

```
public class box : MonoBehaviour
{

    [SerializeField]
    GameObject effect;

    public int damage = 1;
    [SerializeField]
    float Speed =10f;
    [SerializeField]
    GameObject audioexplosion;

    void Update()
    {

        transform.Translate(Vector2.left * Speed* Time.deltaTime);

    }

    void  OnTriggerEnter2D(Collider2D col)
    {
        if(col.CompareTag("Player"))
        {
            Instantiate(audioexplosion, transform.position, Quaternion.identity);
            Instantiate(effect, transform.position, Quaternion.identity);

            movment tmp = col.GetComponent<movment>();

                tmp.health -= damage;
            Destroy(gameObject);
        }
    }
    public void added(float spd)
    {
        Speed += spd;
    }

}

```

And here is my speed script.

```
public class speedscript : MonoBehaviour
{
    [SerializeField]
    GameObject effect;
    [SerializeField]
    GameObject speedaudio;
    //[SerializeField]
   public float speed;
    public float add_v = 5;
    private float timeindue;
    //[SerializeField]
 //  public box io;

    void Start()
    {

     //  io= GetComponent<box>();
       // Debug.Log(io);
    }

    void Update()
    {
        transform.Translate(Vector2.left * speed * Time.deltaTime);
    }

    void OnTriggerEnter2D(Collider2D sp)
    {
        if (sp.CompareTag("Player"))
        {
            Instantiate(speedaudio, transform.position, Quaternion.identity);
            Instantiate(effect, transform.position, Quaternion.identity);
            box io = GetComponent<box>();
                Debug.Log(io);
                io.added(add_v);

                Destroy(gameObject);
        }
    }
}

```

# Answer
> 1 votes
Are both the scripts on the same Gameobject? Because by using `box io = GetComponent<box>();` statement you are getting the box.cs from the same gameobject where "speed.cs" is added. You can try `box io = sp.GetComponent<box>();`

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


# Question
Title: How can I rotate an object with random speed with some delays?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Turn_Move : MonoBehaviour {
    public int TurnX;
    public int TurnY;
    public int TurnZ;

    public int MoveX;
    public int MoveY;
    public int MoveZ;

    public bool World;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        if (World == true) {
            transform.Rotate(TurnX * Time.deltaTime,TurnY * Time.deltaTime,TurnZ * Time.deltaTime, Space.World);
            transform.Translate(MoveX * Time.deltaTime, MoveY * Time.deltaTime, MoveZ * Time.deltaTime, Space.World);
        }else{
            transform.Rotate(TurnX * Time.deltaTime,Random.Range(3,300) * Time.deltaTime,TurnZ * Time.deltaTime, Space.Self);
            transform.Translate(MoveX * Time.deltaTime, MoveY * Time.deltaTime, MoveZ * Time.deltaTime, Space.Self);
        }
    }
}

```

This is the random part :

```
Random.Range(3,300)

```

but sine it's changing the random numbers too quick the changes are almost not visible. I want somehow to make that if for example the next random will stay for example 5 seconds at this speed number then move to the next random number and again stay at this number 5 seconds and so on.

Tried this :

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

public class Turn_Move : MonoBehaviour {
    public int TurnX;
    public int TurnY;
    public int TurnZ;

    public int MoveX;
    public int MoveY;
    public int MoveZ;

    public bool World;

    private bool IsGameRunning = false;

    // Use this for initialization
    void Start ()
    {
        IsGameRunning = true;
        StartCoroutine(SpeedWaitForSeconds());
    }

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

    }

    IEnumerator SpeedWaitForSeconds()
    {
        var delay = new WaitForSeconds(3);//define ONCE to avoid memory leak
        while (IsGameRunning)
        {
            if (World == true)
            {
                transform.Rotate(TurnX * Time.deltaTime, TurnY * Time.deltaTime, TurnZ * Time.deltaTime, Space.World);
                transform.Translate(MoveX * Time.deltaTime, MoveY * Time.deltaTime, MoveZ * Time.deltaTime, Space.World);
            }
            else
            {
                transform.Rotate(TurnX * Time.deltaTime, Random.Range(3, 300) * Time.deltaTime, TurnZ * Time.deltaTime, Space.Self);
                transform.Translate(MoveX * Time.deltaTime, MoveY * Time.deltaTime, MoveZ * Time.deltaTime, Space.Self);
            }

            yield return delay;//wait
        }
    }
}

```

but that just rotate the object once each 3 seconds. and not rotating it all the time with speed changing every 3 seconds.

but now it's not rotating for 3 seconds it rotating every 3 seconds.

better to describe what I want is like intervals. The object should spin all the time nonstop like i Update but then each 3 seconds to change for a random speed.

for example spin at speed 5 ....after 3 seconds spin at speed 77 ....after 3 second spin at speed 199

# Answer
> 1 votes
```
public class Turn_Move : MonoBehaviour {
public int TurnX;
public int TurnY;
public int TurnZ;

public int MoveX;
public int MoveY;
public int MoveZ;

public bool World;

int randomNumber;

// Use this for initialization
void Start () {
    InvokeRepeating("GetRandomNumber",0,5);
}

// Update is called once per frame
void Update () {
    if (World == true) {
        transform.Rotate(TurnX * Time.deltaTime,TurnY * Time.deltaTime,TurnZ * Time.deltaTime, Space.World);
        transform.Translate(MoveX * Time.deltaTime, MoveY * Time.deltaTime, MoveZ * Time.deltaTime, Space.World);
    }else{
        transform.Rotate(TurnX * Time.deltaTime, randomNumber * Time.deltaTime,TurnZ * Time.deltaTime, Space.Self);
        transform.Translate(MoveX * Time.deltaTime, MoveY * Time.deltaTime, MoveZ * Time.deltaTime, Space.Self);
    }
}

void GetRandomNumber()
{randomNumber = Random.Range(3,300);}}

```

You can try this.

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


# Question
Title: Random.range giving me the same value at the same time
I created a random direction in x and y-axis at where to move, then my problem is when I tried to randomize it sometimes I get the same value at the same time on both x and y-axis. How do I not let this happen, I only want one axis to have a value, not both?

---

**ERROR**

---

**HOW I WANT IT TO HAPPEN**

---

**CODE**

```
public Vector2 randomDirection;

void Awake()
{
}

void Update()
{
    randomDirection = new Vector2(Random.Range(-1, 2), Random.Range(-1, 2));
}

```

# Answer
There are lots of ways to skin this cat.

You could decide your axis first, then decide the direction along that axis:

```
public static Vector2 GetRandomCardinalDirection() {
    Vector2 direction = Vector2.zero;
    int componentIndex = Random.Range(0, 2);
    direction[componentIndex] = Mathf.Sign(Random.value);
}

```

You could use a switch statement to pick one of your four possible values:

```
public static Vector2 GetRandomCardinalDirection() {
    int direction = Random.Range(0, 4);
    switch(direction) {
        case 0: return Vector2.up;
        case 1: return Vector2.right;
        case 2: return Vector2.down;
        default: return Vector2.left;
    }
}

```

You could store the 4 values in an array, and use your random value as an index:

```
static readonly Vector2[] _cardinalDirections = new Vector2[] {
    Vector2.up, Vector2.right, Vector2.down, Vector2.left
};

public static Vector2 GetRandomCardinalDirection() {
    return _cardinalDirections[Random.Range(0, 4)];
}

```

You could do some bit tricks to decode a direction from an integer 0-3:

```
public static Vector2 GetRandomCardinalDirection() {
    // Make a random number 0-3 (that's 00, 01, 10, or 11 in binary)
    int dieRoll = Random.Range(0, 4);
    // Take just "the ones bit" and use it as our axis (0 = x, 1 = y)
    int axis = dieRoll & 1;
    // Take "the twos bit" (value 0 or 2) and subtract 1 to get -1 or +1
    int sign = (dieRoll & 2) - 1;

    // Initialize a vector2 with zeroes (0, 0)
    Vector2 direction = Vector2.zero;
    // Set our chosen axis, x or y, to have our desired -1/+1 value
    direction[axis] = sign;
    // Send that vector back to our caller.
    return direction;
}

```

...etc.
> 2 votes

---
Tags: unity, c#, physics, vector, random
---


# Question
Title: DirectXTK: Only SpriteBatch::Begin and Draw methods give LNK2019: unresolved external
I'm using DirectXTK Desktop 2017 with Visual Studio 2017 and SpriteBatch::Begin() and SpriteBatch::Draw() give an LNK2019 unresolved external error (but not SpriteBatch::End() or SpriteBatch::GetRotation()). Since I am able to call these functions as well as use WICTextureLoader to load a texture, I believe the include and library paths are all fine, but something might have gone wrong in the .lib compilation of the DirectXTK.

Anyone know what this might be due to? Thanks in advance.

# Answer
I had this same issue and found it was due to having \_XM\_NO\_INTRINSICS\_ defined. I also had to comment out the lines in DirectXMath.h that defined \_XM\_VECTORCALL\_ so that XM\_CALLCONV would be \__fastcall. I don't actually understand the underlying reason for this - just found it by trial and error...
> 0 votes

---
Tags: directx11
---


# Question
Title: Why does the volume not decrease when I move away from the AudioSource?
I created a simple scene with an audio source and a player that can move. The main camera is a child object of the player. I set the audio source volume rolloff to "logarithmic rolloff". As far as I understand, this means that the sound should become weak very fast when the main camera moves away from the audio source. But this does not happen: as I move the player (with the camera) away from the audio source, the volume remains the same. I see, in the rolloff graph of the audio source, a line denoted by "Listener", which moves to the right as the camera moves away from the source. But still, the volume remains the same. Why?

# Answer
> 3 votes
Be sure that you have set ***Spatial Blend*** **to "3D"**. The slider is two entries above the 3D Sound Settings collapsible section (in my version of Unity). You can also enter a value from 0 to 1, with 1 for full 3D. The slider position defaults to 0 for 2D, which will override any 3D settings you configure in the lower section.

---
Tags: unity, audio
---


title: Unity Serialize IConvertible variable

text:
# Question
Title: Unity Serialize IConvertible variable
How can i Serialize IConvertible variable to show up in the inspector? As it now, i can only see the string name. But not the value.

E.g adding CStat

```
item.AddCStats("description", "This a long ranged boosted weapon.");
item.AddCStats("attack", 10);
item.AddCStats("speed", 50f);
item.AddCStats("unique", true)

```

```
[System.Serializable]
public class Item : ISerializationCallbackReceiver
{
    [SerializeField]
    public int id = 0;
    [SerializeField]
    public int amount = 1;
    [SerializeField]
    public List<CStats> cstats = new List<CStats>();
    public Dictionary<name, IConvertible> cstatsDictionary = new Dictionary<name, IConvertible>();

    public Item(int id, int amount)
    {
        this.id = id;
        this.amount = amount;
    }

    public void AddCStats<T>(string name, T value) where T : IConvertible
    {
        if (!cstatsDictionary.TryGetValue(name, out _))
        {
            cstatsDictionary.Add(name, value);
        }
        else
        {
            cstatsDictionary[name] = value;
        }

        for (int i = 0; i < cstats.Count; i++)
        {
            if cstats[i].name == name)
            {
                cstats[i].value = value;
                return;
            }
        }

        cstats.Add(new CStats(name, value));
    }

    public T GetCStat<T>(string name) where T : IConvertible
    {
        return cstatsDictionary.TryGetValue(name, out IConvertible value) ? ConvertToType<T>(value) : default;
    }

    public void OnAfterDeserialize()
    {
        cstatsDictionary = new Dictionary<string, IConvertible>();
        for (int i = 0; i < cstats.Count; i++)
        {
            cstatsDictionary.Add(cstats[i].name, cstats[i].value);
        }
    }

    public void OnBeforeSerialize()
    {
    }

    private T ConvertToType<T>(IConvertible value) where T : IConvertible
    {
        return (T)value.ToType(typeof(T), null);
    }
}

[System.Serializable]
public class CStats
{
    [SerializeField]
    public string name = String.empty;
    [SerializeField]
    public IConvertible value = null;

    public CStats(string name, IConvertible value)
    {
        this.name = name;
        this.value = value;
    }
}

```

# Answer
> 1 votes
It looks like you're using this `CStat` type purely for serialization, and at runtime everything uses the versions you've decoded into your dictionary.

With that in mind, we can set up a type that always serializes its value down to a string, but remembers its assigned type so it can be decoded to the appropriate type in your dictionary:

```
[System.Serializable]
public struct SerializedStat
{
    public enum ValueType {
        String,
        Integer,
        Long,
        Float,
        Double,
        Boolean
    }

    public string name;

    [SerializeField]
    ValueType _type;

    [SerializeField]
    string _serializedValue;

    public SerializedStat(string name, string value) {
        this.name = name;
        _type = ValueType.String;
        _serializedValue = value;
    }

    public System.IConvertible GetValue() {
        switch(_type) {
            case ValueType.String: return _serializedValue;
            case ValueType.Integer: return GetIntValue();
            case ValueType.Long: return GetLongValue();
            case ValueType.Float: return GetFloatValue();
            case ValueType.Double: return GetDoubleValue();
            case ValueType.Boolean: return GetBoolValue();
            default: return null;
        }
    }

    public string GetStringValue() { return _serializedValue; }
    public int GetIntValue() { return int.Parse(_serializedValue); }
    public long GetLongValue() { return long.Parse(_serializedValue); }
    public float GetFloatValue() { return float.Parse(_serializedValue); }
    public double GetDoubleValue() { return double.Parse(_serializedValue); }
    public bool GetBoolValue() { return bool.Parse(_serializedValue); }

    public void SetValue(string value) {
        _type = ValueType.String;
        _serializedValue = value;
    }

    public void SetValue(int value) {
        _type = ValueType.Integer;
        _serializedValue = value.ToString();
    }

    public void SetValue(long value) {
        _type = ValueType.Long;
        _serializedValue = value.ToString();
    }

    public void SetValue(float value) {
        _type = ValueType.Float;
        _serializedValue = value.ToString("R"); // "R" means "Round-trip-able"
    }

    public void SetValue(double value) {
        _type = ValueType.Double;
        _serializedValue = value.ToString("R");
    }

    public void SetValue(bool value) {
        _type = ValueType.Boolean;
        _serializedValue = value.ToString();
    }
}

```

This is a bit messy, but it lets the Unity serializer work with types it knows what to do with, and we can convert to `IConvertible` to add them to your dictionary by calling `GetValue()` after deserializing.

We can put a custom property drawer script in an Editor folder, to allow us to author these various types in the Inspector:

(Disclaimer: it's been a while since I wrote property drawers - I think this one still needs a bit of work to support multi-object editing and other such cases)

```
using UnityEngine;
using UnityEditor;

[CustomPropertyDrawer(typeof(SerializedStat))]
public class SerializedStatDrawer : PropertyDrawer {
    // Draw the property inside the given

    public override float GetPropertyHeight(SerializedProperty property, GUIContent label) {
        return EditorGUIUtility.singleLineHeight * (property.isExpanded ? 2 : 1);
    }

    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {

        float valueWidth = position.width - EditorGUIUtility.labelWidth;

        var nameProperty = property.FindPropertyRelative("name");
        var valueProperty = property.FindPropertyRelative("_serializedValue");
        var typeProperty = property.FindPropertyRelative("_type");
        var currentType = (SerializedStat.ValueType)typeProperty.enumValueIndex;

        var fieldRect = position;
        fieldRect.height = EditorGUIUtility.singleLineHeight;
        fieldRect.width = EditorGUIUtility.labelWidth;

        string caption = property.isExpanded ? "" : nameProperty.stringValue;
        property.isExpanded = EditorGUI.Foldout(fieldRect, property.isExpanded, caption, true);

        if (property.isExpanded) {
            // Name Field
            fieldRect.width = position.width;
            EditorGUI.PropertyField(fieldRect, nameProperty);

            // Type Field
            fieldRect.y += EditorGUIUtility.singleLineHeight;
            fieldRect.width = EditorGUIUtility.labelWidth;
            var selectedType = (SerializedStat.ValueType)EditorGUI.EnumPopup(fieldRect, currentType);

            // If the user changes the type, reset the value to something valid for that type.
            // Here I just nuke everything to default, but you could try converting the previous value as close as possible.
            if (selectedType != currentType) {
                typeProperty.enumValueIndex = (int)selectedType;
                switch(selectedType) {
                    case SerializedStat.ValueType.Integer:
                    case SerializedStat.ValueType.Long:
                    case SerializedStat.ValueType.Float:
                    case SerializedStat.ValueType.Double:
                        valueProperty.stringValue = "0";
                        break;
                    case SerializedStat.ValueType.Boolean:
                        valueProperty.stringValue = "False";
                        break;
                    case SerializedStat.ValueType.String:
                        valueProperty.stringValue = "default";
                        break;
                }
                currentType = selectedType;
            }

        }

        // Value Field
        fieldRect.x += EditorGUIUtility.labelWidth;
        fieldRect.width = valueWidth;
        string value = valueProperty.stringValue;
        switch (currentType) {
            case SerializedStat.ValueType.Integer:
                valueProperty.stringValue = EditorGUI.IntField(fieldRect, int.Parse(value)).ToString();
                break;
            case SerializedStat.ValueType.Long:
                valueProperty.stringValue = EditorGUI.LongField(fieldRect, long.Parse(value)).ToString();
                break;
            case SerializedStat.ValueType.Float:
                valueProperty.stringValue = EditorGUI.FloatField(fieldRect, float.Parse(value)).ToString("R");
                break;
            case SerializedStat.ValueType.Double:
                valueProperty.stringValue = EditorGUI.DoubleField(fieldRect, double.Parse(value)).ToString("R");
                break;
            case SerializedStat.ValueType.Boolean:
                valueProperty.stringValue = EditorGUI.Toggle(fieldRect, bool.Parse(value)).ToString();
                break;
            case SerializedStat.ValueType.String:
                valueProperty.stringValue = EditorGUI.TextField(fieldRect, value);
                break;
        }
    }
}

```

---
Tags: unity
---


title: Optimization of rendering of cube world

text:
# Question
Title: Optimization of rendering of cube world
I have a world made of many cubes (like in Minecraft), they have only color (not texture). I am rendering them using OpenGL 3.3 core profile (GLFW3, GLAD, GLM). I am already have done some optimizations:

* not rendering internal faces
* backface culling
* rendering faces using `GL_TRIANGLES` and indexing

But it's still a lot slower than Minecraft, but Minecraft is in Java and blocks have textures, there is bigger world (there are entities etc. too)! How can I optimize my program further?
It may be something with pre-computing. Player rarely change the world (only small part of ticks).
I am currently filtering faces with this code:

```
// for every block
if (blocks[x][y][z] != nullptr) { // nullptr means that block is air
    bool drawSides[6];
    if (world.GetBlockAt(BlockPos(x, y, z - 1)) != nullptr)
        drawSides[0] = false; // internal face, culled
    else
        drawSides[0] = true; // draw that side
    // other 5 sides
    // ...
    blocks[x][y][z].draw(sides);
}

```

# Answer
> 55 votes
No high-performance voxel renderer draws individual cubes or cube faces.

To get good performance, groups of voxels are assembled together into a single mesh, called a "Chunk".

A chunk is typically something like 16x16x16 voxels, but might be larger or smaller as you need. It contains only the visible faces of voxels in that chunk, stitched together into a single mesh that can be drawn with a single draw call.

Compare that to drawing a solid 16x16x16 block of voxels using your current method:

* iterate over all 16x16x16 voxels (4096 iterations)
* check all 6 faces of each one (24 576 iterations)
* draw those that border empty space (1 536 draw calls)

Instead:

* check if chunk is in camera view frustum (1 check per chunk)
* if so, draw the whole thing (1 draw call per chunk)

We've cut our work down by *several* orders of magnitude!

This means less work for your CPU to do in preparing the drawing instructions for each frame, and each draw call gives more for the GPU to churn through in parallel, making use of the dedicated hardware it has for this purpose.

When a voxel's state changes, you re-compute the visible faces in the affected chunk, and update its mesh accordingly. As you point out, this happens much more rarely than we render a frame, so we can skip that work for most chunks, most of the time, and just keep re-using our cached meshes.

I show some pseudocode in this answer for what such a chunk mesh building algorithm could look like.

You can also use your chunks for a form of occlusion culling. A single voxel doesn't occlude much, but a chunk's worth of voxels might be enough to completely block the view through one of the far sides. If it does, you can skip drawing whole chunks worth of content behind it, saving yourself a lot of work and overdraw.

Taking a look at the demo applet from Tommo's Advanced Cave Culling Algorithm article linked above, you can see the kind of savings chunks can offer. The dark shaded chunks are behind the camera frustum, so they get skipped. The green lines trace the order in which chunks are evaluated, stepping outward from the camera. The pink shaded chunks are completely hidden from view by closer chunks, and can be skipped too. So here the engine has to draw only 19 chunks, instead of millions of individual faces.

---
Tags: opengl, c++, performance, optimization
---


# Question
Title: I am creating a Tetris clone on Khanacademy, will I get into trouble?
For those don't know, Khanacademy is an education site that also has lessons on simple computer programming and allows you to publish your own games that are made on the website.

# Answer
If your game is called "Tetris" and/or it uses assets from the original game, then yes you might get in trouble.

If your game is called "Falling Block Extremo" and it uses assets you have permission to use, then no you should't get in trouble.

This is the same of any platform, not just Khanacademy.
> 0 votes

---
Tags: legal, tetris
---


# Question
Title: Collision doesn't work in isometric view
I have problems with collision detection in my isometric game - the collision is on a different spot then the actual object is, its like the SDL\_Rect is somewhere else then the object itself which is impossible. I checked the values with the debugger it seems there is everything right.

My player has Isometric movement. This is the calculation for the screenworld to isometric

```
Vector2 Vector2::PosToIso()
{
    return Vector2(x - y, (y + x) / 2);
}

```

When the player doesnt have the isometric movement the collision works fine. I tried to calculate the the objec's x and y pos to iso and i tried with the normal 2D screen values same result.

Collision code:

```
    bool checkCollision( SDL_Rect a, SDL_Rect b )
{
    int leftA, leftB;
    int rightA, rightB;
    int topA, topB;
    int bottomA, bottomB;

    leftA = a.x;
    rightA = a.x + a.w;
    topA = a.y;
    bottomA = a.y + a.h;

    leftB = b.x;
    rightB = b.x + b.w;
    topB = b.y;
    bottomB = b.y + b.h;

  if( bottomA < topB )
    {
        return false;
    }

    if( topA > bottomB )
    {
        return false;
    }

    if( rightA < leftB )
    {
        return false;
    }

    if( leftA > rightB )
    {
        return false;
    }
    return true;
}

```

# Answer
First of even you have isometric movement or place your objects in isometric space the Objects stay still in normal "topdown" 2D so the collision happens the same way as you would have a top down game (if your work in 2D space only) - the shape of SDL\_Rect doesn´t change. You didn\`t provide the code where you keep track of your collision Rect so its hard to help you. You can try to use SDL\_RenderDrawRect to draw your collisionbox around your player and so on and see how the rects behave when you move your player. Also you can use SDL\_HasIntersection to check if there is a collision between 2 rects instead of your check collision function you have.
> 1 votes

---
Tags: c++, isometric, sdl2
---


title: Conversion between coordinate systems

text:
# Question
Title: Conversion between coordinate systems
I have a chunk system that I created for my tile-based game, however I am having problems translating the coordinate in tiles of the cursor to the coordinate in chunks. This is my code so far:

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

public class MapGeneration : MonoBehaviour
{
    public DimensionScriptable dim;
    public Tilemap ctm;
    public Tilemap nctm;
    public Grid grid;
    public Transform target;
    public int renderDistance = 1;

    private Vector2Int offset;
    private Dictionary<Vector2Int, Chunk> map;

    private void Start()
    {
        nctm.SetTile(Vector3Int.zero, dim.tiles[3]);
        int seed = 1232421;

        map = new Dictionary<Vector2Int, Chunk>();

        System.Random rng = new System.Random(seed);
        offset = new Vector2Int(rng.Next(-100000, 100000), rng.Next(-100000, 100000));
    }

    private void Update()
    {
        Vector2Int centerPoint = (Vector2Int)grid.LocalToCell(target.localPosition);
        centerPoint.x /= dim.chunkSize.x;
        centerPoint.y /= dim.chunkSize.y;

        for (int y = -renderDistance; y <= renderDistance; y++)
        {
            for (int x = -renderDistance; x <= renderDistance; x++)
            {
                Vector2Int pos = new Vector2Int(centerPoint.x + x, centerPoint.y + y);
                Chunk chunk;

                if (!map.TryGetValue(pos, out chunk))
                {
                    Chunk newChunk = new Chunk(pos, dim.chunkSize, dim.tiles, ctm, nctm);
                    newChunk.GenerateTiles(dim.scale, dim.persistance, dim.lacunarity, dim.octaves, offset);
                    newChunk.RenderTiles();

                    map.Add(pos, newChunk);
                }
                else
                {
                    chunk.RenderTiles();
                }
            }
        }

        if (Input.GetMouseButton(0))
        {
            Vector2Int mouseTile = (Vector2Int)grid.WorldToCell(Camera.main.ScreenToWorldPoint(Input.mousePosition));
            Vector2Int mouseChunk = new Vector2Int((mouseTile.x + dim.chunkSize.y / 2) / (dim.chunkSize.x), (mouseTile.y + dim.chunkSize.y / 2) / (dim.chunkSize.y));
            Chunk chunk;
            //Debug.Log("Mouse: " + mouseTile);
            Debug.Log("Chunk: " + mouseChunk);

            if (!map.TryGetValue(mouseChunk, out chunk))
            {
                Debug.Log(mouseTile);
                Debug.LogError("TILE NOT FOUND");
            }
            else
            {
                Vector2Int conversionVec = new Vector2Int(mouseChunk.x / 2 + dim.chunkSize.x / 2, mouseChunk.y / 2 + dim.chunkSize.y / 2);
                Vector2Int convertedCoords = mouseTile + conversionVec;
                //Debug.Log(new Vector2(convertedCoords.x % dim.chunkSize.x, convertedCoords.y % dim.chunkSize.y));
                //Vector2Int tileInChunk = new Vector2Int((mouseTile.x + dim.chunkSize.x / 2) % (dim.chunkSize.x), (mouseTile.y + dim.chunkSize.y / 2) % (dim.chunkSize.y));
                //Debug.Log("Tile: " + tileInChunk);
                //Debug.Log(new Vector2Int(Mathf.Abs((mousePos.x % dim.chunkSize.x) + dim.chunkSize.x / 2), Mathf.Abs((mousePos.y % dim.chunkSize.y) + dim.chunkSize.x / 2)));
                chunk.Modify(new Vector2Int(convertedCoords.x % dim.chunkSize.x, convertedCoords.y % dim.chunkSize.y), Tiles.WATER);
                ctm.SetTile(new Vector3Int(mouseChunk.x * dim.chunkSize.x - dim.chunkSize.x / 2, 0, mouseChunk.y * dim.chunkSize.y - dim.chunkSize.y / 2), dim.tiles[3]);
            }
        }
    }

    public void GenerateMap()
    {
        map = new Dictionary<Vector2Int, Chunk>();
    }
}

```

And this is my Chunk class (the static class method Noise.GenerateNoiseMap is always returning a constant value and as such is not relevant for this problem)

```
using UnityEngine;
using UnityEngine.Tilemaps;

public class Chunk
{
    private Vector2Int position;
    public static int width;
    public static int height;

    private int[,] modifiedMap;
    private int[,] map;

    private Tilemap ctm;
    private Tilemap nctm;
    private Tile[] tiles;

    public Chunk(Vector2Int position, Vector2Int size, Tile[] tiles, Tilemap colidableTileMap, Tilemap nonCollidableTilemap)
    {
        this.position = position;
        width = size.x;
        height = size.y;
        map = new int[width, height];
        modifiedMap = new int[width, height];
        ctm = colidableTileMap;
        nctm = nonCollidableTilemap;
        this.tiles = tiles;
    }

    public void GenerateTiles(float scale, float persistance, float lacunarity, int octaves, Vector2Int mapOffset)
    {
        Vector2 offset = new Vector2(position.x * width + mapOffset.x, position.y * height + mapOffset.y);
        float[,] heightMap = Noise.GenerateHeightMap(offset, scale, persistance, lacunarity, octaves);

        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                float height = heightMap[x, y];
                Tiles tileId = Tiles.STONE;

                if (height < 0.25)
                {
                    tileId = Tiles.WATER;
                }
                else if (height < 0.75)
                {
                    tileId = Tiles.GRASS;
                }

                map[x, y] = (int)tileId;
            }
        }
        map[0, 0] = (int) Tiles.GRASS;
    }

    public void RenderTiles()
    {
        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                if (modifiedMap[x, y] == 0)
                {
                    if (map[x, y] == (int)Tiles.GRASS)
                    {
                        nctm.SetTile(new Vector3Int(position.x * width + x - width / 2, position.y * height + y - height / 2, 0), tiles[map[x, y]]);
                    }
                    else
                    {
                    ctm.SetTile(new Vector3Int(position.x * width + x - width / 2, position.y * height + y - height / 2, 0), tiles[map[x, y]]);
                    }
                }
                else
                {
                    if (modifiedMap[x, y] == (int)Tiles.GRASS)
                    {
                        nctm.SetTile(new Vector3Int(position.x * width + x - width / 2, position.y * height + y - height / 2, 0), tiles[modifiedMap[x, y]]);
                    }
                    else
                    {
                        ctm.SetTile(new Vector3Int(position.x * width + x - width / 2, position.y * height + y - height / 2, 0), tiles[modifiedMap[x, y]]);
                    }
                }
            }
        }
    }

    public void Modify(Vector2Int position, Tiles tile)
    {
        modifiedMap[position.x, position.y] = (int)tile;
        RenderTiles();
    }
}

```

# Answer
Found the answer, the thing was that I wanted the least positive residue, not the signed modulo, so I followed this answer from ShreevatsaR

> I always use my own `mod` function, defined as
>
> ```
> int mod(int x, int m) {
>     return (x%m + m)%m;
> }
>
> ```
>
> Of course, if you're bothered about having *two* calls to the modulus operation, you could write it as
>
> ```
> int mod(int x, int m) {
>     int r = x%m;
>     return r<0 ? r+m : r;
> }
>
> ```
>
> or variants thereof.
>
> The reason it works is that "x%m" is always in the range \[-m+1, m-1\]. So if at all it is negative, adding m to it will put it in the positive range without changing its value modulo m.
> 0 votes

---
Tags: unity, tilemap, coordinates
---


# Question
Title: Trouble destroying an SDL2 texture from another class
In my main class (game loop) I have created a couple of object textures:

```
//main game class
    SDL_Texture* objectTexture;
    SDL_Texture* objectTexture2;

```

If I do this in the main class (game loop) the texture doesn't destroy itself, it leaves part of the animated SDL\_Rect on the screen. This is the result of when the user clicks pick up on the menu.

```
 gameObject = mob.PickUp(scene,x, y,gd, gy,mInteraction,spriteTexture,objectTexture,objectTexture2,renderer,spriteDown1, "");

        if (gameObject != "") {

            pob.DestroyObjects(gameObject, objectTexture, objectTexture2, renderer);

        }

```

But if I do this in the main class, it works?

```
gameObject = mob.PickUp(scene,x, y,gd, gy,mInteraction,spriteTexture,objectTexture,objectTexture2,renderer,spriteDown1, "");

  if (gameObject == "Object 1!"){

            SDL_DestroyTexture(objectTexture);
            objectTexture = SDL_CreateTextureFromSurface(renderer, NULL);
       }

       if (gameObject == "Object 2!"){

          SDL_DestroyTexture(objectTexture2);
          objectTexture2 = SDL_CreateTextureFromSurface(renderer, NULL);
       }

```

pob.DestroyObjects does the same thing as above code, just in a different class. I have passed the pointers to the other class. I would be tearing my hair out but I have shaved my head during the lockdown.

# Answer
> 0 votes
it was due to the render in the game loop. I had to add a check before the render to confirm if the object had been picked up, so that not to keep rendering the object on each iteration of the game loop.

SDL\_RenderCopy(renderer, objectTexture, &srcrect, &dstrect);

---
Tags: sdl2
---


title: Unity both duration and cooldown system

text:
# Question
Title: Unity both duration and cooldown system
I have a boss with machine gun and i am trying to make him shoot for 5 seconds and then stop for 5 seconds and so on. I tried to create an IEnumerator and call it on Start (as far as i know i can not call it from update) but its not the behaviour i want as i always want him to start shooting when he spots the player. Any help is appreciated.

```
IEnumerator MachineGunShootTimer()
{
    while(true)
    {
        machineGunOnCooldown = false;
        yield return new WaitForSeconds(3f);

        machineGunOnCooldown = true;
        yield return new WaitForSeconds(3f);

    }

}

```

# Answer
It looks like you want something like this:

```
public float firingSeconds;
public float cooldownSeconds;

float _fireSecondsRemaining;
float _cooldownSecondsRemaining;

void Start() {
    _fireSecondsRemining = firingSeconds;
    _cooldownSecondsRemaining = cooldownSeconds;
}

void Update() {
    if(_cooldownSecondsRemaining > 0) {
        _cooldownSecondsRemaining -= Time.deltaTime;
    } else {
        _fireSecondsRemaining -= Time.deltaTime;
        Fire();

        if(_fireSecondsRemaining <= 0) {
            _cooldownSecondsRemaining = cooldownSeconds;
            _fireSecondsRemaining = firingSeconds;
        }
    }
}

```
> 0 votes

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


# Question
Title: Enemy gun won't aim properly when collision line is flipped | Game maker studio
When the enemy move's to the right their gun faces right. When they move left the gun will face left as it should. When the player collides with the enemy collision line on the right side, the enemy gun will point towards the player properly.

When the player is on the left side of the enemy and hits the collision line, the enemy gun will sort of point towards the player but not facing the right direction.

```
 Step Event of Enemy gun object:

//image_xscale = 1 is looking to the right, -1 is left
// I use image_angle so the enemy gun will aim at the player on x and y axis

if obj_testEnemy.image_xscale == 1 { //When the enemy is looking to the right
    if (collision_line(x, y, x + 128, obj_testPlayer.y , obj_testPlayer, false, true)) {
        image_angle = point_direction(x,y,obj_testPlayer.x,obj_testPlayer.y); //how it aims at the player
    } else {
        image_angle = obj_testEnemy.image_xscale; // faces the correct direction when not colliding
    }

} else {
    if (collision_line(x, y, x - 128, obj_testPlayer.y , obj_testPlayer, false, true)) {
        image_angle = point_direction(x,y,obj_testPlayer.x,obj_testPlayer.y);
        image_xscale = -1; //gun should be facing left but it's not
    }
}

```

I don't understand why the gun won't face left when the collision line is facing left

Working:

Not Working:

# Answer
Well, I've done a lot of thinking and decided to try a collision circle instead. This is what I've come up with and it has also solved my problem of the gun not aiming properly! here are my changes:

```
if !collision_circle(x,y,128,obj_testPlayer,true,true) {

image_xscale = sign(xspd);

if image_xscale == 1 {
    obj_testGun.image_angle = 0;
} else {
    obj_testGun.image_angle = 180;
}

} else {

obj_testGun.image_angle = point_direction(x,y,obj_testPlayer.x, obj_testPlayer.y);

if obj_testPlayer.x > x {
    image_xscale = 1;
} else {
    image_xscale = -1;
}
}

```

Here's a link to see it in action: https://www.youtube.com/watch?v=wRhcnLi82E4&feature=youtu.be
> 0 votes

---
Tags: collision-detection, ai, game-maker, platformer, direction
---


# Question
Title: How do game engines implement multiple rendering platforms?
How do game engines like UE4, Unity, Source, Cry Engine, etc add different rendering library's to their game engines? (Eg. OpenGL, DirectX, Vulkan)

# Answer
> 4 votes
Most game engines will have a layer between their rendering abstraction and the actual rendering API. In Unreal and Qt this is called the Rendering Hardware Interface, or RHI. I'm not sure if the others use the same terminology.

Typically the rendering engine will make high level calls to the rendering abstractions, and it will be the job of the various RHI implementations for different rendering APIs to translate those into actual rendering calls.

Supporting the various APIs isn't actually all that complicated since they all tend to do roughly the same things, just with different names. Probably the biggest engineering challenge is that each one of them uses a different shader language. Since game engines want to allow developers to customize the shading, they have to provide some common shading language or customization system that can then be translated into each of the languages and dialects needed by the different rendering APIs. This is far harder than just mapping a rendering abstraction to OpenGL, Vulkan, Metal and Direct3D.

# Answer
> 1 votes
I think there are another two options: Angle, https://github.com/google/angle, or Dawn, https://dawn.googlesource.com/dawn.

If your game is written by OpenGL, Angle can help you translate it into several backends, such as Vulkan, D3D.

And if you are designing a game from the beginning, you may try writing it by Dawn. Dawn is similar to a middle layer, if your game is based on dawn, it can make sure your game runs smoothly on the different backends.

---
Tags: opengl, rendering, directx, vulkan
---


# Question
Title: Function to draw an image inside a rectangle
How can I draw an image inside a rectangle?

I am introducing myself in the manipulation of images for games, I have a window and inside there is a rectangle that deforms. I would like to fill the rectangle with an image, but I have no idea how to translate the coordinates of the image to the rectangle. I don't want a library function, I want to implement it myself.

the idea would be to have a function:

```
void fill_image_rectangle (img, b1, b2, b3, b4) {

// *
}

```

I use Java on Windows 7 CPU

# Answer
You do it backwards.

You need a transformation that maps from the original image to the cuadrilateral. Well, actually, you need the inverse. In particular, you want a transformation matrix such that you multiply a position from the target canvas and it gives you a position in the original image.

To derive that matrix, you define that `image_position = M * canvas_position`, and knowing the coordinates of the corners, you solve the matrix equation.

*I explain how to derive such transformation in another answer, in that want we want to fit a model to the image of a QR code, it is the same approach. You probably can work in 2D instead of 3D. Please refer to the demo code there.*

Once you have that transformation, you can iterate over the pixels of the target canvas, for each one you query the pixel at the corresponding position of the image and pain it.

---

The iteration over the pixels is a bit tricky too… You will not iterate over the original image, instead you iterate over the target canvas (that is what I mean by doing it backwards). If you were to go over the original image and map each pixel to one pixel on the target you could end up leaving gaps in the target image (you might be interested in seeing some kind of interpolation there).

Thus, we iterate over the target canvas… You can, of course, go over each pixel, check if it is inside the target cuadrilateral and if it is proceed… however, that will have a lot of wasted effort.

Instead, think of iterating over one axis, and draw the shape segment by segment. That part is easy, you get the minimum and maximum coordinate on the main axis of the corners. Then for each segment You want to know where it starts and ends in the secondary axis.

One easy approach is to break the cuadrilateral at the main axis coordinate of each corner. That should give you a series of trapezoids (with two special cases: a rectangle, where the sides are parallel and a triangle where the sides meet at one end). Each trapezoid would be defined by a range in the main axis, and two line equation for the other sides… These line equations will be the secondary axis coordinate as a function of the main axis coordinate.

Alright, what main axis? It could be the vertical or the horizontal. Usually the images are stored such that the next and prior pixel in a row are contiguous in memory. Because of this, making the vertical the main axis will perform better. This means that the line equations for the sides of the trapezoids are going to be the horizontal as a function of the vertical, which is not how we usually see them. *And I want to draw attention to that.*

For clarity:

Thus, you will be iterating over the trapezoids (I remind you that the triangles are trapezoids where the sides meet at one end), for each trapezoid, you will iterate on its vertical range. For each row in the vertical range of the trapezoid, you compute the start and end column, and iterate over those pixels. For each pixel you find where it is in the image, and you query the pixel and draw.

---

Bonus: you might be interested in finding the neighbor pixels and interpolate them.

See also: Resizing Images - Computerphile and Bicubic Interpolation - Computerphile.

---

Yeah, this is going to have very bad performance in Java. If done on CPU, you want to manipulate the image memory directly (without the overhead of an API call to read and write each pixel) to have a decent performance. It is, of course, much better to solve the problem in GPU with a fragment shader, where each pixel gets resolved in parallel, with hardware optimized for that, and without taking CPU time.
> 1 votes

---
Tags: java, mathematics, algorithm, software-rendering, image-processing
---


# Question
Title: Why can't UObject derived objects call BlueprintFunctionLibrary functions?
My question is a very simple one.

Why can't UObject derived classes (direct inheritance) call functions from Blueprint Function Libraries?

\__

**Edit:**

My question relates to Blueprints *only*.

An `Object` derived `Blueprint` seems to be incapable of calling *functions* from an *editor-created* `BlueprintFunctionLibrary`

# Answer
> 1 votes
This is a current bug in Unreal Engine.

---

The thread on the Answer Hub can be found here :

https://answers.unrealengine.com/questions/326679/cant-call-function-librarys-function-in-macro-libr.html#comment-326679-form

---

The Issue Tracker is here :

https://issues.unrealengine.com/issue/UE-22946

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


# Question
Title: Which works best to describe character, item or dungeon properties: Affix or Trait?
I am working on an RPG portion of my game called "**The Underground King**".

My item generator uses the same properties that also apply to characters, vehicles and racing levels (dungeons for short).

I am torn between using the term "Affix" and the term "Trait" to describe the procedurally generated properties, mainly because English is not my first language, and there may be a clear difference in usage between the two.

Examples of traits: **Hearty**: For items, it gives 5 more HP, for characters they have 5 more HP, for vehicles they have 5 more durability, for dungeons, enemies have 5 HP each. **Indomitable**: For items, characters and vehicles, it gives the player the ability to ressurect at 100% hp, once dead. For the dungeon, dead enemies remain invulnerable for a few seconds after being dead.

I am open to either opinions or arguments for any of them. Thanks!

# Answer
As a native English speaker, Trait sounds much more accurate in this case. Affix is much less used and so harder to understand. Calling them traits makes it clear that they are properties of the item. Other options could be Property, or Modifier, but Trait still sounds best in my opinion. "Affix" sounds like something you learn in school and never worry about again, whereas Trait is in everyday use in ways similar to your system.
> 3 votes

# Answer
I would agree with trait or modifier if you are listing it below the name. It should be called prefix if you list it before the name and suffix if it is after the name

Hearty ring, Shield of indomitably -\> Affix description

Discipol's robe

* Hearty
* Indomitable

A trait or modifier of the robe\`
> 1 votes

---
Tags: game-mechanics, terminology
---


# Question
Title: Unity drop items enemy sprite size problem
how can i make items drop infront of the enemy without getting hidden under the enemy sprite due to the size of different enemies. I would also like to spread the drop items

How currently it is

How i would like it to be

My code:

```
public void TakeDamage(int damage)
{
    int dist = 10;
    Vector3 spawnPos = transform.position + transform.forward * dist;
    GroundItem.Create(new Item(3, 1), spawnPos);

    health -= damage
}

public class GroundItem : MonoBehaviour
{
    [SerializeField]
    private Item item;
    [SerializeField]
    private SpriteRenderer spriteRenderer = null;

    public static GroundItem Create(Item item, Vector3 position)
    {
        GameObject groundItemGO = Instantiate(GameManager.Instance.GetData.GetAssetDatabase.GetPrefabByName("GroundItemPrefab"), position, Quaternion.identity);
        GroundItem groundItem = groundItemGO.GetComponent<GroundItem>();
        groundItem.SetItem(item);
        return groundItem;
    }

    private void SetItem(Item item)
    {
        this.item = item;
        spriteRenderer.sprite = item.data.icon;
    }
}

```

# Answer
You can use Sprite bounds to get the rough size of your sprite.
In your enemy class,

```
float spriteSize;

void Start(){
    Sprite Sprite = GetComponen<SpriteRenderer.().Sprite;
    spriteSize = Vector3.magnitude(sprite.bounds.extents);// get this only once for efficiency
}

public void TakeDamage(int damage)
{
    int dist = 10;
    Vector3 spawnPos = transform.position + (-1*transform.up) * (dist*spriteSize);
    GroundItem.Create(new Item(3, 1), spawnPos);

    health -= damage
}

```

EDIT:

As pointed out in the comments `transform.forward` will be *into* the game's third dimension, entirely not what you want. `-1*transform.up` (down direction) should work
> 1 votes

---
Tags: unity
---


# Question
Title: Show world space UI object on top of the Mesh
I want to show object name whenever mouse over happens on a certain object and here is my code snippet that trying to place World space UI image object on top of the object.

```
private void OnMouseEnter()
{
    if (!EventSystem.current.IsPointerOverGameObject())
    {
        Vector3 topPosition = MeshTopPoint.GetMeshTopPoint(this.gameObject);
        partNameImage.transform.position = topPosition;
    }
}

```

but the problem is it is not placing the object on center top of the object instead of it like this (placing UI on the corner):

And here is my mesh top position get function:

```
public class MeshTopPoint : MonoBehaviour
{

    // Update is called once per frame
    public static Vector3 GetMeshTopPoint(GameObject go)
    {
        Vector3 worldUp = go.transform.InverseTransformDirection(Vector3.up).normalized;
        Plane p = new Plane(worldUp, Vector3.zero);
        Vector3[] verts = go.transform.GetComponent<MeshFilter>().sharedMesh.vertices;
        Vector3 topVertex = Vector3.zero;
        float maxDist = float.NegativeInfinity;
        for (int i = 0; i < verts.Length; i++)
        {
            float dist = p.GetDistanceToPoint(verts[i]);
            if (dist > maxDist)
            {
                maxDist = dist;
                topVertex = verts[i];
            }
        }

        topVertex = go.transform.TransformPoint(topVertex);
        return topVertex;

    }
}

```

Here is my UI Image:

# Answer
You are getting the topmost vertex, and setting the coordinates to this point. The problem is, on a box you have 4 top vertices if it is placed with a 0 rotation angle. One for each corner of the face.

There are multiple ways to solve this, but using what code you already have, you can add the topvertices in a list if they are equally high and then you can take the average position of those. This will bring it into the middle. However, by doing this you will see artifacts when rotating the object, the UI will jump around as the calculations will be different.

Therefore it would be better to just take the center position of the object, take the bounding volume of the mesh, and add half of the bounding volume height to the center position. Then you would be placing your UI in the center of the object at the same height just above the mesh at all times.

EDIT: Here is some code to do this, however note that I am not at my computer to verify, but it is something along the lines of:

```
Mesh mesh = GetComponent<MeshFilter>().mesh;
Bounds bounds = mesh.bounds;
Float halfheight = bounds.extents.y;
Vector3 pos = new Vector3(bounds.center.x, bounds.center.y+halfheight, bounds.center.z);

```
> 0 votes

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


# Question
Title: Moving a top-down camera while keeping its height constant
I'm currently writing the script for the player to explore the plane below. The camera view is set to be slightly rotated as to look down. And I have set the code to make the camera move.

This is the code, and everything is set in the update method.

```
        if (Input.GetKey("w"))
        {
            transform.Translate(Vector3.forward * panSpeed * Time.deltaTime);   // , Space.World if want to avoid camera going down
        }
        if (Input.GetKey("s"))
        {
            transform.Translate(Vector3.back * panSpeed * Time.deltaTime);
        }
        if (Input.GetKey("d"))
        {
            transform.Translate(Vector3.right * panSpeed * Time.deltaTime);
        }
        if (Input.GetKey("a"))
        {
            transform.Translate(Vector3.left * panSpeed * Time.deltaTime);
        }

```

The problem is that everytime that the camera goes forward, it goes straight down. And I don't want it to do that. I want to keep the "height" from the plane below to be the same as in the picture below. I want the camera to move along the red axis.

I know of the existence of Space.World in order to achieve this, but the problem is that if I do that, whenever I rotate, now the controllers are all screwed up, because if I rotate to the right for example. Now Forward (W) moves the camera to the left, Right (D), moves the camera forward, etc etc.

So basically what I need is 1: to make the camera keep the distance to the plane below while moving (not going down). and 2. To make it possible that even with rotations, the controllers are kept, and not having this weird behavior, when forward is not longer forward.

Any ideas how to achieve this?

# Answer
One way to do this would be to take the respective vector that you use (forward, backward, left and right) and only use the x and z coordinates, leaving y at 0.

Something along the lines of

```
Vector3 direction = new Vector3(transform.forward.x, 0, transform.forward.z);

```

Notice that it should be transform.forward as it will be forward relative to the object you are moving (the camera)

Edit: Finally you could normalize the vector after creating it in order to keep the same speed at all times
> 1 votes

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


title: Constructing a game stock market

text:
# Question
Title: Constructing a game stock market
**Short Question**: How do I calculate market values for different resources in the game?

**Long Question**:

I am building a game around the concept of resource gathering and manufacturing to gain different resources. Those resources can be traded with other players or with a "game market", meaning auto generated trades that get created on a certain time interval (undecided on the interval yet). Because it would be too complex to create different exchange rates for each pair of resources (there are currently just under 100 types of resources and plans for a few hundred in total), I have come to the conclusion that there needs to be a "game currency" (lets just call it GC for now). Each resource would have its exchange rate to GC and this exchange rate would, on a certain interval, be impacted based on what is going on in the game. How would I calculate this exchange rate or market value of a certain resource every interval? I assume different things would effect it like popularity of trading within previous interval, previous exchange rate, abundance of resource currently, etc etc. But I am not sure how to apply this methodically.

**Update**: Some of my concerns are around the value of a resource:

1. Some resources can be mined directly from the environment. Other can only be obtained from manufacturing the mined resources. Other resources may be manufactured for other manufactured resources. How do I create a stable starting point to account for these factors? Obviously manufactured resources would be worth more because they are more time consuming to create.
2. Should players be forced to observe the market value or place their trade requests at what ever value they desire? If the value is forced, what happens to trades after a market value changes? If the is opened ended, what stops players from gaming the market to boost or fall prices? Should I only calculate the value based on successful trades and consider that open request haven't been filled for a reason?
3. How do I calculate what will happen in a large multiplayer situation when the game is only in development and I only have myself and a few AI players trading? The market values could be effected differently in different situations and I don't want to be caught in a situation where I have to change game mechanics after a game in live which could potentially upset players who have figured out the predictability of the market and over night, the rules change.

# Answer
Common wisdom when it comes to MMO economics is to just let players decide at what prices they are willing to trade resources and equipment between each other. Create a trade platform where sellers can offer items or resources for any price and where buyers can then accept those offers if they find them fair (often called "auction house"). Some games also allow players to post buy-offers on the auction house, but the players in most games rarely make use of this feature.

The law of supply and demand will quickly stabilize the prices at what the items are *really* worth to the players. This usually works much better than just trying to dictate prices. If you feel that some items are too cheap or too expensive, you as a game designer can try to influence prices indirectly by either changing how easy it is to obtain items (affecting the supply) or by changing how useful these items are to players (affecting the demand).

The question mentions concerns about price fixing and market manipulation. After playing lots and lots of MMOs with free market player economies, I made the experience that this rarely works, because there are just too many players. It is hard to build a cartel when most resources in the game can be obtained and offered by any player in the game. Even creating an artificial shortage by buying up a certain resource rarely works out. It will usually just encourage more players to farm that resource, because they see a chance to profit from the current lack of supply on the market. And if the hoarder then tries to dump their stash back onto the market, people will underbid them with the regular price, so they end up making almost no profit at all.

If you want to find out the current market price, either for your own metrics, as an information for the players or because some game mechanic depends on it, then it is usually best to not look at offers but to look at the trades which actually get executed. Standing offers are not that interesting, because if their price was the actual market price, then someone would take them. The price of the last transaction should give you realtime data, but if you want more stable and reliable data then it can be more useful to look at the median price of the past x trades or of the trades in the last x hours.

However, there might be a chance to manipulate the prices you come up with that way. For example, two players (or two accounts operated by the same player) might manipulate the displayed price by trading items back and forth between each other for greatly inflated or deflated prices until their fake price shows up in your statistic. You might have to take some measures to detect such manipulation patterns and filter out such trades when estimating the real market price. Or don't, and call it "emergent gameplay".

---

But let's say you really want to avoid a free market economy and want fixed prices instead. There can be good reasons for that, most of all that it makes your design process much easier if you know the price of everything.

In that case it is a good idea to convert the price of everything into **play time**. The time it takes to acquire that resource. If acquiring a carrot takes 1 minute of playtime and acquiring a pumpkin takes 5 minutes of playtime, then a pumpkin should be 5 times as expensive to buy. If resources can only be bought and not acquired through play time, then you can alternatively try to value them by the play time this resource *saves* the player. If a potion of dexterity cuts off 5 minutes of the time it takes to grind to level 42, then it is half as valuable as a potion of life which cuts off 10 minutes of time it takes to grind to level 42.
> 3 votes

---
Tags: game-design, game-mechanics, game-theory
---


# Question
Title: Can i release a game in steam with free assets?
I'm making a game with unity, and i'm planing release the game in steam as FREE. I'm using free assets from unity asset store, and also i'm using free assets models from another sites. I always see if the 3d models are free. I'm no using models like Batman, that have rights from DC. But for example i use a model of door or a stair.

My question is, can i publish my game in steam, or another place, without care about someone someone processing me because i use his 3d models, that is free?

# Answer
To be sure you need to check the license for each asset to see if you have any legal restriction - most free assets I have seen have no such restriction, but some do require crediting, others are free for demo purposes only.

Regrettably this isn't enough to be 100% certain, at one point 7 Days to Die was taken off Steam for using an asset that they'd purchased on the Unity Asset store, but had been uploaded by someone who didn't own the copyright. Unity takes this seriously and actively curates their asset store, so it's quite rare, and if you did get caught with an asset you didn't have rights to you could probably amend your game and republish it, and be given the benefit of the doubt.

Additionally, while not a legal consideration by using free or low cost assets you run the risk of being classed by players as an asset flip, which can cause some potential players to just skip over the game without playing it.
> 4 votes

---
Tags: publishing
---


# Question
Title: What files can I delete from my project folder?
I have a large Unity project and I want to put the source code online. I tried to do it in GitHub but I am out of quota for LFS, so I decided to just zip the project folder and put it on the cloud. Before I do this, I would like to make the folder as small as possible. What files can I delete from the project folder, such that anyone who downloads the remaining files will be able to use my project?

# Answer
> 6 votes
The standard Unity .gitignore file shows what files and folders should not be committed to git and can therefore be deleted.

```
# This .gitignore file should be placed at the root of your Unity project directory
#
# Get latest from https://github.com/github/gitignore/blob/master/Unity.gitignore
#
/[Ll]ibrary/
/[Tt]emp/
/[Oo]bj/
/[Bb]uild/
/[Bb]uilds/
/[Ll]ogs/
/[Uu]ser[Ss]ettings/

# MemoryCaptures can get excessive in size.
# They also could contain extremely sensitive data
/[Mm]emoryCaptures/

# Asset meta data should only be ignored when the corresponding asset is also ignored
!/[Aa]ssets/**/*.meta

# Uncomment this line if you wish to ignore the asset store tools plugin
# /[Aa]ssets/AssetStoreTools*

# Autogenerated Jetbrains Rider plugin
/[Aa]ssets/Plugins/Editor/JetBrains*

# Visual Studio cache directory
.vs/

# Gradle cache directory
.gradle/

# Autogenerated VS/MD/Consulo solution and project files
ExportedObj/
.consulo/
*.csproj
*.unityproj
*.sln
*.suo
*.tmp
*.user
*.userprefs
*.pidb
*.booproj
*.svd
*.pdb
*.mdb
*.opendb
*.VC.db

# Unity3D generated meta files
*.pidb.meta
*.pdb.meta
*.mdb.meta

# Unity3D generated file on crash reports
sysinfo.txt

# Builds
*.apk
*.unitypackage

# Crashlytics generated file
crashlytics-build.properties

# Packed Addressables
/[Aa]ssets/[Aa]ddressable[Aa]ssets[Dd]ata/*/*.bin*

# Temporary auto-generated Android Assets
/[Aa]ssets/[Ss]treamingAssets/aa.meta
/[Aa]ssets/[Ss]treamingAssets/aa/*

```

The big one is the /Library folder, and of course any folder that contains build outputs.

---
Tags: unity, publishing
---