# Question
Title: class diagrams / design for an adventure game (rooms, objects, inventory)?
Any links to existing design (e.g. class diagrams, database ER diagrams) for a basic adventure game - i.e. that has the aspects of:

* rooms/locations (which you move between)
* objects which you collect / use (which may have behaviours)
* inventory (i.e. items which you carry)
* rules (e.g. if you to want to open Door X, then you need Key Y)

# Answer
> 1 votes
I hate to say it but the basic adventure games with those features that I know of are mostly just thrown together ad hoc, it's pretty basic programming following YAGNI principles. There are no diagrams, UML, or extensive documents except for the scripting language chosen and the interfaces the designers can use. I've never seen any, at any rate.

That being said, one great example to check out would be SCUMM and another, more elaborate example would be LPMUD engine code which has all those features and could be downgraded into a single player experience with some work.

This forum itself is a good resource but you must narrow your search to just one feature at a time to get the best results; even then you're going to see a lot about techniques and very little in the way of diagrams.

# Answer
> 0 votes
Sorry for necro'ing this thread nearly a decade later, but in case someone else comes across this like me:

The structure for a graphical adventure game is sort of the natural structure you would think about (naming taken mostly from the TADS standard library):

* You have a `Room`, which is a single screen. There is the concept of the current `Room` in which the player may be, and each `Room` can contain `Object`s, and have a background image.
* You have `Object`s, which are things visible on screen at a certain position and size. This is the base class for NPCs, doors, items to be picked up, or containers holding other `Object`s etc. There is also one `Object` representing the player. The player is special in that it is drawn in front of or behind the other items depending on where it is vertically, lower or higher. An `Object` has a current image, and probably multiple images that it can rotate through (for an animation), and also `frame sets` that can be swapped out, so you can do things like put a player on a "climbing" set of frames, or "walking down" or "walking up" or "picking something up" etc.
* You have `Item`s, which are `Object`s that the player can pick up. They're like items, but often have an extra image attached to them that will be shown in your inventory to represent them. They have methods that allow checking preconditions before picking them up or dropping them again is permitted.
* You have `NPC`s which are `Object`s you can have conversations with. For this, you need a conversation tree GUI, and a `ConversationNode` with a list of `Phrase`s a character can say. Each `Phrase` has a reference to another `ConversationNode` that will be shown after it has been said. Each `ConversationNode` also has a bit of text (usually the `NPC`'s answer to your question) that will be shown above the conversation choices.
* You have `Container`s, which are `Object`s that can hold other objects. Some containers are like locked bookshelves that just let you look at items in them once they've been examined once themselves, others are like chests, where you can take things out of them, or put things into them.
* You have `Door`s, which are `Object`s that you can click at to take you to a different room. Some doors can be locked, meaning you need a special `Item` in your inventory to be able to walk through them, like a key. Doors are often part of the background, so can also just be invisible rectangles over which the mouse pointer changes to a "walk" arrow or so, they don't need to have a current image or a frame set.

The structure for a text adventure would be roughly similar, except that instead of images, it contains description messages, and a list of adjectives and nouns that can be used to refer to it.

Note that you can also combine these classes, e.g. you could have a vendor NPC be both an `NPC` and a `Container`, and selling or buying stuff from them just means putting stuff into/out of them, but it would also check that you have enough money and deduct the cost, or pay you money for sold items.

Also, nested rooms (like a car inside a room) could be a door to another room. You don't actually need a `Room` that is contained in another room. Though if you did put a room in a room, that would make it easier to show what is outside the car, as you could just ask the `Room` containing the car-`Room` to provide an image to show through the windshield. But then your `Room` would have to also be a `Door` so you could enter it.

Your inventory would probably just be a `Container`, or a `Container` inside the player.

To save game state, you probably want each item to produce JSON or so that describes any changes to its state, so you'd need to remember its original state, and if the current state differs, note that in the JSON. Then saving game state would just be asking each object in every room to produce that JSON, and saving every JSON dictionary that is not empty. `Container`s would also report any non-empty JSON in their contained items. Each JSON could include a reference to the containing item, if that changed (like, its unique ID number), and their own unique ID (so you know which item the JSON is for).

---
Tags: game-design, rpg, adventure-games
---


# Question
Title: Help understand Z value of CameraToWorldPoint
I do not understand what this CameraToWorldPoint function is used for, what is the use case of this function:

1.From my understanding, my cursor is sitting on the near clipping plane, so I am actually clicking all the points on the near clipping plane, the near clipping plane represents my screen, am I right?

2.When I use this function to convert B point to world point, I am getting the point C position, is that true?

3.Is part A-\>C represent the Z value, or part B-\>C is the Z value?

4.Then finally, is this function useless? Because I get a world position in the predefined Z position, and I do not even know what Z value should be in the first place, I can randomly assign a pointless Z value, so what is use case for this function, I know raycast can do anything I want, but when to use this function?

# Answer
The z value of `Camera.ScreenToWorldPoint` is the depth from the camera where you want the point to be placed.

This function is something we call an "un-projection". We're taking a projected point in 2D space, and reversing the camera's projection to go into 3D space. The problem is that projections destroy information. When say the player clicks pick a point on the screen, we only have two dimensions worth of information about which position in the world they meant, but we need three dimensions worth to get a 3D point.

So that third piece of information needs to be added by us, the developers, in a way that's consistent with the feature we're trying to implement - since there's no one universal way to deduce it from a 2D point that will work for every feature we might imagine.

> Am I clicking all the points on the near clipping plane? Does the near clipping plane represent my screen?

Well, that's one way you can think of it. But we could just as easily say that you're clicking points on the far clipping plane.

Take a particular position on your near plane. Draw a ray from the camera position through that point, and keep extending it to or even past the far plane. Every point on that ray maps to the same position on the screen, just at different depths (z values).

This depth corresponds to how far you've travelled "forward" along the camera's viewing direction, from the position of the camera itself.

```
float depth = Vector3.Dot(
               camera.transform.forward,
               worldPoint - camera.position
              );

```

Or equivalently:

```
float depth = camera.transform.InverseTransformPoint(worldPoint).z;

```

That's similar to the A-C distance in your diagram. But just note we're measuring this distance along the camera's forward axis, not along the ray joining the camera to the point of interest.

Each different depth or z value defines a plane slicing through your scene, perpendicular to the camera's forward axis. (If we measured along the ray instead, each depth value would define a spherical shell rather than a flat plane)

The near clipping plane is at `depth = camera.nearClipPlane`, and the far clipping plane is at `depth = camera.farClipPlane`, intuitively enough.

> Is this function useless?

No. But it might not be the function that solves your present problem.

It sounds like you might be trying to solve a picking problem, where the player clicks on the screen, and you want to know the closest object or surface under the clicked screen point. In this case, we have no information in the input about what depth the player meant, but we can infer it from our scene geometry. For that problem, you'd use `Camera.ScreenToWorldRay` to get the whole ray of potential positions we described before, then do a physics raycast along this ray to find where it intersects a pickable object the player can see.

`Camera.ScreenToWorldPoint` is useful for cases where you already know the depth you want. Say the player already clicked a sphere, and now wants to drag it around the scene. We could set up our dragging mechanic so that it keeps the object at its original depth from the camera, so the player is dragging it along a plane perpendicular to their view, never bringing it closer or further away. To do that, we'd store the depth of the picked object in a member variable when the player first clicks on it, then on subsequent frames use it as our z value to unproject the latest cursor position to a point on that plane to move the object to.

We'll also use this if we want to position something exactly at the near or far planes, by passing the values of those camera parameters as z.

Or we might use it to position worldspace UI like health bars, name labels, or AR elements a fixed screen distance above an object, using that object's depth from the camera as our z so the UI sits in the same plane.
> 0 votes

---
Tags: unity
---


title: Border around game preview window

text:
# Question
Title: Border around game preview window
I'm trying to put my game view and scene view next to each other, but the game window seems to have a border around the actual game view that I can't remove:

In the screenshot above, the game view should be touching the sides. I've tried changing the aspect ratio setting at the top to no avail, increasing the scale works to remove the border but that also zooms in so isn't a correct representation of the game. Does anyone know how I can remove this border?

# Answer
> 2 votes
Make sure you have "Low resolution aspect ratios" ticked OFF under the aspect ratio tab:

That should make the game view as big as possible, but the actual aspect ratio (e.g. 16:9) may still be leaving gaps on either left and right, or up and down. You can get rid of those by resizing the game window.

---
Tags: unity, editors
---


title: How to have a tilted FNT font on Godot?

text:
# Question
Title: How to have a tilted FNT font on Godot?
Since FNT is a bitmap font I was thinking perhaps making the padding negative to the right and left side of the characters and rasterizing each glyph already skewed by an angle could make the font appear to be tilted. Does any one know whether FNT sports negative padding or whether Godot support some form of skewing that could accomplish that?

Please take a look at the image to see what I'm describing

# Answer
A web search for "godot text padding" brings up the documentation for BBCode in RichTextLabel; among the text rendering option that can be adjusted, it mentions:

> `_process_custom_fx`
> This is where the logic of each effect takes place and is called once per character during the draw phase of text rendering. This passes in a `CharFXTransform` object, which holds a few variables to control how the associated character is rendered:
> ...
>
> * `offset` is an offset position relative to where the given character should render under normal circumstances.
> 1 votes

# Answer
This will work with any kind of font.

The image shows a shader written for a `CanvasItem` of type `Label`. To create the shader I followed the tutorial here.
> 1 votes

---
Tags: godot, fonts
---


# Question
Title: How to draw 2D images using OpenGL, in SDL?
After everything, I managed to find a simple piece of code that shows how to draw a 2D image with openGL:

```
    #include "SDL/SDL.h"
    #include "SDL/SDL_opengl.h"
    #include "SDL/SDL_image.h"

    const int SCREEN_WIDTH = 640;
    const int SCREEN_HEIGHT = 480;
    const int SCREEN_BPP = 32;

    int tex;

    int loadTexture(char* fileName){
        SDL_Surface *image=IMG_Load(fileName);
        SDL_DisplayFormatAlpha(image);
        GLuint object;
        glGenTextures(1,&object);
        glBindTexture(GL_TEXTURE_2D,object);
        glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
        glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
        glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);
        glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
        glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,image->w,image ->h,0,GL_RGBA,GL_UNSIGNED_BYTE,image->pixels);
        SDL_FreeSurface(image);
        return object;
    }
    void init(){
        glClearColor(0.0,0.0,0.0,0.0);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(0.0,800,600,1.0,-1.0,1.0);
        glEnable(GL_BLEND);
        glEnable(GL_TEXTURE_2D);
        glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
        tex = loadTexture("hi.png");
    }
    void draw(){
        glClear(GL_COLOR_BUFFER_BIT);
        glBindTexture(GL_TEXTURE_2D,tex);
        glBegin(GL_QUADS);
            glTexCoord2f(0,0);
            glVertex2f(0,0);
            glTexCoord2f(1,0);
            glVertex2f(500,0);
            glTexCoord2f(1,1);
            glVertex2f(500,500);
            glTexCoord2f(0,1);
            glVertex2f(0,500);
        glEnd();
        glFlush();
    }
    int main(int argc,char** argv){
        SDL_Init(SDL_INIT_EVERYTHING);
        SDL_Surface* screen=SDL_SetVideoMode(800,600,32,SDL_SWSURFACE|SDL_OPENGL);
        bool running=true;
        Uint32 start;
        SDL_Event event;
        init();
        while(running){
            start=SDL_GetTicks();
            draw();
            while(SDL_PollEvent(&event)){
                switch(event.type){
                    case SDL_QUIT:
                        running=false;
                        break;
                }
            }
            SDL_GL_SwapBuffers();
            if(1000/60>(SDL_GetTicks()-start))
                SDL_Delay(1000/60-(SDL_GetTicks()-start));
        }
        SDL_Quit();
        return 0;
    }

```

I'm inexperienced in 2D, and about a week ago started messing with SDL. Built some simple structures to have images, which would be on layers, so I could have my own drawing order, so sprites would be drawn after background, etc, and then did a little "sprite engine". I got a Megaman sprite walking left and right just like I wanted it, above a simple 900x900ish background image.

Thing is, CPU almost reached 20% on my i5... so I thought of using the graphic card to do the drawing! Delved abit into OpenGL and today, finally managed to get gl3w working!

So now I'm looking for a simple way to display my sprites/images, on the window, through use of OpenGL. I've tried all sorts of code I ran across, but I can't get anything displaying, despite that I've done error checks basically everywhere, and everything seems to check out to be right!

**TL:DR; I was looking for some simple working code, using SDL, on how to draw 2D images (which, if it doesn't work, for sure I've got something wrong).**

Thanks!

# Answer
> 7 votes
I recommend loading your sprites using SOIL, and then rendering them by just drawing textured quads. If you do it without any deprecated functionality (use shaders) you will find it's very fast.

# Answer
> 3 votes
Here's a rather basic but great starting point to drawing textured quads in OpenGL, from this function starting point I have 7 other functions that provide slightly different functionality, to drawing with tinted colours, to drawing items with different alpha values and then we have rotation, clipping etc. etc. But this should help get you started :).

Edit: Updated Code;

```
void Draw(int x, int y, Image* texture, bool blendFlag) {
//Bind Texture
glBindTexture(GL_TEXTURE_2D, texture->getData());

if (blendFlag)
{
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}

GLfloat Vertices[] = {(float)x, (float)y, 0,
                    (float)x + texture->getWidth(), (float)y, 0,
                    (float)x + (float)texture->getWidth(), (float)y + (float)texture->getHeight(), 0,
                    (float)x, (float)y + (float)texture->getHeight(), 0};
GLfloat TexCoord[] = {0, 0,
    1, 0,
    1, 1,
    0, 1,
};
GLubyte indices[] = {0,1,2, // first triangle (bottom left - top left - top right)
                     0,2,3}; // second triangle (bottom left - top right - bottom right)

glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, Vertices);

glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2, GL_FLOAT, 0, TexCoord);

glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, indices);

glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);

if (blendFlag) glDisable(GL_BLEND);
}

```

Image is a basic structure holding the texture data (GLuint) and then two integers to hold width & height.

# Answer
> 0 votes
Is SDL necessary for you? SFML is alternative to SDL that uses OpenGL for rendering. It may be also easier for beginners, because of the object-oriented API.

# Answer
> 0 votes
The CPU is working the most time on the bucle that wait to the Next frame. You must use a invalidate rect o know that you can do much more without use more CPU

---
Tags: c++, opengl, sdl, windows
---


# Question
Title: Why does my Perlin Noise Terrain have rough parts on the edges?
I followed this tutorial: https://gamedevacademy.org/complete-guide-to-procedural-level-generation-in-unity-part-1/

The important bits of my code are below. I tried messing around with different parameters for a while, and I'm not sure how to fix the noticeable lines between tiles.

```
void GenerateTile()
    {
        Vector3[] meshVertices = this.meshFilter.mesh.vertices;
        int tileDepth = (int) Mathf.Sqrt(meshVertices.Length);
        int tileWidth = tileDepth;

        // calc heightmap
        float[,] heightMap = this.noiseMapGenerator.GenerateNoiseMap(tileDepth, tileWidth, this.mapScale, -this.transform.position.x, -this.transform.position.z, waves);

        // update texture and mesh
        Texture2D tileTexture = BuildTexture(heightMap);
        this.tileRenderer.material.mainTexture = tileTexture;
        UpdateMeshVertices(heightMap);
    }

```

```
public float[,] GenerateNoiseMap(int mapDepth, int mapWidth, float scale, float offsetX, float offsetZ, Wave[] waves)
    {
        // Instantiate noiseMap
        float[,] noiseMap = new float[mapDepth, mapWidth];

        // Populate noiseMap
        for (int zidx = 0; zidx < mapDepth; zidx ++)
        {
            for (int xidx = 0; xidx < mapDepth; xidx ++)
            {
                float noise = 0f;
                float norm = 0f;
                float x_val = (xidx + offsetX)  / scale;
                float z_val = (zidx + offsetZ) / scale;

                // Layer multiple waves on top of each other
                foreach (Wave wave in waves)
                {
                    noise += wave.amplitude * Mathf.PerlinNoise( (x_val * wave.frequency + wave.seed), (z_val * wave.frequency + wave.seed));
                    norm += wave.amplitude;
                }

                // Normalize and assign
                noise /= norm;
                noiseMap[zidx, xidx] = noise;
            }
        }
        return noiseMap;
    }

```

# Answer
According to this, Unity's Mathf.PerlinNoise is symmetrical. That seems to be the root of your problem. https://forum.unity.com/threads/perlin-noise-symmetrical.390981/

That's not the only reason I wouldn't use it though. Perlin noise in general tends to generate a lot of 45 and 90 degree aligned features, and not much else. This takes a lot away from the quality of your project, for not very good reason because it's very easy to use other noise instead.

Take any tutorial that tells you to use Mathf.PerlinNoise, or Perlin noise in general, with a grain of salt. Unity is probably causing more problems than it solves by including Mathf.PerlinNoise without any Mathf.SimplexNoise or documentation to steer developers to the latter, but that's a separate issue that warrants its own discussion.

I would do one of the following:

1. Import Unity.Mathematics and use Unity.Mathematics.noise.snoise(float2) for noise.
2. Import FastNoiseLite (I contributed to this repo) and use one of the "Simplex" noise options. https://github.com/Auburn/FastNoise

Both of these should fix your problem, as well as increase the quality of your terrain.
> 3 votes

---
Tags: unity, perlin-noise
---


# Question
Title: How do I convert a humanoid retargetted animation to a generic animation?
In my game, I use a Generic Rig model called "hero\_generic".

I have a pistol-shooting animation. This animation was created for another rig, so I need to use Humanoid retargetting to use it on my model.

To try out how it looks, I copy my "hero\_generic" character, name it "hero\_humanoid" and create a Humanoid avatar for it. Then I set the animation to "Humanoid", put it on an animation controller and put the animation controller onto the "hero\_humanoid".

It works, the animation is now playing on my Humanoid character, but I don't want my character to be Humanoid.

I want to bake the animation out for my hero\_generic character. Unity doesn't provide any built-in option to do that.

How can I turn this retargetted animation to a generic .anim file?

# Answer
> 2 votes
I put a script on my "hero\_generic" that copies the position and rotation of each bone of "hero\_humanoid" to each bone of "hero\_generic". This way, I have the animation playing on my generic rig. :-)

