# Question
Title: How to detect collision of a wall with grid movement?
I have this little game, where my player is moving around a simple level, using a grid based movement script (See code below). My problem is that I have tried to implement a 2D raycast, which has to detect if the next 'tile' is a movable tile (not a wall). However all the examples I have found on the internet hasn't been something I could make work. So please help me with how I can detect if the player is allowed to move, before he moves.

I am using Unity 5.

```
using System.Collections;
using UnityEngine;

public class GridMove : MonoBehaviour {
    public float moveSpeed = 2f;

    private float gridSize = 1f;
    private enum Orientation {
        Horizontal,
        Vertical
    };
    private Orientation gridOrientation = Orientation.Vertical;
    private bool allowDiagonals = false;
    private bool correctDiagonalSpeed = true;
    private Vector2 input;
    private bool isMoving = false;
    private Vector3 startPosition;
    private Vector3 endPosition;
    private float t;
    private float factor;
    private Animator animator;

    // Use this for initialization
    void Start () {
        animator = GetComponent<Animator>();
    }

    public void Update() {
        if (!isMoving) {
            input = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
            if (!allowDiagonals) {
                if (Mathf.Abs(input.x) > Mathf.Abs(input.y)) {
                    input.y = 0;
                } else {
                    input.x = 0;
                }
            }

            if (input != Vector2.zero) {
                StartCoroutine(Move(transform));
                animator.SetBool("isWalking", true);
            }
            else {
                animator.SetBool("isWalking", false);
            }
        }
    }

    public IEnumerator Move(Transform transform) {
        isMoving = true;
        startPosition = transform.position;
        t = 0;

        animator.SetFloat("x", input.x);
        animator.SetFloat("y", input.y);

        if(gridOrientation == Orientation.Horizontal) {
            endPosition = new Vector3(startPosition.x + System.Math.Sign(input.x) * gridSize,
                                      startPosition.y, startPosition.z + System.Math.Sign(input.y) * gridSize);
        } else {
            endPosition = new Vector3(startPosition.x + System.Math.Sign(input.x) * gridSize,
                                      startPosition.y + System.Math.Sign(input.y) * gridSize, startPosition.z);
        }

        if(allowDiagonals && correctDiagonalSpeed && input.x != 0 && input.y != 0) {
            factor = 0.7071f;
        } else {
            factor = 1f;
        }

        while (t < 1f) {
            t += Time.deltaTime * (moveSpeed/gridSize) * factor;
            transform.position = Vector3.Lerp(startPosition, endPosition, t);
            yield return null;
        }

        isMoving = false;
        yield return 0;
    }
}

```

# Answer
If you're using a grid, you shouldn't be using Unity's physics for collision detection - use the grid. Get your position on the grid then do something like this:

```
public bool GridCast (Coordinate Position, Coordinate Direction, int Length)
{
    for (int i = 0; i < Length; i++)
    {
        Coordinate Check = Position + Direction * Length;
        if (GridNodes[Check.x,Check.y].Occupied)
        {
            //Collision
            return true;
        }
    }
    return false;
}

```

To check if you can walk forward 4 tiles, do something like this:

```
if (GridPhysics.GridCast(MyCoordinate, new Coordinate (0,1), 4))
{
   //Something's in the way
}
else{
   //Nothing's in the way; proceed with walking
}

```

If you want to find out how many tiles you can walk forward IF something is in the way, add an out parameter called Point that represents the point of collision.

```
Coordinate Check = Position + Direction * Length;
if (GridNodes[Check.x,Check.y].Occupied)
{
    //Collision
    *Point = Check*
    return true;
}

```

Then just move up to that point.

```
Move (Point - MyCoordinate);

```

To answer the title question, you can create a wall by simply accessing the GridNodes array and marking the nodes the wall occupies and detect collision with the GridCast method.

```
For (int i = Wall.MyCoordinate.x; i < Wall.Width + Wall.MyCoordinate.x; i++)
{
    for (int j = Wall.MyCoordinate.y; j < Wall.Height + Wall.MyCoordinate.y; j++)
    {
        GridNodes[i,j].Occupied = true;
    }
}

```

Note that this GridCast implementation won't work accurately for diagonals but it will be uber fast, especially if you flatten the GridNodes array.

---

Here's an example of something else you can do with a grid map: https://www.youtube.com/watch?v=MEd6XV2Pecw. I call it influence map in this overview but the concepts remain the same - map your position to a 2D point on the grid's plane then do whatever you need to with the point and the information stored in the grid.

Pathfinding, fog of war (would be really cool for a grid game), and AI Bots can all be implemented with an influence map. I'm 99.99% sure MineCraft uses a flattened 3D array to store its blocky information. Starcraft uses a grid for pathfinding, building, and attack searching (I think). Anyways, you get the point. Grids are cheap, effective ways of storing and interacting with information.
> 3 votes

# Answer
Using a 2D tile array for your world/level generation and representation will definitely simplify things. For example you could internally represent your world in a grid of tiles and take it from there :

```
using System;
using System.Collections.Generic;
using System.Text;

namespace Tiles {
    public class Vector2 {
        public int x; public int y;
        public Vector2(int x, int y) {
            this.x = x; this.y = y;
        }
    }

    public enum TileType {
        None,
        Grass,
        Dirt,
        Stone,
        Water,
        Air,
    }

    public class Tile {
        public Vector2 position;
        public TileType tileType;

        public Tile(int x, int y, TileType tileType) {
            this.position = new Vector2(x, y);
            this.tileType = tileType;
        }
    }

    public class World {
        public Tile[,] tiles;
        public int sizeX; public int sizeY;

        public World(int sizeX, int sizeY) {
            this.sizeX = sizeX;
            this.sizeY = sizeY;
            int tileCount;

            // build the world
            tiles = new Tile[sizeX, sizeY];

            Random rnd = new Random();
            tileCount = Enum.GetValues(typeof(TileType)).Length;
            // construct grid of tiles
            for (int x = 0; x < sizeX; x++) {
                for (int y = 0; y < sizeX; y++) {
                    tiles[x, y] = new Tile(x, y, (TileType)rnd.Next(tileCount));
                }
            }
        }
    }

    class Program {
        static void Main(string[] args) {
            World world = new World(20, 20);
            for (int y = 0; y < world.sizeY; y++) {
                for (int x = 0; x < world.sizeX; x++) {
                    Console.Write((int)world.tiles[x, y].tileType + " ");
                }
                Console.WriteLine();
            }
        }
    }
}

```

Once thats set up you can then interrogate a tile in your move path to see if its walkable based on the terrain type, or if it's blocked by an child obstacle etc.
> 2 votes

---
Tags: unity, 2d, collision-detection, grid
---


# Question
Title: Determine if an object is inside a ship's turn radius, rotation via torque
I have a 3d space game where all ships move around using physics. I am trying to determine if a given object is reachable by a ship at a given velocity and turn radius. I believe the formula for turn radius `movementSpeed / rotation_in_radians` but that doesn't seem to be working for me. I think it is because the torque rotations are unpredictable and changing rotations takes extra time because of excess torque in a different direction. There is also a bit of a slip factor in `AerodyanmicEffect` that probably needs to be accounted for.

I have code to tell if something is within a given turn radius that I am pretty sure works

```
  public bool InsideTurnRadius(Vector3 point) {
    float turnRadius = GetTurnRadius();
    var toTarget = point - transform.position;
    toTarget = Vector3.ProjectOnPlane(toTarget, transform.forward);
    var toCenterNormalized = toTarget.normalized;
    var turnRadiusCenter = transform.position + toCenterNormalized * turnRadius;

    return ((point - turnRadiusCenter).sqrMagnitude) > (turnRadius * turnRadius);
}

```

But I don't know how to actually find the right turn radius value to plug in there.

Does anybody know how I can account for all the forces to determine if a target point is reachable?

I am using a cut down and modified version of the Unity Standard Assets Plane script.

