# Question
Title: how to move a char value "down" in a two dimensional array?
I managed to move it up, left and right but when i try to move it down it goes to the last Y position in the array instead of the Y position below it.

the code i wrote to move it up, left and to the right works!

the name of the array is "mapa\[h\]\[b\]", the "help" variable has the same value as the values i want to move but as an int instead of a char, the variable "i" is for the Y position and the variable "j" is for the X position

```
//movement upwards
         for (i=0;i<h;i++){
            for (j=0;j<b;j++){
                if(mapa[i][j]==help){
                    aux=mapa[i-1][j];
                    mapa[i-1][j]=mapa[i][j];
                    mapa[i][j]=aux;
                    break;
                    break;
                }
        }
        }
//movement to the left
        for (i=0;i<h;i++){
            for (j=0;j<b;j++){
                if(mapa[i][j]==help){
                    aux=mapa[i][j-1];
                    mapa[i][j-1]=mapa[i][j];
                    mapa[i][j]=aux;
                    break;
                    break;
                }
        }
        }
//movement to the right
        for (i=0;i<h;i++){
            for (j=0;j<b;j++){
                if(mapa[i][j]==help){
                    aux=mapa[i][j+1];
                    mapa[i][j+1]=mapa[i][j];
                    mapa[i][j]=aux;
                    break;
                    break;
                }
        }
        }

```

And as I said before, this part works, what I did its just to exchange the value I want to move with the one on the position I want to move it to, to locate the value I want to move I use the for() cycles to "scan" the array and the if() is meant to find it, when the if() finds the wanted value I add one to the Y or X position, but when i try to move it down using the same logic

```
for (i=0;i<h;i++){
        for (j=0;j<b;j++){
            if(mapa[i][j]==help){
                aux=mapa[i+1][j];
                mapa[i+1][j]=mapa[i][j];
                mapa[i][j]=aux;
                break;
                break;
            }
    }
    }

```

it just moves to the bottom of the array regardles of its current location on the Y position

# Answer
Putting two break statements in the inner for-loop doesn't break from the outer loop.

The 2nd break is ignored so the object gets moved all the way down as the outer loop keeps going.

You need to either use a goto or force the loop to exit by forcing the iteration variable to the end condition:

```
for (i=0;i<h-1;i++){
    for (j=0;j<b;j++){
            if(mapa[i][j]==help){
                aux=mapa[i+1][j];
                mapa[i+1][j]=mapa[i][j];
                mapa[i][j]=aux;
                goto exit_loops;
            }
    }
}
exit_loops:

```

Or:

```
for (i=0;i<h-1;i++){
    for (j=0;j<b;j++){
            if(mapa[i][j]==help){
                aux=mapa[i+1][j];
                mapa[i+1][j]=mapa[i][j];
                mapa[i][j]=aux;
                i=h; // force i to end the loop
                break;
            }
    }
}

```

Alternatively you can change your loop to be a single loop by treating the 2D array as a linear array:

```
for (i=0;i<((h-1)*b);i++){
    if(mapa[0][i]==help){
        aux=mapa[0][i+b];
        mapa[0][i+b]=mapa[0][i];
        mapa[0][i]=aux;
        break;
    }
}

```

Also don't forget to reduce your vertical loop by 1 (not the whole height) as you are swapping with one line further down: use (h-1) otherwise doing i+1 will overrun your array and trash memory.
> 1 votes

---
Tags: c++, 2d, movement
---


# Question
Title: Having trouble with btGeometryUtil::isPointInsidePlanes
I'm in the process of parsing a BSP file to create btConvexHullShape objects for each brush. I've seen a few examples of how to do this on Github and they all use the getVerticesFromPlaneEquations function. This function in turn uses isPointInsidePlanes. The problem I'm having is that isPointInsidePlanes returns false for every potentialVertex, leaving me with an empty verticesOut array.

I'm looking at the code for isPointInsidePlanes, and it seems like it is checking the vertex against ALL planes in the brush which I find confusing.

For example if the brush is a simple rectangular prism, you wouldn't expect the point that results from the intersection of 3 planes to be inside all 6 planes, right? Shouldn't it only be checked against the 3 planes that intersected to locate it?

Now this file hasn't changed in 9 years, so either I'm doing something very wrong or nobody uses this function. I'm going to assume I'm wrong for the time being.

**TL;DR:** Why does isPointInsidePlanes check the point against every plane equation and not just the 3 that intersect to create it? Should I not even be using the getVerticesFromPlaneEquations function and instead be using something else?

EDIT: Added link to code

Here is a link to the relevant source file: https://github.com/bulletphysics/bullet3/blob/master/src/LinearMath/btGeometryUtil.cpp

Specifically, on line 175, the planeEquations array is passed to isPointInsidePlanes which then compares the point against every plane in the array.

# Answer
> 1 votes
It turns out I had a fundamental misunderstanding of the purpose of the "isPointInsidePlanes" function. It is not checking whether the point lies *on* every plane. It is checking whether the point is *behind* every plane (since the normals of the planes point outwards) which ensures that the shape is convex.

---
Tags: physics-engine, bullet-physics, binary-space-partitioning, convex-hull
---


# Question
Title: How to prevent images from being resized in game maker?
This warning appeared in the compilation menu of my game.

The images were rescaled in half. I understand that this happened because they had very large dimensions.

It turns out that the images, although they have a large size (pixels), are very light, because they are composed for the most part by simple traces in addition to having the transparent background.

Below, one of the images:

You see, it is very light.

It turns out that in the game it stops being clear.

How do I solve my problem? Using smaller images is out of the question.

# Answer
When your image is bigger than texture pages size then GMS resizes the image.

Don't see how small your PNGs are. They will be unpacked when loaded into memory. Each pixel will eat 4 bytes (32 bits). So 2446×1008 requires more than 9 MB. Moreover, some videocards can work only with textures which size is a power of two. It means that 2446×1008 actually will be 4096×1024 (empty area will be added). And Texture pages is thing which allows to optimize it (but for very big images it may work inefficient in some cases).

Change texture pages size from 2048\*2048 (default value) to 4096\*4096. But keep in mind that then your game may not work on some “old” hardware. Also you can split your each big image into two smaller. Like 2446×1008 → 2048×1008 + 398×1008

But when I see your images I don't see any reason to do it as big images. It's very inefficient. I would prefer draw it using that small blocks.
> 0 votes

---
Tags: sprites, game-maker, image
---


# Question
Title: How can I add a gap between each Instantiated object?
This will instantiate the prefab 10 times at the same position. And I want to add equal gap between the objects.

The prefabs should be instantiate on the drawn circle. I want inside this:

if (moveInCircles) To move in circles all the new prefabs.

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

public class rotate : MonoBehaviour
{
    [Header("Spin")]
    public bool spin = true;
    public Vector3 Direction;
    [Range(0, 300)]
    public float speed = 10f;
    public bool randomSpeed = false;
    public bool randomDirection = false;
    [Range(0f, 100f)]
    public float timeDirChange;
    public Vector3 defaultDirection = new Vector3(1, 0, 0);

    [Space(5)]

    [Header("Move in circles")]
    public bool moveInCircles = false;
    public GameObject rotateAroundTarget;
    public Vector3 axis;//by which axis it will rotate. x,y or z.
    public float rotationSpeed; //or the speed of rotation.
    public float upperLimit, lowerLimit, delay;// upperLimit & lowerLimit: heighest & lowest height;
    [Range(5, 50)]
    public float radius = 5;
    private float height, prevHeight, time;//height:height it is trying to reach(randomly generated); prevHeight:stores last value of height;delay in radomness;

    private float nextRotationTime = 0f;
    private int counter = 0;

    public DrawCircle dc;
    public GameObject prefab;
    public int numOfObjects;
    public int gap = 3;

    // Use this for initialization
    void Start()
    {
        dc.xradius = radius;

        if (prefab != null)
        {
            for (int i = 0; i < numOfObjects; i++)
            {

                Instantiate(prefab);

                var v = Quaternion.AngleAxis(Time.time * speed, Vector3.up) * new Vector3(radius, 0, 0);
                //prefab.transform.position = rotateAroundTarget.transform.position + v;
                prefab.transform.position = rotateAroundTarget.transform.position + v + new Vector3(rotateAroundTarget.transform.position.x * gap,0, 0);
            }
        }
    }

    private void Update()
    {
        if (randomSpeed)
        {
            speed = UnityEngine.Random.Range(0, 300);
        }

        if (spin)
        {
            if (randomDirection == false)
            {
                nextRotationTime = 0;
                timeDirChange = 0;
                Direction = defaultDirection;
            }
            else
            {
                if (Time.time > nextRotationTime)
                {
                    nextRotationTime += timeDirChange;
                    RandomDirection();
                }
            }

            transform.Rotate(Direction, speed * Time.deltaTime);
        }
        else
        {
            timeDirChange = 0;
            randomDirection = false;
            randomSpeed = false;
        }

        if (moveInCircles)
        {
            var v = Quaternion.AngleAxis(Time.time * speed, Vector3.up) * new Vector3(radius, 0, 0);
            transform.position = rotateAroundTarget.transform.position + v;
        }

        dc.xradius = radius;
    }

    private void RandomDirection()
    {
        Direction = new Vector3(UnityEngine.Random.Range(-1, 1), UnityEngine.Random.Range(-1, 1), UnityEngine.Random.Range(-1, 1));
        while (Direction == new Vector3(0, 0, 0))
        {
            counter++;
            Direction = new Vector3(UnityEngine.Random.Range(-1, 1), UnityEngine.Random.Range(-1, 1), UnityEngine.Random.Range(-1, 1));

            if (counter == 2)
            {
                Direction = new Vector3(1, 0, 0);
                break;
            }
        }

        counter = 0;
    }
}

```

This is the script that I draw the circle:

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

[RequireComponent(typeof(LineRenderer))]
public class DrawCircle : MonoBehaviour
{
    [Range(0, 50)]
    public int segments = 50;
    [Range(0, 50)]
    public float xradius = 0;
    [Range(0, 50)]
    public float yradius = 0;
    LineRenderer line;
    public GameObject objectToDrawCircle;

    void Start()
    {
        line = objectToDrawCircle.GetComponent<LineRenderer>();
        line.positionCount = segments + 1;
        line.useWorldSpace = false;
        line.startWidth = 0.05f;
        line.endWidth = 0.05f;
        CreatePoints();
    }

    void Update()
    {
        if (xradius > 0)
        {
            yradius = xradius;
            CreatePoints();
        }
    }

    void CreatePoints()
    {
        float x;
        float y;
        float z;

        float angle = 20f;

        for (int i = 0; i < (segments + 1); i++)
        {
            x = Mathf.Sin(Mathf.Deg2Rad * angle) * xradius;
            z = Mathf.Cos(Mathf.Deg2Rad * angle) * yradius;

            line.SetPosition(i, new Vector3(x, 0, z));

            angle += (360f / segments + 1);
        }
    }
}

```

What I want is in the first script rotate in the Start to place prefabs on the drawn circle.

In the screenshot example. The circle I draw is in red and the prefabs are in green. I want to Instantiate the prefabs on the circle like the greens in the screenshot. But in equal gap between them.

