# Question
Title: Drawing textures in 3D/2.5D at an angle using spriteBatch in Monogame
for a university project we are creating a small "2d" game. Im writing 2D in "" because we would like to achieve a look similiar to the one in games like Don't Starve (so more like 2.5D).

As you might see, all the characters, trees, etc. are always drawn facing the camera. Because we are working with monogame/xna, spritebatch is pretty much the way to go there.

We use the following code to draw our WorldObjects:

```
 spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, currentCamera.CompleteMatrix);
//spriteBatch.Draw(texture, objectRectangle, Color) <- this works perfect and as intended:
//if we move the cameraPosition the sprites move accordingly.

```

Now on to our problem: We (of course) don't want the ground also to always face the camera, but instead to be looked at an slight angle of let's say 45 degrees. Spritebatch doesn't directly let us do so, but the aforementioned .Begin()-Method takes a Effect (in our case a BasicEffect) as well. This should us in theory allow to draw in 3D with spritebatch (or am I getting something completely wrong here?).

Our drawing-code for the ground looks like this:

```
        BasicEffect effect = new BasicEffect(Resources.graphicsDevice);
        Matrix projection = Matrix.CreateOrthographicOffCenter(0, Resources.graphicsDevice.Viewport.Width, Resources.graphicsDevice.Viewport.Height, 0, -1000, 100000);
        Matrix halfPixelOffset = Matrix.CreateTranslation(-0.5f, -0.5f, 0);

        effect.World = currentCamera.Translation * Matrix.CreateRotationX(0) * currentCamera.Scale * currentCamera.TransformToScreencenter;
        effect.View = Matrix.Identity;
        effect.Projection = halfPixelOffset * projection;

        effect.TextureEnabled = true;
        effect.VertexColorEnabled = true;
        Resources.spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, effect, null);

```

The code above is from a blog post of Shawn Hargreaves at msdn on how to use BasicEffect with SpriteBatch (not allowed to post more links here :/ ). It just mimics the standard spritebatch effect for drawing in 2D. I modified it slightly to fit how we implemented our camera. The code for the Cameraclass is the following:

```
    public Matrix CompleteMatrix
    {
        get
        {
            return Translation * Matrix.CreateRotationX(0f) *
                Scale *
                TransformToScreenCenter;
        }
    }

    public Matrix Translation
    {
        get
        {
            return Matrix.CreateTranslation(new Vector3(-Position.X, -Position.Y, 0));
        }
    }

    public Matrix Scale
    {
        get
        {
            return Matrix.CreateScale(new Vector3(2, 2, 1));
        }
    }

    public Matrix TransformToScreenCenter
    {
        get
        {
            return Matrix.CreateTranslation(new Vector3(Resources.graphicsDevice.Viewport.Width * 0.5f,
               Resources.graphicsDevice.Viewport.Height * 0.5f, 1f));
        }
    }

```

---

Now the question is: How can we achive this "tilted ground"-effect using the BasicEffect? I already tried things like using

```
Matrix.CreateLookAt(new Vector3(cameraPos.X, cameraPos.Y, 1f), new Vector3(cameraPos.X, cameraPos.Y - 1f, 0f), Vector3.Up)

```

and apply it to effect.View. But this didn't resulted in the way I expected it to (drawing the ground at an certain angle). I also tried applying a Matrix.CreateRotationX(MathHelper.ToRadians(30)) to our WorldMatrix, but this didn't gave me the desired effect eihter.

Is it just not possible (which I'm shure isn't the case)? Or am I getting something horribly wrong here (which is what I think is the problem)?

If some information is missing, i can provide more code or what ever is needed.

---

**Edit:** I looked into Billboards as mentioned in the comments: It looks like a very good solution, but would break all collisiondetection and mechanics we already implemented. So I experimented a little bit more with spritebatch, and came up with the following:

I used the following Matrix for the spriteBatch.Begin() overload:

```
public Matrix CompleteMatrix
    {
        get
        {
            return Translation * Matrix.CreateRotationX(45) * Matrix.CreateRotationY(-45) * Scale *
                TransformToScreenCenter;
        }
    }

```

Problem now: We don't want the gameobjects (in this case trees and characters) to "lay down flat" like the background does. I can achieve this, if I apply the same CompleteMatrix into a new spriteBatch.Begin() call (and draw all gameobjects after this begin call) but change the rotation around the X-axis to 0 (of course). But now if I move the camera/player down (along the Y-axis), the background moves at a different speed than the game objects and the gameobjects' positions are no more aligned with their expected positions relative to the background (because I removed the rotation around the X-axis). See here:

I think I'm on the right track but missing something small yet crucial here.. My question now is how can I combine the correct alignement of the background and foreground but still getting the foreground to be drawn "normal" like with the standard spritebatch.Draw call? Any links or advice is very much appreciated!