```
public class SpaceCraftController : MonoBehaviour {
[SerializeField]
private float m_MaxEnginePower = 40f;        // The maximum output of the engine.
[SerializeField]
private float m_AerodynamicEffect = 0.5f;   // How much aerodynamics affect the speed of the aeroplane.
[SerializeField]
private float m_ThrottleChangeSpeed = 0.3f;  // The speed with which the throttle changes.

public float Throttle { get; private set; }                     // The amount of throttle being used.
public float ForwardSpeed { get; private set; }                 // How fast the aeroplane is traveling in it's forward direction.
public float EnginePower { get; private set; }                  // How much power the engine is being given.
public float MaxEnginePower { get { return m_MaxEnginePower; } }    // The maximum output of the engine.
public float RollAngle { get; private set; }
public float PitchAngle { get; private set; }
public float RollInput { get; private set; }
public float PitchInput { get; private set; }
public float YawInput { get; private set; }
public float ThrottleInput { get; private set; }

public float maxPitchSpeed = 360;
public float maxRollSpeed = 360;
public float maxYawSpeed = 360;
public bool useAeroFactor = true;

private float m_AeroFactor;
private Rigidbody m_Rigidbody;

[Header("Debug")]
public bool drawVelocity = true;

/* THIS IS WHAT I NEED A HAND WITH */
public float TurnRadius {
    get {
        float pitchRadius = maxPitchSpeed * Mathf.Deg2Rad;
        float yawRadius = maxYawSpeed * Mathf.Deg2Rad;
        if (pitchRadius > yawRadius) {
            return ForwardSpeed / (yawRadius);
        } else {
            return ForwardSpeed / (pitchRadius);
        }
    }
}

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

public void Move(float rollInput, float pitchInput, float yawInput, float throttleInput) {
    RollInput = rollInput;
    PitchInput = pitchInput;
    YawInput = yawInput;
    ThrottleInput = throttleInput;

    ClampInputs();

    CalculateRollAndPitchAngles();

    ControlThrottle();

    CaluclateAerodynamicEffect();

    CalculateTorque();

    if (drawVelocity) {
        Debug.DrawRay(transform.position, GetComponent<Rigidbody>().velocity.normalized * ForwardSpeed, Color.white);
    }
}

private void ClampInputs() {
    RollInput = Mathf.Clamp(RollInput, -1, 1);
    PitchInput = Mathf.Clamp(PitchInput, -1, 1);
    YawInput = Mathf.Clamp(YawInput, -1, 1);
    ThrottleInput = Mathf.Clamp(ThrottleInput, -1, 1);
}

/* ALSO not 100% sure why this works, if anybody knows I'd be very happy to learn*/
private void CalculateRollAndPitchAngles() {
    // Calculate roll & pitch angles
    // Calculate the flat forward direction (with no y component).
    var flatForward = transform.forward;
    flatForward.y = 0;
    if (flatForward.sqrMagnitude > 0) {
        flatForward.Normalize();
        // calculate current pitch angle
        var localFlatForward = transform.InverseTransformDirection(flatForward);
        PitchAngle = Mathf.Atan2(localFlatForward.y, localFlatForward.z);
        // calculate current roll angle
        var flatRight = Vector3.Cross(Vector3.up, flatForward);
        var localFlatRight = transform.InverseTransformDirection(flatRight);
        RollAngle = Mathf.Atan2(localFlatRight.y, localFlatRight.x);
    }

}

private void ControlThrottle() {
    Throttle = Mathf.Clamp01(Throttle + ThrottleInput * Time.deltaTime * m_ThrottleChangeSpeed);
    EnginePower = Throttle * m_MaxEnginePower;
    m_Rigidbody.AddForce(EnginePower * transform.forward, ForceMode.Acceleration);
    var velocity = m_Rigidbody.velocity;
    var magnitude = velocity.magnitude;
    if (magnitude > 0 && magnitude > m_MaxEnginePower) {
        velocity *= (m_MaxEnginePower / magnitude);
        m_Rigidbody.velocity = velocity;
    }
    // Forward speed is the speed in the forward direction (not the same as its velocity)
    var localVelocity = transform.InverseTransformDirection(m_Rigidbody.velocity);
    ForwardSpeed = Mathf.Max(0, localVelocity.z);
}

private void CaluclateAerodynamicEffect() {
    // "Aerodynamic" calculations. This is a very simple approximation of the effect that a plane
    // will naturally try to align itself in the direction that it's facing when moving at speed.
    // Without this, the plane would behave a bit like the asteroids spaceship!
    if (m_Rigidbody.velocity.sqrMagnitude > 0) {
        // compare the direction we're pointing with the direction we're moving
        //areoFactor is between 1 and -1
        m_AeroFactor = Vector3.Dot(transform.forward, m_Rigidbody.velocity.normalized);
        // multipled by itself results in a desirable rolloff curve of the effect
        m_AeroFactor *= m_AeroFactor;
        // Finally we calculate a new velocity by bending the current velocity direction towards
        // the the direction the plane is facing, by an amount based on this aeroFactor
        var newVelocity = Vector3.Lerp(m_Rigidbody.velocity, transform.forward * ForwardSpeed,
                                       m_AeroFactor * ForwardSpeed *
                                       m_AerodynamicEffect * Time.deltaTime);
        m_Rigidbody.velocity = newVelocity;

        // also rotate the plane towards the direction of movement
        m_Rigidbody.rotation = Quaternion.Slerp(m_Rigidbody.rotation,
                                              Quaternion.LookRotation(m_Rigidbody.velocity, transform.up),
                                              m_AerodynamicEffect * Time.deltaTime);
    }
}

private void CalculateTorque() {
    var torque = Vector3.zero;
    torque += PitchInput * (maxPitchSpeed * Time.deltaTime) * transform.right;
    torque += YawInput * (maxYawSpeed * Time.deltaTime) * transform.up;
    torque += -RollInput * (maxRollSpeed * Time.deltaTime) * transform.forward;
    if (useAeroFactor) {
        m_Rigidbody.AddTorque(torque * m_AeroFactor, ForceMode.Acceleration);
    } else {
        m_Rigidbody.AddTorque(torque, ForceMode.Acceleration);
    }

```

# Answer
You may use splines to predict body trajectory based on short history. For example, script below interpolates trajectory of object with cubic splines then use these spline to extrapolate future movement of the object.

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

// Natural cubic spline

public class CubicSpline
{
 #region Public
 public struct Cubic
 {
  public float a;
  public float b;
  public float c;
  public float d;

  public void Set(float A, float B, float C, float D)
  {
   a = A; b = B; c = C; d = D;
  }

  public float Evaluate(float T)
  {
   return ( ( ( d * T) + c ) * T + b ) * T + a;
  }
 };

 public float[] ControlPoints = new float[0];
 public Cubic[] Cubics = new Cubic[0];
 public int NumControlPoints { get { return ControlPoints.Length; } }
 #endregion

 #region Private
 private float[] _gamma;
 private float[] _delta;
 private float[] _D;
 #endregion

 #region Interface
 public CubicSpline(int numControlPoints)
 {
  Resize( Mathf.Max( numControlPoints, 3 ) );
 }

 public void Resize(int numControlPoints)
 {
  ControlPoints = new float[numControlPoints];
  Cubics = new Cubic[numControlPoints];
  _gamma = new float[numControlPoints];
  _delta = new float[numControlPoints];
  _D = new float[numControlPoints];
 }

 public void Calculate(int numControlPoints)
 {
  if( Cubics.Length < numControlPoints ) System.Array.Resize<Cubic>( ref Cubics, numControlPoints );
  if( _gamma.Length < numControlPoints ) System.Array.Resize<float>( ref _gamma, numControlPoints );
  if( _delta.Length < numControlPoints ) System.Array.Resize<float>( ref _delta, numControlPoints );
  if( _D.Length < numControlPoints ) System.Array.Resize<float>( ref _D, numControlPoints );

  int n = numControlPoints-1;
  int i;

  _gamma[0] = 1.0f/2.0f;
  for ( i = 1; i < n; i++)
  {
   _gamma[i] = 1/(4-_gamma[i-1]);
  }
  _gamma[n] = 1/(2-_gamma[n-1]);

  _delta[0] = 3*(ControlPoints[1]-ControlPoints[0]) * _gamma[0];
  for ( i = 1; i < n; i++)
  {
   _delta[i] = (3*(ControlPoints[i+1]-ControlPoints[i-1])-_delta[i-1])*_gamma[i];
  }
  _delta[n] = (3*(ControlPoints[n]-ControlPoints[n-1])-_delta[n-1])*_gamma[n];

  _D[n] = _delta[n];
  for ( i = n-1; i >= 0; i--)
  {
   _D[i] = _delta[i] - _gamma[i]*_D[i+1];
  }

  for( i = 0; i < n; i++ )
  {
   Cubics[i].Set(
    ControlPoints[i],
    _D[i],
    3*(ControlPoints[i+1] - ControlPoints[i]) - 2*_D[i] - _D[i+1],
    2*(ControlPoints[i] - ControlPoints[i+1]) + _D[i] + _D[i+1]
    );
  }
 }
 #endregion
};

// Trajectory

public class SplineTrajectory : MonoBehaviour
{
 public int NumHistoryPoints = 100;
 public int NumControlPoints = 5;

 CubicSpline _xSpline = null;
 CubicSpline _ySpline = null;
 CubicSpline _zSpline = null;

 float[] _xControlPoints;
 float[] _yControlPoints;
 float[] _zControlPoints;

 List<Vector3> _xyzHistory = new List<Vector3>();

 // Use this for initialization
 void Start ()
 {
  _xControlPoints = new float[NumControlPoints];
  _yControlPoints = new float[NumControlPoints];
  _zControlPoints = new float[NumControlPoints];
 }

 // Update is called once per frame
 void LateUpdate ()
 {
  _xyzHistory.Add( transform.position );
  if( _xyzHistory.Count > NumHistoryPoints ) _xyzHistory.RemoveAt( 0 );
  if( _xyzHistory.Count >= NumControlPoints )
  {
   if( _xSpline == null ) _xSpline = new CubicSpline( NumControlPoints );
   if( _ySpline == null ) _ySpline = new CubicSpline( NumControlPoints );
   if( _zSpline == null ) _zSpline = new CubicSpline( NumControlPoints );

   for( int i=0; i<NumControlPoints; i++ )
   {
    int indexInHistory = Mathf.Clamp( i*_xyzHistory.Count/(NumControlPoints-1), 0, _xyzHistory.Count-1 );
    _xControlPoints[i] = _xyzHistory[indexInHistory].x;
    _yControlPoints[i] = _xyzHistory[indexInHistory].y;
    _zControlPoints[i] = _xyzHistory[indexInHistory].z;
   }

   _xSpline.ControlPoints = _xControlPoints;
   _ySpline.ControlPoints = _yControlPoints;
   _zSpline.ControlPoints = _zControlPoints;

   _xSpline.Calculate( NumControlPoints );
   _ySpline.Calculate( NumControlPoints );
   _zSpline.Calculate( NumControlPoints );
  }
 }

 void OnDrawGizmos()
 {
  if( _xSpline != null && _ySpline != null && _zSpline != null )
  {
   const int Details = 10;

   Gizmos.color = Color.red;

   Vector3 p0 = new Vector3( _xSpline.ControlPoints[0], _ySpline.ControlPoints[0], _zSpline.ControlPoints[0] );
   Vector3 p1 = Vector3.zero;

   for( int i=0; i<NumControlPoints-1; i++ )
   {
    for( int j=0; j<Details; j++ )
    {
     p1.x = _xSpline.Cubics[i].Evaluate( (float)(j) / (float)(Details) );
     p1.y = _ySpline.Cubics[i].Evaluate( (float)(j) / (float)(Details) );
     p1.z = _zSpline.Cubics[i].Evaluate( (float)(j) / (float)(Details) );

     Gizmos.DrawLine( p0, p1 );

     p0 = p1;
    }
   }

   Gizmos.color = Color.green;

   for( int i=0; i<NumControlPoints-1; i++ )
   {
    for( int j=0; j<Details; j++ )
    {
     p1.x = _xSpline.Cubics[NumControlPoints-2].Evaluate( 1.0f + (float)(i*Details+j)/(float)(Details) );
     p1.y = _ySpline.Cubics[NumControlPoints-2].Evaluate( 1.0f + (float)(i*Details+j)/(float)(Details) );
     p1.z = _zSpline.Cubics[NumControlPoints-2].Evaluate( 1.0f + (float)(i*Details+j)/(float)(Details) );

     Gizmos.DrawLine( p0, p1 );

     p0 = p1;
    }
   }
  }
 }
}
```
> 2 votes

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


# Question
Title: Unity2D Sprite flips camera when moving left and right
I am using the Unity Engine and coding in C#.

I have a sprite as a parent with a main camera as a child so that the main camera follows the sprite. However, when pressing 'A' and 'D' to move the camera 'flips 180 degrees' due to me using transform.eulerangles is there anyway that the camera can be excluded from this 'flip'?

```
void Movement () {

anim.SetFloat ("moveSpeed", Mathf.Abs (Input.GetAxisRaw ("Horizontal")));

if (Input.GetAxisRaw ("Horizontal") > 0) {
  transform.Translate (Vector3.right * moveSpeed * Time.deltaTime);
  transform.eulerAngles = new Vector2(0,0);
}

if (Input.GetAxisRaw ("Horizontal") < 0) {
  transform.Translate (Vector3.right * moveSpeed * Time.deltaTime);
  transform.eulerAngles = new Vector2(0,180);
}
}

```

# Answer
Hold a reference to your Camera, then set its localEurlerAngles to Vector3.zero.

```
Camera yourCamera;

