title: Why do edges make the player jump?

text:
# Question
Title: Why do edges make the player jump?
I'm making a 2D platformer with Unity and I have a problem with platform edges.

This problem is usually visible in the situation where I want the player to walk up the stairs by jumping, but the problem is, it can climb the stairs by just moving, not jumping. This means that the edges make the player jump, so it can jump higher and higher when collides with edges. I have this problem with almost all objects that player should jump on.

This looks like a bug to me. I've been searching for the answer and all the existing answers are related to a situation where the player is stuck on the edge and can't move anymore, which I realized that sometimes can happen but a little bit different than that scenarios. In this situation, the player freezes in the air after jumping and sticks to the platform, while I'm not holding the move button.

I tried adding a physics material and using zero friction but it didn't work. My player has a `CapsuleCollider2D` and the stairs object has a `PolygonCollider2D`. The player script inherits from a `PhysicsObject` script which handles the game physics. (Maybe this script is the root of the problem).

Player script (this script is so long, so I deleted the parts that were unrelated to this problem):

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

public class NewPlayer : PhysicsObject
{
    [Header("Attributes")]
    [SerializeField] private float jumpPower = 10;
    [SerializeField] private float maxSpeed = 1;
    [SerializeField] private float fallForgiveness = 1; //This is the amount of seconds the player has after falling from a ledge to be able to jump
    [SerializeField] private float fallForgivenessCounter; //This is the simple counter that will begin the moment the player falls from a ledge
    bool isFacingLeft;

    void Update()
    {
        targetVelocity = new Vector2(Input.GetAxis("Horizontal") * maxSpeed, 0);

        //If the player is no longer grounded, begin counting the fallForgivenessCounter
        if (!grounded)
        {
            fallForgivenessCounter += Time.deltaTime;
        }
        else
        {
            fallForgivenessCounter = 0;
        }

        //If the player presses "Jump" and we're grounded, set the velocity to a jump power value
        if (Input.GetButtonDown("Jump") && fallForgivenessCounter < fallForgiveness)
        {
            velocity.y = jumpPower;
            grounded = false;
            fallForgivenessCounter = fallForgiveness;
        }

        //Flip the player's localScale.x if the move speed is greater than .01 or less than -.01
        if (isFacingLeft)
        {
                transform.localScale = new Vector2(Mathf.Abs(transform.localScale.x) * -1, transform.localScale.y);
        }
        else
        {
            transform.localScale = new Vector2(Mathf.Abs(transform.localScale.x), transform.localScale.y);
        }
    }
}

```

Physics Object script:

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

public class PhysicsObject : MonoBehaviour
{

    [Header("Physics Object Attributes")]
    public float minGroundNormalY = .65f;
    public float gravityModifier = 1f;

    protected Vector2 targetVelocity;
    protected bool grounded;
    protected Vector2 groundNormal;
    protected Rigidbody2D rb2d;
    protected Vector2 velocity;
    protected ContactFilter2D contactFilter;
    protected RaycastHit2D[] hitBuffer = new RaycastHit2D[16];
    protected List<RaycastHit2D> hitBufferList = new List<RaycastHit2D>(16);

    protected const float minMoveDistance = 0.001f;
    protected const float shellRadius = 0.01f;

    void OnEnable()
    {
        rb2d = GetComponent<Rigidbody2D>();
    }

    void Start()
    {
        contactFilter.useTriggers = false;
        contactFilter.SetLayerMask(Physics2D.GetLayerCollisionMask(gameObject.layer));
        contactFilter.useLayerMask = true;
    }

    void Update()
    {
        targetVelocity = Vector2.zero;
        ComputeVelocity();
    }

    protected virtual void ComputeVelocity()
    {

    }

    void FixedUpdate()
    {
        velocity += gravityModifier * Physics2D.gravity * Time.deltaTime;
        velocity.x = targetVelocity.x;

        grounded = false;

        Vector2 deltaPosition = velocity * Time.deltaTime;

        Vector2 moveAlongGround = new Vector2(groundNormal.y, -groundNormal.x);

        Vector2 move = moveAlongGround * deltaPosition.x;

        Movement(move, false);

        move = Vector2.up * deltaPosition.y;

        Movement(move, true);
    }

    void Movement(Vector2 move, bool yMovement)
    {
        float distance = move.magnitude;

        if (distance > minMoveDistance)
        {
            int count = rb2d.Cast(move, contactFilter, hitBuffer, distance + shellRadius);
            hitBufferList.Clear();

            for (int i = 0; i < count; i++)
            {
                PlatformEffector2D platform = hitBuffer[i].collider.GetComponent<PlatformEffector2D>();
                if (!platform || (hitBuffer[i].normal == Vector2.up && velocity.y < 0 && yMovement))
                {
                    hitBufferList.Add(hitBuffer[i]);
                }
            }

            for (int i = 0; i < hitBufferList.Count; i++)
            {
                Vector2 currentNormal = hitBufferList[i].normal;
                if (currentNormal.y > minGroundNormalY)
                {
                    grounded = true;
                    if (yMovement)
                    {
                        groundNormal = currentNormal;
                        currentNormal.x = 0;
                    }
                }

                float projection = Vector2.Dot(velocity, currentNormal);
                if (projection < 0)
                {
                    velocity = velocity - projection * currentNormal;
                }

                float modifiedDistance = hitBufferList[i].distance - shellRadius;
                distance = modifiedDistance < distance ? modifiedDistance : distance;
            }

        }

        rb2d.position = rb2d.position + move.normalized * distance;
    }
}

```

As you can see, the player just jumps once or twice and then automatically goes up only by moving forward. At that point, I was just holding the right arrow key on the keyboard.

# Answer
> 0 votes
I wasn't able to find the root cause of this problem, but I found a way to prevent it and that is using a **Box Collider 2D** instead of a Capsule Collider 2D for the player. This solved the problem for me.

---
Tags: unity, c#, physics, platformer
---


# Question
Title: Unreal Engine 4 AI Character Pawn Entirely Unresponsive to Movement Commands
I'm new to game development and to Unreal but I cannot for the life of me get my AI character pawn to move at all using any method I know.

I'm developing a 2d Sidescroller game using a Tilemap. I have made sure collision is set up with the map and tiles, the player character can interact with it all just fine, and I made sure to widen the collision thickness of the map so that the navmesh can properly appear (as seen with the green areas).

Nav Mesh loading. AI spawns in the air and falls down so I know he isn't overlapping with the ground

I've disabled and enabled collision for the static mesh cube component in the character pawn, but he still doesn't move. The goal is to get him to follow the player when he sees him. The pawnsensing trigger works just fine, as I had it print whenever he sees him, and he even properly gets to the point of executing the "follow player" function (the print statement works).

However, using AIMoveTo fails every time. I've tried putting the player as the target, the player's worldLocation as a vector, and even an arbitrary point vector to the right of the AI but AIMoveTo fails every time.

I've deleted and replaced the NavMesh, and I've even tried completely skipping using AIMoveTo and just using Add Movement Input in both the AI Thinking Blueprint and Character Pawn Blueprint but neither make it move. I literally put an Add Movement Input function on the Pawn's event tick but it never moves.

Any suggestions?

Code: AI Logic event is triggered every tick

Character Pawn Tick (for debugging). Does not cause the Pawn to move

# Answer
To move the AI on a navmesh, you need a behaviour tree, a blackboard and an AI controller (BP).

At the AI Controller you need to run the behaviour tree:

In the BehaviourTree you need a new custom task and move to:

In the BehaviourTree you can create a new task; in the task, you need to set a blackboard value, which is editable:

And in the blackboard you need a new key which is edited by the task:

And the AI controller must be the controller of your BP\_Character in the Details.

Hope this helps you :)
> 0 votes

---
Tags: movement, ai, unreal
---


title: Lerp Teleporting In Unity

text:
# Question
Title: Lerp Teleporting In Unity
I am trying to make a object move back and fourth but its teleporting instead of moving smoothly. This is my code.

```
void Start()
{
    StartCoroutine(timer1());
}

IEnumerator timer1()
{
    yield return new WaitForSeconds(3);

    Vector3 a = transform.position;
    Vector3 b = target.position;
    transform.position = Vector3.Lerp(a, b, t);

    StopCoroutine(timer1());
    StartCoroutine(timer2());
}

IEnumerator timer2()
{
    yield return new WaitForSeconds(3);

    Vector3 A = transform.position;
    Vector3 B = target2.position;
    transform.position = Vector3.Lerp(A, B, t);

    StopCoroutine(timer2());
    StartCoroutine(timer1());
}

```

}

# Answer
> 0 votes
Wait for 3 seconds means: put the object here; do nothing for 3 seconds; now move it over there. Teleport, if you like.

To get smooth movement you have to update the position of the object every frame. You don't need a coroutine to do that, just update the position in the Update() callback. The Unity docs have plenty of examples eg https://docs.unity3d.com/ScriptReference/Vector3.Lerp.html.

# Answer
> 0 votes
You're making the common beginner error of believing that "Lerp" is a tweening function, ie. that you can invoke Lerp once and it will act on an object over a period of time, moving it until it reaches a destination.

Lerp does not do *anything* like that at all. It's just a math function that accepts some numbers/vectors and returns a different number/vector. Note that you don't even pass it a reference to the thing that should be moved, so there's no way it could do what you're trying to use it to do.

If you want to move something with Lerp, you need to have a loop that runs every frame, calculates a new position for that one frame using Lerp, and moves the object to that position. Something like this:

```
// Start a coroutine the first frame this script is enabled:
IEnumerator Start() {
   // Loop forever.
   while (true) {
       // Chain execution to the MoveTo coroutine, until it finishes.
       yield return MoveTo(target.position, 3);

       // Once it's done, chain execution to the MoveTo coroutine again,
       // moving to the other target, until the coroutine finishes.
       yield return MoveTo(target2.position, 3);

       // Return to the top of the loop to move back to the first target.
   }
}

// Move toward a destination point over a given time interval.
IEnumerator MoveTo(Vector2 destination, float duration) {
    // Remember where we started from.
    Vector2 start = transform.position;

    // Control how fast we move.
    float speed = 1f/duration;

    // Loop until we progress from 0% all the way to 100%
    // of our duration, storing the current progress in t.
    for (float t = 0; t < 1; t += Time.deltaTime * speed) {
        // Calculate a new in-between point for this frame, and move there.
        transform.position = Vector2.Lerp(start, destination, t);

        // Wait until next frame before resuming the loop.
        yield return null;
    }

    // Finish exactly at the destination (the last loop execution
    // ran when t was still slightly less than 100% of the way there).
    transform.position = destination;

    // No need to call StopCoroutine, we can just hit the end of the function.
}

```

