# Question
Title: How to hide objects behind an invisible plane?
I am using Unity 2019.1.4f1 (personal) in regular 3D mode. I want to make a material for a plane that will cause everything behind that plane to be invisible.

I want a character who steps through a doorway to appear to disappear into "hammerspace" when he passes the door frame. I will post pictures in a minute.

Blender concept (note how space after the doorframe is successfully occluded):

Unity WIP (note how path after doorway is not yet occluded):

# Answer
> 4 votes
You can do this with the depth buffer.

This shader will cause an object to write its depth to the depth buffer, without actually drawing anything.

Any content behind this object's front faces that tries to draw after it in the rendering order will fail the depth test and abort drawing those pixels.

If you need some content to be hidden but not others, then one way to solve it is to play with the Render Queue for each material - sandwiching this material before the object you want to hide, but after the objects you want to show through it.

```
Shader "Custom/DepthReserve"
{
    Properties
    {
    }
    SubShader
    {
        Tags { "RenderType" = "Opaque" "Queue"="Geometry-1" }
        LOD 100

        Blend Zero One

        Pass
        {

        }
    }
}

```

If you want to be more selective about what gets hidden / not, then you'll likely want to modify the shader of the object being hidden, to eg. check the stencil buffer or do a test against a custom render texture to determine whether it's allowed to draw here.

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


# Question
Title: Unity - Top Down Perspective Camera to Orthographic size
I have a perspective camera with an fov of 60. It looks at an object from top view with a rotation(90, 0, 0) and position (0, 50, 0)

The user has the option to change the camera to orthographic view to get a 2D view without any depth from top

Now how can i calculate the orthographic size so the view looks same as that in the perspective view(just not having the depth)?

# Answer
```
  size
--------
 \     | d
  \    | i
   \  f| s
    \ o| t
     \v|
      \|

```

`size / distance = tan(fov)` using SOHCAHTOA

`size = distance * tan(fov)`

So the orthographic size should be set to `distance * Mathf.Tan(Mathf.Deg2Rad(fov))` where `distance` is how far away the camera is from the object it's viewing (in your case, I believe `50`).

If you know that you won't change the FOV, and/or you know the distance, you can pre-calculate it. For `60 degs` and `50 units` the orthographic size will be `86.6025403784`.
> 0 votes

---
Tags: unity, camera
---


# Question
Title: How to modularly call a script based on parameters within the script?
I am coding an interaction system in Unity that does things based on whether the player *taps* interaction, or *holds* interaction. Each object holds their own scripts of how a player can interact with them and what happens (e.g., they can physically lift an object, add an object to their inventory, open/close a door, etc)

What I want is for the `interactable_object` to call component scripts that have been added to it and categorized as `tapInteraction` or `holdInteraction`, but I also want the component scripts to be separated from *how* they're called (e.g., they might be called via tap or hold, it shouldn't matter).

If I use interfaces, the `tapInteraction` could check for `GetComponent<ITap>()` and the `holdInteraction` could check for `GetComponent<IHold>()`, but then wouldn't each action need separate scripts defined as `Lift : ITap` and `Lift : IHold`? I feel like there would be a lot of repetition.

I'm wondering if there is some better way to go about this.

EDIT:

Thank you very much for the input DMGregory and Alex F!

I ended up going with an interface approach similar to what Alex F answered, but with two key differences:

* It was very important to me to have the actions as components on the gameobject since a specific action (e.g. `Lift` or `AddToInventory`) would have a large amount of customization from object to object.
* I also wanted the interaction to return a status as to whether it succeeded or not.

As such I created a base class `Interaction` that implements the interface `IInteraction` with a bool `TryInteraction` method, and registers/deregisters itself to an `interactable_object` via `OnEnable` and `OnDisable` as the `tapAction` or `holdAction` depending on if that Interaction is set as a tapAction or holdAction.

`InteractionLift` and `InteractionInventoryPickUp` inherit that base `Interaction` class, they implement the `TryInteraction` interface, and depending on their parameters will register themselves to a interactable\_object script as either the hold or tap action. Then the `interactable_object` fires the hold or tap `TryInteraction` accordingly.

# Answer
You can have just one interface, an `IAction` or similar. Make `Lift` implement it. Then, inside your main `interactable_object` script, say

```
public IAction holdAction;
public IAction tapAction;

```

Now you can set the actions just by dragging the scripts into the main script, rather than setting them as extra components.
> 3 votes

# Answer
Since Alex F already covered tackling the two with a single interface, I'll show you one other trick, using the Unity Events system:

```
using UnityEngine;
using UnityEngine.Events;

public class InteractableObject : MonoBehaviour {

    public UnityEvent tapAction;
    public UnityEvent holdAction;

    // ...

    public void PerformTapAction() {
        if(tapAction != null) tapAction.Invoke();
    }

    // And so on for hold.

```

This will let you apply any public zero-argument function as the action to get called on tap / on hold, whether on the same object or a different one, via the Inspector. You can also wire up listeners via code, in which case you can access non-public methods too.

This makes things super flexible - you won't need to create or implement an extra interface for the interactions. You can even implement interactions that call into built-in type methods, without adding an extra type of your own to bridge your interaction system with the types from other developers.

But this can also be a double-edged sword - you can't guarantee anything else about the script that's being called (say, if you wanted to ask it for its preferred hold duration - it's not guaranteed to be a type that has such a quality or query). A chaos-minded Level designer could use this to do just about *anything* even if it goes outside your system design principles.

So, there are legitimate reasons why you might prefer an interface method, to enforce through your types more predictable relationships for how your game actions plug together, or support additional state & metadata in addition to just firing actions.

But if you want something simple and flexible to let your designers get up and running quickly, this is one way to do it. :)
> 3 votes

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


# Question
Title: Using Burst Compile attribute on methods
Can we use `BurstCompile` attribute without using any Jobs or ECS System in Unity? does adding `[BurstCompile]` attribute before methods bring us any benefits?

# Answer
> 2 votes
No. The burst compiled version of a method is called only by the job system. Regular C# scripting tasks you do in Unity without jobs will not benefit from the burst compile attribute.

---
Tags: unity, optimization
---


# Question
Title: How can I create procedurally placed points in an infinite world?
My issue is that I need to create consistently placed points in an open world. This means that optimally, I would have some function that takes an area as an input and outputs all the points that exist in that area. It would also be great if it was possible to specify the minimum distance between points.

Something like the following would be great:

What is a good way to achieve this?

# Answer
I managed to get a solution with the following function:

```
    public List<Vector3> GetPoints(Vector2Int center, Vector2Int size)
    {
        List<Vector3> points = new List<Vector3>();

        float probabilityScale = 0.2f;
        int gridDist = 150;
        string seed = "a";
        float noiseScale = 4000f;

        Vector2Int topLeft = center - new Vector2Int(size.x / 2, size.y / 2);
        Vector2Int topLeftGridAligned = new Vector2Int(topLeft.x - topLeft.x % gridDist, topLeft.y - topLeft.y % gridDist);

        for (int x = 0; x < size.x; x+= gridDist)
        {
            for (int y = 0; y < size.y; y+= gridDist)
            {
                Vector2 samplePoint = topLeftGridAligned + new Vector2Int(x, y);

                System.Random random = new System.Random((seed + samplePoint.x.ToString() + ":" + samplePoint.y.ToString()).GetHashCode());
                float noiseVal = Mathf.PerlinNoise(samplePoint.x/noiseScale, samplePoint.y/noiseScale);
                float randomNum = (float)random.NextDouble();
                if (randomNum < noiseVal * probabiltyScale)
                {
                    points.Add(new Vector3(samplePoint.x, 0, samplePoint.y));
                }
            }
        }
        return points;
    }

```

Notice that I am using the UnityEngine library containing the Vector2Int, Vector3 and Mathf classes. It works even when the center vector is moved around, consistently returning a location to either have a point or not have one.

In the future I will be adding jitter to the noise so it doesn't look as grid-aligned.
> 0 votes

# Answer
I don't have a complete answer for you but I have some things that may be useful.

**Blue noise** produces points that are "evenly spread" with some distance between them.

Typically an algorithm such as Poisson Disc will generate a set of blue noise points that have a given spacing. However, you want a *varying* spacing. For this you can use a blue noise algorithm that gives you a number (such as 0-255) at each pixel location. When that number is in a certain range, you place an object there. If your range is small (e.g. 0-1) you will get points with large spacing; if the range is large (e.g. 0-20) you will get points with small spacing. This technique is used for **dithering** images. The best article I've found for this is Christoph's precomputed blue noise, which includes downloadable textures with the output of the "void and cluster" algorithm.

Variants: 1 - if you need to place different kinds of objects with different spacing, and have them respect each others' positions, see multi-class poisson disk sampling; 2 - if you need to vary the density as you zoom in, see recursive wang tiles (video is cool!). Also worth a read: Casey Muratori's blog post The Nebraska Problem.

I don't have a complete answer for you, especially for an infinite world, but keywords *blue noise*, *dithering*, and *poisson disc* may help you find papers/algorithms for this.
> 3 votes

# Answer
What you want to do is take advantage of the fact that a pseudo-random number generator that uses a seed will reproduce the same "random" set of numbers every time. You can read a bit about them at https://en.wikipedia.org/wiki/Random\_seed

Given an area for input, find a way to create a seed from that area's information that gives you a unique seed for each area. It might be based on the area's coordinate for example.

Given a seed, when you want to generate your procedural points for the area you set the seed, and create your set of point coordinates from a sequence of random numbers made from the seed.

The only thing to be careful with is that you must use the random generator to generate your sequence the same time every time to ensure repeatability.

A nice twist of this is that you can have a "master seed" for your world that is used to generate each area seed. So given a "master seed", you can recreate an entire unique world in a reproduce-able way. I assume this is how Minecraft works with world seeds.

I just saw the image you uploaded, which sort of clarifies a few things. My answer isn't necessarily answering exactly how you will generate those points, but how you will ensure that procedurally generated points will be reproduceable every time you need to generate them.
> 2 votes

---
Tags: procedural-generation, procedural
---


# Question
Title: Unsupported API version on Spigot 1.14 snapshot
I'm (trying to) develop a plugin for Spigot Minecraft 1.14.2. I have tried putting both `api-version: 1.14.2` and `api-version: 1.14.2-R0.1-SNAPSHOT` in my `plugin.yml` file however it always comes up with the following error:

