# Question
Title: IK bones stretching vertices to ground during animation (UE4, 3DS Max, using default skeleton)
I modified the 3rd person example skeletal mesh to a simplistic model in 3DS Max 2016 student edition, by deleting all but one faces and building thereon, thus leaving the hierarchy just as it is needed to re-import to UE4 without any changes and without touching the skin modifier.

In Unreal, **the problem** appears upon animation, where a vertex from each hand, and one from each foot, is stretched to the ground, and in Persona I see that it's the `ik_hand_l` and `ik_hand_gun` bones, as well as the two IKs of the feet, though due to overlapping names I can't make out the entire bone name.

Another issue I successfully dealt with was the model flickering, as suggested I deleted the physics asset and that was corrected, it seems to be a frequent problem so I don't think it's particularly related.

Here is the related post in the Unreal Engine forums with an image of the problem.

# Answer
Though there were a few vertices attached to the IK bones, the problem eventually proved to be that some vertices were not weighed to any bone at all. For reasons relating to the implementation of UE4, the mesh and skeleton are placed facing down and the bones placed the vertices to their appropriate position during animation playback, thus the vertices not associated to any bones remained on the ground.
> 2 votes

---
Tags: 3dsmax, skeletal-animation, unreal-4
---


# Question
Title: Method keyTyped in ClickListener is not working
When im click my SelectBox and press some key, nothing happens.

```
sbNationality.addListener(new ClickListener() {
    @Override
    public boolean keyTyped(InputEvent event, char character) {
        System.out.println(character);
        return super.keyTyped(event, character);
    }
});

```

Im doing something wrong?

# Answer
> 1 votes
According to the documentation (SelectBox.addListener), this element seems to reacting only to 'touch' and 'click' related events, not to keyboard related events.

Perhaps you could try and use the stage events instead.

---
Tags: java, libgdx
---


title: Enemy Retargeting

text:
# Question
Title: Enemy Retargeting
I am trying to make a game using NavMesh agent in Unity, where the enemies first attack the player and change their target to tanks when player spawns them. Then again retarget player after the tank dies, have no idea how to do this as tank is not in game initially and cannot check it in awake.

```
using UnityEngine;
using System.Collections;

public class enmymove : MonoBehaviour {

Transform player;
NavMeshAgent nav;
healthscript Health;
Animator anim;
public GameObject GORTLE;
Transform Gortle;
Gortlehealth Ghealth;

void Awake ()
{
    player=GameObject.FindGameObjectWithTag ("Player").transform;
    nav = GetComponent<NavMeshAgent>();
    Health =player.GetComponent<healthscript> ();
    anim = GetComponent<Animator>();
    //Gortle = GameObject.FindGameObjectWithTag ("Gortle").transform;
    //Ghealth = Gortle.GetComponent<Gortlehealth> ();
}

void Update ()
{

    if (Ghealth.currenthealth > 0 )
    {

        nav.SetDestination (Gortle.position);

    }
    else
    {
        if (Health.currenthealth > 0 && Ghealth.currenthealth <= 0 )
        {
            nav.SetDestination (player.position);
        }
        else
        {
            GetComponent<NavMeshAgent> ().enabled = false;
            anim.SetTrigger ("idle");
        }
    }
 }
 }

```

# Answer
> 0 votes
Easiest approach would be to have a list of spawned Tanks in Player object ( and have some callback for Tank to call, when it dies, or check if it's alive in Player's Update() to remove dead Tanks from list ).

And then in your Enemy class in Update() just look at this list. If it's empty or all listed tanks are dead ( eg. list was not updated yet ) - attack Player. If it has any living Tanks - attack them.

You have requested for some code, so here's a stub:

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

public class Tank : MonoBehaviour {} // remember to not Destroy it on kill, just SetActive(false)

public class Player : MonoBehaviour {
    public List<Tank> tanks = new List<Tank> ();
    public Tank prefab;  // set this to your Tank prefab in Editor
    private bool click = false;

    void Update () {
        if (Input.GetMouseButtonDown(0) && !click && prefab != null) {
            click = true;
            Tank r = Instantiate (prefab, transform.position, Quaternion.identity) as Tank;
            // ^ this will spawn one tank in Player position
            tanks.Add (r);
        }
        if (Input.GetMouseButtonUp (0) && click) {
            click = false;
        }
        // reverse for, not foreach, because we modify list
        for (int i = tanks.Count - 1; i >= 0; i--) {
            if (tanks[i] == null) {
                tanks.RemoveAt(i);
            }
            if (!tanks[i].isActiveAndEnabled) {
                Destroy (tanks[i].gameObject);
                tanks.RemoveAt(i);
            }
        }
    }
}

public class Enemy : MonoBehaviour {

    void Update () {
        Player p = GameObject.FindWithTag ("Player").GetComponent<Player> ();
        if (p != null) {
            if (p.tanks.Count > 0) {
                Tank t = p.tanks [0]; // or choose some other Tank
                shootToTank (t); // implement this in your own way, just remember to not Destroy it on kill, just SetActive(false)
            } else {
                shootToPlayer (p);  // implement this in your own way
            }
        }
    }
}

```

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


# Question
Title: Skeletal Animation - Caching global bone transforms
Very often I see skeletal animation implemented like this:

* On Init - store bone's local transforms and inverse bind pose
* On Update - traverse the skeleton tree, multiplying local transforms on the way (and inverse bind pose)

However, it is more efficient to pre-calculate global poses from local transforms and just reassign them at specified time point to constant buffer.

What is the benefit of keeping all those local matrices? Does it have any meaningful application in other systems like physics, collision detection? People still choose the first scenario and that actually keeps me puzzled.

# Answer
In a lot of cases animations are blended between to create a pose. In some cases many animations are layered at once, sometimes on only part of the body. Finally inverse kinematics can be applied on top or under animations. The only way for all this to work is if the bones transforms are first calculated in local space.
> 1 votes

---
Tags: animation, graphics, graphics-programming, skeletal-animation
---


# Question
Title: What is the proper way to process joystick input?
What is the proper way to process joystick input?

Take, for example, the Xbox One controller. XInput returns joystick input along the x and y axis. I'm not sure if the hardware just measures voltage across the two axis, or not; I'm not very knowledgeable, in the hardware domain.

I'm unsure what data processing is done by API's like XInput already - but since the dead zone is still prevalent, I'm assuming XInput does very little input massaging. This leaves me with a few questions:

* Should the dead zone be clipped circularly or rectangularly?
* What type of low-pass filter should be applied, if any? Perhaps a moving average should be applied?
* Should a bias be introduced into the input based on the resting input?

# Answer
Most API's don't do much processing. It's best done in hardware or in a device specific driver anyway. There's too much variety in hardware to create the one true processing method. That being said, at the application level most joysticks will need to be processed the same way just to different degrees.

## Filtering

Most modern joysticks have little to no noise in the analog sticks so filtering is unnecessary. If your stick does have noise, however, lowpass and moving average filtering are a blunt instrument that will make the input feel soggy/laggy. Your best bet is a Kalman filter which adapts the filter strength based on motion and predicted motion. Here is a demo.

## Deadzoning

Square vs circle depends on the stick. Circle is a safe default but the correct deadzone exactly matches the shape of the slop in the stick.

A different style is independent axes, where you deadzone each axis independently. Use this when you're controlling unrelated things like x-axis turning with y-axis movement.

A consideration, based on your game, is whether or not to normalize the position so that the rim of the deadzone has a magnitude of 0. If you don't then the player won't be able to make a movement slower than the size of the deadzone.

## Bias

Don't bias based on resting position. This is what the deadzone is for. The stick will rest in a different position every time the player lets go.

## Shaping

Something you didn't mention is shaping which adjusts the sensitivity. You'll want to do this after deadzoning (if at all). A simple method is to use the pow function like so: `x = pow(x, 1.5)` To make the joystick less sensitive, for sniping for example, use a power \> 1. To make them more sensitive use a power \<1 but \>0.
> 3 votes

---
Tags: input
---


# Question
Title: Is localisation important for a mobile game with little text?
Let's say it's a physics puzzle (Cut the Rope, Angry Birds) or a runner (Crossy Road, Subway Surfers) clone with some gameplay twists. Assume it puts text on some of the few controls: 'Play', 'Sound Volume', 'Level 15' etc. Most labels are accompanied with "standard" icons. Story is communicated with a text-free comic strip. Tutorial is also text-free.

1. can I publish it to Apple App Store and Google Play Store to every market while using English labels or it will be rejected?
2. will sales be affected a lot or negligibly when going:

* freemium
    * premium.

Most articles I have seen are either PR of localisation companies or dealing with large/medium story-rich games.

PS: recommendations like "just remove all the text and use only icons" and "just localize it" are not something I am looking for.

# Answer
> 1 votes
***Disclaimer:** The following might be a bit biased, since I'm both a native German player as well as (professional) video game translator. So, sorry for that. But I think I might be able to provide you some insights. I'm not trying to sell you anything. :)*

*Want to know what got me into this business? Being annoyed by bad translations in my favorite game(s) and complaining continuously about them. After all the years I'm still doing this mostly due to me hating bad game translations. You don't get rich in that business (unfortunately). ;)*

---

## Is localization important for a game?

**Yes!** (No matter tha actual platform or amount of text).

## Is it a must-have feature?

**Definitely not.** This might be different for some platforms, but I don't know any forcing you to provide translations – neither Google, Amazon, nor Apple.

---

## So should you translate your game?

That's really up to you, but **if you provide localization, make sure it's good.**

**While I can't speak for others, I think that playing a non-translated game provides a far better experience than playing a game with a bad translation.**

If I start a game or app and the translations clearly uses the wrong context, I consider it a lost case already. One very obvious example for this has been the initial release of *Dungeon Defenders* (might have changed in patches):

In their game's launcher, there's a button labelled *"Exit"*. In the German version the text is *"Ausfahrt"*. While the basic dictionary translation is correct, the meaning behind the word is **not** the same, since *"Ausfahrt"* is an exit ramp or gateway – so they even used a noun rather than a verb here!

These are **only three words** in this dialog screen. It's far from being *story rich* or *complex* to begin with. With just **1$** you can usually get these professionally translated into 2, 3 or even more languages (based on quotes). Yet they either decided to use machine translation or just looked it up in a dictionary (or whoever worked on it, didn't have the slightest clue).

The result? In this case, this got me to immediately change the game's language to English, essentially making the whole translation pointless/unused, while also lowering my opinion a bit about the quality delivered by the developer. **Why?** Because such problems add up and can make games far less enjoyable. Even if there's just very little text, misleading button texts can be confusing (especially for new players). Unfortunately this is really hard to explain, when using the English language only. E.g. think of a city builder game. After selecting a building, you have to click the button "boot" (which might be the result of translating back/forth from "start" to "start up" and then "boot" without caring for the actual context).

Unfortunately, especially in the mobile market, there are tons of games having localizations **worse** than what *Google Translate* spits out. And that's a really sad state.

## Will a translation influence monetization?

**Definitely**, but once again this is just my opinion. For some mobile apps it's very tricky (or even impossible) to change the app's language independently from the system one. So with a bad translation, your players might be stuck with a game they don't understand or don't want to play. This automatically leads to them not spending any more money (assuming they even did so), and/or possibly causing them to leave bad reviews.

So, just to repeat myself again:

* If you're not sure about the quality you're able to provide, don't localize it.
* If you localize, make sure it's good, and in the end you can only **win**.

With localization you'll have some costs (community provided translations might be an option though, especially for small indies), but you'll open up your game (or application in general) to a far wider audience, especially when targeting markets that are used to having the option to enjoy some game localized (like Germany and France).

---

### Addendum:

In your case (mostly picture driven, just very few words), I'd definitely skip localization for now.

Publish your app, see whether it's successful, and once you think you've made enough money to provide *good* translations (and it's worth the additional work/costs), add them.

# Answer
> 2 votes
It is not important if all the text is just standard video-game english words like 'Play', 'Levels', etc.

1) The stores themselves don't care at all, at least not Google Play which is the only one I have published to. Google Play automatically translates the store page of your app using Google Translate to the language of the user if you don't provide translation yourself. The app is unaffected.

---
Tags: mobile, publishing, monetization, localization
---


# Question
Title: Is * calling *= (or *= calling *) slower than writing seperate functions (for math library)?
I have some vector classes where the arithmetic functions looks like this:

```
template<typename T, typename U>
auto operator*(const Vector3<T>& lhs, const Vector3<U>& rhs)
{
    return Vector3<decltype(lhs.x*rhs.x)>(
        lhs.x + rhs.x,
        lhs.y + rhs.y,
        lhs.z + rhs.z
        );
}

