# Question
Title: makeing a quest system in a html clicker. need help making repeatable quests and quests being done
So i have a pretty good clicker quest system in place( click/ use spells/collect stuff etc) but im having a hard to making it a reward system. The reward should only go off once then the quest should be done. how would i show the player the quest is done and continue onto the next set of quests. i want the first 2 quests to be the only ones shown until the player has a certain amount of quest points to unhide more. then i eventually want repeatable quests that would be like if numberofclicks=maxnumberofclicks gold= gold+100 then the quest would restart https://jsfiddle.net/xzyat57v/2/ this is a fiddle with all my code. at the moment the quest kind fo finishes but you keep getting 1 quest points everytime the else goes off. it should be 1 quest point once then quest finishes. having a hard time makeing it mode on.

html

```
<html>

<head>
   <title> Basic Clicker</title>
   <link rel="stylesheet" href="css/style.css" />
</head>

<body>
    <div class="nav_bar">
    <ul>
       <li id="HomeTab"><a href="GameMainWindow.html" >Home</a></li>
        <li id="SkillTreeTab"><a href="SkillTree.html">SkillTree</a></li>
        <li id="EquipmentTab"><a href="Equipment.html">Equipment</a></li>
        <li id="PetsTab"><a href="Pets.html">Pets</a></li>
        <li id="SkillsTab"><a href="Skills.html">Skills</a></li>
        <li id="QuestsTab"><a href="Quests.html"id="onlink">Quests</a></li>
        <li id="ShopTab"><a href="Shop.html">Shop</a></li>
    </ul>
</div>
<div class="main_container">
    <p>
        <html>

        <head>
            <link rel="stylesheet" type="text/css" href="interface.css" />
        </head>
        <title> Basic Clicker</title>

        <body>
            <style>
                div,
                a {
                    text-align: center;
                }
            </style>
            Quests
            <br />
            Quest Points: <span id="QuestPoints">0</span>
            <br />
            <button onclick="Clickquest1()">Click Me!</button>
            <br />
            Click 1000 times <span id="Numberofclicks">0</span> / <span id="Maxnumberofclicks">10</span>
            <br />
            Use skills 50 times <span id="Spelluses">0</span> / <span id="Maxspelluses">50</span>
            <br />
            <span id="Clickquest2">Click 10000 times <span id="Numberofclicks">0</span> / <span id="Maxnumberofclicks">10000</span>
            <br />
           <span id="Useskills2"> Use skills 100 times <span id="Spelluses">0</span> / <span id="Maxspelluses">100</span>
            <br />
            <span id="Bronzeorecollect1">Collect 100 Bronze Ore <span id="Spelluses">0</span> / <span id="Maxspelluses">100</span>
            <br />
           <span id="Shrimpcollect1"> Collect 100  Shrimp  <span id="Spelluses">0</span> / <span id="Maxspelluses">100</span>
            <br />
            <span id="Bronzeorecollect2">Collect 1000 Bronze Ore <span id="Spelluses">0</span> / <span id="Maxspelluses">1000</span>
            <br />
            <span id="Shrimpcollect2">Collect 1000 Shrimp <span id="Numberoffish">0</span> / <span id="MaxFish">1000</span>
            <br />
            Use skills 50 times <span id="Spelluses">0</span> / <span id="Maxspelluses">50</span>
            <br />
            Use skills 50 times <span id="Spelluses">0</span> / <span id="Maxspelluses">50</span>
            <br />
            Use skills 50 times <span id="Spelluses">0</span> / <span id="Maxspelluses">50</span>
            <br />
            Use skills 50 times <span id="Spelluses">0</span> / <span id="Maxspelluses">50</span>
            <br />
            Use skills 50 times <span id="Spelluses">0</span> / <span id="Maxspelluses">50</span>
            <br />
            Use skills 50 times <span id="Spelluses">0</span> / <span id="Maxspelluses">50</span>
            <br />
            Use skills 50 times <span id="Spelluses">0</span> / <span id="Maxspelluses">50</span>
            <br />
            Use skills 50 times <span id="Spelluses">0</span> / <span id="Maxspelluses">50</span>
            <br />
            Use skills 50 times <span id="Spelluses">0</span> / <span id="Maxspelluses">50</span>
            <br />
            Use skills 50 times <span id="Spelluses">0</span> / <span id="Maxspelluses">50</span>
            <br />
            Use skills 50 times <span id="Spelluses">0</span> / <span id="Maxspelluses">50</span>
            <br />
            Use skills 50 times <span id="Spelluses">0</span> / <span id="Maxspelluses">50</span>
            <br />
            Use skills 50 times <span id="Spelluses">0</span> / <span id="Maxspelluses">50</span>
            <br />
            Use skills 50 times <span id="Spelluses">0</span> / <span id="Maxspelluses">50</span>
            <br />
            Use skills 50 times <span id="Spelluses">0</span> / <span id="Maxspelluses">50</span>
            <br />
            Use skills 50 times <span id="Spelluses">0</span> / <span id="Maxspelluses">50</span>
            <br />

            <script type="text/javascript" src="main.js"></script>
            <script type="text/javascript" src="Quests.js"></script>
    </p>
</div>

```

javascript: ( i dont have alot but i would like a example for clicks, spell uses, a repeatable quest, and ore collection. i was just going to have on my mineing page later once i have the quests working if rebirths\>=5 && Questpoints\>=4 ) add to that counter.

```
var Numberofclicks = 0;
var Maxnumberofclicks = 10;
var Spelluses = 0;
var Maxspelluses = 50;
var NumberofBore = 0;
var MaxnumberofBore = 10;
var rebirths = 5;
var QuestPoints = 0;
document.getElementById('rebirths').innerHTML = rebirths;

function Clickquest1(){
    if (rebirths >=5 && Numberofclicks < Maxnumberofclicks){
        Numberofclicks = Numberofclicks +1
    document.getElementById('Numberofclicks').innerHTML = Numberofclicks;

    }else{
        QuestPoints = QuestPoints + 1
        document.getElementById('QuestPoints').innerHTML = QuestPoints;

    }
}

function Clickquest2(){
    if (rebirths >=5 && Numberofclicks < Maxnumberofclicks && QuestPoints>=1){
        Numberofclicks = Numberofclicks +1
    document.getElementById('Numberofclicks').innerHTML = Numberofclicks;
    }else{
        QuestPoints = QuestPoints + 1
        document.getElementById('QuestPoints').innerHTML = QuestPoints;

    }
    }

function CollectingOre(){
    if (rebirths >=5 && NumberofBore < MaxnumberofBore){
        NumberofBore = NumberofBore +1
    document.getElementById('NumberofBore').innerHTML = NumberofBore;
    }else{
        QuestPoints = QuestPoints + 1
        document.getElementById('QuestPoints').innerHTML = QuestPoints;

    }
    }

```

I expect when the first or any quest is complete unless it is repeatable for it to finish, give the reward once, then move onto the next quest. for example after you click 100 times for first quest it gives you a quest point then unlocks the next click quest. then it moves onto that quest. But at the moment after the quest finishes if u keep clicking it keeps adding 1 questpoint( i know why it does this but not sure how to make it do it once). I want a working quest page for the player

# Answer
> 1 votes
You need an **if statement** to check against your variable. Such as:

```
if (clickedTotal == questClickAmount){
    questPoints++;
}

```

This will insure that you will only get 1 quest point whenever you reach the correct amount.

I have another way you could easily implement click quests. I have made the changes in this jsfiddle.

I have created a **ClickableQuest** class:

```
class ClickableQuest {
    clickAmount = 10; //Default 10
    clickTotal = 0;

    elementID = "";

    constructor(clickAmount, elementID){ //Ran once you initalize class
        this.clickAmount = clickAmount;
        this.elementID = elementID
        this.UpdateDisplay();
    }

    GetQuestString(){
        return "Quest: Click 10 times. " + this.clickTotal + " / " + this.clickAmount;
    }

    Incrementer(){
        this.clickTotal++;
        if (this.clickTotal == this.clickAmount){
            QuestPoints++;
        }
    }

    UpdateDisplay(){
           if (this.clickTotal > this.clickAmount){
            document.getElementById(this.elementID).innerHTML = ""; //Hide
        } else {
              document.getElementById(this.elementID).innerHTML = this.GetQuestString()
        }
    }
}

```

If you don't know what a class is then imagine it like reusable code. Classes are objects that have variables related to it. If you wanted to make a class about a table you could have variables inside the class for how many legs, how tall is it, how wide it is etc.

When you create a new instance of this class you will need to pass it two parameters. Those are: **clickAmount** and **elementID**.

You can create a new instance with this code:

```
var tenClick = new ClickableQuest(10, "tenClickID");

```

When a new class object is made like above it runs the constructor function within the class.

You can see that it sets the class's clickAmount variable to be 10 and the class's elementID variable to "tenClickID". It also runs the class's UpdateDisplay function which uses the elementID and QuestString to update it on the screen.

The class's Incrementor function will update the clickTotal and if it is the same number as the clickAmount it will reward 1 questPoint.

I created a function called **UpdateQuest**:

```
function UpdateQuest(clickableQuest) {
    clickableQuest.Incrementer();
    clickableQuest.UpdateDisplay();
}

```

This require a quest object aka tenClick that we made above. When ever you call the function it will run the Incrementer and UpdateDisplay function in that object. I called UpdateQuest from within your button click code.

If you wanted to make a lot more click quests you could just create new quest objects like:

```
var tenClick = new ClickableQuest(10, "tenClickID");
var twentyClick = new ClickableQuest(20, "twentyClickID");
var onehundredClick = new ClickableQuest(100, "onehundredClickID");

```

Remember you have to pass each quest through the **UpdateQuest** function for it to increment.

I would recommend looking up how to make an array of objects so you can loop through each quest to increment them.

You could also create Quest objects for your other quest types just like I did.

---
Tags: javascript, html
---


# Question
Title: How to know if two surface are in the same direction?
In my code I creat a Mesh that are composed by multiple tile. those tile can have edge that are shared, and I need to know if the normal of the tile that have shared edge have the same direction, because I calculat the normal of the edge to smooth the light. before I used the Vector.Dot() , but I've sometimes two tile that have a curve that make impossible to use this function as you can see in the 4th image. and the only information that i have in the calcul is the 2 normal of the tile.

img 1 : diferent direction  img 2 : diferent direction  img 3: same direction  img 4: same direction

img 5: same direction

# Answer
Imagine applying a force along those normals to the faces. If the normals both face in the same direction (e.g. outward), then it would have a book closing effect, the faces would get closer. If they faced in different directions, it would just rotate the whole thing.

