title: Casting a Matrix4 class to float*

text:
# Question
Title: Casting a Matrix4 class to float*
```
glUniformMatrix4fv(glGetUniformLocation(program, "projMatrix"), 1, false, (float*)&projMatrix);

```

`projMatrix` is a an object of type Matrix4 where the first variable declared is a float array. Does `(float*)&projMatrix` therefore somehow retrieve this array? What does the casting appear to be doing?

# Answer
It only works, because you supply a pointer to the beginning of the matrix object, which by chance is the same as the beginning of the float array. I wouldn't personally rely on this behaviour, since it can make your code fail silently if you just change the order of two lines, add a new line in front of it or change the matrix library.
> 1 votes

# Answer
What this does is get a pointer to the start of the Matrix object and then `reinterpret_cast` that to a pointer to floats using c-style casting shorthand `(float *)`.

It happens to work because the Matrix class happens to only contains the float cells or the cells are right at the beginning of the Matrix class.

**If any other member variables ever gets added to the beginning of the Matrix class or any virtual functions\* this will stop working**

(\*Due to the virtual table pointer that is put at the beginning of the struct/class in memory by some compilers, in full accordance with the C++ standard.)

What you want to do to improve maintainability is add implicit (or explicit) `operator float *()` cast operators that will return a pointer to the first float of the cell array:

```
struct Matrix4 {

  // cells[row][column]
  float cells[4][4];

  operator float *() {
    return &(cells[0][0]); // get pointer to first cell
  }

  // const version
  operator const float *() const {
    return cells[0]; // alternative way to write it
  }

};

```

(alternatively 4x vec4 can be used for the rows)

Then you can remove the `(float*)&` "magic" and just pass the matrix object directly

```
glUniformMatrix4fv(location, 1, false, projMatrix);

```

If using C++11 or later you can add `explicit` to both operators to fix some implicit cast issues and ambiguities:

```
explicit operator float *() { ...

```
> 1 votes

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


title: Black Area in skybox in opengl

text:
# Question
Title: Black Area in skybox in opengl
Hi I am using opengl and I am having a problem if I go further from the skybox with the camera I get black areas, a smaller radius of the skybox will make the camera too close to the object to stay inside the skybox and increasing it obviously doesn't help. :

Here is the code for the skybox:

```
  glEnable(GL_TEXTURE_2D);
    glPushMatrix();
    qobj = gluNewQuadric();
    glTranslated(50,0,0);
    glBindTexture(GL_TEXTURE_2D, underwater);
    gluQuadricTexture(qobj,true);
    gluQuadricNormals(qobj,GL_SMOOTH);
    gluSphere(qobj,100,100,100);
    glPopMatrix();

```

# Answer
> 0 votes
I see you are using GLU. You probably use it for the projection matrix too.

You need to double the 'far' value that you pass into gluPerspective.

---
Tags: opengl, c++, camera, skybox
---


# Question
Title: How do I project the Earth globe on a flat plane with minimal distortion?
* I want to build a game where the game map is the planet Earth.
* The game map needs to be on a 2d plane, with the Earth texture projected on it
* If the player walks endelessly in one direction, it should just run laps around the Earth.
* I want to split the map in several small tiles and Load on Demand as the player walks

I'm not sure how to best solve this problem. What Map Projection do I use? From my research it seems like most maping apps like Google Maps, or OSM etc use variations of the Mercator Projection. I can't use that because, while the player would be able lap around the earth when walking east, he wouldn't be able to walk north. It won't tile vertically.

Then the Peirce Quincuncial Projection looked promising, it's a perfectly tiled projection. But the problem then becomes distortion is too extreme here. Some places don't look the same. I can live with a tiny bit of distortion, but this is too much.

Then I found another common solution was using a Truncated Icosahedron (probably subdivided into smaller tiles for LoD). This looks like the best alternative so far. But now my problem is I'm not sure exactly how I would work out the algorithm to take tiles from the 3d Icosahedron and tile them side by side on a 2d plane. That would look like this:

How would I stretch it to fill the holes?

Is there some other obvious solution I'm missing? How do games like Pokémon Go do this kind of thing?

# Answer
My favourite projection is that of Buckminster Fuller.

You just need to implement some fancy wrap-around that let's you jump from the edge of the map to another edge.

But the distortion is very low: land mass sizes are preserved.

https://en.wikipedia.org/wiki/Dymaxion\_map
> 3 votes

---
Tags: mathematics, maps, projection
---


title: Unity Events with Arguments

text:
# Question
Title: Unity Events with Arguments
I'm fairly new to Unity and I can't really get my head around the best way to communicate between scripts. For example, if the character jumps, what is the best way to inform other scripts (such as ground objects) to act on the characters velocity and move.

I recently had a look at this which describes how to make a messaging system. My problem with this, is that I'm not sure how to pass arguments when triggering events.

For example, If I wanted to do:

```
if (Input.GetButtonDown("Fire1")){
    EventManager.TriggerEvent("Jump", jumpVelocity);
}

...

EventManager.StartListening("Jump", OnJump);

void OnJump(velocity)
{
    //scroll ground objects horizontally
}

```

How could I add arguments to a messaging system, or would there be a better way?

# Answer
> 3 votes
You can use Typed UnityEvent

**EventManager.cs**

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

namespace Assets.Scripts
{
    [System.Serializable]
    public class Event : UnityEvent<System.Object> { }

    public class EventManager : MonoBehaviour
    {

        public static EventManager Instance;

        private Dictionary<string, Event> _eventDictionary;

        private void Awake()
        {
            if (Instance == null)
            {
                Instance = this;
                _eventDictionary = new Dictionary<string, Event>();
            }
            else if (Instance != this)
                Destroy(gameObject);

            DontDestroyOnLoad(gameObject);
        }

        public static void StartListening(string eventName, UnityAction<System.Object> listener)
        {
            Event thisEvent = null;
            if (Instance._eventDictionary.TryGetValue(eventName, out thisEvent))
            {
                thisEvent.AddListener(listener);
            }
            else
            {
                thisEvent = new Event();
                thisEvent.AddListener(listener);
                Instance._eventDictionary.Add(eventName, thisEvent);
            }
        }

        public static void StopListening(string eventName, UnityAction<System.Object> listener)
        {
            if (Instance == null) return;
            Event thisEvent = null;
            if (Instance._eventDictionary.TryGetValue(eventName, out thisEvent))
            {
                thisEvent.RemoveListener(listener);
            }
        }

        public static void TriggerEvent(string eventName, System.Object arg=null)
        {
            Event thisEvent = null;
            if (Instance._eventDictionary.TryGetValue(eventName, out thisEvent))
            {
                thisEvent.Invoke(arg);
            }
        }
    }
}

```

# Answer
> 1 votes
Instead of using the type `UnityAction` in your event handling system as suggested by that tutorial, use (or create) a different delegate type which takes an `Object` as an argument.

Add a second parameter of type `Object` to `EventManager.TriggerInvoke` and pass that parameter when you invoke the delegate.

Your event listener then receives that object you passed and is responsible for casting it to the type expected by it.

---

But note that there are many more ways to communicate between scripts than building your own subscriber-based event system.

For example, if you have a reference to another gameObject, you can use `GetComponent` to get a script-based (or any other) component on it and directly call that component's methods. There are also methods for getting components from relatives in your scene hierarchy, like `GetComponentsInChildren` or `GetComponentInParent` which can be quite useful.

And if you want to communicate between components on the same game object in a message-based manner, then you can use the method `BroadcastMessage` to call a method of a given name in all other components which have one.

# Answer
> 1 votes
In your case, I assume the best way to go about it is to simply attach the camera to the character that jumps instead of moving all the surroundings individually.

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


# Question
Title: Unexpected results during collisions in Unity
I've got a basic car-based game I'm starting in Unity. Currently the scene has only a floor, a car (player-controlled), and one building.

Bumping into the building at low to medium speeds works as expected. When getting the car up to max speed and smashing into the building, though, weird results happen.

Originally, the car was being pushed through the floor and falling off the map. I changed the floor from a plane to a cube that was stretched to be broad and flat (scale 2 height), and that helped. Now the car seems to clip right through the building at top speed, sometimes flipping itself into the air when it emerges.

So what gives?

The car and building are both imported .fbx models and both have box colliders stretched to the outer bounds of the models. The car has a rigid body with gravity. The building used to have a rigid body, but I removed it once I realized it was making the building fly into the air on impact (which was definitely not what I wanted).

Here are the relevant parts of the movement code:

```
  bool key_up = false;
  float top_speed = 1f;
  float current_speed = 0f;
  float acceleration = .01f;

  void Update ()
    {
    if (Input.GetKeyDown (KeyCode.UpArrow) && !key_up) key_up = true;
    if (Input.GetKeyUp (KeyCode.UpArrow) && key_up) key_up = false;

    if (key_up)
      {
      if (current_speed < top_speed) current_speed += acceleration;
      }

    else
      {
      if (current_speed > -.1f && current_speed < .1f) current_speed = 0f;
      if (current_speed != 0f) current_speed = current_speed * 0.9f;
      }

    transform.Translate (0f, 0f, current_speed);
    }

```

**Update**:

After switching the camera to a fixed position (rather than following the car), I've gotten better observations. The car will clip right through at any speed if I keep pushing forward. There's initial resistance from the collision detection and some stuttering from the car, but it always breaks through and then flips into the air on its way out.

I've added the following function to the car code:

```
void OnCollisionEnter (Collision collision_info)
  {
  current_speed = 0f;
  }