Now I want to save the generic animation from "hero\_generic" to an anim file.

To do that, I use the following script:

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

public class TransferAnimation : MonoBehaviour
{
    public Transform HumanoidModelWhoseAnimationWillBeCopiedToThisModel;
    private Animator _OtherAnimator;

    public AnimationClip clip;

    private GameObjectRecorder _Recorder;

    void Start()
    {
        // Create recorder and record the script GameObject.
        _Recorder = new GameObjectRecorder(gameObject);

        // Bind all the Transforms on the GameObject and all its children.
        _Recorder.BindComponentsOfType<Transform>(gameObject, true);

        _OtherAnimator = HumanoidModelWhoseAnimationWillBeCopiedToThisModel.gameObject.GetComponent<Animator>();
    }

    private void LateUpdate()
    {
        //wir können keine animation aufnehmen, während ein animator das modell bewegt
        //also machen wir es so:
        //wir übertragen einfach die animation (siehe unten... über position und rotate) auf ein anderes modell
        //auf diese weise braucht das andere modell keine animation, und wir können die animation aufnehmen
        //wir machen sowohl die animation als auch dieses modell humanoid

        List<Transform> nMyTransforms = new List<Transform>();
        Helpers.GetAllChildren(this.transform, ref nMyTransforms);

        List<Transform> nHumanoidTransforms = new List<Transform>();
        Helpers.GetAllChildren(HumanoidModelWhoseAnimationWillBeCopiedToThisModel, ref nHumanoidTransforms);

        //we also need to process the main transform, not only its bones
        Undo.RecordObject(HumanoidModelWhoseAnimationWillBeCopiedToThisModel, "Inspector"); //Bone rotations done by a script are not recorded. Is there a trick to record these bone rotations via script anyways? For example using something like (pseudo-code) this? -> Undo.RecordObject(nTargetTransform, "Inspector");
        transform.localRotation = HumanoidModelWhoseAnimationWillBeCopiedToThisModel.localRotation;
        transform.position = HumanoidModelWhoseAnimationWillBeCopiedToThisModel.position;//auch die position ist wichtig!!! z. B. wenn sich jemand duckt beim zielen!!

        foreach (Transform nHumanoidTransform in nHumanoidTransforms)
        {
            foreach (Transform nMyGenericTransform in nMyTransforms)
            {
                if (nHumanoidTransform.name == nMyGenericTransform.name)
                {
                    Undo.RecordObject(nHumanoidTransform, "Inspector"); //Bone rotations done by a script are not recorded. Is there a trick to record these bone rotations via script anyways? For example using something like (pseudo-code) this? -> Undo.RecordObject(nTargetTransform, "Inspector");
                    nMyGenericTransform.localRotation = nHumanoidTransform.localRotation;
                    nMyGenericTransform.position = nHumanoidTransform.position;//auch die position ist wichtig!!! z. B. wenn sich jemand duckt beim zielen!!

                    break;
                }
            }
        }

        if (_OtherAnimator.GetCurrentAnimatorStateInfo(0).normalizedTime > 1 && !_OtherAnimator.IsInTransition(0))
        {
            //animation has finished playing
            if (_Recorder.isRecording)
            {
                // Save the recorded session to the clip.
                _Recorder.SaveToClip(clip);
                _Recorder.ResetRecording();

                // gameObject.SetActive(false);

            }
        }
        else
        {
            // Take a snapshot and record all the bindings values for this frame.
            _Recorder.TakeSnapshot(Time.deltaTime);
        }
    }