To make this a little easier to implement, you need to make it more abstract. The concept I described above is torque. Torque relies on the force (normal vector here) and the leverage (the vector from the shared edge to the center of the face here). We don't actually need to calculate torque here, but we can guess the relationship of the two normals based on these two (leverage and normal vector). Let's see an example:

The green vectors are the normals, the red is the leverage. You don't actually need the "leverage" vector to be correct, it just need to be perpendicular to the normal vector and pointing in the same direction. I'll go over this when applying it to 3d.

You can see how in the first image, to rotate the leftmost red vector so that it points in the same direction as the corresponding green (normal) vector while doing the least amount of rotation, you need to rotate it clockwise and to do the same to the other two vectors, you need to rotate that red vector counter-clockwise. On the second image however, you need to rotate both of the red vectors clockwise.

So in short, to find out whether the faces look in the same direction, you need to find the signed angle between the red and green vectors, and if they have opposite signs, they do face the same way, otherwise they don't.

In 3d this would look something like this:

1.) Pick any of the points of the shared edge (marked in orange here):

2.) Subtract the vector pointing to this position from the vectors pointing to a point that isn't part of the shared edge on each triangle to get two vectors (marked in red here):

Now use cross product on these two vectors to get the vector that's perpendicular to both (the order of the two vectors doesn't matter, just keep it consistent for the rest of the steps). The vector is marked with purple:

Based on the answer here, the signed angle as seen from the purple vector is

$$ k:={(\boldsymbol{n}\times\boldsymbol{a})\cdot\boldsymbol{b}\over ab} $$

$$ \cases{ \theta=\arccos{\boldsymbol{a}\cdot\boldsymbol{b}\over ab}, & if $k\ge0$;\\ \theta=2\pi-\arccos{\boldsymbol{a}\cdot\boldsymbol{b}\over ab}, & if $k\<0$\\ } $$

where \\$a\\$ is one of the red vectors, \\$b\\$ is the corresponding normal vector, \\$n\\$ is the purple vector and \\$\theta\\$ is the signed angle.

Get the signed angle from both pairs and if their signs are opposite (one of them is negative, the other is positive), then they face the same direction.
> 3 votes

---
Tags: geometry, 3d-meshes, normals
---


# Question
Title: Why is SpriteBatch.end() generating null pointer exception in this code?
I am getting a null pointer exception using libGDX that the debugger points as the SpriteBatch.end() line. I was wondering what would cause this.

Here is the offending code block, specifically the batch.end() line:

```
    batch.begin();

    for (int j = 0; j < 3; j++)
        for (int i = 0; i < 3; i++)
            if (zoomgrid[i][j].getPiece().getImage() != null)
                zoomgrid[i][j].getPiece().getImage().draw(batch);

    batch.end();

```

The top of the stack is actually a line that calls

```
lastTexture.bind();

```

In the flush() method of com.badlogic.gdx.graphics.g2d.SpriteBatch.

I appreciate any input, let me know if I haven't included enough information.

# Answer
> 1 votes
I know, this is old. But since I stumbled upon this issue just recently, I want to add the cause and solution in my case.

In my case this happened, because I used:

```
val background = TextureRegion()
```

This empty constructor led to a null texture when flushing the SpriteBatch, after drawing it with:

```

batch.begin()
batch.draw(background, 0f, 0f, Constant.WIDTHf, Constant.HEIGHTf)
batch.end()

```

I changed it to the following to prevent this issue:

```

if(background != null)
{
  batch.begin()
  batch.draw(background, 0f, 0f, Constant.WIDTHf, Constant.HEIGHTf)
  batch.end()
}

```

# Answer
> 2 votes
The fact that the exception points to a line in the callstack that reads

```
lastTexture.bind();

```

allows you to easily determine the cause of the exception (assuming the debug information in accurate and the call stack and exception source data is correct, which is probably a safe assumption in this case).

The only thing that be null in that line is `lastTexture`. That itself implies that the problem is that you've failed to initialize the sprite object correct, possibly failing to do something that sets up its backing texture (so it's null when you go to render the batch).

---
Tags: opengl, java, libgdx
---


title: Framerate Dependant Steering Behaviour

text:
# Question
Title: Framerate Dependant Steering Behaviour
I've been studying steering and flocking behaviors, if not directly from Craig Reynolds work on Steering Behaviors For Autonomous Characters (http://www.red3d.com/cwr/steer/). I understand the basic concepts and how to apply forces but the main issue with this is performance. Using Unity, ECS and the job system, I have been able to implement a multi-threaded implementation of some simple behaviors (seek, arrival, evade etc).

The problem is simply that all of the implementations of steering behaviors that I find are all based on this same principle and they all seem to suffer from the same problem - framerate independence. For example, a simplified example of seeking:

```
// get a vector pointing directly at our target, at the maximum speed.
desired_velocity = normalize(target - position) * max_velocity

// get the steering force direction
steering = desired_velocity - velocity

// ensure the steering force never exceeds our maximum steering force
steering = truncate(steering, max_steering_force)

// ensure the velocity never exceeds the max speed
velocity = truncate (velocity + steering , max_speed)

// apply our velocity
position += velocity * delta_time

```

When dealing with the final velocity, we are utilizing delta\_time to ensure that the velocity is applied in a framerate independent manner. But the steering force is not framerate independent at all. If this was running at 120fps, the steering would reach it's maximum velocity much faster than if the game was running at 30fps.

Is there something more I should be doing here. I've experimented with using delta\_time with the steering, but that seems to make little difference.

# Answer
Yes, we can do better. We need a maximun steering per unit of time.

```
// get the steering direction
steering = desired_velocity - velocity

// ensure the steering never exceeds our maximum steering per unit of time
steering = truncate(steering, max_steering * delta_time)

// ensure the velocity never exceeds the max speed
velocity = truncate (velocity + steering, max_speed)

```

That is essentially a cap on acceleration.

Of course, you would have to tweak `max_steering` for this to reflect the behaviour you want.

---

I had a look at OpenSteer, it does something similar to what I put above. Actual source (not sure if I was reading in the worng place, but that is the result that came up):

```
// Euler integrate (per frame) acceleration into velocity
newVelocity += _smoothedAcceleration * elapsedTime;

// enforce speed limit
newVelocity = newVelocity.truncateLength (maxSpeed ());

```

So, you see, it is similar to:

```
newVelocity = newVelocity + _smoothedAcceleration * elapsedTime;

newVelocity = truncate(newVelocity, maxSpeed())

```

Which is the same as:

```
newVelocity = truncate(newVelocity + _smoothedAcceleration * elapsedTime, maxSpeed())

```

Alternatively, if you prefer:

```
steering = _smoothedAcceleration * elapsedTime;

newVelocity = truncate(newVelocity + steering, maxSpeed())

```

Which is basically what I am suggesting. Evidently `_smoothedAcceleration` is doing some of the work. In fact, given that this steering "force" does not deal with mass, I suggest to start thinking of it in terms of acceleration.

**Addendum**: Looking a bit more on the context of the code, they take the force, they truncate it, then divide by mass to get acceleration, then they dampen the acceleration (they seem to be aplying it over time) to get the `_smoothedAcceleration`.
> 3 votes

---
Tags: unity, steering-behaviors
---


# Question
Title: Windows 10 GPU Engine Performance Counters - Phys / Eng Meaning
For performance tracing of intermittent degredation in performance I wanted to use the Performance Counters available in Windows 10 1809 under GPU Engine -\> Utilization percentage. This particular laptop has NVIDIA GeForce GTX 1050 with 4 GB VRAM + 16GB shared memory.

The instance names look like this:

pid\_1388\_luid\_0x00000000\_0x00011372\_phys\_0\_eng\_8\_engtype\_Compute\_1 pid\_912\_luid\_0x00000000\_0x00010F5C\_phys\_0\_eng\_2\_engtype\_Copy

While I know pid\_xxxx is the process identifier, what I am trying to work out the meanings of remaning components.

1) luid\_xxxx\_xxx

In my case all instances start with luid\_0x00000000 and have 3 different endings:

* 0x00010F5C
* 0x0001134D
* 0x00011372

2) Next is phys\_0, I assume this is first physical GPU, but I want to be able to programatically translate it to GPU adapater name.

3) Eng\_x, on my machine this ranges from 0-12

4) Eng\_type have the following. While mostly self explanatory, is the difference between Compute\_0 and Computer\_1 different cores on the GPU

* 3D
* Compute\_0
* Compute\_1
* Copy
* GDI
* Render
* Graphics
* LegacyOverlay
* Security
* VideoDecode
* VideoEncode
* VideoProcessing
* VR

# Answer
> 2 votes
> 1) luid\_xxxx\_xxx

These appear to be locally-unique identifiers. They're 64-bit values that are unique within the scope of the machine they're generated one.

> Next is phys\_0, I assume this is first physical GPU but I want to be able to programatically translate it to GPU adapater name.

That seems correct to me. You should be able to use your 3D API of choice to enumerate the physical adapters available and correlate those with these counters in order to get a name for them, if you like.

> Eng\_x

This looks like an "engine" index. See below.

> 4) Eng\_type have the following. While mostly self explanatory, is the difference between Compute\_0 and Computer\_1 different cores on the GPU

This identifies the type of GPU engine; a GPU engine is distinct unit of silicon that runs in parallel with others on the CPU. There are two compute engines on that GPU. GPU engines *are made up of* cores, they are not the same as cores.

---
Tags: performance, windows, gpu, debugging
---


title: How to decrease the size of a distance?

text:
# Question
Title: How to decrease the size of a distance?
I made a code for the character to be teleported to the place where the mouse cursor is, if the distance is less than or equal to 350.

**Blueprint:**

I happen to wish that if the distance were greater, the character teleported to the equivalent point of the line (distance between character and mouse cursor) of 350.

**What I would like to know how to do:**

I've thought about using the **Line Trace by Channel**, but I can not think of how to decrease the value of a distance and find the equivalent point in a line (vector value).

---

**EDIT 1 (attempt based in Ocelot comment)**

**Blueprint:**

**Result in game:**

Now the character teleports to a point that seems to have reference to the center of the level. I tried to add this vector to the character's position, but I did not get the desired result.

**PS** \- *The print of the word "Hello" on the screen indicates how many times I clicked on the teleportation key in the last 2 seconds.*

# Answer
"Mouse line up to the mouse cursor" is a vector, and vector could be normalized. Normalized vector is a vector of length 1. What this gives to us is that we can scale it to any length we want.

Simply normalize your character-to-mouse vector and multiply it by your range, that's the solution.

**You should do the following steps:**

* character position **-** mouse position
* normalize the result
* normalized value **x** 350
* character position **+** normalized value already multiplied

**In blueprint (in the case of the question) it looks like this:**
> 1 votes

