# Question
Title: If I design a game that has both guns and melee weapons, how do I make them equally viable?
I have a plan to make a 2D action platformer game, and I've started prototyping a bit in Godot 2D. My intention was to make the character fight with both guns and melee weapons, with gunplay like the Metal Slug series and melee mechanics akin to what's found in Dead Cells.

The gun would be bound to the right mouse button \[as a secondary attack\] and the melee to the left mouse button \[as a primary attack\], though I do plan on making it so that the player can switch their primary attack type.

The gun used and the melee weapon would be different per character - one would have a high caliber revolver and a greatsword, while another would have a high RoF assault rifle and a knife, for example.

The basics, I get (right now I use a free game art sprite set, and I can use the frame number in the animation to fire a bullet or enable the melee attack hitbox).

It's the balancing issues that got me stumped.

I want to make both ranged and melee combat viable, or as close to equally viable. Though, with the existence of guns, I'm not sure anyone would want to use the characters' melee weapons.

I know it's possible to make guns and melee weapons fulfill different functions, like guns only able to attack one target at a time (except shotguns) with varying fire rates, while most melee weapons are able to attack faster than guns but with a much shorter range, or able to attack multiple targets at once within its hitbox but much slower than guns.

For example, make the melee weapon have a large hitbox and able to apply some non-elemental Damage over Time but with low damage itself \[and, when charged, able to pull an enemy in front of the character\], and the gun a quad-barreled shotgun that delivers massive damage at close range but with long cooldown.

Would that be a viable option to make both melee and guns equally viable, and are there other ways to do it?

# Answer
> 73 votes
There's many different carrot/stick approaches you can use to solve this problem, more than I can list in an answer. You'll have to play around to feel what work best for your game.

1. **Ammo System** \- your gun has limited ammo. You can get more ammo by killing enemies or attacking them in melee. Maybe the gun has a long reload time so it's better to shoot off a salvo and then close in for melee. Maybe you need to move forward to pick up more ammo crates so you need to make efficient use of ammo and melee while pushing forward so you don't get stuck completely ammo-less.
2. **Make the gun unable to work at close range** \- This incentivizes the sword-user to close the distance as fast as possible, while the rifleman needs to figure out ways to maintain the distance. Meanwhile, the knife is still useful to finish off weak enemies that get too close if you've softened them up with the rifle
3. **Make the melee weapon do more damage** \- raise the numbers up to the point where the player *wants* to close into melee range
4. **Make a variety of enemies with different weaknesses** \- That big scary ogre will smash your face in if he gets in melee range, maybe we should shoot him from afar? The goblin archers die in one hit in melee, but are hard to hit from range because they hide behind trees.
5. **Score the player on variety** \- kind of blunt, games like Devil May Cry just tell the player they're awesome for mixing up different combos and tactics.
6. **Have different mobility options** \- The difference in range requires the shorter-range combatant to close the distance. Having a variety of movement speeds and movement/CC abilities helps differentiate ranged vs melee combat. Generally, the ranged player should be less mobile, or otherwise they will be able to kite the melee character around forever.
7. **Have the weaker option provide CC (Crowd Control)** \- the melee guy can use a gun to cripple a target to make it easier to chase down, the ranged guy can use a spear to hold an incoming attacker at spears-length for friends to attack

# Answer
> 20 votes
In addition to the excellent answer already given:

* risk of collateral damage. You don't want to fire a shotgun in a hot air balloon, or around oxygen tanks, or near fragile treasure or the NPC you are trying to rescue
* stealth. The classic "strangle the sentry" is the most obvious example.
* proficiency. Present the player with weapons that take skill or time points to master.
* critical failures. Your fists never explode.

# Answer
> 15 votes
Another option I've not seen mentioned is this:

**Allow the player to reflect or destroy projectiles with melee weapons.**

Albeit unrealistic, sending a deadly bullet barrage back into the enemy's face with your trustworthy {*baseball bat* | *katana* | *lightsaber* | *frying pan* | *...*} feels both "cool" and rewarding, and can provide a good incentive to use melee weapons without making them overpowered in terms of raw damage output.

Nuclear Throne and Ubermosh use that mechanic to their great advantage.

# Answer
> 6 votes
---

## TL;DR

**Note**: You can read "Mechanical Balance" only, if you only care for a traditional answer.

* Carpal Tunnel Syndrome is a thing. Avoid repetitive smashing buttons.
* Improving accesibility will help everybody (Curb-cut effect).
* Do not think of accesibility options as cheating.
* Allow to change keybindings. If possible, multiple keybindings for a single command. If possible, across multiple input devices.
* Allow melee to do something that ranged attacks cannot do.
* A command is not a verb. Think in terms of verbs, not input commands. *Well, actually, both.*
* Construct combos instead of botton smashing.

See also:

Other accesibility settings:

* Target snapping while aiming.
* Auto aiming. For peole who do not have mouse, or do not have good aim.
* Slow game. For people with slow reaction timing.

Note: you can change your scoring system or even disable it (and archivements if you have them) when using these settings.

---

## Introduction

As game developer you should be able to put forth the vision you have for the game. And that vision can include making it difficult.

In favor of allowing more people to enjoy the game, I would like to interest you in the idea of assit mode. Not really related to the melee and ranged problem. So have a video: What Makes Celeste's Assist Mode Special | Game Maker's Toolkit.

Sometimes the distinction between a diffulty setting, an accesibility feature, and a cheat, is a matter of presentation and culture. After all, in the lack of proper accesibility features, people may turn to difficulty settings or cheats. Do not be condescending. A player with a disability does not need to be labelled a cheater, or be mocked. By principle of giving the same experience to everybody.

---

## Carpal Tunnel Syndrome

Carpal tunnel syndrome is - in my opinion - the most relevant condition for this case. In modern office work, it is often associated with the use of the mouse. In particular, fast clicking for long periods and improper posture. It will also happen with the keyboard.

While, arguebly, people should be taking measures to prevent the syndrome (which may include using wrist support and not playing your game), it is preferible to make your game accesible even to people who have it. By the (Curb-cut effect), we will be helping others that do not have the condition. *I will not elaborate on how, brevity eludes me, and this answer is already long as it is.*

We want to:

* Spread the work, so people are not pressing the same key all the time.

To do this, it is useful to balance melee and ranged attack. However, that is not the only thing we will do. We will also allow the player to remap the keybindings.
* Avoid the need for quick repetitive input.

To do this, we need to stop thinking in terms of input commands. This will not only mean less click-click-click, but will also open to you the posibility of structured combos.

Another thing you can do, is have the option to slow down the game (not as a power up, but as a setting).
* Give natural exit points, so people can put down the game.

This, of course, is not directly related to the melee and ranged problem. So, have another video: Exit Points - Putting Down the Game - Extra Credits.

---

## Mechanical balance

*I think Jimmy gave a great answer, so go read that.*

Evidently, melee weapons are not useful at range. This means they got to outshine ranged attacks at short distance. The issue is that ranged weapons would be effective in close combat.

What we want is to make the melee weapon *faster*. I want you to think in terms of speed. Not fire rate, mind you, but dead enemies per second.

How do you do that?

**Better melee:**

* Melee is stronger (more damage = more kills).
* Melee can do combos. No, no click-click-click. *Go read about Verbs below.*
* Allow a single melee attack to hit multiple enemies (possibly stunning enemies, probably with low damage per enemy and potentially with high damage per attack - adding across all enemies, and may kill multiple at once).

**Handicap ranged attacks:**

* They have spread and recoil.
* Ranged attacks are slower (low fire rate =\> less kills)
* Ranged attacks use wind up (like Mega Man, or like a bow, or like Futurama Fallout 4 laser guns)
* They require ammo.

---

But that is thinking insde the box. Numerical differences only go so far. I would like to advocate for diffences in kind, in particular incomparable differences in kind.

Even if melee is perfectly functional, then comes ranged attack that can do all that melee can do, and also works at distance... Melee needs to be able to do something that ranged attacks cannot do.

Of course, combos. However, let us be creative consider some tropes:

---

## Remap keybidings

> The gun would be bound to the right mouse button \[as a secondary attack\] and the melee to the left mouse button \[as a primary attack\]

No. It is NOT good to hardwire acctions to pre-defined keybinding.

You should allow players to rebind these. At least to the keyboard, to game pad if possible. In fact, I will advice to allow to map commands to two different bindings. That way, I can have a way to do them with either hand.

Futhermore, if you can allow to spread bindings across multiple input devices (something that few games do), this will not only help people with carpal tunnel syndrome. It will also help people with other disabilities, for example, if you can only use one hand or if you need to play with your feet.

Given that you have bound attack to the mouse, and given this is an (action) platforming game. I am guessing, that you have bound input to ASDW or to cursor keys. Those should be configurable too.

I also suspect you aim with the mouse. Thus, some options to consider are aim snapping and auto aiming. *Yes, I know that makes ranged attacks better, we will balance it, Ok? Ok.*

---

## Verbs

Let me talk you about verbs.

**What is a verb?**

A "verb" is an abstraction of the physical interaction with the input device. There is an actual physical interaction (pressing a button, for example), and you get a representation of that in your game. We want to disassociate that representation from what the physical interaction actually was (we do not care what button you pressed, just that you did the thing that you configured the game to recognize). That way we abstract the input, and that is how we get to a verb.

We will label the verb according to what it is intended to do (and that is what we tell the user they are configuring). Therefore, we can say that we have a verb to "jump". However, the verb is not the action; in fact, it is not the command.

In some games, you have one to one relationship between verb and command. In addition, when that happens we can treat them as the same thing. However, commands can be composed of multiple verbs.

Furthermore, verbs may not be discrete. For instance, these inputs we can understand these as different verbs:

* Press a button
* Hold it for a given amount of time
* Release the button

Alternatively, they might be the same verb. That is up to the game.

**Addendum**: While a command can be composed of multiple verbs, it is also true that a single verb could translate to multiple commands. For example, holding a button could translate to repeated commands to fire.

---

The advantage of verbs is that you can program how verbs are executed disasociated from how you input them.

First, let us consider the action "run" (as in, moving fast: sprinting, running, jogging※). There are a few common solutions:

* You hold a key to run, and the direction you want to run. (Key combination)
* You double tap the direction you want to run. (Double press)
* You hold the direction, and after a short while, the avatar start running. (Hold over time)

*Some games will have you tapping a botton, or even alternating tapping two bottons to run. Those are not common.*

※: Not claiming these to be the same, but whatever you have in the game.

The linked video above will expand on "jump", but I want to mention that there are two common conventions for jump: using the vertical direction, and using a dedicated key. The correct approach is: no matter. You should be able to map these however you want.

