# Question
Title: Why is my character not reacting to the gravity I set?
I've got a little question about my gravity that isn't working and I can't find out why...

The issue is that the player just go upper but doesn't really 'jump' and doesn't come back on the ground. Plus, he can move like if he is on the ground while in the air but not like in a game like Mario...

It's like the condition about if I'm above or below a certain amount of Y position in the Move() method isn't seen I didn't really know how to use the acceleration though so it doesn't have any value, I'm so lost

Here is the code:

```
using System;
using SFML.Graphics;
using SFML.Window;
using SFML.System;

namespace ITI_First_Game
{
    public abstract class GameLoop
    {
        #region Fields

        public const int TARGET_FPS = 60;
        public const float TIME_UNTIL_UPDATE = 1f / TARGET_FPS;

        Clock _clock = new Clock();

        static Texture _backgroundTexture = new Texture("../Content/Bbackground.jpg");
        static Sprite _backgroundSprite;

        static Texture _mouseTexture = new Texture("../Content/mousesad.png");
        static Sprite _mouseSprite;

        static Texture _playerTexture = new Texture("../Content/playersprite.png");
        static Sprite _playerSprite;
        int _direction;
        //int _speed;
        int _animFrames;
        int _animStop;
        float deltaTime;

        float _velocityX = 0;
        float _velocityY = 0;
        float _accelerationX = 0;
        float _accelerationY = 0;
        float _gravity = 0;

        #endregion

        #region Properties

        public RenderWindow Window
        {
            get;
            protected set;
        }

        public GameTime GameTime
        {
            get;
            protected set;
        }

        public Color WindowClearColor
        {
            get;
            protected set;
        }

        #endregion

        protected GameLoop(uint windowWidth, uint windowHeight, string windowTitle, Color windowClearColor)
        {
            _backgroundTexture.Repeated = true;
            _backgroundSprite = new Sprite(_backgroundTexture);

            _mouseSprite = new Sprite(_mouseTexture);

            _playerSprite = new Sprite(_playerTexture);
            //_playerSprite.TextureRect = new IntRect(0, 0, 64, 96);
            _playerSprite.Position = new Vector2f(640, 580);
            //_speed = 400f;

            this.WindowClearColor = windowClearColor;
            this.Window = new RenderWindow(new VideoMode(windowWidth, windowHeight), windowTitle);
            this.GameTime = new GameTime();

            Window.Closed += WindowClosed;
            Window.SetFramerateLimit(60);

            Window.KeyPressed += WindowEscaping;
            //Window.KeyPressed += WindowPlayerMoved;

            Window.MouseMoved += MouseMoved;
            Window.MouseLeft += MouseLeft;
            Window.MouseEntered += MouseEntered;
            Window.MouseButtonReleased += WindowMouseButtonReleased;
        }

        public void Run() // Main method of the gameloop
        {
            LoadContent();
            Initialize();

            _animFrames = 0;
            _direction = 192;
            _animStop = 64;

            float totalTimeBeforeUpdate = 0f;
            float previousTimeElapsed;//= 0f;
            previousTimeElapsed = _clock.ElapsedTime.AsSeconds();
            deltaTime = 0f;
            float totalTimeElapsed = 0f;

            while (Window.IsOpen)
            {
                Window.DispatchEvents();

                totalTimeElapsed = _clock.ElapsedTime.AsSeconds();
                deltaTime = totalTimeElapsed - previousTimeElapsed;
                previousTimeElapsed = totalTimeElapsed;

                totalTimeBeforeUpdate += deltaTime;

                Move();

                if (totalTimeBeforeUpdate >= TIME_UNTIL_UPDATE)
                {
                    GameTime.Update(totalTimeBeforeUpdate, totalTimeElapsed);
                    totalTimeBeforeUpdate = 0f;

                    Update(GameTime);

                    Window.Clear(WindowClearColor);

                    _backgroundSprite.Draw(Window, RenderStates.Default);

                    _mouseSprite.Draw(Window, RenderStates.Default);

                    if (_animFrames == 4) _animFrames = 0;
                    _playerSprite.TextureRect = new IntRect(_animFrames * _animStop, _direction, 64, 96);
                    ++_animFrames;
                    _playerSprite.Draw(Window, RenderStates.Default);

                    Draw(GameTime);
                    Window.Display();
                }
            }
        }

        public abstract void LoadContent();
        public abstract void Initialize();
        public abstract void Update(GameTime gameTime);
        public abstract void Draw(GameTime gameTime);

        private void Move()
        {
            _gravity = 5000;

            if (_playerSprite.Position.Y < 580) _velocityY += _gravity;
            else if (_playerSprite.Position.Y > 580) _playerSprite.Position = new Vector2f(_playerSprite.Position.X, 580);

            _velocityX += _accelerationX;
            _velocityY += _accelerationY;

            if (Keyboard.IsKeyPressed(Keyboard.Key.Space))
            {
                _animStop = 0;
                _velocityY = -100;
                _playerSprite.Position += new Vector2f(0f, _velocityY * deltaTime);
                Console.WriteLine(_playerSprite.Position);
            }

            if (Keyboard.IsKeyPressed(Keyboard.Key.Q))
            {
                _direction = 96;
                _animStop = 64;
                _velocityX = -500;
                _playerSprite.Position += new Vector2f(_velocityX * deltaTime, 0f);
            }

            else if (Keyboard.IsKeyPressed(Keyboard.Key.D))
            {
                _direction = 192;
                _animStop = 64;
                _velocityX = 500;
                _playerSprite.Position += new Vector2f(_velocityX * deltaTime, 0f);
            }
            else _animStop = 0;

            /*if (_playerSprite.Position.X >= 960) _backgroundSprite.TextureRect = new IntRect(new Vector2i((int)_playerSprite.Position.X % (int)_backgroundSprite.Texture.Size.X, 0), new Vector2i(1280, 720));
            else if (_playerSprite.Position.X < 320) _backgroundSprite.TextureRect = new IntRect(new Vector2i((int)_playerSprite.Position.X % (int)_backgroundSprite.Texture.Size.X, 0), new Vector2i(1280, 720));*/

            /*if (_playerSprite.Position.X < 0) _playerSprite.Position = new Vector2f(0, _playerSprite.Position.Y);
            else if (_playerSprite.Position.X > 1220) _playerSprite.Position = new Vector2f(1220, _playerSprite.Position.Y);*/
        }

        private void WindowClosed(object sender, EventArgs e)
        {
            Window.Close();
        }

        private void WindowEscaping(object sender, KeyEventArgs e)
        {
            if (e.Code == Keyboard.Key.Escape) Window.Close();
        }

        private void MouseLeft(object sender, EventArgs e)
        {
            Window.SetMouseCursorVisible(true);
        }

        private void MouseEntered(object sender, EventArgs e)
        {
            Window.SetMouseCursorVisible(false);
        }

        private void MouseMoved(object sender, MouseMoveEventArgs e)
        {
            _mouseSprite.Position = new Vector2f(e.X, e.Y);
        }

        private void WindowMouseButtonReleased(object sender, MouseButtonEventArgs e)
        {
            //if (e.Button == Mouse.Button.Left) _playerSprite.Position = new Vector2f(e.X, e.Y);
        }

    }
}

```

For those who prefer Hastebin, this is one: https://hastebin.com/ligerarigo.cs

# Answer
Here's a quick block of pseudo-code that could help you, with the comments.

Basically, the gravity is your acceleration, it modifies the velocity every frame, and the velocity modifies the position.

A jump is an impulse that modifies the velocity once (you have to make sure to not apply it every frame).

```
const gravity = 5000 // this should not change during the execution of your game

_accelerationY = gravity // Assuming that the 0,0 is at the top left of the screen

// As frames go by, the acceleration will increase, having the character falling faster and
// faster.

// Manage your input first (this will override the gravity.
if ( _spaceReleasedLastFrame && spaceDownThisFrame )
{
  // give  impulse
  _velocityY = -30000 // This high value is to scale with your gravity
  // Again, as frames go by, the gravity will revert the effect of this jump, slowing the
  // speed the character is going in the up direction, then making it go down.

  _spaceReleasedLastFrame = False // Make sure we don't spam the jump
}
else if ( !spaceDownThisFrame )
{
  _spaceReleasedLastFrame = True
}

_velocityY += _accelerationY // Change the velocity based on the acceleration (gravity)
_positionY += _velocityY

// When you reach the floor, make sure you don't get through, and set the velocity to 0 in
// case you find another force
if ( _positionY > 580 )
{
  _velocityY = 0
  _positionY = 580
}

```

*Keep in mind that it's been a while since I worked on something like this so there might be a small issue here or there.*

You'll eventually need a flag that sets when you jump, and resets when the character touches the ground to prevent double/triple/quadruple/etcuple jump.

---

