# Question
Title: How can I simplify my state machine transitions?
I currently have the following base class which I inherit from for my player states (e.g. Idle, Walking, Jumping).

```
struct PlayerState : std::enable_shared_from_this<PlayerState> {
    virtual ~PlayerState() {
    }

    virtual auto handle_input(const Input& input) -> std::shared_ptr<PlayerState> {
        return shared_from_this();
    }

    virtual auto update(AudioQueue& audio_queue, double dt) -> std::shared_ptr<PlayerState> {
        return shared_from_this();
    }
};

```

`handle_input` and `update` can both be overridden to allow transistions between states, e.g.

```
struct IdleState : PlayerState {
    virtual auto handle_input(const Input& input) -> std::shared_ptr<PlayerState> override {
        bool jump = input.was_button_pressed(0);

        if(jump) {
            return std::make_shared<JumpingState>();
        }

        return shared_from_this();
    }
};

```

This works reasonably well and lets me write new states very quickly, however as the number of states is expanding I find I'm repeating myself a lot.

Take the example above, the code for handling jumping is duplicated in both the Idle and Walking states (as you can jump from either).

I'm sure there must be a better way to model these transitions but I just can't see it right now.

My first idea was to add an additional property to each state, e.g. `bool can_be_jumped_from` and then pushing the logic for jumping down into the base `PlayerState` class and ensure all inherited classes call the base `handle_input` method before their own. My concern here is that the number of these flags will grow every time I have a state that can be transitioned to from multiple places.

Is there an another simpler/tidier implementation I'm missing here?