Verbs become more interesting when you can mix them. With these two you already have the running jump, and the double jump, and with enviromental context you have wall jumps. But, let us talk about attacks...

---

**Melee attack verbs**

*Here is something that ranged attacks cannot do...*

Evidently, there will be a key for melee attack. A common command is the rush attacks (a.k.a. consecutive normal punchs), archived by pressing the attack key repreatedly. I need you to think in terms of verbs. This is not attacking fast, this is a different kind of attack, which is often *reached* by quick presses.

However, the animation does not have to be one hit per press. And you do not need to require the player to press faster for better damage, instead you can require the player to keep a particlar rhythm, and the higher the damage the closer you match the rhythm. The attack would end if you fall off the rythm too much (or simply stop pressing for a short while).

Other combinations of verbs:

* Jumping attack. It can take a different form, some common versions are a diagonal doward kick and a spin attack. You can have both: Jump + Attack = spin. Run + Jump + Attack = kick.
* Running attack. Usually a dash.
* Holding attack. Could be blocking attacks, could be charging. *Could be both, for example, each blocked attack adds to the damage of the attack you do when you release*.
* Slam attack. Smash the grown, hits nearby enemies. Usually Jump + Down + Attack. *Some games just use Jump + Attack.*

Also, consider context sensitive moves. I have already mentioned one: finishing an unalerted enemy.

So, one context to consider is the state and distance of the enemies. In that example, an unalerted enemy can be finished in one hit. However, an alerted enemy gets a regular attack. What if the enemy is attacking? The melee attack could knock down their weapon (parry/unarm/steal weapon).

Another context to consider is what you where doing before the attack. For example, a quick change of direction before (in a small time window) the attack can be a different attack. Being something you would in when surrounded by enemies, this can be a ground spin attack... It could even be different if you were running or not. For example, it can be a ground sping when not running, but a backflip when running, it could even push enemies up to air if they are cough infront of the backflip.

**Addendum**: Also consider quick time events.

---

**Melee ammo**

Some attacks may have a resource. Although, it is often the case that ranged attacks require ammo. Some special melee attacks could have their own resorce. That way, when the player has the resource, will want to use melee (or may want to save it for a difficult battle).

You can put special attacks on a hit counter, so that you do not use them all the time. That is, you load up your hit counter before being able to use the special attack (thus, arguably, the hit count is a resource).

It could be the case that you want to load your melee hit count to have the attack ready before entering an area, encouraging the player to use melee in the previous area.

---

**Combos**

There are three common approaches for combos:

* Pressing buttons fast. *Please, don't.*
* Timing. This is ok for the rush attack. It will not work well for other things because it becomes a waiting game.
* Mixing verbs and timing. *This is what we want.*

Combo would have some reward (usually better damage, but it could be more loot, or simply more score). I mention this because you can leave the combos be emergent or scripted, however we want to have an incentive to use them.

**Addendum**: If the combos are emergent, the game needs to be aware of them, or more precisely, of the context of each attack, that is what was the previous attack, how much time ago, to what enemie (was it the same enemy?) and what is the state of the enemy. And then, it can reward you.

Taking a page from the design of Devil May Cry. You can throw enemies into the air, jump to meet them, smash them down, and land on them with another melee. It can be more interesting if you have a way to pull enemies to you.

Taking another page... your raged attack is a verb you can mix. There are two main blueprints for these combos:

* Using a mele attack, throw enemies into the air, then shoot them.
* Mega Man Jump and shoot enemies from the air, and land with melee.

Once you consider these, you will also consider jumping to with them, then pushing them down, and then shooting them from the air, landing with melee, and then repeat.

For ranged attack, it can be useful to be able to (if not have something like bullet time) slow down the fall of a jump. If you lack another input command for something like this, consider the use of holding melee to slow down falling. It will allow you to jump, slow down the fall, aim and shoot. And will also allow a bit more vesatility in platforming.

# Answer
> 3 votes
Among the things the others mentioned, consider making some enemies very difficult to kill with ranged weapons. The 5th boss (The Hand) in Furi is like this, as are many enemies in various MegaMan games that require you to get around shields and other stuff to use your gun.

Simply having some enemies with difficult-to-bypass shields that can be neutralized much more effectively with melee gives a natural ebb and flow for the game on which weapon type to use.

Also, Reloading can be a big weak point for ranged weapons. If your reload takes several seconds (even with unlimited ammo) you can expect the best players will optimize how to utilize the melee and the shooting collaboratively as to not let themselves be weak during the reload.

# Answer
> 2 votes
LEOs cite the time it takes to react, unholster, unsafe, and aim a firearm, vs the time it takes a knife wielder to close the range. If a the knife wielder is closer than ~7 meters, they can close before you can get your gun out. Also, even FPS should recognize the real-world difficulties in going around w finger on trigger of an unsafed weapon. There must be some reason SWAT teams, HRT, SEAL teams etc., don't do that- there's too much danger of an accidental discharge, losing stealth, and possibly shooting your team members. People stumble, get distracted, etc. Rushing a gunman is risky; rushing a swordsman w main a gauche is suicide. (Nod to Heinlein.)

# Answer
> 2 votes
The answers here are very excellent, but something you could also consider:

* Implement disarming; that is, if you can sneak up/jump on/get to a gunner, you can disarm them as a melee ability which then forces them to use melee. This makes melee mains very helpful when you can get to a gunner without them killing you.
* Implement deflection. Sort of similar to \[Overwatch\] Genji's E ability (deflect), you can implement a long-cooldown ability that will deflect bullets back at the sender, which allows you to close the distance to a gunner and force them to use melee (since shooting you would just deal themselves damage).
* Implement strong shields. Sort of similar to \[Minecraft\] regular shields which completely block arrows but not their effects and \[Overwatch\] Reinhardt, Brigitte, Orisa, and Winston's shields which block all bullets and drain shield HP, you can implement shields which can either regenerate or require repairing, which allow you to hold them out and charge a gunner while blocking the bullets. This is similar to deflection but slightly less overpowered because they can break your shield if you are running at them for too long of a distance / if they are moving back to maintain distance.

# Answer
> 0 votes
A good game to study for this would be the free MMO Warframe, which provides a rich choice of ranged and melee weapons for the player. They make it clear that use of each weapon type is situational; using a rifle to hold off enemies from range and using a sword to cleave through several smaller enemies that are harder to hit. Both weapon types don't have to be equally viable in all situations.

# Answer
> 0 votes
The key difference between a melee weapon and a gun is the range; everything else can be tweaked. One way to look for options to change things around is to simply look at how you're balancing a gun vs a longer ranged gun and work from there.

What keeps a sniper rifle from completely overshadowing everything else in your game? The same thing that can be used to make a machine gun beat a sniper rifle, or a shotgun beat a machine gun can be used to make a sword beat a shotgun.

There's a few key things, like balancing out range with lower rate of fire (a sniper rifle vs a machine gun), lower base damage (a machine gun vs a shotgun) or lower ammo capacity before having to reload.