template<typename T, typename U>
Vector3<T>& operator*=(Vector3<T>& lhs, const Vector3<U>& rhs)
{
    lhs.x *= rhs.x;
    lhs.y *= rhs.y;
    lhs.z *= rhs.z;

    return lhs;
}

```

I want to do a bit of cleanup to remove duplicated code. Basically, I want to convert all the `operator*` functions to call `operator*=` functions like this:

```
template<typename T, typename U>
auto operator*(const Vector3<T>& lhs, const Vector3<U>& rhs)
{
    Vector3<decltype(lhs.x*rhs.x)> result = lhs;
    result *= rhs;
    return result;
}

```

But I'm concerned as to whether it will incur any additional overhead from the extra function call.

Is it a good idea? Bad idea?

# Answer
> 18 votes
In practice, **no additional overhead will be incurred**. In C++, small functions are usually inlined by the compiler as an optimization, so the resulting assembly will have all the operations at the callsite— the functions won't call each other, since the functions won't exist in the final code, only the mathematical operations.

Depending on the compiler, you may see one of these functions calling the other with no or low optimization (as with debug builds). At higher optimizations level though (release builds), they'll be optimized down to just the math.

If you'd still like to be pedantic about it (say you're creating a library), adding the `inline` keyword to `operator*()` (and similar wrapper functions) may hint your compiler to perform the inline, or using compiler-specific flags/syntax like: `-finline-small-functions`, `-finline-functions`, `-findirect-inlining`, `__attribute__((always_inline))` *(credit to @Stephane Hockenhull's helpful info in the comments)*. Personally, I tend to follow what the framework/libs I'm using do— if I'm using GLKit's math library, I'll just use the `GLK_INLINE` macro that it provides too.

---

Double-checking using Clang *(Xcode 7.2's Apple LLVM version 7.0.2 / clang-700.1.81)*, the following `main()` function (in combination with your functions and a naive `Vector3<T>` implementation):

```
int main(int argc, const char * argv[])
{
    Vector3<int> a = { 1, 2, 3 };
    Vector3<int> b;
    scanf("%d", &b.x);
    scanf("%d", &b.y);
    scanf("%d", &b.z);

    Vector3<int> c = a * b;

    printf("%d, %d, %d\n", c.x, c.y, c.z);

    return 0;
}

```

compiles to this assembly using optimization flag `-O0`:

```
    .section    __TEXT,__text,regular,pure_instructions
    .globl  _main
    .align  4, 0x90
_main:                                  ## @main
Lfunc_begin0:
    .loc    6 30 0                  ## main.cpp:30:0
    .cfi_startproc
## BB#0:
    pushq   %rbp
Ltmp0:
    .cfi_def_cfa_offset 16
Ltmp1:
    .cfi_offset %rbp, -16
    movq    %rsp, %rbp
Ltmp2:
    .cfi_def_cfa_register %rbp
    subq    $128, %rsp
    leaq    L_.str1(%rip), %rax
    ##DEBUG_VALUE: main:argc <- undef
    ##DEBUG_VALUE: main:argv <- undef
    movl    $0, -4(%rbp)
    movl    %edi, -8(%rbp)
    movq    %rsi, -16(%rbp)
    .loc    6 31 15 prologue_end    ## main.cpp:31:15
Ltmp3:
    movl    l__ZZ4mainE1a+8(%rip), %edi
    movl    %edi, -24(%rbp)
    movq    l__ZZ4mainE1a(%rip), %rsi
    movq    %rsi, -32(%rbp)
    .loc    6 33 2                  ## main.cpp:33:2
    leaq    L_.str(%rip), %rsi
    xorl    %edi, %edi
    movb    %dil, %cl
    leaq    -48(%rbp), %rdx
    movq    %rsi, %rdi
    movq    %rsi, -88(%rbp)         ## 8-byte Spill
    movq    %rdx, %rsi
    movq    %rax, -96(%rbp)         ## 8-byte Spill
    movb    %cl, %al
    movb    %cl, -97(%rbp)          ## 1-byte Spill
    movq    %rdx, -112(%rbp)        ## 8-byte Spill
    callq   _scanf
    .loc    6 34 17                 ## main.cpp:34:17
    leaq    -44(%rbp), %rsi
    .loc    6 34 2 is_stmt 0        ## main.cpp:34:2
    movq    -88(%rbp), %rdi         ## 8-byte Reload
    movb    -97(%rbp), %cl          ## 1-byte Reload
    movl    %eax, -116(%rbp)        ## 4-byte Spill
    movb    %cl, %al
    callq   _scanf
    .loc    6 35 17 is_stmt 1       ## main.cpp:35:17
    leaq    -40(%rbp), %rsi
    .loc    6 35 2 is_stmt 0        ## main.cpp:35:2
    movq    -88(%rbp), %rdi         ## 8-byte Reload
    movb    -97(%rbp), %cl          ## 1-byte Reload
    movl    %eax, -120(%rbp)        ## 4-byte Spill
    movb    %cl, %al
    callq   _scanf
    leaq    -32(%rbp), %rdi
    .loc    6 37 21 is_stmt 1       ## main.cpp:37:21
    movq    -112(%rbp), %rsi        ## 8-byte Reload
    movl    %eax, -124(%rbp)        ## 4-byte Spill
    callq   __ZmlIiiE7Vector3IDTmldtfp_1xdtfp0_1xEERKS0_IT_ERKS0_IT0_E
    movl    %edx, -72(%rbp)
    movq    %rax, -80(%rbp)
    movq    -80(%rbp), %rax
    movq    %rax, -64(%rbp)
    movl    -72(%rbp), %edx
    movl    %edx, -56(%rbp)
    .loc    6 39 27                 ## main.cpp:39:27
    movl    -64(%rbp), %esi
    .loc    6 39 32 is_stmt 0       ## main.cpp:39:32
    movl    -60(%rbp), %edx
    .loc    6 39 37                 ## main.cpp:39:37
    movl    -56(%rbp), %ecx
    .loc    6 39 2                  ## main.cpp:39:2
    movq    -96(%rbp), %rdi         ## 8-byte Reload
    movb    $0, %al
    callq   _printf
    xorl    %ecx, %ecx
    .loc    6 41 5 is_stmt 1        ## main.cpp:41:5
    movl    %eax, -128(%rbp)        ## 4-byte Spill
    movl    %ecx, %eax
    addq    $128, %rsp
    popq    %rbp
    retq
Ltmp4:
Lfunc_end0:
    .cfi_endproc

```

In the above, `__ZmlIiiE7Vector3IDTmldtfp_1xdtfp0_1xEERKS0_IT_ERKS0_IT0_E` is your `operator*()` function and ends up `callq`ing another `__…Vector3…` function. It amounts to quite a lot of assembly. Compiling with `-O1` is almost the same, still calling out to `__…Vector3…` functions.

However, when we bump it up to `-O2`, the `callq`s to `__…Vector3…` disappear, replaced with a `imull` instruction (the `* a.z``* 3`), an `addl` instruction (the `* a.y``* 2`), and just using the `b.x` value straight-up (because `* a.x``* 1`).

```
    .section    __TEXT,__text,regular,pure_instructions
    .globl  _main
    .align  4, 0x90
_main:                                  ## @main
Lfunc_begin0:
    .loc    6 30 0                  ## main.cpp:30:0
    .cfi_startproc
## BB#0:
    pushq   %rbp
Ltmp0:
    .cfi_def_cfa_offset 16
Ltmp1:
    .cfi_offset %rbp, -16
    movq    %rsp, %rbp
Ltmp2:
    .cfi_def_cfa_register %rbp
    .loc    6 33 2 prologue_end     ## main.cpp:33:2
Ltmp3:
    pushq   %rbx
    subq    $24, %rsp
Ltmp4:
    .cfi_offset %rbx, -24
    ##DEBUG_VALUE: main:argc <- EDI
    ##DEBUG_VALUE: main:argv <- RSI
    leaq    L_.str(%rip), %rbx
    leaq    -24(%rbp), %rsi
Ltmp5:
    ##DEBUG_VALUE: operator*=<int, int>:rhs <- [RSI+0]
    ##DEBUG_VALUE: operator*<int, int>:rhs <- [RSI+0]
    ##DEBUG_VALUE: main:b <- [RSI+0]
    xorl    %eax, %eax
    movq    %rbx, %rdi
Ltmp6:
    callq   _scanf
    .loc    6 34 17                 ## main.cpp:34:17
    leaq    -20(%rbp), %rsi
