title: Quaternions distorting object in Metal

text:
# Question
Title: Quaternions distorting object in Metal
I've been trying to get rotations with quaternions to work for a while now, and I feel I am very close to it actually working but I just can't get it to work.

I do not have a view matrix yet and am just working in 2D space to make this slightly easier to set at the moment. So I'm only rotating around the Z axis.

My model matrix is calculated like this

```
var modelMatrix: matrix_float4x4 {
    var modelMatrix = matrix_identity_float4x4

    modelMatrix.translate(_position)

    modelMatrix.rotate(_orientation)

    modelMatrix.scale(_scale)

    return matrix_multiply(matrix_identity_float4x4, modelMatrix)
}

```

\_orientation is defined as

```
private var _orientation: quaternion = quaternion(angle: toRadians(0), axis: float3(0, 0, 1))

```

quaternion is just a typedef of simd\_quatf

my rotate function is

```
mutating func rotate(_ quat: quaternion) {
    let quatMatrix = matrix_float4x4(simd_normalize(quat))

    self = matrix_multiply(self, quatMatrix)
}

```

I also tried to do it with the .act method

```
mutating func rotate(_ quat: quaternion, _ vec: float3) {
    let rotatedVec = quat.act(vec)

    self.translate(rotatedVec)
}

```

This did the seemingly same thing as the first rotate function.

When I initialize \_orientation with a rotation of 0, the program acts as normal but when I initialize it with 45, it warps the rectangle:

and when I do it with 90, it produces the same result as with 0, which shouldn't happen. I'm assuming the problem lies somewhere in the way I'm applying the rotation to the object, but I have no clue what it is.

Edit:

Also A thought, maybe it is because of the way I am applying the modelMatrix to the shader positions. I'm pretty sure this is the right way but it might be slightly wrong.

```
vertex RastData vertexShader(const VertexIn vIn [[stage_in]],
                             constant ModelMat &modelMatrix [[buffer(1)]]) {
    RastData rd;

    rd.position = modelMatrix.modelMatrix * float4(vIn.position, 1.0);
    rd.color = vIn.color;

    return rd;
}

```

Edit 2: I Have tried to do it with the math described in this answer https://gamedev.stackexchange.com/a/188776/157187 but that did nothing

```
mutating func rotate(_ angle: Float, _ axis: float3, _ pQuat: quaternion) {
        let newQ = quaternion(vector: float4(axis, cos(angle / 2)))

        let newPQ = newQ * pQuat * newQ.conjugate

        let newVec = float3(newPQ.vector.x, newPQ.vector.y, newPQ.vector.z)

        var mat = matrix_identity_float4x4

        mat.columns = (
            float4(1, 0, 0, 0),
            float4(0, 1, 0, 0),
            float4(0, 0, 1, 0),
            float4(newVec.x, newVec.y, newVec.z, 1)
        )

        self = matrix_multiply(self, mat)
}

```

Edit 3: Alright I think the problem lies in my lack of a view and projection matrix, so I have defined some quick ones, not really implemented a camera system, just having the functionality of the view and projection matracies.

I have a function that makes an orthographic projection:

```
func makeOrthographicMatrix(tooManyArgsLol) {
return float4x4(
        float4(2 / (right - left), 0, 0, 0),
        float4(0, 2 / (top - bottom), 0, 0),
        float4(0, 0, 1 / (far - near),   0),
        float4((left + right) / (left - right), (top + bottom) / (bottom - top), near / (near - far), 1)
    )
}

```

This uses the Column constructor so it looks weird but it's correct.

And a view matrix that should be -3 on the Z axis:

```
var viewMatrix: float4x4 {
        var viewMat = matrix_identity_float4x4

        viewMat.translate(float3(0, 0, -3))

        return viewMat
}

```

but now all I get is the clearColor I set.

In my vertex shader I do the multiplication like this

```
cameraMats.projectionMatrix * cameraMats.viewMatrix * modelMatrix.modelMatrix * float4(vIn.position, 1.0);

```

When I debug using the Metal debugger, it shows that all the data is going through to the shader correctly, so it's definitely some sort of math issue, I just don't really know where to look now.

# Answer
> 1 votes
Alright so the main problem was actually that I had to projection matrix that changed depending on the aspect ratio of the window that was being rendered to. So with that out of the way I actually did end up getting quaternion rotations to work:

```
mutating func quatRotate(_ angle: Float, _ axis: float3) {
    var q = quaternion(angle: angle.toRadians, axis: axis)

    let qMat = float4x4(q.normalized)

    self = qMat * self
}

```

And use this before I translate like so:

```
var viewMatrix: float4x4 {
    var vm = matrix_identity_float4x4

    vm.quatRotate(_orientation.x * 50, XAXIS)
    vm.quatRotate(_orientation.y * 50, YAXIS)
    vm.quatRotate(_orientation.z * 50, ZAXIS)

    vm.translate(_position)

    return vm.inverse
}

```

The * 50 is because just using \_orientation.angle was like a 1 pixel per second rotation speed lol.

Thank you to everyone who commented on this despite it being hot mess in the context of me actually knowing what was wrong! @DMGregory the goat I love you.

# Answer
> 0 votes
I am not familiar with Metal's API so I can't be 100% sure on the usage correctness but mathematically what must happen is the following:

1. Create a model matrix by applying scaling, rotation then translation, in that order (you are doing the reverse)
2. Apply the resulting matrix to each point of the model (that is what the vertex shader does)

Code-wise this would look like:

```
var modelMatrix: matrix_float4x4 {
    var modelMatrix = matrix_identity_float4x4
    modelMatrix.scale(_scale)
    modelMatrix.rotate(_orientation)
    modelMatrix.translate(_position)
    return modelMatrix
}

```

Also the rotation method might need to change to

```
mutating func rotate(_ quat: quaternion) {
    let quatMatrix = matrix_float4x4(simd_normalize(quat))
    self = matrix_multiply(quatMatrix, self) // the rotation matrix must be multiplied from the LEFT
}

```

For the rotation, you must make sure that the `quatMatrix` value ends up being $$C=\begin{pmatrix} 0 & -1 & 0 & 0 \\ 1 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 1 \end{pmatrix}.$$ or something very close to it (i.e. the 1x1 and 2x2 cells should be very small values). This is for clockwise 90 degree rotation.

As mentioned, I am not familiar with the API at all so the fixes I've suggested might be incorrect or not needed but that's the theory at least.

The vertex shader looks correct to me, again with assumptions on Metal's shader language.

Finally, remember that since vertex shaders output normalized device coordinates (that is, all coordinates range from \\$\[-1, 1\]\\$) you have to compensate for the viewport aspect ratio distortion. What this means is that if you have a square in the vertex shader for example with the top left corner at \\$(-200,-200)\\$ and bottom right at \\$(200,200)\\$, these must not be mapped to something like \\$(-0.2, -0.2)\\$ and \\$(0.2, 0.2)\\$. Instead the x coordinate must be divided by the viewport's aspect ratio \\$(-0.2 / aspectRatio, -0.2)\\$ in order for a *square* to be rendered on the screen. This can be easily done by applying an orthographic projection matrix after the model matrix (view this page https://en.wikipedia.org/wiki/Orthographic\_projection on how to create it).

---
Tags: mathematics, rotation, quaternion, swift, metal
---


# Question
Title: When are Lagrangian Mechanics useful in a game?
I have not used or heavily studied Lagrangian Mechanics before and I have not built a physics engine modeled with constraints yet.

I understand that Lagrangian Mechanics are an alternative way to think about Newtonian Mechanics (standard kinematics equations) in-terms of constraints, does this actually come into practical usage in a game engine?

I've been getting started with constraint-based resolution with this tutorial: http://gamedevelopment.tutsplus.com/tutorials/modelling-and-solving-physical-constraints--gamedev-12578

In addition I'm going through Erin Catto's white paper "Iterative Dynamics with Temporal Coherence": http://www.bulletphysics.com/ftp/pub/test/physics/papers/IterativeDynamics.pdf

# Answer
> 6 votes
Lagrangian mechanics is nice for a few different reasons:

* You can add constraints directly into the differential equation which leads to the equations of motion of a body.
* You can use whatever coordinate system best suits your purpose, so long as you can represent an object's potential and kinetic energy in terms of those coordinates.
* It's not *too* hard to take into account many particles interacting at once, even though it can be computationally expensive - which would be a problem no matter what method you try to use to analyze the system.

Let's look at some cases where these could be useful.

