title: Mathf.Round returning wrong values

text:
# Question
Title: Mathf.Round returning wrong values
I want to check if the Y position is changing or not for the player and the enemy. If it has changed in the frame I want it to return `true` and if it didn't I want it to return `false`. I round because the enemy's position alternates between 0.8 and 0.800001 .

I tried to do `Mathf.Round(transform.position * 100)/100` and I compare is to the enemyOldPosition which I assigned using `enemyOldPosition = Mathf.Round(transform.position * 100)/100`, but it says it's not equal.

I tried to check `Debug.Log(enemyOldPosition - Mathf.Round(transform.position * 100)/100)` and it returned 1.192093E-08.

```
void Update()
{
     if(Mathf.Round(player.transform.position.y*100)/100 == oldPosition)
     {
         isChangingY = false;
         oldPosition = Mathf.Round(player.transform.position.y*100)/100;
     }
     else
     {
         Debug.Log(oldPosition - Mathf.Round(player.transform.position.y*100)/100);
         isChangingY = true;
         oldPosition = Mathf.Round(player.transform.position.y*100)/100;
     }

     if(Mathf.Round(transform.position.y*100)/100 == enemyOldPosition)
     {
         enemyIsChangingY = false;
         enemyOldPosition = Mathf.Round(transform.position.y*100)/100;
     }
     else
     {
         Debug.Log(enemyOldPosition - Mathf.Round(transform.position.y*100)/100);
         enemyIsChangingY = true;
         enemyOldPosition = Mathf.Round(transform.position.y*100)/100;
     }

 }

```

This script is placed my on enemy, and they both have rigidbodies

# Answer
You generally want to avoid comparing floats for exact equality. Instead, use a range.

```
float closeEnough = 1f/100f;

float differenceFromPrevious = transform.position.y - oldPosition.y;

if(Mathf.Abs(differenceFromPrevious) <= closeEnough) {
   // ...do your stationary stuff, but leave oldPosition where it was to avoid drift.
} else {
   // ...do your moving stuff, and update oldPosition to reflect the movement.
   oldPosition = transform.position;
}

```

---

If you want context as to *why* your subtraction isn't giving you an answer of zero as you expect, it's not that the round function is returning the wrong value. It's that you're not comparing apples to apples.

It's important to know that the intermediate registers your CPU uses to evaluate float expressions are actually wider than 32 bits: that way you minimize rounding errors that can accumulate in intermediate steps in a calculation. But values you save to RAM get rounded to 32-bit precision.