On a side note, you seem to be working on a 60 FPS basis, and you seem to `Update` your game with the frame time (it's unclear now what `GameTime` does), but this does not apply to your `Move` method. You might want to pass the deltaT to the `Move` method and base your calculations on that. You'll have an easier time to wrap you head around x-pixels-per-second than x-pixels-per-variable-frame.
> -1 votes

---
Tags: c#, physics, sfml
---


title: How do I get min/max on a mesh

text:
# Question
Title: How do I get min/max on a mesh
I am trying to create an AABB but I need to know how to store min/max from a mesh.

Here is my code(I got it from thin matrix) :

```
package com.chimpro.london.objLoader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.lwjgl.util.vector.Vector2f;
import org.lwjgl.util.vector.Vector3f;

import com.chimpro.london.MainComp;
import com.chimpro.london.gfx.Loader;
import com.chimpro.london.models.TexturedModel;

public class OBJFileLoader {

public static TexturedModel loadOBJ(String objFileName,String textureLoc) throws IOException {
    InputStreamReader fis = new InputStreamReader(MainComp.class.getResourceAsStream(objFileName));
    BufferedReader reader = new BufferedReader(fis);
    String line;
    List<Vertex> vertices = new ArrayList<Vertex>();
    List<Vector2f> textures = new ArrayList<Vector2f>();
    List<Vector3f> normals = new ArrayList<Vector3f>();
    List<Integer> indices = new ArrayList<Integer>();
    try {
        while (true) {
            line = reader.readLine();
            if (line.startsWith("v ")) {
                String[] currentLine = line.split(" ");
                Vector3f vertex = new Vector3f((float) Float.valueOf(currentLine[1]),
                        (float) Float.valueOf(currentLine[2]),
                        (float) Float.valueOf(currentLine[3]));
                Vertex newVertex = new Vertex(vertices.size(), vertex);
                vertices.add(newVertex);

            } else if (line.startsWith("vt ")) {
                String[] currentLine = line.split(" ");
                Vector2f texture = new Vector2f((float) Float.valueOf(currentLine[1]),
                        (float) Float.valueOf(currentLine[2]));
                textures.add(texture);
            } else if (line.startsWith("vn ")) {
                String[] currentLine = line.split(" ");
                Vector3f normal = new Vector3f((float) Float.valueOf(currentLine[1]),
                        (float) Float.valueOf(currentLine[2]),
                        (float) Float.valueOf(currentLine[3]));
                normals.add(normal);
            } else if (line.startsWith("f ")) {
                break;
            }
        }
        while (line != null && line.startsWith("f ")) {
            String[] currentLine = line.split(" ");
            String[] vertex1 = currentLine[1].split("/");
            String[] vertex2 = currentLine[2].split("/");
            String[] vertex3 = currentLine[3].split("/");
            processVertex(vertex1, vertices, indices);
            processVertex(vertex2, vertices, indices);
            processVertex(vertex3, vertices, indices);
            line = reader.readLine();
        }
        reader.close();
    } catch (IOException e) {
        System.err.println("Error reading the file");
    }
    removeUnusedVertices(vertices);
    float[] verticesArray = new float[vertices.size() * 3];
    float[] texturesArray = new float[vertices.size() * 2];
    float[] normalsArray = new float[vertices.size() * 3];
    float furthest = convertDataToArrays(vertices, textures, normals, verticesArray,
            texturesArray, normalsArray);
    int[] indicesArray = convertIndicesListToArray(indices);
    TexturedModel model = new TexturedModel(Loader.loadToVao(verticesArray, texturesArray, normalsArray, indicesArray),0,vertices,furthest, textureLoc);
    return model;

}

private static void processVertex(String[] vertex, List<Vertex> vertices, List<Integer> indices) {
    int index = Integer.parseInt(vertex[0]) - 1;
    Vertex currentVertex = vertices.get(index);
    int textureIndex = Integer.parseInt(vertex[1]) - 1;
    int normalIndex = Integer.parseInt(vertex[2]) - 1;
    if (!currentVertex.isSet()) {
        currentVertex.setTextureIndex(textureIndex);
        currentVertex.setNormalIndex(normalIndex);
        indices.add(index);
    } else {
        dealWithAlreadyProcessedVertex(currentVertex, textureIndex, normalIndex, indices,
                vertices);
    }
}

private static int[] convertIndicesListToArray(List<Integer> indices) {
    int[] indicesArray = new int[indices.size()];
    for (int i = 0; i < indicesArray.length; i++) {
        indicesArray[i] = indices.get(i);
    }
    return indicesArray;
}

private static float convertDataToArrays(List<Vertex> vertices, List<Vector2f> textures,
        List<Vector3f> normals, float[] verticesArray, float[] texturesArray,
        float[] normalsArray) {
    float furthestPoint = 0;
    for (int i = 0; i < vertices.size(); i++) {
        Vertex currentVertex = vertices.get(i);
        if (currentVertex.getLength() > furthestPoint) {
            furthestPoint = currentVertex.getLength();
        }
        Vector3f position = currentVertex.getPosition();
        Vector2f textureCoord = textures.get(currentVertex.getTextureIndex());
        Vector3f normalVector = normals.get(currentVertex.getNormalIndex());
        verticesArray[i * 3] = position.x;
        verticesArray[i * 3 + 1] = position.y;
        verticesArray[i * 3 + 2] = position.z;
        texturesArray[i * 2] = textureCoord.x;
        texturesArray[i * 2 + 1] = 1 - textureCoord.y;
        normalsArray[i * 3] = normalVector.x;
        normalsArray[i * 3 + 1] = normalVector.y;
        normalsArray[i * 3 + 2] = normalVector.z;
    }
    return furthestPoint;
}

private static void dealWithAlreadyProcessedVertex(Vertex previousVertex, int newTextureIndex,
        int newNormalIndex, List<Integer> indices, List<Vertex> vertices) {
    if (previousVertex.hasSameTextureAndNormal(newTextureIndex, newNormalIndex)) {
        indices.add(previousVertex.getIndex());
    } else {
        Vertex anotherVertex = previousVertex.getDuplicateVertex();
        if (anotherVertex != null) {
            dealWithAlreadyProcessedVertex(anotherVertex, newTextureIndex, newNormalIndex,
                    indices, vertices);
        } else {
            Vertex duplicateVertex = new Vertex(vertices.size(), previousVertex.getPosition());
            duplicateVertex.setTextureIndex(newTextureIndex);
            duplicateVertex.setNormalIndex(newNormalIndex);
            previousVertex.setDuplicateVertex(duplicateVertex);
            vertices.add(duplicateVertex);
            indices.add(duplicateVertex.getIndex());
        }

    }
}

private static void removeUnusedVertices(List<Vertex> vertices){
    for(Vertex vertex:vertices){
        if(!vertex.isSet()){
            vertex.setTextureIndex(0);
            vertex.setNormalIndex(0);
        }
    }
}

}

```

# Answer
Same solution as Macky ben Jonah's but a little neater:

```
private static Vector3f getExtreme(final List<Vertex> vertices,
        final BinaryOperator<Float> op) {
    final float x = vertices.stream().map(v -> v.getPosition().x).reduce(op).orElse(0f);
    final float y = vertices.stream().map(v -> v.getPosition().y).reduce(op).orElse(0f);
    final float z = vertices.stream().map(v -> v.getPosition().z).reduce(op).orElse(0f);
    return new Vector3f(x, y, z);
}

```

Then you can use it like this:

```
Vector3f min = getExtreme(vertices, Math::min);
Vector3f max = getExtreme(vertices, Math::max);

```

This requires Java 8 because it makes use of Streams and it is also a lot more performance friendly than the original solution since it does not have to create new lists and loop through them every time it is called.
> 0 votes

# Answer
Set each component of the initial `maximum` coordinate to the *minimum* value of a float. Similarly, set each component of the initial `minimum` to the *maximum* value of a float.

Iterate over every vertex in the mesh. With each vertex, set the `maximum`, component-wise, to the larger of the current `maximum` or the current vertex. Similarly, for the `minimum`, set it component-wise to the smaller of the current maximum or the vertex.

In pseudo-code, this might look like:

```
Vector minimum(Float.Maximum, Float.Maximum, Float.Maximum);
Vector maximum(Float.Minimum, Float.Minimum, Float.Minimum);
foreach(Vertex vertex in mesh) {
  minimum = componentwiseMinimum(minimum, vertex.position);
  maximum = componentwiseMaximum(maximum, vertex.position);
}

```
> 4 votes

# Answer
**Here is my solution:**

```
    private static Vector3f min(List<Vertex> vertices) {
    List<Float>  xArray= new ArrayList<>();
    List<Float> yArray = new ArrayList<>();
    List<Float> zArray = new ArrayList<>();
    for(Vertex vertex : vertices) {
        xArray.add(vertex.getPosition().x);
        yArray.add(vertex.getPosition().y);
        zArray.add(vertex.getPosition().z);
    }
    return new Vector3f(Collections.min(xArray),Collections.min(yArray),Collections.min(zArray));
}

private static Vector3f max(List<Vertex> vertices) {
    List<Float>  xArray= new ArrayList<>();
    List<Float> yArray = new ArrayList<>();
    List<Float> zArray = new ArrayList<>();
    for(Vertex vertex : vertices) {
        xArray.add(vertex.getPosition().x);
        yArray.add(vertex.getPosition().y);
        zArray.add(vertex.getPosition().z);
    }
    return new Vector3f(Collections.max(xArray),Collections.max   (yArray),Collections.max(zArray));
}

```
> 0 votes

---
Tags: opengl, java, lwjgl, mesh, obj
---


# Question
Title: Rigidbody has unintended effect, velocity limiter from unknown source
I have made a script that alters a rigidbody's angular velocity. It works well but has one issue, its speed plateaus past a certain point.

Here is the script:

```
    void Start(){
    //Get references.
    bat = transform.GetChild (0).gameObject;
    rig = bat.GetComponent<Rigidbody> ();
    //Initialize variables.
    initPos = bat.transform.position;

    initAngle = bat.transform.rotation.eulerAngles.y;
    if (leftSide) {
        maxAngle = bat.transform.rotation.eulerAngles.y - 45;
        rig.centerOfMass = bat.transform.localPosition;
    } else {
        maxAngle = bat.transform.rotation.eulerAngles.y + 45;
        rig.centerOfMass = -bat.transform.localPosition;
    }
}

void Update(){
    if(leftSide){ // True and false does the same but mirrored effect.
        if(Input.GetButton ("Left Bat")){// button pressed?
            if(bat.transform.rotation.eulerAngles.y > maxAngle){//lower than max angle?(since this is the mirrored version, its rot starts at 180 and turns CCW, thus the '>')
                currAngle = -1 * turnSpeed; // then allow turning
            } else {// otherwise
                currAngle = 0f; //prevent further turning
            }
        } else {// button not pressed?
            if(bat.transform.rotation.eulerAngles.y < initAngle){// greater than resting angle?(same reason as above explanation)
                currAngle = 1 * turnSpeed; // then automatically return
            } else {//otherwise
                currAngle = 0f; //stop returning
                bat.transform.rotation = Quaternion.Euler (new Vector3 (bat.transform.rotation.eulerAngles.x, initAngle, bat.transform.rotation.eulerAngles.z));// this statement re-aligns the rotation of the flipper its initial state(instantly) to prevent slight kinks due to inconsistencies.
                bat.transform.position = initPos;//turning the flipper for some reason can deviate its own position(slight but cumulative), this returns the flipper to its initial position.
            }
        }
    } else { // default version.
        if(Input.GetButton ("Right Bat")){
            if(bat.transform.rotation.eulerAngles.y < maxAngle){
                currAngle = 1 * turnSpeed;
            } else {
                currAngle = 0f;
            }
        } else {
            if(bat.transform.rotation.eulerAngles.y > initAngle){
                currAngle = -1 * turnSpeed;
            } else {
                currAngle = 0f;
                bat.transform.rotation = Quaternion.Euler (new Vector3 (bat.transform.rotation.eulerAngles.x, initAngle, bat.transform.rotation.eulerAngles.z));
                bat.transform.position = initPos;
            }
        }
    }
}

void FixedUpdate(){// rigidbodies should be processed in fixedupdate I think
    rig.angularVelocity = new Vector3( 0, currAngle, 0);
}

```

The issue is, no matter how high a value I enter for the movement part, it doesn't get faster than a specific speed. I tried hardcoding a value instead of changing the variable but it didn't make a difference. If I enter a small value, the movement is slower though.

# Answer
> 0 votes
I found that Unity has a limit on the max angular velocity for rigidbodies. This can be overridden individually using `rigidbodyRef.maxAngularVelocity`

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


# Question
Title: Exporting Fbx from maya to Unity makes the model deformed
So I have a female avatar model and I have attached cloth model to it by binding it to skeleton rig. After that copying weights from avatar to the cloth model. Now when i export it as an fbx and open it in unity, it converts the whole model into a deformed shape. I have removed the errors related to scale compensation as well by running the (ScaleCompenstationOff ) mel script in Maya but still no success. Kindly let me know if you guys know of any solution to this problem !!!

# Answer
I might come a bit too late. I had the same issue, what I did to fix this was to copy and paste the following code and paste it on the MEL box:

```
{
string $selected[] = `ls -type joint`;
select -r $selected;
}

string $sel[] = `ls -sl`;
string $singleJnt;
for ($singleJnt in $sel)
{
setAttr ($singleJnt + ".segmentScaleCompensate") 0;
}

```

You have to do it everytime you make a new joint. Source
> 2 votes

# Answer
I've had this problem as well. What solved it for me was deleting non-deformer history for the model. (edit -\> delete all by type -\> non deformer history)
> 1 votes

---
Tags: unity, maya
---


# Question
Title: NullReferenceException shown every single time a change is applied to my prefab
I created a prefab out of a game object in my scene. Every single time I hit `Apply` after making changes to my game object, I see the following stack trace:

However, as far as I can surmise, the changes are applied nonetheless, because the bolded field (indicating that its value is yet to be applied to the prefab) immediately becomes un-bolded once I hit `Apply`.

1. If, contrary to my belief, my changes are not applied to my prefab, what should I do to ensure that they are?
2. If the error message appears even when I successfully apply my changes to my prefab, what can I do to make it go away?

**UPDATE 1:**

I noticed that after the first time I hit `Apply`, the game object went from being highlighted in blue (indicating that it mirrors a prefab) to being highlighted in black (indicating that it no longer mirrors a prefab).

Game objects that mirror other prefabs work fine. This is the only exception.

**UPDATE 2:**

I deleted the prefab, and created another prefab from the same game object. This time, after hitting `Apply`, I still see the same exception, but the game object remains highlighted in blue (indicating that it is still mirroring a prefab).

# Answer
> 1 votes
What I did to resolve the issue:

I deleted the game object from the scene, along with its prefab. I checked my changes into source control.

I asked my game designer to add the game object back into the scene, and then to check in his change.

I pulled his change, and re-created a prefab from the game object. Everything started working as expected -- I no longer see the error message, and all changes I make to the game object are now correctly applied to the prefab as well.

I still don't understand what happened in the first place to cause the problem, but the aforementioned approach fixed it.

---
Tags: unity
---


# Question
Title: How to use quaternions with JOML and LWJGL3
I'm implementing a space fps game (there is no up or down in space!) using LWJGL3 and JOML (math library).

Entities in my game have a rotation based on the Forward, Up and Right vectors. I use pitch, yaw and roll methods to rotate my entities. The methods can be seen in the pseudo code further down.

When I construct the model matrix for an entity I calculate a rotation matrix based on the 3 vectors described above and apply it. It can be seen in the pseudo code further down.

I also use angular and linear acceleration and velocity to rotate and move an entity. It can be seen in the pseudo code further down.

Entity:

```
Vector3f position
Vector3f scale
Vector3f forward
Vector3f up
Vector3f right
private Vector3f linearAcc
private Vector3f linearVel
private Vector3f angularAcc
private Vector3f angularVel

public void pitch(double angle) {
    forward.mul((float) Math.cos(angle), tempVector1).add(up.mul((float) Math.sin(angle), tempVector2)).normalize(forward);
    right.cross(forward, up);
}

public void roll(double angle) {
    right.mul((float) Math.cos(angle), tempVector1).add(up.mul((float) Math.sin(angle), tempVector2)).normalize(right);
    right.cross(forward, up);
}

public void yaw(double angle) {
    right.mul((float) Math.cos(angle), tempVector1).add(forward.mul((float) Math.sin(angle), tempVector2), right);
    up.cross(right, forward);
}

public Matrix4f getRotationMatrix(Matrix4f dest) {
    dest.set(
        right.x, right.y, right.z, 0,
        forward.x, forward.y, forward.z, 0,
        up.x, up.y, up.z, 0,
        0, 0, 0, 1);
    return dest;
}

```

Model matrix:

```
public static Matrix4f createModelMatrix(Vector3f position, Matrix4f rotationMatrix, Vector3f scale) {
    Matrix4f modelMatrix = new Matrix4f();
    modelMatrix.translate(position);
    modelMatrix.mul(rotationMatrix);
    modelMatrix.scale(scale);
    return modelMatrix;
}

```

Basic logic for rotating and moving an entity:

```
        // Angular acceleration:
        // Angular acceleration is reset every update
        entity.getAngularAcc().zero();

        // Components may rotate an entity by applying angular acceleration
        Vector3f someAngularThrust = new Vector3f(0, 0, 0.025f);
        entity.getAngularAcc().add(someAngularThrust );

        // The accumulated angular acceleration is added to the angular velocity
        entity.getAngularVel().fma(dt, movement.getAngularAcc());

        // Finally, the entity is rotated by the angular velocity
        entity.pitch(dt * entity.getAngularVel().x);
        entity.yaw(dt * entity.getAngularVel().y);
        entity.roll(dt * entity.getAngularVel().z);

        // The basic logic applies for linear movement:
        // Linear acceleration is reset every update
        entity.getLinearAcc().zero();

        // Components may move an entity by applying linear acceleration
        Vector3f someLinearThrust = entity.getForward().mul(5);
        entity.getLinearAcc().add(someLinearThrust );

        // The accumulated linear acceleration is added to the linear velocity
        entity.getLinearVel().fma(dt, entity.getLinearAcc());

        // Finally, the entity is moved by the linear velocity
        entity.getPosition().fma(dt, entity.getLinearVel());

```

So far it seems that this setup works, but it does not give me all the functionality I need in my game:

* I want an alternative way of setting/modifying the rotation of an entity - right now it can only be done by setting the Forward, Up and Right vectors or using the pitch, yaw and roll methods.
* I want to be able to represent the rotation of an entity with a smaller unit (a rotation vector / axis?). It is a multiplayer game where I need to send the orientation of entities. Sending 2 or more 3d vectors to represent the orientation is not optimal.

From what I understand quaternions can do all that I want. I tried to use it in my game (Quaternionf in JOML), but couldn't get it to work properly:

* I couldn't get the pitch, yaw and roll methods to work.
* The model matrix didn't work. The facing direction of the entities did not match the direction they were moving - they were supposed to move in the direction they were facing.
* The movement logic didn't seem to work either (even when not using pitch, yaw and roll). Could have got something to do with the above point.

Any ideas how I should go on about to use quaternions in my code?

# Answer
Sorry you've been waiting so long for an answer. Learning quaternions was a huge headache for me, but it was definitely worth it. Here is my code. I don't fully understand it some times, but the more I play with it the better I get.

Just play around with it and you'll see what's going on.

```
import org.joml.Matrix4f;
import org.joml.Quaternionf;
import org.joml.Vector3f;

Quaternionf dest1 = new Quaternionf();
Quaternionf dest2 = new Quaternionf();
Vector3f v = new Vector3f();

// verticesModel is the initial position of my vertices
//before the 3D transformations are done
// Vector3f[] verticesModel

for(int i = 0 ; i < verticesModel.length;i++)
{

        // I have a global variable 'v' just to avoid making a new Vector3f object 60 times every second when the draw() method is run
        v.x = verticesModel[i].x;
        v.y = verticesModel[i].y;
        v.z = verticesModel[i].z;

        // blank out my quaternions
        dest1.w = 1f;
        dest1.x = 0f;
        dest1.y = 0f;
        dest1.z = 0f;

        dest2.w = 1f;
        dest2.x = 0f;
        dest2.y = 0f;
        dest2.z = 0f;

        // I keep my pitch/yaw/roll in another Vector3F called rotationXYZ as degrees
        float x, y, z;
        x = rotationXYZ.x;// + rotationXYZ.x;// testX;
        y = rotationXYZ.y;// + rotationXYZ.y;//testY;
        z = rotationXYZ.z;// + rotationXYZ.z;//testZ;

        // just make sure the degrees values don't get bigger than they need to be
        x = x % 360.0f;
        y = y % 360.0f;
        z = z % 360.0f;

        // convert to radians and start transforming
        dest2.rotate((float) Math.toRadians(x), (float) Math.toRadians(y), (float) Math.toRadians(z), dest1);

        dest1.transform(v);

        // vv is the new value for v after the transformations
        // Vector3f[] vertices is the array of vertices I use to draw
        Vector3f vv = vertices[i];

        vv.x = v.x;
        vv.y = v.y;
        vv.z = v.z;

```

}
> 1 votes

