# Question
Title: Why do I get java.lang.OutOfMemoryError in android studio after adding a 2nd activity?
After I decided to create an activity to show the results of the game with try again button. Every 3rd try the game will stop with this error.

> java.lang.OutOfMemoryError: Failed to allocate a 3819212 byte allocation with 610080 free bytes and 595KB until OOM

What am I doing wrong here?

My try again button code.

```
 public void tryAgain(View view) {
    startActivity(new Intent(getApplicationContext(), StartActivity.class));
}

```

How I call my result activity

```
Intent intent = new Intent(Constants.CURRENT_CONTEXT.getApplicationContext(), ResultActivity.class);
            intent.putExtra("SCORE", obstacleManager.getScore());
            Constants.CURRENT_CONTEXT.startActivity(intent);

```

# Answer
> 0 votes
Found a solution on this 1. calling finish() before the starting new intents in every activity solve this issues.

E.g

```
finish() ;
Intent intent = new Intent(Constants.CURRENT_CONTEXT.getApplicationContext(), ResultActivity.class);
        intent.putExtra("SCORE", obstacleManager.getScore());
        Constants.CURRENT_CONTEXT.startActivity(intent);

```

---
Tags: android, android-studio
---


# Question
Title: Is there a way to set texture wrap mode as repeat in SDL 2?
In `SDL2`, I would like to render a texture on the screen, but with destination rectangle greater than texture size. Instead of stretching the texture, I would like the texture to be repeated as many time as possible.

Here is code I use (pseudo code)

```
SDL_Rect src = { x = 0, y = 0, w = texture.Width, h = texture.Height };
SDL_Rect dst = { x = 0, y = 0, w = texture.Width * 3, h = texture.Height * 3 };

SDL_RenderCopy(renderer, texture, src, dst);

```

# Answer
> 2 votes
No.

Sadly, this isn't something that SDL can do, which I find slightly annoying as it seems such a simple feature.

So, you'll need to implement your own loop that renders the whole texture a bunch of times and possibly crops the border textures by clamping the source rectangle.

---
Tags: textures, rendering, sdl2
---


title: Tetris Copyright Issues?

text:
# Question
Title: Tetris Copyright Issues?
I am making a Tetris clone with a new idea but I won't use the Tetris or Tetriminos name in the game I will refer to them as Tetrominos. Will there be copyright issues if I release this game? Does the Tetris company own the right to produce "Tetris" games?

# Answer
> 6 votes
"Tetris" is a trademark of The Tetris Company, LLC. Game mechanics are not patentable or covered by copyright, but the name trademarks "Tetris" and "tetrimino" (note the spelling) are theirs.

However, the company have been annoyingly successful at bullying simple clones of their game out of marketplaces using the legal system anyway, even though the legal standing of their claims to ownership of the exact playfield size and shape of pieces is highly questionable.

---
Tags: legal, copyright, tetris
---


title: Changing Force of my fall after a jump

text:
# Question
Title: Changing Force of my fall after a jump
I'm trying to change the speed of the jump. I noticed if I jump twice the fall speed force gets implemented. Otherwise it is unchanged. If I try to change my onGround to be else false it remains false. Any Ideas.?

```
public class PMRigidBody : MonoBehaviour {
    public Rigidbody rb;
    private ConstantForce cf;
    public float fallSpeed = -10;
    private bool onGround = false;
    private int jumpHeight = 7;

    void Start (){
        // get the components
        rb = GetComponent<Rigidbody>();
        cf = GetComponent<ConstantForce>();
    }

    void Update()
    {
        float dist = 1f;
        Vector3 dir = new  Vector3(0, -1, 0);

        Debug.DrawRay(transform.position, dir * dist, Color.green);

        if (Physics.Raycast(transform.position, dir, dist))
        {
            onGround = true;
        }
        //else
        //{
        //    onGround = false;
        //}

        if (onGround)
        {
            cf.force = Vector3.zero;
            if (Input.GetButtonDown("Jump"))
            {

                onGround = false;
                rb.velocity = new Vector3(0, jumpHeight, 0);
                rb.MovePosition(transform.position + transform.up * Time.deltaTime * 10);

                cf.force = new Vector3(0, fallSpeed, 0);
            }
        }
    }
}

```

# Answer
> 1 votes
Let's walk through two loops of your code, starting with a player on the ground pressing jump. I'm also going to assume you're running around 60 fps.

**Frame 1 Update**

* We raycast down 1 unit and find the ground. `onGround = true`
* `onGround = true` so we set `cf.Force = 0`
* The "Jump" button was pressed this frame, so:
    + `onGround = false`
    + we set our vertical velocity to 7
    + we move up by `Time.deltaTime * 10` or about 0.166
    + we set `cf.force` to `fallspeed`

**Frame 2 Physics Step**

* Our vertical velocity moves us up roughly `Time.fixedDeltaTime * 7` or about 0.14 (neglecting gravity and downward force for the moment, but they'll only reinforce the effect we're about to see...)

We're now about 0.3 units higher than we started.

**Frame 2 Update**

* We raycast down 1 unit **and still find the ground** because we're only 0.3 units away from it! `onGround = true`
* `onGround = true` so we set `cf.force = 0`
* "Jump" is not pressed this frame, so we don't try to set `cf.force` back to `fallspeed`.

So: what's happening is your onGround test is too inclusive. It's counting you as still being on the ground the frame after you jump, and resetting your force to zero as a consequence. I'd recommend tightening the onGround check, or disabling it while you have an upward velocity (since I can't very well land on the ground if I'm moving away from it).

# Answer
> 0 votes
Looks like you're using public variables that show up in the inspector.

**Any variables written in the inspector override your code.** Check the inspector variables first, if they're changed and your code is changed, I'm not sure how to help you. Good luck! :)

---
Tags: unity
---


# Question
Title: How do I change quaternion rotation to use the local camera axis rather than the world axis in DirectX 11?
I'm currently trying to rotate the camera around its local axis based on keyboard/mouse input and the code I currently have uses DirectXMath and works nicely, however it is using the world axis to rotate around rather than the cameras local axis. Because of this, some of the rotations are not as expected and causes issues as the camera rotates. For example, when we tilt our camera, the Y axis will change and we will want to rotate around another axis to get our expected results.

What am I doing wrong in the code or what do I need to change in order to rotate around its local axis?

vector.x, vector.y, vector.z (The vector to rotate around, i.e. (1.0f, 0.0f, 0.0f))

```
//define our camera matrix
XMFLOAT4X4 cameraMatrix;

//position, lookat, up values for the camera
XMFLOAT3 position;
XMFLOAT3 up;
XMFLOAT3 lookat;

void Camera::rotate(XMFLOAT3 vector, float theta) {
    XMStoreFloat4x4(&cameraMatrix, XMMatrixIdentity());

//set our view quaternion to our current camera's lookat position
XMVECTOR viewQuaternion = XMQuaternionIdentity();
viewQuaternion = XMVectorSet(lookat.x, lookat.y, lookat.z, 0.0f);

//set the rotation vector based on our parameter, i.e (1.0f, 0.0f, 0.0f)
//to rotate around the x axis
XMVECTOR rotationVector = XMVectorSet(vector.x, vector.y, vector.z, 0.0f);
//create a rotation quaternion to rotate around our vector, with a specified angle, theta
XMVECTOR rotationQuaternion = XMVectorSet(
XMVectorGetX(rotationVector) * sin(theta / 2),
XMVectorGetY(rotationVector) * sin(theta / 2),
XMVectorGetZ(rotationVector) * sin(theta / 2),
cos(theta / 2));

//get our rotation quaternion inverse
XMVECTOR rotationInverse = XMQuaternionInverse(rotationQuaternion);

//new view quaternion = [ newView = ROTATION * VIEW * INVERSE ROTATION ]
//multiply our rotation quaternion with our view quaternion
XMVECTOR newViewQuaternion = XMQuaternionMultiply(rotationQuaternion, viewQuaternion);

//multiply the result of our calculation above with the inverse rotation
//to get our new view values
newViewQuaternion = XMQuaternionMultiply(newViewQuaternion, rotationInverse);

//take the new lookat values from our newViewQuaternion and put them into the camera
lookat = XMFLOAT3(XMVectorGetX(newViewQuaternion), XMVectorGetY(newViewQuaternion), XMVectorGetZ(newViewQuaternion));

//build our camera matrix using XMMatrixLookAtLH
XMStoreFloat4x4(&cameraMatrix, XMMatrixLookAtLH(
    XMVectorSet(position.x, position.y, position.z, 0.0f),
    XMVectorSet(lookat.x, lookat.y, lookat.z, 0.0f),
    XMVectorSet(up.x, up.y, up.z, 0.0f)));
}

```

The view matrix is then set

```
//store our camera's matrix inside the view matrix
XMStoreFloat4x4(&_view, camera->getCameraMatrix() );

```

-

Edit:

I have tried an alternative solution without using quaternions, and it seems I can get the camera to rotate correctly around its own axis, however the camera's lookat values now never change and after I have stopped using the mouse/keyboard, it snaps back to its original position.

```
void Camera::update(float delta) {
    XMStoreFloat4x4(&cameraMatrix, XMMatrixIdentity());

//do we have a rotation?
//this is set as we try to rotate, around a current axis such as
//(1.0f, 0.0f, 0.0f)
if (rotationVector.x != 0.0f || rotationVector.y != 0.0f || rotationVector.z != 0.0f) {

    //yes, we have an axis to rotate around

//create our axis vector to rotate around
    XMVECTOR axisVector = XMVectorSet(rotationVector.x, rotationVector.y, rotationVector.z, 0.0f);

//create our rotation matrix using XMMatrixRotationAxis, and rotate around this axis with a specified angle theta
    XMMATRIX rotationMatrix = XMMatrixRotationAxis(axisVector, 2.0 * delta);

//create our camera's view matrix
    XMMATRIX viewMatrix = XMMatrixLookAtLH(
        XMVectorSet(position.x, position.y, position.z, 0.0f),
        XMVectorSet(lookat.x, lookat.y, lookat.z, 0.0f),
        XMVectorSet(up.x, up.y, up.z, 0.0f));

//multiply our camera's view matrix by the rotation matrix
//make sure the rotation is on the right to ensure local axis rotation
    XMMATRIX finalCameraMatrix = viewMatrix * rotationMatrix;

/* this piece of code allows the camera to correctly rotate and it doesn't
snap back to its original position, as the lookat coordinates are being set
each time. However, this will make the camera rotate around the world axis
rather than the local axis. Which brings us to the same problem we had
with the quaternion rotation */
    //XMVECTOR look = XMVectorSet(lookat.x, lookat.y, lookat.z, 0.0);

    //XMVECTOR finalLook = XMVector3Transform(look, rotationMatrix);

    //lookat.x = XMVectorGetX(finalLook);
    //lookat.y = XMVectorGetY(finalLook);
    //lookat.z = XMVectorGetZ(finalLook);

//finally store the finalCameraMatrix into our camera matrix
    XMStoreFloat4x4(&cameraMatrix, finalCameraMatrix);
} else {

    //no, there is no rotation, don't apply the roation matrix

//no rotation, don't apply the rotation matrix
    XMStoreFloat4x4(&cameraMatrix, XMMatrixLookAtLH(
        XMVectorSet(position.x, position.y, position.z, 0.0f),
        XMVectorSet(lookat.x, lookat.y, lookat.z, 0.0f),
        XMVectorSet(up.x, up.y, up.z, 0.0f)));
}

```