# Answer
Not sure about blueprints but this is how i do it.

```
vector3 GetCoordInFrontOfGameplayCam(float Range)
{
    vector3 GameplayCamRot = GET_GAMEPLAY_CAM_ROT(2);//pitch,roll,yaw
    vector3 GameplayCamCoord = GET_GAMEPLAY_CAM_COORD();
    float Tan = Range * COS(GameplayCamRot.x);
    return Vector3(Tan * SIN(-GameplayCamRot.z) + GameplayCamCoord.x, Tan * COS(-GameplayCamRot.z) + GameplayCamCoord.y, Range * SIN(GameplayCamRot.x) + GameplayCamCoord.z);
}

```
> 1 votes

---
Tags: unreal-4, blueprints, direction, localization
---


# Question
Title: How can I easily create/edit a level for a scrolling shooter game?
I've been asking this question over the years many a time, but I still haven't found an answer when i search for one. Now I have slightly more knowledge of how programming is done and want to start making some full games.

I want to start with a side scrolling shooter (space style like R-Type/Gradius). I have many ideas in my head for good levels, and i even have some basic 3d skills in Maya/Blender to make the assets, but I do not know how best to formulate the levels. Lets say the space shooter has 30 levels. Each level might have about 10-15 enemy types and a boss on some levels. How best to store the location of all the enemies? (Same scenario for all the background objects,obstacles, powerup locations etc.)

**Is there a better way than manually building the whole level in a Unity Scene editor view?** Another way I have tried is to set spawn positions for every single object as a Vector2 or similar in XML or JSON, but how i did it that seemed even harder to make the levels than just inside the editor (not even accounting for having to write the functionality to get the data from the textfile).

# Answer
The reason you might not find any good literature about this subject is because the best solution always depends on the game, its architecture, its scope and your team's preferred workflow.

Possible options are:

* Hardcode your levels. Crude and hard to maintain, but a simple and effective solution for small games or proofs of concept.
* Create it in Unity using the Unity scene editor
* Create it in Unity, but use editor scripting to add some functionality to the Unity editor which helps you with building levels. This ranges from custom inspectors to editor-only behaviours to completely new editor UIs running in their own windows.
* Create your level in Unity as a Timeline asset. Levels in scrolling SHMUPs are usually just a series of chronological events, so you might be able to represent a level as timeline. (Disclaimer: I never tried this, but it sounds like it could be a good idea *in theory*)
* Make up a file format which might or might not be based on a markup language like JSON or XML and:
    + Edit it with a text editor
    + Create a visual level editor as a stand-alone executable
    + Create a visual level editor as part of your game.
* Make use of procedural generation. Only define a few basic parameters for each level and create the actual content of the level with an algorithm.
> 3 votes

# Answer
Currently I know only of two ways.

pre-defined

If your levels are limited and should always (basically) be the same then you are good to go to create the levels with as Unity scene. 30 levels, 30 scenes. If you don't use Unity scenes and store pre-defined levels in a different format they are still pre-defined.

procedural

If you are looking for some infinite runner type you will need to create the objects dynamically/procedural using scripts or code. Here you can define patterns (e.g. enemy formations) as prefabs and instantiate them from your script.
> 2 votes

---
Tags: unity, game-design, level-design, side-scroller, levels
---


title: wglCreateContextAttribsARB is undefined

text:
# Question
Title: wglCreateContextAttribsARB is undefined
I've just downloaded the latest headers from the OpenGL registry and included them in my project. I am attempting to create an OpenGL 3+ context. Every tutorial/resource has used wglCreateContextAttribsARB to do this. However, this does not seemed to be defined in the headers I have.

```
#include <Windows.h>
#include <gl\GL.h>
#include "glcorearb.h"
#include "glext.h"
#include "wglext.h"
...
wglCreateContextAttribsARB = // Not recognised
(PFNWGLCREATECONTEXTATTRIBSARBPROC) wglGetProcAddress("wglCreateContextAttribsARB"); // Recognised (Why this and not the function name?)

```

The closest existing function is wglCreateContext, which I don't believe is what I want.

In the wglext.h header, there is this though:

```
typedef HGLRC (WINAPI * PFNWGLCREATECONTEXTATTRIBSARBPROC) (HDC hDC, HGLRC hShareContext, const int *attribList);
#ifdef WGL_WGLEXT_PROTOTYPES
HGLRC WINAPI wglCreateContextAttribsARB (HDC hDC, HGLRC hShareContext, const int *attribList);
#endif

```

And that can get me the function, but is defining WGL\_WGLEXT\_PROTOTYPES really the "correct" way to do what I want?

I haven't been able to find any information on the issue, what is the correct procedure? And where can I find information on changes/problems like these?

I'm not interested in using any extension loading libraries such as GLEW to handle this.

Thanks.

# Answer
> 0 votes
You have to define that function pointer yourself. It doesn't exist in the OpenGL implementation that ships with Windows and this is why you have a problem on that line labeled `// Not recognised`.

### At the very least, you need something to the effect:

```
PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB =
  (PFNWGLCREATECONTEXTATTRIBSARBPROC) wglGetProcAddress("wglCreateContextAttribsARB");

```

But be aware that you have to create and destroy a render context just to load and use this extension. It is rather convoluted considering the whole point of this extension is to create a render context. That's just how WGL works unfortunately.

# Answer
> 1 votes
your trying to find that EP(entry point) - and its also in GLX(linux)...

PGLXContext:^GLXCREATECONTEXTATTRIBSARBPROC;
GLXCREATECONTEXTATTRIBSARBPROC=procedure (PDisplay, Fbc, ctx, Bool, intPtr);

I believe is the correct Pascal translation.
GLX\_Context cant be an assigned anything AND something else...In the C- it appears to be.

---
Tags: opengl, windows
---


# Question
Title: Where is the part of the code of the mouse click in the TopDownCharacter blueprint?
I have a project where by pressing the **B key**, the character after a time interval is teleported to a point on the map.

I can do this. It turns out that I imposed conditions so that at the end of the time interval the teleportation would be executed successfully.

**For example:**

* Pressing the **D key** prevents the teleportation from happening.
* Character moves around

It is as if the character must be meditating/channeling/motionless.

**To do this correctly I use 2 variables:**

* varCanalizando =\> becomes true if the **B key** is pressed / becomes false if the **D key** is pressed or the character walks.
* varInterrompeu =\> becomes true if varCanalizando is true and **D key** is pressed or the character walks.

Pressing the **D key** will cancel the meditating/channeling/motionless and the character will not teleport at the end of the time interval.

***I can not identify the part of the blueprint that makes the character walk.***

But I say almost certainly, that it's not in the TopDownCharacter default code.

**The closest I got to something related to the mouse in the blueprint:**

**I suspect it may be in some of the TopDownCharacter components and I've tried something related based on this post:**

https://forums.unrealengine.com/development-discussion/blueprint-visual-scripting/1455206-on-mouse-click-event-won-t-work

**My attempt:**

I consider it pertinent to inform that I have modified the standard click button from left to right, but I do not know if that is the cause of the problem.

**I looked for the event in the component of the character that I found most suspicious, but none of them seems to me correct:**

---

**EDIT 1 (attempt)**

**I tried using the Right Button Mouse, but neither the print worked:**

# Answer
On your character blueprint, there's a movement component which is where all movement is handled. You have two options:

1. There is a blueprint node called "Get Velocity" which returns a vector. Use this then call Vector length from it like so.

You can now use a branch to check whether the value is greater than 0 and set varInterrompeu to true.

2: Create a new Vector variable in your character blueprint.

OnTick, check your actor location. If it is not equal (false) to the value of the vector variable, set the new location to this variable and set the varInterrompeu boolean to true.

If it's true, do nothing.
> 1 votes

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


# Question
Title: My GameObject keeps spawning when it shouldn't
I'm trying to instantiate a new gameObject when the current gameObject gets to a select point. The problem comes when the program gets to the second if() statement. It sets the floorsSpawned to 1 and when it does, the game object instantiates a bunch of times. Shouldn't the floorSpawned be set to 2 in the first if() statement and only instantiated once?

```
public class FloorMovement : MonoBehaviour
{

    public GameObject floor;
    [SerializeField] int speed = 10;
    public int floorsSpawned = 1;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        transform.Translate(Vector2.left * Time.deltaTime * speed);

        if (transform.position.x <= -18.0 && floorsSpawned == 1)
        {
            floorsSpawned = 2;
            Instantiate(floor, new Vector2(11.5f, -2.0f), Quaternion.identity);
        }

        if (transform.position.x <= -40.25 && floorsSpawned == 2)
        {
            floorsSpawned = 1;
            Destroy(floor, 3);
        }
    }
}

```

# Answer
What happens:

1. Your object state is (x = -10, floorsSpawned = 1)
2. You object moves to the limit of the first if (state: x = -18.1, floorsSpawned = 1) and the first object is instantiated (floorsSpawned becomes 2)
3. You object keeps moving to reach the second if (state: x = -40.26, floorsSpawned = 2), the object gets destroyed and floorsSpawned becomes 1

Now your problem on the next frame(s)

x is still smaller than the value in the first if ( x \<= -18.0) and since floorsSpawned = 1 the object gets created and floorsSpawned is set to 2

On the next frame you are most likely smaller than the value in the second if (x \<= 40.25)....

and so it repeats

The solution depends on the desired behaviour and how the object moves (can it move only along -x or both -/+ x)

* introduce ranges in the ifs (e.g.)

if (transform.position.x \<= -18.0 && transform.position.x \> -40.25 && floorsSpawned == 1)

* if it shouldn't be spawned any more (so only once) you could set floorsSpawned to 3 in the second if
> 1 votes

# Answer
If transform.position.x is lower than -40.25, on the same frame you are instantiating and destroying the gameobject. First not solution: Use and else-if for avoiding do the 2 things at the same frame.

Second thing: Why the object is not being destroyed at the second if. You are destroying the non-instantiated prefab gameobject, not the instantiated one 3 instruction lines above. Cache the instantiated gameobject somewhere for destroying it later.

Anyway, with that 2 "solutions" in one frame you will create the go and at the next frame you will send the Destroy instruction to that go, and the engine will destroy it when it wants (its destroy, not immediatedestroy).

There is no real solution, you will have to rethink that method.
> 0 votes

---
Tags: unity, gameobject, spawning
---


# Question
Title: How game engines generate single executable games?
I was taking a look at Cryengine's and Unreal's code and when built both engines generates lots of dlls. Inside Cryengine's System code I could see that it calls LoadLibrary to load the dlls and Initialize the modules.

Ex:. LoadLibrary("CryPhysics.dll")

