title: Enabling anchors in gameplay mode

text:
# Question
Title: Enabling anchors in gameplay mode
Basically, I was attempting to write a piece of code that alters the position of an object dynamically, so, I think moving anchors around would also be necessary. If I move them around dynamically, it would be great if I could preview them moving in the unity editor dynamically. Is there a way to enable them in gameplay mode?

Below is the screenshot of gameplay vs. scene mode:

As you can see, the anchor is not visible in gameplay mode. I'd like to make it visible, so, I can see the results in real-time when I'm programmatically altering the anchors.

# Answer
> 4 votes
> Is there a way to enable them in gameplay mode?

The purpose of anchors is that they can be edited in the Scene window. You can't edit them in the Game window (like many other editable stuff), so there is no need for them to be visible there. But you can use Gizmos to visualize their positions in the Game window even when the game is not running. To do this add either OnDrawGizmos() or OnDrawGizmosSelected() methods to your MonoBehaviour class. There are various forms of Gizmos visualization available:

Example:

```
/// <summary>
/// Draw wired cube at `transform.position` of the current object.
/// </summary>
private void OnDrawGizmos()
{
    float cubeSize = 0.1f;
    Gizmos.color = Color.white;
    Gizmos.DrawWireCube(transform.position, Vector3.one * cubeSize);
}

```

In your case, you should add `Gizmos.*` drawing for each anchor position you want to be visible and replace `transform.position` with their actual positions. Keep in mind that Gizmos methods accept position and size parameters in world coordinates.

Here is an example of a component class that shows (visualizes with Gizmos) its anchors both in Game and Scene windows:

```
[DisallowMultipleComponent]
public class ShowAnchors : MonoBehaviour
{
#pragma warning disable CS0649

    [SerializeField]
    private float _gizmosSize = 5f;

    [SerializeField]
    private Color _color = Color.white;

#pragma warning restore CS0649

    private void OnDrawGizmos()
    {
        RectTransform rt = transform as RectTransform;

        if (!rt)
            return; // the object is not an UI element

        if (!rt.parent)
            return; // the object doesn't have a parent

        Gizmos.color = _color;
        RectTransform parent = rt.parent as RectTransform;
        Rect parentRect = parent.rect;
        Matrix4x4 mat = parent.localToWorldMatrix;
        Vector2 minPos = parentRect.min + new Vector2(rt.anchorMin.x * parentRect.size.x, rt.anchorMin.y * parentRect.size.y);
        Vector2 maxPos = parentRect.min + new Vector2(rt.anchorMax.x * parentRect.size.x, rt.anchorMax.y * parentRect.size.y);

        // Anchor positions in screen coordinates.
        Vector2[] anchors = new Vector2[4]
        {
            minPos,
            new Vector2(minPos.x, maxPos.y),
            maxPos,
            new Vector2(maxPos.x, minPos.y)
        };

        for (int i = 0; i < anchors.Length; i++)
        {
            Vector3 anchor = anchors[i];
            // convert anchor position from screen to world coordinates
            Vector3 worldPos = mat.MultiplyPoint(anchor);
            // make gizmos look the same size for different camera projections & sizes
            float size = constGizmoSize(worldPos);
            // draw point
            Gizmos.DrawSphere(worldPos, size);
            // draw line
            Vector3 dir = Vector3.ClampMagnitude(_dirs[i], size * 2);
            Gizmos.DrawLine(worldPos, worldPos + dir);
        }
    }

    private static readonly Vector3[] _dirs = new Vector3[4]
    {
        Vector2.left + Vector2.down,
        Vector2.left + Vector2.up,
        Vector2.right + Vector2.up,
        Vector2.right + Vector2.down,
    };

    private float constGizmoSize(Vector3 position)
    {
        Camera camera = Camera.current;

        if (!camera)
            return _gizmosSize;

        position = Gizmos.matrix.MultiplyPoint(position);
        Transform transform = camera.transform;
        Vector3 position2 = transform.position;
        float z = Vector3.Dot(position - position2, transform.TransformDirection(new Vector3(0f, 0f, 1f)));
        Vector3 a = camera.WorldToScreenPoint(position2 + transform.TransformDirection(new Vector3(0f, 0f, z)));
        Vector3 b = camera.WorldToScreenPoint(position2 + transform.TransformDirection(new Vector3(1f, 0f, z)));
        float magnitude = (a - b).magnitude;
        float size = _gizmosSize / Mathf.Max(magnitude, 0.0001f);
        return size;
    }
}

```

Add it to the UI elements and you'll get a picture in the editor like this:

(added to the `Button`(red) and its child `Text`(green))

---

> If I move them around dynamically, it would be great if I could preview them moving in the unity editor dynamically.

Could you explain this more clearly?

---
Tags: unity, rendering
---


# Question
Title: How does Unity use C# as a scripting language?
To my knowledge, thus far, I have thought that C# is and has always been a compiled language. I have recently started studying Unity3d and noticed that they give C# as an option for scripting and interacting with game objects through their API (along with JavaScript and a couple of other alternatives).

How is this done? Is C# actually being executed or is this an abstraction that is being converted to a different scripting language under the covers? It seems to me that there is some sort of interpretation going on for this functionality.

# Answer
> 16 votes
Unity is using Mono behind the scenes. Every time you make a change to your C#/UnityScript scripts it recompiles the code almost instantly.

If you look in the data directory of a standalone unity player, you can see it has compiled all the scripts into Assembly-CSharp.dll, or similar.

So yes, the C# is being compiled.

# Answer
> -2 votes
C# is an object oriented programming language - it needs to be compiled before ran. Just because it is widely used in Unity3d, don't let its ease and flexibility fool you.

# Answer
> -4 votes
First, scripting languages are not necessarily interpreted languages. Some scripting languages such as Lua and Python can be either JIT-compiled or interpreted.

And, as for the question itself: because C# is a scripting language, but Microsoft does a good job on making it not look as such.

C# has everything a scripting language needs: dynamic typing, JIT-compiling rather than static compiling, runs in a virtual machine...

---
Tags: c#, scripting, mono
---


# Question
Title: LibGDX - Actors added to a stage from a network thread are not drawn
I have an application with several `Screen` and `Actor`. On my main screen, the actors added to the stage during creation are rendering fine.

However, I have a Netty server running, and when it receive certain events, it adds, in the network thread, new actors to the stage. These are never drawn, despite the main thread continuing to call the render function of the corresponding screen.

In the code below, if I call `recieveInbound` from the Screen's `show` by mocking the exact same network payload, the actors are drawn as expected.

**What am I doing wrong?**

*MainScreen.java*

```
// ...

public MainScreen(Game game) {
    batch = game.getBatch();
    viewport = game.getMainViewport();
    stage = new Stage(viewport, batch);

    try {
        capabilities = GL.getCapabilities();
    }
    catch (IllegalStateException e) {
        capabilities = GL.createCapabilities();
    }
}

/**
 * Receives and manages signals from the remotes.
 *
 * @param code The received code
 * @param object The received payload
 */
public void receiveInbound(int code, Object object) {

    // Restore OpenGL context if needed before processing.
    try {
        GL.getCapabilities();
    }
    catch (IllegalStateException e) {
        GL.setCapabilities(capabilities);
    }
    // LOGGER.debug(stage.getActors().size); <-- 1 added in show, as expected
    if (code == 10) {
        LevelMap map = mapManager.serve(code, object);
        stage.addActor(map.getBackground());
        Arrays.stream(map.contentMatrix)
            .forEach(row -> Arrays.stream(row)
                .forEach(stage::addActor)
            );
    }
    // LOGGER.debug(stage.getActors().size); <-- 854, as expected
}

@Override
public void render(float delta) {
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL33.GL_COLOR_BUFFER_BIT);
    batch.setProjectionMatrix(viewport.getCamera().combined);
    // Expected position, actors are around there.
    viewport.getCamera().position.set(0,0,0);
    stage.act();
    stage.draw();
}

```

# Answer
> 0 votes
If you are communicating with game using another thread, then bugs can happen. In such cases you can execute code on main thread using this code:

```
Gdx.app.postRunnable(new Runnable() {
    @Override
    public void run () {
        // put your code here
    }
});

```

---
Tags: libgdx
---


# Question
Title: Can anyone tell me how to implement ammo types in C#
I want to implement an ammo changing mechanism for my game and I know how to do it with array index, is there another easy way to implement this feature in C#, Thanks in advance.

# Answer
Your best bet is to use Enum

```
enum AmmoType
{
    Heavy,
    Light,
    Sniper,
    Energy
}

```

More references: Unity Tutorials, GFG
> -1 votes

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


# Question
Title: How do I keep the camera behind the player?
I am developing a Third Person Shooter.

Until now, I had parented the camera to player. It would therefore automatically stay behind the player.

Because this would not work well with Root Motion, I need to use a different approach:

In my script, I need to make it so that the camera follows the player.

How could I make it so that the camera stays behind the player at always the same position (and with the same rotation)?

This is my current code, but it doesn't work:

```
    _camera.transform.rotation = Quaternion.Euler(0, this.transform.rotation.eulerAngles.y, 0);
    _camera.transform.position = _InitialCamPos + this.transform.position;

```

Can anybody help?

Thank you!

# Answer
It looks like you want something like this:

```
// Get a "yaw-only" rotation without relying on Euler angles.
var forward = transform.forward;
forward.y = 0;
_camera.transform.rotation = Quaternion.LookRotation(forward);

// Map the camera position from the player's local space to world space.
_camera.transform.position = transform.TransformPoint(_InitialCamPos);

```

Here `_InitialCamPos` is measured in the local coordinate system of `this` object. So for instance if the character's origin is at its feet, and you want the camera to be 1 m above that and nudged 0.1 m forward, that's (0, 1, 0.1). The `TransformPoint` method will automatically handle adjusting this based on the character's rotation and translation.

If you need to determine `_InitialCamPos` dynamically based on where the camera was at scene load time, you can use something like this:

```
void Awake() {
     _InitialCamPos = transform.InverseTransformPoint(_camera.transform.position);
}

```

This maps a world space point into the object's local coordinate system.
> 2 votes

# Answer
Create an empty `gameobject` as a `child` of your `player` then attach the `camera` to the empty `gameobject` and reposition `camera` as per your need. Hierarchy would look something like:

```
 Player
    |- EmptyGO
          |- Camera

```
> 2 votes

# Answer
Why don't you use unity cinemachine it has a lot of different camera options and you can do most of the thing without coding and it is really flexible. Here are the docs: https://docs.unity3d.com/Packages/com.unity.cinemachine@2.3/manual/index.html
> 2 votes

