# Question
Title: How to Change position + rotation of a parent while keeping X and Z Rotation
Sooo this question is a problem , a evolution by another solution of this problem here:

How can I change the parents rotation so the childs rotation is looking at a specific direction

Basically:

We have a "Eye" (HTC Vive). We have a "Parent" which is the Parent of "Eye".

We can not change the position or rotation of the Eye in code. We can only change the position and rotation of the Parent.

1.We want to modify the Parent Position so that Eye to goes to a certain "Target 1" position.

2.We want to modify the Parent Y-Rotation so that the Eye looks at a certain "Target 2" position.

3.While doing this we dont want to modify the Parent X or Z , because this would lead to a Rotated game experience.

The Parent Position changes so the Eye gets to "Target 1" position. The Parent Position changes so Y- Rotation should look at Target 2 position The Parent X/Z Rotation should not modify the Eye X/Z

# Answer
```
// Construct a scale vector to flatten our directions into the horizontal plane,
// so we only consider the yaw component of the rotation.
var horizontal = new Vector3(1, 0, 1);

// Find which way the eye is pointing in the parent's horizontal plane.
var eyeHeadingHorizontal = Vector3.Scale(eye.localRotation * Vector3.forward, horizontal);
// Find which way we want it to look in the world's horizontal plane.
var lookHeadingHorizontal = Vector3.Scale(target2 - target 1, horizontal);

// Compute a rotation that takes the eye's heading to the desired heading.
parent.rotation = Quaternion.FromToRotation(
             eyeHeadingHorizontal,
             lookHeadingHorizontal);

// Compute the eye's worldspace offset from its parent in this orientation.
Vector3 eyeOffset = parent.TransformVector(eye.localPosition);

// Move the parent so that its position plus this offset puts the eye exactly on-target.
parent.position = target1 - eyeOffset;

```
> 3 votes

---
Tags: unity, rotation, virtual-reality, htc-vive
---


# Question
Title: How to work with libddx and Android studio
I am new in game development.I am getting problem with libgdx. when i download libgdx i get zip file.where is setup

# Answer
> 1 votes
After setting up your development environment (process varies depending on what you plan to use), you can use the Libgdx wizard tool (gdx-setup.jar) to create a Gradle ready project, which can then be imported into your IDE:

1. Download LibGDX Project setup tool "gdx-setup.jar"
2. Open your command line tool, go to the download folder and run: `java -jar ./gdx-setup.jar`

---
Tags: libgdx
---


title: Hide network latency for ingame dialog

text:
# Question
Title: Hide network latency for ingame dialog
I have a tick-based Multiplayer-RTS game: Client sends action to server at Frame n which will be broadcasted to all clients and executed at Frame n+x (x depends on network latency of slowest player)

I'm unsure how to hide this latency in GUI dialogs. E.g. a value that is adjustable with a slider between 0 and 100. The current solution simply fills a "virtual" value with the actual value at game start and always operates on that value. It is highly unlikely that a change command for this does not get executed (TCP, unconditional change execution) but it is possible (packet sent and ignored during pause)

I also wanted to keep that value local to the dialog and not store it somewhere else. Start idea: Get the current value on dialog open and use this while the dialog is open. Problems: Maybe the value was changed before (packet sent, but not executed) in which case the change does not get displayed. An idea I have is storing the last value I got and update the slider if that value has changed. Maybe only when the sliders position itself did not change (by the user). However then after the update it will detect that change and change it again which leads to a change of twice the amount requested. I could also update the "last value" when the packet is sent but that will cause the (time-based) update to change it back till the actual change is made which might even result in a loop of back-and-forth changes. How can I keep the GUI and game in sync but allow visual changes? Seems I'm missing a little piece here...

Another part where this is even worse is with other kinds of dialogs. E.g. an ordering dialog (put some entities in a specific order) or a number input that is used to request producing the specified amount, hence the game may also decrease this, not only the packet. I could not find any guides or solution besides "use inter/extrapolation" which is not applicable here. How do others do this?

Edit: Maybe a little example for the strategy I though off with its flaws:
A) **OK**

* Value=4
* Open Dialog -\> Show Value=4
* User Changes Value to 6 (Slider position change)-\> Sent to server
* Server sends "6" -\> Slider changes to "6" (no change as it already is)

B) **OK**

* Same as A) but dialog closed before receiving from server
* Dialog reopened -\> Show Value=4
* Server sends "6" -\> Slider changes to "6"

C)

* Value=4
* Open Dialog -\> Show Value=4
* User Changes Value to 6 (Slider position change)-\> Sent to server
* User Changes Value to 7 -\> Sent to server
* Server sends "6" -\> Slider changes to 6 **BAD**
* Server sends "7" -\> Slider changes to 7 =\> OK, but strange and may cause feedback loops

D)

* Value=4, change to 6 requested
* Open Dialog -\> Show Value=4 (6 was stored in the old dialog)
* User Changes Value to 7 -\> Sent to server
* Server sends "6" -\> Slider changes to 6 **BAD**
* Server sends "7" -\> Slider changes to 7 =\> OK, but strange and may cause feedback loops

So on one hand I only want to show visual values (and store them between dialogs) but on the other hand I want to keep them in sync with the actual value. So only solution here seems to be to persistently store the visual value and make sure, each update will eventually be executed. But I'm still clueless what to do with values that can be changed by the came (e.g. production orders that decrease once they are processed)

# Answer
First, you need to assure that you get your commands to be more stable than "highly unlikely." Why is 'pause' state ignoring remote updates?

Second, often quoted networking reference contains examples of handling latency on both server and client, plus dependable communications. I think that ideas on that page may make you rethink your "turn n+1" concept because server time is quite fluid and not lockstep to the clients at all.

Using ideas from that networking reference your GUI latency will mostly disappear. However, there will be times when the server invalidates your choice and that means that your GUI and game will have to adjust to the new, blessed value, but that's expected in an online, real time title.

In your particular case I have a suggestion: I think that you're right about wanting two variables to track this visual. The first variable is the server blessed setting which is updated from messages received. The second variable is the locally requested value, what the player wants this to be.

In your GUI you show the real value so the player always knows what it is and then you also show the requested value (as an overlay, a different icon or color, whatever works for your look) and when the real value is received from the server the overlay disappears.

In your logic you will work from the requested value. Also in your logic if the server invalidates your setting you will need to be able to go back to that frame and re-run the game simulation up to that point. This is also covered in the reference.

The blessed value from the server is a one-way communication and will fix your ping-pong scenario and/or double movement. At the expense of extra logic to replay unaccepted requests.
> 1 votes

# Answer
I think your mental model of how to handle state updates is fundamentally flawed. @Patrick Hughes suggestion of Gaffer on Games' Networking Articles are really a good primer on the subject.

When working with real world networks you need to overcome four problems:

* latency
* jitter
* packet loss
* out of order delivery

Now you though about latency, which just the time it takes for packets to go from application to application. Jitter is changes in latency. Packet loss is when packets simply don't get delivered. And finally out of order delivery is when one packet gets delivered after the next one in the sequence.

It appears you are using TCP, where you man not need to handle the two later ones, but that just results in more jitter. (Not on the wire, but the app, since TCP masks the issues by waiting.) In a client server environment these network effect will ensure that your clients will run out of sync quickly. That is why the replay approach never really worked out.

The dominant approach is the send commands to server and send world state client. This allows for two things, first the server can take each command and execute it, which ensure a consistent state (for the server). Secondly, it allows client that are aware they are significantly lagging behind to just skip forward to latest world state and just ignore everything that happened in between.

As to your specific problem, as long as both users see the same value at roughly the same time all is okish. If two users are trying to change one value at the same time, well that is a higher problem in your design. Imagine a system with a perfect network, the fundamental problem will not go away, since Alice will set to 7 and Bob to 6. When Alice sees the value being 6, but not 7, she will be irritated and set it back to 7. But in turn Bob will be surprised the value went to 6...
> 0 votes

---
Tags: networking, client-server, latency
---


title: NullReferenceExepction Error

text:
# Question
Title: NullReferenceExepction Error
I'm getting error an error on this piece of code:

```
if (EventSystem.current.IsPointerOverGameObject())
     return;

```

The error: `NullReferenceExpection: object reference not set to an instance of an object playercontroller.update() { at assets/script/palyer/playercontroller.cs:21)`

Any solution to this?

# Answer
> 3 votes
The error message is there to tell you what the problem is. A `NullReferenceException` means you tried to access a variable that is currently null:

```
Object a = null;
a.ToString();  <-- this line throws a NullReferenceException!

```

So in your case, assuming `EventSystem` is a class, `EventSystem.current` is null.

As this is Unity, the most likely issue is that you haven't added an EventSystem to your current scene, so there is no current EventSystem.

---
Tags: unity
---


# Question
Title: How can I make the camera to rotate from side side but in static movement range?
I mean for some reason now the camera is rotating to the left and to the right but sometimes it's rotating to one of the sides a lot I mean a very sharp angle and sometimes less rotation.

How can I control how much rotation will be from side to side by degrees ?

```
using UnityEngine;
using System.Collections;

public class scr_camera : MonoBehaviour {

    public float rotate_amount;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        transform.rotation = Quaternion.Euler(transform.eulerAngles.x, (Mathf.Sin(Time.realtimeSinceStartup) * rotate_amount) + transform.eulerAngles.y, transform.eulerAngles.z);
    }
}

```

Sometimes cam14 make almost 240 even close to 300 degrees rotation to one of the sides sometimes less. The rotation is not equal to both sides. I want simple rotation to both side just to see the room and not the walls behind the camera.

In this case I set the rotate\_amount to 7 so it will rotate faster.

# Answer
> 2 votes
Try this:

```
public class scr_camera: MonoBehaviour {

    public float rotate_amount;
    float initialAngle;

    void Start() {
        initialAngle = transform.rotation.eulerAngles.y;
    }

    void Update() {
        transform.rotation = Quaternion.Euler(transform.eulerAngles.x, (Mathf.Sin(Time.realtimeSinceStartup)/2 * rotate_amount) + initialAngle, transform.eulerAngles.z);
    }
}

```

Notice that first we need to store the initial rotation, in order to add the offset we calculate.

If you simply add the offset to the current rotation like this:

```
(Mathf.Sin(Time.realtimeSinceStartup) * rotate_amount) + transform.eulerAngles.y

```

`rotate_amount` will be not setting the maximun rotation, but the maximun rotation speed.

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


# Question
Title: Small, High-Speed Object Collisions: Avoiding Tunneling
***EDIT/UPDATE:*** *My biggest question right now is whether step 3's "t=..." equation is a good idea or there a better way to do it. Most other issues have been partially or fully addressed, but no comments or answers have really touched on this issue. Again, an analytic solution is probably required, the velocities and distances are too large, and the objects are too small, for any iterative/recursive solution (a few are suggested below in the comments) that I can think of (although if there is a special iterative/recursive solution that will handle these kinds of situations fine then I'm definitely open to it). Thank you very much for your help so far, you all are awesome and I really appreciate your thoughts and help!*

