# Question
Title: Javascript, how to make player collide with tile map
I'm trying to do a bomberman based game, but I'm struggling to make the player colide with the wall, here's my code below: Inside of the array, 0 is the walls and 1 is the path

```
// xPos is the position of my tiles (horizontal ( width). This array have the starting tile 28.5, and the sum of this value to find another tiles
// yPos is the position of my tiles (vertical(height). The same happens with height.

var xPos = [28.5, 57, 85.5, 114, 142.5, 171, 199.5, 228, 256.5, 285, 313.5, 342, 370.5, 399, 427.5, 456, 484.5, 513, 541.5, 570, 598.5];
var yPos = [40, 80, 120, 160, 200, 240, 280, 320, 360, 400, 440, 480, 520, 560, 600];

// I started this for loop to identify if my player is on a position 0 or 1 if the position x and y result in 1 it means that he's in the path otherwise, wall. I don't know what I need to do with this for loop to identify the wall or the path.

  for(var i = 0; i < xPos.length; i++){
    for(var j = 0; j < yPos.length; j++){
    if(player.x <= xPos[i] && player.y <= yPos[j]){

    }
   }
}

//This is my stage map, 0's are the walls and 1's are the path. I used two for loops to draw the stage.
function drawStage(){
var mapArray =[
    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
    [0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0],
    [0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0],
    [0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0],
    [0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0],
    [0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0],
    [0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0],
    [0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0],
    [0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0],
    [0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0],
    [0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0],
    [0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0],
    [0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0],
    [0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
];

var posX = 0;
var posY = 0;

for(var i = 0; i < mapArray.length; i++){
    for(var j = 0; j < mapArray[i].length; j++){

        if(mapArray[i][j]==0){
            ctx.drawImage(steel, posX, posY, 250,338);
        }
        if(mapArray[i][j]==1){
            ctx.drawImage(grass, posX, posY, 250,338);
        }
        posX+=28.5;
    }
    posX=0;
    posY+=40;
 }
}

//That's my object

var player = {
x: 25,
y: 40,
spdX: 4,
spdY: 4,
width: 42,
height: 38,
};

// That's is my function to collide with another enemies, I don't know if it's possible to use the same collision code of my player x enemy, to player x walls.
function collision(player, enemy){
if (player.x < enemy.x+enemy.width &&
    player.x+player.width > enemy.x &&
    player.y < enemy.y+enemy.height &&
    player.y+player.height > enemy.y){
        console.log("collide");

}
}

// I can't use external libraries, this is a game project for my course of web programming.
// if you need more detais, please ask me.

```

# Answer
> 1 votes
You're on the right track, but just a little off the mark. Like most problems, this can be solved in many different ways. Here's one I think should be simple and effective in your case.

The cool thing about tile-based games is that they allow for a good separation of data and visuals. As you can see from your own code, the map is nothing more than a two-dimensional array of ones and zeroes. Assuming the index of a tile in the map array coincides with the origin of the tile graphic on the player's screen (e.g. its top left corner position), mapping the data to the visuals is easy!

Same goes for any entities or objects placed on the map, such as the player and bombs. From the perspective of the data, their position on the map is nothing more than an index in the map array. This means that checking what other entities and objects surround them is as simple as probing the map array data at surrounding indexes.

Let's assume a simple two-dimensional map where walls are `0`, and paths are `1`:

```
var map = [[0, 0, 0, 0, 0],
           [0, 1, 1, 1, 0]
           [0, 1, 0, 1, 0],
           [0, 1, 1, 1, 0],
           [0, 0, 0, 0, 0]];

```

Let's place a player on the map, for example at position (1, 1):

```
var player = {
  mapX : 1, // Map array row index
  mapY : 1  // Map array column index
};

```

The player wants to move in a direction, but he can only do so if he's moving along path tiles. To see if we can allow the player to move in the desired direction, we probe the map array index in his direction of movement for path tiles:

```
/*
    Checks if path tile exists at map[x][y].
    @param map Map data array
    @param x   Map data array row
    @param y   Map data array column
*/
function isPathTile(map, x, y) {
    return (map[x][y] === 1); // Because 1 is the path tile
}

/*
    Let's assume player wants to move to the right,
    increasing his horizontal position on the map by one.
*/
if (isPathTile(map, player.x + 1, player.y)) {
    move(player, 1, 0);
}

```

There's really not much else to it. Keeping a reference to the player's position in the map array saves you from iterating over the array to learn about the player's environment. Instead, you only check the elements of the array that matter. This saves you a lot of time and makes your checks faster and more efficient. You'll begin to notice this with larger map sizes.

---
Tags: collision-detection, javascript
---


# Question
Title: Drawing only objects that are currently in viewport [Gamemaker]
Following on from my previous question about optimising large object counts in Gamemaker, I am looking for a method for the solution proposed by liggiorgio.

My game has large numbers of small, sprite-based objects, represent individual strands or clumps of fur. For a variety of reasons, they all need to be interactive objects. At the moment, I am reaching limits on how many I can generate without the game grinding to a halt.

As the game involves a very large (20,000px x 20,000px) room with a restricted viewport, liggiorgio proposed a solution using the built-in Application Surface to only draw objects which are currently within the viewport. This would mean that the vast majority of the room, and its objects, would not be drawn, and hopefully framerates should improve.

Can anybody help me with implementing this?

**Update:** I am now using this code in an object's Draw event as a test:

```
if (x > view_xview[0] and x < (view_xview[0] + view_wport[0]))
and (y > view_yview[0] and y < (view_yview[0] + view_hport[0]))
{
draw_self()
} else {
}

```

However, even when I pan the view over to the affected object, it is not drawn.

**Edit:** Thanks, liggiorgio, for your below solution. **This code works well for drawing and not drawing based on view in the room, as far as I can tell.** However, not-drawing the large number of `oFur` objects does not seem to help with my performance issues. I think that *deactivating* those not currently in view is the best option.

I know that deactivating instances can be risky, but I don't think it will be a problem for me:

* I only have one room in my game, so there is no worry about persistent objects not being carried over;
* At no point will I be trying to delete all of the `oFur` objects at once;
* I have created a `FurDeactivation` control object, so I won't fall into the trap of having the `oFur` modules try to deactivate themselves and then therefore be unable to reactivate themselves when they are in the view. I made this mistake at first, but I've now corrected it with the `FurDeactivation` control object.

This is the script that is running in the Step event of the control object. The ObjectType is `oFur`;

```
///DeactivateIfOutOfFrame(ObjectType)

ObjectType = argument0

with ObjectType {
if ((x > (view_xview[0]-sprite_width/2)) && (y > (view_yview[0]-sprite_height/2)) && (x < (view_xview[0]+view_wview[0]+sprite_width/2)) && (y < (view_yview[0]+view_hview[0]+sprite_height/2)) )
{
instance_activate_object(self)
} else {
instance_deactivate_object(self)
}
}

```

At the moment, it does not seem to be deactivating any of the instances of `oFur` outside the view. Any ideas?

# Answer
> 1 votes
Following on from my edit above, I have worked out how to deactivate the `oFur` objects and reactivate them only when they are in the current viewport. While the game runs slowly (considering there are ~400,000 `oFur` objects with about 3000 on screen at any one time) it now, at least, runs. The next steps will be:

* making each `oFur` object larger, to cover more of the screen at a time;
* reduce the number of `oFur` objects to improve performance:
* Perhaps make the room itself smaller, to lower the count needed;
* find a way to generate them more quickly (as the method detailed below takes about 30 seconds to generate all of them).

**Solution**

An invisible block, `mFurBlock`, is generated in the top left of the room, and 1,000 `oFur`s are generated in a random fashion across it. This will serve as the 'seed' block, from which all others are created. If I was to try to generate the fur across the entire room, it would take nearly two hours.