Ltmp7:
    xorl    %eax, %eax
    .loc    6 34 2 is_stmt 0        ## main.cpp:34:2
    movq    %rbx, %rdi
    callq   _scanf
    .loc    6 35 17 is_stmt 1       ## main.cpp:35:17
    leaq    -16(%rbp), %rsi
    xorl    %eax, %eax
    .loc    6 35 2 is_stmt 0        ## main.cpp:35:2
    movq    %rbx, %rdi
    callq   _scanf
    .loc    6 22 18 is_stmt 1       ## main.cpp:22:18
Ltmp8:
    movl    -24(%rbp), %esi
    .loc    6 23 18                 ## main.cpp:23:18
    movl    -20(%rbp), %edx
    .loc    6 23 11 is_stmt 0       ## main.cpp:23:11
    addl    %edx, %edx
    .loc    6 24 11 is_stmt 1       ## main.cpp:24:11
    imull   $3, -16(%rbp), %ecx
Ltmp9:
    ##DEBUG_VALUE: main:c [bit_piece offset=64 size=32] <- ECX
    .loc    6 39 2                  ## main.cpp:39:2
    leaq    L_.str1(%rip), %rdi
    xorl    %eax, %eax
    callq   _printf
    xorl    %eax, %eax
    .loc    6 41 5                  ## main.cpp:41:5
    addq    $24, %rsp
    popq    %rbx
    popq    %rbp
    retq
Ltmp10:
Lfunc_end0:
    .cfi_endproc

```

For this code, the assembly at `-O2`, `-O3`, `-Os`, & `-Ofast` all look identical.

---
Tags: c++, mathematics, performance, refactoring
---


title: Animation Scaling?

text:
# Question
Title: Animation Scaling?
I have an animation that changes the scale of the GameObject but also happens to change the position as well. I do not want the position to be changed by the animation, only the scale. How can I do that?

# Answer
You need to use the new scale to factor the new position! (I just solved this for my game camera)

should be something like:

```
target.position.x = (target.width - target.width * target.scale.x) + target.position.x;

```

My code for re-positioning my stage (camera), centering on a target entity

```
stage.position.x = (- target.position.x * stage.scale.x) + renderer.width/2;

```
> 0 votes

---
Tags: c#, animation, unity, scale
---


title: New to game development

text:
# Question
Title: New to game development
I have some programing experience, and I have tried making some games. I have some knowledge with c#, but I am much better at python. I have a general code structure knowledge, so I am open to learn other languages. I have tried making some demos in Unity. But my question is where can I get the most resources to start making small games. I'm willing to pay some money for tutorials and software, but "free" is always appreciated!

# Answer
Although I think this is a bit off topic, I know of several places where you can get starting making small games with Unity3D, JavaScript, and Python. Zenva Corp has a plethora of tutorials regarding game development for free, the website to view them is GameDevAcademy.org and it is a great starting resource. Youtube has tons of videos regarding game development which also includes walkthroughs on creating games. Lynda.com and Pluralsight.com are both paid services that have great lesson videos on pretty much everything regarding development. The last place I would suggest is looking through github.com because people upload repositories for games and software they are developing in a variety of languages. Some even use github to host their tutorials on game development.
> -1 votes

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


# Question
Title: Unity 5.2 default 3rd person controller makes character fly upwards when moving forward
I'm new to Unity, and already dealing with a problem using the default third person controller script. I am trying to move and animate the player, but I have a problem, as when I try to move the character it moves beautifully but not only vertically and horizontally - it also moves up on the y axis! It just keeps going higher and higher, and though it's quite funny, it really messes the gameplay.

Here are screenshots of what happens, and yes, I do have gravity turned on:

# Answer
Since they original code is not posted on this site, I am not going to click on the link. Instead, I will give you a very simple 3rd person controller script that illustrates how movement can be handled on a basic level. And to be honest, animations are much better handled using the Animation Controller Component. It uses a state machine to control the animations and you can add int parameters. In addition to the simple movement in 3rd person view, I will also comment on how you could take advantage of the Animation Controller in scripting.

```
using UnityEngine;
using System.Collections;

public class ThirdPersonCamera : MonoBehaviour
{
    public Camera cam;
    public GameObject character;
    public Animator anim; // Gets the Animator component and
    // is better used when it is attached to the character

    void followCharacter()
    {
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            cam.transform.position -= new Vector3(1, 0, 0);
            //anim.SetInt(1); if the parameter is an integer
            // it will move to that specific animation
        }

        else if (Input.GetKey(KeyCode.RightArrow))
        {
            cam.transform.position += new Vector3(1, 0, 0);
        }

        else if (Input.GetKey(KeyCode.UpArrow))
        {
            cam.transform.position += new Vector3(0, 0, 1);
        }

        else if (Input.GetKey(KeyCode.DownArrow))
        {
            cam.transform.position -= new Vector3(0, 0, 1);
        }
    }

    void Update()
    {
        followCharacter();
    }
}

```
> 1 votes

---
Tags: unity, movement, character, third-person-view
---


# Question
Title: LibGDX - How to export a texture as a .png onto, say, the desktop
I'm making a game in which I need to export a texture which the user has edited as a .png into a specified location. I'd like it if I could have the default saving window thing (like on other apps when you do cmd+s). If this isn't possible, is there any way in GDX to export a texture (as a .png) to the computer (and preferably not the assets folder)

# Answer
One way of achieving this would be to save the portion of the screen where they've made their edits by taking a screen shot using the `ScreenUtils.getFrameBufferPixmap` method and then dumping the `Pixmap` data to a file using the `PixmapIO` class that can write **PNG**s from a `Pixmap`.

```
public class ScreenshotFactory {

private static int counter = 1;
public static void saveScreenshot(){
    try{
        FileHandle fh;
        do{
            fh = new FileHandle("screenshot" + counter++ + ".png");
        }while (fh.exists());
        Pixmap pixmap = getScreenshot(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false);
        PixmapIO.writePNG(fh, pixmap);
        pixmap.dispose();
    }catch (Exception e){
    }
}

private static Pixmap getScreenshot(int x, int y, int w, int h, boolean yDown){
    final Pixmap pixmap = ScreenUtils.getFrameBufferPixmap(x, y, w, h);

    if (yDown) {
        // Flip the pixmap upside down
        ByteBuffer pixels = pixmap.getPixels();
        int numBytes = w * h * 4;
        byte[] lines = new byte[numBytes];
        int numBytesPerLine = w * 4;
        for (int i = 0; i < h; i++) {
            pixels.position((h - i - 1) * numBytesPerLine);
            pixels.get(lines, i * numBytesPerLine, numBytesPerLine);
        }
        pixels.clear();
        pixels.put(lines);
        pixels.clear();
    }

    return pixmap;
}
}

```

The snippet above is snagged from Take a Screenshot for **libGDX** on github. It should be easy to modify it to take only a portion of the screen or to change it to work on a `Pixmap` grabbed from another `FrameBuffer`.
> 1 votes

---
Tags: java, libgdx, textures, export, png
---


# Question
Title: Selecting the closest point in perspective view mode
I'm trying to improve my algorithm for selecting points in perspective view mode (OpenGL/Qt/C++). The current implementation works as follows.

1. The user clicks on a certain `(x,y)` position (in Window space)
2. Traversing the pipeline from Window space back to World space (that is, Window → NDC → Clip → Eye → World), this defines a point `a` on the `near` clipping plane and a point `b` on the `far` clipping plane
3. The distances from the line between `a` and `b` and the vertices (available in World space) are determined (see e.g. this article on Wikipedia)
4. The point with the minimum distance to the line is selected

Now, this works fine when using orthogonal view mode. However, when visualizing something in perspective view mode, there are some cases where the result might be a bit off.

As example, let's consider the wireframe of a cube. In the illustration below, the point `(x,y)` is the point where all white lines meet. These lines are orthogonal to the line from `a` to `b` which is not visible in this orientation — the second illustration shows a rotated view.

The point that eventually gets selected is highlighted in green. However, as the blue point *seems* to be closer to `(x,y)` in perspective mode, the user probably expects this point to get selected instead. Somehow the computed distances have to be scaled in order to take this effect into account. How is this usually done?

# Answer
> 1 votes
The step you are missing is the perspective divide. To calculate the value to divide by you have to do the perspective matrix math anyway so you might as well convert the point from world space into screen space and solve the problem in 2D screen coordinates.

If you're curious about the math involved you can read up on how the perspective matrix works here

---
Tags: mouse, perspective, selection
---


# Question
Title: How define coordinates for bodies in outer space
What is a simple way of representing celestial bodies in outer space using a coordinate system? There are actual scientific coordinate systems (see https://en.wikipedia.org/wiki/Celestial\_coordinate\_system) but they may be too complicated to really understand and bring up the barrier of entry to my game.

I could just end up using a two-dimensional system to make things simple, but I'd like to inject some realism into the game and make it 3D. Any thoughts?

Edit: This is for a completely text-based game. The coordinates are for the user to situate themselves in 3D space and for me to be able to calculate distances between celestial objects.

# Answer
The problem is that there is no center for Universe, and everything rotates. But it can be simplified if your user is restricted to one Galaxy, and physics is simplified a bit:

You could use Spherical coordinate system based on center of Galaxy. So you take angle from this Galaxy's equator, angle from this Galaxy's axis of rotation ( most of galaxies rotate, you have to arbitraty choose 0 deg ray ), and the distance from Galaxy's center. Those three numbers ( 2 angles, one distance ) could clearly define any Solar system in that simplified Galaxy. And inside Solar system you can just enumerate Planets.
> 2 votes

# Answer
Alternatively, if you don't like spherical coordinates, you could use a simple cartesian (*x*, *y*, *z*) coordinate system. Just put the origin at the galactic center, have the *z*-axis point out of the galactic plane, and arbitrarily choose a direction in the galactic plane as the *x*-axis (with the *y*-axis also in the galactic plane, 90° away from the *x*-axis).

An advantage of this system is that you can calculate distances simply using the Pythagorean formula dist(*a*, *b*) = sqrt( (*xa**xb*)2 \+ (*ya**yb*)2 \+ (*za**zb*)2 ). The main disadvantage, compared to the angular coordinate system suggested by Marqin, is that you'll need to use this formula even for distance from the galactic center, instead of just getting it directly from the first coordinate. Of course, if precise distance from the galactic center doesn't matter much in your game, this might not really be a disadvantage anyway.

(Other possibilities could include a hybrid "cylindrical" (*r*, *θ*, *z*) coordinate system, where position within the galactic plane is given by distance *r* from the center and an angle *θ*, but distance from the galactic plane is simply given as in the cartesian system. Given that the galaxy is mostly a flat disc, this might make some sense.)
> 1 votes

---
Tags: coordinates
---


# Question
Title: Java - LWJGL OBJ Loader with Materials not rendering
So I successfully loading my obj file but I obviously want to get materials on it. I added the vt(texture) to the OBJLoader and the Model.render but still rendering textureless. I have exported the file from Blender with UV unwrap so the materials and vt are appearing in the obj file. Do I need to do something with the mtl file? if so, how so?

Model.java

```
import static org.lwjgl.opengl.GL11.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.lwjgl.util.vector.*;

