# Question
Title: help with shooting projectile along a curve path
so i been trying to find a way to shoot projectiles along a curve path . and i found this tutorial on youtube which was really good.

i also uploaded the project in case you wanted to check it out. here

but there is problem with this script .if i move the target object somewhere above the starting point the curved path will be diapered and i get couple of errors.in fact when ever the path is about to become a straight line the errors will pop up . here is the screenshot of errors

and here is a gif file to show when the problem shows up

and finally here is the code responsible for calculating the curve path a lunching projectiles.

```
 public Transform startPoint;
 public Transform target;
 public int resolution = 30;
 public float curveHight = 25;
 public float gravity = -18;

 public Rigidbody bullet;
 public LineRenderer lineRenderer;
 void Start()
 {

 }

 void Update() {

     DrawPath();

     if (Input.GetKeyDown(KeyCode.Space))
     {
         Launch();
     }

 }

 void Launch()
 {

     Rigidbody clone = Instantiate(bullet, startPoint.position, Quaternion.identity);

     Physics.gravity = Vector3.up * gravity;

     clone.velocity = CalculateLaunchData().initialVelocity;
 }

 LaunchData CalculateLaunchData()
 {
     float displacementY = target.position.y - startPoint.position.y;
     Vector3 displacementXZ = new Vector3(target.position.x - startPoint.position.x, 0, target.position.z - startPoint.position.z);
     float time = Mathf.Sqrt(-2 * curveHight / gravity) + Mathf.Sqrt(2 * (displacementY - curveHight) / gravity);
     Vector3 velocityY = Vector3.up * Mathf.Sqrt(-2 * gravity * curveHight);
     Vector3 velocityXZ = displacementXZ / time;

     return new LaunchData(velocityXZ + velocityY * -Mathf.Sign(gravity), time);
 }

 void DrawPath()
 {
     LaunchData launchData = CalculateLaunchData();
     Vector3 previousDrawPoint = startPoint.position;

     for (int i = 1; i <= resolution; i++)
     {
         float simulationTime = i / (float)resolution * launchData.timeToTarget;
         Vector3 displacement = launchData.initialVelocity * simulationTime + Vector3.up * gravity * simulationTime * simulationTime / 2f;
         Vector3 drawPoint = startPoint.position + displacement;
         Debug.DrawLine(previousDrawPoint, drawPoint, Color.green);

         previousDrawPoint = drawPoint;

         lineRenderer.positionCount = resolution;

         lineRenderer.SetPosition(i - 1, drawPoint);
     }
 }

 struct LaunchData
 {
     public readonly Vector3 initialVelocity;
     public readonly float timeToTarget;

     public LaunchData(Vector3 initialVelocity, float timeToTarget)
     {
         this.initialVelocity = initialVelocity;
         this.timeToTarget = timeToTarget;
     } }}

```

so,any idea what might be causing the the problem?

# Answer
That happens, because the force/speed wasn't enough to reach the specified point. You need to somehow detect this case and do something.