```

current\_speed is what's being used to translate the car forward each frame. This has slowed the bug down, but the car always eventually pushes through if I hold down the gas long enough. It looks as if Unity's collision detection isn't moving the car back far enough on each frame that the car is colliding. Must I handle that portion on my own?

# Answer
> 0 votes
The main problem I was having was the transform.Translate function I was using to move the car. Doing it that way caused the physics engine to be slightly behind each frame, basically making it play catch up with my code. I changed this to move the car's rigid body directly and not the car itself. Specifically, I used Rigidbody.MovePosition().

I should note that after changing the movement code, I had to apply a frictionless physic material to the car's box collider to get it to move across the floor correctly.

I also put my movement code into UpdateFixed() rather than Update(), which also helps the physics engine stay up-to-date.

With these three fixes, I no longer needed any of the other band-aid solutions I'd added, including changing the fixed timestep, messing with the box collider sizes, or trying to use continuous collision detection.

Here's the new movement code:

```
public class car_input : MonoBehaviour
  {
  bool key_up = false;
  bool key_down = false;
  bool key_left = false;
  bool key_right = false;

  float top_speed = 1f;
  float current_speed = 0f;
  float acceleration = .02f;

  Rigidbody body;

  //////////////////////////////////////////////////

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

  //////////////////////////////////////////////////

  void Update ()
    {
    if (Input.GetKeyDown (KeyCode.UpArrow) && !key_up) key_up = true;
    if (Input.GetKeyUp (KeyCode.UpArrow) && key_up) key_up = false;

    if (Input.GetKeyDown (KeyCode.DownArrow) && !key_down) key_down = true;
    if (Input.GetKeyUp (KeyCode.DownArrow) && key_down) key_down = false;

    if (Input.GetKeyDown (KeyCode.LeftArrow) && !key_left) key_left = true;
    if (Input.GetKeyUp (KeyCode.LeftArrow) && key_left) key_left = false;

    if (Input.GetKeyDown (KeyCode.RightArrow) && !key_right) key_right = true;
    if (Input.GetKeyUp (KeyCode.RightArrow) && key_right) key_right = false;
    }

  //////////////////////////////////////////////////

  void FixedUpdate ()
    {
    if (key_up)
      {
      if (current_speed < top_speed) current_speed += acceleration;
      }
    else if (key_down)
      {
      if (current_speed > -top_speed) current_speed -= acceleration;
      }
    else
      {
      if (current_speed > -.1f && current_speed < .1f) current_speed = 0f;
      if (current_speed != 0f) current_speed = current_speed * 0.9f;
      }

    float turning_rotation = current_speed * 2.5f;
    if (key_left) transform.Rotate (0f, -turning_rotation, 0f);
    if (key_right) transform.Rotate (0f, turning_rotation, 0f);

    Vector3 movement = transform.forward * current_speed;
    body.MovePosition (body.position + movement);
    }
  }

```

---
Tags: unity, collision-detection, physics
---


title: Detecting Overlapping Shapes

text:
# Question
Title: Detecting Overlapping Shapes
I have two classes `Circle` and `Square` which derive from an abstract base class `Shape`.

A `Shape*`array stores pointers to the `Circle` and `Square` objects (which include their random position in a 2D grid).

The objective is to determine which shapes in the array overlap and the objects themselves should contain the methods to calculate this. For example, the `Square` class would have methods: `bool overlapsWithSquare(Shape s)` and `bool overlapsWithCircle(Shape s)`.

My idea is to construct two for loops which compare each and every shape in the array, however, how would my program know which method to call upon as we don't know what sub-type each Shape object is?

If the actual type was known, I could have two virtual methods in each object, `bool overlaps(...)` with different parameters `Square s` and `Circle c`.

# Answer
I had solved a similar problem by simplifying my geometry. In my case there was only one such function: `bool overlaps(Shape)`

A shape was just a list of floats, and the collision logic switched internally based on that list using the following logic:

* A shape with only 3 values was assumed to be a circle `[x, y, radius]`
* A shape with only 4 values was assumed to be a line `[x1, y1, x2, y2]`
* A shape with any even number of values \> 4 is a polygon `[x1, y1, ... xn, yn]`
* Any shape with an odd number of values \>= 5 is not a valid shape

Also worth looking into is the Separating Axis Theorem. This is what I was using in my physics engine. It works really well if you're only using convex polygons.

This article did wonders for me understanding this in case you haven't chosen a method for actually implementing your `overlaps` function yet: http://www.metanetsoftware.com/technique/tutorialA.html
> 1 votes

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


# Question
Title: AddForce not moving imported model in Unity
I've got a Unity project with an imported .fbx model I'm attempting to add movement to.

As a test, I've added a sphere primitive with a sphere collider, a rigid body, and the following script:

```
public class ball_test : MonoBehaviour {

  private Rigidbody rb;

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

  void FixedUpdate ()
    {
    Vector3 movement = new Vector3 (1f, 0.0f, 1f);

    rb.AddForce (movement);
    }
  }

```

This is partly copied from the Roll A Ball tutorial, and this works fine. The ball slowly rolls with no problem.

I've imported a custom model, added a box collider, a rigid body, and assigned to it the same script. **It doesn't move.**

Here's how they're set up:

# Answer
The difference here had to do with the sphere collider versus the box collider. I didn't realize the physics engine was taking the shape of the object into consideration.

**The box requires a lot more force to move than the sphere.**

I had to increase the force on the custom model to at least 6f before I saw any movement, where as 1f was fine for the ball.

**There was also too much friction with the ground.**

I had to apply a zero friction physic material to the model's box collider. Without this, the car would move at 10f, but just roll over end-to-end instead of sliding/driving.
> 0 votes

---
Tags: unity, physics, movement
---


title: Convert Tris to Quads or Polygons

text:
# Question
Title: Convert Tris to Quads or Polygons
Im working on a ledge climbing system in Unity. I am coding a method that takes a mesh and tries to generate a bunch of connected nodes that will help the player detect ledges that can be climbed.

This is what I have made so far:

The thing I need to do now is to remove connections that are not ledges (sorry if that doesn't explain much). This is the desired result:

So, basically, I need to convert those Tris to Polygons. I have no idea of how to do this. Each node stores its position, its normal, and what nodes it is connected to.

Thank you for reading!

# Answer
> 0 votes
Since your problem is pretty much solved by you having carefully crafted the nodes yourself, I'm just going to offer up a method to remove the interconnections.

Your each node has two or more connections, but a node at the "edge" of your mesh will only ever have two connections. These will always be towards the "outside" of your mesh, meaning your edges will trace the mesh from the outside.

So, what you need to do is to take the first node you can find with two connections and start there. Lets say you have a mesh like so:

What you want is to have connections between the outer nodes and remove all else. Now, you go over the nodes and find the first one with two connections. Let's say you've found D in this example. Next, you need to move on to another node which is connected to D. Since E has too many connections to think about and since it's actually easier to solve compared to the others (I'll explain this later), I'm going to go with A.

So, we're on the node A and we have three nodes connected to A. We only need two, so we need to eliminate one. The way we go about that is to find the previous connection we came from (which is D in this case) and then go over each of the connections and find which one has the largest angle value between the previous connection (A-D) and the current one. In this case, this would be A-B connection with a 90 degree angle difference (since A-E to A-D has a 45 degree difference). So, we need the A-B connection to stay, then we let the A-E connection go. Now we have this:

Before we move on, I'd like to add something. In case you have a larger angle than 180 like a 230 or something, you need to find where your object is then decide whether this angle is actually 230 or just 130. If your angle is not facing your object then you need to find the one that is facing your object (i.e. do a subtraction from 360). This could be a question in and of itself, so I'm not going to go into too much detail on this.

Next up, we move onto B (since we came from D and the only other connection A is now B). Now we look at each connection B has and find out that B is connected to A and C which are both outer nodes (they only have two connections), so B must also be an outer node. We pick B-C to stay and remove B-E and B-F. Then we move on to C, and see that it only has two connections, so we move on to F. Since F has three connections (and only one is an outer node, which is C), we look at each connection and compare angles and decide that E-F has to go. Then we do the same with H (in which case it's already connected to two outer nodes) and remove E-H. Then we move on to G, then E then when we come back to D, our starting node, we stop and have a perfect edge detection (in theory).

You might be thinking, "Why didn't we go to E node instead at first? Is that because E has too many connections?", and the answer would be: No, not because it has too many connections but because it's already connected to two nodes which have only two connections and this would've made it too easy to solve this situation.

The solution would be like this if we took the other way around:

We go to E and check each connection. Since E has two nodes that each have two connections connected to it, E is connected to two outer nodes. Two outer nodes will mean that this is also an outer node (because of how you set your nodes up), then we remove all other connections of E and we're just left with the B-F connection. We iterate to F and remove B-F, then iterate through the rest and we're done. (This would've made the example somewhat meaningless).

So, there you have it. I don't have any code to show for it, but it should be relatively easy (since you already seem to have experience) to turn the logic into a code algorithm.

---
Tags: unity, 3d, mesh
---


title: Enemy (prefab) Behaviour messed up

text:
# Question
Title: Enemy (prefab) Behaviour messed up
I have created a prefab of an enemy with a NPC Behaviour script attached to it. The enemy correctly detects the player's position and walks (with animation) towards it (NavMesh Agent). If in range the enemy attacks the player until one of them dies. So far so good!

I duplicated the enemy in the scene a couple of times and the original enemy works as it should but the "replicas" completely ignore the player and just sit in Idle. What am I missing?

**\[EDIT\]** As requested in the comments: This is how Character Health is assigned

```
//From my player script
public class PlayerScript : MonoBehaviour {

public float health = 100f;

//SINGLETON and Assigning instance on Awake();

//yada yada

public void PlayerTookDamage(float damage)
    {
        if(health > 0f)
        {
            health -= damage;
            this.GetComponent<Animator>().SetTrigger("tookDamage");
        }
        else return;
    }

}

```

And this is from the NPC's script:

```
public class NpcBehaviour : MonoBehaviour
{
    private NavMeshAgent _agent;
    private static Animator _anim;
    private Transform _target;
    private float distanceFromTarget;
    private Vector3 direction;
    public float lookRadius = 10f;
    public float rotationSpeed = 1.5f;

    void Start()
    {
        _target = PlayerScript.Instance.transform;
        _anim = GetComponent<Animator>();
        _anim.SetBool("Idle", true);
        _agent = this.GetComponent<NavMeshAgent>();
    }