---
Tags: unity, camera
---


# Question
Title: How can I implement a short-cut grass effect?
I've been looking at some screenshots from games like Rocket League and FIFA:

and I started wondering one would achieve the short-cut grass effect.

Is it a shader? Is it actual geometry? Or just textured quads? If anyone could point me in a direction, that would be greatly appreciated.

# Answer
> 7 votes
You might want to look into fur shading technique. This is what I would use for this type of grass, since the shorter the grass is the better the performance (less layers).
Basically it works by layering the same surface multiple times in small increments:

You can also change the horizontal offset to make the grass look bent.

# Answer
> 2 votes
It is most likely a shader that uses Parallax Occlusion Mapping, which uses normal map to "fake" depth and shadows in a texture. See HERE for examples.

Edit: As @Leggy pointed out, it is perhaps more likely that it is displacement mapping since the foot seems to be going between the grass. Anyway, it is some sort of height mapping shader :)

# Answer
> 2 votes
Rocket league is actually using long quads with texture that sways using vertex shader The trick itself is in the LOD, grass is rendered roughly 20meters ahead and the rest is just flat floor, the thing is, the floor sinks to reveal the close grass and raises gradually as you go further away(until it is at the same height of the grass)

So basically the entire grass field is a few lines and a few rows of long quads let's say 500 long + 500 wide that's 20 meters deep. The rest is simply flat raised ground.

---
Tags: unity, shaders, particles, terrain-rendering
---


# Question
Title: Prevent Unity From Loading The Next Scene After Getting to the Final Scene
I'm a beginner in Unity, I wrote a script that will load the next scene whenever monsters in a scene are dead. The script is working fine. Here's my script.

```
public void Update()
{
    if (MonstersAreAllDead())
        GoToNextLevel();

}

//Loads The next Level After all the monsters are Confirmed Dead

private void GoToNextLevel()
{
    SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);

}

```

However, I only have two scenes in my game and When Unity gets to the final scene, it displays an error since there is not next scene to load to.

```
Scene with build index: 2 couldn't be loaded because it has not been added to the build settings.
To add a scene to the build settings use the menu File->Build Settings...
UnityEngine.SceneManagement.SceneManager:LoadScene (int)
LevelController:GoToNextLevel () (at Assets/Scripts/LevelController.cs:39)
LevelController:Update () (at Assets/Scripts/LevelController.cs:30)

```

My question. How do I tell unity that it should stop trying to load the next scene and instead Display a message to the user? The message displayed can be something like "This is the final scene".

Thank you all in advance for your answers.

# Answer
This is pretty trivial. Just take the number of the scene you want to go to, and then compare it against the number of scenes you built. If the number is at or above the limit, don't load that scene.

```
private void GoToNextLevel()
{
    int nextSceneIndex = SceneManager.GetActiveScene().buildIndex + 1;

    if (nextSceneIndex < SceneManager.sceneCountInBuildSettings) {

        // If we have a next scene to load, load it.
        SceneManager.LoadScene(nextSceneIndex);

    } else {

        // Otherwise, display your "you win" message.
        gameCompletedMessage.SetActive(true);
    }
}

```

Don't forget to read the documentation to find helpful parts of the API like `sceneCountInBuildSettings`.
> 1 votes

---
Tags: unity, c#, scene, scenemanager
---


# Question
Title: Resize and move widgets when screen resized
I want to add buttons to my libgdx based game and have them be independent of the window's size, but when I resize the window, the buttons stretch and deform instead of being resized and/or moved.

Most answers online say that this problem can be solved by resizing the stage's viewport, but I am already doing that and it confuses me, because I have no clue what the problem could be. To me it just looks like it is drawing to a texture that gets initialized to whatever size my window initially has, and is then stretched but never resized. Am I using it wrong? Or do I need to do something else?

What I start with:

What I end up with:

What I actually want (made with paint):

My code:

MainMenuScreen.java

```
public class MainMenuScreen implements Screen
{
    private Stage stage;
    private Table table;

    private MyGame game;

    public MainMenuScreen(MyGame game)
    {
        this.game = game;

        table = new Table();
        table.setFillParent(true);

        stage = new Stage();
        stage.addActor(table);

        Gdx.input.setInputProcessor(stage);

        // FIXME testing
        Skin skin = new Skin(Gdx.files.internal("skins/default/skin/uiskin.json"));

        TextButton button1 = new TextButton("Sandwich", skin);
        table.add(button1);

        TextButton button2 = new TextButton("Kebab", skin);
        table.add(button2);
    }

    @Override
    public void show()
    {

    }

    @Override
    public void render(float delta)
    {
        Gdx.gl.glClearColor(0, 0.2f, 0.3f, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        stage.act(delta);
        stage.draw();
    }

    @Override
    public void resize(int width, int height)
    {
        stage.getViewport().update(width, height, true);
    }

    @Override
    public void dispose()
    {
        stage.dispose();
    }
}

```

MyGame.java

```
public class MyGame extends Game
{
    public SpriteBatch batch;
    public Input input;

    private MainMenuScreen mainMenuScreen;

    @Override
    public void create()
    {
        batch = new SpriteBatch();

        input = new Input();
        Gdx.input.setInputProcessor(input);

        mainMenuScreen = new MainMenuScreen(this);
        setScreen(mainMenuScreen);
    }

    @Override
    public void render()
    {
        super.render();
    }

    @Override
    public void dispose()
    {
        mainMenuScreen.dispose();
        batch.dispose();
    }
}

```

# Answer
It seems that a viewport is missing, as adding one yields the desired behaviour. The following code works for this purpose:

MainMenuScreen.java

```
public class MainMenuScreen implements Screen
{
    private Stage stage;
    private Table table;

    private OrthographicCamera camera;
    private FitViewport viewport;

    private MyGame game;

    public MainMenuScreen(MyGame game)
    {
        this.game = game;

        this.camera = new OrthographicCamera();
        this.viewport = new FitViewport(0, 0, camera);

        table = new Table();
        table.setFillParent(true);

        stage = new Stage();
        stage.setViewport(viewport);
        stage.addActor(table);

        Gdx.input.setInputProcessor(stage);

        // FIXME testing
        Skin skin = new Skin(Gdx.files.internal("skins/default/skin/uiskin.json"));

        TextButton button1 = new TextButton("Sandwich", skin);
        table.add(button1);

        TextButton button2 = new TextButton("Kebab", skin);
        table.add(button2);
    }

    @Override
    public void show()
    {

    }

    @Override
    public void render(float delta)
    {
        Gdx.gl.glClearColor(0, 0.2f, 0.3f, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        stage.act(delta);
        stage.draw();
    }

    @Override
    public void resize(int width, int height)
    {
        camera.setToOrtho(false, width, height);
        viewport.setWorldSize(width, height);
        stage.getViewport().update(width, height, true);
    }

    @Override
    public void dispose()
    {
        stage.dispose();
    }
}

```
> 1 votes

---
Tags: libgdx, scale, scene2d
---


# Question
Title: Reorientation when rotating Transforms around another Transform without parenting
The functionality I am trying to implement, consists of rotating one Transform and appling this rotation to other relevant Transforms in the scene. To make it a bit more clear: I have several objects in the scene. When I grab one (lets call it parent) and rotate it, the others (children) should rotate relative of their own position and rotation to the grabbed object around this grabbed object.

It is exactly the same what parenting does with its child objects when rotating the parent. Unfortunatly I cant just change the hierachy so I am bound to have different objects on the same hierachy level.

So far I have managed to rotate the children relative to the parent but when I grab the parent object the child objects first reorient themselves. After reorienting they do the right thing and rotate and move relative to the parent.

Here are two objects. The left one should rotate relative to the right one.

As the right one is grabbed and the procedure starts, the child object first jumps to another position with another rotation

I feel kind of stupid not seeing where this behaviour comes from. I use a coroutine to be able to construct the functionality in another script. As long as the coroutine is running, the child object should be moved and rotated relatively.

I first calculate the needed offsets of the position and rotation at startup:

```
    Vector3 offsetPos = child.position - parent.position;
    Quaternion offsetRot = child.rotation * Quaternion.Inverse(parent.rotation);

```

Then I apply the calculations in a loop:

```
    while (true)
    {
        child.position = parent.rotation * offsetPos + parent.position;
        child.rotation = parent.rotation * offsetRot;

        yield return new WaitForFixedUpdate();
    }

```

The loop runs as long as the parent object is grabbed and should place and orient the child accordingly.

I assume that my fault is located somewhere around calculating the offsets as once grabbed and reoriented, the children move and rotate exactly as they should.
If somebody has an idea where my mistake could hide I would be really happy if you could tell me.

Here is the related function as a whole:

```
    public override IEnumerator TransformGroupMember(Transform child, Transform parent)
    {
        //calculate offsets
        Vector3 offsetPos = child.position - parent.position;
        Quaternion offsetRot = child.rotation * Quaternion.Inverse(parent.rotation);

        //apply the relative transformation as long as the coroutine is running
        while (true)
        {
            child.position = parent.rotation * offsetPos + parent.position;
            child.rotation = parent.rotation * offsetRot;

            yield return new WaitForFixedUpdate();
        }
    }

```

Since this is my first question asked, I also welcome any suggestions about tips and tricks or changes.

# Answer
> 0 votes
Okay, I guess I found a workaround.

Thinking about what I did I realised that the problem occures because I add the rotation of the "parent" to the "child" when I start the calculations in the while loop. So after calculating the offset position, which is a direction pointing towards the child, I have to rotate this direction inversed by the rotation of the parent. In the end the fist calculation step inside the while loop will rotate it back to its origin rotation, pointing towards the child again:

```
public override IEnumerator TransformGroupMember(Transform child, Transform parent)
{
    //calculate offsets
    Vector3 offsetPos = child.position - parent.position;
    Quaternion offsetRot = child.rotation * Quaternion.Inverse(parent.rotation);

    //workaround solution:
    offsetPos = Quaternion.Inverse(parent.rotation) * offsetPos;

    //apply the relative transformation as long as the coroutine is running
    while (true)
    {
        child.position = parent.rotation * offsetPos + parent.position;
        child.rotation = parent.rotation * offsetRot;

        yield return new WaitForFixedUpdate();
    }
}

```

# Answer
> 0 votes
You could use Transform.RotateAround function and just set the cube you need to rotate around as a target the other cube should follow target cube when you move it.

---
Tags: unity, rotation, quaternion, logic
---