I'm trying to detect collisions between small, high-speed objects. This is a situation where tunneling may occur very easily, even at relatively low speeds.

Ray casting will not work, since this is detecting a collision between two high-speed objects, not between one object and a stationary wall. (Unless if I'm misunderstanding ray casting?) Performance is VERY MUCH a consideration; if at all possible, I want to avoid a large performance hit. I already have a functional and very effective quadtree (http://en.wikipedia.org/wiki/Quadtree) implemented, so I shall modify and use it as described below.

Edit: Reducing the time interval will not work. The speeds are too high for this solution, which means that the performance hits would be too great, *while still missing the vast majority of the tunneling collisions*. (For example, I might have an object with a size of about 1 unit going at a speed measured in millions of units per time interval...)

***PROPOSED SOLUTION:***

Step 1:

Create a box around each object's movement, then feed those boxes into the quadtree to generate an initial list of possible collisions. See the following image (this image shows a circle object moving from one position to another, and the movement generating a rectangle, which will be fed into the quadtree):

Step 2: (might want to skip this step?)

Go through the list of possible collisions generated by the quadtree. See if the rectangles intersect in each possible collision. If so, proceed to step 3.

EDIT: Below, Sean Middleditch suggested using swept volumes/the intersection of capsules (if the objects are circles). That leaves three options: 1) skip step 2 entirely. 2) Do step 2 my way. 3) Do it Sean's way. Sean's way will be more computationally expensive than my box idea, however it will weed out more false positives than my way, preventing them from getting to the final step.

Can anyone speak from experience as to which of these 3 choices is best? (I intend to use this physics engine for a few different thing, so I am looking for the "generally best" solution that works the fastest in the widest variety of situations, not just one specific test case in which I can easily measure which solution is fastest).

Step 3:

Use the t = equation below, if the discriminant (i.e. the part under the square root) is negative or 0, no collision, if positive then use the t value as the time of collision (after which it is easy to adjust positions accordingly...if both objects continue to exist after the collision). Equation:

**t = (-1/2 sqrt((2 a w-2 a x+2 b y-2 b z-2 c w+2 c x-2 d y+2 d z)^2-4 (w^2-2 w x+x^2+y^2-2 y z+z^2) (a^2-2 a c+b^2-2 b d+c^2+d^2-r^2-2 r s-s^2))-a w+a x-b y+b z+c w-c x+d y-d z)/(w^2-2 w x+x^2+y^2-2 y z+z^2)**.

Where (1 and 2 are used to denote objects 1 and 2):

t is a negative time value between 0 and -1, where 0 is the current frame, and -1 is the previous frame;

a = x position 1;

b = y position 1;

c = x position 2;

d = y position 2;

w = x velocity 1;

x = x velocity 2;

y = y velocity 1;

z = y velocity 2;

r = radius 1;

s = radius 2;

Derivation: (^2 means squared)

Take parametric equations (for example, newxpos1 = a + t*w) for the objects' motions and plug them into the distance formula (squaring both sides): distance formula squared = (a + t*w - (c + t*x))^2 + (b + t*y - (d + t\*z))^2. Remember, t is going to be negative. To find the time of collision for two circular objects we set the left side equal to (r+s)^2. Solving for t using the quadratic equation (and a great deal of very tedious algebra), we get the above "t=..." equation.

***My Questions:***

1) Is this a good way to do it? Will it work at all? Am I going to run into any unforeseen issues? (I know I'm going to have trouble when more than 2 objects at a time collide, but I don't care since the only case that I really object to that is when they have low relative velocities (if the relative velocities are high then the "goofy" solution the algorithm gives will be "good enough", and it will be impossible for a human to see the error), and if more than 2 collide with low relative velocities in the same time-step, most solutions will be close enough anyway, since I don't plan on having a bunch of inelastic collisions)

2) Will my performance suffer a lot? I don't think it will, but if it will, is there a better way to do it?

3) Should I skip step 2 and go straight from step 1 to 3? Obviously step 2 is not vital, but it might help performance (OR it might cost more CPU time than it saves).

All other comments, suggestions, or criticism is very welcome. Thank you for your help!

# Answer
The algorithm proposed in the question works great: ***it is fast and is completely accurate***, even when the objects are going at extreme speeds. I have a quadtree implemented, so after feeding the boxes from step 1 into the quadtree, I found step 2 to be unnecessary: my program was running almost as fast as before.

I've been using this algorithm for a couple of months now, and it seems to be perfectly accurate in determining t, the time of collision. Since there seems to be nothing on the web that is better, I highly recommend using this one. (Some of the answers in the other answers and comments above are great, but they either don't quite meet the needs as stated by the question or else the author was very ambiguous about something and never came back to answer when questioned about the ambiguity).
> 5 votes

# Answer
You have essentially create a somewhat over-enthusiastic version of *swept volumes*.

Take the object's two positions. "Sweep" the object from its start to the end. For a sphere, this would create a capsule. For a box, this would create a hexagon (or a longer box is the movement is along a single axis). For general convex polygons, this would create a different convex polygon.

You can now do intersection tests (including quadtree queries) using this swept volume. You can calculate when the collision had occurred, roll forward the simulation from the starting time to the collision time, and repeat.

Another option, somewhat simpler, is to do what @ashes999 stated and to simply use a smaller time interval or smaller speeds. There is an ideal maximum speed derived from the interval in which no object can move farther than its narrowest side in a single physics interation. For particularly small or particularly fast objects you may not be able to find a reasonably small interval that performs well.

See Real-Time Collision Detection for one of the better introductory/intermediary books on the topic of detecting collisions.
> 11 votes

# Answer
I do not have enough reputation yet to comment, but I'd just like to add that using what Sean Middleditch mentioned above makes it possible to calculate your "t". At least if I understood his answer and you question correctly.

Here is a link to an awesome answer by sam hocevar that provides the best explanation about it I have ever found (he drew pictures too, hurray!)

https://gamedev.stackexchange.com/a/55991/112940

If that is faster than your own method I cannot say, but he sure gives you everything you need in order to implement it and compare with yours.

Just to avoid leaving a "link only answer", I will provide a quick summup of his idea:

1. calculate the Minkowski Difference between the two bounding boxes
2. using the relative velocity between then, cast a ray/line segment from the origin to the box created by the Minkowski Difference in order to get the intersection point
3. If the ray hits, divide the distance your ray travaled by the length of the vector representing the relative velocity and you will have your "t"
4. click on the link I provided above and see sam beautiful explanation of all this, with lots of pictures. It is awesome.
> 1 votes

---
Tags: collision-detection, performance
---


# Question
Title: Trying to use 3D vectors for a 2D ping pong game
I am trying to setup a virtual ping pong table, and am getting a little stuck in trying to understand how to do 3D vector math and render it in 2D.

So far, my plan is for the ball: X = up/down, Y = left/right, and Z = forward/backwards

So as a simple start, I am just trying to move the ball forward:

```
ball.vel.x = 0;
ball.vel.y = 0;
ball.vel.z = 1;

```

in my update function:

```
ball.position.x += (ball.vel.x / ball.vel.z) * delta;
ball.position.y += (ball.vel.y / ball.vel.z) * delta;

```

Which obviously makes no sense since 0 / anything is 0.. my ball will never move forward... So I am fundamentally missing something here. What do I need to do so that my Z velocity will actually move the ball's position?

# Answer
> 0 votes
First, I'd change up your coordinate system, because it doesn't match common game conventions and that's likely to cause friction when you try to learn from other answers/tutorials out there.

So, I'd propose the following left-handed scheme:

* x+ is the lateral axis, pointing rightward on your screen
* y+ is the vertical axis, pointing upward on your screen
* z+ is the depth axis, pointing diagonally "into" your screen, away from the viewer

Next, we'll track the ball's position AND velocity in 3D (in what we call worldspace), using all 3 axes.

eg.

```
ball.position.x += ball.velocty.x * deltaTime;
ball.position.y += ball.velocty.y * deltaTime;
ball.position.z += ball.velocty.z * deltaTime;

```

or if we define vector addition and scalar multiplication on our vector types, we can write this more concisely as `ball.position += ball.velocity * deltaTime`

This makes it much easier to check things like "did the ball hit the table?" - let's say our table spans -10 to +10 on the x axis, and -5 to 5 on the z axis, at a height of y = 0. Then our bounce check can look like...

```
if(ball.position.y < table.height /*0*/ ) {
    if(Abs(ball.position.x) <= table.length /*10*/
        && Abs(ball.position.z) <= table.width /*5*/) {
        // In bounds! Let's bounce the ball,
        // reflecting its position & velocity across the table's plane.
        ball.position.y = 2 * table.height - ball.position.y;
        ball.velocity.y *= -1;
    } else {
        // Ball fell out of bounds. Score a point for someone.
        OutOfBounds();
    }
}

```

A more accurate collision method would check the line between the previous & current position of the ball, to check if we clipped the table on our way past the edge, but this shows how simple the math can be in worldspace rather than trying to infer depth & test against a parallellogram in screenspace.

When we want to convert a 3D worldspace position into 2D screenspace for display, we use a *projection*. Here's an example of a simple projection you could use:

```
Vector2 ProjectToScreenPixels(Vector3 worldspace) {
    Vector2 screenSpace = worldSpace.x * screenX
                        + worldSpace.y * screenY
                        + worldSpace.z * screenZ;

    screenSpace += originOffset;

    /* equivalent to:
    screenSpace.x = worldSpace.x * screenX.x
                  + worldSpace.y * screenY.x
                  + worldSpace.z * screenZ.x
                  + originOffset.x;

    screenSpace.y = worldSpace.x * screenX.y
                  + worldSpace.y * screenY.y
                  + worldSpace.z * screenZ.y
                  + originOffset.y;
    */

    return screenSpace;
}

```

We use a few configuration parameters to control the projection. These three decide which way on the screen each axis of our 3D world should point, and how it should be scaled or foreshortened:

```
Vector2 screenX = new Vector2(5, 0);  // +1 unit of x = 5 pixels right on-screen
Vector2 screenY = new Vector2(0, 5);  // +1 unit of y = 5 pixels up on-screen
Vector2 screenZ = new Vector2(2, 2);  // +1 unit of z = ~3 pixels diagonally

```

This is roughly a Cabinet projection: we keep the x & y axes perpendicular & scaled equally, and foreshorten the depth axis that lays diagonal to them. I chose it as a roughly eyeballed match for the image included in your original question.