    void Update()
    {
        float distance = Vector3.Distance(_target.position, transform.position);

        if (distance <= lookRadius && PlayerScript.Instance.health > 0f)
            {
                _anim.SetBool("Walk", true);
                _agent.SetDestination(_target.position);
                _anim.SetBool("Idle", false);

                FaceTarget();

                if (distance <= _agent.stoppingDistance && cooldown <=0f)
                {
                    _anim.SetBool("Walk", false);
                    Attack(); //just reduces player's health
                }
            }
            else
            {
                _agent.isStopped = true;
                _anim.SetBool("Walk", false);
                _anim.SetBool("Idle", true);
            }
    }

```

# Answer
> 1 votes
You have declared `_anim` as static. This means that every copy is going to be modifying a single instance’s animator (the last one `start`ed). Simply removing the `static` keyword may fix the problem.

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


title: How to render gameplay over UI?

text:
# Question
Title: How to render gameplay over UI?
I'm working in 2D.

I have set up 2 cameras. One for UI and another one for gameplay.

I need the UI to be rendered after before game objects (over gameplay). I wanted to achieve this without using world space canvas, because It requires being scaled for every other device along with a camera.

UI can be drawn over gameplay using greater depth than gameplay camera. And because it's depth only there is no solid color, so it all works well.

But you cannot set gameplay camera to depth only because it doesn't render things right, it doesn't clear the render texture I guess.

So this is what happens if gameplay camera is set to depth only.

This is what happens when gameplay camera is set to Solid Color and UI Camera has bigger depth. You can see that the ring is covered by UI arrow.

If the UI Camera depth would be lower than gameplay camera (Solid Color). It would all be covered by gameplay camera without even displaying UI.

These are mine settings.

Is there a way to achieve this in Unity without using World Space Canvas Mode?

# Answer
This (your first screenshot) happens when you have no cameras that clear everything. All you need is a **Background Camera** that renders *nothing* (remove all render flags in the culling mask) but a *Solid Color* (set the clear flags to solid color). Then just set the depth of the **Background Camera** lower than your **Main Camera**. Your **UI Camera** should have a depth value that is higher than both cameras (if I understood what you want correctly).

I'm not sure why you want to have a setup like this, but since you do, there you go. This setup should be possible with just one camera though.
> 2 votes

# Answer
I've seen some of these problems in my own work though I can only comment on the red artifacts as I have never done the same thing as you have in 2D - I have made it in 3D - worked through the problems also. So here goes.

First the red game object is doing that because I think you don't have a background but using a solid black colour. If you can - try using an Unlit shader that is coloured black and try that again - this should fix the artifacts.

As for the cameras - I *think* you should swap your camera depths around and put put both your camera clear flags to depth only.

Let me know if that works.
> 0 votes

---
Tags: unity, rendering, gui
---


# Question
Title: How can I use a different upscaling method in dx11?
I need to upscale images using the 'box' scaling algorithm as the pixel art textures in my game don't scale well with bilinear because of the blur. Either that, or use high res pictures which would be undesirable and inflate the size by many times.

# Answer
> 2 votes
Typically you just draw 2D images as textures (a.k.a. "sprites") as is done with `SpriteBatch` in DirectX Tool Kit. You can specify the sampler state to use `D3D11_FILTER_MIN_MAG_MIP_POINT` to turn off all the filtering.

```
const float border[4] = { 0.f, 0.f, 0.f, 0.f };

// PointWrap
CD3D11_SAMPLER_DESC desc(D3D11_FILTER_MIN_MAG_MIP_POINT,
    D3D11_TEXTURE_ADDRESS_WRAP, D3D11_TEXTURE_ADDRESS_WRAP, D3D11_TEXTURE_ADDRESS_WRAP,
    0.f, maxAnisotropy, D3D11_COMPARISON_NEVER, border, 0.f, FLT_MAX);

// PointClamp
CD3D11_SAMPLER_DESC desc(D3D11_FILTER_MIN_MAG_MIP_POINT,
    D3D11_TEXTURE_ADDRESS_CLAMP, D3D11_TEXTURE_ADDRESS_CLAMP, D3D11_TEXTURE_ADDRESS_CLAMP,
    0.f, maxAnisotropy, D3D11_COMPARISON_NEVER, border, 0.f, FLT_MAX);

```

---
Tags: directx11
---


# Question
Title: Why is it called "roguelike" and "metroidvania"?
As the title says, where did *roguelike* and *metroidvania* genre games get their names from? All other genres (that I can think of) have pretty self-explanatory names like:

* *First Person Shooter*: You shoot and it's first-person perspective.
* *Role-Playing Game*: You role-play as another character.
* *Massive Multiplayer Online*: The game is online with multiplayer and supports a lot of players.

But roguelike and metrodvania doesn't seem to relate to any core gameplay element like the other genres do. So why are they called **roguelike** and **metroidvania**?

# Answer
Roguelike and Metroidvania have pretty unconventional names but they do in fact describe the gameplay elements of the game, just not as straight-forward as the other genres.

---

**Roguelike** originates from the game *Rogue* released in 1980, hence the name **rogue**like. However some claim that there are earlier occurrences of roguelike genre games such as *Beneath Apple Manor* and *Sword of Fargoal*. Some main characteristics of the Roguelike genre are:

* Procedural generation
* Character progression
* Permadeath.

---

**Metroidvania** much like *roguelike* originates from gameplay characteristics of a specific game – or in this case two: *Super **Metroid*** and *Castle**vania***. Koji Igarashi is often credited with establishing the foundation of the genre. Metroidvania is a bit more difficult to define but in this specific case I believe Wikipedia did an excellent job:

> Metroidvania games generally feature a large interconnected world map the player can explore, though access to parts of the world is often limited by doors or other obstacles that can only be passed once the player has acquired special items, tools, weapons or abilities within the game

Metroidvania games are sometimes described as "open world" and are often side-scrolling platformers that heavily rely on some sort of story. Koji Igarashi also noted that Metroidvania games make a key point to guiding the player through the game – often with visual cues and landmarks of some sort.
> 39 votes

# Answer
Both terms describe game genres (or subgenres) by associating the with a very well known game that invented or coined these gameplay elements.

A really good and extensive explanation along with the question if we need the term "soulslike" can be found here: Do We Need A Souslike Genre?

Originally I just wanted to comment on the already given and really good answer but I don't have enough reputation yet.
> 2 votes

# Answer
In some cases, videogame genres are named initially based on the games that popularized them. "Doom-clone" was a fairly common term before the more generic "FPS" was de-facto standardized. This despite the fact that Doom was not the first FPS. DOTA-clone was the standard name for that genre until LOL came along and invented the more neutral term "MOBA". Roguelike and Metroidvania are named for the games that popularized that particular style.

But there's more to it than that. They don't have more generic terms because they're not big enough genres to warrant having a term for them. Indeed, they're not necessarily "genres" at all; they're *styles* of gameplay.

For example, Metroid Prime is Metroidvania, but it's also an FPS. There have been Roguelike FPS games. These terms tend to describe very specific mechanics or ideas used in a game than generic terms like "RPG" or "platformer".

A Roguelike is a general combination of several elements: permadeath, significantly randomized content, etc. It describes games as diverse as Nethack and FTL: Faster than Light. The core gameplay of these games have pretty much nothing in common, but they have the general style of Roguelikes.

Metroidvania is a general combination of a single world, mobility-based navigation impairment (aka: the ability to reach areas is frequently determined by movement abilities rather than locks), frequent back-tracking, and a few other things. It's not as broad of a concept as Roguelike, but it still represents something beyond the standard genre conventions.
> 2 votes

---
Tags: terminology
---


title: All sides shadow outline in Unity NGUI

text:
# Question
Title: All sides shadow outline in Unity NGUI
How can I make such exactly the same shadow using NGUI?

# Answer
> 1 votes
It looks the image has Shadow + Outline. For text you should use "NGUI Label" component for gameobject. But there is only 1 effect could be applied to text: Shadow or Outline. I believe you can make new class inherited from UILabel and make Effect field like an array, with multiplied effects.

Update: I've found not elegant way how to do it without much pain and inheritance. There is a diff for UILabel.cs:

```
--- a/Assets/NGUI/Scripts/UI/UILabel.cs
+++ b/Assets/NGUI/Scripts/UI/UILabel.cs
@@ -18,6 +18,7 @@ public class UILabel : UIWidget
        Shadow,
        Outline,
        Outline8,
+       ShadowAndOutline,
    }

    public enum Overflow
@@ -847,6 +848,7 @@ public class UILabel : UIWidget
            if (mEffectStyle == Effect.Shadow) return 2;
            else if (mEffectStyle == Effect.Outline) return 5;
            else if (mEffectStyle == Effect.Outline8) return 9;
+           else if (mEffectStyle == Effect.ShadowAndOutline) return 9;
            return 1;
        }
    }
@@ -1903,6 +1905,47 @@ public class UILabel : UIWidget

            ApplyShadow(verts, uvs, cols, offset, end, pos.x, -pos.y);