# Answer
If your camera is always facing the same direction (let's say north) and just pans in the horizontal plane, use quads in a 3D plane to draw your scene. Since the camera is not rotating, you don't need to change the facing of your quads, just put them in the right spot in your 3D scene. Note the camera is orthogonal for the effect.

If the camera is not fixed into a direction, you may want to use billboard technique to draw the scene. This means you need to rotate each quad to face the camera. Have a look at the Matrix.CreateBillboard method for the rotation.
> 0 votes

---
Tags: xna, camera, monogame, spritebatch
---


# Question
Title: need to make a ball travel in the angle it was hit from
```
self.hitBall = function (ball, x, y){

        var angle = Math.atan2((x - ball.centerX), (y - ball.centerY));
        ball.velocityY = (Math.sin(angle) * 10);
        ball.velocityX = (Math.cos(angle) * 10);

    }

```

So the function takes in the ball, which has a centerX variable and a centerY variabe. The x and y passed into the function is the x and y is the point the ball was hit. I want to make the ball travel in the direction it was hit from.

Not really sure why my code isn't working.. it's behaving very strangely and I'm not that good with trig so I'm not really quite sure why it isnt working.

# Answer
> 1 votes
Assuming that you mean the x,y passed in is the point on the ball that you hit. A bit like the cue position when you hit a ball with a snooker cue. You can do it with a bit of vector maths.

```
    // create direction vector for ball to go.
    var dirX = ball.centerX - x;
    var dirY = ball.centerY - y;

    // convert dir to unit vector. this'll make it easier to create a set magnitude later
    var magnitude = Sqrt( (dirX * dirX) + (dirY * dirY) );
    dirX /= magnitude;
    dirY /= magnitude;

    ball.velocityX = dirX * 10;
    ball.velocityY = dirY * 10;

```

# Answer
> 1 votes
**Physical 4 State Linear Translation----------**

*FORCE-* The amount of force the ball was hit.(kg)

*ACCELERATION-* That same force divided by the mass of the ball

```
(Force/Mass)

```

*VELOCITY-* Acceleration over time is Velocity

```
(Force/Mass)*T

```

*POSITION-*

Velocity over time changes the position

```
(Force/Mass)*T^2

```

DIRECTION Position is determined by direction on both axis

```
X=(Force/Mass)*T^2 *sin(Direction)
Y=(Force/Mass)*T^2 *cos(Direction)

```

---
Tags: collision-detection, physics
---


title: BulletPhysics ship rotation

text:
# Question
Title: BulletPhysics ship rotation
First of all, I'm a beginner in game physics, and I think this is a relatively easy problem that I'm not grasping.

Short Version:

I have a box(representing a ship on water) going forward with a constant thrust and I need to be able to steer it with the arrow keys so that it rotates and moves along a curved path. My code is not working and I'm obviously not understanding how to achieve this using Bullet-Physics.

Long version:

I'm creating a top-down-view naval game and I'm having a hard time trying to figure out how to use Bullet-physics to steer entities. I'm trying to make it feel somehow realistic by using a physics library.

I'm using SFML to prototype and test Bullet-physics. I have a 2D box representing a ship and during the main loop I'm updating its position and heading this way:

```
    box_bt->getMotionState()->getWorldTransform(trans);
    box_sprite.setPosition(trans.getOrigin().getX(), trans.getOrigin().getY());
    box_sprite.setRotation(RadToDeg(trans.getRotation().getAngle()));

```

relevant code:

```
  (...)

btTransform trans;

while (window.isOpen())
{
        dynamicsWorld->stepSimulation(1 / 60.f, 10);

        // Apply drag force
        box_bt->applyCentralForce(getDrag(box->getLinearVelocity().y()));

        box_bt->getMotionState()->getWorldTransform(trans);
        box_sprite.setPosition(trans.getOrigin().getX(), trans.getOrigin().getY());
        box_sprite.setRotation(RadToDeg(trans.getRotation().getAngle()));

        if (Force < 0)
          Force = 0;

      // Method to apply thrust force along the Y axis relative to the rigidbody
      // from: http://bulletphysics.org/Bullet/phpBB3/viewtopic.php?f=9&t=2366
        btVector3    relativeForce = btVector3(0, -Force, 0);
        btMatrix3x3& boxRot = box_bt->getWorldTransform().getBasis();
        btVector3    correctedForce = boxRot * relativeForce;
        box_bt->applyCentralForce(correctedForce);

        (...)

        if (event.key.code == sf::Keyboard::Up)
        {
            Force += 1000;
        }
        if (event.key.code == sf::Keyboard::Down)
        {
            Force -= 1000;
        }
        if (event.key.code == sf::Keyboard::Right)
        {
           box_bt->applyTorque(btVector3(0, 0, 1000));
        }
        if (event.key.code == sf::Keyboard::Right)
        {
           box_bt->applyTorque(btVector3(0, 0, -1000));
        }

    //draw box
}

```

I'm using applyTorque but I'm not sure if that is the best method to steer a ship in this case.

For the water drag/resistance force I'm using the simplified formula:

Force = vel\*(k1\*vel + k2\*vel^2) where k1 and k2 being tweakable "drag coefficients."

```
btScalar getDrag(btScalar velocity)
{
    btScalar k1 = 0.06f;
    btScalar k2 = 0.03f;
    return velocity * ((k1 * velocity) + (k2 * (velocity*velocity))) * 100;
}

```

I tried to get the drag force on all three axes but when I use the following code the ship doesn't behave right:

```
 btVector3 getDragVec(const btVector3& velocity)
{
    btVector3 Rt(0, 0, 0);

    btScalar k1 = 0.06f;
    btScalar k2 = 0.03f;

    Rt.setX(velocity.getX() * ((k1 * velocity.getX()) + (k2 * (velocity.getX()*velocity.getX()))) * 100); // 100 for scaling
    Rt.setY(velocity.getY() * ((k1 * velocity.getY()) + (k2 * (velocity.getY()*velocity.getY()))) * 100);
    Rt.setZ(velocity.getZ() * ((k1 * velocity.getZ()) + (k2 * (velocity.getZ()*velocity.getZ()))) * 100);

    return Rt;
}

```

**Both thrust and drag work well when moving forward, but once I try to introduce the steering part it rotates the box but it doesn't follow a curved path, the angles keep "flipping" once it gets to a certain limit, and the x-axis speed increases too much compared to the rotation.**

Thank you for any insight!

# Answer
Introducing a rate of change to the current heading

Heading= 050 Change= 0.2/second

(Current Heading + Rate of Change\*Time)=New Heading

(050+0.2\*1)=50.2

(050+0.2\*2)=50.4

(050+0.2\*3)=50.6

(050+0.2\*4)=50.8

(050+0.2\*5)=51.0
> -1 votes

---
Tags: physics, rotation, bullet-physics
---


# Question
Title: Single player game into Multiplayer game(Not online)
How difficult is it to do this?(Like, do you need to so skilled that you aswell might have created the game yourself) Do you need to change a lot of the code? For example, if I have a single player chess game, where one plays vs the computer. How dooes one make this avaible to play to players offline? Since I no very little about programming, I was hoping that one basically can remove the part controlling the computer, and replace it with a copy of the code for the first player.

Well, for an example:

http://ninjakiwi.com/Games/Tower-Defense/Play/Bloons-Tower-Defense-5.html

To make the question less open, is there likely that making a change like this will require less than 50 hours of work?

# Answer
> 1 votes
It depends on how your software architecture looks.

When you have a clear separation between user input, ai input, game mechanics and graphic engine, then you should be able to simply switch out the ai input with a second user input.

But when you have tight coupling between the AI code and the other components of your game, then it might be quite a lot of work to decouple these enough to allow a separate input method.

# Answer
> 0 votes
It's a lot harder than you think (Judging by your words), plus being able to create a game doesn't mean you are able to handle multiplayer gameplay.

I don't know about specific engines, some might help you with online gameplay, but talking just about code:

* You need a server (or servers) (Even if the game is based on 1v1 gameplay, you need a place to store information and do the matchmaking).
* You need to change a great part of the the core code, now information needs to be sent from and to the players computer.

This is explained "grosso modo", there a lot more into it than it seems, but these are the two basic things you need to add/change.

---
Tags: multiplayer, single-player
---


title: Rigidbody2D Circular Orbiting

text:
# Question
Title: Rigidbody2D Circular Orbiting
I am trying to create a basic solar system in 2D. All space objects has *CircleCollider2D* on them *(which are required for raycasting in another script)*. Currently planets are childs of stars, and satellites are childs of planets. This is the code I am currently using on planets and satellites:

```
void Update ()
{
    transform.localPosition = Quaternion.AngleAxis(speed*Time.deltaTime, -Vector3.forward) * transform.localPosition;
}

```

This code basically rotates the GameObject around it's parent on a fixed velocity while keeping the distance at the beginning.

This setup does exactly what I want, but the problem is this:

After some research, I learned this:

> When you move an object with a collider and without a rigidbody, the complete static collision data needs to be recalculated, which is slow.

So moving GameObjects that has colliders via transforms (which I do in code above) causes this horrible workload.

So I need to do the exact same thing with Rigidbody2D, but I have absolutely no idea how to, I have tried a few things but they either caused objects to move out of orbit or draw spirals going out of orbits.

Thanks in advance.

*Note: It is not mandatory for me to parent planets to stars and satellites to planets. So if you have a solution that requires not to parent objects to each other, please don't hesitate to post them.*

---

**Edit:**

First of all, I didn't manage to do what I want with physics engine.

But while experimenting, I discovered that, you don't necessarily have to "move" transform via Rigidbody to prevent collider re-creation; it is enough to have a Rigidbody attached to the GameObject. So if you have a Rigidbody attached to the GameObject, it doesn't matter if you use Transform or Rigidbody to move the GameObject, engine doesn't try to destroy and re-create Colliders.

So I think my problem is solved right now, but question still open for answers since the question itself is still unsolved.

# Answer
I wrote something a while back for Unity 4 that does this. The code isn't the cleanest, and it needs to be updated to version 5, but it does what you want using Rigidbody2D.

I will update it over the next couple weeks and stick it on my Custom Unity Library (if it's good enough). In the meanwhile, here is the script which you can reference, but I wouldn't really trust at this time. I wrote it while I was still learning Unity.

It extends Rigidbody2D. The MovePositionInCircle method is probably the most relevant to you. Perhaps the MovePositionInEllipse method.

Anyways, here it is:

```
using UnityEngine;
using System.Collections;

public static class RigidBody2DExtensions
{
    /// <summary>
    /// Sets the velocity for the game object and all of its descendants.
    /// If a descendant does not have a Rigidbody2D, neither it nor any of its descendants will have their velocity changed.
    /// </summary>
    public static void SetVelocityForDescendants(this Rigidbody2D rigidbody2D, Vector2 velocity)
    {
        rigidbody2D.velocity = velocity;
        foreach (Transform child in rigidbody2D.transform)
        {
            if (child.rigidbody2D)
            {
                child.rigidbody2D.SetVelocityForDescendants(velocity);
            }
        }
    }

    /// <summary>
    /// This ends any active calls of Rigidbody2D.MovePositionInLine() or Rigidbody2D.movePositionInCircle()
    /// </summary>
    public static void CancelMovePosition(this Rigidbody2D rigidbody2D)
    {
        RemoveExistingMovePositionComponents(rigidbody2D);
    }

    /// <summary>
    /// Moves the RigidBody2D's gameobject in a straight line, for a specified duration, for a specified distance, and in a specified direction.
    /// Optionally, whether or not the Rigidbody2D should rotate towards the direction it is moving, whether or not to invert horizontal movement, and whether or not to invert vertical movement can be declared.
    /// If the distance is set to 0, the object will move in line until Rigidbody2D.CancelMovePosition(), Rigidbody2D.MovePositionInLine(), or Rigidbody2D.MovePositionInCircle() is called, and the Seconds will be the speed at pixels per second.
    /// When Rigidbody2D.MovePositionInCircle() is called, any pending calls of Rigidbody2D.MovePositionInCircle() or Rigidbody2D.MovePositionInLine() for that GameObject will be canceled.
    /// Rigidbody2D.MovePosition() will be unavailable until this call completes.
    /// </summary>
    public static void MovePositionInLine(this Rigidbody2D rigidbody2D, float seconds, float distance, Vector2 direction, bool rotate = true, bool invertHorizontalMovement = false, bool invertVerticalMovement = false)
    {
        RemoveExistingMovePositionComponents(rigidbody2D);

        MovePositionInLine movePositionInLine = rigidbody2D.gameObject.AddComponent<MovePositionInLine>();
        movePositionInLine.hideFlags = HideFlags.HideInInspector;
        movePositionInLine.Seconds = seconds;
        movePositionInLine.Distance = distance;
        movePositionInLine.Direction = direction;
        movePositionInLine.Rotate = rotate;
        movePositionInLine.InvertHorizontalMovement = invertHorizontalMovement;
        movePositionInLine.InvertVerticalMovement = invertVerticalMovement;
    }

    /// <summary>
    /// Moves the RigidBody2D's gameObject in a circle for a specified duration, with a specified radius, and starting in a specified direction.
    /// Optionally, the number of circles, whether or not the circle should be clockwise, whether or not the Rigidbody2D should rotate while moving, whether or not to invert horizontal movement, and whether or not to invert vertical movement can be declared.
    /// If the number of circles is set to 0, the object will move in circles until Rigidbody2D.CancelMovePosition(), Rigidbody2D.MovePositionInEllipse(), Rigidbody2D.MovePositionInLine(), or Rigidbody2D.MovePositionInCircle() is called, and the seconds will become the time it takes to complete a single circle.
    /// When Rigidbody2D.MovePositionInCircle() is called, any pending calls of Rigidbody2D.MovePositionInCircle(), Rigidbody2D.MovePositionInEllipse(), or Rigidbody2D.MovePositionInLine() for that GameObject will be canceled.
    /// Rigidbody2D.MovePosition() will be unavailable until this call completes.
    /// </summary>
    public static void MovePositionInCircle(this Rigidbody2D rigidbody2D, float seconds, float numberOfCircles, float radius, Vector2 startDirection, bool clockwise = true, bool rotate = true, bool invertHorizontalMovement = false, bool invertVerticalMovement = false)
    {
        rigidbody2D.MovePositionInEllipse(seconds, numberOfCircles, radius, startDirection, new Vector2(1.0F, 1.0F), clockwise, rotate, invertHorizontalMovement, invertVerticalMovement);
    }

    /// <summary>
    /// Moves the RigidBody2D's gameObject in an ellipse for a specified duration, with a specified radius, starting in a specified direction, and shaped by the specified x and y modifier.
    /// Optionally, the number of ellipses, whether or not the ellipse should be clockwise, whether or not the Rigidbody2D should rotate while moving, whether or not to invert horizontal movement, and whether or not to invert vertical movement can be declared.
    /// If the number of ellipses is set to 0, the object will move in ellipses until Rigidbody2D.CancelMovePosition(), Rigidbody2D.MovePositionInLine(), Rigidbody2D.MovePositionInEllipse(), or Rigidbody2D.MovePositionInCircle() is called, and the seconds will become the time it takes to complete a single ellipse.
    /// When Rigidbody2D.MovePositionInEllipse() is called, any pending calls of Rigidbody2D.MovePositionInCircle(), Rigidbody2D.MovePositionInEllipse(), or Rigidbody2D.MovePositionInLine() for that GameObject will be canceled.
    /// Rigidbody2D.MovePosition() will be unavailable until this call completes.
    /// </summary>
    public static void MovePositionInEllipse(this Rigidbody2D rigidbody2D, float seconds, float numberOfCircles, float radius, Vector2 startDirection, Vector2 ellipticalMultiplier, bool clockwise = true, bool rotate = true, bool invertHorizontalMovement = false, bool invertVerticalMovement = false)
    {
        RemoveExistingMovePositionComponents(rigidbody2D);

        MovePositionInEllipse movePositionInEllipse = rigidbody2D.gameObject.AddComponent<MovePositionInEllipse>();
        movePositionInEllipse.hideFlags = HideFlags.HideInInspector;
        movePositionInEllipse.Seconds = seconds;
        movePositionInEllipse.NumberOfCircles = numberOfCircles;
        movePositionInEllipse.Radius = radius;
        movePositionInEllipse.StartDirection = startDirection;
        movePositionInEllipse.EllipticalMultiplier = ellipticalMultiplier;
        movePositionInEllipse.Clockwise = clockwise;
        movePositionInEllipse.Rotate = rotate;
        movePositionInEllipse.InvertHorizontalMovement = invertHorizontalMovement;
        movePositionInEllipse.InvertVerticalMovement = invertVerticalMovement;
    }

    private static void RemoveExistingMovePositionComponents(Rigidbody2D rigidbody2D)
    {
        MovePositionInLine[] movePositionInLineComponents = rigidbody2D.gameObject.GetComponents<MovePositionInLine>();
        foreach (MovePositionInLine movePositionInLineComponent in movePositionInLineComponents)
        {
            GameObject.Destroy(movePositionInLineComponent);
        }

        MovePositionInEllipse[] movePositionInEllipseComponents = rigidbody2D.gameObject.GetComponents<MovePositionInEllipse>();
        foreach (MovePositionInEllipse movePositionInEllipseComponent in movePositionInEllipseComponents)
        {
            GameObject.Destroy(movePositionInEllipseComponent);
        }
    }
}

[RequireComponent(typeof(Rigidbody2D))]
class MovePositionInLine : MonoBehaviour
{
    public float Seconds { get; set; }
    public float Distance { get; set; }
    public Vector2 Direction { get; set; }
    public bool Rotate { get; set; }
    public bool InvertHorizontalMovement { get; set; }
    public bool InvertVerticalMovement { get; set; }

    private float distanceTraveled;
    private bool moveInfinitely;

    void Start()
    {
        float xDirection = InvertHorizontalMovement ? -Direction.x : Direction.x;
        float yDirection = InvertVerticalMovement ? -Direction.y : Direction.y;
        Direction = new Vector2(xDirection, yDirection);
        Direction = Direction.normalized;

        if (Distance == 0)
        {
            moveInfinitely = true;
        }
    }

    void FixedUpdate()
    {
        if (Rotate)
        {
            float rotationAngle = Mathf.Atan2(Direction.y, Direction.x) * Mathf.Rad2Deg - 90.0F;
            Quaternion quaternion = Quaternion.AngleAxis(rotationAngle, Vector3.forward);
            transform.rotation = Quaternion.RotateTowards(transform.rotation, quaternion, Time.deltaTime * 360);
        }

        float speed = Seconds != 0 ? Distance / Seconds * Time.deltaTime : 0;
        if (Distance == 0)
        {
            speed = Seconds * Time.deltaTime;
        }
        Vector2 oldPosition = rigidbody2D.transform.position;
        Vector2 newPosition = oldPosition + Direction * speed;
        rigidbody2D.MovePosition(newPosition);

        distanceTraveled += Vector2.Distance(oldPosition, newPosition);
    }

    void Update()
    {
        bool movementComplete = distanceTraveled >= Distance && !moveInfinitely;
        if (movementComplete)
        {
            Destroy(this);
        }
    }
}

[RequireComponent(typeof(Rigidbody2D))]
class MovePositionInEllipse : MonoBehaviour
{
    public float Seconds { get; set; }
    public float NumberOfCircles { get; set; }
    public float Radius { get; set; }
    public Vector2 StartDirection { get; set; }
    public Vector2 EllipticalMultiplier { get; set; }
    public bool Clockwise { get; set; }
    public bool Rotate { get; set; }
    public bool InvertHorizontalMovement { get; set; }
    public bool InvertVerticalMovement { get; set; }

    private float angle = 0;
    private float xOffset;
    private float yOffset;
    private float startAngle;
    private bool moveInfinitely;

    void Start()
    {
        float xDirection = InvertHorizontalMovement ? -StartDirection.x : StartDirection.x;
        float yDirection = InvertVerticalMovement ? -StartDirection.y : StartDirection.y;
        StartDirection = new Vector2(xDirection, yDirection);
        Clockwise = !Clockwise;

        StartDirection = StartDirection.normalized;
        EllipticalMultiplier = EllipticalMultiplier.normalized;
        angle = StartDirection.ToRadians();
        if (Clockwise)
        {
            xOffset = StartDirection.y * Radius * EllipticalMultiplier.x + rigidbody2D.transform.position.x;
            yOffset = -(StartDirection.x * Radius * EllipticalMultiplier.y) + rigidbody2D.transform.position.y;
        }
        else
        {
            xOffset = -(StartDirection.y * Radius * EllipticalMultiplier.x) + rigidbody2D.transform.position.x;
            yOffset = StartDirection.x * Radius * EllipticalMultiplier.y + rigidbody2D.transform.position.y;
            angle += Mathf.PI;
        }
        startAngle = angle;

        if (NumberOfCircles == 0)
        {
            NumberOfCircles = 1;
            moveInfinitely = true;
        }
    }

    void FixedUpdate()
    {
        if (Clockwise)
        {
            if (NumberOfCircles != 0)
            {
                angle -= Seconds != 0 ? 2 * Mathf.PI / Seconds * NumberOfCircles * Time.deltaTime : 0;
            }
            else
            {
                angle -= Seconds * Time.deltaTime;
            }
        }
        else
        {
            if (NumberOfCircles != 0)
            {
                angle += Seconds != 0 ? 2 * Mathf.PI / Seconds * NumberOfCircles * Time.deltaTime : 0;
            }
            else
            {
                angle += Seconds * Time.deltaTime;
            }
        }
        Vector3 oldPosition = rigidbody2D.transform.position;
        float newX = Mathf.Cos(angle) * Radius * EllipticalMultiplier.x + xOffset;
        float newY = Mathf.Sin(angle) * Radius * EllipticalMultiplier.y + yOffset;
        Vector3 newPosition = new Vector2(newX, newY);

        if (Rotate)
        {
            Vector3 direction = oldPosition - newPosition;
            float rotationAngle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg + 90.0F;
            Quaternion quaternion = Quaternion.AngleAxis(rotationAngle, Vector3.forward);
            transform.rotation = Quaternion.RotateTowards(transform.rotation, quaternion, Time.deltaTime * 360);
        }
        rigidbody2D.MovePosition(newPosition);
    }

    void Update()
    {
        bool movementComplete = Mathf.Abs(angle - startAngle) >= NumberOfCircles * 2 * Mathf.PI && !moveInfinitely;
        if (movementComplete)
        {
            Destroy(this);
        }
    }
}

```
> 1 votes

# Answer
Most simplistic way of handling simplified orbits.

Define distance for each Celestial body.

R=35000 km

Integrate Theta

Theta=Theta + 0.1

Plot Point by converting Polar to Rectangle

X=R*cos(Theta) Y=R*sin(Theta)

Want a more realistic process just ask.
> 0 votes

---
Tags: 2d, physics, unity, rigidbody
---


# Question
Title: How to calculate the closing speed of two objects
I have the 2D positions and 2D velocity vectors of two objects. How do I calculate the closing velocity ? I want to get the closing speed.

Think of one jet tracks another jet with radar and you want to yield the closing speed, which is actually the distance-change / unit. (In this example Δmiles/h)

# Answer
You essentially have two lines with the equations:
\\$a(t)=a\_0 + t\*v\_a\\$

\\$b(t)=b\_0 + t\*v\_b\\$

where \\$a\_0, b\_0, v\_a, v\_b\\$ are vectors with the same dimension and unit (meters for \\$a\_0\\$ and \\$b\_0\\$ and meters per second for \\$v\_a\\$ and \\$v\_b\\$).

\\$a(t)\\$ and \\$b(t)\\$ are the positions of your objects at time \\$t\\$ (in seconds if using the units above).

Distance over time is calculated by subtracting the positions and taking the length of the vector:
\\$d(t)=\left|a(t)-b(t)\right|=\left|a\_0-b\_0+t\*(v\_a-v\_b)\right|\\$

This has to be differentiated to get the closing speed (The multiplication used is the dot-product): \\$c(t)=d'(t)=\frac{(v\_a-v\_b)\*((v\_a-vb)\*t+a\_0-b\_0)}{\left|(v\_a-v\_b)\*t+a\_0-b\_0\right|}\\$

The value of \\$c(t)\\$ is a scalar.

You probably want the closing speed at t = 0 (i.e. now), so it can be simplified further:

\\$c(0)=d'(0)=\frac{(v\_a-v\_b)\*(a\_0-b\_0)}{\left|a\_0-b\_0\right|}\\$

Unit of the result is the same as the components of the original velocity vectors. It is negative if the objects get closer to each other and positive if the distance increases. If you want it the other way around you have to multiply by -1.

\\$current closing speed=-c(0)=-\frac{(v\_a-v\_b)\*(a\_0-b\_0)}{\left|a\_0-b\_0\right|}\\$

Note that this works for all dimensions.

Every matrix-/vector-math library will support all of the necessary operations. Depending on its design this can be written as a single line of code. However you may prefer to store \\$a\_0 - b\_0\\$ in a temporary variable.

In Pseudocode this may look like this

```
val tmp = a.position - b.position
return -((a.velocity - b.velocity).dot(tmp)/tmp.length)

```
> 6 votes

# Answer
To find the relative velocity vector, you need to substract the vectors. The magnitude of that vector is your closing speed.

*(Note that the operation inside the magnitude function of the third situation is a vectoral substraction, not a scalar one.)*

---

**Edit:**

Assume initial positions are `A` and `B`, distance is `dis`, velocities are `v(A)` and `v(B)`.

*(As you can see, objects can never collide.)*

Now, if we do this:

As you can see now, the `c` vector is the relative velocity.

Now, we can write these equations:

Also these:

Now, here is what you want in question:

As we wrote above, this yields to this:

Which eventually yields to:

Which is our relative velocity.
> 1 votes

# Answer
Simple: Unlike the rest of these answers.

V1\*sin(dir) - V2\*sin(dir)

30\*sin(090) - 40\*sin(270) = 70

If you want the range, just add it in like so

Range-(30\*sin(090) - 40\*sin(270) = 70)
> -2 votes

---
Tags: mathematics, vector
---


# Question
Title: Accelerated movement in a specific time to a specific point
I am trying to move my sprite in a specific time to a specific position while using frame-independent or time-dependent movement. My sprite is also accelerated every frame to simulate gravity. I know the acceleration, the distance and the needed time. So i used the formula for acceleration based movement: s = 0,5 · a · t2 + v₀ · t + s₀ which is equivalent v₀ = (s-s₀) / t - a · t / 2. However, in my implementation the sprite does not move to the specified y-coordinate. *The lower the starting y-coordinate is the higher is the resulting y-coordinate*. For the time I used a quarter second. Here is my implementation:

```
    float resultY = viewport.getWorldHeight() / 6f * 5f;
    float time = 0.25f;
    velocity.y = (resultY - circle.getY()) / time - (-25f * time / 2f);

```

and these are called every frame:

```
    velocity.y -= 25f;
    circle.translate(velocity.x * delta, velocity.y * delta);`

```

What did I do wrong or is there a better method to move an accelerated sprite to a specific position in a specific time?

**EDIT:** I didn't mention that I want the sprite to stop at that specific point. I figured out that using my formula the sprite moves to the specified point in the specified time but it keeps moving and does not stop there. Is there a formula to solve that problem?

**EDIT2:** Ok, I realize that my last question is nonsense because stopping the sprite at a specified position and a specified time with a given acceleration is impossible. Thanks for all the answers.

# Answer
> 0 votes
I solved my problem using steering behaviours thanks to the suggestion by @Alexandre Vaillancourt. The "arrive" behaviour was the solution for me as suggested in his comment.

# Answer
> 3 votes
I've run into this kind of trouble a few times, but not yet on 3d.

First of all, I'm not really sure you transformed correctly the acceleration formula... maybe this source can help in that way.

Secondly, at the end of your post you mention you want to specify a specific TIME for the sprite from one point to the other, if that is your goal then you should really apply upon an easing formula, which basically applies trigonometry upon your starting and your finishing points, but maybe your framework has already some shortcuts to achieve that.

Finally, if you really want to write a formula to achieve your personalized acceleration in a specific timeframe, you would requiere an iteration to apply your formula. If you do, in that path I believe this source can help you a bit.

Maybe this is not a complete answer for your specific case, but might help you in the right path.

# Answer
> 0 votes
This can be done in a simple 3 step looped process.

Step1: Clear screen of all moving objects or sprites

Step2: Apply formula -- Height-(9.8)\*T^2

Step3: Apply objects or sprites in new position

I even made you quick graph to show you what I mean.

https://www.desmos.com/calculator/f0bglhnjjg

---
Tags: java, libgdx, physics, mathematics, frame-rate
---


title: Unity 3D Move Object with RigidBody

text:
# Question
Title: Unity 3D Move Object with RigidBody
I have added RigidBody component as well as Mesh collider to an object moved with keyboard. I know that it the object will go through another (with RigidBody and Mesh collider too) if I use transform to move the object. Could you give me example of code how to move an object with RigidBody. Here is my current code (still using Transform)

```
if (Input.GetKey(KeyCode.RightArrow))
{
    character.transform.position += Vector3.right * speed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.LeftArrow))
{
    character.transform.position += Vector3.left * speed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.UpArrow))
{
    character.transform.position += Vector3.forward * speed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.DownArrow))
{
    character.transform.position += Vector3.back * speed * Time.deltaTime;
}