```
org.bukkit.plugin.InvalidPluginException: Unsupported API version 1.14.2-R0.1-SNAPSHOT
    at org.bukkit.craftbukkit.v1_14_R1.util.CraftMagicNumbers.checkSupported(CraftMagicNumbers.java:252) ~[spigot-1.14.2.jar:git-Spigot-df0eb25-649921e]
    at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:131) ~[spigot-1.14.2.jar:git-Spigot-df0eb25-649921e]
    at org.bukkit.plugin.SimplePluginManager.loadPlugin(SimplePluginManager.java:333) ~[spigot-1.14.2.jar:git-Spigot-df0eb25-649921e]
    at org.bukkit.plugin.SimplePluginManager.loadPlugins(SimplePluginManager.java:252) [spigot-1.14.2.jar:git-Spigot-df0eb25-649921e]
    at org.bukkit.craftbukkit.v1_14_R1.CraftServer.loadPlugins(CraftServer.java:347) [spigot-1.14.2.jar:git-Spigot-df0eb25-649921e]
    at org.bukkit.craftbukkit.v1_14_R1.CraftServer.reload(CraftServer.java:803) [spigot-1.14.2.jar:git-Spigot-df0eb25-649921e]
    at org.bukkit.Bukkit.reload(Bukkit.java:576) [spigot-1.14.2.jar:git-Spigot-df0eb25-649921e]
    at org.bukkit.command.defaults.ReloadCommand.execute(ReloadCommand.java:27) [spigot-1.14.2.jar:git-Spigot-df0eb25-649921e]
    at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:149) [spigot-1.14.2.jar:git-Spigot-df0eb25-649921e]
    at org.bukkit.craftbukkit.v1_14_R1.CraftServer.dispatchCommand(CraftServer.java:707) [spigot-1.14.2.jar:git-Spigot-df0eb25-649921e]
    at org.bukkit.craftbukkit.v1_14_R1.CraftServer.dispatchServerCommand(CraftServer.java:692) [spigot-1.14.2.jar:git-Spigot-df0eb25-649921e]
    at net.minecraft.server.v1_14_R1.DedicatedServer.handleCommandQueue(DedicatedServer.java:433) [spigot-1.14.2.jar:git-Spigot-df0eb25-649921e]
    at net.minecraft.server.v1_14_R1.DedicatedServer.b(DedicatedServer.java:397) [spigot-1.14.2.jar:git-Spigot-df0eb25-649921e]
    at net.minecraft.server.v1_14_R1.MinecraftServer.a(MinecraftServer.java:956) [spigot-1.14.2.jar:git-Spigot-df0eb25-649921e]
    at net.minecraft.server.v1_14_R1.MinecraftServer.run(MinecraftServer.java:801) [spigot-1.14.2.jar:git-Spigot-df0eb25-649921e]
    at java.lang.Thread.run(Thread.java:748) [?:1.8.0_212]

```

however I am using the correct API version. Whenever I change the `api-version` in `plugin.yml` the error message changes accordingly.

What have I done wrong?

EDIT: https://termbin.com/u5a8 \- full server log
plugin.yml:

```
name: choruschaos
main: com.cospox.choruschaos.main
version: 0.1
api-version: 1.14.2-R0.1-SNAPSHOT
commands:

```

main.java:

```
package com.cospox.choruschaos;

import org.bukkit.plugin.java.JavaPlugin;

public class main extends JavaPlugin {
    // Fired when plugin is first enabled
    @Override
    public void onEnable() {
    }
    // Fired when plugin is disabled
    @Override
    public void onDisable() {

    }
}

```

# Answer
Remove everything after 1.14, it should look like this:

```
api-version: 1.14

```

alternatively just remove it. It doesn't really serve any purpose right now.
> 0 votes

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


# Question
Title: How to parse User-defined types from String?
I am trying to save data about various entities in each Level in my game in a JSON file and load it at Runtime(Like a Scene file in Unity). I can save simple stuff like floats and ints and parse them back to with functions like std::stof. I can even handle stuff like a Vector3(3 floats).

Say, I want to save a User-type like *CollisionSystem* which resolves Collision between entities with a *ColliderComponent*. CollisionSystem does not contain any data and only Behaviour. How can I infer the Type from just the string and create an Object of *CollisionSystem*?

```
{
    "MovementSystem" : {},
    "RenderSystem" : {},
    "CollisionSystem" : {},
    "entities" : [
        {
            "PositionComponent" : {
                "x" : 10,
                "y" : 0,
                "z" : 10
            },
            "SpriteComponent" : {
                "source" : "\"assets/textures/Goblin.png\""
            },
            "ColliderComponent" : {}
        },
        {
            "PositionComponent" : {
                "x" : 0,
                "y" : 0,
                "z" : 30
            },
            "SpriteComponent" : {
                "source" : "\"assets/textures/Hero.png\""
            },
            "ColliderComponent" : {}
        }
    ]
}

```

The Brute Force method I could think of is a Switch case statement in the Parser like so:

```
System* GetSystem(string system_type)
{
    switch(system_type)
    {
        case "MovementSystem":
            return new MovementSystem();

        case "CollisionSystem"
            return new CollisionSystem();

        .
        .
        .

        default:
            return nullptr;
    }
}

```

which can be called like:

```
System* moveSystem = GetSystem("MovementSystem");
System* collisionSystem = GetSystem("CollisionSystem");

moveSystem->update();
collisionSystem->update();

```

However, I don't think it's the right way to do this. I am new to C++. So I might be missing some language features that might do this. Is there an elegant way to do this?

# Answer
> 0 votes
Since C++ doesn't support reflection like C# it's not possible to do this in an automatic way. At the end of the day you will need some form of a jump table that converts the string to a type.

To automate this process as much as possible and be less error prone, a common strategy is to use macros to mark classes and a global hash map with lambdas that does the transformation for you.

```
class SystemRegister
{
    public:
        using CreationFunction = System*(*)(); // the signature of a function that takes no arguments and returns a System pointer.

        // Simple way to have a global singleton object
        static SystemRegister& Instance()
        {
            static SystemRegister sys_register;
            return sys_register;
        }

        // This needs to return a value so we can use it outside of the scope of a function.
        // Without that the macro won't work.
        bool Register(const char* type_id, CreationFunction function)
        {
            m_creation_functions[type_id] = function;
            return true;
        }

        // This is the simplest form this method can have
        // Factory methods like this one should in return a std::unique_ptr (if you are using modern c++)
        // Additionally, you will probably have to add some asserts if the type_id doesn't exist in the map.
        System* Create(const char* type_id)
        {
            return m_creation_functions[type_id]();
        }

    private:
        // This map will do the transformation. Given a string it can return you a new object of the type.
        std::map<const char*, CreationFunction> m_creation_functions;
};

```

```
// With this macro you can register your systems in the map
// The bool is used as dummy value just to trick the compiler to allow this to be called outside of the scope of a function. (You can't call void functions on the global scope)
// registration##class_id will concatonate registration with the argument you pass to the macro ex. registrationCollisionSystem.
// #class_id will convert your argument to a c string. ex. "CollisionSystem"
// And finally the lambda will return a newly constructed class_id object as a System pointer.
#define REGISTER_CLASS(class_id) bool registration##class_id =\
                                 SystemRegister::Instance().Register(#class_id, []() -> System* { return new class_id; })

```

How to use:

.h
class CollisionSystem : public System
{
    ...
};

.cpp
REGISTER_CLASS(CollisionSystem);

void Foo()
{
    System* system = SystemRegister::Instance().Create("CollisionSystem");
}

```

---
Tags: c++, json
---


# Question
Title: Animation imported from Blender into Unity via FBX doesn't play?
I started building this model in Blender and gave it a simple animation that rotates the board about the axel.

...I exported it as FBX and imported it into Unity. I can see the animation is stored in the file when I import, but I can't find an animation file after I drop it in the scene, and there is no controller for the Animator controller it generated, either. I can watch the animation play in the FBX preview thumbnail but nowhere else.

How can I get my animation working?

# Answer
Let it be known to others who encounter this issue:

To access animations that are imported with a hierarchy of meshes, you need to go to the dope sheet and cllick "add animation". This will generate a default controller behind the scenes and allow you to use the animation(s) the asset came with.

It is possible, however, that the object on which the Animator and Animation Controller are set are not creating the same effect you saw in the preview (since you have to select the correct part manually). If you find yourself frustrated trying to figure out where to put the damn things, you can re-key generic transformations yourself for objects that are parents of all the objects you want transformed (in my case, this was the Axel).

Like they say, if you want something done right, do it yourself (again).

Here is my first attempt at making gifs of my project. The seesaw and treasurebox have different animation periods and my hardware sucks, so there are noticeable jumps where frames skip or the animation doesn't loop seamlessly. Because I edited in Photoshop, the colors are further optimized and not representative of the actual game.
> 0 votes

---
Tags: unity, animation, blender, assets, fbx
---


# Question
Title: Why does my machine render OpenGL using my onboard chipset instead of my graphics card?
I'm following an OpenGL tutorial series at opengl-tutorial.org, but have run into a problem:

The following lines:

```
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