You can use an additional `originOffset` vector to control where the position (0,0,0) should get drawn on your screen, which effectively pans the whole scene around to help you frame it the way you want.

---
Tags: vector, linear-algebra
---


title: Unity 2D camera behaviour

text:
# Question
Title: Unity 2D camera behaviour
I am trying to create camera behavior where camera moving slightly forward the player along his movement direction to extend the visible area.

For camera movement, I use an empty object which moves as the player object by `Input.GetAxis()` and clamps in some borders around the player for the later to stay in camera area.

But I don't want to simply snap camera to the target object. I want the camera to smoothly lerp forward in player's movement direction and if there is no movement anymore - smoothly lerp back to the player object.

Problem is - I can't detect presence or absence of movement of the empty target object. I thought of using this method https://answers.unity.com/questions/907078/how-to-detect-movement.html `if(Mathf.Abs(rigidbody2D.velocity.y) < 0.001)`

It didn't work at first because I moved my target point with transform.Translate(). When I tried `rigidbody2D.Addforce()` and it didn't work neither. I noticed that applied force actualy isn't reducing per time it stays the same. Then I tried `rigidbody2D.MovePosition()` and it also isn't working also velocity on every axis stays 0 and clamp isn't working with this method. Here is the code:

```
public class TargetPointBehaviour : MonoBehaviour{

[Tooltip("Used as origin point for camera movement.")]
[SerializeField]
private GameObject playerObject; //Used as origin point for camera movement

private Transform playerTransform; //players transform
private Vector2 playerPosition; // x, y player position

private Rigidbody2D targetPointRB2D; //rigidbody2D of target point object

//========================================================================================================

[Tooltip("Value to offset the camera from the player")]
[SerializeField]
private float offsetFromThePlayer; //value to determine how far target to interpolation will be

void Start()
{
    playerTransform = playerObject.GetComponent<Transform>();
    targetPointRB2D = GetComponent<Rigidbody2D>(); // assigning RigidBody2D component to variable
}

void FixedUpdate()
{
    MoveTargetPoint();
    ClampMovement();
    MoveTargetPointToPlayerPosition();
}

private void MoveTargetPoint() // moves targetPoint object by player controls
{
    GetComponent<Rigidbody2D>().MovePosition((new Vector2(Input.GetAxis("Horizontal") * 100,
        Input.GetAxis("Vertical") * 100))); // moves object by player controls
}

private void ClampMovement() //moves target point in defined borders GetComponent<Rigidbody2D>().AddForce
{
    transform.position = new Vector2(Mathf.Clamp(transform.position.x, playerTransform.position.x - offsetFromThePlayer, playerTransform.position.x + offsetFromThePlayer),
    Mathf.Clamp(transform.position.y, playerTransform.position.y - offsetFromThePlayer,
    playerTransform.position.y + offsetFromThePlayer)); //constraints movement by offsetFromThePlayer value

}

//checks if movement of targetPoint stops and when returns it to player object coordinates
private void MoveTargetPointToPlayerPosition()
{
    Debug.Log("Velocity Y: " + targetPointRB2D.velocity.y + ". Velocity X: " + targetPointRB2D.velocity.x);

    if (Mathf.Abs(targetPointRB2D.velocity.y) < 0.01f && Mathf.Abs(targetPointRB2D.velocity.x) < 0.01f)
    {
        StartCoroutine(DelayBeforereturningToPlayerObject());
        transform.Translate(playerTransform.position.x, playerTransform.position.y, 0);
    }
}

private IEnumerator DelayBeforereturningToPlayerObject() //delay for some time befor target returns to player object
{
    yield return new WaitForSeconds(0.1f);
}}

```

I didn't implemented actual camera movement yet cause don't see the point while the target for the camera isn't working. But maybe there is a more efficient way to implement what I want?

# Answer
> 1 votes
If you want to use the object's velocity, you need to move it with velocity / forces / impulses / accelerations. The physics engine won't infer a velocity for you from other types of position setting, and it's generally best to avoid mixing physical and non-physical movements on a single object.