void Start()
{
    yourCamera = GetComponentInChildren<Camera>();
}

void Movement () {

    anim.SetFloat ("moveSpeed", Mathf.Abs (Input.GetAxisRaw ("Horizontal")));

    if (Input.GetAxisRaw ("Horizontal") > 0) {
      transform.Translate (Vector3.right * moveSpeed * Time.deltaTime);
      transform.eulerAngles = new Vector2(0,0);
      yourCamera.transform.localEurlerAngles = Vector3.zero;

    }

    if (Input.GetAxisRaw ("Horizontal") < 0) {
      transform.Translate (Vector3.right * moveSpeed * Time.deltaTime);
      transform.eulerAngles = new Vector2(0,180);
      yourCamera.transform.localEurlerAngles = Vector3.zero;
    }
}

```
> 0 votes

# Answer
Rather than rotating a sprite, I would suggest you try multiplying the sprite's x scale by -1. This will flip the sprite without having to rotate anything.
> 2 votes

---
Tags: unity, c#, 2d
---


title: Shader - Color blending

text:
# Question
Title: Shader - Color blending
I would like to know how to blend colors in a specific way.

Let's imagine that I have a color **(A)** and an other color **(B)**.

I would like to blend them in such a way that if I choose white for the **(B)** then the output color is **(A)** but if have any other color for **(B)** it outputs a blending of **(A)** and **(B)**.

* I've tried the addition, but it doesn't give the expected result.
* I've tried the multiplicative blending it's quite good for the **(B)** white value but it fail for a blue **(B)** and red **(A)** colors.

Any idea how to do that ? Thanks a lot.

# Answer
You can get this behaviour without a branch using the step function:

```
float blendFactor = step(3.0f, dot(B.rgb, B.rgb));
return lerp(B, A, blendFactor);

```

When B = (1, 1, 1), dot(B, B) = 3.0f, so step returns 1, blendFactor = 1, and the lerp gives a result of A.

When B is anything less, dot(B, B) \< 3.0f, so step returns 0, blendFactor drops to 0, and the lerp gives a result of B.

(Here I'm assuming B's components are in the range 0...1)

.

**Edit:** if you'd prefer a smooth blend, you can calculate blendFactor like this instead:

```
float blendFactor = saturate(1.0f - sharpness * (dot(B.rgb, B.rgb) - 3.0f));

```

Here "sharpness" is a parameter you can use to control how narrow the blend range is. Very large values will make the output jump from A to B like step(), while smaller values will let it blend out a little when B is close to white.
> 4 votes

---
Tags: opengl, shaders, directx, glsl, hlsl
---


title: How is RTS Local Avoidance Done?

text:
# Question
Title: How is RTS Local Avoidance Done?
Currently, I'm simulating physics impact forces for local avoidance of units but this method sometimes pushes units out of formation and has very undesirable effects when units clump up.

For RTS games like Starcraft 2, how is local avoidance done? Are physics simulated or an omnicient controller decides where everything should be? I know this question might be a little broad so I'm asking specifically for how to achieve the local avoidance behaviors of Starcraft 2; though anything that works will be very appreciated.

I'm not looking for any code - just useful resources or explanations of how Starcraft 2 (or similar games) handles local avoidance.

Currently, I have collision detection (with penetration vector), collision forces, and movement by velocity implemented. Every unit is checked against another for a collision - if they collide, the objects are immediately offset by the penetration vector then the collision force is applied. Then another loop moves the objects by their velocities and applies drag to the velocities. The offset mitigates the problem of excessive collision forces applied on clumped units, but units still sometimes shoot out.

The solution I'm looking for needs to satisfy the following requirements (as in Starcraft 2):

* Objects musn't overlap; or at least overlaps must be eventually resolved.
* Objects don't push each other away more than necessary so 2 units can stand and move next to each other in a formation.
* There should not be any weird behaviors when objects clump towards the same destination.
* Can support units of different sizes, and even different convex shapes.

What I've been thinking of so far is instead of detecting for collisions, detect for future collisions so the overlap never happens. Then apply the constraint, making sure the 2 units' velocities don't cause them to overlap. I'm still tinkering with the algorithm for restricting movement beyond the overlap.

# Answer
> 16 votes
It seems like what you're looking for is the Optimal Reciprocal Collision Avoidance algorithm. The preceding paper is also worth a read. Although the paper may be a bit involved the theory behind the algorithm is fairly straightforward:

Assume that you already have a simulation (game) with agents (units) that have some sort of bounding volume around them. This bounding volume is likely what you're already using to perform the collision detection and response. For each agent, define a preferred velocity `v_p` that may or may not be based on the agent's goal.

Now, to perform the simulation:

1. For each agent, assuming that it is stationary, calculate all of the velocities that would cause it to collide at any point in the future with any of the other moving agents. This can be represented in "velocity space" as a set of of intersecting half-planes (also known as a *velocity obstacle*).
2. Determine the point in this space closest to `v_p`, this is the new velocity of the unit.

If all of the agents are running the same algorithm, then they will choose velocities that mutually complement each other and will avoid other agents. In some situations, you can cause oscillations like that awkward thing that happens when you walk directly into someone in the hall and you both try to move out of the way in the same direction, but the papers cover how to avoid that.

For computing the two stages of the algorithm above, you can use Minkowski Sums to determine what the velocity obstacle is, and then use a linear programming model (such as the Simplex Algorithm) to determine the closest point to `v_p` that avoids the velocity obstacle. Also, code for doing collision avoidance is available for your perusal and has been ported to C# to be used in game engines like Unity. This technique has been used at least in *Warhammer 40,000: Space Marine*, and maybe other games.

# Answer
> 0 votes
I do not know how your units works but I assume that they are like a state machine :

**Possible states**

* Running to (x,y,z)
* Attaking (enemy\_id)
* Collecting ressource (ressource\_id)

If you pay attention at how starcraft approaches this problem, you will find that :

1. If there is space to move in a direction, the charachter moves in that direction.
2. If there is no space the unit in the way will move to make space
3. If the unit that needs to move to make space already has a command, it will keep the command, but modify it slightly to eventually make place.

Here scenario 1 :

Do I have space to go there? Yes ? Then go

Scenario 2 :

Do I have space to go there? No ? Hey can you make some space for me, you are blocking me. I already have an order to move foward but I will accomodate you.

So what you will need to implement :

* Units must be aware of their surroundings
* Units must have a way to communicate with each other
* You must implement a way to keep executing a command while acomodating an another unit

# Answer
> 0 votes
One way to do it is to have the units auto-form formations, and have them attempt to stay in a position *relative to the center of the formation*. Then, instead of moving each unit individually move the center of the formation around.

Here's a basic way to do it using a box formation and simple springs to keep the units at their appropriate positions:

```
// Defines a phalanx (box) formation
class Formation
    // Center of the box in the world
    Position center;
    // Width in # of units
    int width;
    // Height in # of units
    int height;
    // Space between units
    float scale;
    // How much force units will apply to stay near
    // their assigned spot.
    float springforce;

    // Return a position of a unit at the given row and column
    // Todo: add a rotation to this formation so it can rotate when moving.
    Position GetUnitPhalanxPosition(int row, int column)
        return new Position(center.X + column * scale - width * scale /2,
                            center.Y + row * scale    - height* scale / 2);

// Represents a simple point object with a velocity and position;
// it belongs to a formation.
class Unit
    Position pos;
    Velocity vel;
    Formation formation;
    // What's our assigned spot in the formation?
    int row;
    int column;

    void Update(float dt)
        // Get the desired target position in the formation
        Position target = formation.GetUnitPhalanxPosition(row, column);
        // Apply a spring force toward the position (todo: you might want to damp this)
        vel += (target - position) * dt * formation.springforce;
        // Move along the velocity vector.
        pos += vel * dt;

```

---
Tags: physics, rts, collision-avoidance
---


# Question
Title: Whats causing this weird texture stretching on my mesh?
Making this mesh via code and the texture seems to only tile on the sides, but not on the top. Any idea whats going on?

```
public class CoreMeshCreator : MonoBehaviour
{
//Initialization
public void Start()
{
    MeshFilter meshFilter = this.GetComponent<MeshFilter>();
    MeshCollider meshCollider = this.GetComponent<MeshCollider>();
    Mesh mesh = new Mesh();
    meshFilter.mesh = Generate();
    meshCollider.sharedMesh = meshFilter.mesh;
}

public Mesh Generate()
{
    Mesh mesh = new Mesh();
    float sqrt = (Mathf.Sqrt(3) / 2);

    Vector3 v0 = new Vector3(0, -1, 0);
    Vector3 v1 = new Vector3(-4, -1, 0);
    Vector3 v2 = new Vector3(-5, -1, sqrt * 2);
    Vector3 v3 = new Vector3(-4, -1, sqrt * 4);
    Vector3 v4 = new Vector3(-2, -1, sqrt * 4);
    Vector3 v5 = new Vector3(-1, -1, sqrt * 6);
    Vector3 v6 = new Vector3(1, -1, sqrt * 6);
    Vector3 v7 = new Vector3(2, -1, sqrt * 4);
    Vector3 v8 = new Vector3(4, -1, sqrt * 4);
    Vector3 v9 = new Vector3(5, -1, sqrt * 2);
    Vector3 v10 = new Vector3(4, -1, 0);
    Vector3 v11 = new Vector3(5, -1, -sqrt * 2);
    Vector3 v12 = new Vector3(4, -1, -sqrt * 4);
    Vector3 v13 = new Vector3(2, -1, -sqrt * 4);
    Vector3 v14 = new Vector3(1, -1, -sqrt * 6);
    Vector3 v15 = new Vector3(-1, -1, -sqrt * 6);
    Vector3 v16 = new Vector3(-2, -1, -sqrt * 4);
    Vector3 v17 = new Vector3(-4, -1, -sqrt * 4);
    Vector3 v18 = new Vector3(-5, -1, -sqrt * 2);
    Vector3 v19 = new Vector3(-4, 1, 0);
    Vector3 v20 = new Vector3(-5, 1, sqrt*2);
    Vector3 v21 = new Vector3(-4, 1, sqrt*4);
    Vector3 v22 = new Vector3(-2, 1, sqrt * 4);
    Vector3 v23 = new Vector3(-1, 1, sqrt * 6);
    Vector3 v24 = new Vector3(1, 1, sqrt * 6);
    Vector3 v25 = new Vector3(2, 1, sqrt * 4);
    Vector3 v26 = new Vector3(4, 1, sqrt * 4);
    Vector3 v27 = new Vector3(5, 1, sqrt * 2);
    Vector3 v28 = new Vector3(4, 1, 0);
    Vector3 v29 = new Vector3(5, 1, -sqrt * 2);
    Vector3 v30 = new Vector3(4, 1, -sqrt * 4);
    Vector3 v31 = new Vector3(2, 1, -sqrt * 4);
    Vector3 v32 = new Vector3(1, 1, -sqrt * 6);
    Vector3 v33 = new Vector3(-1, 1, -sqrt * 6);
    Vector3 v34 = new Vector3(-2, 1, -sqrt * 4);
    Vector3 v35 = new Vector3(-4, 1, -sqrt * 4);
    Vector3 v36 = new Vector3(-5, 1, -sqrt * 2);
    Vector3 v37 = new Vector3(0, 1, 0);

    mesh.vertices = new Vector3[]
    {
        v0,
        v1, v2,
        v3, v4,
        v5, v6,
        v7, v8,
        v9, v10,
        v11, v12,
        v13, v14,
        v15, v16,
        v17, v18,
        v19, v20,
        v21, v22,
        v23, v24,
        v25, v26,
        v27, v28,
        v29, v30,
        v31, v32,
        v33, v34,
        v35, v36,
        v37,
    };

    mesh.triangles = new int[]
    {
        //top
        1,0,2,
        2,0,3,
        3,0,4,
        4,0,5,
        5,0,6,
        6,0,7,
        7,0,8,
        8,0,9,
        9,0,10,
        10,0,11,
        11,0,12,
        12,0,13,
        13,0,14,
        14,0,15,
        15,0,16,
        16,0,17,
        17,0,18,
        18,0,1,
        //Bottom
        20,37,19,
        21,37,20,
        22,37,21,
        23,37,22,
        24,37,23,
        25,37,24,
        26,37,25,
        27,37,26,
        28,37,27,
        29,37,28,
        30,37,29,
        31,37,30,
        32,37,31,
        33,37,32,
        34,37,33,
        35,37,34,
        36,37,35,
        19,37,36,
        //Sides
        23,5,6,
        23,6,24,
        24,6,7,
        24,7,25,
        25,7,8,
        25,8,26,
        26,8,9,
        26,9,27,
        9,10,27,
        27,10,28,
        28,10,11,
        28,11,29,
        11,12,29,
        12,30,29,
        13,30,12,
        30,13,31,
        31,13,14,
        31,14,32,
        15,32,14,
        15,33,32,
        33,15,16,
        33,16,34,
        34,16,17,
        34,17,35,
        17,18,35,
        35,18,36,
        18,1,36,
        36,1,19,
        19,1,2,
        19,2,20,
        20,2,3,
        20,3,21,
        21,3,4,
        21,4,22,
        22,4,5,
        22,5,23
    };

    mesh.RecalculateNormals();

    return mesh;
}

}