```

cause my `glfwCreateWindow()` call to return null.

As I understand, this is caused by lack of support for OpenGL 3.3.

Why is my machine trying to render OpenGL 3.3 using my onboard graphics chipset (Intel HD Graphics 3000, which only supports OpenGL 3.1) instead of using my dedicated graphics card (GeForce 520M, which supports OpenGL 4.x)? I think this has something to do with power saving.

Note: I have newly updated nVidia drivers, installed as of yesterday. I know they are working because if I right-click my desktop I get a context menu for nVidia Control Panel.

Running OpenGL Extensions Viewer 4.x also displays that I'm using Intel HD Graphics 3000, supporting OpenGL \<= 3.1, which is consistent with my theory regarding power saving.

Regards,

# Answer
This is the NVidia manual to their Optimus, the driver which is responsible of switching between integrated GPU and NVidia GPU. From a quick look, it seems they describe how to set the default GPU for a program. I haven't tried it yet though.
> 5 votes

# Answer
For Windows and GLFW - You can compile glfw library by yourself and add to cmake **GLFW\_USE\_HYBRID\_HPG** option. More info here - Compiling GLFW
> 4 votes

# Answer
Going into the NVidia control panel by whatever method (From the"Change Default Graphics Processor" link on the "Run With Graphics Processor" menu is how I got there). This will give you the option to change the graphics processor per application:

Or globally:

For your particular case, I'd try adding a program setting for `cmake`, and, failing that, change the global setting.
> 1 votes

---
Tags: opengl, nvidia, glfw, intel
---


title: Destructible tiles in unity's tilemap

text:
# Question
Title: Destructible tiles in unity's tilemap
I'm creating a 2d game and I want to make it so that tiles are destructible whenever a projectile collides with a tile, the problem is I don't know how to get the tile that the projectile is colliding with, I would like to make it so that it area of damage.

However for now I want to make it so that once the projectile reaches the ground it destroys the tile it's sitting on I've made a collider2d to help me with that but I still have no idea how to get the tile that's the projectile is sitting on.

```
IEnumerator OnCollisionEnter2D(Collision2D x)
    {
    Vector2 hit = gameObject.transform.position;
    Debug.Log("y" + hit.y);
    hit.y =- 3; // What y should i put here in order to make sure its the same as the tile the projectile is sitting on
        if (x.gameObject.tag != "Player")
        {
        Collider2D[] collidedwith = Physics2D.OverlapCircleAll(this.gameObject.transform.position, radius);
        tilemap.SetTile(tilemap.WorldToCell(hit), null);
    }

```

A screenshot for better explanation (I would like to get rid of the blue tile):

# Answer
Have you considered using the contactpoint2d? It gives you information about the contact point where the collision occurred. Here is a demo code grabbed from 2D tech demo on tilemap.

```
void OnCollisionEnter2D(Collision2D collision)
{
    Vector3 hitPosition = Vector3.zero;
    foreach (ContactPoint2D hit in collision.contacts)
    {
       hitPosition.x = hit.point.x - 0.01f * hit.normal.x;
       hitPosition.y = hit.point.y - 0.01f * hit.normal.y;
       tilemap.SetTile(tilemap.WorldToCell(hitPosition), null);
    }
}

```
> 3 votes

# Answer
ok so i solved it by using shuvro's code along with some stuff added in

```
 Tilemap tilemap = GetComponent<Tilemap>();
        Vector3 hitPosition = Vector3.zero;
        foreach (ContactPoint2D hit in collision.contacts)
        {
            Debug.Log(hit.point);
            hitPosition.x = hit.point.x - 0.1f;
            hitPosition.y = hit.point.y - 0.1f ;
            Vector3Int cell = new Vector3Int((int)hitPosition.x, (int)hitPosition.y, 0);

            tilemap.SetTile(tilemap.WorldToCell(hitPosition), null);
        }

```
> 2 votes

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


# Question
Title: Non monobehaviour classes not working properly
I am trying to make a deck of cards in c# for use in Unity. But when i planned it I didn't think that 'Deck.cs' or 'Card.cs' would need to inherit from Monobehaviour.

I have written 3 classes (one is a Monobehaviour, 'Table.cs'). I thought these would work to make a pack of 52 cards.

I get a null reference exception when I try to access the specific card from the Debug.Log line.

Here are the three classes. (I wonder if I am using the 'new' keyword properly)

(Also Table.cs is the monobehaviour and is attached to a Cube called Table in my game scene. There are no other objects or components in the scene besides the default Light and Camera)

```
 using UnityEngine;

public class Table : MonoBehaviour
{
Deck deck;

private void Start()
{
    deck = new Deck();
    Debug.Log("card 9 = " + deck.cards[9].value);

}
}

```

and

```
public class Deck
{
public Card[] cards;

public Deck()
{
    cards = new Card[52];
    for (int suit = 0; suit < 4; suit++)
    {
        for (int val = 0; val < 14; val++)
        {
            Card c = new Card((Card.Suit)suit, val);
        }
    }
}
}

```

and

```
 public class Card
{
public enum Suit { HEARTS = 0, DIAMONDS = 1, SPADES = 2, CLUBS = 3 };
public Suit suit;
public int value;

public Card(Suit Suit, int Value)
{
    suit = Suit;
    value = Value;
}

}

```

The error i get is this: NullReferenceException: Object reference not set to an instance of an object Table.Start () (at Assets/Scripts/Table.cs:12)

And also I first made Card a struct and that doesn't give me the error, but for some reason all the cards remain as HEARTS and value 0 .

Anybody see what I have done wrong? Any help would be great. Thanks!

# Answer
> 3 votes
I'm not sure what would lead you to believe this has anything to do with `MonoBehaviour` or not. You just never actually put any cards in your deck, so of course your deck is full of `null`s when you try to read cards from it. (Or full of `default(Card)`s when using `struct`, the default being the zero of hearts)

You're missing an assignment to store the card `c` into your `cards` array, like this:

```
public Deck()
{
    cards = new Card[52];

    int index = 0;
    for (int suit = 0; suit < 4; suit++)
    {
        for (int val = 1; val <= 13; val++)
        {
            Card c = new Card((Card.Suit)suit, val);

            cards[index++] = c;
        }
    }
}

```

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


# Question
Title: Pathfinding with direction considerations
Consider the following road network. The car (orange) needs to get to the red circle. It drives on the right hand side of the road and is initially facing down.

The shortest path is the blue one. But if it follows this path, it reaches the red circle on the wrong side of the road. To actually get to the red circle, it needs to take the green path - much longer. The pink dots represent the nodes - the road network is made up of modular road pieces. Each node also stores all the possible directions a vehicle could take from that piece.

How can I make a pathfinding algorithm that takes this into consideration?

# Answer
> 0 votes
Each purple dot in your image will be represented by multiple nodes in the graph. Each graph-node will not only represent the car's position, but also the direction it came from.

# Answer
> 0 votes
I would use filtering. For example you can assign a filter to the car lest say a bitmask, then you can assign filter to cells (assuming it is a grid system).

When you run your ASTAR (assuming it is an astar) you can calculate cell cost or passibility by the filter masks - for example if the car has right filter mask then all the left filter masked cells will become impassible.

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


# Question
Title: Possible patterns for Registering event listeners of game entities with an event queue
I'm trying to integrate the idea of an event queue with a game loop that creates entities and responds to input. Is it better practice to submit entity reaction functions to the queue during input processing, or is there a way to generically broadcast events like text submission to the event queue? What would the class structures of entity and event queue look like to support the latter?

Specifically I'm looking for a response that includes code (any language) or pseudo code. Similar answers lack the specificity I need to make sense of how fields on the structs or classes enable registration of listeners, broadcasting, and handling of events.

# Answer
> 1 votes
This question was given attention on a discord server and several very helpful blocks of rust code were provided.

The most important to me was seeing in code the creation of an event listener function. In rust the following closure was provided by azrael in the amethyst discord server.

```
let player_entity = unimplemented!("fill this in");
let my_event_listener = |world: &mut World, event: &InputEvent| {
    if event.attack_pressed {
        let players = world.write_storage<Player>();
        let mut player_component = players.get_mut(player_entity).unwrap();
        player_component.set_state(Attacking);
    }
}

```

here we demonstrate a even listener that has the ability to change the player entity to indicate its new state after the event for an attack button getting pressed is triggered.

the event listener would go in a collection separate to the event queue (i suspect you want to add/remove the event listeners separately)

now a demonstration of the actual connection of events to listeners is demonstrated. The events variable would be populated in input processing or game state changes, and then shared with each listener that we iterate over in the bottom of the game loop.

```
loop {
    // receive events from windowing system, and perhaps other system.
    let events = // ...
    // these may also be inserted into the world, and maybe the ECS systems also add more events.

    // run systems
    dispatcher.update(&mut world)

    // event listeners
    for event_listener in event_listeners.iter() {
        event_listener(world, events);
    }
}

```

All in all, this represents one concrete pattern for registering listeners with an event queue.

---
Tags: architecture, design-patterns, events
---


# Question
Title: Ordering a List doesn´t work. - InvalidOperationException: Operation is not valid due to the current state of the object
I have this method. It´s for ordering actors and only displaying the ones which are in direct line of sight with the player.

```
public Actor OrderActorListByDistance(List<Actor> list, Vector2 pos)
{
    return list.FindAll(d => Physics2D.Linecast(d.transform.position, pos, LayerMask.GetMask("Default")).collider == null).OrderBy(i => Vector2.Distance(pos, i.transform.position)).First();
}

```

But that Method throws that error **InvalidOperationException: Operation is not valid due to the current state of the object**

I already made a lot of google research but I couldn´t find any solution. I would appreciate any suggestion or help. Thanks in advance

# Answer
> 1 votes
My guess is the use of `.First()` at the end there is the problem. That method will return the first element in the collection it is called on, but will throw an InvalidOperationException if the collection is empty, which is probably going to be the case at least some times.

Basically, change `First` to `FirstOrDefault` and make sure that the calling code can handle a null return value.

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


# Question
Title: How can I draw an animated vector field on a map?
I want to render an animated vector field map similar to this wind speed visualization. How can I do this?

# Answer
I'm assuming you want to build this without the aid of a readily-available rendering engine. I'd conceptually de-couple the end-result using multi-layer rendering, like this:

1. **Map image texture layer**

it's only purpose is to handle the drawing of the map, without any special effects
2. **Vector animation layer**

this layer renders the animation (real-time or pre-constructed)

Then, you want an orchestrator to merge the two layers and manage codependant parameters like size, speed etc. The output of the orchestrator (given a base image for the first layer, a vector animation for the second layer, a **timelapse** value and a **delta** time point within the lapse) should be the animated image sampled at time point **delta** (**delta** belongs to **\[0, timelapse\]**). Then, a higher level rendering system draws the sampled animation on/off screen.

You can either use a real-time animation that contains all the sprite data (probably an array of **\[start and end coordinates, bezier curve data\]** for each sprite) and interpolate with a given delta time for all elements of the array, or have the animation pre-built and simply merge the two layers.

edit: As I see from the animated image you posted, some sprites last longer than others. In this case, for the model described above, the vector animation consists of an array of **{ startXY, endXY, timelapse, curveData }** for each sprite. When sampled at a timepoint **delta**, if the current element's timelapse \< delta, skip drawing it. Also, if you want transparency (i.e. a fade in and out effect) you could set the current sprite's transparency to **delta / timelapse**.
> 1 votes

---
Tags: animation, vector, maps, graphic-effects
---


# Question
Title: Can I use HL2 Assets in my free Godot game?
I couldn't find some good textures for my Godot game, so I am looking forward using Half-Life 2 assets. I have HL2 in my library on Steam.

Can I use those assets in my game?

# Answer
> 1 votes
No, it is protected by copyright. The way games like Garry's mod get over this is by requiring you to have the game to use the assets

---
Tags: copyright
---


# Question
Title: Why are there weird texture artifacts in baked light which don't appear with realtime light?
This is the comparison of the same scene, realtime light vs baked light.

What's am I wrong ?

EDIT: In particular, also texture are low quality (see image 2). Why ?

# Answer
I solved: what I miss was not to follow this:

"Make sure any Mesh you want to apply a light map to has proper UVs for lightmapping. The easiest way to do this is to open the Mesh import settings and enable the Generate Lightmap UVs setting."

enter link description here
> 2 votes

---
Tags: unity, lighting
---


# Question
Title: how to instantiate a component in a game object controlling by a variable bolean? unity
I have this script

```
public HingeJoint hide;
public bool ver;
// Start is called before the first frame update
void Start()
{
    hide = GetComponent<HingeJoint>();
}

// Update is called once per frame
void Update()
{
    if (ver)
    {
        Destroy(hide);
    }

}

```

I can destroy the component but I need to re-instantiate the component

# Answer
You can do

```
hide = gameObject.AddComponent<HingeJoint>();

```
> 3 votes

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


title: smooth look at only on x and y

text:
# Question
Title: smooth look at only on x and y
i'm using the script down below to make my camera look at mouse x and y position, and it has a limitation for my camera rotation.the problem is the way my camera rotates is not smooth at all.is there any way to make it smoothly look at position on x and y?

```
    rotationX += Input.GetAxis("Mouse X") * sensitivityX;

    rotationX = Mathf.Clamp(rotationX, minimumX, maximumX);

    rotationY += Input.GetAxis("Mouse Y") * sensitivityY ;

    rotationY = Mathf.Clamp(rotationY, minimumY, maximumY);

    transform.localEulerAngles = new Vector3(-rotationY , rotationX, 0);

```

# Answer
You are rotating it on a fixed time step. Unity's `Update` method (which I assume you are using) uses a variable time step. This means you have two options:

Normally you would perform your physics update in `FixedUpdate`, but input does not work in `FixedUpdate`. This means you need to multiply by your time step, AKA the duration of the previous frame. Your new code would look like such:

```
private void Update()
{
    rotationX += Input.GetAxis("Mouse X") * sensitivityX * Time.deltaTime;
    rotationX = Mathf.Clamp(rotationX, minimumX, maximumX);
    rotationY += Input.GetAxis("Mouse Y") * sensitivityY * Time.deltaTime;
    rotationY = Mathf.Clamp(rotationY, minimumY, maximumY);
    transform.localEulerAngles = new Vector3(-rotationY , rotationX, 0);
}

```

With this new code, you will also need to increase your sensitivity variables.
> 0 votes

---
Tags: unity, camera, rotate
---


title: Predict Time of projectile flight

text:
# Question
Title: Predict Time of projectile flight
I am trying to matemathically predict how long will projectile fly until it reach the target. I am trying to implement this formula:

**t = \[V * sin(α) + √(V * sin(α))² + 2 * g * h)\] / g**

where I know V (velocity of projectile) , α (angle of launch) , h (height of launch) The problem is it shows some weird results. I am not sure what is wrong (using ue4):

```
float Time = Velocity * FMath::Sin(AngleDeg) + FMath::Sqrt(FMath::Square(Velocity * FMath::Sin(AngleDeg)) + (2.f * Gravity * Height));
Time /= Gravity;

```

For example this test inputs: Gravity = 9.8; Height = 10; Velocity = 10; AngleDeg = 10; shows 0.97 seconds but theresult should be 1.61 according this calculator: https://www.omnicalculator.com/physics/projectile-motion ... When I try different inputs the result is always wrong... I also got the formula from this website so not sure what's wrong. Thanks for any advice

# Answer
Given that you have **velocity** and **angle**, you can calculate \\$v\_x\\$ and \\$v\_y\\$.
You dont need \\$v\_x\\$ though.

$$v\_y = v \cdot sin \space \alpha $$

**Make sure that you use the right units. If `Sin` accept radians, don't pass degrees there.**

Then, using \\$v\_y\\$, \\$h\\$ and \\$a\\$, you calculate flight time. You need to solve the equation:

$${at^2 \over 2} + v\_yt + h = 0$$

Check your \\$Y\\$ axis. I assume that it goes up. **So acceleration is negative. If you have \\$g \> 0\\$, then you should have \\$a=-g\\$**.

$$t\_1, t\_2 = {-v\_y \pm \sqrt {{v\_y^2} - 2ah} \over a}$$

Omit the negative root and you get

$$t = {-v\_y - \sqrt {{v\_y^2} - 2ah} \over a} = {v\_y + \sqrt {{v\_y^2} + 2gh} \over g}$$

It works:

If you fire from negative heights, be ready to get 2 positive roots, 2 negative roots or no roots at all.
> 1 votes

---
Tags: mathematics
---


# Question
Title: Tiling texture doesn't repeat, even though wrap mode is set to repeat
For some reason, my floor tiling (set to 100 x 100) only shows on one corner of the plane. Past that corner, it just stretches out to the sides and leaves the middle one solid colour:

Here is how I've imported the texture (which was created by Jimmy Vegas:

And my material settings look like this:

# Answer
> 2 votes
I fixed it, I just simply re installed the texture and deleted the material and started it all over again and now it looks like it should!

---
Tags: unity, textures
---


# Question
Title: Custom FPS Controller in Unity 5.6.6f2 not letting me look up or down
Due to the FPS Controller seeming to be broken in Unity now, I started using a custom one by kinifi on GitHub. For some reason though I can't look up or down. I removed the Main Camera so it should of fixed it but no. Is there anything I can change in this script to allow me to look up and down.

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

[RequireComponent(typeof(Rigidbody))]
public class FPS : MonoBehaviour
{

    private float speed = 5.0f;
    private float m_MovX;
    private float m_MovY;
    private Vector3 m_moveHorizontal;
    private Vector3 m_movVertical;
    private Vector3 m_velocity;
    private Rigidbody m_Rigid;
    private float m_yRot;
    private float m_xRot;
    private Vector3 m_rotation;
    private Vector3 m_cameraRotation;
    private float m_lookSensitivity = 3.0f;
    private bool m_cursorIsLocked = true;

    [Header("The Camera the player looks through")]
    public Camera m_Camera;

    // Use this for initialization
    private void Start()
    {
        m_Rigid = GetComponent<Rigidbody>();
    }

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

        m_MovX = Input.GetAxis("Horizontal");
        m_MovY = Input.GetAxis("Vertical");

        m_moveHorizontal = transform.right * m_MovX;
        m_movVertical = transform.forward * m_MovY;

        m_velocity = (m_moveHorizontal + m_movVertical).normalized * speed;

        //mouse movement
        m_yRot = Input.GetAxisRaw("Mouse X");
        m_rotation = new Vector3(0, m_yRot, 0) * m_lookSensitivity;

        m_xRot = Input.GetAxisRaw("Mouse Y");
        m_cameraRotation = new Vector3(m_xRot, 0, 0) * m_lookSensitivity;

        //apply camera rotation

        //move the actual player here
        if (m_velocity != Vector3.zero)
        {
            m_Rigid.MovePosition(m_Rigid.position + m_velocity * Time.fixedDeltaTime);
        }

        if (m_rotation != Vector3.zero)
        {
            //rotate the camera of the player
            m_Rigid.MoveRotation(m_Rigid.rotation * Quaternion.Euler(m_rotation));
        }

        if (m_Camera != null)
        {
            //negate this value so it rotates like a FPS not like a plane
            m_Camera.transform.Rotate(-m_cameraRotation);
        }

        InternalLockUpdate();

    }

    //controls the locking and unlocking of the mouse
    private void InternalLockUpdate()
    {
        if (Input.GetKeyUp(KeyCode.Escape))
        {
            m_cursorIsLocked = false;
        }
        else if (Input.GetMouseButtonUp(0))
        {
            m_cursorIsLocked = true;
        }

        if (m_cursorIsLocked)
        {
            UnlockCursor();
        }
        else if (!m_cursorIsLocked)
        {
            LockCursor();
        }
    }

    private void UnlockCursor()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    private void LockCursor()
    {
        Cursor.lockState = CursorLockMode.None;
        Cursor.visible = true;
    }

}

```

# Answer
Assign a camera object to the `m_Camera` variable so that the script knows which camera you want to rotate.

When `m_Camera` is null, this script silently skips over the vertical camera movement code to avoid triggering a null reference exception.

Since this variable is public, it should show up as a "Camera" slot you can edit in the Unity Inspector for this script. Drag a camera object into that slot, or click the circle next to it to choose an available camera from a list.
> 0 votes

# Answer
I no longer use the kinifi controller, I just tried using Standard Assets again and it worked!
> -2 votes

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


# Question
Title: Texture with transparency not rendered correctly in LibGDX
The title might be a bit misleading but I'm having a hard time to explain the problem so I'll try with pictures:

Same tree from opposite site:

I'm trying to create a voxel game and at the moment I try to get textures with transparency working. The mesh is generated for each chunk individually so that every chunk has its own ModelInstance that is rendered.

And the result should be like in the second picture (almost) so that every block is rendered behind the transparent textures but thats not the case for every side.

The relevant code for the transparent textures:

```
        Mesh mesh = new Mesh(true, meshDataBlended.sizeEstimate, (int)Math.round(meshDataBlended.sizeEstimate * 1.5),
            new VertexAttribute(VertexAttributes.Usage.Position, 3, ShaderProgram.POSITION_ATTRIBUTE),
            new VertexAttribute(VertexAttributes.Usage.Normal, 3, ShaderProgram.NORMAL_ATTRIBUTE),
            new VertexAttribute(VertexAttributes.Usage.TextureCoordinates, 2, ShaderProgram.TEXCOORD_ATTRIBUTE + "0"));

        BlendingAttribute blendingAttribute = new BlendingAttribute();
        blendingAttribute.blended = false;
        blendingAttribute.sourceFunction = GL20.GL_SRC_ALPHA;
        blendingAttribute.destFunction = GL20.GL_ONE_MINUS_SRC_ALPHA;

        mesh.setVertices(meshDataBlended.vertices);
        mesh.setIndices(meshDataBlended.indices);

        Node terrainNode = modelBuilder.node();
        terrainNode.id = "terrain_blended";

        modelBuilder.part(
                "terrain_blended", mesh, GL20.GL_TRIANGLES,
                new Material(TextureAttribute.createDiffuse(World.TEXTURE), blendingAttribute)
        );

```

I'm pretty new to OpenGL, so I'm totally lost with this problem. No idea why it behaves like this and I even don't know where I could find the needed informations. So far i just know that it depends on what is rendered first (that's why it works from one side but not the opposite side) Sorry for using Minecraft textures it's just for testing purposes.