1. As I know you're aware, constraints are easy to add in to the Euler-Lagrange equations, i.e. the equations of motion from a Lagrangian. You simply add in another term, a sum of all the constraints. It's essentially an application of Lagrange multipliers, if you've used those before. In a game, this can be useful if you want a players to move on a certain surface or path (at least one Game Development question has asked for something like this, Specific path for ai for follow). Here, Newtonian mechanics is very close to *useless*. Go for the Lagrangian approach.
2. Say you have a character swinging on a pendulum. If you've done some basic mechanics, you probably know how to approach the system in terms of Newtonian kinematics. This is often simple. But what if you have *multiple* pendula? The equations of motion for, say, a double pendulum are nasty, but they can be computed numerically . . . if you can come up with the suitable Lagrangian. Doing a Newtonian analysis in terms of forces would be much, much harder.
3. Swinging on ropes can also be modeled using Lagrangian mechanics. For instance, you could approximate a rope of length \\$l\\$ as a bunch of \\$N\\$ tiny pendula with lengths \\$l/N\\$. In the limit as \\$N\\$ goes to infinity, you have a very good simulation of a rope of constant length. Do you want Mario to swing from one tree to the next on a vine? This kind of thing can work well. You could also use a Lagrangian density if you want to study the rope as a continuous object, without breaking it into discrete pendula. Rope physics as a whole can actually be described using a Lagrangian. It is the simplest way to approach the general catenary problem (see also a case using the Lagrangian density). Static or moving ropes can both be studied this way.
4. Do you want to navigate an field of really massive asteroids, in a spaceship? Well, if the asteroids are going to influence the ship via gravity (in real life, they won't), you have some options. Here, you *could* use the Newtonian approach of forces, but that can be a little annoying. Alternatively, you could create a Lagrangian and figure out the potential energy at *any* point, then simply find the equations of motion. If you assume the asteroids are somehow fixed (again, not realistic), then this becomes less tricky.
5. Actually, you can extend the previous example using *any type of potential*. Do you want your potential energy to be proportional to the distance between two objects raised to the 14th power? What about something more complicated, like \\$14e^xx^2\sin x\\$? Or what if the potential is somehow tied to the target object's velocity? All of this can be taken into account in your Lagrangian, and the Euler-Lagrange equations can be derived without too much trouble. *Solving* them numerically would be a pain, but so would doing it any other way.

Basically, Lagrangian mechanics isn't just useful in terms of constraints. It makes finding the equations of motion much easier, in any coordinate system you want, for any potential you want. Sometimes, that can be really helpful - and much better than having to constantly split forces up into different vectors.

You also may want to look into Hamiltonian mechanics. The Hamiltonian, \\$H\\$, is the Legendre transform of the Lagrangian, \\$L\\$, and results in a pair of coupled differential equations. I think most people would prefer to use Lagrangian mechanics; if you really want to, you can use Hamiltonian mechanics, but some applications may be trickier.

# Answer
> 1 votes
Lagrangian mechanics is useful for deriving the equations of motion for any system in a simple and structured way. Lagrangian mechanics will result in the same equations of motion (which is what describes how everything moves) as Newtonian mechanics, and once you have the equations of motion, you will probably only be using those in your game and not Lagrangian mechanics.

For simple systems in which you know the forces acting on all objects, Newtonian mechanics is probably going to be easier to use. However, for more complex systems, which may involve holonomic constraints, any coordinate system for describing the state of the system (not necesarily a Carteesian), and many parts that may interact with each other in some non-trivial way, the equations of motion may still be obtained relatively easily with Lagrangian mechanics. If your system is unconstrained, all you need to do is to formulate the kinetic energy and potential energy of the system as functions of the generalized coordinates q, as well as their time derivatives. Then you form the Lagrangian as L = K - V, and the Euler–Lagrange equations will be your equations of motion. You may need to work them a little bit to get them in a form that is useful for implementation in a game (you want to isolate the highest time derivative for each generalized coordinate), but that's basically it.

If you have holonomic constraint, you also need to define a function f(q,t) for each constraint for which the constraint is the iso-surface that corresponds to f(q,t)=0. Then you instead form the Lagrangian as L = K - V + a1·f1 + a2·f2 + ... + an·fn, where f1, ..., fn are the functions for your constraints and a1, ..., an are corresponding, unknown coefficients, or so called Lagrange multipliers (basically, the higher these multipliers are, the higher the force from the corresponding constraints are). Then you use the Euler–Lagrange equations as usual, plus equations for your holonomic constraints, which you use to solve for a1, ..., an to make sure that you stay on the isosurface and that the constraints are satisfied (i.e. you find the forces require to make sure you stay where you are supposed to stay). Even if the principle is simple, how to do this in practice can be a bit involved, but one effective solution is described here. These mutipliers will show up in your equations of motion so you just plug in what you solved for them there.

---
Tags: physics
---


# Question
Title: Why do objects spin in circles instead of stopping when reaching their target?
This script is attached to each drone.

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

public class DroneControl : MonoBehaviour
{
    public Transform target;
    public float turnSpeed = .01f;
    Quaternion rotGoal;
    Vector3 direction;
    public float movingSpeed;
    public bool go = false;

    private bool waitBeforeRotate = false;
    private bool startRotating = false;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if(go)
        {
            transform.position += transform.forward * movingSpeed * Time.deltaTime;

            if (waitBeforeRotate == false)
            {
                StartCoroutine(StartRotating());

                waitBeforeRotate = true;
            }

            if (startRotating)
            {
                direction = (target.position - transform.position).normalized;
                rotGoal = Quaternion.LookRotation(direction);
                transform.rotation = Quaternion.Slerp(transform.rotation, rotGoal, turnSpeed);
            }
        }
    }

    IEnumerator StartRotating()
    {
        yield return new WaitForSeconds(3f);

        startRotating = true;
    }
}

```

I can think of two potential problems here, but I'm not sure if this is what making the behaviour of spinning nonstop at the target:

1. The objects are moving forward but nothing tells them to stop at the target. Only the rotation makes them move to the target direction.
2. Since the objects rotate to face the target direction, maybe when they reach the target they keep rotating ?

The goal at first is to move the objects to the target and stop at the target.

# Answer
The drone does not know when it reached its target. When it passes through the target it just continues its forward movement and rotation toward the target like before. Because the target is so close drone's rotation can't keep up with the forward movement and it looks like rotation around the target, i.e. while turning back toward the target the drone has already moved away from it. When both forward move and rotation balance out it looks like orbiting.

You need a way for your drone to know if it is close enough to its target to stop. I modified your code to add range check:

```
using System.Collections;
using UnityEngine;

public class DroneControl : MonoBehaviour
{
    public Transform target;
    public float turnSpeed = .01f;

    Quaternion rotGoal;
    Vector3 direction;
    public float movingSpeed;
    public bool go = false;

    private bool waitBeforeRotate = false;
    private bool startRotating = false;

    #region AddedCode
    public float targetRange = 1.0f;

    private bool IsTargetReached(Vector3 dronePos, Vector3 targetPos)
    {
        var distance = Vector3.Distance(dronePos, targetPos);
        return distance < targetRange;
    }
    #endregion AddedCode

    // Update is called once per frame
    void Update()
    {
        // next line is modified to incorporate the range check
        if (go && !IsTargetReached(transform.position, target.position))
        {
            transform.position += transform.forward * movingSpeed * Time.deltaTime;

            if (waitBeforeRotate == false)
            {
                StartCoroutine(StartRotating());

                waitBeforeRotate = true;
            }

            if (startRotating)
            {
                direction = (target.position - transform.position).normalized;
                rotGoal = Quaternion.LookRotation(direction);
                transform.rotation = Quaternion.Slerp(transform.rotation, rotGoal, turnSpeed);
            }
        }
    }

    IEnumerator StartRotating()
    {
        yield return new WaitForSeconds(3f);

        startRotating = true;
    }
}

```
> 1 votes

# Answer
I think the method you are looking for is `Quaternion.RotateTowards`. This method can be used to turn one quaternion towards another, but limit the angular distance it is allowed to change per call of the method. When that angular distance is enough to reach the desired rotation, then it will set the rotation to exactly the desired rotation and not overshoot.

This method is the standard solution for making one object track another with its rotation.

```
transform.rotation = Quaternion.RotateTowards(transform.rotation, rotGoal, turnSpeed * time.deltaTime);

```

Note that `turnSpeed` is now measured in degrees per second. For example, if you want the object to be able to turn 180° in one second, you would set it to 180. Your current default value of 0.01 is far too slow to even be visible.

If you want to check whether or not the object reached the desired rotation, you can do this just after the line above:

```
if (transform.rotation == rotGoal) {
    // now aiming directly at the target
} else {
    // still some way to go
}

```
> 1 votes

---
Tags: unity, c#, rotation, movement
---


title: Spritesheet with unstable width

text:
# Question
Title: Spritesheet with unstable width
I'm working on my 2d game engine using HTML5 and Canvas. I have a sprite sheet, and each frame of this sprite sheet has its own size.

Considering that the Viewport is following this sprite sheet (in the sense that it is translated relative to the position and dimension of this spritesheet), the centering process of the object undergoes some changes due to the recalculation that takes into account the size of the aforementioned sprite sheet, which in some frames is larger, and in other frames smaller.

For instance, this is an excerpt of the code that manages part of the translation of the viewport based on the position of the target sprite sheet

```
this._Edge = this.mLocation.X + this.Target.Width - this.Deadzone.Location.X - this.Deadzone.Width;

    if (this.View.Location.X < this._Edge)
    {
        this.View.Location.X = this._Edge;
    }

```

The problem is that "Target.Width" is nothing more than the width of the current frame, so if the frame is much larger than the previous ones the viewport has a "jump", because it tries to reposition itself based on the current frame size.

From the gif you can see that when I activate the sword sequence, the spritesheet is wider, and consequently the viewport is forced to reposition itself.

To avoid these problems, should I give the sprite sheet a fixed size? Or, for example, would it be more appropriate to consider a fictitious dimension that is an average of the dimensions of the individual frames? As a solution I thought to consider only the center of the sprite sheet, which is always 1x1 pixel. What do you think?

I am ready to consider all suggested solutions.

# Answer
When you want to use a spritesheet with non-uniform frame size, then you need to introduce the concept of a separate "pivot point" for each animation frame. The pivot point is the "zero-point" of the frame. When you draw a frame at coordinates `x:y`, then the pivot is the pixel coordinate within that frame where that `x:y` point is supposed to be on that frame.

Where to place the pivot is a matter of taste. But for a platformer it's a good choice IMO to place the pivot at the bottom of the sprite between the feet.

For example, let's say that your sprite above is 32x64 in the idle pose and 64x64 in the attack poses. In that case, the pivot of both the right-facing idle and attack frames would be `16:64` \- the center of the idle and the left quarter of the attack pose. However, for the left-facing attack pose, you would want to draw the whole frame further left. So the pivot of that frame would be `48:64` \- three-quarters to the right.

When you draw a frame, you would calculate the coordinates somehow like this:

```
function drawFrameAtScreenPosition(pos, frame) {
    x = pos.x - frame.pivot.x;
    y = pos.y - frame.pivot.y;
    YourFavoriteGraphicsApi.drawImage(frame.image, x, y, frame.width, frame.height);
}

```
> 4 votes

---
Tags: 2d, camera, spritesheet, viewport
---


# Question
Title: Flappy Bird Pipes not colliding with with Square
So, I'm quite new to game development and am trying to make a clone of flappy bird. The way my game operates is that I am spawning the pipes to the right of the camera, and then making it move all the way left until the camera cannot see it again, and place a square there that will collide with the pipes, destroy it and spawn it again to the right of the camera. Problem is, although the pipes can sense collisions, somehow when I use CompareTag(tag of the square) the collisions will not register at all. A debug message would not even load. They are both on the same layer so that can be eliminated. Here is the relevant code:

```
public class PipeSpawner : MonoBehaviour
{
    // Start is called before the first frame update
    float speed;
    float ypos;
    float spawnPoint;

    float delay;
    void Start()
    {
        speed = 1.5f;
        spawnPoint = -0.03f;

    }

    // Update is called once per frame
    void Update()
    {
        transform.position -= new Vector3(speed,0,0) * Time.deltaTime;

    }