So let's say your y position is actually 1.01, or as close to it as we can represent in a 32-bit float, which is \\$1.00999999\_{10}\\$ in decimal, or \\$1.000 \\, 000 \\, 101 \\, 000 \\, 111 \\, 101 \\, 011 \\, 10\_2\\$ (\\$1 + 83886 * 2^{-23}\\$) in binary. The digit expansion loops forever, since it's not a sum of powers of 2 (dividing by 100 means there's a factor of 5 in the denominator) but we only get to keep 24 digits of it, counting the leading 1.

We multiply it by 100, round it to 101, then divide by 100. We can't represent the output of the division exactly, but in our register we can keep about 53 binary digits, or \\$1.000 \\, 000 \\, 101 \\, 000 \\, 111 \\, 101 \\, 011 \\, 100 \\, 001 \\, 010 \\, 001 \\, 111 \\, 010 \\, 111 \\, 000 \\, 010 \\, 100 \\, 1\_2\\$ (really really close!) which we store in our `oldPosition` variable.

Then you save that value to a float, which rounds it to 32-bit precision, 1.00999999.

Next frame we read that variable as the rounded version we stored: 1.00999999, but your newly-calculated `transform.position.y*100)/100` is part of an expression that hasn't been fully evaluated yet (we still have the subtraction to do), so it's still at register precision! So when we do the subtraction we get:

$$\begin{align} &1.000 \\, 000 \\, 101 \\, 000 \\, 111 \\, 101 \\, 011 \\, 10\_2\\ \- &1.000 \\, 000 \\, 101 \\, 000 \\, 111 \\, 101 \\, 011 \\, 100 \\, 001 \\, 010 \\, 001 \\, 111 \\, 010 \\, 111 \\, 000 \\, 010 \\, 100 \\, 1\_2\\ = \\, -&0.000 \\, 000 \\, 000 \\, 000 \\, 000 \\, 000 \\, 000 \\, 000 \\, 001 \\, 010 \\, 001 \\, 111 \\, 010 \\, 111 \\, 000 \\, 010 \\, 100 \\, 1\_2 \end{align}$$

Which ends up being about \\$0.000 \\, 000 \\, 009 \\, 536 \\, 743 \\, 172 \\, 944 \\, 284 \\, 2\_{10}\\$ away from zero in decimal, or 1.192093E-08 as reported by your debug log. Definitely not equal to zero!

So your program is telling you the truth. You just asked it a slightly different question than you meant to.
> 1 votes

---
Tags: unity, 3d, mathematics, transformation
---


title: Third Person Flying Camera

text:
# Question
Title: Third Person Flying Camera
I am having issues creating a third-person camera for my Rogue Squadron (N64) like game. First I have posted my issue on the official Unity Answers site here. So far my ship is behaving as I want and the camera follows position correctly (XYZ), however, it doesn't rotate how I would like. My first attempt was to set the rotation of the camera to the rotation of the ship and realized that is not what I am looking for either. I have found some information on rotating around a (pivot) point but I am having trouble understanding them. For example, I have found this and this but Im not sure how they work. The end result would be something like the camera found here. Thank you for any help, I would greatly appreciate a description of what you are doing/how it works. Lastly this is done in C# in Unity. I can provide my code if needed.

# Answer
> 1 votes
Hello and welcome to the community!

# Solution 1 - manually setting rotation and position

You almost got it, you just need to do camera offset a bit different. `Transform` has handy-dandy properties, called `.foward`, `.right`, which are normalized vectors for the direction the `Transform` is looking at.

Now imagine your player ir facing north (`transform.forward` is `(x=0, y=0, z=1)`). To move camera 5 units behind, you would do `cameraPosition = playerPosition + playerTransform.forward * -5f`. The multiplication would result in `(x=0, y=0, z=-5)` and camera would be placed 5 units behind. Easy, right?

Now what if you want to place 5 units behids **plus** two units to the left? You add those Vectors together, which results in `cameraPosition = playerPosition + ((playerTransform.forward * -5f) + (playerTransform.right * -4f))`. Now your camera is placed 5 units behind and 4 unit left of the player.

To place the camera 2 units above the player, you would just use `transform.up` property and the whole routine is the same.

After setting the offset, use `camera.rotation = player.rotation` to rotate camera to right angle.

Here's a quick snippet for camera, that follows set object:

```
public class TransformFollower : MonoBehaviour
{
    public Vector3 offset;
    public Transform target;

    private void Update()
    {
        transform.position = target.position +
            (target.right * offset.x) +
            (target.up * offset.y) +
            (target.forward * offset.z);

        transform.rotation = target.rotation;
    }
}

```

# Solution 2 - let Unity hierarchy do it for you

If you're never going to Destroy player character object, you could make the camera as a child of the Player object. Then setting offset in the inspector. All rotation and following would be done automatically by the Unity engine, as the Camera would be anchored to the Player.

---
Tags: unity, c#, camera, rotation, third-person-view
---


title: Moving Rect with KEYDOWN

text:
# Question
Title: Moving Rect with KEYDOWN
I tried to move my obstacle with the event type KEYDOWN, but it seems it is not working.

This is my code.

```
import pygame
import time

pygame.init()
res=(500,500)
blue_color=(0,0,255)
black_color=(0,0,0)
red_color=(255,0,0)
title=pygame.display.set_caption("Pygame Game")
screen=pygame.display.set_mode(res,pygame.RESIZABLE)

coord_rec=pygame.Rect(250,2,20,20)
coord_obs=pygame.Rect(150,450,200,20)
rectangle=pygame.draw.rect(screen,blue_color,coord_rec)
obstacle= pygame.draw.rect(screen,red_color,coord_obs)

pygame.display.flip()
launched= True
while launched:
    for event in pygame.event.get():
        if event.type== pygame.QUIT:
            launched=False
        elif event.type==pygame.KEYDOWN:
            if event.key==pygame.K_LEFT:
                    coord_obs.x+=10
            elif  event.key==pygame.K_RIGHT:
                    coord_obs.x +=-10

    while not coord_rec.colliderect(coord_obs):
              time.sleep(0.0500)
              screen.fill(black_color)
              coord_rec.y+=10
              rectangle=pygame.draw.rect(screen, blue_color, coord_rec)
              obstacle=pygame.draw.rect(screen, red_color, coord_obs)
              pygame.display.flip()

```

# Answer
I suspect your problem is that you're only reacting to KEYDOWN, rather than tracking which keys are down during any given frame. As written, your players have to beat on the arrow keys as fast as possible. I can usually manage 7 key presses per second, but I'm not as fast as I used to be.

So you need to track which keys are down, which means tracking both down and up events, and maintaining a collection of keys currently down. You would then react to which keys are down, rather than directly acting due to the events. As a means of future proofing, I suggest you track all key presses, not just your current controls, that way when you want to configurable controls (wasd instead of arrows for example), you don't have to mess with your event handling, just the way you query the list of currently pressed keys.

I also strongly suggest ditching your hardcoded velocities and 20fps, in favor of tracking how long its been since the last frame and scaling a "per second" velocity. You should probably track your locations as floating point numbers, and then truncate or round them to integers before drawing them. Adding anything less than 1 to a number as a truncated int will never change the given object's position.
> 1 votes

---
Tags: movement, python, pygame, events
---


# Question
Title: Equation to make small number big and big number small (gravity)
I have a sprite that I want to speed up as it gets closer to another object. I really want this to flow well and don't want a series of if statements. All I can think of is to take the distance and have some equation pump out a number that slowly rises as the distance decreases.

But for the life of me I can't think of a way to do this, though I'm sure it's possible. My mathematics knowledge is just too lacking to think of the tools I need for this.

Here's a pseudocode breakdown:

```
50->(function)->1.2
20->(function)->1.8

```

Than I'd could do something like:

```
speed = speed*1.8

```

I've thought about it and I think this would be similar to gravitation, I've tried some googleing, is there anyone that can point me in the right direction

# Answer
```
speed = constant_factor / distance

```

With constant\_factor at 60, you get:

```
50->function->1.2
20->function->3.0

```

If you want to damp the curve a bit, add an exponentiation:

```
speed = (constant_factor / distance) ^ (1 / damping_factor)

```

With constant\_factor at 80, and damping\_factor at 2, you get:

```
50->function->1.26
20->function->2.0

```

One potential issue is that this will approach infinity as distance approaches zero. If you want to clamp the maximum speed, add an adjustment to distance:

```
speed = (constant_factor / (distance + clamp_adjustment)) ^ (1 / damping_factor)

```

Tune as you see appropriate from there.
> 13 votes

# Answer
On a more abstract level, to get an output that decreases as the input increases, you have 2 obvious options:

* Reciprocal, ie. f(x) = 1/x. So, 50 becomes 1/50, 20 becomes 1/20, and so on. As ZorbaTHut pointed out, the '1' can be any constant, and that changes the shape of the curve but not the direction. As x grows, the curve flattens out, and as x approaches 0, the curve becomes infinitely steep. If x is positive, the output is also positive.
* Subtraction. ie. f(x) = 100 - x. So 50 becomes 50, 20 becomes 80, and so on. The slope here is constant and directly proportional to x. The 100 I used is again just an arbitrary constant, but if you want all your outputs to be positive then the constant must be larger than any possible value of x.
> 3 votes

# Answer
If talking about gravity, you could consider the gravity equation.. from wikipedia:

where:

* F is the force between the masses,
* G is the gravitational constant,
* m1 is the first mass,
* m2 is the second mass, and
* r is the distance between the masses.

http://en.wikipedia.org/wiki/Newton%27s\_law\_of\_universal\_gravitation
> 3 votes

# Answer
1 times 10 to the power of 3 is 1000, which is big.

1000 times 10 to the power of negative 3 is 1, which is small.
> 0 votes

---
Tags: mathematics, physics, linear-algebra
---


# Question
Title: Assigning components to variables in Unity, benefits?
I'm wondering if it's beneficial to assign components to variables in Unity C#, as follows

```
public class SceneLoader : MonoBehaviour
{
    GameStatus gameStatus;

    private void Start()
    {
        gameStatus = FindObjectOfType<GameStatus>();
    }

    public void LoadFirstScene()
    {
        gameStatus.DestroyGame();
    }
}

```

Whereas the shorter version would be without initialising the object as a variable, besides readability are there benefits to using one way or the other?

public class SceneLoader : MonoBehaviour
{

    public void LoadFirstScene()
    {
        FindObjectOfType<GameStatus>().DestroyGame();
    }

}
```
</code></pre>

# Answer
> 1 votes
This use of member variables is called caching. It's a space-time trade-off: we use a little extra memory (space) to save ourselves the computation work (time) needed to produce the value from scratch every time.

For something like a reference variable, the memory cost is trivial, so this is a very efficient trade-off to make, if it helps you avoid repeatedly paying a computation cost, or shift that cost to a more convenient moment.

You'll often see it used in cases like this, where we have a homing projectile or enemy that wants to move toward the player every simulation step:

```
void FixedUpdate() {
    var player = FindObjectOfType<PlayerController>();

    body.velocity = (player.transform.position - transform.position).normalized * speed;
}

```

Here we're spending time in every physics step to search through all our game objects to find the player object - even though we just did that same search last physics step!

As the Unity docs say,

> It is a general best practice to eliminate all usage of `Object.Find` and `Object.FindObjectOfType` in production code. As these APIs require Unity to iterate over all GameObjects and Components in memory, they rapidly become non-performant as the scope of a project grows.

So for a case like this, it's recommended to limit your searching: say, do it just once and remember the result for subsequent frames:

```
Transform target;

void Start() {
    target = FindObjectOfType<PlayerController>().transform;
}

void FixedUpdate() {
    body.velocity = (target.position - transform.position).normalized * speed;
}

```

Now we pay the search cost only once, rather than every physics step.

Or better yet, if we can read a reference to our target from a manager/singleton (global variable), or have it passed to us on initialization from a class that already knows our target via eg. a `SetTarget(Transform target)` method (dependency injection), we can avoid ever searching for it at all. :)

In your particular example, the search is occurring only once anyway. All that's different is whether you're doing that search when this script starts up (eg. when the scene it's in loads), or when it needs to do its work (when the next scene transition happens).

Often a lot of scripts will be doing their setup or searching for their dependencies in `Start()`, so deferring this search until later - so you don't need a `Start()` call on this object - might help you reduce the performance hitch you see when first loading a scene.

But in this case you might have an even better option. It looks like both the `SceneLoader` script and the `GameStatus` script exist in the same scene file. If that's the case, you can expose your `gameStatus` variable to be populated in the Inspector when you're authoring the scene:

```
public GameStatus gameStatus;

// or

[SerializeField] private GameStatus _gameStatus;

```

Now just like before you don't need a `Start()` method, *and* you also don't need to search for this reference when it's time to use it. It's been pre-populated for you at edit time, and it's a quick copy operation for the deserializer to fill in the variable when your scene loads.

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


# Question
Title: How to develop a bot for a(n) (arbitrary) FPS game without a game API?
I've been interested in artificial intelligence in computer games for a long time. The question that I have been asking for a long time and to which I have not yet found an answer is the following: How to write a bot that can move through an FPS game without the game offering an API for developers? Is this possible by having only the information that the player sees on his screen? What options are there to implement something like this? Must the pixel information on the screen be processed by neural networks to operate object recognition (e.g., walls, doors, adversaries)? How can a bot, e.g. understand if he is running against a wall and is hanging on the wall? The bot would have to get a feedback about the fact that he just does not move forward in the world, because he hangs on the wall. So far I have not found an answer to these questions. For hints I would be very grateful, like also scientific articles.

**As a supplement:** The starting point for my question should be that you have no access to the source code of the game. Also, the game has no API through which the position data, environment data, etc. can be read.

# Answer
I am a little surprised that no one has answered this, and I am no expert, but the high level concept for one approach, detouring, is straightforward in concept! What your bot will do is read the graphics data, usually from the GPU, and then output keyboard and mouse mappings. You could simply use the screen as input \[hard but doable\] or you could use the graphics resources as input. As discussed in the machine learning paper "Playing for Data", the game communicates resources of different types, including geometric meshes, texture maps, and shaders to the gpu. The game then specifies how these resources should be combined to compose the scene. Because this is consistent between sessions, by tracking the application of resources to different scene elements, you can establish associations between these scene elements. You can intercept these communications with *detouring*, which is often used by screen capture software and graphics debugging and performance analysis tools. One such tool that is commonly used is RenderDoc. By implementing a wrapper for DirectX and using RenderDoc to wrap Direct3D, you can then start monitoring the graphics communication elements. With those in hand, you can decide which virtual mouse and keyboard actions to take and when.

Why don't people do this more often you might ask? Some people do, but its a lot of work, and not guaranteed to yield results.
> 1 votes

---
Tags: ai, first-person-shooter, bot
---


# Question
Title: Cap Framerate in the asynchronous world of Javascript
I'm developing a game in JavaScript & HTML5 with CreateJS. (**I doubt you'll need CreateJS experience to answer this question, though**)

My main game loop function is initialized and run using the CreateJS library like so:

```
createjs.Ticker.on("tick", loop);

```

(Similar to an event handler)

Then, it's off to the races - my function loops indefinitely, running my game at around 50FPS.

**I want to cap this at 30FPS.** But without a "sleep" function, or any real "pause" function, what's the best way to do that? How can I force my loop to slow down?

Thanks! -W

# Answer
From the documentation:

`Ticker.framerate = 30;`

Hope that helps.
> 1 votes

---
Tags: javascript, html
---


title: Direction vector to quaternion

text:
# Question
Title: Direction vector to quaternion
I have a unit vector (direction) which represent a rotation around Y axis,

and would like to turn this into a quaternion to represent the same rotation.

I use GLM library, but interested any library agnostic solution.

Should I pack the direction vector to a matrix then convert to quaternion? Is there a better way?

UPDATE: As I said the matrix solution works already, but there must be a shorter way, as i don't need all dimension only one (around Y):

```
glm::quat q = glm::conjugate(glm::toQuat(
    glm::lookAt(glm::vec3(from.getX(), from.getY(), from.getZ()),
                glm::vec3(from.getX(), from.getY(), from.getZ()) + direction,
                glm::vec3(0, 1, 0)
    )
));

```

# Answer
From http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/

```
qx = ax * sin(angle/2)
qy = ay * sin(angle/2)
qz = az * sin(angle/2)
qw = cos(angle/2)

```

But since your vector represents the rotation, and is **not** the axis of rotation, we need to compute the angle. Your axis of rotation is just 0,1,0

```
angle = atan2( vector.x, vector.z ) // Note: I expected atan2(z,x) but OP reported success with atan2(x,z) instead! Switch around if you see 90° off.
qx = 0
qy = 1 * sin( angle/2 )
qz = 0
qw = cos( angle/2 )

```

NOTE: this even works for non-unit vectors, as atan2 will compute the correct angle for any length vector, as long as it is not zero.
> 6 votes

# Answer
Try to look in this way:

```
Vector3df sundirection = sun->GetDirectionTo();
Vector3df rotaxis = normalize( cross(Vector3df(1, 0, 0), sundirection));
double angle = acos(dot(Vector3df(1,0,0),sundirection));
Quaterniondf orient(angle, rotaxis);

```
> 0 votes

---
Tags: c++, rotation, vector, quaternion, glm
---


# Question
Title: GLFW shift key not behvaing like other keys
I am using GLFW 3.2.1

Currently I am implementing a camera. For the vertical controls I am using space to go up and shift to go down.

For all other keys, pressing the key results in the section of the code associated with the key always executing.

But for shift, it only gets exectuted when pressing and releasing but not while keeping the key pressed.

The key callbak is:

```
#define CAM_SPEED 0.2f
void static key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
        glfwSetWindowShouldClose(window, GLFW_TRUE);

    if(key == GLFW_KEY_W)
    {
        c.translateForward(CAM_SPEED);
    }
    if(key == GLFW_KEY_S)
    {
        c.translateForward(-CAM_SPEED);
    }
    if(key == GLFW_KEY_A)
    {
        c.translateSideways(-CAM_SPEED);
    }
    if(key == GLFW_KEY_D)
    {
        c.translateSideways(CAM_SPEED);
    }
    if(key == GLFW_KEY_SPACE)
    {
        c.translate(vec3(0,1,0)*CAM_SPEED);
    }
    if(key == GLFW_KEY_LEFT_SHIFT || mods==GLFW_MOD_SHIFT)
    {
        c.translate(vec3(0,-1,0)*CAM_SPEED);
    }
}