Examples like this are *everywhere* \- I've written several myself on this site alone. So please do a bit more research in future to make use of the wealth of Unity code examples that are out there. If you do, you'll find you're often able to fix your own problems, faster.

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


# Question
Title: Swipe to move script does not move exactly one unit
I am currently trying left & right, up & down swipe motion in unity C#.

I have done the scripting, it all working,

but after I debug the script, the object's position suddenly changed to a very weird number:

from (-3, 0, 3) changed to (-3.000004, 0.00000464, 2.99999).

And I intend to move **just 1 unit** every time i swipe, but the unit seems different; it always move around 1 but not exact 1 (Ex: maybe like 0.9954, or like 1.002931).

How I set the initial position to be an exact integer number, and also move only 1 unit every time I swipe?

```
  using UnityEngine;

    public class Player : MonoBehaviour
    {
        private Vector3 startTouchPosition, endTouchPosition;
        private Vector3 startRocketPosition, endRocketPosition;
        private float flyTime;
        public float speed = 1f;
        bool canMove;

        void Start()
        {
            transform.position = new Vector3(-3, 0, 3);
        }

        void Update()
        {
            if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
            {
                startTouchPosition = Input.GetTouch(0).position;
            }
            if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended)
            {
                endTouchPosition = Input.GetTouch(0).position;

                float xDifference = Mathf.Abs(endTouchPosition.x - startTouchPosition.x);
                float yDifference = Mathf.Abs(endTouchPosition.y - startTouchPosition.y);

                if ((endTouchPosition.x < startTouchPosition.x) && xDifference >= yDifference && transform.position.x > -5.5f)
                {
                    //StartCoroutine(Fly("left"));
                    MoveLeft();
                }
                else if ((endTouchPosition.x > startTouchPosition.x) && xDifference >= yDifference && transform.position.x < -0.5f)
                {
                    //StartCoroutine(Fly("right"));
                    MoveRight();
                }
                else if ((endTouchPosition.y > startTouchPosition.y) && yDifference >= xDifference && transform.position.z < 5.5f)
                {
                    //StartCoroutine(Fly("up"));
                    MoveUp();
                }
                else if ((endTouchPosition.y < startTouchPosition.y) && yDifference >= xDifference && transform.position.z > 0.5f)
                {
                    //StartCoroutine(Fly("down"));
                    MoveDown();
                }
            }
            if (canMove)
            {
                transform.position = Vector3.Lerp(startRocketPosition, endRocketPosition, speed * Time.deltaTime);
                canMove = false;
            }
        }

        {
            startRocketPosition = transform.position;
            endRocketPosition = new Vector3(startRocketPosition.x - 10f, 0, transform.position.z);
            canMove = true;
        }
        void MoveRight()
        {
            startRocketPosition = transform.position;
            endRocketPosition = new Vector3(startRocketPosition.x + 10f, 0, transform.position.z);
            canMove = true;
        }
        void MoveUp()
        {
            startRocketPosition = transform.position;
            endRocketPosition = new Vector3(startRocketPosition.x, 0, transform.position.z + 10f);
            canMove = true;
        }
        void MoveDown()
        {
            startRocketPosition = transform.position;
            endRocketPosition = new Vector3(startRocketPosition.x, 0, transform.position.z -10f);
            anMove = true;
        }

```

# Answer
This code:

```
if (canMove)
{
     transform.position = Vector3.Lerp(startRocketPosition, endRocketPosition, speed * Time.deltaTime);
     canMove = false;
}

```

...tries to move your object in a single frame. After it's run once, it sets `canMove` to false so now it doesn't continue the motion next frame. This doesn't make sense when using `Lerp` and `deltaTime`.

In this single frame, it tries to move to some ratio of the way between start and end, given by `speed * Time.deltaTime`. But if speed is in `m/s` then this is `m/s * s = m`, ie. you're calculating a distance here, where you're meant to provide a ratio, so your units don't make sense.

If your speed is close to 3 and your game is running at about 30 fps, then this will come out to some number close to 0.1, but not exactly. So when you try to move a fraction of 0.1 of the way between start and end (which are 10 units apart), you get a travel of almost 1 unit, but not exactly. On longer frames you'll overshoot, and on shorter frames you'll undershoot.

Basically: the code you've written does not make any logical sense for the behaviour you want from it. I would rewrite this from scratch, to reduce repetition and improve the behaviour.

```
public float travelDistance = 1f;
public float speed = 1f;

Coroutine movementInProgress;

void Update()
{
    if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
    {
        startTouchPosition = Input.GetTouch(0).position;
    }
    if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended)
    {
        endTouchPosition = Input.GetTouch(0).position;
        movementInProgress = StartCoroutine(Slide(endTouchPosition - startTouchPosition));
    }
}

IEnumerator Slide(Vector3 swipe) {
    Vector3 startPosition = transform.position;
    Vector3 endPosition = transform.position;

    if(Mathf.Abs(swipe.y) > Mathf.Abs(swipe.x)) {
        endPosition.z += Mathf.Sign(swipe.y) * travelDistance;
    } else {
        endPosition.x += Mathf.Sign(swipe.x) * travelDistance;
    }

    // m / m/s = s, so our unit cancellation confirms we've calculated a duration.
    float slideDurationSeconds = travelDistance / speed;

    // Now our increment's units are s / s = 1:
    // all units cancel out, and we're left with a radio, as Lerp expects.
    for(float t = 0f; t < 1f; t += Time.deltaTime / slideDurationSeconds) {
        transform.position = Vector3.Lerp(startPosition, endPosition, t);
        yield return null;
    }

    transform.position = endPosition;
    movementInProgress = null;
}

```

If you want to inhibit a new slide from starting until the previous slide has finished, you can add a check `if(movementInProgress == null)` before starting a new slide.
> 0 votes

# Answer
Those funny values are rounding errors. When you do arithmetic on float values you get float results, perhaps near to integers but not quite.

For most purpose they can be ignored. It seems from your code you have other problems to solve. If you really really want integer values use `Mathf.Round()`.
> 0 votes

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


# Question
Title: What is the purpose of tangent and bitangent vertex attributes?
Every vertex of a 3D mesh has position and some optional values like texture coordinates, vertex color, and normal, but also tangent and bitangent vectors.

While the purposes of texture coords, vertex color, and normal are pretty clear, I'm not understanding what tangent and bitangent vectors should be good for.

I am not asking about the mathematical definition, as I know that tangent and bitangent are vectors orthogonal to the normal and to each other.

# Answer
> 5 votes
Tangent and bitangent vectors are used for **tangent space normal mapping / lighting** and certain forms of **displacement mapping**.

In a **tangent space normal map**, we store the per-pixel normal in the colours of a texture pixel, expressed in the mesh's **tangent space at** that point. The usual convention is that the blue channel represents the mesh normal direction, pointing straight out from the surface, the red channel represents the tangent direction, pointing rightward along the texture map, and the green channel represents the bitangent direction, pointing upward along the texture map, according to the UV mapping used for that triangle.

That's why these normal maps usually look pale blue (most normals point out from the surface), with fringes of red and green where there are bumps, as though it were a relief lit from two sides with red and green lights.

Example tangent space normal map from the Knald Documentation

To do lighting with such a normal map, we need to transform the per-pixel normal and the light / eye vectors into the same coordinate space. Usually this is done by transforming the light and eye vectors into tangent space and doing our calculations there. In order to do that transformation, we need to know which way the tangent vector of the mesh points at the location we're shading, so we need the mesh's interpolated tangent vector so that we can construct the **TBN matrix** (tangent-bitangent-normal) to perform this transformation.

So if having our normals and lighting in tangent space requires this extra transformation step with a matrix we compute on the fly, you might understandably ask why we'd do it. Why not just store all our normals in object space and then transform with the uniform model matrix instead, and never need tangent vectors?

One reason is that tangent space normal maps are agnostic about the global orientation of the surface they're applied to. So we can re-use parts of a tangent space normal map on different parts of meshes, or even different meshes entirely - like a tiling brick pattern that might be re-used on walls in any orientation. Or with some tricks, we can mirror parts of the model that need the same surface colours/bumps, so we need half as much texture area to cover it (or can give it 2x the texture resolution within the same image size). Tangent space lighting also makes it easier to express the BRDF functions used in physically-based rendering to accurately model the reflective properties of different materials at different angles.

The other aspect I mentioned was **displacement mapping** \- specifically forms that are called "**relief mapping**" or "**parallax occlusion mapping**", where instead of moving vertices around, we squish the texture samples/shading around in the fragment shader to get per-pixel displacement and occlusion of small surface bumps.

Here instead of a normal map, we have a height map expressing how high or recessed the surface should be at each point. When our view ray strikes a part of this height map that's over a valley, we need to extend that ray some distance until it hits the floor of the valley - which could be some distance away in UV space if the ray came in diagonally. So we need to do a form of raymarching to step our view ray along the texture to find the correct intersection point, and use those modified texture coordinates for the surface colour and shading. The TBN matrix again lets us transform the view vector into this space - since the mesh's tangent and bitangent directions point parallel to the texture axes (and, when prepared in a way that supports this use, also tell us the amount of texture stretching on each axis, so we can scale our steps accordingly).

More info about computing tangent space and its applications to displacement mapping in this answer.

---
Tags: graphics, 3d-meshes, vertex
---


title: Storage of surface and vertex normals

text:
# Question
Title: Storage of surface and vertex normals
I am writing a program that displays a bunch of 3D objects in a room with lighting. I am doing that from scratch, so I have to implement normals calculation myself.
Say I have a set of 3D points representing a 3D object. On one hand, I can calculate the normals for every surface and vertex, and then store them in memory. Then I'll need to place the object somewhere in the room, that is, add the coordinate of the object to every vertex of it, and also do the same with normals. But I've heard that you always have to normalize normals, so on the other hand, I may normalize normals, but then I won't be able to move them as easy as just adding the location of the object to them.

So, how is that implemented in real 3D games?