    void SpawnPipe() {
        ypos = Random.Range(-0.5f, 0.9f);
        Instantiate(this.gameObject,new Vector3(spawnPoint,ypos,transform.position.z),Quaternion.identity);

    }

    void OnCollisionEnter2D(Collision2D col)
    {
        if (col.gameObject.CompareTag("Destroy")) {
            Debug.Log("hit");

        }

    }

```

and here are the pics of the inspector

The Pipes:

https://i.stack.imgur.com/8e6SA.jpg, https://i.stack.imgur.com/WXk1q.jpg;

The Square:

https://i.stack.imgur.com/hJAOz.jpg

If anything about my question is confusing, please tell me and I will try to make it clearer to the best of my ability. Thanks in advance.

# Answer
> 0 votes
A collision requires that at least one of the objects involved in the collision has a Rigidbody component and the other object is either marked as Static or also has a Rigidbody component. For more information, check the manual article on colliders. It appears that your pipe game object is neither static (and it shouldn't be, because it moves) nor has a rigidbody (but it probably should). I can't see your destroyer, but I would assume that it does not have a rigidbody either.

However, in this scenario you likely don't want to use collisions, you want to use **triggers**. Mark the destroyer as static, and give it a 2D collider with the "IsTrigger" property activated. This turns it into a "Static trigger collider".

It will now be triggered by anything with a Rigidbody2D attached to it. So attach the Rigidbody2D component to your pipes (not the regular Rigidbody - that one only interacts with regular 3d colliders, not with 2D colliders). You probably want that Rigidbody2D to be marked as the body type "Kinetic", because you want to control its movement directly and not leave it to the physics engine.

When you have trigger events instead of collision events, then you don't need to implement OnCollisionEnter2D, you need to implement `OnTriggerEnter2D`. Note that the parameter of OnTriggerEnter2D is not a `Collision2D` object, it's the `Collider2D` component of the other gameObject. When you declare it as `OnTriggerEnter2D(Collision2D other)` then it won't get recognized by the engine and won't anything. You have to do it like this:

```
void OnTriggerEnter2D(Collider2D otherCollider)
{
    if (otherCollider.CompareTag("Destroy")) {
        Debug.Log("hit");
        Destroy(otherCollider.gameObject);
        SpawnPipe();
    }
}

```

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


# Question
Title: Compass objective indicator points towards wrong direction
I have a compass that is pointing towards player forward direction.

```
direction.z = player.eulerAngles.y;
if (_transform.localEulerAngles.y != direction.z)
{
   _transform.localEulerAngles = direction;
}

```

I have indicators for each objective. I'm trying to rotate the indicator towards quest objectives as seen in image bellow.

```
float angle = Vector2.Angle(player.transform.position - player.transform.forward, objective.position);
objectivePositionUI.anchoredPosition = new Vector3(
   Mathf.Cos((angle * 2 * Mathf.PI) / 180f) * radius,
   Mathf.Sin((angle * 2 * Mathf.PI) / 180f) * radius,
   0f
);

```

My result atm

My problem here is that the yellow dots (objectives) should be rotated at the same direction as arrow in this case because I am facing the quest objectives head on.

# Answer
You can do this much more simply, assuming "North" is the world z+ direction and "East" is the world x+ direction:

```
Vector2 GetCompassPosition(Transform target, float radius) {
    Vector3 offset = target.position - player.transform.position;
    return new Vector2(offset.x, offset.z).normalized * radius;
}

```

Your pointer can then point with the angle...

```
float GetCompassAngle(Vector3 direction) {
    return Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg;
}

```

This will give you an angle of 0 degrees when the direction is directly north (0, 0, 1), 90 degrees when the direction is directly east (-1, 0, 0), etc., to be consistent with the version shown in your question.

You can use it like this. This saves you from reading Euler angles, since they can behave counter-intuitively and lead to bugs.

```
_transform.localEulerAngles = new Vector3(0, 0, GetCompassAngle(player.forward));

```
> 1 votes

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


# Question
Title: Only Square Textures loading correctly (Beginner question)
(Sorry if this has already been asked, I couldn't find any other question or source describing my problem)

Okay so basically Square textures load and display just fine.

But for some reason, when trying to load in textures that aren't square (and/or resizing the model so the texture fits) isn't working right.

Here's the Player-bit:

```
float[] vertices = new float[] {
    -1, 1.5f, 0,  // Top Left     0
    1, 1.5f, 0,   // Top Right    1
    1, -1.5f, 0,  // Bottom Right 2
    -1, -1.5f, 0, // Bottom Left  3
};

float[] texture = new float[] {
    0,0,
    1,0,
    1,1.5f,
    0,1.5f,
};

int[] indices = new int[] {
    0,1,2,
    2,3,0
};

model = new Model(vertices, texture, indices);
this.texture = new Texture("animation/player/idle.png");

transform = new Transform();
transform.scale = new Vector3f(16,16,1);

```

and here my Texture Class code:

```
public Texture(String filename) {
    BufferedImage bi;
    try {
        URL path = getClass().getResource("/textures/" + filename);
        if(path == null) {
            throw new IllegalStateException("Texture not found");
        }

        URI file = path.toURI();
        bi = ImageIO.read(new File(file));
        width = bi.getWidth();
        height = bi.getHeight();
        System.out.println(filename + ": " + (int) width + "x" + (int) height);

        int[] rawPixels = new int[width * height * 4];
        rawPixels = bi.getRGB(0,0, width, height, null, 0, width);

        ByteBuffer pixels = BufferUtils.createByteBuffer(width*height*4);

        for(int x = 0; x < width; x++) {
            for(int y = 0; y < height; y++) {
                int pixel = rawPixels[x*width+y];
                // Red, Green, Blue, Alpha
                pixels.put((byte) ((pixel >> 16) & 0xFF));
                pixels.put((byte) ((pixel >> 8) & 0xFF));
                pixels.put((byte) (pixel & 0xFF));
                pixels.put((byte) ((pixel >> 24) & 0xFF));
            }
        }

        pixels.flip();
        id = glGenTextures();
        glBindTexture(GL_TEXTURE_2D,id);

        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
    } catch(IOException | URISyntaxException e) {
        e.printStackTrace();
    }
}

public void bind(int sampler) {
    if(sampler >= 0 && sampler <= 31) {
        glActiveTexture(GL_TEXTURE0 + sampler);
        glBindTexture(GL_TEXTURE_2D,id);
    }
}

```

Notes:

* I am not using Slick or something like that, it's just plain LWJGL.
* I don't know what code I should put in here, just ask me if you need more

# Answer
> 4 votes
It looks like your pixel lookup is backwards:

```
int pixel = rawPixels[x*width+y];

```

Should be

```
int pixel = rawPixels[x+width*y];

```

---
Tags: java, 2d, textures, lwjgl
---


# Question
Title: Unity - How to store a Dictionary in a serializedObject property
I'm writing a custom editor for my `GridModel` object. The object has 2 fields; `Vector2Int dimensions` and a `Dictionary<Vector2Int, bool> grid` variable. Since the script will mostly be editted in the prefab editor, I save the fields with the `serializedObject` property. This works fine for the `dimensions` variable, but the `serializedObject.FindProperty("grid")` method returns `null`. My guess is this is because the `Dictionary` object is not serializable.

My question therefor is, how can I save the `Dictionary` type in the `serializedObject` property to make sure the `grid` field is the same in the prefab editor as in any other editor?

These are my scripts:

```
public class GridModel : MonoBehaviour, IGridModel
{
    public Dictionary<Vector2Int, bool> grid;
    public Vector2Int dimensions;
}

CustomEditor(typeof(GridModel))]
public class GridModelEditor : Editor
{
    public override void OnInspectorGUI()
    {
        Vector2Int dimensions = EditorGUILayout.Vector2IntField("Size", serializedObject.FindProperty("dimensions").vector2IntValue);
        serializedObject.FindProperty("dimensions").vector2IntValue = dimensions;
        SerializedProperty serializedField = serializedObject.FindProperty("grid"); // Returns null
        serializedObject.ApplyModifiedProperties();
    }
}

```

# Answer
I believe you are right, Unity cannot serialize standard dictionaries. I've used this library to serialize Dictionaries in my projects before. The README has a lot of great info features, limitations and usage. In your case, it would be:

```
public class GridModel : MonoBehaviour, IGridModel
{
    // This class can be defined elsewhere if desired
    [Serializable]
    public class Vec2iBoolDictionary : SerializableDictionary<Vector2Int, bool>;

    public Vec2iBoolDictionary grid; // This dictionary should now be serializable
    public Vector2Int dimensions;
}

```

Since `Vec2iBoolDictionary` inherits from `SerializableDictionary` which in turn inherits from `Dictionary` I don't believe you will have to change any other parts of your code that use the Dictionary. I'm not sure if there are any further steps when writing a custom editor, typically I'll just use the default editor.
> 2 votes

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


title: How to get all tiles from a Tilemap?

text:
# Question
Title: How to get all tiles from a Tilemap?
I have been trying a little bit the new `TileMap` system in Unity and I was looking for a way to access the tiles as a List or 2D array but I can't find anything other than `GetTile(Vector3Int vector)` which returns only one tile ... Is there any way to do this ?

# Answer
To get an array with all tiles from a rectangular area of your tilemap, use `tilemap.GetTilesBlock(BoundsInt bounds)`. You will get a one-dimensional array of tiles, so you need to know by yourself when the next row of tiles starts. Any empty cells will be represented with a `null` value.

If you want *all* tiles, use `tilemap.cellBounds`. This gets you a `BoundsInt` object which covers the complete used area of the tilemap. Here is an example script which gets all tiles from the Tilemap on the same game object and lists the tiles with their coordinates:

```
using UnityEngine;
using UnityEngine.Tilemaps;

public class TileTest : MonoBehaviour {
    void Start () {
        Tilemap tilemap = GetComponent<Tilemap>();

        BoundsInt bounds = tilemap.cellBounds;
        TileBase[] allTiles = tilemap.GetTilesBlock(bounds);

        for (int x = 0; x < bounds.size.x; x++) {
            for (int y = 0; y < bounds.size.y; y++) {
                TileBase tile = allTiles[x + y * bounds.size.x];
                if (tile != null) {
                    Debug.Log("x:" + x + " y:" + y + " tile:" + tile.name);
                } else {
                    Debug.Log("x:" + x + " y:" + y + " tile: (null)");
                }
            }
        }
    }
}