Instead, I copy each `oFur` in this `mFurBlock` across the room a number of times corresponding to `(WidthOfRoom / WidthOfBlock`), which in this case is \`20,000 / 1000', which leaves me with 20 'blocks' of fur.

Each time the fur is copied, its `x` is increased by `WidthOfBlock * NumberOfCopiesMade` to gradually move them across the room. Therefore, if 4 copies had been made, the next copies would be moved 4000 pixels across the room. This leaves me with an initial row of fur across the top of the room.

The fur block is then copied down the room, and a new row made using the same code. This leads to a 'scanning' effect across the room, with new furs being created and positions in blocks of 1000px x 1000px, row by row.

The key is to, after each copy has been made and positioned, to deactivate those copies. This means that there are never too many instances active (in fact, only the 'seed' block and the current copied block) and the game won't crash. The framerate does drop, but we could hide this behind a static loading screen or something similar. Or, you know, just optimise it.

When the entire room is finished, the 'only active when in viewport' code is activated in a separate 'Control' object, and persists for the rest of the game:

```
if global.WholeFieldGenerated = true {
if DeactivateToggled = false {
instance_deactivate_object(oFur)
instance_activate_region(view_xview[0], view_yview[0], view_wview[0], view_hview[0], true)
} else if DeactivateToggled = true {
instance_deactivate_object(oFur)
}

```

This deactivates *all* `oFurs` every step, and then activates any deactivated objects in the room that are currently within view.

Below is my commented generation script, so you can see exactly how I did it.

It needs work, but it at least works!

```
//If the first fur block has been completed, and finished generating...
if CreatedFirstFurBlock = true and mFurBlock.FinishedGenerating = true {

/* CREATING THE FIRST ROW */
if FirstRowCompleted = false {

if NumberOfFurBlocksGenerated < global.TotalDuplicationsPerRow {
with oFurBlockFur {
//If a fur piece is within the FurBlock (i.e. it is in the 'root' block)...
if x <= mFurBlock.sprite_width {
//...Copy it and move it along the row the number of 'spaces' required.
ThisCopy = instance_copy(true)
ThisCopy.x = x + (mFurBlock.sprite_width * mFurGeneration.NumberOfFurBlocksGenerated)
//Deactivate the copy, hiding it from view now that it is positioned. This will not effect the 'root' block, meaning that we can use it again.
instance_deactivate_object(ThisCopy)
}
}
//Increase the number of fur blocks generated.
NumberOfFurBlocksGenerated = NumberOfFurBlocksGenerated + 1
} else if NumberOfFurBlocksGenerated >= global.TotalDuplicationsPerRow {
FirstRowCompleted = true
NumberOfFurBlocksGenerated = 1
}
/* CREATING SUBSEQUENT ROWS */

} else if FirstRowCompleted = true {

if NumberOfRowsGenerated < global.TotalRows {

if RowDone = true {
with oFurBlockFur {
//If the fur is part of our 'root block'...
if y <= mFurBlock.sprite_height and x <= mFurBlock.sprite_width {
//...Copy it and move it down the number of 'rows' required. Mark it as in the root so
//that we can deactivate it later.
ThisCopyRoot = instance_copy(true)
ThisCopyRoot.InRoot = true
ThisCopyRoot.y = y + (mFurBlock.sprite_height * mFurGeneration.NumberOfRowsGenerated)
//We don't deactivate the copy, as we need it to generate the row. However, we won't deactivate the 'root' block either, as it is useful to use
//as a generator for subsequent rows. This will only increase the number of 'blocks' active by 1, as each row is deactivated each time they have finished
//generating.
}
}
RowDone = false
ThisRowBlocksGenerated = 1
}

//Reset the row done function. This allows us to get on with making this new row.

if RowDone = false {
if ThisRowBlocksGenerated < global.TotalDuplicationsPerRow {
with oFurBlockFur {
//If a fur piece is in the 'root block' of the current row...
if y >= (mFurBlock.sprite_height * mFurGeneration.NumberOfRowsGenerated) {
//Copy and move it along, as before.
ThisCopy = instance_copy(true)
ThisCopy.x = x + (mFurBlock.sprite_width * mFurGeneration.ThisRowBlocksGenerated)
instance_deactivate_object(ThisCopy)
}
}
//Update the block count in this row.
ThisRowBlocksGenerated = ThisRowBlocksGenerated + 1

//When we have finished this row, update the number of rows, set the row as done (which allows a new 'root' block to be generated next step)
//and deactivate the 'root' block for this row. Can this last thing be done? I'm not sure in this current setup.
} else if mFurGeneration.ThisRowBlocksGenerated >= global.TotalDuplicationsPerRow {
NumberOfRowsGenerated = NumberOfRowsGenerated + 1
with oFurBlockFur {
if InRoot = true {
instance_deactivate_object(self)
}
}
RowDone = true
}
}

//We now replay this code, moving the 'root block' down via copy, using that to generate a new row, and then deactivating the entire row.

//Once all the rows are generated and deactivated, we can tell the ObjectViewDeactivator that it is ready to shine. This Generation object can then be deleted.
} else if NumberOfRowsGenerated >= global.TotalRows {
NumberOfFurBlocksGenerated = 0
global.WholeFieldGenerated = true
instance_destroy()
}

}
}

```

# Answer
> 0 votes
In GM:S, the variables `view_wport[]` and `view_hport[]` refer to the width of the `view` in the game window, not in the room. Thus, they are used for UI design purposes only. Read more about them on the official documentation page.

What you actually need are the variables `view_wview[]` and `view_hview[]`, which define the width of a given `view` inside a room. Try to use this code in the `oFur`'s *Draw Event*:

```
// Draw Event
if ( (x > view_xview[0]) && (y > view_yview[0]) && (x < (view_xview[0]+view_wview[0])) && (y < (view_yview[0]+view_hview[0])) )
}
    draw_self();
}
else
{
    // Else statement
}

```

In addition, you want your objects to be drawn when they intersect the `view` borders, not just if their origin lies within the `view` rectangle; so, let's improve the code as follows:

```
// Draw Event
if ( (x > (view_xview[0]-sprite_width/2)) && (y > (view_yview[0]-sprite_height/2)) && (x < (view_xview[0]+view_wview[0]+sprite_width/2)) && (y < (view_yview[0]+view_hview[0]+sprite_height/2)) )
}
    draw_self();
}
else
{
    // Else statement
}

```

By the way, if the `draw_self()` function fails to do its job, you can replace it with other functions such as `draw_sprite()`, or its advanced version `draw_sprite_ext()` which gives you much more control over the way sprites are drawn on the *Application Surface*.

---
Tags: game-maker, viewport
---


# Question
Title: C++ SFML: Font is clear and the other time blurred
This is my code.

```
    TextRenderer->setString(pCurrentUnit->getCHAR()->getNAME());
    TextRenderer->setCharacterSize(16);
    TextSanitizer::CenterOrigin(TextRenderer);
    TextRenderer->setPosition(108, 34);
    pWindow->draw(*TextRenderer);

    TextRenderer->setString(pCurrentUnit->getCLASS()->GetNAME());
    TextSanitizer::CenterOrigin(TextRenderer);
    TextRenderer->setPosition(242, 34);
    pWindow->draw(*TextRenderer);

```

The font draws perfectly fine with certain texts and other times its really blurry. I've read on the SFML Forum it had something to do with non-rounded positions but mine are already int's.

Is there any way to fix this? It also doesn't matter if I draw the second text first, it's the string it displays that causes the blurriness.

EDIT: It's not the font, I've tested about 10 other fonts and all of them get screwed up in one way or another when below 20px.

# Answer
There must be some transformation you're applying to rendered primitives.
It doesn't matter if you give integer coordinates to text line, if later some transformation will make those coordinates fractional.
To have sharp texts, you must get text line primitive's texels fit exactly into screen pixels, after all transformations was applied. That might even require fractional coords set to initial text, if those coords will be transformed to integer later.
> 0 votes

---
Tags: c++, sfml, fonts
---


title: Swipe Detection with mouse in Unity

text:
# Question
Title: Swipe Detection with mouse in Unity
This is my **swipe detection** code. This code uses touch input. I want to do this using the left mouse button. So basically I want to 'swipe' using the mouse.How can I achieve that?

```
public float maxTime;
public float minSwipeDist;

float startTime;
float endTime;

Vector3 startPos;
Vector3 endPos;
float swipeDistance;
float swipeTime;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    if(Input.touchCount > 0) {
        Touch touch = Input.GetTouch(0);
        if (touch.phase == TouchPhase.Began)
        {
            startTime = Time.time;
            startPos = touch.position;
        }
        else if (touch.phase == TouchPhase.Ended)
        {
            endTime = Time.time;
            endPos = touch.position;

            swipeDistance = (endPos - startPos).magnitude;
            swipeTime = endTime - startTime;

            if(swipeTime < maxTime && swipeDistance>minSwipeDist)
            {
                SwipeFunc();
            }
        }
    }
}

void SwipeFunc()
{
    Vector2 distance = endPos - startPos;
    if(Mathf.Abs(distance.x) > Mathf.Abs(distance.y))
    {
        Debug.Log("Horizontal swipe");
    }
    else if (Mathf.Abs(distance.x) < Mathf.Abs(distance.y))
    {
        Debug.Log(" vertical  swipe");
    }
}
}

```

# Answer
> 1 votes
You need to handle mouse input. Currently you are only handling Touch input.

```
//if(Input.touchCount > 0) { }
if (Input.GetMouseButton()) { }

//if (touch.phase == TouchPhase.Began) { }
if (Input.GetMouseButtonDown()) { }

//else if (touch.phase == TouchPhase.Ended) { }
else if (Input.GetMouseButtonUp()) {}

//touch.position;
Input.mouseposition;

```

Then it would be up to you to either code this in a seperate component, or include it in the same with an if statement, or use precompiler instructions.

The point is, in order for you to be able to do this with Mouse Input, you need to handle the mouse input. The rest of the code should work fine.

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


# Question
Title: How to reset the world in an infinite runner game to prevent an overflowing float?
Im following Mike Geig's 2D infinite runner tutorial. However, I'm seeing a potential problem of overflowing the float

How can I reset all objects and camera back again to the origin?

The approach I'm seeking is similar to the advice made by David Debnar on this question: http://answers.unity3d.com/questions/491411/best-practices-for-endless-runner-type-games.html

> Definitely player. It's a lot easier, but to prevent float overflow, you should pop everything back a few thousand units every few thousand units

# Answer
> 4 votes
You can store the iterations, also how often you popped the whole level to the right. After a certain amount (let's say 1000) put everything back, multiplied by the times of iterations and reset your iteration counter. So you prevent a possible overflow and you don't have to do the "expensive calculation" every time

# Answer
> 3 votes
I have to disagree with David Debnar. In a case of an "endless runner", where player's ability of movement is restricted, I guess it is more efficient to move the world around player to avoid complicated resets on player position.

Because these resets would create a hiccup in the gameplay if not planned carefully, and even for a casual game this is unacceptable for players.

# Answer
> 1 votes
First of, calculate after how much time you're getting into trouble. Say you're runner runs at 1 meter per second, and 1 meter is 1 unit in floats. The maximum number a 32bit float can hold is 2,147,483,647. Which would mean that someone would have to play your game for 68 years before an overflow would occur. Not really worth any extra coding ;).

Another trick is to not have the character move but to move the world. Since once a character has traversed a chunk it will be unloaded nothing will ever even get close to these ridiculous high numbers.

*(Note that a 32 bit float becomes a lot less precise near the high-end of its values so you might encounter problems before overflowing though it would probably still take weeks or years before these problems become apparent).*

# Answer
> 0 votes
You can put every object (except the 2D HUD `Canvas` and the directional light) as a child of a single master empty `GameObject` (let's say with a name "worldPlaceholder") and `Translate` its `Transform` by the position of the main player multiplied by -1. This should be done just once in a while to conserve CPU time (you can use a counter to do that, you place special trigger `Collider` each X meters to perform such a task). Something like that:

`worldPlaceholder.transform.Translate (player.transform.position * -1);`

I advise you don't do this every frame as it could be costly in CPU time.

---
Tags: unity, floating-point
---


# Question
Title: Entity polymorphism and entity attributes
I want to design the entity system of my game in a way such that entities are modular, easily modified without affecting other entities, and finally easy to add new types of entities. So ideally some version of component based design.

In some parts of the code I want to deal with entities generally and abstractly, for example "update all entities" and "render all entities", however in other parts I want to deal with specific types of entity, like when a Soldier entity is fighting a Tank entity.

The problem is some entities need attributes which others do not. For example a soldier needs HP but a missile do not.

How do I keep entity attributes modular, and avoid adding every attribute in the game to the Entity object?

# Answer
> How do I keep entity attributes modular, and avoid adding every attribute in the game to the Entity object?

If you embrace the "entity is just a bag of components" concept, then this can be fairly simple. You package up related attributes into a component, and attach that component to certain entities but not to others. Attaching the component can be as simple as stuffing a pointer/reference to the new component into a list or map or something stored in the entity; the entity doesn't need to know it might have a `HitPointComponent*` specifically, just that it contains `Component*`, the base class of all components:

```
struct Entity {
  std::map<std::type_index, Component*> m_components;