```

# Answer
You can use `velocity` for this purpose. Also you can improvise your code if you have to have inputs through arrow keys and WASD.

```
Rigidbody _rb;
float _speed = 30f;
void Start ()
{
    _rb = character.GetComponent<Rigidbody> ();
}

void Update ()
{
    float horizontal = Input.GetAxis ("Horizontal");
    float vertical = Input.GetAxis ("Vertical");

    Vector3 fVelocity = new Vector3 (horizontal, 0, vertical) * _speed;
    _rb.velocity = fVelocity;
}

```

If you don't want to use WASD then use your code but change `velocity` instead of `transform.position`
> 1 votes

---
Tags: 3d, unity, rigidbody
---


# Question
Title: Draw wireframe models for Gear VR app in Unity
I want to create a 3D Android app for Gear VR that does/lets me do the following:

1. Read an input file with a bunch of coordinates of points (including information about how they should be connected)
2. Draw a wireframe model with these points
3. Walk around and through the model in first person to look at it from different angles using a gamepad/controller. I don't want to directly interact with it!
4. (Maybe have more than one model displayed at the same time, including filled ones)

Is it possible to draw 3D wireframe models in Unity using coordinates instead of using already finished models that were created in Blender/Maya/etc, and if so, how?

# Answer
> 1 votes
To directly answer your main question, yes, you can draw lines connecting arbitrary coordinates in arbitrary ways in Unity.

One of my favorite Unity assets for this is Vectrosity, and you can play with some of their wireframe-style demos here. I haven't used Vectrosity in a VR project yet myself, but I see no reason it wouldn't work, beyond the usual complexities introduced by VR/AR.

Without an asset like that, I think you'd be left using the basic LineRenderer component. Fully possible, but it can be a bit of a headache.

---

Your second question, Eclipse+SDKs vs. Unity, is not something with a concrete answer and therefore ill-suited to this site. The particulars of your project will determine which is most appropriate for you.

That said, if you're building a full-featured product you may find that the benefits of the Unity ecosystem more than make up for the extra effort of learning C# (not that it's especially different from Java, anyways).

---
Tags: unity, android, models, gearvr
---


title: Simple 2.5D flight movement

text:
# Question
Title: Simple 2.5D flight movement
I'm building a simple 2.5D Dogfighting game, kinda similar like this one: https://gfycat.com/PleasantDeterminedArcherfish for the moment my movement works like this:

```
    if (Input.GetKey("left"))
    {
        transform.Rotate(0, 0, rotation);
    }

    if (Input.GetKey("right"))
    {
        transform.Rotate(0, 0, -rotation);
    }

    if (Input.GetKey("up"))
    {
        if (speed <= maxspeed)
            speed += speedIncrease;
        if (gravity > 0)
            gravity -= speedIncrease;
    }

    if (Input.GetKey("down"))
    {
        if (speed > 0f)
            speed -= speedIncrease;

        if (speed <= 0f)
            speed = 0;

        if (gravity < 1.0f)
            gravity += speedIncrease;
    }

    transform.Translate((Vector3.down * gravity), Space.World); //This is for the fake gravity
    transform.Translate(new Vector3(0, 1 * speed, 0)); //This applies the forward speed