```

Regarding the bounds and why you might get more tiles than you expect: Conceptually, Unity Tilemaps have an unlimited size. The `cellBounds` grow as needed when you paint tiles, but they don't shrink again if you erase them. So when your game has a well-defined map size, you might get some surprises if you ever slip while editing maps. There are three ways to work around this issue:
> 30 votes

# Answer
Here is another way to do it with `.cellBounds.allPositionsWithin`

```
public Tilemap tilemap;
public List<Vector3> tileWorldLocations;

// Use this for initialization
void Start () {
    tileWorldLocations = new List<Vector3>();

    foreach (var pos in tilemap.cellBounds.allPositionsWithin)
    {
        Vector3Int localPlace = new Vector3Int(pos.x, pos.y, pos.z);
        Vector3 place = tilemap.CellToWorld(localPlace);
        if (tilemap.HasTile(localPlace))
        {
            tileWorldLocations.Add(place);
        }
    }

    print(tileWorldLocations);
}

```
> 18 votes

# Answer
During figuring out how to get all custom tiles from Tilemap and due to `ITilemap` hasn't `GetTilesBlock` method which mentioned in answers I suggest to add an extension method like this (2D only):

```
public static class TilemapExtensions
{
    public static T[] GetTiles<T>(this Tilemap tilemap) where T : TileBase
    {
        List<T> tiles = new List<T>();

        for (int y = tilemap.origin.y; y < (tilemap.origin.y + tilemap.size.y); y++)
        {
            for (int x = tilemap.origin.x; x < (tilemap.origin.x + tilemap.size.x); x++)
            {
                T tile = tilemap.GetTile<T>(new Vector3Int(x, y, 0));
                if (tile != null)
                {
                    tiles.Add(tile);
                }
            }
        }
        return tiles.ToArray();
    }
}

```

In this case if you have, suppose, custom tile TileRoad, inherited from Tile or TileBase, then you can get all TileRoad tiles with call:

```
TileBase[] = tilemap.GetTiles<RoadTile>();

```

For **ITilemap** we can change parameter `(this Tilemap tilemap)` to `(this ITilemap tilemap)` (pay attention that second is Interface) but I didn't check that.
> 2 votes

# Answer
Using it this way to get a feeling about the bounds and to quickly get the tile based on the local position. Delete the print statements later on.

```
/* assuming 2d (ignoring z)*/
BoundsInt _area = tilemap.cellBounds;
TileBase[] _allTiles = tilemap.GetTilesBlock(_area); // okay, offset [0] is representing (Tile) of area.yMin,xMin
print($"CellBounds xMin={_area.xMin},yMin={_area.yMin},(zMin={_area.zMin}),xMax={_area.xMax},yMax={_area.yMax},(zMax={_area.zMax}),width={_area.size.x},height={_area.size.y}");
print($"CellBounds origin/center={_area.center.x},{_area.center.y},({_area.center.z})");
print($"GetTilesBlock size={_allTiles.Length}");
int _xDelay = Math.Abs(Convert.ToInt32(_area.center.x) - _area.xMin); // to be added to each local x position to ensure an x value between 0..area.size.x
int _yDelay = Math.Abs(Convert.ToInt32(_area.center.x) - _area.yMin); // to be added to each local y position to ensure an y value between 0..area.size.y
int _modulo = _area.size.x; // to be added or subtracted to the current offset position to keep the x position in the array but jump to the next or previous line of the array matrix.
foreach (var pos in _area.allPositionsWithin)
{
    Vector3Int localPlace = new Vector3Int(pos.x, pos.y, pos.z);
    if (tilemap.HasTile(localPlace))
    {
        int offset = (localPlace.y + _yDelay) * _modulo + localPlace.x + _xDelay;
        Tile tile = (Tile)_allTiles[offset];
        print($"x={localPlace.x}, y={localPlace.y}  ->  offset[{offset}]  ->  tile name={tile.name}");
    }
}

```
> 1 votes

# Answer
So drawing from the other answers here, and some other sources, and adding a bit more (as I needed more info on the tiles, so needed the position in the grid), I get the following three options.

To set up for any of the options:

```
TMBase = GameObject.Find("TileMapBase");

if (TMBase == null)
    return DoError("TileMap GameObject is null");

Tilemap tm = TMBase.GetComponent<Tilemap>();
if (tm == null)
    return DoError("TMBase Tilemap component is null");

```

Option 1 - read all the tiles in a batch call (note: the bounds being wrong, e.g. bounds from a different TileMap, can give incorrect `gridPlace`, so be careful with that - that's probably because bounds are in units of the grid's 'grid rectangles' which may have different sizes etc.):

```
if (resetBounds)
    tm.CompressBounds();

BoundsInt bounds = tm.cellBounds;
TileBase[] allTiles = tm.GetTilesBlock(bounds);

for (int x = 0; x < bounds.size.x; x++)
{
    for (int y = 0; y < bounds.size.y; y++)
    {
        TileBase tile = allTiles[x + y * bounds.size.x];

        if (tile != null)
        {
            // you may not need to find gridPlace, in which case cut next line
            Vector3Int gridPlace = new Vector3Int(
                x + bounds.xMin, y + bounds.yMin, bounds.z);

            // do something
        }
    }
}

```

Option 2a: Read the tiles one by one:

```
foreach (var pos in tm.cellBounds.allPositionsWithin)
{
    Vector3Int gridPlace = new Vector3Int(pos.x, pos.y, pos.z);
    TileBase tile = tm.GetTile(gridPlace);
    if (tile != null)
    {
        // do something
    }
}

```

Option 2b: Read the tiles one by one, checking if there is a tile

```
foreach (var pos in tm.cellBounds.allPositionsWithin)
{
    Vector3Int gridPlace = new Vector3Int(pos.x, pos.y, pos.z);
    if (tm.HasTile(gridPlace))
    {
        TileBase tile = tm.GetTile(gridPlace);
        // do something
    }
}

```

In my rather rough testing I found that Option 1 was the fastest, with Option 2a being anywhere from just over 0% to 5% slower, and Option 2b being 15-20% slower. Your mileage may very, please post in comments - and the difference between 2a and 2b may be less significant or even reversed if you had a lot of empty Grid spaces, I'm not sure and didn't test.

You can use gridPlace to get various extra info about the tiles, eg:

```
Vector3 worldPlace = tm.CellToWorld(gridPlace);
// use Tilemap.GetCellCenterWorld if you need
// the center of the tile instead of bottom left

```

or

```
Matrix4x4 m = tm.GetTransformMatrix(gridPlace);
Vector3 rotate = m.rotation.eulerAngles;

```

If you don't need that then you will not need to find gridPlace in Option 1, speeding it up a little more.

Thanks to everyone whose code I adapted.
> 0 votes

---
Tags: unity, tilemap
---


# Question
Title: What is the point of .meta files for Unity source code files?
In my Unity project each of source code files is accompanied by .meta file

```
SceneGenerator.cs
SceneGenerator.cs.meta
Scenes
Scenes.meta
SpawnShape
SpawnShape.meta
Stockpile.cs
Stockpile.cs.meta
WaterAreasMaker.cs
WaterAreasMaker.cs.meta
Workshop.cs
Workshop.cs.meta
WorldGrowth.cs
WorldGrowth.cs.meta
(...)

```

is there some useful info recorded there that should be tracked in a repository?

https://unityatscale.com/unity-meta-file-guide/faq/#should-i-add-unitys-meta-files-to-version-control claims that there are dire consequences for not tracking it, but in my experience just removing all of them results in nothing problematic.

Unity will just (sadly) regenerate them.

What is the use of this `.meta` file for source code? Is it safe to not track them in repository? If not, then why?

Is it possible to get rid of them somehow?

(I know that my problem is partially caused by having a very unusual way if implementing Unity project. Everything is done by code, no models, code is written in an external editor, with Unity Editor treated only as compiler and runner)

# Answer
One of the most important things stored by Unity in .meta files are the GUIDs of assets, including script files. These identifiers are used by Unity to uniquely and definitively identify that asset. Any time Unity needs to identify a specific asset (in particular, because that asset is referenced in Unity's editor) then the GUID stored in the .meta file gets used. This is why it is normally crucial to track the .meta files in version control: if you lose the .meta files, then all references to that asset will break.

The reason it doesn't matter in your specific case is that you don't rely on script references within Unity's editor. Since your workflow doesn't involve Unity's editor, there are no references to break.

(related tangent: Meta files were actually introduced to Unity in order to support version control. Previously, in the earliest versions of Unity, the asset GUIDs were stored along with the giant mess of temp library files, resulting in projects that don't play nice with version control.)
> 2 votes

# Answer
.meta files matter in cases where

* file was renamed/moved outside Unity
* file is assigned to asset in Unity (script is attached to something)

https://docs.unity3d.com/530/Documentation/Manual/BehindtheScenes.html appears to indicate that .meta files are utterly useless for script files not referenced directly by Unity objects.
> 2 votes

---
Tags: unity
---


# Question
Title: How do you repeat a tile texture horizontally/vertically in a UI Image?
It seems Unity UI Image supports Image Type 'Tiled', but I'm not sure how to get the tiling to work both vertically and horizontally. Can someone help me understand?

# Answer
Unity's UI Image components give you many options to manipulate Textures for UI purposes, as long as such Textures are Sprites. If you want to display other Texture Types, you might use the Raw Image component, which, on the other hand, offers fewer options.

### Declaring Textures as Sprites

In your Assets folder, select the image(s) you want to use as UI Texture. Then, in the Inspector, set Texture Type to Sprite (2D and UI).

This way, you tell Unity to optimise usage of these resources for UI drawing.

### Setting up the Image component

Select the GameObject with an Image component in it (create one if you haven't yet). Then, drag the image you set as Sprite into the Source Image property in the Inspector. Now, new options shall pop out.

You can now set the Image Type property to Tiled, but a warning message will show up:

> It looks like you want to tile a sprite with no border. It would be more efficient to modify the Sprite properties, clear the Packing tag and set the Wrap mode to Repeat.

### Defining a Wrap Mode

We can fix this warning by setting the Wrap Mode property of the image in the Inspector from Clamp to Repeat:

Click on Apply to save setting changes for the Sprite. Now, image tiling works, and you can tweak the new additional Pixels Per Unit Multiplier setting to get the desired result. The Sprite's Pixels Per Unit (settable in its Import Settings, where you also set the Wrap Mode to Repeat) is multiplied by this value before rendering. You can use it to make tiles bigger (using fewer tiles) or smaller (using more tiles) on a per-Component basis:

### Scaling along the X and Y separately

Pixels Per Unit Multiplier applies to the source Sprite as a whole, keeping its aspect ratio as a tile when covering the Image area. If you want to scale width and height by different factors, you can either change the Image scale and size combined or use the Raw Image component:

* **Scaling/resizing:** A Sprite whose tiling height is double its width can have an actual height of twice its width, and a Y-scale of 0.5. This solution isn't optimal, as you may incur scaling issues with child GameObjects of your Image if any. Also, non-uniform scaling isn't preferable, if other solutions exist.

* **Using Raw Image:** The Raw Image Component exposes the UV Rect properties, that let you define the horizontal and vertical offsets of the image (X and Y), as well as the normalised UV mapping values for the Texture (W and H):
    + Values between 0 and 1 will draw only a portion of the Texture.
    + Values greater than 1 will result in the Texture being downscaled, hence more tiles along a given axis.
    + Negative values will make the Texture mirrored/flipped.
> 5 votes

---
Tags: unity, unity-ui
---


# Question
Title: How to sync the speed of a rigidbody and the speed of a running animation
I have a character with a run animation. The animation was downloaded from mixamo.com. In the animation controller, the physical update mode is selected. How do I change the speed of an animation based on the speed of a rigid body?

# Answer
> 1 votes
You need a Blend Tree.

In your Animator controller create a speed parameter as float and create Blend Tree.

In your Blend Tree, add motions and select your animations. (Image is from example 2D Blend Type, you can choose 1D if that's what you need). Numbers in Pos Y is max speed, if speed goes above then you may want to transition into another animation.

Choose Blend Type and Parameters (in Blend Tree) as in this case parameter is SPEED\_VARAIBLE.

```
GetComponent<Animator>().SetFloat(ANIMATOR_KEY, SPEED_VARAIBLE);