public class Model {
    public List<Vector3f> vertices;
    public List<Vector3f> normals;
    public List<Face> faces;
    public List<Vector2f> texcoords;

    public static Model getModel(String s) throws IOException{
        return new Model(s);
    }

    private Model(String path) throws IOException {
        vertices = new ArrayList<Vector3f>();
        normals = new ArrayList<Vector3f>();
        faces = new ArrayList<Face>();
        texcoords = new ArrayList<Vector2f>();
        new OBJLoader(this, path);
    }

    public void render(){
        glTranslatef(0, 0, 0);
        glBegin(GL_TRIANGLES);
        for (Face face : faces) {

            Vector3f n1 = normals.get((int) face.normal.x -1);
            Vector2f t1 = texcoords.get((int) face.texcoord.x -1);
            Vector3f v1 = vertices.get((int) face.vertex.x -1);

            Vector3f n2 = normals.get((int) face.normal.y -1);
            Vector2f t2 = texcoords.get((int) face.texcoord.y -1);
            Vector3f v2 = vertices.get((int) face.vertex.y -1);

            Vector3f n3 = normals.get((int) face.normal.z -1);
            Vector2f t3 = texcoords.get((int) face.texcoord.z -1);
            Vector3f v3 = vertices.get((int) face.vertex.z -1);

            glVertex3f(v1.x, v1.y, v1.z);
            glTexCoord2f(t1.x, t1.y);
            glNormal3f(n1.x, n1.y, n1.z);

            glVertex3f(v2.x, v2.y, v2.z);
            glTexCoord2f(t2.x, t2.y);
            glNormal3f(n2.x, n2.y, n2.z);

            glVertex3f(v3.x, v3.y, v3.z);
            glTexCoord2f(t3.x, t3.y);
            glNormal3f(n3.x, n3.y, n3.z);
        }
        glEnd();
    }
}

```

OBJLoader.java

```
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import org.lwjgl.util.vector.*;

public class OBJLoader {

    public OBJLoader(Model m, String path) throws FileNotFoundException, IOException {
        BufferedReader read = new BufferedReader(new FileReader(new File(path)));
        String line;
        while((line = read.readLine()) != null) {
            if (line.startsWith("v ")){
                float x = Float.valueOf(line.split(" ")[1]);
                float y = Float.valueOf(line.split(" ")[2]);
                float z = Float.valueOf(line.split(" ")[3]);
                m.vertices.add(new Vector3f(x,y,z));
            }
            if (line.startsWith("vn ")) {
                float x = Float.valueOf(line.split(" ")[1]);
                float y = Float.valueOf(line.split(" ")[2]);
                float z = Float.valueOf(line.split(" ")[3]);
                m.normals.add(new Vector3f(x,y,z));
            }
            if (line.startsWith("vt ")){
                float x = Float.valueOf(line.split(" ")[1]);
                float y = Float.valueOf(line.split(" ")[2]);
                m.texcoords.add(new Vector2f(x,y));
            }
            if (line.startsWith("f ")) {
                Vector3f vertexIndices = new Vector3f(
                        Float.valueOf(line.split(" ")[1].split("/")[0]),
                        Float.valueOf(line.split(" ")[2].split("/")[0]),
                        Float.valueOf(line.split(" ")[3].split("/")[0]));
                Vector3f normalIndices = new Vector3f(
                        Float.valueOf(line.split(" ")[1].split("/")[2]),
                        Float.valueOf(line.split(" ")[2].split("/")[2]),
                        Float.valueOf(line.split(" ")[3].split("/")[2]));
                Vector3f textureIndices = new Vector3f(
                        Float.valueOf(line.split(" ")[1].split("/")[1]),
                        Float.valueOf(line.split(" ")[2].split("/")[1]),
                        Float.valueOf(line.split(" ")[3].split("/")[1]));
                m.faces.add(new Face(vertexIndices, normalIndices, textureIndices));
            }
        }
        read.close();
    }
}

```

# Answer
> 0 votes
look at exported obj file, there you'll see directives about:
1. import mtl file
mtllib "mtl file name"
2. and use materials
usemtl "material nae"

mtl, obj format are described here
http://paulbourke.net/dataformats/mtl/
http://paulbourke.net/dataformats/obj/

---
Tags: opengl, java, rendering, lwjgl, materials
---


# Question
Title: how to accelerate and stop a sprite(car) using isTouched() in libgdx
I am working on Android libgdx project. I want to accelerate and stop a sprite using isTouched(). Plz help me and give me a answer with example

# Answer
I didn't tested the code but the logic should be like this:

```
float accel;
float speed;
float maxSpeed;
float maxAccel;
float maxDeceleration;

void init()
{
    accel = 0;
    speed = 0;
    maxSpeed = 300.0f; // Speed limit example
    maxAccel = 5.0f; // Acceleration limit example
    maxDeceleration = 1.0f;
}

void update()
{
    if(touching)
        accel += 0.1f;
    else
        accel -= 0.1f;

    if(accel > maxAccel)
        accel = maxAccel;

    if(speed == 0.0f && accel < 0.0f)
        accel = 0.0f;
    else if(speed > 0.0f && accel < -maxDeceleration)
        accel = -maxDeceleration;

    speed += accel;

    if(speed >= maxSpeed)
        speed = maxSpeed
    else if(speed < 0.0f)
        speed = 0.0f;
}

```
> 0 votes

---
Tags: libgdx
---


title: How To generate spiky terrain in 2D?

text:
# Question
Title: How To generate spiky terrain in 2D?
I am learning game design, and wanted to know how one can automatically generate spiky terrain (something like this: Cavernaut, notice, the terrain at the sides?). I have heard about midpoint displacement algorithm. But How can I apply that to my problem, given that I would also like to increase/decrease the randomness of the terrain.
Also, Is there any helpful library for this in libgdx?

# Answer
To generate a random terrain, i find the 'fractal'-ish approach the most effective.
Generate a first set of spikes, with a given amplitude and frequency, then add to this another set, having lesser amplitude and higher frequency, and iterate...
By choosing 'wisely' the frequency/amplitude/phase parameters you should get the terrain that you wish.

Find below a small example i copy-pasted from one of my project, it is not randomized but it's not that hard to randomize it. I might explain more if you're interested.

```
// Canvas setup
var cv = document.getElementById('cv');
var ctx = context = cv.getContext('2d');
var canvasWidth = cv.width,
  canvasHeight = cv.height;
var mountain = null;

window.onresize = resize;

resize();

function resize() {
    canvasWidth = cv.width = window.innerWidth;
    canvasHeight = cv.height = window.innerHeight;
    mountain = new Mountain(canvasHeight / 5, canvasHeight / 2, 600, canvasHeight);
  }
  //

var xo = 0,
  yo = 0;

function animate() {
  requestAnimationFrame(animate);
  // clear screen
  ctx.clearRect(0, 0, canvasWidth, canvasHeight);
  xo += 0.2;
  mountain.draw(xo, yo);
}

animate();

//
function Mountain(baseY, amplitude, basePeriod, yEnd) {
  this.mountainGradient = createGradient([0, 0, 0, amplitude], [
    0, '#FFF',
    0.12, '#EEE',
    0.26, '#DDD',
    0.4, '#BBB',
    1, '#555'
  ]);
  this.endGradient = createGradient([0, amplitude-1, 0, yEnd - baseY], [
    0, '#555',
    1, '#000'
  ]);
  this.baseY = baseY;
  this.amplitude = amplitude;
  amplitude /= (1 + 0.8 + 0.16 + 0.18);
  var mainMountain = buildTriangleFunc(basePeriod, amplitude, 280);
  var secMountain = buildTriangleFunc(basePeriod * 0.52341247, amplitude * 0.8, 230);
  var spikes = buildTriangleFunc(basePeriod * 0.083479532, amplitude * 0.16, 10);
  var spikes2 = buildTriangleFunc(basePeriod * 0.144797531, amplitude * 0.18, 10, 15);
  this.mountainFunction = function(x) {
    return (mainMountain(x) + secMountain(x) + spikes(x) + spikes2(x));
  }
  this.draw = function(xOffset, yOffset) {
    xOffset = xOffset || 0;
    yOffset = yOffset || 0;
    var xMargin = 30;
    var mountainFunction = this.mountainFunction;
    var step = 20;
    var x = 0;
    var xOR = xOffset % step;
    var xBase = xOffset - xOR;
    ctx.save();
    ctx.translate(-xOR, this.baseY + yOffset);
    ctx.beginPath();
    ctx.moveTo(0, mountainFunction(xBase + 0));
    for (; x < canvasWidth + 2 * step; x += step) {
      ctx.lineTo(x, mountainFunction(x + xBase));
    }
    x -= step;
    ctx.lineTo(x, this.amplitude);
    ctx.lineTo(0, this.amplitude);
    ctx.closePath();
    ctx.lineWidth = 5;
    ctx.strokeStyle = '#000';
    ctx.fillStyle = this.mountainGradient;
    ctx.stroke();
    ctx.fill();
    ctx.fillStyle = this.endGradient;
    ctx.fillRect(0, this.amplitude-1, canvasWidth + step, yEnd - baseY);
    ctx.restore();
  }
}

function createGradient(coords, stops) {
  var gd = ctx.createLinearGradient.apply(ctx, coords);
  for (var i = 0; i < stops.length; i += 2) {
    gd.addColorStop(stops[i], stops[i + 1]);
  }
  return gd;
}

