title: How can I rotate object on key press?

text:
# Question
Title: How can I rotate object on key press?
The script:

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

public class ChangeScale : MonoBehaviour
{
    //Scaling change
    public GameObject objectToScale;
    public float duration = 1f;
    public Vector3 minSize;
    public Vector3 maxSize;

    private bool scaleUp = false;
    private Coroutine scaleCoroutine;

    //Colors change
    public Color startColor;
    public Color endColor;
    public float colorDuration; // duration in seconds

    //Lights change
    public DimLights dimlights;
    private Coroutine lightCoroutine;

    //Rotate
    public float rotationSpeed;
    public float rotationDuration;

    private void Start()
    {
        //startColor = GetComponent<Renderer>().material.color;
        endColor = Color.green;
        objectToScale.transform.localScale = minSize;
    }

    // Use this for initialization
    void Update()
    {
        //Scaling
        if (Input.GetKeyDown(KeyCode.F))
        {
            //Flip the scale direction when F key is pressed
            scaleUp = !scaleUp;

            //Stop old coroutine
            if (scaleCoroutine != null)
                StopCoroutine(scaleCoroutine);

            if (lightCoroutine != null)
                StopCoroutine(lightCoroutine);

            //Scale  up
            if (scaleUp)
            {
                //Start new coroutine and scale up within 5 seconds and return the coroutine reference
                scaleCoroutine = StartCoroutine(scaleOverTime(objectToScale, maxSize, duration));
                lightCoroutine = StartCoroutine(dimlights.dimLightOverTime(1, duration)); ;
            }

            //Scale Down
            else
            {
                //Start new coroutine and scale up within 5 seconds and return the coroutine reference
                scaleCoroutine = StartCoroutine(scaleOverTime(objectToScale, minSize, duration));
                lightCoroutine = StartCoroutine(dimlights.dimLightOverTime(0, duration)); ;
            }
        }

        //Change color
        if (Input.GetKeyDown(KeyCode.C))
        {
            StartCoroutine(ChangeColor());
        }

        //Rotate
        if (Input.GetKeyDown(KeyCode.R))
        {
            objectToScale.transform.Rotate(Vector3.up * rotationSpeed * Time.deltaTime);
            //StartCoroutine(RotateObject());
        }
    }

    IEnumerator scaleOverTime(GameObject targetObj, Vector3 toScale, float duration)
    {
        float counter = 0;

        //Get the current scale of the object to be scaled
        Vector3 startScaleSize = targetObj.transform.localScale;

        while (counter < duration)
        {
            counter += Time.deltaTime;
            targetObj.transform.localScale = Vector3.Lerp(startScaleSize, toScale, counter / duration);
            yield return null;
        }
    }

    IEnumerator ChangeColor()
    {
        float t = 0;

        while (t < colorDuration)
        {
            t += Time.deltaTime;
            GetComponent<Renderer>().material.color = Color.Lerp(startColor, endColor, t / colorDuration);
            yield return null;
        }
    }

    IEnumerator RotateObject()
    {
        float startTime = Time.time;

        while (Time.time - startTime < rotationDuration)
        {
            objectToScale.transform.Rotate(Vector3.up * rotationSpeed * Time.deltaTime);
            yield return null;
        }
    }
}