+           if (effectStyle == Effect.ShadowAndOutline)
+           {
+               pos.y /= 2;
+               pos.x = pos.y;
+
+               offset = end;
+               end = verts.Count;
+
+               ApplyShadow(verts, uvs, cols, offset, end, -pos.x, pos.y);
+
+               offset = end;
+               end = verts.Count;
+
+               ApplyShadow(verts, uvs, cols, offset, end, pos.x, pos.y);
+
+               offset = end;
+               end = verts.Count;
+
+               ApplyShadow(verts, uvs, cols, offset, end, -pos.x, -pos.y);
+
+               offset = end;
+               end = verts.Count;
+
+               ApplyShadow(verts, uvs, cols, offset, end, -pos.x, 0);
+
+               offset = end;
+               end = verts.Count;
+
+               ApplyShadow(verts, uvs, cols, offset, end, pos.x, 0);
+
+               offset = end;
+               end = verts.Count;
+
+               ApplyShadow(verts, uvs, cols, offset, end, 0, pos.y);
+
+               offset = end;
+               end = verts.Count;
+
+               ApplyShadow(verts, uvs, cols, offset, end, 0, -pos.y);
+           }
+
            if ((effectStyle == Effect.Outline) || (effectStyle == Effect.Outline8))
            {
                offset = end;

```

Result:

# Answer
> 1 votes
Unity as a built-in Shadow component for UI elements. It's far from perfect but it's a good starting point.

Otherwise, you could duplicate the text, attach an outline component to the front text, and change the font color to the background text after moving it a little bit to get your shadow.

But I definitively advise you to use TextMeshPro, now free on the Asset store. Here is a video about outline and soft shadow using TextMeshPro

---
Tags: unity, ngui
---


title: NavMesh moving is not smooth

text:
# Question
Title: NavMesh moving is not smooth
I have two car in game one of them is cop that chase player, i put a NavMesh on cop with these values:

when the cop get close to player (player speed is 10 ) , movement will go jittery and not smooth.
Note: cop will not collide with player because i have changed stopping distance in script instead of editor. Note 2: this jittery movement is not only in camera its also on scene view.
now how i must make movement smoother? where is the problem?

# Answer
I also had the same problem.. At first i was not sure what was causing the problem but just today i came to realize that the problem was the navmesh agent itself so i moved the object using rigid body instead of navmesh agent and then it was all good
> -1 votes

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


title: LibGDX Game vs ApplicationAdapter

text:
# Question
Title: LibGDX Game vs ApplicationAdapter
When I create a new LibGDX project the main class of Core project extends **ApplicationAdapter**. Here is how it looks like.

```
package com.marimba.apptest;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;

public class AppMain extends ApplicationAdapter {
    @Override
    public void create () {

    }

    @Override
    public void render () {
        Gdx.gl.glClearColor(1, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    }
}

```

So I have to change the **ApplicationAdapter** to **Game** if I want to call setScreen method in order to switch between Screens. So what is the use of **ApplicationAdapter** ? When shall I use it ?

# Answer
As @user3068350 said, both Game and ApplicationAdapter implement ApplicationListener. It's useful to extend Game if you plan on using the Screen interface in your game, however some developers may wish to take a different approach and handle screen management their own way. If this is the case, these will extend ApplicationAdapter.

Personally, I like my classes to implement a custom Updatable and/or Drawable interface, as I separate my render method into update and draw. In this case, using Screen would defeat the purpose as the interface contains a render method.
> 9 votes

# Answer
As the ApplicationAdapter and the Game class implement the ApplicationListener interface they can both be used almost interchangeably when creating your game. If you are set on using Screen, there is nothing stopping you from implementing them with both options.

The **Game** class has a little more overhead with it using Screens. However, this overhead is designed to make it easier to implement different stages/levels in your game. It is important to note that this overhead is minimal.

The **ApplicationAdapter** has no additional overhead (it is a straight implementation of an ApplicationListener). This gives you more control as you have to do everything yourself. Personally, I prefer to use ApplicationAdapters.

**TL;DR:** No real difference between them. ApplicationAdapter gives you a little more control & Game is a little less work.
> 2 votes

# Answer
The Game class implements the ApplicationListener interface and is just a class that is designed to make it easy to switch between different screens. When a method in the ApplicationListener is called, the Game class takes care of delegating it to the currently set screen.
> 1 votes

---
Tags: java, libgdx
---


title: Upgrade items on shop menu

text:
# Question
Title: Upgrade items on shop menu
I made a game and I made a Magnet upgrade and I have 8 game objects to set active 1 by 1 every time when I upgrade the magnet and I have (int upgrade = 0;).

But when I upgrade these game objects it's set active, but if I quit the game and start again all these game objects are FALSE.

How can I make e.g if I upgrade to (int upgrade = 6) and to make my game objects active only from element 0 to element 6. I do upgradeMagnet(); to void Update but its make active only 1 game object depends from (int upgrade) if (int upgrade) is 5 and only game object element 5 is active.

```
    public GameObject[] upgranded;
    public int upgrade = 0;

    public void upgrandeMagnetButton()
    {
        upgrade += 1;
        upgradeMagnet();
    }

        void upgradeMagnet()
    {
        if (upgranded[upgrade])
        {
            upgranded[upgrade].SetActive(true);
        }
    }

```

# Answer
simply activate them in your start.

```
void Start(){

   upgrade = load from player prefs here
   int count = upgrade+1;
   for(int i = 0; i < count; i++){
      upgranded[i].SetActive(true);
   }

}

```
> 1 votes

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


# Question
Title: Scalability/Performance of physics-based character animation
I am asking this question because I am currently at the point where I have to think about how the characters in the game that I am making will be animated and I want to check if my desired approach will apply well.

As the title suggests I am very interested in physics-based skeletal animation and in addition to that I would like to use neural networks to closely connect the AI of a character and its movements.

Things like this have already been done and it should be pretty easy to find resources on how to implement such a system into a 3D rendering engine.

What I am asking is how well can I expect this to work with the game that I am picturing? The game is going to be a top-down shooter (looking very much like Redie) in an open world, which will mean that the animations will have to be able to adapt to any kind of terrain. An important mechanic in the game is an FOV system, which makes the player act like an absolute light, only illuminating areas that the character can directly look at (just like in Teleglitch, but 3D). This is a reason why I want to use volumetric shadows and it should allow for some culling opportunities.

However, during the game, the screen may be filled with swarms of characters, thinking, moving and colliding each individually.

To avoid some work and to be easier on the FPS, I have set my goals for the graphical quality to 'minimal', which means I will only use low polygon meshes (similar to the ones used in Redie or this video) and most objects will be solid coloured.

What I would like to put a lot of focus on is accurate lighting/shadowing (volumetric shadows), accurate physics and dynamic character animation, which should all be computed for hundreds of individual entities at a high frame rate.

Is it a good idea to use physics based skeleton animation for this many (easily 500) characters? Also taking into account all the computation time saved by low poly meshes(and hitboxes) and all the time still to be spent on calculating many lightsources and volumetric shadows?

I am programming in C++ and I am using OpenGL for rendering.

# Answer
> Things like this have already been done and it should be pretty easy to find resources on how to implement such a system into a 3D rendering engine.

Question - has this been implemented in any current game engine? If the answer is no, then there is almost certainly a reason for that.

I think you might be greatly underestimating the distance between research paper and a system so well known and tested a small team can include it in their game (without it being the major feature of the game). Check out NaturalMotions work, and the size of their team when considering comparable efforts.

Also, physically-based animation sounds good, but is often impossible to work with in practice. You lose all control over the characters motion. The paper you reference talks about characters learning to walk, which is the worst way to get something to look like something else. If you want your bipedal characters to look like bipedal characters, just use bipedal mocap. You can't do better than the original source. Google's current state of the art still looks pretty awful when compared to human motion https://www.youtube.com/watch?v=faDKMMwOS2Q

As for performance... well, thats a sliding scale, so kinda impossible to answer. No, you almost certainly can't have 500 characters with a full deep NN evaluating every frame, because it's difficult to get 500 fully-animated characters on-screen on todays hardware using trivial traditional animation techniques.

Long story short - figure out what your game is good at, focus on that, improve animation if you have time & energy left.
> 2 votes

---
Tags: collision-detection, physics, performance, lighting, skeletal-animation
---


title: Love2D how to zoom out map?

text:
# Question
Title: Love2D how to zoom out map?
I've set up a basic map with Tiled, imported it with STI library (https://github.com/karai17/Simple-Tiled-Implementation) and everything looks in place.

How can i get a zoom-out feature now? I can kinda zoom in using scalex and scaley and i tried the same procedure to zoom out.

However, if i set i.e. scalex = 0.5, scaley = 0.5 the map actually scales in size but it only fit 1/4 the screen size, and the remaining 3/4 are just black space.

# Answer
This code just uses individual tile images that must each be 100x100 px. The zoom still needs a bit of tweaking.

```
function love.load()

  tileImage = love.graphics.newImage("tileImage.png") --tile size is currently 100x100px
  tileSize = 100

  mapLength,mapHeight = 20,10
  zoom, zoomSpeed = 0.3, 0.05
  cameraX,cameraY = 1,1
  cameraSpeed = 0.1
  zoomOffset = 0.01

  map = {}

  for x = 0,mapLength+1 do
    map[x] = {}

    for y = 0,mapHeight+1 do

      map[x][y] = {tileImage}

    end
  end

end

function love.draw()

  for x=1,mapLength do
    for y=1, mapHeight do
        love.graphics.draw(map[x][y][1],applyScrollX(x),applyScrollY(y),0,zoom,zoom)
    end
  end

end

function love.update()

  print(zoom..", "..cameraX..", "..cameraY)

  if love.keyboard.isDown('w') then cameraY = cameraY + cameraSpeed end
  if love.keyboard.isDown('a') then cameraX = cameraX + cameraSpeed end
  if love.keyboard.isDown('s') then cameraY = cameraY - cameraSpeed end
  if love.keyboard.isDown('d') then cameraX = cameraX - cameraSpeed end

  function love.wheelmoved(x, y)
    if y > 0 then
        zoom = zoom + zoomSpeed
    cameraX,cameraY = cameraX - zoomOffset, cameraY - zoomOffset
    elseif y < 0 then
        zoom = zoom - zoomSpeed
    cameraX,cameraY = cameraX + zoomOffset, cameraY + zoomOffset
    end
end

end

function applyScrollX(num) --num is x position in tiles

  return num*zoom*tileSize+(cameraX*tileSize)

end

function applyScrollY(num)

  return num*zoom*tileSize+(cameraY*tileSize)

end

```
> 1 votes

---
Tags: lua, love2d
---


# Question
Title: Split a grid into shapes that can be moved back from 4 directions
Basically I have 4 grids Left, Right, Top, Bottom. Player can choose each of them and move all the blocks on that grid to the Middle grid to fulfill it, like tetris from 4 directions:

> ```
>       |0 0 0|
>       |0 0 0|             (0 is empty, 1 is generated block)
>       |0 0 1|
>        _ _ _         Bottom->Mid  Right->Mid  Top->Mid   Left->Mid
> |0 0 0|0 0 0|0 1 0|    |1 0 0|     |1 1 0|     |1 1 1|    |1 1 1|
> |0 0 0|0 0 0|0 1 1|    |1 0 0|     |1 1 1|     |1 1 1|    |1 1 1| -> Win! Generate
> |1 0 0|0 0 0|0 1 1|    |0 0 0|     |0 1 1|     |0 1 1|    |1 1 1|    another game.
>        _ _ _
>       |0 0 0|
>       |1 0 0|
>       |1 0 0|
>
> ```

The point here is to make sure there is at least 1 way for player to combine all 4 grids.

What I've tried so far is generate the right order first (Left-\>Right-\>Top....), then generate all the blocks 1 by 1. When a block is generated, i perfomn a check with the generated order (move all the blocks in Left to Mid, then Right then Top...) to see if its still working, the code is similar to this:

```
// (left->right, top->right->botttom->left, top... it doesn't have to be all 4 directions)
Random the right direction order.

Generate all possible coordinates from all the directions from the path above.
Initialize an empty list to store all chosen coordinates.

While(!(Generate enough x*x block))
{
    Get one coordinate from all possible coordinates

    if (Perform a check with the right order and the chosen list)
        Add it into the chosen list.

}

```

The problem here is a block can be wrong at this point, but it can become right when another block is generated:

> ```
>           |0 0 0|                                      |0 0 1|
>           |0 0 1|                                      |0 0 1|
>           |0 0 1|                                      |0 0 1|
>            _ _ _                                        _ _ _
>     |0 1 0|0 0 0|0 0 0|                          |0 1 0|0 0 0|0 0 0|
>     |1 0 0|0 0 0|0 0 0|                          |1 0 0|0 0 0|0 0 0|
>     |1 0 0|0 0 0|0 0 0|                          |1 0 0|0 0 0|0 0 0|
>            _ _ _                                        _ _ _
>           |0 1 0|                                      |0 1 0|
>           |0 1 0|                                      |0 1 0|
>           |0 0 0|                                      |0 0 0|
>  At this point the logic is wrong          But if I add 1 more block to the
>   with Top->Left->Bottom order.               top grid, it'll become right.
>
> ```

**There is no way to check if the each block is right or wrong without re-calculate all the generated blocks logic**

So i want to ask if there a better way, algorithm to do it.

# Answer
**It turns out there are only 9 968 valid & solvable 3x3 puzzles of this form** (if my math is right), so one simple option is to just generate ALL of them, then shuffle this list as a "deck" of puzzles to present to the player.

(The storage requirements are quite modest. As you'll see, we can store each board as a 32-bit integer with room to spare, so we can store the whole shebang in under 40 kiB without even trying to be frugal)

This eliminates any biasing in the puzzle generation process (other generation methods I thought of tend to produce big blocks for the early selections, and sparse blocks at the end, which could give unwanted order hints to the player solving them), or accidental repeats (though I am counting flips/rotations as distinct in the count above).

**Here's how I derived that number:**

1. Let's label each cell of the fully-assembled/completed puzzle board with the ID of the direction it came from. That gives us 4 options per cell, or 2 bits each.

Multiplied by 3x3=9 cells, that's 18 bits to represent any one completed puzzle. That's comfortably smaller than a 32-bit integer, so we can concatenate all the cells' bits together to make an index between `0` and `2^18 - 1`

So, let's loop over each integer in that range, and check whether it represents a solvable puzzle! (262 144 cases to check in total)
2. First, we check whether the puzzle contains at least one cell from each of the Right, Up, Left, and Down grids. If any grid isn't represented, we'll reject the puzzle as invalid. (After all, we don't want to short-change the player and give them a puzzle with fewer choices to make)

That gets rid of 75 664 cases, off to a good start. :)
3. Next, we pick a solution order to try. There are 24 permutations of {Right, Up, Left, Down}, so I just pre-generate them and loop over the set.

For each of these solution orders in succession, we check whether the puzzle is solvable in that order.

We do this by looping over the directions in our permuted order, and looping from the near to far side of each line of cells along this direction, checking that:

* No cell that came from this direction comes later in its row/column than one from an earlier direction.
    * At least one row has a cell matching the direction we're checking that directly abuts against one that arrived in an earlier pass, OR against the far side of the grid.

If either of these conditions is not met, then this puzzle can't be assembled in this order, and we try the next one.

If no order yields a solution, then we reject this puzzle as unsolvable and continue. (176 512 potential puzzles fail this test)

Now, we might get multiple solutions for some puzzles. If you like, you could limit your selection to only those with a unique solution, or sort them by decreasing solution count to create a difficulty progression. ;)

Here are the counts I get:

```
# Solutions       # Puzzles
---------------------------------
 1  (unique)         2 224
 2                   1 688
 3                   3 672
 4                     680
 5                     832
 6                     872
 7+                      0

```

Even though this may seem like a lot of work, it only took about 10 seconds to find all of these solutions exhaustively on my little tablet PC.

(That said, a brute force search like this does NOT scale well - it's exponential in the number of cells in your grid, so bumping up to a 4x4 puzzle, well... my computer's still working away to see if it can solve it)
> 1 votes

---
Tags: algorithm, procedural-generation, matrix, random
---


# Question
Title: Prefabs property is not overriding when changing from editor script?
In unity we can have different instances of a prefab with different properties. Unity represents the overridden property with bold characters. This works fine when manually change the value of prefab instance. But when I do it using a editor script, it do not turn bold and the property value changes to the source prefab when I play the game.

Here is an example of the code:

```
using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(testScript))]
public class editor : Editor {
    public override void OnInspectorGUI(){
        DrawDefaultInspector ();
        testScript scrt= (testScript)target;
        if (GUILayout.Button ("button")) {
            scrt.test();
        }
    }
}