But when you see Cryengine's or Unreal's deployed games they have only a single big .exe and no first-party dlls. In Crysis 3 Bin32 directory there is only Crysis3.exe and some third-party dlls, there is no CryPhysics.dll for example.

How do they achieve that? How can the LoadLibrary work without those dlls?

PS:. There is no #if wrapping the LoadLibrary to differentiate Debug from Release mode

# Answer
> 2 votes
Generally, game engines that do this support two build modes: building with components as DLLs, and building with the components compiled directly in to a monolithic executable. This is definitely the way that Unreal achieves it, and there are preprocessor directives and similar execution path branches that simply cause the game not to try to load any DLLs in the monolithic case, since the desired code and data is already there.

I can’t speak to how CryEngine specifically handles it, but I’d feel pretty confident saying it’s similar.

# Answer
> 2 votes
DLLs can be packaged in an archive format (PAK, ZIP, BIN, etc) along with other game assets, extracted to a temporary directory on startup, and loaded from there - so have a look for the other supporting files that come with the game, and you're likely going to find a large one which is this archive file.

The primary advantage of this kind of approach is that the game's distributors get to retain a measure of control over these DLLs, which can help to deter casual hackers.

---
Tags: c++, unreal-4, visual-studio, dll, cryengine
---


# Question
Title: FPS Character Controller movement - Any value in reverse engineering movement formulas?
From what I know character movement in popular FPS games tend to be non-linear, but the easing curves change between games as each has its own signature formula.

Typically I imagine the physics engine would provide the feel by adding acceleration, deceleration and attrition.

Most basic games have a simple linear start-stop movement.

Is there any value in reverse engineering the "signature" formulas for these games, or are these openly known and available to everyone?

Also if these are well known where can I read upon the different implementations by these AAA FPS games?

# Answer
> 0 votes
---

## Head bobbing

**Stylized**

Starting from a position in the world and then picking an animation based on that position and movement makes sense from a software engineering stand point. After all, the animation is – mostly – just a visual concern.

This approach will allow for more freedom in animation. And that is good if you want stylized – not so realistic – animation, useful to convey character personality, which is something you want in order to have multiple distinct characters that remain recognizable even in first person.

With this approach, you implement head bobbing by moving the camera (sometimes even independently of the body animation), the animator will come up with some motion curves for that. That is one think to tweak! Head bobbing, plus some sound effects will convey that the character is calm or agitated, for example.

*Many tutorials will have you start with a capsule collider with a camera attached to it ✳cough✳ Unity ✳cough✳, and then animation is attached afterwards. That means that the camera is not attached to the animation, which leads well to this approach.*

A drawback of imposing head bobbing this way is that it is hard to get right. In fact, it can even be a bad gaming experience if the animation affects your aim. You can stabilize it by rotating to whatever object the player is aiming at (so that head bobbing does not make the player aim to something else). However, that is one more thing to tweak! Do not stabilize the aim for a character that does not have much experience with weapons, for example.

References:

---

**Realistic**

On the second approach you attach the camera to an animated model, which ideally comes from motion capture. That is what you want if you are going for realism.

The first problem you encounter is that the animation – even if they are from motion capture – will move the head around too much to feel right. In this case you need to start thinking of camera stabilization. The first thing to get right is turning the camera to compensate the rotation of the head (just like we can rotate the eyes to compensate the rotation of the head), in such way that it locks on where the player is aiming. The second part is translation, and that would be done by imposing inverse kinematics on the model.

References:

---

## Animation selection

**Realistic**

The state of the art is skeletal animation with a blend-space. Usually a the blend-space is 2D, sometimes 1D, 3D is possible but not common. On it, certain points are mapped to certain animations at animator discretion... and each axis of the blend-space are mapped some variables. For example, you can have horizontal and vertical speed for movement, and different points in the blend-space are for walking, running, walking side ways, walking backwards, etc...

There can then be a weighted blend of these blend-spaces a cross the skeleton. For example one blend-space handles legs for walking and running, and another blend-space handles the arms for aiming.

Finally on top of that inverse kinematics tweaks the positions, for example making sure the foot contact the ground, and that the weapon aims where the players wants to, and – as mentioned above – stabilizing the head.

References:

---

**Stilyzed**

The alternative to skeletal animation, would be to use key-frame morph target animation. There you animate by picking the next key-frame and interpolating... that is about it.

Inverse kinematic is completely different here. Instead of trying to work out how to move the non existing bones, it is about picking key-frames depending on the surrounding and squash and stretch.

Speaking of squash and stretch, morph target animation is what you want for a cartoon like look, which is hard to get with skeletal animation. Which also means that it is likely that you won't be caring too much about precision of the animation.

---

References:

---

**Extra**: On the Animation of DOOM (2016): Bringing Hell to Life: AI and Full Body Animation in 'DOOM'

# Answer
> 1 votes
> Is there any value in reverse engineering the "signature" formulas for these games

Fine-tuning the easing curves and such used in a game is often a highly iterative process that's fairly specific to the particular game being developed and how the creators want it to "feel."

The *precise* formula used for one game make not make sense for another, even if you are trying to *emulate* the feel of the first game for the second, because the feel of the camera control (et cetera) comes from more than just some the coefficients on some damping function. The way the camera (3rd person) or character (1st person) slides around collision objects, the nature of the collision geometry, the filtering applied to the sticks or mouse input before it reaches the camera system, the animations triggered in response... all of those (and more) impact that final sensation of control, sometimes in fairly subtle ways.

Consequently, I would argue that it's *not* worth the time reverse-engineering the particular formulas used by other games. They're probably not even particularly clever or magical. Further, the time and effort you'd spend doing so, if you take the simple and obvious approach, is *essentially* going to be the same as just trying to fine-tune your own curves and control systems.

I would advocate that you try to emulate a particular feel if you like, but focus on iterating towards and playtesting that feel. Don't focus on extracting a particular algebraic formula used somewhere in some other game's code. Focus on *your* game's camera and the context in which it operates.

> or are these openly known and available to everyone?

The general family of such functions is fairly well known, and if you're interested in a good place to browse the broad-strokes options, you can check out easings.net.

---
Tags: physics, movement, character, first-person-shooter
---


# Question
Title: How do I use trigger colliders in Unity?
I am trying to create a "Fruit Ninja" style game in Unity in VR. I have a BoxCollider on my sword set to "Trigger" and I have some "fruit" objects coming towards it. I then have this function:

```
void OnTriggerEnter(Collider other)
{
    Destroy(gameObject);
    Destroy(other.gameObject);
}

```

I've tried applying this script to the sword and to the objects, but nothing is destroyed.

In the documentation, there is also a note of "Trigger events are only sent if one of the Colliders also has a Rigidbody attached", but I've attached a Rigidbody to the objects.

# Answer
> 1 votes
Can't write a comment, so I will give you my pointers.

You should not apply that script to every object, you're basically destroying both the sword and the fruits. I think you should only place your script in the sword and only destroy the collided object. Thus, your script will change to the following :

```
void OnTriggerEnter(Collider other)
{
    Destroy(other.gameObject);
}

```

Basically, it will destroy every object entering in contact with your sword. Furthermore, if you want more liberty, you can change the tags of your objects and make sure to only destroy objects tagged as fruits or even have different effects. For example:

```
void OnTriggerEnter(Collider other)
{
    if (other.tag == "Fruit")
    {
        playerPoints++;
    }
    else
    {
        playerPoints--;
    }
    Destroy(other.gameObject);
}

```

Best of luck in your development!

---
Tags: unity, collision-detection, rigidbody
---


title: Game loop inside libGDX game loop

text:
# Question
Title: Game loop inside libGDX game loop
I have the main game loop in libGDX. On the `touch()` event I want an animation to be executed. So I will have a variable which will store the value which will be updated each frame and further rendered side by side each frame.

The problem: I want an another animation to take place after the first one finishes. How do I update variable to do so? Because it should take place after first. I can't place two statements in loop one after another. Is there a way to create an another game loop inside first so that when inner runs the outer is paused?

# Answer
> 1 votes
You would usually use an explicit state machine for that. The idea is that you have a variable that stores the current state (say: animation A). And when that animation finishes you update the state variable to a new state (say: animation B).

Then, in your loop, when playing animations, you have a switch satement that selects a case depending on the state variable, and then that case handles the logic for that state.

---

There are more advance solutions, of course. You might create your state machine as a tree, where each state has sub-states. You may represent them as data (they are not a bunch of switch statements, but dictionaries). Or you could use full-fledged behavior tree.

Alternatively, you might also use coroutines. A common trick is to implement them as iterators (each loop you pull a new item, and the logic is in the iterator), then you can build an implicit state machine around them.

And of course, you can mix and match. For example, have a state machine that picks a behavior tree.

There are also libraries that help you implement all that, you may want to have a look around. *I do not really develop in Java. So, I can’t really recommend.*

---
Tags: libgdx, game-loop
---


title: Two Points Rotating Around Circle?

text:
# Question
Title: Two Points Rotating Around Circle?
Currently I am working on a 2D game just like duet game, it is my first game (Unity 2D).

When I press left key both points rotate fine. But when I press right, the points are not rotated.

So my problem is why do both points rotated only in one direction

Code:

```
public class TouchControll : MonoBehaviour
{
  float movespeed = 3;
  float angle = 45;

  void Update()
  {
    if (Input.GetKey(KeyCode.LeftArrow))   // when i m press leftarrow both point should be rotate fine
    {
        transform.Rotate(Vector3.forward * Time.deltaTime * Input.GetAxis("Horizontal") * angle * movespeed);
        Debug.Log("moveleft");
    }

    if (Input.GetKey(KeyCode.RightArrow))  // problem is here when i m press right arrow key both point are not rotated
    {
        transform.Rotate(Vector3.forward * Time.deltaTime * Input.GetAxis("Vertical") * angle * movespeed);
        Debug.Log("moveright");
    }
  }
}

```

Output:

**create a empty gameobject**:  **first circle**  **second circle**

# Answer
> 0 votes
You code does not seem right for Android.

* `Input.GetKey` in intended to work with a **physical** keys (see How i can control button input android?). Instead you probably want to work with touch input. See `Input.GetTouch`.
* I have no idea what you are mapping at `Input.GetAxis("Horizontal")` and `Input.GetAxis("Vertical")`, however I would expect to use a single axis for rotation in both directions. Perhaps `Input.GetAxis("Vertical")` is mapped to nothing and that is why it does not work.

If you want your second case to have rotation in the opposite direction to the what you have on the first case, I would suggest to have exactly the same code, but use `-angle` instead of `angle`.

---

**Addendum**: This is an example of what I mean:

```
void Update()
{
    if (Input.GetKey(KeyCode.LeftArrow))
    {
        transform.Rotate(Vector3.forward * Time.deltaTime * Input.GetAxis("Horizontal") * angle * movespeed);
        Debug.Log("moveleft");
    }
    if (Input.GetKey(KeyCode.RightArrow))
    {
        transform.Rotate(Vector3.forward * Time.deltaTime * Input.GetAxis("Horizontal") * -angle * movespeed);
        Debug.Log("moveright");
    }
 }

```

In this case both are on the "Horizontal" axis, which I am assuming you need there. However rotation on one direction uses `angle` and for the opposite direction it is `-angle`.

*I want to reiterate that they are both using `Input.GetAxis("Horizontal")` in the example above.*

---

Two other ideas:

* It is common to have `Input.GetAxis("Horizontal")` mapped left and right keys. Which means that you would implement this with a single block:

```
void Update()
{
    if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.RightArrow))
    {
        transform.Rotate(Vector3.forward * Time.deltaTime * Input.GetAxis("Horizontal") * angle * movespeed);
    }
 }

```

Why? Because it is the axis that handling the direction of the rotatiton.
* Alternatively, you may not want to use axis at all (try and see if that works for you the way you want):

```
void Update()
{
    if (Input.GetKey(KeyCode.LeftArrow))
    {
        transform.Rotate(Vector3.forward * Time.deltaTime * angle * movespeed);
        Debug.Log("moveleft");
    }
    if (Input.GetKey(KeyCode.RightArrow))
    {
        transform.Rotate(Vector3.forward * Time.deltaTime * -angle * movespeed);
        Debug.Log("moveright");
    }
 }

```

---

It is also possible that what you need to do is to remap the axis you have. You can do that in the Input Manager, go to the menu Edit \> Project Settings \> Input. There you can find the defined axis and map them to what you want.

See also Beginner Unity Basics #14 - Input Manager.

---
Tags: unity, 2d, mathematics, rotation
---


title: Physics.CheckSphere is not working

text:
# Question
Title: Physics.CheckSphere is not working
I try to use Physics.CheckSphere to check if a coordonate is empty. I use three for loop to cycle threw a 2 x Y x 2 chunk. The problem is that it return true if the corner is touching the coordonate

and its actually not even touching it, since I use a 0.5 sphere radius: if(Physics.CheckSphere(new Vector3(x,y,z), 0.5f) == false)...

(by the way the white cubes you can see on the picture is only to visualize where it detected empty space, they dont have any collider enabled)

and the chunks have a mesh collider, so why is it returning true when its no even touching it ?