```

I tried to create the gravity by myself, so that I would be able to lower the gravity, at higher speeds, so that I can achieve an "uplift" effect, like in reality. But now I wanted to let my model face the movement direction and all solutions, I found to solve this problem use the `rigidbody.velocity`, which is zero in my case. Is there another case to solve this problem? Or maybe even a better solution to achieve a similar movement like in the gif than mine? Maybe adding force instead of Translate?

# Answer
This is actually a multi-particle system based game. The position of the mouse cursor is used to determine the X and Y of the plane. This is done by splitting the screen into quads. Each quad giving the negative and positive values for each axis.

```
Mouse_X = MousePosition.X - (1023 / 2)
Mouse_Y = MousePosition.Y - (767 / 2)

```

The plane on the other hand is only a point on a graph trying to follow the cursor through simple 'if' commands. The background is only a graph whos min and max change to the increase of distance from the center.
> 1 votes

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


# Question
Title: How can I achieve a constant drop rate with a variable frame rate?
In my game, I have particles that should spawn at random intervals but with an average rate of `x` per second.

However, the frame-rate varies from around 60 fps all the way to around *3000* fps. I would like to maintain a variable frame-rate to ensure the game looks as smooth as possible, but this means I cannot simply create particles with probability `x` each frame:

```
if (random.Next(100) > x)
{
    // Create particle...
}

```

How can I maintain a constant "real time" drop-rate when the frame rate fluctuates?

Note that I have a variable `dt` which is the number of seconds since the last frame.

# Answer
> 1 votes
While this is not a perfect solution, you can say something like:

```
if (random.NextDouble() / x < dt)
{
    // Create particle...
}

```

How this works:

For now, let's assume that you want an average of 1/second (so `/ x` does nothing). If it's been one second since the last frame, you want an average of one particle to appear. `random.NextDouble()` always generates a number such that `0 <= n < 1`, so it will always be less than `dt` in this case, causing a particle to always appear. If it's been 1/60th of a second since the last frame, `dt` will be `1/60`. `random.NextDouble()` has a 1/60 chance to be less than `1/60`, so on average there will be 1 particle every 60 frames, or 1/second.

Now, let's say that you want 2/second. If it's been 1/60th of a second since the last frame, `dt` will be `1/60`. `random.NextDouble() / x` (where `x == 2`) has a 1/30 chance to be less than `1/60`, so on average there will be 2 particles every 60 frames, or 2/second.

# Answer
> 0 votes
Would this idea of an accumulator of probability work?

```
float acc -> particle count accumulator

float x   -> particles per second
float dt  -> number of seconds since last frame

update( dt )
{
  // increase the chance of a particle spawned this update
  acc += x * dt;

  // This case where you run at a very low frame rate, or that you want
  // A LOT of particles per second
  while ( acc > 1.0 )
  {
    // [spawn a particle]
    acc -= 1.0; // done with this particle
  }

  // now this is to take care of a "random" but still constant over time.
  if ( acc > 0.0 )
  {
    // as the accumulator increases in value, the more chances there is for a
    // particle to spawn
    float random_value = rnd.next( 0.0, 1.0 ); // random float between 0 and 1
    if ( random_value < acc )
    {
      // [spawn a particle]
      acc -= 1.0;
      // now acc is negative, there will be no chances of spawning until it gets
      // back above 0.0 which will happen over time.
    }
  }
}

```

Keep in mind: **totally not tested, maybe very flawed**... dunno! I'm just suggesting stuff from the top of my head.

# Answer
> 0 votes
One simple way would be to *adjust the chance of the drop by `dt`*. So instead of accumulators etc. you could do a simple multiplication: drop if `dt * random <= threshold`.

# Answer
> 0 votes
Add or subtract a random number from `x`, and use timers to spawn particles once per second

```
if(timer >= 1)
{
  int y=//random number
  int xnew = x + y;
  //clear timer
  for(int i; i <= xnew; i++)
  {
    //span particle
  }
}

```

This will cause the particles to spawn very close together, and then stop for about a second. To space them out more (but not randomly spaced) you can make an array consisting of `[1/x, (1+x)/x, (2+x)/x,...(x-1)/x]` and

```
if(timer in array)
{
//spawn particles
}

```

---
Tags: frame-rate, probability
---


# Question
Title: How to make a GameObject ignore a camera effect?
I have a 2D game and I wanted to apply bloom to the main GameObjects so I attached the effect onto the main camera, however the background also gets affected by the bloom and it gets all shiny. How can I make it ignore the bloom effect?

# Answer
> 2 votes
Bloom effect in Unity is actually a post effect which means it works after all the GameObjects have been rendered by the camera, and it can't be seperately affected.

The only way you can do this is use two cameras, one for the main GameObjects and one for the background, and properly set the layer and Camera's culling mask of the cameras

Check this doc for more detail http://docs.unity3d.com/Manual/Layers.html

# Answer
> -1 votes
Since the Unity bloom effects are post processed, they apply to the whole screen, so they can't be controlled by camera layers. Fixed it by not using it.

---
Tags: unity, camera, post-processing, bloom
---


title: Sine-based Tiled Procedural Bump

text:
# Question
Title: Sine-based Tiled Procedural Bump
I am trying to implement this formula to generate bump but I am facing some issue. The result doesn't look the same it's much darker.

Here is my result (without same parameters) but it is much darker and I don't get why.

And here is the associated code.

```
// randx, randy and frequencies are array with some random values for each sin wave.
for (int x = 0; x < _width; ++x)
{
    for (int y = 0; y < _height; ++y)
    {
        float color = 0.0f;
        for (int i = 0; i < _iterations; ++i)
        {
            val += Mathf.Sin(Mathf.Sqrt(Mathf.Pow(x - randx[i], 2.0f) + Mathf.Pow(y - randy[i], 2.0f)) * 1.0f / (2.08f + 5.0f * frequencies[i]));
        }
        color /= (float)_iterations;
    }
}

```

Any idea why I am getting this result ?
Thanks a lot !

**EDIT**: Thanks to @DMGregory it works by doing this.

```
float tmp = Mathf.Sin(Mathf.Sqrt(Mathf.Pow(x - randx[i], 2.0f) + Mathf.Pow(y - randy[i], 2.0f)) * 1.0f / (2.08f + 5.0f * frequencies[i]));
tmp = tmp * 0.5f + 0.5f;
val += tmp;

```

# Answer
> 5 votes
I would guess that they've scaled and shifted their outputs into the range from 0f to 1f (0-255) for the purpose of that greyscale height visualisation.

They probably omitted that adjustment from the formula because it's not critical to the shape they're describing with the normal map.

Try multiplying the result by something in the neighbourhood of 0.5f and adding 0.5f.

(I say "in the neighbourhood" because the probability that this formula returns 1 or -1 is vanishingly low — most values are clustered close to zero, so using a coefficient somewhere above 0.5 but lower than 1 may help make the variability more visible in a greyscale output. Just watch for oversaturation of the range, which can produce ridge artifacts if you generate normals/lighting after clamping to the 0-1 range)

---
Tags: opengl, shaders, directx, rendering, procedural-generation
---


# Question
Title: I can't center my actors with ExtendViewport, Libgdx
I'm making a level select screen and I need use ExtendViewPort (I can't use Fit for other reasons), but this viewport moves my actors to the left, I need center them. I put X and Y position corresponding with my virtual screen size. This is my problem:

I do this things:

```
setViewport(new ExtendViewport(720, 1280));

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

actor.setPosition(10,100); (Examples..)

```

Sry for my bad english, I speak spanish.

# Answer
I already solved my problem using this:

```
viewport.getWorldWidth()