An example can be seen here: https://i.gyazo.com/f83204389551eff427446e06624b2cf9.mp4

I think I am missing setting the actual lookat value to the new lookat value, but I'm not sure how to calculate the new value, or extract it from the new view matrix (which I have already tried)

# Answer
Looking at the code, I have a bit of trouble understanding exactly the way it works, but the way I would go about implementing a camera rotation is simply using rotation matrices to rotate the camera local axes. Note: I haven't worked with DirectXMath too much, so in the next code I will use imaginary math functions that I am sure you can then replace with DirectXMath equivalents.

So the way I would go about it is to first have a camera class, something along the lines of:

```
class Camera
{
 public:

    // Constructors, public methods etc
    void Update();

 private:

    Vector3 _position; // Camera position
    Vector3 _right;    // Camera local right vector
    Vector3 _up;       // Camera local up vector
    Vector3 _look;     // Camera local look vector

    Matrix4x4 _viewMatrix;
}

```

Of course this is just a simple skeleton of the class. You would probably also want to have other pieces of info such as projection matrix, viewport etc. But these are the members that I consider important for this example.

I will also assume in this example that the input handling will take place in the Update method. So let's see how you could implement the camera rotation you desire inside the Update method. Note: There are many different way in which you could rotate a camera, but I will assume that you would like a FPS rotation style. Even if a new rotation style is required, I think the following example will help.

```
void Camera::Update()
{
   // Calculate mouse deltas... Not shown here, but can easily be done
   // by keeping track of the previous mouse position and subtracting
   // that from the current position. I assume you are already doing
   // that so I will just be using the mouse delta vector as if it was
   // already initialized. deltaX holds the mouse movement along the X
   // axis and deltaY along the Y axis in screen space.

   // For a FPS camera, deltaX rotates the camera around the GLOBAL Y
   // axis. This is as if you are rotating your entire body around the
   // world UP vector. deltaY rotates around the camera's local X axis.
   // This can be associated with tilting your head up and down.
   float yRotation = deltaX; // * sensitivityValue (optional);
   float xRotation = deltaY; // * sensitivityValye (optional);

   // Build a rotation matrix which rotates the camera around GLOBAL Y
   Matrix4x4 yAxisRotMtx = RotationAxis(yRotation, Vector3(0.0f, 1.0f, 0.0f);

   // Rotating the camera around the Y axis can be accomplished by
   // rotating the camera local axes using the rotation matrix we've just
   // built.
   _right = yAxisRotMtx.MultiplyVector(_right);
   _up = yAxisRotMtx.MultiplyVector(_up);
   _look = yAxisRotMtx.MultiplyVector(_look);

   // At this point we have rotated our body around in the world based
   // on the horizontal mouse movement. The next step is to tilt our
   // head based on the vertical mouse movement. In order to do this, we
   // need to construct a rotation matrix which rotates the camera local
   // vectors around the camera's local right vector.
   // NOTE: We only need to rotate the camera look and up vectors.
   //       Rotating the right vector around itself will have no effect.
   Matrix4x4 camRightRotMtx = RotationAxis(xRotation, _right);
   _up = camRightRotMtx.MultiplyVector(_up);
   _look = camRightRotMtx.MultiplyVector(_look);

   // At this point we have achieved the desired rotation effect and we
   // are ready to rebuild our view matrix. The view matrix needs to be
   // rebuilt because we have modified the camera local axes and this
   // is what the view matrix essentially contains (aside from positional
   // information). There are 2 ways in which we could calculate the view
   // matrix: one which is a bit slower, and the other one which is
   // probably a bit trickier to understand but it is faster. We will
   // pretend that a MACRO will be used which allows you
   // to switch between the 2 so we will implement both of them.
   #if defined(USE_SLOW_VIEWMTX_CALCULATION)
   // Slow method. Use the camera local vectors and its position to
   // calculate a world matrix which essentially describes the camera's
   // position and orientation in the 3D world. Inverting this matrix
   // will give you the view matrix. The inversion is needed because
   // the view matrix is supposed to transform points from world space
   // to camera local space.
   Matrix4x4 camWorldMtx;
   camWorldMtx.MakeIdentity();

   // Each row inside the matrix holds a camera local axis. The fourth
   // row holds the camera position.
   camWorldMtx._00 = _right.x; camWorldMtx._01 = _right.y; camWorldMtx.02 = _right.z;
   camWorldMtx._10 = _up.x; camWorldMtx._11 = _up.y; camWorldMtx.12 = _up.z;
   camWorldMtx._20 = _look.x; camWorldMtx._21 = _look.y; camWorldMtx.22 = _look.z;
   camWorldMtx._30 = _position.x; camWorldMtx._31 = _position.y; camWorldMtx.32 = _position.z;

   // The inverse of the matrix we calculated is the view matrix
   _viewMatrix = camWorldMtx.GetInverse();
   #else
   // Faster method. Requires a bit of understanding as to what the view
   // matrix is trying to achieve and that discussion can get a bit
   // lengthy, but the idea is that if we store the camera local vectors
   // in the columns (not rows as was the case in the first calculation
   // method) we are essentially creating a matrix which rotates points
   // out of world space and into camera local space. Rotation is half
   // the journey. We must also calculate the fourth row of the matrix.
   // This is not a simple case of just negating the camera position
   // coords because when a vertex is transformed by the view matrix, by
   // the time it reaches the fourth row, the first 3 rows have already
   // affected the vertex (brought it in camera local space). So we need
   // to ransform the position of the camera in the same space before
   // subtracting it from the vertex. This is done by transforming the
   // camera position via the 3x3 portion of the view matrix, negating
   // the result and storing it. Sorry if this creates more confusion
   // than clarity :)
   _viewMatrix._00 = _right.x;
   _viewMatrix._10 = _right.y;
   _viewMatrix._20 = _right.z;

   _viewMatrix._01 = _up.x;
   _viewMatrix._11 = _up.y;
   _viewMatrix._21 = _up.z;

   _viewMatrix._02 = _look.x;
   _viewMatrix._12 = _look.y;
   _viewMatrix._22 = _look.z;

   // Now position. Performing the dot product for each position
   // component with the corresponding camera axis has the same
   // effect as multiplying the position with the view matrix. We
   // negate the result because we want to bring points relative to
   // the camera's origin (i.e. cancel out any positional information).
   _viewMatrix._30 = -Vector3.Dot(_position, _right);
   _viewMatrix._31 = -Vector3.Dot(_position, _up);
   _viewMatrix._32 = -Vector3.Dot(_position, _look);
   #endif
}

```

There is an optimization which can be performed. For example, the view matrix will most likely be needed only when finally rendering the scene. Camera manipulation happens before that. So instead of calculating the camera view matrix inside the Update method, you could just use a \_viewMtxIsDirty flag to mark the view matrix as dirty. Then, when it comes time to render the scene, you might call a function from your camera class, something like GetViewMatrix(). This function could be implemented as such:

```
Matrix4x4 Camera::GetViewMatrix()
{
    if(_viewMtxIsDirty) { RebuildViewMatrix(); _viewMtxIsDirty = false; }
    return _viewMtxIsDirty;
}

```

The RebuildViewMatrix() method would implement one of the discussed calculation methods.

I saw you were trying to use quaternions to achieve rotation and I believe it can work, but to be honest, quaternions can get confusing sometimes (at least for me :D ). Using rotation matrices seems much more intuitive to me. That is why I chose to go down this road. Hope this helps.
> 1 votes

---
Tags: c++, camera, rotation, directx11, quaternion
---


# Question
Title: Why doesn't my projectile move in my code?
My projectile currently has a create event with the following code:

```
//move towards mouse
move_towards_point(mouse_x,mouse_y,30);

```

My main character has a glob left button event with the following code:

```
instance_create(0,0,main_shuriken);

```

For the output, the shuriken appears at the top left of the screen, and does not move. I've noticed that if I tick off physics world in the "rooms" category, my shuriken seems to work fine.

Why doesn't my projectile move with `move_towards_point` and `create_instance` commands?

# Answer
> 0 votes
First things first. You want your `main_shuriken` instance to appear at your main character's position, not the top-left corner of the screen. Just change your *Global Left Button* Event as follows:

```
instance_create(x,y,main_shuriken);

```

This way the `main_shuriken` will be created at your main character's position (formally `(x,y)` of the instance executing such code) instead of the room origin (`(0,0)`, which is an *absolute* position, and not *relative*).

Your shuriken moves as expected if you tick physics world off in your room for a simple reason. The function `move_towards_point()` sets the current instance `direction` variable according to the direction from the instance position (its `x` and `y`) and the `x` and `y` coordinates given as arguments; also, it sets the instance `speed` variable to the value you give as third argument. The physics functions interfere with these built-in variables, which means that if an instance is ticked as "uses physics", even if you set `speed` and `direction` to some values, they won't work because the Box2D physics engine uses separate variables to deal with motion and physics. As the official documentation states:

> The physics system replaces many of the normal instance functions... for example, rather than set a speed and a direction for an instance, if it has been declared as being a fully simulated physical body, you would use a force or impulse to get it to move around in the game world, or if it is not physics enabled you will need to set the x an y positions yourself. This takes a bit of getting used to, so experiment with the physics functions and get to know how everything works before trying to integrate them into your project.

When you turn off physics world, built-in variables are responsible for an instance motion.

---
Tags: game-maker
---


# Question
Title: What are the practical differences between discrete and continuous simulations?
I've done some research regarding how to simulate a game world, and it seems that I need to decide whether I want to write a continuous or a discrete simulation.

From my understanding, in a continuous simulation, I simulate each entity based on the time passed from the last calculation. For example, if I have a moving entity which has the speed of *N units per second* and one second has passed since the last calculation, the entity will move *N* units. In a discrete simulation, I calculate "turns", and my entity will have a speed measured in *units per turn*.