# Answer
> 1 votes
create one empty gameobject in scene. create one prefab and save it in project folder. create one script and past below code in your script then attach this script to the empty object in unity editor.

```
public GameObject prefab;
int numOfObjects = 10;
// Use this for initialization
void Start ()
{
    if (prefab != null)
    {
        for (int i = 0; i < numOfObjects; i++)
        {
            Instantiate(prefab,new Vector3(0.0f,i+1,0.0f),Quaternion.identity);
        }
    }
    else
        Debug.Log("prefab not set in inspector");
}

```

after attaching the script reference the prefab in the script. then run the program.!

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


# Question
Title: What are the legal considerations with using spritesheets?
If you google for sprites sheets, you'll find a *lot* of sprites sheets. As far as I can remember, industrial patents (the terms may not be the right ones I'm sorry), after 20 years, fall into public domain. For music it's 100 years. How about sprites sheets?

I'd like to know if I can use some of them directly? If I spend a lot of time to take them, rework them as SVG and they will look modern but exactly the same as the original ones?

What is the general rule of thumb to follow to know if I can use a sprite sheet?

# Answer
> 3 votes
IANAL TINLA If you are talking about the technology known as sprite sheets: Such a technology and method is not patentable, as it is not novel to put images in rows or cells. You could easily do this yourself or use countless other softwares to do this without fear of legal issues.

If you are talking about the art that someone created that is a sprite sheet: **all art is copyrighted at its creation**, and unless you are given license to use said work, you would be **absolutely** infringing upon the lawful intellectual property owners rights.

As for "how long" such a copyright lasts, that depends on the owner of the copyright, the date of creation, and many other factors. For instance:

> "For works published after 1977, the copyright lasts for the life of the author plus 70 years. However, if the work is a work for hire (that is, the work is done in the course of employment or has been specifically commissioned) or is published anonymously or under a pseudonym, the copyright lasts between 95 and 120 years, depending on the date the work is published. All works published in the United States before 1923 are in the public domain. Works published after 1922, but before 1978 are protected for 95 years from the date of publication. If the work was created, but not published, before 1978, the copyright lasts for the life of the author plus 70 years. However, even if the author died over 70 years ago, the copyright in an unpublished work lasts until December 31, 2002. And if such a work is published before December 31, 2002, the copyright will last until December 31, 2047."

\[Excerpt from: https://fairuse.stanford.edu/overview/faqs/copyright-basics/#how\_long\_does\_a\_copyright\_last \]

In any case, if you want to use something that you didn't make (even to edit it slightly and make it better) you really should **ask the owner** of the ip for **written permission** to do so; not only to get their permission but to protect your butt from losing rights to use your creation that used their IP (a spit and a handshake: "yeah, go ahead" said in person or over the phone isn't enough... get an email or letter stating unarguably that you are allowed to use the ip in question).

---
Tags: legal, spritesheet, copyright
---


# Question
Title: How to associate a number to a button and get that number when the user clicks on the button?
I am creating buttons for each level through script as shown below

```
private void CreateLevelButtons()
{
    for (int i = 1; i <= no_of_levels; i++)
    {
        Button button = Instantiate(button_prefab);
        button.GetComponentInChildren<Text>().fontSize = 12;
        button.GetComponentInChildren<Text>().text = "Level " + i.ToString();
        button.transform.SetParent(content.transform, false);
        button.onClick.AddListener(() => OnClickLevelButton());
    }
}

```

In OnClickLevelButton() function I want to determine the level number of the button that was clicked. Is there a way to associate a number to a button so that i can access that number later when the user clicks on the button?

# Answer
Yes it is possible, but you have to take care of the **closure problem**. In order to avoid this, create a temporary variable like this:

```
private void CreateLevelButtons()
{
    for (int i = 1; i <= no_of_levels; i++)
    {
        int index = i ; // Create variable to avoid closure problem
        Button button = Instantiate(button_prefab);
        button.GetComponentInChildren<Text>().fontSize = 12;
        button.GetComponentInChildren<Text>().text = "Level " + i.ToString();
        button.transform.SetParent(content.transform, false);
        button.onClick.AddListener(() => OnClickLevelButton( index ));
    }
}

void OnClickLevelButton( int i )
{
    Debug.Log("Button #" + i + " has been clicked!");
}

```
> 1 votes

---
Tags: unity
---


title: How to remove bricks on collision?

text:
# Question
Title: How to remove bricks on collision?
I am on my last stage of creating a simple breakout game in Java using BlueJ. I have added multiple rows of bricks using an `ArrayList`. However now the task is to remove the bricks upon being hit by the ball. I currently have a for loop in my Model class, but it seems to pass through the first few rows and then only collide with bricks around the middle. Here is the loop:

```
for ( int i = 0; i <= 60; i++ ){
    GameObj brick1 = bricks.get(i);

    if ( brick1.hitBy(ball) ){
        bricks.remove(i);
        ball.changeDirectionY();
        addToScore(50);

    }
}

```

When i change the i \<= 60 it seems to start to hit the bricks within the lower rows but still it isn't working properly. Here is the full code for the class:

```
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Observable;

/**
* Model of the game of breakout
* @author Mike Smith University of Brighton
*/

public class Model extends Observable
{
// Boarder
private static final int B              = 6;  // Border offset
private static final int M              = 40; // Menu offset

// Size of things
private static final float BALL_SIZE    = 18; // Ball side
private static final int BRICK_WIDTH  = 48; // Brick size
private static final int BRICK_HEIGHT = 20;
private static final float BAT_WIDTH  = 50;
private static final float BAT_HEIGHT = 30;

private static final int BAT_MOVE       = 5; // Distance to move bat

// Scores
private static final int HIT_BRICK      = 50;  // Score
private static final int HIT_BOTTOM     = -200;// Score

private GameObj ball;          // The ball
private ArrayList<GameObj> bricks;  // The bricks
private GameObj bat;           // The bat

private boolean runGame = true; // Game running
private boolean fast = false;   // Sleep in run loop

private int score = 0;

private final int W ;       // Width of area
private final float H;         // Height of area

private static final int BRICK_SEP = 4;
private static final int BRICK_Y_OFFSET = 100;
private static final int BRICK_X_OFFSET = 42;
private static final int NBRICKS_PER_ROW = 10;
private static final int NBRICK_ROWS = 2;
// Height of area

public Model( int width, int height )
{
    this.W = width; this.H = height;
}

/**
 * Create in the model the objects that form the game
 */

public void createGameObjects()
{
    synchronized( Model.class )
    {
        ball   = new GameObj(W/2, H/2, BALL_SIZE, BALL_SIZE, Colour.RED);
        bat    = new GameObj(W/2, H - BAT_HEIGHT*1.5f, BAT_WIDTH*3,
            BAT_HEIGHT/4, Colour.WHITE);
        bricks = new ArrayList<>();
        // *[1]******************************************************[1]*
        // * Fill in code to place the bricks on the board              *
        // **************************************************************/

        // pink first 2 rows
        for (int i = 0; i < NBRICK_ROWS; i++){
            int y = BRICK_Y_OFFSET + (i * (BRICK_HEIGHT + BRICK_SEP));

            for (int j = 0; j < NBRICKS_PER_ROW; j++){
                int x = (BRICK_X_OFFSET) + (j * (BRICK_WIDTH + BRICK_SEP));
                bricks.add(new GameObj (x, y, BRICK_WIDTH, BRICK_HEIGHT, Colour.PINK));
            }
        }
        // blue second 2 rows // math = 4 + 20 * 2 = 48
        for (int i = 0; i < NBRICK_ROWS; i++){
            int y = (BRICK_Y_OFFSET+48) + (i * (BRICK_HEIGHT + BRICK_SEP));

            for (int j = 0; j < NBRICKS_PER_ROW; j++){
                int x = (BRICK_X_OFFSET) + (j * (BRICK_WIDTH + BRICK_SEP));
                bricks.add(new GameObj (x, y, BRICK_WIDTH, BRICK_HEIGHT, Colour.BLUE) );
            }
        }
        // orange third 2 rows // math = 48 + 48 = 96
        for (int i = 0; i < NBRICK_ROWS; i++){
            int y = (BRICK_Y_OFFSET+96) + (i * (BRICK_HEIGHT + BRICK_SEP));

            for (int j = 0; j < NBRICKS_PER_ROW; j++){
                int x = (BRICK_X_OFFSET) + (j * (BRICK_WIDTH + BRICK_SEP));
                bricks.add(new GameObj (x, y, BRICK_WIDTH, BRICK_HEIGHT, Colour.GREEN) );
            }
        }
        // green fourth 2 rows // math = 96 + 48 = 144
        for (int i = 0; i < NBRICK_ROWS; i++){
            int y = (BRICK_Y_OFFSET+144) + (i * (BRICK_HEIGHT + BRICK_SEP));

            for (int j = 0; j < NBRICKS_PER_ROW; j++){
                int x = (BRICK_X_OFFSET) + (j * (BRICK_WIDTH + BRICK_SEP));
                bricks.add(new GameObj (x, y, BRICK_WIDTH, BRICK_HEIGHT, Colour.ORANGE) );
            }
        }
        // cyan fith 2 rows // math = 144 + 48 = 192
        for (int i = 0; i < NBRICK_ROWS; i++){
        int y = (BRICK_Y_OFFSET+192) + (i * (BRICK_HEIGHT + BRICK_SEP));

        for (int j = 0; j < NBRICKS_PER_ROW; j++){
        int x = (BRICK_X_OFFSET) + (j * (BRICK_WIDTH + BRICK_SEP));
        bricks.add(new GameObj (x, y, BRICK_WIDTH, BRICK_HEIGHT, Colour.CYAN ));
        }
        }
        //magenta sixth 2 rows // math = 192 + 48
        for (int i = 0; i < NBRICK_ROWS; i++){
        int y = (BRICK_Y_OFFSET+240) + (i * (BRICK_HEIGHT + BRICK_SEP));

        for (int j = 0; j < NBRICKS_PER_ROW; j++){
        int x = (BRICK_X_OFFSET) + (j * (BRICK_WIDTH + BRICK_SEP));
        bricks.add(new GameObj (x, y, BRICK_WIDTH, BRICK_HEIGHT, Colour.MAGENTA ));
        }
        }

        //yellow seventh 2 rows // math = 240 + 48
         for (int i = 0; i < NBRICK_ROWS; i++){
        int y = (BRICK_Y_OFFSET+288) + (i * (BRICK_HEIGHT + BRICK_SEP));

        for (int j = 0; j < NBRICKS_PER_ROW; j++){
        int x = (BRICK_X_OFFSET) + (j * (BRICK_WIDTH + BRICK_SEP));
        bricks.add(new GameObj (x, y, BRICK_WIDTH, BRICK_HEIGHT, Colour.YELLOW ));
        }
        }

        }

    }

private ActivePart active  = null;
/**
 * Start the continuous updates to the game
 */
public void startGame()
{
    synchronized ( Model.class )
    {
        stopGame();
        active = new ActivePart();
        Thread t = new Thread( active::runAsSeparateThread );
        t.setDaemon(true);   // So may die when program exits
        t.start();
    }
}

/**
 * Stop the continuous updates to the game
 * Will freeze the game, and let the thread die.
 */
public void stopGame()
{
    synchronized ( Model.class )
    {
        if ( active != null ) { active.stop(); active = null; }
    }
}

public GameObj getBat()             { return bat; }

public GameObj getBall()            { return ball; }

public ArrayList<GameObj> getBricks()    { return bricks; }

/**
 * Add to score n units
 * @param n units to add to score
 */
protected void addToScore(int n)    { score += n; }

public int getScore()               { return score; }

/**
 * Set speed of ball to be fast (true/ false)
 * @param fast Set to true if require fast moving ball
 */
public void setFast(boolean fast)
{
    this.fast = fast;
}

/**
 * Move the bat. (-1) is left or (+1) is right
 * @param direction - The direction to move
 */
public void moveBat( int direction )
{
    // *[2]******************************************************[2]*
    // * Fill in code to prevent the bat being moved off the screen *
    // **************************************************************

    float dist = direction * BAT_MOVE;    // Actual distance to movefinal
    float MIN_X = 10;
    final float MAX_X = 440;

    if(dist > 0 && bat.getX() < MAX_X)
    {
        bat.moveX(dist);
    }
    else if ( dist < 0 && bat.getX() > MIN_X)
    {
        bat.moveX(dist);
    }

    Debug.trace( "Model: Move bat = %6.2f", dist );

}

/**
 * This method is run in a separate thread
 * Consequence: Potential concurrent access to shared variables in the class
 */
class ActivePart
{
    private boolean runGame = true;

    public void stop()
    {
        runGame = false;
    }

    public void runAsSeparateThread()
    {
        final float S = 3; // Units to move (Speed)
        try
        {
            synchronized ( Model.class ) // Make thread safe
            {
                GameObj       ball   = getBall();     // Ball in game
                GameObj       bat    = getBat();      // Bat
                ArrayList<GameObj> bricks = getBricks();   // Bricks
            }

            while (runGame)
            {
                synchronized ( Model.class ) // Make thread safe
                {
                    float x = ball.getX();  // Current x,y position
                    float y = ball.getY();
                    // Deal with possible edge of board hit
                    if (x >= W - B - BALL_SIZE)  ball.changeDirectionX();
                    if (x <= 0 + B            )  ball.changeDirectionX();
                    if (y >= H - B - BALL_SIZE)  // Bottom
                    {
                        ball.changeDirectionY(); addToScore( HIT_BOTTOM );
                    }
                    if (y <= 0 + M            )  ball.changeDirectionY();

                    // As only a hit on the bat/ball is detected it is
                    //  assumed to be on the top or bottom of the object.
                    // A hit on the left or right of the object
                    //  has an interesting affect

                    boolean hit = false;
                    // *[3]******************************************************[3]*
                    // * Fill in code to check if a visible brick has been hit      *
                    // *      The ball has no effect on an invisible brick          *
                    // **************************************************************

                    /* if( // ball Y pos < brick Y pos = collision )
                    {
                    brick = null;
                    }
                    for ( int i = 0; i <= 60; i++ ){
                    GameObj brick1 = bricks.get(i);

                    if ( y <= brick1.getY() - (BRICK_HEIGHT/2)){

                    bricks.set(i, null); // The brick in the position of i when the ball collides, will be null

                    hit = true;
                    Debug.trace("BreakOut");

                    }
                    List<GameObj> toRemove = new ArrayList<GameObj>();
                    for(GameObj a: bricks){
                    if(a.getY() <= brick1.getY() - (BRICK_HEIGHT/2)){
                    toRemove.add(a);
                    }
                    }
                    bricks.removeAll(toRemove); */

                    for ( int i = 0; i <= 60; i++ ){
                        GameObj brick1 = bricks.get(i);

                        if ( brick1.hitBy(ball) ){
                            bricks.remove(i);
                            //hit = true;
                            ball.changeDirectionY();

                            //ball.changeDirectionX();
                            addToScore(50);

                        }
                    }

                    if (hit)
                        ball.changeDirectionY();

                    if ( ball.hitBy(bat) )
                        ball.changeDirectionY();
                }
                modelChanged();      // Model changed refresh screen
                Thread.sleep( fast ? 2 : 20 );
                ball.moveX(S);  ball.moveY(S);
            }
        } catch (Exception e)
        {
            Debug.error("Model.runAsSeparateThread - Error\n%s",
                e.getMessage() );
        }
    }
}

/**
 * Model has changed so notify observers so that they
 *  can redraw the current state of the game
 */
public void modelChanged()
{
    setChanged(); notifyObservers();
}

}

```