```

.

```
using UnityEngine;
public class testScript: MonoBehaviour {
   test(){
       gameManager  =GameObject.Find("GameManager");
       gameManager.GetComponent<gameManager>().arr = new GameObject[3];
   }
}

```

.

```
using UnityEngine;
public class gameManger:MonoBehaviour{
    public GameObject[] arr;
}

```

The arr array in gamemanager class is not overridden and it changes to the source prefab value on play.

> EDIT:

actual function called from editor script

```
    public void assignPortalPass(){
    GameObject gameManagerObj = GameObject.Find ("Game Manager");
    gameManager gameManagerScript = gameManagerObj.GetComponent<gameManager> ();
    Transform passed = GameObject.Find ("passed").transform;
    int noOfChild = passed.childCount;
    if (noOfChild != gameManagerScript.noOfPortals) {
        Debug.LogError ("Check passed objects and noOfPortals (class gameManager) because both values are different");
        return;
    }
    Undo.RecordObject(gameManagerObj, "Made some changes to gameManager");
    //as suggested by the answer

    gameManagerScript.portalPass = new GameObject[noOfChild];
    for (int i = 0; i < noOfChild; i++) {
        gameManagerScript.portalPass [i] = passed.GetChild (i).gameObject;

    }
}

```

}

# Answer
Unity doesn't get any notification when you change properties through script, so you have to tell it you've changed something using methods like Undo.RecordObject(). This logs the change so your script's work can...

* Display the same as manual changes in the Inspector UI
* Work correctly with Undo/Redo in the Editor
* Persist into game when you hit Play, and restore itself back to the value you set in Edit Mode after you exit Play Mode
* Save into your scene file / assets folder so your changes aren't lost when you close Unity

Here's what the Unity docs have to say about this method:

> Records any changes done on the object after the RecordObject function.
>
> Almost all property changes can be recorded with this function. The transform parent, AddComponent, object destruction can not be recorded with this function, for that you should use the dedicated functions.
>
> Internally this will create a temporary copy of the object's state and at the end of the frame Unity will diff the state and thus detect what exactly has changed. The changed properties are then recorded on the undo stack. If nothing has actually changed (Binary exact comparison is used for all properties), no undo operation will be stored on the stack

It's pretty simple to use:

```
void ThisIsMyMethodThatChangesAnObject(GameObject myObject) {

    // Tell Unity we're going to modify this object.
    // Leave a text description so we know what the change was.
    Undo.RecordObject(myObject, "Made some changes to myObject");

    // Okay, now make those changes...
    // Code that changes the object goes here.
    // eg. myObject.name = "Bob";

    //---------------------------

    // Oh, I also want to change a component on the object.
    var component = myObject.GetComponent<SomeKindaComponent>();

    // We need to tell Unity we're changing the component object too.
    Undo.RecordObject(component, "Changing the component on myObject");

    // Now we change the component.
    // Code to change the component goes here.
    // eg. component.SetFloofiness(11.0);
}

```
> 1 votes

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


# Question
Title: Convert the animation inside FBX into Unity
Recently i bought a package with an fbx and lots of animations.

Since I want full control and change a couple of details, I want to convert them into the regular Unities Animation System. I cant convert them into the normal Unity Animations though. They are "read only".

I can load them, copy paste them into my own "not-read-only" animation file. But somehow i cant change the file anymore after I pasted something inside.

What am I doing wrong? Is that something "impossible"? Can you guys help?

# Answer
Allright, its a kind of a workaround but here is how it works:

1. If your Animation inside the FBX is a Humanoid (Avatar/Mecanim..) Animation you have to convert it into a Legacy animation first. Click on the file, import settings, pick animation, convert to legacy.

2. Place a Animation-Compontent to you Animateable Gameobject and increase the Animation Size to 2. Insert your Legacy animation in, and insert a new empty animation in.

3. In the Unity-Animator copy all read-only keyframes and paste them into your new empty animation. You have to use: "ctrl+c / ctrl+v"

4. Profit. The empty Animation is changeable
> 2 votes

---
Tags: unity, animation, fbx
---


# Question
Title: Eliminate isolated cave in procedural cave generation
I've got an algorithm that generates a cave procedurally, the map is modeled in the data as a 2d array of 0s (empty space) and 1s (wall). The algorithm works just fine, but I've got quite some isolated small caves on the scene, which I would like to avoid.

That's how the map looks that gets generated. Is there some efficient algorithm to remove the black holes in the white wall sections? I was thinking of something like:

For every closed cave, check if there is a bigger cave and if so, close it.

But that seems insanely inefficient since I'd have to loop over the map a lot in order to do this for all small caves.

# Answer
> 3 votes
1. Edge-dilate and then edge-constrict the pixels - box or radial filter - basically increase the black areas by 1-2 pixels, then reduce by 1-2 pixels again. This will "smooth" the array out, removing small caves. The problem is this will also affect fine detail in your larger areas (unwanted?).
2. Classify connected regions as nodes in a graph, as a graph is truest representation of what you've generated (that is, it models the flow your entities are able to move within). How:

* Run through the entire 2D array, and add every white / open cell to an open list.
    * Step through each open cell in the open list.
    * Walk all neighbours and neighbours-of-neighbours etc. of the current cell, till you've found all open cells connected to this one (use flood fill for this); each time you find one, remove it from the open list, and add it to the list for this locally-adjacent group / node.
    * Now step to next (remaining, unaccounted for) open cell in the open list and do the same.

At the end you will have a sequence of nodes representing groups of connected, open cells. You can now just look at the number of cells constituting that group and remove it if its too small, or you can look it in a more geometric fashion (such as width / height of bounds) and reduce / eliminate where appropriate. This is a bit more complex, but it gives more control by only affecting those spaces you wish to affect, unlike dilate-constrict.

# Answer
> 1 votes
To get rid of the black spots inside the white portions , you can just flood-fill the large black part, (look for black parts until one is more than say 40% of the cells,) then remove all the other black parts.

If you want to keep sufficiently large caves that are still inside the walls then it is more complicated.

You could flood-fill every cave and remove any of them that are below a certain area/radius. That would be O(n) in caves, plus finding each cave, which I you could do by scanning each cell of the map only once, besides the flood-fill, so O(n) in cells.

If that is still too slow, you could try randomly sampling points, keeping only the large caves you happen to hit, and getting rid of the rest.

---
Tags: javascript, procedural-generation, level-design
---


# Question
Title: Should I rotate the Camera using the View or World?
I have an issue with roll/rotation. I have a Camera defined to move along X and Y axis at a given Z for zoom. The camera is always pointed straight down the Z axis so there is not any yaw or pitch. I do however need to roll or rotate. The problem I have is that when I roll/rotate left or right I am modifying up in the view. So, when the mouse or keyboard are moved up toward the top, the target actually moves toward the new up. If I rotate 90 right degrees when I move mouse up or arrow up it moves right. I fully understand why it is behaving this way. I need to find a way to make it not behave that way. I need to roll/rotate independent of x, y. My first thought is to use the view when moving camera along x and y. Then rotate the target (1-9 quads) in the world space. Any thoughts on this? Any Examples would help and would be greatly appreciated.

# Answer
I found a solution. I added a world matrix and moved the rotation to the world. This corrected the mouse panning issue. I Still need to roll on the local mouse location. However, this was the answer to the post.

```
//Mouse
protected override void Roll(Vector2 mousePosition)
{
    var normalizedMousePosition = mousePosition.Normalize(ViewportSize);
    var screenDelta = normalizedMousePosition - LastMousePosition;

    LastMousePosition = normalizedMousePosition;

    RotationAngle += screenDelta.X;

    UpdateWorld();
}