```

# Answer
You can use `glfwGetKey` (call it each tick).
`if(glfwGetKey(p_window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS)`
> 2 votes

---
Tags: opengl, camera, input, glfw
---


title: Game Engine Memory Allocator

text:
# Question
Title: Game Engine Memory Allocator
I'm a bit confused on how to implement an allocator for my game engine. I'm currently trying to implement PhysX for the physics in my game and it requires an implementation of an abstract allocator class that they defined. I've only heard of allocators spoken about in a general and abstract way so I'm not sure about how they are precisely implemented.

Now what I'm not so certain is that should a game engine contain multiple different allocators for different aspects of the engine i.e a separate allocator for shaders, textures, physics engine, meshes, etc... and if so, how do you know what asset requires an allocator class for it?

Or do you have one allocator class that allocates memory for any type of object? and if so, how do you know how much memory you'd need for the runtime of your program?

In this gamasutra post: https://gamasutra.com/blogs/MichaelKissner/20151104/258271/Writing\_a\_Game\_Engine\_from\_Scratch\__Part\_2\_Memory.php

He chooses an arbitrary value of 64 objects to allocate memory for. If you have different types of objects, surely 1 type of object will take more memory than another type so why the arbitrary 64? I'm sure he was using 64 just as a replacement for N. But how do we define N here?

# Answer
> 4 votes
What kind, and how many, allocators you need depends on what you're doing with memory. If you want a particle system, then you should probably create a pool allocator, as it's often the most efficient for the job. If you have assets that are loaded and unloaded sporadically, you'll need a more dynamic allocator (which is often less performant). So it all depends on exactly how your game works. Many smaller games uses only heap allocation (new or malloc) and works fine. Custom memory allocation is an optimisation and depends on your specific use-case (although, there are commonalities).

Although, many allocators works well in many different circumstances and can be reused. But remember that memory allocation is an optimisation, so you should often profile your use-case before implementing a more specific allocator. If you notice that your game is slow iterating through entities because they're scattered around in memory, you should probably change to an allocator that pack things tightly. But if you then notice that the overhead of packing the entities cost more performance, you should change to another allocator. It's a challenge of weighing pros, cons and restrictions.

They talk about it a little in the gamasutra link under **Memory Manager Types in Games**. Basically, you identify an issue and try to solve that issue. Their example is that when you render a scene, you use a lot of memory that are not needed in the next frame. Instead of constantly asking for memory and freeing memory each frame, you allocate a chunk of memory that you just reuse every scene. Very common. The basic rule is that calling the kernel/OS for memory (using new or malloc) is slow, so you should do this as little as possible.

Why they chose to use the arbitrary value of 64 is because you want to preallocate objects in order to avoid asking the kernel for more memory every time you need a new object. But the 64 is a bit too generic and should probably be changed depending on for what the allocator is used. But this requires some profiling or knowledge about your memory needs.

---
Tags: architecture, memory-efficiency, physx
---


# Question
Title: SharpDX Error 'The Parameter is Incorrect', how to debug from dx?
I have written some code to handle a DX device. When the code is finished and makes it's call to DX the DX engine is complaining. What I'm looking to understand is how one goes about debugging on the DX end or at most what parameter passed is trowing an error.

For reference this is my code. This is not the complete class but gives an idea of the code I'm attempting. Happy to share more if needed.

```
public void doFFBAPI(Joystick joystick)
        {
            var allEffects = joystick.GetEffects( EffectType.All );

            foreach (var ei in allEffects)
            {
                if (Convert.ToString((int)ei.Type & 7, 2) == "101")
                {
                    EffectParameters ep = new EffectParameters();
                    int xAxisOffset = 0, yAxisOffset = 0;
                    int nextOffset = 0;
                    foreach (DeviceObjectInstance d in joystick.GetObjects())
                    {
                        if (d.ObjectType.Equals(DeviceObjectTypeFlags.ForceFeedbackActuator))
                        {
                            if (nextOffset == 0)
                                xAxisOffset = d.Offset;
                            else
                                yAxisOffset = d.Offset;
                            nextOffset++;
                        }
                    }

                    int[] offsets = new int[2];
                    offsets[0] = xAxisOffset;
                    offsets[1] = yAxisOffset;
                    int[] coords = { 0, 0 };

                    ep.Flags = EffectFlags.Cartesian | EffectFlags.ObjectOffsets;
                    ep.Directions= new int[1]{0};//MaxValue
                    ep.Gain = 10000;
                    ep.Duration = int.MaxValue;
                    ep.SetAxes(offsets, coords);
                    ep.SamplePeriod = joystick.Capabilities.ForceFeedbackSamplePeriod;
                    ep.TriggerButton = -1;
                    ep.TriggerRepeatInterval = int.MaxValue;
                    ep.Envelope = new Envelope();
                    ep.Axes = new int[1] { 0 };
                    ep.StartDelay = 0;
                    CustomForce CF = new CustomForce();
                    CF.ChannelCount = 2;
                    CF.SampleCount = 12;
                    CF.SamplePeriod = 1000;
                    int[]  forces;
                    forces = new int[24];
                    forces[0] = 79;
                    forces[1] = 0;
                    forces[2] = 0;
                    forces[3] = 0;
                    forces[4] = 0;
                    forces[5] = 0;
                    forces[6] = 0;
                    forces[7] = 0;
                    forces[8] = 0;
                    forces[9] = 0;
                    forces[10] = 0;
                    forces[11] = 0;
                    forces[12] = 0;
                    forces[13] = 0;
                    forces[14] = 0;
                    forces[15] = 0;
                    forces[16] = 0;
                    forces[17] = 0;
                    forces[18] = 0;
                    forces[19] = 0;
                    forces[20] = 0;
                    forces[21] = 0;
                    forces[22] = 0;
                    forces[23] = 0;
                    CF.ForceData = forces;
                    ep.Parameters = CF;

                    Effect e = new Effect(joystick, ei.Guid, ep);//<-- trows the DX error.
                    effect = e;
                    e.Start();
                }
            }
        }

```

Here is the error

An unhandled exception of type 'SharpDX.SharpDXException' occurred in SharpDX.dll

Additional information: HRESULT: \[0x80070057\], Module: \[General\], ApiCode: \[E\_INVALIDARG/Invalid Arguments\], Message: The parameter is incorrect.

I marked the section of code where the error occurs. I recall doing some debugging in IE once where I could attach a processes, can that be done with some DX dll of sorts? There must be a way to get more detailed info here. I tried contacting sharpDX but they don't seem to frequent the forums much.

# Answer
I was having the exact same error on the same line, and I managed to solve by completing all the properties of the EffectParameters object.

Mine was the ep.TriggerButton, that I changed from 0 to -1.

I know that you already have this property set on yours, but maybe some other property that have wrong value/not set.
> 1 votes

---
Tags: sharpdx, debugging
---


# Question
Title: Collision between a player and a solid block C++ SDL2
I am trying to implement a collision between a player and a solid e.g. a solid box.

```
bool Collision::Checkcollision(const SDL_Rect &A, const SDL_Rect &B)
{
    return A.y + A.h >= B.y &&
    A.y <= B.y + B.h &&
    A.x <= B.x + B.w &&
    A.x + A.w >= B.x;
}

if (CKeyboard::Get()->GetKey(SDL_SCANCODE_DOWN))
        {
             Vel.y += 1.0f;
        }
        if (CKeyboard::Get()->GetKey(SDL_SCANCODE_RIGHT))
        {
            Vel.x += 1.0f;
        }
        if (CKeyboard::Get()->GetKey(SDL_SCANCODE_UP))
        {
            Vel.y -= 1.0f;
        }
        if (CKeyboard::Get()->GetKey(SDL_SCANCODE_LEFT))
        {
            Vel.x -= 1.0f;
        }
        Position = Position + Vel.GetNormalized();
        SDL_Rect r1 = Sprite->Get_Rect();
        SDL_Rect r2 = Sprite1->Get_Rect();
        if (Collision::Get()->Checkcollision(r1,r2))
        {

            if (Vel.x < 1.f)
            {
                Position.x = Position.x - 1;
                Vel.x = 0;
            }
            if (Vel.x > 0.f)
            {
                Position.x = Position.x + 1;
                Vel.x = 0;
            }
            if (Vel.y < 1.f)
            {
                Position.y = Position.y - 1;
                Vel.y = 0;
            }
            if (Vel.y > 0.f)
            {
                Position.y= Position.y + 1;
                Vel.y = 0;
            }
        }

```

The problem is I still can move through the box if i keep pressing a key. So the question is what is the best way to implement collision in SDL? Thank you in advance

# Answer
Create a new rect and initialize it with the dimensions of of your player(you named it Sprite) and make the new rect move with your player and check if the collision box of the player Colides with the solid object(Sprite1) and. Check out lazyfoo´s tutorial: https://lazyfoo.net/tutorials/SDL/27\_collision\_detection/index.php

```
    SDL_Rect r2 = Sprite1->GetRect();
    if (CKeyboard::Get()->GetKey(SDL_SCANCODE_LEFT))
    {
        Vel.x -= 1.0f;
    }
    else if (CKeyboard::Get()->GetKey(SDL_SCANCODE_RIGHT))
    {
        Vel.x += 1.0f;
    }

    Position.x += Vel.x;
    Collisionbox.x = Position.x;

    if (Collision::Get()->Checkcollision(Collisionbox, r2))
    {
        Position.x -= Vel.x;
        Collisionbox.x = Position.x;
    }

    if (CKeyboard::Get()->GetKey(SDL_SCANCODE_UP))
    {
        Vel.y -= 1.0f;
    }
    else if (CKeyboard::Get()->GetKey(SDL_SCANCODE_DOWN))
    {
        Vel.y += 1.0f;
        Vel.y += 1.0f;
    }

    Position.y += Vel.y;
    Collisionbox.y = Position.y;

    if (Collision::Get()->Checkcollision(Collisionbox, r2))
    {
        Position.y -= Vel.y;
        Collisionbox.y = Position.y;
    }

```

I didn't test the code but it should work. If you'll still have trouble check out lazyfoo's tutorial about collision as I said :P.

I hope this helps
> 1 votes

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


# Question
Title: Remove Sprite Shape Controller Icons from 2D sprite shapes
How do I get rid of those "purple icons in my scene"? They are so annoying ... they literally covers the entire 2d shape! GIF showcasing it

# Answer
> 1 votes
> ## **The icons can be turned on/off from under the Gizmo tap.**

---
Tags: unity, 2d, sprites
---


# Question
Title: Apply impulse in direction line is pointing with force proportional to the length of line
I have a line perpetually pointed at the mouse and originating at the player, but the length is limited to a certain value.

I also can create a circular object on demand in Box2D (specifically the love2d bindings). I would like to apply an impulse on the new object that will send it flying in the direction of the line, with force proportional to the length of the line (that specific proportion is not important). The object should not roll along that line like a cannonball in a cannon barrel, but it should begin its journey in the direction of the line, such that a user can intuitively direct the projectile (all my attempts\* at solving this issue have led to some angles (45/135) having similar projectile directions as flat angles (0/180), which means the angle is not functional as an aiming mechanism). I suppose a successful implementation might look like this:

I have been looking through tutorials and haven't found an answer. I see whisperings of ways to do it by simply supplying the angle (if I read the pages correctly) but Love2D's function does not support that.

The way in Love2D to apply a linear impulse is `Body:applyLinearImpulse( ix, iy, x, y )` with ix and iy being the x and y components of the impulse, and x and y being the position to apply the impulse (default to origin of body).

---

\*The best I have tried is to apply the distance of the line as the x/y components in `applyLinearImpulse`. This creates the awful failure I mentioned earlier where the angle of the line does not produce much difference in the angle of the projectile (but it does produce a **tiny** amount, with extremely diminishing returns as the line approaches a 90 degree angle / vertical line).

# Answer
The user bageltan on the love2d discord has supplied me with the answer: (line.x and line.y are the x and y positions of the **end** of the line and in my case player.x/player.y are the **start** of the line and where the projectiles spawn.)

`ix = line.x - player.x`

`iy = line.y - player.y`

You can multiply the sum of these by any number you choose to increase/decrease the force of the throw within the proportion. Here is an example showing it works, with the equations multiplied by `0.5`.
> 1 votes

---
Tags: physics, box2d, projectile-physics
---


title: Tile palette off-centered

text:
# Question
Title: Tile palette off-centered
Unity has a wonderful Tile Palette feature. However after I drag and drop the sprites to the Tile Palette, the tiles are off-centered like so (Notice the white square, it's the cursor):

I've tried fiddling with the Cell Size/Gap within the Grid object, and the Tile Anchor from the Tileset object with no difference.

Although I can place the tiles right in the scene, it's a headache to re-arrange and place the tiles within the Tile Palette with this off-center tile issue.

Did anyone of you faced and solved this issue before? Perhaps I overlooked something?

# Answer
I fixed it by:

1.) Deleting my current tiles in the tile palette.

2.) In the inspector, after selecting the sprite that I wanted fixed properly on the tile palette, I changed the sprite's pivot from "bottom left" to "center".

3.) Made sure to hit apply at the bottom of the inspector.

4.) Then dragged the updated sprite into the editor and it was then centered properly.

Hope this helps, its my first time ever posting something about Unity.
> 7 votes

# Answer
If you want the sprite's pivots te remain off-center, then you should fix it the following way.

* Find the prefab of the tile palette in your project view
* Double click it to open it in Prefab Mode.
* Select the layer
* In the Inspector, set the anchor (here left bottom)

Thanks to the Unity forum
> 1 votes

---
Tags: unity, tilemap
---


# Question
Title: same 8bit created surface resulting in a different pitch value
Given:

```
const int w = 10;
const int h = 10;
const int d = 8;
uint8_t* pixels = new uint8_t[w * h]

SDL_Surface* src = SDL_CreateRGBSurfaceFrom(pixels, w, h, d, w, 0, 0, 0, 0);
SDL_Surface* dst = SDL_ConvertSurface(src, src->format, 0);
// src->pitch == 10;
// dst->pitch == 12;
//std:: cout << src->pitch == dst->pitch << std::endl;

```

My expected result is that the two pitches must match.

In this case I have the "weird" 12 pitch value for the `dst` image create from the `src`.

* Is that due to memory alignment optimization?
* Is there any reasonable explanation about it?
* Are those padding bytes used somehow or just wasted?

# Answer
The following is based on a quick look at the SDL source code for `SDL_ConvertSurface`:

`SDL_ConvertSurface` calls `SDL_CreateRGBSurface`, which determines the used pitch with `SDL_CalculatePitch`, which aims to pad the surface to 4-bytes for speed reasons. This makes sense as memory is likely to be fetched in minimum 32-bit chunks (at least on x86).

So yes, this is indeed a memory alignment optimization (12 is padded to 4, 10 is not). The extra allocated bytes don't seem to be used, as they are allocated to be part of the surface's pixel array.
> 3 votes

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


# Question
Title: Make non-sprite render in front of sprite
**How do I make the non-sprite (*BasicSpellProjectile*) render in front of the sprite (*Tower 2*)?**

**Note:** The camera is located at `z=-10`.

The z positioning apparently doesn't do anything, and I am unable to set the sorting layer/order of the non-sprite as there isn't one such option.

# Answer
> 1 votes
Okay, the solution was very rather simple. It was the sorting layer/order of the child of the *projectile* that caused it. Changing it solved the issue.

---
Tags: unity, rendering, sprites, draw-order, layers
---


# Question
Title: How do I get the player's position in Roblox Studio?
In Roblox Studio, I have this code in a script file:

```
while true do
    wait(0.01)
    local PlayersService = game:GetService("Players")
    local players = PlayersService:GetPlayers()
    for i, player in pairs(players) do
        print(player.Name)
    end
end

```

This successfully prints the player's name many times per second. However, I would like to know how I can get other properties, such as the player's position. `player.Position` doesn't work, and I have no idea what options are available because autocomplete is not working when I type `player.`. What properties are available on `player` and how do I get the position?

# Answer
I feel your pain. Roblox is very confusing, despite their claims that it is an easy way to learn scripting.

To get a player's position (server side) you need to access the player's character property. (`player.Character`).

Before you can access the Character property, you need to get the player's object. This can be done be capturing the player object when they first load onto the server using a regular script somewhere in the Workspace.

The game I'm working on is a single player game, so I store the player object in an object container which I access whenever I need the value in any of my server side scripts.

For example:

```
game.Players.PlayerAdded:Connect(function(player)

workspace.Data.Player.Value = player

end)

```

This script fires when a player joins the game. In my case, only one player is on the server, but you can adapt the code to track other players as you see fit.

'`Data`' is just a folder I put in the Workspace and '`Player`' (Capital P) is an `ObjectValue container` I named '`Player`' which I use to store the player object. You can rename or adjust that any way you see fit, or store the player object in any manner you wish. Now if you want to access the player's properties, including position, you would do this in a regular script:

```
local player = Workspace.Data.Player.Value --Get's player object and stores it in 'player' variable

local var = player.Character.UpperTorso.Position -- Gets vector3 position

```

Or, If you want to get the individual X, Y, Z co-ordinates

```
local varX = player.Character.UpperTorso.Position.X

local varY = player.Character.UpperTorso.Position.Y

local varZ = player.Character.UpperTorso.Position.Z

```

There are different ways of getting the player object, but this is the way that I am using for my purposes.

Also, `UpperTorso` is used for `R15 Humanoids`, so it may not work on `Humanoid models` that are not `R15`. `UpperTorso` is just one of the `humanoid body parts`, which is used to track player position.

If you want to track a different body part, run your game in the Developer Studio, and while it is running, click on `StarterPlayer` and then `HumanoidDefaultBodyParts` (found in Explorer view) which will give you a list of trackable body parts you can use instead of `UpperTorso`. The only way to track a player position is through a body part.

Hope this helps, and good luck.

---

PS: https://developer.roblox.com/en-us/api-reference/class/Player

The above link will take you to a developer page. If you look at the far right, you will see a list of properties and events that are used in conjunction with the player object.
> 6 votes

# Answer
Sometimes Roblox studio actually doesn't show your options. I have experienced this before. This is due to the fact that the object isn't actually present in the workspace but will be created when the game starts. So, treat it like any other object.
> 0 votes

---
Tags: lua, roblox
---


# Question
Title: Can i use the same name for a spell in my game that already exists in another game
what does trademarks and copyrights contain. how similar can a name be to a name that already exists.

# Answer
> 1 votes
Unfortunately your question is too vague to answer in depth. Trademarks are governed based on laws that originate from countries, so what is legal in one country may not be legal in another. As a general rule, Trademarks cannot be copied. So if you want to name your game "Star Trek 2" for example, you will probably get a lawsuit. If you want to name an object in your game "Shields" then you are safe, even though Star Trek uses the same name, because "Shields" is a description based name and cannot be copyrighted, for the most part. To share an example, I use a Music Creation Utility Called "FL Studios". Before they changed their name, it used to be called "Fruity Loops". They were sued by Kellogg's because their cereal "Fruit Loops" is trade marked, and so they had to change the name to FL Studios.

Another example would be "Levi's" and "Wrangler". Both companies produce "Jeans" and both companies can use the term "Jeans" to describe their product, because it is a descriptive term that cannot be copyrighted. So if your spell is named "Fire Ball" or "Lightning Strike" multiple people can use it because it is description based. But if it is a specific name and not descriptive, you could be liable for using it.

# Answer
> 1 votes
we may not be the most suitable to answer. It would be best to go to a lawyer whose specialty is copyright.

But I will try to contribute my 2 cents to the subject, remembering how little I have been taught about Legislation, and Computer Legislation at the University.

Technically the copyright falls on the name of a trademark. And for this, they must be duly registered in the patent and / or copyright office that legislates and controls in each country. One can register any name as a trademark, as long as he can demonstrate that he will make an onerous use of it.

Now, going specifically in the area of computing and software, where things are abstract, there are certain things to consider. What one registers is the manifestation of an idea. And not the idea itself. It is true that there are places in the world where one can patent an idea. In fact, I would almost dare say that the USA is the only one. The USA patent and copyright and trademark system is one of the most disastrous and contrary to common sense. Examples of the ridiculous things you will find in the fight for the one who invented round edges on cell phones.

Pointing out in your case, and considering the legislative aspects of the USA, your concern is totally valid. But it is highly unlikely that a video game company will register the name of one of their spells to screw around and prevent others from using them.

Using Derrick's example, how is the company in question going to demonstrate that they were the inventors of the name for their spells? What other ways could a fireball be called? You cannot limit the action of an idea! If you want to put a fireball spell and other games do it too, that's fine. That some company appears now pretending to prevent others from using fireballs because they already have them ... it is nonsense.

Now, if it turns out that the spell's name properly has a highly distinguishable name, and that it is fully assimilated as part of the game's name trademark, the thing may have some legal complication.

Take as a case the "Windarmium Leviosá", from the world of Harry Potter. Take this spell outside, if it can conflict. Makes the entire package "Harry Poter"! And if you try to use it somewhere else, other than "Harry Poter something" it is quite likely that you will be accused of plagiarism.

On the other hand there are expressions that are already as common and current as "focus focus", or "Abra Cadabra" which do not fit copyrights. Mainly for 2 reasons: 1. are current expressions and that were acquired by popular use and custom. 2. The possible rights that may have been applied to it expired long ago.

One possibility you can evaluate is to consult the developers or the company, and they give you their permission. But first: consult a lawyer who works on the subject.

---
Tags: legal, trademark
---


# Question
Title: Follow behaviour with transform.LookAt on Unity2d
So i've been trying to make an enemy follow my player on Unity2d using `transform.LookAt`.
While it does follow the player, It also rotates the enemy as well in 3D but my sprite is made for 2d so the sprite just vanishes. Any ideas?

```
//follows player
transform.position = Vector2.MoveTowards(transform.position, target.position, speedEnemy * Time.deltaTime);

//make enemy look towards player
transform.LookAt(target);

```

# Answer
> 1 votes
This should work:

```
using UnityEngine;

 public class Enemy : MonoBehaviour
 {

 public Transform target;
 public float speed = 3f;

 private void Update()
 {
     if (Vector3.Distance(transform.position, target.position) > 1f)
     {
         MoveTowards(target.position);
         RotateTowards(target.position);
     }
 }

 private void MoveTowards(Vector2 target)
 {
     transform.position = Vector2.MoveTowards(transform.position, target, speed * Time.deltaTime);
 }

 private void RotateTowards(Vector2 target)
 {
     Vector2 direction = (target - (Vector2)transform.position).normalized;
     var angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
     var offset = 90f;
     transform.rotation = Quaternion.Euler(Vector3.forward * (angle + offset));
 }
 }

```

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


# Question
Title: How can i stop Steam's RPG Maker XP from rewriting my Game.ini file?
I've been using RPG Maker XP for a long time, i think before Steam. back then to get RPG Maker XP Working you had to connect it to the net to get an Ntitles serial before you could put in the activation code.

this has been fine for the past 10-15 years where i have been running it off my Portable HDD with my projects (on Windows XP and 7). i also have gotten RPG Maker XP on Steam with a Humble Bundle that included VX, VX Ace and MV. recently i upgraded my PC now with Windows 10 and when i went to use my old copy on my Portable HDD, even when connected to the internet (and i did check the network, nothing was wrong) it couldn't get the Ntitles serial. so then i fell back to the Steam Version. this worked and didn't even ask me for a key (though downside is that i now have to have Steam running for when it starts up).

While working on my project i went to playtest and i got the error

> The specified procedure could not be found

after debugging i found out that when i saved my Project, the Steam RPG Maker XP dumped a RGSS104E.dll file into my project and rewrite Game.ini to point to it. this is an issue because i use the RPG Maker XP Ace which required VX Ace's RGSS3 .dll. when i edited the .ini file my game worked with no issue and i found that if i save Game.ini with the correct library after saving my project before pressing the playtest button things work.

however keeping Notepad++ open and re-saving the file each time is a pain. ways to avoid this that i have tried are

* **Rename the RGSS3 .dll in my project folder to RGSS104E.dll** \- doesn't work as RPG Maker XP is dumping RGSS104E.dll overtop (confrimed as the Modified Date changes and the error returns)
* **Replace RGSS104E.dll to a renamed RGSS3 .dll in the RPG Maker XP Install Dir** \- doesn't work because then the Editor reports that it couldn't find RGSSInitialize
* **Do above but after the editor has started** \- the .dll is locked and Windows wont let me do anything with the .dll
* **Use my original copy of RPG Maker XP** \- the Ntitles server i suspect is dead as it wit keeps reporting the same issue while while Steam's version is installed all Projects associate with it (as such uninstalling Steam's version wont work)

So I would like to know how can i stop Steam's RPG Maker XP from rewriting my Game.ini file? if i stop it doing this then i can point to the RGSS3 .dll and just not care when it redumps RGSS104E.dll. alternatively i would like to stop RPG Maker XP to stop dumping RGSS104E.dll in my game folder as this way i can just rename the .dll

# Answer
Unfortunately, even the pre-Steam version of RMXP likes to rewrite the Game.ini - it'll change the Library entry to refer to a dll in the root depending on the version. 104E for newer versions, and 102E or older ones. It does *not*, however, alter the present DLL itself.

I'm using XP Ace myself, and I would also like to fix this mostly so I can keep the dll in the System folder, but no dice. So I'm forced to have the RGSS3 dll (renamed) in the root.

The best thing I can recommend is to use the pre-Steam RMXP editor. Because the DRM is broken by this point, you'll need to either enter your registration key manually into the registry somehow, or back it up from a working install and patch it into your existing one, if you have it.
> 1 votes

---
Tags: steam, rpg-maker-xp
---


# Question
Title: glfwCreateWindow function returning NULL
I am working on creating a game engine using GLFW. To begin, I set up a window class in C++ to test how making a window works. For some reason, when I call the glfwCreateWindow function, it returns NULL instead of GLFWwindow\*. Here is my code (I have a header file that defines the class and then the c++ file that defines the class):

Here is the window.h header file:

```
#pragma once

#include <iostream>
#include <GLFW/glfw3.h>

namespace harmony { namespace graphics {

    class Window
    {
    private:
        const char* m_Title;
        int m_Width, m_Height;
        GLFWwindow* m_Window;
        bool m_Closed;
    public:
        Window(const char* name, int width, int height);
        ~Window();
        bool closed() const;
        void update() const;
    private:
        bool init();
    };

} }

```

And here is the c++ window.cpp file:

```
#include "window.h"

namespace harmony { namespace graphics {

    Window::Window(const char* title, int width, int height)
    {
        m_Title = title;
        m_Width = width;
        m_Height = height;
        if (!init())
            glfwTerminate();
    }

    Window::~Window()
    {
        glfwTerminate();
    }

    bool Window::init()
    {
        if (!glfwInit)
        {
            std::cout << "Failed to initialized" << std::endl;
            return false;
        }

        m_Window = glfwCreateWindow(m_Width, m_Height, m_Title, NULL, NULL);
        if (!m_Window)
        {
            std::cout << "Failed to create window!" << std::endl;
            return false;
        }
        glfwMakeContextCurrent(m_Window);

        return true;
    }

    bool Window::closed() const
    {
        return glfwWindowShouldClose(m_Window);
    }

    void Window::update() const
    {
        glfwPollEvents();
        glfwSwapBuffers(m_Window);
    }

} }

```

And lastly here's my main.cpp:

```
#include "window.h"

int main()
{
    using namespace harmony;
    using namespace graphics;

    Window window("Yay it works!", 800, 600);

    while (!window.closed()) {
        window.update();
    }
    return 0;
}

```

I looked it up and there are only a couple cases (in the source code of glfwCreateWindow) where it returns NULL, but I haven't found a good way to troubleshoot which one.

# Answer
To troubleshoot glfw, define the glfw error callback:

```
void error_callback( int error, const char *msg ) {
    std::string s;
    s = " [" + std::to_string(error) + "] " + msg + '\n';
    std::cerr << s << std::endl;
}

```

Before initnializing glfw, set the callback:

```
glfwSetErrorCallback( error_callback );

```

Give it a few hints:

```
if( GL_TRUE != glfwInit() )
    std::cerr << "Error initialising glfw" << std::endl;
glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR, 4 );
glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, 5 );
// If you want the opengl debug context from 4.3 onwards, which you do:
glfwWindowHint( GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE );
glfwWindowHint( GLFW_CLIENT_API, GLFW_OPENGL_API );
glfwWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE );

```

And the window should open effortlessly, assuming the OS base with driver works edit: and the function glfwInit() is called instead of its pointer questioned.
> 0 votes

---
Tags: opengl, c++, glfw
---


# Question
Title: Black texture when manually creating from image
I am trying to create a ID3D11Texture2D from a RgbaImage loaded from a `.jpg`. The below code produces no errors. However, the texture is black when it is actually rendered. I know the standard way to load textures is through the DirectXTex library, but I was having issues linking with it and can't find any premade Rust bindings.

* Should the below code/settings work to create a working `ID3D11Texture2D`?
* Is there a way to view the contents of a `ID3D11Texture2D` in order to debug?
* Are there `DirectXTex` bindings for Rust?

```
fn load_resource_from_file(device: &Device, path: &Path) -> error::Result<Texture> {
    unsafe {
        let image = Reader::open(path)?.decode()?.to_rgba();

        let mut sample_desc = dxgitype::DXGI_SAMPLE_DESC::default();
        sample_desc.Count = 1;
        sample_desc.Quality = 0;

        let mut desc = d3d11::D3D11_TEXTURE2D_DESC::default();
        desc.Width = image.width();
        desc.Height = image.height();
        desc.MipLevels = 1;
        desc.ArraySize = 1;
        desc.Format = dxgiformat::DXGI_FORMAT_R8G8B8A8_UINT;
        desc.Usage = d3d11::D3D11_USAGE_DEFAULT;
        desc.SampleDesc = sample_desc;
        desc.BindFlags = d3d11::D3D11_BIND_SHADER_RESOURCE;
        desc.CPUAccessFlags = 0;
        desc.MiscFlags = 0;

        let mut data = d3d11::D3D11_SUBRESOURCE_DATA::default();
        data.SysMemPitch = (image.sample_layout().width_stride * mem::size_of::<Rgba<u8>>()) as u32;
        let buffer: Vec<u8> = image.into_raw();
        data.pSysMem = buffer.as_ptr() as *const _;
        data.SysMemSlicePitch = buffer.len() as u32;

        let mut texture = ptr::null_mut();
        device.as_ref().CreateTexture2D(
            &desc,
            &data,
            &mut texture,
        ).result()?;
        let texture = NonNull::new(texture).ok_or(null_ptr_err!())?;

        drop(buffer);

        let mut resource_view = ptr::null_mut();
        device.as_ref().CreateShaderResourceView(
            &**texture.as_ref() as *const d3d11::ID3D11Resource as *mut _,
            ptr::null(),
            &mut resource_view,
        ).result()?;
        let resource_view = NonNull::new(resource_view).ok_or(null_ptr_err!())?;

        Ok( Texture(Arc::new(TextureInner {
            texture,
            resource_view,
        })))
    }
}

