# Question
Title: What method could I use to avoid using a lookup table for each item when loading a players inventory?
Let me explain a little about the pickup items and inventory to make this much clearer.

Every in world item that can be picked up has a `ScriptableObject` assigned to it that contains all the information about that item (`id`, `name`, `description`, `maxstacksize`, `sprite` etc).

When a player picks up an item it gets added to a `List<InventoryItem>`. `InventoryItem` is a class that gets populated with some of the data pulled from the `ScriptableObject` (`id`, `name`, `description`, `maxstacksize`), and also gets an `amount` property.

I want to save the players inventory, but want to simplify the `InventoryItem` data. So I created an `InventoryItemSimple` struct that holds the `id` and `amount` for each item in the inventory, and then save that list to file.

When loading the player inventory, currently I have a **BIG** list of `ScriptableObjects` that map to the `id`. So I am looping over the saved inventory list and matching against the `id` in the lookup table, and then adding the item to the inventory. I want to avoid this as over time their could be 2,000+ unique objects that could be in the world.

What's a better method to handle this?

If I stick with the lookup table, do I need to worry about how much memory is being used? I don't think my lookup table will ever contain 2,000+ elements. But the thought of having one massive list to manage doesn't appeal to me.

# Answer
> 2 votes
I think you're trying to prematurely optimise this. There isn't a problem, and you should wait until there is a problem to deal with this.

Ultimately, you have to load all of these items into the inventory. You can either do this from memory, or from a db, or from a text file or whatever - with the associated speed/costs.

Alternatively, you could just hold the IDs of the items in the inventory, and then load the individual items as needed (i.e. "lazy loading") - but this doesn't sound like a particularly good fit for your scenario?

Basically you're doing a unique key based lookup, which is generally pretty fast. You could spread your items into lists by type (search by Id and Type) but this is only really necessary when you have a lot more items.

For now, it sounds like you can leave it alone unless you actually observe it causing a problem.

# Answer
> 0 votes
For saving scriptable objects this is the only real solution since unity doesn't save a reference, but instead just saves the values, then loads a new object of the scriptable object type with those values when your project loads. This means you need some way of equality that's not a reference to determine which object you had, is which scriptable object instance in this particular run. Thus your system of a table of IDs works.

Some advice for this method from experience:

* GetHashCode() is not constant between runs. This means you can lose save data if you're using a hash based lookup. In my case I implemented a custom hash function I googled somewhere else.
* Use AssetDatabase API to automatically build this table upon play in edit mode, and upon building. There's other unity APIs for extending the build pipeline, and you can use Awake with a script execution order to ensure the table is built on play. Or if you want to be explicit, add an editor script that gives you a button to rebuild the table.
* Wrap the ScriptableObject as something like PersistentScriptableObject. In this class write a custom editor with OnEnable that uses AssetDatabase.TryGetGUIDAndLocalFileIdentifier() to store the GUID in a private variable. Use this as your key. This allows you to rename the asset, or basically do w/e you want with it, without the key changing. So if you change any properties between patches in your game, this will remain the same until you delete the asset. You can use this base class as a way to automate saving an object.
* You can implement the ISerializationCallbackReceiver interface from unity, and have it automatically save and load itself from the table. No need for custom loading code on everything that stores it.

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


# Question
Title: Unity Android build fails, error : Could not find com.android.tools.build:gradle:x.x.x
Can't build for Android, error log:

```
CommandInvokationFailure: Gradle build failed,

```

And this is in it's description:

```
Could not find com.android.tools.build:gradle:3.2.0.

```

# Answer
Some Gradle libraries were missing,

Instead of directly building apk, tried to "Export Project", then opened it in Android Studio.

It will start to download the requirements. After the required Gradle libraries are installed, try to build it in Android studio. Directly building apk files in Unity will work afterwards.
> 2 votes

---
Tags: unity
---


# Question
Title: Why would a game engine developer use both DirectX and OpenGL?
It's very common for cross-platform game engines to support both DirectX and OpenGL, and even Vulkan. Why would a studio want to write abstraction code 2, 3, or even 4 times? OpenGL/Vulkan are practically on par with DirectX.

In my experience, businesses care about their bottom line. Paying developers to write duplicate code gets expensive very quickly. It'd be nice to use the most native API for each target platform, but I don't understand how the cost and overhead is worth it.

Since Windows support OpenGL/Vulkan, why bother writing the DirectX code when the final game will look nearly identical?

# Answer
The cost of writing multiple wrappers can be amortized over many products, as generally once you write it, you use it repeatedly (perhaps with bug fixes and upgrades). Additionally that cost can be offset by, potentially, new sales on newly-support platforms that could not have otherwise been accounted for. Finally, many COTS middleware engines already have the multiple-API support baked in, so it's part of the cost of buying the middleware and usually not *separable* from that cost.

One reason to support multiple backends is that different backends may perform better on different platforms, and so having the option allows you to maximize the output on those platforms. For me, this is one of the most important. While OpenGL works on both the Mac and Windows and some consoles, it performs poorly on the consoles, usually. And on desktop platforms, relative to the primary APIs for those platforms (such as Metal and D3D) it tends to lag behind in support and tooling and ability to (readily) access cool new stuff.

Another is that the developer has to support platforms that cannot share a common backend. They must pay the cost of the abstraction wrappers anyway as part of doing business, and that lessens the overall cost of (perhaps eventually) adding support for OpenGL later. (In fact, many big games won't write directly against D3D or whatever *anyway*; they'll write against some kind of simplification layer even if they only expect to support one API, so even this can lesson the eventual cost of supporting many abstractions. Although perhaps not as much as intentionally writing that simplification layer with eventual porting in mind.)

A third is that the codebase needs to both support existing games on older backends like D3D9, but also be forward-thinking for technologies like Vulkan or D3D12.

It's also common to support it "just because" it's "cool" or as a learning experience.
> 2 votes

---
Tags: architecture, software-engineering
---


# Question
Title: How to calculate/structure/define rotation vector for OpenGL / WebGL
I am trying to define the buffer data for WebGL and want to have in there something that encodes the fact that an object might be rotating. So it makes me think of angular momentum. So if you have something like that, like the angular momentum or some other rotation "vector" or something, you could use that to calculate a rotation matrix, and then go from there.

The problem is I don't know what that rotation thing is, angular momentum or something else. I keep searching rotation vector, but I'm not sure that's it. Wondering if you have any suggestions on how to have rotation encoded (the rotation force), *before* it is in a matrix form. This is just for 2D rotation.

# Answer
> 1 votes
In 2D it suffices to track a single angle value.

If you want to animate rotation over time, you can include both an angle and an angular velocity, both signed scalars.

```
float currentAngle = initialAngle + time * angularVelocity;

float s = sin(currentAngle);
float c = cos(cutrentAngle);

```

In tandem with a local scale vector \\$ \vec S\\$ and translation vector \\$ \vec T \\$, your transformation matrix can be...

$$\begin{bmatrix}S\_x \cdot c & -S\_y \cdot s & T\_x \\S\_x \cdot s & S\_y \cdot c & T\_y \\ 0 & 0 & 1\end{bmatrix}$$

(Or, if you multiply your vectors on the other side, use the transpose of this instead)

Because this entails re-computing trig functions every time you construct this matrix, it's also common to pre-compute the matrix and set it as a shader uniform or buffer input rather than reconstruct it from the angle in every shader invocation, where practical.

---
Tags: opengl, rotation, webgl
---


title: Changing animator via scriping

text:
# Question
Title: Changing animator via scriping
I am using the following code, my intention is whenever the 2 objects meet the animator boolean changes and when leave change back to its original setting. But it doesnt seem to work.

```
  public GameObject ThePlayer;
public float TargetDistance;
public float EnemyHealth;
public float AllowedRange = 10;
public GameObject TheEnemy;
public float EnemySpeed;
public Animator animator;
public int AttackTrigger;
public RaycastHit Shot;
public static bool hasAttacked = false;
private bool gapTest = true;

void Start()
{

    animator = GetComponent<Animator>();
    hasAttacked = false;
}

void OnCollisionEnter(Collision col)
{

    if (col.gameObject.name == "FPSController")
    {
        Debug.Log("hit");
        animator.SetBool("Moving", false);
        animator.SetBool("Attack1Trigger", true);
        hasAttacked = true;
    }

}

void OnTriggerExit(Collider col)
{
    if (col.gameObject.name == "FPSController")
    {
        Debug.Log("left");
        animator.SetBool("Moving", true);
        animator.SetBool("Attack1Trigger", false);
        hasAttacked = true;
    }
}

```

Any tips on why this does not work?

This is hitting the debug.log in the console, but it is not hitting the animator changes or the boolean change

# Answer
> 1 votes
I've been working with the animator a fair amount recently so here's a few things you can try in situations like these:

**Verify you're hitting an/the right animator** The first part of this should be relatively easy. If the animator is null you should be seeing console errors. If not though, do a quick check in the editor to make sure whatever animator is hooked up to the public field is in fact the one you're looking at. Sounds silly, but I've had that problem before.

**Check the state of the variable in code** You can do this all the time or just immediately after set, but all the Set methods have corresponding Get methods, so you should be able to call that to see what the state is. This is helpful to see if something else may just be turning it off very quickly, at which case you can search for that instead.

**Look for typos** This is another one that has bitten me before. Since both the parameter in the animator and the one you're passing into that method are typed in manually with no verification, it's possible to make a typo on one of the two such that they don't match and the animator will just silently accept and ignore you when you try to Set.

Hopefully one of these will help you find what is going wrong in your case :)

# Answer
> 0 votes
Classic case of silly mistake. I think you need to be using OnTriggerEnter but you're using OnCollisionEnter. :) Good luck friend

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


# Question
Title: How to make healing in an exploration game interesting
I'm creating a game with a heavy focus on exploration, though I'm at a bit of a loss for healing.

The problem is that I don't like the idea of enemies randomly dropping health, as this usually results in grinding when at low health and not near any healing stations(Metroid, Axiom Verge), and I don't want to copy the Soul/Focus system from Hollow Knight(Combat system has already been stolen by me :3), but Hollow Knight is the only game I've played with a focus on exploration that made healing interesting.

I've also thought of auto-regeneration, however that can easily lead to the player cowarding during a boss fight while they heal, and that would break the flow of the gameplay.

I've also considered something like striking a foe heals 1/8th of a health point, however this leads to the player feeling less tense after they take a gain 1/8th which will keep them from dying if they get hit again, and it makes the game feel like its all offense and little defense.