//Keyboard Q/E
protected override void KeyRoll(float angle)
{
    angle *= RotationScaler;
    RotationAngle += angle;

    UpdateWorld();
}

protected override void UpdateWorld()
{
    var zRotation = Matrix.RotationZ(RotationAngle);
    World = Matrix.Transpose(zRotation);
}

```
> 0 votes

---
Tags: c#, directx, sharpdx
---


title: Unity - Blend tree weird transition

text:
# Question
Title: Unity - Blend tree weird transition
I have duplicated the blend tree from the ThirdPersonCharacter (Ethan) which comes with the Standard Assets package.

In the duplicate I went into the blend tree and swapped out the walk animation "HumanoidWalk" with my own animation named "walk", but now I get a weird transition from the animation "walk" to "HumanoidRun".

Both animations, my **walk** animation and the original "HumanoidWalk" are root animated and look similar they have around 1.5 velocity both and same frame length.

**Animation Settings:**

I created the animation in blender, you will see in my video below that the animation itself runs smooth and as it should, but the transition to **HumanoidRun** is very weird for unknown reasons. I am using a custom metarig armature which comes with the blender add-on "rigify", I deleted some bones on the finger, but the avatar has a check and is ok (no warnings either).

**Rig Settings**

**Player settings**

I basically "copied" all the components from Ethan (ThirdPersonController) and only changed the Animator Controller and the Capsule Collider settings to match the model.

I made some short videos where you clearly see the problem, it happens if the parameter `Forward` is at about 0.6 - 0.8.

https://youtu.be/Q-T7FplDxLE

https://youtu.be/nrJNeo1ltsg **NOTE**: First I am demonstrating how it looks with the normal animations, then I add my own.

What am I doing wrong?

**More Infos:**

I just baked the walk animation in blender and exported it to unity again, but this made no difference.

I tried to export it from blender as FBX, it made no difference. However, I noticed that the import is happening much faster and applying in unity importer is very fast now.

# Answer
> 0 votes
I figured it out. The problem is, that Ethan uses another armature than metarig, and thus it won't blend properly. I thought it will work, because I read that chapter about retargeting which promised that we can use humanoid animations for other models, but it seems like this is only true if both models use the exact same armature.

It finally works perfectly fine after creating my own run and idle animation and assigned them in the duplicated Animator controller.

I also asked the unity support, here is their answer:

> We have tried changing some settings in your animation parameters and found that 'Blend type - 2D Freeform Directional' eliminates this weird blending issue. Try using that for your blend trees.

---
Tags: unity, animation, blender
---


# Question
Title: How can i prevent objects faces clipping over other objects faces?
I have a naked body, I have a bra over that body, I have a suit over that bra.

Since the objects arent accurate enough, i get ugly "clipping". Is there a way or method I can prevent this? (except messing with the Scale)

Like a shader which gives out a Render-Queue to faces near other faces... and does always render first ... if the rendered item is near enough.

# Answer
You don't need to disable enable mesh renderers in order to make this work. I got into a similar problem way back, and i solved it using a shader. All it does is cull the part of the mesh not visible from the camera. Since i learned how to do this through a tutorial, i'll leave the link here:http://www.toxicfork.com/194/per-object-clipping-planes-shader-in-unity3d-5
> 3 votes

---
Tags: unity, 3d, shaders
---


# Question
Title: Frame-rate independant movement with acceleration
First of all, this is different to this question, because that question doesn't update entities the same way I am.

My update loop goes something like this (for the player):

* Apply acceleration based on arrow keys input
* Apply some downwards acceleration for gravity
* Multiply the acceleration by something like 0.999
* Add the acceleration to the velocity
* Multiply the velocity by about 0.6
* Add the velocity to the player's position
* Render the player
* Repeat

So, this is a fairly nice smooth movement, and makes it easy to implement jumping by applying a sharp upwards acceleration in one frame.

The only problem is that it seems to make it very difficult to make the movement speed frame-rate independent. I've tried many different ways, like multiplying the movement acceleration by the delta time when it's *applied*, multiplying the acceleration by the delta time *just before being added to the acceleration*, multiplying the velocity by the delta time, etc., but none of these worked. They pretty much all had the same effect of varying movement speed and jump height dependant on the frame-rate.

My question is: with this, or a similarly working, movement system, how can I use delta-time or otherwise to ensure the movement speed, gravity, and similar, is *not* dependant on the frame-rate.

# Answer
> 4 votes
Most of what you want can be handled by typical deltaTime multiplication just like the example you link. For example, with a simple Euler integration:

```
acceleration = GetTotalAccelerationOnBody();

velocity += acceleration * deltaTime;

position += velocity * deltaTime;

```

The one trick is your damping constants - the * 0.999 and * 0.6. They need a slightly different treatment.

Typically we don't accumulate acceleration from frame to frame - it's computed from scratch based on the forces acting on the body over our current timestep. So you might not need the * 0.999 multiplier at all.

If you do choose to use it, you don't need deltaTime correction on it - all it's doing is scaling the units your forces/accelerations are measured in, not applying a timeslice-sized portion of them. So it can be as simple as

```
acceleration = 0.999 * GetTotalAccelerationOnBody();

```

The * 0.6 damping coefficient on velocity is a different matter. Velocity does have memory from frame to frame, so this acts a bit like a friction to slow the body down in the absence of forces. The trick is that this deceleration isn't linear: multiplying by a fraction between 0 and 1 over and over will give you an exponential falloff (eg. 0.5, 0.25, 0.125, 0.0625...)

So we need a different style of time correction for this type of effect, one that preserves the exponential tail shape even when stepped at different increments.

```
velocity += acceleration * deltaTime;

// eg. referenceDamping = 0.6
// and referenceFPS = the framerate where your old value seemed right (eg. 30 or 60)
scaledDamping = Pow(referenceDamping, deltaTime * referenceFPS);
velocity *= scaledDamping;

position += velocity * deltaTime;

```

This way, when deltaTime is close to zero, the multiplier gets close to 1 (diminishing your velocity less over the timestep), and when running close to your reference framerate, you get your reference damping value back out. Running at half your reference framerate gives the square of the damping value (two reference frames' worth of damping compounded), etc.

This will smooth variations in framerate so the game behaves more consistently, but because our math has only finite precision and longer timesteps introduce more integration error, you still won't get exactly reproducible movement at different framerates.

In particular, even with infinite-precision numbers, we've only correctly calculated the change in velocity by the *end* of the time step. Our formula for computing position doesn't take into account the fact that the velocity was changing continuously over the course of that time step. Accounting for all this continuous change is not particularly practical, so we typically accept this integration error as a consequence of our discrete simulation, and a worthwhile trade for simplicity and performance.

To truly get framerate independent game behaviour, you need to fix your timestep. More on the motivation for this here)

---
Tags: movement, frame-rate
---


title: strategies for detecting regressions

text:
# Question
Title: strategies for detecting regressions
I know writing tests would be a good way to catch regressions. But what are some other strategies? TDD and game dev don't suit, but catching regressions is obviously something desirable. I would love to find some cheap and easier ways to catch regressions without having to invest a lot of effort or writing tests after the fact.

Strategies suggested don't have to be perfect, if they can give rough ideas or things to playtest rapidly then that would also be beneficial.

Please advise.

# Answer
First of all, I would challenge the assumption that TDD and game development don't mix. While there are some things in game development which are hard to unit-test (How do you write a proper unit test for a graphic effect where the only formal requirement is "looks cool"?) there are several other areas where it does make sense. Your core game rules, for example.

But even more useful than automated unit tests are automated integration tests. Create a framework for your game which allows you to automatically:

1. Load predefined game scenes
2. Simulate them for a few seconds, simulating player input if necessary (preferably with enhanced speed)
3. Check if the outcome of the scenes is the outcome you expect and report if it is not

When your game uses a random number generator, make sure you seed it with the same value every test run.

Create such a test suite for every feature and create a way to run all your tests automatically. As an example, here is the test suit of the game Factorio in action:

https://www.youtube.com/watch?v=erYjMMBXy7A

Just imagine testing every single feature you see in that 84 seconds video manually. Sure, no automated test suit can replace real flesh-and-blood testplayers, but it can still save you hundreds of play hours and drastically speed up your change-test-fix cycle if you have a fully automatic test suit.
> 4 votes

---
Tags: unity, game-design, software-engineering, testing, playtesting
---


title: Compiled shader not working?

text:
# Question
Title: Compiled shader not working?
I did a simple pixel shader that makes the texture monochrome, and it works perfectly when it is precompiled, but not when compiled (returns E\_FAIL). The effect was compiled using fxc.exe with these arguments: fxc /T ps\_2\_0 /Fo BasicHLSL.fxc BasicHLSL.hlsl

Here's the code

```
ID3DXEffect* monochromeShader = nullptr;