    public static void GetAllChildren(Transform parent, ref List<Transform> transforms)
    {
        foreach (Transform t in parent)
        {
            transforms.Add(t);
            GetAllChildren(t, ref transforms);
        }
    }
}

```

It is important to note that the .anim file will only be written after Unity has been closed. Before that, the .anim's file size will be like 2 KB only.

Also, it is of course necessary that the animation is played only once, so I should not connect 2 of the same animations like I sometimes to do create an endless animation.

---
Tags: unity, animation
---


# Question
Title: Why LineRenderer texture stretching when I set it to tiled?
**I see this:**

**I have a Line Renderer set up like this:**

**This is the material:**

As you can see even if the texture mode is "Tile" the line stretches after the first element of the line. What am I missing?

# Answer
> 2 votes
Tiling is on as you selected, but you have 1 both on Tiling X and Tiling Y, so the image is displayed once.

You can fix that with a script:

```
image.tile.x = line.magnitude; // as x/1 = x

```

This line is kinda pseudocode, just so you can see the logic. If I remember correctly, the X tiling in a line shows how it is repeated along it's length. This line says that the image will be repeated once for every unit the line has. So if you make a line 5 units long, the image will be tiled 5 times.

This code should ideally run once every time the length of the line changes.

# Answer
> 4 votes
I know this thread is old but for anyone who happens to have the same problem, all you need to do is go to the image file itself and set wrap mode from clamp to repeat.

https://forum.unity.com/threads/material-tiling-not-working-correctly.226282/

---
Tags: unity, textures, tiles
---


# Question
Title: Help solving Uncaught Abort on HTML5 Build
For some reason there is a Invoke that is triggered when a button is clicked that causes my game to crash. Any idea how I can sort this out?

I have plenty other Invokes and none has given problems. I have the Enable Exceptions option set to None and game works fine inside Unity.

I can give more info on the error if you can point to me to what's relevant. Thanks so much!

```
Invoking error handler due to
Uncaught abort(145) at Error
    at jsStackTrace (ed63bf36d25f876fa57fb81632b59202.unityweb:8:22380)
    at stackTrace [Object.stackTrace] (ed63bf36d25f876fa57fb81632b59202.unityweb:8:22551)
    at Object.onAbort (https://v6p9d9t4.ssl.hwcdn.net/html/1680115/PowerTheGrid_Level3_v7.2_HTML5/Build/3998187b7e8feaa618a93b293c0e6812.js:4:11065)

```

EDIT: Here is the code generating the error:

```
    public void OnClick()
    {
        if (buyCoal.interactable == true)
        {
                trainObject.trainMovementStart();

                if (SceneManager.GetActiveScene().name == "Level1" || SceneManager.GetActiveScene().name == "Level2")
                    Invoke("coal_refill", 6f);

                if (SceneManager.GetActiveScene().name == "Level3")
                    Invoke("coal_refill", 12f);

                Money.UseMoney(coalcost);
                buyCoalAudio.Play();
                countdown += 1; //agora é count up
                tipCoalReady = 2;
                buyCoalButtonIndex = 0; //DISABLE COAL Buy Button
                coal_stock_countdown.text = countdown.ToString();
                coaltipCounter += 1;
        }
    }

    void coal_refill()
    {
        ThermoElectric.quota += 17.5m;
        Invoke("reactivateBuyCoalButton", 5f);
    }
    void reactivateBuyCoalButton()
    {
        buyCoalButtonIndex = 1;
    }
}

```

}

# Answer
> 0 votes
I had the same error with my unity project and it solved itself, probably because I just rebuilt it twice. I did not do anything with the code. I don't know if building the project was one of the reason why the error go away.

I'm still looking forward to better solutions.

---
Tags: unity, c#, javascript, html5
---


# Question
Title: Where is the Mclip matrix & how do I set it?
According to this article, the `Mclip` matrix will be used, but I didn't find any function in Directx11 to set this matrix. How do I set it?

# Answer
The documentation link you've provided is not from Direct3D 11, it's from Direct3D 9.

That aside, in the code snippets and formulae around discussion of this matrix we see the following:

> Cx, Cy - dvClipX, dvClipY from D3DVIEWPORT9
> Cw, Ch - dvClipWidth, dvClipHeight from D3DVIEWPORT9
> Zmin, Zmax - dvMinZ, dvMaxZ from D3DVIEWPORT9

The mention of "from D3DVIEWPORT9" is your answer: it comes from the viewport. In Direct3D 11 that's an ID3D11DeviceContext::RSSetViewports call.
> 2 votes

---
Tags: directx, graphics, directx11, transformation, pipeline
---


# Question
Title: How do I disable function when triggerExit2D?
I want to add a system when the player moves to the door, the scene changed but if the player walks away from the door the function that I call disables it. so I put `OnTriggerEnter2D` and `OnTriggerExit2D` to make that. The issue is once the triggerExit the bool return false but not the function.

so this my script:

```
     private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Player")
        {
            finish = true;

            if (finish)
                StartCoroutine(WaitForChangeScene());
        }
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Player")
        {
            finish = false;
        }
    }

    public IEnumerator WaitForChangeScene()
    {
        yield return new WaitForSeconds(1);
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);

    }

```

# Answer
> 1 votes
You can cancel the coroutine `WaitForChangeScene` in the `OnTriggerExit2D` function. Add a variable to hold the coroutine then you can use that variable to start and stop the coroutine.

```
private IEnumerator coroutine;

private void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.gameObject.tag == "Player")
    {
        //finish = true;
        coroutine = WaitForChangeScene()
        //if (finish)
            StartCoroutine(coroutine);
    }
}

private void OnTriggerExit2D(Collider2D collision)
{
    if (collision.gameObject.tag == "Player")
    {
        //finish = false;
        StopCoroutine(coroutine);
    }
}

public IEnumerator WaitForChangeScene()
{
    yield return new WaitForSeconds(1);
    SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}

```

You're only setting the finish variable to false in `OnTriggerExit2D` but not doing anything with it. In `OnTriggerEnter2D` you are checking the finish variable straight after setting it to true so it will always be true.

---
Tags: unity
---


# Question
Title: How to update indices for dynamic mesh in OpenGL?
So I am making a 3D batchrenderer for my engine, and the basic concept is that we make large enough VBO and IBO to accompany all the vertex data(positions, normals, uv etc.) and update the VBO using `glMapBuffer` or using `glbuffersubdata` everyframe if we want to make any changes, but in this case the pattern of the IBO (Index Buffer) is predefined (i.e. we assume we have quads and fill it with 012230 for the entirety of the IBO size) but when using 3D models this won't be the case the IBOs data would be different, so how do I change the IBO data if I instantiate a new model or suppose if I am generating a UV sphere and want to change it's subdivisions?

I have no idea how to deal with dynamically changing(need not be frequent) indices data when using VAOs, VBOs and Index Buffers.

As per OpenGL 4.5, core profile, reading from client memory is unsupported (§10.3.10 OpenGL 4.5 core spec):

> **DrawElements**, **DrawRangeElements**, and **DrawElementsInstanced** source their indices from the buffer object whose name is bound to `ELEMENT_ARRAY_BUFFER`, using their *indices* parameters as offsets into the buffer object in the same fashion as described in section 10.3.9. \[...\] If zero is bound to `ELEMENT_ARRAY_BUFFER`, the result of these drawing commands is undefined.

so we cannot map the ELEMENT\_ARRAY\_BUFFER using glMapBuffer or glBufferSubData (or can we?), and `glDrawElements` does accept a pointer to indices data but only when we are not using VAOs and VBOs, if we are using them it takes the last argument as a pointer offset in the currently bound ELEMENT\_ARRAY\_BUFFER.

**So what's the best way to deal with dynamic indices?**

# Answer
> 2 votes
This is the idea how to upload data to gpu:

```
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_vboID);
void *vbo = glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, GL_WRITE_ONLY);
memcpy(vbo, indices, byteSize);
glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER);

```

---
Tags: opengl, c++, architecture, index-buffer, dynamic-mesh
---


# Question
Title: Unity - Button get function from GameObject
So I have two gameObjects, the blue one the player character and different spheres of difference colors. Each sphere has a function lets say `SphereFunction()`.

When the player character touches a sphere gameobject I want a button to appear on the screen. This can be done using the `ontriggerenter2d` and `ontriggerexit2d`.

What I want is the button OnClick to call the `SphereFunction()` of the sphere if pressed. This function can have different implementations depending on the color of the sphere, just the function name is the same.

How can this be done using a single button?

# Answer
You can do something like this:

```
//Attach this script to a canvas prefab containing your button, and link the
//button reference in the Inspector
public class ButtonDialog : MonoBehaviour {
    [SerializeField] private Button button;

    public Button Button => button;

    //you can also set up a close button that calls this function
    public void Close() {
        Destroy(gameObject);
    }
}

//Base class for the sphere component. Displays the dialog and listens for the button
//click; actual click handling will be defined in child classes
abstract public class Sphere : MonoBehaviour {
    [SerializeField] private ButtonDialog dialogPrefab;

    //display the dialog and add the click event listener
    void OnTriggerEnter(Collider collider) {
        ButtonDialog instance = Instantiate(dialogPrefab);
        instance.Button.onClick.AddListener(OnClickButton);
    }

    abstract protected void OnClickButton();
}