Any help would be appreciated.

# Answer
> 1 votes
You need to loop through *all* of the bricks, not just the first 60. You also should be careful about remove items from a container while iterating over it. I use the "remove list" idiom myself a lot. So you're code should look something like the following (pseudocode):

```
ArrayList removeList = new ArrayList()
for (int i = 0; i < bricks.length(); i++)
{
    GameObj brick = bricks[i]
    if (brick.hitBy(ball))
    {
        removeList.add(brick)
    }
}

for (int i = 0; i < removeList.length(); i++)
{
    GameObj toRemove = removeList[i];
    bricks.remove(toRemove)

    // etc: bounce ball, add score, whatever.
}

```

---
Tags: java, collision-detection, physics, mathematics, swing
---


title: Camera follow while dragging object

text:
# Question
Title: Camera follow while dragging object
I am working on Bowlingball game. And when I move the ball left and right by touching or clicking the camera moves, but it also makes ball keeps moving in the same direction even though I just moved the mouse once in that direction.

The code for moving ball left and right by touching and dragging.

```
void TouchInput()
{
    if (Input.GetMouseButtonDown(0))
    {
        Ray ray = RayGenerator();
        RaycastHit hit;

        if (Physics.Raycast(ray.origin, ray.direction, out hit))
        {
            if (hit.transform.tag == "BowlingBall")
            {
                obj = hit.transform.gameObject;
                objPlane = new Plane(Camera.main.transform.forward * -1, obj.transform.position);

                Ray mRay = Camera.main.ScreenPointToRay(Input.mousePosition);
                float distance = 0.0f;
                objPlane.Raycast(mRay, out distance);
                ballTouchOffset = obj.transform.position - mRay.GetPoint(distance);
            }
        }
    } else if (Input.GetMouseButton(0) && obj)
    {
        Ray mRay = Camera.main.ScreenPointToRay(Input.mousePosition);
        float distance;
        if (objPlane.Raycast(mRay, out distance))
        {
            obj.transform.position = new Vector3(mRay.GetPoint(distance).x + ballTouchOffset.x, obj.transform.position.y, obj.transform.position.z);
        }
    } else if (Input.GetMouseButtonUp(0) & obj)
    {
        obj = null;
    }
}

```

And the code for camera follow

```
public Transform bowlingBall;
public Vector3 offset;

private void LateUpdate()
{
    transform.position = bowlingBall.position + offset;
}

```

# Answer
2 Problems:
First: Your question, too short, vague. I can't be sure what you are talking about.
Second: What you want (if i understood your question) is probably not what you imagined. When you drag an object the camera is a child of (constrained to) you will either get invinite movement until you let go, or only short pulses of movement(when you reset your cursor to 0 relative position all the time).
Imagine this: you have your object. you press on it and move your mouse. Then you get the relative vector between the mouse position where you started pressing at and the current position. This vector you multiply by speed (and Time.deltaTime and some screen independent paramters) to make a speed vector for the object to move at. the object moves.
**however** now your mouse is still on a relative position, thus resulting you to move every single frame.
I suggest you make clear what exactly you are trying to do.
> 0 votes

---
Tags: unity, camera, touch
---


title: SFML Keyboard Input

text:
# Question
Title: SFML Keyboard Input
I've implemented a basic Keyboard Input manager:

```
#include "UserIO.h"

UserIO::UserIO(GameManager* game, Physics* physics)
{
    this->game = game;
    this->physics = physics;
}

UserIO::~UserIO()
{
}

void UserIO::checkInput()
{
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
    {
        physics->moveLeft();
    }

    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
    {
        physics->moveRight();

    }

    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
    {
        physics->moveUp();
    }

    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
    {
        physics->moveDown();
    }

}

```

The physics manager increments the player's velocity as follows:

```
void Physics::moveRight()
{
    //ball->setVelX(ball->getVelx()+0.005f);
    ball->setX(ball->getVelx() + 0.001);

}

void Physics::moveUp()
{
    ball->setVelY(ball->getVely() + 0.001f);
}

void Physics::moveLeft()
{
    ball->setVelX(ball->getVelx() - 0.001f);
}

void Physics::moveDown()
{
    ball->setVelY(ball->getVely() - 0.001f);
}

void Physics::updatePlayerPos()
{
    //dampen velocity
    ball->setVelX(ball->getVelx() * dampen);
    ball->setVelY(ball->getVely() * dampen);

    ball->setX(ball->getX() + ball->getVelx());
    ball->setY(ball->getY() + ball->getVely());
}

```

And my main loop:

```
while (window->isOpen())
    {

        window->clear();
        user->checkInput();
        physics->tick();
        render->draw();

    }

```

The idea is for the player object (circle) to accelerate as one of the keys is pressed. The "tick" method calls "updatePlayerPos" to calculate displacement.

A "dampen" variable ensures the ball decelerates while no keys are pressed.

When running the program, SFML seems somewhat receptive to keyboard strokes, however the motion of the ball is completely erratic: while a key is pressed, the ball will remain stationary for a while, and then zoom off. I've tried a different combination of velocity values and nothing improves. I also tried removing the acceleration aspect altogether, and having the ball's displacement proportional to the length of time the key is pressed (e.g. if "right key" is pressed, add 0.1 to x). Sadly no change.

I'm now starting to think the issue lies with the game loop and/or SFML, as opposed to the physics. Is it possible that keystrokes are being missed? Would a fixed timestep help the situation?

# Answer
What exactly do you mean by "zoom off"?
If you mean disappear then either way I suggest trying to log those values (printf / cout \>\>) to a console so you can see whether its the speed or the position.
Basically if the math is correct. You might also want to see what happens if you set the acceleration to 0 or read out when a button press occurs
> -1 votes

---
Tags: c++, sfml
---


# Question
Title: NullReferenceException Error For Respawning
I am making an infinite runner game, and I am having issues with killing and respawning the player. I have a coroutine setup on the GameMaster objec which is the respawn and on the player I have a method that calls that coroutine. But when ever the player hits an enemy I get a Null Reference Exception and I am not sure why this is happining.

Here is the entire error

NullReferenceException: Object reference not set to an instance of an object Player.OnCollisionEnter2D (UnityEngine.Collision2D col) (at Assets/Script/Player.cs:32)

Here is the line that when I double click on the error it goes to. This line is on the player.

```
StartCoroutine(GetComponent<GameMaster>().RespawnPlayer());

```

This is the method that the above line is in. This method is on the player.

```
void OnCollisionEnter2D(Collision2D col)
{
    if (col.gameObject.tag == "Enemy")
    {
        Debug.Log("HIT");
        Destroy(col.gameObject);
        StartCoroutine(GetComponent<GameMaster>().RespawnPlayer());
    }
}

```