```

# Answer
As others above have said, you need to generate texture coordinates for the top of your object. You can do it by hand (i.e. have your artist do it in their 3D software), or you can do it algorithmically.

I've had good success using tri-planar mapping. There's a good explanation here. Essentially, you take the x, y, and z components of the normal and use them as weights for blending 3 values together. Those values are samples of your texture using xy, yz, and xz coordinates.
> 2 votes

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


title: How to move a cube withour rolling it?

text:
# Question
Title: How to move a cube withour rolling it?
I am trying to move a cube with my keyboard on a plane surface. However, the cube always rolling instead of moving. How could I slide the cube on the plane?

What I have done:

* I added a plane game object with a mesh colider
* I added a 3D cube object with a box colider and rigidbody
* I appended a `ControllerScript` to the cube

> `ControllerScript`

```
private const float Speed = 10;

private Rigidbody rb;

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

void FixedUpdate()
{
    var x = Input.GetAxis("Horizontal");
    var z = Input.GetAxis("Vertical");

    this.rb.AddForce(Speed * x, 0, Speed * z);
}

```

It looks like the `AddForce` method upset the cube. I already tried to reduce the friction of the plane and the cube, but this only delays the problem.

How could I move the cube without rolling it? Whats the common way to do it?

# Answer
> 2 votes
Add the following line to your Start() method:

```
GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationZ;

```

This will prevent the object from rotating on x & z axis, which will prevent it from rolling. If you don't want it to turn sideways as well, add FreezeRotationY as well, and then it will not rotate at all but only move:

```
GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationZ | RigidbodyConstraints.FreezeRotationY;

```

If at any point you wish for it to be able to roll, for any reason, you can re enable the rotation by using:

```
GetComponent<Rigidbody>().constraints = RigidbodyConstraints.None;

```

# Answer
> 1 votes
You can

* Freeze the rotation
* Change the transform's position(with translate, not recommended for physics though)
* Set the rotation equal to itself

---
Tags: unity, movement, unityscript
---


# Question
Title: How to create old-school format music with small file sizes
My friend and I have been working on a project recently, and because we are hard coding everything (other than the graphics library, Pygame), the total size for our project is super small. I feel like this is awesome and because the game has a retro feel to it I thought it was fitting. The whole project including art is about half a megabyte, which is pretty good when factoring the art and level design and such.

However one thing that is not accounted for in this size is the music. The music itself (around 6 or so tracks) plus the sound effects (4 or 5 currently) make up about 99% of the file size (not an exaggeration, 60mb / 60.5mb is a little over 99%), which I find a little ridiculous. In the old days when games had ridiculously lower memory and file sizes, how did they pull off music? Our game uses Chiptune music to give it a more retro feel, so using that style of music for small file sizes is perfectly acceptable.

Also I because I'm using Python and PyGame I don't know if this will be possible, but I still would like to know the process used anyways so maybe I can play around with it.

# Answer
As for your implied question of **how do I reduce the file sizes of music**, you have these options:

## Better compression

60MB for 6 music tracks and 4 or 5 sound effects is *too big*. I'm guessing you either have really long tracks, or they are very high quality and/or lightly compressed, but usually there is no reason to do so:

* Unless you are catering to audiophiles or are making a music game, most people won't care about the sound quality. High quality audio tends to be limited to games distributed over physical media where they can afford the extra size, or is a "HD" game where everything needs to be high quality. Since you're worrying about file size, I'm guessing that's not you.
* In a game, most people would be focused on the game and not the music, and won't notice if the latter is low quality.

Here are some general tips:

* Use a **modern format** like Ogg Vorbis, produced with a modern encoder. These have come a long way since those early MP3s encoded with crappy CBR encoders, achieving the same quality at a fraction of the bitrate (and hence file size).
* Use a **low bitrate**. Most music is produced for listening alone, but since you're putting it in a game, quality is hard to notice. Don't be afraid to go very low with the bitrate, say 60-96kbps, as modern formats/codecs hold up quite well. YMMV so encode and listen for yourself.
* Have **short tracks**. Compared to most popular music which tends to be 3-5 minutes per track, game music tracks are much shorter, partly because the player usually doesn't notice. If you look at the OST for *Oblivion* for example, its tracks are only 2 minutes average. *Skyrim* has longer tracks, but there are still plenty of 2-minute tracks. Most other games have shorter tracks. IMO 1 minute is a good length, as it's long enough for the composer to have room for expression and for the player to not notice the repeating.

With these tricks you can get down to **~2MB per track**.

## Tracker music

As this answer mentions, for a period of time most music used tracker formats, which is a special file that contains a number of *samples* and the instructions on how to play those, at various times and pitches. Most such music was hardware-specific; they'd use the hardware's built-in sample bank as instruments, so the "music file" was analogous to sheet music alone. For example, most consoles prior to the 5th generation had special music chips which contained the sample banks, so all music for the same console tended to sound similar.

For modern PCs however, you need to provide your own sample bank. Still, these files were much smaller than if the music were a single encoded-PCM file. A typical 4MB MP3 would be about **200kB** if it were tracker music. pygame.mixer.music fully supports many tracker formats via libmodplug. The downside is obviously you are greatly limited to a fixed sample bank and you can't do much post-processing.

For examples, Mod Archive contains many outstanding tracks including those by skaven who notably provided tracker music for *Unreal Tournament* and *Bejeweled*. Do note that most of the tracks on Mod Archive are *not* freely derivable, including in your game, so you will need to seek permission or look elsewhere.

There are many music trackers you can use to make tracker music, some free, and each has its own dedicated following owing to their diverse heritages.

## MIDI music

Perhaps the smallest option you can use is to have MIDI files as music, which is, like tracker music, a format that specifies how instruments are played. Since it's a standard format and not hardware-specific, it relies on your computer's MIDI sound module, which IMHO tends to sound *crap* most of the time. Still it must have a niche appeal; *Doom's* music was MIDI after all.

pygame fully supports playing MIDI files; see this SO question.

Depending on the complexity of the track, a typical MIDI composition will be about **50-100kB** in size.

There are also many programs you can use to create MIDI music; a lot of music software exports to MIDI since it's a standard exchange format.

Of course that's not all the ways you can have very small music; you can hit the sound driver directly and synthesise your music, which is likely how a lot of the restricted-size "compos" did it, but it's something you do for its own sake rather than to save on file size.
> 3 votes

# Answer
Music was made using "tracker" software. You'd have a small bank of samples, and would set up a list of times and pitches at which to play those samples. So the memory taken up was a fraction of what it would be if you encoded the final audio itself.

If you listen to the music from the Amiga game Agony on level one, this is readily apparent:

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

You can hear it's the same short orchestral sample played over and over at different pitches.
> 2 votes

---
Tags: python, pygame, music, compression
---


# Question
Title: Small text is very light / faint with FreeType and OpenGL
I'm able to render large text with FreeType just fine:

But when I want to render small text (and the only parameter that changes is the font size), the quality is much poorer:

As you can see, all the characters are very faint, although the 'o' and the 'w' look a bit better than the others.

I've Googled around for similar topics, and many people mention hinting as a potential source of problems. Right now I'm calling FT\_Load\_Glyph() with the FT\_LOAD\_DEFAULT flag, although I've tried pretty much every flag listed at http://www.freetype.org/freetype2/docs/reference/ft2-base\_interface.html#FT\_LOAD\_XXX and none of them have produced adequate results.

Has anyone had a similar problem and determined how to fix it? I really need to render clearly-readable text at a small size, but I've heard that FreeType runs into problems here because certain hinting algorithms are patented, so should I look into an alternative text-drawing library and/or an alternative font? I'm not completely attached to this particular font (it's Liberation Sans TTF), so if there was another font I could use that would look better, that would be fine too.

# Answer
> 1 votes
The problem is that your rendering is not pixel aligned. The same problem is visible with the bigger text as well. When zooming in, you can clearly see blurred edges everywhere. Interestingly this only happens in horizontal direction, not vertical. Without any code it's impossible to tell where the problem is, but first thing to do is make sure your horizontal alignment matches the vertical one. The problem could be e.g. in texture coordinates, vertex coordinates, projection or modelview matrix. As an easy fix you can also disable bilinear filtering.

What you have heard about FreeType's hinting is subtle compared to your problem and you will probably not see any difference without close examination compared to the patented method. Besides the patent has expired years ago and recent versions of FreeType has the better algorithm enabled by default.

---
Tags: opengl, text
---


# Question
Title: Modeling player mechanics with a finite state machine
I have three states

* `standing`
* `walking`
* `jumping`

When I press `D` `standing` transitions to `walking`. The velocity will be set to a defined value and the player moves.

When I release `D` `walking` transitions back to `standing`, which sets the velocity back to `0`.

When I press `W` and the state is `walking` it transitions to `jumping`, but when the player hits the ground, it goes back to `standing`.

`jumping` has a transition `land` that always leads to `standing` because a state doesn't know about its previous states.

Since `standing` sets a velocity of `0` the player stops walking, when he hits the ground.

**How do I prevent this?**

# Answer
What you need is a stack based state machine. Essentially store the last state that was set when transitioning. That way, when your state ends, just pop the last state.

1. Walk
2. Jump -\> stack.push(Walk)
3. Land -\> stack.pop(Walk)
4. Walk

Now, you probably will have to make this work with your keyboard input as well. So you need a way to clear the stack pre-transition.

1. Stand
2. Jump -\> stack.push(Stand)
3. Press D -\> stack.clear()
4. Land
5. Walk

That being said, this is perfect for a Behaviour Tree instead of a state machine. I suspect your character will do multiple things at once with several conditions. A behaviour tree handles that better. NPC or Players are never in a single state.

You're not just Hungry, you are also Tired, Cold and Wounded. Get it?

State Machines are more suitable for Lightbulbs or Doors. It's either closed/off or open/on.

Until you add complex behaviours, like: breakable, lockable and etc.
> 3 votes

# Answer
If your state machine engine (if you use one) supports this, add a second transition from land to walk, which is conditional and only is used if the velocity is greater than 0.

This should work, if it is true that only your standing state sets velocity to zero. If your jumping state does that, too, you may need to create a parallel state chain for jumping with starting velocity or an extra boolean value.

I only mention this because keeping the velocity value greater than zero in jumping may have unwanted effects like the player still moving during the flight. (This too is engine dependend)
> 1 votes

# Answer
Why not change from `jumping` state to `standing` **or** `walking` state depending on keyboard input? It's true you might not have information about previous state but you still have information about current keyboard input, right? So just transition to `walking` state when you hit land **and** you're holding D down.
> 0 votes

---
Tags: game-mechanics, state
---


# Question
Title: How do I make my character jump in any angle?
My character is a square which can spin in any angle but it can not jump in certain angle.

Can anyone help?

```
public class Player: MonoBehaviour {