```

I tried using StartCoroutine but it didn't work. So for testing I tried to make that if I'm click/pressing on R once it will rotate the object nonstop but it's not working either it's not rotating it all.

Nothing i click on R and nothing happen. Tried to change the rotationSpeed from 1 to 10.

# Answer
> 1 votes
I would make the code like this:

```
public Update()
{
  if (Input.GetKey(KeyCode.R))
  {
      // If the player is holding the key, rotate the object.
      objectToScale.transform.Rotate( /* How much to rotate */ )
  } else if (Input.GetKeyUp(KeyCode.R)
  {
      // If the user has just let go of the key we want
      // to rotate for N seconds
      StartCoroutine(RotateObject());
  }
}

IEnumerator RotateObject()
{
    float startTime = Time.time

    while (Time.time - startTime < rotationDuration)
    {
        objectToScale.transform.Rotate( /* How much to rotate */ );
        yield return null;
    }
}

```

This should rotate the object while the player is holding the key, and after the player releases the key it should rotate for `rotationDuration` more seconds.

It's also important to note that this line `Vector3.up * rotationSpeed * t / rotationDuration` is kind of strange. If you want to rotate the object by `rotationSpeed` every second you should just do `Vector3.up * rotationSpeed * Time.deltaTime`.

# Answer
> 1 votes
You need parts from both of your attempts:

```
if (Input.GetKeyDown(KeyCode.R))

```

This will trigger exactly once until you let go of the key again. This is exactly the behavior you describe as wanting to have.

```
StartCoroutine(RotateObject());

```

This will do the rotation (via the coroutine function you already have set up).

When you use `if (Input.GetKey(KeyCode.R))` and start a coroutine, you end up starting a dozen or more *copies* of the coroutine, all of which are trying to rotate your object and are conflicting with each other, leading to unpredictable behavior.

*Then* you have one other problem:

```
objectToScale.transform.Rotate(Vector3.up * rotationSpeed * t / rotationDuration);

```

This math is almost certainly not doing what you want it to. If you want a *linear* rotation speed, then you want `Time.deltaTime` here. Additionally the `rotationDuration` value isn't needed. Just use this:

```
objectToScale.transform.Rotate(Vector3.up * rotationSpeed * Time.deltaTime);

```

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


# Question
Title: How to use SDL_RWops and SDL_RWseek to read text files, line by line?
I'm right now looking for alternative ways to read text files on a line-by-line basis, for cross-platform compatibility (Windows / Linux).

My current solution is to go look for (or seek out) the newline (line break) in a text file using SDL2.

To demonstrate, I have a simple text file, with just 2 lines of gibberish text:

```
Hello world,
This is a new line with a line break.

```

On some text editors, you are able to display newlines or line breaks, and the above text would look somewhat like this:

```
Hello world,↵
This is a new line with a line break.

```

I want to use `SDL_RWops`, and if possible, use `SDL_RWseek`, or `(SDL_RWops*)->seek(SDL_RWops*)`, to find the newline (line break), denoted by  in the above example. That way, I can write a shorthanded version of `SDL_RWreadToLine` or some method that allows me to fetch text, line by line.

I believed the current method is very inefficient to check to see if I reached a newline, using psuedo-code:

```
//File reading/writing (We're only going to read)
//edict2 is a gigantic UTF-8 Japanese <-> English dictionary text file.
//That text file is useful for text operations (read/write) testing purposes.

SDL_RWops* edict2 = SDL_RWFromFile("edict2u", "r");         //The "u" stands for UTF-8 compatible.
if (edict2) {
    Sint64 currentBytePointer = 0;              //Holds the current pointer.
    Sint64 currentReadPointer = 0;              //Holds the current read pointer.
    Sint64 fileSize = edict2->size(edict2);     //Grabs the file size of the file.
    char* buffer = new char[256];               //Some buffer to capture the read text characters.
    while (currentBytePointer < fileSize && currentReadPointer != 0) {
        Sint64 length = edict2->seek(edict2, 1, RW_SEEK_CUR);       //Reads 1 byte from current read position.
        Sint64 temp = edict2->read(edict2, buffer, length, length); //Implicit C conversion from void* to char*.
        if (buffer[0] != '\0' && buffer[0] == '\n') {
            //Found, do something about it
        }
    }
    delete buffer;
}
else {
    //File doesn't exist, do nothing.
}

```

I'm sure there are bugs that I may have missed out on, considering that I'm reading from a text file that may contain multiple bytes.

And that's why I wanted to look for SDL2 alternatives.

**Does anyone know of a better way to read text line by line using SDL2?**

# Answer
> -1 votes
Instead of using SDL2's `SDL_RWops`, just use the C++ standard library.

A combination of `std::ifstream` and `std::getline()` should do the trick for reading strings from text files, line by line.

```
//File reading/writing (We're only going to read)
std::ifstream edict2("dict/edict2u");
if (edict2.is_open() && edict2.good()) {
    std::string buffer;
    while (std::getline(edict2, buffer)) {
        //Do something about the buffer.
        doAction(buffer);

        //Then clear the buffer once you're done with it.
        buffer.clear();
    };
}

```

Thanks to @Tyyppi\_77 for pointing out the obvious.

---
Tags: c++, sdl, sdl2, text, file
---


title: Will my Admob Unity Plugin be Obsolete?

text:
# Question
Title: Will my Admob Unity Plugin be Obsolete?
When I got back to Google Admob Console I received this announcement:

"Beginning on 23 Jan 2018, Google Mobile Ads SDK versions older than 7.0.0 for Android and 7.0.0 for iOS will no longer be supported. Publishers with these older versions will not be able to serve ads in their apps(s). Please ensure that you have upgraded to the latest version of the Google Mobile Ads SDK."

I am concerned about whether the Unity game I released eight months ago will continue to serve Admob ads.

I think this pertains to many Unity developers. It seems that the Google Mobile Ads for Unity uses a different versioning system. Its current version is version v3.10.0.

So what is the latest version of Admob Unity Plugin that will be affected by this? Will we be affected at all?

# Answer
> 1 votes
Yes everyone using an older version than required will be effected with that announcement. The Unity package uses the native plugin in a wrapper and isn't different than the iOS and Android plugin at native level.

Go check here !

+Built and tested with: +- Google Play services 11.6.2 +- Google Mobile Ads iOS SDK 7.27.0 +- Unity Jar Resolver 1.2.59.0

https://github.com/googleads/googleads-mobile-unity/commit/e393e68c9f6737f686af44aa1875e5e10a411464

They mention the underlying native plugin version with each release.

---
Tags: unity, admob
---


# Question
Title: How can i scale object slowly using StartCoroutine?
Both scripts attached to same object in Hierarchy. The first script i'm using the F key to display or not display the object:

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

public class DroidMove : MonoBehaviour
{
    public GameObject droid;

    private float distance;
    private Camera cam;

    private void Start()
    {
        cam = GetComponent<Camera>();
        distance = Vector3.Distance(cam.transform.position, droid.transform.position);
        droid.SetActive(false);
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.F))
        {
            droid.SetActive(!droid.activeInHierarchy);
        }
    }
}

```

Once pressing F to show the object i want the object to be scaled slowly from 0,0,0 to 1,1,1 so i did another script:

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

public class ChangeScale : MonoBehaviour
{
    public GameObject objectToScale;
    public float maxSize = 1f;
    public float growFactor = 1f;
    public float waitTime = 5f;

    // Use this for initialization
    void Start ()
    {
        objectToScale.transform.localScale = new Vector3(0, 0, 0);
    }

    IEnumerator Scale()
    {
        float timer = 0;

        while (true) // this could also be a condition indicating "alive or dead"
        {
            // we scale all axis, so they will have the same value,
            // so we can work with a float instead of comparing vectors
            while (maxSize > objectToScale.transform.localScale.x)
            {
                timer += Time.deltaTime;
                objectToScale.transform.localScale += new Vector3(1, 1, 1) * Time.deltaTime * growFactor;
                yield return null;
            }
            // reset the timer

            yield return new WaitForSeconds(waitTime);

            timer = 0;
            while (1 < objectToScale.transform.localScale.x)
            {
                timer += Time.deltaTime;
                objectToScale.transform.localScale -= new Vector3(1, 1, 1) * Time.deltaTime * growFactor;
                yield return null;
            }

            timer = 0;
            yield return new WaitForSeconds(waitTime);
        }
    }

    // Update is called once per frame
    void Update ()
    {
        if (objectToScale.activeInHierarchy == true)
        {
            StartCoroutine(Scale());
        }
    }
}

```

But i'm getting two exceptions on the first script on the line:

```
droid.SetActive(!droid.activeInHierarchy);

```

First exception:

> Slope Limit must be smaller than 90 degrees. UnityEngine.GameObject:SetActive(Boolean) DroidMove:Update() (at Assets/NAVI/Scripts/DroidMove.cs:23)

Second exception:

> Step Offset must be less or equal to + * 2 UnityEngine.GameObject:SetActive(Boolean) DroidMove:Update() (at Assets/NAVI/Scripts/DroidMove.cs:23)

# Answer
First of all it's a really bad idea of Starting a Coroutine in the Update Loop. Never call it in Update. instead you should use OnEnable as coroutine of your scale shouldn't be calling every frame.
> 1 votes

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


# Question
Title: My collider is not following my humanoid animation: how to do ?
I've a "Zombie" charachter and the following hirearchy:

I put a Capsule collider on parent Zombie\_01. When I kill the zombie, my "Zombie dead" animation is played, Zombie fall to ground, but the capsule collider stay standing.

So my question is: where I've to put capsule collider ? Or, what am i wrong ?

Thanks

# Answer
You need to have a rigid body with your image. If you won't have one then the collider can't react under physical condition changes.
> 0 votes

---
Tags: unity, collider
---


title: Unreal Engine 4 Android Building Error

text:
# Question
Title: Unreal Engine 4 Android Building Error
Android Launch error My sdk settings:

```
LogPlayLevel: UnrealBuildTool: Preparing native code for debugging...
!LogPlayLevel: UnrealBuildTool: UnrealBuildTool Exception: ERROR: D:/Program Files/NDK/NVPACK/android-ndk-r12b/ndk-build.cmd failed with args APP_ABI="arm64-v8a " NDK_DEBUG=1
LogPlayLevel: CommandUtils.Run: Run: Took 36,7394016s to run UnrealBuildTool.exe, ExitCode=5
LogPlayLevel: BUILD FAILED
PackagingResults:Error: Error Launch failed! Unknown Error

```

# Answer
I had the same problem when I 'am trying to deploy my game on my tablet android 5.1 (API 22) so this is what I did : \- Project Settings \> Android \> \- check Support arm64 \[aka arm64-v8a\]

just that and then I had the Gradle problem I just unchecked the "Enable Gradle Instead of Ant"

Hope this helps :)
> 1 votes

# Answer
Sometimes it depends on the sequence of the installation. In my case I have to install the NDK first and Unreal later.

The other thing you can do is to check your environment variables if the NDK variables are there or not. If present then clear all location values from SDK config and try to build again that should work.
> 0 votes

---
Tags: android, unreal-4
---


# Question
Title: What methods can be used to rotate a tiled structure?
I'm trying to rotate some structures that are locked on a grid-like structure. This means I'm looking for lossless ways to rotate the tiles. Maintaining proper distances are not important, I'm aware that diagonals will be longer if we maintain the same number of filled tiles.

Here's a few examples of what I want to do (done by hand, so might be slightly off), where the red block is the front:

On the left are the four cardinal directions, which are East(0°/0.0π rad), North(90°/0.5π rad), West(180°/1.0π rad) and South(270°/1.5π rad).

On the right there's ~22.5° in the top and 315° in the bottom.

Right now I'm looking mostly to do rotations in ~22.5° increments, so a full circle in 16 steps, but a general solution for the problem would be great.

# Answer
It sounds like you might be looking for Rotation by Shearing, or Alan Paeth's "A Fast Algorithm for General Raster Rotation"

I first learned about this technique via the excellent DataGenetics blog. Rather than resample an image into a new (interpolated) raster the way we'd tend to do today, rotation by shearing just shuffles the existing raster values around the grid using 3 axis-aligned shear operations (the first & last repeated):

Mathematically it means breaking down the rotation matrix like so:

$$\begin{align} \begin{bmatrix}x' \\ y'\end{bmatrix} &= R\_\theta \begin{bmatrix}x \\ y \end{bmatrix} \\ &= \begin{bmatrix} cos\theta & sin\theta \\ -sin\theta & cos\theta\end{bmatrix}\begin{bmatrix}x \\ y \end{bmatrix} \\ &= \begin{bmatrix} 1 & -tan(\theta/2) \\ 0 & 1 \end{bmatrix} \begin{bmatrix} 1 & 0 \\ sin\theta & 1 \end{bmatrix} \begin{bmatrix} 1 & -tan(\theta/2) \\ 0 & 1 \end{bmatrix} \begin{bmatrix}x \\ y \end{bmatrix} \\ \end{align}$$

Each of these three component matrices is an axis-aligned shear with determinant 1 (so we're not stretching the source to include more or fewer tiles of area at any step)

Each of these shears can be approximated to within the accuracy of our tile grid (subject to some aliasing & stairstep, like anytime we try to draw diagonals on a grid) by shifting whole rows (or columns) of tiles by full-tile increments (rounding the results of the tan & sin above when multiplied by the row or column indices, respectively).

Here's what that might look like in code (depending on your coordinate system, etc)...

```
Point PseudoRotateTile(Point original, Point center, float angle) {
    Point transformed;

    float vertical = -Tan(angle * 0.5f);

    // First shear.
    transformed.y = Round(original.y + vertical * (original.x - center.x));

    // Second shear.
    transformed.x = Round(original.x + Sin(angle) * (transformed.y - center.y));

    // Third shear
    transformed.y = Round(transformed.y + vertical * (transformed.x - center.x));

    return transformed;
}

```

Just note that if you want to perform multiple rotations one after another, you should always start from the initial untransformed layout. Because of the rounding, errors can pile up and scramble the arrangement if you try to rotate a rotated result, rather than applying the total net rotation from scratch each time.
> 4 votes

---
Tags: mathematics, transformation
---


title: How to move monsters in a C++ game?

text:
# Question
Title: How to move monsters in a C++ game?
I'm creating a dungeon crawler in C++ and I'm almost done but I need to make the monster move and I'm at the end of my wits.

This is my map:

```
Char Map[10][10];

```

and this is how I initialize the positions of the monsters:

```
void fieldinfo::RandomizeMonsterPositions()
{
    amountEnemies=10;
    srand(time(0));

    for(i=0; i<amountEnemies; i++){
        map[rand()%9][rand()%9] = enemy;
    }
}

```

`fieldinfo` is the name of my class.

Each time the player moves, the map is redrawn with the updated players position and I need the monster to move every time the player does (randomly or not I don't care).

# Answer
> 2 votes
I'd start by storing all enemy positions in a separate container (a vector for an example).

Then, when you execute a turn, you'd start by clearing the old positions of the enemies.

```
for (auto& enemyPosition : EnemyPositions)
{
    Map[enemyPosition.y][enemyPosition.x] = empty;
}

```

Then you'd do a move pass and update all monster positions:

```
for (auto& enemyPosition : EnemyPositions)
{
    // TODO: Replace with your own movement logic.
    if (rand() % 2 == 0)
        enemyPosition.x += 1
    else
        enemyPosition.y += 1
}

```

After that you could do some sort of collision pass to make sure the enemies don't walk through walls or check if they collide with each other or the player and handle those situations accordingly.

And finally you'll just blop the enemies back to the map with their new adjusted positions:

```
for (auto& enemyPosition : EnemyPositions)
{
    Map[enemyPosition.y][enemyPosition.x] = enemy;
}

```

As a side note, I'd suggest creating more of a separation of visuals & world state, since it's very easy to accidentally overwrite something in your map grid, which could result in a wide variety of bugs.

---
Tags: c++
---


# Question
Title: what is the script that is needed to move a 2D sprite(square)?
I am trying to find a script for my square sprite to move so the player can use WD to move but every time the script won't run. That script is one of many that won't work. This is what I have so far:

```
using UnityEngine;
using System.Collections;

//The abstract keyword enables you to create classes and class members that are incomplete and must be implemented in a derived class.
public abstract class MovingObject : MonoBehaviour
{
    public float moveTime = 0.1f;           //Time it will take object to move, in seconds.
    public LayerMask blockingLayer;         //Layer on which collision will be checked.

    private BoxCollider2D boxCollider;      //The BoxCollider2D component attached to this object.
    private Rigidbody2D rb2D;               //The Rigidbody2D component attached to this object.
    private float inverseMoveTime;          //Used to make movement more efficient.

    //Protected, virtual functions can be overridden by inheriting classes.
    protected virtual void Start()
    {
        //Get a component reference to this object's BoxCollider2D
        boxCollider = GetComponent<BoxCollider2D>();

        //Get a component reference to this object's Rigidbody2D
        rb2D = GetComponent<Rigidbody2D>();

        //By storing the reciprocal of the move time we can use it by multiplying instead of dividing, this is more efficient.
        inverseMoveTime = 1f / moveTime;
    }

    //Move returns true if it is able to move and false if not.
    //Move takes parameters for x direction, y direction and a RaycastHit2D to check collision.
    protected bool Move(int xDir, int yDir, out RaycastHit2D hit)
    {
        //Store start position to move from, based on objects current transform position.
        Vector2 start = transform.position;

        // Calculate end position based on the direction parameters passed in when calling Move.
        Vector2 end = start + new Vector2(xDir, yDir);

        //Disable the boxCollider so that linecast doesn't hit this object's own collider.
        boxCollider.enabled = false;

        //Cast a line from start point to end point checking collision on blockingLayer.
        hit = Physics2D.Linecast(start, end, blockingLayer);

        //Re-enable boxCollider after linecast
        boxCollider.enabled = true;

        //Check if anything was hit
        if (hit.transform == null)
        {
            //If nothing was hit, start SmoothMovement co-routine passing in the Vector2 end as destination
            StartCoroutine(SmoothMovement(end));

            //Return true to say that Move was successful
            return true;
        }

        //If something was hit, return false, Move was unsuccesful.
        return false;
    }

    //Co-routine for moving units from one space to next, takes a parameter end to specify where to move to.
    protected IEnumerator SmoothMovement(Vector3 end)
    {
        //Calculate the remaining distance to move based on the square magnitude of the difference between current position and end parameter.
        //Square magnitude is used instead of magnitude because it's computationally cheaper.
        float sqrRemainingDistance = (transform.position - end).sqrMagnitude;

        //While that distance is greater than a very small amount (Epsilon, almost zero):
        while (sqrRemainingDistance > float.Epsilon)
        {
            //Find a new position proportionally closer to the end, based on the moveTime
            Vector3 newPostion = Vector3.MoveTowards(rb2D.position, end, inverseMoveTime * Time.deltaTime);

            //Call MovePosition on attached Rigidbody2D and move it to the calculated position.
            rb2D.MovePosition(newPostion);

            //Recalculate the remaining distance after moving.
            sqrRemainingDistance = (transform.position - end).sqrMagnitude;

            //Return and loop until sqrRemainingDistance is close enough to zero to end the function
            yield return null;
        }
    }

    //The virtual keyword means AttemptMove can be overridden by inheriting classes using the override keyword.
    //AttemptMove takes a generic parameter T to specify the type of component we expect our unit to interact with if blocked (Player for Enemies, Wall for Player).
    protected virtual void AttemptMove<T>(int xDir, int yDir)
        where T : Component
    {
        //Hit will store whatever our linecast hits when Move is called.
        RaycastHit2D hit;

        //Set canMove to true if Move was successful, false if failed.
        bool canMove = Move(xDir, yDir, out hit);

        //Check if nothing was hit by linecast
        if (hit.transform == null)
            //If nothing was hit, return and don't execute further code.
            return;

        //Get a component reference to the component of type T attached to the object that was hit
        T hitComponent = hit.transform.GetComponent<T>();

        //If canMove is false and hitComponent is not equal to null, meaning MovingObject is blocked and has hit something it can interact with.
        if (!canMove && hitComponent != null)

            //Call the OnCantMove function and pass it hitComponent as a parameter.
            OnCantMove(hitComponent);
    }

    //The abstract modifier indicates that the thing being modified has a missing or incomplete implementation.
    //OnCantMove will be overriden by functions in the inheriting classes.
    protected abstract void OnCantMove<T>(T component)
        where T : Component;
}

```

# Answer
I agree with the other comments, there a million ways to make this happen. The snippet attached includes a lot of bit that you don't really address in your question. So I'll assume that you are, at the moment, only concerned about making the square move. The easiest way I can think off to do this is something like this:

```
 void Update(){
    Vector3 forward = new Vector3(1,0,0); //assumes increasing the x position moves forward
    float i = Input.GetAxis("Horizontal") * speed * Time.deltaTime; //assumes there's some global float called speed
    transform.Translate(forward * i, Space.World)
}

```

This assumes some global float called "speed" in the class to control the rate of movement. Here's a couple links that might be helpful:

https://docs.unity3d.com/ScriptReference/Transform.Translate.html https://docs.unity3d.com/ScriptReference/Input.GetAxis.html

I'd suggest getting the moving part to work, then work on handling collisions, if I were offering advice. ;)

\*I didn't run this code in unity to test it. But I'm pretty confident I didn't make any breaking errors.

Thanks!
> 1 votes

---
Tags: unity, 2d, sprites, movement
---


# Question
Title: Find objects with a specific class in Scene in Unity
I need to find every object of the same class in the scene. How can I do this?

# Answer
The easiest way is to get them in an array with something like FindObjectsOfType.

https://docs.unity3d.com/ScriptReference/Object.FindObjectsOfType.html

Are you needing some specific functionality that this doesn't offer?
> 0 votes

---
Tags: unity, scene
---


# Question
Title: Box collider/rigid body eventually moves through static collider
I found this question, but I'm not sure if it applies to my problem.

I'm hacking together a Pong-style game, and my problem is with the walls (box collider, no rigid body) not completely stopping movement of the player paddle (box collider, yes rigid body.) Sufficiently fast mouse movement eventually moves the paddle through the wall. There is initial resistance, but I would expect `Player Paddle` to stop moving abruptly at the wall. How can I make this happen? I'm new to Unity/colliders/game dev.

My player paddle simply moves up and down (Z-axis) with up/down mouse movement:

```
public class MouseMovement : MonoBehaviour {
    public float speed = 10f;
    // Update is called once per frame
    void Update () {
        var translation = Input.GetAxis("Mouse Y") * speed;
        translation *= Time.deltaTime;
        transform.Translate(0, 0, translation);
    }
}

```

I exported an asset package that reproduces the problem. My problem objects are `Player Paddle`, `Upper`, and `Lower` https://www.dropbox.com/s/yx9svb51nywdvgg/pong-export.unitypackage?dl=0

# Answer
Its simple, always remember when you are moving objects manually or through Physics.

Here you are moving object manually (through `Translate`) and expecting Physics to perform accurately, this is the problem. Your manual command will overwrite the Physics functionality.

You can try to restrict your object through your code that its `Z` value should not be greater and less than your limits.

OR

Second move your object through Physics instead of `Translate` like change in `velocity` or apply `force`

Its been a long time, correct me if I am wrong. I will welcome everyone.
> 1 votes

# Answer
Unity's CharacterController can handle this, it's a bit clunky to use at first (I thought) but it's how I addressed this exact same problem.

https://docs.unity3d.com/ScriptReference/CharacterController.html

Instead of transform.translate, you'll use the CharacterController's Move() or SimpleMove(). I found SimpleMove() to be much more useful.

https://docs.unity3d.com/ScriptReference/CharacterController.SimpleMove.html

Happy hunting.
> 0 votes

---
Tags: unity, c#, collision-detection, rigidbody
---


title: Why aren't my enemy positions updating?

text:
# Question
Title: Why aren't my enemy positions updating?
I'm trying to make a dungeon crawler but I need to make the monster move around each turn.

Here's what I tried:

My map is initialized like this:

```
char map[10][10];

```

and this is how I spawn the monsters to avoid overwriting:

```
void fieldinfo::RandomizeMonsterPositions()
{
    int Mcounter=0;
    amountEnemies=10;
    int i=0;
    srand(time(0));

    do
    {
        MposX=rand()%9;
        MposY=rand()%9;

        if(map[MposX][MposY]==enemy)
        {
            //do nothing
        }
        else if(map[MposX][MposY]==player)
        {
            //do nothing
        }
        else
        {
            map[MposX][MposY] = enemy;
            tempPosX[i]=MposX;
            tempPosY[i]=MposY;
            i++;
            Mcounter++;
        }

    }while(Mcounter<10);
}

```

You can see that I tried to "save" each monster's position in the `tempPosX/Y` variables to use them here, in my movement logic:

```
void fieldinfo::RandomizeMonsterMovement()
{
    int mouvement;
    for(int i; i<amountEnemies; i++)
    {
        mouvement=rand()%0;
        switch(mouvement)
        {
        case 0:
            tempPosX[i]++;
            MposX=tempPosX[i];
            break;
        case 1:
            tempPosX[i]--;
            MposX=tempPosX[i];
            break;
        case 2:
            tempPosY[i]++;
            MposY=tempPosY[i];
            break;
        case 3:
            tempPosY[i]--;
            MposY=tempPosY[i];
            break;
        }
    }
}

```

This doesn't work and I don't know why?

# Answer
> 0 votes
You're not updating the map when the positions change.

You probably want to do something like the following:

```
void fieldinfo::RandomizeMonsterMovement()
{
    for(int i = 0; i < amountEnemies; i++)
    {
        // Clears the current position.
        map[tempPosX[i]][tempPosY[i]] = empty;

        // Updates the enemy position.
        const int movement = rand() % 4;
        switch(movement)
        {
        case 0:
            tempPosX[i]++;
            break;
        case 1:
            tempPosX[i]--;
            break;
        case 2:
            tempPosY[i]++;
            break;
        case 3:
            tempPosY[i]--;
            break;
        }

        // Updates the map in the new position.
        map[tempPosX[i]][tempPosY[i]] = enemy;
    }
}

```

I'm not really sure what you tried to accomplish with `MposX` and `MposY`...

Anyways, I've got a basic example program with a single enemy moving around here: https://onlinegdb.com/HknD1eeQG

Please refer to my previous answer on how to improve the general movement system to handle corner cases in a much more improved manner.

---
Tags: c++
---


# Question
Title: Problem with FPS camera in Software Renderer
I am currently creating a software renderer (I know they aren't particularly useful anymore, it is purely from a knowledge and learning standpoint). I am using GLM and following OpenGL rules(as GLM is designed for OpenGL).

It's currently pretty basic, just a cube being rendered as either a pixel for each vertex or as a wireframe. Everything was going fine with it till I implemented camera controls. The camera works fine until there is a model directly behind it in the world space. The model behind the camera will be rendered, but flipped (hard to tell which axis it has been flipped on due to it being wireframe). The controls for moving forward and back become inverted. If I put one object in front of the camera and one behind, they are both visible but when the camera moves forward one model moves closer while the other moves further away.

I am not sure if this is a bug or a limitation of the mathematics involved. From what I can tell it is a problem with the perspective division (which is being handled by GLM). It seems that when the camera crosses the Z of an object, it gets flipped. If I spin the camera around the object everything is fine, this only happens when the object is behind the camera. Is this likely to be a bug in my code, or is this normal and anything not in the camera's field of view needs to be culled to stop this happening? (I know things will need to be culled at some point for performance anyway).

The code is a mess at the moment so I am just cleaning it up so it is readable, in case this is likely a bug in my code.

# Answer
Perspective projection as you have probably implemented it is a pure mathematical transformation. It warps your world space by making all of the lines orthogonal to your viewing plane cross at the camera's position.

In the figure z- would be in front of the camera, and z+ would be behind. But the transformation does not have these concepts: if you extrapolate by continuing the lines "behind" the camera, you'll see that a second viewing frustum appears. Since the lines have crossed, it is inverted (rotated by 180°, in fact).

This means that you need to implement the distinction between "front" and "back" yourself, by clipping what falls bahind the camera.

Note: if you haven't got there yet, the *near* and *far* clipping planes are used when doing depth buffering. They put limits on the closest and furthest object you can see, so that the distance values can be normalized and stored without losing too much precision.
> 2 votes

---
Tags: c++, rendering, camera, rotation, glm
---


# Question
Title: Why are the randomly generated numbers not random?
I'm trying to make a game where the damage you deal is rolled by a dice. It all works. However, it keeps on giving the same values in a row so it isn't entirely random

```
ini_open("Health.ini");
attack = ini_read_real( "Attacks", "Felix", 0);
ini_close();
global.damage=0
repeat(attack){
global.damage=irandom(6)
}

if (global.damage ==0){instance_create_depth(300, 400, 0, obj_numbers0)}
if (global.damage ==1){instance_create_depth(400, 400, 0, obj_numbers1)}
if (global.damage ==2){instance_create_depth(500, 400, 0, obj_numbers2)}
if (global.damage ==3){instance_create_depth(600, 400, 0, obj_numbers3)}
if (global.damage ==4){instance_create_depth(700, 400, 0, obj_numbers4)}
if (global.damage ==5){instance_create_depth(800, 400, 0, obj_numbers5)}
if (global.damage ==6){instance_create_depth(900, 400, 0, obj_numbers6)}

```

The attack value is 1 because it is only one dice that is used for damage for now. The software I am using is Game Maker Studio 2

# Answer
> 5 votes
This is intended:

> NOTE: This function will return the same value every time the game is run afresh due to the fact that GameMaker: Studio generates the same initial random seed every time to make debugging code a far easier task. To avoid this behaviour use `randomize` at the start of your game.

Check the reference here.

If you want to have it random every startup as well you'd have to call `randomize();` once. Check that reference here.

---
Tags: game-maker, random
---


# Question
Title: How to draw a circle with MonoGame Extended?
I can not figure this out and have basically no idea. I have already installed MonoGame.Extended through NuGet. I have heard you can draw basic shapes like circles with it, but where can I find the method?

# Answer
> 2 votes
It looks like you can use the SpriteBatch extensions provided in the API. https://github.com/craftworkgames/MonoGame.Extended/blob/develop/Source/MonoGame.Extended/ShapeExtensions.cs

They are extension methods and if you wish to use them as part of SpriteBatch, you will have to add the following at the top of your file where you want to use them

```
using MonoGame.Extended;
...
mySpriteBatch.DrawCircle(...)

```

Alternatively without using it as an extension method,

```
Monogame.Extended.ShapeExtensions.DrawCircle(spriteBatch, ...)

```

---
Tags: monogame
---


title: Why is the while loop an infinite loop?

text:
# Question
Title: Why is the while loop an infinite loop?
I do not know why this while loop is infinite, I've had to restart my computer about 15 times, trying to solve this problem.

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

public class CactusTrigger : MonoBehaviour
{

    public Animator anim;
    public EnemySpawner enemySpawner;
    public bool justToCheck;
    public GameObject AttackersHolder;
    // Use this for initialization
    void Start()
    {
        enemySpawner = FindObjectOfType<EnemySpawner>();
        AttackersHolder = GameObject.Find("Attackers");
        anim = GetComponent<Animator>();
        SetMyLaneSpawner();
        justToCheck = false;
    }

    void JustTo()
    {

        foreach (Transform child in AttackersHolder.transform)
        {
         //An infinite loop is going we need to fix it
            while (child != null)
            {
                if (justToCheck != true)
                {
                    justToCheck = true;
                }
            }

            justToCheck = false;

        }
        if (justToCheck)
        {
            anim.SetBool("underAttack", true);
        }
        else if(justToCheck)
        {
            anim.SetBool("underAttack", false);
        }
    }
    void Update()
    {
        JustTo();
    }
    void SetMyLaneSpawner()
    {
        EnemySpawner[] spawnerArray = GameObject.FindObjectsOfType<EnemySpawner>();

        foreach (EnemySpawner spawn in spawnerArray)
        {
            if (spawn.transform.position.y == transform.position.y)
            {
                enemySpawner = spawn;
                return;
            }
        }
        Debug.LogError("Can't find spawner");
    }
}

```

# Answer
Lets step through this:

```
foreach (Transform child in AttackersHolder.transform)

```

`child` is automatically non-null, therefor `child != null` evaluates to true.

```
    while (true)
    {
        //do stuff
    }

```

Annnd that's infinite. There's no code inside that while loop that ever triggers a break, modifies `child` or otherwise gets out of the loop (return, goto, etc).
> 5 votes

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


# Question
Title: How can I make the object when rotating to keep looking on the character/camera?
Not to look the character/camera direction but to look to the character/camera.

This is a screenshot of the object I'm rotating. And this is the face of the object and he is look at the camera(Looking at me).

The object is a child of a Camera and the Camera is child of a RigidBodyFPSController (1)

In the top of the script:

```
public float rotationSpeed;
private float x;
private int damping = 2;

```

In Update:

```
void Update()
    {
        if (Input.GetKey(KeyCode.R))
        {
            x += Time.deltaTime * rotationSpeed;
            objectToScale.transform.rotation = Quaternion.Euler(0, 0, x);
        }
        var lookPos = transform.position - objectToScale.transform.position;
        lookPos.y = 0;
        var rotation = Quaternion.LookRotation(lookPos);
        objectToScale.transform.rotation = Quaternion.Slerp(objectToScale.transform.rotation, rotation, Time.deltaTime * damping);
    }

```

Now when I press on R the object name NAVI is rotating but when I move the MainCamera around the NAVI object is not facing to me.

This is a screenshot when running the game first time the object is facing to me:

But when I'm pressing on R and the object is rotating it looks like the object is facing to the left and I see the object side:

Then I move the camera to the right he is rotating like I wanted facing to me:

And if I move the camera to the left when the object is rotating I see the object back:

But I want that each time the object is rotating that he will be facing to me.

The last screenshot showing the Hierarchy the RigidBodyFPSController (1) and the MainCamera as child and the NAVI as child of the MainCamera.

The script Change Scale is attached to the MainCamera and with this I'm rotating the NAVI.

The main goal what I want is simple. When I press on R rotate the object and always make the object facing to me.

I tried now in the Update when pressing R to do:

```
if (Input.GetKey(KeyCode.R))
        {
            x += Time.deltaTime * rotationSpeed;
            objectToScale.transform.rotation = Quaternion.Euler(0, 0, x);
            objectToScale.transform.LookAt(Vector3.forward);
        }

```

But now it's not rotating at all.

# Answer
> 1 votes
Since you want the object to look at the camera at all times and you've already made it it's child. It seems a bit redundant to me that you want it to change it's rotation again to look at you. This is of course assuming that the rotation code (with the Key R) that you've written was simply a test and not for the final build. Anyway, from what I understand, this is what you want: The object should look at the camera. You have the ability to rotate the object on its Z axis.

So after changing a few lines:

```
public GameObject objectToScale;
public float rotationSpeed;

private int damping = 2;
public float x;
private bool keyPressed = false;

void Update()
{

    if (Input.GetKey (KeyCode.R)) {
        x += Time.deltaTime * rotationSpeed;
        objectToScale.transform.localRotation = Quaternion.Euler (0, 0, x);
        keyPressed = true;
    }
    if (Input.GetKeyUp (KeyCode.R)) {
        keyPressed = false;
    }

    if (!keyPressed) {
        Quaternion newRotation = Quaternion.identity;
        objectToScale.transform.localRotation = Quaternion.Slerp (objectToScale.transform.localRotation, newRotation, Time.deltaTime * damping);
        x = objectToScale.transform.localRotation.z;
    }
}

```

I hope you get this to work.

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


# Question
Title: Why is it important to have more than one person creating a game?
Why is it important to have more than one person creating a game?

# Answer
> 2 votes
Depending on the scope of your game it comes down to what makes up for the final product.

You have

Mechanic/Gamelogic programmers
Engine programmers (in house development)
AI programmer
Concept artists
3D Artists
2D Artists
Music composers
Animators
game designers
narrative designers/writers
sound designers
tech & VFX artists
tools programmers
quality control
localisation
producers & project managers
Let's not forget the voice actors
Eh legal team too?

And then you probably have branches within those disciplines as well.

Unless you master all these skills and are super efficient at it, you don't need anyone else. But that's hardly the case. And if you take it upon yourself to do everything it will just take more time and effort.

If it's a small indie game that looks super simple you're probably fine on your own.

A medium sized game can be done by a small team.

For big games you have to consider all the additional people such as managers, marketing etc as well.

If you're using a full fledged engine many things are simplified for you. However you're still bound to creating each individual part ( art, music, code?).

# Answer
> -1 votes
I think there is a need for having more than one person creating a game because of there are three main tasks:

Art Music Programming

Which are so different between them.

Also as @Sidar said you could need marketing people to help you too.

---
Tags: game-design
---


# Question
Title: How to make colliders for a darts board in Unity?
I was wondering how to make a darts board in Unity?

Of course it doesn't make triangular objects, or non symmetrical boxes as far as I know, so I would make the board mesh in Blender or something like this.

But how would I be able to detect where a dart had hit the certain area? Until now I have only used box, sphere and capsule colliders

# Answer
> 2 votes
This seems have quite a few possible answers. But I'll take a quick stab at it. I think the key is probably to define the dart board mathematically (distance from center and angles of each area). Then use ContactPoint.point to figure out in area the dart hit as compared to the center of the bulls eye.

Unity docs for ContactPoint.point

https://docs.unity3d.com/ScriptReference/ContactPoint-point.html

And here's a thread that may be useful to get the angles calculated right: https://stackoverflow.com/questions/13458992/angle-between-two-vectors-2d

There's a million options for how to organize the data. I'd probably set up a small class that just stores start distance, end distance, start angle, end angle, and point value. Build an array with all the possible target areas then loop through it until a match is found (or not) and add the score.

---
Tags: unity, c#, collision-detection
---


# Question
Title: Mesh complexity vs Texture Size (Performance)
From a performance view, which is preferable:

* A higher detailed meshes with small textures (like 32x32 pixels) or
* A less detailed mesh with a bigger texture (like 1024x1024 pixels)?

---

Additional info. I'm making a low poly project. Since I'm only using big textures for "alpha FX" (simulating complex geometry just by erasing the alpha on faces), I wonder if this is a bad approach. I could add like 50~150 triangles per model to avoid using a higher texture per asset and made those "FX" directly on geometry (since erasing on a texture very small would look very bad)

Which is the "trend"? Which has more impact on performance?

Thanks.

# Answer
It depends on a lot of things:

* The GPU used,
* The memory bandwidth available,
* The bus bandwidth available,
* If your textures can be compressed,
* Where your bottleneck currently lies,
* What is acceptable for the target art style.

Generally, the cheaper the GPU the less memory bandwidth it has. They are also more limited in texturing units. More expensive and powerful GPUs will likely not be affected either way.

The extra cost of a vertex alpha (8 bits) or vertex colour (16 or 32 bits) is compensated by allowing you to remove the texture completely along with it's UV coordinates and just use vertex colour.

As the texture would be modified dynamically it's unlikely to be compressed. It's doable but a lot more work is involved. So most likely the cost of texels + UVs would be the same as or more than vertex colours.

So there's no added memory bandwidth to your vertex data and you get rid of an entire texture lookup.

You can also delete triangles completely instead of making them transparent.

All that's left to account for is the added geometry to bring back details as needed.

There is a cost to transforming and binning triangles but this also depends on the GPU.

You will have to test and see where your bottleneck is.
> 2 votes

# Answer
**It depends**

There are other variable factors, such as coverage of the mesh on-screen, overdraw, whether you're bottlenecked elsewhere on vertex vs fragment performance, and whether your target hardware prefers vertex or fragment performance, that it's impossible to give a one-size-fits-all answer.

**Benchmark both on your target hardware and make your decision based on that**.
> 0 votes

---
Tags: 3d, textures, performance, mesh
---


title: Smoothly move camera to follow player

text:
# Question
Title: Smoothly move camera to follow player
I'm trying to move my camera with the player but I'm trying to move/lerp over time, so that the camera allows the player to get a small radius from the center as it gets up to speed, and the camera will "catch up" when the player slows or stops.

I've written code that increases the movement speed of the camera the further the player gets - ideally you should only be able to go a set radius before the camera just "follows" you.

This works, except it's too jittery when the player is moving. The larger the distance, the more noticeable the jitter. I've tried different speeds but nothing seems to satisfactorily solve the issue.

**`Player.cs Update()`:**

```
var moveHorizontal = player.GetAxis("Move Horizontal") * rigidBody.mass;
var moveVertical = player.GetAxis("Move Vertical") * rigidBody.mass;

var forceDirection = new Vector3(moveHorizontal, 0, moveVertical);

rigidBody.AddForce(forceDirection);

```

**Camera's `Follow.cs`:**

```
void Awake() {
    offset = transform.position - player.transform.position;
}

void LateUpdate() {
    var dist = Vector3.Distance(transform.position - offset, player.transform.position);

    if (dist != 0) {
        transform.position = Vector3.Lerp(
            transform.position,
            player.transform.position + offset,
            Time.deltaTime * dist * speed);
    }
}

```

Per the first answer, I've also tried setting my player's rigibody to "Interpolation" mode, and I update my follow script with the suggested smoothing code:

```
// Compute our exponential smoothing factor.
float blend = 1f - Mathf.Pow(1f - followSharpness, Time.deltaTime * 30f);

transform.position = Vector3.Lerp(
    transform.position,
    player.transform.position + offset,
    blend);

```

This works initially, but I get awful jitter once my player collides with an object. Plus, interpolation mode appears more susceptible to framerate drops but that's an aspect of my game I haven't worked on yet.

# Answer
> 6 votes
This style of using Lerp:

```
current = lerp(current, target, sharpness)

```

is an exponential moving average. So if we want to correct it for `deltaTime`, a linear adjustment won't do. We need an exponential adjustment.

```
public float followSharpness = 0.1f;

void LateUpdate() {
     // No need for the "if" - we'll practically never reach exactly 0 distance anyway.

     // Compute our exponential smoothing factor.
     float blend = 1f - Mathf.Pow(1f - followSharpness, Time.deltaTime * 30f);

     transform.position = Vector3.Lerp(
            transform.position,
            player.transform.position + offset,
            blend);
}

```

You can verify that as `deltaTime` approaches zero, so does our `blend` factor. When `deltaTime` is exactly 1/30, the `blend` factor is exactly equal to `sharpness`. When `deltaTime` is 2/30 (eg. we missed a VBlank when trying to hit 30 FPS), the blending result is the same as if we'd performed a blend with `sharpness` on two consecutive frames.

You might not find you need to scale the follow sharpness by distance, since an exponential moving average already adjusts its speed according to its distance from the new target - moving slowly when close, and faster when further away.

# Answer
> 0 votes
This is done very easily and the Youtube Channel "Brackeys" has a nice tutorial on how to achieve such an effect. You can find a link to that video here.

To sum up what was in the video:

* Create a script and put it on the camera you want to follow your player.
* Setup a couple public variable which will allow the camera to know which GameObject to follow as well as float variable for desired smooth speed, and a Vector3 for the offset.

*Should like something like this:*

```
public Transform target;

public float smoothSpeed = 15f;

public Vector3 offset;

```

We then set use Unity's built in LateUpdate() function, this allows for all of the other object's to update first, then calls this function. *(We want to move the camera after everything else already has.)*

* Then in our LateUpdate() function we write a line of code to contain the Vector3 of the desired position we have, as well as smoothing that position. Finally we set the camera position equal to the smoothed position variable.

The way we smooth our position is using a function Unity provides us with called **Lerp.** It allows us to interpolate linearly between values based on a time value from 0 to 1.

```
void LateUpdate()
{
    Vector3 desiredPosition = transform.position + offset;
    Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed * Time.deltatime);
    transform.position = smoothedPosition;
}

```

There you go, that's all there is to it.

Final notes:

* Make sure to set the target gameobject in the editor, this should be your player or object you want to follow.
* To achieve the radius effect you want, play around with the smoothspeed.
* If you are still getting jittey movement or updates, change LateUpdate() to FixedUpdate(). Although this is not the best practice, it usually will achieve a very smooth effect and will not have jitter in the movements because we are moving the time of updating the camera to what other people call the 'Physics Loop'.

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


# Question
Title: Suggestions on how to achieve circular "hole" in environment
I'm working on a 2D Sidescroller and I'm wanting to achieve a object that when activated it creates a port-hole to the sprites underneath, giving the appearance of the object "cleansing" the area.

*Edited image showing the desired effect*

At this point I have no idea how to achieve this and am after suggestions, thanks!

# Answer
Several options here.

If your "cleansing area" thing is "just" a color swap, you can do that using a custom shader that will take original pixel colors and swap them with a given palette. Then it'll change purple pixels to light green, dark blue to light blue...

If color swapping is not what you're looking for and you have actually two versions of the same level (one dark, one clean), you have to have the both version in your actual game scene. Using two cameras, one for dark and one for light. The light camera will render into a render texture instead of the screen. With that render texture you'll be able to only display part of it. Using a custom shader you'll be able to show what's around the player or any part you want.
> 1 votes

# Answer
I would use a sprite mask for this, maybe several depending on exactly what you want to do. You would need multiple sprites, for example, a "dirty" trashcan and a "clean" trashcan both at the same position but they respond to the mask differently. The "dirty" sprite would be visible outside the mask, and the "clean" sprite visible inside the mask.

https://docs.unity3d.com/Manual/class-SpriteMask.html

This sounds like a really cool idea, I hope it works out well for you.
> 0 votes

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


# Question
Title: How to work out minimum distance to decelerate and stop at a point
I am building a game in C# using XNA.

I am currently trying to get a character to always travel to the middle of the map which is located a point (0,0,0). I want the character to accelerate to the middle and then decelerate before it hits the middle so it will come to a stop at (or very close to) the middle.

Rate of acceleration does not change. Velocity is a Vector3 and for the purpose of this i will only worry about the X axis.

What I am trying to work out is at what point should I start decelerating to come to a stop in the middle depending on velocity and position.

I have tried to simplify the following code as much as possible

**In My Update Method I basically call two methods**

```
    Move(gameTime);
    HandleAcceleration();

```

**Handle Acceleration is very simple**

```
 this.Transform.TranslateIncrement = this.Velocity;

```

**Move method**

```
protected void Move(GameTime gameTime)
{
    //GetDirection just returns 1 or -1 to accelerate the appropriate direction
    int direction = GetDirection((int)this.Transform.Translation.X);

    //This Is where I have trouble With GetMinDecelerationDistance()
    if (GetDistanceToMiddle() <= GetMinDecelerationDistance())
    {
        //Pass in -direction to decelerate(Accelerate opposite direction)
        Accelerate(gameTime, AxisDirectionType.X, -direction);
    }
    else
    {
        Accelerate(gameTime, AxisDirectionType.X, direction);
    }
}

```

**My Accelerate Method**

```
    VelocityX += (this.acceleration * gameTime.ElapsedGameTime.Milliseconds) * direction;

    this.Velocity = (new Vector3(VelocityX, 0, 0));

```

The problem I am having is how to implement the **GetMinDecelerationDistance()** Method. I know I need to do something with the Velocity and the position but I have no Idea what. Keep in mind the acceleration rate is always the same and the middle is at point 0.

Basically my question is how do I implement GetMinDecelerationDistance() given that I know the Velocity and position, Acceleration is constant and I want to stop at point 0.

# Answer
Considering for now the case where all our movement is in the line joining the target and destination (in 2+ dimensions this becomes much more complicated)...

Let's look at our formulas for position & velocity as functions of time under constant acceleration.

$$\begin{array}{r|l} {p(t) = p\_0 + v\_0 \cdot t + \frac a 2 \cdot t^2 \\ v(t) = v\_0 + a\cdot t }& \begin{align} p(t) &= \text{position at time t} \\ p\_0 &= \text{initial position} \\ v(t) &= \text{velocity at time t} \\ v\_0 &= \text{initial velocity} \\ a &= \text{constant acceleration} \end{align}\end{array}$$

If we imagine we're starting at the destination point, at rest, and accelerating away as fast as we can, then we can work out the relationship between our position and the velocity we can reach by the time we cross that mark.

$$\begin{array}{l|l} {p(t) = \frac a 2 t^2 \\ p(t) = \frac {a^2 t^2} {2a} \\ p(t) = \frac {\left(at\right)^2} {2a} \\ p(t) = \frac {v(t)^2} {2a} } & { v(t) = a t \\ v(t) = \pm\sqrt{a^2t^2} \\ v(t) = \pm \sqrt{2a \cdot \frac a 2 t^2} \\ v(t) = \pm \sqrt{2a \cdot p(t)}} \end{array}$$

Flipping this around, this gives us our limiting position-velocity - the fastest we can possibly be going at a given distance and still decelerate to a stop as we reach the target.

That lets us partition our position-velocity state space like so:

We can look at our initial position & velocity to determine which of three cases we're in:

* **viable**: we can accelerate toward the target for some time \\$t\_a\\$ (possibly zero, if we're right on the curve \\$p = \frac {v^2} {2a}\\$), then decelerate until we come to a stop exactly on the target.
* **overshoot**: we're approaching the target too fast to stop in time. We need to start decelerating immediately, overshoot a little before coming to a stop, continue accelerating back toward the target, and ultimately hit the approach curve from the other side and decelerate again until we come to a rest at the target.
* **wrong way**: we need to kill our outward velocity first, then continue accelerating toward the target to hit the approach curve on the near side, like in the viable case.

In each of these cases, we want an initial acceleration for time \\$t\_1\\$, then a final deceleration for time \\$t\_2\\$

---

If we're in the overshoot (\\$v\_0 * -sign(p\_0) \> \sqrt{2a \cdot p\_0}\\$) or wrong way (\\$sign(v\_0) = sign(p\_0)\\$) cases, we first need to decelerate to a stop, in time \\$t\_d = \frac {\left| v\_0 \right|} a\\$, at post-deceleration position \\$p\_d = p\_0 + v\_0 t\_d - sign(v\_0) \frac a 2 t\_d^2\\$. Now we're in the viable case and we can proceed as though we started at position \\$p\_d\\$ with velocity 0, and add \\$t\_d\\$ to the \\$t\_1\\$ value we get below.

---

In the viable case, we can find the closest position we could reach with our current velocity before needing to slow down, \\$p\_L =\frac {v\_0^2} {2a}\\$, and accelerate until we're halfway there. This brings us exactly onto the approach curve where we can begin decelerating: after crossing the remaining half the distance to \\$p\_L\\$, we'll again be moving with our original velocity since our acceleration and deceleration cancel each other out.

So our turnaround point when we begin decelerating is \\$p(t\_1) = \frac {p\_0 + p\_L} 2\\$, and we can substitute this into the formula for \\$p(t)\\$ to solve for \\$t\_1\\$ using quadratic formula.

Lastly, \\$t\_2 = \frac {v\_0} a\\$

---

This all relates to continuous physics. For discrete timesteps, we'll get some small errors (depending on your physics timestep and integration method), particularly from the frames where the acceleration may change midway through a timestep (flipping direction at the turnaround point, or ceasing upon reaching the target). You can adjust for this by applying a time-weighted average of the acceleration over the frame duration, or by clamping small errors upon arrival.
> 2 votes

---
Tags: c#, xna, physics
---


# Question
Title: Using VMs for game development or physical machine?
When I was doing web development, I would develop websites inside my virtual machines, which had all tools and packages downloaded on them and ready to go. I quite liked this approach to development since I didnt have to clutter up my Host OS with a bunch of different packages and other other software only needed for development.

So for game development, given its focus on speed and much higher demand for system resources, is developing in VMs viable? Or are there any gotcha's or other difficulties when using VMs that could deter someone from developing and testing a game within a VM vs directly on the physical computer hardware? Mainly wondering about speed and if the extra abstraction layer of a VM would cause any significant slow down of game testing (having slower or wonky FPS or things of that nature)?

EDIT: Also, for more info, I'm currently developing on my windows 10 PC with a core i7 processor. I can switch to the built in hypervisor (hyper-v) at any time.

# Answer
If your goal is to use a separate environment for isolation of libraries, dependencies, etc. then yes, you can use either VMs or containers for this purpose. However, they're not without their caveats.

**Virtual Machines** add the overhead of an entire additional operating system, but it much closer mimics what a user would see on their own environment. So, you would need a powerful enough computer to run two operating systems: one for your development, and one for executing your game.

**Containers** are much lighter weight (and you can run containers on Windows, now, too!) but with the caveat is that they're not exactly a full replica of the target environment.

With either of these solutions, keep in mind that it's a bit of a project to get high-performance video as well as audio (with specific hardware acceleration that you might want), as they typically abstract specific hardware and treat it as more generic hardware.

It is *likely possible* to address these issues (YMMV, depends on specific manufacturers of your audio/video hardware, drivers and compatibility, etc.), but some folks have issues running games in VMs and containers for exactly this reason.

For example, speaking of Hyper-V since you brought it up, see this post:

> > I setup Win 7 in a windows 2008 r2 x64 with hyper-v but I can't add any sound device in win7 VM, Would somebody help me?
>
> Hyper-V doesn't provide a virtual audio device. If you want audio, you need to use RDP to get the virtual audio support working.

However, VMConnect (likely much more recent than the earlier post) appears to allow you to use local devices in Hyper-V, such as USB drivers and audio hardware.

You will likely need to spend some time investigating whether it's possible to support the specific hardware devices that you have in either VMs or containers, so while that would be valuable (I agree with you on the benefits), this is definitely an issue to be aware of, and budget time for, if you're interested in going down this route.

If you do manage to make this work, please write up a blog post and/or share your source code in a GitHub repo so that others can find it and benefit from this work in the future.
> 4 votes

---
Tags: testing, virtual-machines
---


# Question
Title: Monogame pipeline tool: "Build failed: 1 is not a supported code page."
I've previously done some coding with Monogame 3.6 in VS 2015 on Windows 10 without any problems, including using the pipeline tool. Last week I was forced to reinstall my whole system and now have VS 2017 + Monogame 3.6. Suddenly the pipeline tool does not do anything anymore, instead of a report on the build success of the various items i only get the following output (which only shows up when I disable the "filter output" setting):

> Build failed: 1 is not a supported code page.
> Parameter name: codepage

I'm rather lost with this one and google did not return anything useful. Since I reinstalled the whole system I guess it could also be something missing which is not directly installed by VS or Monogame and got on my old system some other way.

Any ideas what is going wrong here?

# Answer
This might be depending on the Regional Settings - Language.
So it's possible that during the reïnstall, your regional settings have changed.

Setting it back to the regional setting where you have developed your game with will fix your problem.
> 2 votes

# Answer
A quick look through Pipeline.exe reveals that the build action executes code equivalent to the following:

```
System.Text.Encoding.GetEncoding(System.Globalization.CultureInfo.CurrentCulture.TextInfo.OEMCodePage);

```

Which as far as i can tell, relates to how messages are printed in the output log. (They originate from another native process, presumably MGCB.exe)

Try running the above line of code any C# environment and you should be able to reproduce the error.

You can try and change the locale as according to the other answer, but that solution has a lot of side effects, as it affects all other processes as well, and in my case it did not work anyway.

An alternative solution is to modify the assembly: In pipeline.exe - Module: Monogame.Tools.Pipeline - Class: PipelineController - Method: DoBuild - Around Line: 0x0089

Replace:

```
call class [mscorlib]System.Globalization.CultureInfo [mscorlib]System.Globalization.CultureInfo::get_CurrentCulture()
callvirt instance class [mscorlib]System.Globalization.TextInfo [mscorlib]System.Globalization.CultureInfo::get_TextInfo()
callvirt instance int32 [mscorlib]System.Globalization.TextInfo::get_OEMCodePage()

```

with:

```
ldc.i4.0

```

Turning:

```
System.Text.Encoding.GetEncoding(System.Globalization.CultureInfo.CurrentCulture.TextInfo.OEMCodePage);

```

Into:

```
System.Text.Encoding.GetEncoding(0);

```

Which is the system default encoding instead of the OEM encoding.
> 1 votes

---
Tags: monogame
---


title: How to change pre-splash image for iOS?

text:
# Question
Title: How to change pre-splash image for iOS?
When I launched my game on my iPad, the screen first displayed a faulty splash image with a black lower half momentarily, before displaying the normal splash image.

No matter what I tried, I couldn't get rid of this faulty 'pre-splash image'. I have tried the following:

1. Entered my Plus package serial number and updated my seat in Unity.
2. Deleted and left all splash images blank in Unity.
3. Checked all the LaunchScreen-XXX.png images in Xcode.
4. Checked the files referenced by Images.xcassets in Xcode.
5. Changed all the above images to a completely black image. Still, the old faulty picture would appear.
6. Cleared all the data and installation files on my iPad.
7. Deleted General \> Launch Images Source.

I wonder where Xcode kept the faulty image.

I am using Unity 5.5.1 and Xcode 9.2.

Could someone please help?

# Answer
I restarted the iPad and now it is working! I guess the issue had to do with the memory cache.
> 0 votes

---
Tags: unity, ios, xcode, launcher, splash-screen
---


title: Calculate movement in 2d

text:
# Question
Title: Calculate movement in 2d
In 2d, I have a ship that I want to have move to specific coordinates. I've used Sidar's answer in How do I calculate how an object will move from one point to another? to get something that works allright, but it overshoots and at the end the ship just jumps around the destination. Basically the speed is 10, but the destination isn't a multiple of 10, so it can never be reached. What would be a good way to prevent that ?

Currently the function looks like that (sorry, Haskell, but it should be easy enough to understand) :

```
  let n = normalize $ dest ^-^ cur in
  let (V2 dx dy) = n ^* speed in
  (curx + dx, cury + dy)

```

That's basically what's in Sidar's post, substract the destination coordinates with the current coordinates, normalize that, then multiply it by the speed and add that vector to the current coordinates to get the new ones. The question is : is there a way to prevent that from overshooting the destination, ideally without adding an if for each direction for x and y (that would be a bit ugly, but I don't see how else) ?

# Answer
> 2 votes
I'm not 100% sure if this is what you mean, but a simple check on the remaining distance might be what you're looking for:

```
if ((dest - cur).length < speed)
{
    cur = dest;
}
else
{
    cur.x += dx;
    cur.y += dy;
}

```

(Not Haskell but should be pretty easily readable). Essentially we check if we're "close enough" (meaning that we'd overshoot if we didn't adjust), and just position ourselves at the target if we are. Otherwise we just do the regular movement that you had already figured out.

---
Tags: 2d, coordinates
---


# Question
Title: Moving texture according to position in shader
**Divinity Original Sin** have beautiful particle effect , When I move around game I see galaxy through particle that move according to my position.how can I make like it?

you can see this effect here: https://youtu.be/4fIpQZ2sIAY

# Answer
usually uv coordinate used for uvmapping but here Instead of using uvcoordinate use position!

```
Shader "Custom/ViewMode1"
{
    Properties
    {
        _MainTex ("Base (RGB)", 2D) = "white" {}
        _Color ("_Color", Color) = (1,1,1,1)
        _Size("Size",Vector) = (1,1,1,1)
    }

    SubShader
    {
        Tags {"Queue"="Transparent" "IgnoreProjector"="true" "RenderType"="Transparent"}
        ZWrite Off Blend SrcAlpha OneMinusSrcAlpha Cull Off

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma fragmentoption ARB_precision_hint_fastest
            #include "UnityCG.cginc"

            struct appdata_t
            {
                float4 vertex   : POSITION;
                float4 color    : COLOR;
                float2 texcoord : TEXCOORD0;
            };

            struct v2f
            {
                half2 texcoord  : TEXCOORD0;
                float4 vertex   : SV_POSITION;
                fixed4 color    : COLOR;
            };

            sampler2D _MainTex;
            fixed4 _Color;
            float _Speed;
            float4 _Size;

            v2f vert(appdata_t IN)
            {
                v2f OUT;
                OUT.vertex = UnityObjectToClipPos(IN.vertex);
                OUT.texcoord = IN.texcoord;
                OUT.color = IN.color;
                return OUT;
            }

            float4 frag (v2f i) : COLOR
            {
                float2 screen = i.vertex.xy/_ScreenParams.xy;
                float4 tex = tex2D(_MainTex, screen /_Size)*i.color;
                return tex*_Color;
            }
            ENDCG
        }
    }
}

```

also you can use `Tex2Dproj` try this:

```
Shader "Custom/ViewMode2"
{
    Properties{
        _MainTex("MainTex",2D) = "white"{}
        _Scale("Scale",Vector) = (1,1,1,1)
    }
    SubShader
    {
        // Draw ourselves after all opaque geometry
        Tags{ "Queue" = "Transparent" }

        // Grab the screen behind the object into _BackgroundTexture
        GrabPass
        {
            "_BackgroundTexture"
        }

        Blend SrcAlpha OneMinusSrcAlpha
        // Render the object with the texture generated above, and invert the colors
        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            struct v2f
            {
                float4 grabPos : TEXCOORD0;
                float4 pos : SV_POSITION;
            };

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

            v2f vert(appdata v) {
                v2f o;
                // use UnityObjectToClipPos from UnityCG.cginc to calculate
                // the clip-space of the vertex
                o.pos = UnityObjectToClipPos(v.vertex);
                // use ComputeGrabScreenPos function from UnityCG.cginc
                // to get the correct texture coordinate
                o.grabPos = ComputeGrabScreenPos(o.pos);

                return o;
            }

            sampler2D _BackgroundTexture;

            half4 frag(v2f i) : SV_Target
            {
                half4 bgcolor = tex2Dproj(_MainTex, i.grabPos/_Scale);
                return bgcolor;
            }
            ENDCG
        }
    }
}

```

```
Shader "Smkgames/Particles/OriginalSin" {
    Properties {
        _MainTex ("Particle Texture", 2D) = "white" {}
        _BackGround("BackGround",2D) = "white"{}
        _InvFade ("Soft Particles Factor", Range(0.01,3.0)) = 1.0
        _Scale("Scale",Vector) = (1,1,1,1)

        _Hue ("Hue", Range(0, 1.0)) = 0
        _Saturation ("Saturation", Range(0, 1.0)) = 0.5
        _Brightness ("Brightness", Range(0, 1.0)) = 0.5
        _Contrast ("Contrast", Range(0, 1.0)) = 0.5
    }

    Category {
        Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" "PreviewType"="Plane" }
        Blend One OneMinusSrcColor
        ColorMask RGB
        Cull Off Lighting Off ZWrite Off

        SubShader {
            GrabPass
            {
                "_BackgroundTexture"
            }
            Pass {

                CGPROGRAM
                #pragma vertex vert
                #pragma fragment frag
                #pragma target 2.0
                #pragma multi_compile_particles
                #pragma multi_compile_fog

                #include "UnityCG.cginc"

                sampler2D _MainTex,_BackGround;
                fixed4 _TintColor;

                struct appdata_t {
                    float4 vertex : POSITION;
                    fixed4 color : COLOR;
                    float2 texcoord : TEXCOORD0;

                };

                struct v2f {
                    float4 grabPos : TEXCOORD3;
                    float4 vertex : SV_POSITION;
                    fixed4 color : COLOR;
                    fixed4 hsbc : COLOR1;
                    float2 texcoord : TEXCOORD0;
                    UNITY_FOG_COORDS(1)
                    #ifdef SOFTPARTICLES_ON
                    float4 projPos : TEXCOORD2;
                    #endif
                };

                float4 _MainTex_ST;
                float4 _Scale;

                //__________Hue Saturation Brightness Contrast___________

                fixed _Hue, _Saturation, _Brightness, _Contrast;

                inline float3 applyHue(float3 aColor, float aHue)
                {
                    float angle = radians(aHue);
                    float3 k = float3(0.57735, 0.57735, 0.57735);
                    float cosAngle = cos(angle);

                    return aColor * cosAngle + cross(k, aColor) * sin(angle) + k * dot(k, aColor) * (1 - cosAngle);
                }

                inline float4 applyHSBCEffect(float4 startColor, fixed4 hsbc)
                {
                    float hue = 360 * hsbc.r;
                    float saturation = hsbc.g * 2;
                    float brightness = hsbc.b * 2 - 1;
                    float contrast = hsbc.a * 2;

                    float4 outputColor = startColor;
                    outputColor.rgb = applyHue(outputColor.rgb, hue);
                    outputColor.rgb = (outputColor.rgb - 0.5f) * contrast + 0.5f;
                    outputColor.rgb = outputColor.rgb + brightness;
                    float3 intensity = dot(outputColor.rgb, float3(0.39, 0.59, 0.11));
                    outputColor.rgb = lerp(intensity, outputColor.rgb, saturation);

                    return outputColor;
                }
                //_______________________________________________________________________

                v2f vert (appdata_t v)
                {
                    v2f o;
                    o.vertex = UnityObjectToClipPos(v.vertex);
                    #ifdef SOFTPARTICLES_ON
                    o.projPos = ComputeScreenPos (o.vertex);
                    COMPUTE_EYEDEPTH(o.projPos.z);
                    #endif
                    o.color = v.color;
                    o.texcoord = TRANSFORM_TEX(v.texcoord,_MainTex);
                    UNITY_TRANSFER_FOG(o,o.vertex);
                    o.grabPos = ComputeGrabScreenPos(o.vertex);
                    o.hsbc = fixed4(_Hue, _Saturation, _Brightness, _Contrast);

                    return o;
                }

                sampler2D_float _CameraDepthTexture;
                float _InvFade;

                fixed4 frag (v2f i) : SV_Target
                {
                    #ifdef SOFTPARTICLES_ON
                    float sceneZ = LinearEyeDepth (SAMPLE_DEPTH_TEXTURE_PROJ(_CameraDepthTexture, UNITY_PROJ_COORD(i.projPos)));
                    float partZ = i.projPos.z;
                    float fade = saturate (_InvFade * (sceneZ-partZ));
                    i.color.a *= fade;
                    #endif

                    half4 col = i.color * tex2D(_MainTex, i.texcoord);
                    col.rgb *= col.a;
                    UNITY_APPLY_FOG_COLOR(i.fogCoord, col, fixed4(0,0,0,0)); // fog towards black due to our blend mode
                    half4 bgcolor = tex2Dproj(_BackGround, i.grabPos/_Scale);
                    float4 hsbcColor = applyHSBCEffect(bgcolor, i.hsbc);
                    hsbcColor.rgb *= col.a;

                    return hsbcColor;
                }
                ENDCG
            }
        }
    }
}

```
> 13 votes

---
Tags: unity, shaders, shaderlab
---


title: How to improve my battle system?

text:
# Question
Title: How to improve my battle system?
I'm coding this little game and I need help with my battle system. I don't have any idea how to improve my system. I made it like RANDOM\_VALUE VS RANDOM\_VALUE. It's a console game, so I need console BS ideas.

```
    #include <iostream>
    #include <windows.h>
    using namespace std;

    int main () {
      SetConsoleTitle("Battle game");
      int i, y, jidlo, soused, random, uder1;

      ////Battle system
      random = rand() % 5 + 1;
      uder1 = rand() % 8 + 1;

      system("pause");
      system("CLS");
      cout << "BOJ ZACAL!"<< endl;
      system("pause");
      system("CLS");

      if(uder1 >= random) {
        system("pause");
        system("CLS");
        cout << "You won and earned 3 crowns!" << endl;
      }
      else {
        cout << "You lost!" << endl;
        system("restart");
      }
      system("pause>nul");
      return 0;
    }

```

# Answer
I could think of a few ways to "improve" this system. It's functional as is so nothing is really needed but here are a few ideas.

1. Give each attacker some value of hit points (if you imagine a game like Risk we'd talk about armies). Then loop through the attack as you have it now for each round the loser looses some hit points until one of them reaches zero. That give a nice look too with a "You took 2 damage and have 7 health remaining." or "You dealt 2 damage, your opponent has 9 health remaining." or what have you.
2. Each attacker could have a separate attack and defend "roll" in that way each attacker would attack every round so it would be possible for both to take damage.

This list could quite literally go on forever. But hopefully these ideas would provide some inspiration.
> 1 votes

---
Tags: game-mechanics
---


# Question
Title: Unable to get Box2dlights to cast shadows
I'm trying to use box2dlights to add lighting to my game and I have everything working except I am unable to have shadows cast with my box2d bodies. I also have collision working using category/maskBits with my various objects and I'm trying to apply the same strategy to box2dlight filters. You can see how the light just passed through the body.

EDIT: I think I may have discovered why the lights are not colliding with my box2d bodies. When I define the body shapes using "real world" scale pixel coordinates, the lights cast shadows properly, but I lose collision since the bodies are defined at pixel scale as opposed to the box2d scale I have defined. Does anyone know why the box2dlights are using real world scale?

Here is my RayHandler Setup

```
RayHandler.useDiffuseLight(false);
rayHandler = new RayHandler(world);
rayHandler.setAmbientLight(.5f, .5f, .2f, 1f);
rayHandler.setBlurNum(1);
rayHandler.setShadows(true);

```

I have a PointLight that is positioned in the center of the screen.

```
PointLight pl = new PointLight(game.rayHandler, 128);
pl.setDistance(1000);
pl.setPosition(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2);
pl.setColor(Color.WHITE);
pl.setSoftnessLength(0);
Filter filter = new Filter();
filter.categoryBits = B2DVars.CATEGORY_LIGHT; // Value listed below
filter.maskBits = B2DVars.MASK_LIGHT;         // Value listed below
pl.setContactFilter(filter);

```

Also, my body is defined as

```
body = world.createBody(squareBodyDef);
PolygonShape squareShape = new PolygonShape();
squareShape.setAsBox(b2dWidth / 2, b2dWidth / 2, new Vector2(squareBodyDef.position.x * WORLD_TO_BOX, squareBodyDef.position.y * WORLD_TO_BOX), 0f);
body.setUserData(this);

FixtureDef fdef = new FixtureDef();
fdef.shape = squareShape;
fdef.density = 10.0f;
fdef.friction =  0.1f;
fdef.restitution = 1.15f;
fdef.filter.categoryBits = CATEGORY_SQUARE_OBJECTIVE; // Value listed below
fdef.filter.maskBits = MASK_SQUARE; // Value listed below

body.createFixture(fdef).setUserData(this);
squareShape.dispose();

```

Finally, my box2d filtering constants

```
public static final short CATEGORY_BALL = 1;
public static final short CATEGORY_LINE = 2;
public static final short CATEGORY_WALL = 4;
public static final short CATEGORY_SQUARE_OBJECTIVE = 8;
public static final short CATEGORY_TRIANGLE_OBJECTIVE = 16;
public static final short CATEGORY_LIGHT = 32;

public static final short LIGHT_GROUP = 1;

public static final short MASK_BALL =
                CATEGORY_LINE |
                CATEGORY_WALL |
                CATEGORY_SQUARE_OBJECTIVE |
                CATEGORY_TRIANGLE_OBJECTIVE;

public static final short MASK_LIGHT =
                CATEGORY_LINE |
                CATEGORY_SQUARE_OBJECTIVE |
                CATEGORY_TRIANGLE_OBJECTIVE |
                CATEGORY_WALL;

public static final short MASK_SQUARE =
                CATEGORY_BALL |
                CATEGORY_LIGHT;

public static final short MASK_WALL = -1

```

I've been going non-stop for about 3 days trying to solve this problem to no avail. Any help is appreciated!

# Answer
The problem was that I was using the projection matrix from my main camera with the RayHandler. My main camera by default is in world/pixel units where 100 pixels = 1 box2d meter, but its projection matrix should have been in box2d units (meters).

Based on information from this post on the libgdx reddit forum, I decided to solve the problem by creating a separate camera for my box2dlights. Here was the solution I used...

```
// Create a separate camera for box2dlights
OrthographicCamera b2dCam = new OrthgraphicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
b2dCam.setToOrtho(false);
b2dCam.update();

```

Use the camera above with the RayHandler after the box2d **world.step(..)** call. This camera needs to be scaled to the box2d world.

```
// BOX_TO_WORLD = 100 and WORLD_TO_BOX = 0.01
rayHandler.setCombinedMatrix(b2dCam.combined.scale(BOX_TO_WORLD,BOX_TO_WORLD,BOX_TO_WORLD), b2dCam.position.x * WORLD_TO_BOX, b2dCam.position.y WORLD_TO_BOX, b2dCam.viewportWidth * b2dCam.zoom, b2dCam.viewportHeight * b2dCam.zoom);
rayHandler.updateAndRender();

```

Finally I needed to create my light source in box2d units...

```
PointLight pl = new PointLight(rayHandler, 128, Color.WHITE, 1500 * WORLD_TO_BOX, (Gdx.graphics.getWidth() / 2) * WORLD_TO_BOX, (Gdx.graphics.getHeight() / 2) * WORLD_TO_BOX);

```

The end result:
> 0 votes

---
Tags: java, libgdx, android, box2d, lighting
---


# Question
Title: libGDX, box2d, Ashley ECS - Collision Detection using Box2d does not work when using components with Ashley ECS
I've just recently learned of Ashley ECS while searching up tutorials on the libGDX wiki and I've been replacing many aspects of my code with the Ashley ECS components which has made life a lot easier, however, I have encountered a problem that I can't seem to solve. The problem is is that I am also using box2D for the physics/collision detection side of my game and the problem that I have encountered is is that when I declare my box2D World in my WorldGen class and go on to use that variable in my Ashley ECS system, the collision detection is broken between the bodies on my map and my entities such as the player. In addition, the collision detection of two entities using the system does not work. Here is the code:

In WorldGen:

```
world = new World(new Vector2(0f, 0f), true);
...
   //Instance of an entity in the world
   entityManager.createEntity(new Vector2(500, 500),
            SpriteSheet.npcSpriteSheet, true,
            "Billy",
            MobType.VILLAGER,
            TitleTypes.PEASANT,
            this.getWorld(),
            body, 10,
            BodyDef.BodyType.StaticBody, "npc1_1/");

```

In my EntityManager:

```
    public Entity createEntity (Vector2 position,
                         TextureAtlas atlas, boolean isRenderable,
                         String mobName, MobType mobType, TitleTypes title,
                         World world, Body body, float mass, BodyDef.BodyType bodyType, String extension) {

    Entity entity = new Entity();
    entity.add(new PositionComponent(position.x, position.y))
            .add(new SpriteComponent(extension, atlas))
             .add(new SocialComponent(mobName, mobType, title))
    .add(new BodyComponent(world, body, mass, new SpriteComponent(extension, atlas).getSprite, bodyType, position));

    if (isRenderable) {
        entity.add(new RenderableComponent());
    }
    engine.addEntity(entity);

    return entity;
}

```

BodyComponent:

```
public class BodyComponent implements Component {
public transient World world;
public transient Body body;
public float mass;
public transient Sprite sprite;
public transient BodyDef.BodyType type;
public transient Vector2 position;

public BodyComponent(World world, Body body, float mass, Sprite sprite, BodyDef.BodyType type, Vector2 position) {
    this.world = world;
    this.body = body;
    this.mass = mass;
    this.sprite = sprite;
    this.type = type;
    this.position = position;

    addBody();
}

public void updateBox2D (PositionComponent component) {
    //Forces the values into integers instead of real numbers
    component.posX = this.body.getPosition().x * GameUtils.PPM;
    component.posY = this.body.getPosition().y * GameUtils.PPM;
}

public Body addBody () {

    BodyDef bodyDef = new BodyDef();
    bodyDef.type = type;
    bodyDef.position.set(position.x / GameUtils.PPM, position.y / GameUtils.PPM);
    bodyDef.fixedRotation = true;
    //bodyDef.position.set(700/ GameUtils.PPM, 700/ GameUtils.PPM); //I hard-set values here, change to relative values

    this.body = world.createBody (bodyDef);

    PolygonShape shape = new PolygonShape();
    shape.setAsBox((sprite.getWidth()/4)  / GameUtils.PPM, (sprite.getHeight()/4) / GameUtils.PPM);

    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = shape;
    fixtureDef.density = mass;

    Fixture fixture = this.body.createFixture (fixtureDef);

    shape.dispose();

    return body;
}

```

}

In my ControlledMovementSystem:

```
    public void update(float deltaTime) {
    for (int i = 0; i < entities.size(); ++i) {
        Entity entity = entities.get(i);
        PositionComponent position = pm.get(entity);
        SocialComponent socialComponent = socialComponents.get(entity);
        BodyComponent bodyComponent = bodyComponents.get(entity);
        //bodyComponent.world = this.world;

        switch (socialComponent.mobType) {
            case PLAYER:
                position.isWalking = false;
                position.isStanding = true;

                if (StateGame.getGameRenderer().getPlayerGUI().getInvScreen().getInventoryActorVisibility() == true) {
                    return;
                }

                if (!position.isWalking) {
                    position.isStanding = true;
                }
                bodyComponent.updateBox2D (position);
                handlePlayerMovements(position, bodyComponent);

                System.out.println("-----------------");
                System.out.println("Entity x-pos: " + bodyComponent.body.getPosition().x);
                System.out.println("Entity y-pos: " + bodyComponent.body.getPosition().y);

                break;
            case NOBLE:
                break;
            case VILLAGER:
                break;
            case MONSTER:
                break;
        }

    }
}

private void handlePlayerMovements (PositionComponent positionComponent, BodyComponent bodyComponent) {
    float xa = 0, ya = 0;

    if (Gdx.input.isKeyPressed(Input.Keys.W) || Gdx.input.isKeyPressed(Input.Keys.UP)) {
        positionComponent.setAnimationBooleans(true, false, false, false, true, false);
        ya++;
    } else if (Gdx.input.isKeyPressed(Input.Keys.S) || Gdx.input.isKeyPressed(Input.Keys.DOWN)) {
        positionComponent.setAnimationBooleans(false, true, false, false, true, false);
        ya--;
    }
    if (Gdx.input.isKeyPressed(Input.Keys.D) || Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
        positionComponent.setAnimationBooleans(false, false, false, true, true, false);
        xa++;
    } else if (Gdx.input.isKeyPressed(Input.Keys.A) || Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
        positionComponent.setAnimationBooleans(false, false, true, false, true, false);
        xa--;
    }
    bodyComponent.body.setLinearVelocity(xa * 50, ya * 50);

```

// position.posX += xa; // position.posY += ya; } }

In my Mob class' render method:

```
private void updateEntityPosition () {
    objectBody = objectEntity.getComponent(BodyComponent.class).body;

    position.x = (int) (objectBody.getPosition().x);
    position.y = (int) (objectBody.getPosition().y);
}

```

This is what it looks like in-game:

Before posting this I checked to see if this would be caused by two different box2D worlds being active at the same time, but the body counts are the same when I check this. I feel like the problem lies with the createEntity() method that I have in my EntityManager.

To clarify, I do not declare the 'body' variable fully in the WorldGen class because the body gets created in the BodyComponent class.

# Answer
> 1 votes
After following a suggestion to change the entity body from Static to Kinematic, it seems that the whole problem sorted itself out. The reason for this is that Static bodies do not have collision detection.

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


# Question
Title: Update sprite position when speed changes if frame rate is low
I have a sprite moving horizontally from left to right. For each iteration I want to start decreasing the speed. This works ok, and the sprite will stop at some point, however depending on the frame rate it won't always stop at the same place. What's wrong with my code?

```
...
Vector2 Position;
Vector2 Speed;
...
Speed.X = 50;
...

public override void Update(GameTime theGameTime)
{
    float time = (float) theGameTime.ElapsedGameTime.TotalSeconds;

    Position += Speed * time;

    Speed.X-=10; // Reduce speed for next iteration
    if ( Speed.X < 0 ) Speed.X = 0;
}

```

I have also tried by doing

```
Speed.X-=10 * time;

```

but that didn't work.

# Answer
The problem is in this line:

```
Speed.X-=10;

```

This decreases the speed by a constant amount, so a lower framerate will mean less speed loss in the same amount of time. You touch on this in your second attempt:

```
Speed.X-=10 * time;

```

While the character will indeed stop after five seconds with this iteration, he still might spend more time at higher speeds with a lower framerate. For example, a 10 FPS framerate will cause him to spend 0.1 seconds each at speeds of 10, 9, 8, etc. A 2 FPS framerate will cause him to spend 0.5 seconds at 10 speed and 0.5 seconds at 5 speed.

What you need to do is take the average velocity over the frame and displace the player along that velocity for the given frame time. I'm not familiar with C#, so I'll give some pseudocode that may or may not be proper syntax throughout:

```
float time = (float) theGameTime.ElapsedGameTime.TotalSeconds;
float startFrameSpeed = Speed.X;
float endFrameSpeed = Speed.X - (10 * time);

float displacement = 0;

if(endFramespeed < 0) {
    //This is a problem because the player ends the frame with negative speed and that will throw off our average. We need to calculate the displacement a bit differently in this instance.

    //If you change the speed change from 10 units per second, you'll need to replace these tens with the new value. I would thus recommend storing the step in a variable for quick adjustment later.

    float timeSpentWithNegativeSpeed = -(endFrameSpeed / 10); //Get a positive value for time.
    displacement = 10 * timeSpentWithNegativeSpeed;
}

//Displace the player along the average speed throughout the frame.
Position += (startFrameSpeed + endFrameSpeed) / 2 + displacement;
Speed.X = endFrameSpeed;

if(Speed.X < 0) Speed.X = 0;

```
> 1 votes

---
Tags: c#, xna, physics
---


# Question
Title: I keep getting this error when I run my game so far
I have a tags script:

```
public class Tags {
    //Tags
    public static string PLAYER_TAG = "Player";
    public static string PLATFORM_TAG = "Platform";

    //Player Animation Tags
    public static string ANIMATION_IDLE = "idle";
    public static string WALK = "walk";
    public static string ANIMATION_RUN = "run";
    public static string ANIMATION_JUMP = "jump";
    public static string ANIMATION_JUMP_FALL = "jumpFall";
    public static string ANIMATION_LEDGE_FALL = "ledgeFall";
    public static string ANIMATION_JUMP_LAND = "jumpLand";

}
 Then I have my player animation script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerAnimation : MonoBehaviour {

    [SerializeField]
    private Animation anim;

    void Awake () {
        anim = GetComponent<Animation>();
    }

    public void DidJump () {
        anim.Play(Tags.ANIMATION_JUMP);
        anim.PlayQueued(Tags.ANIMATION_JUMP_FALL);
    }

    public void DidLand()
    {
        anim.Stop(Tags.ANIMATION_JUMP_FALL);
        anim.Stop(Tags.ANIMATION_JUMP_LAND);
        anim.Blend(Tags.ANIMATION_JUMP_LAND, 0);
        anim.CrossFade(Tags.ANIMATION_RUN);
    }

    public void PlayerRun()
    {
        anim.Play(Tags.ANIMATION_RUN);
    }
}

```

When I run the game, the player doesn't run like he's supposed to and I get this error:

```
NullReferenceException: Object reference not set to an instance of an object
PlayerMovement+<StartGame>c__Iterator0.MoveNext () (at Assets/Scripts/Player Scripts/PlayerMovement.cs:83)
UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at /Users/builduser/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)

```

What am I doing wrong here?

# Answer
> 0 votes
I figured it out. I didn't attach the script to the player.

---
Tags: c#
---