# Answer
This is rather tricky question. The problem here are not flags `bool can_be_jumped_from` per se, but what actually lies behind it - FSM state transition.
Number of state transitions required is not given by the *implementation* but rather by the *model* said FSM describes. Or in other words, `bool can_be_jumped_from` is not problem of shown implementation. Though you are very right about the maintenance issue.
A way to improve the ease of maintenance is to *abstract* more. Because code his its limits here, I would suggest employ some form of automation, may that be code generation frameworks (e.g. Visual Studio's T4 temples), tools capable of modeling FSM, custom markup language (e.g. XML describing transitions and states) or any other way that helps both de-coupling implementation from the model and conveniently letting you focus on designing the model itself.
Another way is *optimizing* the model, reducing the number of FSM states and transitions required. I will not go into the details for FSM optimization as it would be out of scope this question - there is whole mathematics field behind. In any case, drawing (either by hand or by tool) the FSM should help understanding it substantially.

---

Not to leave you empty handed, I would suggest using a bit different and maybe more conventional implementation. Following wiki definition, FSM is a quintuple: set F of exit points (irrelevant for us), set of states S, the the entry point S0 (member of S), \*delta \*set of transitions (for convenience, by current state) and *sigma* the input alphabet, giving you a draft:

```
//handles the logic associated with the state through callbacks
class State//abstract
{
   virtual void OnEnter(State* previousState);
   virtual void OnStay();
   virtual void OnExit(State* nextState);
}

class IDecision { //sigma given implicitly by implementation
   virtual bool Decide(State state) = 0;//evaluates to true/false or 0..1 in case on non deterministic
}

//binds two states together and holds the decision logic
class ITransition { //deltaB
  State fromState;//key
  State toState;
  IDecision decision;
}

//to-do optimize shared state, rest of logic
class FSM {
 std::vector<State> States;//S
 State entryPoint;//S0
 std::map<State, std::vector<Transition>> Transitions;
 void Update() {
    //not actual syntax, cut short for brevity
    auto transfer = std::find_first_of(Transitions[currentState], [&t] -> { t.decision.Decide(currentState); });
    if(!transfer) currentState->OnStay();
    else Transfer(transfer);
 }

 void Transfer(ITransition transition)
 {
   transition.fromState().OnExit(currentState);
   transition.toState().OnEnter(currentState);
   currentState = transition.toState();
 }
 //...currentState, constructors, serialization, generic logic...
}

```

with similar setup (did not check any syntax!), you could implement reusable `Jump`ing:

```
class ShouldJumpDecision : public IDecision
{
  bool ShouldJump = false;
  ShouldJumpDecision(CommandManager manager) {
    manager.Resgister<Input::Jump>([&] -> ShouldJump = true; )
  }
  virtual bool Decide(State state) override {
    return ShouldJump;
  }
}

class IddleState : public State {
  virtual void OnEnter(State* previousState) { animator.Play("IddleAnim") }
  virtual void OnExit(State* nextState)  { animator.Stop("IddleAnim") }
}

//PlayerFSM.xml parsed and automatically visualized and built by your engine tools
<Decisions>
  <Decision Name="ShouldJump">
    <Transitions>
      <Transition From="Iddle" To="Jump">
      <Transition From="Attacking" To="Jump">
    </Transitions>
  </Decision>
</Decisions>

//or created manually in code
fsm.AddTransition(iddle, ShouldJumpDecision, jump);
fsm.AddTransition(attacking, ShouldJumpDecision, jump);

```

If you are feeling generous, you can also implement something like the Command pattern for even more de-coupling.
> 2 votes

---
Tags: c++, input, state
---


# Question
Title: Understanding HingeConstraint in jBullet
I'm using the java port of BulletPhysics engine jBullet. I'd like to make a joints between 2 triangles so that one edge of the first and one edge of the seconds act like a hinge.

But I don't understand how to use the HingeConstraint class because it lacks documentation. What `pivotInA` and `pivotInB` are? They are the pivot points of the hinge in respect to the object centre? And `axisInA`? How does it differs from `axisInA`?

For two triangles do I have to make 2 Hinge constrains in 2 vertex or 1 in the middle point of the 2 edges of the hinge?

Where can I find a simple working example of this?

# Answer
When I ported from OpenDE to Bullet, I was puzzled about this as well. I asked on the forum, and the author answered.

*In Bullet you can initialize a Hinge constraint that is in a unsatisfied condition.*

Only when the axes from both point of views (body A and body B) coincide, the constraint is satisfied.

He makes a good point. Could be useful to serialize a simulation exactly as-is, with constraint error and all.
> 1 votes

# Answer
Hinge constraint between two rigid bodies each with a pivot point that descibes the axis location in local space. Axis defines the orientation of the hinge axis. I have found documentation on this here.
> 0 votes

---
Tags: java, bullet-physics, rigid-body-dynamics
---


title: How make circle with multiples holes

text:
# Question
Title: How make circle with multiples holes
In Unity, how can I programmatically make a shape like:

The gaps in the shape will all be the same size but their number may vary.

# Answer
> 2 votes
Here's one way to do it:

Use a `LineRenderer`, and create points programmatically like this:

```
// Lines in circle (in angles)
float[] angles = new float[] {0, 15, 30, 90, 100,120};

for (int i = 0; i < angles.Length; i += 2) {
    // Note that x*PI/180 converts radias "x" to degrees
    point[i].x = Mathf.Cos( angles[i] *Mathf.PI/180 );
    point[i].y = Mathf.Sin( angles[i+1] *Mathf.PI/180 );
}

```

This is pseudocode, so that you can understand the logic behind it. This example will just create a straight line on the edges of the holes, similar to the grey lines in the picture below (note the angles I put are just example and do not resemble the image).

Now the only question remaining is, how high quality you'd like this to be. From my previous example, from angle\[0\] to angle\[1\], you can create as many points as you want, the more points you add, the better quality the circle, at the cost of resources. Of course, for each point you add, you have to interpolate its angle from angle\[0\] to angle\[1\].

```
// Lines in circle (in angles)
float[] angles = new float[] {0, 15, 30, 90, 100,120};

for (int i = 0; i < angles.Length; i += 2) {

    for (int j = 0; j < quality; j++) {
        point[i*quality+j].x = Mathf.Cos(
            Mathf.Lerp(angles[i*quality+j],
                angles[i*quality+j+1], j/quality) *Mathf.PI/180 );
        point[i*quality+j].y = Mathf.Sin(
            Mathf.Lerp(angles[i*quality+j],
                angles[i*quality+j+1], j/quality) *Mathf.PI/180 );
    }
}

```

This is the same example, but it will create `quality` amount of points between to edges, and make the circle smoother. I repeat this is pseudocode and kinda assumes the points are already initialized, it's purpose is to understand the logic of it.

However you mentioned you are not interested in collisions and you just want circles with different sizes and colors. In this case, I could suggest making a texture with a white circle (with holes). Then apply the texture to a `Sprite` and through its `Material` you can change it's color. Since the original color was white, you can change it to any color you want (assuming the background is transparent). You can also scale the `Sprite` to any size you want, depending on your texture quality.

It also sounds like they are going to be used as particles, in this case I could suggest using billboarding (with textures).

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


# Question
Title: Is Quake 3's shader language copyrighted?
Right now I am using Quake 3 tools to make maps for my graphics engine, to have some kind of start and an idea on how to build one from scratch. I know that the BSP format is copyrighted and maps made with GTKRadiant cannot be used in commercial games.

But suppose that I would like to create/use a shading language with syntax that is similar or even identical to Quake 3's shading language's syntax, would I risk copyright issues?

# Answer
> 0 votes
The Quake 3 engine and tools are released under the GNU GPL; you can read the readme here: https://github.com/id-Software/Quake-III-Arena/blob/master/README.txt and access the Github repository here: https://github.com/id-Software/Quake-III-Arena

The source code is copyrighted, but so long as you abide by the terms of the GPL you can otherwise do whatever you wish with it, including using it in your own commercial release.

---
Tags: shading, quake3
---


# Question
Title: How do I prevent floating and jittering when on the ground and using spherical gravity?
**TL;DR:** My ship floats and jitters when it lands on a sphere.

To elaborate on the title: I'm experimenting with a 3D space game. I have created a sphere, which in turn has a larger sphere overlapping it, within which, gravity will take place. However, once my player's ship (currently using an arrowhead) lands on the planet, it doesn't actually make contact with the surface of the sphere, and then the ship begins to rotate erratically and jitter. Code below.

```
private void OnTriggerStay(Collider other)
{
    if (other.CompareTag("SoI"))
    {
    inSoI = true;
    }
}

```

This trigger checks to see if the ship is in the larger overlapping sphere. I have another identical block for OnTriggerExit which sets inSoI to false. I also have a OnCollisionEnter which sets another variable, landed to true, and a OnCollisionExit which sets it to false.

```
private void FixedUpdate()
{
    if (inSoI && !landed)
        {
            gravityVector = (planet.transform.position - transform.position);
            rb.AddForce(gravityVector.normalized * planetrb.mass * rb.mass / gravityVector.sqrMagnitude);
        }
}

```

Simply, if in the larger sphere, then accelerate towards the planet. I tried disabling gravity if in contact with the sphere. It removed a lot of the jitter, however it still floats, and it still rotates side to side. The sphere by the way, is the standard Unity sphere, scaled 10000x in every axis. I don't need code (though it would help), any solution is fine, even if it means abandoning the project.

# Answer
> 1 votes
Can you describe, how did you set up the collision system? In which script are you checking your OnCollisionEnter and OnTriggerEnter? Which of your colliders are set to isTrigger? If the collider on your ship has the isTrigger checked, it does not fire the OnCollisionEnter on the inner sphere, hence, you never going to have your landed true.

If you have your the collder on your ship NOT set to isTrigger, then it is going to fire your OnCollisionEnter, when it has a RigidBody on and collides with another collider, which is not a trigger.

This should clear up things: https://docs.unity3d.com/Manual/CollidersOverview.html

I tried out a simple project, with a plane, and 10000x scaled up sphere, and I only got the jitter with the sphere, so it must be behind the unwanted behaviour of your ship.

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


# Question
Title: Unable to control speed of the movement - object jumps straight to the end of the curve
I have implemented curve movement for two sprites (moon and sun) to simulate daytime changing. Sprites should take turns one after each other and move over the sky.

But they just instantly appear at the finish point no matter how I tweak value supposedly responsible for the speed of lerping.

```
daytimeCounter += 1.0f * Time.deltaTime;

```

---

Here is the full script.

```
[Tooltip("Object to parent sky elements.")]
[SerializeField]
private GameObject objectForParenting;

private float daytimeCounter; //counter to control moon and sun movement
private bool turnSwitch; //controls if it is moon movement or sun

/* Sun object field and parameters that control it's movement. */

[Header("Sun parameters.")]

[Tooltip("Sun object.")]
[SerializeField]
private GameObject sunObject;

[Tooltip("Sun prefab.")]
[SerializeField]
private GameObject sunPrefab;

[Tooltip("Start moving point for sun.")]
[SerializeField]
private Vector2 sunStartMovingPoint;

[Tooltip("Finish moving point for sun.")]
[SerializeField]
private Vector2 sunFinishMovingPoint;

[Tooltip("Multiplier for bezier curve height point.")]
[SerializeField]
private float bezierCurveMultiplierForSun; //multiplier to control height of bezier curve

private Vector2 heightBezierCurvePointForSun; //height point for bezier curve along which sun moves

[Tooltip("Slows sprite interpolation.")]
[SerializeField]
private float speedDividerForSun;

/* Moon object field and parameters that control it's movement. */

[Header("Moon parameters.")]

[Tooltip("Sun object.")]
[SerializeField]
private GameObject moonObject;

[Tooltip("Sun object.")]
[SerializeField]
private GameObject moonPrefab;

[Tooltip("Start moving point for moon.")]
[SerializeField]
private Vector2 moonStartMovingPoint;

[Tooltip("Finish moving point for moon.")]
[SerializeField]
private Vector2 moonFinishMovingPoint;

[Tooltip("Multiplier for bezier curve height point.")]
[SerializeField]
private float bezierCurveMultiplierForMoon; //multiplier to control height of bezier curve

private Vector2 heightBezierCurvePointForMoon; //height point for bezier curve along which moon moves

[Tooltip("Slows sprite interpolation.")]
[SerializeField]
private float speedDividerForMoon;

/* Clouds objects field and parameters that control it's movement. */

[Header("Clouds parameters.")]

[Tooltip("Array for cloud prefabs.")]
[SerializeField]
private GameObject[] cloudsArray;

// Use this for initialization
void Start() {

    daytimeCounter = 0f;

    //initializing bezier curve height point for sun
    InitializeBezierCurve(sunStartMovingPoint, ref heightBezierCurvePointForSun, sunFinishMovingPoint, bezierCurveMultiplierForSun);
    //initializing bezier curve height point for moon
    InitializeBezierCurve(moonStartMovingPoint, ref heightBezierCurvePointForMoon, moonFinishMovingPoint, bezierCurveMultiplierForMoon);
}

// Update is called once per frame
void Update() {
    MoveMoonAndSunAlongBezierCurve(ref sunObject, sunStartMovingPoint, heightBezierCurvePointForSun, sunFinishMovingPoint,
       ref moonObject, moonStartMovingPoint, heightBezierCurvePointForMoon, moonFinishMovingPoint);
}

//initialize bezier curve height point for moon and sun sprite movements
private void InitializeBezierCurve(Vector2 startPoint, ref Vector2 heightPoint, Vector2 finishPoint, float heightMultiplier)
{
    heightPoint = startPoint + (finishPoint - startPoint) / 2 + Vector2.up * heightMultiplier;
}

private void MoveMoonAndSunAlongBezierCurve(ref GameObject movableObject1, Vector2 startPoint1, Vector2 heightPoint1, Vector2 finishPoint1,
    ref GameObject movableObject2, Vector2 startPoint2, Vector2 heightPoint2, Vector2 finishPoint2)
{
    if (turnSwitch == false) //sun turn
    {
        while (daytimeCounter < 1.0f)
        {
            daytimeCounter += 1.0f * Time.deltaTime;

            Vector3 m1 = Vector2.Lerp(startPoint1, heightPoint1, daytimeCounter);
            Vector3 m2 = Vector2.Lerp(heightPoint1, finishPoint1, daytimeCounter);
            movableObject1.GetComponent<Transform>().localPosition = Vector2.Lerp(m1, m2, daytimeCounter);
        }
       // movableObject1.GetComponent<Transform>().localPosition = startPoint1;
    }
    else if (turnSwitch == true) //moon turn
    {
        while (daytimeCounter < 1.0f)
        {
            daytimeCounter += 1.0f * Time.deltaTime;

            Vector3 m1 = Vector2.Lerp(startPoint2, heightPoint2, daytimeCounter);
            Vector3 m2 = Vector2.Lerp(heightPoint1, finishPoint2, daytimeCounter);
            movableObject2.GetComponent<Transform>().localPosition = Vector2.Lerp(m1, m2, daytimeCounter);
        }
        //movableObject2.GetComponent<Transform>().localPosition = startPoint2;
    }

    daytimeCounter = 0f;
    turnSwitch = !turnSwitch;
}

```

---

Related to: \[Unity\]: Moving 2D object along circular arc between two points

# Answer
> 1 votes
From `daytimeCounter += 1.0f` change `1.0f` to any value you want the speed to be. Bigger values mean bigger speed. Do this in both cases in `MoveMoonAndSunAlongBezierCurve`.

Edit:

I found your problem. On `Update` you call the function `MoveMoonAndSunAlongBezierCurve`. However inside that function you are running the whole simulation inside a `while`. This means the simulation will execute in one frame, and when it returns, you will see the final result, which is the sun on the end of the curve. Instead, change `while` with an `if`:

```
while (daytimeCounter < 1.0f)
// Becomes
if (daytimeCounter < 1.0f)

```

Also, every time you increment `daytimeCounter`, you should check if it became more than `1.0f`, in this case the animation ended, and it should either reset or handle code differently. Here's your function re-written so you can understand what I mean:

```
private void MoveMoonAndSunAlongBezierCurve(ref GameObject movableObject1, Vector2 startPoint1, Vector2 heightPoint1, Vector2 finishPoint1,
ref GameObject movableObject2, Vector2 startPoint2, Vector2 heightPoint2, Vector2 finishPoint2)
{
    if (turnSwitch == false)
    {
        // while turned into an if
        if (daytimeCounter < 1.0f)
        {
            daytimeCounter += 1.0f * Time.deltaTime;

            Vector3 m1 = Vector2.Lerp(startPoint1, heightPoint1, daytimeCounter);
            Vector3 m2 = Vector2.Lerp(heightPoint1, finishPoint1, daytimeCounter);
            movableObject1.GetComponent<Transform>().localPosition = Vector2.Lerp(m1, m2, daytimeCounter);

            // Animation just ended - handle what happens next
            if (daytimeCounter >= 1.0f) {
                daytimeCounter = 0f;
                turnSwitch = !turnSwitch;
            }
        }
    }
    else if (turnSwitch == true)
    {
        // Again, while turned into an if
        if (daytimeCounter < 1.0f)
        {
            daytimeCounter += 1.0f * Time.deltaTime;

            Vector3 m1 = Vector2.Lerp(startPoint2, heightPoint2, daytimeCounter);
            Vector3 m2 = Vector2.Lerp(heightPoint1, finishPoint2, daytimeCounter);
            movableObject2.GetComponent<Transform>().localPosition = Vector2.Lerp(m1, m2, daytimeCounter);

            // Animation just ended - handle what happens next
            if (daytimeCounter >= 1.0f) {
                daytimeCounter = 0f;
                turnSwitch = !turnSwitch;
            }
        }
   }

    // These are no longer needed
    //daytimeCounter = 0f;
    //turnSwitch = !turnSwitch;
}

```

I've only kept my comments so that you can see what changes I made. The idea is that this function is now called once per frame, it moves the animation to the next step (with `daytimeCounter += 1.0f` where `1.0f` is the speed) and then draws the object in the new position. Once `daytimeCounter` becomes bigger or equal to `1.0f` this means the animation reached its last point, so it should probably reset.

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


# Question
Title: Why do separate loops run faster than one loop that does multiple things?
My game had some lag, so I tried to improve the performance.

I found that if I write my loops separately like this:

```
for (...){
    for (...){
        // Do operation A
        // (Fill int[][] with 1s)
    }
}

for (...){
    for (...){
        // Do operation B
        // (Work with Sprite Renderers & Spritebatch)
    }
}

for (...){
    for (...){
        // Do operation C
        // (Work with Shape Renderers with alpha)
    }
}

```

then the result runs a whole lot faster than if I try to do all the operations in one loop:

```
for (...){
    for (...){
        // Do operation A
        // Do operation B
        // Do operation C
    }
}

```

Can anyone explain this?

I'm running this game on Android OS!

# Answer
After some deep research and a lot of testing finally found out that the problem wasnt the loop as because it works on a simple maths. but the problem was in the rendering batch, the more batch there is, java will likely to share more memory to each batch as because batch is a collection of vertices. i divided them because i have to batch.begin() and batch.end() every batch, and it runs better. thanks all in helping me today. P.s sorry for bad english XD
> 1 votes

# Answer
This is not an unexpected result actually. It's a little like how a person's efficiency plummets when they try to multi-task, compared to when they can focus on doing one specific job.

Modern CPUs in computers and phones are vastly faster than the memory they're connected to, so there's elaborate caching and pre-fetching machinery set up to try to stuff the cache full of what the CPU might need soon, so that it doesn't have to wait on data to arrive all the way from main memory. This article on data locality from Game Programming Patterns explains the situation very well.

When you're in a tight inner loop that does just one thing, you make it very easy for these caching systems to predict what the CPU needs and keep ahead of it. For instance, iterating over an integer array in order, your CPU will work through sequential memory addresses, working on every bit of data in each cache line before moving onto the next one. That's the ideal access pattern for these systems

As your loop grows more complicated, your CPU has to switch between doing multiple different tasks, asking for stuff from different areas of memory, and possibly evicting data or instructions from the cache that it will need again when it returns to "operation A" to make room for data/instructions it needs to work on "operation C." This makes it harder for the caching systems to stay ahead of the CPU, and it might stall waiting for main memory from time to time.

So sometimes, letting the CPU do a batch of one type of work uninterrupted, then do a batch of a second kind of work, can help it do both faster than if it were trying to interleave the two.

The order of the nested loops matters too, for the similar reasons. Iterating over a 2D/jagged array `[x][y]` in the order `for ( y...) { for ( x...) { ... } }` means grabbing the first entry of the first inner array, then jumping way down the memory address space to the first entry of the second inner array, instead of working on the rest of the data from the first array that got pulled in on the same cache line. That data will probably be evicted from the cache by the time we come back to look at the second entry from the first inner array, forcing us to request it from main memory again...

This is one scenario that *could* lead to the profiling results you're seeing. But we won't know for sure unless you do some deeper profiling to count things like cache misses. As mentioned in the comments above, this could also be due to coincidence - profiling is tricky, and it takes controlled setups and a lot of repetition to be sure of the data.
> 9 votes

---
Tags: java, libgdx, performance
---


# Question
Title: Moving a 2D object along circular arc between two points
I have a sprite which I need to move along a curve between two points in 2D space. Speed must be consistent all the way. No physics involved. How can I achieve this?

The object is sun sprite.

# Answer
> 13 votes
You can use Bezier Curves.

Given 2 given points, you have to define one third point yourself that controls where the curve is made. In your example you can create the point between your two given points, plus some height.

```
// Assuming point[0] and point[2] are your starting point and destination
// and all points are Vector3
point[1] = point[0] +(point[2] -point[0])/2 +Vector3.up *5.0f; // Play with 5.0 to change the curve

```

Then to compute the curve in a script for an object to travel to it, do this:

```
float count = 0.0f;

void Update() {
    if (count < 1.0f) {
        count += 1.0f *Time.deltaTime;

        Vector3 m1 = Vector3.Lerp( point[0], point[1], count );
        Vector3 m2 = Vector3.Lerp( point[1], point[2], count );
        myObject.position = Vector3.Lerp(m1, m2, count);
    }
}

```

Basically, to compute a Quadratic Bezier Curve (one with three points) you have to find the interpolated points of it's two lines, construct a line with those two points (The green line in the gif), and interpolate again to find a final point.

As you can see, if you increase the Y value on your second point, the curve will be bigger.

Edit:

If you want to create moving objects like a sun and a moon, create 3 `Vector3` points: starting point (where the sun begins travelling) an ending point (where the sun ends up) and a control point (that controls the curve). The control point should be located above the mountains, but the exact value depends on what kind of curve you are looking for.

Now substitute these points with the above example:

```
point[0] = startingPoint;
point[1] = controlPoint;
point[2] = endingPoint;

```

I assume that once the sun (or moon) reaches the ending point, they can just disappear from the scene, and re-appear on the next day on the starting point, so it's location until then is irrelevant.

# Answer
> 4 votes
Myself, I'd use a circular arc for this - that way it's easy to get consistent speed.

```
IEnumerator FollowArc(
        Transform mover,
        Vector2 start,
        Vector2 end,
        float radius, // Set this to negative if you want to flip the arc.
        float duration) {

    Vector2 difference = end - start;
    float span = difference.magnitude;

    // Override the radius if it's too small to bridge the points.
    float absRadius = Mathf.Abs(radius);
    if(span > 2f * absRadius)
        radius = absRadius = span/2f;

    Vector2 perpendicular = new Vector2(difference.y, -difference.x)/span;
    perpendicular *= Mathf.Sign(radius) * Mathf.Sqrt(radius*radius - span*span/4f);

    Vector2 center = start + difference/2f + perpendicular;

    Vector2 toStart = start - center;
    float startAngle = Mathf.Atan2(toStart.y, toStart.x);

    Vector2 toEnd = end - center;
    float endAngle = Mathf.Atan2(toEnd.y, toEnd.x);

    // Choose the smaller of two angles separating the start & end
    float travel = (endAngle - startAngle + 5f * Mathf.PI) % (2f * Mathf.PI) - Mathf.PI;

    float progress = 0f;
    do {
        float angle = startAngle + progress * travel;
        mover.position = center + new Vector2(Mathf.Cos(angle), Mathf.Sin(angle)) * absRadius;
        progress += Time.deltaTime/duration;
        yield return null;
    } while (progresss < 1f);

    mover.position = end;
}

```

Now you can start the object moving with:

```
StartCoroutine(FollowArc(sunSprite, sunrisePoint, sunsetPoint, radius, daylightDuration));

```

---
Tags: unity, 2d, mathematics, vector
---


# Question
Title: "Method 'System.Net.Logging.get_On' not found" on built application in Unity
I have a Unity application that uses `System.Net.Http` to fetch data from an API. I am using Unity 2017.3.1f1 and .NET 4.6 and this works perfectly fine in the editor and the application builds fine, however the requests do not work on the built version of the application.

I'd expect the results to be shown on the screen, however I am receiving the "**Method 'System.Net.Logging.get\_On' not found**" error and the requests failed.

This only happens on the built version and not the editor. Does anyone know why this is happening?

Mono version: 5.0.1 (Visual Studio built mono)

---

**EDIT**

Apparently this could be an issue with System.Net.Http 4.3.2/4.3.3, I have downgraded to version 4.3.1 which seems to work and doesn't throw this error, but now I get `Loading script assembly "Assets/Lib/SystemHttp/System.Net.Http.dll" failed!` when running the standalone application. Again this works fine in the editor.

Usually I'd get this if the dll wasn't compatible, however it is targetting .NET 4.6, and this seems to be the only dll that was included in this release.

---

**EDIT**

I enabled logging for the production build and this is what I get

```
Failed loading assembly Managed/System.Net.Http.dll
Loading script assembly "Managed/System.Net.Http.dll" failed!

(Filename: C:\buildslave\unity\build\Runtime/Mono/MonoManager.cpp Line: 964)

- Completed reload, in  0.047 seconds
<RI> Initializing input.

<RI> Input initialized.

<RI> Initialized touch support.

Setting up 4 worker threads for Enlighten.
  Thread -> id: 316c -> priority: 1
  Thread -> id: 3394 -> priority: 1
  Thread -> id: 3b28 -> priority: 1
  Thread -> id: 3bb8 -> priority: 1
UnloadTime: 1.029624 ms
BadImageFormatException: Could not resolve field token 0x040000a3, due to: Could not load type of field 'LobbyInitializer+<getServer>c__async8:<request>__1' (1) due to: Could not load file or assembly 'System.Net.Http, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. assembly:System.Net.Http, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a type:<unknown type> member:<none> assembly:Assembly-CSharp.dll type:<getServer>c__async8 member:<none>
  at System.Threading.Tasks.Task`1[TResult].InnerInvoke () [0x0000f] in <c95265f74fdf4905bfb0d5a4b652216c>:0
  at System.Threading.Tasks.Task.Execute () [0x00010] in <c95265f74fdf4905bfb0d5a4b652216c>:0
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <c95265f74fdf4905bfb0d5a4b652216c>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <c95265f74fdf4905bfb0d5a4b652216c>:0
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <c95265f74fdf4905bfb0d5a4b652216c>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <c95265f74fdf4905bfb0d5a4b652216c>:0
  at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in <c95265f74fdf4905bfb0d5a4b652216c>:0
  at LobbyInitializer+<getServer>c__async1.MoveNext () [0x00082] in LobbyInitializer.cs:42
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <c95265f74fdf4905bfb0d5a4b652216c>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <c95265f74fdf4905bfb0d5a4b652216c>:0
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <c95265f74fdf4905bfb0d5a4b652216c>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <c95265f74fdf4905bfb0d5a4b652216c>:0
  at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in <c95265f74fdf4905bfb0d5a4b652216c>:0
  at LobbyInitializer+<findServersAsync>c__async0.MoveNext () [0x0007c] in LobbyInitializer.cs:36
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <c95265f74fdf4905bfb0d5a4b652216c>:0
  at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__6_0 (System.Object state) [0x00000] in <c95265f74fdf4905bfb0d5a4b652216c>:0
  at UnityEngine.UnitySynchronizationContext+WorkRequest.Invoke () [0x00001] in <4b58939e897a4c34942efe344ae250a9>:0
  at UnityEngine.UnitySynchronizationContext.Exec () [0x00021] in <4b58939e897a4c34942efe344ae250a9>:0
  at UnityEngine.UnitySynchronizationContext.ExecuteTasks () [0x00012] in <4b58939e897a4c34942efe344ae250a9>:0

(Filename: <c95265f74fdf4905bfb0d5a4b652216c> Line: 0)

```

# Answer
> 1 votes
After some digging I managed to find a solution until this issue is fixed.

https://forum.unity.com/threads/httpclient.460748/

Remove all System.Net.Http dlls from the Unity project.

Taken from here, one of the Unity officials

> Try putting a file named mcs.rsp in the Assets directory with one line in it:
>
> -r:System.Net.Http.dll
>
> I think that will correctly reference the assembly from the class library directory, and it should work then.

This solves the editor problem and now System.Net.Http is referenced but may not be recognised in Visual Studio. Install it through NuGet and it should be fine.

# Answer
> 1 votes
If I can put in my 2 cents - I had the same issue but more or less found the solution here. In particular, `marek-safar's` answer:

> All versions of System.Net.Http are broken on Mono because they use private API available in .NET assemblies only (bad InternalsVisibleTo). To workaround that Mono has a hack to disable loading such assemblies and use always Mono's ones. You can simply fix it by deleting System.Net.Http.dll from your bin folder or wait for Mono 5.2 with updated table of broken assemblies.

In my case, I have additional projects that perform the Http tasks rather than the main Unity project, so the solution for me was to remove the `System.Net.Http.dll` and its reference from said main project (it remains in the additional ones).

---
Tags: unity
---


# Question
Title: How to react properly to component field changes?
Let's say, that we have the following components:

`Direction`, which contains direction the object moves:

```
public class Direction : MonoBehaviour
{
    [SerializeField]
    private float angle = 0.0f;

    public float Angle
    {
        get
        {
            return angle;
        }
        set
        {
            angle = value;
        }
    }
}

```

`DirectionVisualizer`, which visualizes this direction in form of a sphere:

```
[RequireComponent(typeof(Direction))]
public class DirectionVisualization : MonoBehaviour
{
    private const float Radius = 2.0f;
    private GameObject sphere;

    private void PositionSphere()
    {
        Direction direction = GetComponent<Direction>();
        float angle = direction.Angle;

        Vector3 position = transform.position + new Vector3(
            Radius * Mathf.Sin(angle * Mathf.PI / 180.0f),
            0.0f,
            Radius * Mathf.Cos(angle * Mathf.PI / 180.0f));
        sphere.transform.position = position;
    }

    // Use this for initialization
    void Start () {
        sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
        sphere.transform.localScale = new Vector3(1.0f, 1.0f, 1.0f);

        PositionSphere();
    }

    // Update is called once per frame
    void Update () {

    }
}

```

The relation above represents simplified model I'm having in my game - a component is used to visualize a set of parameters contained in other component(s).

Now I'd like the sphere to be automatically positioned basing on the `angle` field in `Direction` component without explicitly notifying `DirectionVisualization`, like:

```
var direction = someObj.GetComponent<Direction>();
direction.Angle = 25; // DirectionVisualization reacts automatically here

```

The simplest solution is to position sphere frame by frame, but I know, that `Angle` will change very infrequently and such solution would have dramatic impact on performance (in my game this visualization is a lot more complex).

I might do that by merging `Direction` and `DirectionVisualization` classes, such that I can handle `Angle` property setter, but that's a very ugly solution directly against SRR principle. So it's a no-go.

Other solution would be to create an event in `Direction` component and subscribe to it from within the `DirectionVisualization` component. But that raises following concerns:

* If `DirectionVisualization` is destroyed, the event handler will keep it alive (I should probably detach the event handler when `DirectionVisualization` is destroyed?)
* When `DirectionVisualization` is added to object, it should subscribe to `Direction`'s event
* What should happen if DirectionVisualization is added to object, which does not (yet) have Direction component? Is there a way to detect adding Direction component, such that DirectionVisualization might subscribe to the event?
* What happens if `Direction` component is destroyed? How DirectionVisualization should behave? Is there way to detect it?

Is there a better way to handle notifications between components than one I proposed?

# Answer
> 5 votes
I personally would go with the event sending, because it's more explicit and easier to follow in code. Something like:

```
public delegate void DirectionChangedHandler(float direction);

public class Direction {
    [SerializeField]
    private float angle = 0.0f;

    public event DirectionChangedHandler DirectionChanged;

    public float Angle
    {
        get
        {
            return angle;
        }
        set
        {
            angle = value;
            DirectionChanged?.Invoke(value);
        }
    }
}

[RequireComponent(typeof(Direction))]
public class DirectionVisualization : MonoBehaviour
{
    Direction directionComponent;

    void OnEnable() {
        directionComponent = GetComponent<Direction>();
        directionComponent.DirectionChanged += OnDirectionChanged;
    }

    void OnDisable() {
        directionComponent.DirectionChanged -= OnDirectionChanged;
        directionComponent = null;
    }

    void OnDirectionChanged(float direction) {
        ...
    }

    ...
}

```
* `OnDisable` will be called when component is removed. So nothing will keep it alive.
* `OnEanable` will be called when component is added to game object.
* `RequireComponent` will make sure `Direction` component is added first.
* You can't remove `Direction` component if `DirectionVisualization` component is still present, because of `RequireComponent` attribute.

You can also send messages with `GameObject.SendMessage()`, this way you don't need to worry about event subscription.

---
Tags: unity, component-based
---


# Question
Title: How to automatically destroy a gameobject after a method or block of code
In Unity I frequently find myself doing this in C#:

```
GameObject myObject = new GameObject();
try{
// do something with that object
}
finally{
   Destroy(myObject);
}

```

A good example is creating a temporary pivot point for another object. I create the object, parent whatever object I want to rotate, do the rotation, then destroy the object. It's in a `finally` block so in case anything goes wrong it still destroys the object.

Does Unity have any elegant way to do this? Writing this all the time is tedious, and it's easy to forget the `Destroy` method at the end.

# Answer
I'd recommend not creating objects you don't intend to keep.

For the particular example of pivoting around a point, you can use the Transform.RotateAround method instead, without a temporary object. And it's even fewer lines of code too!

Other temporary uses of GameObjects should have similar, better alternatives.

Creating GameObjects when you don't need them is expensive, and causes garbage collector allocations which eventually build up and force a GC sweep, making your game hitch or stutter if not managed correctly. So, when in doubt, don't make throwaways - create only what you actually need to persist in your scene.
> 2 votes

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


title: Render to cubemap wrong Y values

text:
# Question
Title: Render to cubemap wrong Y values
I'm currently trying to render to a cubemap in order to blur it. However the top and bottom faces appear much closer than they should be in the blurred version. I thought the problem came from my transformation matrices but they're just rotations. I'm beginning to believe that it's the way I'm handling the framebuffer that's causing this problem. Here's how I'm doing it :

```
    unsigned fbo;
    unsigned rt;
    glViewport(0, 0, size, size);
    glGenFramebuffers(1, &fbo);
    glGenRenderbuffers(1, &rt);

    glBindFramebuffer(GL_FRAMEBUFFER, fbo);
    glBindRenderbuffer(GL_RENDERBUFFER, rt);
    glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, size, size);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rt);

    //...
    //enable source cubemap, set projection
    //...

    for(int i = 0; i < 6; ++i) {
        //set rotation
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, target_cubemap, 0);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        //draw cube

```

(the images below are from the same corder)

# Answer
> 1 votes
Found the mistake ! I was using the projection matrix of my camera, which had the aspect ratio of the screen instead of 1.

---
Tags: opengl, frame-buffer, cubemap
---


# Question
Title: How to find the angle of an arc for reflection
I am using the following code to calculate points for a circle arc drawn with a Line Renderer.

```
for (int i = 0; i <= pts; i++)
    {

        float x = radius * Mathf.Cos(ang * Mathf.Deg2Rad);
        float y = radius * Mathf.Sin(ang * Mathf.Deg2Rad);
        arcLine.positionCount = i + 1;
        arcLine.SetPosition(i, new Vector2(x, y));
        ang += (float)totalAngle / pts;

    }

```

How can I change the angle `ang` to create a reflected arc along the line P1P2 as in the image below?

Please note that `totalAngle` represents the portion of the circle that is to be drawn between 0 and 360.

# Answer
> 1 votes
I'm assuming the code handles a special case where the circle center is \[0,0\] and the arc is drawn is counterclockwise from the point \[radius,0\].

The idea is to reflect all points across a line in space, defined by P0 and P1, where P0 is the starting point \[radius,0\] and P1 is the last point on the arc, or \[radius * cos(totalAngle), radius * sin(totalAngle)\]. Note, if a more general arc drawing algorithm were used, you could place the circle center at the reflected location, as proposed, but you still might need similar math to find that reflected location.

First step, redefine the line as P0 and a unit direction, which is VUnitDirection = normalize(P1-P0). Second step, move each point into a coordinate space where P0 is at the origin, which is PRelative = (P0-point). Third step, project the point onto the line, by finding how far along the line its projection lies, which is SAlong = dotProduct(PRelative,VUnitDirection), and then find the actual projected point by moving along the line that distance, which is PProjected = P0 + (SAlong\*VUnitDirection). The distance between the original point and the projected point must be traversed twice to reach the reflected point, so calculate VOffset = PProjected - point, and finally, PFinal = PProjected + VOffset.

The code below is tested in 3ds max using the MaxScript language, a personal preference for prototyping. Note array access is 1-based, so a\[1\] is the first element of an array.

```
radius = 50.0
pointCount = 20
pointList = #() -- empty array
totalAngle = 95.0
ang = 0

for i = 1 to pointCount do
(
    x = radius * (cos ang)
    y = radius * (sin ang)
    ang = ang + (totalAngle / (pointCount-1))
    Point position:[x,y,0] size:1 wirecolor:red
    append pointList [x,y,0]
)

p0 = [radius,0, 0]
p1 = [radius*(cos totalAngle), radius*(sin totalAngle), 0]
vUnitDirection = normalize (p1-p0)
for pCur in pointList do
(
    pRelative = (pCur-p0)
    sAlong = dot pDir pRelative
    pProjected = p0 + (sAlong * vUnitDirection)
    vOffset = pProjected - pCur
    pFinal = pProjected + vOffset
    Point position:[pFinal.x,pFinal.y,0] size:1 wirecolor:blue
)

```

---
Tags: unity
---


# Question
Title: How can I generate spheres equal between the waypoints?
```
public void duplicateObject(UnityEngine.GameObject original, int howmany)
    {
        howmany++;
        for (int i = 0; i < waypoints.Count - 1; i++)
        {
            for (int j = 1; j < howmany; j++)
            {
                Vector3 position = waypoints[i].transform.position + j * (waypoints[i + 1].transform.position - waypoints[i].transform.position) / howmany;
                UnityEngine.GameObject go = Instantiate(original, new Vector3(position.x, 0, position.z), Quaternion.identity);
                go.transform.localScale = lightsScale;
                objects.Add(go);
            }
        }
    }

```

For example howmany value is 21. If I have two waypoints it's fine it will create 21 spheres between the two waypoints.

But if I have 3 waypoints it's creating 42 spheres but it should create 21 since howmany is still 21. And it also position the spheres between waypoint 1 and 2 and then from waypoint 2 to 3.

But I want that it will create 7 spheres between waypoints 1 and 2 and 7 spheres between waypoints 2 and 3 and last 7 spheres between waypoints 3 and 1.

# Answer
> 1 votes
You'll need to divide `howmany` by the number of waypoints.

```
public void duplicateObject(UnityEngine.GameObject original, int howmany)
{
    if(waypoints.Count <= 1) {
        return; // check for division by zero
    }

    // add this division here
    howmany /= (waypoints.Count-1);

    if(howmany < 1){
        howmany = 1; // put at least 1 ball between waypoints ?
    }

    for (int i = 0; i < waypoints.Count - 1; i++)
    {
        // Changed the < to a <= instead of adding one.
        for (int j = 1; j <= howmany; j++)
        {
            Vector3 position = waypoints[i].transform.position + j * (waypoints[i + 1].transform.position - waypoints[i].transform.position) / howmany;
            UnityEngine.GameObject go = Instantiate(original, new Vector3(position.x, 0, position.z), Quaternion.identity);
            go.transform.localScale = lightsScale;
            objects.Add(go);
        }
    }
}

```

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


# Question
Title: How exactly do slopes and edges work in this scenario?
So this sort of behaviour probably exists in other games, but the old Kirby games - Kirby's Adventure and Kirby's Dreamland 2 - is where I noticed it.

So, when dealing with regular block platforms, Kirby's hitbox acts like a simple rectangle, as you'd expect, as evidenced by the fact that you can stand like so:

On the other hand, when dealing with *slopes* of any kind, standing on them looks like this:

As you can see, if we were still using the rectangular hitbox, it would be halfway in the ground. This sort of behaviour is easily explained, however, buy a hitbox shaped like a 'diamond' or a 'plus'. (This is probably so that it doesn't look like Kirby is hovering in midair when walking on slopes)

Platforms such as these show perfect consistency with the 'diamond' hitbox model:

However, of course, the first screenshot shows that it's not possible for a diamond-shaped hitbox to be used *all* the time, or you would be able to 'slide' off any corner as if there was a slope there.

In fact, formations such as this show that it can't even be based on particular tiles, at least not 'full' tiles. (16x16, Kirby's size) (Otherwise you couldn't walk all the way up that slope)

Another model I've come up with is that the hitbox is always rectangular, but all slopes in the game are actually 'sunk' deeper than the tiles would have you believe. However, the stake-shaped platforms in the third & fourth screenshots invalidate this model, since then you wouldn't be able to stand at the top middle like you see there.

By the way, slopes on the ceiling work symmetrically, as can be seen in water stages.

**While it seems intuitive to the player, how could we program a *similar* collision system ?**

**N.B.** I am *not* asking for speculation on the internal workings of Kirby (unless someone here actually developed the collision system for those games - unlikely). Just a general approach.

# Answer
For old 2D games full vector collisions were too CPU heavy and shortcuts were taken. If you want to recreate the same feel and it's associated collision glitches you will have to use the same tricks.

There's two separate types of collisions: the simple and fast full block collision (in blue) and the special cases (slopes in yellow).

The yellow circle is a 1-pixel collision.

The full collision (in blue) only checks for full blocks completely ignoring special tiles (yellow).

This allows walking into the slope's cell boundaries.

Once the foot pixel check (yellow) detects being inside a slope it pushes the character up as needed and disables the full collision check to allow walking all the way up the slope. If the full collision (blue) wasn't disabled when inside a slope cell you'd get stuck halfway up the slope due to hitting the side of the top full cell.

Optionally there is a similar 1-pixel collision for the left and right sides at the centre to handle the case of a wall up a slope (in green).

This could be avoided if there is never a wall up a slope and some games did this. When you only had between 1 and 8MHz you saved where you could.

And a 4th check on top of the head for ceiling slopes.

To save on processing the special case collisions were not a real diamond but single pixel-sized checks. This worked fine with the limited slopes shapes and making sure to edit the map accordingly to avoid the possibility of wedging the character.

Unless you're targeting an ~8Mhz micro-controller or want to reproduce the particular issues this trickery could cause an actual diamond-shaped collision can now be used on modern computers.
> 2 votes

# Answer
One other way this could be handled is by checking for collisions at the center of the character's base first, and falling back to the adjacent overlapped tile if no collision is found there.

Regardless of which tile we end up finding collision in, we always calculate the floor height using the same point in the middle of the character's base, which here I'm calling `characterFootX` & `Y` respectively

Assuming integer pixel coordinates on a 16x16 tile grid, it might look like this:

```
// Round the character's foot position into its corresponding tile indices.
int tileX = characterFootX >> 4;
int tileY = characterFootY >> 4;

// Fall back on an adjacent tile if this tile has no collision.
if(tiles[tileX, tileY] == EMPTY_TILE) {

    // Round the character's tile up or down to the closest neighbouring tile horizontally.
    // (+1 if we're in the right half of the tile, -1 in the left half)
    tileX += (characterFootX & 0x8) >> 2 - 1;

    // Check tile above, to handle cases where we're
    // just off the bottom edge of a slope above us.
    if(tiles[tileX, tileY + 1] != EMPTY_TILE)
        tileY++;
}

int floorY = -1;
Tile tile = tiles[tileX, tileY];

if(tile == EMPTY_TILE) {
    // Falling
} else {
    // Get pixel offset from the center of the tile.
    int deltaX = characterFootX - 16 * tileX + 8;

    // Get base height of the tile.
    floorY = tileY * 16 + tile.baseHeight;

    // Adjust height based on slope.
    floorY += tile.slope * deltaX;
}

```

I think this policy of always using the center of the character's base for collisions, and only looking at the single valid collision tile closest to that center, can account for all of the cases shown in the screenshots.
> 1 votes

# Answer
You could achieve this by using different collision conditions for:

1. adjusting the character y-position while in the "grounded" state to get slope following behavior
2. transitioning from the "grounded" into the "falling" state

Whenever the player-character is in the "grounded" state, you do a raycast from a point between the feet of the character straight down and straight up. See where you hit a platform surface and change the y-coordinate of the player sprite so it sits on that platform. Limit the length of the raycast to less than 1 tile in both directions and don't do anything when there is no hit. This is to not interfere with the cliff-standing behavior seen in the 1st and 3rd screenshot when there is ground below the cliff.

After that, check if the character is still grounded. Use a line-cast from the lower-left to the lower-right corner of the player-sprite to check if it is still in contact with a platform. When it isn't, change the player's state from "grounded" to "falling".

---

Note that this is what you would be doing in a "modern" game where you have the convenience to make deliberate use of floating-point arithmetic and geometrically complex colliders. The game from the example was from a much simpler time. The MOS 6502 CPU of the NES didn't even have a floating-point unit, so they had to do everything with integer math. This meant that their code was likely a lot cruder. I would assume they had special coding for handling walking on the diagonal tiles. Something like:

```
walkRight:
    x++;
    if (tile[x>>4, y>>4 + 1] == UP_SLOPE)
        y--;
    if (tile[x>>4, y>>4 + 1] == DOWN_SLOPE)
        y++;

```
> 0 votes

# Answer
There are multiple ways to do collision systems in 2D games. I find it unlikely that this particular game didn't use a tile-based system of some kind, sprites larger than their hitboxes is a common feature for tile based platformers, and pixel-perfect tile systems are still extremely useful for modern games as well. The only tricky part about it is to handle slopes and other edge-case obstacles like one-way platforms. This article provides a decent explanation for several collision systems, though it is by no means the only method.

I'll describe the basic algorithm the article provides, but I encourage you to read the whole thing for more comprehensive explanations/insights into these systems. There are for sure more efficient, intuitive ways of doing 2D collision systems nowadays, but this is what I can gather from your specific question.

---

The whole level is built as a tilemap with all the relevant information stored on the tiles (type of terrain, player effects, etc...) and characters have their usual collision/hit boxes. Much of 2D collision systems, especially for older games, involved pixel-perfect math and the like.

Each frame we determine the movement in the X and Y directions. If moving left we take the leftmost edge of the hitbox (similarly for moving right, up, and down) and determine what tiles that edge is intersecting with. Go through these tiles to detect any obstacles that would prevent movement and move the character the minimum distance it can move. Repeat until you've calculated all movement for the frame.

That was for maps without slopes, and adding them can get tricky. Unless you want to do some more wacky calculations, it's best to keep the slopes used a consistent size. So, for example, a ramp that is 4 tiles long and goes up 1 tile should never be placed with gaps or end prematurely.

We first need to check the X direction of movement, and before checking for collisions, we first check to see if the tile we are on is a slope and register the tile as a collision only if we're going up the slope (in this case moving left). If we have a slope collision, we'll have to move the player up in the Y direction.

Another case we need to consider is the top and bottom of the entire slope (the tile with the blue dot marked on it). To prevent the character from being stuck, we should ignore the full tile obstacle immediately before and after the slope is completed. The article does this by checking if the slope is filled on the left or right edges, meaning that we're at the end of the slope's tiles.

For vertical movement, usually we have gravity being applied to the character, so again we check for collisions in slope tiles and move the player down accordingly.

A lot of this is pixel-perfect math and collisions which depends heavily on the coordinate system you're using for your tilemap.
> 0 votes

# Answer
For the images that you posted it looks like Kirby has a point collision at the middle of his feet and the scenery has its collision boxes extended beyond the cliff edges so that the point collision doesn't allow Kirby to fall until he is fully beyond the edge of the cliff.
> 0 votes

# Answer
Well, you answered it yourself. When Kirby is standing on a "normal" tile, the bounding box is rectangular and when he is touching a slope, it turns into a diamond.
> 0 votes

---
Tags: collision-detection, platformer
---


title: Runtime Access to Unity 2d Tiles

text:
# Question
Title: Runtime Access to Unity 2d Tiles
I'm trying to use Unity's 2017 tilemap features. What I would like to do is push a tile's sprite up (change its offset), so that the sprite moves up pixel by pixel and the top of the sprite loops (wraps) back around to the bottom. Basically, I want to animate my "Water" sprite without having to build 20 different versions of the sprite to achieve the same effect. I was able to do this in Rotorz tiles by accessing its Atlas' MainTexture Offset or something like that but this product is discontinued. This animation is similar to the water in classic RPG games like Ultima 4.

More than that, I would just love to have runtime access to the tiles to do other things: change out the entire sprite on a single tile, change the color, etc.

I have made a custom Tile class using this example: https://docs.unity3d.com/Manual/Tilemap-ScriptableTiles-Example.html

But this only seems to affect tiles at the time of placement.

Is this possible and does anyone have a good example? Docs on this feature are scarce.

# Answer
> 1 votes
Have a look at the Unity Examples on their GitHub.

Pay special attention to the Animated Tile Example:

```
[Serializable]
public class AnimatedTile : TileBase
{
    public Sprite[] m_AnimatedSprites;
    public float m_MinSpeed = 1f;
    public float m_MaxSpeed = 1f;
    public float m_AnimationStartTime;
    public Tile.ColliderType m_TileColliderType;

    public override void GetTileData(Vector3Int location, ITilemap tileMap, ref TileData tileData)
    {
        tileData.transform = Matrix4x4.identity;
        tileData.color = Color.white;
        if (m_AnimatedSprites != null && m_AnimatedSprites.Length > 0)
        {
            tileData.sprite = m_AnimatedSprites[m_AnimatedSprites.Length - 1];
            tileData.colliderType = m_TileColliderType;
        }
    }

    public override bool GetTileAnimationData(Vector3Int location, ITilemap tileMap, ref TileAnimationData tileAnimationData)
    {
        if (m_AnimatedSprites.Length > 0)
        {
            tileAnimationData.animatedSprites = m_AnimatedSprites;
            tileAnimationData.animationSpeed = Random.Range(m_MinSpeed, m_MaxSpeed);
            tileAnimationData.animationStartTime = m_AnimationStartTime;
            return true;
        }
        return false;
    }
}

```

One thing to note is because of the definition of the framework, you can't get away from an array of sprites for a tile. You can create them dynamically from an asset but that's too complicated to go into on this question.

You can modify tiles at runtime by overriding the `RefreshTile` and `GetTileData` methods.

```
public override void RefreshTile(Vector3Int location, ITilemap tileMap)
{
    // refreshes self and neighbors
    for (int yd = -1; yd <= 1; yd++)
        for (int xd = -1; xd <= 1; xd++)
        {
            Vector3Int position = new Vector3Int(location.x + xd, location.y + yd, location.z);
            if (TileValue(tileMap, position))
                tileMap.RefreshTile(position);
        }
}

public override void GetTileData(Vector3Int location, ITilemap tileMap, ref TileData tileData)
{
    MyCustomUpdate(location, tileMap, ref tileData);
}

```

I agree, information is scarce at the moment, because it's such a new feature. These examples are just about the best leg up I've been able to find.

As you solve your problem, come back and post an answer to your question with the solution you came up with to help others. Now is a prime time to earn some extra reputation :)

---
Tags: unity, tilemap, tiles
---


# Question
Title: How can I change the sprite while jumping?
```
///Initial Values

//Create the initial value of image_speed to use sub images
image_speed = 0.025;
grav = 0.5;
hsp = 0;
vsp = 0;
jumpspeed = 12;
movespeed = 3;
recently_hit = false;
counter = 0;
canshoot = true;
globalvar mpfacing;
mpfacing = 0;

```

are my initial variables

```
///Get player's input
key_right = keyboard_check(vk_right);
key_left = -keyboard_check(vk_left);
key_jump = keyboard_check_pressed(ord("Z"));
key_jump_held = keyboard_check(ord("Z"));

//React to inputs
move = key_left + key_right;
hsp = move * movespeed;
if (vsp < 10) vsp += grav;

if (place_meeting(x, y+1, Obj_Floor))
{
 vsp = key_jump * -jumpspeed;
}

if (vsp < 0) && (!key_jump_held) vsp = max(vsp,0)

//Horizontal Collision
if (place_meeting(x+hsp, y, Obj_Floor))
{
 while(!place_meeting(x+sign(hsp), y, Obj_Floor))
 {
  x += sign(hsp);
 }
 hsp = 0;
}
x += hsp;

//Vertical Collision
if (place_meeting(x, y+vsp, Obj_Floor))
{
 while(!place_meeting(x, y+sign(vsp), Obj_Floor))
 {
  y += sign(vsp);
 }
 vsp = 0;
}
y += vsp;

//Animate
if (move != 0)
{
 image_xscale = move;
}

if (place_meeting(x, y+1, Obj_Floor))
{

 if (move != 0)
 {
  sprite_index = CalvinWalking;
  image_speed = 0.07;
 }

 else
 {
  sprite_index = CalvinStanding;
  image_speed = 0.025;
 }
}

else
{
 if (vsp < 0) sprite_index = CalvinJumping
 else sprite_index = CalvinJumping
}

```

is the main input

```
///Shooting with D
//Shooting direction
if (image_xscale = 1)
{
 mpfacing = 0;
}

if (image_xscale = -1)
{
 mpfacing = 180;
}

if (keyboard_check(vk_up)) && (move = 0)
{
 mpfacing = 90;
 sprite_index = CalvinAimUp;
}

if (keyboard_check(vk_up)) && (move != 0)
{
 mpfacing = 90;
 sprite_index = CalvinAimUpWalking;
}

//Aiming up and jumping
if (keyboard_check(vk_up)) && (keyboard_check(ord("Z")))
{
 mpfacing = 90;
 sprite_index = CalvinAimUpJumping;
}

//Shooting
if (keyboard_check(ord("X"))) && (canshoot = true) && (mpfacing != 90)
{
 instance_create(x+13, y-0.5, Obj_MP_Laser);
 canshoot = false;
 alarm[1] = 30;
}

if (keyboard_check(ord("X"))) && (canshoot = true) && (mpfacing = 90) && (image_xscale != -1)
{
 instance_create(x-10, y-26, Obj_MP_Laser);
 canshoot = false;
 alarm[1] = 30;
}

if (keyboard_check(ord("X"))) && (canshoot = true) && (mpfacing = 90) && (image_xscale = -1)
{
 instance_create(x+12, y-26, Obj_MP_Laser);
 canshoot = false;
 alarm[1] = 30;
}

```

and this is the script for shooting, (note each piece of code is in different scripts) and I can't figure out how to change the sprite in the ///shooting with D/// in //Aiming up and jumping// so the sprite will change until it is on the ground. And not how I set it up so it changes ONLY when I press the jump button (Z).

# Answer
> 1 votes
You don't want to draw a jumping character *only* when the player presses the jump key, rather whenever he's **floating** in mid-air:

```
//Aiming up and jumping
if (keyboard_check(vk_up)) && (!place_meeting(x, y+1, Obj_Floor))
{
 mpfacing = 90;
 sprite_index = CalvinAimUpJumping;
}

```

You may want to use the `if (!place_meeting(x, y+1, Obj_Floor))` condition whenever you want to execute code if your character has no solid objects below his feet.

---
Tags: sprites, game-maker, jumping
---


# Question
Title: Quaternion.Lerp does not actually rotate object when called inside an "if" clause
Let's say I have a `RotatableObject` class, which inherits from `MonoBehaviour`. Here is its `Start()` method:

```
private void Start() {
    this.startingLocalRotation = this.transform.localRotation;
    this.finalLocalRotation = Quaternion.Euler(this.startingLocalRotation.eulerAngles.x, -150f, this.startingLocalRotation.eulerAngles.z);

    // Initialize other private fields
}

```

It has a method called `Rotate()`, defined as follows:

```
private void Rotate() {
    this.transform.localRotation = Quaternion.Lerp(this.startingLocalRotation, this.finalLocalRotation, 0.2f);
}

```

Given the following `Update()` method, the object rotates as expected:

```
private void Update() {
    this.Rotate();
}

```

However, if I make the following changes to `Update()`, then the object does not actually rotate, **even though the `Rotate()` method is hit**:

```
private void Update() {
    if (this.SomeCondition) {
        this.Rotate();
    }
}

```

`this.SomeCondition` always has the value `true` over multiple frames.

What is my mistake, and how can I fix it?

**EDIT:**

In response to this comment:

> When you say "the object rotates as expected" do you mean that the object rotates from starting angles until final angles and then stops rotating (without the if) ?

Yes.

> could you provide some more details about what `SomeCondition` is?

`this.SomeCondition` is determined by the state of another object, say, `Puppy`. E.g. if `puppyInstance.Mood == Mood.Happy`, then `this.SomeCondition` is `true`.

> Did you try replacing the condition with the word `true`

No, I have not tried that. However, when stepping through the call stack in debug mode, I can see that `this.SomeCondition` is `true` and `Rotate()` is called -- I managed to step into the `Rotate()` method itself.

**EDIT:**

I tried the first approach described in this answer. However, it did not produce the effects that I was aiming for.

I set a breakpoint here:

```
transform.localRotation = Quaternion.Lerp(
   startingLocalRotation,
   finalLocalRotation,
   _rotationProgress
);

```

Every single time the breakpoint was hit in the `Update()` call, I could see that the value of `_rotationProgress` was steadily increasing. However, the value of `transform.localRotation` never actually changed -- it was **always** (-0.7, 0.7, 0.0, 0.0).

If I updated `transform.localRotation` *outside of* an `if` clause, however, that game object rotates as expected -- `transform.localRotation` gets updated as `_rotationProgress` gets updated.

**EDIT:**

Never mind, I am an idiot. The problem lies elsewhere in the code. The suggested approach works and I have accepted it as the answer.

# Answer
You need to accumulate some progress between your start and your end. For instance...

```
[Tooltip("How long the rotation should take to complete, in seconds")]
public float rotationDuration = 2f;
float _rotationProgress = 0f;

private void Rotate() {
    // Accumulate rotation progress.
    _rotationProgress = Mathf.Clamp01(_rotationProgress + Time.deltaTime/rotationDuration);

    // Blend to the appropriate fraction of the way between start & final
    transform.localRotation = Quaternion.Lerp(
       startingLocalRotation,
       finalLocalRotation,
       _rotationProgress
    );
}

```

Or you can use the current localRotation itself as your progress measure, using an exponential ease-out style of Lerp:

```
[Range(0f, 1f)]
public float smoothness = 0.9f;

private void Rotate() {
    // Correct the exponential blend speed for the current framerate.
    float blend = 1f - Mathf.Pow(smoothness, Time.deltaTime * 30f);

    // Blend a small incremental step from where we are now to where we're going.
    transform.localRotation = Quaternion.Lerp(
       transform.localRotation,
       finalLocalRotation,
       blend
    );
}

```

Or using the RotateTowards method:

```
[Tooltip("Speed to rotate, in degrees per second")]
public float rotationSpeed = 180f;

private void Rotate() {
    // Rotate at a fixed speed toward the destination.
    transform.localRotation = Quaternion.RotateTowards(
       transform.localRotation,
       finalLocalRotation,
       rotationSpeed * Time.deltaTime
    );
}

```
> 0 votes

# Answer
Try multiplying the last value in the Lerp function by Time.deltaTime. I’m not by my computer to check my old scripts where I used the Lerp function, but I think I remember doing something with Time.deltaTime
> -1 votes

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


# Question
Title: How to make an object with its own sprite draw an additional sprite on top of itself
I'm making character select buttons for a Game Maker Studio 2 game, hoping to do so by just having a single object I can edit on an individual basis to change which character it represents. I also want the button itself to display the sprite of the character it's meant to represent like an image overlaying the button's own sprite. I can't seem to get a clear, direct answer on how this is done.

To sum up:

* Character select button is an object with its own assigned sprite.
* Each individual button object holds (a reference to) a corresponding character object the player may select by clicking that specific button.
* Button object should be able to check the sprite of the character object it references, and draw it on top of its own sprite without replacing it entirely.

If anyone can help show me how to do that last part- or barring that, perhaps point me toward a better way to achieve a similar effect, it would be appreciated.

# Answer
I can think of two different approaches, the earlier keeps code simple whilst requiring more graphics; the latter needs no additional sprites though a little more code to reference the correct sprites.

### Solution 1: a specific sprite for characters

> You add just one line of code, and use an additional sprite resource representing the characters preview to be drawn on your button.

If your buttons have an index reference to a given character like this:

```
/* Button Create Event */
char_ref = -1;    // character reference

```

Create a sprite with as many frames as the number of your characters. Each frame depicts one of your characters (so, 5 char's = 5 frames). Let's call it `sprButtonCharacters`.

If `sprButtonCharacters`' first frame is the first character, and so do other frames, you can use the value of `char_ref` to choose a sub-image of `sprButtonCharacters` to be drawn on top of the button object.

In the button *Draw Event*:

```
/* Button Draw Event */
draw_self();    // draw sprite_index
draw_sprite(sprButtonCharacters, char_ref, x, y);    // draw char. sprite

```

You are **first** drawing the button (you can change `draw_self()` with whatever script or functions you use to render the button), **then** you draw the sprite representing the characters on top of it by choosing the desired sub-image.

You can add some values to `x` and `y` if you need to draw such sprite with given horizontal and vertical offsets.

### Solution 2: everything via code

> Every time you add a new character, just add a new line of code to a script in charge of choosing the sprite to be drawn onto the button. No additional sprites needed.

We still have a `char_ref` variable which tells us what character the button is referencing to, but this time we have different code functions to draw the overlay sprites we need. In the button *Draw Event*:

```
// Button Draw Event
draw_self();    // draw sprite_index
switch (char_ref)    // choose character sprite to draw
{
    case 0: draw_sprite(sprTonyIdle, 0, x, y); break;    // first character
    case 1: draw_sprite(sprAllyCyborg, 0, x, y); break;    // second character
    case 2: draw_sprite(sprRogueWarrior, 0, x, y); break;    // third character
    { ... }
    default: break;    // no character assigned
}

```

This way you can assign *any* sprite you want to be drawn by the button, and no new resources are needed since the sprite is supposed to be already present in your game project.

Also, if you use *-1* instead of *0* as `subimage` argument to `sprite_draw()`, you can draw animated character previews instead of static ones.
> 1 votes

# Answer
If you are using drag and drop then you should be able to simply have it "**create instance**" of an object with the sprite you want and set its position relative to the button. If you want it to be slightly transparent just add a draw event in the object and add "**draw self**" and then add "**set alpha**". If you want to scale the sprite just add a create event and add a "**set instance scale**" block. To ensure that it is on top set it's depth lower.
> 1 votes

---
Tags: sprites, gui, game-maker
---


title: Disconnecting Power Flow from Source

text:
# Question
Title: Disconnecting Power Flow from Source
I'm trying to design a wiring system that allows players to connect power sources to switches via wires. Think redstone in Minecraft. When a wire is placed, if it is not initially connected to the power source, it has no power (behaving as expected). The PROBLEM occurs when the wire is connected to power, detecting that it is powered, and then disconnects from power. After it has touched the power source, it then becomes it's own source if disconnected, which is not what it should be doing.

This is what SHOULD be happening

Here's what is ACTUALLY happening

And here is my code:

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

 public class Wire_Moveable : MonoBehaviour {

 public static Wire_Moveable control;

 public bool IsBlue;
 public bool IsRed;
 public bool powered;

 void Start () {
     IsBlue = false;
     IsRed = false;
 }

 void Update () {
 if (Input.GetMouseButtonUp (0)) {
         following = false;
         this.gameObject.GetComponent<Wire_Moveable>().SnapWire ();
     }
 }

 void OnTriggerStay2D (Collider2D trigger) {
     if (trigger.tag == "wire") {
         if (trigger.gameObject.GetComponent<Wire_Moveable>().powered) {
             powered = true;
         }

         if (trigger.gameObject.GetComponent<Wire_Moveable> ().IsBlue) {
             IsBlue = true;
             IsRed = false;
         } else if (trigger.gameObject.GetComponent<Wire_Moveable> ().IsRed){
             IsBlue = false;
             IsRed = true;
         }
     }
 }

 void OnTriggerExit2D (Collider2D trigger) {
     if (trigger.tag == "startnode_blue") {
         IsBlue = false;
         powered = false;
     }

     if (trigger.tag == "wire") {
         if (trigger.gameObject.GetComponent<wire_Moveable>().powered) {
             powered = false;
         }
     }
 }

 void SnapWire () {
     if (this.gameObject.name == "Wire_Basic" || this.gameObject.name == "Wire_Basic(Clone)") {
         StartCoroutine ("ActivatePower", 0);
     }
 }

 IEnumerator ActivatePower () {
     yield return new WaitForSeconds (0.1f);
     if (powered) {
         PowerBeam.SetActive (true);
     } else if (!powered) {
         PowerBeam.SetActive (false);
     }
 }

```

# Answer
> 2 votes
You can solve this one of two ways, either try to path to a source of power, or the tiles need to keep track of who its source neighbor is.

Pathing can get expensive as your wires become complex, so I'd suggest the second approach.

Basically you need to keep track of where the tile got power from, and check regularly to see if a neighbor has power when the tile doesn't.

I'm going to pseudocode this a bit, because i don't usually use colliders for this when I'm working in 2d, and event handling complicates the solution for future readers.

```
public class WireSegment : MonoBehaviour {

    public bool powered=false;//whether or not we are powered
    public WireSegment source;

    //called when first created
    void Start () {
        checkNeighborsForPower();
    }

    //called each frame
    void Update () {
        if(powered && !source.powered){
            //then our source is unpowered, and we need to turn off
            source=null;
            powered=false;
        }
        if(!powered){
            //We lost our source, so see if we can find a new one.
            checkNeighborsForPower();
        }
    }

    private void checkNeighborsForPower() {
       //we'll require adjacency to get power
       WireSegment left= findMyNeighbor(transform.position+Vector2.LEFT);
       WireSegment right= findMyNeighbor(transform.position+Vector2.RIGHT);
       WireSegment top= findMyNeighbor(transform.position+Vector2.UP);
       WireSegment bottom= findMyNeighbor(transform.position+Vector2.DOWN);

       if(top.powered && top.source!=this){
           source=top;
           powered=true;
       }else if(right.powered && right.source!=this){
           source=right;
           powered=true;
       }else if(bottom.powered && bottom.source!=this){
           source=bottom;
           powered=true;
       }else if(left.powered && left.source!=this){
           source=left;
           powered=true;
       }
    }

    private WireSegment findMyNeighbor(Vector2 neighborLocation){
        //Do a lookup from wherever we are storing our collection of WireSegments
    }

}

```

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


# Question
Title: I can't jump when i press up, and left at the same time
```
///Get player's input
key_right = keyboard_check(vk_right);
key_left = -keyboard_check(vk_left);
key_jump = keyboard_check_pressed(vk_space);
key_jump_held = keyboard_check(vk_space);
key_shoot = keyboard_check(ord("D"));

//React to inputs
move = key_left + key_right;
hsp = move * movespeed;
if (vsp < 10) vsp += grav;

if (place_meeting(x, y+1, Obj_Floor))
{
 vsp = key_jump * -jumpspeed;
}

if (vsp < 0) && (!key_jump_held) vsp = max(vsp,0)

//Horizontal Collision
if (place_meeting(x+hsp, y, Obj_Floor))
{
 while(!place_meeting(x+sign(hsp), y, Obj_Floor))
 {
  x += sign(hsp);
 }
 hsp = 0;
}
x += hsp;

//Vertical Collision
if (place_meeting(x, y+vsp, Obj_Floor))
{
 while(!place_meeting(x, y+sign(vsp), Obj_Floor))
 {
  y += sign(vsp);
 }
 vsp = 0;
}
y += vsp;

//Animate
if (move != 0)
{
 image_xscale = move;
}

if (place_meeting(x, y+1, Obj_Floor))
{

 if (move != 0)
 {
  sprite_index = CalvinWalking;
  image_speed = 0.07;
 }

 else
 {
  sprite_index = CalvinStanding;
  image_speed = 0.025;
 }
}

else
{
 if (vsp < 0) sprite_index = CalvinJumping
 else sprite_index = CalvinJumping
}

```

and

```
///Shooting with D
//Shooting direction
if (keyboard_check(vk_right))
{
 mpfacing = 0;
}

if (keyboard_check(vk_left))
{
 mpfacing = 180;
}

if (keyboard_check(vk_up))
{
 mpfacing = 90;
}

//Shooting
if (keyboard_check(ord("D"))) && (canshoot = true)
{
 instance_create(x+13, y-0.5, Obj_MP_Laser);
 canshoot = false;
 alarm[1] = 30;
}

```

is my code but for some reason when i press up, and move left, i can't jump when i press space. Which i don't understand because i can jump when moving left, and when i press up, but not when i press both.

# Answer
Apparently using any other button other than space works, because the space key has trouble working with multiple buttons. Literally, using any other button fixed it.
> 0 votes

---
Tags: movement, game-maker, jumping
---


# Question
Title: Calculate bounce and friction after a projection-based collision
According to the N Tutorials, after a projection-based collision (i.e, adding a minimum translation vector to an object's position in order to bring it out of collision), bounce and friction are applied with the following three steps:

> * split velocity vector into two components: one parallel and one perpendicular to the collision surface
> * calculate bounce using the perpendicular component
> * calculate friction using the parallel component

I am assuming that, by "velocity vector", the tutorial refers to the object's current velocity.

How is this done? And, please try to keep it low-level so as not to confuse someone who knows essentially nothing about physics.

# Answer
> 5 votes
The "velocity vector" is the difference between the velocities of the two objects. When colliding with a static (unmoving) object (such as the level), the "velocity vector" is indeed its current velocity.

Normally, the collision surface's direction will be represented by a "normal" -- a vector of length 1 that points in the direction the surface is facing.

If you multiply the normal by the dot-product of the normal and the velocity vector (the dot product is a simple formula I'll explain below), you'll get the component of the velocity vector that's in the same axis as the normal (which is the perpendicular component -- the normal is perpendicular to all vectors along the surface).

If we subtract the perpendicular component from the velocity vector, we get the parallel component. That's to say, if we changed the velocity as little as possible to prevent it from going through the surface -- now it's going across the surface.

The dot product I mentioned before multiplies the corresponding elements of each vector together and adds them all together. So if you have velocity vector **V** and normal vector **N**, the dot product **d** is:

**d** = **V**x * **N**x + **V**y * **N**y + **V**z * **N**z

The "perpendicular component" **P** is the normal multiplied by that dot product:

**P** = (**N**x * **d**, **N**y * **d**, **N**z * **d**)

This is going through the surface, though. So if we subtract it from the velocity vector **V** we get the parallel component (let's call it **A** for "across"):

**A** = **V** \- **P**

And if we subtract **P** from that, we get the bounce vector **B**:

**B** = **A** \- **P**

This is all true in both 2D and 3D. For the 2D version, just take out the parts with Z:

**d** = **V**x * **N**x + **V**y * **N**y

**P** = (**N**x * **d**, **N**y * **d**)

---

*Let's bring it all together with how we'd modify the velocity when colliding with a static object.*

First, you can stop moving through the object by subtracting **P** from **V**:

**V** = **V** \- **P**

This is the same as calculating the "across" vector, **A**. Now, if you want to apply friction to the object, you can do it like so:

**V** = **V** \- (**A** * **f**)

...where **f** is a "friction factor". 0 means no friction, 1 means the object stops immediately due to friction. When an object is ontop of another object, they're colliding over and over again due to gravity, so you'll usually want to have "friction" be really small to not cancel out all attempts to move across a surface over a few frames of simulation, and you might want to calculate the amount of friction by fancier means than just a fixed value, but I won't get into that here.

Finally, you can use a "bounce factor" **b** to apply bounce:

**V** = **V** \- (**P** * **b**)

A bounce factor of 0 will mean no bouncing, 1 will mean full bounce.

---
Tags: 2d, physics, collision-resolution, separating-axis-theorem
---


# Question
Title: how to make turret only shoot when pressing in specific location?
im using this code to shoot bullets from turrets, it is working perfectly but what i want to do is that, if i ll click mouse at the bottom of it it will still shoot i want it to only shoot if i will click on those positions i ll attach image to explain what i want to do here is my code:

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

public class shoot : MonoBehaviour {
    public Rigidbody2D projectile;
    public Transform fireTransform;
    public GameObject missilePrefab;
    public float fireForce = 90000;
    public Transform projectileSpawnPoint;
    public float projectileVelocity;
    public float timeBetweenShots;
    private float timeBetweenShotsCounter;
    private bool canShoot;
    protected Animation Animation;

    void Awake() {
        Animation = GetComponent<Animation> ();
    }
    void Start () {
        canShoot = false;
        timeBetweenShotsCounter = timeBetweenShots;
    }

    void Update () {
        if (Input.GetMouseButton(0) && canShoot)
        {
            GameObject missile = Instantiate(missilePrefab, fireTransform.position, transform.rotation);
            Animation.Play ();
            Rigidbody2D missileBody = missile.GetComponent<Rigidbody2D>();
            AudioSource audio = gameObject.AddComponent < AudioSource > ();
            audio.PlayOneShot ((AudioClip)Resources.Load ("sh"));
            missileBody.AddForce(transform.forward * fireForce);
            canShoot = false;
        }
        if (!canShoot)
        {
            timeBetweenShotsCounter -= Time.deltaTime;
            if(timeBetweenShotsCounter <= 0)
            {
                Animation.Stop ();
                canShoot = true;
                timeBetweenShotsCounter = timeBetweenShots;
            }
        }
    }
}

```

# Answer
Instead of putting your code in an `if (mouseClicked ...)`, put it in a public function. Then on your scene, create a UI element (probably a button), move it around the screen to the desired location, then on the Inspector, set its `OnClick()` action by pressing the `+` button, then drag and drop your turret's object on the field that appears, and from the bar choose `MyTurretScript -> MyShootingFunction`. This should only trigger when you click the UI button on the screen.

Alternatively, if you want your button to be in a 3D scene (so that it scrolls together with the camera for example) you can create an object, give it a `Collider` and also a script that looks like this:

```
void OnMouseDown() {
    myTurrentScript.MyFireFunction();
}

```

Please note I used example names, replace them as needed.

Edit:

Instead of

```
void Update () {
    if (Input.GetMouseButton(0) && canShoot)
    {
        GameObject missile = Instantiate(missilePrefab, fireTransform.position, transform.rotation);
        Animation.Play ();
        Rigidbody2D missileBody = missile.GetComponent<Rigidbody2D>();
        AudioSource audio = gameObject.AddComponent < AudioSource > ();
        audio.PlayOneShot ((AudioClip)Resources.Load ("sh"));
        missileBody.AddForce(transform.forward * fireForce);
        canShoot = false;
    }
    if (!canShoot)
    {
        timeBetweenShotsCounter -= Time.deltaTime;
        if(timeBetweenShotsCounter <= 0)
        {
            Animation.Stop ();
            canShoot = true;
            timeBetweenShotsCounter = timeBetweenShots;
        }
    }
}

```

Do

```
void Update () {
    if (!canShoot)
    {
        timeBetweenShotsCounter -= Time.deltaTime;
        if(timeBetweenShotsCounter <= 0)
        {
            Animation.Stop ();
            canShoot = true;
            timeBetweenShotsCounter = timeBetweenShots;
        }
    }
}

public void Shoot() {
    if (canShoot)
    {
        GameObject missile = Instantiate(missilePrefab, fireTransform.position, transform.rotation);
        Animation.Play ();
        Rigidbody2D missileBody = missile.GetComponent<Rigidbody2D>();
        AudioSource audio = gameObject.AddComponent < AudioSource > ();
        audio.PlayOneShot ((AudioClip)Resources.Load ("sh"));
        missileBody.AddForce(transform.forward * fireForce);
        canShoot = false;
    }
}

```

Now other objects on the scene can call `myTurret.Shoot()` in order to attempt to shoot a missile (if `canShoot` is `true`).
> 1 votes

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


# Question
Title: is GameObject.Find() a bad idea even for one frame?
as I searched `GameObject.Find` and `GameObject.FindwithTag` are heavy to work with and for reall projects its better to find repalcements.

for a NPC that get instantiated in game it first needs to find player character. for this issue I only can use `GameObject.find()` .

for a scene with lots of objects maybe its heavy for even one frame if there is lots of objects in the scene. is there any way to set the researching object in head of hierarchi and the NPC to only get that?

# Answer
The `GameObject.Find()` function sure is heavy, but it doesn't mean your game will run slow if you use it even once. The idea is that it's better to get reference of object in another way.

In your example, you can make a script that has static variables, one of them is a reference to the player. Once the player is initialised, it assigns itself to that variable, now every other object (even ones created dynamically) can reference the player from that variable.

That's not to say that `GameObject.Find()` should never be used, but when you are developing a game, it's not very comfortable thinking that every object you add makes everything run slightly slower. Especially if you only plan to run it in one frame, you'd have to have a big amount of objects to cause a noticeable delay.

Edit: Example

```
// MyGlobalConfig.cs
public class Config : MonoBehaviour {

    public static Transform player;
    /* Other static data */

}

// Player.cs
public class Player : MonoBehaviour {

    // ...

    void Start() {

        // Init player

        Config.player = transform;

    }

// SomeFile.cs
public class MyClass : MonoBehaviour {

    Transform player;
    // ...

    void Start() {

        player = Config.player;
        // ...

    }
}

```

You can of course save the player as something different than a `Transform` depending on your needs.
> 4 votes

# Answer
When you use Find only once when the scene loads, then performance is unlikely to be an issue. You would have to do that for quite a lot of objects to get a notable increase in scene load time.

But there are some other problems to keep in mind:

* When you refer to objects by name, you can't rename that object. That might not be a problem in a simple project, but it can lead to problems in a more complex project. You will quickly lose track of which objects can be renamed and which can not because something refers to them by name.
* Names are not enforced to be unique. When you have more than one object of the same name in the scene, you won't know which one you will find. It might find the correct one at first, but then suddenly it finds the other one, your game breaks, and you have no idea why.
* When you refactor your project and turn the object into a prefab you instance at runtime, it will now have a `(Clone)` behind its name. I forgot that once and searched for that problem for hours.

So **tl;dr:** it's a very fragile solution which can easily break during future development.
> 2 votes

---
Tags: unity, unityscript
---


# Question
Title: Why does this work? - camera rotation from screen space
I do not understand the math behind the linked function or why it works. I would like to know this.

https://sidvind.com/wiki/Yaw,\_pitch,\_roll\_camera

```
void Camera::motion(int x,int y){
        theta+= x / 200;        /* Adjust this to control the sensitivity */
        phi+= y / 200;

        target.x = cos(theta) * sin(phi);
        target.y = cos(phi);
        target.z = sin(theta) * sin(phi);
}

```

# Answer
> 4 votes
This is simply converting the input angles theta & phi in spherical coordinates to a vector in Cartesian coordinates.

Think back to high school math & studying the unit circle. From that we know that:

$$\vec p = \left(cos(\theta), sin(\theta)\right)$$

Gives us a vector on a circle with radius 1, an angle of \\$\theta\\$ counter-clockwise from the positive x-axis.

That explains the first term of the `x` and `z` formulas. If `sin(phi) == 1` then these formulas would just trace out a circle with radius 1 about the origin in the xz (horizontal) plane, giving us our yaw behaviour, so our camera can look 360 degrees side to side.

Now we need to handle looking up or down off that horizontal plane. That's where `phi` comes in. It measures how far we've pitched down from the positive y-axis (this is a slightly unusual parametrization - usually I see pitch measured plus/minus from the horizontal plane, but the math is similar either way)

When `phi` is 90 degrees, we're looking at a right angle to the vertical axis, ie. we're facing out directly along the horizontal plane. So it makes sense then that at this point `sin(phi) == 1` so we get the full unit circle of movement from `x` & `z`, and `cos(phi) == 0` so the `y` component of our unit vector is zero.

As we pitch up or down, the `y` component of the vector changes, from `cos(0°) == 1` when we're looking straight up, to `cos(180°) == -1` when we're looking straight down.

The x & z components have to change too though. As we slide the xz plane up & down the unit sphere, the radius of the circle intersecting that plane shrinks and shrinks until it becomes a point at either pole. That's the job the `* sin(phi)` term is doing: scaling back the xz extent of our vector as the y extent grows, so that it remains a unit vector throughout.

---
Tags: camera, rotation
---


title: Why is this stored velocity changing?

text:
# Question
Title: Why is this stored velocity changing?
```
    public void OnGamePause()
{
    Debug.Log("OnGamePause in PauseController");

    if (rb != null)
    {
        velocity = rb.velocity;
        angularVelocity = rb.angularVelocity;
        Debug.Log("Pause vel. = " + velocity + "Avel. = " + angularVelocity);
        rb.Sleep();
        Paused = true;
    }
}

public void OnGameResume()
{
    Debug.Log("OnGameResume in PauseController");

    if (rb != null)
    {
        Debug.Log("Resume vel. = " + velocity + "Avel. = " + angularVelocity);
        rb.velocity = velocity;
        rb.angularVelocity = angularVelocity;

        rb.WakeUp();
        Paused = false;
    }
}

```

Can anyone give me any idea what might be changing velocity?

# Answer
Turns out I was just calling OnGamePause many times due to not limiting input.
> -1 votes

# Answer
Where does OnGamePause come from? the unity documentation reads OnApplicationPause, which is called twice, so i believe that's what causing it. Try copying the vector into a new Vector3, and check if it's set before you do so:

```
Vector3 velocity = velocity == null ? new Vector3(rb.velocity) : velocity;

```

also, i don't think the rb.sleep() and rb.wakeup() are necessary when pausing the game. check this link out: https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnApplicationPause.html
> 0 votes

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


# Question
Title: Are closing window and destroying DirectX11.1 independent?
I have a project with DirectX support. In this program uses two threads. One is a dedicated message loop and the second is executing DirectX API's. The question is about ending such program. The WM\_CLOSE sends asynchronous command, that stops rendering and exits DirectX loop too. After that it destroys the window. Everything works fine. The question is, is this algorithm OK? Should the window's thread or the DirectX thread be synchronized (dependent)?

# Answer
> 0 votes
The main area of synchronization is between your 'windows thread' and the thread you call 'DXGI' from for Present.

See Microsoft Docs.

# Answer
> 0 votes
When executing, you need to be careful, if the close starts releasing our impacting resources in your windows main thread, this can affect your DirectX thread. As another answer has indicated, the Present is your point of Sync. You maybe best to at the least use some atomic flags cross the threads to ensure that your close action has not started at the same time as you are entering a critical part of your draw execution.

If for example, you built a synchronous close function called from your parent thread that waited on other child threads to complete and close then that is one approach. Once you start into the world of deferred contexts and further multi-threading your game. A common sync point for critical system action will be more important (actions such as close).

Having gone through the multithreading pain myself, the key point I have found is that destruction of objects in child threads causes all sorts of headaches.

---
Tags: c++, directx11, windows, visual-studio
---