if(Input.GetKeyDown("i")) {

```
for(int y = 0; y <= amp + 3; y++)
{
    for(int x = 0; x <= chunkSize - 1; x++)
    {
        for(int z = 0; z <= chunkSize - 1; z++)
        {
            if(Physics.CheckSphere(new Vector3(Mathf.Round(x),Mathf.Round(y),Mathf.Round(z)),0.5f) == false)
            {
                Instantiate(grass,new Vector3(x,y,z), Quaternion.identity);
                dontPlaceHere.Add(new Vector3(x,y,z));
            }
        }
    }
}
}

```

# Answer
> 1 votes
If you want to stop the 'kissing' from triggering a detection, you'll need to make sure it doesn't kiss.

Use a smaller detection radius. DMGregory points out that `0.49999997f` would work.

```
            if(Physics.CheckSphere(new Vector3(Mathf.Round(x),Mathf.Round(y),Mathf.Round(z)),0.49999997f) == false)

```

---
Tags: unity, physics, mesh
---


# Question
Title: Coroutine constantly updating animator transition
I have a problem for a while now and I am running out of ideas: I have a made a coroutine used to implement animations in the attacks, something like this

```
private IEnumerator FirstAttack()
    {

        comboCounter = 1;
        myAnimator.SetInteger("comboSequence", comboCounter);
        currentState = PlayerState.attack;
        yield return null;

        yield return new WaitForSeconds(AttackTemplate.SetDuration(0.9f));
        comboCounter = 0;
        myAnimator.SetInteger("comboSequence", comboCounter);

        currentState = PlayerState.walk;

    }

```

This coroutine works perfectly fine. The problem occurs when I try to concatenate this with another coroutine to perform something like a combo sequence; to do so I basically add a while cycle that checks if I am pressing the attack button while there is a time opening for the second attack to connect. The result is this:

```
private IEnumerator FirstAttack() {

        comboCounter = 1;

        myAnimator.SetInteger("comboSequence", comboCounter);

        currentState = PlayerState.attack;
        yield return new WaitForSeconds(AttackTemplate.SetDuration(0.6f) - comboTimer);//Problem: if i reduce the time below the animation time of the second animation, the second animation won't go until the end

        StartCoroutine(IntervalCounter());
        comboCounter = 0;
        myAnimator.SetInteger("comboSequence", comboCounter);
        currentState = PlayerState.walk;

    }

    private IEnumerator SecondAttack()
    {

        comboCounter = 2;
        myAnimator.SetInteger("comboSequence", comboCounter);
        currentState = PlayerState.attack;
        yield return null;

        yield return new WaitForSeconds(AttackTemplate.SetDuration(0.9f));
        comboCounter = 0;
        myAnimator.SetInteger("comboSequence", comboCounter);

        currentState = PlayerState.walk;

    }

    private IEnumerator IntervalCounter()
    {
        comboTimer = AttackTemplate.SetComboTimer(0.4f);
        while (comboTimer >= 0)
        {
            Debug.Log(comboTimer);
            comboTimer -= Time.deltaTime;
            if (Input.GetKeyDown(KeyCode.Mouse0))
            {
                Debug.Log("Chained");
                StartCoroutine(SecondAttack());
                yield break;
            }
            yield return null;
        }

    }

```

My problem is that after adding the while loop the transition to the first animation keeps being updated, to be precise the one going from *Any State* to *Basic Attack Tree* in the following image.

If I press the attack button this transition will be repeated as long as the coroutine working. I tried to wrap around the first two lines in which i set the animator to do nothing if the integer managing the combo sequence, `comboCounter` is already set to 1 (which is the value related to the first attack), like this

```
        if (comboCounter != 1)
        {
            comboCounter = 1;
            myAnimator.SetInteger("comboSequence", comboCounter);
        }else if(comboCounter == 1) {

        }

```

But it keeps repeating. I wanted to use something like WaitUntil, but I tried just to put it and having a bool always false, in order to suspend the coroutine indefinitely, but in that period it **keeps updating the animator**. Do you have any ideas why is that? How do I prevent a coroutine from running all the time?

# Answer
I find that OO and state machines tend to produce spaghetti code and blocks like this can be quite hard to understand. Rewriting it as pseudocode in a functional style, we can architect the flow of states a bit better - An input should trigger the first attack which should trigger waiting for a second attack window which should allow for the combo to continue:

```
        bool canCombo = false;
        void onAttackInput()
        {

            //if we should begin the first attack
            if (comboCounter == 0)
            {
                myAnimator.SetInteger("comboSequence", comboCounter);
                currentState = PlayerState.attack;

                //in 0.6 seconds, will be able to combo
                wait(0.6f, () =>
                 {
                     canCombo = true;
                     //in 0.3 seconds, combo window could be gone
                     wait(0.3f, () =>
                     {
                         //if no combo input happened, reset
                         if (comboCounter == 1)
                         {
                             canCombo = false;
                             comboCounter = 0;
                             myAnimator.SetInteger("comboSequence", comboCounter);
                             currentState = PlayerState.walk;
                         }
                     });

                 });
            }
            //if we should begin the second attack
            if (comboCounter == 1 && canCombo)
            {
                myAnimator.SetInteger("comboSequence", comboCounter);
                currentState = PlayerState.attack;

                //in 0.9 seconds, attack ends
                wait(0.9f, () =>
                {
                    comboCounter = 0;
                    myAnimator.SetInteger("comboSequence", comboCounter);
                    currentState = PlayerState.walk;
                });
            }

            //on any input, check if an input is valid and increment the combo counter
            if (canCombo)
            {
                canCombo = false;
                comboCounter++;
            }
        }

```

But in C# you can't use yield with lambdas ()=\>, so this mythical wait() function really needs to be StartCoroutine() and the lambda should be its own function with a yield WaitForSeconds() at the top:

```

        bool canCombo = false;
        private IEnumerator onAttackInput()
        {

            //if we should begin the first attack
            if (comboCounter == 0)
            {
                myAnimator.SetInteger("comboSequence", comboCounter);
                currentState = PlayerState.attack;

                StartCoroutine(FirstAttack());
            }
            //if we should begin the second attack
            if (comboCounter == 1 && canCombo)
            {
                myAnimator.SetInteger("comboSequence", comboCounter);
                currentState = PlayerState.attack;

                StartCoroutine(SecondAttack());
            }

            //check if an input is valid and increment the combo counter
            if (canCombo)
            {
                canCombo = false;
                comboCounter++;
            }
        }
        private IEnumerator FirstAttack()
        {
            //in 0.6 seconds, will be able to combo
            yield return new WaitForSeconds(0.6f);

            //0.6 seconds later, open the combo window
            canCombo = true;
            StartCoroutine(FirstAttackWindow());
        }
        private IEnumerator FirstAttackWindow()
        {
            //in 0.3 seconds, end the combo window
            yield return new WaitForSeconds(0.3f);

            //0.3 seconds later, reset if not in next attack
            if (comboCounter == 1)
            {
                canCombo = false;
                comboCounter = 0;
                myAnimator.SetInteger("comboSequence", comboCounter);
                currentState = PlayerState.walk;
            }
        }

        private IEnumerator SecondAttack()
        {
            //in 0.9 seconds, attack ends
            yield return new WaitForSeconds(0.9f);

            //0.9 seconds later
            comboCounter = 0;
            myAnimator.SetInteger("comboSequence", comboCounter);
            currentState = PlayerState.walk;

        }

```

Comparing the two sets of code, it looks like your analysis of if(comboCounter != 1) is correct and it's not stopping the rest of the function(including comboCounter = 0;) from happening. You can't really stop coroutines indefinitely, it's better to make sure that they only do what they need to do, and run only when needed, instead.
> 1 votes

---
Tags: unity, coroutines, animation-states, animator
---


# Question
Title: animationClip.SampleAnimation() does not result in visible changes
Here is the relevant code snippet:

```
public class AnimatedGameObject : MonoBehaviour
{
    private float extentPlayed;

    public AnimationClip Clip;
    public GameObject AnimationTarget;

    private void Update()
    {
        if (this.extentPlayed >= 1f)
        {
            return;
        }

        Debug.Log(this.extentPlayed);

        this.Clip.SampleAnimation(this.AnimationTarget, extentPlayed * this.Clip.length);
        this.extentPlayed += 0.005f;
    }
}

```

In the Unity Editor, the game object assigned to `AnimationTarget` contains the animator component controlled by the controller that uses `Clip`.

However, when I start the game, even though I can see that `this.extentPlayed` is being incremented every frame, no animation is taking place that I can see.

I am aware that what I am currently trying to do in the `Update()` method can be achieved by calling `SetBool(string name, bool value)` on the animator, but the purpose of writing the `Update()` method this way is to gain familiarity with how the `SampleAnimation()` method works, so that I can perform more complicated manipulations when necessary.

What changes should I make for the animation to take place?

# Answer
Just leaving this in case it is relevant to someone:

You can't use SampleAnimation for sampling a sub-object of an animation. You have to sample the whole object (the parent object).

For example: If you got a character waving animation, you can't sample just the hand. You need to sample the whole character.
> 1 votes

# Answer
I recently had a problem where a GameObject would not animate via `SampleAnimation()` in the player. To solve it, I:

1. made sure an `Animator` referencing an `Animation Controller` was attached to the GameObject and
2. disabled the `Animator` component.
> 0 votes

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


# Question
Title: Quaternion rotation is inverse of what I expect
I'm trying to learn quaternions and decided to implement my own quaternion class.

To test it I made a couple vertex shaders, one that gets a model matrix (calculated from the quaternion) and another that gets the rotation quaternion directly and rotates vertices in-shader.

I then feed these a quaternion that rotates around the Y axis `t / 10000` radians (t = time):

```
const rotation = Quat.fromAxisAngle(new Vec3([0, 1, 0]), t / 10000)

```

The result surprises me because my model is rotating counter-clockwise but I expected it to rotate clockwise, since the angle is increasing (checked it, quat's xyz increase with time). Rotation around the X or Z axes is also backwards.

All translations as well as matrix rotations work as expected in my coordinate system. I suspect my formulas are wrong, and probably assume +Z is forward. If I transpose my model matrix (or post-multiply with it) it rotates as expected, which suggests it's a handedness problem.

Where are my formulas wrong and how can I understand the math behind this?

### Details

* My matrices are column-major in memory (to match GLSL's `mat4`).
* My coordinate system is +X right, +Y up, -Z forward.

## My code

### Quaternion from axis + angle

```
function fromAxisAngle(axis: Vec3, angle: number, dest = new Quat()): Quat {
  angle *= 0.5
  const sin = Math.sin(angle)

  dest.x = axis.x * sin
  dest.y = axis.y * sin
  dest.z = axis.z * sin
  dest.w = Math.cos(angle)

  return dest
}

```

**Note:** I noticed if I negate this quaternion's x, y and z, everthing works as expected. Is this the root cause? I thought quaternions didn't have handedness!

Since this is actually just inverting the quaternion (and thus its rotation) I'm afraid I'm just patching over the root cause. I don't want to patch the issue, I want to fix my math!

### Matrix from quaternion

```
toMat4(dest = new Mat4()): Mat4 {
  const { x, y, z, w } = this

  const x2 = x + x
  const y2 = y + y
  const z2 = z + z

  const xx = x * x2
  const xy = x * y2
  const xz = x * z2
  const yy = y * y2
  const yz = y * z2
  const zz = z * z2
  const wx = w * x2
  const wy = w * y2
  const wz = w * z2

  // Notice matrix is column-major
  // Source:
  // https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#Quaternion-derived_rotation_matrix
  dest.init([
    1 - (yy + zz), xy - wz,       xz + wy,       0,
    xy + wz,       1 - (xx + zz), yz - wx,       0,
    xz - wy,       yz + wx,       1 - (xx + yy), 0,
    0,             0,             0,             1,
  ])

  return dest
}

```

### Matrix vertex shader

```
precision mediump float;

attribute vec3 aVertexPosition;
attribute vec2 aVertexUV;

uniform mat4 uModelMatrix;
uniform mat4 uViewMatrix;
uniform mat4 uProjectionMatrix;

varying vec2 vUV;

void main(void) {
  vUV = aVertexUV;

  gl_Position = uProjectionMatrix * uViewMatrix * uModelMatrix * vec4(aVertexPosition.xyz, 1.0);
}

```

### Quaternion vertex shader

```
precision mediump float;

attribute vec3 aVertexPosition;
attribute vec2 aVertexUV;

struct Transform {
  float scale;
  vec3 translation;
  vec4 rotation;
};

uniform Transform uModel;
uniform Transform uView;
uniform mat4 uProjection;

varying vec2 vUV;

// Source:
// https://twistedpairdevelopment.wordpress.com/2013/02/11/rotating-a-vector-by-a-quaternion-in-glsl/
vec3 rotateVector(vec4 quat, vec3 vec) {
  return vec + 2.0 * cross(cross(vec, quat.xyz) + quat.w * vec, quat.xyz);
}

void main(void) {
  vUV = aVertexUV;

  vec3 world = rotateVector(uModel.rotation, aVertexPosition * uModel.scale) + uModel.translation;
  vec3 view = rotateVector(uView.rotation, world * uView.scale) + uView.translation;

  gl_Position = uProjection * vec4(view, 1.0);
}

```

# Answer
Turns out my quaternion rotations are completely fine. Positive rotations are CCW in right-handed coordinate systems\[1\].

My rotation matrix functions were the ones rotating backwards! And in fact they were transposed by mistake.

\[1\] https://www.evl.uic.edu/ralph/508S98/coordinates.html
> 2 votes

---
Tags: rotation, glsl, quaternion
---


title: How does mmorpg store data?

text:
# Question
Title: How does mmorpg store data?
I want to use sql database in my server.exe.

lets say 1000 users online. And players will change their data when they play. And server need to save these updates.

But how ?

i think there two way:

1) server will save in ram at run time and sometime or hourly server will write data (update) to sql database from ram. But if electricity goes or somehow the server shuts down , updates won't save. of course i don't want lose updates.

2) server will save updates in database at run time. but what will happen to speed ? I thought of a method. i will show you below with image. Can i get enough speed for 1000 online players with this method ?

# Answer
> 40 votes
Most MMOs (or projects using similar architecture) I've worked on or know of use the first method: the game servers work mainly with the RAM on the machines running the server processes, and only periodically serialize the relevant game data to a SQL database for archival (if one is used at all).

The problems you note regarding power failure are valid, but less likely than issues like crashes in the process (uptime reliability is generally one of those things you'd pay the datacenter for). But still. You mitigate those issues through things like tuning the save interval (so a failure only costs at most a few minutes of progress), distributing the save queues across multiple machines, aggressively scoping the amount of data that needs to be saved, and implementing restartable save queues.

Generally speaking, using the SQL server itself as main memory is going to be unpleasantly slow (and cumbersome). I don't see enough detail in your proposal there to be able to say for sure if it would work for only about 1000 players -- it would probably be fine. But I don't believe you can make it aggressively scalable.

Further, it doesn't solve the problem. A power failure during the save process will still lose or corrupt data unless you do the work to implement the same kind of restartable save queue (which even then, that only severely reduces the likelihood of catastrophic data loss, it doesn't prevent it).

I'd recommend you go with the first approach.

# Answer
> 20 votes
1000 player may or may not be a problem. It depends on how often you need to update the database. However there is a simple solution: put the database on its own server.

---

I had a peek at how the database system works a game that people would call an MMO-Lite – which one I will not disclosure – yet I can tell it consistently has more than 1000 players, this is the abstract:

* They use a document based "No-SQL" database for private character information (inventory, equipment, similar).
* They use a more traditional relational database for public character information that is updated rarely (name, achievements, etc...) and statistics.

Using a document based database turns out to be a good idea for performance in this case. It is good for accessing the data, even though it is bad for doing joins and aggregations... but they won't be doing that with the data that is in there.

On the other hand, when they need to do something like change an object with another object for everybody, the need to run a background script that goes character by character and updates them one by one, it takes noticeable time.

---

The data of the character exists both on the client and on the server, and the system is designed to keep them in sync, doing the same operations on both sides.

Now, when a player does a transaction with the system – say exchange an item for another via NPC or similar – this has these stages:

* The clients checks if the operation is valid
* The client sends the operation to the server (async operation)
* The client updates its model in RAM
* The server checks if the operation is valid
* The server updates its model in RAM
* The server updates the database (async operation)
* The server tells the client that the change happened

**Notes**:

* The database updates, although async, are done right away. If for whatever reason the game server goes down, not much is lost.
* Performance degradation is not a big deal thanks to placing the databases on their own servers.

Trades between players are handled similarly, with extra rules to prevent players scamming other players, and extra traceability in case a transaction need to be undone. I heard there are special logs of all transactions that are kept for some time (to solve issues when somebody complains), I do not know more of how that part works.

---

Sometimes something goes wrong, this has two possible outcomes:

* If the error happens right away, the server will tell the client, which will revert the operation (the player sees the operation undone).
* The UI says the player has an item, but the server does not agree. If the user tries to use it, it will ask the server and fail, rendering the fake object unusable. The false object goes away when the inventory is reloaded, which is used as an opportunity to synchronize the model.

In either case, the client is aware of the error, and will log it along with all that the player was doing. Logging client side is happening all the time. Then, on logout, if there was an error, the client sends the logs to the server.

---

This game does not use the traditional daily or weekly maintenance down time that most MMORPG has. That scheduled maintenance is often used to reset counters, timers, run database procedures. They are also the opportunity to swap server versions for an update.

# Answer
> 8 votes
Both approaches are used with MMORPGs. Keeping everything in memory and periodically check pointing it to disk seems to be the most popular option, at least for older games. It has the advantage of being fairly simple to implement and scaling fairly well, but making it reliable is completely up the to the developer. SQL databases provide ACID properties that make reliability easier, but are overall more complicated to implement well and can have problems with scaling.

EVE Online is an example of an MMO where everything is stored in an SQL database. I think it peaked at something around 60,000 simultaneous users, and has had to dedicate some expensive hardware to the database servers over the years in order keep up with the load. However EVE stores a lot more data per user than than most MMORPGs and has a lot more frequent and varied transactions. The database's ACID properties allows the entire massive and complicated database to always be kept in a consistent state.

For example, consider the case when someone gives an item to another player. EVE's database guarantees that even in the event of a crash or power failure that the item ends up in only one player's inventory. That is, the database transaction that removes the the item from one player's inventory and adds it to the other player's is atomic. The transaction either fully completes or doesn't happen at all. You can't end up in a state were the item exists in neither players' inventory or in both.

An MMORPG that keeps player data in memory and periodically checkpoints it has to implement this atomicity itself. One way to do this would be checkpoint every player's data at the same time, ensuring that new checkpoint is fully committed to disk before its considered the most recent checkpoint. The game would also have to ensure that player data can't change while it's being checkpointed. With a large amount of active players, the challenge becomes doing all this without causing a delay long enough that the players would notice.

Don't underestimate how important consistency is. When you're developing your game its going to crash a lot. You don't want have to track down why items are disappearing and/or duplicating, not when the problem is an unrelated bug is causing the game to crash at a bad time. Moreover when your game goes live, it'll crash way more than you expect it to. Your server that was operating perfectly under testing, will suddenly expose numerous bugs under full load and players doings thing you didn't expect them to.

Note that most MMORPGs use SQL databases for account related information even if they don't for actual game data. Even more important than keeping the game state in consistent state is keeping the billing state consistent. Worst case for the game database getting corrupt is that you have to restore the database from a daily backup. Worst case for account database getting corrupt is that you go bankrupt because of all the chargebacks.

For your project you can probably go either way. Having 1000 simultaneous users probably won't push the limits of what an SQL server can handle on a commodity PC these days, but a lot will depend on the nature of the transactions. If you're familiar with SQL and relational database design then this can work for you. You'll want to minimize the transactions as much possible, for something like player current hitpoints you might only want to periodically save them to the database since stats like these don't necessarily need to be consistent. (In PvP game they might though...) Don't store things like monster HP in the database at all, in most games only player related data is persistent.

On the other hand if you're not an SQL wizard you might find keeping all data in memory much simpler to get working reliably. SQL databases make consistency and reliability easier, but its not automatic. A badly designed database can perform poorly and lead to inconsistencies. Transactions won't be atomic unless you make them so. If you don't use parameterized statements religiously you'll open yourself to SQL injection attacks.

# Answer
> 0 votes
Various games store things in different ways. Often, game companies create some way to do this, and most of their games use the same way. Of course, different studios often use different ways. SQL is certainly used for games, e.g. CCP (EVE) has (or at least had) a network of SQL servers, I am not sure how they do it now. Others, just use lots of files.

Maybe start by creating an agnostic "data broker mechanism", to handle various game data transactions? Since you are just testing anyways, create a mechanism that enables you to not need to care too much about the storage, from a standpoint of the game itself. Meaning, concentrate on how, from the host application, you are going to handle this.

Personally I think it would be a great asset if you could switch the actual store, without having to rewrite the game and the broker itself. Just switch to another module with the same interface for the broker to talk to.

Storing data in itself is likely not going to be an issue, per se. Efficiently shipping data, to/from that store, between host and all the clients, could be trickier. Do I ship the entire player data set, or if I break it down into parts, what granularity do I choose to partition by, etc. Which one is more resource intensive in which situation, etc.

One format to ship the data in, could be XML. That way you can more easily be dynamic in how it you can chunk it up. One character vs multiple characters, or one item vs a collection of items, etc. You could then either "store" the XML as XML (in SQL), and/or have SQL distribute it in a more transactional fashion from the XML, to how you want the data actually stored.

Another way is binary, which is more efficient in terms of shipping, but can incur more cost in other situations.

With 1,000 clients, you could start with, and easily store 10 MB per client and only use 10 GB of effective RAM + add some system administrative RAM for managing that data, say another GB or two. You could keep that in RAM on the host already in data structure ready for use. And load/save dynamically, depending on who is online, in various frequencies depending on activity, etc.

You could even store each client's information in a separate file, and so on.

# Answer
> 0 votes
Keep \*online\* players in ram, and push em to a database (SQLite? MySQL?) when they log out. if you're worried about IO stalling during logout, give each logout it's own thread, don't do it in the main/game thread (actually i keep a dedicated player thread for every online player, it made the networking code so much easier than doing the async network io approach)

---
Tags: mmo, client-server, server, sql
---


# Question
Title: Understanding the ways to access a Graphics object for drawing in Java
I'm making a game in java right now. I've looked around at various tutorials for making Java games and there doesn't seem to be a consistent way to access a Graphics object to draw stuff on the screen.

Three of the different ways have been

1. Overriding the paintComponent() method in a class that extends JPanel
2. Using the getGraphics() method to get the graphics object in a class that extends JPanel
3. Creating a BufferStrategy object and using the getDrawGraphics() method to get the graphics object to draw

All three implementations seem to work, I'm just confused about the difference between them, and in which situations would you use each?

# Answer
> 1 votes
I recommend the third one for making games. Because in:

**CASE-1** When you override the `paintComponent` method all the drawing code inside the method is invoked by calling repaint method. Which is not good, because the repaint method is a just request to Swing to draw stuff. Due to this you might not get consistent frames. You should use this case only if you do not really care about inconsistent frames, for example, the Snake Game.

**CASE-2** This case is also not recommended. It is kind of similar to 1st one.

**CASE-3** This case should be used if you want a consistent game frame rate and do not want flickering in your game. This method renders when it should render and does not delay like the 1st case. Most of the games using this render method.

I would recommend you to use the third case, because it is the best of the three. I have built many games using that approach.

---
Tags: java
---


title: Java BufferStrategy Flickering

text:
# Question
Title: Java BufferStrategy Flickering
I was watching a tutorial on using a BufferStrategy in Java and I wanted to test a very simple example. The issue is that it flickers intensely and it seems as if a piece of the starting oval stays on the screen. I know that the loop is a very bad practice but I just wanted to very simply test the BufferStrategy.

```
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferStrategy;

public class Game extends JFrame {
    private Canvas canvas = new Canvas();

    public Game() {
        setBounds(0, 0, 1280, 720);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        add(canvas);

        setVisible(true);

        canvas.createBufferStrategy(3);
        BufferStrategy bufferStrategy = canvas.getBufferStrategy();

        int x = 0;
        int i = 0;

        while(true) {
            i++;

            if(i == 10) {
                i = 0;
                x++;
            }

            bufferStrategy = canvas.getBufferStrategy();
            Graphics g = bufferStrategy.getDrawGraphics();
            super.paint(g);
            g.setColor(Color.RED);
            g.fillOval(x, 200, 50, 100);
            g.dispose();
            bufferStrategy.show();
        }
    }

    public static void main(String[] args) {
        new Game();
    }

}

```

# Answer
You get flickering because you do not clear the screen after each frame. Add this after you set your graphics object.

g.clearRect(0,0,width,height);

Plus you do not need to call super.paint() method either.
> 0 votes

---
Tags: java
---


title: How to get EditorWindow client rect?

text:
# Question
Title: How to get EditorWindow client rect?
I want to create a simple console-like custom EditorWindow in Unity. There is a bunch of lables (console lines).

I'm using GUILayout.Begi/EndScrollView to position all the labels in one column. The problem is that it places all the content inside the rectangle that matches label bounds, not EditowWindow bounds. As a result, I see weird placed scrollbars.

I would be happy to recalculate ScrollView bounds, but can't find any clue in documentation how to make so. Here is my code:

```
using UnityEditor;
using UnityEngine;
using System;

public class MyEditorWindow : EditorWindow
{
    Vector2 scrollPosition = Vector2.zero;

    [MenuItem("Window/MyEditorWindow")]
    public static void ShowExample()
    {
        var wnd = GetWindow<MyEditorWindow>();
        wnd.titleContent = new GUIContent("MyEditorWindow");
    }

    private void OnGUI()
    {
        scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUILayout.Width(position.width), GUILayout.Height(position.height));

        var elapsed = new TimeSpan();
        for (int i = 0; i < 100; i++)
        {
            elapsed = elapsed.Add(TimeSpan.FromSeconds(1));
        }

        for (int i = 0; i < 100; i++)
        {
            GUILayout.Label("Some long long long long text");
        }

        GUI.EndScrollView();
    }
}

```

What is the proper way of making scrolbars which bound to the edges of the EditorWindow?

# Answer
Turns out I used `GUI.EndScrollView()`, not `GUILayout.EndScrollView()`.
> 0 votes

# Answer
Well, don't overwrite the width with your own value... :p

In my example I Use EditorGUILayout instead of GUILayout, but in this case that won't make a difference. The below code makes the scrollrect fill the entire window.

```
scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);

for (int i = 0; i < 100; i++)
{
    GUILayout.Label("Some long long long long text");
}

EditorGUILayout.EndScrollView();

```

In case you want to get the actual width of the window, see EditorGUIUtility.currentViewWidth
> 1 votes

---
Tags: unity, gui, editors
---


title: Find angle (slope) of collision plane?

text:
# Question
Title: Find angle (slope) of collision plane?
I have implemented a collision and response system based on the famous "Improved Collision detection and Response" paper. However I'm having an issue with objects sliding backwards on slopes. I believe I could circumvent this issue if I understood how to find the angle of the plane of which my object is colliding with. Take the below screenshot as an example of the situation:

I know the following data:

* Position of player object (the ellipsoid at the bottom of the ramp)
* Vertices of the collision triangle
* Normal of the collision triangle
* Intersection point between player object and collision triangle
* Penetration distance between player object and collision triangle

How can I use this information to determine the angle of the collision triangle?

# Answer
If you have the normal of the collision triangle, then you can do a dot product with a normal pointing up (0, 1, 0), the result will be related to the angle of the surface (0 when is completety vertical, 1 when it's completely flat, and in between)

That should be really all, you check that against a threshold to determine if you want the ellipsoid to slide or not.

I actually followed that same paper and this is how I implemented (my Up vector was 0,0,1)

```
// Check if the slide is too steep for gravity
if (is_gravity) {
    var v1 = vector_normalize(velocity),
        v2 = [0, 0, 1 * sign(v1[2])],
        dp = dot(v1, v2);

    if (dp <= 0.70) {
        return true;
    }
}

```
> 3 votes

---
Tags: c++, 3d, mathematics, glm
---


# Question
Title: How to use Pivot Point in Transformations
How to translate object using Center point

I have a rectangle which has a center point away from the position of rectangle.

when i rotate rectangle it rotates around its center axis.

if i multyply position before rotation in the modelView matrix

```
ModelViewMatrix = Rotation * Scaling * Position

```

Suppose if i want to do these translations.

1) Translate the rectangle position by x = 10 units.

1) Rotate the rectangle by 35 degree with the center point at the center of the rectangle.