There are a couple of `Debug.Assert` calls somewhere in your code (you didn't post that part). Those cause the errors. Remove them and replace it, so that the player gets alerted of them (like an in-game message saying "the ball can't reach that spot")
> 0 votes

---
Tags: physics, projectile-physics, curves, trajectory
---


# Question
Title: Sebastian Lague's A* star pathfinding "On condition"
As the title suggests I have been following the wonderful series of tutorials dealing with pathfinding made by Sebastian Lague.

My problem is that the code is meant to be working immediately after launching the scene. It works fine and all, but I simply cannot seem to make it run on a condition, be it a mouse click or any other sort of trigger. Did somebody manage to do it? If so can you please explain please?

In the specific, the problems start to arise going from the 4th to the 5th video, in which mutliple units are taken into account and therefore a new script handling the multiple requests to find paths is added.

The main method in the pathfinding script is this (let's call it **pathfinding**):

```
public void StartFindPath(Vector3 startPos, Vector3 targetPos) {
    StartCoroutine(FindPath(startPos, targetPos));
}

```

And the called coroutine is something like:

```
IEnumerator FindPath(Vector3 startPosition, Vector3 targetPosition) {
    Stopwatch sw = new Stopwatch();
    sw.Start();
    Vector3[] wayPoints = new Vector3[0];
    bool pathSuccess = false;

    Node1 startNode = grid.NodeFromWorldPoint(startPosition);
    Node1 targetNode = grid.NodeFromWorldPoint(targetPosition);

    if (startNode.walkable && targetNode.walkable) {
        //<Update open & closed lists>
        while (openSet.Count > 0) {
            Node1 currentNode = openSet.RemoveFirst();
            closedSet.Add(currentNode);

            if (currentNode == targetNode) {
                sw.Stop();
                pathSuccess = true;
                RetracePath(startNode, targetNode);
                break;
            }

            foreach (Node1 neighbor in grid.GetNeighbors(currentNode)) {
                // Retrieve f cost and find a path
            }
        }
    }
    yield return null;
    if (pathSuccess) {
        wayPoints = RetracePath(startNode, targetNode);
    }

    requestManager.FinishedProcessingPath(wayPoints,pathSuccess);
}

```

The request manager script (**requestManager**) instead is this:

```
public class PathRequestManager : MonoBehaviour {
    Queue<PathRequest> pathRequestQueue = new Queue<PathRequest>();
    PathRequest currentPathRequest;

    static PathRequestManager instance;
    PathFinding pathFinding;

    bool isProcessingPath;

    private void Awake() {
        instance = this;
        pathFinding = GetComponent<PathFinding>();
    }

    public static void RequestPath(Vector3 pathStart, Vector3 pathEnd, Action<Vector3[], bool> callback) {
        PathRequest newRequest = new PathRequest(pathStart, pathEnd, callback);
        instance.pathRequestQueue.Enqueue(newRequest);
        instance.TryProcessNext();
    }

    void TryProcessNext() {
        if (!isProcessingPath && pathRequestQueue.Count > 0) {
            currentPathRequest = pathRequestQueue.Dequeue();
            isProcessingPath = true;
            pathFinding.StartFindPath(currentPathRequest.pathStart, currentPathRequest.pathEnd);
        }
    }

    public void FinishedProcessingPath(Vector3[] path, bool success) {
        currentPathRequest.callback(path, success);
        isProcessingPath = false;
        TryProcessNext();
    }

    struct PathRequest {
        public Vector3 pathStart;
        public Vector3 pathEnd;
        public Action<Vector3[], bool> callback;

        public PathRequest(Vector3 _start, Vector3 _end, Action<Vector3[], bool> _callback) {
            pathStart = _start;
            pathEnd = _end;
            callback = _callback;
        }
    }
}

```

Finally, each unit object is provided with a "**unit**" script in which there is this corouting used to follow the path retrieved from the pathfinding script:

```
IEnumerator FollowPath() {
    Vector3 currentWayPoint = path[0];

    while (true) {
        if (transform.position == currentWayPoint) {
            targetIndex++;
            if (targetIndex >= path.Length) {
                yield break;
            }
            currentWayPoint = path[targetIndex];
        }

        transform.position = Vector2.MoveTowards(transform.position, currentWayPoint, speed * Time.deltaTime);
        yield return null;
    }
}

```

I tried at first to wrap the the `StartFindPath()` in **pathfinding** in an if statement made true upon pressing a button, but it did not work, so i tried to do the same only with the `StartCoroutine` line, but I ended up with the same result. I thought about doing it for the `FollowPath` method in the **unit** script, but it is called in this method:

```
public void OnPathFound(Vector3[] newPath, bool pathSuccessful) {
    if (pathSuccessful) {
        path = newPath;
        StopCoroutine(FollowPath());
        StartCoroutine(FollowPath());
    }
}

```

And I am not sure if it is the most suitable way. I tried to limit as much as possible the amount of code in the question, but if you need more I will add the rest of the scripts (FYI there are also a script in which the nodes features are defined, one to create the grid and one to define the heap data structure).

# Answer
For anybody using the scripts from the tutorials I mentioned, I have found the solution, it's just like as ratchet freak said, only it was another function.

For those familiar with the scripts, the `Unit` script, is the one attached to each unit in your scene, in its update method you can find the `RequestPath`, called from the `PathRequestManager` script. `RequestPath` will then start the pathfinding process and from the `Pathfinding` script the shortest path will be used in the `OnPathFound` method back in the `Unit` script to actually make the unit follow the path. Therefore in order to start the whole process upon a condition, you have to put such condition the first time the `RequestPath` method is called, like this:

```
private void Update()//Change from Start to Update so that it looks for path during game, not at the beginning
{
    /*Put the condition here if you want to make it look for a path only when you want it*/
    if (Input.GetKeyDown(KeyCode.Space)) {
        PathRequestManager.RequestPath(transform.position, target.position, OnPathFound);
    }
}

```

Hope it can be useful for somebody else, cheers!
> 0 votes

# Answer
It looks like your path processing is kicked off by `RequestPath`. The calls to that are what you need to wrap in the if.

So a patrolling unit could have

```
if(transform.position == target.position){
    target = newtTargetPosition();
    RequestPath(transform.position, target, OnPathFound);
}

```

---

answer before edit:
~~Where ever you call the `do_Astar` function you wrap it in an if that checks whether you need to run A\*.~~

~~if(need\_repath){ do\_Astar(); need\_repath = false; }~~
> 1 votes

---
Tags: unity, path-finding, input, scripting
---


# Question
Title: How do I wrap my web browser game as a standalone for Steam?
I've got a PHP/Java based game, which runs in the browser. However, I want to submit this game to Steam.

Now Steam doesn't allow web-based games unless they come in some kind of wrapper.

How can I package my web broswer game so that I could distribute it through Steam?

# Answer
Since you mention PHP as well as Java, which are both server-side languages, I assume you are running a web server that your game connects to for content, game state management, and so forth.

So given you have a web server, you'll want the player to download something to play the game - something that will then connect to your centralized, and hosted on the internet server.

There are a couple of approaches to creating a standalone application that essentially just runs your web page. I've listed a few resources below that might point you in the right direction...

https://github.com/jiahaog/nativefier \- Make any web page a desktop application. I have not tried this, but at first glance it might be promising.

http://www.qtweb.net/ \- QT based open source browser that could perhaps be modified to create a standalone app.

**Footnote**

To reiterate what a few have already stated, this is all dependent on you running an actual web server somewhere that all players connect to. If you don't want to require that, and the game is a single player game with no need to connect online, then you'll have to make a fully standalone game using HTML, CSS, JavaScript, and other file resources.

Here is a collection of different JavaScript game engines that might help if you have to do this: https://github.com/collections/javascript-game-engines
> 1 votes

---
Tags: java, php, steam
---


# Question
Title: rotation matrix problems - opengl and own types
In an effort to learn things deeper I'm writing my own mathematics for the first time instead of using libraries. As far as I can tell my matrix multiplication is correct, and translation and scaling work fine. I am however, struggling to debug the rotations. I've tried pretty much everything I can think to check and it still won't function as expected. If I set the angle to zero then as expected the Model matrix will not be effected. Changing to 1.0f will explode, the only value which results in expected behaviours seems to be zero... I haven't written a view matrix yet and I've been trying to debug this with the projection(orthographic) matrix on and off. Below is code with some notes.

Matrices are linear arrays of 16 values. i32 is an int, f32 is float, internal is static.

```
inline m4x4 operator*(m4x4 a, m4x4 b){
  //TODO redo this with simd
  m4x4 Result = {};

  for (i32 Row = 0; Row <= 3; ++Row)
  {
    for (i32 Col = 0; Col <= 3; ++Col)
    {
      for (i32 n = 0; n <= 3; ++n)
      {
        Result.c[(Row * 4) + Col] += a.c[(Row * 4) + n] * b.c[4 * n + Col];
      }
    }
  }

  return (Result); }

inline m4x4 GetRotationZ(f32 angle) {
  m4x4 Result;
  f32 c = Cos(angle);
  f32 s = Sin(angle);

  Result =  { c, s, 0, 0,
         -s, c, 0, 0,
         0, 0, 1, 0,
         0, 0, 0, 1 };

    return (Result); }

inline m4x4 RotateZ(m4x4 m, f32 angle) {
  m4x4 Rotation = GetRotationZ(angle);
  m4x4 Result = Rotation * m;

  return (Result); }

internal void DrawSprite(sprite Sprite, v2 Position, v2 Size, f32 RotationAngle, v3 Colour) {
  glUseProgram(Sprite.ShaderProgram);
  glBindVertexArray(Sprite.VAO);

#if 0
  Position = v2{400, 300};
  Size = v2{100.0f, 100.0f};
  RotationAngle = 0.0f;
#endif

#if 0
  m4x4 Projection = Orthographic(0.0f, 800.0f, 0.0f, 600.0f, -1.0f, 1.0f);
  u32 ProjectionUniformID = glGetUniformLocation(GlobalSprite.ShaderProgram, "Projection");
  glUniformMatrix4fv(ProjectionUniformID, 1, GL_TRUE, &Projection.c[0]);
#endif

  m4x4 Model = IdentityMatrix();
  Position.x = Position.x * 0.01f;
  Position.y = Position.y * 0.01f;
  Model = Translate(Model, V3(Position, 0.0f));

  Model = Translate(Model, v3{0.5f * Size.x, 0.5f * Size.y, 0.0f});
  //Model = RotateZ(Model, RotationAngle);
  Model = RotateZ(Model, 45.0f);
  Model = Translate(Model, v3{-0.5f * Size.x, -0.5f * Size.y, 0.0f});
  Size = v2{0.25, 0.25};
  Model = Scale(Model, V3(Size, 1.0f));

  u32 ModelUniformID = glGetUniformLocation(Sprite.ShaderProgram, "Model");
  glUniformMatrix4fv(ModelUniformID, 1, GL_TRUE, &Model.c[0]);
  glDrawArrays(GL_TRIANGLES, 0, 6); }

```

Next the shader source

```
char *VertexShaderSource = R"(
  #version 330 core
  layout (location = 0) in vec4 PositionAndTextureCoords;
  uniform mat4 Model;
  uniform mat4 Projection;

  out vec2 TexCoords;
  void main()
  {
     TexCoords = vec2(PositionAndTextureCoords.zw);
     //gl_Position = vec4(PositionAndTextureCoords.xy, 0.0f, 1.0f);
     //gl_Position = Model * vec4(PositionAndTextureCoords.xy, 0.0f, 1.0f);
     //gl_Position = Projection * Model * vec4(PositionAndTextureCoords.xy, 0.0f, 1.0f);
     gl_Position = Model * vec4(PositionAndTextureCoords.xy, 0.0f, 1.0f);
  }
)";

char *FragmentShaderSource = R"(
   #version 330 core
   in vec2 TexCoords;
   uniform sampler2D Texture;

   out vec4 FragColour;
   void main()
   {
     FragColour = texture(Texture, TexCoords);
   }
)";

```

I've stepped through the debugger, I've checked every line of code again and again, I've worked through a few matrices by hand and still I don't know whats going wrong. It should be something so very trivial yet I can't seem to find the bug...

Below are pictures demonstrating the difference between 0.0f and 1.0f, as of this state of the code it not only skews and rotates incorrectly, but its scaling is well off as well.

# Answer
> 1 votes
Your multiplication order is incorrect. If you look at the function calls, it will be in the

$$scale * rotation * translation * identity$$

This is incorrect for the way you set your multiplications up, it should be in the exact opposite order:

$$identity * translation * rotation * scale$$

This is because inside your `Translate`, `RotateZ` and `Scale` functions, you do the multiplication in the wrong order. Replace

```
m4x4 Result = Rotation * m;

```

with

```
m4x4 Result = m * Rotation;

```

With the respective values for every one of these functions.

---
Tags: opengl, c++, mathematics, shaders, matrix
---


# Question
Title: Should I use a FOV slider or fixed camera fov?
I'm making a single-player third person 3D adventure game, and I was wondering if I should fix the camera's FOV, or if I should create an in-game slider to change it. If I should create a slider, what should I limit the range to, and what should be the default?

# Answer
For third person? Allow change of the camera distance, assuming you're also allowing the player to move the camera around. It's hard to sometimes get your bearings on where you are in 3rd, and you need that zoom and move camera function to help establish spatial awareness.

Go play other game and see what they do. In other words, make it something game players are familiar with already.

A very common design pattern is that the mouse wheel zooms the camera in and out, and right click drag moves the camera. Left click is for player interactions.
> 0 votes

---
Tags: graphics, camera, third-person-view
---


title: Unity Events executed out of order

text:
# Question
Title: Unity Events executed out of order
According to this page Events in unity are suppose to execute in a specific order. Specifically, OnCollisionEnter is supposed to be called right after OnTriggerEnter; however, FixedUpdate and Update are both being called **at least** once in between calls to my OnTriggerEnter2D and OnCollisionEnter2D functions in my Enemy class, why is this the case?

Here is my code:

```
public class Enemy : Combatant
{
public int kill_points;
public float force;
public List<GameObject> path_verticies;
private int pathi;
private bool on_path;
private bool is_flying;
private bool ignore_collision;          //Used for ignoring collisions with walls, if the enemy has already touched an enemy_controller.

void Start ()
{   Init();
    pathi = 0;
    ignore_collision = false;
    is_flying = false;
    if (gameObject.tag.Contains("Fly")) is_flying = true;//Assuming contains is cheaper than a full string compare.
    on_path = null != path_verticies && 0 != path_verticies.Count;
}

private void FixedUpdate() { ignore_collision = false; }

void Update ()
{   if (!CheckBounds()) Destroy(gameObject);
    if (on_path)
    {   transform.LookAt(path_verticies[pathi].transform, Vector3.up);
        transform.Rotate(new Vector3(0,-90,0));
        phys.velocity = transform.right * speed;
    }
    else dx = Mathf.Sign(Cx) * speed;
}

public void Flip(){ Cx *= -1; }

#pragma warning disable CS0642 // Possible mistaken empty statement
private IEnumerator OnCollisionEnter2D(Collision2D collision)
{   if (on_path && path_verticies[pathi] == collision.gameObject)
    {   if (collision.gameObject == player)
        {   throw new System.NotImplementedException();
            yield return new WaitForSeconds(0.1f);//Used to prevent damage to the player if the player landed on top of the enemy.
            var atk = player.GetComponent<Combatant>().vigor.Attack(2);
            if (Health.Atk.DIES == atk) player.GetComponent<Life>().Die();
        } else pathi = (pathi+1) % path_verticies.Count;
        yield return new WaitForSeconds(0.0f);
    }
    else if (on_path)
    {   if (collision.gameObject == player)
        {   yield return new WaitForSeconds(0.1f);//Used to prevent damage to the player if the player landed on top of the enemy.
            var atk = player.GetComponent<Combatant>().vigor.Attack(2);
            if (Health.Atk.DIES == atk) player.GetComponent<Life>().Die();
        } else if (collision.collider == On(Truebounds)) /*nothing*/;
        else if (collision.gameObject.layer == 0 || collision.gameObject.layer == 8)// TODO
            /*take velocity in the direction opposite of the normal and add it to
             * the perpendicular component the enemy is moving in*/;
        yield return new WaitForSeconds(0.0f);
    }
    else
    {   if (collision.gameObject == player)
        {   yield return new WaitForSeconds(0.1f);//Used to prevent damage to the player if the player landed on top of the enemy.
            var atk = player.GetComponent<Combatant>().vigor.Attack(2);
            if (Health.Atk.DIES == atk) player.GetComponent<Life>().Die();
        } else if (ignore_collision) /*nothing*/;
        else if (collision.collider == On(Truebounds)) { if (is_flying) Flip(); }
        else if (collision.gameObject.layer == 0 || collision.gameObject.layer == 8) Flip();
        yield return new WaitForSeconds(0.0f);
    }
}

private IEnumerator OnTriggerEnter2D(Collider2D collider)
{   var component = collider.GetComponent<MonoBehaviour2>();
    if(!component) yield return null;
    else if (on_path && path_verticies[pathi] == collider.gameObject)
        pathi = (pathi+1) % path_verticies.Count;
    else if (on_path) /*nothing*/;
    else if (component.type == typeof(Enemy_Controller)) { Flip(); ignore_collision = true; }
    yield return null;
}
#pragma warning restore CS0642 // Possible mistaken empty statement

//public void OnDestroy(){  }
}

```

and these are my timestep settings:

# Answer
`FixedUpdate` and `Update` are not tied together. `FixedUpdate` is called based on how much time has passed (in your case, `0.02` seconds), while `Update` is called each frame. Generally (I think) `FixedUpdate` is used to do physics, collision, and movement, while `Update` handles input, game state, etc.

If you need something to happen `x` times every second, use `FixedUpdate`. If you just need something to happen every frame (but that doesn't rely on the time between frames) use `Update`. However, you can't rely on either of these to be called before or after the other.

Unity Docs, from the page you cited:

> FixedUpdate: FixedUpdate is often called more frequently than Update. It can be called multiple times per frame, if the frame rate is low and it may not be called between frames at all if the frame rate is high. All physics calculations and updates occur immediately after FixedUpdate. When applying movement calculations inside FixedUpdate, you do not need to multiply your values by Time.deltaTime. This is because FixedUpdate is called on a reliable timer, independent of the frame rate.
>
> Update: Update is called once per frame. It is the main workhorse function for frame updates.
> 1 votes

---
Tags: unity, events, timestep
---


# Question
Title: Rigidbody2D moves on x axis without adding force
I'm currently trying to learn some Physics2D in Unity. Now, I've created a Ball (sprite) and added a RigidBody2D and a CircleCollider2D on it.

The RigidBody2D has the following settings:

* Bodytype: Dynamic
* Simulated: true
* Use Auto Mass: false
* Mass: 1
* Linear Drag: 0
* Angular Drag: 0
* Gravity Scale: 25
* Collision Detection: Continous
* Sleeping Mode: Start Awake
* Interpolate: None

Now, when I start the scene, the ball drops as expected. However, it's also moving on the x-axis by ~83 pixels, which I don't want. The movement on the x-axis stops once it reached that ~83 pixels point.

If I freeze the x-position in the Rigidbody2D-Settings I get the intended behaviour (ball just dropping on y-axis), but I feel like that would be a hack instead of fixing the actual problem.

What could cause this? I expected the ball to just drop, if I have no drag, a certain mass and gravity enabled.

# Answer
Found the solution. The object was colliding with the background it seems.
> 0 votes

---
Tags: unity, physics, rigidbody
---


# Question
Title: How to check if a custom Control is focused?
So I am building custom UI for my MonoGame project. I've gotten pretty far already, having created Controls such as:

* Button
* Panel
* TextBox
* Form
* ComboBox
* CheckBox
* etc.

All of these controls obviously inherit from my abstract class `Control`.

This is how I check for Click on a `Control`:

```
if (Destination.Intersects(inputManager.MouseRect) && inputManager.IsMouseClicked(MouseButton.Left)) {
    Click?.Invoke(this, EventArgs.Empty);
    _focused = true;
}
else if (!Destination.Intersects(inputManager.MouseRect) && inputManager.IsMouseClicked(MouseButton.Left)) {
    _focused = false;
}

```

This method has gotten me pretty far already, but unfortunately it doesn't work when there are multiple `TextBox`es: each `TextBox` I click on will become focused, and any key I press will be typed in every focused `TextBox`.

Here is how I hacked around this:

* Since all Controls (including `TextBox`es) the user sees are placed in a certain `Panel`, they are in that panel's array of Controls.
* I added a `Panel _parent` to the `Control` class, thus every control would have a reference to the panel that owns it
* Then in the `Panel` class I added a `Control FocusedControl`, so that every `Panel` will have one field for its focused control

So now I'm checking like this:

```
if (_parent.FocusedControl == this)
    // This specific control is focused

```

Or like this:

```
if (_parent.FocusedControl != null)
    // There is a focused Control

if (_parent.FocusedControl == null)
    // No control is focused in this panel

```

**This works.**

But the problem is that I am doing these checks in the controls themselves, and not, for example, in the `Panel` class.

This means each control has a reference to the panel that owns it, and that panel has a list of all the controls. Also the panel's public methods and properties are available to the owned control.

This eliminates encapsulation and is effectively terrible design.

I consider this to be a huge mess and a dirty hack. Is there any other way to make sure that a `Panel` has only one focused `Control` at a time?

# Answer
> 0 votes
This is not a perfect method but you can try if it is better than yours.

First, you don't need to check both `Intersects` and `Click` event in one line of code. Just check `intersect` first, if the condition is true then check `Click`, if it is false, we don't need to check the second condition.

Create a list of GUI control:

```
public List<GUI_Control> controls = null;
public bool focus=false;
public GUI_Control parent=null;

```

Then check the mouse event:

```
public override bool MouseDownEventLeft(float mouse_x, float mouse_y) {
 if (!visible) return false;
 //if intersects
 if (inside(mouse_x, mouse_y)) {
  if (controls != null && controls.Count > 0) {
   // hand to my children controls
   for (int i = 0; i < controls.Count; i++) {
    bool rc = controls[i].MouseDownEventLeft(mouse_x, mouse_y);
    if (rc) return true;
   }
  }
  parent.clearFocus(true);//clear focus on parent GUI
  focus = true;
  return true;
 }
 return false;
}

```

Then each time you click, only one `textbox` (or something else) is being focused (its `focused boolean` is true).

---
Tags: c#, xna, monogame, gui
---


# Question
Title: What are the pros and cons of these voxel data file formats?
* .VXL
* .VOX
* .KVX
* .KV6
* .V3A
* .V3B

I am trying to decide whether it's worth going with any of the above, or some other, or if I should roll my own. The deciding factors in order of importance are:

1. Animation support (I am aware this is a difficult aspect when it comes to voxels), using voxel deltas or numerical transform descriptions.
2. Simplicity (or at least a concise format)
3. Compression

From what I can tell, the Tiberian Sun VXL format is the only one which is designed for animation, but Ken Silverman of Voxelstein3D fame claimed that VXL does not support animation (in a single file, were his words). So I wonder if maybe there are not two different .VXL formats, since it seems an obvious choice of file extension for voxel data... could be from a medical imaging context.

I do need someone with solid experience of voxel formats to come and comment on the practical pros and cons, in their experience. Consider this question in the same way you might compare JPG to PNG to GIF.

# Answer
> 9 votes
The continuation of my comment:

In essence when choosing an existing format these are the problems you must consider:

* Am I saving time by using this?
    + Do I get a editor?
    + Do I get a library to load this from the game media?
* Am I deriving any benefit from using this?
    + Are there clever optimizations in existing libraries?
    + Is the format compact, but not complicated?
* Does this solve my problem in its entirety?
    + Can I use this format with animations?
* Am I forced to use this (interoperability)?
    + Can I open and edit this file in industry-standard programs?

Sitting around figuring out which library to use will probably take longer than just rolling your own. You could probably throw together a basic format in less than a few days and improve it (or replace it) at some point in the future - start solving real problems in your game before wasting time with something game format (but remember, architect your system in such a way that it can be replaced at some point in the future).

# Answer
> -1 votes
am not sure i agree that this was a stupid question to ask... I guess the assumption is you would already have parsed the formats yourself and thus know the differences or some such. But honestly this doesn't seem too different a question to me from asking how different 3d file formats express data (for instance the difference between a .stl or .obj file which is kinda huge depending what you wanna do with them D: and they all have pros and cons etc.

The only one on your list that i have relative experience working with so far is .vox and i know that it can be easily parsed and has plenty of information online for how to do so (have done quite a lot so far with pyvox for instance and it's easily portable to 3d packages including blender via the bpy module. (https://pypi.org/project/Pyvox/) it also includes tools for parsing .vox data.

I've also found it pretty flexible for point cloud animation data. I really like the palette system that it used as integrated with magica voxel and is a very useful way of managing and interpreting color information across platforms (it creates a slot for each palette rather than an assigned colour or material and so is pretty easy to write multiple interpretations depending on what you want it to do..also working with voxel animation this is a huge plus because honestly colour data can sometimes be the trickiest part (again depending on what you are doing and why etc).

i'd be interested also to hear what experiences people have had parsing information from other voxel formats? Also interested in hearing if any of these have some kind of draw or frame output (which would be usfull for animation processing as well).

---
Tags: animation, data-structure, file-format, voxels, compression
---


# Question
Title: How to change AddForce code to MovePosition or SetVelocity?
```
Vector2 vec = new Vector2(horizontal, vertical);
    vec = Vector2.ClampMagnitude(vec, 1f);

    Vector3 camF = cam.transform.forward;
    Vector3 camR = cam.transform.right;

    camF.y = 0;
    camR.y = 0;
    camF = camF.normalized;
    camR = camR.normalized;

    targetPosition = (camF * vec.y + camR * vec.x) * MoveSpeed;

    Vector2 targetVelocity = (targetPosition - transform.position)/Time.deltaTime;

    rb.AddForce(targetPosition - rb.velocity, ForceMode.VelocityChange);

```

My problem is my character doesn't affects by the gravity when i changed my code from `transform.position` to `rb.AddForce`. I searched online and even asked here how to calculate gravity and add it to my character, nobody knew, so i think if i can change this code to `rb.MovePosition` or `rb.SetVelocity` maybe it does affects by the gravity?

# Answer
> 1 votes
You're removing the gravity when you subtract `rb.velocity` from `targetPosition`

Try doing it like this instead:

```
Vector2 vec = new Vector2(horizontal, vertical);
vec = Vector2.ClampMagnitude(vec, 1f);

Vector3 camF = cam.transform.forward;
Vector3 camR = cam.transform.right;

camF.y = 0;
camR.y = 0;

camF = camF.normalized;
camR = camR.normalized;

targetVelocity = (camF * vec.y + camR * vec.x) * MoveSpeed;

Vector3 horizontalVelocity = rb.velocity;
// Zero out the y so that we don't compute a vertical velocity change.
horizontalVelocity.y = 0;

rb.AddForce(targetVelocity - horizontalVelocity, ForceMode.VelocityChange);

```

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


# Question
Title: Does collision detection data structures require a manifold mesh
Is it possible to apply spatial split techniques (oct-trees bsp-trees, etc) when meshes are not necessary manifolds?

The mesh in question represents the "map". This means that it is static so spatial splits should be a good approach. Not requiring a manifold saves a lot of time when modeling, and also it may reduce the number of extra faces that has to be drawn, as forcing the mesh to be a manifold may require additional cuts.

# Answer
> 1 votes
No game development police will come to arrest you if you try to store a non-manifold mesh in a spatial partition data structure for collision detection purposes. No law of physics will cause your computer to implode if you do this.

So no, it's not a requirement to have a manifold mesh, nor is it impossible to use non-manifold geometry in a spatial partition.

It's just trade-offs. With non-manifold meshes...

* You don't have a consistent definition of "inside" versus "outside" - so you can detect when another primitive is intersecting the surface, but if it happens to tunnel past the surface you can't easily detect that it's on "the wrong side" or know which way to push it out.
* You're not guaranteed the mesh is "water-tight", so very small collision primitives like raycasts might be able to slip through minute cracks in your mesh. Say you have one edge that has a neighbour split into two edges - logically there's a triangular hole in between them, even if it's meant to have zero area. Due to rounding/quantization in your mesh storage or intersection routines, there could be a tiny crack here that can cause a check to miss the mesh. So you need to be more careful with your math and include epsilons to help patch these fissures.

If those trade-offs are acceptable for your case / less painful than using manifold geometry, then go for it.

---
Tags: collision-detection, 3d-meshes, spatial-partitioning
---


# Question
Title: How to avoid minecraft-like map to blend
I am making a minecraft-like world, with some differences. For instance, the camera will be facing always in the same direction.

I am having trouble with the visuals. Here is an example:

As you can see, when looking at a "step", as long as you can see the wall between the 2 levels, kinda like looking from it upwards, it is easy to identify. But when the wall disappear, kinda like when you are looking at it downwards, the step seems to blend, to a point where it is hard to tell where the step begins.

I thought of adding outlines, but due to the heavy palette of tiles that I am going to have, it would require to re-think a lot the logic to choose the correct tile, and I was hoping to find an easier solution.

What could I do to solve this problem?

# Answer
There are two easy ways to solve this.

What minecraft does is use a pseudo ambient occlusion. This essentially creates a shadow around ledges, making them visible from any angle. It can even highlight the edges with the plainest blocks in the game:

If you want to implement this, there's a nice tutorial about it here. You can basically make any corner darker, if two blocks touch there. It's best to send this information as vertex colors to the shaders.

The other solution is to use outlines. This needs a bit more work, including doing edge-detection on the depth buffer and can drastically change the feel of your game. It would look something like this:

To do this, you need to somehow get the depth-buffer of the image. This is a black-and white representation of the distance of the pixel from the camera. This is what it would look like:

Now do an edge-detection on it (basically the difference of the color of a pixel and its neighbours, more here):

The amount of white in this image represents the intensity of the egde, so in this case, the more distance there is between the two positions. You can do a smoothstep on this to only draw edges above a minimum distance and invert to colors at the same time:

Now just reapply this image to the main color buffer and you'll have outlines around ledges.

Example result:

(It doesn't work well with minecraft due to the large amount of non-block foliage everywhere)
> 12 votes

---
Tags: graphics, graphic-effects
---


# Question
Title: How does a minecraft biome finder generates map
How does chunkbase biome finder generates map base on seed? I was curious if chunkbase knows the secret formula for generating the map? Or it uses other math formulas such as scaling, mapping etc...

Here's my main point: If I generate a map in minecraft and grab that minecraft seed. If I place that minecraft seed in biome finder, It also generates the same world that minecraft generated. If I place the coords in that biome finder, it also shows me the correct position in minecraft world.

How can you possibly generate a world similarly to minecraft without knowing the secret formula? Is this possible?

Here is the site https://chunkbase.com/apps/biome-finder

This is my first question and I'm not a real game dev(I just want you to know). If you want me to remove this question, just tell me.

# Answer
> 1 votes
It can do a variety of things to achieve this.

You can either interface the official server using a custom-made wrapper, that dumbs it down to a world generator, throwing any physics and game updates out of the window, then send the data to the client running on the website using websockets or AJAX. This is legal, as far as I'm aware, as the server is treated like a black box. The original Bukkit server did this and just stepped in at points to do any plugin-related modifications.

Or you can implement everything in JavaScript, including the random generator Java uses, the exact noise algorithm the game relies on and the details of the world generator. This however is not only slow, but error prone, as any small detail can majorly change the outcome of the generator. It also requires either heavy reverse-engineering or disassembling the game, which isn't as clear on the legality site based on the EULA:

> **Although we license you permission to install on your device and play our Game, we are still the owners of it. We are also the owners of our brands and any content contained in the Game**. Therefore, when you pay for our Game, you are buying a license to play / use our Game in accordance with this EULA - **you are not buying the Game itself**. The only permissions you have in connection with the Game and your installation of it are the permissions set out in this EULA.
>
> Any Mods you create for the Game from scratch belong to you (including pre-run Mods and in-memory Mods) and you can do whatever you want with them, as long as you don't sell them for money / try to make money from them and so long as you don't distribute Modded Versions of the Game. Remember that a Mod means something that is your original work and that does not contain a substantial part of our code or content. You only own what you created; **you do not own our code or content**.

---
Tags: procedural-generation, coordinates
---


# Question
Title: How do you script movement of two or more characters at the same time?
Its not quite clear how to move 2 characters at the same time from and to fixed positions. Within the tutorials for RPG Maker MV users are shown how to script the movement of single characters at a time to fixed positions. In the tutorials, users are also shown how to have multiple characters moving at the same time in random directions or possibly in repeating loops. However, its not quite clear how to move 2 or more characters at the same time in a one-time scripted manner.

For example, at the start of a conversation, its normal to move the characters to specific screen positions so that they can begin uttering dialogue much like actors on a stage. However, the only way I know how to do this is moving one character at a time, which you often see in many classic jrpgs. In the modern age, however we have a lot more tools and resources at our disposal, so it doesn't seem necessary to move them one at a time. Why not just have them move at the same time so the player doesn't have to watch a second or two of rapid sequential movement?

Is there a way to script the movement of 2 characters at the same time to fixed positions so that they can begin speaking cutscene dialog?

**How does one script simultaneous movement of characters that is not random or looped?**

I don't have enough rep yet to create an rpg maker mv tag.

# Answer
Its fairly easy to create simultaneous movement in RPG Maker MV, the key is to uncheck the 'Wait for Completion' checkbox on all but the last movement route in the set of movement routes within the triggering event. If you don't select the 'Wait for Completion' then the rest of your event may go haywire as the rest of the event script will fire once movement is started.

The steps are fairly easy.

1. Create each character event if they aren't already created If you don't already have ones
2. Create a separate event that will trigger the simultaneous movement. If it wasn't already created.
3. In the separate actual event create the movement routes but uncheck the 'Wait For Completion' checkbox in the '**Options**' panel of the '*Set Movement Route*' dialog box, except for the last route. The last route **should** have the 'Wait For completion' checkbox selected.
4. Click 'OK' to close the event editor.

Test and the movement should work as expected at this point. Sometimes you have to do this more than once in an event if you have multiple sets movement routes that you want to happen at the same time. For each set you need to have one 'Wait for Completion' route at the end of the subset of routes.
> 2 votes

---
Tags: scene, rpg-maker-mv
---


# Question
Title: I see free asset being sold on another site. How and where do I complain?
We all know that there are many repositories and marketplaces for 3D models on the internet. The specific problem I have now is with this 3D asset for sale on a site. It was made for sale a short while ago. The same model is available at another place for free under a CC license, and was first uploaded years ago. Furthermore, the same 3D model was made available for download for free under a personal use license at another place even earlier, about 6 years ago.

My problem is I don't know who to complain to or which person I should complain about. Normally my gut reaction when I see this sort of stuff is that the paid product has made its way around and been made available for free by someone. However it could easily be the other way around. The seller most who most recently uploaded the model looks suspicious. There is hardly any information that would reflect their knowledge of the actual model. Anyone who's done modelling of real objects before will know the extensive references one must use to make an accurate model

At least one person is in breach of copyright, and most likely the code of conduct on their respective site.

If for example the original author is Person 1, then Person 2 selling the model is breaching this license, because it's a non-commercial license. If on the other hand the original author is Person 3, then Person 2 may sell the model, but they need to fulfill the attribution requirement, which they haven't. If however the original author is Person 2 (the person selling the model), then the other two are in breach of the license.

Most likely the model (which appeared in 2013) is proprietary and copyrighted content and all three are in fact in violation of copyright (well, that's what I think is most likely). The asset may be ripped from a AAA commercial game, as was the case with a model I found recently which came from an ARMA military game.

I don't who to complain to or who to complain about. I thought someone could point me in the direction of the best way to go about this, as I think this community has some experience in handling 3D assets and licenses, and many of you who are in the industry or are experienced with this sort of misconduct might know the best way to approach this.

# Answer
You can't know who is the original author. Maybe they **all** are the same legal entity under different pseudonyms? Who knows?

If you really want to do something (which is not your obligation), then contact all the people who claim to be the authors and tell them their copyright might be violated by the others. The real copyright holder is the only one who can take legal actions.

Also, as a game developer, avoid asset stores where the uploaders are anonymous. Buy directly from the artists and have them sign a contract clause which makes them liable if someone sues you for using an asset they stole.
> 3 votes

---
Tags: assets, copyright, licensing
---


# Question
Title: Unity 2d Animation from spritesheet: How can I move the character according to the animation?
I am trying to implement an attack animation that should end up in moving the player by some distance. The animation would be something like this:

As you can see the position of the player should be different by the end of the animation, but I am not sure how to make it so. I tried to use root motion, however even if in the animator component i set "Apply root motion" to true, when I click on the animation itself, there is no option to use root motion, perhaps is it due to the fact that the animation is obtained from a spritesheet and not from a rigging software like Spine or DragonBones? Anyway, is there another way to update, either by scripting or throught the animation window, the character's position after the animation?

# Answer
> 1 votes
Yes, the "apply root motion" flag requires a rigged 3d character model to work.

But the nice thing about the Unity animation system is that you can use it to animate almost any numeric public property of almost any component, including the `Transform`.

When you are editing the timeline of your Animation with the player game object selected, you can add the `Transform` as a property and create a curve for the `Position.x`.

However, I would really recommend you to edit the spritesheet and keep the character centered in the center of the animation cell during every frame. This gives you far more flexibility because you can easily tweak the range of that attack motion in the Unity editor. If your game is an action-oriented game, then the exact distance the character travels when performing that attack is relevant for gameplay. That means it's something you might want to experiment with and iterate on quickly. And then there is also the issue with making sure the collider is where the player would expect it to be during every animation frame. If the character moves around in a sprite which is far larger than itself, then that's quite tedious to get right.

---
Tags: unity, c#, 2d, animation, motion-control
---


title: Minimal, unrealistic physics engine

text:
# Question
Title: Minimal, unrealistic physics engine
I'd like to prototype a game with custom, very simple physics. Something similar to older games, anything from Super Mario to Quake 3 Arena.

I'd prefer to avoid realistic physics engine because they usually reduce the control you have over your objects and require you to manipulate such objects in a specific way.

I'd want to be able to update the objects' physical state using my own rules. E.g. I'd like to implement and apply gravity, movements and all the rest using my own logic.

I believe that what I need is a small *engine* that handles an efficient representation of objects in a space and offers an interface to query it.
I'd also need it to offer decent utilities for very common problems such as collision detection, ray casting, moving overlapping objects away from each other etc.

Do similar *engines* even have a name?
They're not considered physics engine, are they?

I was planning to work on a 3D prototype, and use JavaScript and Three.js as a language and scene-graph/renderer. However I might be open to 2D environments and/or different technologies.
I'd love it if I could find a set of libraries that are meant to work with each other, so that I don't need to write a lot of glue code.

# Answer
You have just described my understanding of a *game engine*. A program that lets you build a game, and offers lots and lots of solutions to common problems in game development. In every game engine I know, there are options to disable, or just to ignore, the built-in physics system. I recommend Unity, but you should research pros and cons of different systems.

tldr; You are looking for a "game engine", not a "physics engine".
> 1 votes

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


# Question
Title: Why is the equation \$S = ut + \frac 1 2 a t^2\$ not used directly to calculate final position of an object?
Most articles I've read on physics integration in games say to do it like this:

1. first we calculate velocity after a certain elapsed time `dt` like this:
`velocity.x += acceleration.x * dt`
2. then we calculate position as: `x += velocity.x * dt`

But this will definitely give an inaccurate result.

Therefore, what is the reason to not use the equation of motion \\$S = ut + \frac 1 2 a t^2\\$ to calculate an accurate displacement and add it to the position?

# Answer
First, the expression $$ S = u\\,dt + \frac{1}{2}\\,a\\,dt^2 $$ is not "accurate" in absolute sense. It is just a second order (in dt) approximation to the real solution. And actually, the other one you provided (which is called symplectic euler) is also a second order approximation, as you can see if you plug the first equation

```
velocity.x = old_velocity.x + acceleration.x * dt

```

into the second equation

```
 x = old_x + velocity.x * dt
   = old_x + (old_velocity.x + acceleration.x * dt) * dt
   = old_x + old_velocity.x * dt + acceleration.x * dt * dt

```

the difference is that here you are using the *new velocity* for updating x. The consequence is a nice physical property that is the conservation of (a quantity close to) the energy. Conservation of energy means that you do not get an unstable simulation, which is important.

In fact, the order of approximation is not the most important aspect to consider when choosing an integration scheme. Lower order symplectic algorithms are sometimes preferred to other higher order algorithms (like Runge Kutta) even in some scientific simulations.

If you are looking just for the most accurate solution, then you should look into the Implicit Euler method solved iteratively with the Newton method which can be made accurate until a desired threshold.
> 3 votes

# Answer
We can do this:

```
position = initial_position + velocity * t + 0.5 * acceleration * t * t;

```

First remember that there could be collisions. We need to detect and solve collisions. Perhaps we do, we solve the collision by picking a new `initial_position` and `velocity` for the object.

Second remember that not every object that has physical interaction follows the laws of motion. *Yeah, I know, you use the formula for those which do.* The issue is that there are motions that the physics engine cannot predict.

Let us take the simple example of the game asteroids. The user steers and accelerate the avatar ship. We are not only talking about an acceleration that change over time, we are talking about an acceleration that change over time in an unpredictable manner (it depends on user input). In this case you will need to compute the position of the avatar ship each frame.

That means that you will have two different pipelines for physics. One for things that the user controls or triggers, and one for thing that it does not.

For another example, platformers have some interesting challenges. Let us say, it is a bad platformer, where you cannot control the avatar midair. So, in the air, it behave as an object beyond user control, but on land it can walk, the user has control over its speed. Now you got an object that switches gears.

How about enemy agents? Perhaps we can push them as per physics, but they will move according to some form of AI. Therefore the physics engine cannot predict their motion, which means we will need the physics we created for player controlled things.

Would it not be better to have a single physics pipeline instead of two? Well, the one that is used for the player controlled things is more versatile. That one wins. So, we compute at increments, frame by frame.

---

Perhaps you want something like this:

```
position = position + velocity * dt + 0.5 * old_acceleration * dt * dt;
acceleration = compute_acceleration();
velocity = velocity + 0.5 * (old_acceleration + acceleration) * dt;
old_acceleration = acceleration;

```

That is a variant of Second Order Verlet Integration known as Velocity Verlet (it is similar to leapfrog integration). And, yes, some games use it. It is better than Euler integration. Many people recommended, usually it is all you need.

With that said, Velocity Verlet will have stability problems (it will drift when dt is not stable). A variant known as Time Adjusted Velocity Verlet is used to compensate for that problem. However, depending on the simulation, objects simulated with can seem to lose energy (which is hidden if you are doing drag or friction too).

**Notes**:

* With Euler integration objects can gain energy. Which is worse.
* It is possible to make a Time Adjusted Euler Integration to be stable for common use, and it behave better than Time Adjusted Velocity Verlet in some situations.
* The Velocity Verlet algorithm assumes that acceleration depends on the updated position, but not the velocity.

---

There are algorithms with better properties in exchange of more computing time. Although that trade-off is less relevant for modern computers, it still is (in particular for the higher frame rates and large numbers of objects).

That is why different games use different integration methods. Being Euler and Velocity Verlet among the more popular.

This discussion often leads to Fourth order Runge-Kutta (RK4). It is more CPU expensive, and harder to understand and implement.

I will refer you to Physics for Flash Games by Richard Lord for a comparison of the common implementations.

See also Ilmari Karonen answer on How can I implement gravity?.
> 2 votes

---
Tags: 2d, motion
---


# Question
Title: Procedurally placing buildings on noise-field
So, I have a procedurally generated planet. In my case it's 3D (hexagon/pentagon globe) but for simplicity let's assume it is a 2D grid.

I have distributed resources over this planet, using Simplex Noise, with a cut-off value, giving me a binary distribution.

One of the things I generate in this way, are fields of wheat, shown in yellow below.

After the wheat-fields are generated, I want to procedurally place farms on the planet.

If I would just randomly pick a "yellow tile" (tile with wheat on it) then I run the danger of having them poorly distributed, as shown on the left.

What I want, is a nice distribution where farms favour large wheat areas that are still unoccupied by other farms, as shown on the right.

Is there a simple algorithm that can do this placement?

NOTE: I want to use this approach for other buildings like mines, quarries, lumberjack operations, etc. So I want to avoid placing first, and then growing resources around it. I want the noise field to drive the placement, not the other way around.

NOTE: Farms will not consume the wheat. I've made wheat fields binary wheat/no-wheat but also have scaled distributions with "potency" for e.g. forests, where the number of trees per tile can vary.

# Answer
Thanks to the insight from @Peethor about computing the number of grain tiles per farm, I managed to solve it with a simple yet very effective approach:

Let ***G*** be the number of grain-tiles.

Let ***F*** be the number of farms.

1. Compute the number of Grain tiles per Farm: ***G / F***
2. Find all contiguous regions of grain ***R₀, R₁, ... Rₙ***
3. **foreach** farm:
    * Find largest grain region ***Rᵢ***.
    * Place farm on region ***Rᵢ***.
    * Adjust the size of region ***Rᵢ*** by subtracting ***( G / F )***
> 0 votes

---
Tags: procedural-generation, grid, noise
---


# Question
Title: Ordered dithering between "discrete" colors?
I want to achieve color dithering between discrete colors like this:

As you can see, there is no gradient, or technically there is, but very discrete as it's only a 3 color image (right bar).

So I want the same results applying ordered dither (or at least try it and see if it works).

I have this test sample:

And this is teh function where i do the dithering:

```
// OrderedDither applies a Bayer matrix to dither.
func OrderedDither(img image.Image, palette []color.Color) image.Image {

rImage := image.NewRGBA(img.Bounds())

matrix := [][]float64{
    {0, 4, 1, 5},
    {8, 12, 9, 13},
    {2, 6, 3, 7},
    {10, 6, 11, 15}}

for j := 0; j < img.Bounds().Max.Y; j++ {
    for i := 0; i < img.Bounds().Max.X; i++ {
        m := matrix[i%4][j%4] / 16
        oldPixel, _ := colorful.MakeColor(img.At(i, j))
        oldPixel.R = oldPixel.R*m + oldPixel.R
        oldPixel.G = oldPixel.G*m + oldPixel.G
        oldPixel.B = oldPixel.B*m + oldPixel.B
        newPixel := GetClosestColor(palette, oldPixel)
        r, g, b, _ := newPixel.RGBA()

        rImage.Set(i, j, color.RGBA{R: uint8(r), G: uint8(g), B: uint8(b), A: 255})
    }
}
return rImage

```

}

I get this:

As you can see, there is not dithering in the borders and the dithering inside the boxes is awful.

Any recommendations?

Edit: I implemented the average distance in the 16 color palette:

```
r := AverageColorDistance(palette)

for j := 0; j < img.Bounds().Max.Y; j++ {
    for i := 0; i < img.Bounds().Max.X; i++ {
        m := matrix[i%4][j%4]/16 - 0.5
        oldPixel, _ := colorful.MakeColor(img.At(i, j))
        oldPixel.R = oldPixel.R + r*m
        oldPixel.G = oldPixel.G + r*m
        oldPixel.B = oldPixel.B + r*m
        newPixel := GetClosestColor(palette, oldPixel)
        r, g, b, _ := newPixel.RGBA()

        rImage.Set(i, j, color.RGBA{R: uint8(r), G: uint8(g), B: uint8(b), A: 255})
    }
}

```

And the result was not satisfactory neither:

The average color was 0.4792891. (got 256 values in a 16 color palette).

But in either case i still got no blur between the boxes. Should i stop trying to make Ordered work and go Floyd-Steinberg? I want to get some blur between the hard edges.

# Answer
This is a very late reply to this, you've likely sorted it out by now but for anyone else who wants an answer to your question.

dithering doesn't do what you are expecting - it breaks the colours up into a limited palette, it doesn't blend between hard edges as you are expecting it to. The outputs you have got are as expected from an ordered dither;

All you need to do to achieve the effect you want is to apply a vertical blur before you dither the image.
> 3 votes

# Answer
You have a small mistake in there. First of all, you have to subtract 1/2 from `m` to make it centered around 8 in this case. Secondly, instead of multiplying `m` with the r, g and b components of the original color, you have to multiply it by the average distance between the colors. For instance if you have three colors, (0,0,0), (100,0,0) and (255,0,0), then the average distance is

```
r = ((100 - 0) + (255 - 100) + (255 - 0)) / 3 = 170

```

For different r, g and b valies, use the 3d extension of the pythagorean theorem to calculate distance.

So basically, instead of

```
oldPixel.R = oldPixel.R * m + oldPixel.R

```

do

```
oldPixel.R = oldPixel.R + r * m

```
> 1 votes

---
Tags: algorithm, graphics, graphics-programming
---


title: Add force to objects while inside area

text:
# Question
Title: Add force to objects while inside area
I'm currently trying to create an area that would somehow push objects to a specific direction. (and also apply angular drag if possible)

I'm currently new to Unity and Godot. I have already seen this in Unity tutorial and checking if this is also possible in Godot.

I have a RigidBody2D (with gravity) that falls down on an Area2D.

I'm currently stuck at this code..

```
func _on_Area2D_body_entered(body):
    body.apply_impulse(Vector2(),Vector2(0,-50))

```

..but it only applied it once after entering the are and not continuously applying force until the object exited the area. I tried using add\_force but it gave the object a constant speed and direction and not falling back down.

# Answer
Use the equivalent of OnCollisionStay (I'm not sure what that would be in Python). Also, use add force not impulse. Impulse is instantaneous, force is over time.
> 1 votes

# Answer
I was able to do what I want by applying force on entry and applying opposite force on exit.

```
func _on_Area2D_body_entered(body):
    body.add_central_force(Vector2(0,-500))

func _on_Area2D2_body_exited(body):
    body.add_force(Vector2(),Vector2(0,500))

```

Thanks for the clarification regarding impulse and force. I'm just new to game development so I'm still having trouble on understanding some terms.
> 0 votes

---
Tags: 2d, godot, gdscript
---


title: How to change the speed of an NPC?

text:
# Question
Title: How to change the speed of an NPC?
I created a blueprint. I added several components to the blueprint. I made it follow a target point and it does it correctly. I'd like to make the NPC make this way to the target point faster, but I do not know how to set the speed.

**How I Created:**

**Components of the NPC:**

I've clicked on all components looking for a way to set their speed. I also clicked **Class Settings** and **Class Defaults**, but nothing resulted.

**Then I tried to find some function or command related to the speed, taking a reference from the NPC itself:**

**I added values to tranform, but did not change the result in the game at all:**

**Links that I clicked at the time I typed the title of the question:**

How do I change the speed of an object without changing path travelled?

Changing speed of an object

# Answer
Did you consider setting `maxwalkspeed` and `maxrunspeed` ? Go to `CharacterMovementComponent` API docs page, and check-out the list. You will find a lot of configurable movement modes and if you are unsatisfied, you can make your own.

The functions are blueprint callable for a blueprint class deriving from character/pawn. For using in C++ class, include `UCharacterMovementComponent.h` .

**In NPC Blueprint, on the Components tab, click in CharacterMovement:**

**Look for the "Character Movement Walking":**

Modify the option that is circled (default value was 600).
> 2 votes

---
Tags: ai, unreal-4, blueprints
---


title: How to Set PlayerPrefs.SetInt?

text:
# Question
Title: How to Set PlayerPrefs.SetInt?
playerpreferance.setint problem

I am develop one game.In this game 15 levels. I am face this type of issues when send one level score into second levels. I am used player preferences in start() method. Get after Increase the score 20% levels. Player will be given score when the levels finished success.

how to score get used preferences in next level??

**Math**: Level 1 would be 20 + 0 Level 2 is 20 + (20), Level 3 is 20 + (40), Level 4 is 20 + (60), Etc. ex:

Scene1-\> Level1(finishlevel) -\> Getclaim button press currentreward=20;

Scene2-\>Level2(finishlevel)-\> Getclaim button press currentreward=40;

Code:

```
GameManager.cs

    int pointAdd;
    public int levelID;   //ex: Leve1 levelId=0 ,Level2 Leveld=1
    public Text creditsText;

    void FixUpdate()
    {
       creditsText.text="" + PlayerPrefs.GetInt("", 0).ToString();
    }

    public void GetClaim()
    {
        pointAdd = PlayerPrefs.GetInt("",0);
        pointAdd = 20 + (levelID * 20); //FIRST SCENE LEVEID=0 //SecondScene LevelId =1 ////problem here when i m quit a game not increment 20,game store only 20
        PlayerPrefs.SetInt("", pointAdd);
        creditsText.text = ("" + pointAdd);
        btnreward.SetActive(false);   //one time claim then deactive button
    }

```

what i m doing: playing a game when i m play level1=20,level2=40 preferance store.that run successful but when i m quit a game and again play a game(means level1)current credittextis=40 but not add a 20 means my credittext is=60,but game can store here Credittext=20??

# Answer
> 2 votes
`PlayerPrefs.SetInt(name_key, value);` saves your value with the name key specified in a string.

`value = PlayerPrefs.GetInt(name_key);` gets the value which was previously saved with SetInt function, and sets it back to value.

So when you want to save your score you have to do this:

```
PlayerPrefs.SetInt("score", pointAdd);

```

But then for loading it into the second level, you have to do this:

```
pointAdd = PlayerPrefs.GetInt("score");

```

And finally, if you want to check if there is a score saved in your PlayerPrefs, you have to do this:

```
PlayerPrefs.HasKey("Score");

```

Which returns a boolean.

**For more information:**

list of PlayerPrefs functions: https://docs.unity3d.com/ScriptReference/PlayerPrefs.html

Set Int : https://docs.unity3d.com/ScriptReference/PlayerPrefs.SetInt.html

Get Int : https://docs.unity3d.com/ScriptReference/PlayerPrefs.GetInt.html

Has Key: https://docs.unity3d.com/ScriptReference/PlayerPrefs.HasKey.html

## Edit

I didn't quite catch what you were trying to achieve, but you can have these functions to help you:

```
void SaveScore(int score){
    PlayerPrefs.SetInt("score", score);
}
int LoadScore(int defaultValue = 20){
    return PlayerPrefs.GetInt("score", defaultValue);
}

```

The LoadScore function is equivalent to this:

```
int LoadScore(int defaultValue = 20){
    if(PlayerPrefs.HasKey("score"))
        return PlayerPrefs.GetInt("score");
    return defaultValue;
}

```

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


# Question
Title: Using Minimum Translation Vector in SAT algorithm
I am working on a simple rigid-body physics engine ,I've already implemented SAT algorithm for collision detection and everything works fine, Now i get to step to use MTV to calculate the distance which objects might move to, In my case the two objects are cubes ,Actually i am a little confused about the distance and how to use it

Here is the two cubes

Both of them are on the same y-axis and z-axis, Only differs in x-axis

I am calculating MTV and i get:

`samllest` which refers to the smallest axis, So it looks like (x,y,z).

`overlapDistance` which refers to the smallest overlap distance as a double variable.

I know that `overlapDistance` is the distance that one of two cubes should move till no collision

But how to use it , How cubes should respond to this distance ?

Sorry if i am not clear, but for summary i know the smallest overlap distance but i don't know how to get use of it

# Answer
> 3 votes
The minimum translation vector isn't a good choice when resolving collision. For example, let's look at the following case:

The three parts of the image show the three states of the physics engine given a static square and a dynamic one (for simplicity). The dynamic object enters the static one during the update. The minimal translation vector is always the shortest vector, that completely separates the two objects, but it's not always the correct one. The MTV here dictates, that the shortest path to separation is to move the dynamic object vertically upwards. This shouldn't happen, since it entered the static one from the sides and everyone would expect it to stop. This leads to the dynamic object essentially jumping across the static one.

If you want to separate the squares realistically, follow this answer

If you don't care, then it's pretty simple. Just take the `smallest` vector, multiply it by `overlapDistance` and subtract it from the position of the moving square

---
Tags: physics
---


title: Camera.main is not what the user sees

text:
# Question
Title: Camera.main is not what the user sees
I'm developing (or rather butchering) plugin for Rust, which was build in Unity, and I need to create a targeting system. Unfortunately I got stuck on `WorldToScreenPoint` and `WorldToViewportPoint`. It seems that the `Camera.main` is not what player sees and is not moving at all. Also it has different resolution from what the game is set up.

Unfortunately I can't use Unity and all the work needs to be done in VS.

Does anyone has a suggestion how to get a "proper" camera for this?

Thank you in advance

**EDIT**

As requested this is my code: `Debug.log(Camera.main.WorldToScreenPoint(bAnimalNPC.transform.position).x.ToString())` `Debug.log(Camera.main.WorldToScreenPoint(bAnimalNPC.transform.position).y.ToString())` `Debug.log(Camera.main.WorldToScreenPoint(bAnimalNPC.transform.position).z.ToString())`

The rest is just getting the `bAnimalNPC` and doing some checks.

# Answer
> 4 votes
## Main Camera

`main` is a property of `Camera` that returns

```
GameObject.FindGameObjectsWithTag("MainCamera").GetComponent<Camera>();

```

Which is not really performant and you need to cache it in a variable at the start, but with that said, you could just tag your desired camera with `MainCamera` tag and it works.

https://docs.unity3d.com/ScriptReference/Camera-main.html

## Current Camera

You can also get the `current` camera which unity is currently rendering, like this:

```
Camera.current

```

https://docs.unity3d.com/ScriptReference/Camera-current.html

## All Cameras

If you can't access the unity scene, you could get all the cameras in the scene via code and check if it's your desired camera.

you can get all enabled cameras in the scene, using this :

```
Camera.allCameras

```

Which returns `Camera[]`.

https://docs.unity3d.com/ScriptReference/Camera-allCameras.html

## EDIT

Put this code on the animal and see what happens:

```
void OnGUI(){
    Vector3 screenPos = Camera.main.WorldToScreenPoint (transform.position);
    Debug.Log(Camera.main.WorldToScreenPoint(transform.position).x.ToString());
    GUI.Box(new Rect(screenPos.x - 30, (Screen.height - screenPos.y) - 15, 60, 30), "Text");
}

```

# Answer
> 1 votes
Mohammed Zamanian explained a lot already, but let me provide you with a generic, practical solution.

You should create a Singleton class, which you put on an invisible gameObject on your scene. Assign your main camera to a public Camera variable. If you use multiple ones, with a fixed amount, use multiple variables.

```
public class CameraManager
{
    public static CameraManager Instance;

    // Refer to these by "CameraManager.Instance.PrimaryCamera"
    public Camera PrimaryCamera; // Remember to assign the camera on the gameObject.
    public Camera SecondaryCamera; // Assign this too.

    public Camera CurrentCamera; // This is your currently active camera set by the methods below.

    protected void Awake ()
    {
        Instance = this;
    }

    public void ActivatePrimaryCamera ()
    {
        CurrentCamera = PrimaryCamera;
        SecondaryCamera.enabled = false; // Do the camera transition here.
        PrimaryCamera.enabled = true;
    }

    public void ActivateSecondaryCamera ()
    {
        CurrentCamera = SecondaryCamera;
        PrimaryCamera.enabled = false; // Do the camera transition here.
        SecondaryCamera.enabled = true;
    }
}

```

Now you can set your camera as the current camera and can efficiently refer to them with your own code. I advise you to assert control over your cameras, so that you don't just arbitrarily search for whatever is currently active, and always know which one is active.

The Unity camera functions should be seen as backup functions, as they are not performant. Do not use them unless necessary. Rely on your own code.

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


# Question
Title: How to synchronize clocks in multiplayer game?
I have 2 to 3 clients, that can exchange messages through Apple Game Center.

The only synchronization I need is: start the game at the same moment.

I guess this involves clock synchronization. How to accomplish this?

# Answer
> 16 votes
Steven's comment is right: this is theoretically impossible to do.

Luckily, in practice you can come close, which is how things like NTP work.

For example, better than just sending a message out to 3 clients saying "start now", you can exchange a couple of ping messages beforehand to measure the time it takes to get a message to the client, and when you send the start message, instead of "start now" say "start in X milliseconds" and adjust X for the different times taken for a message to arrive.

eg.:

* You send a message to Client 1 and get a response back 20ms later. You guess that it takes roughly 10ms to get a message to client 1.
* You do the same for Client 2 and get a response 28ms later - so the transmission time there is likely to be about 14ms.
* So you send out a message to Client 1 saying "start the game in 50ms" and send one to Client 2 saying "start the game in 46ms". Client 2 will get the message about 4ms later, but will wait 4ms less before starting the game.

This can't guarantee synchronisation because the time taken to send a message across the internet varies, and because it can be different in each direction. The first you can reduce the effects of by performing the measurement several times and taking a median reading. The second is trickier and may be theoretically impossible to solve (though I can't remember the proof right now). The good news is that you probably don't need that much accuracy.

# Answer
> 3 votes
As mentioned, this is impossible, so I'd try another approach:

If you don't have a dedicated server, elect one participating client to become the host (this can be transferred if the need arises to).

The host will now perform all important game logic, like hit detection, AI controls, inventory handling, etc. as well as time tracking (i.e. dictating game time).

The other clients will just try to stay in sync to the host, trying to estimate or approximate the expected value. If lag increases or there's packet loss, things might get choppy, but it's trivial to catch up, essentially just waiting for the next update.

Most games (especially FPS) hide this fact by doing their own local calculation for the player's own movement, shots being fired, etc. to avoid the game feeling laggy. Everything is still corrected based on server data. This can lead to some confusion, e.g. you see yourself shooting the enemy, but the same moment you drop dead (without the enemy taking a hit), but it's still a far better approach than full synchronization.

---

If you still insist on keeping everything in sync, you'd probably want to create some kind of step or frame counter, so all client only process one logic step, then syncing their data, etc. Keep in mind that this can be both bandwidth intensive as well as laggy, so I wouldn't recommend doing that unless you've got lots of data otherwise and your gameplay is turn based (e.g. Artillery/Worms style games).

# Answer
> 1 votes
I recommend synchronizing system timers on all clients and the server by means of NTP \[Stratum 2\] protocol, then the server sends a command to start the game at specified time, say, when all the timers reach 0:05:00. This approach should give you 3-4 ms accurate synchronization, I believe.

---
Tags: networking, multiplayer, game-center
---


# Question
Title: How can you tell if what you're buying is legal?
In the past few days I've been browsing 3D asset marketplaces and repositories (I've been doing it for ages, but a lot recently). Many assets are paid for, others are free. In the past few days I've found suspicious activity on these sites, for example something sold on one site and given free on another site. I've recently reported many of these cases to the respective sites. The problem is, that now I look really closely at these models before buying them. I try to compare textures, geometry where I can, and poly count as tools for sniffing out property theft (copyright infringement).

I have bought some real bargains lately, and I know they're the real deal because I have spoken individually with the artists and am 99% I know it's the real deal. However how can I approach a store and have any confidence that what I'm buying isn't some reskinned asset ripped from a commercial game? (These are harder to spot as comparing geometry is harder)? I've tried to stick to reputable and popular sites, but I've already reported a number of people on these for abuse. It's worrying how often sellers aren't discovered by the site's owners or anyone else before I say something. For example there might be multiple thumbs up or 5 star reviews for people buying models that I've found out are actual rip-offs, or have been ripped off by someone else.

How can I know that a model I buy didn't come from some commercial game from 5 or 10 years ago, or from some mod from some point in time? Do I have any protection for example in future I release a commercial game and it's discovered that one of my assets from someone's mod or a commercial game from the past?

A while back I'd bought some products that seemed to be real bargains, and now that I'm a lot more cautious about these issues, I regret buying them.

# Answer
As always with questions like this, let me start out by saying that I am not a lawyer, and if you want more professional advice, seek out a legal practitioner to help you with your specific issue. Having said that, these are my thoughts on the matter:

Basically, this question boils down to "how can I tell I'm being scammed/lied to?". In online stores, where you can't look a person in the eye and make an educated guess on their ability to produce quality artwork, this is almost impossible. The only way to know something is genuine is by making it yourself. If that's not a possibility, you'll have to trust people. Of course, having an artist make assets for you gives you a lower chance to end up with stolen assets, but you will never know for certain.

Especially if you have a license and proof of purchase, you'll probably (worst case) end up as a victim in a legal battle, as opposed to a perpetrator. But the start of a legal copyright battle is usually a "cease and desist" letter (sent to you by the owner of the asset) which gives you the opportunity to get rid of the asset and replace it with something less harmful.
> 4 votes

# Answer
The only way to be sure is to avoid such stores and hire people instead. Let them sign a contract which states that they vouche for having the copyright for anything they deliver and when it turns out that they don't, they are liable for any damages caused by 3rd party copyright claims.

If you work directly with the artists you can quickly notice when they are posers who try to sell you stolen assets because they are incapable of executing any specific requests you have.

Yes, this is a lot more expensive. But on the upside, you get assets made specifically for your game. This ensures that everything fits together, everything looks exactly the way you want it to look and no player will ever recognize something they've seen somewhere else.
> 1 votes

---
Tags: models, assets, licensing
---


# Question
Title: How to accurately capture the direction in which the mouse moves?
I used to play this game on Kongregate called Death vs Monstars.

A tl;dp (too long; didn't play) explanation of the mechanics is that the character you control follows your mouse cursor. Your charcter fires projectiles endlessly in the direction **opposite** of that in which you just moved (basically out of your back). This game offers a fairly smooth experience in that you can be fairly sure that the projectiles will fire in the opposite direction that you move your mouse in.

I recently tried to recreate this idea in Godot 3.0.6 Mono. It's not the same game, but the idea is that the character controlled by your mouse has an object that is always pointing in the opposite direction of the character. The problem I faced is that the capturing the direction in which the player moves every frame is limited to the very discrete grid of pixels which Godot (and presumably most other engines) uses to interpret the cursor position. Essentially I just get the angle of rotation from the old position vector to the new position vector, and rotate the character accordingly before updating the position. The result is that the direction in which the character is facing, and thus the object behind it, is very unpredictable. For example, you may move your mouse at a 60 degree angle, but the character ends up pointing in a 45 degree angle depending on what pixel your cursor ends up in.

Is there a less discrete way to approach this problem? Instead of reading the integer-vector position of the mouse cursor, could one somehow get the velocity of the mouse movement?

Any other methods of doing this are also appreciated. I am not asking this question for Godot specifically, but generally, in case there is a common "right" way to do this.

# Answer
The trick to do it is to have another object for the cross-hair that is different from the character object (a position would suffice but by having an object you can render the cross-hair and debug more easily), and after moving the character you can update the position of the cross-hair keeping it no further than a pre-specified distance from the character.

Here it is in psuedo-code:

```
// somewhere in the update cycle:
character.UpdatePosition(mousePosition);

if (DistanceBetween(character.position, crosshair.position) > MAX_DISTANCE) {
    crosshair.position = character.position +
                         Normalize(crosshair.position - character.position) * MAX_DISTANCE;
}

shootingDirection = Normalize(crosshair.position - character.position);

```

Please note that this code is not optimized for performance, normalization is happening multiple times and it can be avoided but I kept it this way for readability.

Another caveat is if the cross-hair and the character ended up in the same position (which is VERY rare occurrence) the direction vector ends up undefined, but tbh I wouldn't worry about it, it's practically impossible.
> 1 votes

# Answer
Velocity is just a measure of distance over time, so if you want to capture the velocity of the mouse, you would need to capture the amount of time passed as well. In Godot 2, I believe this is delta - I'm not sure what differences there are between 2 and 3:

```
func getVelocity(delta):
    velocity = mouseMoveDifference / timeSinceLastDeltaCheck

```

As for your issue with imprecise mouse coordinates, could you give more details? I've never run into that issue personally, and am using

```
mousePos = get_global_mouse_pos()

```

In a Godot 2 project that tracks mouse position without any issues. You might want to add some debug logs to confirm it is a problem with your mouse coordinates, and not an issue with your math.
> 0 votes

# Answer
Compute the firing direction as a linear combination of the old firing direction and the new mouse movement direction. Thus you get more smooth (but somewhat time lagging) evolution of the firing direction vector.

I assume you always update at equal time intervals and you have stored the old firing direction (as a 2D direction vector).

Ordinary you would replace the firing direction with the inverse of the mouse movement direction. That can be very erratic.

Instead compute the new firing direction as: f times old firing direction + (1-f) times inverse mouse movement direction with a chosen constant f between 0 and 1. For f close to 1 you get a very smooth, but somewhat lagging behind behavior. Choose the value you like most. It may depend on the time between updates of the firing direction.
> 0 votes

---
Tags: rotation, mouse, godot
---


# Question
Title: Is Realtime Lighting calculated every frame, including lights that aren't 'visible'?
I'm working with a big scene, with a lot of realtime lights.

I experienced a big drop in FPS after adding lights, so I suppose that too many realtime lights are a 'bad practice'.

But my question is: are all realtime lights calculated every frame even if they are not visible from the active camera?

Are there any options to specify the behaviour of that calculation?

# Answer
All objects that are affected by any realtime light will take a toll on performance while its being rendered. It doesn't matter if the light itself is visible by the camera.

Basically when a mesh is drawing itself, it's checking all nearby lights, and makes calculations to get the final pixel colours of itself. Lights are too far away and have a small range (so they don't affect any object visible in the camera) could be optimised or not, I'm not sure if Unity handles that, and if you can rely on it on all platforms.

The best advice to give for that is, if you have a big scene, divine it into sections, disabling sections that leave the screen, and enabling others that enter it.
> 0 votes

---
Tags: unity, lighting
---


title: How to change music from room to room?

text:
# Question
Title: How to change music from room to room?
In Unity 2019.3.0a2 I have a labyrinth with multiple rooms. I want the music to change when I get from one room into another. How can I do it so that music from room 1 is only hearable in room 1, and so on..?

# Answer
> 4 votes
If you want to play non-diegetic music (background music which just plays without a positional source), then a simple solution is to add the audio source which plays that music directly to the camera.

Now when the player enters a collider, you can just change the audio clip played by that audio source. In order to do that:

1. turn the room collider into a Trigger if it isn't already
2. attach a new script to the room. Let's call that behavior `BackgroundMusicZone`.
3. Add a variable `public AudioClip backgroundMusic` to the script. This allows you to assign the desired background music clip for the zone in the inspector.
4. Add an `OnTriggerEnter` method to that script. Implement that method to:
    1. check if the object which just entered is the player
    2. if so obtain the audio source component from the main camera using `Camera.main.GetComponent<AudioSource>()`
    3. use `audioSource.Play(backgroundMusic)` to switch to the new audio clip.

Now this is a very basic solution which immediately switches from one music to another. A better solution might be to fade from one music to another by gradually reducing the volume while the old music is still playing and then switching to the new music. This could be done with a coroutine or by going through the audio mixer which has the ability to transition between two setting snapshots. This requires two audio sources attached to different mixer groups: One for the old music and one for the new one.

You might also implement some functionality to only switch to the new music when the player stays in the BackgroundMusicZone for a while to avoid rapidly switching between two tracks when the player moves back and forth between two areas.

---
Tags: unity, audio, music, collider
---


title: Can't Transform.SetParent in Unity

text:
# Question
Title: Can't Transform.SetParent in Unity
i have a problem that i don't understand why is happenning and it's driving me mad. I'm trying to code a script to put the player in the car by disabling the third person controller and then Transform.SetParent. Here's the code:

```
  public ThirdPersonCharacterControl Controller;
  public GameObject Player;
  public GameObject Car;

 public void PutWheel()
    {
        if(isInteractive)
        {
            if(isCar)
            {
                PlacePlaceables();
                Controller.enabled = false;
                Player.transform.SetParent(Car);
            }
        }
    }

```

The error is:

```
Assets/Scripts/Player/Interactible.cs(361,34): error CS1502: The best overloaded method match for `UnityEngine.Transform.SetParent(UnityEngine.Transform)' has some invalid arguments

Assets/Scripts/Player/Interactible.cs(361,44): error CS1503: Argument `#1' cannot convert `UnityEngine.GameObject' expression to type `UnityEngine.Transform'

```

Why is that happening? It doesn't make sense to me because everything seems correct.

# Answer
> 1 votes
Car is a GameObject

SetParent wants to act on a Transform

So, two options:

1. Change `public GameObject Car` to `public Transform Car` to store the car as a reference to its Transform all along, or...
2. Use `Player.transform.SetParent(Car.transform)` to access the Transform component attached to the car.

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


title: How can I child one sprite to another?

text:
# Question
Title: How can I child one sprite to another?
I am a newb at GameMaker. I have a 2D map which you can move around. I want to add pins to the map, such that when the map moves, the pins stay in the same position relative to the map. By default, the map will move, while the pins remain stationary.

I have tried creating a sub-layer of instances on my map instance layer, but the depth of the sub-layer is always greater than the parent layer. I have tried overriding the depth, but it gives me a warning suggesting unpredictable results.

I have searched the internet, but all I could find was overkill code which I am hoping is not necessary. (And none of those suggestions directly addressed my question.)

How can I make it so that my pins move around with the map? I would like to avoid using code for something so simple.

# Answer
> 0 votes
This does not directly answer the question, as it uses code. So hopefully a better answer without using code comes along.

Add to the Begin Step Event:

```
mapStartingX = inst_map.x;
mapStartingY = inst_map.y;

```

Add to the End Step Event:

```
xOffset = mapStartingX - inst_map.x;
yOffset = mapStartingY - inst_map.y;
x -= xOffset;
y -= yOffset;

```

I really hope this answer becomes obsolete. GameMaker is a widely used game engine and supposedly beginner friendly without code - I can't imaging they are missing this basic functionality.

---
Tags: game-maker
---


# Question
Title: How can I play a particle system only when it's visible?
I am making a game and it has a lot of particle systems in it as special effects, and all of them are supposed to be playing at the same time, but doing that will be heavy on the game's performance, then I thought: Is it possible to play a particle system only when it is visible to the camera and stop playing it when it is out of range or hidden from the camera, maybe with physics raycasting? If it is, can someone help me to write codes that will do so.

# Answer
> 1 votes
There are two Unity event methods you can implement for this purpose: `OnBecameVisible()` and `OnBecameInvisible()`. You can use that to pause and unpause the particle system on the same GameObject.

This doesn't use raycasting but instead hooks into the frustum culling and occlusion culling system of the engine which determines the visibility of all game objects anyway.

# Answer
> 1 votes
Note that **Unity already does a form of this on its own** for frustum culling of particle systems (it's more efficient for systems that can be efficiently predicted - see this article for a detailed breakdown)

On the particle system's main module, you'll see a "Culling Mode" dropdown. As described in the Unity docs:

> **Culling Mode** Choose whether to pause Particle System simulation when particles are offscreen. Culling when offscreen is most efficient, but you may want to continue simulation for off-one effects.
>
> * **Automatic** Looping systems use Pause, and all other system use Always Simulate.
> * **Pause And Catch-up** The system stops simulating while offscreen. When re-entering the view, the simulation performs a large step to reach the point where it would have been had it not paused. In complex systems, this option can cause performance spikes.
> * **Pause** The system stops simulating while offscreen.
> * **Always Simulate** The system processes its simulation on each frame, regardless of whether it is on screen or not. This can be useful for one-shot effects such as fireworks, where during the simulation would be obvious.

So far as I'm aware, this applies only to frustum culling (ie. determining whether or not the particle system's bounds overlap with the camera's view frustum). It does not necessarily cull/pause particle systems that are occluded behind walls or other barriers, so a custom solution may be needed for that case.

You can use Unity's Culling Groups to have more explicit control over culling, as demonstrated for particle systems here.

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


# Question
Title: Fixing error(23, 2) Error parsing expression, misplaced: func
When I try to use the GDScript code below, Godot gives me the error:

> error(23, 2) Error parsing expression, misplaced: func

Why am I getting this error, and how can I fix it? Is there another input node that could give the same results without the error?

```
func _ready():
 position = get_viewport_rect().size / 2
 direction.x = rand_range(-1, 1)
 direction.y = rand_range(-1, 1)
 direction = direction.normalized()
 width = get_viewport_rect().size.x
 height = get_viewport_rect().size.y

func _process(delta):
    position += direction * speed * delta
 if position.x < 0 or position.x > width:
  direction.x = -direction.x
 if position.y < 0 or position.y > height:
  direction.y = -direction.y

 func _on_UFO_input_event( viewport, event, shape_idx ):
 if event is InputEvenMouseButton and event.button_index ==
 BUTTON_LEFT and event.pressed:
 direction.x = rand_range(-1, 1)
 direction.y = rand_range(-1, 1)
 direction = direction.normalized()
 position.x = rand_range(1, width -1)
 position.y = rand_range(1, height -1)
 speed += 5

```

# Answer
> 1 votes
> the function that i have keeps giving me the error(23, 2) is there another input node that could give the same results without the error?

This looks like symptoms of the XY problem, you have a syntax error, but you try to change the algorithm to avoid it. You'd better ask how to fix the syntax errors.

---

It looks like you did not format/indent your code properly: the parser thinks you want to add a function (`_on_UFO_input_event`) to another function (`_process`), which is not allowed (highlighted by the error message `Error parsing expression, misplaced`: it does not expect the keyword `func` in the context of a function). GDScript is a lot like Python, where the *indentation* of the code has a significant importance.

Following the tips from this official page, you should use four spaces for your indentation.

Your code should end up looking like this.

```
func _ready():
    position = get_viewport_rect().size / 2
    direction.x = rand_range(-1, 1)
    direction.y = rand_range(-1, 1)
    direction = direction.normalized()
    width = get_viewport_rect().size.x
    height = get_viewport_rect().size.y

func _process(delta):
    position += direction * speed * delta
    if position.x < 0 or position.x > width:
        direction.x = -direction.x
    if position.y < 0 or position.y > height:
        direction.y = -direction.y

func _on_UFO_input_event( viewport, event, shape_idx ):
    if event is InputEvenMouseButton and event.button_index == BUTTON_LEFT and event.pressed:
        direction.x = rand_range(-1, 1)
        direction.y = rand_range(-1, 1)
        direction = direction.normalized()
        position.x = rand_range(1, width -1)
        position.y = rand_range(1, height -1)
        speed += 5

```

Correctly formatting your code is *required* in a language such as GDScript. And it is *very important* with other languages in general: it allows you to read and parse what's going on faster and more easily.

In addition, the `(23,2)` is not a pair of random numbers, it tells you *where* the issue is in your code. It tells you "at this location, I have found this error". Most IDEs allow you to double-click on the error and take you right to there in your code.

---
Tags: debugging, godot, gdscript
---


title: Strange artifacts in Unity Lightmaps

text:
# Question
Title: Strange artifacts in Unity Lightmaps
I experienced this weird lightmapping bug in my game that causes some models to have glowing artifacts on their surface. These artifacts "move" around, when I edit the UVs of the model in Blender, so I assume that it has something to do with them. I took a few screenshots to hopefully clarify the issue.

* Engine used: Unity 2019.1.4f1
* 3D Software: Blender 2.79b

If you need any other screenshots or something, let me know. Thank you in advance!

Lightmap Bug (lights off):

Lightmap Bug (lights on):

Models without Lightmaps baked:

Unity Lightmapper Settings:

Tree model in Blender with UVs:

Model Configuration in Hierarchy:

Model Asset Configuration:

# Answer
> 3 votes
You have a warning in the next-to-last screenshot which says "This GameObject has overlapping UVs". I also see that you've tried the suggested fix - to check "Generate Lightmap UVs" - but often this, in itself, is not enough to fix overlap because Unity's lightmap generation is not great.

To see if UV overlap is indeed the problem in this case, it may help to turn on the "UV overlap" view mode in the inspector window. This will show you the areas in which the lightmap is erroneously mapping lit areas to dark ones. Here's a video that shows how to do this (from this forum thread which may also be helpful):

If you find that you have some overlap, try playing with the lightmap generation settings in your last screenshot, as well as your lightmap resolution settings in your scene Lighting settings, until that warning goes away. I'd start by increasing "Pack Margin", although increasing this too much will deteriorate the quality of your lightmaps as you have a limited resolution to work with.

You could also try unchecking that option, adding a UV channel in Blender and manually UV-unwrapping your model. Unity uses UV channel 2 for lightmaps, and Blender should automatically export the additional UV map as UV channel 2. (UV channel 1 is what you generally use for texture mapping, and it looks like that's what you're using in your fourth screenshot).

---
Tags: unity, blender, uv-mapping, lightmap
---