  public float maxspeed = 10f;
  bool facingRight = true;

  Animator anim;

  bool grounded = false;
  public Transform groundCheck;
  float groundRadius = 0.2f;
  public LayerMask whatIsGround;
  public float jumpFocre = 500f;

  bool doubleJump = false;

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

  void FixedUpdate () {
    grounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround);
    anim.SetBool ("Ground", grounded);

    if (grounded)
      doubleJump = false;

    float move = Input.GetAxis ("Horizontal");
    anim.SetFloat ("Speed", Mathf.Abs (move));

    GetComponent<Rigidbody2D>().velocity = new Vector2(move * maxspeed, GetComponent<Rigidbody2D>().velocity.y);
  }

  void Update()
  {
    if((grounded || !doubleJump) && Input.GetKeyDown ("up"))
    {
      anim.SetBool("Ground", false);
      GetComponent<Rigidbody2D>().AddForce(new Vector2(0, jumpFocre));

      if(!doubleJump && !grounded)
        doubleJump = true;
    }
  }

  void Flip()
  {
    facingRight = !facingRight;
    Vector3 theScale = transform.localScale;
    theScale.x *= -1;
    transform.localScale = theScale;
  }
}

```

# Answer
Your code currently contains :

```
public float jumpFocre = 500f;
//...
GetComponent<Rigidbody2D>().AddForce(new Vector2(0, jumpFocre));

```

`Rigidbody2D.AddForce()` takes a `Vector2` as a parameter, so this can be changed to:

```
public Vector2 jumpDirection = new Vector2(0f, 1f);
public float jumpFocre = 500f;
//...
GetComponent<Rigidbody2D>().AddForce(jumpDirection.normalized * jumpFocre);

```

This will allow you to control both the magnitude and direction of the force applied for your jump by changing the values of `jumpFocre` and `jumpDirection`.
> 1 votes

# Answer
Try something like this

```
public Vector2 jumpDirection = new Vector2(0f, 1f);
public float jumpFocre = 500f;
//...
float move = Input.GetAxis ("Horizontal");
jumpDirection.x = move;
GetComponent<Rigidbody2D>().AddForce(jumpDirection.normalized * jumpFocre);

```

In this way you are giving to the jump force the x component that the user are triggering in that moment.
> 0 votes

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


# Question
Title: Physics not working when game is running on device Unity
I have my bouncing ball game. The ball bounces up when it hits the ground and when it hits the left wall it changes direction to right and when it hits the right wall it changes direction to left and continues to bounce. Now the problem is that sometimes physics system does not register the collision between the ball and left/right wall, so the ball just passes through them and goes out of play, I have no idea whats going on. I will attach two pictures, one from game view and other from scene view.

Again I say everything works great, the ball bounces and hits the wall then changes the direction but sometimes the collision between a wall and a ball is not registered and the ball just passes through the wall like there is no physics and goes out of camera view.

# Answer
If you are using physics simulation, don't just change the `Transform` of your object - this would most likely break the physics (but if you just use colliders as triggers, this might be OK).

If you use physics, you should move your ball with `AddForce`. But here you could encounter various problems. The first problem is keeping the speed constant. You could specify max bounciness to the ball physics material and then call `AddForce` only when the ball changes the direction it moves (you also could just try to change the already applied velocity). Another option is to do `AddForce` with the `ForceMode.VelocityChnage` and specify to it the difference between current and desired velocities on each frame. Unfortunately this is not implemented for 2D physics, but some guys in Unity forums created the exetension method for that. There is also an easier way: you could just `AddForce` on each frame, but right after you could clamp the velocity by using `_rigidbody.velocity = Vecotr2.ClampMagnitude(_rigidbody.velocity, Mathf.Abs(_maxSpeed));`. This, btw, could break the physics a bit, since you're changing the `velocity` directly.

You also should take care about the global treshold values in `Edit->Project Settings->Physics 2D`. But as you could see there is no `Bounce Treshold` value for 2D physics (there is for 3D). This means that when the ball will collide with a collider under a very small angle, it will "stick" to the collider and you have no option to control it - it is just hardcoded into physics settings (that problem 100% was in 4.6, not sure about Unity 5). So you should check that there is no such problem in your game.

Another problem appears, when your ball is moving too fast. This is pretty much similar to what you are getting right now: the ball may pass through the colliders. Physics in Unity is calculated in `FixedUpdated`. `FixedUpdate` is invoked each 0.02 seconds (you could see and change this value in `Edit->Project Settings->Time`). If the ball moves too fast it could pass through the collider between frames - and then there is no collision. You could try to adjust the `Interpolate` and `Collision Detection` settings of your `Rigidbody2D` (the same for 3D), but this would not help if you move your object via `Transform` \- physics can't predict such a movement. You should move with physics. But, if changing those values doesn't help you, then you have the last resort option to use raycasting. There is a special script called DontGoThroughThings in Unity wiki, which does it for you. You only would need to convert it to 2D (or find it somewhere, I am pretty much sure someone already did it).

You could try to move your ball only by using `Rigidbody2D.velocity`. This may work, but may not. Velocity is physics, that's true, but changing it manually may break the physics calculations again. Most likely this would be seen when the ball will hit the other moving objects with "normal" physics. Another problem could be gravity. This happens because when you change the value manually, you remove the forces that were just applied to the object, and it will behave unnaturally. So you need to try it and see if it works the way you want. There is a probability that you can't go with it.

Controlling the physics yourself manually (by checking collisions manually in scripts by using positions and sizes of the objects) is not an option for games with many moving objects (because there is really a lot of work), but could be used for simple games like an arkanoid. Manual collisions in 2D aren't that difficult, but there are some problems to solve. The two most important are collisions with edges and collisions with moving objects.

I hope that you now have a bit better understanding on the subject. I'm not sure what exactly to recommend in your case, but you could try some (or all) of the options described above. I only hope you wouldn't need to write your own physics engine.
> 1 votes

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


# Question
Title: Creating a static 2D background at runtime
I'm using unity for a 2D game.

We have a lot of props for grass, plants, flowers, etc that are static and always in the background. I'd like to optimize the background and reduce the drawcalls as much as possible by making a big image with the final result of the background.

The idea would be to draw on a texture all the elements in the background, and then use this texture as the background. This way a single element has to be drawn.

How can I create these background texture at runtime, so it is generated as soon as the scene is loaded?

# Answer
While you could render your scene to a texture and use this as the background, it's most likely not worth the effort. Here's why:

* Packing your Sprites should already provide a significant reduction in draw-calls (potentially you can draw your whole background with just 1 draw-call and thus your only optimization would be the amount of triangles to draw)
* If you're planning to animate some parts of the background sometime later in the development process, you're stuck with a very inflexible solution.
* You might introduce (minor) lag at the start of the level because of the initialization and rendering of the RenderTexture.

If your sprites use lots of different blend-modes or other features that trigger new draw-calls, and if you're sure you're not going to animate your background in foreseeable future, then the RenderTexture is probably right for you. In all other cases I'd first optimize the drawcalls by making use of sprite-packing.
> 1 votes

# Answer
What you're describing is referred to as "render to texture". As in "render the scene and store that rendering in a texture." Unity provides a special kind of texture for that purpose, called a Render Texture.
> 0 votes

---
Tags: unity
---


title: Pathfinding in 3d voxel: waypoints?

text:
# Question
Title: Pathfinding in 3d voxel: waypoints?
I have an application where I have a 3d collision voxel space (passable or non-passable at each point) and I want to plot a short unobstructed path between two points. There are no gravity constraints, so the shortest unobstructed path is a straight line between two points.

I know that A\* can be generalized to 3-space, but this is a bit slow for my purposes. In my particular application, the collision space changes infrequently and there is a finite number of permutations, so what I'd like to do is automatically pre-process the voxel and generate a set of 'waypoints' with the following properties:

1. Each waypoint has a set of connected waypoints; the straight line path between any two connected waypoints is unobstructed.
2. For every passable point in space, there is an unobstructed straight line path to at least one waypoint. I'll probably store a lookup table to make this easy to find.
3. Ideally, the waypoints are generated so that the paths are still reasonably close to optimal, but I don't need to find the absolute optimal path.

If it's relevant, my collision space mainly consists of a few large contiguous 'blobs'; all empty spaces should be accessible, but the 'blobs' do have concave areas and holes allowing passage. Also, since I'm precomputing this, I can live with relatively long running times (though I'd prefer an upper bound of minutes, rather than hours or days.)

Is there a well-known algorithm for doing this? My first thought is some sort of repeated A\* for random point pairs and looking for 'choke points' (regions through which a lot of paths go), but I'm guessing this is a problem that has already been studied.

# Answer
> 3 votes
Take a look at hierarchical A\* (aka HPA\*); its basically what you're looking for. However, keep in mind that adding pre-processing can add so much overhead that it might not be worth it. You will want to profile your existing planner first to make sure there aren't any obvious bottlenecks.

Another thing you can try is to create a sparse probabalistic road map by randomly sampling grid cells and trying to connect them with A\* to their nearest nieghbors, then caching the result. Once the PRM is generated, modifying it is quite fast -- but you're not garunteed to find paths in more complicated environments.

# Answer
> 2 votes
**A hard but probably better way**: if you walk on surfaces you would use navigation mesh based on triangles that share edges. In 3D space you could use tetrahedrons that share faces. Tetrahedrons should be able to fill your space reasonably and running A\* on the graph of tetrahedra should be much faster, as you would probably not need so many of them. As in NavMesh, the added benefit is that once you have the path built of tetrahedrons, you can effectively cut corners and create really pretty paths.

But how would you generate the tetrahedral partition of your space? If you are in for a tough read and lots of fun in implementation - this paper seems to have an answer http://www.cs.berkeley.edu/~jrs/papers/cdtbasic.pdf

Disclaimer: I have never implemented even remotely similar algorithm. It might be difficult and the generation time may be pretty long.

**An easier but probably workable way**:

1. Generate a point at a random position in the empty space.
2. Find the largest radius so that a sphere centered at the new point with the radius does not intersect any colliding vector. This is your new waypoint
3. Repeat, until sufficient coverage is achieved.

Afterwards you prune the useless waypoints (like spheres completely/almost completely contained in others, spheres that are too small ...) and connect waypoints with each other wherever possible.

This is in principle very similar to the probabilistic road maps hinted in @mklingen's answer.

---
Tags: 3d, algorithm, path-finding, voxels
---


# Question
Title: Actually Implementing "C# as a scripting Language" in XNA
Following an example from this thread, I've made an application that dynamically loads in C# "scripts" (actually, plugins) into my game -- but I've hit a snag: how do I reference the assemblies for XNA when compiling? Can I even be sure the XNA assemblies will be around on the end-user's machine?

This line from the example:

`options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);`

Adds the referenced assemblies for my game only, not the XNA assemblies (for instance, for Vector3, Matrix, etc.). The only way to add the assemblies seems to be inlining an absolute URI to the necessary `.dll` files.

EDIT: Looking at this thread I have discovered how to load all of the required assemblies:

```
foreach (AssemblyName assemblyName in executingAssembly.GetReferencedAssemblies())
        cp.ReferencedAssemblies.Add(Assembly.Load(assemblyName).Location);