2) Translate the rectangle position by x = 10 units.

3) change the x position of the center point by 10 units( rectangle should not be affected by the change in the center point position)

enter image description here

4) Now rotate the rectangle using the new center point.

If someone could please guide me how do we use Center point in transformations. How do i build by ModelView Matrix if i am using a center Point.

# Answer
To make a pivoted transformation, you need to transform the matrix with a pivot space matrix, apply pivoted transformation, and then remove pivot space transformation.

```
//final transformation matrix
mat4x4 m_transform = identity();
//pivot matrix
mat4x4 m_pivot_transform = translation(...);
//desired transformation
mat4x4 m_rotation = rotation(...);
//apply pivot transformation
m_transform = m_transform * m_pivot_transform;
//apply transformation
m_transform = m_transform * m_rotation;
//cancel out pivot transformation
m_transform = m_transform * inverse(m_pivot_transform);

```
> 1 votes

---
Tags: opengl, glsl
---


# Question
Title: Cube not square and being clipped horrendously, color doesn't apply
I'm trying to create my own object-oriented graphics library and use it to make a ping-pong game. I am following some tutorials online, and one uses old-style code with individual calls to `glVertex`, and the new stuff uses VBOs.

I have a project you can clone; it's available here:

https://github.com/awildtechno/ping