  template<typename ComponentType>
  void attachComponent (Component* component) {
    std::type_index key(typeid(ComponentType));
    m_components.emplace(key, component);
  }

  template<typename ComponentType>
  bool hasComponent() {
    std::type_index key(typeid(ComponentType));
    return m_components.find(key) != std::end(m_components);
  }
};

```

(`type_index` provided as a simple example, not a suggestion that it is the "best" approach, in particular because it requires you always know the component types at compile-time.)

> In some parts of the code I want to deal with entities generally and abstractly, for example "update all entities" and "render all entities"

I'd say you don't need to do this. Rather than operate on "all entities," instead operate on "all components of a given type." It's fairly common in component-based entity design to have a component actually belong to a *system*, some kind of container that is responsible for the creation, deletion and updating of all components of a particular type (for example, the implied `HitpointSystem` in my above code example).

Thus you might have a `VisualizationSystem` which hands out `VisualizationComponent`s which describe how some object might look or is otherwise presented in the game. Non-visible entities don't get such a component. To render, the `VisualizationSystem` simply does something like:

```
for(auto && visualizationComponent : m_allVisualizationComponents) {
  renderer.draw(visualizationComponent);
}

```

This sort of design tends to use the "list of components associated with the entity" that `attachComponent` and the like modify purely as a way to test for the presence of a component with an entity, which is why it can be fairly simple. There's no need in this style of design to do "for each entity, for each component in that entity, update it."

> however in other parts I want to deal with specific types of entity, like when a Soldier entity is fighting a Tank entity.

I'm still not sure what specifically you have in mind here for this kind of interaction that requires knowing about the *type* of entity. So I'll say that in general it might be better to push this kind of thing into *data* instead of into the *type system*.

For example, say you have a `CombatantComponent` to indicate that a given entity can be involved in combat iterations with other combatants (maybe you store your hitpoints here too). Suppose also the purpose of knowing whether the entity is a "soldier" or a "tank" is because a tank gets a defensive bonus versus a solider when exchanging blows. This typing information can be expressed directly in the `CombatantComponent` as a enumeration (`UnitType`) which you switch on to apply bonus damage (et cetera). Or it can be expressed less directly as an enumeration indicating the damage types a `CombatantComponent` can use and the damage types it gets bonuses or penalties to upon receipt.

Thus a tank might be defined as a entity with a combat component that has a damage multiplier for the `Bullet` damage type of 0.1, so it takes 10% of any incoming bullet damage. But maybe it also has 2.0 multiplier for `Corrosive` damage as well.
> 1 votes

---
Tags: entity-system, component-based, entity-component
---


# Question
Title: Problem in nested parent-entity relationship in ecs
In the given flow, the `character` is the parent entity, `gun` is child of *character* and `bullet` is child of *gun*. I've got a component called `NodeComponent` which has the storage of child entities and a `NodeSystem` that iterate the children then update its position relative to its parent. The problem is when the iteration reach to the bullet, it takes some time to update the bullet position. So when I move the parent the bullet is noticeable. How do I handle the parent-child relationship transformation without losing or slowing down the update from top to bottom?

```
Character >>
             Gun >>
                    Bullet

```

# Answer
> 2 votes
The relationship between the `Gun` and the `Bullet` is purely 'spawner/spawned'. It's not parent-child.

In real-life, when you shoot a bullet with a gun, both objects are no longer linked: you can move the gun as you want, once the bullet is out of the barrel, there's nothing you can do to change its trajectory.

So in your case, you should make the bullet as a sibling of the player, and not a child of the gun.

---
Tags: java, libgdx, entity-system, entity-component
---


# Question
Title: Choose your own adventure - choices stack
I'm currently building a choose your own adventure game. Now it's easy enough to have one outcome to every choice and create a linear flow, but is there a good algorithm for having all previous selections affect the next outcome? I could obviously store every previous selection and have big 'IF' statements to decide but I wondered if there was a better way?

Part of me wonders if every choice should have a 'score' and then I use this (maybe with a threshold) to determine what the next action should be and each action gets added to the score.

I'm primiarly doing this in swift/SpriteKit but I think it's more about the concept then the code at this point.

In response to Josh's comment below:

I suppose I'm still in the conceptual phase at the moment, but each 'page' would either be a custom object or a json file. I was thinking about your answer (now removed) and maybe having each ENUM option as a bit. Then each page could have a 'score'. Then using the previous options selected work out what bits are set and that determines what page. I guess I just wondered if there was an existing solution to this problem before I began to almost help decide how I should format the 'story'

Rough guess at format :

```
  { "text":"You arrive in the dungeon and there are 2 doors",
   "options":[
    1: "Go left",
    2: "Go Right"
    ],
   "score" : 0 // first page
  }
  {"text" "You went left and meet a dragon",
  "options":[
    0: "Game over, you were eaten" // something to handle game over
    ],
   "score" : 1
  }
  {"text" "You meet a mushroom who tells you the princess is in another castle",
  "options":[
    4: "Give up, game over", // something to handle game over
    8: "Jump down the pipe"
    ],
   "score" : 2
  }

```

Thanks

# Answer
A lot of Adventure/RPG games handle this in two ways (there may be more I'm not aware of).

**Use of flags**

The first one is to set a flag if something happened (usually some bitmask). This is fine if you don't have many things to track. In the room/encounter there may be a check against a flag that alters something. In your example could add a rule:

```
{"text" "You meet a mushroom who tells you the princess is in another castle",
"options":[
  4: "Give up, game over", // something to handle game over
  8: [64:"Jump down the pipe", "Exit stage left"]
  ],
 "score" : 2
 "setflag" : 32
}

```

Where the 2nd option only appears if `flags & 64` is set. You could also implement the `setflag` option if the scene appears, or a particular choice was made.

**Use of items**

The second option, is to add items to the player's inventory. These are the "this item is needed to complete a quest" you see often in games. These basically function as portable 'flags'. This can be implemented two ways (or a combination):

* The item is the 'flag': Have the scene or dialog check if the player has a specific object in their inventory. This is much like the 'check for a flag' mechanic as described above. The upside is that it may be much easier for you to design encounters as you're checking against familiar named objects.
* Items have properties that work as a flag. For example in The Witcher 3, the player obtains an object that can dispel illusionary walls. That item itself could be a 'flag' but it could also be that the object has a property `can_dispel_illusions`. The upside here is that you could implement multiple objects that can be used in the same scenario. Thus a scene/dialog/door could check if the player has 'something' in their inventory that has the property `can_dispel_illusions`.

This gives you the possibility to give the player the illusion of choice; if the player didn't encounter the witch in scene one, thus missing the 'wand of dispel' the player could get a 'ring of dispel' later from some shady merchant- preventing an unwinnable state of the game.

If you don't plan to give the player a "real" inventory, the quest items could go to a list -hidden from the player.

example:

```
{"items":[
  "Wand of Dispel": { "properties": ["can_dispel_illusions","illumination"]}
]}

```

and:

```
{"text" "The corridor ends in a dead end. The wall feels cold when you touch it.",
"options":[
  4: "Turn back",
  8: {"can_dispel_illusions": "Check if the wall is real."}
  ],
 "score" : 2
}

{"text" "The witch hands you an object. She observes what you're going to do next.",
"options":[
  14: "Leave the witch's house",
  22: "Look at the object."}
  ],
 "giveitem" : "Wand of Dispel"
}

```
> 13 votes

# Answer
One solution I've seen that elaborates on your approach is to have various attributes with associated scores. Some choices result in modifying the one or more of these scores. The scores in turn may modify the choices available to the player.

For instance, early in the story, there may be some option combat encounters. If the player engages in combat, the bravery attribute would increase, whereas fleeing would cause it to decrease. Later on, a particular story branch might only be available if bravery score was above or below a given threshold. To add more depth, some decisions should affect more than one score. For instance, picking pockets might increase a stealth score and decrease an honesty score.

Generally, I've seen this approach used in simulation type interactive fiction. You can hear Dan Fabulich from Choice Of Games discuss this solution on this episode of the Game Design Round Table.

The benefits of this approach are:

* each decision doesn't need to provide a unique ending, reducing the total number of endings required
* there can be more than one way to reach a given ending, allowing for more variety in rewarding play styles

Some drawbacks are:

* if decisions hinge on single attributes, it can be shallow & formulaic
* conversely, if decisions are too complex, balancing the game / story becomes more difficult
> 2 votes

# Answer
This is the big problem story-driven games face: Combinatorial explosion. As such, if you look at e.g. Bioware or Telltale games, you'll find that the most common approach seems to still be to try to restrict the story to being more linear, and keeping consequences from actions limited to their chapters.

The approach Bioware seems to be using splits each story up into separate threads or sub-arcs. The arcs are pretty much independent from each other, but happen simultaneously and may all contribute to the ending. That way, you don't have to model each combination of arcs, you just alternate chapters between arcs, and consequences are limited to the particular sub-arc you're dealing with right now, or how to end an arc. (or how to end a character's arc. If you no longer need that NPC, you're often given the choice of killing them, arresting them, or setting them free, for example, giving you choice, but limiting the consequences to the rest of the story)

The ending of the entire story then only needs to know how each arc ended, and tie up the whole narrative in a neat little bow.

**How would you model that in a program?**

This simply pushes the problem down one level (because each sub-arc needs to track differences like a simple story would), but basically you'd have an array of flags (e.g. a bit field, or a list of items with flags representing the ability to effect certain outcomes) for each sub-arc.

Also, when you're telling your ending, you usually take the same approach of alternating when you tell the player about the consequences: Each sub-arc's result gets its own paragraph/conversation node, simplifying your conditionals greatly.
> 1 votes

# Answer
It may take a bit of time, but developing your own tree (like a behavior tree or dialog tree, but for pages) might be beneficial. And you could use one of those as a model. Something like this:

How do dialog trees work?

This would allow you to tailor it for your specific needs, but also let the code handle most of the work.
> 0 votes

# Answer
What if you used a rule engine type approach? When a player interacts with an NPC, the game would run a stripped down rule engine which would start with flags that had been created by past choices/behavior and check it against a set of rules defined by you in advance. Something like Drools is probably too big and ambitious, not to mention slow, but a limited scope rule engine could theoretically give you better performance and a lot of flexibility.
> 0 votes

---
Tags: game-design, game-mechanics, logic
---


# Question
Title: Why is there no glClear() and glClearColor() method in GL30?
In the `GL30` interface, both the methods `glClear()` and `glClearColor()` are absent. I tried to call the method `Gdx.gl30.glClear(GL30.GL_COLOR_BUFFER_BIT)` inside `render()` but it threw me a null pointer exception. So I checked the interface. There's no `glClear()` method in `GL30`. Only in `GL20`. But OpenGL documentation says that they are supported in both v2.0 and v3.0. Why is it not included in LibGDX?

# Answer
LibGDX is primary written in java, so it binds OpenGL functions to java methods. In the process of binding LibGDX is not required to keep original namespaces (java's equivalent of c/c++ namespace is package). LibGDX has a few classes which contain bindings to OpenGL functions and fields. Those classes extend each other: class containing bindings to the most recent supported version of OpenGL inherits a class with a prior version.

Lastly, GDX instantiates the last subclass so you can call any GL function from there not bothering about which specification of OpenGL implements it.

Also ,as said in another answer, you should config GDX to enable functions of OpenGL 3.0:

```
config.useGL30 = true;