function buildTriangleFunc(period, amp, phase) {
  var halfPeriod = period / 2;
  amp /= halfPeriod;
  phase = phase || 0;
  phase += period;
  return function(x) {
    x += phase;
    x = x % period;
    if (x > halfPeriod) x = period - x;
    return x * amp;
  }
}
```

```
<canvas id='cv'></canvas>
```
> 2 votes

# Answer
A good, though not particularly fast, algorithm for this is called "midpoint displacement."

In midpoint displacement, you start with a flat terrain, then find the midpoint between the edges and move the midpoint up or down by a random amount. You then repeat this process, taking the midpoints on either side of the previous midpoint, and move it up or down again, repeating until you have reached some maximum number of iterations. The problem with this approach is it scales very poorly, it's O(n^3), however it is easy to implement and understand.

It's important to play with the amount of jitter each midpoint is allowed at each step in the iteration. Early on you want larger swings, but as you get smaller and smaller segments in the higher iterations you probably want to have smaller swings. The amount that the midpoint is allowed to vary at each iteration controls how "spiky" the final product is.
> 1 votes

# Answer
One (not very good way) would be to generate lots of random y coords, increase the x by, say, 50px every y coord and generate a polygon from that. Hard to explain but if you want I could do a picture.
> 0 votes

---
Tags: libgdx, game-design, procedural-generation, terrain
---


title: HTML UI with SDL2

text:
# Question
Title: HTML UI with SDL2
I realized that I need an HTML-like UI in my game, because by myself I wouldn't be able to achieve such effects (divs, text, coloring, and styling).

So I started to look around for a HTML Engine for C++, and I found Sciter but it's built completely on top of the Win API and I just can't get it to work/debug (because it lacks of decent DOCs too). Now, I'm wondering if there is some very simple engine (I just need HTML and CSS, no JS) and SDL friendly (should have some functions like create, update, render, ...).

# Answer
Take a look at Awesomium. I have integrated it to SDL before and the process was fast. The biggest thing you have to deal with is translating SDL events to Awesomium. Otherwise the rendering is really easy, you can just query pixel data from Awesomium into an SDL surface IIRC, and then render that to your game.
> 6 votes

---
Tags: sdl2, ui-design, c++, html
---


# Question
Title: Libgdx + Ashley moving one texture causes everything to jump
My problem is that as i am moving my player entity all my entities shift position by the reverse total of my player entities movement vector, However the only system to move things is my MovementSystem class which moves a entity by its own movement vector and is clamped by delta Time.

MovementSystem

```
public class MovementSystem extends IteratingSystem
{

    private ComponentMapper<MovementComponent> movementComponentMap;
    private ComponentMapper<TransformComponent> posComponentMap;
    private ComponentMapper<DebugComponent> debugComponentMap;

    public MovementSystem()
    {
        super(Family.all(MovementComponent.class,  TransformComponent.class,
            DebugComponent.class).get());

        movementComponentMap = ComponentMapper.getFor(MovementComponent.class);
        posComponentMap = ComponentMapper.getFor(TransformComponent.class);
        debugComponentMap = ComponentMapper.getFor(DebugComponent.class);
    }

    @Override
    protected void processEntity(Entity entity, float deltaTime)
    {
        TransformComponent pos = posComponentMap.get(entity);
        MovementComponent mov = movementComponentMap.get(entity);
        DebugComponent db = debugComponentMap.get(entity);

        pos.Position.x += mov.Velocity.x * deltaTime;
        pos.Position.y += mov.Velocity.y * deltaTime;
    }
}

```

RenderSystem

```
public class RenderSystem extends SortedIteratingSystem
{
    private ComponentMapper<TextureComponent> textureComponentMap;
    private ComponentMapper<TransformComponent> transformComponentMap;
    private ComponentMapper<DebugComponent> dbMap;

    SpriteBatch batch;
    OrthographicCamera camera;

    public RenderSystem(SpriteBatch batch)
    {
        super(Family.all(TransformComponent.class, TextureComponent.class).get(), new RenderComparator(), 50);

        textureComponentMap = ComponentMapper.getFor(TextureComponent.class);
        transformComponentMap = ComponentMapper.getFor(TransformComponent.class);
        dbMap = ComponentMapper.getFor(DebugComponent.class);
        this.batch = batch;
        camera = new OrthographicCamera(CONST.FRUSTRUM_WIDTH, CONST.FRUSTRUM_HEIGHT);
    }

    @Override
    public void update(float deltaTime)
    {
        camera.update();
        batch.setProjectionMatrix(camera.combined);
        batch.begin();
        super.update(deltaTime);
        batch.end();
    }

    @Override
    public void processEntity(Entity entity, float deltaTime)
    {
        TextureComponent tex = textureComponentMap.get(entity);
        TransformComponent pos = transformComponentMap.get(entity);
        DebugComponent db = dbMap.get(entity);

        batch.draw(tex.Texture, pos.Position.x - tex.TextureOrigin.x,
            pos.Position.y - tex.TextureOrigin.y,
            tex.TextureOrigin.x, tex.TextureOrigin.y,
            tex.Texture.getRegionWidth(), tex.Texture.getRegionHeight(),
            pos.Scale.x, pos.Scale.y,
            MathUtils.radiansToDegrees * pos.Rotation);
    }
}

```

The full code can be found on my github profile

i have no idea what is happening. i have been over my code with a fine toothed comb and lots of console output and i just cannot find a reason for everything to be jumping by essentially the speed of the player. any thoughts or nudges in directions would be greatly appreciated

# Answer
My bug lies in the method of Vector2, Vector2.Zero. All of my Entities were using Vector2.Zero for their origin which turns out to be the same Vector2 object so changing one changed all the rest, The bug disappeared by giving my entities new Vector2 and not just reusing the same Vector2 returned from Vector2.Zero
> 2 votes

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


title: Limiting Bounds of Camera

text:
# Question
Title: Limiting Bounds of Camera
I'm using the following code which I've taken from Unity and edited it a bit, but I seem to misunderstand the right way to actually add bounds to the camera controls and the way to implement the Camera Rotation since I'm not rotating around a Target.

I've tried to `Mathf.Clamp` the axis along the bounds. I've set but I cant seem to grasp how to do it.

I will use only zooming (mouse wheel scroll), rotation (middle mouse button) *\- completely missing in the Script -* and vertical or horizontal movement (right rouse button). The zoom and the movement lack the bounds.

I'm moving on a Terrain object which I have its size and the offsets I need to define.

EDIT ::

```
using UnityEngine;

[AddComponentMenu("Camera-Control/Mouse")]
public class CameraControl : MonoBehaviour
{
    // Mouse buttons in the same order as Unity
    public enum MouseButton { Left = 0, Right = 1, Middle = 2, None = 3 }

    [System.Serializable]
    // Handles left modifiers keys (Alt, Ctrl, Shift)
    public class Modifiers
    {
        public bool leftAlt;
        public bool leftControl;
        public bool leftShift;

        public bool checkModifiers()
        {
            return (!leftAlt ^ Input.GetKey(KeyCode.LeftAlt)) &&
                (!leftControl ^ Input.GetKey(KeyCode.LeftControl)) &&
                (!leftShift ^ Input.GetKey(KeyCode.LeftShift));
        }
    }

    [System.Serializable]
    // Handles common parameters for translations and rotations
    public class MouseControlConfiguration
    {

        public bool activate;
        public MouseButton mouseButton;
        public Modifiers modifiers;
        public float sensitivity;

        public bool isActivated()
        {
            return activate && Input.GetMouseButton((int)mouseButton) && modifiers.checkModifiers();
        }
    }

    [System.Serializable]
    // Handles scroll parameters
    public class MouseScrollConfiguration
    {

        public bool activate;
        public Modifiers modifiers;
        public float sensitivity;
        public float smooth;

        public bool isActivated()
        {
            return activate && modifiers.checkModifiers();
        }
    }

    [System.Serializable]
    // Handles transform boundaries
    public class Boundaries
    {

        public float yMax = 70F;
        public float yMin = 30F;
        public float xMax = 450F;
        public float xMin = 50F;
        public float zMax = 415F;
        public float zMin = 15F;
        public float smoothMax = 255F;
        public float smoothMin = 235F;

    }

    // Vertical translation default configuration
    public MouseControlConfiguration verticalTranslation = new MouseControlConfiguration { mouseButton = MouseButton.Right, sensitivity = 2F, activate = true };

    // Horizontal translation default configuration
    public MouseControlConfiguration horizontalTranslation = new MouseControlConfiguration { mouseButton = MouseButton.Right, sensitivity = 2F, activate = true };

    // Scroll default configuration
    public MouseScrollConfiguration scroll = new MouseScrollConfiguration { sensitivity = 10F, activate = true, smooth = 0.5F };

    // Default unity names for mouse axes
    private string mouseHorizontalAxisName = "Mouse X";
    private string mouseVerticalAxisName = "Mouse Y";
    private string scrollAxisName = "Mouse ScrollWheel";
    public Boundaries boundaries;

    public Vector3 defaultPosition = new Vector3(250, 60, 240);

    void Start()
    {
        resetPosition();
    }

    void resetPosition()
    {

        transform.position = defaultPosition;
    }

    void LateUpdate()
    {

        if (verticalTranslation.isActivated())
        {
            float translateZ = Input.GetAxis(mouseVerticalAxisName) * -verticalTranslation.sensitivity;
            transform.position = new Vector3(
                Camera.main.transform.position.x,
                Camera.main.transform.position.y,
                Mathf.Clamp(Camera.main.transform.position.z + translateZ, boundaries.zMin, boundaries.zMax)
                );
        }

        if (horizontalTranslation.isActivated())
        {
            float translateX = Input.GetAxis(mouseHorizontalAxisName) * -horizontalTranslation.sensitivity;
            transform.position = new Vector3(
                Mathf.Clamp(Camera.main.transform.position.x + translateX, boundaries.xMin, boundaries.xMax),
                Camera.main.transform.position.y,
                Camera.main.transform.position.z
                );
        }

        if (scroll.isActivated())
        {
            float translateY = Input.GetAxis(scrollAxisName) * scroll.sensitivity;
            transform.position = new Vector3(
                Camera.main.transform.position.x,
                Mathf.Clamp(Camera.main.transform.position.y - translateY, boundaries.yMin, boundaries.yMax),
                Camera.main.transform.position.z
                );
        }
    }
}

```

now I'm not sure if gamedev works like code review but I sure am happy to accept and advice on the current code.

# Answer
> 1 votes
Mathf.Clamp is most certainly the way to go for creating boundaries, however, I would also suggest creating a boundary class and give them x, y, and z parameters. The best example I could give is my implementation of creating a boundary in a 3D environment for a side scroller game.

```
using UnityEngine;
using System.Collections;

