# Question
Title: Problems with reflection angles during collision resolution between circle and rectangle vertices (2D)
I'm having a hard time trying to resolve the reflexion angles when the ball collides with one of the brick's corners (square vertices) in my brick breaker game.

The collision detection system is working fine, and I've already managed to resolve the collisions when the ball hits the brick from its sides. The reflection angles are working fine when the ball hits either the walls or the brick's sides, and I've even managed to add slight angle increments to these angles to prevent the ball to bounce indefinitely from one side to the other.

But when it comes to the brick's corners, things get messy. The collision resolution works fine to differentiate the sides from the corners. In general, I'm picking two coordinates x,y (new and previous) to determine the ball positions and using Math.atan2(newY-prevY, newX-prevX) function to get the angles to calculate cos and sin for spdX and spdY for the collision resolution on the walls and the brick's sides. For the corners part, I'm picking the newX,newY ball coordinate (center point) when it collides with one of the bricks corners and picking the x,y coordinate from this corner to determine the normal line, by using Math.atan2(newY-cornerY, newX-cornerX). Note that I've made the adjustments for each corner x,y to get the correct values (adding width to x for the right corners and height to y for the bottom corners). Then, I calculate the angle of incidence incAngle = Math.abs(Math.atan2(prevY-newY, prevX-newX) - normal) and the reflection angle refAngle = normal - incAngle. Lastly I calculate spdX = Math.cos(refAngle) and spdY = Math.sin(refAngle). It seems the mess happens when I calculate incAngle and refAngle. I've already inverted signs on both, used Math.abs(), and in all cases some of the reflection angles show fine, some of them even perfectly, but in certain positions, depending of the inciding angle, the reflection angle shows incorrectly. Definetly the angles sign issue still confuses me a lot.

Where am I doing wrong? Is there something missing? I'm developing my game from scratch using Java and Eclipse and am trying to make the code as simple as I can, since I don't understand much of those quite complicated complex Math equations (I had made some research about them, but did not understand a thing), and don't use external physics/collision engines in it.

Best regards.

# Answer
> 0 votes
After a lot of testing, I discovered there were some unnoticed errors when calculating the normal vector angle and when repositioning the ball off the block. I'm going to take the upper-left corner to explain how I got to the solution.

The normal angle error happened when the ball collided with the block corner and its center point Y was below (greater than) the block corner Y or the center point X was greater than the block corner X. This caused the normal angle to get a positive value (ex. 180 degrees or more) and a value greater than -90 degrees, respectively. The correct normal angles for the upper-left block corner must range between -180 and -90 degrees.

To solve this, I made some adjustments in the conditions to differentiate the collisions on the sides from those on the corners, so that I can always get a normal angle for the upper-left corner from -180 to -90 degrees.