If you want that velocity to go to zero when you stop providing input, you need to tell it to do so. (Newton's first law: an object in motion tends to stay in motion unless acted upon).

You could for instance do this:

```
[RequireComponent(typeof(Rigidbody2D))]
public class SimpleVelocityControl : MonoBehaviour {

    [Tooltip("How fast the object can move, in world units per second")]
    public float maxSpeed = 5f;
    [Tooltip("How long it takes to reach max speed, in seconds")]
    public float accelerationDuration = 0.2f;

    // Cache our physics body for later use
    Rigidbody2D _body;
    void Start() {
        _body = GetComponent<Rigidbody2D>();
    }

    void FixedUpdate() {
        Vector2 input = new Vector2( Input.GetAxis("Horizontal"),
                                     Input.GetAxis("Vertical")    );

        // Clamp the input to a circle (so we don't go faster diagonally)
        if(input.sqrMagnitude > 1f)
            input.Normalize();

        // Apply physics nudges to approach the desired speed
        AccelerateToward(input * maxSpeed, maxSpeed/accelerationDuration);
    }

    // Approach a desired speed without exceeding the allowed acceleration
    void AccelerateToward(Vector2 targetVelocity, float maxAcceleration) {
        // Calculate change in velocity needed.
        Vector2 deltaV = targetVelocity - _body.velocity;
        float magnitude = deltaV.magnitude;

        // Calculate a limit for what we can perform in this frame
        float limit = maxAcceleration * Time.deltaTime;

        // Cap the change at our limit
        if(magnitude > limit)
            deltaV *= limit/magnitude;

        // Apply the velocity change
        _body.velocity += deltaV;
    }
}

```

(There are lots of ways to improve on this basic movement, like amping up the acceleration when turning sharply or stopping, but this gets the foundation)

Now your camera follow has a legitimate velocity value to use:

```
public class LeadBody : MonoBehaviour {

    public Rigidbody2D target;

    [Tooltip("How far to look ahead of the object's movement, in seconds")]
    public float leadSeconds = 0.8f;

    [Tooltip("How gradual / elastic the camera move should be")]
    [Range(0.000001f, 1f)]
    public float smoothness = 0.95f;

    void LateUpdate() {
        Vector3 leadPosition = target.transform.position + (Vector3)target.velocity * leadSeconds;
        leadPosition.z = transform.position.z;

        // Correct exponential ease for framerate.
        float blend = 1f - Mathf.Pow(smoothness, Time.deltaTime * 30f);
        transform.position += (leadPosition - transform.position) * blend;
    }
}

```

---
Tags: unity, 2d, camera, movement, lerp
---


# Question
Title: Should all stats only exist on MySQL database for my Flash browser RPG?
I'm creating a browser RPG in Flash which will have some multiplayer elements and in-app purchases so security is a high concern. Would it be better to have all game stats like health and such exist only in the MySQL database and retrieve them every time I need them? The game is turn based, but that would still require very frequent connections to the database. I could use local copies to cut down on the number of connections, but I imagine that would make it much easier for people to cheat.

# Answer
> 2 votes
"All the logic will be handled in Flash" there's your problem.

It doesn't matter where you store the stats if I can hack my client to ignore them and just always report back "Yeah, I toooottally won that duel. Rank me up!"

To prevent cheating, what you need to do is run your duel logic on the server. Then it doesn't matter if the player hacks their local client to pretend they have 9999999 strength & HP or whatnot. That server does its own calculation with its own authoritative stats, and records/reports the result of the duel with that trustworthy information.

That way a player hacking their local copies of the stats, or any other part of the client, cannot change the game experience for anyone else, nor impact the rankings.

If your duel logic is deterministic, then your client and server don't need to communicate in realtime about the blow-by-blow. The client can still run its own duel logic for presentation to the player. The server can, at minimum, record the player's inputs and the time when the duel was initiated, so it knows what state to use whenever it decides to compute the outcome later (when it has time / when a player asks to see the results).

---
Tags: flash, databases, browser-based-games, security, anti-cheat
---


# Question
Title: Most efficient way to convert Vector3 to Vector2
What is the most efficient and fastest way to convert a Vector3 to a Vector2?

*Casting:*

```
Vector2 vector2 = (Vector2)vector3;

```

*Initializing a new Vector2:*

```
Vector2 vector2 = new Vector2(vector3.x, vector3.y);

```

Or is there another method that I don't know?

# Answer
```
Vector3 v3 = Vector3.one;
Vector2 v2 = v3;

```

> Vector3s can be implicitly converted to Vector2 (z is discarded).

http://docs.unity3d.com/ScriptReference/Vector2-operator\_Vector3.html

If you have to make a lot of conversions you may have to change the way you use your vectors. Make two tests and time them to see which one works for you.

**UPDATE WITH TESTS:** Since you asked which one is the **fastest** I created a test running 10000000 conversions of each in Unity. It appears that the Initializing version is quickest in this case. **BUT, you should always use the one that suits your own context, so I advise you to run your own tests in your game.**

> TestConvertByOperation 10000000 instances: 0.2714049s
>
> TestConvertByCasting 10000000 instances: 0.286027s
>
> TestConvertByInitializing 10000000 instances: **0.1458781s**

```
using UnityEngine;

public class TestVector3Conversion : MonoBehaviour
{

    readonly int iterations = 10000000;
    Vector3 testVector = new Vector3(3f, 14f, 42f);

    void Start()
    {
        Debug.Log(string.Format("TestConvertByOperation {0} instances: {1}s", iterations, TestConvertByOperation()));
        Debug.Log(string.Format("TestConvertByCasting {0} instances: {1}s", iterations, TestConvertByCasting()));
        Debug.Log(string.Format("TestConvertByInitializing {0} instances: {1}s", iterations, TestConvertByInitializing()));
    }

    float TestConvertByOperation()
    {
        var timeStart = Time.realtimeSinceStartup;

        for (int i = 0; i < iterations; i++)
        {
            Vector2 v2 = testVector;
        }

        return Time.realtimeSinceStartup - timeStart;
    }

    float TestConvertByCasting()
    {
        var timeStart = Time.realtimeSinceStartup;

        for (int i = 0; i < iterations; i++)
        {
            Vector2 v2 = (Vector2)testVector;
        }

        return Time.realtimeSinceStartup - timeStart;
    }

    float TestConvertByInitializing()
    {
        var timeStart = Time.realtimeSinceStartup;

        for (int i = 0; i < iterations; i++)
        {
            Vector2 v2 = new Vector2(testVector.x, testVector.y);
        }

        return Time.realtimeSinceStartup - timeStart;
    }

}

```
> 17 votes

# Answer
Both Vector2 and Vector3 are a *struct* in the Unity engine, so the creation of one from the other simply involves the allocation of a storage on the stack (unless the destination is an attribute of a *class* object, which would allow skipping this first step) and the copying of the two component values. Both mechanisms you give ***should*** be compiled to exactly this IL code.

If you are encountering a performance problem with a conversion of this type then you probably have a ***boxing*** issue, with the *struct* being converted to and then from a *class* object. In that case you should investigate whether, when, and how, *boxing* could be avoided in performance-critical portions of your code.
> 6 votes

# Answer
From my test, the best way to do it is manual assign its value by yourself.

```
Vector2 vector2;
vector2.x = vector3.x;
vector2.y = vector3.y;

```

This is my result that I extend from Mattias.

> TestConvertByOperation 10000000 instances: 0.3220527s
>
> TestConvertByCasting 10000000 instances: 0.3226218s
>
> TestConvertByInitializing 10000000 instances: 0.1916729s
>
> TestConvertByManualAssign 10000000 instances: 0.09500527s

```
using UnityEngine;

namespace myTest
{
    public class test: MonoBehaviour
    {
        readonly int iterations = 10000000;
        Vector3 testVector = new Vector3(3f, 14f, 42f);

        void Start()
        {
            Debug.Log(string.Format("TestConvertByOperation {0} instances: {1}s", iterations, TestConvertByOperation()));
            Debug.Log(string.Format("TestConvertByCasting {0} instances: {1}s", iterations, TestConvertByCasting()));
            Debug.Log(string.Format("TestConvertByInitializing {0} instances: {1}s", iterations, TestConvertByInitializing()));
            Debug.Log(string.Format("TestConvertByManualAssign {0} instances: {1}s", iterations, TestConvertByManualAssign()));
        }

        float TestConvertByOperation()
        {
            var timeStart = Time.realtimeSinceStartup;
            Vector2 v2;
            for (int i = 0; i < iterations; i++)
            {
                v2 = testVector;
            }

            return Time.realtimeSinceStartup - timeStart;
        }

        float TestConvertByCasting()
        {
            var timeStart = Time.realtimeSinceStartup;
            Vector2 v2;
            for (int i = 0; i < iterations; i++)
            {
                v2 = (Vector2)testVector;
            }

            return Time.realtimeSinceStartup - timeStart;
        }

        float TestConvertByInitializing()
        {
            var timeStart = Time.realtimeSinceStartup;
            Vector2 v2;
            for (int i = 0; i < iterations; i++)
            {
                v2 = new Vector2(testVector.x, testVector.y);
            }

            return Time.realtimeSinceStartup - timeStart;
        }
        float TestConvertByManualAssign()
        {
            var timeStart = Time.realtimeSinceStartup;
            Vector2 v2;
            for (int i = 0; i < iterations; i++)
            {
                v2.x = testVector.x;
                v2.y = testVector.y;
            }

            return Time.realtimeSinceStartup - timeStart;
        }
    }
}

```

Please note, I test it with unity version 5.6.5
> 1 votes

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


# Question
Title: In Android, is it possible to get the first version of the app the user installed from the Play store?
I have an app currently in alpha, and I am thinking of moving to beta soon. Once I do this step, I want to re-initialize local files as the game changed quite a bit (local scores, etc.), and display a "Thank you for testing the alpha-version"-message and whatnot.

To do this, I would like to check whether the first time the user installed my app from the app-store was during the alpha, i.e. whether the version corresponds to one of the version of alpha. I found that it is possible to get the time the app was first installed, but haven't found a way to retrieve the version.

Short story long: is there a way to get the version of the app the user installed it for the first time?

P.S. If possible, I would like to achieve this in Unity

# Answer
I would suspect a way of doing this would be to push a small update on your alpha version to include a boolean variable (eg. alphaVersionPlayer == true) in the save data to declare that this save was made during an alpha version?

then just check true/false on that for additional rewards or thank you messages.

(disclaimer: I'm undoubtedly less experienced than you at programming and using unity, I'm just getting started)
> 1 votes

---
Tags: unity, android, google-play-services
---


title: Background made with procedural shapes

text:
# Question
Title: Background made with procedural shapes
I would like to know how to make a background like Super Hexagon managed to do: a hexagon in the middle and equally sized trapezoids.

There's a screenshot below & the here is the effect in motion.

How can this be done? Can I use a big sprite or procedural meshes?

# Answer
One way to achieve the look is to use a shader that draws the stripes in each trapezoid. I would do it by defining the distance between 2 stripes and the width of brighter stripe. Then I would tile the plane that the trapezoid is in. Something like this (pseudo-glsl) :

```
uniform float bandWidth; // The width between 2 bright stripes
uniform float stripeWidth; // The width of 1 bright stripe
uniform vec4 bandColor;
uniform vec4 stripeColor;
void main()
{
    vec4 color = bandColor;
    vec2 texCoord = gl_TexCoord[0];
    texCoord.x = mod(texCoord.x, bandWidth);
    if (texCoord.x < stripeWidth)
    {
        color = stripeColor;
    }
    gl_FragColor = color;
}

```

This draws the pattern left to right in 1 trapezoid. If you rotate and repeat the trapezoid, it should make the pattern all the way around the hexagon.

You could use different values for the `bandWidth` and `stripeWidth` in different trapezoids to get some of the different patterns in the linked video. It also looks like the trapezoids alternate the `bandColor` to be slightly darker or lighter.
> 0 votes

---
Tags: unity, procedural-generation, geometry, graphic-effects
---


# Question
Title: Instanced rendering with ARB_vertex_attrib_binding
I'm trying to separate the vertex format specification from the vertex data. I was able to do that for the mesh vertices successfully. For instanced rendering I wanted to further separate the instance data (i.e. model matrices). Here is what I'm trying out, but nothing is rendered.

Loading the data:

```
glGenBuffers(1, &vbo_instanced);
glBindBuffer(GL_ARRAY_BUFFER, vbo_instanced);
glBufferData(GL_ARRAY_BUFFER, n_instances * sizeof(glm::mat4), ModelArray, GL_STATIC_DRAW);

```

Vertex format:

```
glGenVertexArrays(1, &vao_instanced);

glBindVertexArray(vao_instanced);

glEnableVertexAttribArray(0);
glVertexAttribFormat(0, 3, GL_FLOAT, GL_FALSE, 0);
glVertexAttribBinding(0, 0);

glEnableVertexAttribArray(1);
glVertexAttribFormat(1, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3));
glVertexAttribBinding(1, 0);

glVertexBindingDivisor(1, 1);
for(int i = 0; i < 4; i++){ //Model Matrices
    glEnableVertexAttribArray(2 + i);
    glVertexAttribBinding(2 + i, 1);
    glVertexAttribFormat(2 + i, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4));
}

```

When rendering I do the following,

```
glBindVertexArray(vao_instanced);
glBindVertexBuffer(0, vbo_mesh, 0, sizeof(Vertex));
glBindVertexBuffer(1, vbo_instanced, 0, sizeof(glm::mat4));
glDrawArraysInstanced(GL_TRIANGLES, 0, n_vertices, n_instances);

```

but I'm pretty sure the stride argument in `glBindVertexBuffer` of `vbo_instanced` should be wrong because it is the stride per vertex.

Does anyone know what I'm doing wrong and how to fix it?

**EDIT 1:** It seems I made a mistake in the last argument of `glVertexAttribFormat`, it should instead be,

```
glVertexAttribFormat(2 + i, 4, GL_FLOAT, GL_FALSE, 4 * i * sizeof(float));

```

But now, although everything gets rendered, my normals are wrong. Even if I don't transform them, they have a single value per instance instead of a single value per face.

This is what the normals look like,

And this is what it should actually look like,

Note that the normals are fine as long as I instead use the `glVertexAttribPointer` method, i.e. bind the `vbo_instanced` directly to the vao.

For reference, here is how I declare the attributes in my shader,

```
#version 330 core

layout(location = 0) in vec3 in_Position;
layout(location = 1) in vec3 in_Normal;
layout(location = 2) in mat4 ModelMatrix;

```

**EDIT 2:** I wanted to add that I have checked that all offset values are correct. Additionally, I used apitrace and checked that all vertex buffer data are correctly uploaded. Valgrind also doesn't show any errors.

**Now for a weird finding**, if I don't use vertex attribute array with index 1 and instead bind vertex positions at 0, vertex normals at 2, and Model Matrices at 3, everything is rendering correctly. Could this be some driver bug? I tried on two linux systems, both having nvidia gpus, with exactly the same results.

**EDIT 3**: I put together a minimal working example which you can find here. It uses SDL and GLEW and is written in C++11. If I set `SKIP` to 1 (which means it skips attribute 1), I get what I expect, but if I set it to 0, the normals become messed up.

# Answer
> 2 votes
So, I am going to assume that all the instances share the same model data (vertex positions, vertex normals.)

In that case, the Divisor() call is incorrect: currently you tell OpenGL that each instance has its own normal: this is typically incorrect: the instances share positions and normals, and have a matrix each.

The slots for the attributes don't matter: it is fine to have position at 0, normal at 1, and matrix at 3,4,5,6.

What you need to do is tell OpenGL that for the matrices you will provide one matrix for every instance, this means a Divisor of value 1.

Personally I would use:

```
glVertexAttribDivisor( o+0, 1 );
glVertexAttribDivisor( o+1, 1 );
glVertexAttribDivisor( o+2, 1 );
glVertexAttribDivisor( o+3, 1 );

```

...where o is the location where you bind the matrices.

You seem to use glVertexBindingDivisor() instead, which I don't know, but assume is roughly the same as glVertexAttribDivisor(). But whatever it is, I am pretty sure you should be setting it on the matrix attributes and **not** on attributes 0 and 1.

**TL;DR**: you need to take out the `glVertexBindingDivisor(1, 1)` because normals are not per instance.

# Answer
> 0 votes
It's possible that your attribute offsets supplied to glVertexAttribFormat are failing to take data structure padding into account, leading to incorrectly-read vertex normals once your interleaved vertex buffer is bound. When using glVertexAttribPointer, did you calculate the offset pointer in the same way as described above, or were you taking it from the actual data structure layout (e.g. via offsetof)?

You can test for this by measuring the offsets of your actual interleaved vertex structure (via offsetof), and comparing those offsets to your calculated offsets.

---
Tags: opengl, instancing
---


# Question
Title: Should entities auto-register to systems based on their component signature?
I see all the upside in entities registering automatically for basic components. If an entity has a Renderable component, it should be registered to a list that's used by a Renderable System. If an entity has a Physics component, it'll be registered to a list of physics entities that gets used by a Physics System.

But beyond that, say we have an entity that is created with both a Physics and a Renderable component.

I fully understand how ECSs normally handle this case; If there was a system that worked on entities that have both a Physics and Renderable component, most Entity Component Systems (ECSs) would then automatically register that Entity to that system because the signature matches (in other frameworks, if the aspect matches, etc).

Moreover, if you add any components from an entity at runtime, most ECSs will then loop through all systems and try to register this entity if its new signature matches the systems' requirements (similarly unregistering the entity when removing components).

In practice, this seems to have many downsides (specifically talking about cases of where a signature of MORE than 1 component auto matches a system):

**1.** All entities with a particular set of components will automatically register to a system that the programmer *may not have expected/remembered*. Perhaps it makes sense that an entity with a physics and a visual component should be operated on by a physics-visual system, but perhaps not. Every time we add components to an entity, it may be difficult to foresee all the systems that it'll register to and may have unexpected consequences (similarly for removing components). If we have multiple people working on creating systems, the likelihood of unexpected consequences goes up. **\[Logic errors at runtime, maintainability problems\]**

**2.** In the case that we have entities like the ones above that fit a signature but we don't want to register it to a particular system, the best solution revolves adding a tag to the entity. Then we'd add an exclusion to the aspect of the system that would have operated on it - but this couples the behaviour of EntityCreators and System registrations **\[High Coupling\]**. Otherwise, we'd check for a dynamic tag on each entity on the update loop of the system and perform a noop on certain tags **\[Unneeded work, not-exactly 'pure' ECS\]**

**3.** We need to create a bitmask system or some other equivalent to manage signatures, and always loop through almost all systems every time an entity changes. Of course, all of this depends on implementation, but some form of loop-check is always required. In many cases, for complex aspects or when dealing with a large number of systems, this can become super inefficient and constrain how you build up your aspects/systems. **\[Lots of Work\]**

**4.** Sometimes ECS is implemented in a way that allows systems access to all of an entities components which may or may not be part of the systems requirements. **\[easy to break Encapsulation\]**. Now this may not be a big deal if everyone's on board with the intricacies of 'pure' ECS, but given the number of questions surrounding type casting entities and checking entity tags at runtime, its common enough that it can lead to taking shortcuts in systems and creating more **\[Runtime Errors\]**.

Really, problems **1**, **2**, and **4** produce problems inherent similar to those that appear with duck-typing and dynamic casting in general.

---

Instead of automatically registering entities to systems that match a signature (via whole entities or via nodes), wouldn't it be more type-safe and maintainable, yet as extensible, to directly register component-bag nodes in EntityCreators / EntityModifier classes?

If our entity which we create has a Physics component and a Renderable component, and matches in our minds what a PhysicsRenderable object does, then we would add a component called PhysicsRenderable which is constructed with our physics and renderable components injected. By explicitly saying that our entity matches what we believe a PhysicsRenderable should do, we solve **1**.

If it doesn't match what we believe a PhysicsRenderable is, we only add the Physics and Renderable components, solving **2**. Note: this does have the opposite effect of **1** that we have to remember to register it as a PhysicsRenderable if we want systems that work on PhysicsRenderable entities to update us, but this can be more easily debugged and fixed than the reverse situation.

Our entity would then have the components \[Physics, Renderable, PhysicsRenderable\]. Moreover our systems would then register to only one type (Physics, Renderable, PhysicsRenderable) and then the logic for registering the entity would become much simpler than using a bitmask or other method described in **3**. And because we explicitly built the entity with a PhysicsRenderable, this can act as the type for the node-list traversed in our system that operates on PhysicsRenderables (no passing around full entities anymore, solving **4**).

*Added detail: removing a component on an entity that's composed in another component, ie, removing Physics from an entity with a PhysicsRenderable, would require an extra listener to also unregister the PhysicsRenderable component, but it's not much different, if not simpler, than what is already done in ECSs.*

---

Now I realize that this goes against what some people may find to be a core principle of ECS (automatic signature registering), but it still uses a lot of the other core ideas (automatically registering entities to systems that process components that are expected on those entities).

Are there more downsides to this method that I'm not seeing? Do any ECSs use this sort of framework that requires explicit signatures on entities?

# Answer
TL;DR Entities SHOULD NOT auto-register to systems based on component signatures; prefer instead to explicitly declare component sets/nodes to register your entities to systems that operate on specific component signatures.

It’s been almost a year since I’ve asked the question, and I’ve played with both approaches to take a step away from theory and see how things pan out in practice. I’ve tried both:

1) The more-common auto registering entities based on type signatures (ie if we add a physics component and a renderer component to an entity, and we have a system that operates on (physics, renderer) signatures/nodes, the entity would register to this system automatically)