//You can create child classes that extend Sphere and define the click functionality.
//I have no idea what functionality you want, so here's a random example.
public class GrowingSphere : Sphere {
    override protected void OnClickButton() {
        //double the size of the sphere
        Vector3 scale = transform.localScale;
        scale *= 2;
        transform.localScale = scale;
    }
}

```
1. Create a canvas with the button. Add the `ButtonDialog` component to the canvas, and drag the canvas into the Project panel to create a prefab.
2. Create a sphere and add the `GrowingSphere` component (or whatever component you create that extends `Sphere`). In the Inspector for the sphere, link the `dialogPrefab` field to the prefab you created in step 1.

You can create as many components as you like that extend `Sphere` and implement their own version of `OnClickButton()`
> 0 votes

---
Tags: unity
---


# Question
Title: Unity mesh only rendering one set of triangles
I've been using Unity3D to procedurally generate terrain with Perlin Noise and I've come across a problem where the mesh that I've constructed only renders one set of triangles.

The following is my MeshGeneration code:

```
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using NUnit.Framework.Internal.Execution;
using UnityEngine;

public static class MeshGenerator
{
    public static MeshData GenerateMesh(float[,] heightMap)
    {
        int height = heightMap.GetLength(0);
        int width = heightMap.GetLength(1);
        int vertexIndex = 0;

        MeshData meshData = new MeshData(width, height);

        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                meshData.vertices[vertexIndex] = new Vector3(x, heightMap[y, x], y);
                meshData.uvs[vertexIndex] = new Vector2( x/(float)width, y/(float)height);

                // If we are not on the edge, then add two triangles to the mesh
                if ((x != width - 1) && (y != height - 1))
                {
                    meshData.AddTriangle(
                        vertexIndex,
                        vertexIndex + width,
                        vertexIndex + width + 1
                    );
                    meshData.AddTriangle(
                        vertexIndex,
                        vertexIndex + 1,
                        vertexIndex + width + 1
                    );
                }

                vertexIndex++;
            }
        }

        return meshData;
    }
}

public class MeshData
{
    public Vector3[] vertices;
    public Vector2[] uvs;
    public int[] triangles;

    public int triangleIndex;
    public MeshData(int meshWidth, int meshHeight)
    {
        vertices = new Vector3[meshWidth * meshHeight];
        uvs = new Vector2[meshWidth * meshHeight];
        triangles = new int[(meshWidth - 1) * (meshHeight - 1) * 6];
    }

    public void AddTriangle(int a, int b, int c)
    {
        triangles[triangleIndex] = a;
        triangles[triangleIndex + 1] = b;
        triangles[triangleIndex + 2] = c;
        triangleIndex += 3;
    }

    public Mesh CreateMesh()
    {
        Mesh mesh = new Mesh();
        mesh.vertices = this.vertices;
        mesh.uv = this.uvs;
        mesh.triangles = this.triangles;

        mesh.RecalculateNormals();
        return mesh;
    }
}

```

I'm then passing in the mesh that I get from MeshData.CreateMesh() into the following function.

```
public void BuildMesh(MeshData meshData, Texture2D texture)
    {
        meshFilter.sharedMesh = meshData.CreateMesh();
        meshRenderer.sharedMaterial.mainTexture = texture;
    }

```

I'm following this tutorial: https://www.youtube.com/watch?v=4RpVBYW1r5M&list=PLFt\_AvWsXl0eBW2EiBtl\_sxmDtSgZBxB3&index=5

The Mesh generation code works by creating arrays of vertices, uvs, and triangles, and the populating them by iterating over a Vector3\[\] heightMap that I created with perlin noise.

# Answer
Solved the problem myself. The remaining triangles were being generated on the other side of the mesh. This was I didn't know that the order of the vertices had to be in clockwise order.
> 1 votes

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


# Question
Title: Unity OnControllerColliderHit triggered multiple times in one frame
```
private void Update()
{
     Debug.Log("### " + CollisionFlags);
     CollisionFlags = CharacterController.Move(moveAmount);
}

private void OnControllerColliderHit(ControllerColliderHit hit)
{
    Debug.Log("### OnControllerColliderHit " + hit.gameObject.name);
}

```

the characterController is heading down to plane and I called characterController move function in update() and i expect the result is like

"None"

"OnControllerColliderHit Cube (2)"

"Below"

"OnControllerColliderHit Cube (2)"

but result is

"None"

"OnControllerColliderHit Cube (2)"

"OnControllerColliderHit Cube (2)"

"OnControllerColliderHit Cube (2)"

"OnControllerColliderHit Cube (2)"

... 12 times.

"Below"

Why OnControllerColliderHit triggered 12 times in one frame?

# Answer
This happens because CharacterController performs multiple sub-movements on each `Move()` call, this can trigger multiple collisions.

You can get the first collision by setting a variable before each Move() and resetting in inside OnControllerColliderHit like this:

```
bool first;
void Update(){
    first = true;
    CharacterController.Move(moveAmount);
}

void OnControllerColliderHit(ControllerColliderHit hit){
    if(first){
        // do stuff
        first = false;
    }
    else{
        // ignore other collisions
        return;
    }
}

```
> 1 votes

---
Tags: unity
---


# Question
Title: Rigged blender model is deformed when imported into Unity
I am facing a strange problem with a model I rigged in Blender. Everything in Blender seems fine:

* All scales and rotations are normalized
* There is no unassigned vertex
* There is no weight bleeding from other bones

However when I imported the model in Unity, I am faced with some distortion happening in some of the model's meshes (it is a composite model).

Note that this doesn't seem to be happening for all bones or mesh components, but only for a couple of them.

Does anyone have any clue about why this is happening?

Thank you!

# Answer
I finally managed to solve this by noticing that in Blender the model was rotate 90° on the Z axis, which meant that the FBX exporter was getting confused over certain transforms.

By rotating this so that the axis were as supposed in blender and normalizing the rotation (`Ctrl+a > rotation`) I managed to solve this!
> 0 votes

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


# Question
Title: How should I approach AI for Spades game?
I was hoping some one could point me in the right direction about what type of AI you would use for a Spades game? For instance, would you create a behavioral tree or would you implement some other type of AI concept. I'm fairly new to AI which is why I'm hoping to get some AI vets to chime in.

# Answer
> 7 votes
I once programmed AI for Tarneeb, a card game very similar to Spades. The person I was working with wanted to do a pattern recognition thing involving lots of stored games and stats on the outcome based on what moves were done in different situations. In essence, the AI would become better over time the more games it played. However, from playing many hands and analyzing my own thought process, I determined that there were just a small number of "algorithms" I would employ to figure out what card I would play.

Thus the approach I took was to have the computer use a different algorithm depending on the situations, In each case it was pretty straightforward to go from the computer's current hand to deciding what play to make.

The situations were:

**Bidding:**

1. making the first bid,
2. making a bid after the first

**Playing:**

1. playing a new trick with Spades in hand,
2. playing a new trick without Spades,
3. playing into an already started trick with Spades,
4. playing into an already started trick without any Spades.

# Answer
> 2 votes
The current state of the art AI for trick-taking games such as Spades is a search algorithm like **MCTS**/UCT combined with **Supervised Learning** \[\].

---

My implementation of a Spade agent uses several **heuristics**, **Monte-Carlo sampling** and **Supervised learning**. My agent is stronger than recreational humans, but weaker than professional players. I describe it in my paper: https://ecai2020.eu/papers/235\_paper.pdf

Another source is AI-factory, they describe their Spades agents in a series of (5) papers, I would start from: Intergrating MCTS with knowladge based methods to create engaging play in commercial mobile game - AAAI13. See also their Article List on their site.

Note that an agent is a coupling of two completely separate algorithms: **bidding** and **playing**. From my experience, an agent that uses just **heuristics** can get to a level of an **intermediate** human. If you go in that path then you need to write a heuristic for each situation (there are quite a few), some of the parameters that need to be considered:

* In the **bid** phase: your hand, bids by other players, nil bids, scores.
* In the **playing** phase: first trick, leading/2/3/4th in the trick, number of played cards from that suit, can we take this trick, can we set a nil opponent, did we/opponents already made our/thier contract.

# Answer
> 0 votes
As thedaian said, this is indeed too broad of a question. But, for starters, you can have a look at what most board/cards games use: Minimax.

The trick is to have a state of the game and being able to properly evaluate how good in a position a given player is. Once you have solved this step, then you simply emulate X steps ahead to choose the best path the player should go.

# Answer
> -2 votes
Use expectimax (Russell and norvig Artificial intelligence 3rd edition). Alpha beta is possible with bounded evaluation function values)

---
Tags: ai, card-game
---


# Question
Title: Having trouble combining clampMagnitude and some explosion force
I have a character that uses `rigidbody`, and I am using `AddForce()` to make it move. And so I do `rb.velocity = Vector3.ClampMagnitude(rb.velocity, maxSpeed)` to limit diagonal speed. Yes that did worked but my problem is adding for example explosion force. So if explosion force is very high, it will still clamp the velocity of the player. What way should I use to combine `movement that limits diagonal speed` and a `properly working explosion force toward the player`. At least give a clue how can I do it?

My only main problem here is the way that I implemented to limit diagonal movement. I wanna improve that by not using `Vector3.ClampMagnitude()` so the `AddExplosionForce()` will work properly to the player. Because clamping magnitude of the player will also limit the velocity when it is affected by the explosion force.

So can anyone give a clue how can I implement to limit diagonal movement without using clamp magnitude?

I thought about normalizing the move like:

```
Vector3 move = transform.right * x + transform.forward * z;
move = move.normalized * Time.deltaTime * moveSpeed;

```

But I realized I am using `AddForce()`. Even though I limited the diagonal speed, it will go faster and faster because there is no maxSpeed. Help please.

# Answer
> 0 votes
Simply add an isExploding bool which is set to true in your AddExplosiveForce() function and divide your update into two parts, one is if (isExploding) and the second being the else block.

If it’s exploding, check the rigidbody’s velocity magnitude to see if it is less than your max velocity. If so, set isExploding to false. Else if not exploding, clamp the velocity.

You may need to wait a frame for the velocity to show up after adding the force (acceleration must be integrated), if so, simply make sure the explosive force is applied after the check for velocity clamp.

---
Tags: unity, movement
---


# Question
Title: Turning the Turret towards Player Object
I am trying to turn the enemy turret towards player object using the Armory 3D game engine with Blender. The script is written using Haxe. I am using the following code with both the player object and enemy object. Both have their Z values set to be the same (in this case zero):

```
public function turnTowardsPlayer()
{
var A:Transform = enemyObj.transform;
var B:Transform = player.transform;

var A1:Vec2 = new Vec2(A.loc.x,A.loc.y);
var B1:Vec2 = new Vec2(B.loc.x,B.loc.y);

// Finds the Direction Vector.
var res:Vec2 = B1.sub(A1);
// Calculates the angle to turn the turret.
var rot_Z = PI + atan2(res.x,res.y);
rot_Z = -rot_Z;
trace("  --------  ");
trace("rot_Z  in radians "+rot_Z);
trace( "Rot.Z in degrees " + (rot_Z * 180/PI));
trace("  --------  ");
enemyObj.transform.setRotation(0,0,rot_Z);
}