```
> 1 votes

# Answer
You must configure GDX to use GL30 prior to calling functions on `Gdx.gl30`:

```
config.useGL30 = true;

```

`com.badlogic.gdx.graphics.GL30` does not contain `glClear` and `glClearColor` in its interface because it is a subclass of `com.badlogic.gdx.graphics.GL20` and those functions are inherited from `GL20` therefore there is no need to define them in `GL30`'s interface.

See the Gdx docs for Methods inherited from interface com.badlogic.gdx.graphics.GL20.
> 3 votes

---
Tags: opengl, libgdx, opengl-es2, opengl-es3
---


# Question
Title: Unity / How to Hide "Editor Script" in the Inspector?
I want to hide the "editor Script" in the Unity Inspector, so it doesnt show up with all the other components (transform/other scripts etc.) It works with every other "normal" component like this:

component.hideFlags = HideFlags.HideInInspector;

but when it comes to the Editor Script- it just doesnt hide.

EDIT: My Custom Editor Script:

```
using UnityEngine;
using System.Collections;
using UnityEditor;

[ExecuteInEditMode]
[CustomEditor(typeof(DetailCamContScript))]

public class CamEditor : Editor
{

    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();

        DetailCamContScript myScript = (DetailCamContScript)target;
        if (GUILayout.Button("Set Camera Active"))
        {

            myScript.setCamActive();

        }

    }

}

```

EDIT: Problem solved.

the problem was: The editor-script was attached to a Gameobject. It doesnt needs to be attached.

# Answer
I may be misunderstanding, but an editor script doesn't need to be attached to anything. If it's not attached, there's no place for it to show up. If the editor script is in an Editor folder, it places itself in the UI without being part of a game object.
> 2 votes

# Answer
You don't need to attach the custom editors as components. You can leave them in assets folder without attaching them to a gameobject.
> 1 votes

---
Tags: unity
---


# Question
Title: Unity: Build on specific wall of the box
I'm trying to program game similar to Minecraft - you build environment from cubes. So far I found that Unity has a function which tells if mouse is over a box collider. I need a function which will tell me if my mouse is touching specific wall of the cube - to be able to add a cube from side of this wall. I was thinking about many solutions - most obvious is to make a new cube from six different walls which own collider for each one - for me it sounds like a little overkill. I could also try to get it from position of mouse, camera and center of a box... but it sounds like even bigger overkill.

How would you solve this problem?

# Answer
**Use the normal from the collision point of a raycast**

Ensure that your world is axis aligned for this to work properly.

Cast a ray from your camera to your mouse into the scene. When it collides with a box collider, utilize the normal property of the RayCastHit object to determine which side of the cube was hit.

The normal will tell you which direction to move away from your existing cube to place the new cube.
> 2 votes

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


title: Generate camera shakes in Java

text:
# Question
Title: Generate camera shakes in Java
How would one of these work?

(If you don't know what I'm talking about, think like in a game where you shoot a big gun, and your screen bounces in the opposite direction.)

I've been experimenting with a couple different ideas but none are either fully working, or fully smooth.

Using this function for setting the camera position:

```
x = -target.x + halfScreenW;
y = -target.y + halfScreenH;

```

One problem I've run into is when setting the camera to move a certain distance in a direction, it will reach its target X or Y before the other, causing it to go travel in a straight line for a short while. I believe the solution to this is using the Bresenham line algorithm?

What would be the best way to achieve a camera shake?

edit: Related - Realistic Camera/Screen Shake from Explosion

# Answer
> 1 votes
A favorite way to apply camera shake in 2D (or 3D) is to attach the camera's origin to a physics particle, then to attach the physics particle to the focus of the scene with a heavily-damped spring. This allows for adding variable camera shake quite easily, in any direction you want, by adding momentary acceleration (a poke) to the camera's physics particle. As an added bonus, the inertia of the camera will make it move differently in response to a moving focus, which can make acceleration of the focus feel a lot cooler.

---
Tags: java, 2d, camera
---


title: Correct way of managing player states?

text:
# Question
Title: Correct way of managing player states?
I'm a relatively new programmer attempting to create a simple 2d fighter for fun using the SFML 2 library. As a game with interaction dependent on what the character is doing, using a state system seems to be the way to go. I've been trying to incorporate a finite state machine. My question is, what is the best way to go about this? Currently I have something like this:

```
switch (playerstate)
{
case idle:
    if (!onGround)
    {
        playerstate = fall;
    }
    else if (sf::Keyboard::isKeyPressed(controls.Up))
    {
        moveUp();
        playerstate = air;
    }
    else if (sf::Keyboard::isKeyPressed(controls.Down))
    {
        playerstate = crouch;
    }
    else if (sf::Keyboard::isKeyPressed(controls.Right))
    {
        moveRight();
        playerstate = dash;
    }
    else if (sf::Keyboard::isKeyPressed(controls.Left))
    {
        moveLeft();
        playerstate = dash;
    }
    else
    {
        decelOnGround();
    }
    break;
case dash:
    if (!onGround)
    {
        playerstate = fall;
    }
    else if (sf::Keyboard::isKeyPressed(controls.Up))
    {
        moveUp();
        playerstate = air;
    }
    else if (sf::Keyboard::isKeyPressed(controls.Down))
    {
        playerstate = crouch;
    }
    else if (sf::Keyboard::isKeyPressed(controls.Right))
    {
        moveRight();
    }
    else if (sf::Keyboard::isKeyPressed(controls.Left))
    {
        moveLeft();
    }
    else
    {
        decelOnGround();
        playerstate = idle;
    }
    break;
case air:
    if (onGround)
    {
        playerstate = idle;
    }
    else if (sf::Keyboard::isKeyPressed(controls.Up))
    {
        // if numOfJumps > 0, moveUp();
    }
    else if (sf::Keyboard::isKeyPressed(controls.Down))
    {
        fastFall();
    }
    else if (sf::Keyboard::isKeyPressed(controls.Right))
    {
        moveRight();
    }
    else if (sf::Keyboard::isKeyPressed(controls.Left))
    {
        moveLeft();
    }
    break;
case fall:
    if (onGround)
    {
        playerstate = idle;
    }
    else if (sf::Keyboard::isKeyPressed(controls.Down))
    {
        fastFall();
    }
    break;
case crouch:
    if (sf::Keyboard::isKeyPressed(controls.Up))
    {
        moveUp();
        playerstate = air;
    }
    else if (sf::Keyboard::isKeyPressed(controls.Down))
    {
        decelOnGround();
        playerstate = crouch;
    }
    else if (sf::Keyboard::isKeyPressed(controls.Right))
    {
        moveRight();
        playerstate = dash;
    }
    else if (sf::Keyboard::isKeyPressed(controls.Left))
    {
        moveLeft();
        playerstate = dash;
    }
    else
    {
        playerstate = idle;
    }
    break;
default:
    std::cout << "ERROR\n";
}

```

Which as you can see, there is a lot of repetition and a lot of code. I haven't even incorporated using different attacks yet (I'm going to have a variety of these). Am I approaching this the wrong way? Should I instead have each control be a case instead and branch from there? Any help is appreciated!

# Answer
> 4 votes
You should not have if-statements nor case-statements; at least not nearly so many.

The immediate problem is that you're hard-coding a bunch of logic where a data-driven approach would work better. What you have here on first glance is a state graph (or a finite state machine). Rebuilding this as a state graph with inputs triggering transitions would be a first pass "cleanup".

The second pass then is to move all the specifics into separate logic or data. e.g., once you have a state graph runtime, even your hardcoded logic becomes much simpler:

```
state idle = machine.createState();
state falling = machine.createState();
state moving_right = machine.createState();
state moving_left = machine.createState();

idle.when([]{ !player.isGrounded(); }, falling);
idle.when([]{ isKeyDown(KEY_LEFT); }, moving_left);
idle.when([]{ isKeyDown(KEY_RIGHT); }, moving_right);

moving_right.update([]{ player.moveRight(); });
moving_right.when([]{ !isKeyDown(KEY_RIGHT); }, idle);
moving_right.when([]{ !player.isGrounded(); }, falling);

// and so on