# Question
Title: Godot cutout animation with skeletons and ragdoll physics
i'm following the tutorial for cutout animation, but also wanted to combine ragdoll physics from this video, my goal is to make a 2d fight game with this 2 techniques. but not sure how to combine them both at the same time, from **what i have learned the cutout animation will do whatever animation is doing at the moment, but how to switch to ragdoll physics at the moment the dummy is hit?.**

Is this correct?

# Answer
> 2 votes
I have been dealing with this problem too.

Unfortunately, the Skeleton2D and Bone2D seems to be tools for animators only (it is not a physics object). There is support for 3D ragdoll with PhysicalBone but Godot is lacking in terms of 2D.

I had to switch to Unity for my 2D ragdolls. There is a built-in tool for 2D Skeletons and you can make them physical objects with ease. Also, you already have HingeJoint2D present there which is again lacking in Godot.

Or you could wait for Godot 4.0 It seems like they are improving the IK system and adding PhysicalBone2D. https://github.com/godotengine/godot/pull/47872

---
Tags: 2d, physics, godot
---


# Question
Title: Unity Camera resets rotation instead of using existing values
I'm working on a generic camera rig using mouse inputs, kind of like an RTS camera but it will be used to look at models with as a sort of turntable viewer.

The issue I am having is that when I **rotate** the camera, then **pan**, then try to **rotate** again, the rotation resets to the initial value. I think the issue is that the old rotation values aren't remembered when I begin the new rotate operation, so it resets to the default value (0,0,0,1).

If this is indeed the issue, how should I approach saving the value at the end of the frame, then reuse it in following frames?

.gif of issue

Code:

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

public class CameraRigController : MonoBehaviour
{
    public float moveSpeed;
    public float moveTime;
    public float rotationAmount;
    public float zoomAmount;

    public Transform cameraPosition;
    public Quaternion newRotation;

    public Vector3 newPosition;
    public Vector3 newZoom;

    // mouse rotato
    public Vector3 rotateStartPosition;
    public Quaternion rotateCurrentPosition;

    private float z;
    private float y;
    void Start()
    {
        newPosition = transform.position;
        newRotation = transform.rotation;
        newZoom = cameraPosition.localPosition;
    }

    void LateUpdate()
    {
        HandleMovementInput();
    }

    void HandleMovementInput()
    {
        // Zoom
        if (Input.mouseScrollDelta.y !=0)
        {
            newZoom.x += Input.mouseScrollDelta.y * zoomAmount;
        }

        // Pan
        if (Input.GetMouseButton(1))
        {
            z = Input.GetAxis("Mouse X") * moveSpeed;
            y = -Input.GetAxis("Mouse Y") * moveSpeed;

            newPosition.z += z;
            newPosition.y += y;
        }

        // Rotate
        if (Input.GetMouseButton(0))
        {
            z += Input.GetAxis("Mouse X") * rotationAmount;
            y += Input.GetAxis("Mouse Y") * rotationAmount;

            newRotation = Quaternion.Euler(0,z,y);
            rotateCurrentPosition = newRotation;
        }

        transform.position = newPosition;
        transform.rotation = newRotation;
        cameraPosition.localPosition = Vector3.Lerp(cameraPosition.localPosition, newZoom, Time.deltaTime * moveTime);
    }
}

```

# Answer
Thanks to @DMGregory for his input. Adding separate vector variables for rotation and position Z,Y solved the issue.

**Add explicit variables for Position and Rotation Z/Y**

```
    private float positionZ;
    private float positionY;
    private float rotationZ;
    private float rotationY;

```

**Use these variables instead for pan, rotate actions**

```
    // Pan
        if (Input.GetMouseButton(1))
        {
            positionZ = Input.GetAxis("Mouse X") * moveSpeed;
            positionY = -Input.GetAxis("Mouse Y") * moveSpeed;

            newPosition.z += positionZ;
            newPosition.y += positionY;
        }

    // Rotate
        if (Input.GetMouseButton(0))
        {
            rotationZ += Input.GetAxis("Mouse X") * rotationAmount;
            rotationY += Input.GetAxis("Mouse Y") * rotationAmount;

            newRotation = Quaternion.Euler(0, rotationZ, rotationY);
        }

```
> 0 votes

---
Tags: unity, c#, camera, rotation
---


# Question
Title: Unable to restart level in Python Pygame
So, I am making Flappy Bird and when the player dies I have the spacebar assigned to reset the game. However, it's not working and I truly have no idea why (after like 3 hours of going through tutorials and rereading the code).

```
import pygame
import random

# Initiating pygame
pygame.init()

# Variables:
FPS = 60

WHITE = (255, 255, 255)

ORIGIN = (0, 0)
ground_X_pos = 0

run = True
not_collided = True

BIRD_STARTING_POS = (50, 280)
bird_pos = 0
gravity = 0.3

pipe_list = []
available_pipe_height = [300, 310, 320, 330, 340, 350,
                         360, 370, 380, 390, 400, 410, 420, 430, 440, 450]
SPAWN_PIPE = pygame.USEREVENT

GAP = 200

# Setting the display window
pygame.display.set_caption("Crappy Bird")

SCREEN_DIMENSIONS = (352, 600)
SCREEN = pygame.display.set_mode(SCREEN_DIMENSIONS)

# Loading required images as surfaces
bg = pygame.image.load("assets/sprites/background-day.png").convert()
bg = pygame.transform.scale(bg, SCREEN_DIMENSIONS)

ground = pygame.image.load("assets/sprites/base.png").convert()
ground = pygame.transform.scale(ground, (352, 75))

bird = pygame.image.load("assets/sprites/yellowbird-midflap.png").convert()
bird = pygame.transform.scale(bird, (50, 34))

pipe = pygame.image.load("assets/sprites/pipe-red.png").convert()

_game_over = pygame.image.load("assets/sprites/gameover.png")
_game_over = pygame.transform.scale(_game_over, (352, 77))

# Loading required rectangles
bird_rect = bird.get_rect(center=BIRD_STARTING_POS)

# Spawning pipes
pygame.time.set_timer(SPAWN_PIPE, 1010)

# This will load all the required surfaces of entities
def update(_pipe_list):
    # Loading in background surfaces
    SCREEN.blit(bg, ORIGIN)

    # Loading in the bird
    SCREEN.blit(bird, bird_rect)

    # Loading in the pipes
    for _pipe in _pipe_list:
        if _pipe.bottom >= 600:
            SCREEN.blit(pipe, _pipe)
        else:
            _pipe_ = pygame.transform.flip(pipe, False, True)
            SCREEN.blit(_pipe_, _pipe)

    # Loading in the ground
    SCREEN.blit(ground, (ground_X_pos, 525))
    SCREEN.blit(ground, (ground_X_pos + 352, 525))

# This will spawn in pipes
def spawn_pipe():
    seed = random.choice(available_pipe_height)

    bottom_pipe = pipe.get_rect(midtop=(360, seed))
    top_pipe = pipe.get_rect(midbottom=(360, seed - GAP))

    return bottom_pipe, top_pipe

# Puts the pipe in their correct positions
def pipe_pos(_pipe_list):
    for _pipe in _pipe_list:
        _pipe.centerx -= 5

    return _pipe_list

# This checks if the bird has collided with anything or not
def collision_checker(_pipe_list):
    for _pipe in _pipe_list:
        if bird_rect.colliderect(_pipe):
            return False
        else:
            pass

        if bird_rect.bottom >= 525 or bird_rect.top <= 0:
            return False
        else:
            pass

    return True

def game_over():
    SCREEN.fill(WHITE)
    SCREEN.blit(_game_over, (0, 261.5))

# This is the main loop for running the game
while run:
    # Setting a fixed frame rate
    pygame.time.Clock().tick(FPS)

    # Checking if the game needs to be closed
    for event in pygame.event.get():  # pygame.event.get() gets all events occurring (like key press, mouse clicks, etc)
        if event.type == SPAWN_PIPE:
            pipe_list.extend(spawn_pipe())
        else:
            pass

        if event.type == pygame.QUIT:
            run = False
        else:
            pass

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE and not_collided:
                bird_pos = 0
                bird_pos -= 8.25
            else:
                pass

            if event.type == pygame.K_SPACE:
                bird_pos = 0
                bird_rect.center = BIRD_STARTING_POS
                print("Debug : This works.")
                pipe_list.clear()

                not_collided = True
            else:
                pass
        else:
            pass

    # Running the game
    if not_collided:
        update(pipe_list)
        ground_X_pos -= 5

        if ground_X_pos <= -352:
            ground_X_pos = 0
        else:
            pass

        bird_pos += gravity
        bird_rect.centery += bird_pos

        pipe_list = pipe_pos(pipe_list)

        not_collided = collision_checker(pipe_list)

    #Ending the game
    if not not_collided:
        game_over()

    pygame.display.update()

pygame.quit()

```

It gets stuck on this screen.

# Answer
> 0 votes
`if event.type == pygame.K_SPACE:` is incorrect, you want to check against `event.key` like in the code you have written above. You'll probably want to also check and run the resetting code only if there has been a collision detected.

---
Tags: python, pygame
---


# Question
Title: How do I make rigid bodies on a spinning plate move accordingly?
I have two 3D objects in my scene, a spinning plate (rotating flat disc) which has a `Mesh Collider`, and a `Rigid Body` cube.

The cube has gravity enabled, but when it lands on the plate it doesn't move along 'with' the plate, but just kinda lays on it as if the plate wasn't spinning.

The plate spins using the following code:

```
Update(){
    transform.Rotate(0, Time.DeltaTime * 64, 0, Space.Self);
}

```

I tried making the plate itself a `Rigid Body` (with gravity off of course), but it makes no difference.

I also read somewhere about adding `Torque` instead of rotating as I did above, but that had no effect.

I figured it was a lack of friction that was causing the issue, so I added a `Physic Material` to the plate (and also tried it on the cube), and bumped up the dynamic and static friction.... no luck.

How do I make the cube follow the movement of the plate (in other words, ride the plate)?

I expect that if the plate rotates fast enough that the box will start to slide outward.

# Answer
> 1 votes
Transform.rotate doesn't so much rotate the body but rather teleports it to its new position. If you want a rotating object to interact physically correct, give it a rigidbody and rotate it via the rigidbody.MoveRotation method.

If it still doesn't work, check the physics materials to make sure there is enough friction.

---
Tags: unity
---


# Question
Title: How do I respond to clicks in editor mode?
It's working fine in run time but I wonder if there is a way to make it work also in editor mode ? I tried to add to the top of the script :

```
[ExecuteAlways]