From what I understand, discrete simulation is not as granular as a continuous simulation, but is easier to calculate. I'm not sure that I have this right. I'm in the planning stage of a Dwarf Fortress-like roguelike game and I'm not sure which method will be fine for my purposes.

What are the practical differences between *continuous* and *discrete* simulations, in terms of game mechanics and playability? In relation, what are the benefits and disadvantages of each simulation, and do I have any holes in my understanding of the concepts?

# Answer
**(I apologise for the length hereof, but I'd like to clarify a few things to give you solid footing.)**

All digital computer simulations are actually discrete in nature. This includes everything from a non-interactive fluid simulation to an OS with its reactive UI, to a game. Just as the refresh rate of your monitor is a discrete 60 fps, so are the operations run on a processor, also discrete. We don't use analog computers (anymore?). So the very idea of truly "continuous" simulations is debatable at this time. Nevertheless I know that you are trying to draw a distinction between *turn-based* and *real-time*.

Let's focus on *real-time* first. I must pose the question, **real-time at *what level in the code?*** It matters what the core language/platform provides, and what 3rd party engine libraries you are using, because those things totally alter the development landscape. But let's start at the most basic level.

**Loop-based/real-time: Discrete stepping via for/while**

At the foundation of any real-time code is the idea that the program moves screen elements in discrete steps, enough times per second that in the average case it appears like something moving smoothly as in real life. This can be as simple as moving a sprite from left to right, across the screen. If you were to look at the source code of any high level engine like Unity or UE or whatever, you'd find, in native code (C, C++) this fundamental `for` or `while` loop upon which the basic simulation occurs. Unity, for example, wraps this up under the hood, then you write your C# classes/methods which are called by that underlying native loop (UnityEngine). Most modern engines thus hide the loop from you, but you still know your logic is called every frame, even if you never get to see the loop code that does so. If you're using raw C and no libraries, you will on the other hand have to write that loop yourself, usually in `main()`, i.e. the root of your C application, and everything else follows from there.

**Event-based, Automated interpolations etc.**

Here we enter the territory of other sorts of software than games, such as web apps, GUIs and operating systems. Event systems are built for GUIs, and GUIs are highly reactive. Any guesses as to how they are so reactive? That's right - they too are fundamentally loop-based. A GUI system is an extension of the real-time, loop based system described above. That means that operating systems and games share some common heritage! But now there's more than just a loop. Events systems typically consist of some publisher-subscriber mechanism that broadcasts notifications, and a way to provide callbacks on notification receipt. This often (but not always!) ties into the underlying loop. Browser JavaScript and Unity are two platforms exemplifying this association.

Anyway, here's an example: Consider a JavaScript GUI web app that acts on events. Let's say you hit a button to load something. A spinner appears. While the loading proceeds, that spinner keeps moving smoothly onscreen. When the loading completes, the spinner stops. You didn't have to code any of the real meat that makes that spinner spin, or handles the loading and informs the underlying systems of the completion of that load. You just called placed an load spinner in your html, then called something like `json.Load()` in `button.OnClick()`. In the meantime, native code (your browser engine) was running a loop that kept that image animating. But you knew nothing about a loop - you just had a couple of simple functions tying into fabulous event system lying under the hood, whose own functioning relies on a loop-based, real-time system. In regards to the association between loop and event system that I described above, you will find with JavaScript that a load complete event will at the very beginning of the very next frame *after* the load actually completes in native code. This is a textbook case of an event system and loop working in conjunction to provide well-ordered operations.

---

Now that those representations have been made...

---

**Real-time simulations**

Flight Simulator, Wolfenstein, and classic Pong are purely real-time simulations. There is no turn-based element here. They are typically as fine-grained as you can get, often using every one of 60 frames of 16.6ms period each in a second, to perform new logic. Of course, this doesn't mean they *always* do; they can also wait to do certain tasks only periodically, such as AI updates.

**Turn-based simluations**

Angband, Nethack are a good example of a very simple turn-based game. These require *no loop whatsoever in **your** code*. User input comes from the keyboard which is handled by the OS, so you just let the OS notify your application and when a keyboard event occurs, and your functions otherwise know nothing about timing loops, and need not do so.

Battle Chess is a turn based game with real time animation, movement etc. Clearly, a loop is once again the basis for responding to user interaction. In this case it is *also* used for animation, gradual moves between tiles, special effects, etc. (possibly even for sound). But the difference here is that while such a game is fundamentally loop-based, it is preventing you from supplying user input for those periods when a move has just been made and your knight is fighting the enemy bishop: it just controls *when & how* you are allowed to supply input. Otherwise, it operates much like Pong, CoD etc.

World of Warcraft is another interesting example, being (I believe) (semi) turn-based on the server, and real-time on the client. One might also call this *semi turn-based*, although here we are getting into the more complex realm of distributed computing. It's certainly open to debate.

I want to say something more about such a system. We find constructs in many platforms / languages that do interpolations / animations over time, then fire an event on complete. What is crucial to understand here is that this is *still* loop-based under the hood, but from the end-developer's perspective, all you are doing is calling something like `pawn.InterpolateTo(x, y, 5)` to cause the real-time stuff to start happening under the hood, and once it has smoothly moved your pawn to the target location, it fires off a callback that notifies your code that the interpolation has completed 5 seconds later and this then ties back into your own higher level logic. This is crucial to understand: It is event based - but there is still a loop in action at some lower level! It may even be that if this is your own code, that loop is exposed both for step-wise use *and* for specialised interpolation subsystems.

**Conclusion**

You can't get away from using a loop if you want an interactive application, although if you use the right library or platform (Unity, Javascript, Flash or C with SDL frame callbacks all come to mind), then you will not need to write the loop yourself, and that will be a major boon as timing can be a complex issue. Again, most modern engines will call this for you, and you will just supply callback functions to be handled at defined times during each loop step/iteration/tick/frame.

Loop-based / real-time systems are required for any reactive/interactive system. Event-based systems, while often appearing very different to real-time systems, are often fundamentally associate with, if not driven by loops, and co-exist alongside loops in various different forms.

**Your Game**

For a Dwarf Fortress style game, I'd *start* with the following timing mechanism, see Fix your Timestep. Some here may be your code, some like the loop or vsync event mechanism may be 3rd party:

```
bool isRunning = true;
//assume milliseconds for all time* variables
int timeAccumulated = 0;
int timeStep = 1000; //period = 1000ms : frequency = 1fps
while (isRunning) //cpu
{
    tick();
}
//...or don't use such a loop, and instead call tick() on vsync event.

void tick()
{
    timeDelta = SomeMethod(); //may be yours, system's, or library's
    timeAccumulated += timeDelta; //see "Fix your Timestep"

    if (timeAccumulated <= timeStep)
    {
        timeAccumulated -= timeStep;

        turn(); //call all your custom turn logic here
    }
    //inputs must have immediate effect, so are not called in turn()...
    isRunning = CheckKeyPressed("ESCAPE"); //for example
}

```

...So the outer block (`while`) controls actions which must have an immediate response, like queuing up input for use in the next turn, handling loads etc. OTOH the inner block (`if`) only allows this loop iteration to make game logic happen *once* a second has passed since the last turn was enacted.
> 3 votes

---
Tags: game-design, simulations
---


title: Two headphones for two players

text:
# Question
Title: Two headphones for two players
We're looking to create a split screen game using Unity that is highly reliant on audio. We would need each player to have their own headphones and use positional audio to navigate through the map.

Is it possible to output different sound (depend on each player's location) to a set of headphones? If I remember correctly, there may be a limitation in Unity and Windows where only one output device can be used. Is this true or is there some way to go about doing this?

If not, would we just have to resolve to running two instances of the game and using network play?

Thanks!

# Answer
As far as I can tell Unity does not support this. That doesn't mean it can't be done. What you need is a managed wrapper for a native library that allows such fine control.

You could try using NAudio which is just that, it lets you create `IWavePlayers` for multiple audio devices and playback APIs.

Note: NAudio doesn't do 3D audio effects.

*Disclaimer: I have been unable to test it with multiple sound cards, as I don't have an extra one at hand at the moment of posting (not even an USB one).*
> 1 votes

---
Tags: unity, audio, unity-networking
---


title: Spotlight Culling. Plane vs Cone Shape

text:
# Question
Title: Spotlight Culling. Plane vs Cone Shape
I am building forward + engine based off of partially http://www.humus.name/Articles/PracticalClusteredShading.pdf

If you go to page 36 on the pdf and "spot light culling section" they mention "Do plane-cone test and shrink".

However unlike pseudo code they provided for sphere shape culling, it has no more information.

Thus I am stuck drifting internet trying to find methods to achieve this.

Please guide me to the right direction.

# Answer
Screenshot from : Real-Time Collision Detection, Volume 1

The collision check is as simple as checking whether vertex of cone and the far end of the cone are lying two difference sides of the plane.

However in doing so you will end up with either green or purple point depending on the order of your cross product, thus it is important that you check both green and purple to see if the cone is intersection the plane.
> 1 votes

---
Tags: mathematics, lighting, culling
---


# Question
Title: Jerky motion when standing on hovering object
In a level of a 3D FPS I'm making, I have several floating pillars that move up and down (the x and z positions are always the same). When the player stands on one of the pillars, the motion is incredibly jerky going up, but smooth going down. I think the player is sinking into the pillar slightly and then catching up.

I've tried different colliders, all sorts of combinations with rigidbodys and character controllers. I've tried setting the pillar as a parent of the character and then having the player hover slightly. I've just hit a brick wall and would appreciate an outside perspective. Here's my code just in case the issue is in there.

Player movement

```
 public float walkSpeed = 6.0F;
 public float runSpeed = 10.0F;
 public float jumpSpeed = 8.0F;
 public float gravity = 20.0F;
 private Vector3 moveDirection = Vector3.zero;

 void FixedUpdate(){
     CharacterController controller = GetComponent<CharacterController>();

         moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
         moveDirection = transform.TransformDirection(moveDirection);
         moveDirection *= walkSpeed;
         if (Input.GetButtonDown("Jump")){
             moveDirection.y = jumpSpeed;
         }

         if (Input.GetButton("Sprint")){
             walkSpeed = runSpeed;
         }
         else{
             walkSpeed = 6.0F;
         }

     moveDirection.y -= gravity * Time.deltaTime;
     controller.Move(moveDirection * Time.deltaTime);
 }

 void OnCollisionStay(Collision hit) {
     if (hit.gameObject.tag == "Column") {
         transform.parent = hit.transform;
     } else {
         transform.parent = null;
     }
 }

```

Pillar movement

```
 float height;
 float speed;
 Vector3 start;
 Vector3 end;
 Vector3 startOrEnd;
 void Start(){
     speed = 0.01F;
     start = new Vector3(gameObject.transform.position.x, gameObject.transform.position.y, gameObject.transform.position.z);
 }

 void Update () {
     motionControl(speed);
 }

 float randomNumber(float min, float max){
     float number = Random.Range(min, max);
     return number;
 }

 void motionControl(float speed){
     if (gameObject.transform.position == start) {
         end = new Vector3(gameObject.transform.position.x, randomNumber(0, 10), gameObject.transform.position.z);
         startOrEnd = end;
     }else if (gameObject.transform.position == end) {
         startOrEnd = start;
     }
     gameObject.transform.position = Vector3.MoveTowards(gameObject.transform.position, startOrEnd, speed);
 }

```

# Answer
> 1 votes
My suggestion is to have a variable in your character class that holds a reference to whatever object the character is on and then have all of the characters movement be relative to that object as long as he is on that surface.

# Answer
> 0 votes
From the code it looks like you're probably right: The player is sinking into the collider and then bouncing back up again. It looks like this may be because you're moving the player too far down when you set you're `moveDirection.y`.

Instead, I'd use RayCasting to determine whether or not to move the player down (and by how far). Something like this should do it (I'm not in a position to test at the moment)

```
float distance = gravity * Time.deltaTime;
RaycastHit hit;
if (Physics.Raycast(new Vector3(transform.position.x, controller.bounds.min.y, transform.position.z), -Vector3.up, out hit, distance)) {
     distance = hit.distance;
}
moveDirection.y -= distance;

```

---
Tags: unity, c#, collision-detection, physics, 3d
---


# Question
Title: Random numbers inside instance (Game Maker)
I've recently run into a weird problem. When I create instances through with(instance\_create){ ... }, I can always randomize their variables individually (inside {...}). However, when I try running

```
randomize()
random(...)

```

inside their object (in one of the events), they are all synced. Please tell me this isn't a major Game Maker flaw and, most importantly, how do I fix this. Thank you!

# Answer
There seems to be little information on the subject... this is what I gather:

* Game Maker provides a single global random
* Game Maker remembers the set random seed
* `randomize` will set a "random" seed, is intended to be called only once

From the above it is very likely that calling `randomize` generates a seed based on the game or the machine, and calling it multiple times is indempotent.

---

To get over that problem you can use `random_set_seed(val)`, but from where do you get the seed? If you try using random, that random will generate a value using the default seed, therfore it will always generate the same value.

Instead I suggest to use `current_time` for your seed. Under the assumption that calls to `random_set_seed(current_time())` don't happen close enough in time, this will make sure it yields a different seed.

You can make it a bit more interesting if you wrap that in a function, and keep track of the number of times it has been called. Combining that with number with `current_time` would make sure that it sets a different seed every time it gets called even if the calls happen consecutively.

Note: using `current_time` may make your game suceptible to tampering by changing the system clock.

---

You could roll your own number generator, start by reading about Linear congruential generators
> 0 votes

---
Tags: software-engineering, game-maker, random
---


# Question
Title: How to build a C# library for Unity as a pure Visual Studio project
The aim is to build a relatively simple (2D) game in Unity with most of the game logic in a non-visual AI. The AI needs a lot of testing and debugging independently of any visuals (which is best done using VS tools), and the API connecting them is one class and a few methods/properties. \[A future version might not even use Unity.\]

So the question is how to set up a VS solution file to build the AI for testing and debugging while remaining compatible with the Mono build environment used by Unity. Yes, I know it has to be C# 4, but beyond that? At present I'm copying CS files around and that doesn't feel right.

---

Just to make it crystal clear, the AI has no dependency on Unity and will be built in a project that has VS testing and code analysis but no Unity tools or imports. In future it may be used with a different engine.

# Answer
> 3 votes
It's very simple; all you need to do is start a new class library project.

Then, add a reference to the UnityEngine DLL. By default, it should be in C:\Program Files\Unity\Editor\Data\Managed\UnityEngine.dll.

Finally, you need to setup your project's target framework. I advise you download Visual Studio Tools for Unity, then go to your project's properties window. Choose Unity 3.5 .net full Base Class Libraries in the Target Framework dropdown menu.

To use the library in Unity, build the solution, navigate to the bin folder, grab the DLL, paste it in your Assets folder of your Unity project, and you should be set.

---
Tags: unity, visual-studio
---


title: Generic shape design

text:
# Question
Title: Generic shape design
I've been trying to come up with a generic shape design that would support shape-shape interactions (like Intersect), **based on the shape's type**.

So a common class/interface was needed, but a problem arises from shape types since not all shapes have common properties (eg. Circle is composed of a point and a radius, while polygons are composed of multiple points) so each pair of shape types has to have their own Intersect method.

After a lot of reading up on the subject of generics (and the like), i've come up with the following structure:

Collection class for storing delegates to shape Intersect methods

```
class IRdelegateCollection<T> // IntersectResult delegate collection
{
    public delegate IntersectResult IntersectAction<in U>(T a, U b);

    Dictionary<Type, Delegate> _jumpTable;
    public IRdelegateCollection()
    {
        _jumpTable = new Dictionary<Type, Delegate>();
    }
    public IRdelegateCollection(Dictionary<Type, Delegate> jumpTable)
    {
        _jumpTable = jumpTable;
    }
    public void Set<U>(IntersectAction<U> action)
    {
        if (_jumpTable.ContainsKey(typeof(U)))
            _jumpTable[typeof(U)] = action;
        else
            _jumpTable.Add(typeof(U), action);
    }
    public IntersectAction<U> Get<U>()
    {
        if (!_jumpTable.ContainsKey(typeof(U)))
        {
            return null;
        }
        return _jumpTable[typeof(U)] as IntersectAction<U>;
    }
}

```

Interfaces

```
interface IShape
{
    IntersectResult Intersects(IShape shape, out bool flipped);
    IntersectResult Intersects<T>(IShape<T> shape, out bool flipped);
}
interface IShape<T> : IShape
{
    T Instance { get; }
    IRdelegateCollection<T> IC { get; }
}

```

Base Shape class (all shapes will derive from this, although i guess they don't have to as long as they have their own IShape interface implementation)

```
abstract class Shape<T> : IShape<T>
{
    public abstract T Instance { get; } // shape instance
    public abstract IRdelegateCollection<T> IC { get; } // shape type's intersection delegate collection

    public IntersectResult Intersects(IShape shape, out bool flipped)
    {
        IntersectResult r = shape.Intersects<T>(this, out flipped); // call the other shape's intersect method, specifying our type
        flipped = !flipped; // results are flipped since we're calling the other shape's method
        return r;
    }
    public IntersectResult Intersects<T2>(IShape<T2> shape, out bool flipped)
    {
        flipped = false;
        var del1vs2 = IC.Get<T2>();
        if (del1vs2 != null) // we have the intersection delegate
            return del1vs2(Instance, shape.Instance);

        var del2vs1 = shape.IC.Get<T>(); // we dont have the delegate, try get the other shape's intersection delegate
        if (del2vs1 != null)
        {
            flipped = true; // we're returning the results of other shape's delegate, mark it as flipped
            return del2vs1(shape.Instance, Instance);
        }

        // neither of the two shapes have the intersection delegate
        return new IntersectResult();
    }
}

```

Some concrete shape definitions. (ShapeA does not have delegate for ShapeA-ShapeB intersection, but since ShapeB has one for ShapeB-ShapeA thats the one that gets called when intersecting ShapeB on ShapeA)

```
class ShapeA : Shape<ShapeA>
{
    static IRdelegateCollection<ShapeA> _ic =
        new IRdelegateCollection<ShapeA>(
            new Dictionary<Type, Delegate>()
            {
                { typeof(ShapeA), new IRdelegateCollection<ShapeA>.IntersectAction<ShapeA>(MathCol.AIntersectsA) }
            }
        );
    public override ShapeA Instance { get { return this; } }
    public override IRdelegateCollection<ShapeA> IC { get { return _ic; } }
}
class ShapeB : Shape<ShapeB>
{
    static IRdelegateCollection<ShapeB> _ic =
       new IRdelegateCollection<ShapeB>(
           new Dictionary<Type, Delegate>()
           {
                    { typeof(ShapeB), new IRdelegateCollection<ShapeB>.IntersectAction<ShapeB>(MathCol.BIntersectsB) },
                    { typeof(ShapeA), new IRdelegateCollection<ShapeB>.IntersectAction<ShapeA>(MathCol.BIntersectsA) }
           }
       );
    public override ShapeB Instance { get { return this; } }
    public override IRdelegateCollection<ShapeB> IC { get { return _ic; } }
}

```

With this kind of structure i can have a list of shapes and be able to intersect them appropriately without having to manually check their types.

```
ShapeA a = new ShapeA();
ShapeB b = new ShapeB();
bool flipped = false;

// These are called via .Intersects<T>(T shape, out bool flipped)
a.Intersects(a, out flipped); //calls AintersectsA, flipped: False
a.Intersects(b, out flipped); //calls BintersectsA, flipped: True
b.Intersects(a, out flipped); //calls BintersectsA, flipped: False
b.Intersects(b, out flipped); //calls BintersectsB, flipped: False

List<IShape> shapes = new List<IShape>();
shapes.Add(a);
shapes.Add(b);
// These are called via .Intersects(IShape shape, out bool flipped)
shapes[0].Intersects(shapes[0], out flipped); //calls AintersectsA, flipped: True
shapes[0].Intersects(shapes[1], out flipped); //calls BintersectsA, flipped: True
shapes[1].Intersects(shapes[0], out flipped); //calls BintersectsA, flipped: False
shapes[1].Intersects(shapes[1], out flipped); //calls BintersectsB, flipped: True

```

So there it is, now what i would like to know is:

1. Is this design appropriate for my requirement (having base shape that can intersect other shapes based on their subtype)?
2. The double interface - is this considered bad design (since `IShape`'s method accepts `IShape<T>` argument and `IShape<T>` is derived from `IShape`)? Note: i've also tried an alternative design where the `IShape.Intersect<T>` parameter was the abstract class `Shape<T>` but that didn't seem right as well.
3. I've had constraints `where T : IShape` on both the interface, abstract class `Shape<T>` and `IRdelegateCollection<T>` since i was trying to avoid the `T Instance` which is used in the `Intersection<T>()` method, but the compiler still had problems converting `Shape<T> to T`.
    * Is there a way to use the sahpes directly in the delegate invokation of the `Shape<T>.Intersects<T2>` method? (preferably: `del1v2(this, shape)` \- was throwing the above mentioned error, even with the constraints all over the place)
    * Should there be constraints of `where T : IShape` on all the `T`s? (There does not appear to be any advantage to constraining it)
4. Class `IRdelegateCollection<T>` uses a "jump table". My implementation needs a `_jumpTable.ContainsKey(typeof(U))` check for both setting and getting. Is there a better way of making this kind of jump table?

---

**EDIT**: after reading @Theraot's answer, and finding out that non-static classes can also have a static constructor, i've arrived at the following stucture:

```
delegate IntersectResult IntersectAction<in T, in U>(T a, U b);
interface IShape
{
    IntersectResult Intersects(IShape shape, out bool flipped);
    IntersectResult Intersects<T>(Shape<T> shape, out bool flipped);
}
abstract class Shape<T> : IShape
{
    public static class Interactor<U>
    {
        public static IntersectAction<T, U> Intersect { get; set; }
    }
    public abstract T Instance { get; } // shape instance

    public IntersectResult Intersects(IShape shape, out bool flipped)
    {
        IntersectResult r = shape.Intersects<T>(this, out flipped); // call the other shape's intersect method, specifying our type
        flipped = !flipped; // results are flipped since we're calling the other shape's method
        return r;
    }
    public IntersectResult Intersects<T2>(Shape<T2> shape, out bool flipped)
    {
        flipped = false;
        if (Interactor<T2>.Intersect != null)
            return Interactor<T2>.Intersect(Instance, shape.Instance);
        if (Shape<T2>.Interactor<T>.Intersect != null)
        {
            flipped = true; // results are flipped since we're calling the other shape's method
            return Shape<T2>.Interactor<T>.Intersect(shape.Instance, Instance);
        }
        return new IntersectResult();
    }
}
class ShapeA : Shape<ShapeA>
{
    static ShapeA()
    {
        Interactor<ShapeA>.Intersect = MathCol.AintersectsA;
        Interactor<ShapeB>.Intersect = MathCol.AintersectsB;
    }
    public override ShapeA Instance { get { return this; } }
}

```

I've decided to nest the static Interactor class inside the Shape because it didn't feel right having it completely decoupled from the Shape class.
I'm still not happy about `public abstract T Instance { get; }` but i guess it is required if I'm doing the work in the abstract class.
I'll leave the question open for a bit to see if someone else might have some more insight on the whole matter.

# Answer
---

## Selecting the Intersection Method

> 4. Class IRdelegateCollection uses a "jump table". My implementation needs a \_jumpTable.ContainsKey(typeof(U)) check for both setting and getting. Is there a better way of making this kind of jump table?

You need to:

1. Discover the delegates
2. Populate the delegate cache
3. Invoke the delegate from the delegate cache

**1. Discover the delegates**

You may choose not to discover the delegates, but instead to write them by hand in whatever code you are using to populate your delegate cache or directly where invoked.

If you want code to discover the delegates, you can use Reflection to find the right method to call from your `MathCol` class.

You can, for example, select a method by its name and call it:

```
var method = typeof(MathCol).GetMethod("AIntersectsA");
method.Invoke(a, b);

```

By building the string you pass to `GetMethod` you can then select the appropriate method to call.

If needed, you can specify the parameters types:

```
var method = typeof(MathCol).GetMethod("BIntersectsA", new Type[]{typeof(ShapeB), typeof(ShapeA)});
method.Invoke(b, a);

```

**2. Populate the delegate cache**

You can use dictionaries to store the delegates, or you can consider the following: you can create a class with the type parameters and a holder for the delegate.

Something similar to this:

```
public delegate IntersectResult IntersectAction<in T, in U>(T a, U b);

public static class Intersection<T, U>
{
    public static IntersectAction<T, U> Action {get; set;}
}

```

You will get complains because of the use of a static member with generic parameters. This is because each time you use this class with a different combination of type parameters you will be creating a new field with those parameters... and it will never be garbage collected.

Why is this better? Because it will take advantage of the CLR type resolution to find the right instance and at the same time it will make for cleaner code.

You will able to type something like this to store the delegate:

```
Intersection.Action = new IntersectAction<ShapeB, ShapeA>(MathCol.BIntersectsA)

```

---

To populate the `Intersection<T, U>`, I would suggest to do it during the application load. If you can't do that, consider a static constructor in a non-generic class, that will run only once (just note that if you don't interact with that class, it may not run).

In particular, you can do the following:

```
internal delegate IntersectResult IntersectAction<in T, in U>(T a, U b);

internal static class Intersection<T, U>
{
    public static IntersectAction<T, U> Action {get; set;}
}

public static class Intersection
{
    static Intersection()
    {
        // you can populate here, this code will run only once
    }
}

```

**3. Invoke the delegate from the delegate cache**

As for the interface to call the delegate consider that you may use operators in your classes. For example you may overload `&` for intersection, `|` could be union, etc... or you could have named `Intersects` method (static or not).

If you do something like that you will have a method for each combination of shapes distributed among the classes. You already have all those methods but they are in `MathCol`, you may move them or call them from there... of course that would be highly coupled.

So, we come to the current idea of using a delegate cache. Following the idea above, you can add this method to the non-generic `Intersection` class:

```
    public IntersectResult Invoke<in T, in U>(T a, U b)
    {
        var action = Intersection<T, U>.Action;
        if (action != null)
        {
            return action(a, b);
        }
        return new IntersectResult();
    }

```

The code above will allow you to write:

```
var result = Intersection.Invoke<ShapeA, ShapeB>(a, b);

```

We may include the `flipped` logic in there too:

```
    public IntersectResult Invoke<in T, in U>(T a, U b, out bool flipped)
    {
        flipped = false;
        var action = Intersection<T, U>.Action;
        if (action != null)
        {
            return action(a, b);
        }
        action = Intersection<U, T>.Action;
        if (action != null)
        {
            flipped = true;
            return action(b, a);
        }
        return new IntersectResult();
    }

```

Using this, you don't even need to expose an `Intersects` method in your shapes.

---

This is part of your example code:

```
ShapeA a = new ShapeA();
ShapeB b = new ShapeB();
bool flipped = false;

// These are called via .Intersects<T>(T shape, out bool flipped)
a.Intersects(a, out flipped); //calls AintersectsA, flipped: False
a.Intersects(b, out flipped); //calls BintersectsA, flipped: True
b.Intersects(a, out flipped); //calls BintersectsA, flipped: False
b.Intersects(b, out flipped); //calls BintersectsB, flipped: False

```

It would become:

```
ShapeA a = new ShapeA();
ShapeB b = new ShapeB();
bool flipped = false;

Intersection.Invoke(a, a, out flipped); //calls AintersectsA, flipped: False
Intersection.Invoke(a, b, out flipped); //calls BintersectsA, flipped: True
Intersection.Invoke(b, a, out flipped); //calls BintersectsA, flipped: False
Intersection.Invoke(b, b, out flipped); //calls BintersectsB, flipped: False

```

---

## Type inheritance suggestion

> 1. Is this design appropriate for my requirement (having base shape that can intersect other shapes based on their subtype)?

Yes, this would work. I'd suggest having two levels of shape class inheritance. In particular if you have `PolygonShape`, `CurveShape` and `BoxShape`, and then your particular shapes (such as `Circle`, `Triangle`, etc...) can inherit form those.

The idea is that the first level will handle the different intersection algorithms you have (eg: segment shape to segment shape), while the lower level can be particular shapes (eg: star, triangle, etc...).

The simplest case would be of dealing with rectangles (`BoxShape`). You could use it for shapes made of single rectangle. You could consider generalizing it for shapes made of multiple rectangles, but `PolygonShape` should be able to deal with that too. The case of a single rectangle is worth to optimize, you'll see below why.

The second case would be describing shapes as a set of segments. These are the `PolygonShape`. Their intersection is relatively simple, and you can use the rectangle intersection for optimization (use the bounding box of the shape to check if they are close enough, and use the bounding box of the segments to check if they are close enough).

The third case would be describing curves, that is `CurveShape`. This can be done as a set of Bezier curves. To do work with these you can use the bounding box of the Bezier curves (you may have it pre-calculated), intercept the bounding boxes (simple rotated box interception) and if they do, you can use a Bezier interception algorithm.

Those should be enough for most cases (unless you need curves or higher order, or if you need fractals or anything else crazy like that). In this order of ideas, you won't need a large number of algorithms to deal with the different shapes. You may even consider to fallback to a simple `switch` statement instead of using a dictionary or the shenanigans I described above.

---

## Generic typing concern

> 2. The double interface - is this considered bad design (since `IShape`'s method accepts `IShape<T>` argument and `IShape<T>` is derived from `IShape`)? Note: i've also tried an alternative design where the `IShape.Intersect<T>` parameter was the abstract class `Shape<T>` but that didn't seem right as well.
> 3. I've had constraints where T : IShape on both the interface, abstract class Shape and IRdelegateCollection since i was trying to avoid the T Instance which is used in the Intersection() method, but the compiler still had problems converting Shape to T.
>
> * Is there a way to use the sahpes directly in the delegate invokation of the Shape.Intersects method? (preferably: del1v2(this, shape) - was throwing the above mentioned error, even with the constraints all over the place)
>     * Should there be constraints of where T : IShape on all the Ts? (There does not appear to be any advantage to constraining it)

It is not technically wrong, although I have to point that the circular references (eg: `ShapeA : Shape<ShapeA>`) may not be handled well by old compilers and generally are not encoraged.

I'd suggest to get rid of `IShape<T>` and instead use `Shape` as base. I'm unsure if you can get rid of the generic constraint.
> 0 votes

---
Tags: c#
---


# Question
Title: C# Unity - Getting which function affects a GameObject
I have this little code that moves a `GameObject` over time:

```
 public void Move(Transform from, Transform to, float overTime)
     {
         StartCoroutine(_Move(from, to, overTime));
     }
     IEnumerator _Move(Transform from, Transform to, float overTime)
     {
         Vector2 original = from.position;
         float timer = 0.0f;
         while (timer < overTime)
         {
             float step = Vector2.Distance(original, to.position) * (Time.deltaTime / overTime);
             from.position = Vector2.MoveTowards(from.position, to.position, step);
             timer += Time.deltaTime;
             yield return null;
         }
     }

```

Which is easy as it is, I plan to use it for UI animations. However, things get interesting when I wish to use this for a bit more complex animations, or I want it to stop upon restart.

**More complex animations:**

I click a button which then moves to the side and bounches back. For this I need to know when the exact same method finished moving the button so I can restart it to bounce back.

**Stop upon restart:**

Say I hover my mouse over a button which moves then. However, if it's still moving, I want its current animation to stop, and a new one to start. For both of these I need to know which function affects which GameObject so I can manage that. Question is, how? Shall I use one script on each of the animated components which affects only that one? Or if I could use only one script on the whole Canvas, then how?

# Answer
> 2 votes
## Complex Animations:

To know when a coroutine finished executing, you can pass a callback to it as one of its arguments, which it invokes once it's done (or at any other point throughout its execution), like so:

```
private IEnumerator DummyCoroutine(Action onCompletedCallback)
{
    // Do something here...

    onCompletedCallback.Invoke();
}

```

## Stop Upon Restart:

1) Create a global variable for the coroutine:

```
private IEnumerator dummyCoroutine;

```

2) Make sure the coroutine nullifies that global variable once it finishes executing:

```
private IEnumerator DummyCoroutine()
{
    // Do something here...

    dummyCoroutine = null;
}

```

3) Whenever you want to start the coroutine, do a null-check on the global variable. If it's not null, then the coroutine is still running. Call StopCoroutine() on it to stop it. Then, either way, create a new instance of the coroutine, assign it to the global variable, and start it:

```
private void StartMyDummyCoroutine()
{
    if (dummyCoroutine != null)
    {
        StopCoroutine(dummyCoroutine);
    }

    dummyCoroutine = DummyCoroutine();
    StartCoroutine(dummyCoroutine);
}

```

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


title: How to make more jagged terrain

text:
# Question
Title: How to make more jagged terrain
I need some help with some terrain I'm working on. I'm developing a plugin for Minecraft, but these concepts will apply to any game with terrain. I am using Simplex noise to generate cavern-like terrain. I am using the power of the noise to generate hills that look like this:

As you can probably tell, it inst looking very cavern-like. What can I do to improve this terrain?

# Answer
The easiest way to make it more jagged is to add noise to it. You'll get various spikes at various points.

Another thing you could do is take your values and apply some function to them. For example, if your heights are between 0 and 1 when generating your height map, you can square them. That will result in the slopes being more extreme throughout the map.
> 1 votes

---
Tags: procedural-generation, terrain, minecraft-modding
---


# Question
Title: What are the basics of implementing a Goal Oriented AI?
I am currently developing a nations / factions simulator on a map with in-depth resource system, population system, important characters system.. and this is where I finally met a real obstacle.

You see, I wish to give important characters a set of actions which their AI will use to achieve goals, goals that will depend on their character type. For example, an important character who spawns because he leads a migration wave will have two goals : to keep himself and his party alive and to reach his destination and start a new "population node" there. Another example : warlords could seek to increase their "power" variable by making plans to get ahead of other warlords through simple actions like giving money to a local lord to help develop his land, etc.. this would take very long to describe in great detail.