```

Here's the link to documentation https://docs.unity3d.com/Manual/class-BlendTree.html

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


# Question
Title: How do I get a range of vertices/edges using a half-edge data structure?
I have a half-edge data structure in 2D which loops through edges in a triangle in a clockwise order. I'm trying to get a range of vertices within a target vertex. Let's say I want all vertices within a depth of 2 like the picture below where the yellow vertex 0 is the target and the green vertices are the one's being retrieved.

So far this is what I have:

```
public List<Vertex> GetSurroundingVerts(int index)
    {
        List<Vertex> vertContainer = new List<Vertex>();
        HalfEdge startHE = Vertices[index].SourceHE;
        HalfEdge currentHE = startHE;

        vertContainer.Add(startHE.SourceVert);

        do
        {
            vertContainer.Add(currentHE.Next.SourceVert);
            currentHE = currentHE.Twin.Next;
        } while (currentHE != startHE);
        return vertContainer;
    }

```

This works for getting the immediate surrounding vertices of a target vertex but once you increase the range, using this approach for each vertex will be more expensive the larger the range is. For the example picture above we have to check 19 vertices. 19 * 6 = 114 iterations which already becomes more expensive than just using a for-loop and comparing each vertex with the target vertex.

Currently, I'm trying to see if an algorithm that can traverse through the edges in a straight direction is possible (0 to 1 to 7 to 19 to 37 in the picture below) but no luck so far.

What's the best way to go about retrieving the vertices in this situation?

# Answer
Your first approach is the best way to do this. You are getting the surrounding points, and then getting the next layer of points. This is the fastest way to make sure that you get all points depth 2 from the original vertex.

The only thing I would change is using a container like `SortedSet` instead of `Vector` because it will reduce potential overlap.
> 1 votes

---
Tags: c#, vertex
---


# Question
Title: Cascaded Shadow Maps - Handling shadows that cast into different cascades
For example I have 3 shadow cascades. A shadow is cast by a hill in my 2nd cascade, but the shadow itself is cast into not only the 2nd cascade but also the 1st. In the shader program, in order to locate the correct cascade, I check which bounds the Z clip space that the pixel resides within. Since the shadow was cast from the 2nd cascade, the portion of the shadow that is cast into the 1st is cut off, as shown in my image. How can I get around this? Is there something I'm missing, or is my implementation wrong?

# Answer
The 1st cascade was not showing the shadow, as pointed out by DMGregory; the depth information was not recorded. This is because the viewing position of this cascade could not see this part of the hill, because the minimum Z value of the projection was only set to the minimum Z coordinate of the subfrustum in lightspace. Solution: I have now subtracted the screenfar value from the min Z coordinate, which has solved the problem. The more difficult, but more correct solution would be to do what DMGregory suggested; extrude the sub-frustum for this cascade back toward the light until it encompasses all shadow casters.
> 0 votes

---
Tags: directx, directx11, shadows
---


# Question
Title: Is there a concept of "pasted on theme" in video games?
I've prototyped an idea and so far it's quite fun to play. However, it's still abstract and uses placeholder art. I've been thinking about a theme/story to add to the game, but I don't want to make it too obvious it was added almost as an afterthought.

There's a concept of "pasted on theme" within the board game community which basically refers to a game which is easy to reskin without redesigning some of the mechanics. I was wondering how big of an issue this is with video games (indie games in particular of course) and anything else I could do about a story for my game.

# Answer
> 6 votes
If we are talking about theme, it isn't much of an issue per se. Let us say, it is a risk. Will come back to that.

It is a good idea to prototype. And prototype until it is fun. Without final art. In fact, it is a good idea to do that *per mechanic*. So you know they are intrinsically engaging, not depending on art (e.g. it works even without music and cool graphics) and not depending on extrinsic rewards (e.g. achievements). *By the way, those prototypes might include particle effects, camera shakes and other stuff.*

---

I'll be assuming that the game has a player character, avatar of sorts. However, similar arguments would work for strategy or tactic games.

Which also remind me... Even though you would have a theme. That does not mean you need a story. At most you need an excuse. In fact, the characters are more important for players enjoyment than the lore or the worldbuilding. Just make a good player character or characters. Give them some motivation. And perhaps some opinions on the world. And give them a problem. So they have an excuse to go do whatever.

---

The risk I mentioned before can be expressed with a term "Ludonarrative Dissonance". This is a term put forth by critics, and often consider a bad thing. *To be fair, the games accused of it, still sold well, so it is not a deal breaker. Futhermore, it can be an strength of a game, for example as a tool for satire.*

The term "Ludonarrative Dissonance" is about the mechanics and the narrative working against each other. Although it isn't exactly lack of Ludonarrative Harmony, which would be having them in agreement. There is an excluded middle, where mechanics and the narrative don't work together, but don't work against each other either.

The mechanics (have incentives that) encourage a certain behavior. You can think of your rewards and progression systems as a black box that the players are testing and learning about, as they explore the mechanics. This is a way in which the game communicates what to do to the player.

Meanwhile, the game may tell or show or suggest, what behavior is correct (and I don't mean tutorial text, but narrative, character motivation, and plot). That is, the narrative and theme would inform what is "in character" for the player character to do. And thus this is another way the game communicates what to do to the player.

These are two messages that the game delivers to the player. Which may agree, complement or contradict each other.

Also consider that the player point of view is not a perfect match for the point of view of the characters in the story, and may care about different things than the character would care about in universe. One reason this might happen is because the player cares about the mechanics and rewards, which are often not diegetic and might be misaligned with the narrative.

See also:

---

One takeaway is that the game should give incentives that make the player behave as if the player cares about the thing the character cares. And should prevent or discourage the player from doing things that break the theme or the narrative.

A designer could have the character background (or at least their archetype) inform what should be easy and what should be hard for the character. Similarly, could have the intended character arc inform on what what should become easier or harder. And match the difficulty and progression of the game to those ideas. Furthermore, the designer could consider what the character wouldn't do, and either prevent them or discourage them mechanically.

However, that advice is easier if you start with narrative and theme. Since you are starting from the mechanics. And assuming you are not changing them. I suggest you think carefully about what behavior do the mechanics encourage, and then think what theme and narrative is a good fit. That is, try to reverse engineer what would be the theme and narrative that leads to the mechanics you have. A tool at your disposal is you -and play testers- can play the game. Bring what makes you think about while playing, an how it makes you feel, and give it context in the form a narrative.

*I'll remind you that realism is not important. Games don't have to pass a reality check. What you want is believability. Verisimilitude.*

Also remember that whatever mechanics you choose would put your game in a mechanic genre. While you could match any mechanic genre with any theme. Some are easier to make work. *That also means there would likely be plenty of similar games.*

# Answer
> 1 votes
This is a very subjective and context-specific question. Reskins have been common since video games first became a medium. Slapping a (sometimes only marginally) different story or theme over the same gameplay is quite common, and even the biggest of AAA studios are very guilty of this sin. Does it affect sales? Apparently, not much!

"Tacked on story" seems to be a common criticism in many forms of media. Many films have been criticized for having a thin story that seems to be little more than window dressing between action scenes or dramatic visuals. Many games (both tabletop and video) have been criticized for similar reasons.

It doesn't matter *when* you add the story. What makes it feel tacked on is how well written it is and how well it fits the game.

That said, your motivation behind adding a story may have a big impact on how well the story fits the game. If you have strong storytelling skills, have a specific vision in mind, and feel inspired to craft a story around your game, that's a good starting point.

Conversely, if you're thinking "this is just gameplay and I need to add a story for the sake of adding a story", you're starting off on the wrong foot. That attitude is exactly how we end up with so many games with throwaway narratives. Also, *developing* games and *writing stories* for games are very different skill sets, so if you're mostly a developer and don't have a background in creative writing/storytelling, you're much less likely to come up with a good story.

Story is not necessary for a game to be a great game. The original Doom and Doom II are great examples of elaborate (for their time) games with next to nothing in the way of story. Many puzzle games, arcade games, racing games, sports games, and simulation games have no story. Platformers are often light on story, though AAA platformers may have a fair number of cutscenes.

That said, a basic story is sometimes beneficial in providing *motivation* for the player. If the player feels like the game isn't going anywhere or questions why they are doing something, a bit of story can improve the experience by giving them a *reason* for doing what they're doing - for example, we're slogging through these enemies because we need to slay the villain and rescue the princess.

# Answer
> 0 votes
No, after years of on-and-off reading of Gamesutra, PaperRockShotgun and the like I have never seen a computer game criticized because of the mechanics not matching the theme. In fact, we seem to really love a new pasted-on theme to an old idea.

Current darling Hades is a standard new-style rogue-like (you die and start over, but get small bonuses each time). The new idea was that you're trying to escape from your demonic father who ridicules you each time you fail. It's just some pasted on conversations and reskins (instead of upgrading your armoury, you make better friends with the armour guy). No one cares.

The makers of fantasy-themed Clash of Clans went on to make WWII-themed Boom Beach -- a similar game but with completely redone mechanics. It got lots of praise, but never that the new mechanics were such a good match for the new theme. In fact it's been reskinned by others as far future and fantasy and no one complained.

Summoner's War has been reskinned as a Star Wars game, one with with SuperHeroes and many more. Reviews criticize and praise all sorts of things, but I've never read how the rules for summoning felt more or less Star-Wars-y.

# Answer
> 0 votes
There are some cases of games which lend themselves more to pasted-on themes than others.

For example, one genre where that works exceptionally well are slot machines. So well in fact, that two guys went so far as to automatize it: 1,500 Slot Machines Walk into a Bar: Adventures in Quantity Over Quality (seriously, watch that talk. It's hilarious!).

This theme-swapping works well in general for games with very abstract mechanics. Like Candy Crush / Bejewled. The basic match-3 formula only requires a couple symbols which look visually distinct. As long as you have that, you can put any theme on it you want and still end up with a fun and addicting game.

But it does not work so well with more representative mechanics. For example, you couldn't easily reskin a shooter with a zombie survival theme to a World War II theme without changing the gameplay, because zombies and soldiers are expected to behave very differently.

---
Tags: game-design
---


# Question
Title: using javascript canvas.context.scale resets custom font
I am making a HTML5 game using javascript with canvas. I am implementing a custom font adding `@font-face style` tag to header in the .html file, then if I set `canvas.context2D.font = "10px FONT_NAME"` it works and that part seems to work fine.

But when I scale `context2D` using `canvas.context2D.scale` I lose the font and when I try to set it again using `canvas.context2D.font = "10px FONT_NAME"` it does not work.

It is important to me to set different fonts because the game can use those in different UI or levels. How can I fix this problem?

# Answer
> 0 votes
You can draw the fonts to the canvas instead, which also helps with positioning and scale.

Use a pixel font, copy from an image of the font, letter by letter for what you want to type, then you can just scale as normal. When needing to change fonts, simply copy from a different font image.

---
Tags: javascript, html5, html-canvas
---


# Question
Title: How to design a system that allows for custom equations of movement?
I'm developing a top-down shooter and I currently have a `PhysicsSystem` which operates on `TransformComponents`. Basically, it update each component's position based on the component's velocity, etc.

However, this only allows for one type of movement. I would like to extend this by, for example, having a projectile shoot out of a weapon and then arc in a semi-circle.

My initial solution to this was to just have a `SemiCircleProjectile` component along with a `SemiCircleMovementSystem`, but this did not feel generic enough. For one, it updated positions\` directly rather than velocities, and also, I would have to create a new system and new component (and duplicate a lot of code) for every single different "equation" of motion.

Rather, I was wondering if there was a way to have a generic component such as `ParametricMovement`, and be able to supply an equation to it, and then have a `ParametricMovementSystem` be able to update that entity's position based on the equation of motion supplied.

That is, the only thing I would have to do would be to supply the equation to the component and then the generic system would process it all the same. In addition, (and I'm not sure if this is possible), I would be able to have an array of motion-modifying functions, and they would all interact and add in some way, so as to have the ability to have multiple movement-modifiers at once (for example: squiggle shot and arc-shot to make a projectile move in an arc and squiggle along the way).

My question is two-fold. One, does this sound like a good idea? And two, how might something like this be implemented? That is, should the functions set the entity's position directly? Or maybe only add to the velocity? And what sorts of parameters should this "movement equation function" take? Math is not really my strong suit. Additionally, with the "arc" example, would I be using the equation of a semi-circle: (something like `x^2 + y^2 = r^2; x >= 0`) or should I be manually calculating the angles based on `sin` and `cos`? Should the component save the previous iteration's velocity to interpolate upon it, or recalculate it every time?

Basically, I'm not the greatest at math and I'm not exactly sure how to design a system like this. An example of how to develop something like this would be much appreciated.

# Answer
> 1 votes
You don't really need physics. Here is a top down shooter example that you can learn from with code that you can also re-use. https://www.tabageos.com/examples/topDown360Shooter/ It's tile based. For arcs one would utilize geometry.

In that example the enemies are somewhat set up to be doing what you describe, for example at the bottom of the code, in the code for each enemy there is:

```
en.separate(enemies);
en.chase(this.player);
en.update();