Here is the coroutine that the above method is trying to call. This method is on the GameMaster GameObject and this object never gets destoryed or setActive false.

```
public IEnumerator RespawnPlayer()
{
    player.GetComponent<SpriteRenderer>().enabled = false;
    player.GetComponent<BoxCollider2D>().enabled = false;
    player.GetComponent<movemnt>().enabled = false;
    yield return new WaitForSeconds(respawnDelay);
    adMenu.SetActive(true);
}

```

If anybody can give any suggestions that would be great!

# Answer
First of all instead of using such tag comparison use

```
gameObject.CompareTag("Enenmy")

```

This is just an input to avoid GC.

## Answer

Use Singleton for your GameMaster object add these lines of code

```
Public static GameMaster Instance;
void Awake()
{
    Instance = this;
}

```

Then in your script jus use

```
StartCoroutine(GameMaster.Instance.RespawnPlayer());

```

Using this your GameMaster will always be available for you no need to call GetComponent or FindObjectOfType to find it you just need to call GameMaster.Instance.YourMethodOrVariable. Hope this will help
> 0 votes

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


# Question
Title: How make Unity wait before consuming next item in a list?
I have a class like so:

```
public class SomeObject : MonoBehaviour
{
    protected List<EdibleStuff> SomeItemsToConsume;

    private void StartConsuming()
    {
        this.SomeItemsToConsume
            .ForEach(item =>
            {
                StartCoroutine(Consume(item));
            });
    }

    private IEnumerator Consume(EdibleStuff edibleStuff)
    {
        yield return new WaitForSecondsRealtime(2);

        // Check whether edibleStuff is still fresh after 2 seconds
        // Figure out how to consume it -- e.g. by cooking, eating raw, whatever
    }
}

```

Before `SomeObject` consumes the next item in the `SomeItemsToConsume` list, I would like it to wait **another** short period of time, say, **another** 2 seconds.

I have tried these approches:

1. I added another `yield return new WaitForSecondsRealtime(2);` statement at the end of the `Consume(EdibleStuff edibleStuff)` method, but that did not work.
2. I added another co-routine, which simply contains the statement `yield return new WaitForSecondsRealtime(2);` in its definition, at the end of the `ForEach` loop, but that did not work either.

How can I achieve the effect I want?

# Answer
You could put the **ForEach** inside the coroutine:

```
public class SomeObject : MonoBehaviour
{
    protected List<EdibleStuff> SomeItemsToConsume;

    private IEnumerator Consume()
    {
        this.SomeItemsToConsume
        .ForEach(item =>
        {
            WaitForSecondsRealtime wait = new WaitForSecondsRealtime(2);

            /// Process your item...

            yield return wait;
        });
    }
}

```

Since what it was done in your **StartConsuming** method was that in your loop a 'n' number of coroutines (being 'n' the count of your list) were being started at the same frame. Having it inside a coroutine makes sure that the List moves to the next element once the WaitForSecondsRealTime's **keepWaiting** property returns true, which is not on the same frame (even if the time passed were 0).

Hope it helps.
> 3 votes

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


# Question
Title: Loading .PNG file and using it for UnityEngine.UI.Image
Have an Unity UI Image.

I want to load a .PNG file that is in my persistent data path and use it as the sprite source for the UI Image. Code:

```
    byte[] bytes = File.ReadAllBytes(Application.persistentDataPath + "/sprite.png");
    Texture2D texture = new Texture2D(width, height);
    texture.filterMode = FilterMode.Trilinear;
    texture.LoadImage(bytes);
    Sprite sprite = Sprite.Create(texture, new Rect(0,0,width, height), new Vector2(0.5f,0.0f), 1.0f);

    myObject.GetComponent<UnityEngine.UI.Image> ().sprite = sprite;

```

This almost works. **Only a portion of the image is displayed**.

The initial guess would be that I didn't load the image properly. However, if you use a `SpriteRenderer` instead of `UnityEngine.UI.Image` like

```
    myObject.GetComponent<SpriteRenderer>().sprite = sprite;

```

The image is displayed in full. So this seems to be a problem with `UnityEngine.UI.Image` specifically...

... However, if you drag an image from the editor into the `Sprite Source` property of `UnityEngine.UI.Image`, then such image is displayed in full - then suggesting that there is something wrong with the way I load my image bytes.

What should I do?

**Edit**: If you set the image type to `Tiled`, you can see that it tiles with the full image... So apparently the UI Image component DOES have all the image data but for some reason it won't render all of it.

# Answer
I was experiencing this same issue where not all of the image was displaying.

I solved it by setting mipmap to false (last parameter):

```
Texture2D texture = new Texture2D(900, 900, TextureFormat.RGB24, false);

```

My image then displayed as per the source PNG file.
> 7 votes

# Answer
make sure that tye Image of your myObject is child of Canvas. I am guessing that you create the image on the fly or parent it to the myObject instead of Canvas.
> 0 votes

# Answer
If you load files with WWW, it creates the texture for you. You can use WWW to load files from disk. The downside is that you need to wait for WWW to complete so a coroutine is required (not necessarily bad since it might prevent frame stalls when loading lots of images).

```
static WWW LoadFileFromDisk(string filepath)
{
    Uri uri = new Uri(filepath);
    string converted = uri.AbsoluteUri;
    return new WWW(converted);
}

IEnumerator LoadScreenshot(string file_path)
{
    var www = LoadFileFromDisk(file_path);
    yield return www;

    if (!string.IsNullOrEmpty(www.error))
    {
        Debug.LogError("Failed to fetch screenshot image: "+ www.error, this);
    }
    else
    {
        m_Screenshot.sprite = Sprite.Create(www.textureNonReadable,
                new Rect(0, 0, www.textureNonReadable.width, www.textureNonReadable.height),
                new Vector2(0, 0));
    }
}

```
> 0 votes

---
Tags: unity
---


# Question
Title: How to target specific material with Unity VideoPlayer?
I've modeled the following tv-monitor:

This monitor has two materials. The "frame" that makes up the monitor, called `MonitorFrameMaterial` and the black screen material, called `MonitorScreenMaterial`.

I've added the `Video Player` to the monitor and would like to play a video "on the screen material". Here's a screenshot of the inspector:

**I've already searched the web for some time to find an answer, but I can't seem to find a way to play the video on the screen. Whenever I add a video now, it actually targets the monitor-frame (probably because it's the first material?).**

Is there any way to change this, and if yes, how? Thanks!

# Answer
First of all create a RenderTexture in your project with the width and height matching your VideoClip for best performance. Change RenderMode from MaterialOverride to RenderTexture Set the RenderTexture you've created as TargetTexture of your VideoPlayer component and set it also Albedo Property of your material
> 2 votes

---
Tags: unity, materials, video
---


# Question
Title: How to make UI Button to rotate an gameobject?
I'm trying to make a button to make a gameobject rotate and stay rotating in its own axis (Y) but I cannot make it work...

As far as I know it's very simple:

1. Create an empty gameobject (or whatever you want)
2. Make a script and attach it to the gameobject
3. Create `public` methods
4. Link the gameobject with the script attached to the button `onClick` event
5. Click the button and test the script

My problem is that I don't know how I'm wrong here are the scripts of my project

This first script is my attempt using keys, and it works like charm

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

public class TurntableRotation : MonoBehaviour
{
    public GameObject turntable;
    public float turnSpeed;
    public bool canRotate = false;

    void Start ()
    {
    }

    void Update ()
    {
        StartTurntableRotation();

        StopTurntableRotation();
    }

    public void StartTurntableRotation()
    {
        if (Input.GetKey(KeyCode.I))
            {
                canRotate = true;
            }

            if (canRotate)
            {
                turntable.transform.Rotate(Vector3.up * turnSpeed * Time.deltaTime);
            }
    }

    public void StopTurntableRotation()
    {
        if (Input.GetKey(KeyCode.P))
        {
            canRotate = false;
        }

        if (!canRotate)
        {
            turntable.transform.Rotate(0,0,0);
        }
    }
}

```

This second script is my work in progress

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

public class TurntableUIBtns : MonoBehaviour
{
    public GameObject turntable;
    public float turnSpeed;

        //This is my public method used by the button
    public void StartTurntableBtn()
    {

                //This is my attempt to write the code for the object to rotate
        turntable.transform.Rotate(Vector3.up * turnSpeed * Time.deltaTime);
    }
}

```

As far as my knowledge goes, it is supposed to work, but I have to click every time to rotate my object, my goal is to click the button and make the object rotate and stay rotating

# Answer
> 2 votes
```
bool canRotate = false;
void Update()
{
    if(canRotate)
        turntable.transform.Rotate(Vector3.up * turnSpeed * Time.deltaTime);
}
//Your button Method
public void StartRotation()
{
    canRotate = !canRotate;
}

```

# Answer
> 0 votes
That’s because you need to use the Rotate function in Update, just like you do in your first script. You can simply use a bool again.

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


title: UENUM definition in header file

text:
# Question
Title: UENUM definition in header file
I am trying to define a simple enumeration in a header file as per the example published here. My header file consists of the following:

```
#pragma once

#include "CoreMinimal.h"

UENUM()
enum class MyEnum : int32
{
    MyField1,
    MyField2,
    MyField3
};

```

If I remove `UENUM()`, the compiler doesn't complain; however, when I add it, I get multiple errors.

* expected a ';'
* expected a '{'
* identifier "MyField1" is undefined
* identifier "MyField2" is undefined
* identifier "MyField3" is undefined

This all seems odd considering I'm doing exactly what the article says to do and other websites suggest doing the same thing.

Here's what it looks like in my editor:

**What I've tried**

* Changing `enum class` to simply `enum`.
* Not explicitly specifying an underlying type.
* Defining the enum elsewhere (for instance, in one of my classes; but when you add `UENUM()` there, it tells you you can't define it there).

I am new to both C++ and UE4 so it could be silly or trivial. Either way, I'm having a hard time understanding why something so simple won't compile.

# Answer
You would expect these errors if the macro `UENUM` is not defined, which means the compiler tries to interpret `UENUM() enum class` as a function definition.

I'm not familiar with the UDK API, but from browsing some examples it looks like the `UENUM` macro is defined in 'UObject/ObjectMacros.h', so you should include that file as well after CoreMinimal.h
> 2 votes

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


# Question
Title: Unexpected Behavior - Calling method on MonoBehaviour before Start() is called
I'm implementing object-pooling, though that's not the issue, and a bit confused about the order of operations between Monobehaviours. In the `InitGame()` method of `MyGameManager`, I call `SpawnEnemy()` on the `EnemyManager` singleton. What I would *expect* to happen (but is not happening) is for the `Awake()` method in `EnemyManager` to be called, then the `EnemyManager`-\> `Start()` method, and then and only then, would `SpawnEnemy()` be called. What *actually* happens is that `EnemyManager` `Awake()` is called, then `MyGameManager` calls `SpawnEnemy()`, and when that's done, `EnemyManager`'s `Start()` method is called last.

The docs say,

> Start is called on the frame when a script is enabled just before any of the Update methods is called the first time.

I'm guessing that while my `EnemyManager` is Active, it is not Enabled, and thus it's `Start()` method is not called until after the call to `SpawnEnemy()`. I found it surprising that a method can be called on an object before `Start()` is called on that object.

I can work around this situation by simply including the line `gameObject.SetActive(false);` in my `EnemyManager`'s `Awake()` method, and thus the `SpawnEnemy()` method will find and spawn an object from the pool, but it would be helpful to have a deeper understanding of when `Start()` is actually called. I've read the docs and whatever I could find, but don't feel like I fully understand.

---

Here is the `Manager` Singleton designed to easily create `XxxxManager` classes:

```
using UnityEngine;

public class Manager<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T _sharedInstance = null;

    public static T sharedInstance
    {
        get
        {
            if (_sharedInstance == null)
            {
                _sharedInstance = Object.FindObjectOfType<T>();
                if (_sharedInstance == null)
                {
                    Debug.Log("Can't find " + typeof(T));
                }
            }
            return _sharedInstance;
        }
    }

    public virtual void Awake()
    {
        // ...
    }
 }

```

---

An `EnemyManager` class:

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

public class EnemyManager : Manager<EnemyManager>
{
    static private List<EnemyManager> enemyControllers;

    public EnemyManager SpawnEnemy(Vector3 location)
    {

        foreach (EnemyManager controller in enemyControllers)
        {
            if (controller.gameObject.activeSelf == false)
            {
                controller.gameObject.transform.position = location;

                // object available
                controller.gameObject.SetActive(true);
                return controller;
            }
        }

        Debug.Log("Not enough enemies available in pool.");
        return null;
    }

    public override void Awake()
    {
        if (enemyControllers == null)
        {
            enemyControllers = new List<EnemyManager>();
        }

        enemyControllers.Add(this);

        // If we SetActive(false) here, we DO get the desired behavior
        gameObject.SetActive(false); // <-----

        base.Awake();
    }

    protected void Start()
    {
        // wake up and disable self
        // If we SetActive(false) here, we do NOT get the desired behavior
        gameObject.SetActive(false);  // <-----
    }
}

```

---

And I'm using these classes in `MyGameManager`:

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

public class MyGameManager : Manager<MyGameManager> {

    private EnemyManager enemyManager;

    public override void Awake()
    {
        enemyManager = EnemyManager.sharedInstance;
        base.Awake();
    }

    private void Start()
    {
        InitGame();
    }

    void InitGame()
    {
        enemyManager.SpawnEnemy(new Vector3(0, 0, 0));
    }
}

```

# Answer
> Start is called on the frame when a script is enabled just before any of the Update methods is called the first time.

The key word here is "just" - Start is called when Unity is about to run a FixedUpdate or Update on the script that hasn't yet been Start()ed.

Since EnemyManager.SpawnEnemy() isn't called from inside EnemyManager's Update, there's no particular reason to expect EnemyManager's Start() to run first. MyGameManager's Start has as much right to run earlier, if that's what the engine decides to do (and it doesn't have to make the same decision during testing and in a built executable).

All you're guaranteed is that it's had Awake (and, if spawned in the enabled state, OnEnable) called, because this happens before the AddComponent / Instantiate methods return for dynamically-spawned instances, or before any Start methods for objects loaded with the scene.

As Draco18s mentions, when you have sensitive update orders, you can control the order in which scripts Start / Update under Edit =\> Project =\> Script Execution Order. Though generally it's better practice to have the object fully initialized and ready to use in Awake if you can, to avoid hard-to-diagnose update order bugs sneaking in later.
> 4 votes

---
Tags: unity
---


title: How can I Fade Paint over time?

text:
# Question
Title: How can I Fade Paint over time?
I want to fading my paint over time like this:

but currently It's gray! what Is the problem?

Code:

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

// Collider & Renderer Required
[RequireComponent(typeof(Renderer))]
[RequireComponent(typeof(Collider))]
public class Paint : MonoBehaviour {
    public Material PaintMat;

    private Texture mainTexture; // The texture used in the original material
    private RenderTexture renderTexture; // Work render texture (drawn here)

    // shader's propertyID
    private int mainTexturePropertyID;
    private int paintUVPropertyID;

    // Use this for initialization
    void Start()
    {

        // property id set
        mainTexturePropertyID = Shader.PropertyToID("_MainTex");
        paintUVPropertyID = Shader.PropertyToID("_PaintUV");

        // Get the main texture set for the material
        mainTexture = PaintMat.GetTexture(mainTexturePropertyID);

        // create a renderTexture
        renderTexture = new RenderTexture(mainTexture.width, mainTexture.height, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default);

        // Copy main texture to render texture
        Graphics.Blit(mainTexture, renderTexture);

        // set the main texture for the material with the render texture
        PaintMat.SetTexture(mainTexturePropertyID, renderTexture);
    }

    // I hope this is necessary
    void OnDestroy()
    {
        renderTexture.Release(); // render texture open
        PaintMat.SetTexture(mainTexturePropertyID, mainTexture); // Return to the original texture
    }

    void Update()
    {

        // Acquire the uv of the touched place
        if (Input.GetMouseButton(0))
        {
            var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hitInfo;
            if (Physics.Raycast(ray, out hitInfo))
            {
                // Put that
                PaintOnUV(hitInfo.textureCoord);
            }
        }else{
            PaintOnUV(new Vector2(1000,1000));//Just Update
        }
    }

    private void PaintOnUV(Vector2 uv)
    {
        // Create buffer
        var renderTextureBuffer = RenderTexture.GetTemporary(renderTexture.width, renderTexture.height);
        PaintMat.SetVector(paintUVPropertyID, uv);

        Graphics.Blit(renderTexture, renderTextureBuffer, PaintMat); //Copy the material rendered texture to buffer , You can not write directly
        Graphics.Blit(renderTextureBuffer, renderTexture); // Write back from buffer to render texture
        RenderTexture.ReleaseTemporary(renderTextureBuffer); // Release buffer
    }
}

```

Shader:

```
   Shader "Hidden/Paint"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _PaintUV("Hit UV Position", VECTOR) = (0, 0, 0, 0) // Position to  painting with brush
        _FadeTime("FadeTime",Float) = 50
    }
    SubShader
    {
Tags {"Queue"="Transparent" "IgnoreProjector"="true" "RenderType"="Transparent"}
ZWrite Off Blend SrcAlpha OneMinusSrcAlpha Cull Off

        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;
            }

            sampler2D _MainTex,_Temp;
            float4 _PaintUV;
            float _FadeTime;

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 temp = tex2D(_MainTex, i.uv);
                i.uv -= _PaintUV.xy;
                i.uv +=0.5;
                float paint = length(i.uv-0.5 );
                paint = step(paint,0.05);
                float mask = paint+temp;
                float percent = 1.0/500;//why Is gray? can't fade completely!
                percent = 1.0/1000;//not Fade!!
                mask-= percent;
                return  mask;
            }
            ENDCG
        }
    }
}

```

Also you can download and test this from my github.

# Answer
> 2 votes
`frag` is declared as returning a Vector (`float4`). What you are actually returning is a Scalar (`float`). This results in a Scalar-to-Vector conversion which is defined as:

> **Scalar-to-Vector**
>
> Such conversions are always valid. This cast works by **copying** the scalar to **fill** the vector.

(Emphasis mine).

This means that when your code returns `0.02` what it's actually returning is `(0.2, 0.2, 0.2, 0.2)`.

Or...gray.

---
Tags: unity, fragment-shader, rendertexture
---


# Question
Title: Name of this technique used in games such as Minecraft or the sims
In Minecraft, there are some blocks which are a little bit different than just cubes.

For example stairs or fences: these elements are "aware" of their surrounding blocks and render differently based on if they are an edge, in the center, etc.

Other building games such as the Sims use a similar technique in the house building mode: the "voxels" are the same 1x1 metres but the mesh itself is usually thinner (like walls, side walls, etc.).

My question is:

* What is the name of this technique?

**Reference image**

For the user perspective, there is only one "stairs" block. But when put next to each other, they behave differently.

# Answer
It's either called Marching cubes/squares (depends on how many axes you're working with), autotile or -fence.

The marching algorithms work on filled areas. You define whether the corners of the squares or cubes are inside or outside of an object and it automatically generates the mesh for you. Marching squates needs 16, marching cubes needs 256 different tiles, but many of them are repeating.

Autotile is usually strictly 2d (or 3d if you do it only in a single plane, like minecraft) and also works on fileld areas, but this time the algorithm checks the 8 sorrounding tiles and chooses the appropariate texture based on those. You need 48 different tiles for this.

Autofence only checks the sorrounding 4 tiles and chooses the correct texture. Redstone in minecraft works like this and it's also great for fences and walls.

The stairs in minecraft are a little bit different, as they have actual directions and they act based on that, so that algorithm is probably custom.
> 3 votes

# Answer
I'm not aware of any special name for this technique. Nothing I can think of calling it is returning any meaningful results.

I do know that when the texture is different (not the block shape) based on the surrounding blocks it got called "connected textures" (due to the first time that a mod did that in Minecraft it was *called* Connected Textures).

Internally what Minecraft calls things like fences and walls having a different shape is just the block's "extended state" where extra data gets used to render the block model.

For some blocks its encoded in the "actual state" (where the non-adjective "state" is the Block+Metadata combination), which handles states based on information encoded in the world (such as neighboring blocks or TileEntity data). Fences and walls do this to indicate what sides they're connected on and that can be queried server-side by other code (e.g. other blocks).

While for other blocks, data encoded in the "extended sate," such as the exact height of each corner of a liquid block, is *only* used for rendering as it only affects the displayed graphical representation. This allows blocks like water and lava to have a steadily decreasing height slope rather than stair-step like (as snow layers does).

Context Aware Model, maybe?
> 2 votes

---
Tags: voxels, minecraft-modding, terminology
---


title: Graphics API abstraction architecture

text:
# Question
Title: Graphics API abstraction architecture
I'm developing a 3D game engine in C# and I was just wondering what are the different ways I can approach designing a graphics API abstraction.

My original design was going to be something like this:

```
public interface IVertexBuffer : IDisposable
{
    void Bind();
}

#if DRIVER_TYPE_OPENGL_45

public sealed class OpenGLVertexBuffer : IVertexBuffer
{
    public void Bind()
    {
        // Bind buffer...
    }

    public void Dispose()
    {
        // Delete buffer...
    }
}

#endif

#if DRIVER_TYPE_OPENGL_ES30

public sealed class OpenGLESVertexBuffer : IVertexBuffer
{
    public void Bind()
    {
        // Bind buffer...
    }

    public void Dispose()
    {
        // Delete buffer...
    }
}

#endif

```

In C#, sadly pre-processors don't work the same way they do in C++, so I would have to compile two versions of my project, but that just seems hacky and I would much rather be able to switch between drivers types.

So, I had another idea to do something like this:

```
public interface IRenderDevice
{
    IVertexBuffer CreateVertexBuffer(float[] vertexData, int sizeInBytes);

    void DestroyVertexBuffer(IVertexBuffer vertexBuffer);
}