```

# Answer
Finally figured it out. Rather than `DXGI_FORMAT_R8G8B8A8_UINT`, `DXGI_FORMAT_R8G8B8A8_UNORM` is required. Fixing this fixed the black texture. However, there are some other problems with my code.

* The different strides are already multiplied by the size of the pixel. I don't know what happens if you use a non-`u8` image format.
* `height_stride` should be used instead of `width_stride`. Confusingly, `height_stride` is the stride between different heights, aka the width+padding. I assume this is different for column-major images.

I would still appreciate a way to view the contents of a `ID3D11Texture2D`, as well as a solid answer on whether or not there are existing bindings to `DirectXTex`.

Final Code:

fn load_resource_from_file(device: &Device, path: &Path) -> error::Result<Texture> {
    unsafe {
        let image = Reader::open(path)?.decode()?.to_rgba();

        let mut sample_desc = dxgitype::DXGI_SAMPLE_DESC::default();
        sample_desc.Count = 1;
        sample_desc.Quality = 0;

        let mut desc = d3d11::D3D11_TEXTURE2D_DESC::default();
        desc.Width = image.width();
        desc.Height = image.height();
        desc.MipLevels = 1;
        desc.ArraySize = 1;
        desc.Format = dxgiformat::DXGI_FORMAT_R8G8B8A8_UNORM;
        desc.Usage = d3d11::D3D11_USAGE_DEFAULT;
        desc.SampleDesc = sample_desc;
        desc.BindFlags = d3d11::D3D11_BIND_SHADER_RESOURCE;
        desc.CPUAccessFlags = 0;
        desc.MiscFlags = 0;

        let mut data = d3d11::D3D11_SUBRESOURCE_DATA::default();
        data.SysMemPitch = image.sample_layout().height_stride.max(
            image.sample_layout().width_stride
        ) as u32;
        let buffer: Vec<u8> = image.into_raw();
        data.pSysMem = buffer.as_ptr() as *const _;

        let mut texture = ptr::null_mut();
        device.as_ref().CreateTexture2D(
            &desc,
            &data,
            &mut texture,
        ).result()?;
        let texture = NonNull::new(texture).ok_or(null_ptr_err!())?;

        drop(buffer);

        let mut resource_view = ptr::null_mut();
        device.as_ref().CreateShaderResourceView(
            &**texture.as_ref() as *const d3d11::ID3D11Resource as *mut _,
            ptr::null(),
            &mut resource_view,
        ).result()?;
        let resource_view = NonNull::new(resource_view).ok_or(null_ptr_err!())?;

        Ok( Texture(Arc::new(TextureInner {
            texture,
            resource_view,
        })))
    }
}
```

> 1 votes

---
Tags: textures, directx, directx11, rust
---


# Question
Title: Understanding buffer swapping in more detail
This is more a theoretical question. This is what I understand regarding buffer swapping and vsync:

I - When vsync is off, whenever the developer swap the front/back buffers, the buffer that the GPU is reading from and sending to the monitor will be changed to the new one, regardless if the old buffer was being read (i.e. no vblank is needed).