```

But apparently the XNA assemblies aren't included in this list for me :(

# Answer
> 1 votes
You could sum it up like such:

Pre-game install: You can't assume they are there.

Post-game install: You can assume (hope) that the XNA 4.0 Redistributable installed correctly and the assemblies reside in their respected locations.

If the scripting that the user will be doing is tested and run solely in game, then I would think that this is a safe route to go to assume the assemblies are in place or the game wouldn't even be working.

If you create some kind of "scripting editor" it's probably not going to require the same assemblies as a game. Like you stated in your question, Vector3, etc are MOST LIKELY not required to build a "text/script editor", and therefore it wouldn't be safe to assume they are.

As always with XNA Games, make sure you include the appropriate Redistributable and you will be fine.

---
Tags: xna, c#, scripting
---


title: Multiple enemy collidiers

text:
# Question
Title: Multiple enemy collidiers
I currently have an enemy that upon collision kills the player with a kill script, I want to add another collider that acts as the visibility radius for said enemy. However, when adding another colldier with a bigger x radius, the collidier still kills the enemy. Is there any way to assign particular colliders specific methods using

```
OnTriggerEnter2D (Collider2D var)
{
}

```

# Answer
First its good to note the difference between Colliders and Triggers

* *Colliders* \- generally are intended to represent physics interactions, so objects "colliding with them" should not pass through one another. As opposed to...
* *\*Triggers\** \- as the name implies, "fire" off an event but don't carry the typical physics body interactions

Triggers and colliders also send different events upon interaction, and the same can be said as well for 2D and 3D objects

OnTriggerEnter: 3D | 2D

OnCollisionEnter: 3D | 2D

Knowing this there are a few ways to approach this problem. First like you suggested you could add a second collider to the enemy, and from that new Collider's Component Inspector on the enemy check the `isTrigger` box marking it as a "Trigger".

That will allow it to instead respond to the `OnTriggerEnter` Method (if it is a 2D Collider `OnTriggerEnter2D`)

You could also organize your Enemy GameObject with a hierarchical structure

```
Enemy Game Object Parent
    - Damage Collider Object Child
    - Sight Radius Object Child

```

and then adjust the organization of your scripts to only have the kill script on the collider which should kill the player. This way you could use Triggers or Regular colliders.
> 5 votes

---
Tags: c#, unity, 2d, unityscript
---


title: C# comparing alot of elements

text:
# Question
Title: C# comparing alot of elements
Im making a small game in Unity(using c#)

basicly what I have there is each player chooses one Damage Spell or one Shield Spell.and the thing is that the number of combinations is huge. like 100 cases. for example , shadow dmg spell will deal 0 dmg to light shield but will deal 4 dmg to Life shield(just an example) I dont need code, I just need advice, how do I handle all of it withought tons of if statements? Thank you :)

# Answer
If you desire a pure function like `int ComputeDamage(Type a, Type b)`, instead of expressing the combinations of `a` and `b` in code, you can encode them as data in an associative dictionary or a table.

A lookup will then be along the lines of `damageTable[a][b]` or `damageMap.get(pair(a,b))`. An immediate benefit of driving the logic via data is that it's easier to tune and get oversight over a table or mapping than it is to squint past a horde of conditional statements and possibly convoluted logic.

As an example, consider answering the rock-paper-scissors question "does A beat B":

```
    \ A  | Rock  Paper  Scissors
   B \   |
---------------------------------
    Rock | Tie   Win    Loss
   Paper | Loss  Tie    Win
Scissors | Win   Loss   Tie

```

vs.

```
if (a == b)
{
    return Tie;
}
if (a == Rock && b == Scissors ||
    a == Paper && b == Rock ||
    a == Scissors && b == Paper)
{
    return Win;
}
else
{
    return Loss;
}

```

The code approach can be compressed by leveraging symmetries in the parameters and data, but may be considered harder to interpret the effects of, while a set of data has predictable results given any combination of inputs.

If you've got a bit of a hybrid scenario where you've got some special cases but most are covered by data, you can combine a data lookup with regular logic.
> 3 votes

# Answer
From a programming perspective. I think matching individual items will not scale. Every unit, weapon, piece of armor, etc. should know about the different types of damage, multipliers, etc. that it can deal or absorb. The programming gets much easier and you can add new items in the future without having to be sure you got all of the mapping correctly.

Example: I'm going to use a simple example so that you don't get hung up on what a light shield vs life shield should do.

Let's say I have a spell that deals fire damage. The base shield will deal 1 unit (hit point, etc) of fire damage. As the level of the spell goes up, the amount of damage scales in some fashion too. Level 5 deals 5 units of damage.

I have two opponents. One has a fire shield. One has a basic shield.

Each shield knows what kind of damage it can take, and any special rules that may apply to that item. The shields can level up and change this multiplier as well.

I attack the opponent with the basic shield using my level 5 fire spell. His shield is a level 2 shield that absorbs 2 units of damage. My attack reduces the opponents health by 4.

I attack the opponent with the fire shield with the same level 5 spell. Her shield is a lvl 2 fire shield. The fire shield knows that it can absorb 2 units, but it also sees that the type of damage coming in is fire damage. This shield knows that it will reduce the damage by 20% (lvl 2 X 10% reduction each level) before doing to damage math. So the fire resistance reduces the incoming damage number to 4 (5 - 20%), then absorbs 2 more, resulting in my opponents health to reduce by 2. Fire shield was more effective against a fire spell.

Instead of trying to map all items, if you simply let each item know what it's special props are, you the only thing you need to worry about is calculating the amount and type of damage sent out, and how to respond to it.

You can either use distinct values like I did above, or just use multipliers at each level.

A weapon may have a base damage number (lvl 1), then a percentage multiplier for each additional level. You may have to store a value for every type of damage on every weapon. Fire spell get 10% damage boost/resist boost, 0 light boost, 0 life boost.

You can also stack these values by using a multiplier on the player level as well (if you have that). A level 8 player using a lvl 2 fire spell may do more damage than a lvl 2 player using the same lvl 2 spell.

If you go this route, no mapping required. I hope that helps.
> 1 votes

---
Tags: c#
---


# Question
Title: How can I determine the number of pixels drawn within a predefined shape on the screen?
In the image above, I want to know how can I calculate the number of pixels of the rendered players' shadows that are inside the elephant outline.

An occlusion query is used to count the number of pixels occluded in the entire screen, but I want to restrict my count to just the number of pixels that end up inside the outline.

# Answer
> 0 votes
Basically:

1. Render the player's shadows to a render target.
2. Render the shape to a render target.
3. For each pixel, determine if it both (A) contains a shape pixel and (B) contains a player shadow pixel.

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


# Question
Title: Communication in a simple GUI (C++ / SDL2)
I've spent a few months now working on a fairly simply 2D game engine with SDL and C++. I'm now trying to develop a simple but well-featured GUI suitable for most games.

Right now I'm really struggling on figuring out how I should handle communication between the GUI and the other parts of the game / engine that might want to use it.

For example, the "shop" game state may have a list of items that I want to display on a shop GUI, along with their prices and quantities, i.e "Wooden sword / 30GP / 5". Obviously I need to get this information to the GUI in order for it to be useful, along with a way of notifying the shop component which item has been clicked/given focus. Seeing as the internal representation of an object such as an "item" or an "inventory" can vary wildly, how do I get the data I want to/from the GUI in a way that doesn't require excessive coupling between the two components?

I'd really appreciate anyone's advice on how to approach this issue, and I fully appreciate that my understanding is flawed.

Finally, I'm set on developing it from the ground up as a learning exercise, so I'm not really interested in GUI libs for SDL (it seems none of them are updated for SDL2 anyway).

Thanks in advance

# Answer
Basically, you need to know how GUI libraries work. In fact, you could even have a look on some of them to see how they get these things done (for example, you may have a look at GTK+ docs, or Qt docs to see the interface)

However, assuming that you're not building the whole GUI library, but rather some basic `Window`/`Text`/`Image`/`TextLabel`/`Checkbox`/`RadioButton`/`Button` library, I am going to share **one** possible approach how to do it.

---

## Intro - rendering & data storage

Let's say you have a `Window` class. It already handles some basic functionality, like rendering and moving. The class also takes care of *adding widgets*. Widgets are `Text` or `Image`, for example.

```
class Window
{
    ...
    void render() const;
    void move(const Vector & offset);
    void addWidget(const Widget newWidget); // Or you could use a reference, it depends on where do you want to store them/if you want to manipulate with them during their lifetime
    ...
}