```

Because I want it to work on both run time and eidtor.

```
private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if (plane.GetComponent<MeshCollider>().Raycast(ray, out hit, Mathf.Infinity))
            {
                GameObject cube = Instantiate(prefabToSpawn);

                cube.transform.position = hit.point;
                cube.transform.localScale = new Vector3(50, 50, 50);
            }
        }
    }

```

I removed the code from the update and created for testing a public method :

This is in the mono script :

```
public void SpawnThroughPlane()
    {
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if (plane.GetComponent<MeshCollider>().Raycast(ray, out hit, Mathf.Infinity))
            {
                GameObject cube = Instantiate(prefabToSpawn);

                cube.transform.position = hit.point;
                cube.transform.localScale = new Vector3(50, 50, 50);
            }
        }
    }

```

Than created editor script : The editor script is in Assets/Scripts/Editor

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

public class SpawnObjectsEditor : Editor
{
    [CustomEditor(typeof(SpawnObjects))]
    private void OnSceneGUI()
    {
        SpawnObjects spawn = (SpawnObjects)target;

        Event e = Event.current;
        if (e.type == EventType.MouseDown)
        {
            spawn.SpawnThroughPlane();
        }
    }
}

```

But the editor script is not working at all I tried to add a break point in the editor script but it seems like the editor script is not active :

Even if I'm going back to the editor the break point is not working.

# Answer
> 1 votes
As per Unity API documentation for the CustomEditor attribute (here), `[CustomEditor]` must be put on the custom *editor class itself* (in this case, the class is `SpawnObjectsEditor`), and not on the `OnSceneGUI` method.

Try moving the attribute like this:

```
[CustomEditor(typeof(SpawnObjects))]
public class SpawnObjectsEditor : Editor
{
    private void OnSceneGUI()
    {
        ...
    }
}

```

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


# Question
Title: How to keep objects in the same position relative to their parent?
I'm writing a simple game in C# and i'm having some difficulty to calculate the local position of a sprite.

What i'm aiming to achieve:

* *Calculate the sprite* "**local position**" relative to the parent.
* *When the parent sprite position is changed*, **the children sprite should be aways *following the parent* while keeping its relative position**.

Example:

Lets assume i have a parent sprite at world position (4, 4) and a children sprite at local position (2, 2), if the parent sprite world position moves to (5, 5), his children local position should be at (3, 3).

Below is a example code of what i'm trying to make. Lets assume the parent sprite moved and called **UpdateChildrenPositions** with his new position, what should the **local** and **world** positions of his childrens be?

```
public class Sprite
{
    public Sprite parent;
    public List<Sprite> childrens;

    public Point world_position;
    public Point local_position;

    public void UpdateChildrenPositions(Point new_position)
    {
        // What should these numbers contain?
        this.world_position = ???
        this.local_position = ???
    }
}

```

Could someone provide a **direct** answer with the math to solve this problem?

Thanks in advance!

# Answer
The parent moving, by definition, does *not* change the local position. So you only need to change the world position, using the parent's world position and the *unchanged* local position as the source of truth.

```
public void UpdateWorldPositionUsingParent() {
    world_position = parent.world_position + local_position;

    // TODO: update positions of any children of this object
    // (grandchildren of our parent).
}

```

When you want to change the position of an object relative to its parent, you can adjust the world position and local position together:

```
public void SetPosition(Point newWorldPosition) {
    world_position = newWorldPosition;
    local_position = newWorldPosition - parent.world_position;

     // TODO: update positions of any children of this object
    // (grandchildren of our parent).
}

```

You can also use a dirty flag to mark objects whose world position is out of date, and update it lazily down the child hierarchy only when needed.
> 1 votes

---
Tags: c#, mathematics, sprites, windows-forms
---


# Question
Title: What object3D properties are required to make rayCaster.intersectObjects() work?
FYI, I am trying to do something almost identical to the following: Merging geometry/mesh without losing benefits

I essentially have a list of Three.object3D's. These objects are "merged" together into a single `BufferGeometry` (so that I can draw thousands of these objects with a single draw call).

After merging these objects I still do have references to all of the original objects (via a class which simply "has a" object3D object reference).

\*** Question \***

I am calling `raycaster.intersectObjects(myObjects)` on this list of original Object3D's. I'm wondering what properties are required for this `intersectObjects` method to work? In other words, the ray caster must be checking against each objects position and geometry. What properties (position, geometry?) are required and where do these properties exist (within the Object3D reference)?

Whew. I hope this all makes sense.

# Answer
> 2 votes
The properties are dependent on the override of the class that inherits from object which is currently being used. You can see what properties are required by looking at the overridden method that will have the format of `THREE.ClassName.prototype.raycast`. See below for a bit of insight into whats actually going on when you use the raycaster.

## Raycaster.js

```
var intersectObject = function ( object, raycaster, intersects, recursive ) {

    object.raycast( raycaster, intersects ); //The important bit

    if ( recursive === true ) {

        var children = object.children;

        for ( var i = 0, l = children.length; i < l; i ++ ) {
            intersectObject( children[ i ], raycaster, intersects, true );
        }
    }
};

```

## Object3D.js

```
raycast: function () {},

```

The Raycaster doesn't perform the collision logic its self. The Object has a method called `raycast` that does that for it. For the Object3D class that method perform no logic. However if you go look at mesh override that's a hell of a method.

```
THREE.Mesh.prototype.raycast = ( function () {

    var inverseMatrix = new THREE.Matrix4();
    var ray = new THREE.Ray();
    var sphere = new THREE.Sphere();

    var vA = new THREE.Vector3();
    var vB = new THREE.Vector3();
    var vC = new THREE.Vector3();

    return function ( raycaster, intersects ) {

        var geometry = this.geometry;

        // Checking boundingSphere distance to ray

        if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();

        sphere.copy( geometry.boundingSphere );
        sphere.applyMatrix4( this.matrixWorld );

        if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {

            return;

        }

        // Check boundingBox before continuing

        inverseMatrix.getInverse( this.matrixWorld );
        ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );

        if ( geometry.boundingBox !== null ) {

            if ( ray.isIntersectionBox( geometry.boundingBox ) === false )  {

                return;

            }

        }

        if ( geometry instanceof THREE.BufferGeometry ) {

            var material = this.material;

            if ( material === undefined ) return;

            var attributes = geometry.attributes;

            var a, b, c;
            var precision = raycaster.precision;

            if ( attributes.index !== undefined ) {

                var indices = attributes.index.array;
                var positions = attributes.position.array;
                var offsets = geometry.offsets;

                if ( offsets.length === 0 ) {

                    offsets = [ { start: 0, count: indices.length, index: 0 } ];

                }

                for ( var oi = 0, ol = offsets.length; oi < ol; ++oi ) {

                    var start = offsets[ oi ].start;
                    var count = offsets[ oi ].count;
                    var index = offsets[ oi ].index;

                    for ( var i = start, il = start + count; i < il; i += 3 ) {

                        a = index + indices[ i ];
                        b = index + indices[ i + 1 ];
                        c = index + indices[ i + 2 ];

                        vA.set(
                            positions[ a * 3 ],
                            positions[ a * 3 + 1 ],
                            positions[ a * 3 + 2 ]
                        );
                        vB.set(
                            positions[ b * 3 ],
                            positions[ b * 3 + 1 ],
                            positions[ b * 3 + 2 ]
                        );
                        vC.set(
                            positions[ c * 3 ],
                            positions[ c * 3 + 1 ],
                            positions[ c * 3 + 2 ]
                        );

                        if ( material.side === THREE.BackSide ) {

                            var intersectionPoint = ray.intersectTriangle( vC, vB, vA, true );

                        } else {

                            var intersectionPoint = ray.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );

                        }

                        if ( intersectionPoint === null ) continue;

                        intersectionPoint.applyMatrix4( this.matrixWorld );

                        var distance = raycaster.ray.origin.distanceTo( intersectionPoint );

                        if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;

                        intersects.push( {

                            distance: distance,
                            point: intersectionPoint,
                            indices: [ a, b, c ],
                            face: null,
                            faceIndex: null,
                            object: this

                        } );

                    }

                }

            } else {

                var positions = attributes.position.array;

                for ( var i = 0, j = 0, il = positions.length; i < il; i += 3, j += 9 ) {

                    a = i;
                    b = i + 1;
                    c = i + 2;

                    vA.set(
                        positions[ j ],
                        positions[ j + 1 ],
                        positions[ j + 2 ]
                    );
                    vB.set(
                        positions[ j + 3 ],
                        positions[ j + 4 ],
                        positions[ j + 5 ]
                    );
                    vC.set(
                        positions[ j + 6 ],
                        positions[ j + 7 ],
                        positions[ j + 8 ]
                    );

                    if ( material.side === THREE.BackSide ) {

                        var intersectionPoint = ray.intersectTriangle( vC, vB, vA, true );

                    } else {

                        var intersectionPoint = ray.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );

                    }

                    if ( intersectionPoint === null ) continue;

                    intersectionPoint.applyMatrix4( this.matrixWorld );

                    var distance = raycaster.ray.origin.distanceTo( intersectionPoint );

                    if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;

                    intersects.push( {

                        distance: distance,
                        point: intersectionPoint,
                        indices: [ a, b, c ],
                        face: null,
                        faceIndex: null,
                        object: this

                    } );

                }

            }

        } else if ( geometry instanceof THREE.Geometry ) {

            var isFaceMaterial = this.material instanceof THREE.MeshFaceMaterial;
            var objectMaterials = isFaceMaterial === true ? this.material.materials : null;

            var a, b, c, d;
            var precision = raycaster.precision;

            var vertices = geometry.vertices;

            for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {

                var face = geometry.faces[ f ];

                var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : this.material;

                if ( material === undefined ) continue;

                a = vertices[ face.a ];
                b = vertices[ face.b ];
                c = vertices[ face.c ];

                if ( material.morphTargets === true ) {

                    var morphTargets = geometry.morphTargets;
                    var morphInfluences = this.morphTargetInfluences;

                    vA.set( 0, 0, 0 );
                    vB.set( 0, 0, 0 );
                    vC.set( 0, 0, 0 );

                    for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {

                        var influence = morphInfluences[ t ];

                        if ( influence === 0 ) continue;

                        var targets = morphTargets[ t ].vertices;

                        vA.x += ( targets[ face.a ].x - a.x ) * influence;
                        vA.y += ( targets[ face.a ].y - a.y ) * influence;
                        vA.z += ( targets[ face.a ].z - a.z ) * influence;

                        vB.x += ( targets[ face.b ].x - b.x ) * influence;
                        vB.y += ( targets[ face.b ].y - b.y ) * influence;
                        vB.z += ( targets[ face.b ].z - b.z ) * influence;

                        vC.x += ( targets[ face.c ].x - c.x ) * influence;
                        vC.y += ( targets[ face.c ].y - c.y ) * influence;
                        vC.z += ( targets[ face.c ].z - c.z ) * influence;

                    }

                    vA.add( a );
                    vB.add( b );
                    vC.add( c );

                    a = vA;
                    b = vB;
                    c = vC;

                }

                if ( material.side === THREE.BackSide ) {

                    var intersectionPoint = ray.intersectTriangle( c, b, a, true );

                } else {

                    var intersectionPoint = ray.intersectTriangle( a, b, c, material.side !== THREE.DoubleSide );

                }

                if ( intersectionPoint === null ) continue;

                intersectionPoint.applyMatrix4( this.matrixWorld );

                var distance = raycaster.ray.origin.distanceTo( intersectionPoint );

                if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;

                intersects.push( {

                    distance: distance,
                    point: intersectionPoint,
                    face: face,
                    faceIndex: f,
                    object: this

                } );

            }

        }

    };

}() );

```