As you can see, or at least as I see it, the best AI architecture for this kind of behavior would be a Goal Oriented AI : it would allow me to keep expanding the set of actions characters have to advance their interest and at the same time allow me to easily create new types of important characters.

I have done quite a lot of research, and most of the sources I found explain the same thing clearly, which I understood : GOAP is about having a starting "world state" and through a "path" of actions, get to a desired world state called a "goal".

The thing I couldn't understand is how exactly you can achieve this with actions other than actions which do not require any parameters. I could implement a basic system right now, I think, provided actions can fully run by themself with no external information, and more importantly no knowledge of eachother, because that would break the point of the whole system I believe.

The articles talk about that very vaguely. I've read about a "blackboard" system where information like what is the current target, where to move.. can be stored. But while planning how do you use this ? Where does that information come from ? How do you associate it with "world state" key-value pairs ?

Finally, I found that some people solve this problem, or at least solve it for the movement, by making a FSM over the GOAP, where one of the state is "moving" and the other one is, basically "GOAP". But I do not think this is the best approach and more importantly I'd like not to go with a hybrid if I can.

So if someone would be kind enough to explain the basic concepts of implementing a Goal oriented AI, or at least help me deal with actions that require a parameter, I'd be extremely grateful. If you want me to expand this wall of text I can provide more detail, simply ask.