```

You can also support hierarchical graphs so e.g. your attacks can be their own state graphs independent of moving.

With scripting or some other binding system, this can also easily become a data file. Data files are nice because you don't have to recompile to test changes. If you have hot reload support you can even tweak your data while playing the game, which *really* speeds up the development process.

The data then can map to your animation system, giving you controls on animation loops for states or for animations to play on transitions. A more "production grade" approach would also allow the animation system to feed back into the game logic, letting you tie attach hit boxes and such into the animations, or triggering audio and particles from animation frames, or even controlling physics (e.g., you wouldn't hardcode the movement logic into your movement state, but rather give your movement animations the "apply X force" action, making moving tied to animation state, and blendable if you have multiple animations that might affect movement).

---
Tags: c++, 2d, sfml
---


# Question
Title: Unity - How to serialize / show private fields and custom types in Inspector?
By default, Unity only serializes public fields. How can I serialize private fields and custom types to show them in inspector?

# Answer
> 5 votes
The `[SerializeField]` attribute instructs Unity to serialize the field regardless of the accesibility.

All three fields below gets serialized and shows up on inspector:

```
[SerializeField]
private int _foo;

[SerializeField]
protected int _bar;

[SerializeField]
internal int _baz;

```

---

Note that, in order to expose custom types in Inspector, you need to explicitly mark them with `[System.Serializable]` attribute.

All `Foo1` `_foo2` `Bar` `_baz` `_qax` gets serialized and shows up on inspector:

```
public Foo Foo1;
[SerializeField] private Foo _foo2;

[System.Serializable]
public class Foo
{
    public int Bar;
    [SerializeField] private int _baz;
    [SerializeField] protected int _qax;
}

```

---

However, there are some restrictions on serializing:

* Only primitive types internal Unity types, and custom types that marked with `System.Serializable` can be serialized.
* Custom generic types can't be serialized.
* Properties can't be serialized.
* Dictionaries, multi-dimensional arrays, and most of the complex collection types can't be serialized.

---

## Workarounds on restrictions

### Custom inspector scripts (aka Custom editors)

Nearly in all cases where Unity can't serialize something on itself, you can write an editor script to tell Unity how to show the type in Inspector. For more information about custom editors:

Video tutorial about Custom Inspectors
Unity documentation page about Custom Editors

### Wrapper classes and "faking" the type

When Unity can't serialize a collection, you can create a custom class to fake the data structure of the type.

If we take Dictionary type for example, you can fake it with an array of a wrapper class:

**The *original*:**

```
public Dictionary<string, int> FoobarDictionary;

```

**The *fake*:**

```
public FakeEntry[] FakeFoobarDictionary;

[System.Serializable]
public class FakeEntry
{
    public string Key;
    public int Value;
}

```

And with some LINQ, you can basically get a similar behaviour:

```
//using System.Linq;

public int GetFooBarValue(string key)
{
    try
    {
        return FakeFoobarDictionary.Single(a => a.Key == key).Value;
    }
    catch
    {
        throw new KeyNotFoundException("There is no entry that has the given key.");
    }
}

```

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


# Question
Title: Should I use single state or multiple state of an entity in finite state machine?
In the below code, is the options I've created whether to use single or multiple states for my character or other entity. Still can't decide which one is better inf using state machines.

```
public enum CharacterState implements State<Entity> {

    animation // ...
    movement // move_down, move_up ...

}

public enum AnimationState implements State<Entity>
public enum MovementState implements State<Entity>

```

# Answer
> 2 votes
The character should have a single state machine.

Animations should be controlled by the character state so they don't need their own character-specific state machine except as part of a generic animation system.

Status variables (health, ammo, invincibility timer, inventory, etc) are part of deciding which state to transition to but not state machines in themselves.

If there seem to be a need of multiple state machines this usually means the character should be split up into different entities, the AI simplified, or both.

The main reason for this is the K.I.S.S. (keep it stupid simple) principle. Multiple state machines on an entity will too often create unexpected combinations of states, often soft-locking the game in a way that is hard to trace and debug.

If, for example, state machine A has 12 states, state machine B has 5, you have 60 possible combinations that may happen, many of which are probably invalid. Trying to figure out which one of those 59 other possible combined previous states is responsible for entering the current combination becomes a much bigger task.

---
Tags: java, libgdx, state, fsm
---


title: Thrown exception pointing to xmemory0

text:
# Question
Title: Thrown exception pointing to xmemory0
Within a static library I'm creating, I have a struct called `Vertex` that holds three variables used for an image drawn on a plane:

```
struct Vertex
{
    glm::vec2 Position;
    glm::vec3 Color;
    glm::vec2 TexCoord;
};

```

and a list of vertices like so (outside of the class):

```
const std::vector<graphics::Vertex> vertices =
        {
            { { -0.5f, -0.5f },{ 1.0f, 0.0f, 0.0f },{ 0.0f, 0.0f } },
            { { 0.5f, -0.5f },{ 0.0f, 1.0f, 0.0f },{ 1.0f, 0.0f } },
            { { 0.5f, 0.5f },{ 0.0f, 0.0f, 1.0f },{ 1.0f, 1.0f } },
            { { -0.5f, 0.5f },{ 1.0f, 1.0f, 1.0f },{ 0.0f, 1.0f } }
        };

```

When I run the program, I get a thrown exception and points to line 637 in xmemory0:

```
template<class _Objty,
class... _Types>
void construct(_Objty *_Ptr, _Types&&... _Args)
{   // construct _Objty(_Types...) at _Ptr
    ::new ((void *)_Ptr) _Objty(_STD forward<_Types>(_Args)...); // here
}

```

But when I put all my code in main.cpp without modifying anything, the program works as expected.

When the thrown exception is triggered from running my code in the static library, the output points to (in red) Position, Color and TexCoords with these values:

```
Position x=0.0... y=4.059...e-34
Color x=7.119e-43#DEN y=4.0428...e-34 z=7.119e+34
TexCoord x 1.40...e+34 y=4.591e-41#DEN

```

# Answer
Variables and objects in different translation units (c++ / object files) do not have a guaranteed initialization order.

It is possible that your std::vector is being used by another global (or static) object constructor in another file before it is actually initialized.

Put all the dependent variables in order within the same file or initialize them in a controlled fashion some other way, such as inside an Init() function called from main but for this you will need to make it non-const.

Edit: It's called the "static initialization order fiasco".

The C++ initialization steps in practice are:

1. null pointers / zero variables get initialized by the OS when loading the executable (BSS section)
2. Simple struct and classes (POD) and variables with non-zero values either get initialized by the OS during exectuable loading (DATA section) or on embedded systems by copying from ROM in the pre-main() code.
3. Constructors inside each object files get called in order where they are inside the files but no guarantee between individual object files.
4. main() gets called
5. main() returns
6. Destructors are called. It's supposed to be in reverse order but speaking from experience it's not always the case (yes, it's a compiler/linker/SDK bug when it happens but that doesn't change your project deadline.)

1 and 2 are called **static initialization**

Note that what is a POD type (Plain Old Data) varies according to what C++ standard you're using.

Something that is safe:

**FileA.cpp**

```
const char * const my_string = "ABC";

```

**FileB.cpp**

```
extern const char * const my_string;
std::string my_std_string (string);

```

`my_string` is a simple pointer that gets initialized by loading the DATA or RODATA segment before all constructors get called.

Something that depends on initialization order:

**FileA.cpp**

```
std::string my_std_string1("ABC");

```

**FileB.cpp**

```
extern std::string my_std_string1;
std::string my_std_string2 (my_std_string1);

```

If my\_std\_string2's constructor is called before my\_std\_string1 (the linker decides, different linkers pick different orders) it may copy garbage values or nulls depending on the system.
> 3 votes

---
Tags: c++, visual-studio
---


# Question
Title: Why is my zooming-in + changing scenes not woking in Unity?
I'm zooming on a map using Math.Lerp and then I use the scene manager to change the scene. Here is my attempt but it doesn't work on the map.

I have attached it to the main camera, in the worldView:

```
public class zoom : MonoBehaviour {

    // Use this for initialization
    private bool zoomedIn = false;
    int zooom = 20;
    float smooth = 5f;
    void Start () {
        SceneManager.LoadScene("worldView");
    }
    // Update is called once per frame
    void Update () {
        if (Input.GetMouseButtonDown (0)) {
            zoomedIn = !zoomedIn;
        }
        if (zoomedIn == true) {
            Camera.current.fieldOfView = Mathf.Lerp (Camera.current.fieldOfView, zooom, Time.deltaTime*smooth);
            SceneManager.LoadScene("countryView");
        }
    }
}

```

# Answer
> 1 votes
Your script causes a LoadScene to occur on startup, which means the scene will load, and then immediately after loading it will try to load the same scene again, resetting it to the starting state again.

Ignoring that issue, you're not giving the camera script enough time to zoom the camera in. You're loading a new scene on the same frame that you start modifying the camera field of view. You need some timer so the camera has time to zoom in.

If your intent is for this script to persist between scene changes, you need to tell the gameobject not to destroy on load: https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html

# Answer
> 0 votes
By some magical way I found out that your camera is orthographic. You don't use `Camera.current.fieldOfView` for orthographic cameras, instead use `Camera.main.orthographicSize`. Adjust the line in the second if condition to be

```
Camera.main.orthographicSize = Mathf.Lerp (Camera.main.orthographicSize, zooom, Time.deltaTime*smooth);