```

I can't explain more because my english is so bad
> 0 votes

---
Tags: libgdx, viewport
---


# Question
Title: How to manage loads and memory usage and process in unity
I want to know whether level and scene management for memory and process management is handled by Unity, or if the developer has to handle these kinds of concerns.

For example, imagine you want to develop an open world game, and you just start adding prefabs of people and cars and buildings and... until it's certain the target device can't handle all of them at same time. How can I manage the amound of content that is processed in the game?

Is this management handled automatically by Unity, or do I have to implement some techniques for this kind of work?

# Answer
> 2 votes
If you tell Unity to spawn an instance of a prefab, it won't automatically delete that instance without you telling it to do so.

(This is good - we don't want an engine that deletes stuff out from under us! We know better than the engine does which instances we still want - we just need to communicate that knowledge by telling it when we're finished with these objects)

You can use the Level of Detail and Culling systems to reduce the rendering performance impact of objects away from the camera's focus, but they'll still take up at least some time & memory.

If you're hesitant to implement your own solution for unloading unseen content, you can look to existing tools and libraries like SECTR that can help with these kinds of tasks. (This is how Campo Santo managed the world of Firewatch, for instance)

---
Tags: unity, performance, culling, streaming
---


title: How to implement jump in a 2d game?

text:
# Question
Title: How to implement jump in a 2d game?
I am trying to implement jump in a game I have written for android using canvas. I have referred this tutorial for implementing jump. My code is like

```
if(jumpKeyPressed){
    jumpVel = -initialMomentum;
    state = "jumping";
}
if(state == "jumping"){
    jumpVel += gravity * deltaTime / 2;
    loc.y += jumpVel * deltaTime;
    jumpVel += gravity * deltaTime / 2;
}

```

Even after tweaking gravity and initialMomentum, character is jumping too slow (seems like stuck at ground). I have read many posts but I am not able to figure out what am I doing wrong here?

Edit: Video

# Answer
> 2 votes
My answer is based on Lolums' answer. His logic is good, especially if you are making a simulation of something with realism. But Philipp points out something important as well: correct physics do not typically translate well to platform games.

The take-away is that you should apply the idea of gravity `velocity_y -= gravity * delta_time` but you should not be afraid to use numbers that seem unrealistic. The ones you use will likely be higher than you'd expect by studying the real world, sometimes *much* higher. Case in point, consider Super Mario World.

> * When jumping regularly, Mario experienced a gravity of 67.82 m/s^2 (6.9 times Earth gravity). Here he had a push-off velocity of 17.36 m/s.
> * When high-jumping, Mario experienced a gravity of 34.79 m/s^2 (3.5 times Earth gravity). Here he had a push-off velocity of 15.21 m/s.
> * When falling off a ledge, Mario experienced a gravity of 55.88 m/s^2 (5.7 times Earth gravity).
> * As for running, Mario seemed to follow a perfectly constant run velocity pattern (as is expected, really). When walking, he moved at a speed of about 3.7 m/s, and when running, moved at a speed of about 9.1 m/s.

Source: http://hamaluik.com/posts/super-mario-world-physics/

Almost *seven times* Earth's gravity, under some conditions. And for that matter, note how inconsistent the acceleration values are. This violates many laws of physics, and that's okay.

My advice: Apply the basic model of gravity as you know it to exist, and then test your game. Play with the numbers. The force gravity in Castlevania 4 feels very, very strong. The gravity in Symphony of the Night doesn't. They're both excellent platform games, because the developers experimented and found what worked for their games.

# Answer
> 2 votes
Physics student here.

Firstly, separate your velocity into two components.

```
Character {
    float velocity_x;
    float velocity_y;
}

```

Now, when they jump, you add an *initial* velocity to their `velocity_y` and every frame, you do something like `loc.x += velocity_x * delta_time` (and the same for `y`).

Every frame, you also do `velocity_y -= gravity * delta_time` (and only to the `y` value). If they're falling to quickly, turn gravity down. If they're jumping too high, turn gravity up. Play with it.

As for the `velocity_x`, you can set that to the speed at which they're moving whilst they jump. When they horizontally collide, set the `velocity_x` to `0`.

# Answer
> 0 votes
You never tweak gravity. It is a constant force. A jump is an instantaneous force applied to a body only when the altitude of the body is at 0.

To jump, you must apply a force or acceleration strong enough to overcome gravity.

We do this by applying a force that results an acceleration of +9.8 or higher

example: Mass=10 Force=10 Acceleration=1 (no-good)

Mass=10 Force=100 Acceleration=10 (good)

---
Tags: android, physics
---


# Question
Title: How to limit resolutions display in monogame
I can Add resolutions to the list. Here is part of code.

```
List<Vector2> resolutions = new List<Vector2>();
foreach (var item in GraphicsAdapter.DefaultAdapter.SupportedDisplayModes)
{

    for (int i = 0; i < item.Width; i++)
    {
        for (int z = 0; z < item.Height; z++)
        {

            resolutions.Add(new Vector2(i,z));
        }
    }
}

```

That is all great and dandy...but i wanna for example remove 320x200 up to 1024x768? Is there is any way to do that and how can i set/see refresh rate?

# Answer
> 1 votes
I don't think your code is doing what you think it's doing. If I run that code on my computer I get 23,879,696 resolutions in the list.

I think what you intended to write was something more like this:

```
List<Vector2> resolutions = new List<Vector2>();
foreach (var item in GraphicsAdapter.DefaultAdapter.SupportedDisplayModes)
{
    resolutions.Add(new Vector2(item.Width, item.Height));
}

```

Which will produce the following output:

```
{X:320 Y:200}
{X:320 Y:240}
{X:400 Y:300}
{X:512 Y:384}
{X:640 Y:400}
{X:640 Y:480}
{X:800 Y:600}
{X:1024 Y:768}
{X:1152 Y:864}
{X:1280 Y:600}
{X:1280 Y:720}
{X:1280 Y:768}
{X:1280 Y:800}
{X:1280 Y:960}
{X:1280 Y:1024}
{X:1360 Y:768}
{X:1366 Y:768}
{X:1400 Y:1050}
{X:1440 Y:900}
{X:1600 Y:900}
{X:1600 Y:1200}
{X:1680 Y:1050}
{X:1920 Y:1080}
{X:1920 Y:1200}

```

You could also use LINQ to produce the same list.

```
var resolutions = GraphicsAdapter.DefaultAdapter.SupportedDisplayModes
    .Select(item => new Vector2(item.Width, item.Height))
    .ToList();

```

Now to get to you're actual questions.

> but i wanna for example remove 320x200 up to 1024x768?

To remove the resolutions you don't want you're going to have to create some custom logic. I'm not sure exactly what you want but you could do something fairly simple, like filter out resolutions with a width less than 1024.

```
var resolutions = GraphicsAdapter.DefaultAdapter.SupportedDisplayModes
    .Where(r => r.Width >= 1024)
    .Select(item => new Vector2(item.Width, item.Height))
    .ToList();

```

Or of course, you could get more clever and somehow include `Height` or `AspectRatio` in the filter. That parts really up to you.

> how can i set/see refresh rate?

The refresh rate is an entirely different question. By default MonoGame / XNA refresh at a fixed 60fps so you may want to turn that off.

```
IsFixedTimeStep = false;

```

Or alternately you can change the refresh rate from the default 60fps.

```
TargetElapsedTime = TimeSpan.FromSeconds(1.0f / 100.0f);

```

One last thing you should know is that the frame rate might be limited by VSync. This means the game's refresh rate will be limited by the refresh rate of your monitor. To turn that off set `SynchronizeWithVerticalRetrace` on the graphics device manager.

```
_graphicsDeviceManager = new GraphicsDeviceManager(this)
{
    SynchronizeWithVerticalRetrace = false
};

```

I hope that helps.

---
Tags: monogame, resolution
---


# Question
Title: How do I include XML files in an Android build?
I have a few XML files I want to include in a build of my game, and I want to have access to those XML files in Android. How to I store and load those XML files?

# Answer
You load XML files just like you would any other asset file. Review the documentation to learn about loading resources at runtime. Likely the easiest strategy will be to use Resource Folders:

> To put anything into a Resource Folder, you simply create a new folder inside the Project View, and name the folder “Resources”. You can have multiple Resource Folders organized differently in your Project. Whenever you want to load an asset from one of these folders, you call Resources.Load()

An example of how you might use this to load an XML file:

```
TextAsset textAsset = (TextAsset) Resources.Load("MyXMLFile");
XmlDocument xmldoc = new XmlDocument ();
xmldoc.LoadXml ( textAsset.text );

```
> 3 votes

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


title: Stopping 3D object in place

text:
# Question
Title: Stopping 3D object in place
I am at 1.2 stage (moving the player) at Unity course "Roll-a-ball" and have question:

I want to add feature that stops a player and sets his new position on 0, 0, 0.

I can reset the position, but I have really problem with stopping a player. The ball won't stop rolling.

My code is:

```
    using UnityEngine;
    using System.Collections;

    public class PlayerController : MonoBehaviour {

        private Rigidbody rb;
        public float speed = 1.0f;

        void Start()
        {
            rb = GetComponent<Rigidbody>();
        }

        void FixedUpdate()
        {
            float moveHorizontal = Input.GetAxis("Horizontal");
            float moveVertical = Input.GetAxis("Vertical");

            Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);

            rb.AddForce(movement*speed);
            if (Input.GetKeyDown(KeyCode.Space))
            {
                rb.position = new Vector3(0,0.5f,0);
            }
            print(movement);
        }
    }

```

What I tried?

* Adding new vector3 (0,0,0) in `if` section,
* New vector3 that is opposite to movement,
* `.Stop` after ascribing new position to (0,0,0), but it 'freezes' before (example: I click space when sphere is at board's edge, then it freezes there, when I click arrow it go to new position and start going).

So, how to do that? I have no clue right now, although problem seems be easy.

Here a image with code and Unity with opened Inspector on object.

**EDIT**

I've a another problem.

Changed code as below (as Byte56 suggested):

```
if (Input.GetKeyDown(KeyCode.Space))
{
    speed = 0;
    rb.velocity = Vector3.zero;
    rb.transform.position = new Vector3(0, 0.5f, 0);
    rb.constraints = RigidbodyConstraints.FreezeAll;
    speed = 1.0f;
}
if (moveHorizontal != 0 || moveVertical != 0)
{
    rb.constraints = RigidbodyConstraints.None;
}

```

It seems like clicing space not always freezes object. It always put it on right place, but sometimes doesn't freeze. No matter if I use code `rb.constraints = RigidbodyConstraints.FreezeAll;` or `rb.Sleep();` \- sometimes it works, sometimes not. I can't prove it, but it seems the smaller is delta of time between clicking space (smaller than 1 second) the chance that it won't freeze increases. It's not fault of space, I tried it with NumEnter. Any idea? It seems really buggy.

# Answer
If you want to stop a physics object from moving, you need to zero the forces and the velocity of the `RigidBody`.

```
rb.velocity = new Vector3(0,0,0);

```

For zeroing the force, you can apply a force opposite to the forces you've added that frame already. However, I'd suggest simply not adding those forces if you're stopping. It means a slight rearrangement of your code.

```
if (Input.GetKeyDown(KeyCode.Space))
{
    rb.position = new Vector3(0,0.5f,0);
    rb.velocity = new Vector3(0,0,0);
} else {
    rb.AddForce(movement*speed);
}

```

The ultimate way to stop the ball, activating all the constraints on the rigidbody.

```
if(moveHorizontal != 0 || moveVertical != 0) //for starting the movement again
    rb.constraints = RigidbodyConstraints.None;

if (Input.GetKeyDown(KeyCode.Space))
{
    rb.gameObject.transform.position = new Vector3(0,0.5f,0);
    rb.constraints = RigidbodyConstraints.FreezeAll;
} else {
    rb.AddForce(movement*speed);
}