void initEffects(GameWindow& w)
{
    long errorID =
    D3DXCreateEffectFromFile
    (
        w.getD3DDevice(),
        "data/shaders/BasicHLSL.fxc\0",
        NULL,
        NULL,
        D3DXFX_NOT_CLONEABLE,
        NULL,
        &monochromeShader,
        NULL
    );

    std::cout << std::hex << errorID;

    if (monochromeShader == nullptr)
        showErrorMsg(std::to_string(errorID).c_str());
}

```

And here's my shader before compiling with fxc.exe:

```
// Pixel shader input structure
struct PS_INPUT
{
    float4 Position   : POSITION;
    float2 Texture    : TEXCOORD0;
};

// Pixel shader output structure
struct PS_OUTPUT
{
    float4 Color   : COLOR0;
};

// Global variables
sampler2D Tex0;

PS_OUTPUT ps_main( in PS_INPUT In )
{
    // Output pixel
    PS_OUTPUT Out;

    Out.Color = tex2D(Tex0, In.Texture);
    float4 f4 = Out.Color * float4(0.299f, 0.587f, 0.114f, 1.0f);
    float f = f4.r + f4.g + f4.b;
    Out.Color.rgb = f;

    return Out;
}

// Effect technique
technique tech_main
{
    pass P0
    {
        // shaders
        VertexShader = NULL;
        PixelShader  = compile ps_2_a ps_main();
    }
}

```

Thanks for reading.

# Answer
> 0 votes
The problem here is that you compiled the shader with the `ps_2_0` profile which means it's a *pixel shader* binary blob and not an "Effect" binary blob. It does not contain "techniques" or "passes".

You can use that binary blob to create a pixel shader directly without using the optional "Effects" system:

Here's a simple 'binary blob loader':

```
inline std::vector<uint8_t> ReadData(const wchar_t* name)
{
    std::ifstream inFile(name, std::ios::in | std::ios::binary | std::ios::ate);

    if (!inFile)
        throw std::exception("ReadData");

    std::streampos len = inFile.tellg();
    if (!inFile)
        throw std::exception("ReadData");

    std::vector<uint8_t> blob;
    blob.resize(size_t(len));

    inFile.seekg(0, std::ios::beg);
    if (!inFile)
        throw std::exception("ReadData");

    inFile.read(reinterpret_cast<char*>(blob.data()), len);
    if (!inFile)
        throw std::exception("ReadData");

    inFile.close();

    return blob;
}

```

Then you create the shader:

```
std::vector<uint8_t> blob = ReadData(L"data/shaders/BasicHLSL.fxc");

HRESULT errorID = w.getD3DDevice()->CreatePixelShader(blob.data(), &monochromeShader);

```

If you want to use the Effects system, you need to use the `fx_2_0` profile:

```
fxc /T fx_2_0 /Fo BasicHLSL.fxc BasicHLSL.hlsl

```

See this post

> Please note that Direct3D 9 is legacy, `D3DX` is deprecated along with the DirectX SDK itself, the `fx` profiles are deprecated in the modern versions of the HLSL compiler, the use of the "Effects" system generally is discouraged. See MSDN, Where is the DirectX SDK (2015 Edition)?, and Effects for Direct3D 11 Update

# Answer
> 0 votes
**D3DXCreateEffectFromFile Documentation**

The last parameter is to a LPD3DXBUFFER that holds compilation errors, which you can use to determine exactly why this compile (and any future similar compiles you may do) failed.

```
LPD3DXBUFFER errBuff = NULL;

D3DXCreateEffectFromFile (..., &errBuff);

if (errBuff)
{
    // contains the error string
    char *errStr = (char *) errBuff->GetBufferPointer ();

    // contains the size (in bytes)
    int errSize = errBuff->GetBufferSize ();

    // clean up
    errBuff->Release ();
}

```

---
Tags: c++, shaders, directx, hlsl
---


# Question
Title: Which memory is used in D3D12 resources?
According to MSDN there are three types of memory in D3D12, commited resources, placed resources and reserved resources. I do not understand where they are. Are they in RAM? Are they in VRAM? Are they memory mapped somehow so they are both in RAM and VRAM at (approximately?) the same time?

Realised I might have misunderstood memory mapped memory, perhaps it is just an abstraction for sending things over PCIe, not something that goes to RAM and then somewhere else.

# Answer
> 3 votes
They are **not** 3 types of memory. They're 2 different things (physical and virtual memory) and a 3rd that combines the first two for convenience.

**Placed resources** are blocks of **physical memory** that the **GPU** can access but are not mapped to virtual space (Your application can't access them yet). They can be anywhere in memory (GPU or CPU RAM) **but you don't have a pointer to them to access it** (yet) that's the job of a reserved resource.

**Reserved resources** are a **virtual space** windows that the program can access that isn't mapped (yet) to anything. This is the address your program has a pointer to but **there's no actual memory at that spot until you map a placed resource**.

**Committed resources** are **BOTH** a virtual memory space so the program can access it and physical memory large enough for it (may be larger due to driver limitations, we don't really care) that the GPU can access. It's both a placed resource and a reserved resource but you can't separate them, you can't remap the virtual memory to point to a different chunk of physical memory.

The mapping between what your app sees (Reserved resource) and the memory for the GPU (Placed resource) can be changed at any time and multiple sub-mappings can be created at the same time using the D3D12 UpdateTileMappings function.

Different sections of the reserved resource can be mapped to different parts of different placed resources.

For example you can create a 128KB virtual memory "window" and map the first 64KB of that virtual area at the 4th 64KB chunk of a 1MB placed resource and the second 64KB of your memory space mapped to the 1st 64KB of a different 256KB placed resource.

Then your application can access that 128KB area (the reserved resource) as once continuous chunk of memory even tho it's accessing two completely different areas of physical memory (placed resources).

This is to allow a 32bit application (limited to 2GB or 3GB of virtual space) to access large amount of graphic buffers (eg: a graphic card with 3GB when your app already needs 2GB of memory for it's own data and code).

---
Tags: gpu
---


# Question
Title: How can i change door close/open speed in animator, and how to tell player if the door is close wait/idle until the door will open?
In the Animator window of the door i have two states: Door Open and Door Close. And two parameters type of trigger: open and close.

In the two states Door Open and Door Close between them there are two transitions. I didn't make any Has Exit Time but i did add in both transitions the triggers as conditions. On the Door Open to Door Close i added the close condition and on the Door Close to Door Open the open condition.

And the script that attached to the door:

```
using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Animator))]
public class DoorActivatorMecanim : MonoBehaviour
{
    private Animator DoorAnimator;

    void Start()
    {
        DoorAnimator = GetComponent<Animator> ();
    }

    void OnTriggerEnter(Collider col)
    {
        DoorAnimator.SetTrigger("open");
    }

    private void OnTriggerExit(Collider other)
    {
        DoorAnimator.SetTrigger("close");
    }
}

```

The door have a box collider component.

Now when the player is moving to the door when he get inside the box collider area the OnTriggerEnter is on and the door is open and stay opened until the player is moving out of the box collider area then it's getting to the OnTriggerExit and the door is close.

What i want to do is to control the door open/close speed. When the door open it open in medium speed but when the door is close it's shutting down closing at once very fast like the door is falling and not closing animation.

So i want to add another parameter in the Animator maybe type float and call it speed and somehow to control the close/open speed from the script. So i added the speed float parameter but not sure how to use it in the script and control the close/open door speed:

And the second problem is if for example the player is running to the door and door open speed is slower then the player speed i want somehow to tell the player that the door is still close so idle until the door is opened when the door is opened then change from idle to walk/run again. But i'm not sure how to detect when the door is close/open and then how to tell it to the player.

Update the script with the speed parameter setting:

```
using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Animator))]
public class DoorActivatorMecanim : MonoBehaviour
{
    public float doorActivateSpeed = 1f;

    private Animator DoorAnimator;

    void Start()
    {
        DoorAnimator = GetComponent<Animator> ();
    }

    void OnTriggerEnter(Collider col)
    {
        DoorAnimator.SetFloat("speed", doorActivateSpeed);
        DoorAnimator.Play("Door Open");
    }

    private void OnTriggerExit(Collider other)
    {
        DoorAnimator.Play("Door Close");
    }
}

```

For some reason and i can't explain yet why the speed parameter is working only on the door open making it open slow but the door close is still very fast too fast the door is like falling/shutting down. And both open door and close door states and animation settings are the same in the editor.

Can't figure it out.

# Answer
> 1 votes
I'd just add two new states: opening and closing. Both can transition to the open or closed state once they're done. This also avoids duplicate code if you want to add a locked state (which also transits to the opening state.

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


# Question
Title: Trouble referencing a bone transform in Unity. (Using MakeHuman armature / configured in Avatar ok / Anim mocaps working ok))
I've seen that the bones are Transforms. And i've tried copying many examples. The armature is the standard MakeHuman one and is unchanged. It imported to Unity fine and the mocap animations work perfectly. What I need to do is make the hand a parent of my gun .

Here is what I have currently (I have tried many similar permutations):

```
    Transform handR;
public GameObject gunPrefab;
GameObject gun;

private void Start()
{
    rb = GetComponent<Rigidbody>();
    playerAnims = GetComponentInChildren<PlayerAnimations>();
    absoluteGround = rb.transform.position.y;
    distToGround = GetComponent<Collider>().bounds.extents.y;
    handR = transform.Find("hand_r");
    Debug.Log("handR really is: " + handR);

    gun = GameObject.Instantiate(gunPrefab);
    gun.transform.SetParent(handR);
    //gun.transform.position = handR.position;
    gun.transform.rotation = Quaternion.identity;
}