---
Tags: java, rotation, quaternion, lwjgl3
---


title: Input.GetAxis() always returns 0

text:
# Question
Title: Input.GetAxis() always returns 0
Here is a screenshot of the Input Manager for my project:

The 9th and 10th axis refer to `Axis1D.PrimaryIndexTrigger (Squeeze)` and `Axis1D.SecondaryIndexTrigger (Squeeze)` respectively, as documented on this page.

However, `Input.GetAxis(trigger)` always returns `0`, even when

1. the trigger name is correct, and
2. I am squeezing the corresponding trigger really hard.

While running the debugger, I used my **right** Oculus controller to interact with objects in my scene. Here is the debug window:

Even though I was squeezing the corresponding trigger on my right Oculus controller, `Input.GetAxis(trigger)` still returned `0`, thus causing my method to return early.

Here are the fields and properties of my `Hand` class, in which I am invoking the `Input.GetAxis(trigger)` method:

```
public enum XRHandControllerNode
{
    Left,
    Right
}

private XRNode trackedXRNode =>
    this.TrackedXRNode == XRHandControllerNode.Left ? XRNode.LeftHand : XRNode.RightHand;

private const float MinimumSqueeze = 0.8f;
private string trigger =>
                   this.TrackedXRNode == XRHandControllerNode.Left ?
                   "LeftIndexTrigger" :
                   "RightIndexTrigger";

public XRHandControllerNode TrackedXRNode;

```

Why does `Input.GetAxis` always return 0, and what changes should I make to ensure that any squeeze of the trigger will be correctly detected?

# Answer
> 1 votes
It was a timing issue. `Input.GetAxis(trigger)` returned values that are negligibly close to 1 in subsequent invocations of `Update()` as I continued squeezing the corresponding trigger on my Oculus controller.

---
Tags: unity, c#, virtual-reality, oculus
---


# Question
Title: How would I add a sound variable to my code?
I am writing some code in JavaScript for a ray cast shooting program. I have all the variables I need except for sound, and I'm not too sure on how to add that variable into my code. I would really appreciate any help people can give to solve this problem, and show me how to add a sound variable to my code.

```
#pragma strict

var Effect : Transform;
var Damage = 100;

function Update () {

 var hit : RaycastHit;
 var ray : Ray = Camera.main.ScreenPointToRay(Vector3(Screen.width*0.5, Screen.height*0.5, 0));

 if (Input.GetMouseButtonDown(0))
 {
  if (Physics.Raycast (ray, hit, 100))
  {
   hit.transform.SendMessage("ApplyDamage", Damage, SendMessageOptions.DontRequireReceiver);
  }
 }
}
```

# Answer
You'll need to add an audio source to your GameObject and assign it with an `AudioClip`, then you can play the sound like this when your raycast hits something.

```
#pragma strict

var Effect : Transform;
var Damage = 100;
var AudioSource : AudioSource;

function Start () {
    AudioSource = GetComponent.<AudioSource>();
}

function Update () {
    var hit : RaycastHit;
    var ray : Ray = Camera.main.ScreenPointToRay(Vector3(Screen.width*0.5, Screen.height*0.5, 0));

    if (Input.GetMouseButtonDown(0))
    {
        if (Physics.Raycast (ray, hit, 100))
        {
            hit.transform.SendMessage("ApplyDamage", Damage, SendMessageOptions.DontRequireReceiver);
            AudioSource.Play();
        }
    }
}

```
> 1 votes