```

**The above code works well if there is no change in Z value.** Made following changes to take in to account of change in Z value.

```
var A2:Vec2 = new Vec2(A.loc.y,A.loc.z);
var B2:Vec2 = new Vec2(B.loc.y,B.loc.z);

var res_1:Vec2 = B2.sub(A2);
trace("res_1.Z   " + res_1.y);
var rot_X =  atan(res_1.y/res_1.x);
//rot_X = rot_X;
trace("rot_X  in radians "+rot_X);
trace( "Rot.X in degrees " + (rot_X * 180/PI));
enemyObj.transform.reset();
enemyObj.transform.setRotation(rot_X,0,rot_Z);

```

The above addition works only for a certain degree of accuracy. When the player moves either far right or far left from the initial position, the enemy bullet misses the player object. In the initial position the player is directly opposite to the enemy and the bullets from enemy hit the player correctly, with Z = 2m (in Blender units).

# Answer
While i am unfamiliar with the language you are using, i suggest using quaternions to solve this quite easily.

If the forward vector of the turret is pointed in the same direction as the barrel, then what you need to find is the quaternion which rotates your current forward vector, to the desired direction.

The desired direction is simply the target point minus the position of the turret. Now that you have your two vectors, use the functionality described in this article to determine the quaternion which rotates your vector to the desired direction.

What you choose to do from here is up to you. You can simply apply the quaternion if your math library allows it, or you can convert it to euler angles and/or apply the resulting rotation matrix.

Personally, if i wanted the turret to look cool, i would use slerp to make the barrel look like it is turning, rather than immediately point at the target.
> 0 votes

---
Tags: 3d, rotation, transformation, haxe
---


# Question
Title: Why can't I reference "targetVelocity" variable to this script?
Recently, I implemented a shooting system for my 2D game but this system has a problem. The problem is that when the player is facing left, the bullets are still being shoot to the right. For fixing this, I need to access a `Vector2` named `targetVelocity` to check whether the player is facing right or not. `targetVelocity` is defined in another script called `PhysicsObject` that is specifically for the player physics and the player script inherits from it (the variable was `protected` but I changed it to `public`). I just don't know how to reference this in my `Bullet` script and I don't want to add the player script to the bullet. Also, I've read the past questions and answers that were similar to this but I haven't found the answer yet because this is a different case. Thanks in advance.

**This is my `Bullet` script and I want to somehow reference `targetVelocity`.**

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

public class Bullet : MonoBehaviour
{
    [SerializeField] float speed;
    [SerializeField] float lifeTime;

    public GameObject destroyEffect;

    private void Start()
    {
        Invoke("DestroyBullet", lifeTime);
    }

    private void Update()
    {
        transform.Translate(Vector2.right * speed * Time.deltaTime);
    }

    void DestroyBullet()
    {
        Instantiate(destroyEffect, transform.position, Quaternion.identity);
        Destroy(gameObject);
    }

}

```

**Here is the weapon script.**

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

public class Weapon : MonoBehaviour
{
    public GameObject bullet;
    public Transform firePoint;

    private float timeBtwShots;
    public float startTimeBtwShots;

    private void Update()
    {
        if (timeBtwShots <= 0)
        {
            if (Input.GetButton("Fire1"))
            {
                Instantiate(bullet, firePoint.position, transform.rotation);
                timeBtwShots = startTimeBtwShots;
            }
        }
        else
        {
            timeBtwShots -= Time.deltaTime;
        }
    }
}

```

**This is the player script.**

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

public class NewPlayer : PhysicsObject
{
    [Header("Attributes")]
    [SerializeField] private float jumpPower = 10;
    [SerializeField] private float maxSpeed = 1;

    //Singleton instantation
    private static NewPlayer instance;
    public static NewPlayer Instance
    {
        get
        {
            if (instance == null) instance = GameObject.FindObjectOfType<NewPlayer>();
            return instance;
        }
    }

    // Update is called once per frame
    void Update()
    {
        targetVelocity = new Vector2(Input.GetAxis("Horizontal") * maxSpeed, 0);
        //If the player presses "Jump" and we're grounded, set the velocity to a jump power value
        if (Input.GetButtonDown("Jump") && grounded)
        {
            velocity.y = jumpPower;
        }
        //Flip the player's localScale.x if the move speed is greater than .01 or less than -.01
        if (targetVelocity.x < -.01)
        {
            transform.localScale = new Vector2(-1, 1);
        }
        else if (targetVelocity.x > .01)
        {
            transform.localScale = new Vector2(1, 1);
        }
}
}

```

# Answer
> 0 votes
The easy fix for your bullet is to grab once the direction on the start of creating your bullet and just let it fly that way. There could be more elegant solutions and the reference to the targetVelocity seems weird but this is what you asked for.

```
private Vector2 fireDirection;
private void Start()
{
    fireDirection = new Vector2(Math.Sign(NewPlayer.Instance.targetVelocity.x), 0);
    Invoke("DestroyBullet", 2);
}

private void Update()
{
    transform.Translate(fireDirection * speed * Time.deltaTime, Space.World);
}

```

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


title: How to stop sliding properly

text:
# Question
Title: How to stop sliding properly
I wanna stop immediately (not instantly) when I release a key so it would not slide. I don't wanna use `rb.isKinematic = false;` because it's just stopping so instant. So like I thought about:

```
x = GetAxisRaw("Horizontal");
z = GetAxisRaw("Vertical");

move = transform.right * x + transform.forward * z;

if (no inputs pressed)
{
   rb.AddForce(force * -maxSpeed); // maybe force will be the current velocity
}

```

I tried this but seems like nothing is hapenning. And so I think I need some improvements

# Answer
> 0 votes
You can use Unity’s rigidbody object to modify the drag property, which is used to modify the rate that an object slows down when not acted upon by outside forces.

Either that, or if you wanted to get down and dirty, simply do

```
velocity = velocity * 0.979;

```

every update tick when you would like to slow the object. Adjust the numerical value between 0 and 1 to achieve your desired rate of deceleration.

Drag is one of the most difficult things to model accurately. There are many different equations we use to model drag in the real world (it gets extremely complex) but typically for real time simulation in games, highly simplified versions are used. In the examples provided by this discussion, you can see that some people (and most physics engines) model drag using a quadratic value. This is perhaps more realistic, but not required to achieve the results you may be looking for.

I believe the equation for the force of drag they teach in beginner physics classes is typically Fdrag = -v * b where b is some constant value. This is essentially what you already had, but is a less desirable solution in games. In the end, choose the method that feels best for your project.

---
Tags: unity, movement
---


title: Translate code to DIRECTX directxmath

text:
# Question
Title: Translate code to DIRECTX directxmath
How can i translate the code to directxmath code?

```
// Create a quaternion that rotates about the world up
 Quaternion quatYaw = CreateFromAxisAngle( Vector3(0,1,0), yaw )
 // Transform the camera offset and up by this quaternion
 offset = Transform( offset, quatYaw)

```

Do i use XMQuaternionRotationAxis for CreateFromAxisAngle? And also, what function do i use for: Transform

I need to use functions from DIRECTXMATH https://docs.microsoft.com/en-us/windows/win32/api/directxmath/

# Answer
> Do I use XMQuaternionRotationAxis for CreateFromAxisAngle?

Yes.

> What function do I use for: Transform

You use XMVector3Rotate.

You can find these matches just by comparing the function signatures, or plugging "DirectXMath rotate vector by quaternion" into a search engine (this was on the first page of results)..
> 2 votes

---
Tags: c++, directxmath
---


# Question
Title: How can I assign disabled Text ui to array in the Inspector?
```
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class BlendShapesController : MonoBehaviour
{
    public Text[] texts;
    public bool startTalking = false;
    public float talkTime;
    public float duration;
    [Range(0, 100)]
    public float valueRange;
    private SkinnedMeshRenderer bodySkinnedMeshRenderer;
    private bool isTalking = true;

    // Start is called before the first frame update
    void Start()
    {
        bodySkinnedMeshRenderer = GetComponent<SkinnedMeshRenderer>();
    }

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

        if (startTalking && isTalking)
        {
            StartCoroutine(AnimateMouth());
            StartCoroutine(TalkTime());

            isTalking = false;
        }

        if (startTalking == false && isTalking == false)
        {
            isTalking = true;
        }
    }

    //Lerp between startValue and endValue over 'duration' seconds
    private IEnumerator LerpShape(float startValue, float endValue, float duration)
    {
        float elapsed = 0;
        while (elapsed < duration)
        {
            elapsed += Time.deltaTime;
            float value = Mathf.Lerp(startValue, endValue, elapsed / duration);
            bodySkinnedMeshRenderer.SetBlendShapeWeight(0, value);
            yield return null;
        }
    }

    //animate open and closed, then repeat
    public IEnumerator AnimateMouth()
    {
        while (startTalking == true)
        {
            yield return StartCoroutine(LerpShape(0, valueRange, duration));
            yield return StartCoroutine(LerpShape(valueRange, 0, duration));
        }
    }

    public IEnumerator TalkTime()
    {
        yield return new WaitForSeconds(talkTime);

        startTalking = false;
    }

    public void StartTalking()
    {
        for (int i = 0; i < texts.Length; i++)
        {
            if (texts[i].text != "")
            {
                startTalking = true;
            }
        }
    }
}

```

I want that if one of the ui texts is not empty and not disabled to start talking by calling the StartTalking method. The game start when all the ui texts are disabled one of them is not empty but they are all disabled. And during the game they are turning disabled enabled in the game and get empty not empty. On the ui text is not empty.

The problem is in the Inspector I can't drag disabled ui texts to the array of the script.

All the ui texts are childs under their own parents that are childs of the prefab name Game UI Texts.