```

Of course, you could be adding widgets to some grid cells, or you could give some offset relative to window on top of that.

`Widget` class could look like this:

```
class Widget
{
    ...
    virtual void render() const = 0;
    ...
}

```

I think it's clear for you now how you populate the window with the necessary information. `Widget` \- derived classed will contain them. For example:

```
class Text: public Widget
{
    Text(const std::string);
    ~Text();

    void render() const
    ...
}

// Somewhere else in your code
for (const int &obj : weapons)
    windowListingAllTheWeapons.addWidget(Text(obj.getName()));

```

The widgets will be displayed by calling their `render()` methods in the `render()` method of the window, which stores all the widgets (or references/pointers to them).

## Handling events

Now all you have to do is to add some `handleEvents()` method to `Window`, which will call `handleEvents()` of its respective widgets. This may get complicated, but as long as you stay in one-layer-depth, it's easy-peasy.

`handleEvents()` will take care of catching events which occurred in the area of the widget and `Widget` will invoke `onEvent()` methods (for example `onClick()`, `onHover()`, `onMouseRelease()`, etc), which will be appropriately overrided in the derived classes.

```
Widget::handleEvents(Event & event) // I don't know exactly how SDL handles events. I assume here that all the mouse events caught in Window class get distributed based on their position
{
    // this is kind-of-a-pseudo-code. I don't know SDL
    if(event.type == Event::Type::MouseClick)
    {
        onMouseClick(Mouse::getPosition());
    }
    // Yeah, it's better to use switch for multiple options
}

Button::onMouseClick(const Vector & position)
{
    this.setClicked()
    this.invokeSomeOtherAction()
}

```

---

## Disclaimer

This is not a tutorial on creating a GUI library. It's how I make GUI for small, not-GUI-heavy games. This is an overview of the process of creating **quick'n'dirty** GUI system. Anyone reading this, who is more interested in the topic should have a look at **Observer** pattern, **Qt's Signal And Slot**, **MVC** and should spend some time researching even more approaches on how to implement GUI.
> 4 votes

---
Tags: c++, gui, sdl2
---


title: Tiled and tmx files

text:
# Question
Title: Tiled and tmx files
i started using the software tiled and it very simple to create an image and object positions over there. I am using the library XNA and i would like to load the image and the objects into my code, how can i do it? Will it be easier to save the image alone and the objects locations alone? Using XML/text file/in code values?

I found this topic: http://nerdculture.org/2009/07/14/tiled-maps-for-xna-full-support-for-the-tiled-map-xml-specification/ but that is a code that he made? Is there a library that does that? Second, i saw that he draw each tile alone, is there a way to draw the whole image? (will it make it faster?) Do you recommend to use what he posted?

Thank you for your help :)

# Answer
> 1 votes
It seems you may have misunderstood the purpose of Tiled or tilemapping in general, so maybe I could clarify a bit for you.

In simple terms, a tilemap is an array values that you use to construct your stage from an image (the tileset). It basically tells your code which part of the image to draw on the game screen. This way, you can reutilize your assets and construct vast stages using only a small texture.

From what I'm seeing, you're suggesting saving the level image you build in Tiled and then using it on XNA, and that's against the whole purpose of using a tiled-based implementation in your game.

Drawing each tile individually is many times faster than pre-rendering the stage and drawing it as a single image, saves you a lot of memory, disk space, and allows you to have better control over what to draw. It's an extremely efficient and useful technique if used properly.

The correct way of implementing Tiled would be to create a parser for the file format you choose to export your maps in (usually the .tmx extension which is a XML format) and then reading the values from the files to your code using an XML Serializer or reading the values manually, storing them in a class, and then using that as a basis for your game logic and for drawing the stage.

If you feel you can't do that on your own, you could use one of the free libraries. I used to play around with this one befored I made my own implementation:

https://bitbucket.org/vinull/xtiled

Although, I feel you could learn from the experience and should try making your own implementation. I suggest you study a bit about the theory behind the Tilemapping technique before going deep into the coding part itself. Maybe this tutorial can help:

http://xnaresources.com/default.asp?page=Tutorial:TileEngineSeries:1

---
Tags: xna, tiles
---


# Question
Title: LibGDX , Scale button with animation when it is pressed
I am developing game using LibGDX . I want to create beautiful menu and to scale buttons when they are pressed but not in this way , when it is pressed scale it 1.5f , I want to scale it with animation . I am using imagebuttons .

# Answer
Since you are using Actors you can simply give the actor an Action. For scaling you could use this method:

```
myActor.addAction(Actions.scaleTo(scaleX, scaleY, duration);

```

Then when the user stops pressing the button you can cancel the current action and give the actor a new one that scales back down to the original size.
> 2 votes

# Answer
You could change the scale by a factor n each time in the render loop when the button is pressed.

*Initialisation of your ImageButton:*

```
button = new ImageButton(Assets.button_style);
    button.addListener(new InputListener(){
        public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
                // enable scaling when button is pressed
                scale = true;
        return true;
        }

        public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
                button.setChecked(false);

                // disable scaling when button is released
                scale = false;
        }

        public void exit(InputEvent event, float x, float y, int pointer, Actor toActor) {
             // disable scaling when button is exited with mouse
             scale = false;
        }
    });

```

*Render Loop:*

```
if(scale) {
    // set width and height (add n to current size)
    button.setWidth(button.getWidth() + n);
    button.setHeight(button.getHeight() + n);

    // re-adjust position
    button.setPosition(button.getX() - n/2, button.getY() - n/2);
}

```

Hope that helps. Limitations are that your animation has to be linear, if you want another kind of Interpolation you should read something about Interpolation.
> 0 votes

---
Tags: libgdx, animation
---


# Question
Title: How do I create a circular progress bar in Unity3D 5?
I am new to programming and Unity3D. I want to show a circular progress bar starting invisible and growing in 3 seconds to a circular line when reloading is done. How can I do that?

# Answer
1. GameObject-\>UI-\>Image
2. Put your unfilled circle outline sprite in image.
3. Change the Image type to Filled. Then you can play with Fill amount property and also control in through code.

Some credit goes to Shubham who I copied from instructions on a slightly different subject.
> 2 votes

---
Tags: unity, graphic-effects, loading
---


# Question
Title: Given a constant rotation and target point, find position so that point will be in camera center
Given a fixed rotation and a target "center" point, how to I find the position the camera should be in so that that point is the center? LookAt changes the rotation keeping the position constant. Basically, I'm trying to do the reverse, but the math escapes me :-). Thanks!

Camera is currently psuedo-isometric (orthographic with rotation from Euler angles \[X:35.264389683ish°, Y:45°, Z:0°\]). Might want to change these a bit or allow rotation though, so ideally a solution would work for any rotation. Can easily get the projection matrix.

EDIT: thinking about it, there would be infinite such positions that satisfy this constraint. I would want to fix the Y component of the position (camera height) and find only an X/Z.

Thanks to Mokosha's answer below, here's the final code I'm using:

```
    private static Vector3 reverseLookAt(Quaternion cameraRotation, float cameraHeight, Vector3 targetPosition)
    {
        Vector3 d = cameraRotation * Vector3.forward;
        Plane plane = new Plane(Vector3.up, -cameraHeight);
        Ray ray = new Ray(targetPosition, d);
        Vector3 pos = UnityUtils.intersect(ray, plane);
        return pos;
    }

```

# Answer
> 2 votes
Let's rephrase your question:

Given a rotation `R`, and a position `p`, we would like the rotated point `p'` to lie along the Z-axis (also known as the center of the camera). For this, we can use linear algebra:

1. Compose the rotation matrix `R` from your euler angles.
2. Solve problem (1) which we can rewrite as (2): $$\begin{align}Rd&=\begin{vmatrix} 0 & 0 & 1 \end{vmatrix}^T \tag 1\\ \\ d &= R^{-1}\begin{vmatrix} 0 \\ 0 \\ 1 \end{vmatrix}\tag 2\end{align}$$
3. `d` is now the direction in world space that corresponds to the Z-axis of the camera in eye space. Construct `p'` by translating `p` by `d`: `p' = p + d`.
4. Using `p` and `p'`, construct a line `P`.
5. Compute the intersection of `P` with the plane whose normal is `[0 1 0]` at `D` distance away from the origin where `D` is the desired Y value of your camera in world units.

The code for this in Unity's C# would look something like this:

```
Quaternion rot = ...
Vector3 p = ...
float desired_y = ...

Vector3 d = rot * (new Vector3(0, 0, 1)); // Perhaps Camera.forward...?

Vector3 camPos;
if (Mathf.Abs(d.y) < Mathf.epsilon) {
  Log.Error("Camera direction parallel to XZ plane");
} else {
  Plane y_plane = new Plane(new Vector3(0, 1, 0), desired_y);
  float dist;
  y_plane.Raycast(new Ray(p, p + d), dist)
  camPos = r.GetPoint(dist);
}

```

---
Tags: c#, unity, mathematics, camera, input
---


# Question
Title: A 2D Camera Follow Script That Does Not Rotate?
I am attempting to make a 2D racing game. So far I have a player car (sprite) and a main camera.