---
Tags: unity, javascript, sound, sound-effects
---


# Question
Title: Vulkan best practice when submitting draw commands
As with most projects working in a graphics library, I need to dynamically send draw calls to the command buffers, but what is the best way to do this? Currently, for every frame, I rebuild my command buffers, specify the objects I wish to render, then destroy the command buffer. Am I doing it the right way? I thought there might be a clear command for the buffer but I still need to find it.

One other way I thought I could get it to work is when an object is needed to be displayed/removed, then and only then, I rebuild the command buffer. But again I'm not sure how to handle this properly.

Any help is really appreciated.

# Answer
> 1 votes
A good way is to keep several sets of resources, each set for a single frame. Each set should contain a command buffer (or more), a fence and two semaphores.

Now You record a command buffer (or more), potentially with ONE\_TIME\_SUBMIT flag, and submit it to a queue. During submission You wait for "image acquired" semaphore that was provided to vkAcquireNextImageKHR() function. You also provide the second semaphore and the fence to be signaled. Semaphore is used for vkQueuePresentKHR() function.

For the next frame You take another set of the above resources until You run out of all sets. Then You just take the set that is the oldest (least recently used). You check if the fence from this set is already signaled. If it is, You record the command buffer and perform all the usual job. If the fence is not signaled, You wait for it. But if You have 3 or 4 such sets there is a small chance that the fence isn't already signaled.

You can't re-record a command buffer while it still being processed, so You need to wait. But this approach lets minimize waiting. You don't need to use functions like vkDeviceWaitIdle() and thus stalling graphics hardware pipeline. It's also easier to balance memory consumption, input lag and performance. The more sets, the less wait and better performance, but more memory is used and potentially You increase input lag. Typically 2, 3, maybe 4, sets should be enough.

Example of such approach is described in the Vulkan Cookbook and presented on Github:

Increasing the performance through increasing the number of separately rendered frames

# Answer
> 0 votes
> Currently, for every frame, I rebuild my command buffers, specify the objects I wish to render, then destroy the command buffer. Am I doing it the right way?

Assuming you're not just rendering the exact same content over and over again, you're most likely going to have to do *some* command buffer creation and recording on a per-frame basis.

However, you can look into the use of secondary command buffers to contain many of the individual drawing commands. These secondary command buffers would not need to be re-recorded each frame, but could be updated only when the rendering for some item in the command buffer is actually modified.

---
Tags: vulkan
---


title: Keeping 2D camera within game bounds

text:
# Question
Title: Keeping 2D camera within game bounds
I have a simple camera class which works for following my character around, and has an adjustable zoom. However, I cannot figure out how to keep the camera within the bounds of the world. As far as I know, I can't just pull the X and Y coordinates of the Transform, so I don't know how to check if it is out of bounds. Help greatly appreciated.

```
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Game10
{
class Camera
{
    protected float _zoom;
    public Matrix Transform { get; private set; }

    public Camera()
    {
        _zoom = 1f;
    }

    public void DecreaseZoom()
    {
        if (Input.IsZoomDecrease())
           {
                _zoom -= 0.25f;
                if (_zoom < 0.25f
                {
                    _zoom = 0.25f;
                }
           }
    }

    public void IncreaseZoom()
    {
        if (Input.IsZoomIncrease())
           {
                _zoom += 0.25f;
           }
                if (_zoom > 4f
                {
                    _zoom = 4f;
                }
    }

    public void Follow(Player target)
    {
        var position = Matrix.CreateTranslation(
            -target.Position.X - (target.Bounds.Width / 2),
            -target.Position.Y - (target.Bounds.Height / 2),
            0);

        var offset = Matrix.CreateTranslation(
            Platformer.ScreenWidth / _zoom / 2,
            Platformer.ScreenHeight / _zoom / 2,
            0);

        var zoom = Matrix.CreateScale(_zoom, _zoom, 1);

        Transform = position * offset * zoom;

    }

}
}

```

# Answer
> 1 votes
I think your camera class needs some tuning up. If you follow along with this link you'll have a nice implementation to work with.

Now on to the matter of restricting your camera to the world boundaries.

The algorithm looks like this:

1. Take the camera boundaries (position + viewport) and transform them into world coordinates.
2. Restrict those coordinates so that they are inside the world boundaries.
3. Transform the restricted coordinates back into camera coordinates.

*Note: I'm assuming the camera position is supposed to align with the center of the viewpoint.*

In order to find the world space coordinates you will need an inverse transform which you can get from the transform like this: `var inverseTransform = Matrix.Invert(transform);`

```
//Requirements
Vector2 cameraPosition;
Viewport viewport;
Matrix transform;
Matrix inverseTransform;

//Get the top left and bottom right position of the camera in screen space.
var cameraTopLeft = cameraPosition - new Vector2(viewport.Width / 2f, viewport.Height / 2f);
var cameraBottomRight = cameraPosition + new Vector2(viewport.Width / 2f, viewport.Height / 2f);

//Transform the screenspace coordinates into world space coordinates.
var cameraTopLeftWorld = Vector2.Transform(cameraTopLeft, inverseTransform);
var cameraBottomRightWorld = Vector2.Transform(cameraBottomRight, inverseTransform);

//Create the world space boundary rectangle of the camera
var width = cameraBottomRightWorld.X - cameraTopLeftWorld.X;
var height = cameraBottomRightWorld.Y - cameraTopLeftWorld.Y;
var bounds = new Rectangle(cameraTopLeftWorld.X, cameraTopLeftWorld.Y, width, height);

//Use the bounds rectangle to restrict the camera position.
if(bounds.X < worldBounds.X) bounds.X = worldBounds.X; //Off the left side
if(bounds.Y < worldBounds.Y) bounds.Y = worldBounds.Y; //Off the top side
if(bounds.Right > worldBounds.Right) bounds.X = worldBounds.Right - bounds.Width; //Off the right side
if(bounds.Bottom > worldBounds.Bottom) bounds.Y = worldBounds.Bottom - bounds.Height; //Off the bottom side

//Now take the restricted boundaries and transform them back into a position for the camera
var boundsCenter = new Vector2(bounds.X + bounds.Width / 2f, bounds.Y + bounds.Height / 2f);
var cameraCenterPosition = Vector2.Transform(boundsCenter, transform);
cameraPosition = cameraCenterPosition;

```

This algorithm is quite basic but works well. However, if you include rotation into your camera then this will fail.

---
Tags: xna, camera
---