# Answer
> 0 votes
As posted on threejs.org forums:

```
var intersects = raycaster.intersectObjects( group.children);

```

Try it like so:

```
var intersects = raycaster.intersectObjects( group.children, true );

```

The second parameter indicates you want to test all descendants of group.children.

---
Tags: webgl, raycasting, three.js
---


# Question
Title: How to lerp between diferent spot angles
I have this code that Change spot angle randomly between 'minAngle' and 'maxAngle' each 'interval' seconds:

```
public float interval = 0.7f;
public float minAngle = 2;
public float maxAngle = 10;
float timeLeft;

Light lt;

void Start()
{
    lt = GetComponent<Light>();
    lt.type = LightType.Spot;

    timeLeft = interval;
}

void Update()
{
    timeLeft -= Time.deltaTime;

    if (timeLeft < 0.0)
    {
            timeLeft = interval;
            lt.spotAngle = Random.Range(minAngle, maxAngle);

    }
}

```

}

but i want the angle to change gradualy, for example if the angle is 2 and the new random number is 10, i want it to look like its growing gradualy. I supose i have to use a for? or some how take in consideration the previous value and lerp it?

# Answer
Every 'interval seconds' you set a new angle. Of course, this will just snap it instantly, and if you want it to transition smoothly, you're of course going to have to change the spot angle more times than just once every 'interval seconds'.

One solution is every time you calculate the new random angle, you get the difference between the new angle and the current angle and split up this difference into smaller bits; so instead of just taking one big step to the new angle you take smaller steps over multiple frames creating the transition effect you want.

How many steps do you break it up into though?

You would like this to transition before the next 'interval' seconds happens so you can figure out how many times the update function gets called before a new interval seconds happens. This is `ceil(interval / Time.deltaTime)`. This is how many steps we want to break it up into. Divide the difference by this number. Now every frame the spotlight angle gets incremented by this smaller difference and once one full interval happens it will have traveled the full difference.

```
public float angle_increment = 0;
public float updates_per_increment = Mathf.Ceil(increment/Time.deltaTime);

void Update()
{
    timeLeft -= Time.deltaTime;

    if (timeLeft <= 0.0)
    {
        timeLeft = interval;
        float new_angle = Random.Range(minAngle, maxAngle);
        angle_increment = (new_angle - lt.spotAngle) / updates_per_increment;
        lt.spotAngle += angle_increment;
    }
    else
    {
        lt.spotAngle += angle_increment;
    }
}

```
> 1 votes

---
Tags: lighting, random
---


# Question
Title: This keeps popping up while I'm trying to get an animation working in Unity
What does this mean? I've been trying to get a character to change animations when it is near an object. But nothing happens and this keeps showing up. Any advice?

# Answer
> 0 votes
It is as warning says you disabled exit time but didn't set any parameter for transition. To get rid of the warning you need to do one of these things. So if you want to do animation transition when something happens you need to create a parameter in animator and set it on the transition. Then when something happens you can change the value of parameter in code to whatever you set it for that transition. You can find a lot of tutorial on doing animation transition or just take a look at documentation.

---
Tags: unity
---


title: Why my player can suddenly fly?

text:
# Question
Title: Why my player can suddenly fly?
I'm working in a project with **Unity 2d** where player walks on a small planet. I try to use some code from youtube tutorial to apply gravity to my planet.This code consists of two parts, Attractable and Attractor. Attractables are used on objects that are drawn and Attractors placed on planets. I use simple platformer move script to move my player. But I found that if my player moves in one direction and suddenly changes the other direction, my player can "fly". I think this happened because my players moved at the wrong angle. I use my Attractor script to constantly applying force towards the center of the planet every update, but my player still fly and doesn't get pulled down unless if i run to another dirrection, then my player will get pulled again. I'm confused because my player is supposed to be pulled every update, but it seems like it's not being pulled.

in Attractor script, it just find all object inside Circle area with `Physics2D.OverlapCircleAll` and then call Attract function from object with Attractable script. The Attractor code look like this:

```
    void Update()
    {
        SetAttractedObjects();
    }

    void FixedUpdate()
    {
        AttractObjects();
    }

    void SetAttractedObjects()
    {
        AttractedObjects = Physics2D.OverlapCircleAll(planetTransform.position, effectionRadius, AttractionLayer).ToList();// can be optimized
    }

    void AttractObjects()
    {
        for (int i = 0; i < AttractedObjects.Count; i++)
        {
            AttractedObjects[i].GetComponent<Attractable>().Attract(this);
        }
    }

```

And inside the Attractable script, it has Attract function, that apply some force to object rigidbody. This is the function called from the previous Attractor script.

```
public void Attract(Attractor artgra)
    {
        Vector2 attractionDir = (Vector2)artgra.planetTransform.position - m_rigdibody.position;
        m_rigdibody.AddForce(attractionDir.normalized * -artgra.gravity * 100 * Time.fixedDeltaTime);
        if (currentAttractor == null)
        {
            currentAttractor = artgra;
        }

    }

```

This script also has, a RotateToCenter function which ensures the player is always facing the planet. This function is called from the Update function.

```
void RotateToCenter()
    {
        Vector2 distanceVector = (Vector2)currentAttractor.planetTransform.position - (Vector2)m_transform.position;

        float angle = Mathf.Atan2(distanceVector.y, distanceVector.x) * Mathf.Rad2Deg;
        m_transform.rotation = Quaternion.AngleAxis(angle + 90,Vector3.forward);
    }

```

And i use this movement code that add some velocity to my rigidbody to move my player;

```
void Update( )
{
     Move();
}

void Move(){
     scale=transform.localScale;
     if (Input.GetKey(KeyCode.A))
     {
          isMoving=true;
          rb.velocity = transform.right * -moveSpeed;
          scale.x=-1;
     }
     else if (Input.GetKey(KeyCode.D))
     {
          isMoving=true;
          rb.velocity = transform.right * moveSpeed;
          scale.x=1;

     }
     else
     {
        rb.velocity = new Vector2(0f, 0f);
        isMoving=false;
     }
     transform.localScale=scale;
     animator.SetBool("isRunning",isMoving);
}

```

I think the problem is in the Attract function because my player doesn't seem to be pulled to the center of the planet, but when I try to debug it, it seems that this function is still being called every update, even when my player is hovering in the air. Anyone know how to solve this?

# Answer
So thanks for the suggestions in the comments, I have solved this problem. Based on the solution in the comments, I changed the way my character moves using addForce. The code look like this:

```
void Move(){
     scale=transform.localScale;

     if (Input.GetKey(KeyCode.A))
     {
          isMoving=true;
          Vector2 movement = transform.right.normalized * -moveSpeed;
          rb.AddForce(movement);
          scale.x=-1;
     }
     else if (Input.GetKey(KeyCode.D))
     {
          isMoving=true;
          Vector2 movement = transform.right.normalized * moveSpeed;
          rb.AddForce(movement);
          scale.x=1;
     }
     else
     {
          rb.velocity = new Vector2(0f, 0f);
          isMoving=false;
     }

```

And then i call this function from FixedUpdate function. It works well at low moveSpeed, but if my moveSpeed is too big, my players can be "thrown" from the planet. But it's fine for me.
> 0 votes

---
Tags: unity, rotation, platformer, rigidbody
---


# Question
Title: Have VSync on or off while do a game profiling
I'm trying to profile the game using Unity Profiler in order to catch any potential performance issues. The graphics settings support VSync feature.

However, I am not sure which one is the best practice to have a better profiling insight, having VSync on or off?

# Answer
> 1 votes
So based on the Unity Diagnosing Performance article disabling the VSync seems like a good practice while profiling the game.

**Rule out VSync**

Vertical Synchronization, known as VSync, is used to match a game’s frame rate to the refresh rate of the screen it is being displayed on. VSync can affect the frame rate of our game and its effects can show in the Profiler window. If we are not sure what we’re looking at, it can look like a performance problem, so before we go any further we need to learn how to rule VSync out of our investigations.

**Hiding VSync information in the CPU usage profiler**

We can choose to hide information in the CPU usage profiler graph. This allows us to ignore information that is not useful to our current investigations.

To hide VSync information from the CPU usage profiler graph, follow these steps:

Click on the CPU usage profiler to select it.

In the top part of the Profiler window, where the CPU usage profiler shows its data over time, click the yellow colored square labelled VSync to hide VSync information from the graph.

**Disregarding VSync information in the Hierarchy view**

There is no way of hiding VSync information from the CPU usage profiler’s Hierarchy view, but we can learn what it looks so that we can disregard it.

Whenever we see a function called WaitForTargetFPS in the Hierarchy view, this means that our game is waiting for VSync. We do not need to investigate this function and can safely ignore it.

**Disabling VSync**

VSync cannot be disabled on all platforms: many (such as iOS) enforce its use. However, if we are developing for a platform that does not enforce VSync we can disable it altogether in our project while we profile. To disable VSync, open the Quality Settings inspector by going to the top menu bar and selecting Edit \**\> \**Project Settings \> Quality. From the drop-down menu labelled VSync Count, select Don’t Sync.