PS : I use Unity, coding in C# exclusively.

# Answer
> 11 votes
## Planning

You have a world that has some state, and the agents can do actions that affect that state. Now, you can think of the world state as a node, and the actions are the links.

You would not have a graph with all the possible game states. Instead you should express your actions as pre-conditions (needed to be able to do the action) effects (that you should be able to apply to the world state to be able to compute the new state) and some cost (in time or resources).

Then the goals are predicates you should be able to check about the world state (for a given world state, the goal has been met or not). As you can see, the actions have pre-conditions that are basically the same thing. This means that you can model the goal as an action (having the effect of "the AI wins").

What follows is planning. There are two approaches:

**Forward Searching**

The idea is that you need to find a path (a series of actions) that will take the current world state to a world state that satisfies the goals. You do this by pathfinding.

As you know, when pathfinding you can have a heuristic to provide priorities over the different branches you search... that heuristic could be a measurement of the progress towards a goal (you may expand this idea to include the risk of moving away from the goal, perhaps as an estimate of enemy treats).

Now, you can search the action space for a path that will lead you to the goal state. Or, perhaps you could just plan a few steps by finding the path that would take you closer to the goals in those steps, this way keeping the time dedicated to AI short.

Note: As I said above, you don't have a graph will all the possible states of the game. Instead you would generate the game states that the AI explores as it does it. If you give a look to the pseudo code for A\* Search Algorithm or for Dijkstra's algorithm you'll see that you only need to persist the actions, not the states. This also allows you to search an infinite state machine.

**Backtracking**

Here you start with the goal, you attempt to do it as an action and you find you need to meet some condition first. Then you look at the other actions and see what actions may lead to that, etc... until you reach an action that can be performed right away (that is an action to which the current world state satisfies its pre-condition).

As you can see, this is also searching, except you start by the end. Backtracking works better with simple abstract scenarios, but it may not work for open ended games because reaching the goals may be too far away that it takes too long for the AI to start doing any actions.

---

## Abstractions

The world representation that the AI sees doesn't need details. The idea is to move code away from the predicates. For example one possible action is to shoot an enemy; its pre-conditions would be to have a ranged weapon, with enough ammo, and for there to be a nearby visible enemy. You don't want to have to write in the predicate the logic to find nearby objects, line of sight checks, etc... This would be abstracted by the code that creates the world representation with which the AI works. A subsystem will then deal with the details of changing weapon, aiming and shooting.

Another thing you can do is to find interchangeable objects. If something can be done with object A or with object B to similar results, the AI doesn't need to be concerned with it. Instead a subsystem can deal with the details. For example in some combat video games the AI doesn't have the responsibility of choosing kick vs punch. Instead another subsystem can check the collision boxes, the damage of each option, and whatever or not they can be chained in a combo to decide what attack to do. The AI will then worry about being offensive or defensive, going for ranged attacks or close combat and predicting player moves to dodge, block or counter.

Another technique you can apply is to bookmark zones and choke points that are important to control. This will allow you to provide the AI with a discrete list of locations instead of having to deal with coordinates. Then a subsystem dealing with formation and pathfinding will decide exactly where to go.

**Note on large maps**

You will want to keep a structure that allows you to query nearby objects (this is useful for other things), using that structure you will be able to limit the representation of the world state used by the AI to the immediate surroundings of the objects it controls. This will keep the AI performance regardless of the size of the map.

---

## Predicting other agents

Of course there are multiple agents in the game, and there is no way an agent will know what another agent will do (unless they share information). You can approach this by implementing game theory: the agent considers the possible moves the other agents may do and picks what’s best across all the possibilities.

In order to keep things simple you may consider making each agent predict what is best for each other agent according to your AI (similar to MinMax) but with only the information available to the agent doing the prediction.

To predict players, you can represent them as probabilities. To give value to those probabilities you can use the frequency with which the user does an action, is seen in a given location, or uses some item. For the locations you may want to annotate the frequency in the map. Since you are keeping your AI isolated, you would make a separate representation of each player for each AI agent.

---

## Randomness

So far the AI is deterministic, therefore predictable…

A simple way to do is, is having using random to have the AI pick unnecessary actions or actions that nonetheless have some reward for the AI agents, or by taking a suboptimal approach to reach the goal. This may provide a more interesting gameplay, more replay value, and the benefits of the unnecessary action may help the AI to find alternative solutions when their plans fail.

---
Tags: ai
---


title: Why isn't my player moving?

text:
# Question
Title: Why isn't my player moving?
Why is my code not working?

```
using UnityEngine;
using System.Collections;

public class NewBehaviourScript1 : MonoBehaviour
{
    public float moveSpeed;
    public Vector3 input;
    public Rigidbody rb;

    void Start ()
    {
        rb = GetComponent<Rigidbody>();
    }

    void FixedUpdate ()
    {
        moveSpeed = 2;
        input = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
        rb.AddForce(input * moveSpeed);
    }
}

```

# Answer
> 1 votes
After testing your code, the only conclusion I can come to is that you are not actually including a `Rigidbody` on your player. When we use `GetComponent<t>()`, we are referencing an *existing* component on the host `GameObject`.

Given your above code, on an object that contains a `Rigidbody`, the object moves quite clearly. I have included a recording, for reference.

---

### Ensure your `GameObject` has a `Rigidbody` through code

You can add a simple tag to any script to force it to require a component. If said script is attached to a `GameObject` via the Inspector, the required component is added, too. You can do this with *any* `Component`; this is what it would look like if you forced your script to attach a `Rigidbody`:

```
[RequireComponent(typeof(Rigidbody))]
public class NewBehaviourScript1
{
    // ...
}

```

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


# Question
Title: Where do I handle my input in a basic game loop?
I recently had the occasion to work on a game, during a game jam at my college, and it really got me into it, so I've decided to start something more polished with a friend of mine. During the game jam, I made a top-down 2D hack'n'slash with a capped frame rate, thinking it would be easier. However, I ran into some problems for animations, and realized that capping the frame rate wasn't the best solution, as it would also cause the game to run slower on weaker hardware.

I updated the engine, so that it would use variable time steps. However, I've read a lot about patterns, and realized that variable time steps are highly deprecated. After some reading, I thought I'd settle for something like this:

```
const sf::Time MS_PER_UPDATE = sf::seconds(1 / 60);

sf::RenderWindow window(sf::VideoMode(800, 600), "GameEngine");

sf::Clock clock;
sf::Time lag = sf::milliseconds(0);

while (window.isOpen()) {
    sf::Time elapsed = clock.restart();
    lag += elapsed;
    sf::Event event;
    window.pollEvent(event);

    if (event.type == sf::Event::Closed) {
        window.close();
    }

    // Where to process input?
    while (lag >= MS_PER_UPDATE)
    {
        // Update game logic
        lag -= MS_PER_UPDATE;
    }

    window.clear();
    // Rendering
    window.display();

```