# Question
Title: Unity Custom EventManager, multiple arguments, and order
I have some hard question for me... I have a nice EventManager, who handle multiple arguments. (no argument, one int, one bool, a GameObject and a bool... but for each sort, I have to create a special dictionnary for this...

```
public class EventManager : SingletonMono<EventManager>
{
        //here I have many, many class who handle all sorte of different arguments...
         private class UnityEventInt : UnityEvent<int>  {    }

        //here definition of all dictionnnary for each class...
        private Dictionary<GameData.Event, UnityEvent> eventDictionary;
        private Dictionary<GameData.Event, UnityEventInt> eventDictionaryInt;

    private void Awake()
    {
        Init();
    }
    void Init()
    {
        //here initialise all dictionnary
        if (eventDictionary == null)
            eventDictionary = new Dictionary<GameData.Event, UnityEvent>();
        if (eventDictionaryInt == null)
        eventDictionaryInt = new Dictionary<GameData.Event, UnityEventInt>();
        //...
    }

    //One of the startListening
    public static void StartListening(GameData.Event eventName, UnityAction<int> listener)
    {
        if (!Instance)
            return;

        UnityEventInt thisEvent = null;
        if (Instance.eventDictionaryInt.TryGetValue(eventName, out thisEvent))
        {
            thisEvent.AddListener(listener);
        }
        else
        {
            thisEvent = new UnityEventInt();
            thisEvent.AddListener(listener);
            Instance.eventDictionaryInt.Add(eventName, thisEvent);
        }
    }

    //one of the stop
    public static void StopListening(GameData.Event eventName, UnityAction listener)
    {
        if (EventManager.Instance == null)   //au cas ou on a déja supprimé l'eventManager
            return;
        UnityEvent thisEvent = null;
        //si on veut unregister et que la clé existe dans le dico..
        if (Instance.eventDictionary.TryGetValue(eventName, out thisEvent))
        {
            thisEvent.RemoveListener(listener);
        }
    }

    //and one of the trigger
    public static void TriggerEvent(GameData.Event eventName, int param1)
    {
        if (EventManager.Instance == null)   //au cas ou on a déja supprimé l'eventManager
            return;
        UnityEventInt thisEvent = null;
        if (Instance.eventDictionaryInt.TryGetValue(eventName, out thisEvent))
        {
            thisEvent.Invoke(param1);
        }
    }

```

And... when I want, in some script I do:

```
EventManager.StopListening(GameData.Event.PlayerAddScore, SomeFuncntion);
EventManager.StartListening(GameData.Event.PlayerAddScore, SomeFuncntion);

EventManager.TriggerEvent(GameData.Event.PlayerAddScore, 1);

```

here SomeFunction take 1 argument, but if i wanted to have 2... i have to hard code the case in my EventManager

So... My question is... how can I make that dynamic ? with only one Dictionary ? with only one list ? with good OOP or something ?

And secondly, how can I handle order or the call ? Let's say 2 functions are listening for PlayerAddScore from 2 different script, how can I handle an order between the 2 function ?

Thanks you for help.

# Answer
> 1 votes
# You can't do this easily.

If you absolutely, positively, must have a single function declaration that takes in exactly 1 argument and you want to pass more, and only sometimes, your best bet is to have that 1 argument be an `Object[]`. You'll have to figure out how many objects and of what type they are in your handler function, but you *can* do it. It definitely isn't pretty and might cause more problems than it solves.

Your alternative is to make a delegate for each number and type of parameters you wish to use and...have multiple methods that deal with invoking each those delegate calls.

Essentially what this boils down to, is you have an event that has only so many details, and you want to do several different things with it, and that's not something you should be doing. `ThingWasClicked()` only needs 1 parameter: the thing that was clicked. Passing a second object doesn't really make much sense, especially if you are conditionally sending that second object based on what the listener wants to know about...

No, just send everything all the time and if the listener doesn't care, it just ignores the paramters. There is nothing wrong with

```
private void HandleSomeClick(GameObject go, int i, bool b, string s, Qaternion q) {
    /*do nothing*/
}

```

---
Tags: unity, events, oop
---


title: How can I make Diagonal movement?

text:
# Question
Title: How can I make Diagonal movement?
This is a follow-up question to my last one. I am developing a game which has an Icon on a `JLabel`which the user controls with WASD keys. Right now it can go up, down, left, and right, but I want to know how I can make it move diagonally if two keys are held. I have recreated a short example and posted it below along with a gif(sorry, it's not very smooth), and I am hoping you can help me out. Thanks!

```
public class Experiments extends JFrame {
    javax.swing.Timer movement;
    int x = 230;
    int y = 120;
    boolean wPressed, aPressed, sPressed, dPressed;

    public Experiments() {
        layoutGame();
        setTitle("Example");
        setSize(500, 350);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    private void layoutGame() {
        JLabel bg = new JLabel();
        bg.setIcon(new ImageIcon(this.getClass().getClassLoader().getResource("space.png")));
        add(bg, BorderLayout.CENTER);

        JLabel you = new JLabel();
        you.setBounds(x, y, 50, 50);
        you.setIcon(new ImageIcon(this.getClass().getClassLoader().getResource("happy.png")));
        bg.add(you, JLabel.CENTER);

        JTextPane direction = new JTextPane();
        direction.setText("Direction");
        add(direction, BorderLayout.SOUTH);
        move(you);

        direction.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                movement.stop();
                if(e.getKeyChar() == 'w') {
                    wPressed = true;
                    move(you);
                } else if (e.getKeyChar() == 'a') {
                    aPressed = true;
                    move(you);
                } else if (e.getKeyChar() == 's') {
                    sPressed = true;
                    move(you);
                } else if (e.getKeyChar() == 'd') {
                    dPressed = true;
                    move(you);
                }
                direction.setText(null);
            }
            public void keyReleased(KeyEvent e) {
                wPressed = false;
                aPressed = false;
                sPressed = false;
                dPressed = false;
            }
        });
    }

    private void move(JLabel icon) {
        int delay = 10; //milliseconds
        ActionListener taskPerformer = new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                if(icon.getX() >= 0 && icon.getX() <= 450 && icon.getY() >= 0 && icon.getY() <= 250) {
                    if (wPressed) {
                        y = y - 4;
                    } else if(aPressed) {
                        x = x - 4;
                    } else if(sPressed) {
                        y = y + 4;
                    } else if(dPressed) {
                        x = x + 4;
                    }
                    icon.setBounds(x, y, 50, 50);
                    icon.repaint();
                }
            }
        };
        movement = new javax.swing.Timer(delay, taskPerformer);
        movement.start();
    }

    public static void main(String[] args) {
        new Experiments();
    }
}

```

The output is smooth, but I had to make a gif, so it looks bumpy(sorry again):

# Answer
The logic is simple (as shown in the comments). You'll want to make the movement values the sum of potential values, according to which keys are pressed. However, to make the distance traveled constant, you must *normalize the vector*. The vector is the xy pair of movement values (e.g. \<+1,0\> or \<-1,+1\>). Normalizing means making the magnitude (length) of the vector one, to become a unit vector. To do this, you must divide each component (x and y) by it's magnitude. To calculate the magnitude, use the length formula from algebra class:

```
// dx and dy are the respective movement values
mag = sqrt(dx*dx + dy*dy)
dx /= mag
dy /= mag

```

That way, you will always move at the same speed, whether going diagonally or not.
> 3 votes

# Answer
```
centy = stamp('cat6',120,120,120)
centy.move//any coordinate you want.(x,y,milliseconds)

```
> -3 votes

---
Tags: java, movement, swing
---


title: Projection Texture Mapping

text:
# Question
Title: Projection Texture Mapping
I have been trying to understand how projective texture works; and, even I have been able to achieve the result by following the steps in tutorial, I fail to understand how it works in my mind.

To my understanding, we need to construct a model, a view and a projection matrix for the texture along with a bias matrix which maps to `[0, 1]`.

The usual steps consist of:

* Calculating the UV within vertex shader by the projection texture's matrix (MVP + Bias matrix).
* Then, sampling the texture (the smiley face) using the aforementioned UV passed in from vertex.

But what is actually happening within vertex shader and fragment shader?

Take the following image, for instance:

Please correct me if I am wrong:

Here, we have a teapot, a background texture and a texture for the projection (the smiley face).

What is happening when the background and the teapot is going through vertex and fragment shader as far as projective texture is concerned?

Some says rather than projecting the texture onto the objects in the scene, we are *actually* projecting the scene onto the the texture (the smiley face), which I also fail to see.

Again, by using the code found on most tutorial sites I have been able to achieve the result; but my goal is to be able to understand how things work, which I hope someone could offer me a hand here by taking me through the vertex and fragment shader and perhaps post some pictures which could help me to see what is happening in my mind. I have been trying to read several books and online tutorials on this but I have not been successful in understanding it.

Thanks.

# Answer
When you're projecting a texture, the goal is to take some texture and 'paste' it onto the scene. This is essentially mapping points on the texture to points in the scene, so if we can find a mapping between these coordinate systems we'll have our solution. It's difficult to map from the texture's 2D coordinates to 3D world coordinates, but it turns out to be relatively straightforward to go from 3D world coordinates to 2D texture ones with the help of some usual graphics programming tools.

When you use the graphic pipeline normally, you project to the viewport like so:

With texture projection, you're using very similar steps, except instead of a virtual camera, you're creating a view frustum for the texture. You can imagine replacing the near clip plane in the above image with the texture you're projecting, and you can further **imagine all of the projected points of the objects in the scene hitting the texture in some place. These places on the texture being hit can also correspond to UV coordinates**. The UV coordinate being 'hit' corresponds to the 3D point hitting it in the sense that if you had just 'pasted' the texture onto the scene, that UV coordinate would have hit that 3D point. This is the 3D-to-2D mapping I mentioned earlier.

Like the virtual camera, your texture frustum is defined by a set of MVP matrices. However, after applying them, the projection matrix returns points in clip-space, and after applying perspective division you're in a space from \[-1, 1\] on your axes. The bias simply adjusts this to \[0, 1\] so it matches the UV coordinates you want.

I've tried to keep this more conceptual rather than technical because it seems like that's your main problem with it, but let me know if anything can be clarified!
> 3 votes

# Answer
First, let's talk about what "texture mapping" means. The phrase is intended to be taken literally. A texture mapping is the "mapping" from a surface into a texture image. Your surface is defined by vertices, and each vertex has a position.

When it comes to triangle rasterization, the texture mapping is typically created on a per-vertex basis. That is, each vertex has a texture coordinate, which says "for this position in space, get your texture data from this location in the texture." Between a triangle's vertices, the texture coordinates are interpolated, creating a smooth mapping across the planer surface.

But this is merely one particular kind of mapping. There's nothing stopping you from mapping things in another way.

---

Second, let's talk about what "projection" means. When you render a 3D scene to the screen, you are performing some kind of projection operation. A "projection" is merely the transformation of a position from one dimensionality to another. In our case, from 3D space into a 2D space, namely the screen.

3D rendering involves projection. We have 3D points, and we want to do stuff on a 2D image (namely, the screen). So we have to perform projection: we take the 3D scene and project it onto the 2D image. This operation happens on the vertex positions.

Now, before we do the meat of the projection operation, we generally want to transform the positions into a space relative to the camera. This is done with a 4x4 matrix transform, going from model space to camera space. To do the projection, we apply another 4x4 matrix transform, leading us into 4-dimensional clip-space. Of course, since 4x4 matrices can be composed, we can do this with a single matrix multiply of a composed model-to-clip-space matrix.

At that point, we're done with the vertex shader, because OpenGL or D3D will do the rest of the projection work converting from a 4D clip-space position into a 2D screen-space position. See, this is all hard-coded, and I'm not about to get into the deep details of this process here. But there is one detail I do want to cover.

Perspective projection is not a linear transformation, and a 4x4 matrix can *only* encode linear transformations. So how do we do projection with a matrix? Because the next step after the VS is dividing the position by the 4th component, the W component. Division by a coordinate is not a linear transform, and it is this division that makes perspective projection non-linear. So we set the W component to the value that needs to be divided in order to do perspective projection.

That division, called the perspective divide, is important. OpenGL/D3D does this step for us automatically when rendering.

---

So, what is "projection texture mapping"? Well, let's lay out the goal of this process:

**We want to compute texture coordinates for our objects so that it appears that a texture is projected over the objects in the scene.**

That's the goal. Since we're computing texture coordinates, we are performing "texture mapping". And since we're casting a 2D image over a 3D scene, that sounds like "projection", since we're changing dimensionality.

The trick here is to realize that this projection is *no different* from the kind of projection you use to render. When you render, you're projecting a portion of a 3D scene into a 2D screen image. When you do projection texture mapping, you're projecting a portion of a 3D scene into a 2D *texture* image. The only difference is what the destination is. In the former case, you're projecting to do rasterization. In the latter, you're using the post-projection positions as *texture coordinates*.

But the math is the same.

Indeed, OpenGL even has special `Proj` texture accessing functions which take that `W` component, so that you don't have to do the perspective division yourself.

All of the math for doing projection texture mapping is *exactly the same* as you would use for rendering. Instead of projecting the scene onto a screen-sized area, you're projecting it onto the \[0, 1\] normalized texture coordinate area. Oh yes, you will use different camera and projection matrices than the one you use for rendering. But the actual math itself, the formulas you use, are all identical.
> 0 votes

---
Tags: opengl, projection, shadow-mapping
---


# Question
Title: Equivalent to Draw() method in Unity project?
I have been using xna/monogame before this. So I read tutorials about unity, made some classes, loaded some sprites, everything "seems" to be going good, but I can't figure out how to add things into the environment, could anyone tell me or guide me to what's the equivalent of Monogame's Draw() method in Unity? Thank you.

# Answer
> 0 votes
Unity doesn't have XNA equivalent for Draw method. There are some low level helpers, but don't think it's need until you'll try to do something more complex.

Unity takes care of rendering instead of doing the manually. Add GameObjects to scene and attach components like MeshRenderer, SpriteRenderer or some other. And it will be put into rendering queue automatically. To control rendering order there SortingLayer, SortingOrder, DrawQueue(in shader), Layering property, so it's enough to make complex scenes with custom behaviuors.

# Answer
> 2 votes
There is a way to do this without SpriteRenderers using Graphics.DrawMesh(). You can use this method to draw sprites by using properties that sprites have like vertices, triangles, uv, texture, etc. to construct a mesh and appropriate material.

Here is an example

```
public class SpriteDrawer : MonoBehaviour {

// A list of textures we want to build materials for beforehand
// Using the same material saves draw calls
public List<Texture2D> textures;
public Material spriteMaterial;

Dictionary<Texture2D, Material> textureMats = new Dictionary<Texture2D, Material>();

public void Awake() {
    //fill up textureMats with materials
    foreach (Texture2D texture in textures) {
        textureMats.Add(texture, new Material(spriteMaterial) {
            mainTexture = texture
        });
    }
}

public void Draw(Sprite sprite, Vector3 pos) {
    Material mat;
    //check if we already made a prebuilt material, otherwise make a new one
    if (textureMats.ContainsKey(sprite.texture)) {
        mat = textureMats[sprite.texture];
    } else {
        mat = new Material(spriteMaterial) {
            mainTexture = sprite.texture
        };
    }
    //build a mesh for the sprite
    Mesh mesh = new Mesh() {
        vertices = Array.ConvertAll(sprite.vertices, x => (Vector3)x),
        triangles = Array.ConvertAll(sprite.triangles, x => (int)x),
        uv = sprite.uv
    };
    Graphics.DrawMesh(mesh, Matrix4x4.TRS(pos, Quaternion.identity, sprite.bounds.size), mat, 0);
}
}

```

NOTE: I haven't tested this script so it may or may not work

---
Tags: xna, unity, monogame
---


# Question
Title: Unity 2017.3.of3 Raycast2D randomly misses objects
2d up down platformer. Character has 2 Rays(one left one right) going down, when either Ray's hit distance hits between -1 and 1 it should call a function which will change character direction from down to up. Works 1, 2, 3, 4, sometimes 6, sometimes into the teens times then character goes through the obstacle got placing character over an obstacle and hitting play with no changes gave a different amount of time before falling through the obstacle. I have tried changing the Time.time in fixedUpdate, placed movement in last update, varying degrees of success, I will post the current version of code, but it has gone through several revisions any ideas accepted. thanks

```
[RequireComponent (typeof (BoxCollider2D))]
public class YowiController : MonoBehaviour {

  BoxCollider2D yowiCollider;
  Vector2 rayDir, leftRay, rightRay, rayOrigin;

  public AudioSource jumpSound;

  bool jump;
  bool bounce;

  public float upTime;
  float looseTime;

  float bounceCount = 0;
  float gravity = 3f;
  float bounceHeight = 5f;
  float movementSpeed = 2f;
  float bounceTime = .03f;

  void Start () {
    yowiCollider = GetComponent<BoxCollider2D> ();
    rayDir = new Vector2 (0, -1);
    jump = false;
    bounce = false;
  }

  void Update () {
  }

  private void LateUpdate () {
    movement ();
  }

  void movement () {
    drawRays ();
    if (Input.GetKey (KeyCode.RightArrow)) {
      transform.Translate (Vector2.right * Time.deltaTime * movementSpeed);
    }
    if (Input.GetKey (KeyCode.LeftArrow)) {
      transform.Translate (Vector2.left * Time.deltaTime * movementSpeed);
    }
    if (!bounce) {
      transform.Translate (Vector2.down * Time.deltaTime * gravity);
      gravity += .02f;
    } else {
      Bounce ();
    }
  }

  void Bounce () {
    transform.Translate (Vector2.up * Time.deltaTime * bounceHeight);
    looseTime = bounceTime / 2;
    if (upTime < looseTime) {
      bounceHeight += .01f;
      looseTime--;
    } else {
      bounceHeight -= .01f;
    }
  }

  void drawRays () {
    Bounds bounds = yowiCollider.bounds;
    leftRay = new Vector2 (bounds.min.x, bounds.min.y);
    rightRay = new Vector2 (bounds.max.x, bounds.min.y);
    RaycastHit2D leftHit = Physics2D.Raycast (leftRay, rayDir * -1, .05f, 1 << 9);
    RaycastHit2D rightHit = Physics2D.Raycast (rightRay, rayDir * -1, .05f, 1 << 9);
    if (leftHit || rightHit) {
      RayHit (leftHit, rightHit);
    }
  }

  void RayHit (RaycastHit2D leftHit, RaycastHit2D rightHit) {
    if ((leftHit.distance < 1.1f) && (leftHit.distance > -1.1f)) {
      bounce = true;
      StartCoroutine (Bouncing ());
    } else if (rightHit.distance < 1.1f && rightHit.distance > -1.1f) {
      bounce = true;
      StartCoroutine (Bouncing ());
    } else {
      print ("No Joy");
    }
  }

  IEnumerator Bouncing () {
    yield return new WaitForSeconds (bounceTime);
    bounce = false;
  }
}

```

# Answer
> 0 votes
At one point I tried switching the rays to the sprite(didn't work well) instead of the collider, so I move the setting the rays origins to start, this had the consequence of the rays not moving at all from their origin. Moved the origin to update and added a second set of rays in a separate function as a "backup". This seemed to do the trick, I commented out the second set of rays function and tested for 30 minutes with no misses, this is the updated code.

```
[RequireComponent (typeof (BoxCollider2D))]

```

public class YowiTest : MonoBehaviour {

```
BoxCollider2D yowiCollider;
RaycastHit2D firstLeftHit, firstRightHit;
RaycastHit2D secondLeftHit, secondRightHit;

Vector2 firstLeftRay, firstRightRay;
Vector2 secondLeftRay, secondRightRay;
Vector2 rayOrigin, velocity, rayDown;

Bounds bounds;

float midPoints;
float gravity = -.06f;
float movementSpeed = .01f;
float jump = .05f;

void Start () {
    yowiCollider = GetComponent<BoxCollider2D> ();
    rayDown = new Vector2 (0, -1);
    midPoints = (bounds.max.x - bounds.min.x) / 4;
}

void Update () {
    bounds = yowiCollider.bounds;
    movement ();
    drawRaysOne ();
    //drawRaysTwo ();
}

void movement () {
    Vector2 input = new Vector2 (Input.GetAxisRaw ("Horizontal"), Input.GetAxisRaw ("Vertical"));
    velocity.x = input.x * movementSpeed;
    velocity.y += gravity * Time.deltaTime;
    transform.Translate (velocity);
}

void drawRaysOne () {
    firstLeftRay = new Vector2 (bounds.min.x, bounds.min.y);
    firstRightRay = new Vector2 (bounds.max.x, bounds.min.y);
    firstLeftHit = Physics2D.Raycast (firstLeftRay, rayDown, .1f, 1 << 9);
    firstRightHit = Physics2D.Raycast (firstRightRay, rayDown, .1f, 1 << 9);
    Debug.DrawRay (firstRightRay, rayDown, Color.white);
    Debug.DrawRay (firstLeftRay, rayDown, Color.white);
    if (firstRightHit || firstLeftHit) {
        print ("First ray hit");
        velocity.y = jump;
    }
}

void drawRaysTwo () {
    secondLeftRay = new Vector2 (bounds.min.x + midPoints, bounds.min.y);
    secondRightRay = new Vector2 (bounds.max.x - midPoints, bounds.min.y);
    secondLeftHit = Physics2D.Raycast (secondLeftRay, rayDown, .1f, 1 << 9);
    secondRightHit = Physics2D.Raycast (secondRightRay, rayDown, .1f, 1 << 9);
    Debug.DrawRay (secondLeftRay, rayDown, Color.blue);
    Debug.DrawRay (secondRightRay, rayDown, Color.blue);
    if (secondRightHit || secondLeftHit) {
        print ("Second ray hit");
        velocity.y = jump;
    }
}

```

}

---
Tags: unity, 2d, raycasting
---


title: Unity: Problem with swipe

text:
# Question
Title: Unity: Problem with swipe
I rotate a 3D object to left and right with swipe to left and right. Problem is on different devices with different pixel densities, it gets faster and slower. i.e. if you move your finger 1 cmm on one device will not rotate the object same amount that it will on another device, like a Retina and non-Retina one.

Last time I wanted to solve this I could not as IIRC there was no way to get physical pixel density of device or it's dimensions (to get density via division over resolution)

Thanks.

# Answer
Presumably, using `Screen.width` and `Screen.height` should do the trick. Then you just divide the delta in dragged pixels by that total screen dimension, and this will give you some fraction between 0.0 and 1.0. You can multiply that by some fixed angle (and possibly `Time.timeDelta`?) to get your rotational increment.
> 1 votes

# Answer
use viewport coordinates and detect swipes based on percentage of the screen https://docs.unity3d.com/ScriptReference/Camera.WorldToViewportPoint.html

```
const float dragThreshold = 0.15f;
Vector3.Length(cam.WorldToViewportPoint(endDrag) - cam.WorldToViewportPoint(endDrag)) > dragThreshold

```
> 0 votes

---
Tags: unity
---


title: Projectiles in FPS games - OpenGL

text:
# Question
Title: Projectiles in FPS games - OpenGL
I have some experience with Blender, but now I am using Xcode 9.2 and OpenGL 4.1 on MacBook Pro. I am also attending a couple of online courses on edX.

I am developing (for fun and as an exercise) a very simple FPS game. I haven't handled collisions, yet, and I am thinking of how to implement projectiles.The question I have about projectiles, when they are actual object and several of them are present simultaneously in the scene, is the following. Is it better, performance-wise, to generate an object for each active projectile or simply reuse the same object but redrawing it several times and with different transformation matrix (passed to the same shader via uniform mat4)?

# Answer
In first-person shooters, ranged weapons are typically divided into at least two categories:

**Hitscan** \- an instantaneous raycast collision test

**Projectile** \- a dynamic object with a finite speed that is updated every frame until collision

Hitscans (what you mean by "abstraction") offer better performance, especially if there are a lot of weapons being used, since the calculation happens immediately and requires no additional objects in the scene. Projectiles on the other hand offer better accuracy at the cost of some performance (for example, some AAA games make use of extremely long range sniper rifles that take things like drag and the bullet trajectory into consideration).

So to answer your question--yes, a common implementation of projectiles is having N number of objects in the scene, and each frame they are moved forward, and a ray from it's previous position is tested to its current position for collision.

And regarding your other question, for projectiles you can improve performance by having the same vertex buffer, shader, and material data, and then binding that and drawing each projectile using a transform matrix passed to the shader.

I recommend you start with a hitscan weapon and also try projectile weapons, it's pretty fun :)
> 0 votes

---
Tags: projectile-physics
---


# Question
Title: How to make user move in virtual reality with Google Cardboard and Unity?
I am working on a virtual walkthrough using Google Cardboard in Unity 5.3.5.

I have a building, and I need to move around inside the room using google cardboard. How can I do that? Is it possible to move around when we walk holding the Google Cardboard? I have done movement using arrow key. I am able to turn around the building with Google Cardboard.

# Answer
No, the user does not walk around while using VR. That would be extremely dangerous as your are effectively blind to your real-world surroundings. You could stub your toe on your coffee table, or fall off a cliff, depending where you are.

VR relies on some sort of stationary controller. Whether it be keyboard and mouse, PlayStation controller, or Kinect sensors reading body movements, in all cases the user generally doesn't move more than a foot or so from their location while wearing the vision-impairing head unit.

Augmented reality, on the other hand, does allow the user to move around and interact with the real world in some enhanced (i.e. augmented) way. An example of an augmented reality device would be Google Glass.
> 4 votes

# Answer
Most games get around the problem of you hitting wall in VR by teleporting you around. This is usually done in such a way that the player can push a button to teleport where they are looking.

The easiest way to implement this would be to use the button on top of the Cardboard to trigger a touch event. This event would send a raycast and teleport you to the destination if it is valid ( e.g. not inside a wall or out of bounds )
> 2 votes

# Answer
Here is some code that you should apply to the camera in a .cs script. Then you will be able to move around just by looking.

```
using UnityEngine;
using System.Collections;

public class controller : MonoBehaviour
{
    private bool walking = false;
    private Vector3 spawnPoint;

    private void Start()
    {
        spawnPoint = transform.position;
    }

    private void Update()
    {
        if (walking)
        {
            transform.position = transform.position + Camera.main.transform.forward * .5f * Time.deltaTime;
        }

        if (transform.position.y < -10f)
        {
            transform.position = spawnPoint;
        }

        Ray ray = Camera.main.ViewportPointToRay(new Vector3(.5f, .5f, 0));
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit))
        {
            if (hit.collider.name.Contains("plane"))
            {
                walking = false;
            }
            else
            {
                walking = true;
            }
        }
    }
}

```
> 1 votes

# Answer
ummm im not a game dev but what about making it so when they touch the thingy on the side allowing that to make the character run? not sure if you can but hey its worth a shot
> -3 votes

---
Tags: unity, virtual-reality, google-cardboard
---


# Question
Title: Background generation with sprites in 2D dimension in Unity
I am making 2D game with Unity. I want to create a procedurally generated background with a bunch of sprites (space background, I have sprites of nebulas and stars). I want some area around the player to be filled with sprites to some extent.

How to make background filling with sprites inside area around player but outside camera visible area?

How to control generation according to players movement for generating in player moving direction only?

How to control the amount of filling sprites while generating?

# Answer
First you need a way to generate your star prefabs.

This is a simple code that creates your stars randomly:

```
using System.Collections;
using UnityEngine;

public class StarGenerator : MonoBehaviour {
    public GameObject Prefab;
    public Vector2 SpawnRange;
    public int SpawnNumber = 500;
    public float MaxiMaximumSize = 1f;

    private void Start()
    {
        GenerateStar();
    }
    public void GenerateStar()
    {

        for (int i = 0; i < SpawnNumber; i++)
        {
            var star = Instantiate(Prefab, new Vector2(Random.Range(0, 20f),Random.Range(0, 20f)), Quaternion.identity);
            float randomsize = Random.Range(0, MaxiMaximumSize);
            star.transform.localScale = new Vector2(randomsize, randomsize);
        }
    }

}

```

then you can move star randomly. Remember, after a while, the circles are out of range,so you can Regenerate It by Destroying and Instancing again but Instead of this way you can use Object Pooling.

```
using System.Collections;
using UnityEngine;

public class Star : MonoBehaviour {
    public GameObject Prefab;
    private float randomMovement;

    /*public Vector2 SpawnRange;
    public int SpawnNumber = 500;
    public float MaxiMaximumSize = 1f;
    */

    private void Start()
    {

        randomMovement = Random.Range(1, 2f)*Time.deltaTime;
    }

    private void Update()
    {
        var horizontal = -Input.GetAxis("Horizontal");
        var vertical = -Input.GetAxis("Vertical");

        transform.Translate(new Vector2(randomMovement * horizontal, randomMovement * vertical));
    }

    /*
    public void Regenerage()
    {
       transform.position = new Vector2(Random.Range(0, 20f), Random.Range(0, 20f));
        float randomsize = Random.Range(0, MaxiMaximumSize);
        transform.localScale = new Vector2(randomsize, randomsize);
    }
    */
}

```

Also you can create procedural stars by shader or particle:

Star Nest

Star particles
> 2 votes

# Answer
I would divide your world into a grid. If your sprites are N x N pixels (say 32 x 32), I would divide it up into a grid of cells that are each M x M sprites (say 5 x 5). At any position in the world, you can figure out what grid cell you're in by doing:

```
gridCell.x = floor(worldPosition.x / (M * N));
gridCell.y = floor(worldPosition.y / (M * N));

```

You can then use the grid position as a seed for a random number generator. Let's say that the x and y grid positions are 16-bit signed values and your random number generator takes a 32-bit seed. You could do something like:

```
seed = ((uint32_t)gridCell.x << 16) | ((uint32_t)gridCell.y)
randomSeed(seed);

```

Next, generate the index of which sprite to use using your random generator. The key here is to generate *all* of the sprite indexes in the current grid position every time so they always generate in the same order:

```
int i = 0;
for (y = 0; y < M; y++)
{
    for (x = 0; x < M; x++)
    {
        spriteIndex [ i ] = random(0, MAX_NUM_SPRITES);
        i++;
    }
}

```

Then you can fill in the current grid cell with the M x M sprites:

```
int i = 0;
for (y = 0; y < M; y++)
{
    for (x = 0; x < M; x++)
    {
        Draw(sprite[i], (gridCell.x * (M * N)) + x * N, (gridCell.y * (M * N)) + y * N);
        i++;
    }
}

```
> 1 votes

---
Tags: unity, 2d, sprites, procedural-generation, procedural
---


title: Draw triangles around screen

text:
# Question
Title: Draw triangles around screen
I am trying to draw triangles around the screen something like this:

This is my script which can draw 6 triangles but I am not sure how to expand it to draw more like 8 or 10 triangles. Any help is appreciated

```
using UnityEngine;
using System.Collections;

    public class BackgroundScript : MonoBehaviour
    {
        [SerializeField]
        private Material darkMaterial;
        [SerializeField]
        private Material lightMaterial;

        [SerializeField]
        private float triangleDistance = 50;

        private GameObject[] triangles;

        void Start()
        {
            CreateBackground();
        }

        private void CreateBackground()
        {
            float w = triangleDistance * Mathf.Tan(30 * (Mathf.PI / 180));

            triangles = new GameObject[6];

            for (int i = 0; i < 6; i++)
            {
                GameObject backgroundTriangle = new GameObject();
                backgroundTriangle.name = "triangle " + i;
                triangles[i] = backgroundTriangle;

                MeshFilter mf = backgroundTriangle.AddComponent<MeshFilter>();
                MeshRenderer mr = backgroundTriangle.AddComponent<MeshRenderer>();

                Mesh mesh = new Mesh();
                mesh.vertices = new Vector3[] { new Vector3(0, 0, 0), new Vector3(triangleDistance, 0, w), new Vector3(triangleDistance, 0, -w) };
                mesh.normals = new Vector3[] { new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0) };
                mesh.triangles = new int[] { 0, 1, 2 };
                mf.mesh = mesh;

                mr.material = i % 2 == 0 ? darkMaterial : lightMaterial;

                backgroundTriangle.transform.Rotate(new Vector3(0, i * 60 + 30, 0));
                backgroundTriangle.transform.SetParent(this.transform);
            }
        }
    }

```

# Answer
> 1 votes
eight triangle:

```
using UnityEngine;
using System.Collections;

    public class BackgroundScript : MonoBehaviour
    {
        [SerializeField]
        private Material darkMaterial;
        [SerializeField]
        private Material lightMaterial;

        [SerializeField]
        private float triangleDistance = 50;

        private GameObject[] triangles;

        void Start()
        {
            CreateBackground();
        }

        private void CreateBackground()
        {
            float w = triangleDistance * Mathf.Tan(22 * (Mathf.PI / 180));

            triangles = new GameObject[8];

            for (int i = 0; i < 8; i++)
            {
                GameObject backgroundTriangle = new GameObject();
                backgroundTriangle.name = "triangle " + i;
                triangles[i] = backgroundTriangle;

                MeshFilter mf = backgroundTriangle.AddComponent<MeshFilter>();
                MeshRenderer mr = backgroundTriangle.AddComponent<MeshRenderer>();

                Mesh mesh = new Mesh();
                mesh.vertices = new Vector3[] { new Vector3(0, 0, 0), new Vector3(triangleDistance, 0, w), new Vector3(triangleDistance, 0, -w) };
                mesh.normals = new Vector3[] { new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0) };
                mesh.triangles = new int[] { 0, 1, 2 };
                mf.mesh = mesh;

                mr.material = i % 2 == 0 ? darkMaterial : lightMaterial;

                backgroundTriangle.transform.Rotate(new Vector3(0, i * 45 + 30, 0));
                backgroundTriangle.transform.SetParent(this.transform);
            }
        }
    }

```

---

also you can create this shape by shader.

The Book of Shaders Shapes Tutorial

To create a new shader, either choose `Assets > Create > Shader > Unlit Shader` from the main menu, or duplicate an existing shader and work from that. The new shader can be edited by double-clicking it in the Project View.then copy below shader to it:

```
 Shader "Custom/ProceduralTriangle"
{
    Properties
    {
        _numberOfTriangle("numberOfTriangle",Int) = 8
    }
    SubShader
    {

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = v.uv;
                return o;
            }

            int _numberOfTriangle;

            fixed4 frag (v2f i) : SV_Target
            {
     float2 st = i.uv;
        float3 color = float3(0,0,0);

        float2 pos = float2(0.5,0.5)-st;

        float r = step(length(pos),0.);
        float a = atan2(pos.x,pos.y);

        float f = cos(a*_numberOfTriangle+_Time.y);
        float c = smoothstep(f,f+0.02,r);
        color = float3(c,c,c);

        return float4(color, 1.0);
            }
            ENDCG
        }
    }
}

```

then create a material and use this shader.

this is simple fragment shader if you want to create geometry you can use geometry shader.I will update my question and explain this.

---
Tags: unity, geometry
---


# Question
Title: When I use a font in my game, do I have to include its license in the credits?
For example, if I use this font from Google Fonts:
https://fonts.google.com/specimen/Open+Sans

This font is licensed under Apache License 2.0
But regardless of the license, if it allows commercial use, do I have to include a notice or the license in the credits? (assuming that I didn't modify the font)

# Answer
The attribution requirements of a work are part of the licence. You have to refer to it (or your lawyer who has been paid to read it for you) to know what must be done.

If your question is actually "must the attribution be in the credits as opposed to some other place?", the answer is "unless there is some requirement in the license, no". Movies would put this in the credits because that's the only accessable place to a theatre viewer, but plenty of software just includes a file or directory of notices of licenses invoked. You can put it in an about screen or a licenses screen in the options menu (android phones and one smart thermostat i've seen do this) or whatever works for you, as long as it's reasonably findable by anyone looking for it.
> 1 votes

---
Tags: legal, copyright, fonts, licensing
---


title: How to create a 2D physics waterfall

text:
# Question
Title: How to create a 2D physics waterfall
I am trying to create a waterfall that looks similar to the first image below (please check this video for a better idea of what I want to achieve) with physics properties so it can move or around objects with colliders on its course (similar to the second image below). Though the linked waterfall is 3d I am interested in a 2d implementation.

Note that the objects are dynamic and some move frequently hence the waterfall has to reshape every frame. The objects move slowly either moving to different positions or rotating. How can this be done?

# Answer
> 14 votes
I wanted to see if I could pull this off without dynamically regenerating the mesh for the waterfall every frame. It turns out, there is a way. :D

Each object that can block the waterfall (objects bearing a `WaterCatcher` script in my prototype) has an outline mesh wrapping around its perimeter. (This can be auto-generated in advance using the collider's shape)

This outline mesh renders the water flowing along the object. I use a shader to `clip` out the part that's beneath the object. I also track a left and right "catch" point where a waterfall lands on the object and flows left or right respectively, so I can `clip` out the part that's to the left of the right waterfall and to the right of the left waterfall.

Then the vertical falls are just basic quad primitives, stretched to the appropriate length. I use another shader to scroll the waterfall texture over the falls and fade it out at the top & bottom ends. Then I layer on a foam particle system at the impact point to help cover the blend.

Here's a close-up so you can see the component parts.

At the top I have a "root" waterfall to kick things off. Each frame, after all the `Update()` scripts have run to move things around, it fires a `CircleCast` downward, to see if its water hits anything. If it hits a `WaterCatcher`, it tells it to show its water skin downstream of the hit point.

I determine "downstream" using the hit normal - if it's very close to vertical, or if the incoming waterfall spans edges that slope in both directions, then we spill both left and right.

Each `WaterCatcher` has a left and a right waterfall of its own, which it enables and positions on its far edge if it's spilling in that direction - otherwise they stay hidden. These waterfalls in turn fire `CircleCast`s downward to find what *they* spill onto, and so on...

The prototype still has a few visual glitches that could be improved - the water flow along an object pops on all at once instead of animating, and the flow rules could use a little extra tolerance or hysteresis so it doesn't cut off as easily on rotating objects. I think these should be fairly solvable issues though.

Background,rocks, and rotating platform textures via Kenney

---

Here are the tricks I use in my water catcher fragment shader:

```
// My wraparound geometry is build so the "x+" UV direction
// points "outward" from the object.
// Using derivatives, I can turn this into a vector in screen space.
// We'll use this below to clip out water hanging off the bottom.
float2 outward = float2(ddx(i.uv.x), ddy(i.uv.x));

// i.worldX is the worldspace x position of this fragment
// (interpolated from the vertex shader)

// _LeftX is a material property representing the worldspace x coordinate
// of the rightmost water flow that's spilling left,
// and _RightX the wold x of the leftmost water flow that's spilling right.
float left = _LeftX - i.worldX;   // +ve if we're to the left of a left spill.
float right = i.worldX - _RightX; // +ve if we're to the right of a right spill.

float limit = max(left, right); // +ve if we're in the path of either flow.

// If the "outward" vector is pointing down, make this negative.
limit = min(limit, outward.y + 0.001f);

// If any of the conditions above make limit <= 0, abort this fragment.
clip(limit);

// Otherwise, scroll the water texture!
// Counter-clockwise if we're in the left flow, clockwise otherwise.
i.uv.y -= sign(left) * _Time.y;

```

# Answer
> 1 votes
1. You can deform the waterfall mesh on object collision to match the required collider pattern.
2. The easier one and more accurate, but more performance heavy - use particle system - create a particle system with colliders and use every particle as a drop of water. But that looks a bit odd if you have default sprite and if the particle count is small and they are too big. But it's performance heavy, so you don't want molecule simulation in you game.

I would go with 1.

* But Mesh deformation CPU \- it's slow, but may work for you.
* I would use shaders to achieve this - Water shader example \- mesh has effects like it collides with other meshes and it's way faster than methods before. I guess it's possible to make mesh to stop the render in some projected shape - that is the change you would need to make to normal water shader, it's complicated to achieve if you are not familliar with shaders.

No easy solution with good performance.

**Result of particle system:** *(To change the values I had to wait about 3-4s, it's slow)*

---
Tags: unity
---


title: Project 2D texture onto a cubemap

text:
# Question
Title: Project 2D texture onto a cubemap
I'm looking to take a 2D texture (previously rendered from the user's perspective), and overlay it overtop of a cubemap.

Since a cubemap has 6 textures, I need to run a shader over top of all 6, and use some formula for calculating the UV from a given view.

I'm at a loss for how to calculate this.

Here's an illustration

If the user were to spin around in 1 spot, they would build up full panoramic cubemap.

The intention is to reuse end-of-frame data to update a persistent cubemap that follows the user.

I know how to build manual cubemaps by rendering a scene 6 times, once on all axes, however in this case I wish to take an already rendered view and transplant it onto the correct spots on a cubemap.

# Answer
> 3 votes
I think I was going about this the wrong way. I didn't need to do some unruly math to convert spherical coordinates into UV coordinates for all 6 faces, I just needed to project the quad properly.

I made a fragment shader that simply passes through the texture it's provided, and the texture coordinates are just a quad's UV's (with no alterations).

```
#version 430 core
layout (location = 0) uniform sampler2D screenTexture;
layout (location = 0) out vec3 OutputColor;
in vec2 TexCoord;

void main()
{
    OutputColor = texture(screenTexture, UV).rgb;
}

```

Recall my goal: to project what the user sees into a cubemap.

In the vertex shader, I position the quad at the far plane of the user's frustum, and then render it from the perspective of each of the 6 viewing angles of the cubemap.

```
void main()
{
    TexCoord = (vertex.xy + vec2(1.0)) / 2.0;

    // Strip the translation from the matrix
    mat4 InvRotVMatrix = vMatrix_Inverse;
    InvRotVMatrix[3][0] = 0;
    InvRotVMatrix[3][1] = 0;
    InvRotVMatrix[3][2] = 0;

    vec4 WorldPos = (InvRotVMatrix * pMatrix_Inverse * vec4(vertex.xyz, 1));
    gl_Position = Proj * View[View_Index] * WorldPos;
}

```

---
Tags: opengl, graphics, projection, cubemap
---


# Question
Title: How do you time jump animation with uneven landing surface?
Say my player jumps off from a certain point on a 2D surface. Say my surface is uneven, and has varying y positions along the level, how would I then be able to time my jump animation accordingly? (The issue being is that the animation might get cut off half way through, or vice versa - the animation would be already finished while the player is still jumping/landing)

# Answer
> 2 votes
Usually, when working on jumping mechanics, instead of relying on the duration of the animation, the motion is split in 3 (sometimes even more, but most of the times 3 is enough) animations:

* Jump from the ground animation
* in air /falling animation
* landing animation

In Unity, you could merge these three animations inside a blendtree while changing its state (jumping/in air/landing) based on a boolean parameter which is usually called `isGrounded`.

`IsGrounded`, as the name implies, checks if the player is grounded. To set this variable properly, there are two main ways:

* you could either shoot a Raycast from the character origin to the ground(it has to be parallel to the global y axis);
* or a sphere Cast(the same a raycast, but it's using a sphere mesh, to get a bit more precision).

You can see the two different approaches described in more detail here

Via the player script, you can just set `isGrounded`'s value inside with:

```
Animator anim;
bool value;

void Start()
{
    anim = GetComponent<Animator>();
}

void Update()
{
    // set 'value' to true if the player is grounded, set it to false if it's not
    //then set the isGrounded bool inside the animator
    anim.SetBool("isGrounded",value);
}

```

---
Tags: animation, jumping
---


title: Vector field collision avoidance

text:
# Question
Title: Vector field collision avoidance
I'm developing a simple "Geometry Wars" like game: 2D world and multiple enemy spaceships. The enemies should be able to pursue the player and avoid collisions between them at the same time. I've implemented a vector field algorithm based on this one. When two ships are too near between them, a force that slightly modifies the direction of the ship is created.

This works like a charm, the enemies pursue the player and no collision exits, but this happens sometimes:

This is because in one frame they "collide" and the path is modified, but, in the next frame they are not colliding and the path is not altered. This two states in loop cause that shaking.

Do you have any idea to solve this?

PS: if I didn't make myself clear, please ask me, english is not my first language

# Answer
> 1 votes
So yeah... I solved my problem... I was normalizing the vector from the enemies before adding it with the original direction, and this creates a step too big between "no collision" and "collision".

---
Tags: 2d, collision-detection, ai, steering-behaviors, collision-avoidance
---


# Question
Title: In a 2D game with an isometric camera (like Bastion) do I need to create a new animation for every angle the player is facing?
For different actions like jumping, attacking, moving etc, do I need to make new animations for every angle I am doing the action? Or is there a way to somehow run around that requirement?

# Answer
> 7 votes
You can always just use 3d models instead of 2d art (3d models don't neccessarily mean a 3d game). Apart from that, not much. You could mirror half of the sprites, but that may interfere with the lighting a bit.

---
Tags: 2d, animation, isometric
---


# Question
Title: OnRoomConnected always fail (Google play service unity3d)
OnRoomConnected always return false, Im stuck...(Authenticate is success). Thank you for attention.

```
private List<Participant> participants;

public void Authenticate()
{
    PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder()
        .Build();

    PlayGamesPlatform.InitializeInstance(config);
    // recommended for debugging:
    // PlayGamesPlatform.DebugLogEnabled = true;
    // Activate the Google Play Games platform
    PlayGamesPlatform.Activate();

    Social.localUser.Authenticate((bool success) =>
    {
        if (success)
        {
            Debug.Log("Authentication succeeded");
            //CreateQuickGame();
        }
        else
        {
            Debug.Log("Authentication failed");
        }
    });
}

public void CreateQuickGame()
{
    const int MinOpponents = 2, MaxOpponents = 2;
    const int GameVariant = 0;
    PlayGamesPlatform.Instance.RealTime.CreateWithInvitationScreen(MinOpponents, MaxOpponents, GameVariant, this);
}

#region RealTimeMultiplayerListener implementation

public void OnLeftRoom()
{
    SceneManager.LoadSceneAsync(SceneManager.GetActiveScene().buildIndex);
}

public void OnParticipantLeft(Participant participant)
{
    SceneManager.LoadSceneAsync(SceneManager.GetActiveScene().buildIndex);
}

public void OnPeersConnected(string[] participantIds)
{
    Debug.Log("OnPeersConnected");
    byte[] message = Encoding.ASCII.GetBytes("Test"); // build your message
    bool reliable = true;
    PlayGamesPlatform.Instance.RealTime.SendMessageToAll(reliable, message);
}

public void OnPeersDisconnected(string[] participantIds)
{
    //SceneManager.LoadSceneAsync(SceneManager.GetActiveScene().buildIndex);
}

public void OnRealTimeMessageReceived(bool isReliable, string senderId, byte[] data)
{
}

public void OnRoomConnected(bool success)
{
    if (success)
    {
        Debug.Log("Room Connected success");

        MainScene ms = new MainScene();
        ms.Waithing_sprite.SetActive(true);
        // Successfully connected to room!
        // ...start playing game...
        //PlayersNames[0] = participants[0].DisplayName;
        //PlayersNames[1] = participants[1].DisplayName;
        //PlayersNames[2] = participants[2].DisplayName;
        //GenerateBoard();
        //bool reliability = true;
        //string data = "Instantiate:0:1:2";
        //byte[] bytedata = System.Text.ASCIIEncoding.Default.GetBytes(data);
        //PlayGamesPlatform.Instance.RealTime.SendMessageToAll(reliability, bytedata);
    }
    else
    {
        Debug.Log("Room Connected FAIL");
        PlayGamesPlatform.Instance.RealTime.LeaveRoom();
        //Loading.text = "Error!";
        //Back.SetActive(true);
        // Error!
        // ...show error message to user...
    }
}

public void OnInvitation(Invitation invitation, bool shouldAutoAccept)
{
    // handle the invitation
    if (shouldAutoAccept)
    {
        PlayGamesPlatform.Instance.RealTime.AcceptInvitation(invitation.InvitationId, this);
    }
    else
    {
        // do some other stuff.
    }
}

public void OnRoomSetupProgress(float progress)
{
    Debug.Log("Room Progress Waithing players");
    List<Participant> participants = PlayGamesPlatform.Instance.RealTime.GetConnectedParticipants();
    // show the default waiting room.
    if (participants.Count != 3)
    {
        PlayGamesPlatform.Instance.RealTime.ShowWaitingRoomUI();
        Debug.Log("Room Progress Waithing players");
    }
    else
    {
        Debug.Log("Room Progress 100");

        MainScene ms = new MainScene();
        ms.MoveToGame();
        PlayersNames[0] = participants[0].DisplayName;
        PlayersNames[1] = participants[1].DisplayName;
        PlayersNames[2] = participants[2].DisplayName;
    }
}

```

# Answer
> -1 votes
Okay, just need upload apk on the google play console

---
Tags: unity, c#, google-play-services
---