I've also though about an items approach where the player has to eat something or drink something to heal, however this doesn't really encourage healing as once you run out of items, you can no longer heal until you get some more(Legend of Zelda).

I've also though about no healing at all, however I noticed that when exploring and then you take a dumb hit before a hard boss, or a dumb hit before the boss gets hard(*cough* Cuphead *cough*), the player will just either commit suicide or run back to a healing station.

What can I do to make healing interesting, and not break the flow of gameplay?

This is a 2D platformer, and jumping is really important in the combat.

# Answer
> 7 votes
Perhaps you can add some non-conventional healing system.

Like for example :

1. Health steal -\> percentage of health gained = percentage of enemy health lost, and varies with enemy level.
2. Every nth hit -\> every nth hit gains certain health with certain weapon/class/etc.
3. Implement the common methods -\> but minimal like 1-5%

Think something like these, maybe ?

# Answer
> 41 votes
I think you need to consider this at a more fundamental level: what is the gameplay purpose of having a health system in your game?

A conventional health system serves two purposes: (1) it gives a staged failure state to combat, and (2) it serves to create long term resource management with health between fights.

You say you want your game to be exploration heavy. Why is health and death part of your game at all? Is it just there to add challenge? How does the player losing health and then dying in combat support this goal? Does carrying injury from one combat to another support your goals for your game? If not, why use a conventional health system at all? Why not, just for example, have an indestructible character and make the challenge finding a way to get past enemies at all? Why not have being hit cost you some resource, like gold, instead of being a countdown to death?

In order to give a thoughtful design answer to how healing should work you first need to know why the player is healing at all.

# Answer
> 12 votes
You mentioned having thought about auto-regeneration and your issue with that was the possibility of a player, while in the middle of a fight, running around while they auto-regenerate health.

Have you considered auto-regeneration only when not-in-combat (aka out-of-combat)? This is an approach taken in many games.

You could combine this with one or more of your other ideas for a way for players to heal while in-combat.

---

You also mentioned having thought about using healing items, but not wanting the player to feel discouraged from using them, for fear of running out of healing items and having to go collect more.

What if you combined this approach with one of an infinite-use heal? For example, an unlimited-use item that heals a small amount of health, in addition to a limited-use item that heals a large amount of health.

Another approach could be a healing skill/item that can be used over and over, but with a cooldown (or some other cost, such as mana). That way, the player would be able to regularly use their healing skill (when strategically applicable).

---

You could have auto-regeneration, but discourage players from waiting for it all the time by making it very slow regeneration. Then have other healing methods that encourage or promote the way you'd like the player to play (like the idea to heal when you hit an enemy)

# Answer
> 6 votes
There's lots of examples out there in 2D platforming, it's really a question of how you want healing to be "interesting"? I would agree with suggestions that "skillful" play should be rewarded, but also give the player enough opportunities to use resources and play strategically.

A few thoughts:

* DeadCells uses a "flask" system where you fill up between levels (or healing station in your case) and can then heal a limited number of times using it. It also requires the player to stand still for a few seconds, making it tricky (not impossible) to use during combat.
* Mario. You gain "health" (and abilities) by getting power ups. Getting hit loses these abilities/power ups, instead of you dying immediately.
* Health steal/vampire. Kinda interesting, if your theme is right for it. But you've got to balance the game on the premise that you hit a lot more than you get hit, e.g. that 'slow, tanky' bosses become relatively easier.
* You could look at making healing a limited resource that costs you something (e.g. points, gold, items whatever)
* Some kind of special heal attack that is relatively difficult to hit with (long wind-up), and causes player to be vulnerable if they miss (long wind-down). It has a reasonable cooldown and/or cost. Heal amount is dependent on the health/difficulty of the opponent hit. Could be a nice balance of risk/reward. (i.e. I'm on low health, do I risk trying to land my heal on the boss?)

# Answer
> 4 votes
Limit healing resources and put any additional resources into new, unexplored areas. Create the incentive where if a player wants to heal, they have to press on into more of the map.

You can do this a few ways:

1. Have physical healing locations on the map, but cap the health they restore. Many games (like Metroid) have healing rooms, but they provide unlimited health, encouraging the player to backtrack when in danger. Instead, make them limited use.

For example, in *Moonlighter*, each floor of the dungeon has a healing pond that restores a set amount of HP. Once this limit is hit, the pond is "used up" and no longer heals. The cap is also relatively low (a little less than the player's max HP)

The pond on each floor has to be found in the first place (encouraging exploration) and when emptied, the player has to risk exploring the next (more difficult) floor if they want additional healing.
2. Another option is to limit the number of healing items that exist in the game and hide them. This is often seen in survival horror games (I'm specifically thinking of *Resident Evil 4* or the first *Dead Space*).

This creates tension, as healing becomes high risk (health right now may mean less health later). The drawback of this approach is it can make a player avoid risk or combat. Survival horror games address this by making combat unavoidable (which, from an earlier comment, sounds like you are open to).

Another strategy you can use is letting the player know that there will be more items in the next area. Tell them that, for example, "Each level has X healing talismans" (can be explicit dialog or a "You found X/X items" on the map screen).

This way, they know that healing is limited and in order to heal, they have to explore. Also, if they want to heal more, they have to defeat the boss and move on to the next area.
3. Lastly, you could figure out a way to tie health directly into progression, for example, every 1% of the map filled gives the player 1% health. Obviously, this needs more fleshing out (like, what happens after the player explores 100% of the map?), but if you figure out a mechanic where the only way to heal is to *move forward*, that would alleviate many of your concerns.

I hope this helped, good luck with your game!

# Answer
> 4 votes
If cowarding during a boss fight is your major problem with auto-regeneration, make the auto-regeneration **non-linear**: give it a cap of auto-regeneration, and disable it during boss fight (boss fight only, not normal combat).

During normal exploration, make the auto-regeneration fast when your player is in low HP, and it gradually gets slower when HP regenerates (regen\_speed = 1/HP). Such a system will make your player keep their HP not to low (hence the purpose of healing), but also not too high (higher HP, lower regen\_speed).

If the player is patient enough, or if your dynamic-healing-system is not set correctly, waiting can still be an option. To prevent this, set a max cap for auto-regeneration. For example, auto-regeneration speed is 0/second over 50% HP. You can still heal with potion, health stealing, spells etc. to go beyond 50% HP, but not auto-regeneration.

Lastly, give the boss an aura that disable the auto-regeneration. If it's frustrating for players to start the boss fight with low HP, then give the boss an aura that "heals you to full health, but disable the auto-regeneration", or even with "heals you to full health, disable auto-regen, and revert your HP after the boss fight to pre-boss-fight level".

An explanation for the last aura could be: the boss is fighting your player in the "soul realm", and thus

* your soul HP is irrelevant with your character HP, and always starts with 100%
* unlike physical body, soul don't heal themselves
* after the fight, your soul goes back to the character, and hence your (character) HP will be the same level pre-fight

# Answer
> 3 votes
Doom (2016) actually has a great example of rewarding interesting gameplay with healing through its glory kill system. By rewarding the player with health for getting close to finish off demons, it was able to create a gritty fast-paced in-your-face adrenaline shooter in stark contrast to the cover-based shooters that dominate the market. You could do this same sort of thing, but rewarding the kind of gameplay relevant to your game

If your goal is to drive exploration and platforming, work with that. Create healing triggers based on those types of behaviors. Maybe every time you enter a room you've never been in before, recover something like 25% of your health (or 100% when entering a boss room). Perhaps even have healing for killing an enemy for the first time. You could also put a few frames of invincibility at the beginning of jumps and add a small amount of healing if you get hit within this window (perfect dodge healing).

# Answer
> 2 votes
Missed the timeframe by the looks of it, but will still complete my answer:

Associate self-healing in-combat mainly with the player performing combos. It could be combos that the players are taught or that they are subtly hinted at, through messages of general explanation or by suggesting the combo for a particular situation.

Considering the fact that you want to find a way for gaining health and mana, performing combos could cost mana, but *heal* you and in order to gain mana the player has to be accurate with their combos. This would also provide a relatively sustainable approach for a player that seems to be `always 'in combat'`, since everything they would need to succeed is all about their *skill*.

You can always tweak the numbers by:
\- making harder combos heal for more
\- having higher accuracy on landing combos gives you more mana
\- adding synergy between weapons and health/mana (such that if you have a weapon that has `Combo Power +10` would give 10% more healing and more mana from combos, or `Healing Power +10` only 10% more healing.
\- since I saw classes mentioned, you could also have class synergies where, I don't know a Druid gains more Healh innately but has weaker damage to compensate, or a Mage gets more mana out of combos, Archer would have more accuracy on combos, and so on... (Just examples, I know it might be far from your game world.)

This would allow to have levels of difficulty and would mean that, at times, players (and/or their classes) would need some item/strategy in approaching an enemy. It would also require that players get a grasp of the synergies and the advantages and disadvantages of items/classes/combos. You also get to have a more developed world if you wish :)

# Answer
> 2 votes
# Dual hit point system

Pillar of Eternity has an interesting approach to it, having two types of hit points, which may help you or give some ideas:

## Endurance

Whenever a combat starts, this is a character's hit points for the duration of the combat. It quickly regenerates outside of combat. When the character drops to 0, it is incapacitated for the rest of the fight (other characters can still fight, alternatively it could also mean death for single characters). When a character takes damage, it drains both, Endurance and Health. Healing only affects Endurance and is therefore only relevant in combat.

## Health

This is the long term hit points characters have. It is a multitude of Endurance, and the given Endurance in a combat can not exceed the remaining Health of a character. When Health drops to 0, a character dies. Resources have to be used/sacrificed to restore this, and it does not regenerate. Also there are interactions with abilities, like restoring Endurance in a fight, but not Health.

---

Now as an example, you can have a warrior with 20 maximum Endurance and 100 maximum Health. You go around, fight enemies, lose Health from combat to combat. The benefit is this: The character has something long-term to handle while progressing through the game, which can be more slow and difficult to maintain - but the immediate combat hit points are not drastically low or high in order to balance it.

---

## Possible variations:

* Endurance scales with the relative amount of current Health. Meaning as Health drops from fight to fight, the character becomes weaker as well in combat, either by starting with less Endurance or suffering less power.
* Similar to Overwatch, an additional layer of hit points could be added, like Armor. Meaning you can allow your character to take some damage in each combat without draining Health.
* Another version is Endurance which regenerates in a moderate pace in combat, where Health does not. Effectively it would mean the player must take care not to take too much damage in a too short time-span, but also consider that he won't regenerate hit points forever.
* Another honorable mention is World of Warships, where only a part of damage taken can be repaired - be it the last 'n' amount of damage or n% of total damage taken. In essence this is also a dual hit point system. Variance can be had in damage types, meaning some may be better at preventing repair at the cost of other factors.

# Answer
> 1 votes
There's been an isometric (like Fallout 1&2) *'Fallout 76'-like* fan made free game available for the last eight years, called Fonline (F-Online; Fallout Online). All you need are the copyrighted data files from F2.

It has a more or less open world, where in instanced encounters you can usually find the two things **you need to craft healing powder** : a broc flower and a xander root. Maximum carry weight and the time it would take to make too many, prevents abuse *and* getting stuck because something is too hard.

The flowers and roots aren't hard to find like in Fallout3, you just grind as many as you need until that gets boring and you think you can handle it. All the while, real people and NPCs can come kill you and take all your stuff, but at least you get a little XP for crafting things.

Healing level interest: 9/10.

Agency: 11/10. Because there are several ways to heal yourself; the better ones come at the cost of sacrificing points into non-combat skills such as First Aid, or the ability to craft stimpaks (which require points in Science, a blueprint, and having paid to learn the Chemist profession).

Healing Powder is pretty much useless *in combat* for even mid-level characters; it's what you use afterwards because they're free.

---

For a 2D platformer, you need to make (procedurally generated?) places where they can grind what they need if they have to. Otherwise you just die or run back to the save spot like in Castlevania SotN.

If I died because I ran out of powders, that's my fault.... *Agency*.

# Answer
> 1 votes
Have your character eat or drink to heal. Although they can use it unlimited times, you can limit it behind a long use-time—that is, they are required to stand still for 5+ seconds to heal. Have the item only heal 10%-25% means they have to use it multiple times. This would encourage exploring.

As for bosses. Providing an area to "catch-your-breath" before you start the fight would allow them to heal up before fights. Bosses could have "quick interrupt" abilities that they use when you try to heal, thus preventing you from cowering/hiding, while some bosses would have long animations or routines, thus making healing a possible strategy in those "windows" (or dealing a little extra damage).

Maybe have artifacts or relics that the hero can switch between that provide different healing benefits. Such as passive health regen, consumption healing (food), life-steal, etc. Thus, the player can decide which they prefer to play with.

# Answer
> 0 votes
Another idea:

You generate mana through movement. You can spend mana (via a button) to heal. However, while healing, you move at a slower pace (risk enemies catching up) and cannot jump (limited mobility).

# Answer
> 0 votes
Pretty much along the lines of the answer @CertainlyNot provided:

Have you ever played Quest64? You regain magic points by moving around in the world, and striking enemies with melee attacks. You obtain limited amounts of healing items, and a majority of the healing in the later parts of the game in between (or during) fights will come from healing spells. Due to the random encounter system in the game, there's an interesting risk-reward to saving mana for fights, or spending it as you gain it to heal up. Perhaps something like this is what you're looking for.

---
Tags: game-design, game-mechanics, platformer
---


# Question
Title: How do i make enemy tank to follow and face player tank?
I'm creating tank game demo , in game i want enemy tank to always face toward the player tank.

I already check **look\_at()** function but it will face immediately, i don't want that. I want enemy tank to slowly rotate toward player.

What i'hv done so fare is :

**MainWindow.gd**

```
extends Node2D

func _ready():
    $Tank2.loadPlayer1($Tank1)
pass

```

**EnemyTank.gd**

```
extends KinematicBody2D

var rotSpeed = 0.3

var player1

var speed = 30
var velocity = Vector2()

func _ready():
pass

func loadPlayer1(obj):
    player1 = obj

func _process(delta):
    if player1 != null:
        velocity = Vector2()
        var rot_dir = (player1.position - position).angle()
        rotation += rotSpeed*rot_dir * delta
        velocity = Vector2(0,0).rotated(rotation)
        move_and_slide(velocity)
pass

```

My Result is : Enemy Tank (red) keep rotating

Does anyone know how do i fix this?

Thank you

# Answer
> 1 votes
Those who are still locking for same answer, i manage to rotate enemy tank toward the player.

here is the code :

```
var turn_speed = deg2rad(3)

func _process(delta):
if player1 != null:
    var dir = get_angle_to(get_global_mouse_position())
    if abs(dir) < turn_speed:
        rotation += dir
    else:
        if dir>0: rotation += turn_speed #clockwise
        if dir<0: rotation -= turn_speed #anit - clockwise
pass

```

pass target position in place of `get_global_mouse_position()` to rotate toward.

Happy coding :)

---
Tags: rotation, godot
---


# Question
Title: Changing orbit camera to up-down camera at certain position
I'm trying to rebuild the camera movement shown in this video.

For demonstration purposes, I have changed the FoV to a higher value in this video as this allows a larger view.

The player's Y input rotates the chest.

The camera is automatically positioned and rotated according to the chest rotation.

However, at a certain Y-position / height, the camera seems to switch from orbit behaviour to a simple up-down movement. At least that is what it looks like for me when I watch the video.

I would like to recreate this by changing my camera script attached below, but I don't know how because the position seems coupled with the rotation.

Thank you.

```
 using UnityEngine;
 using System.Collections;

 [AddComponentMenu("Camera-Control/Mouse Orbit with zoom")]
 public class MouseOrbitImproved : MonoBehaviour
 {

public Transform target;
public float distance = 5.0f;
public float xSpeed = 120.0f;
public float ySpeed = 120.0f;

public float yMinLimit = -20f;
public float yMaxLimit = 80f;

public float distanceMin = .5f;
public float distanceMax = 15f;

private Rigidbody rigidbody;

float x = 0.0f;
float y = 0.0f;

// Use this for initialization
void Start()
{
    Vector3 angles = transform.eulerAngles;
    x = angles.y;
    y = angles.x;

    rigidbody = GetComponent<Rigidbody>();

    // Make the rigid body not change rotation
    if (rigidbody != null)
    {
        rigidbody.freezeRotation = true;
    }
}

void LateUpdate()
{
    if (target)
    {
        x += Input.GetAxis("Mouse X") * xSpeed * distance * 0.02f;
        y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;

        y = ClampAngle(y, yMinLimit, yMaxLimit);

        Quaternion rotation = Quaternion.Euler(y, x, 0);

        distance = Mathf.Clamp(distance - Input.GetAxis("Mouse ScrollWheel") * 5, distanceMin, distanceMax);

        RaycastHit hit;
        if (Physics.Linecast(target.position, transform.position, out hit))
        {
            distance -= hit.distance;
        }

        Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
        Vector3 position = rotation * negDistance + target.position;

        transform.rotation = rotation;
        transform.position = position;
    }
}

public static float ClampAngle(float angle, float min, float max)
{
    if (angle < -360F)
        angle += 360F;
    if (angle > 360F)
        angle -= 360F;
    return Mathf.Clamp(angle, min, max);
}
}

```

# Answer
> 2 votes
I can't speak to exactly the way the Resident Evil camera was implemented.

What I can say is that it's common practice to use curves to control camera movement. So for instance, you could use a curve to control the blend between two behaviour styles, parametrized by the camera's pitch. Something like this:

```
public AnimationCurve orbitCylinderTransition;
public float cylinderRatio = 0.8f;

Vector3 GetCameraOffset(float pitch, float yaw, float nominalDistance) {
    Vector3 direction = Quaternion.Euler(pitch, yaw, 0) * Vector3.back;

    Vector3 planar = direction;
    planar.y = 0;
    float horizontalLength = planar.magnitude;

    Vector3 onSphere = nominalDistance * direction;

    Vector3 onCylinder = onSphere;
    if(horizontalLength > 0f)
       onCylinder *= cylinderRatio / horizontalLength;

    float blend = orbitCylinderTransition.Evaluate(pitch);

    return Vector3.Lerp(onSphere, onCylinder, blend);
}

```

This computes two possible positions for the camera: one on a sphere around the orbit point, and one on a vertical cylinder, both at the desired angle relative to the orbit point.

Next, it uses the pitch variable to select a sample point on a designer-editable curve to get a blend weight between 0 and 1, with zero being purely spherical orbit behaviour, and one being purely cylinder behaviour. We can control the radius of the cylinder relative to the sphere's using the ratio variable - here I chose something a little under 1, since it looks like as we lower the camera, it swings inward a little bit before starting to drop straight down.

By shaping this curve in the editor, you can precisely control where you want this transition to occur, and how you want to ease in & out of it. This makes it easy to tune for feel, without needing to reverse-engineer a specific math expression to capture the exact transition rule you want.

You might find the sphere / cylinder blend is not quite right for the feel you want, and instead you want to use a curve to control the ratio o nominal distance to final distance by camera pitch instead. Or maybe you want to stack multiple curves. Once you expose this in the editor you can much more freely tweak & tune, whatever model you choose.

---
Tags: unity
---


title: Black screen when building apk Unity

text:
# Question
Title: Black screen when building apk Unity
Alright, I have a bit of a confession to make: I accidentally posted this question in the wrong place: Stack Overflow. Whoops. Anyway, here's my problem. Sorry if you've seen this before. Here's the original post.

I've been struggling with this issue for a few days now. Windows builds for my game work fine, but when I build it to Android, it loads, shows the "made with Unity" screen, then fades to black. Now, I know the next scene (an animated logo) is running because it is playing the audio in real time. However, nothing in the scene is visible. Then, the UI for the in-game loading screen appears. Normally, the game would then load, and it does, but again, the camera thinks there are no sprites in the scene. I can still play the game, and the audio sounds just normal, but I can't see. Then, when I die, the game-over UI appears, and I can use it as normal. The shop-menu works absolutely fine, but the game itself does not. It's as if Unity decided that all SpriteRenderers in the game just didn't exist, and that the camera background color was now black. There are no scripts or animations causing this directly, as it does work in editor and on a PC build. The game also works fine using Unity remote, but the build has the issue. I also made sure that none of the textures were too large for Android (to the point where not one of them is larger than 256x256, which looks terrible but proves a point).

Now, before anyone asks, yes, I have seen the other question on this topic, and no, sadly, it did not help. My camera is set to "solid color", not "don't clear." I tried "skybox" too, just to be safe. I have also tried disabling post-processing, hoping that Android was just unable to handle it. It did nothing. I have even tried entirely disabling all of the sprites in the scene, but even then, the background is still black, indicating that the camera is still not playing nice. Also, here is a screenshot showing the quality settings for the Android build.

# Answer
> 0 votes
Assuming you have set all the camera and render setting properly, it could be :

1. a problem of texture format/compression.

Try experimenting with that in the build settings. I had similar problems when i started, and the solution came through those.

And check if this build runs fine on other devices (with different hardware) or an emulator.

For reference: https://docs.unity3d.com/Manual/class-TextureImporterAndroid.html

2. Other probable cause could be, that there are too many draw calls w.r.t your device

Same can be checked by running it on different hardware or emulator.

If these does not work, kindly comment...

---
Tags: unity, android, rendering
---


# Question
Title: How can I implement (almost) infinitely large maps in Unreal Engine 4?
I'm making a game where a helicopter travels around.

I'd like that the environment around be as realistic as possible. For instance, since the helicopter can travel at speeds up to 200 km/h, I want the player to see very far away, in a realistic fashion.

I'm talking about a map where let's say there is a "real" mountain 50km away and you could "walk" there, as well as the mountain looking like a mountain in game from the any distance (no matter the quality).

How could I manage my map in UE4 that would allow me to implement such a "real" world?

# Answer
> 3 votes
The default MAX WORLD constant for a level in Unreal Engine is 20km so you can make a single map as large as 20\*20km.

But then, Unreal Engine does have a feature that could help you do that: World Composition is the way to go for very large worlds.

Also have a look at Open World Toold and the Kite Demo they released

There are limitations though, like multi-player

# Answer
> 1 votes
There can be two methods, but one requires extensive work and other, some serious coding skills.

1. Divide your complete map into multiple pieces, lets say grids with different skyboxes for each (as you want to display things from large distances, like the mountain). Display them based on player position from a WorldController script.
2. Generate the map programmatically (like world engine plugins) in multple LOD settings, it will be much easier than above method if you know how to code or apply logic using blueprints. But the details will be much less than what you could achieve through method 1.

If you want to base your game on some real life location, then method 1 must be used, else use method 2 if possible.

---
Tags: maps, unreal-4, streaming
---


# Question
Title: UE4 crashes on launch when using custom components in C++?
I created `SM_Door` in my Editor with a custom `Actor` class named "Door" to fire some events like open and close.

The problem is, when I open the UE4 Editor, it loads nearly to 75% loading and then crashes, and I really don't know why!

The code of the Door Header file is:

```
#pragma once
 #include "CoreMinimal.h"
 #include "Components/ActorComponent.h"
 #include "GameFramework/Actor.h"
 #include "Door.generated.h"

 UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) )
 class MAZE_API UDoor : public UActorComponent
 {
     GENERATED_BODY()

 public:
     // Sets default values for this component's properties
     UDoor();

     void Open();
     void Close();
     bool IsOverlapping(AActor*);

 protected:
     // Called when the game starts
     virtual void BeginPlay() override;

 public:
     // Called every frame
     virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;

 };

```

Then I created Runner class representing the default player:

The full code of the Runner class is:

```
#pragma once

 #include "CoreMinimal.h"
 #include "Components/ActorComponent.h"
 #include "Engine/World.h"
 #include "Door.h"
 #include "GameFramework/Actor.h"
 #include "Runner.generated.h"

 UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) )
 class MAZE_API URunner : public UActorComponent
 {
     GENERATED_BODY()

 public:
     // Sets default values for this component's properties
     URunner();

 protected:
     // Called when the game starts
     virtual void BeginPlay() override;

 public:
     // Called every frame
     virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;

     void IsNearToDoor();
     void IsNearToLampKey();

 private:
     void SetupComponents();

     UDoor Door;
     AActor* Runner = nullptr;
 };

```

# Answer
The problem could be with this line in `Runner.h`:

```
UDoor Door;

```

In this case, the constructor, `UDoor()`, from `Door.h` is being called to initialize the default value of the private variable, `Door` in `Runner.h`. However, `Runner.h` may not have access to all of the includes and variables required by the `UDoor()` constructor. *I can't be sure if this is the case because you haven't posted the constructor code from your `Runner.cpp` file.*

Try making the variable `Door` in `Runner.h` a pointer instead, like this:

```
UDoor* Door;

```

To further clean up the code, you might use a sort of forward declaration by using the `class` keyword like this:

```
class UDoor* Door;

```

If you use forward declaration like this, you could remove `#include Door.h` from your `Runner.h` file and add it to your `Runner.cpp` file instead.
> 0 votes

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


# Question
Title: Unity3D - Finding every subclass of monobehaviour in current project with reflection
I am trying to find all types that inherit from monobehaviour inside my Unity project. So not the instances of them but the actual types in the assembly. I've tried this little piece of code and I don't understand why it is not getting the types. The debug is logging 0.

Also I am going to use this in editor scripting. But for testing purposes I am running the code in the start method of a component.

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

public class TypeGetter : MonoBehaviour
{
    private Dictionary<Type, FieldInfo[]> monobehavioursInfo = new Dictionary<Type, FieldInfo[]>();

    private void Start()
    {
        monobehavioursInfo = GetTypes<MonoBehaviour>();
        Debug.Log(monobehavioursInfo.Count);
    }

    private Dictionary<Type, FieldInfo[]> GetTypes<T>()
    {
        Dictionary<Type, FieldInfo[]> temp = new Dictionary<Type, FieldInfo[]>();
        foreach (Type t in Assembly.GetAssembly(typeof(T)).GetTypes()
            .Where(myType => myType.IsClass && !myType.IsAbstract && myType.IsSubclassOf(typeof(T))))
        {
            FieldInfo[] fields = t.GetFields();
            temp.Add(t, fields);
        }
        return temp;
    }
}

```

# Answer
My guess is that MonoBehaviour is not in the assembly-csharp assembly. Try `Assembly.GetAssembly(this.type)`. Although this won’t work once this code goes into an editor script, because the editor script goes into a different assembly on its own. In that case, you would probably just want to use `typeof(SomeInGameType)`
> 1 votes

---
Tags: unity
---


title: Server Side Movement Box2D LibGDX

text:
# Question
Title: Server Side Movement Box2D LibGDX
I am trying to implement server-side movement using box2d on libgdx client and planck-js(box2d for javascript) on nodejs server. I am running box2d world on both client and server.

Before server i was moving player on client with applying force on input

```
player.body.applyForce( Vector2(-4.5f, 0f), player.body.worldCenter, true)

```

Now from client to server i am just sending input data and applying force on server side:

Client if left key pressed:

```
 var inputData:JSONObject = JSONObject()

            inputData.put("type", "left");
            inputData.put("x", player.body.worldCenter.x);
            inputData.put("y", player.body.worldCenter.y);
            socket.emit("inputFired",inputData)

```

So server gets this data and applies force code to move player on server side.

```
    var movePlayer = find_playerid(this.id);
    if (!movePlayer) {
        console.log('player does not exist');
        return;
    }
      console.log(data)
      var positionVector = Vec2(data.x,data.y)
      if(data.type =="left"){
        var impulseVector = Vec2(-4.5,0.0)

      }else if(data.type =="right"){
        var impulseVector = Vec2(4.5,0.0)

      }else if(data.type=="up"){
        var impulseVector = Vec2(0.0,4.5)

      }else if(data.type=="down"){
        var impulseVector = Vec2(0.0,-4.5)

      }
  movePlayer.body.applyForce(impulseVector,positionVector,true)
      movePlayer.x = movePlayer.body.getPosition().x
      movePlayer.y = movePlayer.body.getPosition().y
      console.log("new position")

```

After this point what is confusing me is what should i really return to client ? If i just return position values of body after applying force,how im gonna position client side body according to this ?

# Answer
> 1 votes
With what you have already laid out **you want to use snapshot-interpolation**.

Read this very good article series to learn about snapshot-interpolation:

**This explains in all detail how you could synchronize a networked physics simulation by sending compressed snapshots of the game state and interpolating between them.**

You can also **simulate locally and on the server** to use the server side position to correct the locally generated position, this **allows you to hide lag**.

# Answer
> -1 votes
What i did is just returning new linear velocity of body to client.So server applies force then gets linearvelocity of body sends it to client and client equals new linear velocity to body but still having sync problems.asked this on another question

---
Tags: libgdx, box2d, client-server
---


# Question
Title: How to avoid enemies overlapping each other when chasing player in Unity?
I am trying to get enemies to chase player but without them overlapping each other when they get closer to the player.

So far what I have is that I check for the distance between current enemy and the another enemy in a list and if their distance is less than 2 then update their position away from each other.

But when I do that, the enemies instantly move away rather than smoothly moving away from each other. What can I do to improve this?

Here is my script for chasing player:

```
public void ChasePlayer()
{
    foreach (GameObject enemy in enemies)
    {
        if (enemy != null)
        {
            float currentDistance = Vector3.Distance(transform.position, enemy.transform.position);

            if (currentDistance < 2.0f)
            {
                Vector3 dist = transform.position - enemy.transform.position;
                transform.position += dist;
            }
        }
    }

    if (lantern.transform.GetChild(0).gameObject.GetComponent<Light>().enabled)
    {

        gameObject.GetComponent<MeshRenderer>().enabled = true;
        gameObject.GetComponent<Collider>().enabled = true;
        transform.LookAt(player.transform);
        transform.position += transform.forward * speed * Time.deltaTime;

    }
    else
    {
        gameObject.GetComponent<MeshRenderer>().enabled = false;
        gameObject.GetComponent<Collider>().enabled = false;
    }
}

```

# Answer
> 1 votes
You could change your approach, and look into using the Unity's NavMesh Agent system instead.

With a `nevmeshagent`, there is a property on the agent which offsets the character along a vertical axis to get a result you would be looking for.

# Answer
> 1 votes
I fixed it. All I needed to do was multiply `dist` by `Time.deltatime`.

Like so: `transform.position += dist * Time.deltatime;`

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


title: Inputs in realtime multiplayer game

text:
# Question
Title: Inputs in realtime multiplayer game
I'm using a structure, where client sends his inputs every 20ms in one packet and server parses his inputs every update(20ms aswell). I've got a problem, since player can send me more than one inputs packet per tick(if he uses cheats), so he can move faster than others. The thing is that I don't know how to check if his messages aren't too frequent. Before, I've been doing like this: Clients copy his inputs in buffer every 20ms and sends the buffer to server every 100ms. Server parse 1/5 of this buffer every 20ms and sends client's state to client. The problem was the thing that there was a big delay, and client's state on his screen was unstable since he sends message on 100ms and waits for server to parse it(100ms more) and it stacks so delay will be bigger with every client's message. I've been using this since server parses only one input message per 100ms, so even if client tries to cheat his speed will be the same. My question is, how do other game developers do, how they can be sure that the server won't parse too much client messages and delay will be little? I'm sure I miss something, since I don't see other questions like this one, it should be easy to fix, so please tell me if I'm wrong.

# Answer
> 5 votes
It sounds like your problem arises from processing players' input eagerly, the moment it comes in. In this situation, it's harder to keep track of the context of the input and its timing/frequency with respect to other players and your own primary/authoritative update time step.

Instead, try thinking of your game as though it were turn-based, just with very fast, auto-advancing turns.

Every time your server receives input from a player, assign it a timestamp that represents the moment in game time when it should be applied (this could be the time of receipt, or a backdated time to try to compensate for latency) and stuff it in a priority queue to process all at once.

Every fixed timestep on your server, advance the game by one turn, using the inputs gathered for that turn. That means you run one update pass, updating the authoritative game state to a new stamped time. In this pass, process all the inputs in the queue that occur in this slice of game time.

Because you're running all your server logic for the turn in one pass, you can make sure you never double-process any one player's input for a single turn, or let them combine/spam actions that shouldn't be allowed.

(eg. maybe "I pressed right" and "I pressed jump" both stack, and can both execute in one update turn, but "I pressed right" and "I pressed right" just collapse down to a single rightward input for this turn. Or maybe you re-stamp the second input and stuff it back in the queue to enforce it happening in a later turn instead)

You can also use this pass to look at how many inputs you've gotten from each player in this update window, to keep track of deviations, and flag cases that look like cheating rather than ordinary timing fluctuations.

---
Tags: networking, input, client-server, server
---


# Question
Title: How do I parent an object to a bone in the blender hierarchy?
So, I'm trying to make a simple RPG game using Blender and Unity. I would like to have an empty object to be used as a weapon holding position parented to my right hand bone so that I can switch weapons in and out and they'll be able to animate along with my character by being the child of the empty position. The problem I am having is that I can't get the empty position to be a child of the specific right hand bone, only the armature. Is there a way to make this work? Also, if this isn't a good procedure to accomplish what I am trying to do, please enlighten me with the proper way, I'm kind of a noob, thanks.

# Answer
> 1 votes
I was doing similar things recently and got it working. What you are talking about sounds strange to me because the "empty object" you mention sounds more like Unity's empty game object instead of Blender's empty, but anyway, if you want to parent anything to a bone in Blender, select only that bone in pose mode, go select the object, then shift select the bone, press ctrl+p you should see a menu which allows you to parent the object to just the bone. In the case of Unity, you just parent the object's transform to the bone's transform. If your armature is humanoid, you can find the right-hand bone with Animator.GetBoneTransform method.

---
Tags: unity, animation, blender, rigging, importing
---


# Question
Title: Randomizing material across meshes - UE4
I have multiple instances of the same mesh which is using the same material.

While looking for randomizing textures, I came across texture bombing and so the material in 1 wall looks fairly random. Its a blend of 2 materials. But the problem is different walls look the same. Is there some way so the walls look different with same material. For eg: The green moss is random across the walls and not look same?

Thanks

# Answer
You can look at creating "Macro Texture Variation" with the "Reduce Macro Contrast" that will help with breaking up tiling.

Include Starter Content in your project, and open up "M\_Brick\_Clay\_New" or try opening a few different materials in the StarterContent\Materials folder, and look for the commented block "Macro Texture Variation" and "Reduce Macro Contrast", you may simply copy/paste those nodes, and multiply the output from the final node, with your final base color node.
> 1 votes

---
Tags: textures, rendering, unreal-4
---


# Question
Title: How to UV map a procedural cylinder mesh? (Unity)
I have a script that generates a procedural cylinder. Each side is a quad that consists of two triangles. The two triangles share vertexes, so, a side with two triangles is defined by 4 points.

The mesh generates fine as you see here:

However, I am unable to UV map it correctly. My current progress has led me here:

With a different texture you can see how it stretches at certain points. If the first quad is the "front" of the cylinder, then these points occur on each side.

I thought it would work to use the vertex data directly as UV points, but I can't get it to work.

Here is the (old) script.

```
private void _CreateSegmentSides()
{
    if(m_Sides > 2) {

        float angleStep = 360.0f / (float)m_Sides;
        BranchSegment seg = new BranchSegment(m_NextID++);
        Quaternion rotation = Quaternion.Euler(0.0f, angleStep, 0.0f);
        float height = m_SegmentStartLength;
        int max = m_Sides - 1;
        int index_tr = 0, index_tl = 3, index_br = 2, index_bl = 1;
        float angle = 0f;

        // Make first triangles.
        seg.vertexes.Add(rotation * (new Vector3(m_Radius, height, 0f)));       // top right
        seg.vertexes.Add(rotation * (new Vector3(m_Radius, 0f, 0f)));           // bottom left
        seg.vertexes.Add(rotation * seg.vertexes[seg.vertexes.Count - 1]);      // bottom right
        seg.vertexes.Add(rotation * seg.vertexes[seg.vertexes.Count - 3]);      // top left

        // Add triangle indices.
        seg.triangles.Add(index_tr);    // 0
        seg.triangles.Add(index_bl);    // 1
        seg.triangles.Add(index_br);    // 2
        seg.triangles.Add(index_tr);    // 0
        seg.triangles.Add(index_br);    // 2
        seg.triangles.Add(index_tl);    // 3

        // UV.
        seg.uv.Add(rotation * seg.vertexes[seg.vertexes.Count - 4]);
        seg.uv.Add(rotation * seg.vertexes[seg.vertexes.Count - 3]);
        seg.uv.Add(rotation * seg.vertexes[seg.vertexes.Count - 2]);
        seg.uv.Add(rotation * seg.vertexes[seg.vertexes.Count - 1]);

        for (int i = 0; i < max; i++)
        {
            Debug.Log("add side ("+(i+1).ToString()+"/"+ max.ToString()+ ") angle: " + angle.ToString());

            // First triangle.
            seg.vertexes.Add(rotation * seg.vertexes[seg.vertexes.Count - 2]);

            seg.triangles.Add(seg.vertexes.Count - 1);  // new vertex
            seg.triangles.Add(seg.vertexes.Count - 2);  // shared
            seg.triangles.Add(seg.vertexes.Count - 3);  // shared

            seg.uv.Add(rotation * seg.vertexes[seg.vertexes.Count - 1]);

            // Second triangle.
            seg.vertexes.Add(rotation * seg.vertexes[seg.vertexes.Count - 2]);

            seg.triangles.Add(seg.vertexes.Count - 3);  // shared
            seg.triangles.Add(seg.vertexes.Count - 2);  // shared
            seg.triangles.Add(seg.vertexes.Count - 1);  // new vertex

            seg.uv.Add(rotation * seg.vertexes[seg.vertexes.Count - 1]);

            angle += angleStep;
        }
        m_Segments.Add(seg);
    }
}

```

I've been at this all day, what is going wrong here ??

**Edit: Current progress, updated code**

```
    // Making the first two UV coords:

rad = angle * Mathf.Deg2Rad;
ux = rad * m_Radius;

uy =  seg.vertexes[0].y;
seg.uv.Add(rotation * new Vector2(ux, uy));

uy = seg.vertexes[1].y;
seg.uv.Add(rotation * new Vector2(ux, uy));

// in the loop
for (int i = 0; i < max; i++)
{
    angle += angleStep;
    Debug.Log("add side (" + (i + 1).ToString() + "/" + max.ToString() + ") angle: " + angle.ToString());

    rad = angle * Mathf.Deg2Rad;
    ux = rad * m_Radius;

    // First vertex.
    seg.vertexes.Add(rotation * seg.vertexes[seg.vertexes.Count - 2]);

    seg.triangles.Add(seg.vertexes.Count - 1);  // new vertex
    seg.triangles.Add(seg.vertexes.Count - 2);  // shared
    seg.triangles.Add(seg.vertexes.Count - 3);  // shared

    // UV
    uy = seg.vertexes[seg.vertexes.Count - 1].y;
    seg.uv.Add(rotation * new Vector2(ux, uy));

    // Second vertex.
    seg.vertexes.Add(rotation * seg.vertexes[seg.vertexes.Count - 2]);

    seg.triangles.Add(seg.vertexes.Count - 3);  // shared
    seg.triangles.Add(seg.vertexes.Count - 2);  // shared
    seg.triangles.Add(seg.vertexes.Count - 1);  // new vertex

    // UV
    uy = seg.vertexes[seg.vertexes.Count - 1].y;
    seg.uv.Add(rotation * new Vector2(ux, uy));
}

And trying to fix the last to the first section
rad = 360f * Mathf.Deg2Rad;  // (I've tried keeping the angle from the loop, but that didn't solve it either)
ux = rad * m_Radius;

uy = seg.vertexes[seg.vertexes.Count - 2].y;
seg.uv.Add(rotation * new Vector2(ux, uy));

uy = seg.vertexes[seg.vertexes.Count - 1].y;
seg.uv.Add(rotation * new Vector2(ux, uy));

```

**Edit: Implemented the suggestion from the second comment.**

Okay, so I'm going over the calculated UV values in a second loop after the part that I've posted, then I use the rounded value from `UVx_max / UVx_max_rounded_to_int` to multiply each UV to adjust the UV tiling. This works! (I wonder if it is possible to do it without a second loop?) There is a visible line (normal related?) on the seam even if the texture is seamless. I am calling `RecalculateNormals()` on the last part of the mesh creation.

**Edit: Implementation of the corrected code:**

```
private void _CreateSegmentSides2()
    {
        if(m_Sides > 2)
        {
            float           angleStep   = 360.0f / (float)m_Sides;
            BranchSegment   seg         = new BranchSegment(m_NextID++);
            Quaternion      rotation    = Quaternion.Euler(0.0f, angleStep, 0.0f);
            float           height      = m_SegmentStartLength;
            float           angle       = 0f;
            int             max         = m_Sides - 1;
            float ux, uy, rad;

            // Make first side.
            seg.vertexes.Add(rotation * (new Vector3(m_RadiusTop, height, 0f)));    // tr
            seg.vertexes.Add(rotation * (new Vector3(m_RadiusBottom, 0f, 0f)));     // bl
            seg.vertexes.Add(rotation * seg.vertexes[seg.vertexes.Count - 1]);      // br
            seg.vertexes.Add(rotation * seg.vertexes[seg.vertexes.Count - 3]);      // tl

            // Add triangle indices.
            seg.triangles.Add(0);
            seg.triangles.Add(1);
            seg.triangles.Add(2);
            seg.triangles.Add(0);
            seg.triangles.Add(2);
            seg.triangles.Add(3);

            // Making the first two normals:
            if (m_CustomNormals) {
                seg.normals.Add(seg.vertexes[0].normalized);  // Points "out" of the cylinder.
                seg.normals.Add(seg.normals[0]);
            }

            // Making the first two UV coords:
            float circumferenceTop      = Mathf.PI * 2.0f * m_RadiusTop; // We know this in advance.
            float circumferenceBottom   = Mathf.PI * 2.0f * m_RadiusBottom;
            float uvScaleTop            = Mathf.Max(1, Mathf.Round(circumferenceTop)) / circumferenceTop;
            float uvScaleBottom         = Mathf.Max(1, Mathf.Round(circumferenceBottom)) / circumferenceBottom;
            float uvScaleDiff           = Mathf.Abs(uvScaleBottom - uvScaleTop);

            // UV starts here.
            rad = angle * Mathf.Deg2Rad;

            ux = 0;
            uy = seg.vertexes[0].y * uvScaleTop;
            seg.uv.Add(new Vector2(ux, uy));

            uy = seg.vertexes[1].y * uvScaleBottom;
            seg.uv.Add(new Vector2(ux, uy));

            // The remaining sides.
            for (int i = 0; i < max; i++)
            {
                angle += angleStep;
                rad = angle * Mathf.Deg2Rad;

                // First vertex.
                seg.vertexes.Add(rotation * seg.vertexes[seg.vertexes.Count - 2]);

                seg.triangles.Add(seg.vertexes.Count - 1);  // new vertex
                seg.triangles.Add(seg.vertexes.Count - 2);  // shared
                seg.triangles.Add(seg.vertexes.Count - 3);  // shared

                // UV: x = arc length around the cylinder, y = height, scaled to tile uniformly.
                ux = (rad * m_RadiusTop) * uvScaleTop;
                uy = seg.vertexes[seg.vertexes.Count - 1].y * uvScaleTop;
                seg.uv.Add(new Vector2(ux, uy));

                // Normal: rotate normal from the previous column.
                if(m_CustomNormals) { seg.normals.Add(rotation * seg.normals[seg.normals.Count - 1]);  }

                // Second vertex.
                seg.vertexes.Add(rotation * seg.vertexes[seg.vertexes.Count - 2]);

                seg.triangles.Add(seg.vertexes.Count - 3);  // shared
                seg.triangles.Add(seg.vertexes.Count - 2);  // shared
                seg.triangles.Add(seg.vertexes.Count - 1);  // new vertex

                // UV: x is the same, update y for new vertical position.
                ux = (rad * m_RadiusBottom) * uvScaleBottom;
                uy = seg.vertexes[seg.vertexes.Count - 1].y * uvScaleBottom;
                seg.uv.Add(new Vector2(ux, uy));

                // Normal: copy previous normal.
                if(m_CustomNormals) { seg.normals.Add(seg.normals[seg.normals.Count - 1]); }
            }

            // Last UV to connect the seam.
            rad = 360f * Mathf.Deg2Rad;

            ux = (rad * m_RadiusTop) * uvScaleTop;
            uy = seg.vertexes[1].y * uvScaleTop;
            seg.uv.Add(new Vector2(ux, uy));

            ux = (rad * m_RadiusBottom) * uvScaleBottom;
            uy = seg.vertexes[0].y * uvScaleBottom;
            seg.uv.Add(new Vector2(ux, uy));

            m_Segments.Add(seg);
        }
    }

```

Custom normals:

Automatic normals by unity:

UV skew on different top and bottom radius:

(Seems like the UV is rotated ever so slightly sideways with each side, making it really messed up when it comes back around. height is also oddly scaled)

# Answer
> 5 votes
It looks like you're trying to use (rotated) vertex positions as UV coordinates. When you're using this to look up into a 2D texture, only the x & y values are used and the z is ignored, giving you a planar projection:

The effect is like shining your texture onto the object using an orthographic projector, along one directional axis. Portions of your model perpendicular to that axis catch the image flat-on, and you get a nice undistorted appearance there.

But as the surface turns diagonally to the axis, the image gets stretched. In the worst case, imagine a long edge of your model running parallel to the projection axis. Every point on that edge maps to the same pixel in the source image, so that one point of colour gets smeared out along the whole edge.

For a cylinder, you'll more often want to use a cylindrical projection:

Here, the U (x) coordinate of our UV is our arc-length around the cylinder, and our V (y) coordinate is the vertical position of the vertex.

You can get the arc-length value by multiplying the total angle stepped so far (in radians) by the radius of your cylinder.

Note though that this has a discontinuity, where 360 degrees wraps around to 0 degrees. Here we'll want to duplicate the column of vertices we started with, so we have two sets of co-incident vertices with identical positions & normals: one to be the let edge of the texture sheet we've wrapped around our cylinder, and one to be the right edge.

You may also want to apply some scaling to your UVs so that one complete trip around the cylinder takes you an integer distance in texture space. That way you can use a tiling texture and completely erase the seam at the 360-to-0 wraparound line.

---

Here's a corrected version of your code:

```
// Making the first two normals:
seg.normals.Add(seg.vertices[0].normalized);  // Points "out" of the cylinder.
seg.normals.Add(seg.normals[0]);

// Making the first two UV coords:
float circumference = Mathf.PI * 2.0f * m_Radius; // We know this in advance.
float uvScale = Mathf.Max(1, Mathf.Round(circumference)) / circumference;
// No second loop required for fix-up - we can scale as we go.

uy =  seg.vertexes[0].y * uvScale;
seg.uv.Add(new Vector2(0, uy));

uy = seg.vertexes[1].y * uvScale;
seg.uv.Add(new Vector2(0, uy));

// in the loop
for (int i = 0; i < max; i++)
{
    angle += angleStep;
    Debug.Log("add side (" + (i + 1).ToString() + "/" + max.ToString() + ") angle: " + angle.ToString());

    // First vertex.
    seg.vertexes.Add(rotation * seg.vertexes[seg.vertexes.Count - 2]);

    seg.triangles.Add(seg.vertexes.Count - 1);  // new vertex
    seg.triangles.Add(seg.vertexes.Count - 2);  // shared
    seg.triangles.Add(seg.vertexes.Count - 3);  // shared

    // UV: x = arc length around the cylinder, y = height, scaled to tile uniformly.
    ux = angle * Mathf.Deg2Rad * m_Radius * uvScale;
    uy = seg.vertexes[seg.vertexes.Count - 1].y * uvScale;
    seg.uv.Add(new Vector2(ux, uy) * uvScale);

    // Normal: rotate normal from the previous column.
    seg.normals.Add(rotation * seg.normals[seg.normals.Count - 1]);

    // Second vertex.
    seg.vertexes.Add(rotation * seg.vertexes[seg.vertexes.Count - 2]);

    seg.triangles.Add(seg.vertexes.Count - 3);  // shared
    seg.triangles.Add(seg.vertexes.Count - 2);  // shared
    seg.triangles.Add(seg.vertexes.Count - 1);  // new vertex

    // UV: x is the same, update y for new vertical position.
    uy = seg.vertexes[seg.vertexes.Count - 1].y * uvScale;
    seg.uv.Add(new Vector2(ux, uy));

    // Normal: copy previous normal.
    seg.normals.Add(seg.normals[seg.normals.Count - 1]);
}

```

Now you don't have to ask Unity to calculate normals automatically: you've provided exactly the normals you want. Just watch out for floating point rounding errors, where applying `max` incremental rotations / angle additions might not bring you to exactly the total you expect. If that becomes a problem, you can do something like...

```
angle = Mathf.Lerp(0, 360.0f, i/(max - 1.0f));

```

---
Tags: unity, procedural-generation, 3d-meshes, uv-mapping
---


# Question
Title: Collision detection in Arkanoid-like game at intersections
I'm creating an Arkanoid-like game from scratch. I have no (formal or informal) education of any kind in game-development, so I kinda made up things as I went regarding collision detection based on personal ideas of "how it probably works".

I approximate the ball as a point and ignore its thickness, which is small anyway. I compensate for this visually by very slightly making all objects smaller than they are.

I don't "detect" collision, but anticipate it and change the outcome of the next frame. For example:

The ball is currently in position A, and it "wants" to go to E (red line). But I calculate all intersections with all segments which make up the bricks: B, C, D. The closest one to starting point (A) is B, so I choose B as the "real" intersection. I destroy the brick this segment belongs to.

Now I check how would the ball proceed if it would start at B, with its vector flipped horizontally (because I determine that the segment it hit was horizontal). This is the blue line. Again, from F and G, I pick F. I destroy the brick this segment belongs to.

Lastly, the orange line doesn't intersect, so I determine that the bottom of the orange line is where I should place the ball in the next frame.

---

This worked fine and I was satisfied with it, until I started nailing the edge case of the ball hitting the T intersection, where it all goes bananas.

What should happen here is that the ball bounces to the left and destroys either of the bricks. But what *can* happen is that my algorithms decides to choose the middle vertical segment (connecting boxes 1 and 2) as the collision point, either belonging to the 1st or 2nd box.

I thought of ignoring the edges of the segments, but then the ball would pass right through the T-intersection in this scenario, because it would also ignore what it's supposed to hit.

You can see it in action here (around after 00:07 mark): https://www.mp4upload.com/p6966u6kuzad

What are common techniques for handling this case? Even if I introduce the width to the ball, it could still hit the exact T-intersection at the tangent, so the problem would remain.

---

Requested to post code. Here's the main bit. Please note that I'm not expecting you to (or looking for) debugging the application. I'm more asking about how are these things even handled in general.

```
export function bounceBall(
  ball: Point,
  vx: number,
  vy: number,
  obstacles: Obstacle[],
) {
  const projectedNextPoint = ball.clone().translate(vx, vy)
  const movement = new Segment(ball, projectedNextPoint)

  const touchedObstacles: Obstacle[] = []

  let loop = 10

  let hasCollision = false
  do {
    hasCollision = false

    if (loop-- < 0) {
      throw new Error('oops')
    }

    // If in the previous loop the ball just grazed the surface
    if (movement.isZeroLength()) break

    const collisions: Collision[] = []
    for (const obstacle of obstacles) {
      const collision = getIntersectionOfSegmentAndObstacle_ClosestToStartExcludingStart(movement, obstacle)
      if (collision != null) collisions.push(collision)
    }

    const collision = getClosestCollisionExcludingSelf(movement.start, collisions)

    // We don't count a collision if it's the starting point.
    // If we did, grazing a surface would turn into an infinite loop.
    if (collision == null || Point.AreEqual(collision.point, movement.start)) {
      hasCollision = false
    } else {
      hasCollision = true
      touchedObstacles.push(collision.obstacle)
    }

    if (hasCollision) {
      movement.setStart(collision!.point)
      if (collision!.segment.isVertical()) {
        movement.mirrorVerticallyWrtStart()
        vx = -vx
      }
      if (collision!.segment.isHorizontal()) {
        movement.mirrorHorizontallyWrtStart()
        vy = -vy
      }
    }

  } while (hasCollision)

  return {
    touchedObstacles,
    vx,
    vy,
    newBall: movement.end,
  }
}

```

# Answer
> 1 votes
Solution 1 is to set your game in a universe of discrete pixels.

Solution 2 is to include the decimals of the right and underneath the blocks in the blocks area.

Let's say this is one block:

It is 6 units wide and 4 units high.

Instead of limiting the collision area to what is inside block make it 6.9999999999999999999... wide and 4.999999999999999999... high like this:

So here is 4 of these block in the way your animation makes it look:

And here is 4 blocks when you include what is "outside" of the block to be inside the blocks collision area:

When your ball hit the area between the blocks it would in this case count are hitting the upper right block.

Because 0.99999999999999999999999999999... != 1 a ball will not hit two blocks at once. And to prevent graphical glitches then you must also make each block one pixel wider and higher for the human eye,.

# Answer
> 1 votes
I'd recommend thinking of your blocks as a regular grid, with a fixed spacing horizontally & vertically. We'll use componentwise division to divide these spacing parameters out of both our starting position & velocity, so from here on in we can pretend our grid has a spacing of 1 unit in each direction to keep the math simple.

Now we can think of this collision detection problem as though we were rasterizing a line to a grid of pixels.

Our travelling ball is a ray that we can raymarch through this space, along the line:

```
positionAtTimeT = initialPosition + velocity * t

```

Where `initialPosition` is the position of our ball at the start of this check, and `positionAtTimeT` is its position `t` seconds later, travelling with constant `velocity`.

We can find the integer coordinates of the current cell we're occupying by flooring the initial position:

```
int2 cell = (floor(initalPosition.x), floor(initialPosition.y))

```

Next we're going to see which cell borders we cross as we continue to march across the grid. I'm going to elide checks for a zero velocity along either axis in what follows, but if your ball can move purely horizontally or purely vertically you'll want to ignore the zero'd axis to avoid division-by-zero errors.

The direction we're travelling across the grid horizontally & vertically is the sign of our velocity:

```
int2 cellIncrement = (sign(velocity.x), sign(velocity.y))

```

And, after we reach the first border along each axis, we continue striking a new border along that axis regularly, with interval:

```
float2 crossingInterval = (cellIncrement.x / velocity.x, cellIncrement.y / velocity.y)

```

So the next (vertical) cell border we'd reach by travelling horizontally is:

```
int nextBorder = cell.x + cellIncrement.x + (cellIncrement.x < 0 ? 1 : 0)

```

And we'd reach it at time `tX` seconds:

```
float tX = abs(nextBorder - initialPosition.x) * crossingInterval;

```

We can do the same to find the time to hit a horizontal border by travelling vertically, `tY`.

Now we take turns, choosing whichever is smaller, `tX`, `tY`, or `tMax`, the duration of our frame.

* If `tX` is smaller:

+ we add `cellIncrement.x` to `cell.x`
    + we check if that `cell` is occupied. If so, break it, and reflect our ray horizontally:

    `positionAtTimeT = initialPosition.x + velocity.x * tX`
    `velocity.x *= -1`
    `initialPosition.x = positionAtTimeT - velocity.x * tX`

    `cell.x -= cellIncrement.x`
    `cellIncrement.x *= -1`
    + we add `crossingInterval.x` to `tX` to get the time of the next crossing.
* if `tY` is smaller: we do all of the above, but for y instead.
* it `tMax` is smaller:

we stop iterating, and position our ball where it's ended up at the end of the frame,

`positionAtTMax = initialPosition + velocity * tMax`

We loop this until we reach the `tMax` exit case (or hit some maximum number of bounces if you want to account for pathological cases)

The advantage of this style is that the crossing of each border segment is well-ordered, and can never result in the ball tunneling into the edge between two blocks when it should have hit their outside faces first.

Even in the case where it hits a corner first (like the example in the question), we get sensible results:

1. `tX` & `tY` are equal, let's say we arbitrarily choose `tY` to process first.
2. We increment our current `cell` vertically, and check if for the presence of a block.
3. Since the block is empty, (we haven't crossed the vertical line into the next column of blocks to our right yet), we do no breaking / reflection, so we increment `tY` and carry on.

(So we don't get an erroneous vertical reflection when hitting two stacked blocks side-on)
4. Now `tX` is smaller, since they were equal and we just incremented `tY`.
5. We increment our current `cell` horizontally, and check for the presence of a block.
6. We find one (the upper of the two stacked blocks), so we break it & reflect off of it to the left (into a cell we already checked above & know is free), then increment `tX`.
7. We've now correctly bounced past the corner, destroying one of the blocks (the top one).

If we'd handled `tX` before `tY` in the event of equality, we would have destroyed the bottom block, but our trajectory would be the same.

If you really wanted to, you could add a special case for `tX == tY` to flip a coin or destroy all adjacent blocks, to ensure there's no bias at exact corner hits.

# Answer
> 0 votes
I watched a few vidoes of Arkanoid and it seems that usually the gaps between bricks is filled with material which when touched doesn't destroy any bricks but instead acts only as material that the ball bounces off.

So in your second picture the ball would bounce with -45 degrees.

You asked not to debug anything, so there it isn't.

---
Tags: collision-detection, collision-prediction
---


# Question
Title: How to disable gravity for a RigidBody moving on a slope?
I created a script that handles movement for my player (moving around, going down and up slopes). However, since I'm using a RigidBody not a CharacterController when I go up slope and stop on the middle of it the gravity pulls me backward, which is fine, but the problem is when I move forward, the gravity force pulls me backward when I'm trying to go forward. This problem wouldn't have appeared if my character wasn't a sphere but my character is a sphere so it always roll down when gravity is applied to it.

What I want is to somehow stop the gravity for a second or reset it to zero when I move my character, and when I'm going up a slope so it won't hold me back. I tried:

```
if(grounded) rb.velocity = Vector3.zero;

```

but I don't think it's the right approach.

# Answer
I've had great success by the following method. The idea is that, under the specific circumstance that the Rigidbody is in contact with a surface appropriately angled in relation to gravity(which is to say, 'a slope that isn't too steep'), it will be pulled toward the surface normal instead of in the direction of gravity. As a bonus, this code will work regardless of what direction gravity happens to currently be.

Rigidbody ourRigidBody;
bool isGrounded; // Handy to have for jumping, and we'll use it here too
Vector3 currentGravity; // Just holds some data for us...
ContactPoint[] cPoints; // ContactPoints are generated by Collision, and they hold lots of fun data.
public float maxGroundedAngle = 45f; //The steepest you want the character to be able to stand firmly on. Steeper than this and they'll slide.
Vector3 groundNormal; //The angle that will be perpendicular to the point of contact that our Rigidbody will be grounded on.

void Start()
{
    ourRigidBody = GetComponent<Rigidbody>();
    ourRigidBody.useGravity = false; //we'll make our own!
    /*Freezing rotation is not necessary, but highly recommended
      if we're making a character rather than just some object
      that happens to be on a slope.*/
}

void OnCollisionStay(Collision ourCollision)
{
    isGrounded = CheckGrounded(ourCollision);
}

void OnCollisionExit(Collision ourCollision)
{
    /*It's okay to not have to check whether or not
     the Collision we're exiting is one we're grounded on,
     because it'll be reaffirmed next time OnCollisionStay runs.*/
    isGrounded = false;
    groundNormal = new Vector3(); //Probably not necessary, but a good habit, in my opinion
}

bool CheckGrounded(Collision newCol)
{
    cPoints = new ContactPoint[newCol.contactCount];
    newCol.GetContacts(cPoints);
    foreach(ContactPoint cP in cPoints)
    {
        /*If the difference in angle between the direction of gravity
          (usually, downward) and the current surface contacted is
          less than our chosen maximum angle, we've found an
          acceptable place to be grounded.*/
        if(maxGroundedAngle > Vector3.Angle(cP.normal, -Physics.gravity.normalized))
        {
            groundNormal = cP.normal;
            return true;
        }
    }
}

void ObeyGravity()
{
    if(isGrounded == false)
    {
        //normal gravity, active when not grounded.
        currentGravity = Physics.gravity;
    }
    else if(isGrounded == true)
    {
        /*Not normal gravity. Instead of going down, we go in the
        direction perpendicular to the angle of where we're standing.
        This means whatever surface we're grounded on will be
        effectively the same as standing on a perfectly horizontal
        surface. Ergo, no sliding will occur. */
        currentGravity = -groundNormal * Physics.gravity.magnitude;
    }
    ourRigidBody.AddForce(currentGravity, ForceMode.Force);
}

void FixedUpdate()
{
    ObeyGravity();
}

```
</code></pre>
> 4 votes

# Answer
Not saying that turning off gravity is the right approach, but if you want to cancel gravity, you only need to apply a force equal to gravity. The sum of the forces is then zero, the object doesn't move. Thus, anti-gravity is enabled.

```
public class AntiGravity : MonoBehaviour
{
    private Rigidbody rb;
    public Rigidbody getRigidbody
    {
        get { return rb ?? (rb = GetComponent<Rigidbody>()); }
    }

    void FixedUpdate()
    {
        Vector3 v = Physics.gravity * getRigidbody.mass;
        getRigidbody.AddForce(-v);
    }
}

```

You'd apply the anti-gravity force in the same `FixedUpdate` frame that you apply your movement force.
> 0 votes

# Answer
I would not change the global gravity. This will cause numerous complications in the future. Instead of changing the gravity, have you considered increasing the friction on the player or the slope? Maybe attaching a physic material to the player and then modifying the **PhysicMaterial.staticFriction** in the editor or at runtime via code might help? Static friction seems to work on objects that standing still which would stop the sliding on your character.
> 0 votes

# Answer
After doing some debugging i found that using if(grounded) rb.velocity = Vector3.zero wasnt the issue, the issue was in mycheckgrounded function i had to add 0.05f to the height of the ray because when i was on the slope the grounded bool was false, wish was odd but actually it made sense my object wasnt rotated at the same angle as the slope so that must have created a small gap between the slope and my player.
> 0 votes

---
Tags: unity, movement, rigidbody
---


# Question
Title: WebGL - two different approaches to Point Light: what is the difference?
So I'm studying Webgl and after directional light I'm approaching point light.

So I've seen two different approaches:

1. Take the directional light (diffuse and specular components) and multiply them by a falloff attenuation, for example with the attenuation function is by Tom Madams that anyway take in account the distance from the fragment surface point to the light point. This approach is spotted in this webgl light walkthrough tutorial, and I find it easier to understand. Seems also the same approach from this OpenGL tutorial (in the section Point Light)
2. The other approach listed here does not involve a light attenuation falloff but calculate the light direction from any fragment position and the light point source. It seems a little bit more complicated to me.

Is there something that I have totally misunderstood? What is the difference between this two approaches? When to use the first and when to use the second?

Thanks!

# Answer
> 0 votes
The latter isn't point lighting in the traditional sense and also discusses Phong shading (that's where the complication comes from mostly, it's a simpler approach by default). It will lighten up a surface if it's facing in the direction of the point, regardless of distance. It works similarly to stars (e.g. the Sun), while the former imitates a desk lamp

---
Tags: shaders, lighting, webgl
---


# Question
Title: How to transform Capsule Component in UE4?
The collision of the character with the environment only works correctly (in the eyes) when I use the original skeletal mesh.

I tested it in the most varied sizes and it worked perfectly.

It turns out that when I import any 3D object (FBX of Blender), it does not work properly (though the UE4 says that in the import it makes several adjustments).

I realized that the problem is because of the **capsule component**, which is responsible for detecting the character's collision with the environment. So at first I would like to know how to **increase its size and make modifications**.

Links that I researched and that helped me in some way:

https://answers.unrealengine.com/questions/853084/is-it-possible-to-transform-the-capsule-component.html

https://answers.unrealengine.com/questions/200546/change-the-capsule-component.html

https://answers.unrealengine.com/questions/465122/how-to-change-character-capsule-component-location.html

# Answer
First, you can not click on the capsule component only.

To change the dimensions of the capsule component, simply type 'capsule' in the search box that will appear two edit boxes: lighting and shape.

It is not possible to change the position of the capsule component, but it is possible to change the position of the character mesh. Just double click on the character that it becomes possible to change the position of the mesh.

References:

https://answers.unrealengine.com/questions/200546/change-the-capsule-component.html

https://answers.unrealengine.com/questions/465122/how-to-change-character-capsule-component-location.html
> 0 votes

---
Tags: fbx, collider
---


# Question
Title: Send a Push Notification from a device to another device
I have setup Firebase authentication in my game for Android. I need to implement a feature in my Android game, where a user can challenge another player. I need to implement it this way: The user is shown the list of all users registered on Firebase on the Game. To any user, he can tap on a button for respective user to send a challenge. When, he taps, a push notification is to be recieved by that user. When he taps on the notification, he is redirected to a specific part of the game. Maybe a specific scene for now and he is shown there the Challenger's name.

I have explored the Firebase documentation, but it does not provide information for client-client push notifications.

Maybe there are other options available like GameSparks and OneSignal. But I don't know if there is a requirement of own Server for implementing it.

# Answer
> 0 votes
Don't send the notification directly. That isn't possible. However, you can deal with the notifications like this: One user sends the challenge to the other. I'd assume it could be as simple as a string saying that it is a challenge and a couple of strings with information about the sender. Then, all you have to do is tell the receiving end to notify the user every time it receives a challenge. This way, all the code is local, and the information being sent is nice and simple.

In short, send the other device the challenge, which then prompts the user with a notification. The rest is all handled locally. Hope this helps!

---
Tags: unity, social, firebase
---


# Question
Title: Preventing the mouse from breaking keyboard navigation in UI?
I am trying to achieve the following, a behavior like Windows Explorer where mouse and keyboard play nice together.

Here's a GIF along explanations:

* first I click one of the folders using the mouse
* second I click the background area, folder is not focused but still selected
* third I move to the next folder below using the keyboard

To sum it up, mouse and keyboard play well together.

Now in Unity it's an entirely different story, here is a fairly simple menu created using the actions in Hierarchy context menu, nothing special:

Here's what happens:

* I click one of the buttons using the mouse
* I move down to the next button using the keyboard
* I click in the blank area, button loses focus
* I try to move down to the next button using the keyboard, nothing happens

I have tried a couple of things like disabling *Raycast target* on images, disabling background panels or making them opaque but without success.

**How can one make Unity UI behave like Windows Explorer's one ?**

(where clicking in the blank area with the mouse does not break keyboard navigation)

# Answer
> 1 votes
In turned out there was an **utterly simple** solution to this problem and that works really well, the trickiest part being to figure it out by thinking out of the box loud enough!

One extra script next to the `ScrollRect` which tracks selection and restores it after dragging but with visual feedback being preserved, with a bit of reflection, though.

In the following GIF:

* dragging the scroller with the mouse
    + last control is saved but its state looks like selected
* mouse is released
    + control is restored and really selected
* navigation with the keyboard
* dragging again

While I show a drag operation, it works when you just click on the back, like in Windows Explorer.

```
using System.Reflection;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace WIP
{
    public sealed class PreventLostFocus : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
    {
        private GameObject _current;

        [Tooltip("Selectable should look as selected during drag?")]
        public bool SelectedLook;

        #region IPointerDownHandler Members

        public void OnPointerDown(PointerEventData eventData)
        {
            if (_current == null)
                return;

            if (!SelectedLook)
                return;

            var selectable = _current.GetComponent<Selectable>();
            if (selectable == null)
                return;

            var method = selectable.GetType().GetMethod("DoStateTransition", BindingFlags.Instance | BindingFlags.NonPublic);
            if (method == null)
            {
                Debug.LogWarning("Couldn't perform discreet state transition, something has probably changed under the hood.");
                return; // fail gracefully but let dev know it didn't work
            }

            method.Invoke(selectable, new object[] {3, true}); // 3 == Selectable.SelectionState.Selected
        }

        #endregion

        #region IPointerUpHandler Members

        public void OnPointerUp(PointerEventData eventData)
        {
            // restore last good selection

            if (_current == null)
                return;

            EventSystem.current.SetSelectedGameObject(_current);
        }

        #endregion

        private void Reset()
        {
            SelectedLook = true;
        }

        private void Update()
        {
            // track current selection

            var current = EventSystem.current.currentSelectedGameObject;
            if (current == null)
                return;

            _current = current;
        }
    }
}

```

# Answer
> 2 votes
You need to create some kind of manager class, which controls the logic of the control element. Add a script, which holds references to the buttons and create methods, which react to user input. In this manager you would build a dictionary of type `(Button, int)`, or if it's easier for you a List of type `(Button, int)`, which you fill at the `Awake` method of the class. You do this in order to create a relationship between a button and an index.

So, whenever the user clicks on a button, the manager saves the last clicked index. Now, when the user uses the keyboard, you check the last clicked index and depending on the direction of the keyboard input (up/down), you increase/decrease the index by one and look up the right button in the list. You then activate the respective button and update the last saved index. Make sure to catch edge-cases when the index reaches a value smaller than 0 or an index greater than the elements in the list minus one.

---
Tags: unity, gui
---


# Question
Title: Can I use my Unity Plus licence with Unity version 5.3.4p3?
I had Unity 5.3.4p3 from 2 years ago, and I want to use it for my current project.

Since then, I've purchased a Unity Plus licence.

Can I use that licence to develop and publish my Unity 5.3.4p3 project?

(And what does the "p" in 5.3.4p3 even mean?)

# Answer
> 0 votes
According to the official Unity support site:

> ## Can My License Work On Previous Versions Of Unity?
>
> Unity licenses are backwards compatible. This means that for each license version, you can activate all versions prior to that release, but not newer versions.
>
> For example if you have a Unity 4.x license, you can activate any version of Unity 4, or Unity 3. 5.x licenses can be activated in all versions of Unity 5, 4 and 3.
>
> ...
>
> **Subscription licenses can be used on *all* currently released versions of Unity**. They are automatically upgraded to the latest version, so **you are able to download the version you wish** to use and activate with your subscription license.

(Emphasis added)

So yes, if you have licensed the current version of Unity, you have permission to use any prior released version of your choosing.

If you have operational questions about how to make this transition or register your licence with Unity 5.x, please contact a Unity representative - this is the type of thing they're there to help you with as a paying customer of theirs.

---
Tags: unity, licensing
---


# Question
Title: Unity3D - Generate a position within a circular band around the player
Given a certain condition in my game I need to generate a position around the player. It needs to be at least 8 meters away from him and within 10 meters, in a circular matter, as in the dotted green area in the picture below.

Can anyone point me into the right direction? Thank you.

# Answer
I think something like this could work, I haven't tested it, just rotate a normalized vector by a rotation (quaternion) and the vector will rotate; and for the vector to be within your range, just scale it by your minimum range plus the range of space (min + rand(max - min)). You could also try with Quaternion.Euler if Quaternion.Axis does not work:

```
private float minRange = 8.0f;
private float maxRange = 10.0f;

public Vector3 GetPosition()
{
    float randomRotation = Random.Range(0.0f, 360.0f);
    float projection = minRange + Random.Range(minRange, minRange +  (maxRange - minRange));
    // You could also try with Quaternion.Euler(0, angle, 0)...
    return Quaternion.AngleAxis(randomRotation, Vector3.up) * Vector3.forward * projection;
}

```

Hope it helps.
> 1 votes

# Answer
Here is another way to get it done:

```
public Vector3 GetPosition2(Vector3 origin, float minRange, float maxRange)
{
    var startingPoint = Random.insideUnitCircle;
    var normalized = startingPoint.normalized;
    var actualPoint = normalized * Random.Range(minRange, maxRange);
    var relativeToOrigin = new Vector3(actualPoint.x, origin.y, actualPoint.y) + origin;

    return relativeToOrigin;
}

```
> 1 votes

---
Tags: unity, geometry
---


# Question
Title: How many unity version support with 1 seat?
I bought plus unity license 1 seat so Can I use it on 2 unity version Example: Uity5.3.4p3 and unity 20183.18f1 Or it use only for one version?

# Answer
1 seat means you are licensed for one developer to develop with the Unity platform, any version(s).

You may not have more than one developer without purchasing additional seats.
> 1 votes

---
Tags: unity
---