```

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


title: Difference Between LibGDX and LWGJL

text:
# Question
Title: Difference Between LibGDX and LWGJL
I've been looking into developing a small game with Java, as I am fairly familiar with it and see game development as good opportunity to improve my knowledge. When I research different libraries and other such things, the two resources I have often seen are LibGDX and LWJGL. I am however still unsure of the differences between the two. Would someone be able to explain where the differences lie and what each's strength is.

# Answer
LibGDX is based on LWGL and its advantage are that a lot of the base stuff is already written and you don't need to write it. Some people prefer to write it themselves though. LibGDX is generally used in mobile game development, but can also be used on Windows, Mac and Html.

Some final words: For beginners I would suggest using LibGDX, because it is easier to understand and LWJGL is very complicated for beginners.
> 7 votes

# Answer
## LWJGL is Lightweight Java Game Library. It is not engine.

LWJGL is a Java library that enables cross-platform access to popular native APIs useful in the development of graphics (OpenGL), audio (OpenAL) and parallel computing (OpenCL) applications. This access is direct and high-performance, yet also wrapped in a type-safe and user-friendly layer, appropriate for the Java ecosystem.

More info you can find at **LWJGL site**

## LibGDX is based on LWJGL java game development framework.

Libgdx is a Java game development framework that provides a unified API that works across all supported platforms.

The framework provides an environment for rapid prototyping and fast iterations. Instead of deploying to Android/iOS/Javascript after each code change, you can run and debug your game on the desktop, natively. Desktop JVM features like code hotswapping reduce your iteration times considerably.

More info you can find at **LibGDX site**
> 4 votes

# Answer
LWJGL is simply a wrapper for the C libraries OpenGL, OpenAL and OpenCL. It provides access to the raw functions that the C libraries provide.

With LWJGL as it's core, LibGDX provides a framework. It provides a gameloop,a rendering system, an audio system as well as other features. LibGDX abstracts the basic LWJGL interface from you. It provides an Object-Oriented package to make games.
> 1 votes

# Answer
LWJGL is a low level framework that includes window creation, input handling and other low level features. Libgdx is a full featured 2d and 3d game framework that is built on top of LWJGL.

The typical workflow for drawing a triangle on screen with LWJGl is: 1- Create a window using the included GLFW3 framework. 2- Create an Opengl context using the built in functionality that come with GLFW. 3- Call OpenGL and draw your triangle. Each step will take a lot of coding.

The workflow for Libgdx is: 1- Setup the project using the provided GUI tool. 2- Build and run the generated project and you have example code that loads an image and displays it. In Libgdx all the low level stuff is handled for you and you just have to worry about designing and developing your game.

If you want to make a game as quickly as possible then go with the JmonkeyEngine. The engine lets you go low level if you need to(the LWJGL route) or the Libgdx way but with a GUI engine included.

If your goal is to learn java without the game development quirks then just use JavaFx or the Java Canvas and push out your games. This will be easiest route to take and you will be working with Java APIs more than dealing with game development specific details.
> 0 votes

---
Tags: java, libgdx, lwjgl
---


title: Ball bouncing with box2d in libgdx

text:
# Question
Title: Ball bouncing with box2d in libgdx
I just started using Box2d and libgdx. I followed this tutorial, https://github.com/libgdx/libgdx/wiki/Box2d And a ball would bounce if I run the following code I took from the tutorial.

```
// ...omit the rest of code
World world = new World(new Vector2(0, -10), true);
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyType.DynamicBody;
bodyDef.position.set(100, 300);
Body body = world.createBody(bodyDef);
CircleShape circle = new CircleShape();
circle.setRadius(6f);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = circle;
fixtureDef.density = 0.5f;
fixtureDef.friction = 0.4f;
fixtureDef.restitution = 0.6f; // Make it bounce a little bit
Fixture fixture = body.createFixture(fixtureDef);
circle.dispose();
// ...omit the rest of code

```

I'm wondering how I can make the ball bounce like a basketball or volleyball? It's like the ball movement is in a space, move so slowly. I changed some properties such as density or friction, but it seems box2d doesn't care of air friction, so nothing changed at all. Could you tell me how I can make the ball movement to be a basketball or such stuff?

# Answer
I now understand how box2d works. It is 1 pixel = 1 meter and my screen size is 480 * 320. That means 480m * 320m in box2d! It is so huge. So I just needed to convert default positions of box2d Bodies something like 1/32, then box2d worlds would be like 15m * 10m. To confirm things going well, I needed to put some sprites to draw in actual size which is 480 * 320. I multiplied box2d bodies position with 32.
> 3 votes

# Answer
Best way to do this is by damping factor. LinearDamping and AngularDamping factor can be modified according to your requirement. Just try and manipulate these two parameter according to your choices.
> 0 votes

---
Tags: libgdx, box2d
---


# Question
Title: How to set object's / node's absolute rotation correctly?
Usually when I want to rotate an object/node in my Ogre scene I call the node's `rotate()` method. That rotates the node locally relative to it's current rotation. So for example, when I start with 0 rotation, then rotate twice for 5 degrees about one axis, then after the second call the object is rotated by 10 degrees in total.

Now I need to set the absolute rotation of the node/object directly, regardless of its current rotation. Thus, say I don't know the objects current rotation, I need to set it say to 45 degrees on the X axis. Something like `setRotation()`.

I know there is a `setOrientation()` method in the `SceneNode` class, which expects a quaternion object. I also know that I can get the current orientation quaternion. What I don't know: how can I use/change this current orientation quaternion to set the new absolute rotation of the node?

PS: Crosspost at http://www.ogre3d.org/forums/viewtopic.php?f=2&t=77710

# Answer
> 0 votes
I'm just replicating the answer from that crosspost :D

`setOrientation(Quaternion(Degree(45),Vector3(1,0,0)));`

---
Tags: rotation, ogre, quaternion
---


# Question
Title: Why do modern games use a render-to-texture approach for mirrors?
When looking at old games like Mario64 or DukeNukem3D, all the mirrors in the game are essentially just holes in the wall with a mirrored copy of the geometry in front of the mirror put behind them. In the case of DukeNukem3D one can even activate no-clip and walk into that mirrored room.

In contrast modern games use a render-to-texture approach for mirrors. This leads to the mirrors getting noticeably pixelated when getting to close to them. One of the first games I noticed this approach was Luigi's Mansion, but it seems to be used in almost all modern games.

What change in the hardware or engines made the second approach become so dominant these days and what are the benefits to it? In terms of pure visuals the first approach seems superior, as it doesn't suffer from pixelation issues.

# Answer
1. Using RTT (render-to-texture) allows to easily scale rendering quality (resolution, LOD, lighting complexity) for adjustable performance. RTT also makes it easier to replace the surface with a cubemap at a certain distance where it's hard to see the reflection exactly.
2. Since the output is a texture, there are more options regarding what can be done with it afterwards (lighting, shading, blending, distortion etc.).
3. If a mirrored version of geometry is placed in the scene, it would require more complicated culling when it intersects with real geometry and could be seen behind the corner. In older games, levels were designed to avoid this. Not to mention that somebody has to do the actual mirroring.
4. If geometry is not manually mirrored, rendering must be done by changing the view matrix and culling mode (to compensate for the space inversion in the matrix), and using the stencil buffer to cut out the mirror. Modern engines prefer to create all render states in advance, so there would be a minor issue with making copies of every scene render state with the required changes for mirror rendering.

So basically using RTT gives more freedom to everyone.
> 38 votes

# Answer
No, you are wrong - that's not how Duke Nukem 3D's mirrors worked at all.

DN3D used a *portal engine*. A joint between any two sectors was arbitrary to an extent, and when the rendering engine came to a portal, it knew that it has to start rendering another sector in that. The sector behind the mirror was basically a place holder to deal with a quirk in the engine - the only point of the sector was to be bigger than whatever you needed "reflected". It didn't contain any real geometry. In fact, it worked pretty much the same way "portals" work in Portal - except that Portal (itself being based on a portal engine) creates the portals at runtime, and has a limit to how many times the portals can recurse (i.e. A -\> B -\> A -\> B -\> A ...), while Build (DN3D) would simply crash as its stack overflowed if you pointed a mirror at another mirror.

It's obvious how simple it is to implement a mirror with that - make a portal that points *back* into the room. This meant that rendering the mirror would cost exactly as much as rendering the room itself, giving great performance and consistency. As long as you didn't point a mirror at another mirror, that is. If you look through the Build engine source code, you'll see there's no code handling mirrors at all - there doesn't have to be one, because that's how portals work *NOTE: actually, there is code to flip the rendered pixels - it just doesn't flip the geometry and all the various sprites and effects*. The editor had to be able to make these "fake" portals, though - looking back on itself. If you want to know more about the quite smart Build engine, there's a great analysis by Fabien Sanglard at Build engine internals. The whole engine has been open sourced and ported to modern platforms as well, though the old one still works flawlessly on Windows 10 (tested for you :P). Many of the games based on Build have also been open sourced and/or remade.

Why is this no longer used? Well, some engines no longer prefer portals, for one. It's tricky to apply a lot of graphics hacks and optimizations - I can't point you to anything specific, but a lot of post-processing depends on hacks that wouldn't work in a true portal engine (they make a lot of assumptions that no longer hold). This is basically the same kind of issue these games have with stereoscopic imagery - the hacks no longer work.

Most importantly, mirrors got more complicated. They can have complex shapes, textures, they may be on the ground (also known as "water") etc. While all of those problems are solvable in a portal engine, RTT becomes the simpler choice at some point, and GPUs are fast enough to handle it.

However, even with all that, there are plenty of games with hardware 3D acceleration that do things "real". Of the older games, Quake 3 or Alien vs. Predator, for example. As far as I know, Source engine games still use "real" mirrors. If you expect that people are going to get close to the mirror, and you can guarantee that there's not too many reflective surfaces at the same time (e.g. through level design), portal mirrors are still very attractive.
> 30 votes

# Answer
RTT would have been used if it was possible but the hardware rendering pipeline was one way.

Older hardware also had limitations that prevented render to texture. Writing to RAM means it can not be read at the same time. To improve rendering performance the destination buffer was locked to write only, only the display hardware could read from it. You could request reading, but that locked the RAM and the render had to wait for the lock to clear before it could start the next frame. RTT would cause a major bottleneck to the pipeline and thus other solutions were used.

You will find that befor Hardware rendering pipelines were the norm RTT was used as it provided a way to reduce the rendering load. 3D rendered to sprites to provide pseudo 3D content. Texture rendering was way too costly (CPU) to be used back then, apart from specialised machines that were outside the general consumer market.
> 3 votes

# Answer
Duke Nukem handle that by re-rendering the geometry behind the mirror, the other answers are partially correct. There are areas behind mirrors that actually contains no geometry (in game data files), the geometry is re-rendered at run time infact, the reason for those areas to exist is to avoid to place accidentally a piece of level there when editing the level:

since theres' an area marked you will not place accidentally any geometry in there.
> 1 votes

---
Tags: 3d, rendering
---


# Question
Title: Rotate character 180 degrees determine direction
In my game it should be possible to rotate the character 180 degrees. I always want the character to rotate clockwise.

If the character is rotated 0 degrees and I press the rotate button, the character rotates clockwise to 180 degrees. However, if I know press the rotate button again, the character rotates to 0 degrees but doing so counterclockwise. How can I modify my code so that the character always rotates in a consistent direction?

*One solution I've been thinking of is to do the rotaiton in steps like on first button press { 90, 180 } and on second {270, 0 }...*

Any help would be greatly appreciated!

```
_currentTurnAroundAngle += TurnAroundSpeed*Time.deltaTime;