public sealed class OpenGLRenderDevice : IRenderDevice
{
    public IVertexBuffer CreateVertexBuffer(float[] vertexData, int sizeInBytes)
    {
        // Create vertex buffer
    }

    public void DestroyVertexBuffer(IVertexBuffer vertexBuffer)
    {
        // Destroy vertex buffer, or should I just call vertexBuffer.Dispose()?
    }
}

```

and then just use an enum to determine which render device to create, but I know this solution will quickly get out of hand when I begin to introduce other things like vertex arrays, index buffers, frame buffers, etc.

What other options do I have that will still maintain readable code and look native to C#?

# Answer
> 2 votes
Your second choice is somewhat better, but still requires development.

My advice would be to develop and inheritance tree of base type IRenderer, which defines the common API of any possible renderer object.

Secondly, define a static factory method, which has the pre-processor directives in the body of the method. When you call `CreateRenderer()`, the factory will return a reference to the renderer most appropriate to the platform, which will be hard coded according to the platform it was compiled for.

Functionally, for all practical purposes pre-processor directives work the same way as C++. They define how the code will be compiled, therefore if you have a bunch of platforms with pre-processor guards, then you will have to compile for each platform whether you code it in C# or C++. The only way to avoid that, would be to code for the Java Virtual Machine, which allows true platform agnostic code.

But your users would not thank you for that.

There is no way to write native code which will work on all platforms. It is simply not possible on a machine code level, as differing CPU's have different instruction sets, and may have differing endianness. An executable compiled for one platform will not work on another(best case), or crash it out completely (worst case).

On a related note. If true platform abstraction is a real concern to you, I would recommend moving away from C# altogether, and coding with C/C++, with the very compelling reason being, a C/C++ compiler exists for *all* platforms, past and present. The same cannot be said for C#, which at present, is only supported natively on windows, and only recently has the support extended to Linux/Mac. Console manufacturers (with the notable exception of Microsoft, with the XBox360) do not write compilers to support C#, as the vast majority of the games industry codes in C/C++. You will find support and information sorely lacking.

# Answer
> 1 votes
People have tried in the past to create such abstraction over opengl, they either just complicated the API until using the original was better, or abstracted too much so that a lot of operations that are a bit more advanced than what you had in mind when creating the abstraction became impossible.

For example a buffer in opengl can be used in a lot of different ways, holding vertex data, holding index data, holding uniform data (that may or may not be writable by the shader), holding texture data during upload/download. The same buffer can do all of those things one after the other. So binding a buffer to be strictly vertex data may be a mistake when a user wants to build vertex data in a compute shader.

---

You should also consider Vulkan and D3D and whether you want to provide abstractions for them as well. And if you will, will it be with the same user-facing API transparently.

---
Tags: opengl, rendering
---


# Question
Title: Converting between world coordinate systems
I have a mesh (verticies, indicies, normals).This mesh uses following world coordinate system:

* Forward: x
* Up: z
* Right: y

I am trying to convert it to a different coordinate system:

* Forward: z
* Up: y
* Right: -x

---

I swizzled verticies from xzy to zy-x and the geometry looks fine. But the same trick didn't work for normals. What I am missing? Should I use some kind of matrices?

Thank you for any help you can offer!

**EDIT** Red lines - normals vizualization

Here is a part of code that shows normals:

`GLKVector3 up = GLKVector3Make(0, 0, 1);
 GLKVector3 normalVec = GLKVector3Make(normalBuffer[i * stride + normalOffset],
 normalBuffer[i * stride + 1 + normalOffset],
 normalBuffer[i * stride + 2 + normalOffset]);
 GLKVector3 axis = GLKVector3Normalize(GLKVector3CrossProduct(up, normalVec));
 float dotProduct = GLKVector3DotProduct(up, normalVec);
 normalNode.rotation = SCNVector4Make(axis.x, axis.y, axis.z, acos(dotProduct));`

# Answer
Every time you interchange two axes, or negate an axis, you mirror space.

So to go from `xzy` to `zy-x` we perform:

1. Interchange `x` & `z`: `zxy` (mirrored)
2. Interchange `x` & `y`: `zyx` (unmirrored)
3. Negate `x`: `zy-x` (mirrored)

Because we used an odd number of flips, the mesh we have at the end is a mirror image of the one we started with. (That makes sense, since our starting coordinate system was left-handed but our destination is right-handed)

This mirroring means that any faces that had been wound counter-clockwise are now wound clockwise, or vice versa, flipping which side of the surface the renderer thinks is "outside" versus "inside." This can look like a problem with the normals because it affects how the faces get rendered.

To fix this, you can take a pass through all of your triangles and interchange two vertices to reverse the winding order, or flip the direction of backface culling in your render state.

As an aside, it looks like the conversion formula you'd want would look like this:

```
output.x = -input.y  // left = -right
output.y = input.z   // up = up
output.z = input.x   // forward = forward

```
> 1 votes

# Answer
Your mesh should not be in world space. It should be in "object space". It can then be scaled/translated/rotated into world space by homogeneous transform matrices on the GPU.

This includes changes in coordinate system (which, mathematically speaking is exactly the same thing, as a translation).

To do this, you create a 4x4 transform matrix, with the scale component being (-1,1,1), then multiply all other operations by this as a final step:

```
// right to left ordering
mat4 transform = Othercoordinate * Wscale * Wrotation * Wtranslation
vec4 FinalVertex = transform * ObjectVertex;

```

To transform your normals:

```
// right to left ordering
mat3 NormalTransform = transpose(inverse(mat3(transform)));
vec3 finalNormal = NormalTransform * ObjectNormal;

```

I strongly recommend you read this, and this, to better understand how homogeneous coordinate systems work, as it is integral to modern computer graphics.
> 1 votes

---
Tags: coordinates, normals
---


# Question
Title: Does Debug.LogAssert gets deleted in Unity once I build the game?
Does `Debug.LogAssert(expression)` gets deleted in Unity once I build the game?

I was not able to find it here. I feel like it should get deleted, but still I can not assure myself in it (no reliable source was found by me).

So, I would be grateful for the source provided which would assure me in it or point me out, that it is not the case.

# Answer
Yes, `Debug.Assert` gets removed from non-development builds by default. It's possible to change this setting - see the Unity documentation on BuildOptions.ForceEnableAssertions:

> BuildOptions.ForceEnableAssertions
>
> Include assertions in the build. By default, the assertions are only included in development builds.
> 0 votes

---
Tags: unity, debugging
---


title: Errors while instancing particles

text:
# Question
Title: Errors while instancing particles
Im creating a particle system of my own, and I have some draw issues with it. It's the first time I use instancing, so it's probable I have some concept errors.

First, I create three buffers: one for the quad that I will use in all particles, one for the transformations (which contains a planed 4x4 matrix for each particle) and one for the colors (four floats per particle):

```
/*Geometry buffer*/
 static const GLfloat  vertex_data[] = {
     -0.5f, -0.5f, 0.0f,
     0.5f, -0.5f, 0.0f,
     -0.5f, 0.5f, 0.0f,
     0.5f, 0.5f, 0.0f,
 };

 glGenBuffers(1, &geometry_buffer);
 glBindBuffer(GL_ARRAY_BUFFER, geometry_buffer);
 glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_data), vertex_data, GL_STATIC_DRAW);

/* Transform buffer */
glGenBuffers(1, &transform_buffer);
glBindBuffer(GL_ARRAY_BUFFER, transform_buffer);

// Initialize with empty (NULL) buffer : it will be updated later, each frame.
// 16 items, since we give a planed 4x4 matrix
glBufferData(GL_ARRAY_BUFFER, MAX_PARTICLES_PER_EMITTER * 16 * sizeof(GLfloat), NULL, GL_STREAM_DRAW);

/* Color buffer */
color_buffer;
glGenBuffers(1, &color_buffer);
glBindBuffer(GL_ARRAY_BUFFER, color_buffer);
// Initialize with empty (NULL) buffer : it will be updated later, each frame.
glBufferData(GL_ARRAY_BUFFER, MAX_PARTICLES_PER_EMITTER * 4 * sizeof(GLubyte), NULL, GL_STREAM_DRAW);

```

Each frame, I update the transform and color buffer:

```
    /*Transform*/
glBindBuffer(GL_ARRAY_BUFFER, transform_buffer);
glBufferData(GL_ARRAY_BUFFER, MAX_PARTICLES_PER_EMITTER * 16 * sizeof(GLfloat), NULL, GL_STREAM_DRAW);
glBufferSubData(GL_ARRAY_BUFFER, 0, Particles.size() * sizeof(GLfloat) * 16, particles_transforms_planed);

 /*Color*/
 glBindBuffer(GL_ARRAY_BUFFER, color_buffer);
 glBufferData(GL_ARRAY_BUFFER, MAX_PARTICLES_PER_EMITTER * 4 * sizeof(GLfloat), NULL, GL_STREAM_DRAW);
 glBufferSubData(GL_ARRAY_BUFFER, 0, Particles.size() * sizeof(GLfloat) * 4, particles_color_planed);

```

particles\_transform\_planed and particles\_color\_planed are both arrays of floats that contains the data of all particles

I use this shader of my own:

```
static const GLchar* ParticleVert[] =
{
"#version 330 core\n"
"layout(location = 0) in vec3 position;\n"
"layout(location = 1) in vec2 texCoord;\n"
"layout(location = 2) in mat4 transform;\n"
"layout(location = 3) in vec4 _color;\n"

"out vec4 ourColor;\n"
"out vec2 TexCoord;\n"

"uniform mat4 viewproj;\n"

"void main()\n"
"{\n"
"gl_Position = viewproj * transform *vec4(position.x,position.y,position.z,   1.0f) ;\n"
"ourColor = _color;\n"
"TexCoord = texCoord;\n"
"}\n"
};

static const GLchar* ParticleFrag[] =
{
"#version 330 core\n"
"in vec4 ourColor;\n"
"in vec2 TexCoord;\n"

"out vec4 color;\n"

"uniform sampler2D albedo;\n"

"void main()\n"
"{\n"

//Z-Buffer Line Shader
"color= ourColor * texture(albedo, TexCoord);\n"
"}\n"
};

```

Finally, I instantiate all particles like:

```
/*Vertex buffer*/
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, geometry_buffer);
glVertexAttribPointer(
    0, // attribute.
    3, // size
    GL_FLOAT, // type
    GL_FALSE, // normalized?
    0, // stride
    (void*)0 // array buffer offset
);

/*Position buffer*/
glEnableVertexAttribArray(2);
glBindBuffer(GL_ARRAY_BUFFER, transform_buffer);
glVertexAttribPointer(
    2, // attribute.
    4, // size
    GL_FLOAT, // type
    GL_FALSE, // normalized?
    sizeof(GLfloat) * 4 * 4, // stride
    (void*)0 // array buffer offset
);

/*Color buffer*/
glEnableVertexAttribArray(3);
glBindBuffer(GL_ARRAY_BUFFER, color_buffer);
glVertexAttribPointer(
    3, // attribute.
    4, // size
    GL_FLOAT, // type
    GL_FALSE, // normalized?
    0, // stride
    (void*)0 // array buffer offset
);