2) Explicitly registering entities based on components only- if we have a physics component and a renderer component, as well as a system that operates on entities with a (physics, renderer) signature, it WILL NOT register the entity UNLESS we ourselves also create a (physics,renderer) component and add it to our entity directly.

Now, YMMV, but I’ve come to find that all the issues I brought up in the original question do in fact exist with 1) and that by going down route 2), your code becomes more modular, less coupled and easier to reason about, not to mention solves all the issues addressed in the original question 1-4.

Is this more work/more painful? In reality, as you assemble most entities you would like to have fine grained control of how each entity behaves stored in one place. Going down route 2 would put that logic solely at entity creation/modification sections. Route 1 would put that logic at both entity creation/modification and at system registration- and becomes a real pain to diagnose.

I highly recommend route 2 as its explicit nature comes with a lot of benefits and little downside.
> 5 votes

# Answer
I think you may be overthinking this.

The point of ECS is to be simple:

An entity is nothing more than an aggregate of components. A system is only interested in a subset of those components. For example: A rendering system would only be interested in Transform and Graphics data components,and a physics system would be interested in Position, Motion and Body (maybe Transform too).

Registering an entity with a system on creation is also simple:

1. Check if the entity has the components the system is interested in. If not, ignore it.
2. Once viability is established, create a proxy for the entity, and store pointers to those components. This is the systems' working data set for that entity.

During work cycles, iterate over the proxies, and do work.

Now, in this example, the components are stored within the entity itself, however, I've heard tell that some engines do it in a way that the entity just stores id's of components. I believe Unity does this, but don't quote me on that.

In any event, I will attempt to address the points you raise, in order:

1. If multiple developers are working on different systems, it shouldn't matter. Each system is a self contained module, and the only coupling that should be happening is between the entity interface and system. (System needs to know how to query the entity for component information).
2. The simplest solution is to simply have a vector, or list, of booleans within the entity, the position of which can be translated to a component type. In this way, the existence and recovery of an entity can be performed in O(1) time.
3. Solution for 2 deals with this point nicely.
4. It's good that you consider things like encapsulation in general, but bear in mind that an ECS system is not "pure" OO design. Don't make the mistake of trying to adhere to OO too strictly. Use OO when it helps, and don't let it force you to code yourself into difficult situations. Typecasting of entities can be handled in some pretty neat ways, depending on the language used, I code in C++, and you can use template functions to handle all the typecasting, and component storage. I'll show you an example:

Entity has a member variable:

```
std::map<std::type_index, Icomponent*> m_Components;

```

then you have a generic insert function:

```
template<typename T>
void add(Icomponent* component)
{
    m_Components.insert(std::type_index(T), component);
}

```

To query (O(1)):

```
template<typename T>
bool hascomponent()
{
    auto it = m_Components.find(std::type_index(T));
    if (it != m_Components.end())
        return true;
    return false;
}

```

and to retrieve a component in constant time:

```
template<typename T> get()
T* get()
{
    auto it = m_Components.find(std::type_index(T));
    if (it != m_Components.end())
        return dynamic_pointer_cast<T>(it.second);
    return nullptr;
}

```

If the dynamic cast fails, a null pointer will be returned, so the calling code just has to check for this, which indicates a fail.

Yes, this gives all systems potential access to all components, but this is actually a good thing, as in the game play systems, you may wish to retrieve and modify any number of the entities components at run-time. This generic method is also highly maintainable, as you can continue adding component types for game mechanics without ever having to change the entity code, and all systems can work from the same interface.

This also simplifies the "signature" issue, as all any system needs to do is query the entity on creation for the presence of appropriate components that it cares about.

Beyond this, anything further could be construed as opinion, and as such, not helpful, so I'll stop there.
> 3 votes

---
Tags: entity-system, entity-component, entity
---


# Question
Title: How to change color of text in canvas in phaser.js?
I want to change the text color in my game that is build in phaser.js. But i have no idea how to do this, because i am not a coder.

Can somebody help me to change the color of my game text?

My Game is http://games.eyebraingym.com/slotreading/

I want to change the color on the canvas where the heading is 'Slot Reading'.