```

The end result of this: The gun will spawn but isnt parented to anything. And if I try to set its position using handR.position then i get null exception. Pic above shows the image where I see its called "hand\_r"

One more thing of note: The bones shown in the image above , do NOT appear in the hierarchy. I have on occasion imported models with the bones included whose bone names all appear in the hierarchy - could this be the reason Unity is finding "hand\_r"??? and if so whats the best way to fix that (Please done say remove the armature and make my own in Blender !! :O )

PS: I have since tried it with a new model, made in Blender with a Rigify rig. The code part "handR = transform.Find("hand\_R"); -yes the rigify rig names it with capital "R". Still doesnt work, **BUT THERE IS A WORKAROUND I FOUND**... if I make the Transform handR public and drag it into the Inspector it all works fine! (And yes the Rigify skeleton also shows up in hierarchy!) (So if you are reading this and struggling too, DONT use the MakeHuman skeleton, use one from Blender Rigify.)

But I'm still very confused why the "Find" command doesnt find the bone

# Answer
Have you tried reading about transform.find on the scripting Api?

"public Transform.Find(string name)

Finds a child by name and returns it.

IF NO CHILD WITH NAME can be found, null is returned. If name contains a '/' character it will access the Transform in the hierarchy like a path name.

Note: Find does not perform a recursive descend down a Transform hierarchy."

Here is an example of its usage:

```
using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour
{
public GameObject player;
public GameObject gun;
public Transform ammo;

//Invoked when a button is clicked.
public void Example()
{
    //Finds and assigns the child of the player named "Gun".
    gun = player.transform.Find("Gun").gameObject;

    //If the child was found.
    if (gun != null)
    {
        //Find the child named "ammo" of the gameobject "magazine" (magazine is a child of "gun").
        ammo = gun.transform.Find("magazine/ammo");
    }
    else Debug.Log("No child with the name 'Gun' attached to the player");
    }
}

```

It's not working in your case because of its wrong usage inside the script.
> 0 votes

---
Tags: unity, animation, skeletal-animation, bones, avatar
---


# Question
Title: Multiplayer client-server architecture sending input
I've got a 2D java game with an infinite generating world with a player and other entities. I wish to make this game multiplayer and have done my research. I read this article multiple times and is what I want to implement.

In short: Client acts as terminal sending input to server. Server is authoritative and controls the game, deciding the result of the input from the client and sending back the relative info. Maintaining performance the server each 100 milliseconds keeps a list of all received input from the client and only then processing it. Client predicts its own game state by its input and when it received the processed state from the server it validates if the state is correct, otherwise corrected by the server.

E.g. Player pressed D -\> client sends 'move right" input to server -\> client predicts its own location to avoid choppy movement -\> server finishes 100ms wait and processes all received input -\> server decides new location of player by received input -\> server sends the decided location to client -\> client validates its current predicted location by the server received one, corrects the client if neccessary.

My question: **How do I properly send all the inputs to the server and in what format? And how to receive different kinds of output back?**

I shouldn't just send the entire player object (which has all inputs such as if WASD keys are held down), should I? Seems way too bandwidth and CPU intensive. Also seems overkill since most properties at each update will be false. Server only needs to be aware of what happened, not what didn't happen. Can I somehow only send single commands to the server? No strings with switch statement please.

How to receive different kind of information from the server? Player needs new world chunks when it moved. Needs to validate its own world position against the server. Needs to check if client inventory is same as server.

# Answer
> 0 votes
You certainly could send the whole Player object to the server. Java makes that quite easy with ObjectOutputStream. But as you recognized yourself, this is usually a quick&dirty method, because it sends a large amount of redundant and irrelevant data.

A good network protocol should only send changes. That means you send one message when a player starts doing something and another message when they stop doing it. How exactly such messages look is up to you.

One option would be to make each message a `byte[]` where the first byte says what kind of message this is (for more complex games which need more than 256 message types you might have to extend this to two bytes) and the following bytes are a message-dependent payload where the size depends on the message type. For example, a "I start walking" message might be structured like this:

* 1 byte saying that is a "I start moving" package
* 1 byte telling you the direction (assuming you have just 8-directional movement. When you allow movement in any direction, 256 possible angles might not be enough)

The reply from the server could then be:

* 1 byte saying that this is a "Something started moving" package
* 2 bytes Object Id
* 8 bytes start coordinates (to make synchronization more reliable)
* 1 byte direction

All messages which occur during the same game tick should be collected and then sent over the socket together at the end of the tick. When you don't do this, then the messages might end up in individual IP packets, and each IP packet has a fixed overhead which might then be more data than your actual payload.

---
Tags: networking, multiplayer, input, game-state
---


title: BufferedImage canvas is null

text:
# Question
Title: BufferedImage canvas is null
I'm sorry if this isn't the right place for this post, but I don't know where to go.

I'm trying to make a simple game loop but it's already failing

```
package main;

import javax.swing.JPanel;
import java.awt.*;
import java.awt.image.*;

public class Logic extends JPanel implements Runnable {

/**
 *
 */
private static final long serialVersionUID = 1L;

// Main Game Stuff
private int gWidth = 800;
private int gHeight = 640;
private int scale = 2;

private int fps = 30;

private boolean running;

private Thread thread;
private BufferedImage image;
private Graphics2D g;

public Logic(){
    super();
    setPreferredSize(new Dimension(gWidth, gHeight));
    setFocusable(true);
    requestFocus();
}

public void addNotify(){
    if(thread==null)
    {
        thread=new Thread(this);
        thread.start();
    }
}

public void init()
{
    image = new BufferedImage(
            gWidth, gHeight, BufferedImage.TYPE_INT_RGB
        );
    g = (Graphics2D) image.getGraphics();
    System.out.println("Hello!");
    running = true;
}

private void update() //main logic
{
    //do stuff
}

private void render(Graphics2D g)
{
    g.setColor(Color.BLUE);
    g.fillRect(0, 0, gWidth, gHeight);
}

private void PaintCanvas(){
    Graphics g2 = getGraphics();
    g2.drawImage(image, 0, 0, null);
    g2.dispose();
}

public void run()
{
    init();

    int loops = 0;
    long startTime = System.nanoTime();
    float rate = 1000/fps;
    long lastTime = startTime;
    float waitTime = rate;

    while(running) // game loop
    {
         long currTime = System.nanoTime();
         if(currTime > (lastTime + waitTime))
         {
             waitTime = rate;
             if((currTime - lastTime) > rate)
                 waitTime = currTime - lastTime;

             //-- Paint Canvas --//
             PaintCanvas();

             //-- LOGIC -- //

                update();

             ////////////////
             //-- RENDER --//
             if(loops % 2 == 0)// draw every second frame
             {
                 render(g);
             }
             ////////////////
             loops++;

             lastTime = currTime;
         }

    }
}

}

```

I keep getting this error:

```
Exception in thread "Thread-2" java.lang.NullPointerException
at main.Logic.PaintCanvas(Logic.java:67)
at main.Logic.run(Logic.java:93)
at java.lang.Thread.run(Unknown Source)

```

Why is the image null? I can't for the life of me figure it out. I already declared it in the init() function.

# Answer
Simply override `paintComponent` and use the `Graphics` object from parameter. Your way of using `Graphics` object is wrong.

```
@Override
public void paintComponent(Graphics g) {
  // draw.
}

```

And use `repaint` to do refresh.
> 2 votes

---
Tags: java, game-loop
---


# Question
Title: Best way of implementing custom UI objects jawa.awt.Graphics
What is the best way to implement custom sliders (for volume), buttons normal, with images (icons) and with text, text boxes and other stuff with java.awt.Graphics?

Thanks,
Kerdo

# Answer
This is easy.
First you have to capture the click and move events:

```
addMouseListener(new MouseListener() {
    @Override void mouseClicked(MouseEvent e) {
        mouse(e)
    }
...

```

And you travel through all the `button`s, `slide`s, etc.. in the `mouse` method, to pass the location of the mouse to them:

```
public void mouse(MouseEvent e) {
    allComponents.forEach(a -> a.hey(e.getX(), e.getY()));
}

```

And then you update the states in the `hey` method. For example, if it's a button, you see if the location of the mouse is inside the button. If so, you set your `button`'s color to a darker one (just for example).

Then draw all the game objects to the screen. Override the `paintComponent` method, and invoke the methods of the parameter `Graphics g`, like `drawString`, `drawRect`, etc..

The approach described above is used in one of my personal project.
> 2 votes

---
Tags: java, graphics
---


# Question
Title: Sphere / Simple Gravity (relative magnitude) - Push-back force C++
To save time in my game with pathfinding, I have a lower quality pathfinder, but the way units move between points is direct using

```
double distance = sqrt(xDistance * xDistance + yDistance * yDistance + zDistance * zDistance);
util_timer_movedelay += updatetime;
if (util_timer_movedelay > speed / 1000)
{

//  cout << "Distance:" << distance << endl;
    if (distance > 0.05)
    {
        unit_x += (0.5 * xDistance * speed * updatetime / distance);
        unit_y += (0.5 * yDistance * speed * updatetime / distance);
        unit_z += (0.5 * zDistance * speed * updatetime / distance);
        util_timer_movedelay = 0;

    }

```

Diagram I would like help with a formula to help 1 push objects away from the sphere, but also attract objects to the sphere, now I already know how to calculate the distance that is easy as the above method is also spherical.

precision is an issue, due to the nature of how I've developed my game and the engine, the units are very compact, I'm having to use .3 float accuracy, so being as accurate as is reasonable is important (don't want to get stuck inside the planet or too far away for my path-finding to work), I don't want to push out 1 whole unit of location if the units on the surface of the globe are only 0.5 units in.

And obviously this would be able to work in the same way for the opposite direction yes ?

Basically simple question, how do I find the relative magnitude off distance for my red dot in the diagram to move exactly to the surface, or as close as possible. Should I just project a dot outwards ? I'm unsure / can't remember how to translate the point outwards relative to the sphere.

# Answer
> 1 votes
This can be as simple as normalizing the vector.

```
offset = interpolatedPoint - sphereCenter

snappedPoint = sphereCenter + offset * sphereRadius/offset.length

```

Dividing by the vector's length gives you a unit vector (length = 1), and multiplying by the sphere radius gives you a vector precisely on the surface of the sphere (up to numeric precision).

You can subtract your original interpolatedPoint to get the correction vector.

# Answer
> 0 votes
For those interested in my solution code based on answer above

```
// offset from centre
CVector3 cen{ 0,0,0 };
CVector3 unitvec{ unit_x,unit_y,unit_z };
float mag = dist2(unitvec, cen);
if (mag < 20.2 && CUnitType != Aircraft) // if distance to globe is less than 21 units- execute (saves process time) as this executed every second
{
    CVector3 offset{ cen,unitvec }; // construct as a vector between 2 vectors
    CVector3 newpoint = cen + offset * (AWorld.planet_radius)/ offset.Length();
    (*UnitModel)->SetPosition(newpoint.x, newpoint.y, newpoint.z); // offset new position
    unit_x = newpoint.x;
    unit_z = newpoint.z;
    unit_y = newpoint.y;
}

```

---
Tags: c++
---