---

The question is, where do I handle my input? In my last project, I passed the event polled in the update function (something like `update(event, dt)`), and handled user input there; I'm wondering if it is actually the way it is supposed to be done. Since I'm only polling one event per frame, I'm wondering if it would significantly affect the user experience.

# Answer
> Where do I handle my input? \[...\] I'm wondering if it's actually the way it's supposed to be done.

That's the advantage of using a framework or library rather than a complete engine: It's up to you to decide based on what you want or what you need. You're not forced to either approach.

> Also since I'm only polling one event per frame, I'm wondering if it would significantly affect user experience...

This can and will create massive input delays and lags, if the program is running slower for whatever reason. You should always poll all events available between drawing.

---

Personally I'd try handling input in your primary event loop (which you're missing right now; see the note above). Create and update some kind of state, which could be as simple as a bit field in an integer.

This encapsulation allows you to rework or replace the input handling at any time (you might not want to use SFML forever or redo something) without rewriting everything.
> 0 votes

---
Tags: game-loop, sfml, design-patterns
---


# Question
Title: Why transform.Rotate(X,0,Z) rotates also Y?
In my game I'm trying to rotate a turret. I'm using the classic pattern:

```
float h = Input.GetAxis ("Horizontal");
float v = Input.GetAxis ("Vertical");

if (h != 0 || v!=0)
    rb.transform.Rotate (new Vector3(v, 0, h));

```

The problem is that if I move in vertical axis also Y axis rotates. Why?

How can I achieve a rotation that rotates only the X and Z axis and **not** the Y axis?

# Answer
The rotation is applied first around the z-axis, then around the x-axis and last around the y-axis. This means that rotating around the x-axis results in a rotation around the original y-axis aswell.

The easiest way to achieve what you want is probably to parent the object to another game object, and rotate the parent and child around the two axes separately.

That way the order of rotation doesn't matter. You need to set the localTransform of the child instead of the transform to get the correct behavior.

You might also want to keep the two angles in variables, and set the rotation using `localTransform.rotation = Quaternion.Euler(x,y,z)`, instead of applying the rotation to the current transform, because that will be more robust against rounding errors and the state is easier to inspect and control.

Example (untested):

```
baseRotation += Input.GetAxis ("Horizontal");
barrelRotation += Input.GetAxis ("Vertical");
turretBase.localTransform.rotation = Quaternion.Euler(0, 0, baseRotation);
turretBarrel.localTransform.rotation = Quaternion.Euler(barrelRotation, 0, 0);

```
> 0 votes

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


# Question
Title: How can I destroy generated (cloned) obstacles in Unity?
The obstacles are generated using a generate script, and the main game object is in the prefabs folder. I have attached the game object with the generate script, the problem is that it is not destroyed. I have tried using the `OnBecameInvisbile()` method in the `Generate` script.

```
using UnityEngine;
using System.Collections;

public class Generate : MonoBehaviour
{
    public GameObject rocks;

    void Start()
    {
        InvokeRepeating("CreateObstacle", 3f, 3f);
    }

    void CreateObstacle()
    {
        Instantiate(rocks);
    }

    void OnBecameInvisible()
    {
        Destroy(this.rocks);
    }
}

```

---

How do I destroy the generated obstacles?

# Answer
You can try adding this script to your prefab bullet:

```
using UnityEngine;
using System.Collections;

public class Bullet: MonoBehaviour
{

    void OnBecameInvisible()
    {
        // Destroy the when Become Invisible
        Destroy(gameObject);
    }
}

```
> 1 votes

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


# Question
Title: How to randomly spawn a Rect on x position (android studio)?
I want to draw a rect with a 50x50 size, however I want it to appear randomly on the x position. Where should i set the x position?

This is how i set my rectangle.

```
rectangle.set(50, 50, 100, 100);

```

I've done several changes on this setting the but I can't figure it out.

# Answer
> 0 votes
You need to do the following:

```
rectangle.set(randomX, 50, randomX + 50, 100);

```

Where `randomX` is the random value.

---
Tags: java, android, android-studio
---


title: How can I create a title screen demo?

text:
# Question
Title: How can I create a title screen demo?
I am writing a 2D game in Unity and I want to offer an old-school style title screen demo (such as in Super Mario, etc.) where it shows a brief run through of either one or various levels. How would I accomplish this?

If anyone can either enlighten me or point me to some further reading then it would be very welcome.

# Answer
The easiest way is to record a play through of the game using some kind of screen-recording software and just play that back. It's probably also the least *flexible* way, but it would work.

A more interesting solution is to build a record-and-playback feature into your game. These are also known as "replay systems," and you can find quite a few questions about them on here if you search around (try ).

The basic concept is to first record all the input (along with timestamps of that input) as it happens in your game, and save this recording out into a buffer somewhere you can load back up.

Then you load it back up and run the game in a mode where instead of processing input from the actual controllers or keyboards or whatever, you pop an input event off the recorded queue, wait until the appropriate relative amount of time has passed since playback began, and then feed that input to the rest of your game *as if* the user had simply pressed the correct button.

This often requires you to have a deterministic simulation, so you will find that you'll want to save the random seed used to initialize any random generators with the recording buffer as well, and make sure that everything in your gameplay (that matters) is keyed to that seed so you don't get out-of-sync errors.

Then it's simply a matter of recording a good-enough demo run yourself, saving that buffer as an asset with your game, and then in the "title screen" game state, playing that recording back (probably on a loop of some sort).
> 9 votes

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


# Question
Title: What are the alternatives to additive damage?
By additive damage I do not mean additive damage bonuses. I mean damage that adds up over time:

```
New HP = Old HP - Damage

```

Additive damage has the following properties:

1. It is linear as damage adds up over time.
2. Characters are knocked out when their HP falls to 0 or below.
3. HP can be displayed as a linear progress bar.

One alternative that I thought of was multiplicative damage:

```
New HP = Old HP / Damage

```

Multiplicative damage has the following properties:

1. It is exponential as damage multiplies over time.
2. Characters are knocked out when their HP falls to 1 or below.
3. HP can be displayed as a logarithmic progress bar.

However, multiplicative damage is just additive damage in disguise because `a * b = exp(log(a) + log(b))`.

So, when I say that I'm looking for an alternative to additive damage what I mean is that I'm looking for a group structure for damage that's not isomorphic to addition.

A group is a set `G` together with a binary operation  that must satisfy the following properties:

1. **Closure:** For all `a, b` in `G`, the result of the operation `a • b` is also in `G`.
2. **Associativity:** For all `a, b, c` in `G`, we have `(a • b) • c = a • (b • c)`.
3. **Identity:** There exist a unique element `e` in `G` such that, for all `a` in `G` we have `e • a = a • e = a`.
4. **Inverse:** For each `a` in `G`, there exists a unique element `b` (denoted as `a^-1`) such that `a • b = b • a = e` where `e` is the identity element.