```

You could change .chase to .circle and they would circle the player, you could change it to .wander() and they would wander. They also have the .followPath method which takes a path of points to follow. In the tabageos library the GeometricMath Class has the methods you would want for making paths, for example getHermiteCurvePath, getArcCurvePath etc.. You could use those methods and give the resulting path to the followPath method of the enemies, and have them follow whatever path.

The update method is updating velocity and the position is updated based on velocity.

The core library Classes you would want to see are GeometricMath and TravelerSkeleton, they are the base of how the enemies are moving in that example.

---
Tags: mathematics, javascript, architecture, movement, design-patterns
---


# Question
Title: How can I color each squad in another color?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SquadsGenerator : MonoBehaviour
{
    public GameObject squadPrefab;
    public int numberOfSquads;
    public int numberOfMembersInsquad;

    private GameObject squadsParent;

    private void Start()
    {
        squadsParent = GameObject.Find("Squads");
        GenerateSquads(numberOfSquads, numberOfMembersInsquad, squadPrefab);
    }

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

    }

    public void GenerateSquads(int squadsCount,
        int numberOfMembers,
        GameObject squadMemberPrefab)
    {
        for (int i = 0; i < squadsCount; i++)
        {
            GameObject newSquad = new GameObject();
            newSquad.name = "Squad " + i;
            newSquad.tag = "Squad";
            newSquad.transform.parent = squadsParent.transform;

            ColorSquads(newSquad);

            for (int x = 0; x < numberOfMembers; x++)
            {
                var go = Instantiate(squadMemberPrefab);
                go.name = "Member " + x;
                go.tag = "Squad Member";
                go.transform.parent = newSquad.transform;
            }
        }
    }

    private void ColorSquads(GameObject squad)
    {
        //Fetch the Renderer from the GameObject
        Renderer rend = squad.GetComponent<Renderer>();

        //Set the main Color of the Material to green
        rend.material.shader = Shader.Find("_Color");
        rend.material.SetColor("_Color", Color.green);

        //Find the Specular shader and change its Color to red
        rend.material.shader = Shader.Find("Specular");
        rend.material.SetColor("_SpecColor", Color.red);
    }
}

```

But now it will color all the squads in green.

I want that it will color the first squad for example in green the next squad in red the next in green and so on. green,red,green,red....

To extend the method ColorSquads to get two colors for example Color 1, Color 2 and this will set the colors switch to color each squad once in Color 1 once in Color 2.

Screenshot of the hierarchy each Squad is empty gameobject and the squad members are child of each squad.

# Answer
First I would rename the method `ColorSquads` to `ColorSquad`. After all, it changes the color of *one* squad, not of multiple. Then I would add a second parameter `color` so it takes the color which it is supposed to use for this particular squad:

```
private void ColorSquad(GameObject squad, Color color)
{
    Renderer rend = squad.GetComponent<Renderer>();
    rend.material.SetColor("_Color", color);
}

```

But now you of course need to state which color you want to use for each squad within the for-loop. And considering that your code allows any number of squads, you need to decide here which squad-number should get which color. A simple way to do that is via a switch/case:

```
switch(i) {
   case 0: ColorSquad(newSquad, Color.green); break;
   case 1: ColorSquad(newSquad, Color.red); break;
   case 2: ColorSquad(newSquad, Color.blue); break;
   case 3: ColorSquad(newSquad, Color.yellow); break;
   case 4: ColorSquad(newSquad, Color.cyan); break;
   case 5: ColorSquad(newSquad, Color.magenta); break;
   default: ColorSquad(newSquad, Color.white); break;
}

```

This will color the first 6 squads with 6 different colors and then use white for any further squads. If you want to support more squads with more colors, then modify this code accordingly.

Another option would be to make those colors configurable in the inspector of this component. Add this variable to the class:

```
public Color[] squadColors;

```

Then in the for-loop:

```
if (i < squadColors.Length) {
    // pick the color from the list
    ColorSquad(newSquad, squadColors[i]);
} else {
    // default color when you run out of colors
    ColorSquad(newSquad, Color.white);
}

```

Now you can set the squad colors in the inspector.

---

By the way: Using red and green for the two most used squads might not be the best decision, because of red/green color blindness. It affects about 10% of all genetically male people, making it the most common form of color-blindness. But that's a different question.
> 1 votes

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


# Question
Title: How to perform a sliding collision between a square and a circle?
Please point me to the duplicate if this has been asked before. I couldn't find it.

Basically, I am creating a 2d top-down game where the player is represented by a circle, and the tiles are represented by 16x16 squares. I have gotten collision detection working, such that the player cannot collide with tiles, by using the following algorithm:

```
let curPosition = player.position;
let newPosition = player.position + player.velocity;

if (canTouchPosition(newPosition.x, curPosition.y)) {
  player.position.x = newPos.x;
}

if (canTouchPosition(curPosition.x, newPosition.y)) {
  player.position.y = newPos.y;
}

if (canTouchPosition(newPosition.x, newPosition.y)) {
  player.position.x = newPos.x;
  player.position.y = newPos.y;
}

```

This works, except there's a problem. If the player is on the edge of a tile and moving to the right, I want them to slide past it, instead of getting stuck. Like so:

See how currently the circle is stuck on the corner when trying to move right? Instead I want it to slide along the corner until it is able to move freely, and then continue moving to the right. I can't quite figure this out. I figure a circle would make this easier, but if a square is instead easier to perform this operation on, maybe I'll use one of those instead? I mostly just want to get it working.

# Answer
> 0 votes
An easy way would be to think of the circle as a rectangle still, so just have a circle displayed, but still be rectangle colliding. And then instead of preventing movement, move first, holding the updated x,y somewhere that is not the final x,y, and then apply that movement if there is not collision, if there is adjust, which you're doing. But let the collision method return the point of collision, for example:

```
        this._pos.x += this._veloc.x*this._deltaTime;
        this._pos.y += this._veloc.y*this._deltaTime;

        var pgy, pgx;
        pgx = this.isLeftPushingOnMap(this._lastPos,this._pos,this._veloc,this._map,this._tw,this._th);
        if(pgx > 0) {
            this._pLeft = 1;//pushing left
            this._pos.x = pgx +1;
            this._veloc.x = 0;
        } else {

            this._pLeft = 0;
        }

        ...
        this.setX( this._pos.x );
        this.setY( this._pos.y );

```

---
Tags: 2d, collision-detection, physics, javascript, vector
---


# Question
Title: Cannot drag GameObject into exposed field in the Inspector
I followed the Brackeys' *How to make a health bar* tutorial on YouTube, and it worked perfectly when playing around with the sliders myself. But, when I tried to drag the health bar object into the script's exposed attribute in the Inspector (like Brackeys does at 10:14 in the video), but it won't let me drag it in. I followed the tutorial exactly as shown, but it still won't work. Can anyone explain why and/or how to fix it?

**The script for the player stamina:**

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

public class PlayerStamina : MonoBehaviour
{
    public int maxPlayerStamina = 100;
    public int currentPlayerStamina;

    public int leftMouseStaminaDrain = 20;
    public int rightMouseStaminaDrain = 35;

    public StaminaBar staminaBar;

    // Start is called before the first frame update
    void Start()
    {
        currentPlayerStamina = maxPlayerStamina;
        staminaBar.SetMaxStamina(maxPlayerStamina);
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.G))
        {
            LoseStamina(20);
        }
        if (Input.GetKeyDown(KeyCode.Mouse0))
        {
            LoseStamina(leftMouseStaminaDrain);
        }
        if (Input.GetKeyDown(KeyCode.Mouse1))
        {
            LoseStamina(rightMouseStaminaDrain);
        }
    }

    void LoseStamina(int staminaDrain)
    {
        currentPlayerStamina -= staminaDrain;

        staminaBar.SetStamina(currentPlayerStamina);
    }
}

```

**The script for the stamina slider:**

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

public class StaminaBar : MonoBehaviour
{
    public Slider slider;

    public void SetMaxStamina(int stamina)
    {
        slider.maxValue = stamina;
        slider.value = stamina;
    }

    public void SetStamina(int stamina)
    {
        slider.value = stamina;
    }
}

```

# Answer
> 0 votes
You have a GameObject called `StaminaBar`, but you are not showing if that GameObject has the `StaminaBar` Component attached to it. Please double-check if you actually dragged the `StaminaBar` script to your `StaminaBar` GameObject inside the Inspector, and try again to drag the GameObject to the field exposed by your GameObject containing the `PlayerStamina` class. This is mandatory because the script is looking for a GameObject with a `StaminaBar` component attached to it, otherwise it won't let you perform the drag & drop.

# Answer
> 0 votes
Maybe try using the circle button beside the bar where we put in the slider and choose it. Also it would be nice if you could post the code you used for the StaminaBar class, as there might be an issue there.

# Answer
> 0 votes
Your `PlayerStamina` script exposes a field of type `StaminaBar`, meaning that you can assign any GameObject with a `StaminaBar` Component to it. But, you *cannot* assign a GameObject that doesn't have such a Component, even if one of its children has it instead.

In order to drag the **StaminaBar** GameObject into the exposed field, make sure **StaminaBar** *does* have the `StaminaBar` Component itself. I try to guess that **StaminaBar** is an empty GameObject that contains the *actual* GameObject with a `StaminaBar` Component. This setup may be desirable for *ad-hoc* UI displacement with anchors. In this case, try and drag the child GameObject in the exposed field in the Inspector instead of its parent.

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


# Question
Title: Enable SteamVR hand collision for when holding objects
Just getting started on a game project with SteamVR in Unity. I've run into an issue with the collisions though. The hands and the objects that can be held collide with everything in the scene as they should. But when an object is picked up, the hand and the object stop colliding with everything.

How would I go about fixing this? I *could* leave it as is, but if an object is let go of inside another, it gets flung out of the object it was inside.

The other odd behavior happens after you let an item go. The hand that was holding it continues to not collide with anything until you move the hand away. After that it'll collide with everything normally again.

# Answer
It sounds like the colliders used in detecting hand-object intersection may be temporarily disabled whilst holding an object. This may be part of SteamVR's interaction script logic. I don't recall off the top of my head how the latest SteamVR rig operates; however, within the SteamVR rig hierarchy, I would take a look at the specific script components that react via OnTriggerEnter(), such as any "on grab" logic, and see how they act on colliders they reference. There should be a script API within SteamVR's rig package where you can register a listener to an "on grab" event. You can use this to troubleshoot, or enable/disable your own custom colliders used specifically to handle any further collisions on held objects. Ideally, studying SteamVR's API and interaction scripts will inform you about what happens to hand colliders OnTriggerEnter (they will likely have a Rigidbody component attached to them in the prefab hierarchy, likely set to be kinematic).

As for objects getting flung out from inside another: it sounds like both objects in question may be non-trigger colliders. Trigger colliders can pass through one another (assuming no additional script logic acts on them to do otherwise), whereas non-trigger colliders will separate upon impacting one another, preventing sustained intersection. A bouncy ball for instance can be realized with a rigidbody component using gravity and a non-trigger sphere collider, such that it bounces away from a non-trigger floor collider upon impact, producing an OnCollisionEnter() event. If the ball were a trigger collider instead, it would invoke an OnTriggerEnter() event upon passing through the floor collider, but it would continue falling through it.

In your case, it may be that a non-trigger collider is placed inside another via SteamVR's "object hold" interaction script, allowing for such placement during an object grab and hold (perhaps due to it disabling the object's collider component temporarily), but restoring non-trigger collision behaviour on the object upon its release, causing the released object to fly out.
> 0 votes