transform.rotation = Quaternion.Euler(0, Mathf.Lerp(transform.rotation.eulerAngles.y, _targetTurnAround, _currentTurnAroundAngle), 0);

if (transform.rotation.eulerAngles.y >= (_targetTurnAround - 0.1f) && transform.rotation.eulerAngles.y <= (_targetTurnAround + 0.1f))
{
    _currentTurnAroundAngle = 0;
    transform.rotation = Quaternion.Euler(0, _targetTurnAround, 0);
    _targetTurnAround = (_targetTurnAround == 0 ? 180 : 0);
    _isTurning = false;
}

```

# Answer
> 0 votes
Try Mathf.LerpAngle(). So, this line becomes:

`transform.rotation = Quaternion.Euler(0, Mathf.LerpAngle(transform.rotation.eulerAngles.y, _targetTurnAround, _currentTurnAroundAngle), 0);`

Some suggestions:

1. In general, you should keep the start and end angles, and lerp between them. Right now you are lerping from the current angle rather than the start angle.
2. When you have two angles and you want to make an operation between them (add, subtract, lerp, compare, etc.), you should move them to the same 360 region. For example, if your angles are -300 and 300, you should convert the first -300 to 60, which represents the same angle.

Here is a way I do that:

```
float angle1 = -300;
float angle2 = 300;
while (angle1 - angle2 > 180) angle2 += 360;
while (angle2 - angle1 > 180) angle1 += 360;
Assert.IsTrue(Mathf.Abs(angle1 - angle2 <= 180));

```

# Answer
> 0 votes
Could you not simply use

```
transform.Rotate(Vector3.up * Time.deltaTime * rotateSpeed);

```

And have it stop rotating once it hits 180 degrees? As I recall, transform.Rotate will always rotate clockwise unless you provide it with a negative number, in which case it will rotate counterclockwise.

Or, a different approach would be to go between from 0 to 180 and from 180 to 360, rather than from 0 to 180 and from 180 to 0. Since 0 = 360, you could just reset your rotation after the second turn.

---
Tags: unity, rotation, quaternion
---


# Question
Title: Why object spawn duplicate and double sides.?
I have a script, I am using this script to instantiate new path and also wall (as border) to generate new path and wall. Before some time all scripts work fine. but at this time my player enter in empty trigger collider 3 times to generate new path.

I am using capsule as player and also capsule collider. when my game start my player enter 2/3 times to empty collider(PathSpawnCollider) so it give me unwanted path and boundary walls.

Any one can help me what is problem here in my code.?

**PathSpawnCollider.cs**

```
using UnityEngine;
using System.Collections;

public class PathSpawnCollider : MonoBehaviour {

public float positionY = 0.81f;
public Transform[] PathSpawnPoints;
public GameObject Path;
public GameObject DangerousBorder;
public Transform[] BorderSpawnPoints;

void OnTriggerEnter(Collider hit)
{
    //player has hit the collider
    if (hit.gameObject.tag == "Player") {

            //find whether the next path will be straight, left or right
            int randomSpawnPoint = Random.Range (0, PathSpawnPoints.Length);
            //int randomBSP = Random.Range (0, BorderSpawnPoints.Length);
            for (int i = 0; i < PathSpawnPoints.Length; i++) {

                //instantiate the path, on the set rotation
            if (i == randomSpawnPoint) {
                Debug.LogError ("Value of if i : " + i);
                Instantiate (Path, PathSpawnPoints [i].position, PathSpawnPoints [i].rotation);
            }
                else {
                Debug.LogError ("Value of else i : "+i);
                    //instantiate the border, but rotate it 90 degrees first
                Vector3 rotation = BorderSpawnPoints [i].rotation.eulerAngles;
                    rotation.y += 90;
                Vector3 position = BorderSpawnPoints [i].position;
                    position.y += positionY;
                    Instantiate (DangerousBorder, position, Quaternion.Euler (rotation));
                }
            }
        }
    }

```

}

# Answer
> 0 votes
I solve my question with some different logic.

I have changed for loop to while loop and increase I in last of all code, and problem solved.

```
while(i < PathSpawnPoints.Length){

//all code here

i++;
}

```

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


# Question
Title: How to get a position from a radial distance and angles?
I have a radius and the 2 angles for northSouth and eastWest rotations in degrees. I need a Spherical position or a cartesian position (I have code translate one to the other)

Where a position is defined as one of the following ...

```
class Vector {
  public float x; // distance along x axis
  public float y; // distance along y axis
  public float z; // distance along z axis
}

class SphericalPosition {
   public float radius;       // distance from center
   public float azimuth;      // distance from 0 degrees around polar axis
   public float inclination;  // distance up from equator (x,z plane)
}

```

I am looking for an implementation to one of the following 2 methods ...

```
SphericalPosition FromAngles(float radius, float degreesUpDown, float degreesRound)
{

}

Vector FromAngles(float radius, float degreesUpDown, float degreesRound)
{

}

```

EDIT: Maybe someone can confirm or deny this but given a radius and 2 angles I believe this is referred to as a polar coordinate?

So in that light I guess i'm asking how to convert from a polar coordinate defined as the following ....

```
class PolarPos
{
   public float radius;         // distance from center
   public float AngleUpDown;    // rotation of x,z plane
   public float AngleLeftRight; // rotation round y axis
}

```

... in to one of the above

EDIT 2: Ah ha ok it looks like what I have are the radius and ...

orbital / inclination angle (in degrees): http://en.wikipedia.org/wiki/Orbital\_inclination

and the polar / azimuth angle (in degrees): http://en.wikipedia.org/wiki/Azimuth

And essentially I think I need the math to turn degrees in to longitude / latitude type coords (the spherical position as defined above).

# Answer
> 0 votes
I was having this issue today and thought I would share what I found. Link to some Maths!

I resolved this code into the following C# code, making note that my up axis is Y:

```
private Vector3 getPosition(float hAngle, float vAngle, float distance)
{
    Vector3 result = new Vector3();
    result.x = (Mathf.Sin(hAngle * Mathf.Deg2Rad) * Mathf.Cos(vAngle * Mathf.Deg2Rad)) * distance;
    result.z = (Mathf.Cos(hAngle * Mathf.Deg2Rad) * Mathf.Cos(vAngle * Mathf.Deg2Rad)) * distance;
    result.y = (Mathf.Sin(vAngle * Mathf.Deg2Rad)) * distance;
    return result;
}

```

Is it the best solution? no idea but it works for me :) hAngle is the horizontal angle around the Y axis, and that * Mathf.Deg2Rad is converting the Euler angle into a Radian.

Hope this helps someone.

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


# Question
Title: Why does accessing ParticleSystem.IsAlive() raise this error?
I am trying to record if my particle system `IsAlive` with:

```
GameObject prefab = Instantiate (Prefab, myPosition, Quaternion.identity) as GameObject;

Component ps = prefab.GetComponent<ParticleSystem> ();
bool checkIfPSPlaying = ps.IsAlive ();
//bool playing = prefab.GetComponent<ParticleSystem> ().isPlaying // This works fine

```

The code above gives this error:

**error CS1061: Type *UnityEngine.Component* does not contain a definition for *IsAlive* and no extension method *IsAlive* of type *UnityEngine.Component* could be found**

What am I doing wrong?

# Answer
> 5 votes
It looks like you haven't set `ps` to the correct type (it should be a particle system). Try something like this:

```
GameObject prefab = Instantiate (Prefab, myPosition, Quaternion.identity) as GameObject;

ParticleSystem ps = prefab.GetComponent<ParticleSystem> ();
bool checkIfPSPlaying = ps.IsAlive ();

```

# Answer
> 1 votes
When you assign an object to a variable with the type of its base class (like `Component` which is the base-class for all components, including `ParticleSystem`) you only get to call those methods which are defined in the base class.

When you want to call methods which are defined in a more specific class, you need to assign the object to a variable of that more specific type. Like this:

```
ParticleSystem ps = prefab.GetComponent<ParticleSystem> ();

```

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


title: camera following player

text:
# Question
Title: camera following player
this code is for camera follow player:

```
    using UnityEngine;
using System.Collections;

public class cameraMovement : MonoBehaviour {
    public GameObject player;
    private Vector3 pos;
    private Vector3 rot;

    // Use this for initialization
    void Start () {
        pos = transform.position;
        rot = transform.localRotation;

    }