[System.Serializable]
public class Boundary
{
    public float xMin, xMax, zMin, zMax;
}

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour
{
    public float speed;
    public float tilt;
    public Rigidbody stiffBody;
    public Boundary boundary;

    void WindowsMovement()
    {
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        Vector3 movement = new Vector3(moveHorizontal, 5.0f, moveVertical);
        stiffBody.velocity = movement * speed;

        stiffBody.position = new Vector3
        (
            Mathf.Clamp(stiffBody.position.x, boundary.xMin, boundary.xMax),
            0.0f,
            Mathf.Clamp(stiffBody.position.z, boundary.zMin, boundary.zMax)
        );

        stiffBody.rotation = Quaternion.Euler(0.0f, 90f, stiffBody.velocity.x * -tilt);
    }

    void FixedUpdate()
    {
        WindowsMovement();
    }
}

```

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


# Question
Title: How to keep track of elements inside a std::vector?
Let's say I have a `std::vector` with `sf::sprites` and my maps are auto-generated.

Then you won't know which element is which sprite.

---

Example :

I want **THAT** tree sprite to be removed, but I have no idea which element that tree sprite is inside of my vector... :(

---

# Answer
> 3 votes
Fundamentally you're going to have to decide on some kind of external representation of your sprites, something that other code can pass around and store that affords them quick access to your sprites. This kind of object, however implemented, is often referred to as a "handle."

You have several *basic* options:

* Store the index of the sprite associated with the logical object (e.g., `Tree` has a field for `m_sprite` or more generally `WorldObject` has a field for `m_sprite`), so that when you want to destroy or otherwise manipulate the sprite for that object you already have a way to reference it.
* Use an associative container (such as `std::map`) instead of `std::vector` to store your sprites, use the world object or some other useful handle object (as described initially) as the key.
* Use an associative container as above, but mapping to indices in the sprites vector instead of directly mapping to the sprites (this allows you to preserve the contiguous nature of the sprites array).

For slightly more advanced scenarios, you may find Sean Middleditch's article on slot maps interesting.

# Answer
> 2 votes
I would suggest instead of using a std::vector, you use a std::map.

This is what I do in similar situations where I want to keep a "heap" of world objects, but still be able to identify any one of them in O(1) time. In this case, each sprite would maintain a unique identifying key value which you could use to access it in the map.

Keep in mind you can still iterate through a std::map the same way you would as a vector, so you can still use it the same way. But this way, if you want a specific sprite, you can refer directly to it by its key value.

# Answer
> 2 votes
Although Josh's answer cover's more cases, but in your special case you can do it with an easier (but slightly slower in some cases) approach.

Each sprite has a texture.. you can use that to your advantage in this case. When you want to remove all the trees from your scene, you can iterate over all the objects and mark any sprite using "tree texture" to be removed.

The same idea can also be expanded by sub classing the Sprite class, and adding a tag to each sprite. Then you can assign different tags to objects based on what ever feature you want to keep track of, and later make decisions using these tags.

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


# Question
Title: FB.Init() is not accepting in my c# Script
I am trying to connect fb with my game. its first time i am connecting fb with game. i downloaded fb SDk 7.3.0 and i am using unity 5.2.1f1. i imported the sdk in my game asset. then i created a new c# script "FBholder". in Awake() i tried to use FB.Init(). but its not accepting. all other scripts used inside the game are calling correctly, only the scripts came with fb sdk is not working.

```
 using UnityEngine;
 using System.Collections;

public class Fbholder : MonoBehaviour {

// Use this for initialization
void Awake() {
    FB.Init (SetInit, OnHideUnity);// This line is not accepting
}
}

```

i Used this Video for my referance

# Answer
You have not included the correct namespace for `FB`.

Write `using Facebook.Unity;` at top of your class.

Here is the sample script for using `Facebook` with common features, such as posting score, with latest SDK.

```
using Facebook.Unity;

List<string> perms = new List<string> (){"public_profile", "email", "user_friends"};

void Awake ()
    {
        if (!FB.IsInitialized) {
            // Initialize the Facebook SDK
            FB.Init (InitCallback, OnHideUnity);
        } else {
            // Already initialized, signal an app activation App Event
            FB.ActivateApp ();
        }
    }

private void InitCallback ()
    {
        if (FB.IsInitialized) {
            // Signal an app activation App Event
            FB.ActivateApp ();
            // Continue with Facebook SDK
            // ...
        } else {
            Debug.Log ("Failed to Initialize the Facebook SDK");
        }
    }

    private void OnHideUnity (bool isGameShown)
    {
        if (!isGameShown) {
            // Pause the game - we will need to hide
            Time.timeScale = 0;
        } else {
            // Resume the game - we're getting focus again
            Time.timeScale = 1;
        }
    }

    private void AuthCallback (ILoginResult result)
    {
        if (FB.IsLoggedIn) {
            // AccessToken class will have session details
            var aToken = Facebook.Unity.AccessToken.CurrentAccessToken;
            // Print current access token's User ID
            Debug.Log (aToken.UserId);
            // Print current access token's granted permissions
            foreach (string perm in aToken.Permissions) {
                Debug.Log (perm);
            }
        } else {
            Debug.Log ("User cancelled login");
        }
    }

// On Facebook login button
public void OnFacebook ()
    {
        FB.LogInWithReadPermissions (perms, AuthCallback);
    }

```
> 3 votes

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


# Question
Title: What's the most efficient way to send a users keypresses to the server?
So I've been coding a little project in JS recently, using node.js and socket.io to create a server, and HTML5 canvas to draw the client side. The user receives info from the server every 20ms, and the client interprets the data and displays it. If the user presses a key on the keyboard, it stores this information and sends it to the server instatly - so currently, the code is basically 'is keyboard pressed? if yes, send data to server'.

This has all worked great so far, however recently I increased the servers enemies (AI objects) from only 10 to a whopping 100... this lagged the server. Although I will work out enemy spawning efficiency later, the problem that immediately became apparent is that the user's character moved *slower* when the server was lagging. This meant that chasing enemies were able to easily catch up to the character and kill him, whereas usually the character could run away with relative ease.

This leads me to the question, what is the most efficient way that the server can interpret the keypresses of the user, and **ensure that even if it is lagging that enemies will move at the same proportional speed to if the server wasn't lagging**.

Sorry if this question is long-winded, any advice or help would be greatly appreciated. I assume that the same methodologies should apply from different coding languages, so if you have a vague idea how it works in a language you've used... please still share! :)

Thanks,

Cameron

# Answer
In desktop games this is usually resolved by having the client assume it's allowed to do something (and running it's own physics engine etc). You could do the same thing here. The client uses the server to sync for online save or multiplayer and the server can reject events sent from the client; if this is the case the clients environment is set to what the server considers the current valid state.

That said; your problem is almost certainly that your code doesn't have a delta; your player should move X **per second** not X per key press.

So (no particular language);

```
Update (float delta){
    If (keypressed){
           Player.x+=delta*SPEED_PER_SECOND;
    }
}