float data[MAX_PARTICLES_PER_EMITTER*4] = {};
glGetBufferSubData(GL_ARRAY_BUFFER, 0, MAX_PARTICLES_PER_EMITTER * 4 * sizeof(float), data);

//Pass the viewproj matrix to the shader
uint viewLoc = glGetUniformLocation(program_id, "viewproj");
glUniformMatrix4fv(viewLoc, 1, GL_TRUE, App->renderer3D->active_camera->frustum.ViewProjMatrix().ptr());

glVertexAttribDivisor(0, 0); // particles vertices : always reuse the same 4 vertices -> 0
glVertexAttribDivisor(2, 0); // transform : one per quad (16 floats per quad) -> 1
glVertexAttribDivisor(3, 1); // color : one per quad -> 1

//Draw all particles!
GLsizei particle_count = Particles.size();
glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, particle_count);

```

But, in screen, the particles are drawing like:

Strangely, when I change the color in the editor, the shape of the particle starts to change. I suspect that I'm using the VertexAttribDivisor in the wrong way, and im not sure if OpenGL is taking the transform buffer in chunks of 16. Anyone sees any error?
Thanks for the help.
PS: i'm not using yet the texture attribute, and i'm not sure if this could cause any issue;

EDIT: I found that the transformation matrix should be passed to the shader like:

```
 /*Position buffer*/
glBindBuffer(GL_ARRAY_BUFFER, transform_buffer);

glEnableVertexAttribArray(3);
glVertexAttribPointer(
    3, // attribute.
    4, // size
    GL_FLOAT, // type
    GL_FALSE, // normalized?
    sizeof(GLfloat) * 4 * 4, // stride
    (void*)0 // array buffer offset
);

glEnableVertexAttribArray(4);
glBindBuffer(GL_ARRAY_BUFFER, transform_buffer);
glVertexAttribPointer(
    4, // attribute.
    4, // size
    GL_FLOAT, // type
    GL_FALSE, // normalized?
    sizeof(GLfloat) * 4 * 4, // stride
    (void*)(sizeof(GLfloat) * 4) // array buffer offset
);

glEnableVertexAttribArray(5);
glVertexAttribPointer(
    5, // attribute.
    4, // size
    GL_FLOAT, // type
    GL_FALSE, // normalized?
    sizeof(GLfloat) * 4 * 4, // stride
    (void*)(sizeof(GLfloat) * 4*2) // array buffer offset
);
glEnableVertexAttribArray(6);
glBindBuffer(GL_ARRAY_BUFFER, transform_buffer);
glVertexAttribPointer(
    6, // attribute.
    4, // size
    GL_FLOAT, // type
    GL_FALSE, // normalized?
    sizeof(GLfloat) * 4 * 4, // stride
    (void*)(sizeof(GLfloat) *4* 3) // array buffer offset
);

glVertexAttribDivisor(3, 1);
glVertexAttribDivisor(4, 1);
glVertexAttribDivisor(5, 1);
glVertexAttribDivisor(6, 1);

```

After this changes, if the trasnformation matrix is equal to identity, the particle draws:

Which is correct. The problem: if i apply any transformation (in this case, a rotation to face the camera)...

The color doesn't affect anymore the shape, so i think the problems is now in the view matrices

# Answer
Ok, error solved. The thing was that the transform matrix had to be trasposed.
> 1 votes

---
Tags: c++, particles, instancing
---


# Question
Title: Strange LibGdx box2d body.ApplyLinearImpulse(); behavior
I have been working on this game NinjaThief and when I apply linear impulse to player body it just keeps on moving. Some of the functions are still unfinished so it looks a bit messy.

Here is my code:

NinjaThief class(main game class)

```
public class NinjaThief extends Game {

  public static final int V_WIDTH = 400;
  public static final int V_HEIGHT = 800;
  public SpriteBatch batch;

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

    setScreen(new PlayScreen(this));
  }

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

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

```

PlayScreen:

```
public class PlayScreen implements Screen {

 public static int PPM = 100;
 Player p;
 World world;
 TiledMap map;
 OrthographicCamera gamecam;
 TiledMapRenderer maprenderer;
 NinjaThief game;
 Box2DDebugRenderer b2dr;
 public PlayScreen(NinjaThief game) {
  varinit();
  this.game = game;
 }

 @Override
 public void show() {}

 public void varinit() {
  float width = Gdx.graphics.getWidth();
  float height = Gdx.graphics.getHeight();
  gamecam = new OrthographicCamera();
  gamecam.setToOrtho(false, width, height);

  gamecam.update();
  map = new TmxMapLoader().load("mapDebug.tmx");
  maprenderer = new OrthogonalTiledMapRenderer(map);

  world = new World(new Vector2(0, 0), true);
  b2dr = new Box2DDebugRenderer();
  p = new Player();
  p.init(world);
 }

 public void viewsetup() {
  maprenderer.setView(gamecam);
 }

 @Override
 public void render(float delta) {

  update();

  ClearScreen.clear();
  gamecam.update();
  viewsetup();
  maprenderer.render();
  game.batch.begin();
  p.render(game.batch);
  game.batch.end();
  world.step(1 / 60 f, 6, 2);
  b2dr.render(world, gamecam.combined);
 }

 public void update() {
  p.update();
 }

 @Override
 public void resize(int width, int height) {
 }

 @Override
 public void pause() {
 }

 @Override
 public void resume() {
 }

 @Override
 public void hide() {
 }

 @Override
 public void dispose() {
  map.dispose();
  p.dispose();
 }
}

```

Player:

```
public class Player {

 boolean isKeyPressed = false;

 Texture texture;
 Sprite sprite;
 BodyDef bdef;

 int MaxVel;
 Vector2 vel;
 Vector2 pos;

 PolygonShape PlayerB;

 public static Body PlayerBody;
 Vector2 beginPos;
 Vector2 currentPos;

 @SuppressWarnings("static-access")
 public void init(World world) {
  MaxVel = 10;

  texture = new Texture("Player.png");
  sprite = new Sprite(texture);

  bdef = new BodyDef();
  bdef.type = bdef.type.DynamicBody;
  bdef.position.set(new Vector2(sprite.getX(), sprite.getY()));

  bdef.position.x = 30;
  bdef.position.y = 40;

  PlayerBody = world.createBody(bdef);

  Vector2[] vertices = new Vector2[4];

  vertices[0] = new Vector2(sprite.getX(), sprite.getY());
  vertices[1] = new Vector2(sprite.getX() + sprite.getWidth(), sprite.getY());
  vertices[2] = new Vector2(sprite.getX(), sprite.getY() + sprite.getHeight());
  vertices[3] = new Vector2(sprite.getX() + sprite.getWidth(), sprite.getY() + sprite.getHeight());

  sprite.setPosition(0, 0);

  FixtureDef fixDef = new FixtureDef();
  PlayerB = new PolygonShape();
  PlayerB.set(vertices);
  fixDef.shape = PlayerB;
  Fixture fix = PlayerBody.createFixture(fixDef);

  vel = PlayerBody.getLinearVelocity();
  pos = PlayerBody.getPosition();
 }

 public void setTexture(String dir) {
  texture = new Texture(dir);
 }

 public void render(Batch batch) {
  sprite.draw(batch);
 }

 public void update() {
  if (Gdx.input.isKeyJustPressed(Keys.W) && isKeyPressed == false) {
   isKeyPressed = true;
   PlayerBody.applyLinearImpulse(new Vector2(0, 1), PlayerBody.getPosition(), true);
  }

  handleBdefPos();
  handleGroundCollision();
  handleTextureMovement();
  handlePlayerB();
 }

 public void handleTextureMovement() {
  sprite.setPosition(bdef.position.x, bdef.position.y);
 }

 public void handleBdefPos() {
  bdef.position.x = PlayerBody.getPosition().x;
  bdef.position.y = PlayerBody.getPosition().y;
 }

 public void handleInput() {
  beginPos = PlayerBody.getPosition();
  currentPos = PlayerBody.getPosition();
  if (Gdx.input.isKeyJustPressed(Keys.W)) {
   while ((beginPos.y - currentPos.y) < 300) {
    currentPos = PlayerBody.getPosition();
    PlayerBody.setLinearVelocity(new Vector2(0, 4));
   }
   PlayerBody.setLinearVelocity(new Vector2(0, 0));
  }
 }

 public void handleGroundCollision() {
 }

 public void handlePlayerB() {
 }

 public void dispose() {
  texture.dispose();
 }
}

```

# Answer
What friction does the player have? Is it sliding against another body that also has friction?

If not, applying a impulse will make it move until you apply a force in the opposite direction.
> 0 votes

# Answer
Set the density of the fixture:

```
fixDef.density = 1;