I would like to know how to make the main camera follow the player car while still showing signs of movement (I don't want the positions to match exactly in the middle of the screen).

My Player Car has a `Rigidbody2D` and a `MoveCar` script

```
using UnityEngine;
using System.Collections;

public class MoveCar : MonoBehaviour {

    public float speed = 10f;
    public float gravity = 0f;

    void CarMove ()
    {
        if(Input.GetKey(KeyCode.RightArrow))
        {
            transform.Translate(Vector2.right * speed * Time.deltaTime);
        }
    }

    // Update is called once per frame
    void Update ()
    {
        CarMove();
    }
}

```

Then there is my Main Camera, its projection is switched to Orthographic and has default settings as well as a `FollowCar` script:

```
using UnityEngine;
using System.Collections;

public class FollowCar : MonoBehaviour {

    public Transform player;

    public GameObject other;
    public Rigidbody2D rb = other.GetComponent<Rigidbody2D>;

    void Update()
    {
        transform.Translate(Vector2.right * .5f * Time.deltaTime);
        Vector2.MoveTowards( Vector2 , Vector2 player,
    }
}

```

I would like to know where to go next or if I'm even going in the right direction. I have no idea how to utilize the MoveTowards() function.

# Answer
> 1 votes
There are lots of ways to do this, though MoveTowards seems reasonable for your purposes.

Essentially, you'll want to determine some speed you want the camera to follow the car. Let's say that's `float cameraFollowSpeed;`

Then you need to adjust that to be framerate independent with `Time.deltaTime`

So now `FollowCar`'s `Update()` your code is something like

```
transform.position = Vector2.MoveTowards(
         transform.position, car.transform.position,
         Time.deltaTime*cameraFollowSpeed);

```

I don't think you need to use `transform.Translate()`.

As written, with the appropriate (experimentally determined) value of cameraFollowSpeed, your camera should drift lazily behind the car.

This might be enough to feel fun, or you might want to calculate the cameraFollowSpeed each frame based on the distance between the camera and car.

# Answer
> 1 votes
Sounds to me like what you need is to define a box in the middle of the screen, and only if the car moves outside of that box then the camera will move. That way the car has a bit of freedom to move without the camera moving, but as soon as it gets too far away from the center of the screen the camera does follow it.

This is similar to the technique used in older platform games like Super Mario, where the camera would only move once mario gets near the right edge of the screen.

I've actually written a script like this in the last game jam so I can share it:

```
using UnityEngine;
using System.Collections;

public class CameraTracking : MonoBehaviour {

    public Vector2 cameraSize;

    public Vector2 horizontalWorldBounds;
    public Vector2 verticalWorldBounds;

    public GameObject player;

    // Use this for initialization
    private void Start()
    {
        transform.position = new Vector3(player.transform.position.x, player.transform.position.y, transform.position.z);
        player = PlayerController.Instance.gameObject;
    }

    // Update is called once per frame
    void Update ()
    {
        float deltaX = player.transform.position.x - transform.position.x;
        deltaX = (Mathf.Abs(deltaX) > cameraSize.x) ? (Mathf.Abs(deltaX) - cameraSize.x) * Mathf.Abs(deltaX) / deltaX : 0;

        float deltaY = player.transform.position.y - transform.position.y;
        deltaY = (Mathf.Abs(deltaY) > cameraSize.y) ? (Mathf.Abs(deltaY) - cameraSize.y) * Mathf.Abs(deltaY) / deltaY : 0;

        float width = CalculateGameWorldWidth();
        float newX = Mathf.Clamp(transform.position.x + deltaX, horizontalWorldBounds.x + 0.5f * width, horizontalWorldBounds.y - 0.5f * width);
        float newY = Mathf.Clamp(transform.position.y + deltaY, verticalWorldBounds.x + 0.5f * width, verticalWorldBounds.y - 0.5f * camera.orthographicSize);
        transform.position = new Vector3(newX, newY, transform.position.z);
    }

    private float CalculateGameWorldWidth()
    {
        return (camera.pixelWidth / camera.pixelHeight) * camera.orthographicSize;
    }
}

```

Attach this script to your camera. Assign the player car in "player" in the inspector.

`cameraSize` defines the size of the box in the middle of the screen where the player can move freely and the camera will stay put.

`horizontalWorldBounds` and `verticalWorldBounds` define the final bounds of your world, so the camera will never display anything outside these bounds even if the player moves there. It's the edges of the map. They are `vector2`, so `x` is the lower bound and `y` is the upper bound. These are in world coordinates.

---
Tags: unity, c#, 2d, camera, movement
---


# Question
Title: Is there any easy way to understand the Alpha Beta for Othello?
I'm stuck with coding the Alpha Beta algorithm for a console-based game I'm developping at the moment. I tried to understand how it works for a week but still no idea how to get started with it. Here is the algorithm in pseudo-code :

```
    minimax (in game board, in int depth, in int max_depth,
         in boolean alpha_beta, in score black_best, in score white_best,
         out score chosen_score, out score chosen_move)
begin
        :
        :
        minimax(new_board, depth+1, max_depth,
                alpha_beta, black_best, white_best,
                the_score, the_move);
        if (alpha_beta) then
            if (to_move(black) and (the_score > black_best))
                if (the_score > white_best)
                    break;  /*  alpha_beta cutoff  */
                else
                    black_best = the_score;
                endif
            endif
            if (to_move(white) and (the_score < white_best))
                if (the_score < white_best)
                    break;  /*  alpha_beta cutoff  */
                else
                    white_best = the_score;
                endif
            endif
        endif
        :
        :
end.

```

I've already done the Min Max algorithm for a fixed depth of 2. Minmax pseudo-code :

```
minimax(in game board, in int depth, in int max_depth,
        out score chosen_score, out score chosen_move)
begin
    if (depth = max_depth) then
        chosen_score = evaluation(board);
    else
        moves_list = generate_moves(board);
        if (moves_list = NULL) then
            chosen_score = evaluation(board);
        else
            for (i = 1 to moves_list.length) do
                best_score = infinity;
                new_board = board;
                apply_move(new_board, moves_list[i]);
                minimax(new_board, depth+1, max_depth, the_score, the_move);
                if (better(the_score, best_score)) then
                    best_score = the_score;
                    best_move = the_move;
                endif
            enddo
            chosen_score = best_score;
            chosen_move = best_move;
        endif
    endif
end.

```

and my code (it is really messy sorry for that) :

```
char *minimax (Data *t, Data *u)
{
    int bestScore1=0, bestScore2=0, i,p,k,pn1=0,pb1=0,pn2=0,pb2=0, bestMove=0,score1=0,score2=0;
    Data *saveState1,*saveState2;
    saveState1=malloc(sizeof(Data));
    saveState2=malloc(sizeof(Data));
    *saveState1=*t; //Saving the state of the game before testing a move (first row which is AI's move)

    for (i=11; i<89; i++)
    {
        *t=*saveState1;

        if (check(i,t,u,1) > 0) //We're checking if the cell i is playable for WHITES
        {
            t->p[i]=BLANC; //Make the move (BLANC = WHITE in french)

            pn1=0; pb1=0; //PN1: number of BLACKS PB1: number of WHITES
            for (k=11;k<89;k++) //counts the white and black game pieces
            {
                if(t->p[k]==NOIR)
                    pn1++;
                else if(t->p[k]==BLANC)
                    pb1++;
                //printf("\npb1=%d",pb1); //DEB
            }
            score1=pb1-pn1; //Save the score
            if (score1 > bestScore1) //Set as best score if better than previous
                bestScore1=score1;
            *saveState2=*t; //Saving state for second row which is the player's move
            //printf("\n%s played by white",tostring(i)); //DEB
            for (p=11; p<89; p++) //Testing all the cells of the game
            {
                *t=*saveState2; //saving state before making a move

                if (check(p,t,u,-1)) //Checking if BLACK can play the cell i
                {
                    t->p[p]=NOIR; //Do the actual move

                    pn2=0; pb2=0; //PN: number of BLACKS PB: number of WHITES
                    for (k=11;k<89;k++) //Counts the white and black game pieces
                    {
                        if(t->p[k]==NOIR)
                            pn2++;
                        else if(t->p[k]==BLANC)
                            pb2++;
                            //printf("\npb2=%d",pb2); //DEB
                    }
                    score2=pb2-pn2; //Saving score for second row
                    if (score2 > bestScore2) //Setting score as bestScore if better than previous
                    {
                        bestScore2=score2;
                        bestMove=i;
                    }
                    else if (score2 == 0 || score1 == 0) //Setting default move if scores are ex aequo
                    {
                        bestMove=i;
                    }
                    else if (score2 < 0 || score1 < 0) //Setting default move if both scores are making the AI lose points
                    {
                        bestMove=i;
                    }
                    //printf("\n%s played by black",tostring(p)); //DEB
                    //printf("\nscore1=%d\tscore2=%d\tbestMove=%s",bestScore1,bestScore2,tostring(bestMove)); //DEB
                }
            }
        }
    }
    return bestMove;
}

```

Where \*t is the array representing the current game and \*u the precedent state of the game. Each array has 100 cells with the following values :

* 0 : black
* 1 : white
* 2 : empty
* 3 : border

Thanks for reading and sorry for the bad english skills. *Sources : http://pressibus.org/ataxx/autre/minimax/node2.html*

# Answer
> 1 votes
There are a lot of resources on the web for understanding alpha-beta. This short video will probably help you understand: https://www.youtube.com/watch?v=xBXHtz4Gbdo

My 1st game was an alpha-beta Othello, back in 1981. Good luck!

Footnote: once you get alpha-beta working, if you want to search deeper, I recommend the "MTD(f)" algorithm with "Iterative Deepening".

# Answer
> 0 votes
here is the alpha-beta algorithm definition:

Alpha–beta pruning is a search algorithm that seeks to decrease the number of nodes that are evaluated by the minimax algorithm in its search tree. It is an adversarial search algorithm used commonly for machine playing of two-player games (Tic-tac-toe, Chess, Go, etc.). It stops completely evaluating a move when at least one possibility has been found that proves the move to be worse than a previously examined move. Such moves need not be evaluated further. When applied to a standard minimax tree, it returns the same move as minimax would, but prunes away branches that cannot possibly influence the final decision.\[1\]

---
Tags: algorithm, ai, game-mechanics, c
---


# Question
Title: Image drawing then blackscreen on AVD using cordova
I have an issue on my android JS based game, the game displays well for 1 second then total blackscreen.

```
    window.requestAnimFrame = (function(){
      return  window.requestAnimationFrame       ||
              window.webkitRequestAnimationFrame ||
              window.mozRequestAnimationFrame    ||
              window.oRequestAnimationFrame      ||
              window.msRequestAnimationFrame     ||
              function(/* function */ callback, /* DOMElement */ element){
                window.setTimeout(callback, 1000 / 60);
              };
    })();

    (function() {
        var game = {
            canvas : document.getElementById('canvas'),
            frameWidth : 1280,
            frameHeight : 720
        };
        game.context = game.canvas.getContext('2d'),
        game.canvas.setAttribute('height', game.frameHeight);
        game.canvas.setAttribute('width', game.frameWidth);
        game.screens = {
            splash : new Image()
        }
        game.screens.splash.src = "src/img/splash.jpg";
        render(game);
    }());

    function render(game){
        game.context.drawImage(game.screens.splash, 0, 0, 1260, 720, 0, 0, 1260, 720);
        requestAnimFrame(function(){render(game)});
    }

```

The game works well on CocoonJS, I don't have any build error with Cordova. I tried to draw a rectangle instead of the image and it works.

I'm really sure it's a `drawImage()` issue.

# Answer
I found the answer : the .jpg image was to hi-res, I just had to reduce it.
> -1 votes

---
Tags: android, javascript
---