```

This ensures a lagging server moves in larger jumps if lagging but at the same velocity
> 2 votes

---
Tags: client-server, node.js, websocket
---


# Question
Title: Why did 320x240 become the famous Mode X, and not 400x300?
Mode X was hack invented during the good old days of DOS gaming, offering 320x240 resolution, 256 colors, square pixels, and page flipping.

VGA adapters had 256 KB of memory.

320 * 240 = 76800 bytes 262144 / 76800 = 3.413 pages

So you have lots of memory left over when you do page flipping with two pages (equivalent of double buffering).

400 * 300 = 120000 bytes 262144 / 120000 = 2.18453 pages

You get all the benefits of Mode X, but more resolution. So what is the reason 400x300 resolution didn't become the standard for DOS games? What were its drawbacks?

# Answer
After reading Michael Abrash's Graphics Programming Black Book Special Edition and other resources, I have a good guess why Mode X is 320x240.

The main reason is that affordable VGA monitors were "fixed frequency" and could only cope with a small set of inputs. Setting 400x300 on them would get you something like this:

Overall, VGA graphics cards were rather underpowered and it was a challenge to get smooth animation even at 320x240. The VRAM was slower than main memory and had half or quarter the bandwidth (8 bits vs 16 or 32 bits).

From the book:

> However, the maximum rate at which data can be written to the adapter turns out to be no more than one byte every microsecond. Put another way, you can only write one byte to this adapter every 33 clock cycles on a 486/33. Therefore, no matter how fast I made the line-drawing code, it could never draw more than 1,000,000 pixels per second in 256-color mode in my system.

Philipp's comment is right too. There's a trick you can do to push 32 bits per cycle to the back buffer.
> 1 votes

# Answer
Was the hardware capable of supporting that resolution? I mean both as video card output and monitor input? Just considering actual pixels clock (ignoring front/back porches, h/v syncs etc), at 60 Hz refresh rate:

320\*240\*60Hz = 4608000 ~= 4.61 MHz 400\*300\*60Hz = 7200000 = 7.20 MHz

We are talking of ~56% higher clock here.

And this is BEFORE considering porches, syncs etc.
> 0 votes

---
Tags: graphics-programming
---


# Question
Title: Should I consider a cloud-based networking solution?
In my spare time for the past few years, I have been working on both the front-end and back-end for a space-based online game. This game is initially designed for the PC, and is hopefully able to host thousands of players in a massively playable universe.

Along with the development of the game, I have been building the networking solution almost entirely from scratch. The architectural design of the networking solution is based on a fairly traditional master-server \> sub-server model. I recently was able to run some fairly decent-scale tests on this model and was pleased to see that both my expectations and goals were met. Which leads me to my current fear.

The basic idea behind the current solution is that the master server acts as a router. It knows about all of the currently active sub-servers, including their load (cpu, memory, bandwidth etc) and what the sub server is assigned to handle. The master server has literally no other purpose.

Each sub server is designed to handle one (or more) solar systems. The idea being: as a player, you connect to the master server and tell it which solar system you want to go to. The master server looks to see if there is a sub server already assigned to this solar system and sends you there, otherwise it finds the sub server with the least load and assigns that sub server to the solar system before sending you there.

The part that I am worried about is that this is pretty much as much as I can get out of this model. Once you have been sent to a solar system, you (and everyone else in that solar system) are on that sub server until you leave that solar system. Although I am happy with my testing so far, and that it looks to be able to handle around 300 fairly active peers, fairly comfortable on a well-fitted server, I am worried if I ever end up in the situation where this isn't enough.

I discussed this recently with a few acquaintances of mine. The discussion lead to a cloud-based network maybe being a better solution than single server machines acting as sub servers. Atmittedly, cloud commputing is fairly unknown territory for me. With that being said I've spent some time looking into this and I am fairly confident with the basics, but I have the following questions:

I assume that if I were to re-design the networking solution to work within a cloud-based network, I would no longer need the master-server \> sub-server model, since I could build a single application that would handle all solar systems and peers, and that the cloud would scale based on the number of solar systems and peers?

Any and all advice is welcome!

# Answer
> I assume that if I were to re-design the networking solution to work within a cloud-based network, I would no longer need the master-server \> sub-server model, since I could build a single application that would handle all solar systems and peers, and that the cloud would scale based on the number of solar systems and peers?

I don't know what you think "cloud computing" is. "The cloud" is a marketing buzzword for "others people's servers". It's not a magically scaling supercomputer.

If you decide to move your application "into the cloud", what you would be doing is rent some virtual machines from a company and run your server applications on them. These virtual machines run on normal commodity hardware.

That means your distributed architecture might already be a solution which might scale quite well.

Turning it all into a monolithic server which handles the whole world might be a step back. You could of course try to rent the biggest, most expensive server you can find, but at one point you will hit the limit of what is technically possible.

A distributed approach, however, allows you to rent multiple smaller servers and distribute your server instances on them. When you have some locations in your game which are more frequented than others and start to lag, you could move them to their own servers.

When individual systems become so load-heavy that even the largest servers can't handle them, the next step might be to use sharding. Instead of running one star system with 10,000 users, you run 10 identical copies of that star system with 1,000 users each and put each on its own server. If this is a viable option depends on your game.

Some cloud computing companies even have APIs which allow you to automatically rent and cancel virtual machines, so you might even be able to automate this.
> 2 votes

---
Tags: networking, mmo, server, client-server, cloud-computing
---


title: Casting in UE4 to derived class

text:
# Question
Title: Casting in UE4 to derived class
I’m stuck in understanding of usable actors from survivable c++ example. I have `return Cast<AUsableItem>(Hit.GetActor());`. I have class `AUsableItem`. And I have another class `AUsableWeapon` inherited from `AUsableItem`.

I have function `Use()` in both classes, so basically in the end it looks like `Cast<AUsableItem>(Hit.GetActor())->Use()`. `Hit.GetActor()` returns instance of `AUsableWeapon`. And when i do that `->Use()` call, it goes into `AUsableWeapon` even though it was casted to `AUsableItem`. Problem is - I cant understand how exactly after casting to `AUsableWeapon` I get `Use()` called from `AUsableWeapon`.

# Answer
That is the whole point of inheritance, that the method of the derived class is called. When `AUsableWeapon` redefines a method from its base class then it also has to ensure that a caller never has to worry about which method is called.

To do that, you usually use `Super::Use()` from inside your `AUsableWeapon::Use()` method, so it calls the method from the parent class and then does something in addition to that.
> 1 votes

# Answer
Your `Use` function must be declared as virtual. As the instance is of type `AUsableWeapon` virtual will ensure that AUsableWeapon's version of the `Use` function is always called even if it is casted to a base class pointer type.

Either make it non-virtual by removing the keyword or rename the function in both classes to something else like `UseItem` and `UseWeapon`.
> 1 votes

---
Tags: c++, unreal, unreal-4
---


title: Calculated normals for mesh not working

text:
# Question
Title: Calculated normals for mesh not working
I am trying to implement a 3D mesh viewer with C++ and OpenGL ES 2. I am currently struggling with the calculation of the normals for the vertices, or at least I think that is where the problem lies... I tried to use the technique described in http://www.iquilezles.org/www/articles/normals/normals.htm to calculate the normals for my mesh. Here is the code that I came up with:

```
    // Calculate the non-unit normals for each face first
    glm::vec3 faceNorms[mesh->trigCount];
    for (std::size_t i = 0; i < mesh->trigCount; i++)
    {
        glm::vec3 vecs[3];

        for (uint8_t j = 0; j < 3; j++)
        {
            auto idx = (mesh->indices[i + j]) * 3;
            vecs[j].x = mesh->vertexFloats[idx];
            vecs[j].y = mesh->vertexFloats[idx + 1];
            vecs[j].z = mesh->vertexFloats[idx + 2];
        }

        glm::vec3 e1 = vecs[0] - vecs[1];
        glm::vec3 e2 = vecs[2] - vecs[1];
        faceNorms[i] = glm::cross(e1, e2);
    }

    // Now we need to sum the face normals for each vertex with larger faces carying more weight
    // due to their non-unit normals. We can then normalize the sum to get the vertex normals.
    for (std::size_t i = 0; i < mesh->vertexCount; i++)
    {
        glm::vec3 norm(0.0f);

        for (std::size_t j = 0; j < mesh->vertices[i].trigIdxs.size(); j++)
        {
            norm += faceNorms[mesh->vertices[i].trigIdxs[j]];
        }

        mesh->vertices[i].trigIdxs.shrink_to_fit();

        if (norm != glm::vec3(0.0f))
            norm = glm::normalize(norm);

        std::size_t pos = i * 3;
        mesh->normalFloats[pos]       = norm.x;
        mesh->normalFloats[pos + 1]   = norm.y;
        mesh->normalFloats[pos + 2]   = norm.z;
    }

```

At the moment I believe that all the importing code is correct as I thoroughly checked it out and tested what I could. The model is imported with arrays for all the vertex and normal floats and a float with indices. This is so that I can easily pass the data to OpenGL. As part of the importing I am keeping track of which faces share a vertex.

As far as I can see this code should be compatible with that in the article. I don't really have too much experience with OpenGL and the math involved to know if it should work in the first place though.

I tried to implement some shading using the information on http://www.learnopengles.com/android-lesson-two-ambient-and-diffuse-lighting/ but quickly ran into some trouble. It seems that the moment I try to translate the normals to eye-space, the dot product of the normal and the "light vector" becomes 0 and any form of lighting vanishes, leaving me with a black silhouette of my model. The below shader is an attempt to try an determine if the value is indeed 0. It is not a proper shader though so please don't comment on it being incomplete as to any specific lighting model.

```
uniform mat4 uModelMatrix;
uniform mat4 uViewMatrix;
uniform mat4 uProjMatrix;

attribute vec4 aPosition;
attribute vec4 aNormal;

varying vec4 vColor;

const vec3 lightPos = vec3(10.0, 10.0, 10.0);
const vec4 baseColor = vec4(1.0, 0.5, 0.25, 1.0);

void main()
{
    vec3 norm = vec3(uViewMatrix * uModelMatrix * aNormal);
    vec3 objPos = vec3(uViewMatrix * uModelMatrix * aPosition);
    vec3 lightVector = normalize(lightPos - objPos);
    float cosine = dot(norm, lightVector) * 100000000.0;
    vColor = baseColor * cosine;
    vColor.w = 1.0;

    gl_Position = uProjMatrix * uViewMatrix * uModelMatrix * aPosition;
}

```

And the other half:

```
varying vec4 vColor;

void main()
{
    gl_FragColor = vColor;
}

```

This happens with any model that I try to load. I can post more information if needed but I have a feeling that my mistake is glaringly obvious (for an OpenGL expert of course) and somewhere in the code that I have here.

PS. If I use some basic non calculated shading like just using a semi-transparent color for each vertex then I can see that my model appears to be correctly loaded.

# Answer
> 7 votes
> vec3 norm = vec3(uViewMatrix * uModelMatrix * aNormal);

The normal cannot be transformed like a point, to transform a normal you use the inverse transpose matrix.

If you want the fun details of why this is here is a qoute from the OpenGL Red Book that explains it better then I ever will:

> Mathematically, it's better to think of normal vectors not as vectors, but as planes perpendicular to those vectors. Then, the transformation rules for normal vectors are described by the transformation rules for perpendicular planes.
>
> A homogeneous plane is denoted by the row vector (a , b, c, d), where at least one of a, b, c, or d is nonzero. If q is a nonzero real number, then (a, b, c, d) and (qa, qb, qc, qd) represent the same plane. A point (x, y, z, w)T is on the plane (a, b, c, d) if ax+by+cz+dw = 0. (If w = 1, this is the standard description of a euclidean plane.)
>
> In order for (a, b, c, d) to represent a euclidean plane, at least one of a, b, or c must be nonzero. If they're all zero, then (0, 0, 0, d) represents the "plane at infinity," which contains all the "points at infinity."
>
> If p is a homogeneous plane and v is a homogeneous vertex, then the statement "v lies on plane p" is written mathematically as pv = 0, where pv is normal matrix multiplication.
>
> If M is a nonsingular vertex transformation (that is, a 4X4 matrix that has an inverse M-1), then pv = 0 is equivalent to pM-1Mv = 0, so Mv lies on the plane pM-1. Thus, pM-1 is the image of the plane under the vertex transformation M.
>
> If you like to think of normal vectors as vectors instead of as the planes perpendicular to them, let v and n be vectors such that v is perpendicular to n. Then, nTv = 0.
>
> Thus, for an arbitrary nonsingular transformation M, nTM-1Mv = 0, which means that nTM-1 is the transpose of the transformed normal vector. Thus, the transformed normal vector is (M-1)Tn.
>
> **In other words, normal vectors are transformed by the inverse transpose of the transformation that transforms points**

---
Tags: opengl, shaders, opengl-es2, 3d-meshes, normals
---


# Question
Title: Collision resolution when moving in two directions
I am making a bomberman clone and I'm having problems regarding moving on both x and y axis (pressing down+left, down+right, up+left). Here is a video to demonstrate the problem. I use Tiled for the map. Below is the code:

```
private void checkCollision(float delta) {
    player.getVelocity().scl(delta); // dont mind
    Vector2 position = player.getPosition();

    if(player.isMovingRight()) {
        Array<Rectangle> tiles = getTiles((int)(position.x/TILE_SIZE + 1), (int)(position.y/TILE_SIZE - 1),
                (int)(position.x/TILE_SIZE + 1), (int)(position.y/TILE_SIZE + 1));
        for (Rectangle tile : tiles) {
            if(player.getRectangle().overlaps(tile)) {
                System.out.println("overlap right");
                player.setPosition(tile.x - player.getWidth() , player.getPosition().y);
            }
        }
    }
    if(player.isMovingLeft()) {
        Array<Rectangle> tiles = getTiles((int)(position.x/TILE_SIZE - 1), (int)(position.y/TILE_SIZE - 1),
                (int)(position.x/TILE_SIZE + 1),  (int)(position.y/TILE_SIZE + 1));
        for (Rectangle tile : tiles) {
            if(player.getRectangle().overlaps(tile)) {
                System.out.println("overlap left");
                player.setPosition(tile.x + tile.width, player.getPosition().y);
            }
        }
    }

    if(player.isMovingUp()) {
        Array<Rectangle> tiles = getTiles((int)(position.x/TILE_SIZE - 1), (int)(position.y/TILE_SIZE - 1),
                (int)(position.x/TILE_SIZE + 1), (int)(position.y/TILE_SIZE));
        for (Rectangle tile : tiles) {
            if(player.getRectangle().overlaps(tile)) {
                System.out.println("overlap up");
                player.setPosition(player.getPosition().x, tile.y + tile.height);
            }
        }
    }
    if(player.isMovingDown()) {
        Array<Rectangle> tiles = getTiles((int)(position.x/TILE_SIZE - 1), (int)(position.y/TILE_SIZE + 1),
                (int)(position.x/TILE_SIZE + 1), (int)(position.y/TILE_SIZE + 1));
        for (Rectangle tile : tiles) {
            if(player.getRectangle().overlaps(tile)) {
                System.out.println("overlap down");
                player.setPosition(player.getPosition().x, tile.y - player.getHeight());
            }
        }
    }

    player.getVelocity().scl(1/delta);

}