II - When vsync is on, the buffers are not immediately swapped, they will only be changed when the old buffer was completely read (i.e. vblank is needed).

III - Turning vsync off can boost the frame rate to be greater than the monitor refresh rate, but screen tearing can appear when buffers are swapped when they are being read

IV - Turning vsync on prevents tearing, but the monitor refresh rate limits the FPS.

Based on this I tried to do the following experiment: I disabled vsync and rendered a simple `glClear + glClearColor` every frame, with a new random color per frame. I got ~2400FPS in a 60Hz monitor. Since every frame I swapped the buffers, and since the monitor takes 1/60 second for each full screen drawing, I was expecting that each time the monitor was being refreshed, the buffers would have been swapped roughly ~40 times. This is because in 1/60s, there are around 40 buffer swapping calls. Since everytime the buffers are swapped the clear color is different, I was expecting to see a really messy image, with lots of different colors, because of the tearing. Instead, by taking some screenshots I didn't see any tearing... every pixel had the same solid color.

Could someone point the wrong assumptions that I had and why I see such behavior?

Thanks in advance!

# Answer
The problem was related to the window manager. I could see the expected behavior when I ran in full screen.
> 1 votes

---
Tags: opengl, gpu, vsync
---


# Question
Title: Calculating price increases in a virtual economy
I'm trying to design a method to have price increase depending on the number of items bought from shops in my game.

I'm fairly new to coding and I am struggling to figure out how to program the increase in price when buying multiple items.

Currently the price increase is a percentage increase based on the quantity of items in store, however if I buy 5 items, all 5 items will be charged the same. How can I get it so each item is charged at a different price?

I also need a reasonable inflation system, right now my code just determines a price increase based on the percentage of items remaining, but it's very simple and easy to exploit. It looks like this:

30 - 2 = 28

1 - (28 / 30) = 0.07 0.93

1 + 0.07 = 1.07

10 * 1.07 = 10.7

Rounded up

Price = 11

I'd like to make this more complex also.

# Answer
I don't have enough reputation points to leave comments. So it forces me to answer this way.

First of all excuse me if my English is not very good. It is not my native language.

If I am allowed any constructive criticism, generating a price hike for each item you buy sooner or later will be a negative point for the player. I would say that sooner rather than later and I end up producing a displeasure and that in the end I end up leaving the game.

Let's say you buy the first bottle of miracle potion at 5, the 2nd at 55, the 3rd at 70, the 4th at 93, you will be paying the 5th for more than 100.

And from what I'm understanding, you want the boost value to be given regardless of whether you make all those purchases in the same transaction. That is, it does not matter if you buy the 5 together, or at different times. If you wanted to emulate the market, that is not the way.

If I go to the market today and buy 5 soda cans of the same thing, I pay it at the same price for each can, unless I find a 3x2 offer to give an employment. Tomorrow is something else, and the price may be different.

You should objectively analyze what you intend to do. Define the limits or scope of the "simulation of an inflationary process". That by the way, inflation is not given in that way.

The inflation process is largely due to an excessive increase in the money supply. More info in Money Supply.

But it is possible that achieving a mathematical model that allows you to carry a macroeconomic balance in your game is more complex than you are looking for.

It seems to me that the simplest approach you can start with is to find a way to emulate the principle of the law of supply and demand.

There is a great video that explains the basis for this.

If managing to implement even the simplest algorithm to cover the basics of that, it might be enough to satisfy your needs.

But as I said before: you should first have your limits well established. How far do you intend to go with emulating the micro and macro economic aspects?
> -1 votes

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


# Question
Title: How to find a non active gameobject in unity?
I am trying to find a gameobject, which is not active in the current scene.It throws Null Reference error.

```
GameObject gameObject;
void start(){
//a non active gameobject tagged with InactiveTag
gameObject = GameObject.FindGameObjectWithTag("InactiveTag");
}
void update(){
if(someCondition){
gameObject.setActive(true); //this line throws Null Reference error
}
}

```

# Answer
> 1 votes
You won't be able to find GameObjects that are inactive at start. you have 2 options:

1. You can start with the object active, so the script can find and deactivate it, at start. But, then it has a reference to track.
2. You can create a public var in your script and drag the object in question to the Inspector reference. Then your script will see it whether it active or not.

# Answer
> 1 votes
This is a method for getting a reference to an initially inactive object that avoids the overhead of the `Find()` type functions:

```
private GameObject myObject;

void Start()
{
    myObject = (GameObject)Instantiate(Resources.Load("MyObject"));
}

```

Your inactive objects must exist in a folder named "Resources" or within a sub-folder of it:

# Answer
> 0 votes
first set a trigger name to the game object

if(trigger.tag == "that game object") { gameObject.setActive(true); }

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


# Question
Title: I can't figure out whats wrong with my .obj file reader
I'm just loading a simple textured cube but it always has missing bits or warped textures. This is for directx 11 rendering by the way. Updated with more information. I think my problem is with duplicate verticies. Generally only 8 are needed to make the cube but there is more texture coordinates than that.

```
std::ifstream file(filepath);

if (file)
{
    std::string buffer;

    std::vector<DirectX::XMFLOAT3> vertexPositions;
    std::vector<VertexPositionTexture> verticies = std::vector<VertexPositionTexture>();
    std::vector<unsigned short> indicies = std::vector<unsigned short>();
    std::vector<DirectX::XMFLOAT2> textureCoordinates;
    std::vector<VertexTextureNormalIndex> faceIndicies;

    while (std::getline(file, buffer))
    {
        if (buffer[0] == 'v' && buffer[1] == ' ') {
            float tmpx, tmpy, tmpz;
            sscanf(buffer.c_str(), "v %f %f %f", &tmpx, &tmpy, &tmpz);
            vertexPositions.push_back(DirectX::XMFLOAT3(tmpx, tmpy, tmpz));
        }
        else if (buffer[0] == 'v' && buffer[1] == 't') {
            float vt1 = 0, vt2 = 0;
            sscanf(buffer.c_str(), "vt %f %f", &vt1, &vt2);
            textureCoordinates.push_back(DirectX::XMFLOAT2(vt1, vt2));
        }
        else if (buffer[0] == 'f') {
            int v1 = 0, v2 = 0, v3 = 0;
            int vt1 = 0, vt2 = 0, vt3 = 0;
            int vn1 = 0, vn2 = 0, vn3 = 0;

            if (buffer.find("//") != std::string::npos) {
                sscanf(buffer.c_str(), "f %d//%d %d//%d %d//%d", &v1, &vn1, &v2, &vn2, &v3, &vn3);
                faceIndicies.push_back({ v1 - 1, -1, vn1 - 1 });
                faceIndicies.push_back({ v2 - 1, -1, vn2 - 1 });
                faceIndicies.push_back({ v3 - 1, -1, vn3 - 1 });
            }
            if (buffer.find("/") != std::string::npos) {
                sscanf(buffer.c_str(), "f %d/%d/%d %d/%d/%d %d/%d/%d", &v1, &vt1, &vn1, &v2, &vt2, &vn2, &v3, &vt3, &vn3);
                faceIndicies.push_back({ v1 - 1, vt1 - 1, vn1 - 1 });
                faceIndicies.push_back({ v2 - 1, vt2 - 1, vn2 - 1 });
                faceIndicies.push_back({ v3 - 1, vt3 - 1, vn3 - 1 });
            }
            else
            {
                sscanf(buffer.c_str(), "f %d %d %d", &v1, &v2, &v3);
                faceIndicies.push_back({ v1 - 1, -1, -1 });
                faceIndicies.push_back({ v2 - 1, -1, -1 });
                faceIndicies.push_back({ v3 - 1, -1, -1 });
            }
        }
    }

    int faceCount = static_cast<int>(faceIndicies.size());

    if (faceCount > 0) {
        std::map<int, int> vertexMap;
        int nextIndex = 0;
        for (int f = 0; f < static_cast<int>(faceIndicies.size()); f++) {
            VertexTextureNormalIndex vtn = faceIndicies.at(f);

            std::map<int, int>::iterator iter = vertexMap.find(vtn.VertexIndex);

            // Check if index already exists
            if (iter != vertexMap.end())
            {
                indicies.push_back(iter->second);
            }
            else {
                DirectX::XMFLOAT2 textureCoords;

                if (vtn.TextureIndex > -1) {
                    textureCoords = textureCoordinates.at(vtn.TextureIndex);
                }
                else {
                    textureCoords = DirectX::XMFLOAT2(0, 0);
                }

                verticies.push_back({ vertexPositions.at(vtn.VertexIndex), textureCoords });
                vertexMap[vtn.VertexIndex] = nextIndex;
                indicies.push_back(nextIndex);
                nextIndex++;
            }
        }
    }

    mesh->verticies = verticies;
    mesh->indicies = indicies;
}

```

```
# Blender v2.80 (sub 75) OBJ File: 'SpaceBox.blend'
# www.blender.org
v 1.000000 1.000000 -1.000000
v 1.000000 -1.000000 -1.000000
v 1.000000 1.000000 1.000000
v 1.000000 -1.000000 1.000000
v -1.000000 1.000000 -1.000000
v -1.000000 -1.000000 -1.000000
v -1.000000 1.000000 1.000000
v -1.000000 -1.000000 1.000000
vt 0.257701 0.281720
vt 0.486975 0.052446
vt 0.257701 0.052446
vt 0.257701 0.510994
vt 0.486975 0.281720
vt 0.257701 0.281720
vt 0.257701 0.740269
vt 0.486975 0.510994
vt 0.257701 0.969543
vt 0.486975 0.740269
vt 0.028426 0.740269
vt 0.257701 0.510994
vt 0.028426 0.510994
vt 0.716249 0.510994
vt 0.486975 0.510994
vt 0.486975 0.281720
vt 0.486975 0.740269
vt 0.486975 0.969543
vt 0.257701 0.740269
vt 0.716249 0.740269
vn 0.0000 -1.0000 0.0000
vn 0.0000 0.0000 -1.0000
vn 1.0000 0.0000 0.0000
vn 0.0000 1.0000 0.0000
vn -1.0000 0.0000 0.0000
vn 0.0000 0.0000 1.0000
s off
f 3/1/1 5/2/1 1/3/1
f 8/4/2 3/5/2 4/6/2
f 6/7/3 7/8/3 8/4/3
f 8/9/4 2/10/4 6/7/4
f 4/11/5 1/12/5 2/13/5
f 2/10/6 5/14/6 6/15/6
f 3/1/1 7/16/1 5/2/1
f 8/4/2 7/8/2 3/5/2
f 6/7/3 5/17/3 7/8/3
f 8/9/4 4/18/4 2/10/4
f 4/11/5 3/19/5 1/12/5
f 2/10/6 1/20/6 5/14/6

```

# Answer
> 1 votes
Usually you do need one vertex per texture co-ordinate.

So you would need 4 vertices x 6 faces = 24 verts. It seems inefficient but it is the way to do it.

Also, you will find that each corner of the cube should have 3 vertex normals, so you will need the 24 verts to accommodate correct normals.