Are normals calculated once for every object, get saved in memory, and get normalized before calculating the angle of incidence and reflection?
OR
Are normals recalculated and normalized every time an objects changes its position?
OR
Maybe normals are not stored in memory at all, and you calculate and normalize them every time a new frame is rendered?
Or even maybe something else?..

# Answer
> 1 votes
You seem to have some misconceptions about how to work with mesh data.

1. **You do not add a position to a normal. Ever.**

Normals represent a facing *direction*, not a *location*. If an object translates in space, without rotating or scaling, its normal vectors remain 100% unchanged.
2. **We usually don't modify the mesh source data at all when we move objects around the scene.**

Instead, we associate each instance of a rendered mesh with its own transformation matrix (sometimes called a "Model" matrix), which expresses its translation, rotation, and scale within the scene. We can have many copies of the object, all sharing the same mesh data in memory, so each copy only needs to store a dozen(ish) floats to describe its transformation relative to the source data.

When we want to render the object, we send its vertex data (positions, normals, texture coordinates) to the GPU as a vertex buffer, and send the transformation matrices to use in uniform variables or a separate buffer.

The vertex shader then runs once for each vertex, and transforms the vertex position by the MVP matrix (Model - View - Projection) to map it into the screen coordinate space. This folds together the transformation of this instance of the mesh within the scene (Model) with the transformation of the camera viewpoint (View) and the projection parameters like field of view angle and near/far planes (Projection), and we can compute that combined matrix just once per object per frame and then get all three transformations applied at just the cost of a single matrix-vector multiplication per vertex.

We'll also transform the normals (and tangents/bitangents, if applicable) in a way that ignores the translation of the model instance. One way to do this, if you don't have non-uniform scales on the object, is to just treat the normal as if its 4th component "w" was zero, and then multiply by the Model matrix to get it into world space, or by the Model-View matrix if working in view space.

If you do have non-uniform scale, then you need to use a related matrix called the inverse transpose.

Finally, inside the fragment shader, we normalize our normal/light/view vectors per-pixel. This compensates for any shortening that occurred when these vectors were linearly interpolated between the vertices of the triangle to the point we're shading right now.

Note that through all of this, the mesh's vertex position and normal data stored in video memory remains read-only. All our transformations work on temporaries that exist only during the execution of a shader, and are not stored anywhere.

Now if you're writing a software renderer or raytracer/path tracer that does not use the conventional GPU pipeline described above, you can still treat the mesh position/normal information as read-only. When you want to intersect a ray against a transformed instance of the mesh, first transform the ray by the inverse of the instance's transformation matrix. Now your ray is in the coordinate system of the original, untransformed mesh data, and you can do your intersection and reflection calculations on that unmodified data. Then you can take the results and transform them back to world space (or the coordinate system of your choice), using the instance's transformation matrix again.

---
Tags: lighting, normals
---


# Question
Title: How can I calculate "All squares within R" in a natural looking manner?
I'm working with a square grid, and I have a couple of effects that target all squares within R; in other words, a circular (or spherical) effect.

But, circles being, well, circular, and squares being... less so, things obviously have to be approximated. For instance:

But! I feel that some of these approximations don't quite give the approximation I want. For instance, consider this square:

It's obvious that the *majority* of the square falls within the circle, but using a pure "square counting" method (i.e., all squares within R of the origin), it gets left out.

Is there a better algorithm to grab all squares for which the majority of their area lies within the circle?

# Answer
> 6 votes
Without details of your existing algorithm, it's hard to say, but in pretty much any case involving a line over a grid, I've found the answer to be Bresenham's, or a variant thereof. In this case, I'd recommend looking at the Midpoint Circle Algorithm. That can give you a set of outer-bounds tiles, and then just fill it from there.

# Answer
> 4 votes
As was approximately pointed out in comments, the simplest way to do what you're after is to test the center of the square, rather than all of the corners. This isn't *exactly* equivalent to a majority of the square's area being within your circle, but the latter is a Hard Problem, and it should be close enough for your needs.

But note that this doesn't take any floating-point arithmetic, either — testing whether (x+1/2, y+1/2) is within some distance r of your center (which I'll take as the origin) is just checking whether (x+1/2)2+(y+1/2)2 \< r2, and by multiplying by 4, this is exactly the same as testing whether (2x+1)2+(2y+1)2 \< 4r2. This is useful for testing individual grid cells for inclusion.

For anything beyond this, though — and in particular, for generating all the points at once — I heartily second David Kiger's recommendation of "Bresenham-style" algorithms like the midpoint algorithm. They're also all-integer algorithms and can find you the endpoints for each row of your circle with only a small amount of arithmetic.

# Answer
> 0 votes
Since all the other answers leave parts of the answer as an assignment to the reader.

A traditional Midpoint Circle Algorithm implementation look like the below and only outlines the circle.

```
draw_circle(int x0, int y0, int radius)
{
  int x = radius, y = 0;
  int radiusError = 1-x;

  while(x >= y)
  {
    set_pixel(x + x0, y + y0);
    set_pixel(y + x0, x + y0);
    set_pixel(-x + x0, y + y0);
    set_pixel(-y + x0, x + y0);
    set_pixel(-x + x0, -y + y0);
    set_pixel(-y + x0, -x + y0);
    set_pixel(x + x0, -y + y0);
    set_pixel(y + x0, -x + y0);
    y++;
    if (radiusError<0)
    {
      radiusError += 2 * y + 1;
    } else {
      x--;
      radiusError+= 2 * (y - x + 1);
    }
  }
}

```

Here is a brute force method that bumps things up from O(N) to O(N2) but benefits from not utilizing with Cosine or Squaring functions. It also actually fills in the circle instead of outlining it.

```
void draw_circle (int radius)
{
  int x, y;

  for (y = -radius; y <= radius; y++)
    for (x = -radius; x <= radius; x++)
      if ((x * x) + (y * y) <= (radius * radius))
        set_pixel(x, y);
}

```

More about Circles.

# Answer
> 0 votes
As you titled "*in a natural looking manner*" I think it is a dither or "photoshop feather" problem, not a geometric problem.
You can fill any square that is *touching* circumference line with color compensated by brightness according to area inside circle. In your example, all squares inside circumference are filled with red (inside color), and all outside squares are white (outside color). If a given square have 25% of area inside circumference, then it can be filled with an color equivalent with 25% inside color and 75% outside color. The tricky part is color calculation and you should research about it. This how I solved it:

```
for(col=0, col<grid_size, col++{
  for (row=0, row<grid_size, row++{
    x = radius - col;
    y = radius - row;
    d = sqr(x^2 + y^2); // Distance from center
    d_i = floor(d); // Integer part of distance
    if (d_i < radius){
      // Paint with inside color i.e red (0xFF0000).
    } else if (d_i > radius){
      // Paint with outside color i.e. white (0x000000).
    } else{
      // Pixel is touching circumference line.
      // Lets calculate how much area is inside circle.
      // Get angle from center.
      if (x == 0) {
        if (y > 0) {
          angle = pi();
        } else {
          angle = -pi();
        }
      } else {
        angle = atan(y / x);
      }
      p_w = (d - d_i) * sin(angle);
      p_h = (d - d_i) * cos(angle);
      a = p_w * p_h; // (rough) Pixel area under circumference, which falls inside circle.
      // Trivial solution. Color averaging is a non-trivial issue.
      if ($a >= 0.50) {
        // Bigger area, more like inside color
        // Paint with 0xAA0000
      } else {
        // Less area, more like outside color
        // Paint with 0x660000
      }
    }
  }
}

```

# Answer
> 0 votes
The final answer is usually: hardcode it. That is, if you are going to be using this in any performance restricted way, such as interwoven with frame rendering, and assuming that you can bound the problem to some reasonable set of radii, iterating over references to each predetermined output skips the calculation phase entirely.