This are the ui texts in the screenshot that should be dragged to the sccript on the right in the Inspector :

Scene Text , Description Text , and Long Distance Description Text

The main goal is to use one script to control automatic the talking with the text in the game. When there is a text in the game on the screen StartTalking and stop talking when there is no text on the screen.

# Answer
> 1 votes
If your current Text\[\] is still 0 as in the screenshot, you need to first increase the size of it to the amount you want to drag -\> 3. You can drag them regardless if they are enabled or not.

Now you should be able to drag each of the texts into the text array. There is no need to change the type of the Array to a GameObject Array, Unity is able to find the matching component as long as there is only one Text component on the dragged GameObject.

# Answer
> 0 votes
The array is of type Text, which is the type of a component, but you're trying to drag an object which contains the Text component, which is of type GameObject. Make your array of type GameObject\[\] and then use GetComponent or GetComponentsInChildren on the stored objects to get to the text itself.

EDIT: given the new info, I've included the import and type of the array you need:

```
using TMPro;

```

and then define the array as:

```
public TextMeshProUGUI[] texts;

```

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


# Question
Title: Interpolation on Rigidbody2D not working
I'm trying to achieve smooth movement for a ball. I seem to be failing to achieve this and now I've created a sample scene, which shows my setup from the game and the problem exists in that sample scene, as well.

**I've uploaded the sample project to github:** https://github.com/iQew/PhysicsTesting (open Assets/Scenes/SampleScene)

**Here's a recording of the problem. It's a bit more extreme here than it is in the editor, but it shows the problem even better because of it:** https://i.stack.imgur.com/xY30j.jpg

Scenario: I have a 2D mobile game (android) using Unity 2019.4.14f1 with URP. The camera does not move and will always have the same settings. The playfield consists of a certain area, which is blocked in by walls, which have a BoxCollider2D on them. The ball is a simple sprite with a CircleCollider2D, RigidBody2D and a Trail Renderer.

I have deleted all quality settings except the "Low" one, which has VSync Count set to "Don't Sync". In the Awake block of a controller script I set the Application.targetFrameRate to 60. In the Start block I use BallRigidBody2D.AddForce(new Vector2(1f, 10f), ForceMode2D.Impulse) to make the ball move.

The RigidBody2D of the Ball has the following settings:

* Body Type: Dynamic
* Material: DefaultBall (a Physics2D material with friction: 0 | bounciness: 1)
* Simulated: true
* Use Auto Mass: false
* Mass: 0.025f
* Linear Drag: 0
* Angular Drag: 0
* Gravity Scale: 0
* Collision Detection: Continous
* Sleeping Mode: Start Awake
* Interpolate: Interpolate

All other project settings are at default.

When I launch the game, the ball starts moving as expected. Most of the time the movement is smooth, but there is stuttering every now and then. I am wondering, if there is a way to make this stuttering go away. The tutorials I found on the internet, which solve this exact problem set the Interpolation mode of the RigidBody2D to "Interpolate", but I did that and there's no change.

There are no other scripts interfering with the physics calculation at all. So, I assume this has to do with some kind of project settings? Using a smaller Fixed Timestep does not help, in fact it gets a lot worse, if I use 1/120 for example.

Any help would be greatly appreciated!

# Answer
> 0 votes
I've added VSync back in and removed the targetFrameRate code. The stuttering is still visible in the editor, but on the target devices it's a lot better now.

# Answer
> 0 votes
I think the stuttering comes from your set resolution. The default aspect after your checkout was 3840x2160 which is about 4 times the size my screen can handle and even more so in the small preview window. I can see under Stats - Screen that it tried to render the 4k resolution into my 1483x616 game view. For every ~2.5 that it tried to render, it had only the space of one pixe;. The stuttering comes from the fact that the ball can't fit perfectly in and sometimes places it a pixel ahead or behind. Changing to Free Aspect and the ball was running smoothly.

Since you wrote that you are targeting mobile in the first place, it would be better to change the aspect to your test targets resolution and not what is your full monitor resolution (not many phones have that big of a resolution in the first place)

I lowered the fixed timestep to as much as 0.005 and the ball was still running smoothly between 100-120 fps on free aspect but it fell to around 30 on the 4k setting.

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


title: Unity3D: Firing a projectile from orbit

text:
# Question
Title: Unity3D: Firing a projectile from orbit
I am dropping bombs from a spaceship orbiting a planet. My camera is affixed to the ship.

I fire bombs by instantiating a bomb at the position of the camera, which is at all times facing toward the planet, however, the bomb is not intended to move directly toward the planet center. Rather, there is a movable crosshair between the camera and the planet and I want the bomb to move from the camera in the direction of the crosshair. My bomb script looks like this:

```
public class bomb : MonoBehaviour {

    public float speed;
    GameObject crosshair;

    // Use this for initialization
    void Start () {
        crosshair = GameObject.Find ("Crosshair");
        transform.SetParent (null);
        transform.LookAt (crosshair.transform);
    }

    // Update is called once per frame
    void Update () {
        transform.Translate (transform.forward * Time.deltaTime * speed);
    }

 }

```

My expectation is that the bomb instantiates at the camera, disassociates from its parent (the camera), turns to face the crosshair and then moves in that direction until it hits the planet.

But that's not what happens.

For reasons unknown, the projectile travels due left of the camera. So I adjust my projectile to move transform.right instead of transform.forward. And this works - half of the time.

Here's what it looks like on the West (working):

Here's what it looks like on the East (not working):

The projectiles are kind of small, but trust me, they're there.

As mentioned, my ship is orbiting the planet. If it is orbiting on one hemisphere (0:180), it shoots toward the planet, but if it is on the other hemisphere(0:-180), it shoots directly away from the planet. I can't explain this, because the camera continuously looks toward the planet, and the crosshair is always between the two, and the bomb disassociates from them anyway.

# Answer
When you move your projectiles like you did in this code:

```
transform.Translate (transform.forward * Time.deltaTime * speed);

```

it defaults into using `Space.Self` which takes into account all three position, rotation and scale of the object. this is why your code works on the west side but when rotating to the east side it no longer works.

so all you need to do is use `Space.World` in your `transform.Translate` method:

```
transform.Translate (transform.forward * Time.deltaTime * speed, Space.World);

```

this will move the object relative to unity's (0,0,0). this way no matter which direction your projectiles are facing they will always move forward.
> 0 votes

---
Tags: unity, rotation, orbit
---


title: Touchscreen controls for a game

text:
# Question
Title: Touchscreen controls for a game
I made a pc game recently (uni project) and now I want to put it on google market but I am having troubles changing original controls to touchscreen. The problem is that I don't really know what I can use for controls (tap, double tap, etc.) so the app is really easy to use. I will be incredibly grateful if you could share ideas for what types of controls can be used for my game.

The player controls a shield, which moves around the inner circle (originally the object follows mouse cursor). The player can also shoot with the shield to destroy obstacles, so the bullet is created inside the shield and then travels in the direction the shield was facing (the bullet is created on mouse click).