Ammo capacity especially is easy; melee weapons don't run out of ammo so if the fight lasts long enough that your opponent runs out of bullets you're almost certainly going to win. Even if they need to reload, that might you give all the opening you need. (Doubly so if you can't reload in melee because taking damage aborts your reload action).

Higher damage is also easily added; video-game swords already cleave people in half so nobody will bat an eye at melee weapons dealing a ton of damage.

In 3d games there is also the advantage that it's hard to hit something that's very close because it's moving very quickly compared to your viewpoint. This advantage doesn't exist as much in 2d, but you might introduce a mechanic to simulate it. For example if you take melee damage, your weapon's base damage goes down due to distraction. This would make shooting in melee much harder because once you are hurt, you won't be able to fight effectively. Make the effect more profound the longer ranged your weapon is, and make switching to a melee weapon take some time, and a sniper will start sweating a lot when a melee character moves in close. They'll have to choose between trying to drop them before they are hit, or accept that they're probably going to lose.

A point that has already been mentioned is map design; a sniper rifle is useless if the map is a maze with no clear stretches. But you can also add tools that change the map design in the advantage of melee wielders. A smoke grenade that reduces ranged damage by a large amount can be used to close distance (or protect you from a hail of gunfire while you flee). Likewise, a shock grenade that temporarily disables ranged weapons can give you time to re-position.

# Answer
> 0 votes
There are many good answers here already, but I would like to add a couple of insights.

There is an episode of the Mythbusters tv show where they experiment with bringing a knife to a gunfight. They had the gunner keep his gun in a holster before they started, so it was perhaps a poor comparison, but they found that it was a much closer fight than you'd think. Guns have to be aimed, and that can be difficult when things get hectic.

It's also very difficult to shoot someone who is interfering with your aiming. Controlling your arms, etc.

This might not apply to your game, but making it difficult to aim both precisely and quickly is something that can be implemented in a game.

Secondly, stealth. Guns are loud, and a knife can be very deadly against an unaware opponent. Again not the most applicable to your type of game, I suppose.

Lastly, many games have combined ranged and melee combat already. For inspiration, check out Street Fighter, Alien vs Predator, Halo, Tenchu Stealth Assassins and many more I'm sure. ;)

# Answer
> 0 votes
One more alternative is make melee combat a lot flashier and visually/auditory impressive compared to ranged combat. The visual feedback does not have to match the actual damage, but a melee combat system that looks and feels really powerful can cause people to naturally prefer it over the other option, even if it might be numerically slightly weaker.

---
Tags: game-design
---


# Question
Title: Texture being rendered to main frame buffer?
I'm using Ogre 1.10.12 (openglES2 as render system) to create a manual texture like this:

```
    rtt_texture = Ogre::TextureManager::getSingleton().createManual("RttTex",
                                                                Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
                                                                Ogre::TEX_TYPE_2D,
                                                                m_size.width(),
                                                                m_size.height(),
                                                                0,
                                                                Ogre::PF_A1R5G5B5,
                                                                Ogre::TU_RENDERTARGET);

m_renderTexture = static_cast<Ogre::GLES2FBORenderTexture *>(rtt_texture->getBuffer()->getRenderTarget());

m_renderTexture->addViewport(m_camera);
m_renderTexture->getViewport(0)->setClearEveryFrame(true);
m_renderTexture->getViewport(0)->setBackgroundColour(Ogre::ColourValue::Red);
m_renderTexture->getViewport(0)->setOverlaysEnabled(false);

```

then, I bind the texture to the FBO and retrieve the FBO's ID like:

```
Ogre::GLES2FrameBufferObject *ogreFbo = 0;
m_renderTexture->getCustomAttribute("FBO", &ogreFbo);
Ogre::GLES2FBOManager *manager = ogreFbo->getManager();
manager->bind(m_renderTexture);

GLint id;
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &id);

```

My concern is that `id` is **0** so I cannot render this texture outside my display, **it's getting visible which I don't want it to be**.

Shouldn't be ogre creating an unused frame buffer object when creating a manual texture with the `TU_RENDERTARGET` parameter?

# Answer
Finally got the answer to my question: Creating a texture with parameter `TU_RENDERTARGET`, Ogre will always attempt to create a new frame buffer object (fbo) and then bind it, i.e, Ogre will call `glGenFramebuffers` followed by `glBindFramebuffer`. But this can fail if for example you are playing with opengl contexts (sharing, switching between them), this was the cause of my problem since I was sharing Ogre's context with other opengl app, and the visual effect was that everything was being rendered to the main framebuffer (id 0) making all contexts visible all time, mixing them up. So if you encounter with this kind of problems, always check that Ogre's context is well defined, debugging the state of member `mContext` of class `OgreRenderSystem` helps a lot.
> 0 votes

---
Tags: opengl, opengl-es2, ogre
---


# Question
Title: Finding the contact point of two spheres
Is there a way to get the normal and depth of two spheres that have collided.

I know that it is something to do with the center and radius of two spheres but I am not sure what

# Answer
> 5 votes
This is probably the simplest 3D collision check.

Distance between sphere centers is `length(c1.center - c2.center)`

Depth is distance - radius1 - radius2 = `length(c1.center - c2.center) - c1.radius - c2.radius`

Normal is `normalized(c1.center - c2.center)` for c2 and the inverse of that for c1.

---
Tags: collision-resolution, sphere
---


title: Distributed Leaderboard for p2p games

text:
# Question
Title: Distributed Leaderboard for p2p games
I've heard about this term distributed leaderboard for p2p games and I've searched it online but couldn't find much of a thing about it.I was curious what does it really mean and didn't really knew where to ask.Do you guys know what does it mean to have a distributed leaderboard? it's something like a global leaderboard but for p2p players?

# Answer
In the same way that you can do distributed monetary balances in cryptocurrencies via public and private keys, you could build a distributed leaderboard by hashing the result (a transaction of sorts between players) and passing it around. Everyone who connects to someone will have a validated list of players beaten and beat by that player, and any ranking system based on that information can be calculated on the fly.

I suggest reading up about Bitcoin transactions here to get you started.
> 1 votes

---
Tags: leaderboards
---


title: Instantiate object with spawn time?

text:
# Question
Title: Instantiate object with spawn time?
I have script that makes waves of enemies. It selects enemy from array randomly. I want to add function allow me to select any object in my array and instantiating it for number of times. In wave 1, randomly select enemy from enemy list and represent for several of time. In wave 2, I want to select from my enemy list, and how many will instantiate, and time between spawn.

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

public class wer : MonoBehaviour
{
public Wave[] waves;
public GameObject[] enemy;   // enemy list
private int enemies;
Wave currentWave;
int currentWaveNumber;
int enemiesRemainingToSpawn;
int enemiesRemainingAlive;
float nextSpawnTime;
public Transform[] spawnPoints;

void Start()
{
    NextWave();
}

void Update()
{

    if (enemiesRemainingToSpawn <= 0)
    {
        NextWave();
    }

    if (enemiesRemainingToSpawn > 0 && Time.time > nextSpawnTime)
    {

        if (currentWaveNumber == 1) // WAVE 1
        {
            enemiesRemainingToSpawn--;
            nextSpawnTime = Time.time + 1; // spawn time 1 second
            int spawnPointIndex = Random.Range(0, spawnPoints.Length);
            enemies = Random.Range(0, 1);
            Instantiate(enemy[enemies], spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);

        }

        if (currentWaveNumber == 2) // WAVE 2
        {
            for (int i = 0; i < enemy.Length; i++)
            {
                enemiesRemainingToSpawn--;
                int spawnPointIndex = Random.Range(0, spawnPoints.Length);
                Instantiate(enemy[0], spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
                Instantiate(enemy[1], spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);

                // enemy [0] = Instantiate 5 times, time between spawn 1 second;
                // enemy [1] = Instantiate 7 times, time between spawn 1.5f second;

            }

        }

    }

} // end update

void NextWave()
{
    currentWaveNumber++;
    print("Wave: " + currentWaveNumber);
    if (currentWaveNumber - 1 < waves.Length)
    {
        currentWave = waves[currentWaveNumber - 1];
        enemiesRemainingToSpawn = currentWave.enemyCount;
        enemiesRemainingAlive = enemiesRemainingToSpawn;
    }

}

[System.Serializable]
public class Wave
{
    public int enemyCount; // Quantity or number of enemy to Instantiate
    public float timeBetweenSpawns;
}

}

```

# Answer
> 3 votes
I would suggest creating a coroutine which takes three arguments, one for the gameobject which is to be instantiated, another for the number of times it should be instantiated, and the final parameter should be the amount of time between spawns.

Psuedocode

```
public IEnumerator InstantiateRandomCoroutine(Gameobject obj, int repeat, float cooldown)
{
    for i < repeat {
        instantiate obj;
        yeild return WaitForSeconds(cooldown);
    }
}

```

I would suggest getting a random index value within the bounds of the array and using that to reference the GameObject being used as an argument to the coroutine. If you need more information on using coroutines then I would suggest looking reading this.

There may be some fundamental things you will have to change about your implementation but I would very much suggest reading about coroutines if you are looking to instantiate game objects repeatedly with a varying or constant pause in between.

For information about coroutines with multiple arguments please reference this discussion on Unity Answers. Credit to JinxM.

---
Tags: unity, spawning
---


# Question
Title: Java: Updating entities in composite design
I'm trying to move beyond inheritance based design, but I've been doing it like that for 6 years. My current hurdle is this: What's the simplest( or proper) way to update all my objects? Before, everything was a subclass of an Entity class. It was as simple as throwing them into ArrayList and iterating through them all, calling update() on each object. How does this translate in composition? Where the Entity class is within classes that can't be simply passed as each other.

```
for(Entity e : Entites) // I know this is bad practice, but good for an example
    e.update();
// e could be any subclass of entity

```

Since moving to a component - composition based system I can't do that, as each game object is it's own class. I can't make an ArrayList of my objects and call update on each of them. And as far as I know,

My game objects are setup like this

```
class Apple implements iEntity {
    Entity  innerEntity;
    public Apple{
        innerEntity = new Entity(1); // 1 represents Apple as an identifier
    }
    @override // From iEntity
    public void update(){
    }
}

```

Because Apple no longer extends Entity, I can't load it into an ArrayList with Pears(example). All my other objects are similar. Id' rather not make a AppleManager class for Apples, a PearManager for Pears, and build functionality between them. That just seems messy.

Maybe I'm missing a few points, but that's why I'm here. Before this gets closed for some obscure reason, I googled the heck out of this. Each article explained the advantages of a system like this, but failed explaining beyond that. Thanks and advance dudes.

# Answer
why don't you make lists of your interface?

```
List<iEntity> fruitList = ...; //list of interfaces
fruitList.add(new Apple()); //can be added because it implements iEntity
fruitList.add(new Pear()); //can be added because it implements iEntity

for (iEntity entity: fruitList){
    entity.update(); //each objects implements iEntity - no matter if pears or apples
}

```
> 1 votes

---
Tags: java, inheritance
---


# Question
Title: How can I ensure a radius variable doesn't get reduced below 0?
For some reason when I'm using the mouse to change the radius in the Update, the minimum radius is -1 even if I set the range in the top of the script to be 0,50 and even if I check that the xradius is be 0 or higher it's still getting to -1.

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

[RequireComponent(typeof(LineRenderer))]
public class DrawCircle : MonoBehaviour
{
    [Range(0, 50)]
    public int segments = 50;

    public bool circle = true;
    [Range(0, 50)]
    public float xradius = 15;
    [Range(0, 50)]
    public float yradius = 15;
    LineRenderer line;

    public float drawSpeed = 0.3f;

    void Start()
    {
        line = gameObject.GetComponent<LineRenderer>();

        line.positionCount = (segments + 1);
        line.useWorldSpace = false;
    }

    private void Update()
    {
        if (xradius >= 0)
        {
            if (Input.GetAxis("Mouse X") < 0)
            {
                xradius = xradius + 1;
                CreatePoints();
            }
            if (Input.GetAxis("Mouse X") > 0)
            {
                xradius = xradius - 1;
                CreatePoints();
            }
        }
    }

    private void CreatePoints()
    {
        if (circle == true)
            yradius = xradius;

        float x;
        float z;

        float change = 2 * (float)Math.PI / segments;
        float angle = change;

        for (int i = 0; i < (segments + 1); i++)
        {
            x = Mathf.Sin(angle) * xradius;
            z = Mathf.Cos(angle) * yradius;

            line.SetPosition((int)i, new Vector3(x, 0.5f, z));

            angle += change;
        }
    }
}

```

In the Update I did:

```
if (xradius >= 0)

```

But yet when using the mouse for the minimum radius it set both xradius and yradius in the sliders to -1 not sure how can it be -1 if I set the range in both xradius and yradius to be 0,50

You can see in the screenshot in the Inspector in the right both Xradius and Yradius are -1

# Answer
First of all, keep in mind that using a `Range` to limit a variable is something **inspector-only**! That means that if in the `Update` you did something like `xradius = 100` it would work. `Range` is for convenience only and is in no way restricting.

Based on your update, it seems that nothing happens when `xradius` drops below 0. That means by moving your mouse around, it can get a variety of values (including above 50 and below 0), but once it hits -1, it gets stuck, and there is no way for the value to change again.

There are many ways to fix that, one of them is limiting the value of `xradius` the moment you change it, something like:

```
if (xradius < 50) xradius++; // Ensures that xradius is always <= 50

...

if (xradius > 0) xradius--; // Ensures that radius is always >= 0

```

To avoid errors, as suggested by Bilkokuya, it would be better to `xradius = 50` or `xradius = 0` after you change its value, to ensure it is within range. Or alternatively use a min/max function `xradius = Mathf.Max(Mathf.Min(50, xradius), 0)`

Or as a one liner, as pointed out by DMGregory, you can use `Mathf.Clamp(radius + change, minRadius, maxRadius)` like so:

```
// where `change` in your case is either +1 or -1
xradius = Mathf.Clamp(xradius +change, 0, 50);

```
> 2 votes

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


# Question
Title: Can a set of 3D positions be separated by plane?
I have 3 points in 3D space: A, B and C. I also have another set of 3D points: P, Q, R, S, T and U. What would be the simplest algorithm to figure out if there exists a plane that completely separates the first and second set? I know all the coordinates of all points.

# Answer
As mentioned in the comments, you can construct the convex hull of each point set, then test the convex hulls for intersection using your favourite convex collision detection algorithm (eg. SAT, GJK...)

If the two hulls intersect one another, or kiss at a point, then there is no plane that completely separates the two sets.

If there is a separation distance between them, then you have a choice of planes perpendicular to the separating axis, passing through any point in the gap in their projection onto the separating axis.
> 1 votes

# Answer
You could find such a plane using a simple linear support vector machine. I wouldn't describe this as the "simplest" algorithm but there will definitely be a very fast solution using this method.
> 0 votes

# Answer
What you're talking about refers to the linear separability of data (in your case in 3D). This is an explored topic in Machine Learning (which extends to N dimension). It was one of the reasons SVMs became extremely popular back in the day, as it computes the best hyper-plane (most distant related to two classes of categories), providing good performance for many problems. The topic known as VC dimension provides a rigorous analysis of this notion.

As mentioned in the comments the Convex Hull algorithm will compute this in 3D for you, as it will be the smallest polyhedron that will encapsulate a set of points. If these do not intersect you can have a plane between the two set of points.
> 0 votes

---
Tags: mathematics, vector
---


# Question
Title: Does Minecraft Really Rely on CPU More Than GPU For FPS?
I understand that Minecraft runs on Java which is very demanding on the CPU (garbage collection and JVM processes), but I still don't understand how FPS is the CPU's responsibility. Shouldn't the CPU handle game logic while the GPU handles rendering the results of that logic asynchronously? Minecraft was developed using OpenGL libraries afterall. But I still see a ton of people saying that upgrading your CPU is more worth it than upgrading your GPU if you want good FPS on Minecraft. What's actually happening under the hood?

# Answer
The point here is that although CPU and GPU works asynchronously they also work alternately. GPU can't draw what CPU didn't compute yet.

If you have fast CPU and slow GPU then there's no point in computing many frames on CPU in advance, while GPU is still drawing the first one.

If you have slow CPU and fast GPU then the GPU will wait for its job.

Every game is different, some do much work on CPU, some work more in GPU and almost always one of this component will wait for another (but it may change frame-by-frame). In general, if you want 30fps then both your CPU and GPU have to do their job in less than 1/30s.

According to Minecraft specifically:

* It has VERY simple shading and texturing (little work for GPU)
* Uses a lot of geometry (this may become very hard for GPU)
* To optimize GPU drawing it does some magic on geometric data on CPU

Given those points I believe that Minecraft may be CPU-bound.
> 1 votes

---
Tags: java, minecraft-modding
---


title: Unity bowling pins detection

text:
# Question
Title: Unity bowling pins detection
I'am working on bowling ball game and I want to detect how many bowling pins has been knocked down by ball? **What is the solution for this problem?**

# Answer
Depending on precise requirements, the detection can be as simple as checking the `transform.position.y`:

1. (optional) add child `Top` at top of each bowling pin
2. When placed, record the vertical position of (`Top` of) pin
3. each `Update()` check if pin's original and current vertical position difference is greater than a threshold (e.g. 1/2 pin height)

`bool isKnocked = Mathf.Abs(transform.position.y - originalY) > halfHeightThreshold;`
4. (optional) when crossed the threshold, emit `PinKnocked`, a custom `UnityEvent<Pin>` which you have subscribed to in your game logic controller (e.g. `GameManager`)

`if(isKnocked && !wasKnockedLastFrame) OnKnocked?.Invoke(this);`
> 1 votes

# Answer
Here's an example similar to how I detected domino tipping in Last One Standing.

```
public class Tippable : MonoBehaviour {

    // roughly 1/sqrt(2), for a 45 degree angle.
    const float TIP_THRESHOLD = 0.707f;

    // This lets you register another script to
    // listen for "tip" events & tally them.
    public UnityEvent onTip;

    public bool tipped {get; private set}

    // Start with a loop to check if we're tipped over.
    IEnumerator Start() {

        while(!tipped) {
            // Wait till next frame.
            yield return null;

            // Check if our local up is not very upward anymore.
            tipped = transform.up.y < TIP_THRESHOLD;
        }

        // Report that we've tipped.
        onTip.Invoke();
    }
}

```
> 3 votes

---
Tags: unity, unityscript
---


# Question
Title: Pass and Change Objects Between Scenes in Unity
I ran into a bit of a problem with organasing object changes as well as storing them and passing to scenes. By that, I mean that I'm programming a game that has different characters and possibility to customize them as well as their equipment and weapons. It's gonna be a multiplayer game...so, the question is what's the BEST practice of storing and passing customized characters with weapons between scenes and via network connection?

Similarly to Rainbow Six Siege, where all your custom stuff is saved on a user and passed both in single and multiplayer modes into a level.

Just need some refs, tips or maybe articles on the matter. No code needed. Thanks in advance!

# Answer
If you are just looking for a pointer in the right direction, I would suggest reading about SyncVars. I would be tempted to suggest using scriptable objects, but I read that they have problems in multiplayer games where data needs to be synced with the server.

As far as I know, the "best practice" for this would depend completely on how you choose to model client-server interactions. If you plan to have data stores for character information hosted locally on the machine, it may be best to simply create a configuration file, and then pass that data into a class that syncs each attribute with the server using SyncVars. I would **avoid** using PlayerPrefs for this if you care about the data being secure from manipulation, and instead find a way to write the data in some encrypted form using a key that is stored server-side.

If you are hosting all the player data on the server, you may want to look into implementing some kind of database model external from your code and developing a manager class that collects data via queries on player id's as they log in and connect to a session. If you are worried about cheating this would be the route I would go. If you want to go the SQL route, many people use MySQL with Unity projects requiring databases, otherwise MongoDB may be a good option for you.

Regardless of which of the above options you use, you will likely either need to store data about players between sessions either locally in an a DontDestroyOnLoad class or classes between scenes and access this data that way, or sync the data with the server between scenes, load the new scene, and then get the synced data about the player back from the server on scene load and re-instantiate the players object and data.
> 0 votes

---
Tags: unity, c#, assets, asset-management, streaming-assets
---


# Question
Title: How to get image/icon/texture of asset from project window
I want to get image of any asset from code. Unity can display assets as with images of those assets. Is there a way to get that image from code? I need it to be able to display it in the inspector.

```
public class AssetIconDisplayAttribute : MultiSupportPropertyAttribute
{
#if UNITY_EDITOR
    public override void DrawInInspector(Rect position, SerializedProperty property, GUIContent label)
    {
        EditorGUILayout.ObjectField(new GUIContent(property.displayName), property.objectReferenceValue, property.GetContainingObjectFieldType(), true);

        EditorGUI.DrawPreviewTexture(position, @that asset image here@);
    }
#endif
}

```

Is there a better way to achieve this? The ideal result I want is object field that is displayed like a `Texture2D` field in inspector but is **not** a type of `Texture2D` but stays its own type.

An example of `Texture2D`:

**EDITS:**

With AssetPreview.GetMiniThumbnail:

With AssetPreview.GetAssetPreview:

Gives `null` if the object reference is a component, you have to pass `GameObject` in order to get the value.

Fix:

```
AssetPreview.GetAssetPreview((serializedProperty.objectReferenceValue as Component).gameObject)

```

With AssetDatabase.GetCachedIcon:

**@EDIT - note: the code won't work out of the box as some elements which are not important/related for/to this task are custom made.** This is what I currently have and what has been working for me before in the old project. Because of some non-related errors after upgrading to new unity version I can't get an example of how it looked but anyway I wanted to share it.

```
public class AssetIconDisplayAttribute : MultiSupportPropertyAttribute
{
#if UNITY_EDITOR
    public override float GetPropertyExtensionHeight()
    {
        if (this.serializedProperty != null && this.serializedProperty.objectReferenceValue != null)
        {
            return EditorGUIUtility.singleLineHeight + 80f;
        }

        return EditorGUIUtility.singleLineHeight;
    }

    public override void DrawInInspector(Rect rect, SerializedProperty serializedProperty, GUIContent label)
    {
        EditorGUI.PropertyField(new Rect(rect.position, new Vector2(rect.size.x, EditorGUIUtility.singleLineHeight)), serializedProperty);

        if (serializedProperty.objectReferenceValue != null)
        {
            if (AssetPreview.IsLoadingAssetPreview(serializedProperty.objectReferenceValue.GetInstanceID()))
            {
                EditorGUI.DrawPreviewTexture(new Rect(new Vector2(rect.max.x - 82f, rect.position.y + EditorGUIUtility.singleLineHeight * 1.5f), new Vector2(64f, 64f)), AssetPreview.GetMiniThumbnail(serializedProperty.objectReferenceValue), null, ScaleMode.ScaleToFit);
            }
            else
            {
                EditorGUI.DrawPreviewTexture(new Rect(new Vector2(rect.max.x - 82f, rect.position.y + EditorGUIUtility.singleLineHeight * 1.5f), new Vector2(64f, 64f)), AssetPreview.GetAssetPreview((serializedProperty.objectReferenceValue as Component).gameObject), null, ScaleMode.ScaleToFit);
            }
        }
    }
#endif
}

```

# Answer
Try to keep things simple:

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

public class LoadTexture : MonoBehaviour {

    public GameObject texture;
    public Texture2D gameObjectTex;
    public Texture gameObjTex;

    // Use this for initialization
    void Start () {
        var getImage = UnityEditor.AssetPreview.GetMiniThumbnail(texture);
        print(getImage);

        gameObjectTex = getImage;

    }

    // Update is called once per frame
    void Update () {

        CheckIfNull();

    }

    void CheckIfNull(){
    var instance = texture.GetInstanceID();
    if(UnityEditor.AssetPreview.IsLoadingAssetPreview(instance)){

        Debug.Log("still fetching");
    } else {
        var getAssetPreview = UnityEditor.AssetPreview.GetAssetPreview(texture);
        gameObjTex = getAssetPreview;
    }
}

```

}

Now, since the code gets the GameObject directly (from the public dec.) it gets loaded immediately. If you are mapping an array, you can use the already integrated API from unity to check if its still loading to prevent nil status.

GetAssetPreview will give you the thumbnail, however, it will be small. In this case, if you want to create a bigger 'thumbnail' preview, you have to customize the editor via:

```
EditorGUI.DrawPreviewTexture

```

You could create a preview window via:

```
function OnGUI() {
        texture = EditorGUI.ObjectField(Rect(3,3,200,20),
                "Add a Texture:",
                texture,
                Texture);

```

and then add via if statement:

```
if(texture) {
            EditorGUI.PrefixLabel(Rect(25,45,100,15),0,GUIContent("Preview:"));
            EditorGUI.DrawPreviewTexture(Rect(25,60,100,100),texture);
            }

}

```

to draw the picture. Now you'd simply have to write a function that injects the texture automatically into your new Preview window. Before you do that, i suggest you to do everything and 'manually' add the texture when you run unity to check everything works fine.

Greetings!
> 1 votes

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


# Question
Title: Java Event-Based Card Game Using Client-Server with two Threads
I have been working on a two-player card game and have been stuck on updating the respective players' JPanels. Each player has their own panel and after each player makes a move, I want to allow the JPanel of both players to display the updated move. I can't get this to work! I have been able to allow each player to take turns (concurrency via locks). If there is a thread out there where I can find some help on this, please help me out. I can't find any documentation on how to get my code to work. Here is the main thread:

```
private static void openConnection() throws IOException{
    int port = 2222;
    try(ServerSocket serverSocket = new ServerSocket(port);){
        setDeckAndPlayers();
        //Two threads.
        PlayerThreadGame game = new PlayerThreadGame();
        PlayerThreadGame.PlayerThread p1 = game.new PlayerThread(serverSocket.accept(), panel1);
        PlayerThreadGame.PlayerThread p2 = game.new PlayerThread(serverSocket.accept(), panel2);
        PlayerThreadGame.PlayerThread activeThread;

        p1.setOpponentThread(p2);
        p2.setOpponentThread(p1);

        if(p1.panel.active){
            activeThread = p1;
        }
        else{
            activeThread = p2;
        }
        game.setCurrentPlayerThread(activeThread);

        p1.start();
        p2.start();

    } catch(IOException ie){
        System.err.println("Could not listen on port " + port);
    }
}

```

and here is the PlayerThreadGame:

```
public class PlayerThreadGame{
private volatile PlayerThread currentPlayer;
private volatile Table sharedTable;
private volatile Deck sharedDeck;
private volatile int[] score;

public PlayerThreadGame(){
    score = new int[2];
    score[0] = 0;
    score[1] = 0;
}

public synchronized void setCurrentPlayerThread(PlayerThread curr){
    currentPlayer = curr;
}

public PlayerThread getCurrentPlayerThread(){
    return currentPlayer;
}

public synchronized void updateGameTable(Table t){
    sharedTable = t;
}

public synchronized void updateGameDeck(Deck d){
    sharedDeck = d;
}

public synchronized void updateGameScore(int s, int playerNum){
    score[playerNum] = s;
}

public class PlayerThread extends Thread{
    @SuppressWarnings("unused")
    private Socket socket;
    //private BufferedReader input;
    private ObjectInputStream in;
    //PrintWriter output;
    private ObjectOutputStream out;
    public volatile PlayerThread opponent;
    public volatile GamePanel panel;
    private int playerNumber;
    //public volatile Player player;
    //public volatile Player opp;

    public PlayerThread(Socket socket, GamePanel panel){
        super("PlayerThread");
        this.socket = socket;
        this.panel = panel;

        System.out.println("Deck pos in thread server: " + sharedDeck.deck_position);

        this.playerNumber = panel.P.ID;
        try{
            //Initialize the player.
            //input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            in = new ObjectInputStream(socket.getInputStream());
            out = new ObjectOutputStream(socket.getOutputStream());

            out.writeInt(this.playerNumber);
            out.flush();

            out.writeObject(panel);
            out.flush();

        }
        catch(IOException e){
            System.out.println("Bad stream for player. " + e);
        }
    }

    public void setOpponentThread(PlayerThread opp){
        this.opponent = opp;
    }

    public PlayerThread getOpponentThread(){
        return opponent;
    }

    public synchronized void updateTable(Table t){
        panel.table = t;
    }

    public synchronized void updatePlayer(Player p){
        panel.P = p;
    }

    public synchronized void updatePanel(GamePanel p){
        panel.table.number_of_heads = p.table.number_of_heads;
        panel.D = p.D;
        System.out.println("Updating the thread panel:\n\tPanel ID: " + panel.panelID
                + "\n\tPlaying: " + panel.P.playing + "\n\tActive: " + panel.active);
        opponent.panel.table.number_of_heads = panel.table.number_of_heads;
        opponent.panel.D = panel.D;
    }

    public synchronized void updateDeck(Deck d){
        panel.D = d;
    }

    public void run() {
        try{
            //Setup the initial play status.
            if(panel.active){
                out.writeObject("PLAY");
                out.flush();
            }
            else{
                out.writeObject("WAIT");
                out.flush();
            }

            //The player must be updated here also.
            out.writeObject(panel);
            out.flush();

            synchronized(this){
                while(true){
                    String clientIn = (String) in.readObject();

                    GamePanel p = (GamePanel)in.readObject();
                    if(clientIn.equals("MOVED") && currentPlayer == this){
                        updatePanel(p);
                        //Update players' panels, and the game table and deck.

                        updateGameTable(panel.table);
                        updateGameDeck(panel.D);

                        panel.P.handSize--;

                        if(panel.P.handSize == 0 && opponent.panel.P.handSize == 0){
                            panel.P.hand.removeAllElements();
                            opponent.panel.P.hand.removeAllElements();
                            System.out.println("Both hands empty.");
                            sharedDeck.deal(panel.P, opponent.panel.P);

                            sharedTable.handSize = panel.P.handSize;
                            sharedTable.before_deal = 0;
                        }
                        System.out.println("Switch from " + currentPlayer + " to " + opponent);

                        opponent.panel.P.playing = true;
                        opponent.panel.P.dropped = false;
                        opponent.panel.active = true;

                        //Update opponents thread
                        setCurrentPlayerThread(opponent);
                        Thread.sleep(20);   //let the JVM catch up in case the system resources are being drained.
                        out.writeObject("WAIT");
                        out.flush();
                    }
                    else if(clientIn.equals("WAITING") && currentPlayer == this){
                        //in.readObject();
                        out.writeObject("PLAY");
                        out.flush();
                    }
                    else{
                        out.writeObject("WAIT");
                        out.flush();
                    }

                    out.writeObject(panel);
                    out.flush();
                }
            }
        } catch (IOException | ClassNotFoundException | InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("Bad I/O in Thread.");
        }

    }

    public String toString(){
        return playerNumber+"";
    }
}

```

}

and the client:

```
public class Player{
private static final String ip = "localhost";
private static final int PORT = 2222;
private JFrame frame = new JFrame("Game!");
private final static int WIDTH = 1020;
private final static int HEIGHT = 600;
private GamePanel panel;
private static int id;
private Socket socket;
private ObjectInputStream in;
private ObjectOutputStream out;

public Player() throws IOException, ClassNotFoundException {
    try{
        socket = new Socket(ip, PORT);
        out = new ObjectOutputStream(socket.getOutputStream());
        out.flush();
        in = new ObjectInputStream(socket.getInputStream());
        id = in.readInt();
        panel = (GamePanel)in.readObject();

        //currentThread = (PlayerThread) in.readObject();
    } catch (UnknownHostException e){
        System.err.println("Don't know about host " + ip);
        System.exit(1);
    } catch (IOException e){
        System.err.println("Couldn't get I/O for the connection to " + ip);
        System.exit(1);
    }
}

public synchronized void updatePanel(GamePanel p){
    panel = p;
    panel.active = true;
    panel.P.playing = true;
    panel.P.dropped = false;
    frame.add(panel);
    frame.repaint();
}

public void play() throws Exception{
    try{
        synchronized(this){
            while(true){
                String status = (String) in.readObject();
                GamePanel p = (GamePanel) in.readObject();
                if(status.equals("PLAY")){
                    updatePanel(p);
                    System.out.println("Set panel " + id + " to active.");

                    while(!panel.message.equals("NEXT")){
                        //wait for the player to make their move
                    }
                    System.out.println("Player " + panel.P.ID + " moved.");

                    panel.active = false;
                    panel.message = "";

                    out.writeObject("MOVED");  //set the opponent panel to "active"
                    out.flush();
                }
                else if(status.equals("WAIT")){
                    //in.readObject();
                    //panel.active = false;
                    out.writeObject("WAITING");
                    out.flush();
                }
                out.writeObject(panel);
                out.flush();
            }
        }
    }
    catch(Exception e){
        System.out.println("Out of while loop scope.");
        System.exit(1);
    }
    finally{
        System.err.println("Closing the socket");
        socket.close();
    }
}

public static void main(String[] args) throws Exception{
    System.out.println("in main.");
    while(true){
        Player client = new Player();
        client.createBoard();
        client.play();
        if(!client.rematch())
            break;
    }
}

private boolean rematch() {
    int response = JOptionPane.showConfirmDialog(frame, "Would you like a rematch?",
                                                " Again?", JOptionPane.YES_NO_OPTION);
    //this.dispose();
    frame.dispose();
    return response == JOptionPane.YES_OPTION;
}

private void createBoard(){
    frame.setTitle("! Player " + id);
    frame.add(panel);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    BufferedImage imgUrl = null;
    ImageIcon imgIcon = null;

    try {
        imgUrl = ImageIO.read(_Applet.class.getResource("cards/card.png"));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    imgIcon = new ImageIcon(imgUrl);
    Image img = imgIcon.getImage();
    frame.setIconImage(img);
    frame.setSize(WIDTH, HEIGHT);
    frame.setVisible(true);
    frame.setResizable(false);

    System.out.println("Deck pos in client: " + panel.D.deck_position);

    if(panel.active)
        System.out.println("Player " + id + " is first!");

}

public String toString(){
    return id+"";
}

```

You can see I'm writing the panel and then attempting to updated the other players' panel, but I am definitely not doing it right...

# Answer
> 0 votes
I fixed my problem. The major issue I had was that I didn't instatiate the JPanel in the Client. Now I have this fixed. But, I have new issues with repaint and paintComponent. I will create new thread with my issue.

---
Tags: java
---


# Question
Title: Unity3D Problem Temporarily Stop Players Movement When Playing a specific Animation
This is my first time in Unity3D and programming so forgive me if i'm a bit vague on this. I'm working on my own project in Unity3D but I couldn't get the player to stop moving when I press the key. I avoided using the GetButton since it triggered the animation to play twice. After bout 2 hours, I still can't find any answer to my problem.

Can someone help me please?

Here's part of the code of the the player script.

```
    if (Input.GetButtonDown("Fire1"))
    {
        animator.SetTrigger("AttackSword");
        Debug.Log("Animation called");
    }

    if(!animator.GetBool("AttackSword"))
    {
        Move(inputDir, running);
    }

```

If you would like me to add the full code of the script, let me know.

# Answer
I decided to experiment other codes and see if it works and I found out about this code and it works like a charm.

```
    if (!this.animator.GetCurrentAnimatorStateInfo(0).IsName("AttackSword"))
    {
        Move(inputDir, running);
    }

```

Even though the transition isn't smooth, I still find it satisfying to solve this problem on my own.
> 1 votes

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


title: Camera scrolling hiccups

text:
# Question
Title: Camera scrolling hiccups
I'm working on a 2D side-scroller, and I've got the technical aspects working. OpenGL renderer, camera movement using acceleration.

However, while scrolling I'm constantly seeing tiny random hiccups. Split-second pauses, just enough to cause the perception of smooth scrolling to feel choppy instead. Turning on VSync actually accentuates the hiccups. But when I display frame render times, it's always constant (well, constantly flipping between 0.016 and 0.017 second). So far it's just a render loop, no processing going on in the background.

When I look at other 2D side-scrolling games, I never see this stutter, so I don't know if there's something I'm missing that other games know to do...

I recorded a video of it from my phone, on a repeating row of tiles, to show what I mean. It's poor quality, but recorded at slow-motion to emphasize the hiccups. Any tips on how to get rid of this would be great.

# Answer
Are you measuring the rendering rate using external tool like FRAPS, etc? If not, I would first suggest that.

As far as troubleshooting goes, try lowering the framerate to anything lower than the VSync, like 30 or whatever, and see if the problem persists. If it does not, then your rendering rate/game loop mechanisms are a likely culprit.

If it does persist even at lower framerate, it may possibly due to rounding errors in the logic.

Another question, likely unrelated, but what language or base framework are you using?
> 1 votes

# Answer
I had the same thing only in 3D - upgrading the NVIDIA driver fixed it without making any other changes to my code.
> 0 votes

---
Tags: opengl, 2d, camera, side-scroller
---


title: Sorting sprites based on Z index

text:
# Question
Title: Sorting sprites based on Z index
I am working on a 2D game engine in C# using OpenGL. I am trying to find a collection to satisfy my needs for sprite ordering, and I can't seem to find the combination of performance and functionality.

The following is the criteria I am after:

* The ability to be iterated over in order according to "Z" value, which may change for any sprite at any time
* Possible for many sprites to be added/removed within a single frame, so sorting each time a value was added/removed will have large performance impact without the correct implementation
* Insertion/removal speed is much lower priority than access speed during enumeration
* Have no need for indexing
* Only unique values, but with the correct collection, I can manage that manually if the base collection does not implement it, as I do in the example

Currently, this is the best I could come up with. (I removed all the interface implementations for clarity, leaving only the important stuff)

```
    public class SpriteBatch : ICollection<IRenderable>
{
    private readonly Dictionary<uint, IRenderable> _dict;
    private readonly List<uint> _keys;
    private bool _needSort;

    public SpriteBatch()
    {
        _dict = new Dictionary<uint, IRenderable>();
        _keys = new List<uint>();
        _needSort = false;
    }

    public void Add(IRenderable renderable)
    {
        if (renderable == null)
            throw new ArgumentNullException(nameof(renderable), "Item cannot be undefined.");
        if (_dict.ContainsKey(renderable.Id))
            return;
        _needSort = true;
        renderable.Disposed += (sender, args) => Remove(renderable);
        renderable.ZChanged += (sender, args) => _needSort = true;
        _keys.Add(renderable.Id);
        _dict.Add(renderable.Id, renderable);
    }

    public bool Remove(IRenderable renderable)
    {
        if (renderable == null)
            return false;
        _dict.Remove(renderable.Id);
        return _keys.Remove(renderable.Id);
    }

    public IEnumerator<IRenderable> GetEnumerator()
    {
        if (_needSort)
            _keys.Sort((a, b) => _dict[a].Z.CompareTo(_dict[b].Z));
        foreach (var key in _keys)
            yield return _dict[key];
    }
}

```

Was curious if anyone else had a better approach, or what the "standard" tried-and-true way of doing this is?

# Answer
Deferred sort (lazy so it only sorts at the last moment before the sorted values are needed) as you've done is the typical approach I've used in the past, so I'd say your current solution is pretty good.

Depending on your insert/remove demographics (i.e. the ratio of inserts / deletions to items that stay the same each frame), you may get slightly higher performance if you maintain a separate collection of new keys instead of tacking them onto the end of the sorted list. Then you can sort those keys on insert, and then use multi-way/k-way merging to combine them with the existing sorted collection. That way your sort should be able to avoid having to check all the existing items are still in the right place, instead it just has to find the right spot for each of the new items. But that will start to break down, as the ratio of insertions to existing sorted items rises, plus it means that to handle removes you have to traverse both main and new collections.
> 1 votes

---
Tags: c#, opengl, 2d, sprites, sorting
---


title: Passing data to objects and sub-systems

text:
# Question
Title: Passing data to objects and sub-systems
I am currently creating a game in C++ using SDL. Many game objects and sub-systems require the use of variables such as an `SDL_Renderer` for drawing to the screen and `delta time` for updating positions and there may be more added in the future (such as a `TextureManager` object). In this case the code for a game object might look something like this:

```
void Update(float deltaTime)
{
    // ...
}

void Render(SDL_Renderer* renderer)
{
    // ...
}

```

However, if another variable was added as a parameter, any subclasses would have to be updated and other systems made consistent with the new parameter.

Another way of passing data around would be to have one "storage class/structure" to store these variables and pass that instead. For example:

```
struct Data
{
    SDL_Renderer* renderer;
    float deltaTime;
    TextureManager textureManager;
};

```

My question is: what a good way of passing around data in a game engine? The first example would be bothersome to update if any changes were made to the parameters and would make adding more classes difficult. What about the second example? Would it be good design to have objects depend on a single class? Are there any other design patterns for passing around data without causing dependency issues?

# Answer
Having built out my first game engine for the first time (in 20 years), and completely ignored alot of good literature (I should of read more but oh well :)). I can offer a few quick insights into my issues and what dawned on me. That question is why do I need to pass objects locally around, there are good reasons in many cases, but what I found was to limit that and at the least make it a pattern of use.

I won't go into actual architecture, because there are a number of ways to do this. I've used your model of update and render. So it triggered some recollections.

Firstly I thought more about how to loosely couple systems together so I can swap out and enhance components as I went. One such method that worked for me was I found that by using an event manager (in my experience) where objects subscribed and unsubscribed from events removed about 80% of my coupling across the system. All components had the right to post events to the system and really became the piping for alot in my game engine. This event system was VERY basic, passing around an event type, subtype and a payload (it could be anything else, this is just my example). I still have coupling afterwards but now only for creating certain entities in game. The model itself allows you to have completely different classes and systems convey simple loosely coupled messaging between systems. Having said that, my Eventmanager was a Singleton, which probably contradicts point 2 to a degree.

Secondly, Globals most of the time won't help, in fact, it just makes it worse in many cases (YES, they do help in some spots, so its actually cleaner way although they are a bit of a crutch) . So I used container classes for the more major manager objects and don't be afraid to group managers into specific containers, my grouping was coarse, graphics and game logic managers for example.

In respects to globals, I found that it meant I had flattened the dependency tree of the various system components. Removing the globals meant I was forced to address the hierarchy of my critical objects and order them more logically. The globals were a reflection of my lack of planning in the architecture of my engine. It has a number of roll improvements once I had fixed this, controlling the order of destruction and creation of objects was natural. Rather than having to understand explicitly dependence of objects, it was implied and also enforced a standard.

Thirdly (and a little off topic), you will continue to learn and that will mean you will see patterns where you didn't before. So don't be hard on yourself, there is code you will look at and say "What the hell was I thinking.". Always revise, and improve. You can read a book, but if you shoe horn yourself into a discipline/design and don't end up liking it, it will kill your enjoyment. So diving in on your project can be a good and bad experience, but just keep learning.

Finally, all is a disclaimer, because of my experience with developing my own game. I've learned alot and would redo some things from the start, but I have had some surprising results around design and execution just through learning. good luck. Everyone's experience is different, I'm sure you will get some good tips from others on here.
> 1 votes

# Answer
There is no ideal solution, it's just a matter of understanding Pros/Cons of each choices and endorse them.

```
void Update(float deltaTime)
{
    // ...
}

```

As you said, this will be a pain to refactor but it's not an impossible task. Moreover you can expect to have an API that become more and more stable over the time.

I would discourage to 'hide' this into a Struct, because 'Data' makes no sense. What if you have different function with different 'Data' struct. It will be a pain to understand the project when it grows. This is the inverse of the first solution: Quick now but hard latter. However you can use struct when it make sense (just a dummy example):

```
struct FrameTime
{
    Millisecond  deltaTime;
    int          frameNumber;
};

```

Statics (or globals) make thing easier to use (but not easier int case of refactoring). For instance a paradigm I like, because it's not really a Singleton but provide me a Global 'Main' access:

```
// Time.h
class Time
{
  public: // Public class API
    Millisecond getDeltaTime();

  public: // Static Main access (Better if in another class)
    static Milliseconds GetDeltaTime();
};

// Time.cpp
Millisecond Time::getDeltaTime()
{
  return ...;
}

static Time s_time;
Millisecond Time::GetDeltaTime()
{
return s_time.getDeltaTime();
}

// ...

void Update()
{
    Millisecond deltaTime = Time::GetDeltaTime();
    // ...
}

```

Then question is not, is it possible that you need something else than the 'Global delta time', because there is always a possibility. But the question is, what happens if suddenly you need to provide an independent delta time. How much energy you will need to refactor it versus which is the risk. This rarely happens, but it happens.
> 0 votes

---
Tags: architecture, software-engineering, design-patterns
---


# Question
Title: Start timer when button pressed (what is wrong with my code?)
I want a timer to start when my rocket takes off and stop when it lands. Stopping works fine (using a collider and state-switching) but I can't get the timer to start when I press the boost button.

Currently the timer text is displayed at the moment I pressed the button but clearly has been counting from the moment the scene started, not the moment the button is pressed.

Any help will be greatly appreciated. If there is a better way to start the timer rather than when I press the boost button then I am open to ideas!

Here is the all relevant code (I think). It appears as though it should be working to me, but it isn't.

---

```
// Timer
public Text timerText;
private float startTime;
private bool started = false;
private bool finished = false;

  void Start ()
{
    startTime = Time.time;  // get time since scene started
}

void Update ()
{
    if (currentState == State.Alive)
    {
        ProcessBoostInput();
        ProcessRotationInput();
        ProcessFiringInput();
        if (started)
        {
            RunTimer();
        }
    }

}

    private void ProcessBoostInput()
{
    if (Input.GetKey(KeyCode.A) || (CrossPlatformInputManager.GetButton("Fire1")))
    {
        BoostShip();
        PlayBoostSound();

        if (started != true)
        {
            started = true;
        }

    }

    private void RunTimer()
{
    if (finished)
    {

        return;
    }
    else if (started)
    {
        float timeSinceTimerStart = Time.time - startTime;

        string minutes = ((int)timeSinceTimerStart / 60).ToString();
        string seconds = (timeSinceTimerStart % 60).ToString("f3");

        timerText.text = minutes + ":" + seconds;
    }
}
private void StopTimer()
{
    finished = true;
    timerText.color = Color.green;
}

```

# Answer
This line here:

```
float timeSinceTimerStart = Time.time - startTime;

```

Measures the time between two timestamps:

* `Time.time` (ie. now/this frame)
* `startTime`

You're currently setting the `startTime` timeStamp in the `Start()` method, which runs just before the object's first updates (ie. generally when the scene is loaded or the object is spawned), so it's recording the time of spawn, not the time you pressed the button.

Instead, you want to set `startTime` when you press the button to launch the rocket (ie. right where you set `started = true`). That ensures the earlier timestamp you're measuring from corresponds to the button input, rather than whenever the object happened to get spawned.
> 0 votes

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


# Question
Title: OpenGL ES texture rendered not as expected with disproportional aspect ratio triangles
I cannot seem to understand how texture coordinates work. I try to render a texture into two triangles and this is what I get

Where the expected output is a normal continuous image as you can imagine.

Triangles coordinates (where `w = 1080`, `h = 1920`):

```
0, 0, w, 0, 0, h,
w, 0, 0, h, w, h

```

Texture coordinates

```
0, 1, 1, 1, 0, 0,
1, 1, 1, 0, 0, 0

```

Texture parameters

```
gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_REPLACE);

gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);

gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE);

```

# Answer
> 1 votes
Take a piece of paper and draw your 2 triangles vertices coords and uv coords. They seem to be misplaced (e.g. `0,h` corresponds one time to `0,0` and other time to `1,0`)

---

For such cases I could also recommend to use textures with clearly defined characteristics, e.g. a checkerboard with marked uv coords:

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


# Question
Title: Does destroying object at List element make it null?
I'm using a list in Unity and I'm adding objects to it as they are collected through the game. But they will then be used and destroyed. My first question is do I use Destroy(), or should I just use List.Remove()? I'm not sure what happens to an object once it is removed from a list and not used anymore. Does garbage collection get it? My other question is, when I check the list (I will always be checking the first index), if that object was just destroyed or removed, will that element now be null? I've tried reading about this but it's hard to find an exact answer. Thanks for the help.

For reference, here is the code that I came up with based on my current assumptions about lists:

```
public List<BasePickUp> pickUpQueue = new List<BasePickUp>();
public bool pickUpActive = false;

void Update ()
{
    if (pickUpQueue[0] != null && !pickUpActive)
    {
        pickUpActive = true;
        pickUpQueue[0].ActivatePickUp();
    }
}

```

Edit: I have been playing with the if statement conditions, and even if I change pickUpActive to true, it somehow still manages to get inside the if statement to the breakpoint there. How is that possible? The condition says pickUpActive must be false, and yet it blows right by it. When I set the first condition to pickUpQueue != null, I get an error for index out of range once, when it is set to check the first element, as it is in the above code, I get an index out of range every frame. I finally changed it to pickUpQueue.Count != 0, and that finally kept it from getting into the if statement. If anyone can help me understand what is going on with my bool, and to understand exactly how to handle this list, I would greatly appreciate it! Thanks!

# Answer
> I'm using a list in Unity and I'm adding objects to it as they are collected through the game. But they will then be used and destroyed. My first question is do I use Destroy(), or should I just use List.Remove()? I'm not sure what happens to an object once it is removed from a list and not used anymore. Does garbage collection get it?

You should use `Destroy` to destroy objects. Removing from an object from a list does not destroy the object. For example, let's say you create 10 `Ball` Objects into the scene and add them to a list. If you remove these objects from the list, they will still be visible in the scene. Object destruction and garbage collection will only occur on objects that you've destroyed.

---

> My other question is, when I check the list (I will always be checking the first index), if that object was just destroyed or removed, will that element now be null?

If an object was just destroyed, assuming it inherits from `UnityEngine.Object` (e.g. like a `MonoBehaviour`), that element in the list will now be null. Removing the object from the list is a separate step.

The reason the element becomes null once you destroy it is because Unity overloads the == operator to return null on destroyed `UnityEngine.Object` objects. You can find more details about this custom null check at this Unity blog post: "Custom == operator, should we keep it? ". There are reasons behind this, but as mentioned there it is counterintuitive.

---

EDIT: For the comment in your edit, I suggest you use the debugger to try to figure out what's going on with your code.
> 2 votes

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


title: Unexpected lighting on cube

text:
# Question
Title: Unexpected lighting on cube
I am following a tutorial for 3D game development in Java, using LWJGL. I have completed all chapters up to chapter 14 - Terrain, inclusive. The tutorial is in Java, but I'm using Scala. My full code is here.

After completing chapter 14, I'm trying to render a few cubes, but the lighting comes out unexpected.

Having diffuse, texture and specular lighting, I expect the cube to be lit on the areas pointing to the light and be (relatively) dark on the sides that are facing away from the light.

Instead, the cube gets lit in a very weird way, with some lit areas and some dark areas, in a way that doesn't look like the lighting is working.

The cube is rendered at (0,0,0). Light position is different for each picture.

**EDIT:** I found that I was using the wrong cube mode. I fixed that and uploaded new pictures.

This is what the cube looks like from the bottom, camera at ~(0,-30,15), light at (100, 200, -100):

This is how it looks from the front, camera at ~(0,5,10). Here with the light at (0,20,0):

And here with the dragon, which has perfect lighting. Camera at ~(0,5,-30), light at (100, 200, -100):

Here are my shaders and object file:

vertex-shader:

```
#version 400 core

in vec3 position;
in vec2 textureCoords;
in vec3 normal;

out vec2 pass_textureCoords;
out vec3 surfaceNormal;
out vec3 toLightVector;
out vec3 toCameraVector;

uniform mat4 transformationMatrix;
uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;
uniform vec3 lightPosition;

void main(void) {
    vec4 worldPosition = transformationMatrix * vec4(position, 1.0);
    gl_Position = projectionMatrix * viewMatrix * worldPosition;
    pass_textureCoords = textureCoords;

    surfaceNormal = (transformationMatrix * vec4(normal, 0.0)).xyz;
    toLightVector = lightPosition - worldPosition.xyz;
    toCameraVector = (inverse(viewMatrix) * vec4(0.0, 0.0, 0.0, 1.0)).xyz - worldPosition.xyz;
}

```

fragment-shader:

```
#version 400 core

in vec2 pass_textureCoords;
in vec3 surfaceNormal;
in vec3 toLightVector;
in vec3 toCameraVector;

out vec4 out_Colour;

uniform sampler2D textureSampler;
uniform vec3 lightColour;
uniform float shineDamper;
uniform float reflectivity;

void main(void) {
    vec3 unitNormal = normalize(surfaceNormal);
    vec3 unitLightVector = normalize(toLightVector);

    float nDot1 = dot(unitNormal, unitLightVector);
    float brightness = max(nDot1, 0.2);
    vec3 diffuse = brightness * lightColour;

    vec3 unitVectorToCamera = normalize(toCameraVector);
    vec3 lightDirection = -unitLightVector;
    vec3 reflectedLightDirection = reflect(lightDirection, unitNormal);

    float specularFactor = dot(reflectedLightDirection, unitVectorToCamera);
    specularFactor = max(specularFactor, 0.0);
    float dampedFactor = pow(specularFactor, shineDamper);
    vec3  finalSpecular = dampedFactor * reflectivity * lightColour;

    out_Colour = vec4(diffuse, 1.0) * texture(textureSampler, pass_textureCoords) + vec4(finalSpecular,1.0);
    //out_Colour = vec4(diffuse, 1.0) * texture(textureSampler, pass_textureCoords) ;
}

```

cube2.obj:

```
# Blender v2.79 (sub 0) OBJ File: 'cube.blend'
# www.blender.org
o Cube
v 1.000000 -1.000000 -1.000000
v 1.000000 -1.000000 1.000000
v -1.000000 -1.000000 1.000000
v -1.000000 -1.000000 -1.000000
v 1.000000 1.000000 -0.999999
v 0.999999 1.000000 1.000001
v -1.000000 1.000000 1.000000
v -1.000000 1.000000 -1.000000
v -0.000000 1.000000 0.000000
v 1.000000 0.897903 -0.901142
v 1.000000 -0.000853 -0.000852
v -0.000000 0.000000 1.000000
v -1.000000 0.000000 -0.000000
v 0.000000 -1.000000 -0.000000
v 0.000000 -0.000000 -1.000000
vt 0.838954 0.838954
vt 0.161046 0.838954
vt 0.161046 0.161046
vt 0.838954 0.838954
vt 0.161046 0.838954
vt 0.161046 0.161046
vt 0.161046 0.161046
vt 0.838954 0.161046
vt 0.838954 0.838954
vt 0.161046 0.838954
vt 0.161046 0.161046
vt 0.838954 0.838954
vt 0.161046 0.838954
vt 0.161046 0.161046
vt 0.161046 0.838954
vt 0.161046 0.161046
vt 0.838954 0.838954
vt 0.161046 0.838954
vt 0.161046 0.161046
vt 0.838954 0.838954
vt 0.838954 0.838954
vt 0.161046 0.161046
vt 0.161046 0.838954
vt 0.161046 0.161046
vt 0.838954 0.161046
vt 0.838954 0.838954
vt 0.161046 0.838954
vt 0.161046 0.161046
vt 0.161046 0.838954
vt 0.838954 0.838954
vt 0.161046 0.838954
vt 0.161046 0.161046
vt 0.838954 0.838954
vt 0.161046 0.838954
vt 0.838954 0.838954
vt 0.161046 0.161046
vt 0.838954 0.838954
vt 0.838954 0.838954
vt 0.161046 0.838954
vt 0.838954 0.838954
vt 0.161046 0.838954
vn 0.0000 -1.0000 0.0000
vn 0.0000 1.0000 0.0000
vn 1.0000 -0.0000 0.0000
vn 0.0000 -0.0000 1.0000
vn -1.0000 -0.0000 -0.0000
vn 0.0000 0.0000 -1.0000
s off
f 1/1/1 14/2/1 4/3/1
f 5/4/2 8/5/2 9/6/2
f 1/1/3 10/7/3 11/8/3
f 2/9/4 6/10/4 12/11/4
f 3/12/5 7/13/5 13/14/5
f 5/4/6 15/15/6 8/16/6
f 6/17/2 9/18/2 7/19/2
f 7/20/2 9/18/2 8/16/2
f 9/21/2 6/10/2 5/22/2
f 2/9/3 11/23/3 6/24/3
f 6/17/3 10/7/3 5/25/3
f 11/26/3 2/27/3 1/28/3
f 3/12/4 12/29/4 7/19/4
f 7/20/4 12/29/4 6/24/4
f 12/30/4 3/31/4 2/32/4
f 8/33/5 4/34/5 13/14/5
f 13/35/5 4/34/5 3/36/5
f 13/35/5 7/13/5 8/16/5
f 4/37/1 14/2/1 3/36/1
f 14/38/1 1/39/1 2/32/1
f 3/12/1 14/2/1 2/32/1
f 8/33/6 15/15/6 4/3/6
f 4/37/6 15/15/6 1/28/6
f 15/40/6 5/41/6 1/28/6
f 1/1/3 5/41/3 10/7/3
f 6/17/3 11/23/3 10/7/3

```

# Answer
> 2 votes
I don't see anything wrong with the vertex or fragment shader. But since the dragon is beeing lit properly and the cube isn't I was wondering could it be that you don't duplicate your vertices properly between the OBJ and and the data sent to your GPU.

For openGL one vertex can have only one normal, and one UV coordinate, but the OBJ can have as many normals linked to a vertex has possible. In this case I can see that the first vertex is both linked to VN 1 and VN 3. If you didn't make sure to create a new vertex so each one has one normal it will cause this kind of weird issue.

The reason the dragon renders just fine would be that one vertex has one normal which give it this smooth aspect. I cannot be sure since I don't have the wavefront loading code. But to be sure check the data you send to the GPU and make sure it is coherent.

---
Tags: opengl, shaders, lighting, lwjgl, lwjgl3
---


title: Acceleration in Unity

text:
# Question
Title: Acceleration in Unity
I am trying to emulate acceleration and deceleration in Unity.

I have written to code to generate a track in Unity and place an object at a specific location on the track based on time. The result looks a little like this.

The issue I currently have is that each section of the spline is a different length and the cube moves across each section at a different, but uniform, speed. This causes there to be sudden jumps in the change of the speed of the cube when transitioning between sections.

In order to try and fix this issue, I attempted to use Robert Penner's easing equations on the `GetTime(Vector3 p0, Vector3 p1, float alpha)` method. However, whilst this did help somewhat, it was not sufficient. There were still jumps in speed in between transitions.

Does anyone have any ideas on how I could dynamically ease the position of the cube to make it look like it was accelerating and decelerating, without large jumps in speed between segments of the track?

---

I have written a script that shows a simple implementation of my code. It can be attached to any game object. To make it easy to see what is happening when the code runs, attach to something like a cube or sphere.

```
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif

public class InterpolationExample : MonoBehaviour {
    [Header("Time")]
    [SerializeField]
    private float currentTime;
    private float lastTime = 0;
    [SerializeField]
    private float timeModifier = 1;
    [SerializeField]
    private bool running = true;
    private bool runningBuffer = true;

    [Header("Track Settings")]
    [SerializeField]
    [Range(0, 1)]
    private float catmullRomAlpha = 0.5f;
    [SerializeField]
    private List<SimpleWayPoint> wayPoints = new List<SimpleWayPoint>
    {
        new SimpleWayPoint() {pos = new Vector3(-4.07f, 0, 6.5f), time = 0},
        new SimpleWayPoint() {pos = new Vector3(-2.13f, 3.18f, 6.39f), time = 1},
        new SimpleWayPoint() {pos = new Vector3(-1.14f, 0, 4.55f), time = 6},
        new SimpleWayPoint() {pos = new Vector3(0.07f, -1.45f, 6.5f), time = 7},
        new SimpleWayPoint() {pos = new Vector3(1.55f, 0, 3.86f), time = 7.2f},
        new SimpleWayPoint() {pos = new Vector3(4.94f, 2.03f, 6.5f), time = 10}
    };

    [Header("Debug")]
    [Header("WayPoints")]
    [SerializeField]
    private bool debugWayPoints = true;
    [SerializeField]
    private WayPointDebugType debugWayPointType = WayPointDebugType.SOLID;
    [SerializeField]
    private float debugWayPointSize = 0.2f;
    [SerializeField]
    private Color debugWayPointColour = Color.green;
    [Header("Track")]
    [SerializeField]
    private bool debugTrack = true;
    [SerializeField]
    [Range(0, 1)]
    private float debugTrackResolution = 0.04f;
    [SerializeField]
    private Color debugTrackColour = Color.red;

    [System.Serializable]
    private class SimpleWayPoint
    {
        public Vector3 pos;
        public float time;
    }

    [System.Serializable]
    private enum WayPointDebugType
    {
        SOLID,
        WIRE
    }

    private void Start()
    {
        wayPoints.Sort((x, y) => x.time.CompareTo(y.time));
        wayPoints.Insert(0, wayPoints[0]);
        wayPoints.Add(wayPoints[wayPoints.Count - 1]);
    }

    private void LateUpdate()
    {
        //This means that if currentTime is paused, then resumed, there is not a big jump in time
        if(runningBuffer != running)
        {
            runningBuffer = running;
            lastTime = Time.time;
        }

        if(running)
        {
            currentTime += (Time.time - lastTime) * timeModifier;
            lastTime = Time.time;
            if(currentTime > wayPoints[wayPoints.Count - 1].time)
            {
                currentTime = 0;
            }
        }
        transform.position = GetPosition(currentTime);
    }

    #region Catmull-Rom Math
    public Vector3 GetPosition(float time)
    {
        //Check if before first waypoint
        if(time <= wayPoints[0].time)
        {
            return wayPoints[0].pos;
        }
        //Check if after last waypoint
        else if(time >= wayPoints[wayPoints.Count - 1].time)
        {
            return wayPoints[wayPoints.Count - 1].pos;
        }

        //Check time boundaries - Find the nearest WayPoint your object has passed
        float minTime = -1;
        float maxTime = -1;
        int minIndex = -1;
        for(int i = 1; i < wayPoints.Count; i++)
        {
            if(time > wayPoints[i - 1].time && time <= wayPoints[i].time)
            {
                maxTime = wayPoints[i].time;
                int index = i - 1;
                minTime = wayPoints[index].time;
                minIndex = index;
            }
        }

        float timeDiff = maxTime - minTime;
        float percentageThroughSegment = 1 - ((maxTime - time) / timeDiff);

        //Define the 4 points required to make a Catmull-Rom spline
        Vector3 p0 = wayPoints[ClampListPos(minIndex - 1)].pos;
        Vector3 p1 = wayPoints[minIndex].pos;
        Vector3 p2 = wayPoints[ClampListPos(minIndex + 1)].pos;
        Vector3 p3 = wayPoints[ClampListPos(minIndex + 2)].pos;

        return GetCatmullRomPosition(percentageThroughSegment, p0, p1, p2, p3, catmullRomAlpha);
    }

    //Prevent Index Out of Array Bounds
    private int ClampListPos(int pos)
    {
        if(pos < 0)
        {
            pos = wayPoints.Count - 1;
        }

        if(pos > wayPoints.Count)
        {
            pos = 1;
        }
        else if(pos > wayPoints.Count - 1)
        {
            pos = 0;
        }

        return pos;
    }

    //Math behind the Catmull-Rom curve. See here for a good explanation of how it works. https://stackoverflow.com/a/23980479/4601149
    private Vector3 GetCatmullRomPosition(float t, Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float alpha)
    {
        float dt0 = GetTime(p0, p1, alpha);
        float dt1 = GetTime(p1, p2, alpha);
        float dt2 = GetTime(p2, p3, alpha);

        Vector3 t1 = ((p1 - p0) / dt0) - ((p2 - p0) / (dt0 + dt1)) + ((p2 - p1) / dt1);
        Vector3 t2 = ((p2 - p1) / dt1) - ((p3 - p1) / (dt1 + dt2)) + ((p3 - p2) / dt2);

        t1 *= dt1;
        t2 *= dt1;

        Vector3 c0 = p1;
        Vector3 c1 = t1;
        Vector3 c2 = (3 * p2) - (3 * p1) - (2 * t1) - t2;
        Vector3 c3 = (2 * p1) - (2 * p2) + t1 + t2;
        Vector3 pos = CalculatePosition(t, c0, c1, c2, c3);

        return pos;
    }

    private float GetTime(Vector3 p0, Vector3 p1, float alpha)
    {
        if(p0 == p1)
            return 1;
        return Mathf.Pow((p1 - p0).sqrMagnitude, 0.5f * alpha);
    }

    private Vector3 CalculatePosition(float t, Vector3 c0, Vector3 c1, Vector3 c2, Vector3 c3)
    {
        float t2 = t * t;
        float t3 = t2 * t;
        return c0 + c1 * t + c2 * t2 + c3 * t3;
    }

    //Utility method for drawing the track
    private void DisplayCatmullRomSpline(int pos, float resolution)
    {
        Vector3 p0 = wayPoints[ClampListPos(pos - 1)].pos;
        Vector3 p1 = wayPoints[pos].pos;
        Vector3 p2 = wayPoints[ClampListPos(pos + 1)].pos;
        Vector3 p3 = wayPoints[ClampListPos(pos + 2)].pos;

        Vector3 lastPos = p1;
        int maxLoopCount = Mathf.FloorToInt(1f / resolution);

        for(int i = 1; i <= maxLoopCount; i++)
        {
            float t = i * resolution;
            Vector3 newPos = GetCatmullRomPosition(t, p0, p1, p2, p3, catmullRomAlpha);
            Gizmos.DrawLine(lastPos, newPos);
            lastPos = newPos;
        }
    }
    #endregion

    private void OnDrawGizmos()
    {
        #if UNITY_EDITOR
        if(EditorApplication.isPlaying)
        {
            if(debugWayPoints)
            {
                Gizmos.color = debugWayPointColour;
                foreach(SimpleWayPoint s in wayPoints)
                {
                    if(debugWayPointType == WayPointDebugType.SOLID)
                    {
                        Gizmos.DrawSphere(s.pos, debugWayPointSize);
                    }
                    else if(debugWayPointType == WayPointDebugType.WIRE)
                    {
                        Gizmos.DrawWireSphere(s.pos, debugWayPointSize);
                    }
                }
            }

            if(debugTrack)
            {
                Gizmos.color = debugTrackColour;
                if(wayPoints.Count >= 2)
                {
                    for(int i = 0; i < wayPoints.Count; i++)
                    {
                        if(i == 0 || i == wayPoints.Count - 2 || i == wayPoints.Count - 1)
                        {
                            continue;
                        }

                        DisplayCatmullRomSpline(i, debugTrackResolution);
                    }
                }
            }
        }
        #endif
    }
}

```

# Answer
Given that you don't need it to be physics based, wouldn't it be easier to animate the cube in the different positions and then use transitions curves to smooth out the rest?
> 0 votes

---
Tags: unity, c#, mathematics, algorithm, interpolation
---