```
> 0 votes

---
Tags: java, libgdx, box2d
---


# Question
Title: OpenGL: How do I map a square texture onto a rectangular surface?
I'm not asking about how to map the texture itself. I'm just wondering how I could go about evenly mapping a texture to an object so that it repeats itself instead of stretching to the surface.

For example:

Thanks.

# Answer
> 1 votes
If you know you're spawning a quad with `width` and `height`

and you want your texture to spawn its entire height exactly once

and you want the width to truncate/repeat accordingly to preserve the texture aspect ratio

then you want your UV x values to run from `0` to `width/height`

and your UV y values to run from `0` to `1`

This way if `width` is twice as large as `height`, your texture will tile two times horizontally. And correspondingly for other sizes.

# Answer
> 0 votes
You want to set the wrapping mode:

```
glTexParameteri(GL_TEXTURE2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

```

You can also do

```
GL_CLAMP
GL_REPEAT
GL_MIRRORED_REPEAT
GL_CLAMP_TO_EDGE
GL_CLAMP_TO_BORDR
GL_MIRROR_CLAMP_TO_EDGE

```

See What does changing GL\_TEXTURE\_WRAP)\_(S/T) do? for more info

# Answer
> 0 votes
First set the wrap mode:

```
glTexParameteri(GL_TEXTURE2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

```

Then you just need to make your texture coordinates bigger than 1.

Instead of putting 1, 1, you need to put 2, 2 and it will repeat itself twice. Good luck!

---
Tags: opengl, textures, graphics, geometry, graphics-programming
---


title: How to move NavMesh Agent by animation?

text:
# Question
Title: How to move NavMesh Agent by animation?
What's the best way to create a simple moving navmesh agent with animation? (e.g. a human enemy running to player)

I have run animation that **moves** the enemy

```
public void Run ()
{
    animator.SetFloat ("Speed", 1f);
}

```

but I am not sure how to combine it with navmesh.

In one tutorial I saw Standard Assets `ThirdPersonController` `.Move(...)` used for that, but I am not sure if I should use it for that purpose, as I understand it was intended only for player characters?

Or should I use animation that runs in place?

# Answer
You need to attach this animation to your player gameobject and in code (the third person controller does this as an example) set a variable whenever it's moving and send it to the animator. Then in the animator for the player have the transition between (i'm guessing) "Idle" and "Run" be based on the state of that variable.
> 2 votes

---
Tags: unity, animation, movement, navmesh
---


title: Tile slopes and jittery movement

text:
# Question
Title: Tile slopes and jittery movement
I'm trying to handle slopes in a tiles based world. I'm using basic linear interpolation to find the Y coordinate of the character based on his X position. But i have a problem, when the character move up or down the slopes the sprite is all jittery, it doesn't move smoothly and i can't figure out why.

I don't use a "true physics engine" all the engine does is AABB collision and tell when a collision occurs and let you handle the reaction. When the character is on a slope no "gravity" (Y velocity) is applied the Y position is adjusted by hand using the linear interpolation result.

Here is the linear interpolation function that i use :

```
float InterpolateY(Vector2 point1, Vector2 point2, float x)
{
    float x1 = point1.X;
    float y1 = point1.Y;

    float x2 = point2.X;
    float y2 = point2.Y;

    float y = y1 + (x - x1) * (y2 - y1) / (x2 - x1);

    return y;
}

```

I've made a webm to show you the problem (ignore the fact that the sprite sink into other tile it doesn't matter for the moment)

Link to the webm : https://webmshare.com/play/vPXLD

# Answer
> 0 votes
I found the problem, it was pretty obvious actually. The position of the character was calculated using a motion vector and the motion.X used in the interpolation was a float number so the result was also a float number (ex : 125.5). The problem happen when i put my character to the Y position calculated (a float) on the screen, the screen coordinate are integers so the Y value get rounded (ex : 125.5 -\> 125) thats why i got this jittery effect.

# Answer
> 0 votes
I suspect that the engine is doing that. Basically the character is colliding but is getting pushed away from the collider of the ground.
When I used Unity similiar problems occured.
I think its a Physics/Engine Problem

---
Tags: c#, xna, monogame
---


title: How can I rig an SVG humanoid?

text:
# Question
Title: How can I rig an SVG humanoid?
I have a template SVG file for an articulated doll and it looks something like this:

I can manually rotate and pose it in Adobe illustrator, but is there a better workflow to rig 2D segmented assets?

# Answer
What you need is a tool like Spriter (https://brashmonkey.com/). It is specifically designed to let you combine components like you have, and create animations from them.

With it or tools like it, you can join your pieces together, then move them about to create poses, or sequences of poses to make an animation.

Here's a video that Brash Monkey has on Spriter that shows how this all works...

https://www.youtube.com/watch?v=NrgGhK48Joo

If anyone knows of any other good tools, please feel free to comment. I happened to know Spriter so that's the one I shared.
> 1 votes

---
Tags: rigging
---


# Question
Title: ForEach vs For loop in JavaScript | Which is more efficient?
I was wondering which for loop is less hard on the computer, and why it is

Example:

```
    var greet = ["Hey", "Howdy", "Hello", "Hi"];
    greet.forEach(function(index){
        console.log(index);
    });

```

vs

```
    var greet = ["Hey", "Howdy", "Hello", "Hi"];
    for(var i = 0; i < greet.length; i++) {
        console.log(greet[i]);
    }

```

# Answer
You should not micro-optimize code at this level, unless you have good reason to believe it is a bottleneck in your code. This is for a number of reasons:

1) optimization depends on the particulars of the Javascript runtime. What is fast in node or V8 is not necessarily fast in SpiderMonkey or Chakra.

2) optimization depends on the particulars of your code, how often and in what order you access it, how large the data is, etc.

If the above arguments have not persuaded you that you shouldn't optimize prematurely, you should learn to profile and figure out for yourself which is faster. For example, if I open up node, I can write:

```
> {
    var s = 0,  arr = new Array(1000000);
    console.time("for");
    for(var i = 0; i < arr.length; i++) { s += arr[i] };
    console.timeEnd("for");
}
for: 35.022ms

> {
    var s = 0, arr = new Array(1000000);
    console.time("forEach");
    arr.forEach(x => s += x);
    console.timeEnd("forEach");
}
forEach: 13.610ms

```

Now, you're thinking: "oh! forEach must be twice as fast as a for loop!. I'll use forEach for everything"

But wait! maybe something is up because arr is a bunch of `undefined`s. What if we actually initialize the array to a number before running the sum?

```
> { var s = 0, arr = new Array(1000000); for(var i=0; i<arr.length; i++) arr[i] = i;
    console.time("forEach");
    arr.forEach(x => s += x);
    console.timeEnd("forEach");
    console.log(s) }
forEach: 23.947ms
499999500000

> { var s = 0, arr = new Array(1000000); for(var i=0; i<arr.length; i++) arr[i] = i;
   console.time("for");
   for(var i=0; i<arr.length; i++) { s += arr[i] };
   console.timeEnd("for");
   console.log(s) }
for: 13.959ms
499999500000

```

Ahh ... the for loop got much faster and the forEach loop got slower! why? You'll have to dig into the particulars of each runtime's optimization features for the answer.

**Summary:**

Q) Which loop style is faster?
A) It depends.

Q) Should I spend time optimizing small for-loops
A) no

Q) But how should I know when to optimize?
A) measure it by profiling instead of guessing.
> 4 votes

# Answer
The indexed for loop is a bit faster (not much, but it is), since the js engine doesn't have to look the properties of the object up before looping through them. It basically does your job when it does the first part.

So to put it into a metaphor, it's like telling someone to look up 50 addresses you gave them instead of telling someone, to look up 50 addresses, that are stored in a safe 3 floors below you.

I did profile it if you're curious.

Details:

I just created an array with 10,000,000 elements, each being equal to its index (\[0, 1, 2, 3...\]), then added their squares to a number to make sure it doesn't get optimized out. The forEach method came out at an average of 1407ms and the normal for method came out at 1443ms with 20 test runs.
> 2 votes

---
Tags: javascript, html
---


# Question
Title: Adding a typewriter effect in Java using g.drawString()
Disclaimer: I'm a bit new to stack exchange and programming so go easy :)

I'm currently working on a small text-based Oregon Trail type game and I'd like to add a typewriter effect to slow down the pacing of the game. The main class that actually runs the game implements runnable and the text is rendered using g.drawString() in the render method. I've tried rendering each character separately using a for loop and thread.sleep() but it just appeared on the screen all at once. Here is the code I used for that:

```
for(int i = 1; i <= events.result.length(); i++) {
    try{
        thread.sleep(millisPer);//0.5s pause between characters
    } catch(InterruptedException ex) {
        Thread.currentThread().interrupt();
    }
    g.drawString(events.result.substring(0, i), 300, 300);
}

```

I also tried getting the system time like this:

```
package mains;

import java.awt.Graphics;

public class Typewriter{
    long stallTime = 0;

    public void typeResult(Graphics g, String result)   {
        int spacing = 300;
        for(int i = 0; i < result.length(); i++) {

            if(getElapsedTime() > 1) {
                g.drawString(result.substring(i, i+1), spacing, 300);
                spacing+=5;
            }

        }
    }

    public int getElapsedTime(){
        return (int)((System.currentTimeMillis()-stallTime)/1000);

    }

    public void setStallTime(){
        stallTime=System.currentTimeMillis();
    }

}

```

This had the same effect. Are there any other means of adding a delay that work with my class? Thanks for the help. The full game class is below:

```
package mains;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;

public class Game extends Canvas implements Runnable{

    private static final long serialVersionUID = -6672699999969016018L;
    private boolean isRunning = false;
    private Thread thread;
    private GameState state;
    Window window = new Window(1000,800,"Prototype", this);
    EventManager events = new EventManager();
    BufferedImage image = ImageLoader.loadImage("/textures/Syria.png");
    Typewriter typewriter = new Typewriter();

    public Game() {
        this.addMouseListener(new MouseInput(this));
        this.addMouseListener(window);
        state = state.MainMenu;
        start();

    }

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

    private void start() {
        isRunning = true;
        thread = new Thread(this);
        thread.start();

    }
    private void stop()  {
        isRunning = false;
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    public GameState getGameState(){
        return state;
    }

    public void setGameState(GameState state){
        this.state = state;
    }

    public void run() {
        //game loop - lifted from Zach from RealTutsGML
        this.requestFocus();
        long lastTime = System.nanoTime();
        double amountOfTicks = 60.0;
        double ns = 100000000 / amountOfTicks;
        double delta = 0;
        long timer = System.currentTimeMillis();
        int frames = 0;
        while(isRunning) {
            long now = System.nanoTime();
            delta += (now - lastTime) / ns;
            lastTime = now;
            while(delta >= 1) {
                tick();
                //updates++;
                delta--;
            }
            render();
            frames++;

            if(System.currentTimeMillis() - timer > 1000) {
                timer += 1000;
                frames = 0;

                //updates = 0;
            }
        }
        stop();
    }

    private void tick() {
        events.tick();

        if(events.distance >= 100) {
            state = state.Escape;

        }

        if(events.getHealth() <= 0) {
            state = state.Death;
        }

    }

    private void render() {
        BufferStrategy bs = this.getBufferStrategy();
        if(bs == null) {
            this.createBufferStrategy(3);
            return;
        }

        Graphics g = bs.getDrawGraphics();

        //ANYTHING BETWEEN THIS LINE AND g.dispose() IS RENDERED

        if(state == state.MainMenu) {
            g.drawImage(image,-100,0, null);
            g.setColor(Color.red);
            g.fillRect(100, 700, 50, 50);
        }

        if(state == state.Escape) {
            g.setColor(Color.blue);
            g.fillRect(0, 0, 1000, 800);
            g.setColor(Color.white);
            g.drawString("YOU ESCAPED! :)", 500,500);

        }

        if(state == state.Death) {
            g.setColor(Color.black);
            g.fillRect(0, 0, 1000, 800);
            g.drawString("YOU DIED! :(", 500,500);

        }

        if(state == state.CharScreen) {
            g.setColor(Color.black);
            g.fillRect(0,0,1000,1000);
            g.setColor(Color.blue);
            g.fillRect(200, 700, 50, 50);
            g.setColor(Color.yellow);
            g.fillRect(700, 200, 100, 50);
            g.setColor(Color.green);
            g.fillRect(700, 300, 100, 50);
            g.setColor(Color.red);
            g.fillRect(700, 400, 100, 50);
            g.setColor(Color.orange);
            g.fillRect(700, 500, 100, 50);
            g.setColor(Color.white);
            g.drawString("Day " + events.getDays(), 300, 100);
            g.drawString("Time " + events.getHours(), 300, 200);

            typewriter.typeResult(g, events.result);
            //g.drawString(events.result, 300, 300);
            g.drawString("Distance: " + events.distance, 500, 200);
            g.drawString("Health: " + events.getHealth(), 300, 400);
            g.drawString("Sustenance: " + events.getSustenance(), 300, 500);
            g.drawString("Sanity: " + events.getSanity(), 300, 600);
            g.drawString("Exhaustion: " + events.getExhaustion(), 300, 700);

        }

        g.dispose();
        bs.show();
    }

}

```

# Answer
> 3 votes
Welcome to StackExchange! You may find the answers at https://stackoverflow.com/questions/5478962/problem-with-thread-sleepx-in-a-for-loop-java helpful.

The short explanation is that Java needs to redraw the graphics on the main thread, but you've put it to sleep with thread.sleep(), so only when your loop is finished does Java regain access to the thread it needs to actually update the display.

You'll want to use a swing Timer, which handles invoking code on the main thread when each timer "tick" happens.

---
Tags: java
---