In the mobile version, the player controls the shield with his finger. It creates two problems: the player is not able to see some of the obstacles because his hand covers some parts of the screen. Also, it means I cannot use simple tap (or at least I don't know how) for shooting, which makes the controls unintuitive. To shoot the player has to touch the screen with two fingers. It is not a common gesture, so people won't think of using it straight away unless told what to do. And the main point of my game is that there are no words at all and people are expected to understand controls without any tutorials. Also, the game relies on quick reactions, so controls cannot be complicated.  Thank you!

# Answer
> 0 votes
Regarding Movement: As Bálint suggested in a comment, move the shield by pointing it away from where the user holds their finger. It might be a bit more difficult to implement, but I think you could get even better results by allowing the player to have their finger anywhere. Don't track the absolute position of touch events, track the relative finger-movement of drag gestures. When the user drags their finger 45° around the center, also turn the shield by 45°. Think of the whole playing field like a record turntable.

Regarding shooting: Many smartphones have pressure-sensitive touchscreens. It is pretty standard for Android since the first models. iPhones are pressure-sensitive since the iPhone 6. You can use light pressure for movement and strong pressure for shooting.

# Answer
> 0 votes
An immediately obvious interaction would be to use accelerometer input. As the user tilts their device, they would see the shield moving, and they can’t help but tilt it a little bit while holding it. Then just use tap to shoot. No hand getting in the way normally.

# Answer
> 0 votes
The simplest solution for the problem of fingers touching the visual part of the screen is to place the controls in a location separate and distinct from the action.

"Reversing direction" for the shield might work, but I imagine from your description that "enemies" could easily appear from any angle? So having your thumb anywhere near the "circle and shield" would obscure potential "enemies". The only solution, if that is true, is to place the controls in a separate location. A simple circle at the bottom that you slide your thumb around would work well.

For the problem of having two controls using one finger, two solutions present themselves.

1. Have a "fire" button next to or as the circle on the bottom. This would mean losing control of the direction for a moment, but the proximity would limit the time lost switching.
2. Have the "player" firing constantly if "enemies" are present on the screen. The question to ask for this solution is "Do I need the player to be able to fire intermittently, or is constant-fire a viable approach?"

# Answer
> 0 votes
If you don't want the players hands covering the screen, it would be a good idea to move the controls away from the action or make the touch input instantaneous like using taps.

So for movement you can have the player tilt the device, or just tap the direction they want the shield to cover.

And for shooting you might want to implement automatic shooting so if the shield faces an enemy it shoots it or the player can tap on an enemy and the shield would move in that direction and shoot.

But regarding design questions like this it is pretty hard to come by a perfect solution.

So what I would recommend is to implement multiple ways to control the shield and letting the player choose which one they like.

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


# Question
Title: How to Detect a Right Mouse Click on a UI Button in Unity
I've been recently working on a videogame, and I'm trying to make a script that will destroy the game object it is applied to whenever the right mouse button is clicked on it. It doesn't function at all and I don't receive any error messages in the Console. Here is all my code:

```
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class RightClick: MonoBehaviour, IPointerClickHandler
{
    // Initiates whenever the pointer is clicked
    public void OnPointerClick(PointerEventData eventData)
    {
        // Destroys item from players inventory when pressed
        if (eventData.pointerId == -2)
        {
            // Removes object from inventory
            Object.Destroy(this.gameObject);
        }
    }
}

```

I have searched for hours on this topic and have only found extremely outdated sources, please help me!

# Answer
> 1 votes
Add this script to your button.

```
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine.Events;

public class UIClickHandler : MonoBehaviour, IPointerClickHandler
{
    public UnityEvent onLeftClick;
    public UnityEvent onRightClick;
    public UnityEvent onMiddleClick;

    public void OnPointerClick(PointerEventData eventData)
    {
        if (eventData.button == PointerEventData.InputButton.Left)
        {
            onLeftClick.Invoke();
        }
        else if (eventData.button == PointerEventData.InputButton.Right)
        {
            onRightClick.Invoke();
        }
        else if (eventData.button == PointerEventData.InputButton.Middle)
        {
            onMiddleClick.Invoke();
        }
    }
}

```

I steal it from here.

---
Tags: unity, unity-ui
---


# Question
Title: How to flip the player without local scale and velocity problems?
I'm making a 2D game with Unity. Recently, I've implemented a shooting system. I wanted to change bullets direction based on the player's facing but since the flipping code was changing the local scale based on velocity (.01 and -.01), the bullets were suspended in the air when the player was not moving but was shooting. I ended up using local scale and a bool variable but there are still some problems. Since this code was changing the local scale to 1, the player size was getting so bigger at the start of the game. I wanted the player to have a float type scale which is smaller and more suitable for my game, so I parented an empty object to the player and this solved the problem but now it shakes weirdly at the start of the game . This is a GIF that shows the shaking problem. I thought it is definitely due to the scale change but after removing that line of code, I could see it again. So it might have another reason but I don't know what is that. Also, the previous code was using `Input.GetAxis` (which was helpful for supporting gamepad) but now I can't seem to find a way to use it again without getting errors because the code has been changed.

In general, my goal is fixing these problems:

* The player's shaking at the start of the game
* A way to use `Input.GetAxis` to support the left analog stick and D-pad like the past
* A flipping code that flips the player and its children but does not cause any problems for the bullets direction and shooting system

**Here's my player script.**

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

public class NewPlayer : PhysicsObject
{
    [Header("Attributes")]
    [SerializeField] private float jumpPower = 10;
    [SerializeField] private float maxSpeed = 1;

    [Header("References")]
    [HideInInspector] public bool isFacingLeft;

    //Singleton instantation
    private static NewPlayer instance;

    public static NewPlayer Instance
    {
        get
        {
            if (instance == null) instance = GameObject.FindObjectOfType<NewPlayer>();
            return instance;
        }
    }

    void Update()
    {
        if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
        {
            rb2d.velocity = new Vector2(maxSpeed, rb2d.velocity.y);

            GetComponent<SpriteRenderer>().flipX = true;

            isFacingLeft = false;
        }

        else if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
        {
            rb2d.velocity = new Vector2(-maxSpeed, rb2d.velocity.y);

            GetComponent<SpriteRenderer>().flipX = false;

            isFacingLeft = true;
        }

        else if (grounded)
        {
            rb2d.velocity = new Vector2(0, rb2d.velocity.y);
        }

        if (Input.GetButtonDown("Jump") && grounded)
        {
            rb2d.velocity = new Vector2(rb2d.velocity.x, jumpPower);
        }

    }
}

```

**This is from the old script where I used both velocity and local scale for flipping. (this and my current script inherit from another script called Physics Object which handles the physics and has a definition for target velocity.**

```
  void Update()
    {
        targetVelocity = new Vector2(Input.GetAxis("Horizontal") * maxSpeed, 0);

        if (Input.GetButtonDown("Jump") && grounded)
        {
            velocity.y = jumpPower;
        }
        //Flip the player's localScale.x if the move speed is greater than .01 or less than -.01
        if (targetVelocity.x < -.01)
        {
            transform.localScale = new Vector2(-1, 1);
        }
        else if (targetVelocity.x > .01)
        {
            transform.localScale = new Vector2(1, 1);
        }
}
}

```

**And this is the weapon script. Here, I used `isFacingLeft` parameter to change the bullets direction.**

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

public class Weapon : MonoBehaviour
{
    public GameObject bullet;
    public Transform firePoint;
    private bool isShooting;
    [SerializeField]
    private float shootDelay = .5f;

    private void Update()
    {
        if (Input.GetButtonDown("Fire1"))
        {
            isShooting = true;
            GameObject b = Instantiate(bullet);
            b.GetComponent<Bullet>().StartShoot(NewPlayer.Instance.isFacingLeft);
            b.transform.position = firePoint.transform.position;

            Invoke("ResetShoot", shootDelay);
        }
        void ResetShoot()
        {

        }
    }
}

```

# Answer
For flipping the player character you can use the SpriteRenderer component directly to flip the character without changing the scale.

```
private SpriteRenderer spriteRenderer;
void Awake()
{
    spriteRenderer = GetComponent<SpriteRenderer>();
    if (!spriteRenderer) Debug.LogError("Can't Find the Sprite Renderer");
}

void Update()
{
    if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
    {
        spriteRenderer.flipX = false;
    }

    else if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
    {
        spriteRenderer.flipX = true;
    }
}

```

this will flip your character on the X axis and setting in to `false` will flip your character to the default side.

Alternatively, you can shoot the bullets in world space, you can read more about it here.

Basically by moving your bullets in world space they will move relative to the original (0,0,0) coordinates of unity and your bullets will not be effected by the scale or the position of the player.
> 0 votes

# Answer
Instead of setting the localScale, you can use rotation to achieve a similar effect:

```
transform.Rotate(Vector3.up * 180);

```

This will "flip" your object by rotating 180 degress around the up axis. This should help to avoid some of your scale difficulties.
> 0 votes

---
Tags: unity, c#, input, scale, gamepad
---


# Question
Title: Unity: How can I find the center position of a particular triangle?
I need to face an object from a central point directly through any one of many triangles which are faces on an icosphere whose position is centered on that point. Is there a way to get the center position of the triangle itself, even though its position is the position of the larger object of which it is a part?

# Answer
There are actually tens of thousands of well defined triangle centers.

The centroid is always a safe and fast center, which is simply the sum of the 3 points which define the triangle, divided by 3 (or multiplied by 1/3rd, which is the faster operation)
> 1 votes

---
Tags: unity, mesh, face, position
---


title: A terrain with underground tunnels

text:
# Question
Title: A terrain with underground tunnels
The Terrain tool in Unity is great for constructing 3-D landscapes that are open from above. I am working on a game that happens entirely inside tunnels (specifically, blood vessels in a human body. But it can also be tunnels in an ant nest, or sewers below a city). There is nothing "overground" - all movement is inside the tunnels. I am looking for a tool, similar to Terrain, for easily constructing this complex system of tunnels.

One solution I thought of is to construct a terrain with "half tunnels" (i.e., open from above), then duplicate it, rotate 180 degrees, and "glue" on top of the first copy. But it can only handle one layer of tunnels, and in addition, for some reason I could not rotate the terrain.

Is there a way to construct such underground tunnels with the Terrain tool, or with a different tool in Unity?

# Answer
I think, you can use something called Marching Cubes to make your own tunnel making tool. This video from Sebastian League should help you understand it quickly. It Explains how he used it to make his own tunnel making tool. https://www.youtube.com/watch?v=M3iI2l0ltbE
> -1 votes

---
Tags: unity, terrain, world-design
---


title: Why are setcolor and color not reset

text:
# Question
Title: Why are setcolor and color not reset
When I do a color exchange directly on the material in playmode, but then I go back to editmode, why do the settings still remain?

For example:
`mymaterial.SetColor("_Color", blue);`
or
`mymaterial.color = blue;`

# Answer
> 0 votes
This actually has nothing to do with `SetColor` and `color`, and everything to do with the difference between *Scene Objects* and *Assets*.

For data in your scene, like Game Objects in your scene hierarchy and their Components, as well as some lighting settings, Unity saves a copy of the open scenes just before entering Play Mode. When you exit Play Mode, it restores the saved copy, effectively erasing/resetting any changes that occurred in your scene while the game was running.

But asset files like Materials, Textures, Scriptable Objects, *prefabs* of Game Objects etc. do not live in your scene. They're their own independent asset files in your project folder. So they're not swept up and saved this way when entering Play Mode, or reverted afterward.

This can be useful, if you want to tune a material to look just right, or a set of gameplay parameters to feel just right in a particular moment of play, then exit play mode and keep your changes.

If you don't want to modify your source asset in this way, then you should create a copy of it. This will occur automatically if you use the `Renderer.material` or `Renderer.materials` property getters. But you can also copy it manually with:

```
var myMaterial = Instantiate(sourceMaterial);

```

Then you can modify `myMaterial` without those effects spilling over into persistent changes to your source asset on-disc.

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


# Question
Title: Programming with Python in a recent version of Minecraft
I've been teaching Python programming to a friend's son using the book Adventures in Minecraft. This book comes with a starter kit that contains a pre-configured Bukkit (v.1.6.4) server, and targets Minecraft 1.6.4.

My friend's son would like to use a more recent version of Minecraft, unfortunately Bukkit is no longer maintained.

Is there another way to use Python with Minecraft? I've googled a bit but without success. I'm not a player of Minecraft myself so there is a lot of Minecraft terminology that I don't understand.

Thanks