pingpong.py is the entry point. Run `pip install -r requirements.txt`, `python pingpong.py` to see the issue. The box seems to be deformed to the aspect ratio and it's clipping severely. It also doesn't use the color I passed in.

In line 31, if you switch VBOGameLoop for just GameLoop, you will get a nicely formed colorful cube using the same vertexes. There are a lot of trash files hanging out as a result of the switch, so I've cut out the code below. The relevant files are `Shape3D.py`, `Rect2D.py` `VBOGameLoop.py`, and of course `pingpong.py`.

This is a trimmed down version of the relevant PyGame/PyOpenGL code:

Setup:

```
# PyGame Init
pygame.init()
gameDisplay = pygame.display.set_mode((WIDTH, HEIGHT), pygame.DOUBLEBUF|pygame.OPENGL)
pygame.display.set_caption('Ping Pong')
clock = pygame.time.Clock()

drawables = {cube(1, Point3D(-.5, -.5, .2))}  # Point3D is just a wrapper for vectors.
glEnable(GL_POLYGON_SMOOTH)
# glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST)
glEnable(GL_BLEND)
glEnable(GL_DEPTH_TEST)

# initial translation/camera angle
glTranslate(0., 0., -2)
glRotate(0., 0., 0., 0.)

```

Main loop:

```
    gluPerspective(0, (display.get_width() / display.get_height()),
                   .05,
                   100.)
    glClearColor(.2,.2,.2,1)
    # Main Loop #####################################
    self.exit_flag = False
    while not self.exit_flag:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            if event.type in self._event_handlers:
                self._event_handlers[event.type](self, event)

        # clear the screen
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)

        # Render all the things
        for d in self.drawables:
            verticies, shader, mode = d.to_renderable()
            vbo = VBO(verticies)
            try:
                # Add the VBO to gfxcard memory
                shaders.glUseProgram(shader)
                assert not glGetError()
                try:
                    vbo.bind()
                    glEnableClientState(GL_VERTEX_ARRAY)
                    glVertexPointerf(vbo)
                    glDrawArrays(mode, 0, len(verticies))
                finally:
                    # Release the VBO memory in the graphics card
                    vbo.unbind()
                    glDisableClientState(GL_VERTEX_ARRAY)
            finally:
                # Remove the shader
                shaders.glUseProgram(0)

        pygame.display.flip()
        clock.tick(clock_rate)

```

Raw vertex data being passed into VBO:

```
[[-0.5 -0.5  0.2]
 [-0.5  0.5  0.2]
 [ 0.5  0.5  0.2]
 [-0.5 -0.5  0.2]
 [ 0.5  0.5  0.2]
 [ 0.5 -0.5  0.2]
 [-0.5  0.5  0.2]
 [-0.5  0.5  1.2]
 [ 0.5  0.5  1.2]
 [-0.5  0.5  0.2]
 [ 0.5  0.5  1.2]
 [ 0.5  0.5  0.2]
 [-0.5 -0.5  1.2]
 [-0.5 -0.5  0.2]
 [ 0.5 -0.5  0.2]
 [-0.5 -0.5  1.2]
 [ 0.5 -0.5  0.2]
 [ 0.5 -0.5  1.2]
 [-0.5 -0.5  1.2]
 [-0.5  0.5  1.2]
 [-0.5  0.5  0.2]
 [-0.5 -0.5  1.2]
 [-0.5  0.5  0.2]
 [-0.5 -0.5  0.2]
 [ 0.5 -0.5  0.2]
 [ 0.5  0.5  0.2]
 [ 0.5  0.5  1.2]
 [ 0.5 -0.5  0.2]
 [ 0.5  0.5  1.2]
 [ 0.5 -0.5  1.2]] 3 GL_TRIANGLES (4)

```

code for the shader:

```
    color=(.5, .5, .5, 1.0)
    # irrelevant stuff
        # Create the C code for the vertex shader.
        vshader = shaders.compileShader("""#version 120
        void main() {
            gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
        }""", GL_VERTEX_SHADER)
        # Create the C code for the fragment shader.
        fshader = shaders.compileShader("""#version 120
        void main() {
            gl_FragColor = vec4""" + self.color.__str__() + """;
        }""", GL_FRAGMENT_SHADER)
        # Have openGL compile both shaders and save the result.
        self.shader = shaders.compileProgram(vshader, fshader)

```

I presume I'm misusing something about gluPerspective?

# Answer
> 0 votes
The clipping issue was solved with glLoadIdentity() before the perspective call.

The shader color issue was actually not an issue, I was passing in black like an idjit.

---
Tags: opengl, pygame
---


# Question
Title: How to calculate score in my game based on playtime and coins picked?
I've been trying to figure out a way to calculate the score in my game.... but nothing seems to work properly...

The score is to be calculated according to:

* playtime
* coins collected.

The playtime should be as low as possible and number of coins should be as high as possible.

For example: Let's say an idle play for a level X has:

* playtime = 15 seconds
* coins = 20.

The score is 100.

Then what will be the score when the:

* playtime = 20 seconds
* coins = 14.

P.S.: Pardon me if the example is wrong but I can't figure out how to explain my problem... Thanks in advance.

# Answer
Maybe you want this one:

$$ (c\_0 + c) \cdot {t\_0 \over t\_0 + t} $$

\\$ c\_0 + c \\$ is the part for coins.
\\$c\\$ is how many coins a player has. \\$c\_0\\$ is a constant which ensures positive score even if a player has no coins.

\\$ t\_0 \over t\_0 + t \\$ is the part for playtime.
A player finishes the level in time \\$t\\$. \\$t\_0\\$ is a time constant.

How you should pick \\$c\_0\\$ and \\$t\_0\\$? Let's assume they are 30 coins and 30 seconds, and the level has 30 coins.

If \\$t = 0s\\$ then time multiplier will be \\$1\\$.
If \\$t = 15s\\$ then it will be \\$2 \over 3\\$.
If \\$t = 30s\\$ then time multiplier will be \\$0.5\\$.
If \\$t = 60s\\$ then time multiplier will be \\$1 \over 3\\$.
If \\$t = 120s\\$ then time multiplier will be \\$0.2\\$.

So, if a player just speedruns a level in 30 seconds without collecting any coins. His score will be \\$30 \cdot 0.5 = 15\\$.
Another player spends time collecting every single coin, \\$t = 120s\\$, his score will be \\$60 \cdot 0.2 = 12\\$.
But what if we decide to collect some easy coins while trying to finish level quickly? Let \\$t = 60s\\$, \\$c = 15\\$. Our score is... no, \\$15\\$ again.

You can encourage players to collect coins by lowering \\$c\_0\\$, and to hurry up by increasing it. If you want to punish both those who don't collect coins and those who spend much time to collect them all, try lowering \\$t\_0\\$. If we set \\$c\_0 = 10, t\_0 = 10s\\$, those players will score \\$2.5\\$, \\$3.08\\$ and \\$3.57\\$ points respectively.

If that's not enough, square the time multiplier. Or put some coins into places that are hard to get into.

Or course you can multiply the result by some constant, \\$1000\\$ for example, to prevent players from saying *"why is my score always so low??"*
> 1 votes

---
Tags: unity, c#, mathematics, statistics
---


# Question
Title: OpenGL Fragment shader: not all fragments showing colors
I'm writing a simple 3D renderer and while the model loads fine, the colors are off. Quite a few fragments in the model show no color at all.

Here is the render:

The locations of the blacked out fragments change everytime I move my camera. From another angle:

**Vertex shader**:

```
#version 330 core
layout (location = 0) in vec3 pos;
layout (location = 1) in vec3 normal;
layout (location = 2) in vec2 uvCoords;

out vec2 texCoords;
out vec3 normCoords;
out vec3 fragmentPos;

uniform mat4 viewMatrix;
uniform mat4 projMatrix;
uniform mat4 modelMatrix; // Just an identity matrix for now

void main()
{
    normCoords = normal;
    fragmentPos = pos;

    texCoords = uvCoords;

     gl_Position = projMatrix * viewMatrix * modelMatrix * vec4(pos, 1.0);
}

```

**Fragment shader:**

```
#version 330 core

out vec4 frag_color;

in vec2 texCoords;
in vec3 normCoords;
in vec3 fragmentPos;

struct Light
{
    vec3 lightPos;
    vec3 lightColor;
};

uniform Light light;
uniform vec3 modelColor;

bool checkInf(in vec3 vect)
{
    return (isinf(vect.x) || isinf(vect.y) || isinf(vect.z));
}

bool checkNan(in vec3 vect)
{
    return (isnan(vect.x) || isnan(vect.y) || isnan(vect.z));
}

void main()
{
    float ambientValue = 0.05;
    vec3 ambientColor = ambientValue * light.lightColor;

    vec3 result;
    vec3 normalizedNormal = normalize(normCoords);
    vec3 lightDir = normalize(light.lightPos - fragmentPos);

    if(checkInf(normalizedNormal) || checkInf(lightDir) || checkNan(normalizedNormal) || checkNan(lightDir))
        result = vec3(0.5,0.5,0.5);

    else
    {
        float diffuseValue = max(dot(normalizedNormal, lightDir), 0.0);
        vec3 diffuseColor = diffuseValue * light.lightColor;

        result = (diffuseColor + ambientColor) * modelColor;
    }
    frag_color = vec4(result, 1.0);
}

```

After some playing around, I realized that the blacked out fragments were due to the diffuse lighting calculations. After some searching on the internet, I found this answer: answer that suggested it may be caused by normalized vector being Nan or infinity. To test that, I decided to check each normalized vector to see if it was Nan or infinity and if it was, set it to a grey color. But that didn't work.

Any help would be appreciated.

# Answer
> 2 votes
This is definitely Z-Buffer problem, artifacts seem to resolve at a distance closer to the viewer, where precision is supposed to be higher.

It is worth knowing, that exactly this problem has been covered on the OpenGL wiki:

> As the zNear clipping plane is set increasingly closer to 0.0, the effective precision of the depth buffer decreases dramatically.

---
Tags: opengl, shaders, models, fragment-shader
---