# Answer
> 0 votes
In Script: QualitySettings.vSyncCount = 0; \[Don't sync\] QualitySettings.vSyncCount = 1; \[Every V Blank\] QualitySettings.vSyncCount = 2; \[Every Second V Blank\]

---
Tags: unity, c#, performance, profiling, profiler
---


# Question
Title: How to make the image in Unity the same as in MagicaVoxel?
I've seen a similar question before, but this question was asked 5 years ago and a lot of things in Unity have changed.

Here is the result I would like to achieve

But what happened in Unity

How can I achieve the same result, or as similar as possible?

# Answer
> 2 votes
After sitting and thinking, I was able to achieve a result very similar to MagicaVoxel

In the first, I added two direct lights on both sides of the pistol, with these settings

Secondly, I added post effects to the camera by changing the Volume Layer to Everything, as well as adding Anti-aliasing. Then I added a collider that had Color and Occlusion post effects.

As a result, we get this image.

I think it can still be edited and made more similar, but if you compare it with what it was, then the difference is obvious

---
Tags: unity, magicavoxel
---


title: Move two sprites together with offset?

text:
# Question
Title: Move two sprites together with offset?
I'm making a simple game in C# for practice and i'm having some problems when dragging a sprite and making another sprite follow it.

What i'm trying to achieve:

* When dragging a sprite, **i want another sprite to move with it**.
* While dragging, i want the two sprites to **keep the same distances they where before from one another**.
* If possible, but not related to the question, i would like to **adjust this distance with another offset**.

Example:

* Lets suppose i have two sprites, one at position (10, 10) and another at (10, 20).
* If i drag the first sprite to (10, 20) the second sprite should be at (10, 30).

Example code of what i'm trying to do:

```
public class Drag
{
    public Sprite first;
    public Sprite second;

    public bool dragging = true;
    public Point mouse_position;

    public void Update()
    {
        if (dragging == true)
        {
            first.position = mouse_position;

            var offset = ???
            var another_offset = ???
            second.position = ???
        }
    }
}

```

**Edit:** I tried the code that **@DMGregory** posted and **@Tyyppi\_77** linked but **it is not working as expected**. Here is the code that i'm using. Currently, *the second sprite* is flying all over the place.

```
public class Sprite
{
    public Sprite parent;
    public List<Sprite> childrens;
    public Rectangle bounds;

    public Point World { get { return new Point(bounds.X, bounds.Y); } }
    public Point Local { get { return new Point(World.X - parent.World.X, World.Y - parent.World.Y); } }
}

public class Drag
{
    public Sprite first;
    public Sprite second;

    public Point mouse;
    public bool dragging;

    public void Update()
    {
        if (dragging == true)
        {
            first.bounds.X = mouse.X - (first.bounds.Width / 2);
            first.bounds.Y = mouse.Y - (first.bounds.Height / 2);

            second.bounds.X = second.Local.X;
            second.bounds.Y = second.Local.Y;
        }
    }
}

```

Thanks in advance!

# Answer
> 1 votes
The sprite class you have written is not fit for purpose. As I've repeated to you a few times now, you should treat your local position as the source of truth, and *derive* the world position from it and the parent.

Your code does the *opposite* \- it takes the world bounds as the source of truth, and derives local position from it and the parent.

That means whenever your parent moves without moving the child's bounds, the child will stay in place in the world and its local position will change to compensate. This is not at all what you want.

We can fix that by making the local position the source of truth:

```
public class Sprite
{
    public Sprite parent;
    public List<Sprite> children; // No "s" - "children" is already plural
    public Rectangle localBounds;

    public Point World {
        get {
            Point origin = default;
            if (parent != null) origin = parent.World;

            return new Point(origin.X + localBounds.X, origin.Y + localBounds.Y);
        }

        set {
            Point origin = default;
            if (parent != null) origin = parent.World;

            localBounds.x = value.X - origin.X;
            localBounds.y = value.Y - origin.Y;
        }
    }

    public Point Local {
        get {
            return new Point(localBounds.X, localBounds.y);
        }

        set {
            localBounds.X = value.X;
            localBounds.Y = value.Y;
        }
    }
}

```

With that in hand, you can drag two sprites and maintain their offset something like this.

```
public class Drag
{
    public Sprite first;
    public Sprite second;

    public Point mouse;
    public bool dragging;

    // Alter this offset if you want to adjust the spacing during a drag.
    private Point _offset;

    // Call this when you want to begin dragging a pair of objects.
    public void StartDrag() {
         _offset = new Point(second.World.X - first.World.X,
                             second.World.Y - first.World.Y);

         dragging = true;
    }

    public void Update()
    {
        if (dragging == true)
        {
            var position = new Point(mouse.X - (first.localBounds.Width / 2),
                                     mouse.Y - (first.localBounds.Height / 2));

            first.World = position;
            second.World = new Point(position.X + _offset.X,
                                     position.Y + _offset.Y);

            // In case the first could be a child or grandchild of second,
            // then we need to apply a fix-up after second moves.
            first.World = position;

            // (Though in that case, you'd be better off just dragging
            //  second alone, without touching first, and let it come
            //  along for the ride automatically through parenting)
        }
    }
}

```

---
Tags: c#, mathematics, windows-forms
---


title: Surface-Sphere collision response

text:
# Question
Title: Surface-Sphere collision response
I'm making basketball throwing simulator and I have two questions about the collision response. To make collision response with any surface like the wall or ground, I'm using the following formulas to calculate impulse then linear velocity and angular velocity after collision:

for more info about the formula see this. The formula in the picture is a little bit different from the one in the site cause the mass of the object B(which is a surface) is considered infinite.

First question: the vector r(AP) is from the center of the sphere to the collision point, and the normal vector (n) goes in the opposite direction, so the cross product of these two vectors is zero vector, only (1/ma) left in the denominator of the impulse. And for angular velocity the cross product of r(AP) and the normal will be also zero vector and this leads to not to rotate after collision and this is wrong of course, what's the problem with these results?

Second question: in the denominator of the impulse: (n) *dot* ( ( n *cross* r(AP) ) / I *cross* r(AP)

What's the order of operations in this case, should I do the cross products first then the dot product at the end, or just do the operations from left to right?

# Answer
> 1 votes
For your first question: don't doubt yourself! Your results are reasonable for a sphere-surface collision. Assuming that the wall/ground can't move (has infinite mass), then your impulse would indeed be proportional to the mass of the sphere times its incoming velocity. Ending up with just `1/mA` in the denominator (equivalent to `mA` in the numerator) is consistent with this.

What's more, rolling is a phenomenon caused by friction, which is a force that is applied parallel to the surface. Since your resolution is along the surface normal, you can't get rolling from this collision, so it makes sense that you have no angular velocity.

For your second question, when a cross product and a dot product are written together, order of operations dictates that the cross product must be solved first. This is because the dot product generates a scalar, not a vector. If you do the dot product first, you won't have a vector left to cross!

---
Tags: 3d, collision-resolution
---


# Question
Title: How to display localized text from the selected language's script file?
I am trying to make a textbox engine for my RPG using Gamemaker Studio 2 as my game engine, and so far I have managed to make a pretty good-looking animation for when the textbox comes in and out. I think it looks really nice...

...However, I've come across some complications when it comes to the actual text itself.

You see, a basic rundown of what I wanted to do was keep the main lines of dialog on separate scripts (labeled as TEXT\_EN and TEXT\_JP, for the potential different languages), and have the dialog box object print the specific line from the TEXT scripts depending on which one I call, basically how UNDERTALE and DELTARUNE handled it (from what I could tell, they relied on arrays but that's all I know, I'm not sure on how to utilize them to my advantage).

I'm not sure on how I should start doing that... And I tried following along with some guys on Youtube who were better at it, but it didn't really feel right to me... I was planning on having different languages with my game, and these tutorials didn't have that in mind... If any of you guys could point me in the right direction, I would GLADLY appreciate it. Thank you for your time.

# Answer
I don't know how Undertale and Deltarune actually manage localisation from an implementation point of view, but I can propose a simple working solution that works with multiple text files.

### The main idea

Let's introduce our main actors:

* **Textboxes:** these are objects defined by visual properties (size, position, colours...) and internal data. Specifically, there's a variable holding the string the textbox is going to draw on the screen.
* **Text Files:** plaintext files where we save ALL the strings appearing in our game. There're menu strings, UI strings, item strings... Strings for everything, in conclusion. I'll call these *localisation files*.

Our game *checks* the current language setting, *reads* the language strings from the appropriate file, *saves* them internally, and *loads* them when needed.

We save strings internally for later use because we don't want to read the disk continuously while the game is running (this is bad for the hardware). Then, we save them at runtime inside a dedicated object:

* **`Strings`:** object (or, *collection* of objects, if you want to specialise instances with respect to the current context) that hold(s) all game strings, which we can access using a fixed variable name.

### Structure of a localisation file

Let's suppose there's a file named *LANG\_ENG.ini* that contains the following:

```
[menu]
menu_newgame = New game
menu_continue = Continue
menu_settings = Settings

[level1]
l1_intro0 = Welcome to the Dreamworld!
l1_intro1 = There's a lot to do around here. Let's get to work!
l1_barry = Hello there, I'm Barry. What's your name, traveller?
l1_genericnpc0 = Hello, traveller!
l1_genericnpc1 = Have we met before?

...

```

Different languages will keep the same structure, and only the actual string values will differ. For example, the *LANG\_IT.ini* file will look like this:

```
[menu]
menu_newgame = Nuova partita
menu_continue = Continua
menu_settings = Impostazioni

[level1]
l1_intro0 = Benvenuto a Dreamworld!
l1_intro1 = Abbiamo molto da fare qui. Mettiamoci al lavoro!
l1_barry = Salve, io sono Barry. Qual è il tuo nome, viaggiatore?
l1_genericnpc0 = Salve, viaggiatore!
l1_genericnpc1 = Ci siamo già incontrati?

...

```

INI files are useful for they let you retrieve data (real numbers or strings) by using **key-value** pairs grouped in collections called **sections**.

Similarly, our `Strings` object may contain instance variables as follows:

*`Strings` Create Event:*

```
// Main menu strings
menu_newgame = "";
menu_continue = "";
menu_settings = "";

// Level 1 strings
l1_intro0 = "";
l1_intro1 = "";
l1_barry = "";
l1_genericnpc0 = "";
l1_genericnpc1 = "";

```

The reason strings are empty is because we assign values programmatically via scripts at startup. You may assign hardcoded strings as a fallback solution, but it becomes hard to manage them as the number of strings grows. Plus, you can simply include a base *LANG\_EN.ini* file in your game bundle ("included files"), so that you are sure at least one localisation file exists.

### Reading strings

At this point, you may have guessed how the system works. You open a file (given its name), then you read all the needed strings, and save them in the `Strings` object. A small example may be:

```
// Load some localised strings
if ( file_exists("Lang/LANG_EN.ini") ) {
    ini_open("Lang/LANG_EN.ini");
    Strings.menu_newgame = ini_read_string("menu", "menu_newgame", "default_string");
    Strings.menu_continue = ini_read_string("menu", "menu_continue", "default_string");
    Strings.menu_settings = ini_read_string("menu", "menu_settings", "default_string");
    // More assignments here
    ini_close();
}

```

This way, the `Strings` object will be our single reference for in-game texts and strings, without the need to keep opening and reading localisation files. Similarly, we can call the function above again when the user switches to a different language in the game settings.

### Displaying localised strings

How do textboxes and UI objects access the appropriate strings to show? Since we can identify every piece of string by a unique variable name, we can code UI elements so that their text content is initialised when the object itself is instantiated:

*`TextBox` Create Event:*

```
// Init textbox strings
string_title = Strings.tutorial0_title;
string_content = Strings.tutorial0_content2;

```

*`TextBox` Draw Event:*

```
// Display current text message
draw_text(x + 20, y + 20, string_title);
draw_text(x + 20, y + 50, string_content);

```

And, that's it. The behaviour of your UI elements may vary depending on the length of the same string in different languages, so you may want to implement some sort of scrollable textboxes. The important thing is that localisation is made simple by removing hardcoded strings (so, no need to create language-specific versions of your game).

In addition to that, the accepted answer to this previous question describes a nice way to deal with UI when localised strings are needed:

> Instead of pushing out a change to all text in the game when the player changes the language, instead each text field pulls-in its text when it's time to be displayed.

The advantage is that you delegate string retrieval to each UI element rather than force-update everything from a single function.

### Limits

My experience with INI files in GameMaker Studio is limited to simple strings and common charsets. Since you mentioned Japanese as a language, you may need to use UTF-8 character sets to support these languages (Japanese, Russian, Chinese, Korean...). In such a case, INI files may not fit your purpose, and you'll need to implement your own solution for reading strings from well-formatted text files.

---

Since working with files is not that trivial, always remember to check if a file exists before opening it. This is in order to prevent your game from crashing due to badly formatted localisation files: users may translate and create new files, but may not be aware of INI files structure and usage.
> 1 votes

---
Tags: game-maker, text, localization
---


title: help with gravity gun mechanism

text:
# Question
Title: help with gravity gun mechanism
```
public void HitWithRay()
{
    Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);

    if (Input.GetMouseButton(1))
    {
        RaycastHit2D hit2d = Physics2D.Raycast(player.playerbulletFirePoint.position, mousePos , 10f);
        if (hit2d.collider == null)
            return;
        else
        {
            Vector2 velocityDirX = this.transform.position - hit2d.transform.position;
            hit2d.rigidbody.AddForce (velocityDirX * pullingForce);
        }
        Debug.Log(hit2d.transform.gameObject.tag);
    }
        Debug.DrawRay(player.playerbulletFirePoint.position, mousePos , Color.white);
}

```

**This script was actually grabbing the objects and hitting the player the help I wanted here is I want to stop the grabbed object in front of player**

# Answer
I suggest adding an OnTrigger to detect if the object is in contact with the player, and then set object velocity to zero so the object stop moving. You can do:

```
private void OnTriggerEnter2D(Collider2D other) {
        if(other.CompareTag("Object")){
            Rigidbody2D rigidbody2D=other.GetComponent<Rigidbody2D>();
            rigidbody2D.velocity=new Vector2(0,0);

        }
    }

```

If you need the object to stop at some distance from player, you can use:

```
GameObject object;
object = Physics2D.OverlapCircle(player.position, radius, objectLayer);
       Rigidbody2D rigidbody2D=object.GetComponent<Rigidbody2D>();
            rigidbody2D.velocity=new Vector2(0,0);

```
> 1 votes

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


# Question
Title: gl.drawArrays() not rendering whole mesh
I have a mesh that is generated using the marching cubes algorithm that is drawn using gl.drawArrays(), however the whole mesh isn't rendered, only part of it. I checked if the count I was specifiying in my gl.drawArrays() method was equal to the number of triangles, it was, and I checked if the mesh data was valid, and it was. So I am out of ideas on what to do. My meshes are split into 16x16 chunks. Here is what the issue looks like:

For a 1x1 mesh, it didn't even render, even though the 1x1 mesh data looks correct. If it helps, the vertex data where every 3 entries is an x, y, z position looked like this:

`[1, 0.5, 0, 0, 0.5, 0, 1, 0.5, 1, 1, 0.5, 1, 0, 0.5, 0, 0, 0.5, 1]`

Have you guys ever had meshes being partially rendered, if so, any ideas on how to solve it? If it helps, here is the chunk class:

```
function Chunk(chunkX, chunkY, cameraMatrix) {
  this.chunkX = chunkX;
  this.chunkY = chunkY;
  this.cameraMatrix = cameraMatrix;
  this.positionData = [];
  this.textureIdData = [];
  this.uvData = [];
  this.normalData = [];

  const chunkSizePlusOne = chunkSize + 1;
  const full = -1;
  const empty = 1;
  const totallyInside = 255;
  const totallyOutside = 0;
  const edgeIntersectionsSize = 16;
  const surface = 0;
  const chunkXPosition = chunkSize * chunkX;
  const chunkYPosition = chunkSize * chunkY;

  this.build = function () {
    const normalsOfTrianglesAdjacentToVertex = {};
    const vertexNormals = {};
    const perlinValues = [];

    for (let y = 0; y < chunkSizePlusOne; y++) {
      for (let x = 0; x < chunkSizePlusOne; x++) {
        const trueX = x + chunkXPosition;
        const trueY = y + chunkYPosition;

        perlinValues[y * chunkSizePlusOne + x] = perlin(trueX, trueY);
      };
    };

    for (let y = 0; y < chunkSize; y++) {
      for (let x = 0; x < chunkSize; x++) {
        const trueX = x + chunkXPosition;
        const trueY = y + chunkYPosition;

        for (let z = 0; z < worldHeight; z++) {
          const cubePositions = [
            [trueX, trueY, z],
            [trueX + 1, trueY, z],
            [trueX + 1, trueY + 1, z],
            [trueX, trueY + 1, z],
            [trueX, trueY, z + 1],
            [trueX + 1, trueY, z + 1],
            [trueX + 1, trueY + 1, z + 1],
            [trueX, trueY + 1, z + 1]
          ];
          const cubeScalarField = [];
          let lookupIndexOrrer = 1;
          let lookupIndex = 0;

          for (let cubePosition of cubePositions) {
            const [cubeX, cubeY, cubeZ] = cubePosition;
            const perlinValuesIndex = chunkSizePlusOne * (cubeY - chunkYPosition) + (cubeX - chunkXPosition);
            const height = worldHeight * perlinValues[perlinValuesIndex];

            if (cubeZ <= height) {
              cubeScalarField.push(full);

              lookupIndex |= lookupIndexOrrer;
            } else {
              cubeScalarField.push(empty);
            };

            lookupIndexOrrer <<= 1;
          };

          if (lookupIndex != totallyInside && lookupIndex != totallyOutside) {
            const edgeIntersections = triangulationTable[lookupIndex];

            for (let i = 0; i < edgeIntersectionsSize; i += 3) {
              const edgeIntersectionAtI = edgeIntersections[i];

              if (edgeIntersectionAtI !== -1) {
                const triangleEdgeIntersections = [
                  edgeIntersectionAtI,
                  edgeIntersections[i + 1],
                  edgeIntersections[i + 2]
                ];
                const xArray = [];
                const yArray = [];
                const zArray = [];

                for (let edgeIntersection of triangleEdgeIntersections) {
                  const [vertex1, vertex2] = verticesByEdge[edgeIntersection];
                  const [x1, y1, z1] = cubePositions[vertex1];
                  const [x2, y2, z2] = cubePositions[vertex2];
                  const vertex1Value = cubeScalarField[vertex1];
                  const vertex2Value = cubeScalarField[vertex2];
                  const vertex2Bias = (surface - vertex1Value) / (vertex2Value - vertex1Value);
                  const vertex1Bias = 1 - vertex2Bias;
                  const interpolatedX = x1 * vertex1Bias + x2 * vertex2Bias;
                  const interpolatedY = y1 * vertex1Bias + y2 * vertex2Bias;
                  const interpolatedZ = z1 * vertex1Bias + z2 * vertex2Bias;

                  xArray.push(interpolatedX);
                  yArray.push(interpolatedY);
                  zArray.push(interpolatedZ);

                  // push in order of actual webgl coordinates
                  this.positionData.push(interpolatedX);
                  this.positionData.push(interpolatedZ);
                  this.positionData.push(interpolatedY);
                };

                this.textureIdData.push(textureId(zArray));

                const uvData2D = uv(xArray, yArray);
                // parameters in order of webgl coordinates
                const normalOfTriangle = triangleNormal(xArray, zArray, yArray);

                for (let i = 0; i < numberOfTriangleVertices; i++) {
                  for (let j = 0; j < 2; j++) {
                    this.uvData.push(uvData2D[i][j]);
                  };

                  // in order of webgl coordinates
                  const vertexCoordinate = [xArray[i], zArray[i], yArray[i]];

                  if (normalsOfTrianglesAdjacentToVertex[vertexCoordinate]) {
                    normalsOfTrianglesAdjacentToVertex[vertexCoordinate].push(normalOfTriangle);
                  } else {
                    normalsOfTrianglesAdjacentToVertex[vertexCoordinate] = [normalOfTriangle];
                  };
                };
              };
            };
          };
        };
      };
    };

    for (let vertex of Object.keys(normalsOfTrianglesAdjacentToVertex)) {
      vertexNormals[vertex] = meanOfVector3Ds(normalsOfTrianglesAdjacentToVertex[vertex]);
    };

    const positionData = this.positionData;
    const positionDataLength = positionData.length;

    for (let i = 0; i < positionDataLength; i += 3) {
      const vertex = [positionData[i], positionData[i + 1], positionData[i + 2]];
      this.normalData.push(...vertexNormals[vertex]);
    };
  };
  this.render = function () {
    gl.useProgram(program);

    const positionBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(this.positionData), gl.DYNAMIC_DRAW);

    gl.enableVertexAttribArray(positionLocation);
    gl.vertexAttribPointer(positionLocation, 3, gl.FLOAT, false, 0, 0);

    const textureIdBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, textureIdBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(this.textureIdData), gl.DYNAMIC_DRAW);

    gl.enableVertexAttribArray(textureIdLocation);
    gl.vertexAttribPointer(textureIdLocation, 1, gl.FLOAT, false, 0, 0);

    const uvBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, uvBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(this.uvData), gl.DYNAMIC_DRAW);

    gl.enableVertexAttribArray(uvLocation);
    gl.vertexAttribPointer(uvLocation, 2, gl.FLOAT, false, 0, 0);

    const normalBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, normalBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(this.normalData), gl.DYNAMIC_DRAW);

    gl.enableVertexAttribArray(normalLocation);
    gl.vertexAttribPointer(normalLocation, 3, gl.FLOAT, false, 0, 0);

    gl.uniformMatrix4fv(matrixLocation, false, this.cameraMatrix);

    gl.drawArrays(gl.TRIANGLES, 0, this.textureIdData.length);
  };
};

```

# Answer
For the count parameter, I needed to not use the number of triangles, but the number of vertices, also if I do that, I need to add a textureId to this.textureIdData for each vertex, and not for each triangle. I guess I forgot how gl.drawArrays worked... Here is the updated chunk class

function Chunk(chunkX, chunkY, cameraMatrix) {
  this.chunkX = chunkX;
  this.chunkY = chunkY;
  this.cameraMatrix = cameraMatrix;
  this.positionData = [];
  this.textureIdData = [];
  this.uvData = [];
  this.normalData = [];

  const chunkSizePlusOne = chunkSize + 1;
  const full = -1;
  const empty = 1;
  const totallyInside = 255;
  const totallyOutside = 0;
  const edgeIntersectionsSize = 16;
  const surface = 0;
  const chunkXPosition = chunkSize * chunkX;
  const chunkYPosition = chunkSize * chunkY;

  this.build = function () {
    const normalsOfTrianglesAdjacentToVertex = {};
    const vertexNormals = {};
    const perlinValues = [];

    for (let y = 0; y < chunkSizePlusOne; y++) {
      for (let x = 0; x < chunkSizePlusOne; x++) {
        const trueX = x + chunkXPosition;
        const trueY = y + chunkYPosition;

        perlinValues[y * chunkSizePlusOne + x] = perlin(trueX, trueY);
      };
    };

    for (let y = 0; y < chunkSize; y++) {
      for (let x = 0; x < chunkSize; x++) {
        const trueX = x + chunkXPosition;
        const trueY = y + chunkYPosition;

        for (let z = 0; z < worldHeight; z++) {
          const cubePositions = [
            [trueX, trueY, z],
            [trueX + 1, trueY, z],
            [trueX + 1, trueY + 1, z],
            [trueX, trueY + 1, z],
            [trueX, trueY, z + 1],
            [trueX + 1, trueY, z + 1],
            [trueX + 1, trueY + 1, z + 1],
            [trueX, trueY + 1, z + 1]
          ];
          const cubeScalarField = [];
          let lookupIndexOrrer = 1;
          let lookupIndex = 0;

          for (let cubePosition of cubePositions) {
            const [cubeX, cubeY, cubeZ] = cubePosition;
            const perlinValuesIndex = chunkSizePlusOne * (cubeY - chunkYPosition) + (cubeX - chunkXPosition);
            const height = worldHeight * perlinValues[perlinValuesIndex];

            if (cubeZ <= height) {
              cubeScalarField.push(full);

              lookupIndex |= lookupIndexOrrer;
            } else {
              cubeScalarField.push(empty);
            };

            lookupIndexOrrer <<= 1;
          };

          if (lookupIndex != totallyInside && lookupIndex != totallyOutside) {
            const edgeIntersections = triangulationTable[lookupIndex];

            for (let i = 0; i < edgeIntersectionsSize; i += 3) {
              const edgeIntersectionAtI = edgeIntersections[i];

              if (edgeIntersectionAtI !== -1) {
                const triangleEdgeIntersections = [
                  edgeIntersectionAtI,
                  edgeIntersections[i + 1],
                  edgeIntersections[i + 2]
                ];
                const xArray = [];
                const yArray = [];
                const zArray = [];

                for (let edgeIntersection of triangleEdgeIntersections) {
                  const [vertex1, vertex2] = verticesByEdge[edgeIntersection];
                  const [x1, y1, z1] = cubePositions[vertex1];
                  const [x2, y2, z2] = cubePositions[vertex2];
                  const vertex1Value = cubeScalarField[vertex1];
                  const vertex2Value = cubeScalarField[vertex2];
                  const vertex2Bias = (surface - vertex1Value) / (vertex2Value - vertex1Value);
                  const vertex1Bias = 1 - vertex2Bias;
                  const interpolatedX = x1 * vertex1Bias + x2 * vertex2Bias;
                  const interpolatedY = y1 * vertex1Bias + y2 * vertex2Bias;
                  const interpolatedZ = z1 * vertex1Bias + z2 * vertex2Bias;

                  xArray.push(interpolatedX);
                  yArray.push(interpolatedY);
                  zArray.push(interpolatedZ);

                  // push in order of actual webgl coordinates
                  this.positionData.push(interpolatedX);
                  this.positionData.push(interpolatedZ);
                  this.positionData.push(interpolatedY);
                };

                const triangleTextureId = textureId(zArray);
                const uvData2D = uv(xArray, yArray);
                // parameters in order of webgl coordinates
                const normalOfTriangle = triangleNormal(xArray, zArray, yArray);

                for (let i = 0; i < numberOfTriangleVertices; i++) {
                  this.textureIdData.push(triangleTextureId);

                  for (let j = 0; j < 2; j++) {
                    this.uvData.push(uvData2D[i][j]);
                  };

                  // in order of webgl coordinates
                  const vertexCoordinate = [xArray[i], zArray[i], yArray[i]];

                  if (normalsOfTrianglesAdjacentToVertex[vertexCoordinate]) {
                    normalsOfTrianglesAdjacentToVertex[vertexCoordinate].push(normalOfTriangle);
                  } else {
                    normalsOfTrianglesAdjacentToVertex[vertexCoordinate] = [normalOfTriangle];
                  };
                };
              };
            };
          };
        };
      };
    };

    for (let vertex of Object.keys(normalsOfTrianglesAdjacentToVertex)) {
      vertexNormals[vertex] = meanOfVector3Ds(normalsOfTrianglesAdjacentToVertex[vertex]);
    };

    const positionData = this.positionData;
    const positionDataLength = positionData.length;

    for (let i = 0; i < positionDataLength; i += 3) {
      const vertex = [positionData[i], positionData[i + 1], positionData[i + 2]];
      this.normalData.push(...vertexNormals[vertex]);
    };
  };
  this.render = function () {
    gl.useProgram(program);

    const positionBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(this.positionData), gl.DYNAMIC_DRAW);

    gl.enableVertexAttribArray(positionLocation);
    gl.vertexAttribPointer(positionLocation, 3, gl.FLOAT, false, 0, 0);

    const textureIdBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, textureIdBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(this.textureIdData), gl.DYNAMIC_DRAW);

    gl.enableVertexAttribArray(textureIdLocation);
    gl.vertexAttribPointer(textureIdLocation, 1, gl.FLOAT, false, 0, 0);

    const uvBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, uvBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(this.uvData), gl.DYNAMIC_DRAW);

    gl.enableVertexAttribArray(uvLocation);
    gl.vertexAttribPointer(uvLocation, 2, gl.FLOAT, false, 0, 0);

    const normalBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, normalBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(this.normalData), gl.DYNAMIC_DRAW);

    gl.enableVertexAttribArray(normalLocation);
    gl.vertexAttribPointer(normalLocation, 3, gl.FLOAT, false, 0, 0);

    gl.uniformMatrix4fv(matrixLocation, false, this.cameraMatrix);

    gl.drawArrays(gl.TRIANGLES, 0, this.positionData.length / 3);
  };
};
```

> 0 votes

---
Tags: javascript, rendering, mesh, webgl
---


# Question
Title: LIBGDX ShaderProgram not passing uniforms
**I'm trying to implement a Shader that turns any RGB values below 190 into black.**

---

LIBGDX code:
```
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g3d.shaders.DefaultShader;
import com.badlogic.gdx.graphics.glutils.FrameBuffer;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.utils.ScreenUtils;