# Answer
There are a wide variety of ways to interact with Minecraft programatically, including an official Javascript "add-on" API to the "bedrock" version of Minecraft, APIs for Minecraft servers, unofficial hacks on the client side to the Java version of Minecraft, and other specialized offerings. They are briefly introduced at Minecraft modding (Wikipedia) and covered in more detail at the Official Minecraft Wiki. (*I'd love to see a good comparison of how comprehensive each approach is, and how the APIs compare....*)

Here I'll cover just one approach, which explains how to connect with Python to a "Spigot" Minecraft server and manipulate the world and players. It supports a Python 3 API rooted in the *Minecraft: Pi Edition* for Raspberry Pi described at \<Stuff about="code" /\>: Minecraft.

The full explanation, with videos for a Windows 10 environment, is at Learn Python With Minecraft — Part 1: Setting Up The Environment | by Carlos Argueta | Medium. Here is a quick summary of the steps, as I did them in Debian Linux "Buster" in the standard Crostini virtual environment on a Chromebook (Pixelbook Go):

* Download Minecraft (Java version)
* If necessary, download and install Python, e.g. version 3.8
* Download Carlos' Minecraft server, which seems to be based on Spigot and CraftBukkit, from https://sourceforge.net/projects/learn-python-minecraft-win/files/latest/download
* Unzip Carlos' server
* Run `python -m pip install minecraftPythonAPI.zip`
* Start the server up via `java -Xmx1024M -Xms1024M -jar spigot.jar` (Carlos provides a `.bat` file for that for Windows). When you run spigot for the first time, it automatically creates a new Minecraft world for you
* Notice which version of Spigot you're running. It is listed towards the top of the output of the java command, and is currently 1.14.4. More specifically in my case: `[Server thread/INFO]: This server is running CraftBukkit version git-Spigot-ea7e48b-368f4e9 (MC: 1.14.4) (Implementing API version 1.14.4-R0.1-SNAPSHOT)`
* You need to launch the same version of Java Minecraft as you're running on the server. That requires using the Minecraft launcher, and downloading a different version (currently 1.14.4) as shown in his video number 5.
* Run the matching version in multiplayer, and add your server, by specifying a network address as "localhost".
* Note that Minecraft defaults to creative mode
* Run some Python code like this, which just shows where the player is, and then moves the player:

```
from mcpi.minecraft import Minecraft
mc = Minecraft.create()
PlayerTile = mc.player.getTilePos()
print(PlayerTile)
mc.player.setTilePos(0, 140, 0)

```

See also an early demo of the Pi interface but note you have to change two lines to import via `mcpi` rather than `minecraft`, e.g.
`import mcpi.minecraft as minecraft`.

More code snippets are at the github repo Learn-Python-With-Minecraft

A completely different option out there might also be of interest. It allows Python programming for Minecraft version 1.12.2 from 2017, and is supported with these instructions, which covers installing the older version, and handles Python 2.7 or 3: Python Coding for Minecraft : 18 Steps (with Pictures) - Instructables. There are recent comments from the author so it seems to still be relevant.
> 4 votes

# Answer
Using `jycraft` and Spigot, I think you could easily get a server up and running with python.
> 1 votes

# Answer
Minecraft Education Edition (https://education.minecraft.net/) offers an immersive integration with Python, however this requires an educational account so that's not a general solution for everyone.

Besides this, there are a number of Java environments, but I don't know about Python environments. I did find this article: https://medium.com/@kidargueta/learn-python-with-minecraft-part-1-setting-up-the-environment-fa0c7f9e3ca6
> 1 votes

# Answer
Unfortunately, Minecraft mods are (as far as my knowledge goes) coded in Java. But, you might be able to convert the .py files into .jar using a program such as **Jython**. I steal it from here:

Distributing Python Scripts as Jar Files with Jython
> 0 votes

# Answer
You could get a Raspberry Pi which has a special version of Minecraft that can easily be scripted with Python. The default OS for Raspberry Pi's is a Debian fork called Raspbian which comes with the special version of Minecraft preinstalled.

There are tons of tutorials online and Mag Pi #41 is actually dedicated to Minecraft creations.

Here is a link to the tutorial I first used after getting my Pi. It starts with the very basics and will walk him through all the steps involved in creating mods with Minecraft.

https://www.raspberrypi.org/learning/getting-started-with-minecraft-pi/

A Raspberry Pi can be had for ~$35 dollars and most people have all the other peripherals needs(Micro SD card, Micro USB for power, keyboard, mouse, monitor).

As a side note if he ends up liking programming there are tons of cool projects that can be done with a Raspberry Pi with varying degrees of difficulty.
> -1 votes

---
Tags: python, minecraft-modding
---


# Question
Title: Downsides of using a large texture atlases?
So I am using Unity to build a 2D game and one thing that I needed is to be able to render a lot (talking about 10s of thousands) of sprite to the screen so I have a custom solution that basically is a single game object with a script that uses `Graphics.DrawMesh()` with pretty good results right now. Now I know another way to reduce draw calls is to have a few materials as possible (as I believe a single mesh can only use 1 material) so I was think about using a 8192 x 8192 texture as basically my main (maybe only texture) as with 64 x 64 sprites, I can fit a bit over 16000 sprites which should be more than enough for all the sprites in the game world).

My question is whether or not there is any major downside of using a texture of this size? I am sure there are decides and video cards that would not support this but I am curious as to what those are. Would current gen / next gen consoles support this? At what point would video card not support this? For the game I am working on mobile / VR is not a concern.

If this texture size would restrict support too much, what about 4096 x 4096?

# Answer
The downside is that you will have to load the entire spritesheet.

When you load level 1, you need to load the entire sprite sheet that contains even a single asset on it from level 1. This means you will be loading all of the sprites for level 2, 3, 4, and 5 as well.

If you were to have a separate sprite sheet for each level, you only load the sprites needed for that level. So when you load level 1, you get the sprites for level 1, and levels 2-5 remain unloaded.

(I know this answer is a bit vague - that is because I do not know the specifics of how Unity is loading those sprites. But this should give you a general idea.)
> 2 votes

# Answer
Most current devices should be able to support an 8192 x 8192 texture, but the possible problem you might run into is how it might slow down the game’s performance significantly. This depends on a few factors. Below I have a list that determines this:

* GPU limits: some older/weak mobile GPUS limit textures to 512/1024. Most modern ones will handle at least 2048.
* VRAM limits: this will limit the overall number of textures you can have loaded at once without going out to slower system RAM. If the device supports it, texture streaming can work around it.

I found that article snippet from here: Maximum Texture for Mobile Devices in Unity
> 1 votes

---
Tags: unity, 2d, performance
---


# Question
Title: How do I refer to the two types of loading screen?
I'm troubleshooting some issues beyond the scope of this forum, and I'd like to be able to talk about certain parts of the gaming experience, specifically the two types of loading screen I see in Prey.

Both are shown in this short video I made.

The first type with the loading bar is what I usually think of as the "loading screen", but what do I call the second "loading screen" that happens right after with the moving squares in the bottom-right? To be clear, I'd like a term to be used with non-game-devs.

# Answer
> 0 votes
The first is a classic "progress bar", or when it's specifically to visualize loading, a "loading bar".

UI designers call the second a "loading spinner". Or when it's not spinning but doing something else, a "loading indicator". It's useful to visualize to the user that something is still happening in the background when you don't have any means to estimate how long that process will take.

---
Tags: rendering, terminology, loading
---


# Question
Title: How can I build a virtual barrier to block and prevent from the player to keep moving forward?
This is my logic :

When the player is moving I'm getting the distance from another object.

When the player is at distance for example 61 slow down the player moving "Forward" until the player stop and can't move any further forward.

The same logic should be applied for any direction the player is moving from the object not only from the object front or the sides 360 degrees no matter where the player is moving to when the distance is 61 start slow down the player to stop.

The next logic/rule is one of my biggest problem :

When the player is rotating by me and facing the other direction the give the player to option to move again this time make the player start moving again from slowdown to the regular walking speed. but only if the player is facing the other direction.

Now the problems I'm facing :

When the player moved forward reached distance 61 then start slow down and then stop, if the player is rotating facing the other direction and start moving back even a bit for a millisecond then if I rotate the player to the forward direction again he can move again and pass the distance 61. This way even if the player stopped already I can cheat the block by rotating facing the player the other direction moving only a bit then rotating back again and move much more. I need some how to make that if the player stopped then rotating the other direction start walking again only if he reach some distance like 50 or 40 then he can rotate back and move forward again and slow down and stop at distance 61.

The second problem is when I'm moving far away from the object but in another place from the side or from the back then the player is walking/running automatic and everything get messed. The play not stopping not slow down.

I can record a very short and small video clip to show what I mean, What it's doing so far and what are the problems if the video clip maybe will be more help to understand what I'm trying to do.

This is a short video clip I recorded showing the problem/s.

The problem/s I shot it starting from second 37 : in this case the distance is checked from the big space ship behind the player.

https://www.youtube.com/watch?v=Rrw\_swX5Q8A&feature=emb\_logo

```
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityStandardAssets.Characters.ThirdPerson;

public class DistanceCheck : MonoBehaviour
{
    public GameObject distanceTarget;
    public GameObject longDistanceDescriptionTextImage;
    public TextMeshProUGUI text;

    private Animator anim;

    float timeElapsed = 0;
    float lerpDuration = 3;
    float startValue = 1;
    float endValue = 0;
    float valueToLerp = 0;

    // Opposite Direction
    float timeElapsedOpposite = 0;
    float lerpDurationOpposite = 3;
    float startValueForOpposite = 0;
    float endValueForOpposite = 1;
    float valueToLerpOpposite = 0;

    float angle;

    // Start is called before the first frame update
    void Start()
    {
        angle = transform.eulerAngles.y;
        anim = transform.GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        var distance = Vector3.Distance(transform.position, distanceTarget.transform.position);
        angle = transform.eulerAngles.y;
        if (distance > 61f && angle < 180)
        {
            if (timeElapsed < lerpDuration)
            {
                valueToLerp = Mathf.Lerp(startValue, endValue, timeElapsed / lerpDuration);
                anim.SetFloat("Forward", valueToLerp);
                timeElapsed += Time.deltaTime;
            }
            anim.SetFloat("Forward", valueToLerp);
            timeElapsedOpposite = 0;
            longDistanceDescriptionTextImage.SetActive(true);
            text.text = "I can't move that far by foot. I need to find some transportation to move any further.";
        }

        // Get the angle:

        if (angle > 180f && distance > 61f)
        {
            text.text = "";
            longDistanceDescriptionTextImage.SetActive(false);

            if (timeElapsedOpposite < lerpDurationOpposite)
            {
                valueToLerpOpposite = Mathf.Lerp(startValueForOpposite, endValueForOpposite, timeElapsedOpposite / lerpDurationOpposite);
                anim.SetFloat("Forward", valueToLerpOpposite);
                timeElapsedOpposite += Time.deltaTime;
            }
            anim.SetFloat("Forward", valueToLerpOpposite);

            timeElapsed = 0;
        }

        if (distance > 61f && Mathf.Abs(anim.GetFloat("Forward")) < 0.003943384f)
        {
            anim.SetBool("Idle", true);
        }
        else
        {
            anim.SetBool("Idle", false);
        }
    }
}

```

# Answer
> 0 votes
There’s a million ways to do this, here’s a few easy ways off the top of my head:

1. You could make a distance joint with unity’s configurable joint pretty easily using linear limits. Make sure to use the spring dampener as mentioned, it will make your character softly bump the edge of the boundary.
2. Instead of constraints, you could simply attach 4 objects with no renderer, only a box collider. Make the boxes very tall and box your player in. Super simple. Disable the objects when the character has a vehicle.
3. This one is a bit odd, but you could create an object with no renderer and make one big inverted box or sphere collider. It would (in theory) keep your character from passing outside.

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