I recommend getting some graph paper out and then translating the squares you want for the circle radii you want to select for and reuse a method like this (c#)

void relativeAddress(sbyte x = 0, sbyte z = 0) { var \_address = data.rootAddress; \_address.X += x; \_address.Z += z; addresses.Add(\_address); }

and then for each case of radii as they grew in size, you can add additional rings. I recommend if (radii \< nextThreshold){return;}, as it is easy to read and makes the perfect branch prediction.

---
Tags: 2d, grid, mathematics
---


# Question
Title: How can I come up with unintelligible spoken speech like what can be heard in The Sims?
When I search for "Voice Samples" and "Unintelligible Voice Samples" I can only find vocals of singers or just background noise of people talking at the distance, like a crowded place, however, what I'm searching for are voice samples where a single person says something unintelligible (like in The Sims) or simply noises like "hum", "oh?".

How could I come up with something like this in my game?

# Answer
> what I'm searching for are voice samples where a single person says something unintelligible (like in The Sims) or simply noises like "hum", "oh?".
>
> How could I come up with something like this in my game?

I'll state the obvious: You can record it. Welcome to the world of voice acting.

*Simlish was improvised by voice actors.*

---

With that said, if I can get you interested in a system to generate and play the audio, I would like to separate the problem in two dimensions:

* When to play the sounds.
* What sounds to play.

---

**When to play the sounds**

Many old RPGs played a sound per character of the text. Usually at the same time the character is revealed on the screen. Beyond that, you are going to add a burden to any translation effort.

For example, you could hyphenate the text, and have a sound per syllable.

Or, for something more elaborate, you could convert the text into phonemes and play a sound per phoneme.

---

**What sounds to play**

Those same old RPGs used simple beep sounds (sine waves) with pitch variations.

One step above that is to have a wave generator that can generate random effects and use it instead of the beep sounds.

Alternatively, you could have grunt style audio samples and play them with pitch variations (*Take Banjo-Kazooie for inspiration*). Or use music instrument samples (*Take Don't Starve for inspiration*).

And, of course, you could have multiple gibberish samples. For example you could have specific samples for specific texts (phonemes, syllables, words…), except they do not match the text pronunciation, but there would be a one to one mapping between audio and text (at least in one language). You could also have variations of them for end of sentence, questions and other intonations you may want, or you could handle that with pitch variations.

---

I have found a few things that you could be interested in:

* Animalese: This is a JavaScript library for gibberish audio, inspired by Animal Crossing speech.
* sfxr: This is an 8-bit style sound effect generator (this one has been ported many times, so you may want to search for a port for either the audio tools you are using, or the game engine you are using if you want to generate the effects in real time).
* RPG Dialogue Generator: This is a Unity asset phoneme based gibberish audio, also inspired by Animal Crossing speech.
> 2 votes

---
Tags: audio, sound, voice
---


# Question
Title: What are the alternative play to earn systems out there except NFT/Crypto?
I'm looking for play to earn system to use, The idea in itself seems neat until one realize that it's all about NFTs and Crypto, and I don't want any of that.

What are the alternative play to earn systems out there? The game is supposed to be an RPG with multiple minigames in it, a roleplaying party game.

I need to know if ''play to earn'' is only limited to basically just selling nfts or fake currencies, be them in game currencies or crypto or if maybe there are other options.

# Answer
**Alternatives to "play to earn"**

There are plenty of monetization systems. They include:

* Selling licenses to the game (i.e. selling digital copies).
* Selling time limited subscriptions (either to access parts of the game, or access the game at all).
* And selling items in the game (i.e. micro-transactions).

*This is not an exhaustive list.*

---

"Play to earn" is a very new terminology. Before I get into what it means, I want to point out that it sounds like an alternative to:

* "pay to play": Games supported by selling licenses.
* "pay to win": Microtransactions supported games where you can pay to be reduce the difficulty. It could be, for example, by making the player more effective, or outright skipping content.
* "free to play": Games where there is no entry fee. They could be games supported by microtransactions or ad revenue or something else.

In fact, I would argue that whoever came up with the term "play to earn" made it sound like those terms on purpose.

---

**What is "play to earn" and what does it promise?**

Is there some promise made by "play to earn", which you wish to fulfill? (without blockchains, cryptocurrencies and NFTs). I don't know. So beyond what "play to earn" means, I'll try to cover other related promises.

So, what "play to earn" says on the tin is that you will play the game and earn things.

The promise of being able to play and earn things in a game is nothing new. Plenty of game have mechanics in which you earn trophies or titles, or you buy things in the game. Thus, that cannot be what they mean by "play to earn".

Instead, "play to earn" means that:

* There will be an entry fee (paid in a crypto-currency).
* Then in the game you will be able to earn assets (in the form of NFTs).
* And you will be able to exchange those assets for money outside the game (again as the crypto-currency).

What remains if we remove the crypto-currencies and NFTs from "play to earn"? You pay an entry fee (in real money) to play, and you will play the game, hoping to earn more than your entry fee, and cash out.

That is the same promise that casinos make. In fact, I would argue casinos are "play to earn". Except without the use of blockchains. In fact, they do have their custom currency in the form of casino chips/tokens.

You need to consider that having a cash out option in your game have legal implications. In fact, you will have similar - if not the same - legal liabilities as game shows, casinos, and lotteries.

---

There is also the unrealistic promise that the things you earn will keep their value. Even after the game or the game company is defunct. This is unrealistic because without the game the assets are useless and thus won't keep value.

Due to data protection laws, video games companies must give you a copy of your in-game data upon request. So the information about what you owned in the game is not lost when the game or game company is defunct.

If you add a digital certificate to that, it would be possible to verify its authenticity. Even the game company is defunct.

Yet digital certificates are not what you would call an NFT. They are not on a blockchain. In fact, it has a central authority: your game servers. People cannot trade or transfer them without your game server. Since there is a central authority, you can do something about any scammers.

I have also seen another related promise: that you will be able to bring items you got in a game into other games. That is unrealistic because games are not homogeneous, nor are game engines. But, If a game can honor NFTs from another game, a game can honor digital certificates from another game. Which does not need a blockchain or anything like that.

---

By the way, in-game currencies have been around for much longer than crypto-currencies. You kill some monster, you earn some "gold", you use it to buy from an NPC, that is an in-game currency.

The same goes for premium (i.e. paid with real money) in-game currencies. And I'd argue they are not a bad thing. *Yes, loot boxes, fear of missing out, and other predatory strategies are bad. But a premium in-game currency does not imply any of that.*

---

*Addendum:*

There is another promise these games make that I had skipped over: That the NFTs will be unique. On one hand, unique drops aren't new. See for example equipment in Diablo. Or for a more recent reference see weapons in Borderlands. Or riven mods in Warframe. Also, every Pokémon has unique hidden stats. On the other hand, an unique NFT does not mean an unique item in game. There could be multiple unique NFTs that all refer to identical things in the game.

Another thing I want to mention is that NFTs have a minting cost. And if this cost is not transferred to the player directly, it is being paid from the pool of cryptocurrency from the entry fees, or people buying premium currency in the game (which they may do as secondary NFTs). In other words, the players are paying for the NFTs with extra steps. Which is why the promises are mostly about the value *outside* of the game.

---

**On the monetization for your game**

> The game is supposed to be an RPG with multiple minigames in it, a roleplaying party game.

You can do this with monetization options that do not depend on in-game currencies. For example it could be a subscription, or it could be ad supported. Or the game could be free to play, with microtransaction paid on a premium in-game currency. *Which does not imply blockchain, or crypto-currency or NFTs.*

Be aware that running central servers has a cost, and you would need to recoup it.

With the words "party" and "minigame" I'm imagining something like Mario Party, which would not have to be an MMO. If that is the case, you could build it without a central server.

Instead of a central server, you could do couch multiplayer, or over LAN. Or you could take advantage of third party infrastructure available at no cost. For example run it over Discord servers, or with WebRTC. That way, the game can avoid the server cost. Which means you don't need as aggressive monetization.
> 4 votes

---
Tags: monetization, real-money-transactions
---


# Question
Title: How can I improve collision padding against level geometry in my 2D game?
I'm scripting my own collision logic for a 2D game that works like this:

1. `Boxcast` in the direction of movement against appropriate colliders in the scene
2. If a contact is detected, move to the `RaycastHit2D.centroid`
3. Move back in the opposite direction of movement while trying to maintain constant "padding" around level geometry
4. Finish movement (using something similar to a collide and slide algorithm)

My issue is with #3. Once it's time to resolve collisions, instead of resolving in the direction of the surface's normal, I want my collider to be moved backwards in the opposite direction from which it just came (easy enough). But I also want it to be placed in a such a way that it is displaced from the contacted surface by the surface's normal multiplied by some padding amount.

Let me try to clarify with these pictures:

Here, my collider in green boxcasts (in red) against the square shape; the translucent, dark box around it represents my desired padding around the geometry. The collision is then resolved in the direction of the red vector. This is simple and works fine because the surface normal is identical to my desired resolution direction.

But then if the collision occurs on rotated geometry, or I contact, for example, a 90-degree surface while moving diagonally, **I don't know how to find the appropriate resolution vector**, as the opposite direction of my movement is different than the surface normal (in white).

My goal is to find a reliable way to calculate the red vectors regardless of the contacted surface's normal, or to find a different way to maintain a constant distance around my collision geometry. I have found this problematic in certain scenarios, especially in top-down games in which the player may move in several directions on the same surface.

# Answer
This is a right triangle.

You can get the angle A in degrees by getting the angle between a horizontal vector and the normal.

And then you get the red vector length by doing:

cos A = adjacent leg / hypotenuse.

You already know the white vector length (half the box + padding), which is the adjacent leg. Now you can solve the hypotenuse and that is the length of the horizontal red vector.
> 1 votes

---
Tags: unity, raycasting, collision-resolution
---


# Question
Title: How to add feature to save game at any location during gameplay?
recently I was playing Cold War a game released in 2005 ( please refer wikipedia link \> https://en.wikipedia.org/wiki/Cold\_War\_(video\_game) ). This game has feature where player can save game at any given point be it while shooting bullets or running after enemy or whatever the player is doing.

I wanted to ask how do the devs implemented a save game feature which can be saved at any given point without any restriction?

Is there any way this feature can be implemented in todays latest games like a patch or plugin kinda thing?

Thank you for your responses in advance.

# Answer
The naive solution to create a "save anywhere" feature would be to simply take a snapshot of the whole game memory, dump it to a file and restore it later. When a game requires very little RAM, then that can actually be a viable strategy. Modern emulators for 90s consoles use this strategy successfully to implement quicksave and quickload which works in any game at any time, including games which never even had a savegame feature. But those consoles had RAM measured in kilobytes, which is trivial to handle on modern hardware.

Modern games, on the other hand, often use several GB of RAM. And don't forget all the data they are storing in the GPU RAM. So dumping the whole memory would result in savegames of the same size, which would mean really long saving and loading times. So when you want to do this *well*, then you need to differentiate between:

* Static data which can be loaded from the game files. Textures, models, audio files, (non-changing) level geometry etc. While this needs to be loaded from files anyway, there is no reason to store it redundantly in the savegame files.
* Transient data which does not need to be saved because losing it does not really matter. Like particle systems or other purely cosmetic features. Or lookup data structures which only exist for optimization purposes and can easily be restored.
* Data which actually matters for gameplay. Positions of entities, their velocities, hit points, AI state, animation state, inventories and so on.

Identifying which pieces of data fall into which category is not trivial. Which is why so many games have weird bugs which are triggered by saving and loading in specific situations.

For that reason it's a good idea to implement savegames relatively early in the development, consider with every new feature what data of that feature needs to be persisted in the savegames, implement the persistence together with each feature and only consider the feature "done" when it saves and loads correctly.

Yes, this is as much work as it sounds like. Which is why more and more games nowadays say "screw this, we only do fixed savepoints in situations where there is not much going on". This greatly minimizes the amount of data which needs to be persisted and restored and the number of edge-cases to consider which could lead to savegame-related bugs.

Implementing savegames retroactively can be a real pain. Even if you have access to the sourcecode. Creating a working savegame system as a mod for a game you did not make can be next to impossible.
> 1 votes

---
Tags: game-mechanics, savegame
---


# Question
Title: Facing Arrow on right direction while launch
Hey guys I've been making a bow and arrow system. I'm stuck on making an arrow facing the right direction before its launch. I've attached 3 arrow prefabs in the right position of the player's hand and set that active status to false. I've just turned set active to true while the particular frame of animation through animation event.it's spawned in the right direction at first. but when my character moves its transform direction is totally changed. I want my arrow is always facing its launch direction. if anyone has an idea about that please tell me the solution are ping any video tuts relative to this. I'm stuck on this long while. here is the code I've scripted to active my arrow prefab.

```
public void spawnArrow()
{

    string name = spawnArrowPool.transform.GetChild(0).gameObject.name;
    Vector3 movdir = new Vector3(0,0,0);
    if(spawnArrowPool.transform.childCount>0)
    {

        arrow = name=="Dummy" ? spawnArrowPool.transform.GetChild(1).gameObject :
        spawnArrowPool.transform.GetChild(0).gameObject;
        arrow.transform.rotation = transform.localRotation;
        arrow.SetActive(true);
    }
}

```

# Answer
> 0 votes
The root of this problem could be some misunderstanding regarding the difference between `transform.rotation` and `transform.localRotation`.

I suspect that you have that script on the `SpawnArrowPool` game object. In that case `transform.localRotation` refers to the rotation of `SpawnArrowPool` relative to its parent `RightHand`.

If you want to spawn objects which are not parented to the same object as the spawner, then you likely want the rotation of the spawner relative to the game world. You can get that rotation with `transform.rotation`.

If you *do* want the arrows to stay parented to the `SpawnArrowPool`, then you don't need to set the rotation at all. You can just do `arrow.transform.localRotation = Quaternion.identity`. The arrows will then have the same rotation as their parents. But remember that while the arrows are parented to the `SpawnArrowPool`, they will rotate and move when the arrow pool rotates or moves. Which is the desired behavior for an unlaunched arrow stuck to the hand of the character, but probably not what you want with independent projectiles after they were launched.

For more information on the Transform component, check out the documentation.

---
Tags: unity, c#, game-mechanics
---


# Question
Title: Calculating bounds of a "dirty rectangle"
I'm following noita's GDC (10:30 is where the talk becomes relevant to what I'm doing) to implement various optimization techniques for my falling sand simulation.

The one that's currently blocking me is dirty rects, where a rectangle is stored inside each chunk that covers the area that needs to be updated. The purpose of this is to reduce the amount of particles you have to iterate over for each chunk each frame.

Currently, I'm able to create the bounds when a new particle is placed, but the tricky part seems to be shrinking the dirty rect when a particle moves/replaced with air.

Here's a gif showcasing what I currently have

As can be seen in the gif, the rectangle expands to accommodate newly placed particles, but does not shrink when they're erased (erasing is just replacing that particle with an air particle).

What's the most efficient way to calculate a new bounds when a particle is replaced?

In the GDC, the developer says that even if you don't multi-thread the simulation, the dirty rect is still supposed to give a performance boost due to how much it reduces the amount of particles you have to iterate over each frame during the update of the simulation, so is something that is supposed to increase performance and thus needs to be done in somewhat of an efficient manner.

(People have told me that I don't need to do this in the first place, perhaps due to a misunderstanding of the simulation I'm creating, which I feel is wrong, because in my profiling I've found that the game starts losing FPS when updating multiple chunks even when those chunks don't have any particles to update because of just the sheer amount it has to iterate over even if it's skipping all of them)

If anyone has any insight on this that would be great (code examples would be amazing, too) because I've been trying to figure this out for days without any progress due to how obscure this optimization method is.

# Answer
I've been thinking about this myself. First of all, the dirty rect as far as I understand is reset to zero every time the 64x64 chunk is rendered. Before that, anything that changes the actual color during the simulation step increases the size of the dirty rect. This should include you "erasing" stuff by drawing space. Doing this makes it so you don't have to update every pixel color of your texture each step. I never heard of a dirty rect before watching that awesome YouTube video though, so I may be totally confused.

As far as the time it takes to loop over all of the pixels in the world for the purpose of updating mechanics and physics, I would set a counter for each chunk that represents how many dynamic pixels it has in it and increment/decrement it when things get drawn in or swapped to another chunk. Then you only have to update the chunks with counts greater than zero. I think that's the optimization you're looking for. I don't know if it's actually better. I'm going to implement it in my own sand sim and find out.

However, I'm actually totally wrong about everything, if you slow down the video at 10:41 you can see that Petri erases the stone and no dirty rect is drawn. Also earlier he says that this method allows you to not have to "test" every pixel, not "draw". So I have just as many questions as OP.

So it looks like you can just save a copy of the previous update's dirty rect and build the next update rects from nothing. Include everything around dynamic elements that swap with each other, elements in freefall, and any element that is created from thin air. There are some artifacts and particles getting stuck in the air so you can randomly check the whole 64x64 chunk every once in a while. I think Noita does this when a thread runs out of work to do. This really does give you a massive performance boost even without multi threading and allows your sim to scale up to giant worlds. Here's my attempt to do this so far, the dirty rects are purple, hopefully they are visible.

example video
> 1 votes

# Answer
Here's how I would do it:

In the rectangle object, store two arrays: an X array and a Y array. The Y array will store the number of sand pixels in each row. The X array will store the number of sand pixels in each column.

Whenever you "paint" sand, check every pixel under the paintbrush. If it is not sand already, increment both the X and Y arrays corresponding to that pixel as appropriate. If it is sand already, do nothing.

When you erase sand, do the opposite.

Then, all you have to do when you erase sand is check whether the first or last value in the X and Y arrays are 0. If so, check the next value, and so on, until you get a row or column that is not empty. Then shrink the rectangle accordingly.

This strategy will make large paintbrushes *slightly* less efficient, but it can handle arbitrarily large rectangles without having to check every pixel.
> 1 votes

---
Tags: algorithm, optimization
---


# Question
Title: Unity3d - Tile-based "Slippy" map rendered on a sphere (earth)
**Scenario**

I'm creating a spherical version of a slippy map using osm tiles and my luck has been limited thus far. I'm starting to think my strategy has lead me astray and that I need to start from scratch.

**Current Progress**

* Like the mentioned slippy maps I'm only loading tiles the user is interested in, using camera position & rotation to decipher X,Y of tiles needed
* Tiles are downloading via c# async/await
* Tiles are being positioned correctly on a sphere
* Tiles are partially rotated correctly (using basic normals)
* I'm currently working on sizing the tiles based on Y coordinate of image
* Will need to correctly position vertices for tiles as tiles close the poles need to be thinner and tiles near the equator need to be fatter
* Will need to bend tiles to match curvature of earth

**Question**

Is there a shader or some sort of math that already exists for Unity so that I can plug in the X,Y of an osm tile and have that texture appear correctly on the surface of a sphere ?

\** *some code* \**

```
    // tilesXY is the tile count per axis which depends on zoom level
    // position for 3d tiles; adding .5 to keys so the polar caps look correct
    float phi = (keyY + 0.5f) / tilesXY * Mathf.PI;
    float theta = (keyX) / tilesXY * (Mathf.PI * 2);
    float x = Mathf.Sin(phi) * Mathf.Cos(theta);
    float y = Mathf.Sin(phi) * Mathf.Sin(theta);
    float z = Mathf.Cos(phi);
    this.transform.position = new Vector3(x, y, -z);

    // wip rotation for tiles
    Vector3 pu = new Vector3(x, y, -z); // plane up
    Vector3 pr = Vector3.Cross(pu, Vector3.up); // plane right
    Vector3 pf = Vector3.Cross(pr, pu); // plane forward
    this.transform.rotation = Quaternion.LookRotation(pf, pu);

    // wip scaling of tiles
    float sfsy = Mathf.Sin(keyY / tilesXY * Mathf.PI);
    float tsf = scaleFactor * 0.16f * (sfsy * 0.25f) + 0.016f;
    this.transform.localScale = new Vector3(tsf, tsf, tsf);

```

---

```
    // code for using camera position + angle to figure out what tile(s) need to be loaded

    Vector3 camAngle = MainCamera.instance.AngleToTarget();

    UnityEngine.Camera cam = UnityEngine.Camera.main;
    bool hemiFront = cam.transform.position.x > 0 ? true : false; // top bot vs front back hemispheres @jkr
    bool hemiBot = cam.transform.position.y < 0 ? true : false;

    // Debug.Log($"{hemiFront}, {hemiBot}");
    float sinX = Mathf.Sin(camAngle.y / 360 * Mathf.PI);
    int centerX = (int)(sinX * (tilesInfo["tilesXY"] / 2)); // center of where camera is looking, on the surface @jkr
    if (hemiFront == false)
    {
        centerX *= -1;
        centerX += tilesInfo["tilesXY"];
    }

    // if (hemiFront == false) 0 = 0;
    float sinY = Mathf.Sin(camAngle.x / 360 * Mathf.PI);
    int centerY = (int)(sinY * (tilesInfo["tilesXY"] / 2));
    if (hemiBot == true)
    {
        centerY *= -1;
        centerY += tilesInfo["tilesXY"];
    }

```

\** *extra* \**

Screenshot of current progress

* the tight grouping of images is the north pole
* I'm pulling from a custom set of osm so anything green is water while blue is ice
* the underlying blue is a sphere I put in my scene to help me make sure the tiles are being positioned correctly

# \** EDIT \**

The shader is starting to come along

# Answer
Mapbox has made something similar to what I've made but I didn't find any unity opensource projects (just pieces) so I've had to create my own. Here are the highlights:

* be able to figure out latlon for anywhere on your sphere, you can do this with sin & cos but I took a shortcut with inversing camera.rotation per my situation
* map tiles are by-in-large "web mercator" so your longitude will always be 1:1 but the latitude needs to be converted from mercator to equirectangular with `atan(sinh(latitudeRadians))` which I think is a Gubermannian Inverse function but don't quote me

below is how I mapped tiles to a sphere

```
    float x = r * Mathf.Cos(phi) * Mathf.Cos(theta);
    float y = r * Mathf.Sin(phi);
    float z = r * Mathf.Cos(phi) * Mathf.Sin(theta);

```

"theta" and "phi" are my latlon after I applied the GubermannianInv, which is how I get the xyz placement of tiles around a sphere.

It's been a long journey and I'm planning to add my code to slippymap so that other people can leverage a "free" google maps solution for unity.

video of project
> 0 votes

---
Tags: unity, mathematics, shaders
---


# Question
Title: Unity- how to stream videos from external source?
I'm working on a Unity level for a VR project that requires displaying multiple 360 videos in a hall. These videos are large (8k and 60 minutes each) so cannot be contained in the app itself. Is it possible to have them streamed from an external site (AWS, Vimeo)?

# Answer
The video player component is able to load videos from the Internet. Just change "Source" from "Video Clip" to "URL" and enter the `https://` URL of the video file. There is also an article specifically on how to use a 360° video on a skybox material which might or might not fit your particular use-case.

Note that the URL must point to *the file*, not to a website embedding the file. So `https://www.youtube.com/watch?v=dQw4w9WgXcQ` is not going to work. For that reason I would recommend to host the videos on a plain old webserver and not on a dedicated video hosting platform.

But you might not want to go with the cheapest option. A 360° video requires to stream 6 different videos simultaneously. And no, you can not just cull those in the direction the user isn't looking at right now, because you don't want them to look at a buffering-placeholder when they turn around. When each one of them has 8k resolution, then that's going to create quite a lot of traffic. Webhosting which is able and willing to provide that much bandwidth per user is going to be costly. (And no, I can not give you any recommendation)
> 0 votes

---
Tags: unity, virtual-reality, video
---


# Question
Title: How can I draw orbit paths for a solar system?
I’m trying to make the orbital paths visible for my solar system simulation game. I have most around with trail renderers and solid line sprite but not achieving the desired look I want. I’m hoping to get something where the path is alway present but darker directly behind where the planet currently is, and lighter and more transparent ahead of where it’s going. This effect is achieved in the game Worbital.

If anyone could point me in the right direction how I can achieve this I would be much appreciated.

# Answer
Don't use a trail renderer, use its static cousin line renderer.

You can control the width of the line renderer using curves. So a linear falloff from 1.0 at the beginning to 0 at the end will give you a "tail" which looks similar to a trail renderer.

In order to create a circular line, you might want to generate the positions of the line procedurally.

Here is an untested code example.

```
float radius = 10f; // radius of circle in units
int num_points = 360;  // adjust based on desired tradeoff of performance vs. quality
var points = new Vector3[num_points];
for (var i = 0; i < num_points; i++) {
    var angle = (Mathf.PI * 2f) * ((float)i / num_points);
    points[i] = new Vector3(Mathf.Sin(angle) * radius, Mathf.Cos(angle) * radius, 0f);
}
lineRenderer.SetPoints(points);

```

I don't know how you built your scene, so I had to make a couple assumptions. Should the circle be in the wrong orientation (vertical instead of horizontal), change the order of arguments to `new Vector3()`). I don't know if your planets orbit clockwise or counter-clockwise, so if the trail is in the wrong direction, replace `angle` with `-angle`. Should it be off by 90°, switch `Sin` and `Cos`.

This code is also rather costly (both calculating the points and setting them), so you might want to do this only once in `Start()` and then just rotate the LineRenderer with the planet while it moves on its orbit.
> 1 votes

# Answer
**It really depends on your use case.**

But if your orbits are not 1000000 light years long you can use a semi-transparent mesh (torus from Blender, or ProBuilder, just find the setting for the thickness ) for your lighter colored path, and a particle system or VFX for your darker stuff, that trails the ship.
You might have to smoothen out some edges if it looks too blocky. Might not be super optimized but can be set up realatively quickly.

Or you can divide up your path torus and call something on OnTriggerEnter() and do some color changes to that part of the mesh...

Hope it helps!
> 0 votes

---
Tags: unity, c#, shaders, graphics
---


# Question
Title: How to find out the type of GameObject selected in the scene?
If I select some `GameObject` in the Unity, e.g. recently added `TextMeshProUGUI` inside the `Canvas`, where can I find out the type of selected game object?

In Inspector window, same as in Properties window (shown using context menu on the game object in Hierarcy window), I can see the name, tag, layout, etc. But where is the type?

I need to know the type to reference the game object in the code:

```
using TMPro;
using UnityEngine;

public class Foo: MonoBehaviour
{
    public TextMeshProUGUI bar;
    ...
    public SomeMethod() => bar.text = "bla";
}

```

I've found this topic which is rather confusing than helpful. Sure, all of game objects are inherited from `GameObject`, but to access `bar.text` I will need to know its type anyway.

From other point of view, I can look for components in Inspector and always use `bar.GetComponent<XYZ>()`, but similarly, `XYZ` is not shown in Inspector, I can see "TextMeshPro - Text (UI)" caption, which is not really `TMPro.TextMeshProUGUI` **type** I need to use in the code. So I have come to another question, how to get component type... Great isn't it?

I am likely missing something obvious. Am I the first asking this question?

# Answer
Note that a TextMeshProUGUI is a Component, not a GameObject. When you add a TextMeshProUGUI component it adds it to a new GameObject by default, which can be confusing. To make this more confusing, if you drag a GameObject into a Component slot, it will look for Components that match and add those directly.

If you have dragged the GameObject that contains the TextMeshProUGUI component in `bar` in the Editor, then you should just be able to set it with:

```
bar.SetText("bla");

```

Also note that you should use the `SetText()` method with the text mesh component instead of directly setting the `text` property.
> 1 votes

# Answer
Since you can add multiple components on a GameObject, there is no defined type for a GameObject (i.e. its type is already a GameObject). From there you can only try `GetComponent<>()` (or `GetComponent(s)InChildren<>()` for more complex objects) and see if there is one.

```
var textComponent = GetComponent<TextMeshProUGUI>();
if (textComponent != null) { // do something }

```

Or, you can use a serialized field and assign it manually from Unity editor, or automatically during `Awake()`.

About your question on the naming of TextMeshPro components, they use a specific attribute to display a different name in Editor (which I believe is an anti-pattern for Unity). If you check the `TextMeshProUGUI` source code you can see it there:

```
...
[AddComponentMenu("UI/TextMeshPro - Text (UI)", 11)]
...
public partial class TextMeshProUGUI : TMP_Text, ILayoutElement
{
    ...
{

```

\` For finding such type names conveniently, you can do a text search across the solution for the name you see in Unity editor (e.g. UI/TextMeshPro - Text (UI)) and see type names (e.g. TextMeshProUGUI) in source code instead of struggling around the documentation or web.
> 1 votes

---
Tags: unity, gameobject
---


# Question
Title: how to detect a 2d box collission with 3d box colliders
I have a bunch of TextMeshPro labels in a scene at various x,y,z positions and I would like to detect when labels overlap from the camera's perspective so I can keep the labels from stacking. The labels on the left & right of the image are visually overlapping but physically they have different z indices so a classic 3d collision won't work.

How can I detect "2d collisions" for 3d gameobjects?

*extra*

My camera moves AROUND the sphere of labels otherwise I could probably get away with putting all the labels on the same z-index;

\** EDIT \**

*current TEMPORARY solution*

3d collider in the label prefab with a very exaggerated z-index

# Answer
> 0 votes
You can use `Physics.RaycastAll` on screen-points of the corners of the last text object you created. If there is more than one hit on any of the corners it means there is another object behind. Then, you can relocate your latest object and check again.

Roughly it should go like this. You need to find a way to calculate corner positions in world space (i.e. `GetCornerWorldPositions(myText)`):

```
List<Vector3> cornerWorldPositions = GetCornerWorldPositions(myText);

foreach (Vector3 cornerWorldPosition in cornerWorldPositions)
{
    Vector3 cornerScreenPosition = Camera.main.WorldToScreenPoint(cornerWorldPosition);
    Ray ray = Camera.main.ScreenPointToRay(cornerScreenPosition);
    RaycastHit[] hits = Physics.RaycastAll(ray, 100f);

    if (hits.length > 1) { // There is an object behind. }
}

```

You may need to add a safety that shrinks the corner coordinates towards the center to prevent approximation errors during raycasting.

Also, use a tag to prevent raycasting from interfering with objects other than texts.

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


title: Sliding character inside the circle

text:
# Question
Title: Sliding character inside the circle
When it comes to rect against rect smooth sliding movement, that is easy.

Something like this will work

```
// this isn't real code, just for you to get the idea
// this is a simple sliding code, not really for a good game
sprite.moveX(5);
if (sprite.touches(wall)){
sprite.moveX(-5)
}
sprite.moveY(5);
if (sprite.touches(wall)){
sprite.moveY(-5)
}

```

EDIT: Link for demonstration https://streamable.com/wf9sn7

This will result in the character sliding against the wall, but only if the wall is rectangle.

How do I deal with circles, especially when the character is inside a circle, and colliding with the circle edges?

Note: This will be used for TurboWarp, so any code as Scratch/Turbowarp code will work, but not required

# Answer
> 0 votes
It is not a slide but collision effect. In a circle, keep in mind the radius of the circle. If the distance of your object from the center of the circle is smaller than the aforementioned radius, your character is inside the circle.

So if you want to keep a character inside a circular area, you could do this (in the same vein as your sample code):

```
sprite.Move()
if(distance(sprite,circlecenter)>circleradius)
{
    //character is moving outside of circle!
    sprite.undoMove()
}

```

Now it is better to check if the sprite will cross the boundary *before* you move the sprite, if that predicts the sprite will move outside the circle, limit the movement to the edge of the circle instead.

---
Tags: collision-detection, movement
---


# Question
Title: How to rotate parent and all children by center pivot?
I have a `DoorSprite` with an `Animator` component which I animate by rotating it by 90 degrees (makes the door look like opening around a hinge).

The parent, `Door`, is empty and only holds the `DoorSprite` child GO.

To achieve the hinge effect, I've set the pivot of the door sprite to the left side. I now want to rotate the parent but the problem is that all the children inside the parent rotate too, but not by the parent's pivot (which is center), but by their pivot.

This is the `Door` parent before rotation:

When I rotate the `Door` parent by 90 degrees, this is what I **want to** achieve:

However, this is what actually happens (the sprite pivot (hinge) is marked with the arrow):

How can I rotate everything by the pivot in the center, regardless of child pivots?

# Answer
> 1 votes
I have managed to solve this issue by rotating the door parent around the center point of the coordinates it's sitting in. In my case, if the door was on (0,0), but it's actual center was on (0.5, 0.5), then I'd want to rotate around (0.5, 0.5).

For me, that meant that I just want to rotate the object around it's position + an offset that represents it's actual center.

```
var offset = new Vector3(0.5f, 0.5f, 0);
door._doorGameObject.transform.RotateAround(door.Node + offset, Vector3.forward, 90);

```

Doing it this way, the children no longer rotated around their own axis and I could properly rotate the base of the door as intended.

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


# Question
Title: array of classes then give each class different properties, class selection random
So iam trying to practice java with a text based adventure game. This code gives out an enemy of an array(random) and then gives it a Randoam health between 0 and 100. What I want to do is give each enemy in the array properties like hp or attack damage while having a random enemy "drop".

I thought about doing it with if statements but I did some research and found about getters and setters, but I haven't been able to get it working so I deleted it.

I also thought about doing it with multiple classes but I am just to new to java to get it working.

Here is my code (The base is from a yt video but I added some things like the boss, stats and item drops):

import java.util.Random; import java.util.Scanner;

public class Firstd {

```
public static void main(String[] args) {

    String filepath = "bgmusic.wav";
    String file = "death.wav";

    music musicObjekt = new music();
    musicObjekt.playMusic (filepath);

    //System Objects
    Scanner in = new Scanner(System.in);
    Random rand = new Random();

    //Player variables
    int health = 100; //Start Health
    int attackDamage = 40; //Attack Damage
    int numHealthPots = 3; //Number of Health potions
    int healthPotionHealAmount = 30; //What number of Healing
    int healthPotionDropChance = 60; //Percentage of drops
    int score = 0; // score enemies defeated
    int numpots = 0; //used pots
    int statsdam = 0; // number of damage dealt
    int statsdamtaken = 0; //number of damage taken
    int swordChance = 15;
    int shieldChance = 15;
    int bossHealth = 200;

    boolean bossDefeated = false;
    boolean swordowned = false;
    boolean shieldowned = false;

    //Game variables

    String[] enemies = {"Zombie" , "Assasin" , "Giant" , "Skeleton"};

    int maxEnemyHealth = 80;

    int enemyAttackDamage = 25;

    boolean running = true;

    System.out.println("Welcome to the Dungeon");

    GAME: //Label of While Loop (Main Loop)
    while(running) {

        System.out.println("---------------------------------------------");

            int enemyHealth = rand.nextInt(maxEnemyHealth);
            int sword = rand.nextInt(swordChance);
            enemyHealth = enemyHealth += 10;

            String enemy = enemies[rand.nextInt(enemies.length)]; //Randoam Enemy from array

            System.out.println("\t# " + enemy + " appeared! #\n"); // Tab than # than rand enemy than #

            while(enemyHealth > 0) { //When Enemy not dead (0) keep going

            System.out.println("\tYour HP: " + health); //All the options aveible
            System.out.println("\t" + enemy + "´s HP: " + enemyHealth);
            System.out.println("\n\tWhat would you like to do?");
            System.out.println("\t1. Attack");
            System.out.println("\t2. Drink health potion");
            System.out.println("\t3. Run!");

            String input = in.nextLine(); //Input from User and set cases
            if(input.equals("1")) {

                int damageDealt = rand.nextInt(attackDamage);
                int damageTake = rand.nextInt(enemyAttackDamage);

                enemyHealth -= damageDealt; //Health minus the attack

                if(shieldowned == true) {
                    if (damageTake <= 10) {
                        health -= damageTake;
                    }
                    health -= damageTake - 10;
                            }
                else {
                health -= damageTake;
                }

                System.out.println("\t> You strike the " + enemy + " for " + damageDealt + " damage");
                System.out.println("\t> You recived " + damageTake + " in retaliation!\n");
                statsdam += 0 + damageDealt;
                statsdamtaken += 0 + damageTake;

                if(health <= 0) {
                    System.out.println("\t> You have taken too much damage, you are too weak to go on!\n");
                    break GAME;
                }
            }
            else if(input.equals("2")) {
                if(numHealthPots > 0) {
                    health += healthPotionHealAmount;
                    numHealthPots --;
                    System.out.println("\t> You drint a health potion, healing yourself for " + healthPotionHealAmount
                                        + "\n\t> You have now have " + health + " HP."
                                        + "\n\t> You have " + numHealthPots + " health potions left.\n");
                    numpots++;
                }
                else {
                    System.out.println("\t> You have no health potion left! Defeat enemies for a chance to get one!");

                }

            }
            else if(input.equals("3")) {
                System.out.println("\t You hava run from the " + enemy + "!");
                continue GAME;  //Breakout of the Loop go to above generator a new enemy

            }
            else {
                System.out.print("\tWhat are you doing?");

            }

    }
        System.out.println("---------------------------------------------");
        System.out.println(" # " + enemy + " was defeated! #");
        System.out.println(" # You have " + health + "HP left. #");
        System.out.println("---------------------------------------------");

        System.out.println("---------------------------------------------");
        System.out.println("What would you like to do now?");
        System.out.println("1. Continue fighting");
        System.out.println("2. Exit dungeon");
        System.out.println("---------------------------------------------");

        String input5 = in.nextLine(); //Input when input not 1 or 2 say not valid

        while(!input5.equals("1") && !input5.equals("2")) {
            System.out.println("What are you doing?");
            input5 = in.nextLine();
        }
        if(input5.equals("1")) {
            System.out.println("You continue on your adventure!");
            continue GAME;
        }
        else if (input5.equals("2")) {
            System.out.println("You exit the dungeon, successful from your adventure!\n");
            break;
        }
                    if(health < 1) { // if player dead
                    System.out.println("You limp out of the dungeon, weak from battle :(\n");

                        music musicObjekt1 = new music();
                        musicObjekt1.playMusic (file);

                break;
                    }
        score++;

        if(rand.nextInt(100) < swordChance) {
            if(swordowned == true) {
                continue;
            }
            else {

            attackDamage += 4 + attackDamage;
            System.out.println("The " + enemy + " dropped a sword! You are know able to make more damage! (+4HP attack damage)\n");
            swordowned = true;
        }
        }
        else {
            continue;
        }

        if(rand.nextInt(100) < shieldChance) {
            if(shieldowned == true) {
                continue;
            }
            else {
            System.out.println("The " + enemy + " dropped a shield! You are now more resistent to damage! (-10HP on every attack above 10HP)\n");
            shieldowned = true;
        }
        }
        else {
            continue;
        }

        if (score == 5) {
            System.out.println("---------------------------------------------");
            System.out.println("\tA Boss appeared!");
            System.out.println("\tIt´s a Witch!");
            System.out.println("\tThe Witch has " + bossHealth + "HP!");
            System.out.println("\tYou need to fight, no escape this time!");
            System.out.println("---------------------------------------------");

            BOSS:
            while(bossHealth > 0) { //When Enemy not dead (0) keep going

            System.out.println("---------------------------------------------");
            System.out.println("\tYour HP: " + health); //All the options avaible
            System.out.println("\tWitch´s HP: " + bossHealth);
            System.out.println("\n\tWhat would you like to do?");
            System.out.println("---------------------------------------------");
            System.out.println("\t1. Attack");
            System.out.println("\t2. Drink health potion");
            System.out.println("---------------------------------------------");

            String input1 = in.nextLine();
            if(input1.equals("1")) {
                int damageDealt = rand.nextInt(attackDamage);
                int damageTake = rand.nextInt(enemyAttackDamage);

                bossHealth -= damageDealt; //Health minus the attack
                health -= damageTake;

                System.out.println("\t> You strike the Witch for " + damageDealt + " damage");
                System.out.println("\t> You recived " + damageTake + " in retaliation!\n");
                statsdam += 0 + damageDealt;
                statsdamtaken += 0 + damageTake;

                if(health < 1) {
                    System.out.println("\t> You have taken too much damage, you are too weak to go on!\n");
                    break BOSS;

                }
                if(bossHealth < 1) {
                    System.out.println("#########################");
                    System.out.println("# YOU KILLED THE WITCH! #");
                    System.out.println("# YOU RECIVE 2 HEALTH POTS! #");
                    System.out.println("#########################");
                    numHealthPots = 2 + numHealthPots;
                    System.out.println("You now own " + numHealthPots + " health potions!");

                    bossDefeated = true;

                    continue;
                }

            }
            else if(input1.equals("2")) {
                if(numHealthPots > 0) {
                    health += healthPotionHealAmount;
                    numHealthPots --;
                    System.out.println("\t> You drint a health potion, healing yourself for " + healthPotionHealAmount
                                        + "\n\t> You have now have " + health + " HP."
                                        + "\n\t> You have " + numHealthPots + " health potions left.\n");
                    numpots++;
                }
                else {
                    System.out.println("\t> You have no health potion left! Defeat enemies for a chance to get one!");

                }

            }
            else {
                System.out.print("\tYou can not escape!\t");

            }
        }

            break;

        }

        if(rand.nextInt(100) < healthPotionDropChance) { //Generator a rand number if number less than drop chance than drop a hp
            numHealthPots++;
            System.out.println(" # The " + enemy + " dropped a health potion! # ");
            System.out.println(" # You have " + numHealthPots + " health potion(s). # " );

        }

    }

    System.out.println("#########################");
    System.out.println("# THANKS FOR PLAYING! #");
    //System.out.println("# YOU KILLED " + score + " ENEMIE(S)! #"); // add if when 1 enemy than enemies when more than enemies
    System.out.println("#########################");
    System.out.println("######### Stats #########");
    if (bossDefeated == true) {
        System.out.println("# You killed the Witch! Congrats!");
    }
    if (score == 0) {
        System.out.println("# You killed no enemy! Weakkk!! #");
    }
    else if (score == 1) {
        System.out.println("# You killed one enemy! #");
    }
    else if (score > 1) {
        System.out.println("# You killed " + score + " enemies! #");

    }
    if (swordowned == true) {
        System.out.println("# You found the sword! #");
    }
    else {
        System.out.println("# You did not find the sword :( #");
    }
    if (shieldowned == true) {
        System.out.println("# You found the shield! #");
    }
    else {
        System.out.println("# You did not find the shield :( #");
    }
    System.out.println("# You used " + numpots + " health potions! #");
    System.out.println("# You did " + statsdam + "HP damage to your enemies! #");
    System.out.println("# You took " + statsdamtaken + "HP damage from your enemies! #");
    System.out.println("########################");

        System.exit(0);
}
}

```

# Answer
> 0 votes
If you define a class enemy, like this:

```
public class Enemy
{
    // …
}

```

Then, instead of this:

```
    String[] enemies = {"Zombie" , "Assasin" , "Giant" , "Skeleton"};

```

You can do this:

```
    Enemy[] enemies = {new Enemy(), new Enemy(), new Enemy(), new Enemy()};

```

---

Oh, wait, we lost the names! So, let us add a name field:

```
public class Enemy
{
    public String Name;
    // …
}

```

And now we can do this:

```
    Enemy Zombie = new Enemy();
    Zombie.Name = "Zombie";

    Enemy Assassin = new Enemy();
    Assassin.Name = "Assassin";

    Enemy Giant = new Enemy();
    Giant.Name = "Giant";

    Enemy Skeleton = new Enemy();
    Skeleton.Name = "Skeleton";
    Enemy[] enemies = {Zombie, Assassin, Giant, Skeleton};

```

---

Well, we can do better. Let us define a constructor:

```
public class Enemy
{
    public String Name;

    public Enemy(String name)
    {
        Name = name;
    }
}

```

And now we can do this:

```
    Enemy[] enemies =
    {
        new Enemy("Zombie"),
        new Enemy("Assassin"),
        new Enemy("Giant"),
        new Enemy("Skeleton")
    };

```

And, as you can imagine, you can add other fields aside form the name for other stats. And you could use getters and setters with private fields instead of having public fields.

---

Oh, but I need to warn you. There are enemies, and there are enemies. I mean, there is the enemy kind to which multiple enemy units belong, and there is the particular enemy unit that exists in the game world. These should not be the same object.

So, I don't think you should add the current health of the enemy as a field of this class. Well, unless you mean there are only these four enemy units ever.

There are multiple ways to go about this:

* You could use prototypes. That is, there are actually these four enemy units, but what you do is clone them. I mean, you will have a method on the enemy class that give you back a new object with the same values. And you deploy these cloned objects in the game world.
* You could use descriptors. That is, there will be an object that has the values that are common to the enemy kind. And the enemy units will copy those values when you create them.
* You could use composition. Again there will be object that has the values that are common to the enemy kind. But this time you don't copy those values, you reference the object.
* And yes, some people will push you to use inheritance. Which implies making a new class for each enemy kind. Despite that not being really necessary since they only differ in values. *A red car is not a different class of car from a green car, instead its color field has a different value.*

I'm going to say composition.

*Feel free to explore the other options. Heck, don't lose track of the fact that these are options. And they may have drawbacks down the line. But, in absence of the future (isn't that always?), we resource to the past. And composition often works well - or has often worked well, in the past.*

Thus, we will have a class for the enemy, and a class for the enemy kind:

```
public class EnemyKind
{
    public String Name;
    public int MaxHealth;

    // add fields for other stats
    // change it to getter and setters if you want

    public Enemy(String name, int maxHealth /*, other stuff*/)
    {
        Name = name;
        MaxHealth = maxHealth;
        // other stuff
    }
}

```

And a class for the enemy unit:

```
public class EnemyUnit
{
    public EnemyKind Kind;
    public int Health;

    // add fields, you know…

    public EnemyUnit(EnemyKind kind /*, perhaps other stuff*/)
    {
        Kind = kind;
        // Should there be a MinHealth?
        // If you are going to use random here, either:
        //     - Make a singleton Random.
        //     - Or add a Random as a parameter.
        Health = kind.MaxHealth;
        // other stuff
    }
}

```

And now you can make your array like this:

```
    EnemyKind[] enemies =
    {
        new EnemyKind("Zombie", 80),
        new EnemyKind("Assassin", 100),
        new EnemyKind("Giant", 110),
        new EnemyKind("Skeleton", 90)
    };

```

Please notice that the first argument will go into the `Name` field and the second argument will go into the `MaxHealth` field. So the numbers above are the max health for these kinds of enemies. *Just some values I came up with.* In a similar fashion you could specify other stats/attributes.

And when you need to deploy an enemy, you would do something like this:

```
EnemyUnit enemy = new EnemyUnit(enemies[rand.nextInt(enemies.length)]);
System.out.println("\t# " + enemy.Kind.Name + " appeared! #\n");

```

---

You also mention drops. I'm not sure how you want to handle them. However, you could have an array of possible drops defined in `EnemyKind`. And then pick from the `Kind` of the `enemy` that was killed.

---
Tags: java, random
---


# Question
Title: How to write Perlin Noise generated data to a vector in Rust?
Tell me if i need to be more specific.

My program is advanced enough that it can read tile data from a .txt file and display a tile image for each tile ('~' = water), I am trying to make my game use a procedurally generated world, at first i just appended to a vector, but then i found out about perlin noise, At the moment, i can generate a seed:

```
 let perlin = Perlin::new();
 let world_seed = perlin.get(
     [rand::thread_rng().gen_range(35.0..42.4),
     rand::thread_rng().gen_range(30.0..37.7),
     rand::thread_rng().gen_range(2.0..2.8)]);

```

But i do not know how to write noise data to a vector to create a 5000 x 5000 tile map,

example:

# Answer
> 2 votes
**Perlin Noise**

You should be able to query the Perlin noise with some 2D coordinates.

*If you are using this Peril: noise::Perlin, then you can call get with a `Point2`. If you are using this Perlin: perlin\_rust::PerlinNoise then you can call perlin2 with `x` and `y` values. Most Perlin implementations have a way to do it.*

So you can query for the coordinates of a given position on the tilemap, and from the result decide what will be there in that tile, and add it to the tilemap data. You do that for every tile you want to generate. *You would, of course, have some logic to decide if it is water or not, and so on, based on the result form the perlin noise.*

---

Presumably the contents of a tile do not come from a single variable. Consider using an extra dimension so you can query the perlin noise at the same 2D coordinantes of the tile, but at different positions along the extra dimension. So you have multiple values you can use to decide what is in the tile. *For example, one could be elevation, another could be vegetation, another could be temperature, and so on.*

---

**Storing to file**

If you are not going to manipulate the tilemap, then storing the seed for the perlin noise is enough to store the tilemap. Because it should generate the same way from the same seed.

Thus, if you need to serialize the tilemap, I presume that either you need it in a particular format for another software to read, or you will manipulate it further after you generated it from perlin noise. For example, you might be picking spawn points or generating structures. Keep in mind that this may not only require modifying the tiles, but also adding metadata to the tiles, which you would also need to serialize.

---

Perhaps serializing the tilemap requires no manipulation at all, and you can simply write the memory representation to a file.

Otherwise, perhaps you want to start with some header with the tilemap size at the start of the file. So you can start adding that to the data that you will write. *Although if you are going for human readable perhaps you simply use newlines. I'm trying to show you alternative scenarios of how the serialization might go.*

Then we have the same question for the individual tiles. If the memory representation of the tile is the same as the file representation, you can just copy them to the data you will write.

Otherwise, you will need to iterate over each tile, figure out how the tile will be represented in the file, and adding that to the data you will write.

And that is assuming here that it will be stored as a single compact blob. However, you may want to break it into chunks, or have some other structure that helps to query nearby tiles for a given position. And then may have to also store an index for that structure. Yes, I'm saying you may want to serialize with that structure, so you don't have to expend extra time generating it when you load the tilemap.

Then you could manipulate the data you will write, for example you may want to compress it. And finally write it to a file.

---

Storing to file does not have to deal with perlin noise. However, if writing directly to file is a requirement, you could have a single loop that queries the perlin noise, decides what the tile will be, and how it is encoded, and writes it to file. Then you would have to read it to display it. *And I remind that this would imply you are not manipulating the tilemap after you generated it from the perlin noise, so you could be writing the seed instead, unless you need the tilemap in some particular format.*

Otherwise, you may want to display the result without storing it to file, and for that you better have a representation of the tilemap data in memory which you can either serialize to a file, or display, or whatever.

---
Tags: procedural-generation, perlin-noise, rust
---


# Question
Title: Simulating movement input in server-side, with different tick rates
I'm designing a simple MMO game server with the help of ENet (reliable UDP library) and the Godot engine for client-side. I've read tons of articles, guides, stack exchanges questions regarding movement prediction. Here is what I have so far:

* A network thread that sends/receives packets from a ConcurrentQueue, so that no blocking is necessary.
* A game thread that will periodically check if there are any new packets in the queue (every 15ms) and a game loop that runs each 100ms.

My issue is the following: how can I get inputs from packets sent by the client (input data is sent 60 times per second to server) and correctly simulate them on the server? Since the server game loop runs on 10 ticks per second, my "delta" will be different than the ones used by godot, right?

Is this approach (sending inputs instead of position data/velocity data) feasible with different tick rates? Right now I'm sending Godot inputs every 16.6ms, reading batched packets every 15ms and updating physics every 100ms.

**Edit**: I think a possible solution would be to send the game frame number along with the move input, but wouldn't that be unnecessary data? (at 60 inputs per second, I would need 4 bytes to make sure it wont overflow)

# Answer
If your client input is being sent to a queuing system, which will then be processed by the server at a certain tick rate, you don't need to worry about the variation in the information processing between the client and the server.

It's the same on the server even if different information (physics vs input) is processed at different tick rates because queued information will be unsynchronized when the tick happens.

Let me know if that makes sense or if you meant something else.
> 0 votes

---
Tags: movement, networking, mmo, frame-rate, movement-prediction
---


title: Multiplayer bullet trails

text:
# Question
Title: Multiplayer bullet trails
The problem is as follows:

A receives the position of B as 40,40. Now, obviously this position is already out of date. On Bs screen B is of course already at 50, 40. Now A shoots at an angle from 15,0 such that it would hit B (bullet has drag and gravity). When this information "shot from 15,0 angled at X". If I now render the bullet it's obviously going to miss because now B is already at 70,50. But the player aimed at 40,40 + predicted trajectory.

The image shows this situation from both A (left) and B (right) perspectives. Blue really got hit (because it counts what A can see of course. If it hit from A's perspective then it is a legit "hit") but the visuals are just off obviously.

So how do I render the bullet trails correctly?

The only solution I see is for A to display B not at the position the server told A but extrapolate the position such that it displays B where B is predicted to B when the information about the shot would arrive at B. Now this has obvious caveats because we don't know if B has stopped already so this would allow you to shoot players that stopped right before they would pop out from behind geometry because we predicted B to pop out.

But this would allow players to "aim correctly" such that the bullet trails would appear correct on the receiver (if the prediction is correct).

# Answer
You could do two things. You can look into Rollback netcode to resolve your issue by looking to synchronize the player input from the client's side.

Another simple implementation to fix it could be to slow down the speed of the bullet to give the server enough time to receive and send the information from the other player. And, at the same time, when the info is received, you can accelerate the movement of player B so that he reaches his "real" position faster.
> 0 votes

---
Tags: networking, multiplayer, synchronization
---