Let me know if some additional information is needed I'll add them then.

Thanks Blakk

EDIT: setting blended to true will make everything visible behind the leaves except other leaves (still only from specific sides).

# Answer
Solved the problem by writing my own shader which now renders the mesh with the transparent textures.

Fragment shader:

```
#ifdef GL_ES
precision mediump float;
#endif
varying vec2 v_texCoords;
uniform sampler2D u_texture;

void main() {

    vec4 texel = texture(u_texture, v_texCoords);
    if (texel.a < 0.5) {
        discard;
    }

    gl_FragColor = texel;
}

```

Render function:

```
public void render(ShaderProgram solidShader, ShaderProgram transparentShader) {
    Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
    Gdx.gl.glEnable(GL20.GL_CULL_FACE);
    World.TEXTURE.bind();

    //Render transparent mesh
    renderMesh(transparentShader, transparentMesh);

    //Render solid mesh
    renderMesh(solidShader, solidMesh);

    Gdx.gl.glDisable(GL20.GL_DEPTH_TEST);
    Gdx.gl.glDisable(GL20.GL_CULL_FACE);
}

private void renderMesh(ShaderProgram shader, Mesh mesh) {
    if (mesh != null) {
        shader.begin();
        shader.setUniformMatrix("u_projTrans", Game.getPlayer().getCamera().combined);
        shader.setUniformi("u_texture", 0);
        mesh.render(shader, GL20.GL_TRIANGLES);
        shader.end();
    }
}

```