For the purpose of this question, `G` need not be the set of integers. It could be any set (e.g. reals or complex numbers or even a set of things which aren't numbers) as long as it makes sense in the context of damage:

```
New HP = Old HP • Damage^-1

```

Furthermore, it would be nice if `G` also formed a ring structure but it's alright if it doesn't. Having a ring structure would make calculating damage easier.

Finally, I'm aware that this question is quite subjective and I know that StackExchange is a place for objective questions. However, I hope that by providing an objective basis for a subjective question this would lead to objective discussions.

# Answer
One interesting direction is suggested by the "Wealth Check" used in the d20 Modern tabletop system.

Rather than counting every coin or bill, the system models wealth as a generalized condition:

```
Condition                    Bonus
Impoverished or In Debt       -1
Struggling                   +1-4
Middle Class                 +5-10
Affluent                     +11-15
Wealthy                      +16-20
Rich                         +21-30
Very Rich                    +31-up

```

Any purchase or fee is then resolved through a wealth check, rolling a die and adding your bonus, compared against the "difficulty class" or the purchase.

You automatically succeed at any check where your bonus is at least as high as the difficulty. Succeeding a wealth check for a difficulty class higher than your current bonus reduces your bonus. This models the fact that at high wealth, small purchases are negligible, while purchases exceeding your normal means have a longer-term cost. It also reduces the complexity of modern financial management so players don't have to track virtual bank balances and credit scores. ;)

We could apply a model like this to health & damage: give the character or object a set of evocative conditions like "robust" "winded" "staggered" "debilitated" etc, and a threshold of damage they can shake off in each (a player in a high health state shouldn't need to track every paper cut, but one barely maintaining consciousness would need to attend to every threat). Beyond that you can add ranges of damage that should move them to another condition, either deterministically or with some probability.

Stone Librande's board game "Us vs It" uses a similar mechanic for the health of the player tank characters. Namely, they have two states, and their response to incoming damage is different in each state:

```
Hits Taken     Normal            Damaged (flipped)
--------------------------------------------------
    1           Stun               Stun
    2       Become Damaged       Destroyed
    3       Stun + Damaged       Destroyed
    4         Destroyed          Destroyed

```

This lets the game express multiple levels of impact, and create more fragile gameplay for damaged tanks, while keeping the math and state-tracking simple: a single 2-sided token suffices, rather than an HP counter.
> 4 votes

# Answer
Try logical damage. Player health is represented as a set of bits and damage is a logical operation on those bits. For a simple example, picture Nerf Fencing: You have to hit all four of your opponents targets to win. Player state is four bits initialized to 0. Damage is a logical OR operation of a single 1 bit (the sword can only poke one target at a time). Death is defined as player state of four 1 bits.

Concepts such as regeneration can be implemented with another logical formula applied periodically such as state=state&rand()

This technique can be combined with additive damage where bits are set when hp=0 in a traditional system.
> 2 votes

---
Tags: mathematics, game-design, game-mechanics
---


# Question
Title: Appropriate data structures for large item database
I'm currently building an RPG Game and as such I intend to have a lot of items. In my current system I have a database of items stored in a JSON file which I read and then store the items in a generic List\<\>. My question is as the numbers of items grow should I be looking into using a better data structure to store my database? As I wonder if i'll be able to search the list in an appropriate time when there's potentially thousands of items.

# Answer
> 1 votes
In terms of performance, it probably isn't a problem until you have a few thousand items (which you say you may have).

As per the data-structure to keep them in memory, you should consider how you use it. In particular: Do you iterate over it? Do you search by some criteria? Do you insert or remove often?

Since you mention searching, you may consider to use `Dictionary<TKey, TValue>` or even `Dictionary<TKey, List<TValue>>` to serve as indexes to access the items you need.

Going forward, there is nothing wrong with choosing a database engine for your game. I'd suggest to give a look to SQLite.

---
Tags: unity, c#, data-structure, databases
---


title: OpenGL - texture releasing

text:
# Question
Title: OpenGL - texture releasing
If I call `glDeleteTextures`, will it release memory immediately? And what is the performance? I know that `glGenTexture` is quite cheap, because it only alocated id, but I have nor found anything about deleting.

# Answer
> 9 votes
> If I call glDeleteTextures, will it release memory immediately?

glDeleteTextures

> After a texture is deleted, it has no contents or dimensionality, and its name is free for reuse.

This says absolutely nothing about the backing storage for a texture, i.e the memory used for it. From that we can infer that behaviour is entirely up to the GL implementation. Typically one of three things might happen:

* Memory is released immediately.
* Memory is not released immediately but will be released at some point in time shortly after you call glDeleteTextures; a scenario where this might make sense is if releasing the memory immediately (and not returning until done) is an expensive operation - if so, queueing-up the release for later on might help with performance right now.
* Memory is not released at all. Where this might make sense is if the memory can be re-used to satisfy a future allocation requirement and where this re-use is faster than a full release and reallocate cycle.

Because OpenGL doesn't specify which, any of these three, or something else entirely different, may happen.

Otherwise the only things you can rely on after calling glDeleteTextures are:

1. The texture name can be reused by a future call to glGenTextures, and,
2. glGet calls against the contents or dimensionality will return NULL or 0.

> And what is the performance?

OpenGL specifies functionality, not performance. As always with performance-related questions, you should know your target platforms and benchmark/profile your code on them so that you are satisfied that the performance you get is within acceptable tolerances.

---
Tags: opengl, textures, opengl-es
---


# Question
Title: Odd exception when calling a method in DirectX 11
I am following the "3D game programming with directx 11" book (Frank Luna) and I am trying to render a cube. In the code there is this `m_device->CreateBuffer()` function which is giving me problems.

The exception I get is:

> Device was 0XFFFFFFFFFFFFFFFF
>
> DirectX11 exception in a method which is external to where the CreateDevice() method is called

So I tried to put it in the method where the device is created, and it gives no exception, so I'm wondering if I have to make the `m_device` something like global or I don't know.

```
struct Vertex {
        XMFLOAT3 Pos; XMFLOAT4 Color;
    };

 Vertex vertices[] = {
        { XMFLOAT3(-1.0f, -1.0f, -1.0f), XMFLOAT4((const float*)&Colors::White)},
        {XMFLOAT3(-1.0f, +1.0f, -1.0f),  XMFLOAT4((const float*)&Colors::Black)},
        {XMFLOAT3(+1.0f, +1.0f, -1.0f),  XMFLOAT4((const float*)&Colors::Red)},
        {XMFLOAT3(+1.0f, -1.0f, -1.0f),  XMFLOAT4((const float*)&Colors::Green)},
        {XMFLOAT3(-1.0f, -1.0f, +1.0f),  XMFLOAT4((const float*)&Colors::Blue)},
        {XMFLOAT3 (-1.0f, +1.0f, +1.0f), XMFLOAT4((const float*)&Colors::Yellow)},
        {XMFLOAT3 (+1.0f, +1.0f, +1.0f), XMFLOAT4((const float*)&Colors::Cyan)},
        {XMFLOAT3 (+1.0f, -1.0f, +1.0f), XMFLOAT4((const float*)&Colors::Magenta)}
    };
    D3D11_BUFFER_DESC vbd;
    vbd.Usage = D3D11_USAGE_IMMUTABLE;
    vbd.ByteWidth = sizeof(Vertex) * 8;
    vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    vbd.CPUAccessFlags = 0;
    vbd.MiscFlags = 0;
    vbd.StructureByteStride = 0;
    D3D11_SUBRESOURCE_DATA vinitData;
    vinitData.pSysMem = vertices;
    m_device->CreateBuffer(&vbd, &vinitData, &mBoxVB); //exception is here

```

I repeat the code perfectly works in the method where I called the `CreateDevice()` method, but doesn't here, in another method of another class.

# Answer
m\_Device will be of type ID3D11Device\*, i.e. it should be a pointer to a Direct3D 11 device object. In almost all Direct3D 11 applications, there is exactly *one* device, which is initialized with D3D11CreateDevice or a similar function at the start of your program, and uninitialized at the end of it.

All of your 3D objects will usually be created by that device using functions like CreateBuffer. So a lot of times, a global pointer to the device makes sense. In standard notation, the "m\_" prefix means that the variable is a *member* of the class. So if you've created the device in one class, but want to use it in another, the m\_device pointer will need to be copied across.

It looks in this case like you've created the device, but either not stored its pointer, or you're using a different device pointer that hasn't been initialized. Perhaps in the constructor of the class that has the problem you can put something like:

```
ThisClass::ThisClass(ID3D11Device *dev): m_device(dev)
{
}

```

As long as the class instance is initialized after the device was created, and you have the device pointer from D3D11CreateDevice, you can pass it in to the constructor, and the m\_device pointer will be correct.
> 1 votes

---
Tags: c++, directx11
---


# Question
Title: Why this simple SFML app produce such high CPU usage?
I written the following SFML.NET app. It draw a single 128x128 sprite on the screen.

```
RenderWindow window = new RenderWindow(new VideoMode(800, 600), "SFML window");
window.SetVerticalSyncEnabled(true);

Texture texture = new Texture("test.jpg");
Sprite sprite = new Sprite(texture);

// Start the game loop
while (window.IsOpen())
{
    window.DispatchEvents();
    window.Clear();
    window.Draw(sprite);
    window.Display();
}

```

Since VSync is enabled, the number of FPS is capped to 60. I expect the program to use very little CPU, but under task manager it show me that is use about 50% (two cores fully actually). Also it seems it use about 30% kernel time and the rest is user time.

The exact same application in SDL (just drawing a single sprite) use about 0% (regardless SDL\_RENDERER\_ACCELERATED is used or not).

EDIT : surprisingly, if I let the app run for a given amount of time (let's say 10-20 seconds, the CPU usage fall down to 0%). I manage to repeat this several times. That is really strange.

# Answer
> 0 votes
Switching the "Threaded Optimisation" option to "Off" in the NVidia control panel totally fixes the problem (it was "Auto" by default). So this is a video card driver issue, not a SFML one. I don't know what this setting exactly do (must read about it)

---
Tags: sfml, vsync, cpu
---


# Question
Title: InputField text to string variables of a struct
So, here's my issue. I have a class that contains a struct. This struct contains about 7 different string variables. I can set the values of these variables via a constructor that takes the struct variables and matches them to separate holder variables that have the actual values. However, I'm having issues, getting these values. I need to retrieve them from 7 different InputFields. I've tried to do this already. I ended up having some variables without values and some with the same value. **How can I retrieve the text value of the different InputFields and pass them to the 7 different holder variables that will set the values of the struct variables?**

Below is the first method I tried, this only resulted in Age actually having a value (Note, I had debugging logs to check the assignments, I left out anything that was deemed unnecessary such as debugging logs and methods that are irrelevant to the problem.). I also set the Collect() method to a Button so when the button was pressed it would collect the data. I also tried replacing all the if statements with a switch case, that yielded the same result. As further try, I set up Get methods for all the types and attached them to the InputFields themselves to have them return `field.text` to the variables. This resulted in the aforementioned issue that some had no values and some had the same value as Age.

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

namespace Handlers
{
    public class EventHandler : MonoBehaviour
    {
        InputField field;

        public static string f_name;
        public static string l_name;
        public static string p_age;
        public static string p_height;
        public static string p_weight;
        public static string p_hair;
        public static string p_eye;

        private void Awake()
        {
            field = FindObjectOfType<InputField>();
        }
        public void Save()
        {
            if (File.Exists(Application.persistentDataPath + "/PlayerData.dat"))
            {

            }
            else
            {
                BinaryFormatter formatter = new BinaryFormatter();
                FileStream fstream = File.Create(Application.persistentDataPath + "/PlayerData.dat");
                Profile playerData = new Profile();
                formatter.Serialize(fstream, playerData);
                fstream.Close();
            }
        }
        public void Collect()
        {
            if (field.name == "FirstName")
            {
                f_name = field.text;
            }
            if (field.name == "LastName")
            {
                l_name = field.text;
            }
            if (field.name == "Age")
            {
                p_age = field.text;
            }
            if (field.name == "Height")
            {
                p_height = field.text;
            }
            if (field.name == "Weight")
            {
                p_weight = field.text;
            }
            if (field.name == "Hair_Color")
            {
                p_hair = field.text;
            }
            if (field.name == "Eye_Color")
            {
                p_eye = field.text;
            }
        }
    }
    [Serializable]
    class Profile
    {
        struct Player
        {
            public static string firstName;
            public static string lastName;
            public static string age;
            public static string height;
            public static string weight;
            public static string hair_color;
            public static string eye_color;
        }
        public Profile()
        {
            Player.firstName = EventHandler.f_name;
            Player.lastName = EventHandler.l_name;
            Player.age = EventHandler.p_age;
            Player.height = EventHandler.p_height;
            Player.weight = EventHandler.p_weight;
            Player.hair_color = EventHandler.p_hair;
            Player.eye_color = EventHandler.p_eye;
        }
    }
}

```

Here's an example of the second attempt (just an example as the entire method system is laid out above, and there is no need to repeat the same process over and over):

```
public void getFN()
{
    f_name = field.text;
}
public void Collect()
{
    getFN();
}

```

getFN() would be placed on the InputField and Collect() would be on the button so that when the button was clicked it would call each individual like style methods of getFN(). (getLN(), getAge(), etc.)This in return, at least in my mind, should have gotten the individual texts but it didn't.

# Answer
> 2 votes
You have a single `field` that is the first `InputField` found by `FindObjectOfType`. Apparently in your case it was the age `InputField` and that's why that was the only variable that was set.

Read your code for the `Collect` method, if the value of `field` or `field.name` is not changing behind your back (it shouldn't be), the code will only enter one of the `if` clauses (you may aswell have used a `switch` statement).

Instead you should be using `Object.FindObjectsOfType` it should give an array of `InputField`. Then in the `Collect` method you would iterate over that array, and for each item check the name and set the appropiate variable.

Something like this:

```
public class EventHandler : MonoBehaviour
{
    InputField[] fields;

    // ...

    private void Awake()
    {
        fields = FindObjectsOfType<InputField>();
    }

    public void Collect()
    {
        foreach (var field in fields)
        {
            // your old code here
            // or use a switch statement
        }
    }
}

```

---
Tags: unity, input, text, struct
---