```
> 2 votes

# Answer
It is due to constantly applying `AddForce` in `FixedUpdate`. You can easily do it by assigning zero to `speed` and set `velocity` to zero.

```
rb.AddForce(movement*speed);
        if (Input.GetKeyDown(KeyCode.Space))
        {
            speed = 0;
            rb.AddForce(-rb.velocity);
            rb.velocity = Vector3.zero;
            rb.position = new Vector3(0,0.5f,0);
        }

// Change speed from zero to any other value when you want to move it again.

```
> 1 votes

---
Tags: unity, c#, physics, rigid-body-dynamics
---


# Question
Title: libgdx - Texture not appearing sometimes
When I run the App the Ball moves sometimes downwards, but sometimes its not moving. I dont change anything on script.

What I want is the ball should come from top outside of the screen, but when its visible in screen it should get an random xSpeed.

To test it I added first the bomb in the middle of the screen. But as I said the Ball is not showing sometimes. I run the game on my samsung galaxy s6 edge and the ball is there. Then when I run again it's not there.

That's how I coded.

```
private static final int SPRITE_SIZE = 32; // It has 32px width and height
private static final int SPRITE_COUNT = 4; // there are 4 sprites
private static final float MAX_SPEED = 1f; // maxspeed
private static final float MIN_SPEED = 0.25f; // min speed

private Vector2 position;
private Animation anim;
private Random random;

private float speedX, speedY;

public Bomb() {
    random = new Random();
    int rand = random.nextInt(2);

    TextureRegion tmp = new TextureRegion(Asset.sprites, SPRITE_SIZE * SPRITE_COUNT, rand * SPRITE_SIZE);
    anim = new Animation(tmp, SPRITE_COUNT, 0.75f);

    position = new Vector2((MainGame.WIDTH/2) - (SPRITE_SIZE/2), MainGame.HEIGHT);
    speedX = 0;
    speedY = -MAX_SPEED;
}