# Answer
> 1 votes
In your source code "game.js" (http://games.eyebraingym.com/slotreading/states/game.js) there are multiple lines that look like

```
text_line[l].addColor("#e6e6e6",0);

```

here, the "#e6e6e6" is the color. If you aren't familiar with CSS hexadecimal colors, there are sites like https://htmlcolorcodes.com/ where you can pick out a color.

You'll have to find a new color, for example, "#FF0000" for red, and replace all the old instances of "#e6e6e6" with "#FF0000".

---
Tags: phaser
---


title: Playing Tetris on non-linear surfaces

text:
# Question
Title: Playing Tetris on non-linear surfaces
I am considering designing a Tetris game where instead of a traditional flat game board, the game will transform the board into different kinds of surfaces. I think I lack the appropriate mathematical terms to describe the behavior I'm looking for, but here is one example of the design. The board starts as a flat plane, and starts bending outwards until it forms a cylinder (at which point the entire board is not visible in one view). My question is what strategy can I use to implement the interactive graphics on non-uniform surfaces? I've seen that meshes are used a lot, but how can I show this Tetris board on any random mesh?

Here is an example of the transformation I am trying to make. Note that it will not be limited to curvature on a single axis.

# Answer
> 2 votes
Just render your interactive 2D tetris game into a texture, instead of directly to the screen.

Then you can put that texture on any 3D object you want.

---
Tags: game-design, geometry, 3d-meshes, curves
---


# Question
Title: Trouble with assigning a model's own mesh to a mesh collider in Unity
I'm trying to use a mesh collider on the player's avatar, rather than the box collider.

I've added the mesh collider to the game object (which also has a rigid body) and selected the "convex" checkbox. However, the player still falls through all geometry, including Unity primitives, terrain, and other models.

In the mesh collider's property box, there's a value for "Mesh", which I have set to "None (Mesh)". I was led to believe this defaults to the model's own mesh, but now I'm not certain. If I change the value to something else from the "select mesh" list, like the cube, the collisions work. When I click over to Select Mesh --\> Scene, the list is empty. I'm assuming I need to add the model's mesh to the list, but I can't find any documentation about that.

# Answer
Did some trial and error.

**The mesh collider has to be added to the actual mesh object, not the game object that contains the mesh**.

For example, if you have player\_car, which contains a car\_mesh, a camera, and whatever else you need, then the mesh collider has to be added to car\_mesh and not player\_car.

If you created your object by dragging the model into the scene, then the game object and mesh object likely are one and the same. However, if you needed to create a more elaborate hierarchy (like I did), then you'll need to be more careful about where the collider goes.

Apparently a box collider can just be put any old place since the dimensions are user-defined.
> 1 votes

---
Tags: unity, collision-detection, meshcollider, collider
---


# Question
Title: How to randomly calculate the necessary velocity changes to reach a x,y,z target?
I am working on creating a mini vector graphics ping pong table, as described in this previous post: Trying to use 3D vectors for a 2D ping pong game

Currently, the stage I am at, I am trying to make it so that when the ball exceeds the X bounds of the table, it will reflect backwards and at a new target: a random x,y,z position on the opponent's side of the table.

Trying to use this post as a starting point: How can I launch a GameObject at a target if I am given everything except for its launch angle? I have attempted to adapt some of that example code in my program, but I am not quite getting the desired results.

\** updated code \**

```
update: function(paceFactor) {
  this.ball.pos3D.x += this.ball.vel.x * paceFactor;
  this.ball.pos3D.y += this.ball.vel.y * paceFactor;
  this.ball.pos3D.z += this.ball.vel.z * paceFactor;
  this.ball.vel.y += this.gravity * paceFactor;

  if (!this.stop && Math.abs(this.ball.pos3D.x) > 15) {
    this.stop = true; // for testing to prevent velocity from getting changed due to bad values returned from velocityForNextTarget()
    var modifier = this.ball.pos3D.x < 0 ? 1 : -1;
    var velocity = this.velocityForNextTarget(modifier);
    this.ball.vel.x += velocity.x;
    this.ball.vel.y += velocity.y;
    this.ball.vel.z += velocity.z;
  }

  if (this.ball.pos3D.y >= 0) {
    this.ball.vel.y *= -1;
    this.ball.pos3D.y -= this.ball.pos3D.y;
  }

  this.convert3Dto2D();
},

velocityForNextTarget: function(modifier) {
  var targetX = 5 * modifier;
  var targetY = 0;
  var targetZ = 0;

  var deltaX = this.ball.pos3D.x - targetX;
  var deltaY = this.ball.pos3D.y - targetY;
  var deltaZ = this.ball.pos3D.z - targetZ;

  var sqrMagnitude = (deltaX * deltaX) + (deltaY * deltaY) + (deltaZ * deltaZ);
  var speed = Math.sqrt((this.ball.pos3D.x * this.ball.pos3D.x) + (this.ball.pos3D.y * this.ball.pos3D.y) + (this.ball.pos3D.z * this.ball.pos3D.z));

  var gSquared = this.gravity * this.gravity;
  var b = speed * speed + (deltaY * this.gravity);
  var discriminant = (b * b) - (gSquared * sqrMagnitude);

  var discRoot = Math.sqrt(discriminant);

  var t = Math.sqrt((b - discRoot) * 2 / gSquared);

  return {
    x: deltaX / t * t / 2,
    y: deltaY / t - this.gravity * t / 2,
    z: deltaZ / t * t / 2,
  };
},

```

So what I am trying to do is make it so that when the ball reaches the location of a player, it will target the center of the opponent's side of the table, and the ball will move there, and right now this code is making the ball rapidly jump off the screen as soon as it hits the x bounds, and I am not sure what I am doing wrong with the math in velocityForNextTarget()...

I should also mention that gravity is just a constant that I am only adding to my Y velocity so far. I am not sure if that's "right" ?

# Answer
> 0 votes
More errors following the updates:

1. Your return velocity is not correctly calculated.

In the source:

`velocity = delta / T - gravity * T/2.0`

Your code:

```
return {
x: deltaX / t * t / 2,
y: deltaY / t - this.gravity * t / 2,
z: deltaZ / t * t / 2,
};
```

Correct translation:
(your gravity's x & z are zero, so those terms vanish: `a - 0 * t / 2 = a` not `a * t / 2`)

```
return {
x: deltaX / t,
y: deltaY / t - this.gravity * t / 2,
z: deltaZ / t,
};
```
2. You're adding the result velocity instead of setting it:

```
var velocity = this.velocityForNextTarget(modifier);
this.ball.vel.x += velocity.x;
this.ball.vel.y += velocity.y;
this.ball.vel.z += velocity.z;
```

You want to use the new velocity as-is, not mix it with something else:

```
var velocity = this.velocityForNextTarget(modifier);
this.ball.vel.x = velocity.x;
this.ball.vel.y = velocity.y;
this.ball.vel.z = velocity.z;
```
3. Your speed calculation is still not meaningful (it's the ball's distance from the origin, not its speed). Why not just pass the ball speed that you want as an input as it was in the source answer?

```
velocityForNextTarget: function(modifier, speed) {
```

Or treat it as a configuration parameter similar to your `paceFactor`

---
Tags: mathematics, projectile-physics, trajectory
---


# Question
Title: Tiled2Unity depth sorting issue with multiple layers
I have been struggling with an issue for a couple of days now trying to get depth sorting properly when using multiple layers in tiled.

My tiled map is set up as follows:

The sorting Layers I have in unity are:

Tiled to Unity sorting layers map as follows:

Background : Level 0

Background Noise : Level 0

Shadows : Level 0

Paths : Level 0

Tree Bases : Level 1

Tree Tops : Level 2

House Bases: Level 1

Objects ( crates and barrels ) : Level 1

House Roofs : Level 2

House Roof Items : Level 3

I have set the player sprite to be on sorting layer 1 along with the tree stumps, walls and floor objects.

When exporting to unity I'm ticking the check box for Use Depth Buffer as below:

Now the problem I am having is that when setting the layer to interact with on the Sprite Depth in map script I can only seem to make one layer work at a time.

eg, if I set it to interact with the tree bases layer, then the depth sorting works on there, but the character appears below the walls and the crates etc, but if I set the layer to interact with the objects layer then the character is always on top of the tree trunks rather than behind.

*Interacting with tree layer*

*Interact with object layer*

If I have one layer with the tree trunks, walls and objects (crates, barrels etc) and interact with this layer then it works as expected, but with only one layer in tiled I cant put the barrels in front of the house, or trees behind the house etc.

Is what I'm trying to do even possible with Tiled2Unity? or should I be doing something else?

Any pointers would be appreciated.

# Answer
> 1 votes
Ok I have finally managed to come up with a solution for this one, Ill post what I did here as I could not find the information anywhere else online so hopefully it will help someone else in future.

I created a CustomTiledImporter that will look at the sorting layer name on the tiled layer and set the z position of the layer based on the number of layers in the map. This will set all layers that target the same sorting layer to the same value so the map can be created with multiple layers, but they will all share the same sorting layer and z position in unity.

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

[Tiled2Unity.CustomTiledImporter]
public class WraithNathCustomTiledImporter : Tiled2Unity.ICustomTiledImporter
{

    public void HandleCustomProperties(UnityEngine.GameObject gameObject, IDictionary<string, string> props)
    {
    }

    public void CustomizePrefab(GameObject prefab)
    {
        Tiled2Unity.TiledMap map = prefab.GetComponent<Tiled2Unity.TiledMap>();

        Rect mapRect = map.GetMapRect();
        float depthPerLayer = -map.TileHeight / mapRect.height;

        var renderers = prefab.GetComponentsInChildren<Renderer>();

        foreach (Renderer renderer in renderers)
        {
            //Get the transform for the parent layer
            Transform parentTransform = renderer.transform.parent.transform;
            float z = (depthPerLayer * SortingLayer.GetLayerValueFromID(renderer.sortingLayerID));

            //Set the z position for the layer
            parentTransform.position = new Vector3(parentTransform.position.x, parentTransform.position.y, z); ;
        }
    }
}

```

I then copied the Tiled2Unity SpriteDepthInMap script and created a new version of it called SpriteDepthInSortingLayer. This is essentially exactly the same but with a property called InteractWithSortingLayer.

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

public class SpriteDepthInSortingLayer : MonoBehaviour {

    [Tooltip("The TiledMap instance our sprite is interacting with.")]
    public Tiled2Unity.TiledMap AttachedMap = null;

    [HideInInspector]
    [Tooltip("Which Sorting layer our sprite is interacting with. Will render above lower layers and below higher layers. Render order of Tiles on same layer will depend on location.")]
    public int InteractWithSortingLayer = 0;

    [Tooltip("For maps where tileset heights are different than map tile heights. Enter the tileset height here. Useful/crucial for isometric maps. Leave at default (0) if you don't care.")]
    public int TilesetHeight = 0;

    private void Start()
    {
        if (this.AttachedMap == null)
        {
            Debug.LogError(String.Format("Sprite must be attached to a TiledMap instance in order to calucluate the 'z-depth' on that map. Check the SpriteDepthInMap component in the Inspector."));
            return;
        }
    }

    private void Update()
    {
        UpdateSpriteDepth();
    }

    public void UpdateSpriteDepth()
    {
        // Put position into map space
        Vector3 spritePosition = this.gameObject.transform.position;
        spritePosition -= this.AttachedMap.gameObject.transform.position;

        // Some maps (like isometric) have a tileset height that is larger than the map tile height in order to get the isometric illusion. We need to know that difference in caluclating depth.
        if (TilesetHeight != 0)
        {
            int delta_y = this.AttachedMap.TileHeight - this.TilesetHeight;
            spritePosition.y += delta_y;
        }

        Rect mapRect = this.AttachedMap.GetMapRect();
        float depthPerLayer = -this.AttachedMap.TileHeight / mapRect.height;

        float depth_z = (spritePosition.y / this.AttachedMap.ExportScale / mapRect.height) + (depthPerLayer * this.InteractWithSortingLayer);

        // Assign our depth value in the z component.
        this.gameObject.transform.position = new Vector3(this.gameObject.transform.position.x, this.gameObject.transform.position.y, depth_z);
    }

}

```

You don't need to create the new script above as the old one will work, just remember you are now referencing a sorting layer rather than a map layer. I just wanted to make a new script so I could create a better editor for it as per below;

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

[CustomEditor(typeof(SpriteDepthInSortingLayer))]
public class SpriteDepthInSortingLayerEditor : UnityEditor.Editor
{

    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();

        // Get the renderer from the target object
        var script = (target as SpriteDepthInSortingLayer);

        // If there is no script we cant do
        if (script==null)
            return;

        //Get the current sort layer selection
        int sortLayerSelection = script.InteractWithSortingLayer;

        GUIContent[] sortingLayerContexts = GetSortingLayerContexts();
        int newSortingLayerIndex = EditorGUILayout.Popup(new GUIContent("Sorting Layer"), sortLayerSelection, sortingLayerContexts);

        //Change layer or show layers menu
        if (newSortingLayerIndex == sortingLayerContexts.Length - 1)
        {
            EditorApplication.ExecuteMenuItem("Edit/Project Settings/Tags and Layers");
        }
        else if (newSortingLayerIndex != sortLayerSelection)
        {
            Undo.RecordObject(script, "Edit Sorting Layer ID");
            script.InteractWithSortingLayer = newSortingLayerIndex;
            EditorUtility.SetDirty(script);
        }

        //Add button to set the depth now
        if (GUILayout.Button("Set Depth (Changes Transform Z Position)"))
        {
            if (script.AttachedMap == null)
            {
                Debug.LogError("Cannot set sprite depth without an Attached Map");
            }
            else
            {
                script.UpdateSpriteDepth();
            }
        }
    }

    public static string[] GetSortingLayerNames()
    {
        Type internalEditorUtilityType = typeof(UnityEditorInternal.InternalEditorUtility);
        PropertyInfo sortingLayersProperty = internalEditorUtilityType.GetProperty("sortingLayerNames", BindingFlags.Static | BindingFlags.NonPublic);
        return (string[])sortingLayersProperty.GetValue(null, new object[0]);
    }

    public static GUIContent[] GetSortingLayerContexts()
    {
        List<GUIContent> contexts = new List<GUIContent>();

        foreach (string layerName in GetSortingLayerNames())
        {
            contexts.Add(new GUIContent(layerName));
        }

        contexts.Add(GUIContent.none);
        contexts.Add(new GUIContent("Edit Layers..."));

        return contexts.ToArray();
    }
}

```

Now the character can go in front and behind of any sprite I put on sorting layer level 1 (or different if selected in the editor) regardless of which map level they are on.

Note: Its Important to still export the Tiled map into unity with the Use Depth buffer option ticked as this uses a depth shader on the layers.

Note 2: I also set the order in layer of my player sprite to 999 so it was on top of everything else, I added some more layers to the map later and it started appearing behind sprites with higher order in layers. Works perfectly now.

# Answer
> -1 votes
mine works nothing at all no matter what setting I use I am pretty sure the version of tiled I use has a broken script

but how do you run your own version of scripts ?

(sorry I cant comment becos of insufficient reputation please move this into the comment section instead of voting me down in such a childish manner)

---
Tags: unity, depth-buffer, tiled, layers, tiled2unity
---


# Question
Title: Unity GIT - managing `.meta` files / Working with multiple repositories in Unity
**(Original Question) →** ScriptableObject has empty inspector after cloning from git

After cloning repository from git the data from the `ScriptableObject` asset isn't there.

An example of the problem:

A working example:

I assume the problem is in `.gitignore` because there is `*.meta`, so the data of `ScriptableObject` is lost. Is there a way to configure `.gitignore` to leave the `*.meta` files in some subdirectory?

# Answer
> 0 votes
I have found the solution, but I felt like sharing it with people who could encounter the same problem. And also add additional information, solutions and troubleshooting that I have found/made.

---

Yes, you can ignore specific files and folders as well as make exceptions to work with 2+ repositories in same unity project without losing references on objects because of lost `.meta` files.

1. You can do `Project/.gitignore` and `Project/Assets/SpecificFolder/.gitignore` which will override the parent `Project/.gitignore`. *Look tip **(4)** to get the opposite result*
2. To exclude `.meta` files but save `ScriptableObject`s data - add `*.meta` and `!*.asset.meta` to your `.gitignore` which will exclude all `.meta` files except the ones that are `.asset.meta`.
3. If you have a sub-folder that is a `.git` repository and you want it to be added as sub-folder to remote`(not as a link or submodule)`. You can first add some specific file from that repository folder `git add Assets/my-git-repo-i-use/Controllers`. Now your `my-git-repo-i-use` isn't anymore considered as `submodule` by your main `.git`. So you can add everything in there **(4)** including `.meta` files even if you have `.gitignore` that ignores `*.meta`.
4. If you have a sub-folder that has `.gitignore` with, for example, `*.meta` because you have the code that you reuse for every project there, but you don't want to store specific data for specific project via pushing meta files - then you can ignore the sub-folder's `.gitignore` from/by(haven't found a solution yet - in the parents `.gitignore` I have tried `!Assets/my-git-repo-i-use/**` \- didn't work for me. I will update the asnwer, though maybe someone in the comments will have the solution to this). For now you can → 1. Just rename `.gitignore` in sub-folder to something like `.gitignoreC` to use root `.gitignore` rules. || 2. Create an empty folder, call it something like `Archived`, move sub-folder's `.gitignore` there.

**(4)** \- useful/related information:

---
Tags: unity, git
---


# Question
Title: Godot radial TextureProgress does not fully fill in after value of 61?
So i've been trying to create a radial TextureProgress node in Godot engine. I created two simple png textures of two different colored circles. Both textures are the same size and contain alpha background.

I apply one texture to the "under" and the other one as "progress". Everything seems to work fine and the progress gets filled in while the value rises until value is 61 (max 100 range). The progress then just disappears. However; once i hit 100 (exactly, not 99) the progress comes back and is fully filled in.

Why am i getting this gap of nothing between 61 and 99.9?

# Answer
> 2 votes
looks like this is a known issue: https://github.com/godotengine/godot/issues/17102

---
Tags: godot
---


title: Why is overlapping a possibility?

text:
# Question
Title: Why is overlapping a possibility?
I have three dynamic Rigidbody2D's, two of them paddles and the other a ball - this ball is also a trigger. If I used OnCollisionEnter before, I understand that the physics engine calculates the collision that should happen based on the position and velocity of the ball and paddle. This created the so called lag problem I had where seemingly two collision results happened. However, now I am using OnTriggerEnter and have a couple questions related to the problem I'm having.

When the ball is level with the paddle on the x-axis and you move up to hit it, the paddle is able to go through the ball but the collision happens from where the ball hit the paddle originally. Why is this? Also, if I print the x position of the ball, the position should be 7.175 but instead it's 7.19996, is there a way to get the actual point of collision? Is this linked to the first question?

Thanks!

# Answer
It sounds like you might be asking about continuous collision detection.

When this is enabled, the physics engine considers the full swept movement of the object over the duration of the physics time step. If there is a collision, we can pinpoint the precise moment of contact and respond accordingly.

The trouble is, this is a very expensive way to detect collisions. So the default behaviour for most game physics is a simpler method: move every object through its full displacement for the physics time step, then check if any are overlapped. If they are (and aren't triggers - triggers detect collisions but don't resolve them), try to nudge them so they're no longer overlapped.

If you need full continuous collision precision for a small number of objects in your scene, you can enable it in their `Rigidbody2D`'s collision detection mode property. Or you can "scan ahead" of the object with raycasts/circle casts to find pending collisions and handle the bouncing yourself.
> 1 votes

---
Tags: unity, collision-detection
---


# Question
Title: Unity 2d - Vector3.Lerp Not Working as Expected
I have asked this question on other community but still get no response after a month, so I decided to ask it here.

I am trying to put player position to the middle of camera when it is reaching near the edge of the camera. It works correctly with the following code:

transform.position = playerPosition;

where playerPosition is the current position of the player.

But, when I try it with Vector3.Lerp or Vector3.MoveTowards, it won't reach the player's x position.

```
Here is how it looks when using Lerp or MoveTowards

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

And here is when not using Lerp or MoveTowards

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

```

**The script:**

```
 public GameObject player;
 private Vector3 playerPosition;
 private Vector3 pos;
 public float offsetSmoothness;
 void Update () {
     // player's position relative to camera
     pos = Camera.main.WorldToViewportPoint(player.transform.position);
     playerPosition = new Vector3(player.transform.position.x,
                                    transform.position.y,
                                    transform.position.z);
     // if player reach the edge of the camera do the following
     if (pos.x < 0.1 || pos.x > 0.9)
     {
          transform.position = Vector3.Lerp (transform.position,
                                                playerPosition,
                                                offsetSmoothness * Time.deltaTime);
          // transform.position = playerPosition;
     }
 }

```

Why Vector3.Lerp is not positioning the player to the center of the camera when this condition is used to execute it: if (pos.x \< 0.1 || pos.x \> 0.9) ?

And how to make it working as expected, which is making the Vector.Lerp position the player to the center of camera when the player close to the edge of the camera?

# Answer
This is because you are only calling `Vector3.Lerp` or `MoveTowards` while `pos.x < 0.1 || pos.x > 0.9`. This means that once the camera moves a little bit `pos.x < 0.1 || pos.x > 0.9` won't be `true` anymore so the camera won't keep moving. To fix this you could create a co-routine that runs until the player is in the middle of the camera:

```
public GameObject player;
public float speed;
private bool isMovingCamera;

void Update () {
    // player's position relative to camera
    Vector3 pos = Camera.main.WorldToViewportPoint(player.transform.position);
    Vector3 playerPosition = new Vector3(player.transform.position.x,
                                    transform.position.y,
                                    transform.position.z);
    // if player reach the edge of the camera do the following
    if ((pos.x < 0.1 || pos.x > 0.9) && !isMovingCamera)
    {
        StartCoroutine(CenterCameraOnPlayer());
    }
}

IEnumerator CenterCameraOnPlayer() {
    isMovingCamera = true;

    do {
        Vector3 camPos = transform.position;
        Vector3 playerPos = player.transform.position;

        float step = speed * Time.deltaTime;
        // Move camera towards player at speed units per second.
        transform.position = Vector3.MoveTowards(camPos, playerPos, step);
        yield return null;
    } while(Vector3.Distance(camPos, playerPos) > 0.1f);

    isMovingCamera = false;
}

```

You might have to tweak some numbers (like `0.1f` in the while condition) to make it feel right. This is also untested, but the general idea should work.
> 2 votes

# Answer
You're misunderstanding Lerp, or Linear Interpolation. You're not supposed to set the third parameter or **t** to speed * time, you're supposed to give it a value between 0-1 for which it will interpolate.

So:

Lerp(A, B, 1) will return B,

Lerp(A, B, 0) will return A,

Lerp(A, B, 0.5) will return the middle point between A and B.

With that in mind, what you need is to have a function that makes **t** go from 0-1 within X seconds.
> 0 votes

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


# Question
Title: Pitch becomes yaw as camera gets near object
I have been having trouble with my camera, first encountering the roll tilt that is so many times asked... I fixed that issue by following the instructions at this link: Unwanted roll when rotating camera with pitch and yaw But now I find another issue, whenever I get close to my triangle, pitch becomes roll, and instead of moving up and down the triangle, the camera rotates around the plane of that triangle, see:

This is my code, I follow the same logic as the link above!

```
  float spitch = pitch * camera.sensitivity, syaw = yaw * camera.sensitivity;
  float npitch = Math_Quaternion_GetPitch(camera.rotation) + spitch;
  if(npitch > Math_Degrees_ToRadians(85) || npitch < Math_Degrees_ToRadians(-85)) return;
  Math_Quaternion yaw_quat;
  Math_Quaternion pitch_quat;
  Math_Vec3 up = {0, 1, 0};
  Math_Vec3 left = {1, 0, 0};
  Math_Quaternion_RotationAroundAxis(yaw_quat, up, syaw);
  Math_Quaternion_MultiplyVec3(left, camera.rotation, \* this is out! *\ left);
  Math_Quaternion_RotationAroundAxis(pitch_quat, left, spitch);
  Math_Quaternion_Multiply(pitch_quat, camera.rotation, camera.rotation);
  Math_Quaternion_Multiply(yaw_quat, camera.rotation, camera.rotation);
  Math_Quaternion_Normalize(camera.rotation);

```

Edit: Also, switching the quaternion multiplication order or just using a normal pitch yaw roll method fixes the problem, but then the roll problem comes back!

# Answer
I fixed it by omiting the multiplyVec3(left... line and just using left as (1, 0, 0); Edit: I just clumsily moved the code, made a mistake and it solved the issue, but I believe I'm locking the rotation around the x and y axis hence left and up instead of rotating my object relative to the quaternion's own up and left vectors... I'm not sure why it fixes the problem but it does!
> 0 votes

---
Tags: camera, rotation, quaternion
---


title: When should I use a physics engine?

text:
# Question
Title: When should I use a physics engine?
Since I found out Box2D, I'm using it for kind of any game-like application I try to write, from very small prototypes or small programs to test something, to actual projects.

Thanks to it it's so terribly easy to handle anything from collisions, to the actual physics.

Sometimes, though, I have some doubts about it: if I only have to handle circles or AABB, and don't need advanced physics tools (joints or stuff like that), I think that a physics engine could add a sort of big, unneeded overhead.

To reassume my question: would you use Box2D (or other physics engines) in a game where physics is really simple (like Super Mario, let's say)? And, if not, why?

# Answer
> 8 votes
If the memory, disk space, development effort, or processor time used for Box2D is too much for your purposes, then don't use it. Otherwise, there's no reason to avoid it if you find it useful.

# Answer
> 4 votes
Something as easy as Super Mario no, as it doesn't really have much physics. (Mario does not affect other object's physics with his jumping)

if you are using physics in the sense of multiple items (more than one) using physics to affect the outcome of other objects, then I would use an engine.

# Answer
> 2 votes
My answer is yes, absolutely use a physics engine like Box2D for simple stuff, because you shouldn't spend unneeded development time implementing some of the features that you quickly get from a physics engine. For instance, define a static body and drop a dynamic body on it, and apply force to your dynamic body for directional input, and you've got a platformer in a few minutes. I don't think that an engine adds enough overhead to make this not worth it.

# Answer
> 1 votes
If the "physics" in a game is simple there is no need to import a physics engine.

I use the term physics loosely since there is a difference between modeling physics and simulating phyiscs. A very important thing to differentiate.

For example, in Mario Bros. when you run and stop you will slide a bit. Think about how you might implement that.

You can model it by defining all of the necessary variables: eg. mass, gravity, co-efficient of friction, thrust, etc. and then calculating your new velocity, acceleration, etc.

but is it worth it? You can simulate the same effect by diminishing the players' speed while they aren't moving...

Something like:

```
if( pressing movement key ) {
 speed = 5;
} else {
 if(speed) speed--; // slide!
}

```

The difference is one is physics the other is not. There are pros and cons to both. But as a general rule for simple games it is much easier to fake it.

# Answer
> 0 votes
You must decide according to the situation

Pros using your custom engine

* Software under control (no change due to new release)
* Suited for your game (only the features that you need for your game, in the way you need them)
* Flexibility (any crazy dynamics you want can be encoded, any future feature would not rely on the engine)
* Learning Experience (maybe one day you need to improve an engine and you need how to build one)
* Less studying and programming for simple features (sometimes to do something with an engine may require to understand its structure deeply.. and may be not worthy)
* Higher performance for simple features (for simple specific features you may obtain higher performance than with a quite general purpose engine)
* Less memory (the object and the code may take much less space and memory when only the necessary features are used)

Pros of off-the-shelf physics engine:

* May adapt to new hardware and new OS without much effort
* Less studying and programming effort for complex features
* Higher performance for complex features

---
Tags: physics
---


# Question
Title: Which size do I need to use in Blender to import to Unity
I want to create a cube with different textures in Blender. But if I import the model to Unity 2017 the cube has not the same size as a cube with scale x,y and z = 1 from Unity's default components. Which size do I need for my cube in Blender so it has the same size as a default cube in Unity?

# Answer
The cube in Blender is 2 x 2 x 2m. You need to scale that down and then apply that scale.

Here is how I handle it when exporting to Unity.

Text on those images could have been better. Sorry, was in a rush.
> 1 votes

---
Tags: unity, blender
---


# Question
Title: Color change effect, with a sharp line separating the old & new colors
I want to achieve some sort of "transformation" effect in Unity while changing colors in a mesh.

For instance, when changing its color from red to blue, I have a line going around the mesh, where the part of the mesh on one side of the line is red and the other is blue. Over time, the line moves so the object is entirely blue.

From what I understand, I would need some sort of custom shader to do that? Or would I need some sort of animation? I really have no clue how to achieve this kind of effect so any tips are welcome.

# Answer
This is pretty straightforward. I'll add it to a standard shader and comment on it as we go...

```
Shader "Custom/TwoTone" {
    Properties {
        // Add a second color property
        _Color ("Color", Color) = (1,1,1,1)
        _Color2 ("Second Color", Color) = (1, 0, 0, 1)
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _Glossiness ("Smoothness", Range(0,1)) = 0.5
        _Metallic ("Metallic", Range(0,1)) = 0.0
        // And a divider to store our transition plane
        _Divider ("Divider", Vector) = (0, 1, 0, 1)
    }
    SubShader {
        Tags { "RenderType"="Opaque" }
        LOD 200

        CGPROGRAM
        #pragma surface surf Standard fullforwardshadows
        #pragma target 3.0

        sampler2D _MainTex;

        struct Input {
            float2 uv_MainTex;
            float3 worldPos;
        };

        half _Glossiness;
        half _Metallic;

        UNITY_INSTANCING_BUFFER_START(Props)
            // Color divider properties here for instancing, if desired.
            fixed4 _Color;
            fixed4 _Color2;
            float4 _Divider;
        UNITY_INSTANCING_BUFFER_END(Props)

        void surf (Input IN, inout SurfaceOutputStandard o) {
            // Compute the "height" of this point along the dividing axis.
            float level = dot(IN.worldPos, _Divider.xyz);
            // Select one of the two colours,
            // depending on the threshold in the fourth component.
            float thresh = sin(_Time.y) * 0.6f + 0.6f;
            fixed4 color = lerp(_Color, _Color2, step(level, _Divider.w));

            fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * color;
            o.Albedo = c.rgb;
            o.Metallic = _Metallic;
            o.Smoothness = _Glossiness;
            o.Alpha = c.a;
        }
        ENDCG
    }
    FallBack "Diffuse"
}

```

The trick here is the `_Divider` property. The first three components of this vector, `xyz` represent the direction the line moves (the transition plane's normal vector). So by changing those you can make the split run top-to-bottom, left-to-right, whatever direction you need.

The last component `w` represents the height along that axis where the colour transition should happen. By sliding this value up and down, you move the transition plane.

Right now I'm doing the comparison in world space, but you can also do this in object space so the transition plane moves with the object rather than staying at a fixed spot in the world.
> 2 votes

# Answer
DMGregory answer Is correct but I like to explain It visually.

first we need a way to draw Black and White mask.since you need horizontal line we just use `U` in UVcoord,then we use **step function** to making thick line.

It seems it's over but pay attention to below Image:

as you can see uvcoordinate Isn't good choice here because It Isn't integrated and It Depends on the model's uvcoordinate.so Instead of It we can use world space.

finally you can colorize your mask:
> 0 votes

---
Tags: unity, shaders
---


title: Distance based item interaction

text:
# Question
Title: Distance based item interaction
I'm having an odd issue in my implementation of distance based object interaction in Unity. Basically it's a simple "Press \[key\] to \[search/pickup/open/etc\]" function which requires the player to be within a certain distance of the object before interaction is allowed (via mouse over). In my scene I have 2 test objects which I have set up as similarly as possible, but they are acting differently and I cannot seem to work out why. * https://i.stack.imgur.com/Y8vKJ.jpg * https://i.stack.imgur.com/2DWGw.jpg These are the setups, and the script which is on both parent objects is as follows:

```
public class DisplayUI : MonoBehaviour
{
    public string itemName;
    bool isSelected;
    bool isNear;

    void OnTriggerEnter(Collider col)
    {
        isNear = true;
    }

    void OnTriggerExit(Collider col)
    {
        isNear = false;
    }

    void OnMouseOver()
    {
        if (isNear)
            isSelected = true;
        else
            isSelected = false;
    }

    void OnMouseExit()
    {
        isSelected = false;
    }

    void OnGUI()
    {
        if(isSelected == true)
        {
            GUI.Label(new Rect(Screen.width / 2, Screen.height / 2, 200, 20), "Press E to search " + itemName);
        }
    }
}

```

For some reason the sphere/cube game object is acting as desired where the mouseover detects the edge of each mesh perfectly, and relies on the distance (within the trigger collider) too, creating the gui label as coded. The trash can however seems to think the main trigger collider is the edge of the mesh so even when the mouse is way outside the physical mesh, the gui label is showing. Where am I going wrong with this?

# Answer
> 1 votes
Your object Trash1 has two non-triggering colliders attached to it: A Box Collider and a Mesh Collider. The OnMouseOver and OnMouseExit events will take both of them into account. So the OnMouseOver event gets fired when the mouse is over the BoxCollider which surrounds the model.

Your Sphere1 also has two colliders, but in this case they are a Sphere Collider and a Mesh Collider which have almost the same shape, so the problem is not noticeable. But it's still a slight performance hook (not noticeable in such a simple scene but it could become problematic when you have a lot of these).

I don't know why you attached two colliders to your objects, but it seems to me like one for each of them would suffice. In general you should prefer the "Geometric Object" colliders over Mesh Colliders because they are far more performance-friendly (especially when the mesh colliders are directly derived from high-polygon models and not based on simplified versions). But in the case of the trash can you have no choice because there is no optimized "Cylinder Collider" in Unity.

# Answer
> 0 votes
You could use a vector 3 to check if the object is near.

Example:

```
if (Vector3.Distance ( "Put your player here".transform.position, "Put object to check for here".position) < 5)
{
    "Block of code here"
}

```

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