---
Tags: c++, mesh, obj, model-loader
---


# Question
Title: How can I my homing missile avoid walls (2D)?
Okay, I have the homing missile implemented. It will follow the player, but I want it to avoid the walls. I tried out A\* but I want to make my own. I need some help plzz.

# Answer
fo me, I am using raycast to create nodes and then use a\* algorithm to calculate path. But I am just create some iteration of path since game environment will changed every frame. Here's how I create nodes:

1. cast a ray (Physics.raycast) from missile to target, if there's a obstacle get hit point of raycast (usually it's a return value of raycast method).
2. add `missile pos` & `hitpoint pos` divide by `3/4` or `4/8` or whatever it's up to u.
3. we got a **node** by execute step 2.
4. we can repeat step 1 & 2 but this time, we start from the **node** and we cast some degree to the left or right (the degree is up to u). 5.let's said you cast to the left first, since this cast is not to target, just decide how long you want to cast. 6.same as step 1 & 2. but this time we not cast a ray anymore, just switch it to right direction from first **node** we've got from step 3. and do the same thing as left in step 5.
5. now you have 3 nodes! now all you have to do is compare the last two nodes (left & right) because they are branched from the first node, compare who is closest to the target. 8.let's said the result of comparison between left and right nodes is **second nodes**
6. now missile will move to **first node** and then **second nodes**

important to note: 1. as this method is not generate path nodes from start to end, missile can't arrive to the target if they reach dead end like maze environment. But I like this method because it's like realistic missile and low cost performance. 2. you can improve it by increase branch nodes per turn.
> 0 votes

---
Tags: unity, ai, path-finding, steering-behaviors
---


# Question
Title: Making NavMeshAgent to look the direction it was moving when it stops
I'm currently using NavMeshAgent as my player character controlled by keyboard or gamepad input. Also, I'm flipping my character instead of turning via controlling localScale as below.

```
        private void FixHeadRotation()
        {
            float dir = (myAgent.velocity.normalized.x > 0) ? 1 : -1;
            transform.localScale = new Vector3(1, 1, dir);
        }

```

However, since I'm relying on the velocity I'm getting the direction(flip) right when moving, but not when I'm not moving(x should be -1 but 1 since no velocity).