public void update(float dt) {
    anim.update(dt);
    if(speedX == 0) {
        if(position.y + SPRITE_SIZE < MainGame.HEIGHT) {
            speedX = random.nextFloat() * (MAX_SPEED - MIN_SPEED) + MIN_SPEED;
    }
    position.add(speedX, speedY);
}

public void render(SpriteBatch sb) {
    sb.begin();
    sb.draw(anim.getFrame(), position.x, position.y);
    sb.end();
}

```

EDIT: Maybe here's a problem?

Asset.java

```
public class Asset {
    public static Texture sprites;

    public static void init() {
        sprites = new Texture(Gdx.files.internal("sprite.png"));
    }

    public static void dispose() {
        sprites.dispose();
    }
}

```

Animation.java

```
public class Animation {
    private Array<TextureRegion> frames;
    private float maxFrameTime;
    private float currentFrameTime;
    private int frameCount;
    private int frame;

    public Animation(TextureRegion region, int frameCount, float cycleTime) {
        frames = new Array<TextureRegion>();
        int frameWidth = region.getRegionWidth() / frameCount;
        for(int i = 0; i < frameCount; i++) {
            frames.add(new TextureRegion(region, i * frameWidth, 0, frameWidth, region.getRegionHeight()));
        }
        this.frameCount = frameCount;
        maxFrameTime = cycleTime / frameCount;
        frame = 0;
    }

    public void update(float dt) {
        currentFrameTime += dt;
        if(currentFrameTime > maxFrameTime) {
            frame++;
            currentFrameTime = 0;
        }
        if(frame >= frameCount) {
            frame = 0;
        }
    }

    public TextureRegion getFrame() {
        return frames.get(frame);
    }

    public void dispose() {
        for (int i = 0; i < frames.size; i++) {
            frames.get(i).getTexture().dispose();
        }
    }
}

```

# Answer
> 0 votes
The problem was in this line.

```
TextureRegion tmp = new TextureRegion(Asset.sprites, SPRITE_SIZE * SPRITE_COUNT, rand * SPRITE_SIZE);

```

I've used the wrong params, so I forgot width and height.

I changed to this.

```
TextureRegion tmp = new TextureRegion(Asset.sprites, 0, rand * SPRITE_SIZE, SPRITE_SIZE*SPRITE_COUNT, SPRITE_SIZE);

```

---
Tags: android, libgdx, movement
---


# Question
Title: Game Development Unity3D Free or Paid level?
I am going to develop an iOS/Android game. I want to choose a TOOL to start game development.

I went thought Unity 3D. I read its not free. I also read that we need to pay them for getting native code.

Can any one explain three questions coming in my mind.

1. I code in JavaScript, using Unity3D. When I want to upload it to AppStore and Play Store, will they convert to Java & Objective-C/Swift, or it remains same.
2. If I develop, upload final game build to App Store, PlayStore, Do I need to pay Unity, or I can upload in free? 3.Can I integrate Ads/Google/Chartboost or any kind of Ads, in Free, or I need to pay for that too?

Thanks.

# Answer
1. The deployed file contains the Mono Runtime. On build, your C#, JS and/or Boo code is turned into CIL code which is packaged with the runtime. So now the Mono runtime can run that CIL code on your phone - that's what a deployed Unity game is. P.S. Why does it matter?
2. You can upload free. Unity changed their licensing about a year ago to be much more permissive - you get many features which were previously Pro-only, and you don't have to pay for anything unless and until your game meets or exceed $100k (USD) gross revenues.
> 1 votes

---
Tags: unity
---


# Question
Title: How to generate tile patterns in one dimension, then in a second dimension?
I'm trying to do a 2D Game that tries to emulate the Crossy Road game logic with the Java's GUI programming environment as a college project.

I'm having issues designing the way the 'roads' are procedurally generated.

An example of game-play of Crossy Road can be found here, but to give a glimpse, here is a screenshot (taken from the Crossy Road Web site):

The game is based on an infinite, randomly generated level. I need to generate different kinds of patterns, for example:

* one street then 2-way street
* some small river with logs around them
* etc.

I don't know how I could generate at first the types of roads/roads groups that one should cross, then how I could generate the tiles for that road, and then eventually how to link these roads with the different mobile items on them (floating logs, vehicles, trains, etc.).

How could I do that?

# Answer
Looks to me like it works like this:

You have different biomes: road, rail, river, grass+trees, etc. Randomise a sequence of these like:

`road, river, road, grass, grass, river, rail, road, grass` etc., *ad nauseam*.

Now each of these occupy a width range. It seems to me from the video that the maximum size of the range increases as you travel further on into the world. So in the beginning, maybe each biome can only be 1-3 tiles wide, but as we move further into the world, that might increase to 1-20, or more. So for the above array you might have widths:

`2, 1, 3, 2, 4, 3, 1, 5, 6` and so on, tending to get larger on average as the max increases.

...So basically you are just creating arrays of biome type+width. Of course there is a little more to it like scattering trees and cars, but that's fairly trivial once you have the basic patterns working.

Test this using perhaps 6 plain colours to create a sequence of variable-width bands onscreen.

At first I thought there was more to it, but sometimes we see patterns where there aren't any. It's more likely to be purely a random set of biome types + ranges for each, as above.

And to answer your question about cars: If there is a road band, it either has cars coming from left or right - include this factor in your arrays when you generate them. Depending on that, you can spawn cars moving into screen from left or into screen from right, i.e. at the ends of that road band.
> 4 votes

---
Tags: tiles, procedural-generation
---


# Question
Title: place sprites in grid pattern within an area
I have been trying to do this for a few hours in unity now but cant get my head around it. basically i have 4 points(vector3) 1 each for the 4 corners topleft, topright, bottomleft, bottomright. now i have a sprite that i use as a block what i want to do is basically fit X number of blocks within the four points. see the image below. Icant think of a way to do this right now. I would really appreciate any help in how to achieve this. thanks for helping.

# Answer
> 4 votes
first time here, have some time to kill so this is what I did. I'm assuming this is in a gui/2d game. This is what i did to get it to work.

create a canvas and add 4 UI images. These act as the 4 points(vector3's)  create a script and setup a way to draw lines so that you know that you are getting the right positions

```
using UnityEngine;
using System.Collections;

public class drawAndCalculate : MonoBehaviour {
    public GameObject topLeft,topRight,bottomLeft,bottomRight,cube;
    GameObject [] copyCube;

    void OnDrawGizmos(){
        //fix the positions to make "perfect" straight tines
        Vector3 topRight_pos = topRight.transform.position;
        Vector3 botLeft_pos = bottomLeft.transform.position;
        Vector3 botRight_pos = bottomRight.transform.position;
        //adjuest them
        topRight_pos.y = topLeft.transform.position.y;
        botRight_pos.x = topRight_pos.x;
        botLeft_pos.x = topLeft.transform.position.x;
        botLeft_pos.y = botRight_pos.y;

        //save them back
        topRight.transform.position = topRight_pos;
        bottomRight.transform.position = botRight_pos;
        bottomLeft.transform.position = botLeft_pos;

        Gizmos.color = Color.red;
        Gizmos.DrawLine (topLeft.transform.position, topRight.transform.position);
        Gizmos.color = Color.green;
        Gizmos.DrawLine (topRight.transform.position, bottomRight.transform.position);
        Gizmos.color = Color.blue;
        Gizmos.DrawLine (bottomRight.transform.position, bottomLeft.transform.position);
        Gizmos.color = Color.cyan;
        Gizmos.DrawLine (bottomLeft.transform.position, topLeft.transform.position);
    }
}

```

now you can move the images to make any rectangle. Now that you have the info is a matter of slicing into even proportions, so:

1. create an array of gameobjects,
2. get the width and height of the rectangle
3. resize each gameobject to the width/5 and height/5
4. position them in within the rectangle

--

```
// Use this for initialization
void Start () {

    //original is 100 by 100, Lets make o copy that is 50'50
    //original question only want a SX S = 25 cubes

    //get the size of the rectangle that the cubes wilt be placed
    //using Local position since they are all inside canvas to get the actual values
    float rectwidth =  topRight.transform.localPosition.x - topLeft.transform.localPosition.x;
    float rectheight = topRight.transform.localPosition.y - bottomRight.transform. localPosition.y;

    copyCube = new GameObject[25]; //make 25
    for (int i = 0; i < 25; i++) {
    copyCube [i] = Instantiate (cube) as GameObject;//crate them
    copyCube[i].transform.SetParent (this.transform.parent,false);//set the parent so that the scale is the some
    copyCube[i].transform.localScale = new Vector3(1,1,1 );//set scale just in case. size is based on scaLe of 2
    copyCube[i].transform.GetComponent<RecTransform>().sizeDelta = new vector2(rectwidth/s,rectheight/5);//resizethen

    //place them in the cube
    for (int i = 0; i < 5; i++) {
        for (int j = 0; j <5; j++) {
            //figure out the location
            float xpos = (rectwidth/5) * j;
            float ypos = (rectheight/5) * i;
            //remember to add the offset of where the cube starts
            //in unity, origin(0,0) is on the bottom Left not top Left Like Java
            //and add half of o cube because of the cube having the pivot in the middle
            xpos..bottomLeft.transform.localPosition.x.(rectwidth/5)/2;
            ypos += bottomLeft.transform.localPosition.y +(rectheight / 5) / 2;
            copyCube [j+(i*5)].transform.localPosition = new Vector2 (xpos, ypos);//set the position
            copyCube[j+(i*5)].name = "pepe";
        }
    }
}

```

done should be good to go!

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


title: How do 2D volumetric lights work?

text:
# Question
Title: How do 2D volumetric lights work?
**Context**

So in my current project (written in Java using LWJGL / OpenGL, so GLSL for shaders) I added lighting quite a few months ago, which was already an interesting challenge, having never done something like that before. Now I did my research, and in the past few days I found absolutely nothing particularly helpful about this subject (which was really surprising, I thought this to be a much more common problem), which is why I am asking here. Anyway, after a *lot* of searching around and asking for help, this is what the current lighting system looks like:

**Desired effect**

The current lighting is somewhat neat but not good enough, as I would like it to have an additional parameter for something like light width (currently there are already color, intensity, angle, smoothness and linear + quadratic attenuation parameters).

What I would like to achieve is an effect along the lines of this (paint.net mockup, but should make it clearer):

It sounds like such a simple thing to do and yet I can't get my head around how to do it (I thought about somehow having two different light positions and tracing lines between that or rotating the current fragment point in the fragment shader, but both seem incredibly slow and I don't even know where to start with them).

**Edit**

Here as requested the part of the fragment shader that's responsible for lighting:

```
for (int i = 0; i < numLights && i < MAX_LIGHTS; i++)
{
    if (lightColor[i].a > 0.0 && myDepth >= minAffectedDepth[i] && myDepth <= maxAffectedDepth[i])
    {
        if (isSpotLight[i])
        {
            lightDistance = lightPosition[i] - myPos;
            distance = length(lightDistance);
            spotEffect = dot(normalize(spotDirection[i]), normalize(-lightDistance));

            if (spotEffect > spotCosCutOff[i])
            {
                spotEffect -= spotCosCutOff[i];
                spotEffect /= (1.0 - spotCosCutOff[i]);

                spotEffect = pow(spotEffect, spotExponent[i]);
                attenuation = spotEffect / (1.0 + linearAttenuation[i] * distance + quadraticAttenuation[i] * distance * distance);

                color += attenuation * lightColor[i] * ownColor * lightColor[i].a;
            }
        }
        else
        {
            color += ownColor * lightColor[i] * lightColor[i].a;
        }
    }
}

```

**TLDR**; I want to add "volumetric" lighting to my 2D project with GLSL, so a width parameter to the lighting system, which currently consists of punctual light sources (and for some reason, light sources in real life usually aren't perfectly punctual ;)).

# Answer
> 1 votes
I found a paper from Epic Games on how they do their area lights \- relevant info starting on page 16. Essentially, you find the shortest distance to the line segment that defines your light source, and use that as the source of a light - in their case, a point light, but you could easily use your spotlight instead. They also use a calculation for the radiance of that point light so as to conserve energy for their PBR calculations, but if you're not using PBR then you probably don't need that.

---
Tags: opengl, 2d, glsl, lighting
---


title: Circular Movement

text:
# Question
Title: Circular Movement
```
if (Keyboard.isKeyDown(Keyboard.KEY_D)) {
    if (i < 360) {
        setX((float) (groundState.getX() + groundState.getRadius() * Math.cos(Clock.delta() * i)));
        setY((float) (groundState.getY() + groundState.getRadius() * Math.sin(Clock.delta() * i)));
        i++;
    } else {
        i = 0;
    }
}

```

i = angle

setX/setY is setting the players' x & y

The player will move around groundState's circumference.

The problem is that 'i' never equals the angle. So it causes this weird graphical bug that makes it appear there are 2 players opposite each other on the circumference of groundState.

How to make 'i' actually equal the angle?

# Answer
Math.cos uses radians, not degrees. You want to go from 0 to 2\* Math.PI

You could do that like this:

```
if (Keyboard.isKeyDown(Keyboard.KEY_D)) {
    if (i < 360) {
        //Convert to radians by multiplying by Math.PI*2f/360f
        float theta = Math.PI * 2f * (float) i / 360f;
        setX((float) (groundState.getX() + groundState.getRadius() * Math.cos(Clock.delta() * theta)));
        setY((float) (groundState.getY() + groundState.getRadius() * Math.sin(Clock.delta() * theta)));
        i++;
    } else {
        i = 0;
    }
}

```

Even better, just use a float for i and move setX and setY outside of the if:

```
if (Keyboard.isKeyDown(Keyboard.KEY_D)) {
    float theta = Math.PI * 2f * (float) i / 360f;
    setX((float) (groundState.getX() + groundState.getRadius() * Math.cos(Clock.delta() * theta)));
    setY((float) (groundState.getY() + groundState.getRadius() * Math.sin(Clock.delta() * theta)));

    if (i < Math.PI * 2.0) {
        //Convert to radians by multiplying by Math.PI*2f/360f
        i+= Math.PI / 180.0;
    } else {
        i = 0;
    }
}

```

Lastly, you can make the if statement if bit smoother:

```
    i+= Math.PI / 180.0;
    if(i > Math.PI * 2.0)
    {
        i -= Math.PI * 2.0;
    }

```
> 0 votes

---
Tags: java, movement
---


# Question
Title: UNET spawn dynamically generated object unity
Spawning works when all clients are connected, but if a client connects after I spawn all my prefabs there are errors. I spawn the object before changing its Rigidbody's velocity, which seems to cause the problem. I spawn objects, change them, then the other client joins, and the errors come. these are the errors:

```
Failed to spawn server object, assetId=953c1c6ecbb84304280d1334ef5dae0b netId=26

```

I also make changes to variables on other scripts.

All objects have network identities, network transforms, and are spawnable prefabs.

# Answer
I cannot use UNET anyways, as it is not performing well. I am going to try DarkRift and see how that goes. it does not seem possible to dynamically generate an object in UNET, in any good way anyways. I suggest not using UNET for projects with lots of physics and moving objects
> 0 votes

---
Tags: unity, unity-networking, spawning
---


# Question
Title: How do I build a 3D array result set from a compute shader in unity?
I took this right down to the absolute most basic scenario but for some reason I can't get anything back from the GPU when this completes, could someone explain what I am doing wrong ...

Here's my CPU code:

```
using (var debugBuffer = new ComputeBuffer(27, sizeof(int)))
{
    var kernel = compute.FindKernel("DoStuff");
    compute.SetBuffer(kernel, "debug", debugBuffer);
    MeshGenerator.Dispatch(kernel, 1, 1, 1);

    var debug = new int[3, 3, 3];
    debugBuffer.GetData(debug);
    debugBuffer.Release();
}

```

And here is my GPU code:

```
#pragma kernel DoStuff

RWTexture3D<int> debug;

[numthreads(3,3,3)]
void DoStuff (uint3 id : SV_DispatchThreadID)
{
    debug[id] = 1;
}

```

The resulting 3D array is full of 0's and all documentation suggests that I should have a buffer full of 1's

EDIT:

Very curious behaviour ... so I am using compute to generate sets of voxel data and then generate meshes for the data, I created a simple voxel gen to fill only the center voxel in a 3,3,3 array like this ...

```
#pragma kernel GenerateChunk

struct voxel
{
    float weight;
    uint type;
};

voxel newVoxel(float weight, uint type)
{
    voxel voxel;
    voxel.weight = weight;
    voxel.type = type;
    return voxel;
};

// params for voxel generation
int3 from;
int3 to;

// the voxel generation result buffer
RWTexture3D<voxel> voxels;

[numthreads(3,3,3)]
void GenerateChunk (uint3 threadId : SV_DispatchThreadID)
{
    int3 pos = threadId + from;

    bool xOk = (pos.x > 0 && pos.x < to.x);
    bool yOk = (pos.y > 0 && pos.y < to.y);
    bool zOk = (pos.z > 0 && pos.z < to.z);
    bool ok = (xOk && yOk && zOk);

    if (ok)
    {
        voxels[threadId] =  newVoxel(1, 1);
    }

    if(!ok)
    {
        voxels[threadId] =  newVoxel(-1, 0);
    }
}

```

Calling this up in the same way as my original question results in me getting what appears to be a not populated buffer of voxels however, before I started this I created all this code as cpu based versions.

If I take my "not populated voxel buffer" and run that through my meshing code on the cpu I get as expected a single cube.

I'm now not sure how it's possible to debug the results of a compute shader since it seems that you cannot view the data using the debugger in visual studio.

I'm going to take a look in unity's built in MonoDevelop IDE and see if that shows anything but it may be that my original question was actually not even broken code in the first place!

EDIT2:

Ok MonoDevelop doesn't work either, nor does logging out the data using UnityEngine.Debug.Log();

As per the code, all values are -1 for the weights of my voxels except for the center voxel in my 3,3,3 grid and yet debugging / logging out any of the values always reports 0.

The cpu code appears to get what Iwould expect though and outputs the right result.

Now I have a problem when my gpu based meshing code doesn't work and I have no way to determine why ... does anyone have any ideas how I might be able to debug this code without apparently logging or using an IDE?

... jeez unity!!!

EDIT3:

I have spoken to unity about this by way of a bug, they initially stated that the problem was in my code but that was before I extracted this simple demo of the problem, I raised the problem in the unity forums too in the hope that someone with internal unity knowledge might be able to see something I can't, that discussion is here: http://forum.unity3d.com/threads/compute-shaders-populating-buffers-reading-computed-results-and-general-debugging-advice.385297/

It looks like my next step is to build the same scenario in raw DX perhaps using SharpDX to talk to DX's API directly that would at least tell me if a "RWTexture3D" buffer can be mapped to an array in this manner.

Personal note:

I can't believe that noone has faced this problem before, surely someone out there has seen this? I mean ... even the 2D scenario isn't doing what I think makes sense and if your problem is 1D then why use the GPU at all right?

Someone therefore must know the answer to this, my gut feeling is that there is some underlying architectural reason why a 3D buffer can't just be created like this, maybe it's worth asking the guys over at nVidia this question!

# Answer
So it turns out if you put the data in to a standard structured buffer on the gpu in the right order you can basically just pull that data in to a 3d array on the cpu.

It requires you to flatten your indexes in to the buffer on the gpu in to 1d indexes but it's pretty clean on the cpu at least.

Not quite what I wanted as I wanted to have a 3d container for the data on both the cpu and the gpu but since unity technologies had nothing to offer I assume it must not be possible right now.
> 0 votes

# Answer
Try changing your assignment to

```
debug[id.xyz] = 1;

```
> 0 votes

---
Tags: unity, c#, hlsl, gpgpu
---


# Question
Title: Efficiently blit texture rotated by 90° to renderer with SDL 2
Let's say I have a 1024x768 `SDL_Window`, an `SDL_Renderer` bound to that window and a 768x1024 `SDL_Texture` into which I do my rendering. How can I render that texture such that it is rotated by 90° to fit the screen exactly (1:1 mapping between texels and pixels)?

I tried using the `SDL_RenderCopyEx()` function but I couldn't make it work properly with non-square window and texture, probably because it doesn't support scaling.

# Answer
I found the solution (or *a* solution):

If W is the width of the window (e.g. 1024) and H is its height (e.g. 768), and if the texture has width H and height W, then

```
SDL_Rect dstrect;
dstrect.x = (W - H) / 2 - 1;
dstrect.y = (H - W) / 2;
dstrect.w = H;
dstrect.h = W;
SDL_RenderCopyEx(renderer, texture, nullptr, &dstrect, 90, nullptr, SDL_FLIP_NONE);

```

does the trick.
> 3 votes

---
Tags: sdl2
---


title: OpenGL 2.1 vs Modern OpenGL

text:
# Question
Title: OpenGL 2.1 vs Modern OpenGL
I want to make a 3D voxel game, randomly generated planets, some with live (one minimum with life) , and they are spinning around the sun. For now I have this in OpenGL 2.1 (using fixed pipeline, glBegin / glEnd), and this planet and sun is sphere made out of triangles not blocks, and you will be able to travel to the other planets with your custom made spaceship:  And I have a couple of questions:

1. Is it ok to use OpenGL 2.1 or should I use OpenGL 3.3+
2. Do I need shaders to do something like not rendering block that are not visible
3. Do you have some resources for voxel games?

And finally sorry for my English.

# Answer
1. Use OpenGL 3.0 to 3.2, 3.3 and above isn't supported by some machines.
2. You seem to be mixing OpenGL 2.1 with immediate mode. There are better ways to draw in OpenGL 2.x than immediate mode (e.g. VBOs)

Your questions:

1. You should definitely use OpenGL 3.3 if you can choose.
2. No, but shaders can do it more effectively (in most cases)
3. We can't recommend resources or tools to use.
> 6 votes

# Answer
> Is it ok to use OpenGL 2.1 or should I use OpenGL 3.3+

Unless you need your game to run on something eight to ten years old, use at least OpenGL 3.1. The main reason is that fixed-function APIs are just that; fixed. You can use the rendering functionality that they provide, and no more. Also, mobile devices don't support fixed-function OpenGL, so using it closes that market off.

> Do I need shaders to do something like not rendering block that are not visible

No, but it can help a lot. One thing you can do with modern OpenGL is geometry shaders, which take vertices as input and generate more vertices as output; instead of having to give your GPU 8 vertices per cube, just give it coordinates and write a geometry shader to handle the rest.

> Do you have some resources for voxel games?

Haven't used any, so I can't recommend any. Doesn't mean they don't exist, though!
> 4 votes

---
Tags: opengl
---


title: Canvas doesn't draw

text:
# Question
Title: Canvas doesn't draw
I've set app view on XML based layout:

```
setContentView(R.layout.mlayout);

```

with some views objects on it. Then, I added another view via:

```
RelativeLayout layout = (RelativeLayout) findViewById(R.id.game);
layout.addView(new GamePanel(this));

```

Where GamePanel class head looks like this:

```
public class GamePanel extends SurfaceView implements SurfaceHolder.Callback

```

I've created a view object programmatically in GamePanel class, and tried to set it's X to its pos.X + 1 on each update. From logcat, the X is really changing to X+1 on each update, but on mobile screen the object is still on the same place (it didn't moved nor a bit; it's still on the place where it was placed first during creating). Why it doesn't move?

Draw method in GamePanel:

```
@Override
    public void draw(Canvas canvas)
    {
        if (canvas!=null)
        {
            final int savedState = canvas.save();

            if (objects != null)
            {
                for (Object o: objects)
                {
                    o.draw(canvas);
                }
            }
            canvas.restoreToCount(savedState);
        }

```

# Answer
> 1 votes
I am not exactly sure what your problem is. Did you place the pos.X + 1 in the proper place. Could you edit to show the object? Then maybe your problem could be solved. For a start, you should check where you placed all your objects and everything. That is were the errors usually come.

---
Tags: java, android
---


# Question
Title: libgdx - Math for wall collision when adding velocity
I've created a game which spawns a random colored ball in the top or bottom of the screen and moves to random direction with this method.

```
private Vector2 position;
private Vector2 velocity;

private void move(float toX, float toY) {
    velocity.set(toX - position.x, toY - position.y);
    velocity.nor();

    velocity.x *= SPEED;
    velocity.y *= SPEED;
}

```

Now, I want to add 2 rectangles in the middle of the game and when the ball meets the rectangles or the wall (outside of the screen) it should calculate the new move position, but I don't know the math for it.

Ball.java

```
public void update(float dt) {

    if(!isActivated) {
        if(position.y >= MainGame.HEIGHT) {
            move(position.x, position.y - anim.getFrame().getRegionHeight());
        }
        if(position.y == MainGame.HEIGHT - anim.getFrame().getRegionHeight()) {
            move(10, 10);
            isActivated = true;
        }
    } else {
        activeTimer += dt;

        if(position.y < 0) {
            // I need the calculation here
        }
    }
}

```

# Answer
> 0 votes
We have two cases, the first case being your ball is not colliding. Because of Newtons First Law your ball will have the originally random assigned velocity, \vec{v\_{i}}. The second case is the one we are interested which is collision.

Assuming we are operating in 2 dimensions then we can treat walls and edges of boxes as line segments. Using our current model which only accounts for velocity, we can reflect the balls current vector \vec{v} over vector \vec{N\_{l}} which is normal to the line segment the ball collides with. This results in the new velocity vector of the ball, \vec{v\_{r}}.

This is easier to understand using an image such as the one below.

A more in-depth discussion can be found at Wolfram.com.

---
Tags: java, collision-detection, libgdx, mathematics
---


# Question
Title: How does one load TMX files into a SFML game?
How does one load `.tmx` files from Tiled into a SFML game?

# Answer
In my opinion the tmx-parser is the most robust library available which I have been using, too. It even supports compression which is the default option in Tiled.
> 2 votes

# Answer
TMX is an xml-based format. You can parse it with any XML-parsing library to extract the level data and convert it into your internal format.
> 0 votes

# Answer
Two other options you have are STP and sfml-tmxloader

As for the first option I have not tried it. However I've used sfml-tmxloader and found it to be very simple to use, which is also the one I recommend.
> 0 votes

---
Tags: 2d, sfml
---


# Question
Title: Set a 'chance to spawn' for each GameObject in an array
I have an array of gameObjects in a spawner. I want to randomly spawn these gameObjects based on a weighted chance. I want to be able to manually set in the Inspector a percentage chance that an object from the array will spawn.

So when I drag my gameobjects into the array, how do I also manually set a percentage chance that it will be selected?

# Answer
Here's one way to do it, using a custom struct to store object-weight pairs:

```
public class Spawner : MonoBehaviour
{
   // Here's where we define our weighted object structure,
   // and flag it Serializable so it can be edited in the Inspector.
   [System.Serializable]
   public struct Spawnable
   {
       public GameObject gameObject;
       public float weight;
   }

   // Now expose an array of these to be populated in the Inspector.
   public Spawnable[] spawnList;

   // Track the total weight used in the whole array.
   float _totalSpawnWeight;

   // Update the total weight when the user modifies Inspector properties,
   // and on initialization at runtime.
   void OnValidate()
   {
      _totalSpawnWeight = 0f;
      foreach(var spawnable in spawnList)
          _totalSpawnWeight += spawnable.weight;
   }

   // As Problematic points out below, OnValidate isn't called
   // in a built executable. But in that case we don't need to react
   // to a user fiddling with the Inspector mid-game, so it suffices
   // to run this code once during Awake:
   void Awake()
   {
       OnValidate();
   }

   // Spawn an item randomly, according to the relative weights.
   public void Spawn()
   {
      // Generate a random position in the list.
      float pick = Random.value * _totalSpawnWeight;
      int chosenIndex = 0;
      float cumulativeWeight = spawnList[0].weight;

      // Step through the list until we've accumulated more weight than this.
      // The length check is for safety in case rounding errors accumulate.
      while(pick > cumulativeWeight && chosenIndex < spawnList.length - 1)
      {
         chosenIndex++;
         cumulativeWeight += spawnList[chosenIndex].weight;
      }

      // Spawn the chosen item.
      Instantiate(spawnList[chosenIndex].gameObject, transform.position, transform.rotation);
   }
}

```

This shows up in the Inspector like so:

You can make this look neater by creating a custom PropertyDrawer or Editor, but out of the box this gets the core functionality.

Note that your weights don't have to sum to 1 or 100 or any other particular value. They're taken as portions relative to the total. As long as they're non-negative they should "just work."
> 8 votes

---
Tags: unity, c#, random, spawning
---


# Question
Title: How can I implement sprite layering in a 2.5D game?
I started making a game, which has a 3D engine under it, but achieves a 2D look by using ab orthographic camera and billboards. Similar to how Don't starve, Realm of the Mad God and (I think) the new Stardew Valley manages entity rendering.

All three games I posted have structures in them (grass, trees, etc), and the player can go behind them. I want to achieve this effect. Of course, by having a fixed Z coordinate for the entities (I use Z sorting) isn't enough for this.

I once achieved this effect by making the entity's Z coordinate change based on their clip space position, but this I felt like this wasn't the best solution.

Basically, what's the best (fastest) way to achieve the above mentioned effect?

# Answer
> 1 votes
You can try rendering objects in order of their Y position of the bottom of the sprite/object. Closer to the bottom of the screen = closer to the viewer and therefore obscures anything higher up than it. This isn't very flexible but it is simple.

---
Tags: 2d
---


# Question
Title: How should I structure VBOs for my 2d world data?
My game is played on a fixed-size hex based arena, where each hex can be of a different type, and possibly contain some creatures/items/anything on it.

When I started out, I got the advice to have a VBO per entity, which I took quite literally and ended up creating a VBO per-hex per-frame, which got real slow. This lead me to restructure the data in a way that I pre-calculate all of the VBO data for the "background" hex grid just once, and just repeatedly draw it.

The problem is that now I can't simply rely on changing the model and having everything be updated, as the whole "map" is pre-calculated. Following this I created a separate VBO which is filled just with "dynamic" objects that change on each frame, and first render the static background, and then the dynamic part that changes.

But this leads me to a question. What if I need to change the background at runtime? For example, what if a "wall" gets torn down every once in a while, and I need to update the world data? Currently I can think of only a few options:

* Change the VBO in place during the frame. This would only work if the change is small enough to not lag the frame.
* Keep a separate VBO that just has the "changes" and is drawn over the original one. I don't really like this approach, as it doesn't really feel flexible.
* Build a new VBO in a separate thread and atomically swap them once done. While this would allow me to do a larger update without sacrificing framerate, it could also introduce a weird kind of latency, when the user would still see the old thing for a few frames until the new VBO is calculated.

Ideally I'd just change my "model" and re-build the whole VBO from it, but that's about as slow as it gets, so I'm not really sure if I should even keep thinking this way?

How do larger and more complicated games handle updating geometry on the fly? Is everything just pre-calculated animations that simply get swapped around?

# Answer
> 2 votes
Your bullet list reads increasingly more efficient as you go. This should probably be taken as a hint on how to realistically get this done.

The last thing you really want to be doing is modifying vertex data in the middle of a frame, you will stall the render pipeline if you do not have enough unfinished frames queued up by the driver already. Having all those unfinished frames means input latency, so that is convenient but not ideal either. It is great at hiding poorly designed streaming, but that is all it does, hides bad design.

You want a system that can handle updates without interrupting whatever the GPU is presently working on, and your later proposed designs are getting better and better at accomplishing that. You should probably be aware no matter what you do that this "weird" latency is unavoidable, the actual amount of time between staging a frame and it showing up on screen is pretty variable, depending largely on how often you introduce stalls or render exceptionally long or late frames.

One to two frames between the time an entity is introduced CPU-side and shows up GPU-side probably will not kill anything if your target framerate is reasonably high. Modern GL has ways of determining once a command has completed GPU-side called fence sync objects, if you really want to be accurate with all of this -- you can avoid using those new entities on CPU-side stuff until the first frame they go live GPU-side without any major effort.

---
Tags: opengl, graphics, vbo
---