I hope this will help someone in the future (:
> 1 votes

---
Tags: opengl, java, libgdx, voxels, blending
---


# Question
Title: Unity2D: Avoid attack animation looping during combo
I am trying to implement a combo system in my Unity project. I started with a coroutine to call a single attack and it goes relatively smoothly, the problem occurs when I try to modify said coroutine in order to open a time interval in which the player has the chance to click again in order to perform the second attack of the combo, the animation of the first attack keeps looping for the whole duration of the coroutine, unless I manage to connect the second attack, in that case the second animation gets triggered without any problems. Here is the concerned script:

```
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityStandardAssets.CrossPlatformInput;
    using UnityEngine.SceneManagement;

    public enum PlayerState {
        walk,
        attack,
        interact,
        dash,
        stagger
    }

    public class Player_Base : MonoBehaviour {

        //Basic parameters
        Rigidbody2D myRigidBody;
        public static Transform playerPos;
        public PlayerState currentState;
        Animator myAnimator;
        public HealthManager myStatus;
        private bool isAlive = true;

        //Movement parameters
        [SerializeField] float moveSpeed = 3f;
        public Vector2 moveInput;
        private bool isMoving;

        //Combat parameters
        private int comboCounter = 0;
        private float comboTimer = 0;

        // Use this for initialization
        void Start()
        {
            currentState = PlayerState.walk;//Initial default state of the player
            myRigidBody = GetComponent<Rigidbody2D>();
            myAnimator = GetComponent<Animator>();
            myAnimator.SetFloat("MoveX", 0);
            myAnimator.SetFloat("MoveY", -1);
            myStatus = GameObject.FindObjectOfType<HealthManager>();
        }

        // Update is called once per frame
        void Update()
        {
            moveInput = Vector2.zero;
            moveInput.x = Input.GetAxisRaw("Horizontal");
            moveInput.y = Input.GetAxisRaw("Vertical");
            if (!isAlive)
            {
                return;
            }
            else {
                if (currentState == PlayerState.walk)           {
                    if (moveInput != Vector2.zero)
                    {
                        Move();
                        myAnimator.SetFloat("MoveX", moveInput.x);
                        myAnimator.SetFloat("MoveY", moveInput.y);
                        myAnimator.SetBool("isMoving", true);
                    }
                    else {
                        myAnimator.SetBool("isMoving", false);
                    }
                }

                if (Input.GetKeyDown(KeyCode.Mouse0) && currentState != PlayerState.attack)//second clause because i do not want to indefinitely attack every frame
                {
                    StartCoroutine(FirstAttack());
                }
        }

        public void Move()
        {
            moveInput.Normalize();
            myRigidBody.MovePosition(myRigidBody.position + moveInput * moveSpeed * Time.deltaTime);
            //If i want to work with the velocity vector: i have to use rb.velocity, not just taking the xplatinput times movespeed
        }

        public void MoveOnAnimation(int xMove, int yMove, float displacement)
        {
            moveInput.x = xMove;
            moveInput.y = yMove;
            moveInput.Normalize();
            myRigidBody.MovePosition(myRigidBody.position + moveInput * displacement * Time.deltaTime);
        }

        private IEnumerator FirstAttack() {

            //Start Attack
            comboCounter = 1;
            myAnimator.SetInteger("comboSequence", comboCounter);
            currentState = PlayerState.attack;

            yield return new WaitForSeconds(AttackTemplate.SetDuration(2f) - comboTimer);
            comboTimer = AttackTemplate.SetComboTimer(1.5f);
            //Interval for combo chain
                while (comboTimer >= 0)
            {

                comboTimer -= Time.deltaTime;
                if (Input.GetKeyDown(KeyCode.Mouse0))
                {
                    Debug.Log("Chained");
                    StartCoroutine(SecondAttack());
                    StopCoroutine(FirstAttack());
                }
                yield return null;
            }
//Combo not triggered
            comboCounter = 0;
            myAnimator.SetInteger("comboSequence", comboCounter);
            //yield return new WaitForSeconds(AttackTemplate.SetDuration(1f));
            currentState = PlayerState.walk;

        }

        private IEnumerator SecondAttack()
        {

            comboCounter = 2;
            myAnimator.SetInteger("comboSequence", comboCounter);
            currentState = PlayerState.attack;
            yield return null;

            //if combo not triggered:
            yield return new WaitForSeconds(AttackTemplate.SetDuration(1f));
            comboCounter = 0;
            myAnimator.SetInteger("comboSequence", comboCounter);

            currentState = PlayerState.walk;

        }

    }

```

The coroutine `SecondAttack()` keeps the logic for the single attack, whereas `FirstAttack()` has a while loop that simply reduces the time interval and eventually starts the second attack. I have noticed that in the animator window the transition towards the first attack animation keeps reactivating, as if constantly checking the value of the parameter that triggers it.

Has this happened to anybody else? All kinds of hints will be very much appreciated and sorry if my script is not too tidy!

# Answer
You'll have to forgive me for using the answer field for a less than totally certain answer -- but the coroutine `FirstAttack` looks like its logic shouldn't repeat, so if you're getting the animation looping, what are the conditions in your animator for the animation to run?

As it stands, when `FirstAttack` begins it sets combo to 1 and state to attack. This does not change until the attack either times out or combo changes to 2 which triggers the new attack.

How are the attacks triggered in the animator? If the only condition for the first attack is that combo is 1 -- which remains true for the entire duration -- then it will loop. Have you ensured the wrap mode / play mode is set to 'play once' and not to loop?
> 1 votes

---
Tags: unity, animation, mecanim, combat
---


# Question
Title: How to calculate IsGrounded more effective?
```
    if (SimpleInput.GetButtonDown(jumpButton) && IsGrounded())
    {
        rb.AddForce(0f, 8f, 0f, ForceMode.Impulse);
    }

bool IsGrounded()
    {
        return Physics.CheckCapsule(Char_Collider.bounds.center, new Vector3(Char_Collider.bounds.center.x, Char_Collider.bounds.min.y, Char_Collider.bounds.center.z), Char_Collider.radius * 0.27f, GroundLayers);
    }

```

I've multiplied `Char_Collider.radius` with 0.27f 'cause in the tutorial that guy said `You need to multiply this with %90 of your character's actual size` **That might be the problem** because i don't actually know my character's size, i've made it in blender and scaled it down at the unity.

So if you look at the inspector panel you'll see it's `0.1 0.1 0.1` but it's actually not. I tried to spawn a cube and match them together roughly, cube's size was `0.3 1.2 0.3`, that's way the number is 0.27f 'cause i just simply calculated it with the 0.3.

And finally my problem is:

I get return values from IsGrounded **delayed**, sometimes doesn't even get a value. Like example when i jump, sometimes it returns the value of `IsGrounded False` when i'm just about the hit the ground, and sometimes it doesn't returns the value of `IsGrounded False`. Because of this i can't make jump animation properly.

This is my HandleAnimation() method (I call that from FixedUpdate()):

```
void HandleAnimation()
{
    if (!IsGrounded())
    {
        anim.SetBool("Jumping", true);
    }
    else
    {
        anim.SetBool("Jumping", false);
    }
}

```

And this is my animator:

I am also adding those because sometimes when IsGrounded() returns false, animation doesn't works.

# Answer
According to my tests and researches my problem isn't the **IsGrounded** or **raycasting**, it's my jumpButton! I'll post an another question about that and link it to here if you guys want to check out.

So this IsGrounded() method is fine you can try it if this is your problem. Just make sure when multiplying `Char_Collider.radius with 0.27f`, You need to multiply it with your character's **Actual Size** not the `Collider's Size`.
> 0 votes

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


# Question
Title: How can I create a reverb zone depending on audio source location instead of the listener's position?
Is there a way to make a reverb zone act on an audio source not on the audio listener? Or in other words: Is there a way to apply an audio filter gradually depending on a position in space?

Let's say I have three objects: A plane with a reverb zone attached (some echo-effect), a movable sphere with an audio source and a player character with an audio listener. If I use the player character to push the sphere onto the plane the audio will be echoed, but as soon as the player leaves the plane the audio loses it's effect, because the listener left the zone. Is there any way to make the zone act on the source, not the listener?

# Answer
> 0 votes
My solution looks like this. I created an audiomixer with the effects that I want to apply and some 3D-shape as trigger (a cube for example). To this trigger I add the following script, which allows to attach the audiomixer to the trigger. As soon as any object with an audio-source component enters the trigger the audio of the object will be fed into the audiomixer.

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

public class AddAudioMixer : MonoBehaviour
{

    public AudioMixerGroup audioMixer;

    void OnTriggerEnter (Collider other)
    {
        if (other.gameObject.GetComponent<AudioSource>() != null){
            AudioSource compAudio;
            compAudio = other.gameObject.GetComponent<AudioSource>();
            compAudio.outputAudioMixerGroup = audioMixer;
        } else {
            Debug.Log("No Audiosource on this Component");
        }
    }

    void OnTriggerExit (Collider other)
    {
        if (other.gameObject.GetComponent<AudioSource>() != null){
            AudioSource compAudio;
            compAudio = other.gameObject.GetComponent<AudioSource>();
            compAudio.outputAudioMixerGroup = null;
        } else {
            Debug.Log("No Audiosource on this Component");
        }
    }

    // Start is called before the first frame update
    void Start()
    {

    }

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

    }
}

```

---
Tags: unity, audio
---


title: how to clamp the look at function?

text:
# Question
Title: how to clamp the look at function?
how can i look at a target on 2 axis but clamp the the object's rotation ,to only rotate from -45 to 45 on x and from -60 to 60 on y axis. i used this script to look at target and clamp the rotation, but it's not working right ): there is no problem with maximum value but whenever the rotation is about to become zero or a negative value the wired problem will show up. i made a gif here (http://www.mediafire.com/view/55phgr5qrhy8fk1/record.gif)

```
public Transform target;
public float speed;

public float minimumX;
public float maximumX;

public float minimumY;
public float maximumY;
// Start is called before the first frame update
void Start()
{

}

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

    Quaternion OriginalRot = transform.rotation;
    transform.LookAt(target);
    Quaternion NewRot = transform.rotation;
    transform.rotation = OriginalRot;
    transform.rotation = Quaternion.Lerp(transform.rotation, NewRot, speed * Time.deltaTime);

    transform.eulerAngles = new Vector3(Mathf.Clamp(transform.eulerAngles.x, minimumX, maximumX), Mathf.Clamp(transform.eulerAngles.y, minimumY, maximumY), 0);

}

```

}