I've noticed the NavMeshAgent has built-in function displaying an arrow gizmo over the agent's head. Perhaps I could use that(don't know how atm)? or any other suggestions to this?

# Answer
> 1 votes
I've solved this by simply conditioning my direction control within a velocity cap

```
private void LateUpdate()
{
    if (myAgent.velocity.x != 0)
    {
        FixHeadRotation();
    }
}

```

---
Tags: unity
---


# Question
Title: Centralized event system using dictionary
I'm trying to make a centralized event system for my unity game - a central hub where other parts of the game can register/broadcast their own types of events. This means I have a singleton `GameEventSystem` that is globally accessible.

This is an example structure:

I have tried to combine multiple sources, trying to figure out how to do this, and this is where I got.
I have a Dictionary where the key is Type(that supposed to be `T : GameEvent`), and the value is `GameEventListener<GameEvent>`, `GameEventListener` is supposed to be `Action<T : GameEvent>`.
What I'm trying to achieve is a singleton class that manages `Dictionary<T : GameEvent, GameEventListener<T : GameEvent>>`.

The implementation of **RegisterListener**:

```
Type eventType = typeof(T);

GameEventListener<GameEvent> listenerTemp;
if (EventListeners.TryGetValue(eventType, out listenerTemp))
{
    listenerTemp += (GameEventListener<GameEvent>)listener;
    EventListeners[eventType] = listenerTemp; // Copy the newly aggregated listener back into the dictionary.
}
else
{
    listenerTemp += (GameEventListener<GameEvent>)listener;
    EventListeners.Add(eventType, listenerTemp);
}

```

And this would be the **UnregisterListener**:

```
Type specificGameEventType = typeof(T);
if (!AnyListeners(specificGameEventType, this.EventListeners))
{
    // No one is listening, we are done.
    return;
}

EventListeners[specificGameEventType] -= (GameEventListener<GameEvent>)listener;

```

Passing an `Action<UnitDiedEvent>` to **RegisterListener** will lead to `InvalidCastException: Specified cast is not valid.`, at the following line:

```
listenerTemp += (GameEventListener<GameEvent>)listener;

```

Why can't I cast a `GameEventListener<UnitDiedEvent>` class, to `GameEventListener<GameEvent>`?

Is there a better approach to achieve a centralized event system in unity?
From my research I can't just make `GameEventSystem` a static class and expect it to be accessed by the rest of the game objects/components. That makes global systems/managers like this one a little problematic to instantiate and access.

I think I'm not fully grasping events/delegates and generics as a whole to tackle this on my own.

# Answer
> 5 votes
This looks like a situation you can tackle with the curiously recurring template pattern.

First, we'll define a generic GameEvent, that could work on payloads of some unknown type, with static methods to register/unregister listeners who care about events of that type, and broadcast the event to all listeners:

```
public abstract class GameEvent<T>
{
    static event System.Action<T> onEvent;

    public static void RegisterListener(System.Action<T> listener) {
        onEvent += listener;
    }

    public static void UnregisterListener(System.Action<T> listener) {
        onEvent -= listener;
    }

    public static void BroadcastEvent(T eventData) {
        onEvent?.Invoke(eventData);
    }
}

```

Then we can specialize it by defining derived types of `GameEvent<T>` where `T` is their own type:

```
public class UnitDiedEvent : GameEvent<UnitDiedEvent>
{
    public enum CauseOfDeath {
        Unknown,
        NaturalCauses,
        Murder
    }

    public GameObject deadUnit;
    public CauseOfDeath cause;
    public GameObject killer;
}

```

Now we can register/unregister a listener by calling a static method on the derived event type we care about:

```
UnitDiedEvent.RegisterListener(OnDeath);

```

And we can fire the event to all listeners similarly:

```
var death = new UnitDiedEvent();
death.deadUnit = gameObject;
death.cause = UnitDiedEvent.CauseOfDeath.NaturalCauses;

UnitDiedEvent.BroadcastEvent(death);

```

And we've done it all without any casting, hashing, or dictionary lookups along the way. :D

---

As to why your original attempt didn't work, it's because arguments to delegates are contravariant.

We generally find covariance most familiar:

```
Animal someAnimalVariable = new Animal();
Cat someCatVariable = new Cat();

// This is valid, because all cats are animals, so we preserve the meaning of
// "someAnimalVariable contains an animal"
someAnimalVariable = someCatVariable;

// This is not valid, because not all animals are cats.
someCatVariable = someAnimalVariable;
// If someAnimalVariable contained a Turtle, our code would become very
// confused when it tries to call someCatVariable.Meow() to make a turtle meow!

```

But delegate arguments are contravariant:

```
System.Action<Animal> someAnimalAction;
System.Action<Cat> someCatAction;

// This is valid. (Delegate with a less derived argument
// assigned to a variable with a more derived argument)
someCatAction = someAnimalAction;

// This is not. (Delegate with a more derived argument
// assigned to a variable with a less derived argument)
someAnimalAction = someCatAction;

```

Why this difference? Think about what happens when code tries to call `someCatAction`:

```
Cat myFavouriteKitty = GetFavouriteCat();
someCatAction(myFavouriteKitty);

```

As long as `someCatAction` accepts an animal, this call is still valid, since all cats are animals. So *any* `System.Action<Animal>` is valid as a value for a delegate we want to pass cats to, like `someCatAction`.

Now think about what happens when code tries to call `someAnimalAction`:

```
Turtle myFavouriteTurtle = GetFavouriteTurtle();
someAnimalAction(myFavouriteTurtle);

```

This call looks valid, since we're calling a delegate that says it expects an animal, and passing it a turtle, which is an animal.

But if somewhere else in your code you were allowed to say this:

```
someAnimalAction = someCatAction;

```

...then now the code above is trying to invoke a delegate that expects a cat, but passing it a turtle! So if the variable is of type `Action<Animal>`, then only delegates that accept *all* animals (or possible more types) are valid values, because they're the only ones that could handle any invocation that tries to send any old animal down the pipe.

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


# Question
Title: score and high score system for multiple levels
I'm trying to create a scoring system for a game with multiple levels. For this I'm using the binary formatter instead of playerprefs (I read online that playerprefs are not that secure). I have created the system but whats happening is that the score is not resetting to 0 when I load a new level. If in one level the score was 10 and I start some other level, the score in this level starts from 10 instead of 0. This is the code I have so far:

```
public class ScoreIncrease : MonoBehaviour
{
  public Text scoreTxt;
  public int score;

void Start()
{
    LoadScore();
}

void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        Save();
    }
}

public void Save()
{
    score++;
    scoreTxt.text = "Score" + score;
    BinaryFormatter bf = new BinaryFormatter();
    FileStream file = File.Open(Application.persistentDataPath + "/scoreContainer.dat", FileMode.Create);

    ScoreContainer scoreContainer = new ScoreContainer();
    scoreContainer.score = score;
    bf.Serialize(file, scoreContainer);
    file.Close();
}

public void LoadScore()
{
    if(File.Exists(Application.persistentDataPath + "/scoreContainer.dat"))
    {
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Open(Application.persistentDataPath + "/scoreContainer.dat", FileMode.Open);
        ScoreContainer scoreContainer = (ScoreContainer)bf.Deserialize(file);
        file.Close();
        score = scoreContainer.score;
        scoreTxt.text = "Score" + score;
    }
  }
}

[Serializable]
public class ScoreContainer
  {
    public int score;
  }

```

How can I change this so that each level has a separate highscore and all levels have a start score of 0?

# Answer
> 1 votes
You could have a separate file for each level and put the level number into the filename. For example, if your game has 200 levels, name the files "scoreContainer0.dat" to "scoreContainer199.dat".

When there is no score entry for a level yet, then that file won't exist yet. You can handle that case in LoadScore by setting score to 0 in that case.

```
string filename = Application.persistentDataPath + "/scoreContainer" + level + ".dat";
if(File.Exists(filename))
{
    BinaryFormatter bf = new BinaryFormatter();
    FileStream file = File.Open(filename, FileMode.Open);
    ScoreContainer scoreContainer = (ScoreContainer)bf.Deserialize(file);
    file.Close();
    score = scoreContainer.score;
    scoreTxt.text = "Score" + score;
} else {
    score = 0;
    scoreTxt.text = "Not played yet";
}

```

However, a cleaner solution might be to store the scores for all levels in one file. In that case I would use a C# integer array with each entry representing a score and the index being the level, or a `Dictionary<int, int>` with the first integer being the level number and the second integer being the score (the value-type of the dictionary might later receive an upgrade to a structure which contains more information about the state of the level). Either data type can be handled by the BinaryFormatter.

But this will require some more considerations regarding how you access the score values for levels in the rest of your code.

---
Tags: unity, scoring
---


# Question
Title: An object twice as close appears twice as big?
So I was thinking about creating a 2D game where you can also move along the Z-axis, by changing in which layer you are. Depending on the depth I want to scale my 2D sprites.

Once, someone had shown me a demo in which he had a lot of 2d sprites, and by scrolling he could change the depth of the camera. So when zooming in, the objects would come closer to the player, and appear bigger. Then I wondered, how much bigger should an object be when it gets 1 unit closer. How would you calculate that? So the guy told me: There is one basic rule I am using: "objects twice as close, appear twice as big."

Now, by testing it myself, I know that rule doesn't apply in the real world ;) But is there some constant that is used in real world calculations for perspective or something? Or a formula?

I know this might not be the best place to ask such a question, but since this is the only site I use for game-related questions, and my context is a game, I thought I'd give it a try. Also, I am kind of expecting that there is this person here that knows everything about 3D perspectives and matrices or something, since it might relate to 3D games ;)

tl;dr:

"an object twice as close, appears twice as big" That is not true in the real world. But which constant or formula is correct?

# Answer
> 20 votes
Generally it is true, depending on your view point and in which direction it has moved, as well as the viewing angle.

Note how in the first camera view, as the Red block is perpendicular to the camera view, the object seems to be twice as large in a perfect 1:2 ratio (Note the arrow pointing that it hits the edge of the view after being moved twice as close)

The second is the same size block rotated at 45 degrees. As it is rotated, the bottom edge is no longer at the same distance from the camera as the top edge, so it does not SEEM correctly scale to a 1:2 ratio but it in actual fact is twice as large (as it is at the same angle on the further away blue block as it is in the close blue block.)

In conclusion this actually means your friend was correct and a 1:1 ratio *("objects twice as close, appear twice as big.")* for your objects is a good choice.

# Answer
> 9 votes
An object twice as close does appear twice as big. It is a consequence of Thales's Theorem and it is true in the real world.

One could argue that Thales's Theorem is the core mathematical tool behind perspective projection and what's known in the graphics pipeline (OpenGL or DirectX) as **perspective division**. It a theorem you should definitely know, and learn to recognise when it can be used.

# Answer
> 7 votes
Actually that's pretty much true (if you move an object twice as far away it looks half as big) but it obscures how the visual size of objects should change as the viewers moves. Specifically, objects appear to get bigger faster the closer they are. That's because the viewer covers half the distance a lot faster when the object is close, compared to when the object is further away. Or to put it another way, while the viewer's speed is constant, the value of "half the distance" changes as the distance to the object changes.

# Answer
> 2 votes
Since you're not actually working in 3D space, we can assume the sprites never rotate (rotation can be simulated with skewing, etc.) This simple constraint makes it pretty easy to get somewhat accurate numbers on what the size should be depending on distance from the camera.

First, you need to understand how 3D objects are rendered. Even though a camera converges to single point, there is an invisible plane that acts as a screen on which to draw the objects. The only thing you need to know about the screen is how far away it is from the camera.

Here is a diagram of how an object is rendered to a camera at two different distances.

As you would expect, the height of the object is dependent on the the distance from the camera. BUT since rending occurs on the near culling plane, we must calculate the height of the sprite at that point.

Some basic trig calculations will lead you to the following formula:

```
f(d, v) = v/(v+d)
* Where f is the size ratio to the original sprite aka size factor
    and v is the distance to the near clipping plane (trial and error value)
    and d is the distance from the near clipping plane to the object

```

### EXAMPLE:

```
Assuming you have a sprite that is 2.5x1.8 units in size and 10 units away
   from the camera, and that the near clipping plane is 5 units from the camera.

sizeFactor = 5/(5+10) = 0.3

renderHeight = actualHeight * sizeFactor = 1.8 * 0.3 = 0.54
renderWidth  = actualWidth * sizeFactor = 2.5 * 0.3 = 0.75

```

I would suggest starting with `v=5` and then adjust from there based on how it looks. I may throw a fiddle together that allows you to see the changes in realtime.

### TL;DR

```
The change in height or width should be multiplied by the following factor:

sizeFactor = v/(v+d)

Where v = Some number greater than 0 that never changes (try 1 thru 5)
  and d = the distance from the camera

So an object that is 2.5 units tall would be rendered at 2.5*sizeFactor units tall.

```

---

**EDIT:** When you say move along the z-axis I'm assuming you will want a perspective view (like most 3D games; shooters, etc.) The math to calculate object size based on distance will also depend on location in the frame, similar to peripheral vision. Instead, I would try it with my math which is an orthographic view (think Mario, Angry Birds, Super Smash Bros, etc.). I don't know the look and feel you are trying to achieve, but as long as it seems real then the players will never know!

DEMO!

# Answer
> 1 votes
You have to define "twice as big". A line will be twice as long, or tall, at half the distance, but simple mathematics tells us that the surface area of a rectangle, for example, is the height multiplied by the width. The result is that any object with both length and height will be four times as big at half the distance. Binoculars with 8x augmentation will show objects other than lines to appear 64 times bigger.

# Answer
> 0 votes
This wasn't covered and I thought this might be beneficial: It should be noted when you half the distance, doubling the size in both X and Y dimensions will *quadruple* the total area of the sprite. This is because:

```
Area = X * Y

```

After Zooming in:

```
NewArea = (x*2) * (y*2)

```

This may give you the impression that the zooming effect is happening quickly or is too intense. You can adjust the factor by changing 2 in the above formula to a float value like 1.5 or 1.33 instead.

Alternatively, what I've done is store camera depth (distance) to your tiles in a byte value along with camera translation (X and Y) then calculate projected tile size thusly:

```
XTileSize = (255 / CameraZ) * DefaultTileWidth
YTileSize = (255 / CameraZ) * DefaultTileHeight

```

Note that `CameraZ` has to be strictly between 1-255, and that restriction may be a benefit or a bane to you in the future.

---
Tags: perspective, objects
---


# Question
Title: Controlling Unity 3D cube with remote gyroscope
This probably will go into conceptual things as well, but what I would like to do is take a Raspberry Pi (with a Sense Hat), transmit the gyro values to Unity, and effectively have a 1-1 realistic representation of orientation changes.

I have no problem transmitting values from the Pi to Unity (though learning about hidden firewall rules was fun), however I am lacking some understanding of how to transform raw gyro values to something representative in Unity.

I have not calibrated the Sense hat recently, but know that is something that should be done.

For example, I am transmitting the pitch/roll/yaw values from the Pi (resting normally, these are about: `100.30272132022793, 351.3885231076573 354.9306950697191`).

I have a cube gameobject that I've flattened out and set to the origin.

My question is basically, what is the best way to translate raw values from some anonymous object to the Unity coordinate system, and have it rotate appropriately? I don't necessarily want its position to change, just rotation.

---

Screenshot for reference. Raspberry Pi sending gyro data is on the left, Unity is on the right. Tabletop (flattened cube) is what I'd like to rotate to simulate a ball balancer.

# Answer
> 1 votes
I find the documentation a little under-defined, in terms of how to interpret the numbers coming in from the various methods.

From this diagram it *looks* like you might be able to set...

```
Dictionary<string, float> orientation = ReadOrientationDegrees();

transform.localEulerAngles = new Vector3(-orientation["pitch"],
                                         orientation["yaw"],
                                         -orientation["roll"]);

```

Here I've negated two of the axes, based on the direction of the arrows in the diagram above, which are opposite the direction of positive rotation in Unity. But it's possible the diagram is not indicating the sign, and the arrow directions are just incidental.

**Edit: apparently that is the case. Ignore the minus signs**

Test this out, and if it's not behaving as expected, update your question with specific test cases, eg..

* When I orient the sensor like this \[insert photo\]
* The orientation I read is: (yaw: ####, pitch: ####, roll: ####)
* I transform that to the Unity Euler angles (x: ####, y: ####, z: ####)
* And the object looks like this in scene \[insert screenshot\]
* But I expect it to look like this \[insert screenshot\]

With a good sampling of such test cases, we should be able to identify where the mismatch arises.

---
Tags: unity, rotation, gyroscope
---


# Question
Title: Making an RTS game- how to handle player-created units interacting with each other
I'm making an RTS game in Unity with C#. However, the interaction I'm going to have with player-created units interacting with other player-created units is what has me stumped. The player and his opponent can purchase units when they have the resources, and it instantiates them in the game. The main thing is checking whether an opponent's unit is within range to attack. Obviously, you can't have every unit asking every other unit what its position is, or it would get exponentially more CPU-consuming the more units are built, right? I'm trying to figure out how I'm going to go about this.

I figured I could have every unit report its position to a sort of master 'tracker', and then every unit could ask the tracker if any opponents' units have a position within X of their own. How I would actually implement this in Unity, though, I'm not sure about.

Moreover, I'm trying to get my head around Instantiated objects. If every unit is telling its position to the master 'tracker', what does it call itself? And let's say a unit asks the tracker if an enemy is in range and one is, what does the tracker tell it so it can locate the right GameObject and attack it? Sorry if I'm talking about it all wrong, I'm sure there's a simple methodology that exists on how to do it, but I can't think of any. Thank you.

# Answer
Using a manager class is absolutely how I would go about implementing this. As you instantiate each object your manager class can add that object to a list. As for CPU usage, you could optimize as comments suggest but unless you have literally millions of units per side something like asking for a position on a modern computer should be absolutely possible even with the quadratic scaling, an easy fix would be not asking for this every frame - only asking when a unit is about to attack etc.

---

Under the hood unity will keep a separate reference to each instantiated game object, so by passing an object's `this` to your manager class will absolutely allow the manager to use the game object, or select the correct object out of a list.

```
// Manager class
void func(Unit unit){
    unit.member; // you can do this!
    unit.function(); // and this
    unit == unitList[0]; // this too!
}

```

Then in your unit class you can just do

```
unitManager.func(this);
or
unitManager.func(gameObject.getComponent<Unit>());

```

---

I would implement this so your manager class returns a list of units within a range of a position, something like this

```
// manager class
List<Unit> GetUnitsInRange(Vector3 position, float range){
    List<Unit> unitsInRange = new List<Unit>(); // list that will be returned
    float rangeSquared = range*range // this will allow us to avoid an expensive sqrt() later
    foreach(Unit unit in unitList){
        float distanceSquared = (unit.transform.position - position).sqrMagnitude;
        if(distanceSquared <= rangeSquared){
            unitsInRange.Add(unit);
        }
    }
    return unitsInRange; // return this to your unit
}

```

You could then in your `Unit` class, simply ask your manager class for the units in range like

```
// in Unit class
List<Unit> unitsInMyRange = unitManager.GetUnitsInRange(transform.position, range);

```

So long as you don't have hundreds of thousands of units, or you aren't calling this each frame, this should absolutely be something your machine can handle - it's only one for loop per unit, however if you're having performance issues you can have different `unitList`s per segment of your map, or look into the way the physics system optimizes its calculations as suggested in the comments.

---

As for if your unit then wants to attack one of the enemies in range, returned by this function, you can simply treat everything in the list as a reference to a gameObject. So something like

```
// in Unit
int randomInt =  Random.Range(0,unitsInMyRange.Count-1); // -1 so don't index outside list
Attack(unitsInMyRange[randomInt]);

```

or

```
FireAt(unitsInMyRange[randomInt].transform.position);

```

Would be completely valid
> 0 votes

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