# Answer
The issue was that the hand colliders were getting disabled when an object was picked up, and would only re-enable when it completely left the area around original collider (Which wasn't working properly apparently). I tweaked it a little and now it works!

Fixed version here (HandPhysics.cs): https://pastebin.com/wXQvsLEY
> 0 votes

# Answer
I had this issue, by getting something "lose" by colliding to it with an held stick. I solved this issue by using an OnTriggerEnter logic instead of Collision logic. however, I don't know your use case.
> 0 votes

---
Tags: unity, steam-vr
---


# Question
Title: How do I track 2 lights in real time with a camera and send it to a phone in Unity?
I am trying to track 2 lights and send that data to Unity for VR controller tracking. How do I get started? Do I make an app that communicates with Wifi or something? And how do I detect the lights? OpenCV seems complicated. I will have a 3DOF IMU in the controllers and a big orb so it will be kind of like a Playstation Move but with a normal webcam. I will use the lights combined with the rotational data to figure out the position.

---

For other people to know, I will use the Processing video library to recognize the lights and OSCP5 to send it to Unity.

# Answer
> 1 votes
You have a few high-level tasks:

* Detect The position of the lights relative to the camera
* Convert that location into "world" space
* Transmit it to the device
* Do it all **Fast**

Looking at each in turn:

### Detect the position of the lights

I'm not entirely clear what hardware will be doing this? Desktop PC with a webcam?

Assuming so, then yes, you're going to need to do some image analysis. OpenCV is a solid option although there are alternatives. Many professional positional controllers

Your biggest issue is that a single camera *almost* doesn't have enough information to locate an object in 3D space.

Let's say you detect the object is 15° left of center on the °0 above horizontal.

There are an infinite number of points which meet those criteria, all on a line pointing out from your camera.

So you also need to detect *where* on the line that is.

Some systems like Oculus use multiple cameras, others (like Kinect) us a depth-sensor.

You *could* potentially factor in the known size of the controller but you'd likely need to calibrate on a per-webcam basis as each lens will have a slightly different FoV and optical properties.

If using multiple cameras, you need to know their position relative to each other, then cross-reference the "lines" you get from each. The place they \[almost\] intersect is where your controller is.

### Convert to world space

So now you've got a Vector2 relative to a couple of cameras \[or single camera w/ depth info\].

You now need to convert that into the same worldspace as the VR simulation.

To do that you'll need some basic trigonometry and a way of reading the VR world coordinate system \[so you know how to map/transform the position information\]

### Transmit to device

As to how to get the data back to the device running the VR simulation... It depends what the webcam is connected to.

Your default option should always be a wired connected. LAN is far better throughput than Wifi and has lower inherent latency. Custom cables (like a Serial cable) would potentially be even faster. Likewise you might be able to communicate over a USB protocol at an acceptable rate.

### Do it all **Fast**

So the big issue is latency. The longer the delay between controller movement and response in the simulation, the less immersive/believable it will be.

Ideally you want to have latencies from movement to pixel updates on the order of 10s of milliseconds.

Whatever process you pick needs to be iterating rapidly and each of the above steps is going to require some level of processing/waiting, so you need to steal as much time and performance as you can at each step of the process.

---
Tags: unity, camera, unity-networking
---


# Question
Title: How do you make html elements not blurry
I was making a html game and all the elements are blurry is there a fix to this? I use css but it makes it blurry

**Code**

```
 <!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
    border:1px solid #d3d3d3;
    background-color: #f1f1f1;
    width:  75%;
  height: 75%;
  margin: 0;
}
</style>
</head>
<body onload="startGame()">
<script>

var myGamePiece;
var myObstacles = [];
var myScore;

function startGame() {
    myGamePiece = new component(30, 30, "red", 10, 120);
    myGamePiece.gravity = 0.05;
    myScore = new component("30px", "Consolas", "black", 280, 40, "text");
    myGameArea.start();
}

var myGameArea = {
    canvas : document.createElement("canvas"),
    start : function() {
        this.canvas.width = 480;
        this.canvas.height = 270;
        this.context = this.canvas.getContext("2d");
        document.body.insertBefore(this.canvas, document.body.childNodes[0]);
        this.frameNo = 0;
        updateGameArea();
        },
    clear : function() {
        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    }
}

function component(width, height, color, x, y, type) {
    this.type = type;
    this.score = 0;
    this.width = width;
    this.height = height;
    this.speedX = 0;
    this.speedY = 0;
    this.x = x;
    this.y = y;
    this.gravity = 0;
    this.gravitySpeed = 0;
    this.update = function() {
        ctx = myGameArea.context;
        if (this.type == "text") {
            ctx.font = this.width + " " + this.height;
            ctx.fillStyle = color;
            ctx.fillText(this.text, this.x, this.y);
        } else {
            ctx.fillStyle = color;
            ctx.fillRect(this.x, this.y, this.width, this.height);
        }
    }
    this.newPos = function() {
        this.gravitySpeed += this.gravity;
        this.x += this.speedX;
        this.y += this.speedY + this.gravitySpeed;
        this.hitBottom();
        this.hitTop();
    }
    this.hitBottom = function() {
    var rockbottom = myGameArea.canvas.height - this.height;
    if (this.y > rockbottom) {
        this.y = rockbottom;
        this.gravitySpeed = 0;
    }
} // This curly brace was missing.

this.hitTop = function() {
    var skyhigh = 0;          // Top of the window.
    if (this.y < skyhigh) {   // Use less-than to check if you're above.
        this.y = skyhigh;
        this.gravitySpeed = 0;
    }
}
    this.crashWith = function(otherobj) {
        var myleft = this.x;
        var myright = this.x + (this.width);
        var mytop = this.y;
        var mybottom = this.y + (this.height);
        var otherleft = otherobj.x;
        var otherright = otherobj.x + (otherobj.width);
        var othertop = otherobj.y;
        var otherbottom = otherobj.y + (otherobj.height);
        var crash = true;
        if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
            crash = false;
        }
        return crash;
    }
}

function updateGameArea() {
    var x, height, gap, minHeight, maxHeight, minGap, maxGap;
    for (i = 0; i < myObstacles.length; i += 1) {
        if (myGamePiece.crashWith(myObstacles[i])) {
            return;
        }
    }
    myGameArea.clear();
    myGameArea.frameNo += 1;
    if (myGameArea.frameNo == 1 || everyinterval(150)) {
        x = myGameArea.canvas.width;
        minHeight = 20;
        maxHeight = 200;
        height = Math.floor(Math.random()*(maxHeight-minHeight+1)+minHeight);
        minGap = 50;
        maxGap = 200;
        gap = Math.floor(Math.random()*(maxGap-minGap+1)+minGap);
        myObstacles.push(new component(10, height, "green", x, 0));
        myObstacles.push(new component(10, x - height - gap, "green", x, height + gap));
    }
    for (i = 0; i < myObstacles.length; i += 1) {
        myObstacles[i].x += -1;
        myObstacles[i].update();
    }
    myScore.text="SCORE: " + myGameArea.frameNo;
    myScore.update();
    myGamePiece.newPos();
    myGamePiece.update();
}

function everyinterval(n) {
    if ((myGameArea.frameNo / n) % 1 == 0) {return true;}
    return false;
}

function accelerate(n) {
    if (!myGameArea.interval) {myGameArea.interval = setInterval(updateGameArea, 20);}

    myGamePiece.gravity = n;
}
</script>
<br>
<button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.05)">ACCELERATE</button>
<p>Click the ACCELERATE button to start the game</p>
<p>How long can you stay alive? Use the ACCELERATE button to stay in the air..</p>
</body>
</html>

```

# Answer
Crisp edges css may help. And drawing pixel text from a sprite sheet will be the most crisp vs fillText.

```
   canvas {
       image-rendering: -moz-crisp-edges;image-rendering: -webkit-crisp-edges;image-rendering: pixelated;image-rendering: crisp-edges;
       border:1px solid #d3d3d3;
       background-color: #f1f1f1;
       width:  75%;
       height: 75%;
       margin: 0;
   }

```
> 0 votes

---
Tags: javascript, html5, html, css
---


# Question
Title: How to run a DOTween tween on float and apply it to a component on each update?
I am trying to use DOTween by tweening a float and then applying that float to the parameters of a gameObject's components on each update.

In LeanTween, this was done like this:

```
LeanTween.value(gameObjectIn, 0f, 1f, 3f).setEase(LeanTweenType.easeInOutQuad).setDelay(0f).setOnUpdate((float val) => {
            gameObjectIn.GetComponent<Image>().color = new Color32(255, 255, 255, (byte)(val * 255));
        });

```

Or alternatively:

```
var seq = LeanTween.sequence();
        seq.append(LeanTween.value(gameObjectIn, 0f, 1f, 3f).setEase(LeanTweenType.easeInOutQuad).setDelay(0f).setLoopPingPong().setOnUpdate((float val) => {
            gameObjectIn.GetComponent<Image>().color = new Color32(255, 255, 255, (byte)(val * 255));
        }));

```

I have tried doing something similar with DOTween like this:

```
float valueToTween = 0f;
DOTween.To(() => valuetoTween, x => valuetoTween = x, 1, 1).onUpdate((valuetoTween) => {
            gameObjectIn.GetComponent<Image>().color = new Color32(255, 255, 255, (byte)(valuetoTween * 255)); }
            );

```

However, this is not working. It says regarding `onUpdate`: `Delegate TweenCallback does not take 1 arguments.`

I am not that good with C# to figure out what exactly is wrong. How would I do this basic task? ie. Tween a float and on each update run a few lines of script using that float without having a second function defined/stored outside of this code?

The syntax for DOTween tweens is listed here: http://dotween.demigiant.com/documentation.php

Thanks

---

***Addendum:***

As per the comments I tried also setting a separate function:

```
private static void callbackTest(float paramIn, GameObject gameObjectIn){
gameObjectIn.GetComponent<Image>().color = new Color32(255, 255, 255, (byte)(paramIn * 255));
}

```

and then in my other function:

```
private static void startTween(GameObject gameObjectIn){
float valueToTween = 0f;
DOTween.To(() => valuetoTween, x => valuetoTween = x, 1, 1).onUpdate(() => callbackTest(valueToTween, gameObjectIn));
}

```

But this similarly gives the same error and is just less efficient because I need to maintain separate functions.

# Answer
> 1 votes
The problem was you need to use OnUpdate not onUpdate within DOTween - these are two similar sounding but different functions.

---
Tags: unity, c#, tweening, dotween
---


# Question
Title: Minimax in a losing scenario vs an imperfect player
I'm working on a solver for Triple Triad, a simple two-player zero-sum card game. Right now, I'm using Negamax (a variant of the well-known Minimax algorithm) with alpha beta pruning, and the game is simple enough that I can usually explore the entire search tree in a reasonable amount of time. I have it working, but I'm running into an interesting problem: in many cases, if A's deck is much better than B's, then no matter what move B makes first, A can always win with perfect play.

But in this game, normally you play against an opponent who doesn't actually make perfect plays. I'm trying to think of a way to still optimize for B to make the move that gives them the best chance of winning. Right now my best idea is essentially:

1. Use Negamax search to try to select your best move. Instead of finding *one* best move, find *all* moves with the highest score.
2. For each possible move with the highest score, apply that move and simulate a large number of games with random play by both players for the remainder of the game. Select the move in which you won the largest number of games.

Heuristics could be applied to the Monte-Carlo search to make certain moves more likely based on their immediate outcome.

Are there any well-known algorithms for this type of problem - a problem where you want to maximize your odds of winning a losing game versus a sub-optimal opponent? Are there any obvious problems I'm missing with my proposed solution?

# Answer
I ended up implementing and testing the Monte-Carlo method I described in my question, and it seems to work quite well as a tiebreaker for the Negamax search.

Here's some details and thoughts about the implementation:

* I ended up simulating 100k games for each tiebreak. I started with 10k, but didn't quite get the consistent results; with 100k, the output was the same every time I tested it.
* The simulation I went with is purely random - on each player's "turn", it gathers a list of all possible moves and randomly chooses one.
* Since ties are possible, when counting up the results of the simulations, I assigned values of 1 for a win, 0.3 for a tie, and 0 for a loss, and averaged those values across all the simulations, selecting the outcome with the maximum average value. These selections were arbitrary and different values might have significant improvements on performance.
* Performance: Using parallelization following the general Map-Reduce strategy (thanks to the Rayon library), I could run 50-60 Monte-Carlo simulations (each with 100k iterations) in about 1 second on my Ryzen 3700x. This is comparable to the time it takes to search the game tree itself (about 1.8 seconds from an empty board). Disabling that concurrency made the same simulations take about 10 seconds.
* The simulation leads to plays that seem to be "good", from the perspective of a human who also plays the game. For example, the overall algorithm now plays cards with high numbers facing inwards and low numbers facing towards the edges, which is basic good strategy in the game.
> 1 votes

---
Tags: ai, game-theory
---


# Question
Title: How to handle octave & frequency in the Perlin noise algorithm?
I would like to implement a Perlin noise algorithm into my MonoGame project in order to procedurally generate 2D terrain. I've been using engines in the past (Godot, mostly) where there was an API to call, we would set the seed, the octave and frequency to have the wanted noise.

Problem is, in the clean implementations I gathered online, I don't know where I'm supposed to tweak the parameters of the noise.

For instance, with this one implementation that seems to be well-written: how to handle tweaking with octaves & frequency?

Or, with a simpler and shorter code, here with the pseudo-code of the original algorithm.

Thanks!

# Answer
These functions compute a single octave of noise.

To layer noise into something like Fractional Brownian Motion (FBM), you can invoke one of these functions multiple times.

Let's say I have a noise function like `EvaluateNoise(float x, float y)`

The number of octaves determines how many times I call that function. The frequency determines a scaling value I apply to my x,y values before calling it. In addition to this we'll usually have persistence and lacunarity parameters, determining how the amplitude should diminish and frequency increase as we drop down the octaves. Something like...

```
float EvaluateFBM(float x, float y,
                  float amplitude, float frequency,
                  int octaveCount, float persistence, float lacunarity) {

    float value = 0;

    for (int i = 0; i < octaveCount; i++) {
        value += amplitude * EvaluateNoise(x * frequency, y * frequency);
        amplitude *= persistence;
        frequency *= lacunarity;
    }

    return value;
}

```

Persistence (also called gain) is a value in the range (0, 1) that controls how quickly the later octaves "die out". Something around 0.5 is pretty conventional here.

Lacunarity is a value greater than 1 that controls how much finer a scale each subsequent octave should use. Something around 2.0 is a conventional choice.

You may also want to apply an offset to x/y/z at each octave to decorrelate the layers, so you don't see repeated features constructively interfering when you're close to zero.

You can modify this function in various ways to get things like turbulence or ridge noise, IQ Noise, Swiss or Jordan Turbulence, or other custom terrain styles.
> 1 votes

---
Tags: c#, monogame, procedural-generation, perlin-noise
---