private Array<Rectangle> getTiles(int startX, int startY, int endX, int endY) {
    TiledMapTileLayer layer = (TiledMapTileLayer)level.getMap().getLayers().get(1);
    Array<Rectangle> rectangles = new Array<Rectangle>();
    for (int x = startX; x <= endX; x++) {
        for (int y = startY; y <= endY; y++) {
            Cell cell = layer.getCell(x, y);
            if(cell != null) {
                Rectangle rect = new Rectangle(x*TILE_SIZE, y*TILE_SIZE, TILE_SIZE, TILE_SIZE);
                rectangles.add(rect);
            }
        }
    }
    return rectangles;
}

```

To reproduce the problem shown in the video: Try to collide (coming from up) with one of the blocks that is not on the sides, press both down and left. Try again but press down and right. For the third one, make sure you are colliding with the top wall by pressing up then press left (both are pressed). It can also be done on the bottom wall by pressing down and left.

# Answer
> 1 votes
This is almost a comment, but too long so i'll post as an answer. Hopefully it will help.

There's a design flaw i think in your code : you solve on x then on y but in both cases you set both x and y...
So when you solve on Y, you 'break' the solve on X you just made.

I think you should split the collision detection and its resolution :

(pseudo-code)

```
 var alignOnX = false, alignOnXCoordinates = -1;
 var alignOnY = false, alignOnYCoordinates = -1;

 // detection

 if (moving left && collide left)
     alignOnX = true;
     alignOnXCoordinates = the right coord

 if (moving right && collide right )
     alignOnX = true;
     alignOnXCoordinates = the right coord

 if (moving up && collide up )
     alignOnY = true;
     alignOnYCoordinates = the right coord

 if (moving down && collide down )
     alignOnY = true;
     alignOnYCoordinates = the right coord

  // resolution

  if (!alignOnX && !alignOnY) return; // regular move, just return

  var newX = expectedX, newY = expectedY;

  if (alignOnX) newX = alignOnXCoordinates;
  if (alignOnY) newY = alignOnYCoordinates;

  setCoords(newX, newY)

```

---
Tags: collision-detection, tiles, collision-resolution, direction
---


title: Looping trough a std::map won't work

text:
# Question
Title: Looping trough a std::map won't work
**Answer** :

> Turns out the for loop did work.
>
> Lesson Learned :
>
> You might want to try putting something in it to see if the code inside actually executes....

---

As the title says I would like to loop trough a `std::map` filled with `sf::Sprite*`'s.

However when I try it like this :

```
(in .h file)

std::map<std::string, sf::Texture*> textures;

(in .cpp file)

for (auto const &ent1 : textures)
{

}

```

It tells me that the `Debug Assertion Failed!`.

With this error "log" :

> Program: C:\WINDOWS\SYSTEM32\MSVCP140D.dll File: c:\program files (x86)\microsoft visual studio 14.0\vc\include\xtree Line: 237
>
> Expression: map/set iterator not dereferencable

---

At this point I've tried reading some on how it works, and I don't understand what I'm doing wrong.

I've been playing around with it, removing some parts and adding new ones.

I'be been removing `const`, removing the `&` and combining those two.

# Answer
It is likely that you have corrupted the underlying storage of your `map` object and the VC++ debug runtime has protection code that tests if the data structure and iterators are in a valid state to avoid more damage. Clobbering memory and other undefined behaviour can result in all sorts of amusing results.

When in doubt about the semantics of something, consider making a test project in which you explore the concept, and if you run into a bug, try to isolate it as far as possible to rule out things.
> 1 votes

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


# Question
Title: How to embed unity webplayer built inside phonegap app?
After exporting my game made with unity, I got two files web.html and web.unity3d

I want to embed this game in a phonegap app. I used this code:

```
<object id="UnityObject"
          classid="clsid:444785F1-DE89-4295-863A-D46C3A781394"
          width="1024"
          height="768"
          codebase="http://webplayer.unity3d.com/download_webplayer/UnityWebPlayer.cab#version=2,0,0,0">
     <param name="Web/Web.unity3d"
            value="Web.unity3d" />
         <embed id="UnityEmbed"
                src="Web/Web.unity3d"
                width="1024"
                height="768"
                type="application/vnd.unity"
                pluginspage="http://www.unity3d.com/unity-web-player-2.x" />
 </object>

```

This code works on the browser but nothing shows when I build with xcode.

# Answer
> 2 votes
You can't run webplayer builds on smartphones (you shouldn't use the webplayer at all, since it'll be discontinued in 2016)!

You can however export your game as an Xcode project for iOS.

There is also the option of exporting your game as a WebGL application.
The problem here being that
A.) *The build will detect mobile browsers and refuse to start* * and
B.) *The performance will not be good. (expect \<10fps)*

You should however be able to add native iOS code to your project and run the rest of your phonegap app in a UIWebView.

*-- more on the WebGL solution --*

**UPDATE 1:**

I tested a WebGL build in the FirefoxOS Emulator. It worked, but I can not tell you anything about the performance on the actual smartphone or if it works with iOS. It only shows a javascript confirm dialog in the beginning about WebGL and support for mobile deviecs. You should be able to remove this somewhere in a .js file.

**UPDATE 2:**

OK - I tested the same build on my Xperia Z3 compact running the latest Version of Chrome for Android. While it did work, the framerate was very poor. If your scene is not to complex and you don't mind low end smartphone users suffering through an unplesent experience, you could to it.
BUT YOU SHOULDN'T!

I still can't say anything for iOS, but since they added support for WebGL in Safari, I assume it will work to.

\*If you want to remove the annoying popup you get,
just remove the lines 57 to 61 in the `/Release/UnityConfig.js`-file in your WebGL build.

# Answer
> 0 votes
The Unity webplayer is an NPAPI browser plugin, compiled to run using Intel x86-derived processors on OS X & Windows. There is no NPAPI support in iOS, and the plugin isn't compiled for ARM processors— this is the core reason why what you're trying to do isn't possible.

NPAPI is an old (the “N” stands for “Netscape”) and flawed technology that's on its way out (Chrome no longer supports it), so it's not really what you want even if it sounds like the simplest approach. Follow @RUB3N's advice in his/her answer and use an iOS build instead. It would take some work, but you should be able to integrate the native code Unity spits out with your PhoneGap app.

---
Tags: unity, web, webapp
---


title: Area attack collision resolving

text:
# Question
Title: Area attack collision resolving
I'm planning to write little 2D go-right-and-swing-your-sword game. When i started to write my ideas on paper i've come across a little problem. Let's say i'm using magic spell, ex. fireball which technically is a signle projectile flying slowly in a specified direction. As it's defined to be a piercing projectile, I want it to hit every enemy only once, no matter how big their sprites are. And how I do it? I know i can use the array of already hit enemies and check every frame if projectile collides something new, but is it a correct way? Are there any tried and true ways of resolving problems like this?

# Answer
> 2 votes
I see two ways to do this:

1. An array on the enemy that keeps track of what fire ball has hit it and check against it every time there is a collision.
2. As you have already suggested: an array of identifiers of enemies that have been hit by the fireball.

Now you have to ask *"Who's responsible for calculating the damage of the fireball on the enemies?"*, if you answer "The fireball", then the approach you suggested, 2., is the way to go: unless the enemy knows anything about a fireball, there is no need for it to keep track of those; the fireball however should probably know about the enemies.

Another option is that if your fireball and your enemies are completely decoupled and the damage is managed by a 3rd party (e.g. 'DamageManager'), well in this case, the DamageManager will have to keep track of the enemies and fireballs combinations that have occurred and not re-apply the damage.

To be honest, however, ultimately, as long as it fits your game architecture, and it's efficient enough (you check that by using a profiler), any method to make it work is ok :)

# Answer
> 0 votes
A completely different aproach may be: consider your "fireball" (or area weapon) damage as **HP per second**. And every step you calculate the damage in this way

```
 enemy.HP = enemy.HP - firebal.damagePerSec * dt

```

where dt is your frame delta time.

I know this is a bit out of target , as your question is very specific.

---
Tags: collision-detection
---


# Question
Title: Switching character and keeping animations in Unity default third person controller
This is probably a ridiculous question, but I am doing a school project in Unity and am trying to create a basic game. For movement I want to use third person controller and since this is very basic I wanted to keep the default 3d model of character as well (Ethan). But since it is so colorless I had a friend of mine to color it up and then export it back to unity. The problem is that it's a different model now and animations don't work anymore so I want to know how to correctly switch them to keep default animations? The models are the same otherwise so animations should be possible to apply. Since nothing I tried so far didn't help I really hope someone can give me some instructions.. :) Thanks

# Answer
This is a somewhat complex thing, which there are a couple of different options.

1. You could take Ethan and color him. The "Ethan Occlusion" in ThirdPersonCharacter/Textures show this file. You can add some color to him via it. The mapping is a bit tricky to see from the file, but it could be done.
2. Load Ethan.fbx into a 3d modeling program (Blender, for instance), and use that to help color him. This will make #1 a bit easier.
3. Bring your own model. The trick with this is you need to set the bones up. Really this needs to be done in the 3d program, while bringing it into Unity and setting it up with the controller, via what's called an Avatar. Ethan's is called EthanAvatar, in the Models folder. In theory, switching the Avatar but keeping the same controller should allow you to use the same motions. If all of this is greek to you, well, let's just say it's a complex process.

If you can, I would try for #1 or #2. If you really want your friends model, then you need to go through the third step, in particular setting up the Avatar correctly.
> 2 votes

---
Tags: unity, animation, character
---