As for the ball repositioning part, I needed to get the X,Y point coordinate on the ball circle corresponding to the normal+PI angle, and then subtract the X,Y values plus the ball radius from the current X,Y ball position values. (Because I wasn't figuring out how to do this before, the ball repositioning was inaccurate, thus causing "multi collisions" issue and wrong reflection angles.)

Below is the pseudo-code on how I got correct reflection angles for the collisions between the ball and the upper-left corner of the block. I will still make slight adjustments for the other corners, but the logic is the same.

```
//conditions for left side collisions
if(ballX+ballWidth >= blockX &&
ballY+(ballHeight/2) >= blockY &&
ballY+(ballHeight/2) <= blockY+blockHeight &&
Math.abs((ballY+ballHeight)-blockY) >= Math.abs(ballX+ballWidth)-blockX) &&
Math.abs((blockY+blockHeight)-ballY) >= Math.abs((ballX+ballWidth)-blockX))
{not relevant here}

//conditions for upper side collisions
else if(ballY+ballHeight >= blockY &&
ballX+(ballWidth/2) >= blockX &&
ballX+(ballWidth/2) <= blockX+blockWidth &&
Math.abs((ballX+ballWidth)-blockX) > Math.abs((ballY+ballHeight)-blockY) && Math.abs((blockX+blockWidth)-ballX) > Math.abs((ballY+ballHeight)-blockY))
{not relevant here}

//conditions for upper-left corner collisions
else if(ball.contains(blockX, blockY) && ballY+(ballHeight/2) < blockY && ballX+(ballWidth/2) < blockX) {code}

```

Code from upper-left corner collisions resolution made in Java:

```
    else if(e1Mask.contains(e2Mask.getX(), e2Mask.getY()) &&
        e1Mask.getY()+((e1Mask.getHeight()-1)/2) < e2Mask.getY() &&
        e1Mask.getX()+((e1Mask.getWidth()-1)/2) < e2Mask.getX()) {
      prevX = newX; //previous ball position x (center point)
      prevY = newY; //previous ball position y (center point)
      newX = getX()+getRadius()-0.5; //new ball position x (center point)
      newY = getY()+getRadius()-0.5; //new ball position y (center point)
      double normal = Math.atan2(newY-e2Mask.getY(), newX-e2Mask.getX()); //normal line angle
      double inX = (getRadius()-0.5)*Math.cos(normal+Math.PI); //x coordinate from circle point that is inside the block
      double inY = (getRadius()-0.5)*Math.sin(normal+Math.PI); //y coordinate from circle point that is inside the block
      x -= (getX()+getRadius()+inX)-e2Mask.getX()-1; //ball repositioning x. Ball radius was added in order to get the correct coordinate result.
      y -= (getY()+getRadius()+inY)-e2Mask.getY()-1; //ball repositioning y. Ball radius was added in order to get the correct coordinate result.
      newX = getX()+getRadius()-0.5; //updated newX to calculate ball incoming angle
      newY = getY()+getRadius()-0.5; //updated newY to calculate ball incoming angle
      //Alternative way to repositioning the ball
      /*double inX = (getRadius()-0.5)*Math.cos(normal+Math.PI);
      double inY = (getRadius()-0.5)*Math.sin(normal+Math.PI);
      x = Game.bloco.getX()-(getRadius()-0.5+inX)-1;
      y = Game.bloco.getY()-(getRadius()-0.5+inY)-1;
      newX = getX()+getRadius()-0.5;
      newY = getY()+getRadius()-0.5;*/
      //
      //Didn't use these variables, but they helped me understand the logic
      /*double slopeNormal = Math.tan(normal);
      double slopeRefLine = -1/slopeNormal;
      double refLine = normal + (Math.PI/2);*/
      //
      double prevAngle = Math.atan2(prevY-newY, prevX-newX); //ball incoming angle
      double incAngle = prevAngle - normal; //inciding angle
      double refAngle = normal - incAngle; //reflection angle
      spdX = Math.cos(refAngle); //new speedX value
      spdY = Math.sin(refAngle); //new speedY value
    }

```

Certainly there are other ways to resolve collisions between circles and rectangles vertices, even better ones than mine but, at least, this one has worked for me, and I hope it can help other game developers who are facing the same challenges.

My best wishes to you all!

---
Tags: 2d, collision-resolution, vertex, angles
---


# Question
Title: Trying to generate a Tile labyrinth in Unity
So I have a generator code that renderes a TileMap on the scene, but It keeps creating a sollid block of walls

Where I want it to have empty cells(**This is not the final algorythm(Recursive Backtracker)**, just the begining where we fill the maze), I'm following this tutorial,trying to addjust it to the Tilemap (https://www.youtube.com/watch?v=ya1HyptE5uc&t=870s), here is my code for the renderer

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

public class MazeRenderer : MonoBehaviour {
    [SerializeField]
    [Range(1, 50)]
    private int width = 10; // width of the maze
    [SerializeField]
    [Range(1, 50)]
    private int height = 10; // height of the maze
    [SerializeField]
    private Tilemap floorMap; // Tilemap for the floor(without collider, render layer 0)
    [SerializeField]
    private Tilemap collidableMap; //  Tilemap for the walls(with the collider, render layer 1)
    [SerializeField]
    private TileBase floorTile = null; // base tile for the floor
    [SerializeField]
    private TileBase wallTile = null; // base tile for a wall
    [SerializeField]
    private Transform wallPrefab = null; // unused code for a regular wall prefab
    [SerializeField]
    private int size = 1;// offset for tile placement
    private void Start()
    {
    }
    private void Update()
    {
        var maze = MazeGenerator.Generate(width, height);// creating a maze with width and height
        Draw(maze); // rendering the maze with the Draw() method
    }
    private void Draw(Node[,] maze)// Draw method, takes in an
    {
        for (int i = 0; i < width; i++) // simple floor generation
        {
            for(int j = 0; j < height; j++)
            {
                var position = new Vector3Int(-i, -j, 0); // floor generation from the negative position
                floorMap.SetTile(position, floorTile); //setting floor tiles
            }
        }
        for(int i = 0; i < width; i++) //maze generation
        {
            for(int j = 0; j < height; j++)
            {
                var  cell = maze[i,j]; //creates connections between cells
                var position = collidableMap.WorldToCell(new Vector3(-width + i, -height + j, 0));//sets  cells positions
                if(cell.TopWall) //sets top tile for the cell
                {
                    position = collidableMap.WorldToCell(position + new Vector3Int(0, size, 0));
                    collidableMap.SetTile(position, wallTile);
                }
                if (cell.LeftWall) // sets left tile for the cell
                {
                    position = position  + new Vector3Int(-size, 0, 0);
                    collidableMap.SetTile(position, wallTile);
                }
                if (i == width - 1) // checks if we reached the right side of the maze
                {
                    if (cell.RightWall) //generates right wall
                    {
                        position = position + new Vector3Int(size, 0, 0);
                        collidableMap.SetTile(position, wallTile);
                    }
                }

                if (j == 0) // checkes if we reached bottom
                {
                    if (cell.BottomWall) // generates bottom wall
                    {
                        position = position + new Vector3Int(0, -size, 0);
                        collidableMap.SetTile(position, wallTile);
                    }
                }

            }
        }
    }
}

```

And for the generator:

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

public struct Node // setups up all possible wall placements + if the cell has been visited or not
{
    public bool LeftWall;
    public bool RightWall;
    public bool TopWall;
    public bool BottomWall;
    public bool isVisited;
}
public struct Position // position of the neighbouring cell
{
    public int x;
    public int y;
}
public struct Neighbour // creates a full neighbour position with possible wall placements
{
    public Position position;
    public Node sharedNode;
}
public static class MazeGenerator{
    public static Node[,] Generate(int width, int height)//generates possible wall  placements in a maze
    {
        Node initial = new Node(); //creating initial tile with all true possible wall placements
        initial.LeftWall = true;
        initial.RightWall = true;
        initial.TopWall = true;
        initial.BottomWall = true;
        Node[,] maze = new Node[width, height]; //creating an array of wall placements
        for(int i = 0; i < width; i++)
        {
            for(int j = 0; j < height; j++)
            {
                maze[i, j] = initial; // inputing initial wall placements into array
            }
        }
        return maze; //returning array
    }

}

```

picture of the objects in the scene

MazeRenderer is the only object in the scene that has a script(MazeRenderer),

# Answer
It is a solid block of walls because you tell it to generate a solid block of walls.

```
if(cell.TopWall)  {
    position = collidableMap.WorldToCell(position + new Vector3Int(0, size, 0));
    collidableMap.SetTile(position, wallTile);
}

```

every single cells is having cell.TopWall true according to your MazeGenerator since you never change it. This should be always true, so your loop just places a tile everywhere.

As a side node, you want to generate your maze once and not in `Update()`
> 1 votes

---
Tags: unity, c#, algorithm, maze
---


# Question
Title: Achieving minigame layout within my main game
I appreciate this is a pretty broad question but I'm not sure of a way to go about this. I have read some other questions on adding minigames but they don't all quite answer what I want.

I essentially want "minigames" to be able to happen within my main game. I have a layout of what I'm trying to describe below

A couple of solutions I thought of could be

* Using a canvas and just overlaying it
* Rendering the minigame in another part of the "world space" and using another camera while disabling the main camera
* Another scene (Seems a bit overkill to me)

I understand how to get a camera viewport cropped in the top corner and such like that, I am more concerned with how to go around achieving this layout.

Are there any other ways I can go about this?

# Answer
> 0 votes
Use a screen space canvas. I’ve done this with multiple games. Using a camera is cool if it’s a 3d mini game but else it’s just wasted resources.

---
Tags: unity, 2d
---


title: How to measure deltaTime?

text:
# Question
Title: How to measure deltaTime?
I'm trying to make a simple console application and don't want to use Unity, but I want to implement a timer, so I would want to use Time.deltaTime.

# Answer
# How to Measure deltaTime

It is measured by calling a timer every frame per second that holds the time between now and last call in milliseconds. Thereafter the resulting number (delta time) is used to calculate how far, for instance, a video game character would have travelled during that time.

## Basic implementation in Javascript

```
let lastTime = performance.now(); // performance.now() returns the current timestamp
function gameLoop() {
    let now = performance.now();
    let deltaTime = now - lastTime;
    lastTime = now;
}

```
> 0 votes

---
Tags: c#, game-loop, timestep
---


# Question
Title: (Fluid Behavior Tree) Random NavMesh position returning the same position, instead of calculating a new one
I have a NavMesh agent that wanders around every x seconds, moves to a random position, and lastly it repeats the sequence. I made a test using a coroutine, which was called through a context menu method.

However, when I reimplemented the logic in a behavior tree, the random point was only generated the first time. In the following turns of the sequence, the random point was always the same. I'm using this library, called Fluid Behavior Tree. I'm really not sure what's wrong, since the logic from the coroutine and the logic from the nodes of the tree is quite literally the same.

The code from the Coroutine:

```
CheckForSafeDestinationPoint(); // Caculates the random point and sets it as the destination of the agent

// wait until the path is ready
while (agent.pathPending)
{
    yield return null;
}

if (agent.pathStatus == NavMeshPathStatus.PathComplete)
{
    Debug.Log("Path is valid");
    agent.isStopped = false;

    while (agent.GetPathRemainingDistance() > agent.stoppingDistance)
    {
        // Wait until the agent reaches its destination
        Debug.Log("Wandering");
        yield return null;
    }
}

yield break;

```

The code from the node of the tree (a leaf node called AgentDestination):

```
protected override void OnStart()
{
    // Literally the same as CheckForSafeDestinationPoint(), with the exception that the random point (the Destination) is first calculated on the parent tree a passed as a parameter to this node
    SetDestinationPoint(Destination);
}

// This code is executed on the Update method
protected override TaskStatus OnUpdate()
{
    while (agent.pathPending)
    {
        return TaskStatus.Continue;
    }

    if (agent.pathStatus == NavMeshPathStatus.PathComplete)
    {
        agent.isStopped = false;

        if (agent.GetPathRemainingDistance() > agent.stoppingDistance)
        {
            // This is the equivalent of yield return null
            return TaskStatus.Continue;
        }
    }

    // Once the node succeeded, the tree leaves this node
    return TaskStatus.Success;
}

```

The previous logic is later implemented trough the tree:

```
void Awake()
{
    agent = GetComponent<NavMeshAgent>();

    tree = new BehaviorTreeBuilder(gameObject)
            .Sequence()
                .Wait(waitTicks)
                // Here we pass in the random calculated point as a parameter
                .AgentDestination("RandomDestination", ComputeRandomDestination())
            .End()
        .Build();
}

void Update()
{
    tree.Tick();
}

```

I have my theories, though I'm not entirely sure about them. First, I think that every time I call the coroutine, a new instance is created, thus creating with it a new random point, as expected. However, I may be confusing the instance creating with the string-based call of the coroutine. Since the tree is created on the Awake() method, the ComputeRandomDestination *may* be getting cached somehow. However, I think this doesn't make a lot of sense since the agent can follow a moving target, which means that it can calculate a new path every frame, so in theory, it should be capable of calculating a random point more than once, right?

Anyway, point is, I have no idea what's wrong. All I know is that the leaf node AgentDestination is, after the first turn, always going to the same spot. It's not calculating a new random point. The node is in fact exiting, so it seems that it's working as expected.

# Answer
So basically, the tree was being created on the `Awake` function, which by nature is caching everything I create inside of it.

The tree is not actually being updated in real-time, and by that I mean, that it isn't creating a new instance of itself on every frame (which would actually dynamically create the random data I was trying to create), the `Update` function was just reading the tree that was previously created and cached in `Awake`, which of course makes sense performance-wise.

And that's it, I just moved the function `ComputeRandomDestination()` to an `Update`-dependent method: the leaf (action) node has 3 states, Start, Update, and Exit. All of them runs on Update, so they're not cached, as it would on `Awake`.
> 0 votes

---
Tags: unity, c#, behavior-tree
---


# Question
Title: Skipped function calls on Integer based frame data
I'm creating a basic animation system, where I call functions to change the rendered sprite and turn on hitboxes based on the current frame of the animation.

For example, if (current\_frame == 8), I turn on the hitbox. Then, if it hits something or if current\_frame == 9, the hitbox is turned off.

However I've stumbled into a problem. If I implement an attack speed modifier, like, 20% attack speed increase, on 7th game update, the current\_frame is 8.4 and I miss the function call to turn on the hitbox. I know I can implement something like (current\_frame \>= 8 && \<= 9), but this doesn't work If I add an attack speed multipler of 100% or more - the frame will be skipped and functions wouldn't be called.

I'm also open for new animation systems / books / articles to study!

# Answer
> 2 votes
**Option 1:** Have a second, integral frame counter.

After updating the original counter, gradually increment this new counter to match it, executing all your logic along the way:

```
for (; current_frame_int + 1 <= current_frame; current_frame_int++)
{
    // Add all your frame-based logic here.
}

```

---

**Option 2:** Have a flag to tell you if a specific step is already finished.

```
bool hitbox_shown = false;

```

```
if (current_frame >= 8 && !hitbox_shown)
{
    hitbox_shown = true;
    ShowHitbox();
}

```

---
Tags: c++, game-mechanics
---


# Question
Title: How to navigate a moving 2d spaceship under newtonian mechanics to a point in space?
I am creating a real-time game where ships move through space using basic laws of motion. The ships move by rotating (instantly for our purposes) to an angle and then firing their engine to accelerate.

I have coded up a basic ECS system wherein every tick velocity is added to position and acceleration is added to velocity.

So the problem is at any given moment how can a ship determine the rotation to fire its engine (assume constant acceleration) to intercept an arbitrary point elsewhere in the world. Ideally in the shortest time possible, however I'd settle for ever.

I have the following variables:\\$v\\$ the current velocity vector of the ship at \\$t = 0\\$ , \\$P\_0\\$ the current postition of the ship, \\$P\_2\\$ the desired intercept point, and \\$||a||\\$ the maximum magnitude of the acceleration vector.

I need to find some rotation \\$\theta\\$ to fire my engine in to follow a curve to the given intercept point \\$P\_2\\$.

I have tried solving for the quadratic bezier curve control points for such a path and then deriving its acceleration. Like so:

\\$P'(t) = 2(1-t)(P\_1 - P\_0)+2t(P\_2 - P\_1)\\$

\\$P'(0) = v = 2P\_1 - 2P\_0\\$

\\$P\_1 = \frac{v}{2} + P\_0\\$

To derive \\$P\_1\\$ and then:

\\$P''(t) = 2(P\_2 - 2P\_1 + P\_0)\\$

plugging in the three points to get an acceleration vector, however if I understand correctly bezier curves are from \\$t=0\\$ to \\$t=1\\$? So this is a massive acceleration vector that would get my ship to the point in one game tick. I have tried scaling this vector to the maximum magnitude of the engine's acceleration, but that doesn't quite work. I feel like my approach is close but I can't quite figure it out.

Cont.

I have thought about this more and returned to this solution. I believe I need to solve for time \\$T\\$ to reach the point by calculating the radius of the circle in the aforementioned answer. If I do that then I can calculate the second control point as \\$P\_0 + Tv\\$.

It seems to me that the minimum time necessary to reach a point is when the destination point \\$P\_2\\$ is on the circumference of the circle described by it's center \\$P\_0 + Tv\\$ and radius \\$\frac{T^2}{2}a\\$ where \\$a\\$ is the maximum acceleration.

Previously I was conflating the \\$t\\$ in the bezier curve polynomial (between 0 and 1) with some time \\$T\\$ it will take to complete the maneuver which is unbounded.

# Answer
I found a working solution for myself. Here's my code in Typescript (using bitecs) with comments:

```
// eid here is the entity id in my ECS
const position = getPos(eid);
const velocity = getVelocity(eid);
const destination = getDestination(eid);
const mass = Mass.value[eid];
const maxForce = Engine.maxForce[eid];

// Bezier curve control points
// p0 and p2 are trivial: they're just the starting and ending location
// p1 is half the distance the ship would have travelled if no further
// acceleration. The core issue is we must know the entirety of the
// travel time in terms of the unit our velocity is in.
// In this case frames/ticks.
const p0 = position;
// this function is explained below. It returns the time used for the
// entire maneuver
const time = findTimeToPoint(p0, destination, maxForce / mass, velocity);
// Here we add the distance to p0 that is travelled in time / 2 frames
const p1 = vec2Add(p0, vec2Mult(velocity, time / 2));
const p2 = destination;

// The second derivative of a quadratic Bezier curve is
// P''(t) = 2(P_2 - 2P_1 + P_0)
// which makes it a constant value with respect to time. Since we have
// all three points we can just solve for it.
const a = vec2Mult(vec2Add(vec2Sub(p2, vec2Mult(p1, 2)), p0), 2);

// The resulting vector (a) of the acceleration has a large magnitude
// since it's in terms of unitary time from 0 to 1. However since we only
// need the rotation and we already know the magnitude we can just
// solve it.
let rotation = Math.atan(a.y / a.x);
// deal w/ principle values of atan
if (a.x < 0) {
  rotation += Math.PI;
}

// Then we update the rotation and my physics systems take it from there
Engine.percent[eid] = 1;
Rotation.radians[eid] = rotation;
removeComponent(world, MoveTo, eid);

```

Here is my function to find the time of the entire maneuver. It's not very efficient but works for my use case. You could potentially solve for T using the proper equations:

$$ \displaylines{ S = \\|\vec{P\_3} - \vec{v}T\\| \\ S = \sqrt{(P\_{3x} - v\_xT)^2 + (P\_{3y} - v\_yT)^2} } $$

and

$$ R = \frac{T^2}{2}a $$

but I couldn't figure it out. This sort of computational iterative approach is good enough for now.

```
const findTimeToPoint = (p0: Vec2, p3: Vec2, a: number, v: Vec2) => {
  // Coordinate transform in terms of origin at p1
  // I found it easier to think about p3 moving _away_ from
  // the center of the circle than the circle moving but I think
  // it's the same
  const p3_ = vec2Sub(p0, p3);
  const v_ = vec2Mult(v, -1);

  let T = 0;
  // The distance between the potential position without acceleration
  // at time T and the edge of a circle described by R
  let S = vec2Magnitude(p3_);
  let R = 0;
  // We just iterate one frame forward and solve for R and S
  // when R < S then the time given is enough for the movement
  // from p0 to p3
  while (R < S) {
    T++;
    S = vec2Magnitude(vec2Sub(p3_, vec2Mult(v_, T)));
    R = a * (Math.pow(T, 2) / 2);
  }
  return T;
};

```

This works to have the ship follow a curve to an intercept point. I can probably do some cool stuff with the engine percentage if I wanted to take fuel usage into account but this is good enough for now.
> 1 votes

---
Tags: physics, linear-algebra, simulations, beziers
---


# Question
Title: How can I adapt the 2d joystic value to a 3d direction for the character?
Hello I am trying to move the character in joystick direction

Green arrow is what I am trying to get.

```
private void OnMovement(InputAction.CallbackContext obj)
    {
        if(obj.performed){
            _MovementPoint = new Vector3(-obj.ReadValue<Vector2>().y, 0,obj.ReadValue<Vector2>().x ).normalized;
            Debug.Log(this.transform.position);
        }
    }

```

And I am calling this on Update

```
 private void Update()
    {
        this.transform.position = this.transform.position + _MovementPoint*Time.deltaTime*6;
    }

```

Is there a way?

# Answer
> 2 votes
The screen coordinate system and the world coordinate system are different. You can convert the coordinates by Camera.ScreenToWorldPoint. Find the transformed vector by transforming two points:

```
void Update()
{
    var p1 = Camera.main.ScreenToWorldPoint(Vector3.zero);
    var p2 = Camera.main.ScreenToWorldPoint(_MovementPoint);
    var moveDir = p2 - p1;
    this.transform.position += moveDir * Time.deltaTime * 6;
}

```

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


# Question
Title: Why is rotating an object for a specific keyframe changing the original rotation of the object?
I'm following along on a game development course and it's going well, but I've come into an issue that I can't quite find the proper words for to google, so I decided that I would ask here. The game is a simple rail shooter, and at the moment we are using the built in timeline animator for unity to animate the course that the camera and ship will follow. In the link to the video below, I explain what the problem is since I find it hard to exactly describe in just words and screenshots. https://drive.google.com/file/d/13C1AK5RLOk3eoPMwMK3SW9Jx6gII7n4\_/view?usp=sharing
I'm still getting used to Unity and it's features, so hopefully it's just a simple mistake. If anything else is needed, just let me know and I'll update the question.
And apologies for the extremely low quality of the video, I had to use OBS after NVIDIA crashed, and then it had to get compressed through the editing software and then once more through google docs.Hopefully it doesn't impact what I was trying to explain, but like I said earlier if any screenshots are needed to be able to look at parts that were blurry or anything else then just let me know.

Text summary of the video - Like I stated above, the game is a rail shooter, meaning that the camera and ship will move to pre-determined spots for scripted enemies to show up and shoot at you. On keyframe 1, our ship is facing forward about to take off. On keyframe 2, about a second later, the ship rises up. And on keyframe 3, the ship flies forward and makes a turn, and then makes another turn on keyframe 4. Here's where the problem starts. On the 3rd keyframe, where the ship makes its first turn, instead of rotating the camera from its 2 to 3 position, Unity changes the rotation of the camera from the start. (Ex - If the camera starts facing North but has to make a turn to the west, Unity makes it face West from the start instead of turning from North to West like it should) The odd thing is that this only happens once, because going from 3 to 4 rotates the camera properly.  This is the ship's rotation on keyframe 1 ^
And this is the same keyframe but after keyframe 3 was animated. So now instead of turning the camera from the original position to the new position in 3, it changed the entire rotation of the camera + ship rig and it now only glides to the new position

# Answer
> I'm completely guessing here, but it could be due to the interpolation mode (looks like it aligns it with the direction of travel). I think the mode is indicated by the squiggle next to the little red circle left of the timeline - see if you can change it; if not, you could maybe try adding an extra key frame right next to the first one with the same orientation.
> – Filip Milovanović

In summary, create a rotation key frame of the original rotation that you want in the "show curves" view on the timeline, so that way any new changes made to the rotation of the object do not update the original orientation. (Ex - If you want your object to start at (0,0,0), make a rotation key frame of the object in that orientation so that any changes only effect the key frame it's supposed to.)
> 1 votes

---
Tags: unity, animation
---


# Question
Title: How to prevent weapon clipping WITHOUT camera stacking?
This is a FAQ, and answers involve camera stacking. **I am not using a SRP.** I do not want camera stacking as various post-processing instructions (e.g. FXAA, MSAA, etc) are all done on the active camera, and redoing all these instructions on multiple camera would be costly

Is there any way to prevent weapon clipping through walls without using camera stacking or a SRP?

# Answer
> 0 votes
I fixed this issue in a simple way: by taking a step back when my weapon bumps on something.

It works absolutely fine for me. Please take a look at it.

I hope it helps someone.

---
Tags: unity, rendering, camera
---


title: Play sound on animation state exit

text:
# Question
Title: Play sound on animation state exit
I'm trying to figure out how to play a sound effect when a game object leaves a particular state and goes into another. For simplicity, let's just say I want a sound effect to play when the animation for an object transitions from state A to state B, but not the other way around and not for other states. How would I achieve this? I've found information related to playing sound effects when entering a state, but not when exiting from one particular state to another.

To be more specific, I tried implementing this code as a behavior on State A exit:

```
override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        GameObject self = animator.gameObject;
        MyScript myScript = self.GetComponent<MyScript>();
        myScript.PlaySFX();
    }

```

But since state A is accessible from any state, I think it is constantly entering state A from itself over and over again. I say this because the sound effect plays repeatedly whenever I am in state A.

# Answer
> But since state A is accessible from any state, I think it is constantly entering state A from itself over and over again. I say this because the sound effect plays repeatedly whenever I am in state A.

Check `Can Transition To Self` in the inspector.
> 0 votes

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


# Question
Title: Putting a List of Scriptable Objects inside of another Scriptable Object
I'm making a word game in Unity.

I've made two Scriptable Objects. The first one is for FeemData.

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

[CreateAssetMenu(fileName = "New FeemData", menuName = "Feem Data", order = 51)]

public class FeemData : ScriptableObject
{
[SerializeField]
public string feemName;

[SerializeField]
public string Neem;

[SerializeField]
public Int32 neemNumber;

[SerializeField]
public string coreGrapheme;

[SerializeField]
public string shadowString;

}

```

And the second one is for NeemData

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

[CreateAssetMenu(fileName = "New NeemData", menuName = "Neem Data", order = 51)]

public class NeemData : ScriptableObject
{
[SerializeField]
public string neemName;

[SerializeField]
public string feemText;

[SerializeField]
public Color feemColor;

}

```

Right now, the NeemData Scriptable Object has a string field called feemText.

In actuality, each Neem can have multiple Feems. I'd love to turn the feemText into a List of Feems, so that I can drag and drop the relevant Feems into the Neem in the Inspector.

Any suggestions on how to edit the NeemData Scriptable Object to include a List of Scriptable Objects (in this case, the FeemData)? Thank you!!

# Answer
> 2 votes
You should use a public or serialized `List<FeemData>` (or an array `FeemData[]`). Like so:

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

[CreateAssetMenu(fileName = "New NeemData", menuName = "Neem Data", order = 51)]

public class NeemData : ScriptableObject
{
    [SerializeField]
    public string neemName;

    [SerializeField]
    public string feemText;

    [SerializeField]
    public Color feemColor;

    //Do this
    [SerializeField]
    public List<FeemData> Feems;

}

```

---
Tags: unity, scriptable-object
---


# Question
Title: Generate random line path with no intersection
The idea is to generate a path with a certain distance `m`. Currently the generation pseudo code is as follows:

```
lines: List of line

lines[0]: line starting at (x:0, y:0) and ending at (x:0, y:1)
for i: 1 to m:
    random_angle: randomly generate angle between -90 and 90 degress.
    lines[i]: new line starting at the end of lines[i-1] forming and angle = random_angle
    between lines[i-1] and and lines[i]

```

The general idea is illustrated in the below:

**But the problem is that when `m` is big enough the lines create a loop and end up intersecting each other.**

**Any solution to this ?**

1- Been trying to find a good math library that detects the intersection between 2 lines, then check for each new line if it intersects the others already created, but no library was found

2- Any another algorithm that can generate a random line path ?

# Answer
Finding a line-line intersection has a well documented solution, and while the equation might look complicated it is really simple enough to not warrant a library to solve.

In python it might look like this:

```
# line is a tuple of two Vector2 (the two end points of the line)
def line_length(line:tuple):
    a = Vector2(line[0])
    b = Vector2(line[1])
    return (b - a).length()

# line is a tuple of two Vector2 (the two end points of the line)
def line_contains_point(line:tuple, point:Vector2):
    a = line[0]
    b = line[1]
    if a == point or b == point:
        return True

    l = line_length(line)

    a_to_point = point - a
    b_to_point = point - b

    return a_to_point.length() <= l and b_to_point.length() <= l

# line_to_check is a tuple of two Vector2 (the two end points of the line)
# line_to_check_against is a tuple of two Vector2 (the two end points of the line)
def find_line_intersection(line_to_check:tuple, line_to_check_against:tuple):
    x1 = line_to_check[0].x
    y1 = line_to_check[0].y
    x2 = line_to_check[1].x
    y2 = line_to_check[1].y

    x3 = line_to_check_against[0].x
    y3 = line_to_check_against[0].y
    x4 = line_to_check_against[1].x
    y4 = line_to_check_against[1].y

    denominator = (x1 - x2)*(y3 - y4) - (y1 - y2)*(x3 - x4)
    if denominator == 0:
        return (True, None)

    xNominator = (x1*y2 - y1*x2)*(x3 - x4) - (x1 - x2)*(x3*y4 - y3*x4)
    yNominator = (x1*y2 - y1*x2)*(y3 - y4) - (y1 - y2)*(x3*y4 - y3*x4)

    px = xNominator / denominator
    py = yNominator / denominator

    point = Vector2(px, py)
    on_line = line_contains_point(line_to_check, point) and line_contains_point(line_to_check_against, point)
    return (on_line is not None and on_line, point)

```

An algorithm that creates a path that does not intersects with itself simple enough to create, as all it has to do is to check the new line to see if it intersects with any of the previous lines:

```
lines[0]: line starting at (x:0, y:0) and ending at (x:0, y:1)
for i: 1 to m:
    possible_angles = -90 to 90 in random order
    for random_angle in possible_angle

       new_line: new line starting at the end of lines[i-1] forming and angle = random_angle
       between new_line and and lines[i]
       if not intersects(new_line,lines)
           lines[i]: new_line
           break

```

What is harder is to find an algorithm that never "wraps in" on itself to the point where there is no next line that does not intersect an existing line. But this can potentially be solved by detecting that state, and in those cases remove a number of path segments and then trying again.

This sort of solution gets progressively slower as the max length of the path goes up, but depending on your use-case it could work.

In the above example I manually add a segment on a key-press to slow the process down, I also reduce the path manually when it's stuck in a loop, but that would just be a matter of saying `if stuck remove N number of segments`.

Full python source for the above example:

```
import random
import pygame
from pygame.math import Vector2

pygame.init()
screen = pygame.display.set_mode((400, 300))
should_run = True

# line is a tuple of two Vector2 (the two end points of the line)
def line_length(line:tuple):
    a = Vector2(line[0])
    b = Vector2(line[1])
    return (b - a).length()

# line is a tuple of two Vector2 (the two end points of the line)
def line_contains_point(line:tuple, point:Vector2):
    a = line[0]
    b = line[1]
    if a == point or b == point:
        return True

    l = line_length(line)

    a_to_point = point - a
    b_to_point = point - b

    return a_to_point.length() <= l and b_to_point.length() <= l

# line_to_check is a tuple of two Vector2 (the two end points of the line)
# line_to_check_against is a tuple of two Vector2 (the two end points of the line)
def find_line_intersection(line_to_check:tuple, line_to_check_against:tuple):
    x1 = line_to_check[0].x
    y1 = line_to_check[0].y
    x2 = line_to_check[1].x
    y2 = line_to_check[1].y

    x3 = line_to_check_against[0].x
    y3 = line_to_check_against[0].y
    x4 = line_to_check_against[1].x
    y4 = line_to_check_against[1].y

    denominator = (x1 - x2)*(y3 - y4) - (y1 - y2)*(x3 - x4)
    if denominator == 0:
        return (True, None)

    xNominator = (x1*y2 - y1*x2)*(x3 - x4) - (x1 - x2)*(x3*y4 - y3*x4)
    yNominator = (x1*y2 - y1*x2)*(y3 - y4) - (y1 - y2)*(x3*y4 - y3*x4)

    px = xNominator / denominator
    py = yNominator / denominator

    point = Vector2(px, py)
    on_line = line_contains_point(line_to_check, point) and line_contains_point(line_to_check_against, point)
    return (on_line is not None and on_line, point)

def extend_path(path:list, line_length:float):
    from_point = path[-1]
    to_point = Vector2()
    possible_angles = list(range(-90, 90, 1))
    random.shuffle(possible_angles)

    last_direction = (path[-1] - path[-2]) if len(path) > 1 else Vector2(line_length, 0)
    while len(possible_angles) > 0:
        angle = possible_angles.pop(0)
        to_point = from_point + last_direction.rotate(angle)
        path.append(to_point)
        if check_if_path_is_valid(path):
            return True
        path.pop()

    return False

def check_if_path_is_valid(path:list):
    lines = []
    for index in range(1, len(path)):
        lines.append( (path[index - 1], path[index]))

    for line in lines:
        for index in range(1, len(path)):
            other_line = (path[index - 1], path[index])
            intersects_on_line, intersection_point = find_line_intersection(line, other_line)
            if other_line != line and intersects_on_line:
                if intersection_point != line[0] and intersection_point != line[1]:
                    return False
    return True

point = Vector2(200, 150)
path = [ point ]
mouse_position = Vector2()
extend_path(path, 16)

while should_run:
    screen.fill((10, 20, 40))
    # Build two-point segments from path
    lines = []
    for index in range(1, len(path)):
        lines.append( (path[index - 1], path[index]))

    for line in lines:
        pygame.draw.line(screen, (40, 80, 160), line[0], line[1])

    pygame.display.flip()

    for events in pygame.event.get():
        if events.type == pygame.KEYDOWN:
            if events.key == pygame.K_w:
                if not extend_path(path, 16):
                    path.pop()
            if events.key == pygame.K_q:
                path = [ point ]
            if events.key == pygame.K_e:
                path.pop()

        if events.type == pygame.MOUSEMOTION:
            mouse_position = pygame.mouse.get_pos()
        if events.type == pygame.QUIT:
            should_run = False

```
> 2 votes

---
Tags: random, path, lines
---


# Question
Title: Access a variable on an object hit by a ray
So, I know that there are better ways to access a variable on another object, but this way, as far as i know, needs to be accessed in this specific way. What I need to do is get a variable on an object when that object is hit by a ray. Something like GetComponent but for a variable. Ive already got the ray able to spawn and check if the object the ray hit has the script with the variable in it, i just need to access the variable.

I cant really set this up in the inspector, as the variable i need is on something that there are many of, so i need to get the variable from the specific object that was hit by the ray.

Ive been researching it for awhile but it seems all the other questions are either not what im looking for or just outdated. I dont really think posting any code would help in this case, as what i have currently does everything except what im asking about here.

# Answer
> Something like GetComponent but for a variable

That's still just `GetComponent`. You'd use it like this:

```
if (Physics.Raycast(ray, out var hitInfo)) {
    if (hitInfo.collider.TryGetComponent(out SomeComponent comp)) {
        comp.variableToChange = "Success!";
    }
}

```

Here I chose to use the `TryGetComponent` flavour as it's a bit more concise in cases where the component might not be present, and avoids unnecessary memory allocations when using it in the editor (regular `GetComponent` has a special editor behaviour where it spawns a dummy object if no matching component was found, to help you get better error messages - but coding defensively with the `Try` version avoids that)

For this example, I'm assuming that the variable you want to read or assign is declared something like...

```
public class SomeComponent : MonoBehaviour {
    public string variableToChange;
}

```
> 3 votes

# Answer
If I understand your question correctly, then you have multiple components of different classes which each have a variable `float foo`, and you want to access the `foo` of the first component on the object which has a `foo` variable.

You could solve this problem with interfaces.

Step 1: Define an interface as a new C# file. Let's name it `IHasFoo`.

```
interface IHasFoo() {
    public float GetFoo();
    public void SetFoo(float newValue);
}

```

Step 2: Make each class which has a foo variable implement that interface:

```
public class ThingamabobController: MonoBehaviour, IHasFoo {
    private float foo;

    public float GetFoo() { return foo; };
    public void SetFoo(float newValue) { foo = newValue };
}

```

Step 3: Now when you use `GetComponent<IHasFoo>()` on an object, you get a reference to the first component on the object which implements the `IHasFoo` interface. The return value is of the type `IHasFoo`, so you can only call the methods defined in that interface. But that's all you need.

```
var fooHavingComponent = otherObject.GetComponent<IHasFoo>();
if (fooHavingComponent != null) {
     fooHavingComponent.SetFoo(42.5f);
}

```
> 2 votes

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


# Question
Title: How do I make a game that can transition from 2D to 3D?
My plan is to start from an really old game and build my way up to todays graphics and games. So for example start with Pong and then go to Space Invaders, then go to Zelda and Super Mario. But then I need to make the first 2D games change into 3D games. How do I do that?

# Answer
That's easy. Just program your game with the z-axis aligned to to the camera forward direction. Set z=0. Everything appears flat, or 2D.

Skew the axis a bit to reveal the world is actually 3d

So in short, to make a 2D game appear 3D, it has to be 3D in the first place. You cleverly draw the 3D scene to make it *appear* 2D. Then later you can change the camera angles to show it is really 3D.
> 9 votes

# Answer
I have messed a bit with Unity and XNA both of which force you to develop in a 3D environment, even when making 2D games. In order to do this you need to ignore the 'Z' axis and just focus on 'X' and 'Y'. If you're looking on how to make a 2D game, there are several tutorials out there that aren't hard to find.

To transition from a 2D to a 3D game could mean several different things. You could go from traditional 2D side scroller (original mario) to 3D adventure (super mario 64) to 3D side scroller (splosion man) (its more like a 2D sidescroller with 3D textures) so you need to know what kind of 3D game you want to make.

If you want to make a 3D side scroller then just change objects from 2D objects to 3D and TADAA you're pretty much done. However, if you are wanting to go from 2D to 3D adventure, I would suggest the advice of @bobobobo (Master of Fist of the Nose Hair).

I would definitely learn how to make 2D and 3D games separately first THEN learn how to transition since you would know more about both.
> 0 votes

# Answer
I'm not a 3d dev, but I think that all you have to do is make scenes for each game,3d or 2d, then swap them
> -1 votes

---
Tags: 2d, 3d
---


# Question
Title: How to resolve swept AABB collision when two boxes are hit at exactly the same time?
I've read many posts here about sweeping AABB collisions and the corner problem. But I still couldn't solve the problem.

In the image below, the object starts touching both boxes, and when I apply a diagonal motion, it collides with both, and getting the collision times I get 0.0 for both.

Many of the posts that I read recommend sorting collisions by the time of impact, but what do I do if the times are equal?

In this example I'm using tiles, but I want a solution that will work with AABBs of different sizes.

Here are the links to the important sections of the code

Raycast: https://github.com/anynoise00/bevy\_simple\_aabb/blob/v0.2.0/src/collision/raycast.rs (above the intersection function there's a link to the article that I read to make the RayVsBox intersection test)

Aabb: https://github.com/anynoise00/bevy\_simple\_aabb/blob/v0.2.0/src/collision/aabb.rs

Broad, narrow and solve phases: https://github.com/anynoise00/bevy\_simple\_aabb/blob/v0.2.0/src/collision/mod.rs (the sorting happens at the narrowphase, I tried also sorting it by the far times when the near times where equal, but it is still sticking to the corner of walls when moving vertically)

Maybe there is something wrong with the code?

Thank you for your attention.

# Answer
> 0 votes
A collision detection algorithm will necessarily compute one collision before another, even if the estimated time for them is the same. So, a good criterion for ordering collisions before solving them could be: **lower time first; if time is the same, early detected first**.

This can be easily achieved using a priority queue, where the priority value is the collision time and ordering entries with the same priority has FIFO criteria (First In, First Out, then latest enqueued values go at the bottom of their priority level).

Here's a pseudocode example, where `pairX` is a valid collision detected during the narrow phase and waiting for the collision response, and the float is the collision time estimated for that pair:

```
collisions = PriorityQueue()

collisions.Enqueue(pair0, 0.1)
collisions.Enqueue(pair1, 0.0)
collisions.Enqueue(pair2, 0.05)
collisions.Enqueue(pair3, 0.04)
collisions.Enqueue(pair4, 0.5)
collisions.Enqueue(pair5, 0.1)
collisions.Enqueue(pair6, 0.01)

print(collisions)

```

The result will be:

```
[pair1, pair6, pair3, pair2, pair0, pair5, pair4]

```

---
Tags: collision-detection, collision-resolution, aabb
---


# Question
Title: What to do when the NavMeshAgent is as close as it will get to the destination?
If I determined the NavMeshAgent is as close to its destination as it's ever going to get, what do I do with it? Do I set the destination to the agent's current position? Do I set `isStopped` to true? Because it'll still be trying to get to that destination and I don't want it to keep trying.

# Answer
> 1 votes
If this is a general problem whenever your agent tries to reach any destination, you should use the `stoppingDistance` property of NavMeshAgent:

```
//Stop when we're 1 meter from our destination
navMeshAgent.stoppingDistance = 1;

```

If it's a situational issue, where you use your own code to determine that the agent can't get closer to a *specific* destination, you can use `navMeshAgent.isStopped = true` (don't forget to un-stop it later when it's given a new destination!) or `navMeshAgent.ResetPath()`.

---
Tags: unity
---


title: Ads in a desktop game?

text:
# Question
Title: Ads in a desktop game?
For my Destiny Garden project, which is a desktop game, I want to use freemium monetisation strategy, so I plan to publish both free demo version and a paid full version, and I'm wandering is there any advertisement networks for desktop games? There are dozens of them for mobile games, but I cannot find any for a desktop app Theoretically, something like embedding of an HTML-page with ads is possible, but I'm not sure this is a good approach... Or, does anybody knows other ways of monetisation of free desktop games?

# Answer
Ads in desktop games can receive a significant backlash, but there's a way around that. Rewarded Video Ads are optional, and are all over my apps now. Here's a quick explanation:

\<\< Rewarded video ads are one of the most popular mobile types of in-app ads. Publishers, advertisers, and gamers – everybody can benefit from rewarded video ads. ...

When players watch a rewarded video ad, they receive a reward in exchange. That can be any kind of in-game benefit like extra lives, currency, points, etc. This gives players the incentive to watch through the whole ad. And the only thing required from the players is their time and maybe attention. \>\>

https://www.blog.udonis.co/mobile-marketing/mobile-games/rewarded-video-ads

I use DuoLingo to study foreign languages and if you want to get free Gems, you have to watch a video. Then you get the gems... but you have to wait an hour or so before you have the option to watch another Rewarded Video. (I imagine the rate limiting is just to prevent someone from watching tons of videos to earn gems and avoid buying them.)

For your RPG, you could make it so that if you want a powerup of some kind... you can watch a Rewarded Video and earn it that way. Or maybe they earn Gems which they can use to buy your powerup... or if they don't want to earn it that way, they can just outright buy the powerups with cash.

I always thought skins and cosmetics were huge for free games but this video had a great overview on monetization that puts skins/cosmetics in perspective: https://www.youtube.com/watch?v=y3\_Oe0SD1rc

His point was that the most profitable microtransactions are those that reduce the amount of grinding a player has to do. Maybe this is why there's so much grinding in free games these days!
> 1 votes

---
Tags: windows, linux, macos, monetization, advertisements
---


# Question
Title: How do I modify parts of a texture on a quad?
I am programming a Real Time Strategy game, and I was wondering how I could retexture one part of a terrain quad to change a texture in the position where I click at. For example, if I clicked in the center of the terrain, I could change the standard grass texture into a dirt texture.

I was considering, perhaps, using blend maps, but those would not work, as they map out the terrain pre-render, as is done by a heightmap.

Here is a video of the RTS game at the moment

I intend to use these so that I can retexture the ground when there are trees (like in the image below):

or if there are farms (minus the wheat, just the tilled land):

or, last, but not least, resources:

Are there any shader techniques that I could try to get an effect similar to these? If so, are there any resources that I could try that would provide me enough information? It does not have to be in C++/OpenGL. I am in greater need of an explanation of how I could do this correctly and efficiently, in order to give the RTS map more flavor.

I am willing to provide any code that might be needed of me.

# Answer
> 0 votes
Let's go from the top:

1. You need 2 textures - grass and dirt.
2. Terrain geometry needs some UV mapping for both textures (explicit or procedural, whatever).
3. You also need a mask to denote where each texture goes (assume simple black-n-white)
4. For each fragment, sample from mask and draw either of two textures (or a blend)

How this can go:

1. Could be in a single pass and single shader with both textures and mask lookups.
2. Could be in two separate passes and shaders. Think decals.
3. Could be a single megatexture (prepared beforehand or dynamically).

Now come details:

1. Mask could be a simple greyscale to allow for smooth blending, but it is generally looking washed-out. You might want to use some dithering or a blend texture or blend based on original textures height info.
2. Rendering whole terrain whilst checking with the mask might be inefficient. You might want to render "plain grass" areas with a simpler shader without mask lookup. and reserve the more complex mask sampling shader for the areas where this is needed.
3. Storing mask texture in high-enough resolution for the whole terrain might be wasteful. Perhaps you could store the mask values in terrain geometry (per-vertice).
4. Could be texture-less solution if you know how to generate the pattern you need programatically in shader.

---
Tags: opengl, c++, graphics, glsl, rts
---


title: how to offset a rays starting point

text:
# Question
Title: how to offset a rays starting point
So the problem i am working with here is about rays piercing objects. Basically, a ray is created, it hits a piece of armor, and then some math happens, if it is able to pierce the armor, then I need it to create a ray just past it, moving in the same direction. Ive already figured out the math for if it can pierce the armor, I think i can figure out the direction part, i just need to know how to offset the position. I dont think i can just add an x or y constant variable for this reason:  The green is the initial shot, and the blue is the second ray that needs to be created. If its hitting like this, its pretty easy, you would just offset the starting position of the ray by a little bit on the x axis. But it might not always hit like that. What if it hits like one of these:  I accidentally inverted the colors of the rays but my point still stands.

I cant just add an x value to the starting point of both of those secondary rays. For one, it would work alright, but the other, that would put it back outside of the armor and just hit it twice. And this project is in 3d, so there's a z coordinate to deal with as well. What i would need to do is add a value to the origin of the secondary ray that is a few units forward of the first ray's eventual impact point. And that is what I can't figure out how to do.

# Answer
What's industry standard is to take the surface normal vector of the surface that you've hit/intersected, and add a small bit of that vector to the starting pos of the next ray. How small is a complete can of worms into robustness of numerical methods and computational geometry that I'm not qualified to open, but something like 0.0001\*normvec should do it. Of course that assumes your geometry is much larger than 0.0001.
> 0 votes

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


# Question
Title: Animation clip that acts relative to the object's current position
I am making a 2D game in Unity and I want to create an animation that works with any object and takes that object's position into account.

The animation should be a little bounce, basically move it up from its current position and then move it back down to that same position. The problem is when I create that animation and then move the object after, and later play that animation, it goes back to the keyframed location instead of bouncing in-place.

What is the correct way to achieve the goal that I'm describing?

# Answer
> 1 votes
You have to make Empty GameObject and make your GameObject parent of this. After that you don't have to add animation component to Empty GameObject; you have to add Animation component to your GameObject and test again, but don't move Empty GameObject: you have to move your main GameObject.

Look at this video, not mine: How To Fix Unity Animation Position Issues

---
Tags: unity, 2d, animation, animator
---


# Question
Title: How to remove hardcoded path in UserSettings?
I would like to use Git for my Unity projects. I took the default .gitignore file that GitHub provides, but I noticed that it doesn't ignore the UserSettings folder. That wouldn't really be a big deal usually, but I noticed that the full project path is hardcoded in one of the files in that folder, specifically "UserSettings -\> Layouts -\> default-2021.dwlt" under "m\_LastProjectPath".

I'm not a fan of that.

* Should I put the UserSettings folder into the .gitignore as well, or maybe just "default-2021.dwlt"?
* Is there perhaps a setting in Unity that removes m\_LastProjectPath?

# Answer
> 2 votes
Yes it should be ignored because, as you noticed, it's specific to each Unity user. You can find details behind the reasoning here: https://forum.unity.com/threads/whats-the-usersettings-directory.754436/

I don't know why the gitignore generated on the github website is out of date. I usually go directly to the source repository to get an up to date gitignore. As of today it contains the "UserSettings" folder. https://github.com/github/gitignore/blob/main/Unity.gitignore

Btw, if some folks need a little more detail on how to use it with Unity, I've written a blog post about that: https://crafty.creatiel.ca/blog/unity-gitignore-essentials

# Answer
> 0 votes
Yes, you can add this line to your .gitignore file to ignore /UserSettings folder:

```
/[Uu]ser[Ss]ettings/

```

---
Tags: unity, git
---


title: How to generate terrains in real time?

text:
# Question
Title: How to generate terrains in real time?
I am trying to make a terrain editor for my Empire Earth OpenGL clone engine. Are there any articles of how to generate terrains in real time? It would be cool if it had pseudocode, even cooler if it had C++, and the best would be if it had OpenGL code too. But none of these are really necessary. I just need to be able to understand how real time rendering is done.

Any ideas? Here is a video of the terrain

```
for (int i = 0; i < VERTEX_COUNT; i++) {
        for (int j = 0; j < VERTEX_COUNT; j++) {
            vertices[vertexPointer * 3] = (float)j / ((float)VERTEX_COUNT - 1) * SIZE;

        GLfloat height = getHeight(j, i, pData, texture_height, texture_width, channels);
        heights[j][i] = height;
        vertices[vertexPointer * 3 + 1] = height;

        vertices[vertexPointer * 3 + 2] = (float)i / ((float)VERTEX_COUNT - 1) * SIZE;
        normals[vertexPointer * 3] = 0;
        normals[vertexPointer * 3 + 1] = 1;
        normals[vertexPointer * 3 + 2] = 0;
        textureCoords[vertexPointer * 2] = (float)j / ((float)VERTEX_COUNT - 1);
        textureCoords[vertexPointer * 2 + 1] = (float)i / ((float)VERTEX_COUNT - 1);
        vertexPointer++;
    }
}
for (int gz = 0; gz < VERTEX_COUNT - 1; gz++) {
        for (int gx = 0; gx < VERTEX_COUNT - 1; gx++) {
            int topLeft = (gz*VERTEX_COUNT) + gx;
            int topRight = topLeft + 1;
            int bottomLeft = ((gz + 1)*VERTEX_COUNT) + gx;
            int bottomRight = bottomLeft + 1;
            indices[pointer++] = topLeft;
            indices[pointer++] = bottomLeft;
            indices[pointer++] = topRight;
            indices[pointer++] = topRight;
            indices[pointer++] = bottomLeft;
            indices[pointer++] = bottomRight;
        }
    }

```

This is the terrain creation code(modified version of an example from the OpenGL shader Cookbook). I am aware that this function is called each frame. I have successfully been able to lift the terrain by modifying values such as"vertices\[vertexPointer * 3 + 1\]."

# Answer
Starting off from the code you posted, you're right: this code will generate the terrain, then will be used for rendering. And you'll likely "generate" your terrain each frame.

Since you want to edit your terrain, you'll need to extract the data, then save it.

An option for you is to generate your terrain offline first: take this loop that generates the terrain, move it to a new small program that will generate the height for each vertex, then save it to disk in a binary file.

Then within your editor you will load this "height map" from disk into memory (into a vector); when you'll generate your terrain mesh, you'll refer to this vector to set the height.

The next step will be to generate the normal vectors for the mesh. Internet is full of info on this so I will not explain how to do it here.

Then you'll need to find a way to deform your terrain by changing the height of each vertex\**. After each time the terrain is deformed, you need to recompute the normal of the involved vertices. (At first, you can just recompute them all, it shouldn't be too costly.)

Once you're done with your session of terrain edition, you need to save your map again back to disk, so that it can be loaded and edited again in your terrain editor, or so that it can be loaded in your game.

---

<sup>\** You can try your favourite SimCity game and try to understand how they do it as a first pass. </sup>
> 1 votes

---
Tags: opengl, c++, glsl, terrain, rts
---


title: How to get height from a mesh

text:
# Question
Title: How to get height from a mesh
I have a terrain which is a mesh. Given the `x` and `z` coordinates in which a character is placed, I would like a function that returns the `y` (so, the height) at that given point.

I am using Vulkan and I would like to know how can I implement it in C++.

Thanks

# Answer
The height of an object relative to an underlying terrain is the distance from its position \\${P}\\$ (plus an optional offset \\$C\\$ of choice) and the position projection \\$P'\\$ onto the terrain:

Since a terrain mesh is usually made up of many (triangle) faces, it's more appropriate to use a ready-made physics library: this way, one could cast a ray from \\$P\\$ downwards, detect the collision on the terrain at position \\$P'\\$ and get the current height by computing \\$P\_y-P\_y'\\$. Implementing such functionalities from scratch is unsuitable since it's time-consuming and probably out of the scope of your assignment.

However, you can easily implement your own support functions and compute the height, provided that some assumptions on the terrain mesh shape are met. Here're some requirements for this solution to work:

1. The mesh, when projected, resembles a **regular square grid**. This means all vertices are the same distance from their front, back and side neighbours when ignoring the vertical coordinate.
2. The quads in the meshes are **triangulated**. This means each quad is made up of two triangles. Unlike generic polygons, triangles have many geometric properties we can take advantage of, as we'll do later.

### Grid Mesh: finding \\$P\\$'s grid coordinates

Before computing height, we must first discover in what part of the terrain \\$P\\$ lies. We may check \\$P\\$ against all vertices and find the ones closest to it to compute height, but this is computationally expensive.

We could subdivide the terrain into cells, and find the cell containing \\$P\\$ instead. A grid-like mesh lets us identify each cell using row and column indices, and \\$P\\$ would be inside one of the cells. Moreover, if the grid is regular (like in the pictures), we can find out the correct cell by "snapping" \\$P\\$ to the grid and finding out the cell position in the grid coordinate system.

If the grid cells have size \\$l\\$ (assuming squares), and the grid origin has position \\$D = (D\_x, D\_y, D\_z)\\$, the cell containing \\$P\\$ has indices:

$$ \begin{align} u &= \LARGE{\lfloor} \normalsize \frac{P\_x-D\_x}{l} \LARGE{\rfloor} \\ v &= \LARGE{\lfloor} \normalsize \frac{P\_z-D\_z}{l} \LARGE{\rfloor} \\ \end{align} $$

Once we get the indices, we can reference the four vertices belonging to that quad, if we have a convenient look-up table for storing such information. A similar approach can be used to find the indices of the grid vertices (which coincide with geometry vertices in the mesh) and use them to directly reference the geometry instead:

$$ \begin{align} (u, v)\_{v\_1} &= \LARGE{\lfloor} \normalsize \frac{P-D}{l} \LARGE{\rfloor} \\ (u, v)\_{v\_4} &= \LARGE{\lceil} \normalsize \frac{P-D}{l} \LARGE{\rceil} \\ (u, v)\_{v\_2} &= (u\_{v\_4}, v\_{v\_1}) \\ (u, v)\_{v\_3} &= (u\_{v\_1}, v\_{v\_4}) \\ \end{align} $$

### Triangulated Quads: finding the actual triangle below \\$P\\$

Once we find the quad containing the position from which to sample the relative height to the terrain, we need to determine the actual projection \\$P'\\$. Since four points are hardly co-planar, we triangulate the quads so that every vertex triad lies on a flat surface.

Depending on the mesh triangulation, we may have one of the following cases:

We can easily discriminate which triangle contains \\$P\\$, for it can be either above or below the triangulation diagonal. We can discriminate between such cases by checking the sign of the cross product between \\$P\\$ and the end vertex of the diagonal, with respect to the start vertex of the diagonal:

* On the left, \\$\overrightarrow{V\_3P}\times\overrightarrow{V\_3V\_2}\gt 0\\$, so \\$P\\$ lies in the semi-plane above the oriented vector \\$\overrightarrow{V\_3V\_2}\\$, and the triangle to check for during the next step is \\$\langle V\_3V\_2V\_1\rangle\\$.
* On the right, \\$\overrightarrow{V\_1P}\times\overrightarrow{V\_1V\_4}\gt 0\\$, so \\$P\\$ lies in the semi-plane above the oriented vector \\$\overrightarrow{V\_1V\_4}\\$, and the triangle to check for during the next step is \\$\langle V\_1V\_4V\_2\rangle\\$.

### Triangles: projecting \\$P\\$ and get \\$P'\\$

Once we know what triangle is directly below \\$P\\$, we must find the projection \\$P'\\$ so that we can compute the distance \\$(P, P')\\$, thus the height of \\$P\\$ relative to the terrain.

Setting \\$P\_x' = P\_x\\$ and \\$P\_z' = P\_z\\$ are conditions needed to find out the missing \\$P\_y'\\$ that satisfies the barycentric coordinate relationship for the current triangle (a good, practical explanation of this topic can be found here). Barycentric coordinates are also the foundation of the ray-triangle intersection algorithm, which lets you find the actual coordinates for \\$P'\\$. An implementation has been provided in this past StackOverflow answer.

---

I acknowledge there's A LOT of room for optimisation and improvement on this method: take rotations into account, generalising to any equivalent terrain topology...

Also, I didn't test it beyond some pen-and-paper calculations, however, I believe the main idea behind is a good starting point to make things work in the first place, and maybe refine the procedure to get more fine-tuned results when working with complex terrain meshes.
> 2 votes

---
Tags: 3d-meshes, heightmap, vulkan
---


# Question
Title: Projectile arc velocity changes depending on target x-axis position
I am trying to create an enemy for a 2D platformer that launches a projectile in an arc at the player position (think throwing a grenade, launching an arrow style parabola).

Everything works as expected if the player and enemy are more or less on the same y-axis (or similar, within a few units), but the further the difference on the y axis, the faster the projectile moves. This also happens the closer the target gets on the x-axis (but only if there is a difference in the y-axis).

I've included the code in the script that's attached to the projectile that moves it as everything else (the collision, the actual launching of the projectile, etc) works as it should.

```

GameObject target; // The player is the target
float velX = 10; // Initial x velocity is known
float velY;

private void Start()
{
    // Initialize the target object
    target = GameObject.FindGameObjectWithTag("Player");
    // Reverse the x velocity depending on player position
    velX = target.transform.position.x > transform.position.x ? velX : -velX;
    // Calculate the time to impact
    float timeToImpact = (target.transform.position.x - transform.position.x) / velX;
    // Calculate the initial y velocity
    // Add 2 to the target position to aim at the top of the player - it's 2 units tall
    velY = (target.transform.position.y + 2f - transform.position.y + 0.5f * -Physics2D.gravity.y * (timeToImpact * timeToImpact)) / timeToImpact;
}

private void Update()
{
    // Set the rigidbody velocity
    Vector2 vel = new Vector2(velX, velY);
    GetComponent<Rigidbody2D>().velocity = vel;
    // Gravity alters the y velocity over time
    velY += Physics2D.gravity.y * Time.deltaTime;
}

```

I'm sure that there's just some value that I need to divide or multiply one of the velocities or time by but I can't quite wrap my head around it.

# Answer
> 1 votes
The way you've written this code, you've fixed the horizontal velocity to be 10. That means the projectile's time-of-flight will be directly proportional to the horizontal distance to the target: the farther it is horizontally, the longer it will take to reach it. That means the projectile needs more upward velocity to counter the pull of gravity over that longer duration. Since you've fixed your horizontal velocity, the vertical can't take away from that component, it can only add on - resulting in a greater total speed the farther away your target is.

If you want to launch your projectile with \[up to\] a fixed speed instead, consult one of the existing answers that shows how to do this.

As an aside, your `Update()` method in this code looks very strange. You should not need to apply gravity yourself - the Rigidbody will integrate that for you. You can use the gravityScale property to adjust the amount of gravity each object gets if you want to apply more or less (or no) gravity to some objects, without extra scripts. If you do find you need to make custom scripted changes to physics behaviour, you should generally do that in `FixedUpdate()`, not `Update()` \- especially for continuous effects like gravity - this will give you more consistent behaviour even under varying framerates.

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


# Question
Title: In Unity, why does a positive Z-axis rotation goes counter-clockwise while X and Y rotations go clockwise?
In Unity:

With a perspective having Y and Z axes pointing up and right respectively, if I make a positive X rotation, the object rotates clockwise

With a perspective having Z and X axes pointing up and right respectively, if I make a positive Y rotation, it also rotates clockwise

But Z rotation behaves differently. With a perspective having Y and X axes pointing up and right respectively, if I make a positive Z rotation, It rotates counter-clockwise, not clockwise.

Why is that?

# Answer
When you have Y and Z pointing up and right respectively, the rotation is *positive* and the X-axis is pointing *towards* you.

When you have Z and X pointing up and right respectively, the rotation is *positive* and the Y-axis is pointing *towards* you.

When you have Y and X pointing up and right respectively (I assumed "X and Y" is a typo), the rotation is **counter-clockwise** and the Z-axis is pointing **away from** you.

What you wrote, "X up and Y right", is equivalent to having Y pointing up and X pointing left (or, Y pointing down and X pointing right). This implies the Z-axis is now pointing **towards** you, and the rotation will occur **clockwise**.
> 1 votes

---
Tags: rotation
---


# Question
Title: Can I use Libgdx to create a game that runs on multiple platforms?
I created my first game using Libgdx and Android Studio. The game runs smoothly on my Android phone. How can I run it on an Apple phone with IOS or a computer with Linux etc.?

# Answer
> 0 votes
The way to deploy your game on all possible platforms is described here on official LibGdx wiki. Mostly it is just running single command:

* Desktop (JRE binary - Windows, Linux, MAC OS X): `./gradlew desktop:dist`
* HTML: `./gradlew html:dist`
* iOS: `./gradlew ios:createIPA`

Desktop and HTML should work out of box without any configuration, but you can sometime hit small issues with HTML build. I have no experience with iOS, but you need to set signing certificates. Check link above for more details.

---
Tags: libgdx, android, ios, linux
---


# Question
Title: What kind of game is best to learn the basics
I am interested in learning Unreal Engine. What kind of game should I aim to build as a beginner which will teach me the most? Thanks.

# Answer
Unreal supports almost every imaginable type of gameplay and they all use most of the same systems, just in slightly different ways.

It comes with example scenes for a number of different types of game (FPS, Top-down, etc)

Pick one and start trying to modify the game world to suit your interests.

Eg in the top-down example scene, the player character can already navigate to a click.

Try expanding the walkable area and adding some navmesh complexity, or change how widely the player avoids objects, or perhaps you want to create dozens of gems and start tracking/displaying the player score as they're collected.

It doesn't really matter what you do... All of it will be a learning experience, just use google and youtube liberally. It's very unlikely you're the first person trying to do *{whatever you choose}*.
> 0 votes

---
Tags: game-design, game-mechanics, unreal-4
---