    // Update is called once per frame
    void Update () {
        transform.position = player.transform.position + pos;
        transform.RotateAround = player.transform.RotateAround + rot;
    }
}

```

camera position work good.

but camera rotation don't work!! what is the problem?

# Answer
> 1 votes
You have a problem with the way you're trying to set the rotation. transform.RotateAround is a function, not a variable. You can't set transform.RotateAround equal to something else.

The easiest way to get the camera to follow the player would be to make the camera a child of the player in the editor. You wouldn't have to use any scripting at all, and the camera would always follow the player, including rotation.

If you do want to have the camera follow via scripting, you should try transform.rotation = player.transform.rotation + Quaternion.Euler(rot). However, the best way really would be to make the camera a child of the player.

---
Tags: unity
---


# Question
Title: How to have an AI controlled GameObject naively avoid another one?
I have an idea of an AI controlled game which the gameobject will follow a path but it will change its path if I put another gameobject in front of it. For instance, if the moving game object is moving horizontally, and I put a static game object on its path, I want it to turn and continue its progression vertically just before it hits it.

How can I achieve this?

# Answer
You can use raycasting. From the GameObject, cast a ray to `transform.forward` with a specific avoidance range. When raycast hits an object, save the original target, turn either `transform.right` or `transform.left` and continue moving.

From now on, start casting another ray in the direction of obstacle we are avoiding. Continue moving forward until the second raycast hits nothing, then rotate `GameObject` to original target again.
> 1 votes

# Answer
So, if I understand correctly, the existence of the second object (regardless of location) changes the direction of the first object? If that's the case, and there are only two options (move this way without the object, this other way with), then create a bool on the controller of the first object, and either send a message from the second object to set the bool to true on the first object (which would be read by the controller), or have the first object constantly check for the existence of the second object (potentially easier, but much less efficient).
> 0 votes

---
Tags: unity
---


# Question
Title: Object have the same "speed" all time JavaScript
I try to create a 2D game with a big map and multiple objects. The player is always in the middle of the screen and all the other objects is moving around so it feels like a big map.

I want the player to always move after the mouse location. I have modified the mouse location to (0,0) by this:

```
                var mouseX = 0;
                var mouseY = 0;
                if (e.pageX < window.innerWidth/2) {
                    mouseX = -(window.innerWidth/2-e.pageX);
                }else{
                    mouseX = e.pageX-window.innerWidth/2;
                }
                if (e.pageY < window.innerHeight/2) {
                    mouseY = -(window.innerHeight/2-e.pageY);
                }else{
                    mouseY = e.pageY-window.innerHeight/2;
                }

```

That is working just fine. When it comes to the moving part i can't relly get it to move with the same "speed". I have made some animations to explain how it is now and how i want it to be.

How it is now:

DC is the speed that my player would go and as you can see it is moving the most when its closest to x=0 and y=0, i have done it like this so far:

```
            var all = mouseX + mouseY;
            clientsID[key]['x'] += mouseX / all * speed;
            clientsID[key]['y'] += mouseY / all * speed;

```

But as i know it is not working well. Here is a animation to show how i want it to be:

DA would be the speed and it's always 1 because it's radius of the circle. But as i don't know how far the mouse is from the center (mouse is E on the last animation) i have to scale it down somehow.

Does anyone know how to get how much i have to add x and y so the speed always will be the same?

Thank you

EDIT: See the solution under here

# Answer
> 0 votes
I got the solution, it's simple.

This is my animatin for it:

I saw that it make a square out of the lines and then i could get the diagnol in the square. In that way i could get how much i had to scale the mouse x and y to match where it needed to go.

The code would look this this:

```
            if (mouseX >= 0 && mouseY >= 0) {
            var diagonal = Math.sqrt((mouseX*mouseX)+(mouseY*mouseY));
            clientsID[key]['x'] += mouseX/diagonal * speed;
            clientsID[key]['y'] += mouseY/diagonal * speed;
        }
        if (mouseX >= 0 && mouseY <= 0) {
            var diagonal = Math.sqrt((mouseX*mouseX)+(-mouseY*-mouseY));
            clientsID[key]['x'] += mouseX/diagonal * speed;
            clientsID[key]['y'] -= -mouseY/diagonal * speed;
        }
        if (mouseX <= 0 && mouseY >= 0) {
            var diagonal = Math.sqrt((-mouseX*-mouseX)+(mouseY*mouseY));
            clientsID[key]['x'] -= -mouseX/diagonal * speed;
            clientsID[key]['y'] += mouseY/diagonal * speed;
        }
        if (mouseX <= 0 && mouseY <= 0) {
            var diagonal = Math.sqrt((-mouseX*-mouseX)+(-mouseY*-mouseY));
            clientsID[key]['x'] -= -mouseX/diagonal * speed;
            clientsID[key]['y'] -= -mouseY/diagonal * speed;
        }

```

# Answer
> 2 votes
I'm happy you figured it out, and I find it really cool that you managed to do it in your own way. But yours is a specific solution for a specific occurrence of a very general problem.

I would like to explain what exactly happened and why it happened. Just in case others stumble upon this answer, sooner or later, with their own specific occurrence of the same problem.

---

We're working on a game with a top-down view of the world. The player character is positioned firmly in the centre of the game screen. The player moves around the world at a constant speed. The player's direction of movement is determined from the mouse's position relative to player's own position - or the centre of the game screen. We can think of the mouse position as a **vector** which points in the direction the player moves in.

Naively, we attempt to direct the player with the mouse by adding the mouse coordinates, multiplied by the player's velocity, to the player's current world position.

```
player.x += mouse.x * player.velocity;
player.y += mouse.y * player.velocity;

```

But it doesn't work as expected - the player starts moving very, *very* fast if we move the mouse too far away from the centre of the game screen. What did we do wrong?

Well, the mouse x and y values can get pretty large. The former has a range of `[-screenWidth / 2, screenWidth / 2]` and the latter `[-screenHeight / 2, screenHeight / 2]`, providing we move the mouse from one end of the screen to the other in both directions. Multiply any value in those ranges with the player's velocity and you can see how quickly things can go wrong.

Let's limit the mouse x and y values to a `[-1, 1]` range. This way the player can't exceed his preset velocity when it's multiplied by the mouse position values.

```
mouse.x /= (screenWidth / 2);
mouse.y /= (screenHeight / 2);

```

But, again, it doesn't completely work the way we want it to. The player can now moves *slower* than before, but still doesn't move at a constant velocity. What could be the problem this time?

---

Let's take a couple of steps back and look at the problem from a different perspective.

The player's position, direction, and velocity have two components: a **horizontal component**, and a **vertical component**.

For the player's position to update according to a constant velocity, the sum of the two direction components must equal 1. In other words, the direction vector (again, mouse position relative to game screen centre) must be a **unit vector**.

Turning any old vector into a unit vector is called **normalisation**. Normalisation is the process of dividing each vector component by the vector's **magnitude** (length). The vector's magnitude is the hypotenuse of the triangle formed by each of the vector components, and the 'arrow' connecting them. It is calculated from the Pythagorean theorem.

With that in mind, let's rewrite the code:

```
var magnitude = Math.sqrt(mouse.x * mouse.x + mouse.y * mouse.y);
var unitX = mouse.x / magnitude;
var unitY = mouse.y / magnitude;
player.x += unitX * player.velocity;
player.y += unitY * player.velocity;

```

The player should now always move at a constant velocity, no matter how the mouse is positioned!

---

I recommend checking out the links below for more information. They contain interactive demos, illustrations, and great coverage of the subject matter.

---
Tags: javascript, html-canvas, html
---


# Question
Title: UDP sending important data often - Should I use a reliable send or unreliable with resend?
I'm making a multiplayer RPG. My problem is that I send player data very often (100 ms), that contains:

* Position (float x, y, z)
* Radius (float angle)
* Animation (int16\_t id)

And because the package is unreliable, sometimes packets are lost and here the problem starts. The packet is only sent if something changes, like animation; but animation is important, they must arrive to the clients.

So the question is, should I change reliability to reliable? Or just split packet into two? Or simply resend packet?

# Answer
> 0 votes
I'd never heard of Raknet prior to this post, but I looked a bit at the information contained here. I would agree that the queuing of data with `PacketReliability.Reliable` seems like it could be problematic, though it looks like your packets are pretty small. It appears like you could probably use `PacketReliability.Unreliable_With_ACK_Receipt` and create your own queue pending the ACK for things that may require it, and letting things that don't continue to fire at will.

Frankly, the Reliable datatype seems far less efficient than just using TCP and letting the network control most of the verification of data.

# Answer
> 0 votes
Reliable sending is for data that "must" reach the target, or otherwise can cause unexpected behaviour.

Unreliable sending is for data that has no significance on it's own, and can be replaced easily with next packages.

The problem with reliable sending is, once a package is lost, all pending packages gets into a queue until the lost package is successfully sent to target. So using reliable sending for position and rotation can cause serious hiccups on player positions (aka teleporting, lagging). Because of this, I'd use unreliable sending for positions and rotations.

If you are having problems with packets lost for position and rotation sync, you should reconstruct your algorithm; because position and rotation should be overwritten by the most recent packages received.

---
Tags: multiplayer, synchronization, raknet
---


# Question
Title: Strange 1D Perlin noise generation with negative x values
I'm trying to use 1D Perlin Noise to generate "random" terrain for a side-view scrolling game (Think Terraria). I've gotten it mostly working, however strange things start to happen when generating terrain for negative x values. This is a sample of the terrain:

As you can see, the left side, where the x values are negative, is generated in a much more jagged and sharp way than the positive side. I would much prefer it to be more smooth like the positive side. This is the noise generator I am using:

```
private long seed;

public PerlinNoise(long seed) {
    this.seed = seed;
}

public int getNoise(int x, int range) {
    int selectionSize = 16  * 16;
    float noise = 0;

    range /= 2;
    while (selectionSize > 0) {

        int selectionIndex = x / selectionSize;

        float distanceToIndex = (x % selectionSize) / (float) (selectionSize);

        float leftRandom = random(selectionIndex, range);
        float rightRandom = random(selectionIndex + 1, range);

        noise += (1 - distanceToIndex) * leftRandom + distanceToIndex * rightRandom;

        selectionSize /= 2;
        range /= 2;

        range = Math.max(1, range);
    }

    return Math.round(noise * (noise < 0 ? -1 : 1));
}

private int random(int x, int range) {
    return (int) ((x + seed) ^ 10) % range;
}

```

# Answer
> 2 votes
My bet is on integer division. Integer division doesn't always round down, it always cuts off the decimal part, so for negative values it is rounding up.

The reason this looks jagged is because the values you are feeding in jump up every time you cross an integer border in the negative x region.

Also with negative numbers the % operator isn't guaranteed to yield a positive result.

I bet that if you replace the first division and modulus operation with their floating point variants and then floor instead of just letting the integer division handle it, it will turn out normal.

# Answer
> 0 votes
That probably is a variant of a value noise implementation (which is slightly lower in quality than pure Perlin noise).

You can find the original Perlin noise implementation (written by Perlin himself) here (it's already in Java so you don't even have to translate it)

The array `p` is just a specific mix of 0-255 values, you can generate a new noise every time by varing the order of the values in this array (with a code like `int p[256]; for (int n = 0, n < 256, n++) {int t = random(0, 255); while(p[t]) {t = random(0, 255);} p[t] = n;}`)

---
Tags: perlin-noise
---