# Answer
> 1 votes
My guess that `eulerAngles` returns angle from 0 to 360, so "-1" is 359 and is clamped to `maximumY`.

Try this:

```
float ry = transform.eulerAngles.y;
if (ry >= 180) ry -= 360;
transform.eulerAngles = new Vector3 (
    Mathf.Clamp(transform.eulerAngles.x, minimumX, maximumX),
    Mathf.Clamp(ry, minimumY, maximumY),
    0
);

```

---
Tags: unity, rotation
---


# Question
Title: How can I automatically pause my timeline at a specific time code?
I want to setup a way that the timeline will pause at a particular time/frame. I have tried this, and it doesn't work:

```
public PlayableDirector playableDirector;
void Update() {
    if (playableDirector.time == 4f)
        playableDirector.pause();
}

```

Also, is it alright to leave this in the update method?

# Answer
The variable `playableDirector.time` is rarely going to be *exactly* 4.00000f. It's a floting point value, so it will usually be slightly off. Your update might get called at time 3.99215f and then again at time 4.01721f.

That's why you should generally never check `float` values for equality. You should only check them for being larger or smaller than another value.

What you can do instead is check if the time *just passed* the 4f second mark. In order to do that you need to keep track of the previous time.

```
public PlayableDirector playableDirector;
private float lastTime;

void Update() {
    if (playableDirector.time >= 4f && lastTime < 4f ) {
         playableDirector.pause();
    }
    lastTime = playableDirector.time
}

```

There are two edge-case this code won't handle: If your timeline is looping and your break-point is very close to the beginning or very close to the end of the timeline, this code might not work reliably because `playableDirector.time` will be smaller than `lastTime` during the first update of each loop. If these two edge-case are relevant for your particular case, then this slightly more complicated code should handle it:

```
public PlayableDirector playableDirector;
private float lastTime;

void Update() {
    if ( (playableDirector.time >= 4f && lastTime < 4f ) || // usual case
         (lastTime > playableDirector.time && lastTime < 4f ) || // breakpoint was after last update in timeline
         (lastTime > playableDirector.time && playableDirector.time >= 4f) ) // breakpoint before first update in timeline
    {
         playableDirector.pause();
    }
    lastTime = playableDirector.time
}

```
> 1 votes

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


# Question
Title: How can I change a materials properties in my Unity c# code?
Hello everyone I want to change my materials tiling offset in code, but the only way I found to access it other than drag-dropping to a public field in inspector is to check by name. But I then noticed the name is suffixed with ' (Instance)' .

So it seems a little odd to me having to access it this way, is there another way that I don't know about?

```
foreach(Material m in GetComponent<MeshRenderer>().materials)
{
    if (m.name == "card_front (Instance)")
    {
        m.mainTextureOffset = new Vector2(value * 1/13f, (int)suit * 1/5f);
    }
}

```

# Answer
> 1 votes
If you know the order of the materials you can just access the materials list like an array, if you only have one you can always use `[0]`. For example:

```
GetComponent<MeshRenderer>().materials[?].mainTextureOffset = new Vector2(value * 1/13f, (int)suit * 1/5f);

```

You also don't necessarily need to worry about the `(instance)` in the name if you use .StartWith. This will return `true` as long as the start of the string matches but anything after the text you pass in will be ignored so `card_front2`, `card_front two`, `card_fronts (instacnce)` will all pass. For example:

```
if (m.name.StartsWith("card_front"))

```

but linking to the material in the inspector isn't necessarily a bad thing as it decouples the material from the code so you don't need to change the code if someone goes in and changes the material for a different one or changes the name.

---
Tags: unity, materials
---


# Question
Title: Transform bone absolute position to relative position
I'm working on adding IK to my engine and right now I'm implementing the FABRIK algorithm to give full support to more than three bones.

The algorithm works by giving the joints positions, the start position (first joint), the target, and a threshold. I have already wrote the code and, as far as I can tell, it is correct.

When I use the algorithm I feed the world positions of each bones in the current frame and the target to reach and then the algorithm returns the position each bone should be in.

The issue is that the positions returned are also in WS and my animation library, Cal3D's setTranslation function, requires the relative translation of the bone (if I'm not wrong, this is the position relative to the father bone).

Does anybody know how I should transform the WS my bone is supposed to be at to the relative position I must give to the setTranslation method? Is that possible?

# Answer
> 1 votes
First of all thanks to ColdSteel for his/her help. :)

I ended up solving the issue by applying the following algorithm. I will list the points as I find it clearer this way. **Note that I'm not exactly sure if this is the best (or even the correct solution) but it worked quite well for my case.**

* Get the absolute positions of the bones according to the fabrik algorithm.
* Now, for each bone starting from the first one up to the second last (included), we need to calculate the necessary rotation to look at to the next bone. For example, for the upper arm, calculate the look at to point to the forearm one (or whatever is the next one in your skeleton).

```
// Loop through all the bones minus the last one.
// bonesIKPosition has the positions accoriding to the FABRIK algorithm
for (int i = 0; i < bonesIKPosition.size()-1; ++i){
   int boneID = boneIds[i];
   int boneToPick = i + 1;

   TBoneCorrection corrector = TBoneCorrection();
   corrector.bone_id = boneID;
   corrector.local_axis_to_correct = Vector3(1.0, 0.0, 0.0f);
   corrector.amount = 1.f;
   corrector.apply(skeleton, bonesIKPosition[boneToPick], amount);
}

```

While I can't share the code of the look at corrector (not mine, sorry!), I will explain what it does step by step so you might be able to do it yourself. (I think there are probably some tutorials or videos about this online but not sure). The Bone corrector applies a lookat correction to a bone so it will point in a given direction, to do so it uses the following parameters:

* The **skeleton** we are applying the correction to.
* The **bone\_id** to know which bone will be affected by the look at. (Which one we want rotate).
* The **position** to point at (the next bone in the hierarchy in our case).
* The **amount** to apply the correction (same as with the amount before, we set it to 1.0f here as we want the correction to be instant in the case of this type of ik (we are already applying the correction to the position to look at to).
* And the **local axis to correct**, which means the axis of the bone (in bone space) which we want to be pointing to the given direction (in this case the x vector which is the forward vector of the bone in our skeleton.

The algorithm is as follows:

* Get the **absolute position of the bone** we are applying the look at to.
* Get the **direction** in ws between the **position** we want to point to and the **absolute position of the bone** (the point before).
* Get the absolute rotation of the bone. Invert it to get the absolute to local rotation.
* Use this rotation that rotates from absolute to local to convert the **direction** in ws. Now, you should have the **direction in bone space**.
* Now, you should use this **direction** and the **local axis to correct** to build a quaternion to rotate the bone as necessary so it point where it needs to. To build it you should do:
    + Calculate the cross product between the direction and the local axis, this will be the rotation axis.
    + Get the angle between the direction and local axis to correct, search a function online if necessary but you probably have one in your vector class or somewhere else.
    + Finally, use your Quaternion class and see if there is a function that allows you to create a quaternion from a rotation axis and an angle, if so, now you have the rotation that needs to be added to the bone so it points where you want to.

Use this rotation and apply it over the current rotation of your bone. Something like this:

```
CalQuaternion rotationToAddToBone = deltaRotationToAdd; // Delta rotation is the rotation we need to apply to the bone and just calculated before.
rotationToAddToBone *= bone->getRotation(); // Combine the rotation with the one from the bone.
bone->setRotation(rotationToAddToBone ); // set the final rotation to the bone.
bone->calculateState(); // This is a call function so the rotation also affects the children bones.

```

You are done!

Hopefully it may help somebody in a similar situation.

---
Tags: skeletal-animation, inverse-kinematics
---


# Question
Title: RendererColorChange and Transform.position doesn't work
```
    void LeftPartFalls()
{
    if (LeftPartMat)
    {
        for (int i = 0; i < Mathf.Min(5, FirstLine.Length); i++)        // COLOR CHANGE
        {
            Debug.Log(i);
            FirstLine[i].gameObject.GetComponent<MeshRenderer>().material.color = Color.grey;
            SecondLine[i].gameObject.GetComponent<MeshRenderer>().material.color = Color.grey;
            ThirdLine[i].gameObject.GetComponent<MeshRenderer>().material.color = Color.grey;
            FourthLine[i].gameObject.GetComponent<MeshRenderer>().material.color = Color.grey;
            FiftLine[i].gameObject.GetComponent<MeshRenderer>().material.color = Color.grey;
            SixthLine[i].gameObject.GetComponent<MeshRenderer>().material.color = Color.grey;
            SeventhLine[i].gameObject.GetComponent<MeshRenderer>().material.color = Color.grey;
            EighthLine[i].gameObject.GetComponent<MeshRenderer>().material.color = Color.grey;
            NinthLine[i].gameObject.GetComponent<MeshRenderer>().material.color = Color.grey;
            TenthLine[i].gameObject.GetComponent<MeshRenderer>().material.color = Color.grey;
        }
    }
    if (!LeftPartMat)
    {
        for (int i = 0; i < Mathf.Min(5, FirstLine.Length); i++)        // COLOR CHANGE
        {
            FirstLine[i].gameObject.GetComponent<MeshRenderer>().material.color = new Color(162f / 255f, 172f / 255f, 186f / 255f, 1f);
            SecondLine[i].gameObject.GetComponent<MeshRenderer>().material.color = new Color(162f / 255f, 172f / 255f, 186f / 255f, 1f);
            ThirdLine[i].gameObject.GetComponent<MeshRenderer>().material.color = new Color(162f / 255f, 172f / 255f, 186f / 255f, 1f);
            FourthLine[i].gameObject.GetComponent<MeshRenderer>().material.color = new Color(162f / 255f, 172f / 255f, 186f / 255f, 1f);
            FiftLine[i].gameObject.GetComponent<MeshRenderer>().material.color = new Color(162f / 255f, 172f / 255f, 186f / 255f, 1f);
            SixthLine[i].gameObject.GetComponent<MeshRenderer>().material.color = new Color(162f / 255f, 172f / 255f, 186f / 255f, 1f);
            SeventhLine[i].gameObject.GetComponent<MeshRenderer>().material.color = new Color(162f / 255f, 172f / 255f, 186f / 255f, 1f);
            EighthLine[i].gameObject.GetComponent<MeshRenderer>().material.color = new Color(162f / 255f, 172f / 255f, 186f / 255f, 1f);
            NinthLine[i].gameObject.GetComponent<MeshRenderer>().material.color = new Color(162f / 255f, 172f / 255f, 186f / 255f, 1f);
            TenthLine[i].gameObject.GetComponent<MeshRenderer>().material.color = new Color(162f / 255f, 172f / 255f, 186f / 255f, 1f);
        }
    }

    if (LeftPartFall)       // FALL DOWN
    {
        for (int i = 0; i < Mathf.Min(5, FirstLine.Length); i++)
        {
            FirstLine[i].gameObject.transform.position = Vector3.Lerp(FirstLine[i].transform.position, new Vector3(FirstLine[i].transform.position.x, -4f, FirstLine[i].transform.position.z), t);
            SecondLine[i].gameObject.transform.position = Vector3.Lerp(SecondLine[i].transform.position, new Vector3(SecondLine[i].transform.position.x, -4f, SecondLine[i].transform.position.z), t);
            ThirdLine[i].gameObject.transform.position = Vector3.Lerp(ThirdLine[i].transform.position, new Vector3(ThirdLine[i].transform.position.x, -4f, ThirdLine[i].transform.position.z), t);
            FourthLine[i].gameObject.transform.position = Vector3.Lerp(FourthLine[i].transform.position, new Vector3(FourthLine[i].transform.position.x, -4f, FourthLine[i].transform.position.z), t);
            FiftLine[i].gameObject.transform.position = Vector3.Lerp(FiftLine[i].transform.position, new Vector3(FiftLine[i].transform.position.x, -4f, FiftLine[i].transform.position.z), t);
            SixthLine[i].gameObject.transform.position = Vector3.Lerp(SixthLine[i].transform.position, new Vector3(SixthLine[i].transform.position.x, -4f, SixthLine[i].transform.position.z), t);
            SeventhLine[i].gameObject.transform.position = Vector3.Lerp(SeventhLine[i].transform.position, new Vector3(SeventhLine[i].transform.position.x, -4f, SeventhLine[i].transform.position.z), t);
            EighthLine[i].gameObject.transform.position = Vector3.Lerp(EighthLine[i].transform.position, new Vector3(EighthLine[i].transform.position.x, -4f, EighthLine[i].transform.position.z), t);
            NinthLine[i].gameObject.transform.position = Vector3.Lerp(NinthLine[i].transform.position, new Vector3(NinthLine[i].transform.position.x, -4f, NinthLine[i].transform.position.z), t);
            TenthLine[i].gameObject.transform.position = Vector3.Lerp(TenthLine[i].transform.position, new Vector3(TenthLine[i].transform.position.x, -4f, TenthLine[i].transform.position.z), t);
        }
    }
    if (!LeftPartFall)      // RISE UP
    {
        for (int i = 0; i < Mathf.Min(5, FirstLine.Length); i++)
        {
            FirstLine[i].gameObject.transform.position = Vector3.Lerp(FirstLine[i].transform.position, new Vector3(FirstLine[i].transform.position.x, 0f, FirstLine[i].transform.position.z), t);
            SecondLine[i].gameObject.transform.position = Vector3.Lerp(SecondLine[i].transform.position, new Vector3(SecondLine[i].transform.position.x, 0f, SecondLine[i].transform.position.z), t);
            ThirdLine[i].gameObject.transform.position = Vector3.Lerp(ThirdLine[i].transform.position, new Vector3(ThirdLine[i].transform.position.x, 0f, ThirdLine[i].transform.position.z), t);
            FourthLine[i].gameObject.transform.position = Vector3.Lerp(FourthLine[i].transform.position, new Vector3(FourthLine[i].transform.position.x, 0f, FourthLine[i].transform.position.z), t);
            FiftLine[i].gameObject.transform.position = Vector3.Lerp(FiftLine[i].transform.position, new Vector3(FiftLine[i].transform.position.x, 0f, FiftLine[i].transform.position.z), t);
            SixthLine[i].gameObject.transform.position = Vector3.Lerp(SixthLine[i].transform.position, new Vector3(SixthLine[i].transform.position.x, 0f, SixthLine[i].transform.position.z), t);
            SeventhLine[i].gameObject.transform.position = Vector3.Lerp(SeventhLine[i].transform.position, new Vector3(SeventhLine[i].transform.position.x, 0f, SeventhLine[i].transform.position.z), t);
            EighthLine[i].gameObject.transform.position = Vector3.Lerp(EighthLine[i].transform.position, new Vector3(EighthLine[i].transform.position.x, 0f, EighthLine[i].transform.position.z), t);
            NinthLine[i].gameObject.transform.position = Vector3.Lerp(NinthLine[i].transform.position, new Vector3(NinthLine[i].transform.position.x, 0f, NinthLine[i].transform.position.z), t);
            TenthLine[i].gameObject.transform.position = Vector3.Lerp(TenthLine[i].transform.position, new Vector3(TenthLine[i].transform.position.x, 0f, TenthLine[i].transform.position.z), t);
        }
    }
}
private IEnumerator enumerator(float waitTime)
{
    while (true)
    {
        LeftPartMat = true;

        yield return new WaitForSeconds(waitTime);

        LeftPartFall = true;

        t = 0f;
        t += Time.deltaTime / 0.7f;

        yield return new WaitForSeconds(4);
        LeftPartFall = false;
        LeftPartMat = false;
        yield return new WaitForSeconds(waitTime);
    }
}

```

> WaitTime is 4f

1. Color doesn't changes
2. The result i want is;  The result i get;

> By the way this script was working last day, i tested it several times and save&closed it, other day i changed nothing and just open the client and test it again and noticed it doesn't work.

# Answer
> 1 votes
I've solved my problem, if you're having the some issue:

```
public Vector2Int size = new Vector2Int(10, 10);
public float spacing = 1f;
public MeshRenderer tilePrefab;
MeshRenderer[,] tiles;

public Material fallingMaterial;
public Material risingMaterial;
public float fallSeconds = 3f;
public float fallHeight = -4f;
public float riseSeconds = 4f;

void Awake()
{
    CreateFloor();
    StartCoroutine(AnimationLoop(3f));
    transform.position = new Vector3(0, 0, -20);
}

void CreateFloor()
{
    // Define our tiles array in the appropriate size.
    tiles = new MeshRenderer[size.x, size.y];

    // Spawn the floor centered around this object's position.
    Vector3 origin = transform.position + new Vector3(size.x, 0, size.y) * -0.5f * spacing;

    // For each row, and each column, instantiate a tile.
    for (int x = 0; x < size.x; x++)
    {
        for (int y = 0; y < size.y; y++)
        {
            tiles[x, y] = Instantiate<MeshRenderer>(tilePrefab, new Vector3(x, 0, y) * spacing + origin, Quaternion.identity);
        }
    }
    for (int x = 0; x < size.x; x++)
    {
        for (int y = 0; y < size.y; y++)
        {
            tiles[x, y].gameObject.layer = LayerMask.NameToLayer("GroundLayer");
        }
    }
}

void SelectLeftHalf(List<MeshRenderer> pattern)
{
    Debug.Log("SelectLeftHalf");
    pattern.Clear();
    for (int x = 0; x < size.x / 2; x++)
    {
        for (int y = 0; y < size.y; y++)
        {
            pattern.Add(tiles[x, y]);
        }
    }
}

void ChangeAllMaterials(List<MeshRenderer> pattern, Material material)
{
    foreach (var renderer in pattern)
        renderer.sharedMaterial = material;
}

IEnumerator SlideAllBlocks(List<MeshRenderer> pattern, float startHeight, float endHeight, float duration)
{
    float progress = 0f;
    while (progress < 1f)
    {
        progress = Mathf.Clamp01(progress + Time.deltaTime / duration);

        // Compute a height to move to, with an ease-out curve.
        float height = Mathf.Lerp(startHeight, endHeight, 1 - (1 - progress) * (1 - progress));

        // Set all blocks in the pattern to this height.
        foreach (var renderer in pattern)
        {
            var position = renderer.transform.position;
            position.y = height;
            renderer.transform.position = position;
        }

        // Wait one frame, then resume.
        yield return null;
    }
}

IEnumerator AnimationLoop(float moveSeconds)
{
    // Prep our variable for tracking the pattern of tiles we're acting on.
    // Since this is a local variable, we can control exactly who gets to act on it,
    // so anything that changes the pattern should be easy to track down.
    var pattern = new List<MeshRenderer>();

    while (true)
    {
        // Each cycle, select a randomly-chosen pattern of blocks.
        int selection = Random.Range(1, 2);

        switch (selection)
        {
            case 1: SelectLeftHalf(pattern); break;
        }

        // Change the material of all blocks in this pattern.
        ChangeAllMaterials(pattern, fallingMaterial);

        // Wait before we start to fall.
        yield return new WaitForSeconds(moveSeconds);

        // Chain control to our sliding method until the fall is complete.
        yield return SlideAllBlocks(pattern, 0f, fallHeight, fallSeconds);

        // Done falling. Reset the materials and rise back up.
        ChangeAllMaterials(pattern, risingMaterial);

        // Chain control to our sliding method until the fall is complete.
        yield return SlideAllBlocks(pattern, fallHeight, 0f, riseSeconds);

        // Everything has risen and reset. Now adjust our moveSeconds for next cycle:
        if (moveSeconds >= 1.3f)
        {
            moveSeconds -= 0.7f;
        }
        else if (moveSeconds <= 1.3f)
        {
            moveSeconds = Mathf.Max(moveSeconds - 0.6f, 0.7f);
        }

        // Wait before starting the next cycle & choosing a new pattern.
        yield return new WaitForSeconds(moveSeconds);
    }
}

```

It can be look complicated at the first look but trust me it's simple.

**If you are having a problem with understanding**, check this link, at that post DmGregory has a great answer about it.

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


# Question
Title: How to move Character according to Camera's look direction?
```
    Vector3 newPosition = new Vector3(-horizontal, 0.0f, -vertical);
    transform.LookAt(newPosition + transform.position);
    transform.Translate(newPosition * MoveSpeed * Time.deltaTime, Space.World);

```

I'm developing 3d mobile game, you can look around with hold&sliding the right side of the screen and move with virtual joystick.

**Goal;**

Moving character to camera's lookDirection

**Issue is;**

When i push joystick up, character moves to the same direction (world related)

*And I'm not good at coding that's why i can't solve the problem myself, i would be glad if you help me*

# Answer
> 0 votes
Here's how I calculated my movement according to my camera's direction:

**Note:** There's TouchField because my game is for mobile. If your game is not mobile you need to calculate somethings different than mine.

```
void Movement()
{
    Vector2 vec = new Vector2(horizontal, vertical);
    vec = Vector2.ClampMagnitude(vec, 1f);

    Vector3 camF = cam.transform.forward;
    Vector3 camR = cam.transform.right;
    Vector3 rbVelocity = rb.velocity;

    camF.y = 0;
    camR.y = 0;
    rbVelocity.y = 0;
    camF = camF.normalized;
    camR = camR.normalized;

    targetPosition = (camF * vec.y + camR * vec.x) * MoveSpeed;

    Vector2 targetVelocity = (targetPosition - transform.position)/Time.deltaTime;

    rb.AddForce(targetPosition - rbVelocity, ForceMode.VelocityChange);

    transform.eulerAngles = new Vector3(transform.eulerAngles.x, transform.eulerAngles.y, Mathf.Clamp(transform.eulerAngles.z, 0, 0));

    Vector3 deltaPosition = transform.position - prevPosition;

    if (deltaPosition.sqrMagnitude > 0.1 * Time.deltaTime * Time.deltaTime)
    {
        transform.forward = deltaPosition;
    }

    prevPosition = transform.position;

    CameraAngle += FixedTouchField.TouchDist.x * CameraAngleSpeed;

    Camera.main.transform.rotation = Quaternion.LookRotation(transform.position + Vector3.up * 2f - Camera.main.transform.position, Vector3.up);

}

```

# Answer
> 0 votes
Camera look direction is represented by its transform orientation value. The vector you want to move your character along is `transform.forward` of your camera.

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


# Question
Title: With gravity enabled, how do you move a RigidBody forwards at a specific speed?
I have a perfectly smooth cube on top of a perfectly smooth plane. I am applying a forward-force of 1 unit per second, using `rigidBody.AddForce(new Vector3(0, 0, 1), ForceMode.VelocityChange)`. I apply this force every `FixedFrame()`, taking into account `Time.fixedDeltaTime`, of course.

When the "Use Gravity" checkbox on the RigidBody is ***not*** checked, the object behaves as expected; after exactly 3 seconds, it has a speed of exactly 3 units per second.

However, when I enable the "Use Gravity" checkbox, the object barely moves. Both the object and the surface are using Physic Materials with zero friction, and the moving object's RigidBody has zero drag and zero angular drag.

Why does this happen? And more importantly, how would I apply a force to this object so that it moves forward at, say, exactly 3 units per second, with gravity enabled?

Thank you.

# Answer
> 0 votes
Are you using a "frictionless" physic material or just leaving it unassigned altogether? I've learnt that an unassigned physic material still has some kind of friction resistance, along with physic materials having a diference in friction with the `dynamic friction` and `static friction` attributes.

Try creating a true frictionless physic material with these set to 0 and you should have behavior similar to an ice cube sliding along.

# Answer
> 0 votes
You can multiply your vector3 with MoveSpeed variable. In my `How to move Character according to Camera's look direction?` question i've posted an answer. I'll link that so you can examine it.

1. That's how i did:

```
targetPosition = (camF * vec.y + camR * vec.x) * MoveSpeed;

Vector2 targetVelocity = (targetPosition - transform.position)/Time.deltaTime;

rb.AddForce(targetPosition - rbVelocity, ForceMode.VelocityChange);

```

As you can see all i have to do was multiply my calculation with MoveSpeed variable.
2. Here you can find whole code if you are curious.

---
Tags: unity, physics
---


# Question
Title: custom mesh object orientation is not correct using
I am making a custom mesh with the help of **Traingulator** script. At runtime, user can click and and generate a point then mesh creation start. Here is the way i am getting user input.

```
void Update()
    {
        RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out hit))
        {
            if (Input.GetMouseButtonDown(0))
            {
                GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
                sphere.transform.position = hit.point;
                sphere.transform.localScale = new Vector3(0.2f, 0.2f, 0.2f);
                positions.Add(sphere.transform.position);
                positionsVector2.Add(new Vector2(sphere.transform.position.x, sphere.transform.position.z));

                traingulatorTester.MeshMaker(positionsVector2.ToArray());
            }
        }

    }

```

And here is the mesh maker function that calling tringulator

```
 public void MeshMaker(Vector2[] vertices2D)
    {
        // Use the triangulator to get indices for creating triangles
        Triangulator tr = new Triangulator(vertices2D);
        int[] indices = tr.Triangulate();

        // Create the Vector3 vertices
        Vector3[] vertices = new Vector3[vertices2D.Length];
        for (int i = 0; i < vertices.Length; i++)
        {
            vertices[i] = new Vector3(vertices2D[i].x, vertices2D[i].y, 0);
        }

        // Create the mesh
        Mesh msh = new Mesh();
        msh.vertices = vertices;
        msh.triangles = indices;
        msh.RecalculateNormals();
        msh.RecalculateBounds();
        if (gameObject.GetComponent<MeshRenderer>() == null)
        {
            // Set up game object with mesh;
            gameObject.AddComponent(typeof(MeshRenderer));
            filter = gameObject.AddComponent(typeof(MeshFilter)) as MeshFilter;
        }
        filter.mesh = msh;

    }

```

Now the problem is the rotation of the custom mesh object is not correct look at this.

Now I have manually set the rotation.

# Answer
> 1 votes
Triangles, normals and other things seem fine in the images, so it must be a problem with vertices. you placed Z axis of spheres in Y axis of positionsVector2 so you have to put Y axis of positionsVector2 into Z axis of new vectors.

```
vertices[i] = new Vector3(vertices2D[i].x, 0, vertices2D[i].y);

```

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


title: license for old vehicle/track

text:
# Question
Title: license for old vehicle/track
If I want to develop an android racing game set in the 1940-1950, with the real track of that period (that differs from the actual one), both closed and street circuit, and the real car of that period (F1 car), do I have to pay a license to use its name and aspect?

If so, how much it would be cost?

# Answer
I am not a lawyer. If you are serious about creating a project which might infringe on 3rd party intellectual properties, always get legal advise by an actual professional lawyer familiar with IP rights. But as a layman I believe this to be true:

Names are protected by trademark law. You can generally use a trademark when the owner doesn't use that trademark for business purposes anymore and doesn't have a registered trademark for that name.

Architectural features like race tracks and mechanical designs like cars are protected by copyright law. Copyright expiry durations vary around the world, and can be somewhere between 50 and 120 years.

What would it cost to use a trademarked name / copyrighted design in your game? Whatever the owner wants you to pay. You would have to find out who owns the IP rights and negotiate with them.
> 3 votes

---
Tags: licensing, racing
---


title: button thumbnail slider effect unity3D

text:
# Question
Title: button thumbnail slider effect unity3D
I am trying to make this effect for buttons. i.e the middle one is bigger and is selected. the buttons can be moved left or right by swapping with finger. Does anyone have any idea how to do it?

# Answer
I found this tutorial link with the help of DMGregory. Click here for the tutorial project

All you have to do is add panels as

```
-main
    ->child
        ->grandChild
            ->emptyObject
                ->button1
                ->button2...

```

add script `CreateProfile` to child. and the the buttons and emptyObject to it. And thats it.
> 1 votes

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


# Question
Title: What is a good algorithm for a stock market simulation?
I am making a text game about investing in the stock market, however I need a better algorithm, as the current simulation just goes up and down randomly. How can I make it so that its a more realistic simulation in python.

I've looked at the answer to the question "How would I implement a realistic stock market?", but I want the stock price to be influenced by the users actions, and based on non random actions that they have done. For example, if they buy a massive quantity of an item in the game, the value will go up

# Answer
As you've pointed out, the other question you linked to is more about how to render a nice graph and numerical change, and not how to decide exactly how or why the number should change. It just states...

1. You start at time T1. You're going towards time T2. Price at time T1 is P1. P2 is end price.
2. You generate a random number (probably based on some events, maybe?) for P2. This is your larger number target price.

Obviously you don't want a random number, you want a stock market model to tell you what P2 should be. And what that value is can be influenced by a market simulator and also player actions that impact the simulator's outcome.

To that end (how to model and simulate a stock market) I think you're going to have to go deep and learn more about actual stock market simulators outside of the game space.

Below are a few links to reading on this topic, that I think should help get you further down the path of how a market simulator works, what the inputs to it are, etc.

Modeling and Simulation of the Artificial Stock MarketTrading System

Multi-agent modeling and simulation of a stock market

Wikipedia Stock market simulator page

You might also check out the MarketWatch virtual stock exchange at https://www.marketwatch.com/game. No source code but it should be a good learning experience to see how this is done in other games/simulators.

Lastly, you might find this previous question in a different stack somewhat useful: https://softwareengineering.stackexchange.com/questions/84490/what-algorithms-would-be-useful-for-designing-a-stock-market-simulator

In the end, this is potentially a pretty complex problem if you truly want an accurate simulation.
> 1 votes

---
Tags: algorithm, python
---