import static com.badlogic.gdx.Gdx.gl;

public class Main extends ApplicationAdapter {
    SpriteBatch batch;
    Texture img;
    OrthographicCamera camera;

    @Override
    public void create () {
        ShaderProgram.pedantic=true;
        camera=new OrthographicCamera(1920, 1080);
        batch = new SpriteBatch();
        ShaderProgram sp= new ShaderProgram(Gdx.files.internal("normal.vert").readString(),
                Gdx.files.internal("threshold.frag").readString());
        sp.setUniformi("threshold", 190);
        batch.setShader(sp);
        img = new Texture("badlogic.jpg");
    }

    @Override
    public void render () {
        ScreenUtils.clear(1, 0, 0, 1);
        batch.begin();
        batch.draw(img, 0, 0);
        batch.end();
    }

    @Override
    public void dispose () {
        batch.getShader().dispose();
        batch.dispose();
        img.dispose();
    }
}

```

Vertex Shader:

```
attribute vec4 a_position;
attribute vec4 a_color;
attribute vec2 a_texCoord0;

uniform mat4 u_projTrans;

varying vec4 v_color;
varying vec2 v_texCoords;

void main() {
    v_color = a_color;
    v_texCoords = a_texCoord0;
    gl_Position = u_projTrans * a_position;
}

```

and Frag Shader:

```
#ifdef GL_ES
precision mediump float;
#endif

varying vec4 v_color;
varying vec2 v_texCoords;
uniform int threshold;
uniform sampler2D u_texture;
uniform mat4 u_projTrans;

void main() {
    float t=float(threshold)/255.;
    vec3 color = texture2D(u_texture, v_texCoords,0.).rgb;

    if(color.r<=t||color.g<=t||color.g<=t){
        color=vec3(0,0,0);
    }
    if(threshold==0){
        color=vec3(1);

    }
    gl_FragColor = vec4(color, texture2D(u_texture, v_texCoords,0.).a);
}

```

expected output(directly setting "threshold" to be 190 in Frag shader file): expected
actual output(`if threshold==0: color=vec3(1)`): actual output
which can only mean that Uniform is not passed into the Frag shader correctly.
any help in fixing this weirdness will be greatly appreciated.
Thanks!

# Answer
Adding `sp.bind()` before setting Uniforms solved the issue.
> 0 votes

---
Tags: opengl, java, libgdx, shaders, glsl
---