# Question
Title: Moving ship to new destination when already having a velocity?
*Feel free to skip to the bottom and see the actual question.*

**NOTE: Question updated below based on comments**

I am trying to make a space game and implement basic movement, unlike most, this is a simulation over time in the likes of Aurora 4x where time can pass by seconds or by days, months, years. I only mention this because my delta and inclusion of ticks would probably raise questions.

Quick Notes:

* Vector2Wide is just the .NET System.Numerics Vector2 that I copied and made it use `double` instead of `float`
* I am not using a game library. This is actually drawn in WPF taking my "space" location in AU and converting it to pixels on a canvas.
* Frictionless space
* Ship can accelerate/decelerate in any 2D direction. There's no ship rotation.
* X,Y are cartesian coordinates with the sun being at 0,0
* I am using Kilometers as my distance and acceleration, but I don't think it matters, just mentioning it in case.
* I also simulated it for every second to make sure it wasn't an issue skipping so much time and the results were basically the same with my acceleration value.

Going from a velocity of 0 is fine as shown here where my path properly shows my ship (center of the sun) moving to where I clicked just past Venus.

From here I jump a couple of hours and the ship has velocity from constant acceleration. I then give the ship a new destination and this is where I have thoroughly fried my brain the past couple of days.

The red arrow is the destination the ship is tracking, but my flawed math is sending the crew to their death.

```
var velocity = _velocity;
var position = SystemPosition;
var mid = VectorMath.Midpoint(position, to);
var distanceToMid = Vector2Wide.Distance(position, mid);
var accelerate = true;
var oldDistanceToTarget = distanceToMid;
var acceleration = MaxAccelerationPowerKms;

var alreadyMoving = _velocity != Vector2Wide.Zero;
var oldAcceleration = new Vector2Wide();
var oldDistanceToMid = Vector2Wide.Distance(position, mid);
var headingTowardsDestination = false;

for (var i = 0; i < 72; i++)
{
    var newDirectionToTarget = Vector2Wide.Normalize(Vector2Wide.Subtract(position, to));
    var accelerationDirection = new Vector2Wide(1, 1) * -newDirectionToTarget;
    if (i == 0 && alreadyMoving)
        accelerationDirection = AccelerationDirection;

    if (oldAcceleration == Vector2Wide.Zero)
        oldAcceleration = accelerationDirection;

    if (alreadyMoving)
    {
        var angleInRadians = Math.Atan2(position.Y, position.X) - Math.Atan2(to.Y, to.X);

        accelerationDirection = VectorMath.RotateRadians(accelerationDirection, angleInRadians);
        if (i == 0)
            Debug.WriteLine($"{i + 1} | {angleInRadians} | {accelerationDirection} | {oldAcceleration - accelerationDirection}");
    }

    var newPosition = PeekPath(TickConstants.HourTicks, position, ref velocity, accelerationDirection, acceleration);
    var newDistanceToMid = Vector2Wide.Distance(newPosition, mid);
    var newDistanceToTarget = Vector2Wide.Distance(newPosition, to);

    if (newDistanceToMid < oldDistanceToMid)
        headingTowardsDestination = true;

    if (accelerate)
    {
        if (headingTowardsDestination && newDistanceToMid > oldDistanceToMid)
        {
            //Debug.WriteLine("Decelerating");
            acceleration = -acceleration;
            oldDistanceToTarget = newDistanceToTarget;
            accelerate = false;
            i--;
            continue;
        }

        oldDistanceToMid = newDistanceToMid;
    }
    else
    {
        if (headingTowardsDestination && oldDistanceToTarget < newDistanceToTarget)
        {
            //PathPoints.Add(position);
            break;
        }
    }

    oldDistanceToTarget = newDistanceToTarget;
    position = newPosition;

    //if (i % (60*60) == 0)
    PathPoints.Add(position);
}

```

Actual movement code:

```
Vector2Wide PeekPath(long deltaTicks, Vector2Wide currentPosition, ref Vector2Wide velocity, Vector2Wide accelerationDirection, double acceleration)
{
    var seconds = deltaTicks / TickConstants.SecondTicks;
    var distanceXKm = CalculateDistance(velocity.X, acceleration * accelerationDirection.X, seconds);
    var distanceYKm = CalculateDistance(velocity.Y, acceleration * accelerationDirection.Y, seconds);
    velocity += accelerationDirection * (acceleration * seconds);

    var spaceDistanceX = distanceXKm / CelestialBody.AuKilometer;
    var spaceDistanceY = distanceYKm / CelestialBody.AuKilometer;
    return currentPosition + new Vector2Wide(spaceDistanceX, spaceDistanceY);
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static double CalculateDistance(double velocity, double acceleration, double time)
{
    return (velocity * time) + (0.5 * (acceleration * (time * time)));
}

```

I know the code is horribly flawed, but I don't know how much.

**Actual Question**

With a velocity and direction change, how do I apply or find the proper directional force to apply to my velocity to reach the destination? The more I deviate the direction, the more skewed/off the path gets. It will also not allow me to set a destination opposite direction, but I think that's my own issue with trying to figure out when to decelerate.

I do hate to ask this, but if you give an actual formula, can you please explain with an example? I sadly just don't have the math skills to know how to read them correctly =/

---

## Update

Thanks to DMGregory great post, I am much closer. Spaceship acceleration for following waypoints

Red arrow points to the destination. The ship has a positive X velocity and the destination is directly above.

The new problem is that I don't know if I am using the correct vector to use for steering. The other issue is that I now have no idea how I am supposed to properly handle or calculate when/where/angle to decelerate so I can actually get to the destination. The crew are still guinea pigs on a no return mission.

```
for (var i = 0; i < 72; i++)
{
    var time = TickConstants.HourTicks;
    var seconds = (double) time / TickConstants.SecondTicks;

    // A
    var startPosition = position;

    // B
    var halfwayPointNoAcceleration = startPosition + ((seconds /2) * velocity) / CelestialBody.AuKilometer;

    // D
    var finalPositionNoVelocity = startPosition + (seconds * velocity) / CelestialBody.AuKilometer;

    var dRadiusKm = MaxAccelerationPowerKms * (seconds * seconds / 2);
    var dRadius = dRadiusKm / CelestialBody.AuKilometer;

    var radianFromCenterDToTarget = Math.Atan2(target.Y - finalPositionNoVelocity.Y, target.X - finalPositionNoVelocity.X);

    // C
    var steeringVector = FindCoordinateOfVectorRadius(finalPositionNoVelocity, dRadius, radianFromCenterDToTarget);

    var directionToSteeringVector = Vector2Wide.Normalize(Vector2Wide.Subtract(steeringVector, finalPositionNoVelocity));

    var accelerationDirection = directionToSteeringVector;

    position = PeekPath(TickConstants.HourTicks, position, ref velocity, accelerationDirection, acceleration);

    PathPoints.Add(position);
}

public Vector2Wide FindCoordinateOfVectorRadius(Vector2Wide center, double r, double radian)
{
    //x = r cos radian
    //y = r sin radian
    return new Vector2Wide(r * Math.Cos(radian), r * Math.Sin(radian)) + center;
}

```

# Answer
You're fixing your time horizon as always taking 1 hour to get to your destination.

```
var time = TickConstants.HourTicks;
var seconds = (double) time / TickConstants.SecondTicks;

```

Even if you've already spent 59 minutes flying, you continue re-plotting a new trajectory designed to bring you to the destination after 1 hour of *additional* flight from here - guaranteeing mathematically that you will *never* reach your goal.

You've also decided to always steer for a point at the outer limit of what you can accelerate to reach, even if your actual target point is closer/further. (In the general case, our target will *not* sit exactly on this circle, if it does not take *exactly* one hour to reach from here at max acceleration)

```
var steeringVector = FindCoordinateOfVectorRadius(finalPositionNoVelocity, dRadius, radianFromCenterDToTarget);

```

What we want to do instead (if you choose to go with the quadratic approach from the first link) is plan what time horizon we need to reach this point with a single constant acceleration burn. ie. at what time \\$T^\*\\$ does point \\$C\\$ lie exactly on the circle of radius \\$\frac {T^{\*2}} 2 a\_\text{max}\\$?

This involves solving the quartic equation:

$$||\vec C - \vec D|| = \frac {T^{\*2}} 2 a\_\text{max}\\ T^{\*4} \left(\frac {a\_\text{max}^2}2 \right) - T^{\*2}v^2 - T^\* \left(2 \vec v \cdot (\vec C - \vec A)\right) - \left(\vec C - \vec A\right)^2 = 0$$

I won't go into that here, but you can plug that into the math package of your choice and take the smallest positive real solution as your \\$T^\*\\$.

Once you've done that, you can calculate your point \\$\vec D = \vec A + T^\* \vec v\\$,

And your acceleration vector is then \\$\vec a = \frac {2 (\vec C - \vec D)} {T^{\*2}}\\$

And you can compute points along this path as...

```
for (int i = 0; i <= 100; i++) {
    double time = T * i/100.0;
    var positionAtTime = startPosition
                       + initialVelocity * time
                       + acceleration    * time * time / 2.0;
    PathPoints.Add(positionAtTime);
}

```

Note that we calculate our trajectory just once, then loop over its points to plot it. We don't plan a new trajectory at every iteration of the loop.

This will give you a trajectory travelling through your target point, but you might build up quite a lot of velocity on your way there. If you want to allow for braking or otherwise controlling your velocity at the destination point, you should use the cubic approach from my second link instead.
> 1 votes

# Answer
I fail to understand your code because it's early morning here and the code looks quite messy on mobile, but I have one thing that I think might be useful to you to determine where to start to decelerate.
You can find the distance threshold where the ship should start to decelerate to stop at the target position with velocity = 0.

The formula is:

```
float t = velocity / accel;
float d = velocity * t + accel * (t * t) / 2f;

```

In the case of linear deceleration when you decrease the velocity over time by simple subtraction:  `velocity -= accel`, the `d` will be the distance from the target where you should start to do that.
So, you find the distance from current position to target position, and then check if the distance is less than `d`, and if it is, you decrease the velocity by the acceleration value.
> 0 votes

---
Tags: c#, physics, movement, movement-prediction
---


# Question
Title: Google Play Game Services Detecting Top 3 Players
I used Google Play Services Leaderboard in my Libgdx game. This is what I want to do; I would like to give awards to the best 3 players in this table. How can I help you?

It automatically connects to the Google Play Services Leaderboard and I can show players' information in the game.

Please help

# Answer
The LeaderboardsClient.loadCurrentPlayerLeaderboardScore method returns a LeaderBoardScore that you can use to query the `rank` of the current player.
> 0 votes

---
Tags: java, libgdx, android, google-play-services, leaderboards
---


# Question
Title: Predict future position of a moving body in Phaser arcade physics
I am looking for an equation for predicting the future position of a moving arcade physics body in Phaser 3. The body has drag applied and isDamping set to true. Phaser applies the drag using the following run on each update (showing x axis only but same applies to y).

```
//  Damping based deceleration
dragX = Math.pow(dragX, delta);

velocityX *= dragX;

```

**Given the above, how would I write a kinetic equation to predict the future position?**

I am currently using the method below, where I am iterating over frames to calculate the position accumulatively. But this is inefficient and inelegant so would prefer a solution which estimates the position without any looping.

```
public futurePosition(timeInSeconds: number): Phaser.Math.Vector2 {
  const DELTA = 1 / 60; // Assume we are running at 60fps
  const DRAG = 0.3; // Drag value
  const position = this.position.clone(); // Current position of body
  const velocity = this.body.velocity.clone(); // Current velocity

  // Inefficiently looping through frames
  for (let i = 0; i < timeInSeconds / (DELTA * 1000); i++) {
    velocity.x *= Math.pow(DRAG, DELTA);
    velocity.y *= Math.pow(DRAG, DELTA);
    position.x += velocity.x * DELTA;
    position.y += velocity.y * DELTA;
  }

  return position;
}

```

Any help appreciated. Thanks.

# Answer
> 1 votes
Solved with a geometric progression.

```
public futurePosition(timeInSeconds: number): Phaser.Math.Vector2 {
  const fps = 60;
  const drag = Math.pow(0.3, 1 / fps);
  const x = ((this.body.velocity.x / fps) * (1 - Math.pow(drag, timeInSeconds * fps))) / (1 - drag);
  const y = ((this.body.velocity.y / fps) * (1 - Math.pow(drag, timeInSeconds * fps))) / (1 - drag);

  return new Phaser.Math.Vector2(this.position.x + x,  this.position.y + y);
}

```

---
Tags: physics, mathematics, physics-engine, phaser
---


# Question
Title: Transparent gui Shows another gui when it is not supposed to?
I am making a game in roblox. and in that game i need a Main-menu. and the main-menu gui is basically transparent and there is more guis behind in another `ScreenGui` those gui's are not supposed to show until the main menu is turned off. I have a post on `Scriptinghelpers.org` about this and it seems nobody knows the answer. My Post: https://scriptinghelpers.org/questions/117430/object-transparency-showing-not-what-its-not-supposed-to

# Answer
This is because Gui's stack on top of each other and other Gui objects (`Frames`, `TextButtons`, etc) can bleed through them if the top Gui has Transparent layers/parts.

To fix this just set the `Enabled` value to false for all the other Gui's and set it to true once the main Gui is disabled.
> 1 votes

---
Tags: gui, roblox
---


title: Free movement in a 3D isometric world

text:
# Question
Title: Free movement in a 3D isometric world
I'm currently experimenting with movement in a isometric perspective world and i'm thinking about how the movement should work. The movement can be either by WASD or gamepad.

Since the player can rotate the camera, what do you feel make a more natural movement? Pressing up would always move the character to the world z like this:

Or is it more natural to move forward in the characters direction when pressing up like this:

# Answer
The convention I've observed in most modern games is neither option you've proposed.

Instead, `W` or "Forward" on the stick usually corresponds to "Upward" on the screen from the current viewpoint, what we call "camera-relative" controls.

This way, the player does not need to attend to which compass direction they're currently looking toward, or the direction their character model is pointing. If the place they want to go is on the right half of the screen, they press right. If it's on the bottom half of the screen, they press down. This keeps the mental mapping very simple and intuitive.

We have lots of past Q&A about implementing this style of input and movement, in case that can be helpful to you.

In some isometric games, movement is restricted to travelling along the world axes, so only up-left / up-right / down-right / down-left is allowed. It sounds like this does not apply to your game. For those games, mapping `W` to "upward on the screen" doesn't quite work, so games will often rotate the mapping slightly, so your "up" key corresponds to "up-left" on the screen, for instance. The important thing here is that the mapping is consistent, so once the player learns it, they don't have to re-calibrate their mental link from screen to keys each time they turn their camera or character.
> 1 votes

# Answer
I feel like you should give the player the option to pick whichever one they prefer.
> 0 votes

---
Tags: unity, 3d, camera, movement, isometric
---


# Question
Title: How to handle movements of objects in a platformer with a cylindrical map?
I was wondering what would be the best approach for a game with a perspective like Resogun, where the world wraps around in a cylinder:

In my opinion, the easiest approach is to:

* have a "Center Parent" for each moving object
* Offset the child object by the wanted radius
* Rotate the parent

=\> The objects will move, though this will become super limited very quickly, especially if you want to do any sort of physics.

The 2nd approach is math:

```
x = centerX + cos(angle)*radius;
x = centerY + sin(angle)*radius;

```

Now i wonder if there is another way, I was thinking of another method which basically consist of changing the Forward direction of the moving objects based on their position in "the circle", so basically the objects always move forward but adjust their rotation according to their position so they are always facing the right angle.

My main question is that if you want to create a puzzle platformer game like Limbo for example, but in a "cylindrical" map like Resogun, how would you tackle it ?

Thanks!

# Answer
> 1 votes
One way is to internally handle everything in 2D, and remap the x-coordinate into a cylindrical space for your graphics.

Here's a very simple example. Attach this to an object that moves in 2D space to have it move a corresponding mesh renderer in cylinder space.

```
public class CylinderSpaceObject : MonoBehaviour {
    [SerializeField] private Transform cylinderCenter;
    [SerializeField] private float cylinderRadius = 5;
    [SerializeField] private GameObject renderer;

    void LateUpdate() {
        float rads = GetPositionRads();

        //convert rotation to cylinder space
        renderer.transform.rotation = transform.rotation * Quaternion.Euler(0, Mathf.Rad2Deg * rads, 0);

        //convert position to cylinder space
        //note we negate the value here so positive x values move counter-clockwise
        //we also add 90 degrees so our renderer is towards the camera when x = 0
        float positionRads = -rads + Mathf.PI / 2f;
        float x = Mathf.Cos(positionRads) * cylinderRadius;
        float z = Mathf.Sin(positionRads) * cylinderRadius;
        var offset = new Vector3(x, transform.localPosition.y, z);
        renderer.transform.position = cylinderCenter.position + offset;
    }

    float GetPositionRads() {
        float rads = transform.localPosition.x / cylinderRadius;
        return rads;
    }
}

```

Using this approach, all of your gameplay components (such as rigidbodies, colliders, etc) would be attached to the GameObject that has the `CylinderSpaceObject` component. The renderer would be a separate GameObject containing only rendering components.

---
Tags: unity, movement, geometry
---


title: Change value in arrays in array

text:
# Question
Title: Change value in arrays in array
The title might be confusing and I don't think this short explanation is 100% accurate, but I will try my best to show the problem. So I have this hierarchy:

And I want to change "measureOfTime" value in all subWave in wave\[i\], because I had no clue how to do this in a short way (at least I bet there is a shorter way) and I made this:

```
    using UnityEngine;

public class EnemySpawner : MonoBehaviour
{
    [Header("Set this value here to set time to 1 wave")]
    public float timeUntilWave;
    [Header("Measure Time basically = 0")]
    public Wave[] waves;
    public float waveTime;
    public bool roundStarted;
    public int wave;

    private void Start()
    {
        wave = -1;
        roundStarted = false;
    }
    private void Update()
    {
        if (timeUntilWave >= 0)
        {
            timeUntilWave = timeUntilWave - 1 * Time.deltaTime;
        }else if (timeUntilWave < 0)
        {
            roundStarted = true;
            wave++;
        }
        if (roundStarted == true)
        {
            waveTime = waveTime + 1 * Time.deltaTime;
            int subwaveLenght = waves[wave].subWave.Length;
            int count = 0;
            while (count <= subwaveLenght)
            {
                waves[wave].subWave[count].measureOfTime = waves[wave].subWave[count].measureOfTime + 1 * Time.deltaTime;
                count++;
            }
        }
    }
}

```

And in lines 33 and 37 I see an error: "IndexOutOfRangeException: Index was outside the bounds of the array."

And here are 2 questions: Why those errors appear here?

Is there an easier way to raise the value in arrays in an array?

I hope it's not too confusing, and thanks for your help!

# Answer
> 0 votes
An `IndexOutOfRangeException` happens whenever you try to access an array element with an index which is outside of the array.

Keep in mind that array indices start at 0, so the valid array indices are always one less than the length of the array. For example, when `subWave.Length` is `3`, then the available array indices are `[0]`, `[1]` and `[2]`. That means a loop `while (count <= subWave.Length)` will try to access `[0]`, `[1]`, `[2]` and then the illegal index `[3]`.

You could fix that problem by changing that line to `while (count < subwaveLenght)`. But there is a more readable and less error-prone way to do something with all entries of an array. A foreach loop:

```
foreach(var subWave in waves[wave].subWave) {
     subWave.measureOfTime = subWave.measureOfTime + 1 * Time.deltaTime;
}

```

Note that this will only work when subWave is a `class` and not a `struct`. When it is a struct, then the local variable `subWave` will be an independent copy of the array entry, and any changes you make to that copy will not automatically be written back to the original array.

---

Oh, and you are also not testing if `int wave` is out of range either. So that's the other source of `IndexOutOfRangeException`s which will occur as soon as you run out of waves. So:

```
    if (roundStarted == true && wave < waves.Length)
    {
         waveTime = waveTime + 1 * Time.deltaTime;
         foreach(var subWave in waves[wave].subWave) {
              subWave.measureOfTime = subWave.measureOfTime + 1 * Time.deltaTime;
         }
    }

```

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


# Question
Title: How do I set the size of a single 'unit' in my game?
I'm currently trying to remake/port an old game created on Unreal Engine 2.5 to my own engine, and I have access to its physics data. It's using a scale of 80 units per meter, or 1 unit = 1.25cm.

The walk speed value for example is 5, and physics is simulated at 60 FPS, so the walking speed I need to implement would be 3.75 meters per second.

But I don't exactly know what the size of a game engine's "unit" *actually means*. I of course want my own engine (I'm using C++, OpenGL, and GLM) to use this same scale, but I'm not sure how to go about that. I'd assume this affects not only physics/movement code, but the scale of models and maps I load in as well, so it's important to make sure it's the same as in the original game.

How would I implement this? What parts of a game does the size of a 'unit' affect and how? Just the physics and movement calculations, or the graphics side as well (matrices, clipping space, FOV, etc.)?

(I'm not sure if I'm overthinking things)

# Answer
> 2 votes
The length units, for 3D graphics, are whatever. As long as they are internally consistent, it does not matter. *For graphics.*

For physics units matter.

However, you do not set the units. There is nothing different in game engine or its settings. In fact, the units for most engine only exist in documentation and in the mind of people. *Except time, because time is time.*

---

Your game will have real units of time. You need to make your physics engine be consistent with that. In your engine, I suppose you would measure the elapsed time between frames, your `delta` time is some units. What units is that?

Figure out what is your unit for time. Then pick a unit for length. *You can write it down in comments, or in some means of communication to other developers, or in a piece of paper.* You are going to express everything with the units you picked.

For example, if you are trying to mimic earth gravity, and you set your gravitational acceleration to 9.8. What units is that? Well, that is meters over seconds squared. This means you are working with meters and seconds. You would have 980, if you were working with centimeters and seconds. 9800 for millimeters and seconds (also nanometers and milliseconds). 0.0000098 is meters and milliseconds. 0.0098 is millimeters and milliseconds. *I'll reluctantly mention 32.15 is feet and second*. And so on.

Remember that time is time. So getting speed and acceleration right, is important.

---

Of course, it makes sense to create models with whatever scale you are using for physics. What do I mean by that? Well, if you make a human, how many units tall should it be? Ah, units are whatever, but humans are around 1.6 meters tall. So, if you are working with meters, you make your human model 1.6 units. If you are working with centimeters, then it is 160 units. And so on. *The graphics don't care, but remember that the the physics do.*

If you create your models with the physics units, that will save you scaling the models. However, if you have to scale the models, that is not the end of the world. You would be using matrix transformations to place the models in the world anyway, it cost you nothing, *nothing*, to have those matrix transformations also scale the models appropriately.

# Answer
> 1 votes
The engine's units are whatever you want want them to be. Wether one unit is a centimeter and your character is 100 units tall, or one unit is a meter and your character is 1 unit tall, in both cases the result will be the same.
Plain numbers in a computer are unitless so you have to **decide** how to interpret them, i.e. what is their unit.

What's really important here is **consistency**. Your unit system has to be consistent throughout the whole application. Don't implement a function that works with altitude in meters, another one working with altitude in feet and send a probe to Mars.

In addition, you also want your system to be practical **for your context**: if you're implementing a game with normal-sized humans using time in seconds and distance in nanometers, you'll work with huge numbers that are impractical for the human brain (and incidentally can lead to problems with floating point numbers).
But the same problem arises if you're working on a game in which the entities are molecules and you choose the meter as a length unit.

---
Tags: physics, mathematics, movement, scale
---


# Question
Title: How to spawn one dummy for each "d" in the message string?
Im working on a script building game, I have the executor etc done. However, I have one problem. To spawn a test dummy, you say pse/d You can spawn no more than one dummy, how would I make it so if you say pse/d d d d, it spawns as many dummies as there is in the message

EG: pse/d (Spawns 1 dummy) pse/d d d d (Spawns 4 dummies)

Current code:

game.Players.PlayerAdded:connect(function(p)
p.Chatted:connect(function(msg)
msg = msg:lower()
if (msg == prefix.."d") then  if (p.Character ~= nil) then
    local d=game.ServerStorage.Dummy:Clone()
    d.Parent=workspace.Debris
    d:MoveTo(p.Character:FindFirstChild'HumanoidRootPart'.Position)
end
end
end)
end) ```
</code></pre>

# Answer
> 1 votes
My solution is using string.sub first to check if the command prefix is correct then to get external arguments.

**--\> CODE**

```
local Players = game:GetService("Players")

local CommandPrefix = "!call" -- Your Prefix
local PrefixLength = #CommandPrefix -- string is basically an array of characters therefor # operator will return it's length

local function PlayerChatted(Message)
    Message = string.lower(Message)

    local Pattern = string.sub(Message, 1, PrefixLength)

    if Pattern == CommandPrefix then --ends the scope if Command Prefix is not valid

        local Amount = string.sub(Message, PrefixLength+1, #Message)
        Amount = tonumber(Amount)

        if not Amount > 0 then return end

        for i = 1, Amount do
            -- create clones of dummies
        end

    end
end

Players.PlayerAdded:Connect(function(Player)
    Player.Chatted:Connect(PlayerChatted)
end)

```

# Answer
> 1 votes
What you can do is use `string.split()` to get a table return of items inside a string.

*Note: This will only work if you separate the d's with spaces(or any other character)*

## Code

```
local function PlayerChatted(msg)
    msg = string.lower(msg)

    if string.find(msg, "pse/") then
        msg = string.gsub(msg, "pse/") -- Gets rid of the prefix from the message
        local dTable = string.split(msg, "") -- Splits the string into a table using a seperator (" ")

        if #dTable > 0 then -- Making sure there are more than 0 d's
            for i=1, #dTable, 1 do
                -- Clone your dummies here
            end
        end
    end
end

game.Players.PlayerAdded:Connect(function(plr)
    plr.Chatted:Connect(PlayerChatted)
end

```

---
Tags: text, roblox
---


# Question
Title: Compile shader and root signature of a ray tracing shader into a single binary using DXC
I'm new to DXR, so please

If I got it right, when we want to compile a ray tracing shader using the DirectX Shader Compiler, we need to specify `lib_6_*` as the target profile.

Now assume I've got a HLSL file containing a single ray generation shader `RayGen` whose root signature is specified by a RootSignature attribute of the form

```
#define MyRS "RootFlags(LOCAL_ROOT_SIGNATURE),"  \
        "DescriptorTable("                  \
            "UAV(u0, numDescriptors = 1),"  \
            "SRV(t0, numDescriptors = 1))"
[rootsignature(MyRS)]
[shader("raygeneration")]
void RayGen() {}

```

Using `IDxcCompiler::Compile`, I'm able to compile both the shader itself using the target profile `lib_6_3` and the root signature using the target profile `rootsig_1_1`, but if I got it right it's not possible to invoke `IDxcCompiler::Compile` such that the created `IDxcBlob` contains both the shader and the root signature. (I've tried to add the argument `-rootsig-define MyRS` to the call for the compilation of the shader, but it seems to me that the compiler expects the root signature specified in this way to be a *global* root signature.)

So, I end up with two `IDxcBlob`'s. Is there any possibility to "merge" them into a single one which can later be used to specify the shader as well in a call of `ID3D12Device5::CreateRootSignature`?

# Answer
`ID3D12Device::CreateRootSignature` expects a pointer to the data, as well as the data length. You could combine your shader and root signature into one blob, but you'd need to know the offset from the start of the file to your signature (or if the signature were first, then when you create a shader you would need to know the offset from the start of the file to the compiled DXIL).

You could create a file that looked like this:

```
FileIdentifier
OffsetToShader
ShaderLength
OffsetToSignature
SignatureLength
ShaderData
...
...
...
SignatureData
...
...
...

```

Then when you load your custom file, you would have all of the data and data lengths at your disposal.

To write an `IDxcBlob`, you can access the raw data and size via it's functions:

```
struct IDxcBlob : public IUnknown {
public:
  virtual LPVOID STDMETHODCALLTYPE GetBufferPointer(void) = 0;
  virtual SIZE_T STDMETHODCALLTYPE GetBufferSize(void) = 0;
};

```

Then just write the data to a file with something like `fwrite`:

```
fwrite(blob->GetBufferPointer(), 1, blob->GetBufferSize(), fileHandle);

```
> 1 votes

---
Tags: directx, raytracing, directx12
---


# Question
Title: Move object to mouse direction without raycast?
I have script moving object to mouse postion using raycast. But what I need now is use the mouse movement to move my object.

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

public class HoverPanel : MonoBehaviour
{

public GameObject ground;
private Rigidbody rg;
public float moveForce, speed = 2;
public Vector3 Mouse_pos;

void Start()
{
    rg = gameObject.GetComponent<Rigidbody>();
}

void Update()
{

    rg.AddForce(Input.GetAxis("Vertical") * moveForce * ground.transform.forward);

    if (Input.GetAxis("Mouse X") < 0)
    {
        //Code for action on mouse moving left
        print("Mouse moved left z");
    }
    if (Input.GetAxis("Mouse X") > 0)
    {
        //Code for action on mouse moving right
        print("Mouse moved right z");
    }
    if (Input.GetAxis("Mouse Y") < 0)
    {
        //Code for action on mouse moving left
        print("Mouse moved back x ");
    }
    if (Input.GetAxis("Mouse Y") > 0)
    {
        //Code for action on mouse moving right
        print("Mouse moved forward x");
    }

}

void FixedUpdate()
{

  /// No need to use this
  /*
    RaycastHit hitGround;
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    if (Physics.Raycast(ray, out hitGround, 500))
    {
        Mouse_pos = new Vector3(hitGround.point.x, transform.position.y, hitGround.point.z);
        transform.localPosition = Vector3.Lerp(transform.localPosition, Mouse_pos, speed * Time.deltaTime);
    }
  */
}

```

}

# Answer
> 1 votes
```
public class MoveWithMouseDirection : MonoBehaviour
{
    public float speed = 2f;
    private Rigidbody rb;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

// Update is called once per frame
void Update()
{
    //Get the mouse axis input, turn it into a vector3 so we can simpifly movement.
    //normalize the vector3
    Vector3 mouseDirection = new Vector3(Input.GetAxis("Mouse X"), 0, Input.GetAxis("Mouse Y")).normalized;

    //Use the direction however you want
    //Make sure to multiply it by Time.deltaTime so it stays in sync with frame rate
    transform.Translate(mouseDirection * speed * Time.deltaTime);

    //or
    //rb.AddForce(mouseDirection * speed * Time.deltaTime);
}
}

```

Hopefully the comments are self explanatory but let me know if I didnt explain anything well enough.

But the gist of it is, we turn the mouse axis input into a Vector3 and use that to drive movement.

If you want to smooth the movement out you can use Vector3.MoveTowards or Vector3.Lerp (the exact same way you did for the local position) I opted to used MoveTowards

*With Smooth Interpolation*

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

public class MoveWithMouseDirection : MonoBehaviour
{
    public float speed = 2f;

    // Update is called once per frame
    void Update()
    {
        //Get the mouse axis input, turn it into a vector3 so we can simpifly movement.
        //normalize the vector3
        Vector3 mouseDirection = new Vector3(Input.GetAxis("Mouse X"), 0, Input.GetAxis("Mouse Y")).normalized;

        Vector3 lerpedValue = Vector3.MoveTowards(transform.position, transform.position - mouseDirection, speed * Time.deltaTime);
        transform.position = lerpedValue;
    }
}

```

You should change  `Vector3 lerpedValue = Vector3.MoveTowards(transform.position, transform.position - mouseDirection, speed * Time.deltaTime);` and either add or subtract the mouseDirection depending on wether you want the object to move in the mouse direction or opposite to it.

I also removed the rigidbody as this doesn't seem to be an object that would exist physically in-scene, the name Hover Panel makes me think this is UI so changing the transform is more appropiate.

---
Tags: unity
---


# Question
Title: pause Menu only working in one scene and not in others
Hi I'm working on a game for a school project but I'm still pretty new at game dev, I decided to add a pause menu to my game but for some reason, it only works in one of the scenes in unity, and I can't tell why it won't work on any of the other ones

Here is a video showing the problem: https://youtu.be/28fD9UEtfpg

and here is my script just in case

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

public class PauseMenu : MonoBehaviour
{
public static bool GameIsPaused = false;

public GameObject PauseMenuUI;

// Update is called once per frame
void Update()
{
    if (Input.GetKeyDown(KeyCode.Escape))
    {
        if (GameIsPaused)
        {
            Resume();
        }
        else
        {
            Pause();
        }
    }
}

public void Resume()
{
    PauseMenuUI.SetActive(false);
    Time.timeScale = 1f;
    GameIsPaused = false;
    Cursor.lockState = CursorLockMode.Locked;
    Cursor.visible = false;
}

void Pause()
{
    PauseMenuUI.SetActive(true);
    Time.timeScale = 0f;
    GameIsPaused = true;
    Cursor.lockState = CursorLockMode.None;
    Cursor.visible = true;
}
}

```

# Answer
> 2 votes
Some of the endless possibilities:

* You accidentally deleted the GameObject with the Event System component (as noted by DMGregory, this is not visible in the scene hierarchy in the second half of the video)
* An invisible UI element (such as an image with alpha set to 0) is covering the pause menu and blocking raycasts
* You have a canvas group in the pause menu hierarchy somewhere and accidentally unchecked "interactable" or "blocks raycasts"
* The canvas is missing a Graphic Raycaster
* "Raycast target" is unchecked on the button UI components in the Inspector
* You're getting some error that prevents the UI from working. Check the Console for errors (the Console is not visible in the video).

It looks like your code is working, since the cursor gets unlocked when the pause menu appears.

---
Tags: unity
---


title: Problems creating a biomes map

text:
# Question
Title: Problems creating a biomes map
I am working on an infinite procedural terrain generator and at the moment I am trying to generate a proper heightmap from a biomes map.

I'm not sure what is the best way in creating a proper biomes map, but I decided to use a cellular noise.

I have setup a simple biomes by providing a threshold and a noise generator for each of the biome.

When I generate a heightmap, I sample a biomes map and I get a biomes index by using a sampled value. Once I retrieve an index, I use a biome sample function to get a noise value at the position.

Currently this is the result I am getting

Which is expected, however I am currently struggling in blending these biomes seamlessly together. Also at the moment the biomes map defines these sharp regions, but instead I would like to make it more organic. I tried to blend the sampled cellular noise with a perlin noise, however it resulted in the same map.

I use this library in my code to generate noise maps: https://github.com/Auburn/FastNoiseLite/tree/master/CSharp

This is the whole code:

```
using System;
using UnityEngine;
using UnityEngine.UI;

public class BiomesMap : MonoBehaviour
{
    [SerializeField] RawImage output;

    const int size = 512;

    [SerializeField] int seed = 5;

    [SerializeField] Biome[] biomes;

    void Start()
    {
        for (int i = 0; i < biomes.Length; i++)
        {
            biomes[i].InitNoise(seed);
        }
        GenerateMap();
    }

    float[,] GenerateBiomesMap()
    {
        var noise = new FastNoiseLite(seed);

        noise.SetFractalType(FastNoiseLite.FractalType.None);
        noise.SetDomainWarpType(FastNoiseLite.DomainWarpType.BasicGrid);
        noise.SetFrequency(0.005f);
        noise.SetCellularJitter(1f);

        noise.SetNoiseType(FastNoiseLite.NoiseType.Cellular);
        noise.SetCellularDistanceFunction(FastNoiseLite.CellularDistanceFunction.EuclideanSq);
        noise.SetCellularReturnType(FastNoiseLite.CellularReturnType.CellValue);

        float[,] map = new float[size, size];

        for (int y = 0; y < size; y++)
        {
            for (int x = 0; x < size; x++)
            {
                map[x, y] = (noise.GetNoise(x, y) + 1) * .5f;
            }
        }
        return map;
    }

    void GenerateMap()
    {
        float[,] biomesMap  = GenerateBiomesMap();

        float[,] heightmap = new float[size, size];
        for (int y = 0; y < size; y++)
        {
            for (int x = 0; x < size; x++)
            {
                var value = biomesMap[x, y];
                int biomesIndex = GetBiomeIndex(value);

                if (biomesIndex == -1) { Debug.LogErrorFormat("Biome not found. {0}", value); return; }

                heightmap[x, y] = biomes[biomesIndex].Sample(x, y);
            }
        }
        Output(heightmap);
    }

    int GetBiomeIndex(float value)
    {
        for (int i = 0; i < biomes.Length; i++)
        {
            if (value <= biomes[i].threshold)
            {
                return i;
            }
        }
        return -1;
    }

    void Output(float[,] heightmap)
    {
        Color[] pixels = new Color[size * size];

        for (int y = 0; y < size; y++)
        {
            for (int x = 0; x < size; x++)
            {
                float value = heightmap[x, y];

                pixels[x + (y * size)] = new Color(value, value, value, 1);
            }
        }
        Texture2D result = new Texture2D(size, size);
        result.SetPixels(pixels);
        result.Apply();

        output.texture = result;
    }
}
[Serializable()]
public class Biome
{
    public string name;

    [Range(0, 1)]
    public float threshold;
    public NoiseGenerator noiseParameters = new NoiseGenerator();

    FastNoiseLite noise;

    public void InitNoise(int seed)
    {
        noise = new FastNoiseLite();

        noise.SetSeed(seed);
        noise.SetNoiseType(noiseParameters.noiseType);
        noise.SetFrequency(noiseParameters.frequency);

        noise.SetFractalType(noiseParameters.fractalType);
        if (noiseParameters.fractalType != FastNoiseLite.FractalType.None)
        {
            noise.SetFractalOctaves(noiseParameters.octaves);
            noise.SetFractalLacunarity(noiseParameters.lacunarity);
            noise.SetFractalGain(noiseParameters.gain);
            noise.SetFractalWeightedStrength(noiseParameters.weightedStrength);
            noise.SetFractalPingPongStrength(noiseParameters.pingPongStrength);
        }
        if (noiseParameters.noiseType == FastNoiseLite.NoiseType.Cellular)
        {
            noise.SetCellularDistanceFunction(noiseParameters.distanceFunction);
            noise.SetCellularReturnType(noiseParameters.cellularReturn);
            noise.SetCellularJitter(noiseParameters.cellularJitter);
        }
        noise.SetDomainWarpType(noiseParameters.domainWarpType);
        noise.SetDomainWarpAmp(noiseParameters.amplitude);
    }
    public float Sample(float x, float y)
    {
        return (noise.GetNoise(x, y) + 1) * .5f;
    }
}
[Serializable()]
public class NoiseGenerator
{
    [Header("General")]
    public FastNoiseLite.NoiseType noiseType;
    public float frequency;

    [Header("Fractal Noise")]
    public FastNoiseLite.FractalType fractalType;
    [Range(1, 10)]
    public int octaves;
    public float lacunarity;
    public float gain;
    public float weightedStrength;
    public float pingPongStrength;

    [Header("Cellular Noise")]
    public FastNoiseLite.CellularDistanceFunction distanceFunction;
    public FastNoiseLite.CellularReturnType cellularReturn;
    public float cellularJitter;

    [Header("Domain Wrap")]
    public FastNoiseLite.DomainWarpType domainWarpType;
    public float amplitude;
}

```

# Answer
The problem is blending between borders right? It can be trickier than it sounds. I wrote an article on this exact problem recently. Basically, sample scattered points much like the Voronoi diagram itself uses, except at a higher resolution, and use the data points to generate blending data. Here's the article https://noiseposti.ng/posts/2021-03-13-Fast-Biome-Blending-Without-Squareness.html At the end, there is a link to Java code which should be straightforward to port to C#.

Blending is separate to biome map generation itself. You can go more involved, especially if you want to control which biomes border which. Then you can try temperature and humidity maps, or other methods of generating maps with more complex rulesets. But you don't have to worry about that immediately.

Sidenotes regarding your noise: FastNoiseLite is a great lib, but if you're going to use the Perlin option in it, I would do the following to avoid its characteristic square bias. Take it with a grain of salt when tutorials recommend Perlin noise with no caveats. Perlin is an older noise algo that, without the included 3D domain-rotation technique (SetRotationType3D), produces a lot of squareness that is an entirely unnecessary compromise for most applications.

```
noise.SetRotationType3D(FastNoiseLite.RotationType3D.ImproveXYPlanes);

```

then do

```
public float Sample(float x, float y)
{
    if (perlin -- or value, or value-cubic)
        return (noise.GetNoise(x, y, 0) + 1) * .5f;
    else
        return (noise.GetNoise(x, y) + 1) * .5f;
}

```
> 1 votes

---
Tags: unity, c#, procedural-generation, heightmap
---


# Question
Title: How to make two keys pressed to make an action?
Hey i am beginner gamedev. I couldn't find answer to this or I am bad articulating my problem. But really would like an answer to this. **How can i make function to press two keys like A and D at the same time to make a jump animation if A and D are already taken separately to A = walk left and D = to walk right? **Without them overlapping**.**

```
func _input(event):

if event.is_action_pressed("left") && event.is_action_pressed("right"):
    $DancerSprite.play("bluedouble")

if event.is_action_pressed("left"):
    $DancerSprite.play("blueleft")
    return

elif event.is_action_pressed("right"):
    $DancerSprite.play("blueright")
    return

```

# Answer
> 3 votes
Let us start with simple input. First of all, set your actions in the Input Map in project settings.

Now, there are two ways to go about getting input. You can add a `_input` function:

```
func _input(event):
    if event.is_action_pressed("action"):
        print("action start")

    if event.is_action_released("action"):
        print("action end")

```

Or you can use `Input.is_action_pressed` in your `_physics_process`:

```
func _physics_process(delta):
    if Input.is_action_pressed("action"):
        print("action is ongoing")

```

---

If you don't care if they actions were pressed previously, then using `_physics_process` it is easy to check for both "at the same time":

```
func _physics_process(delta):
    var a = Input.is_action_pressed("action_a")
    var b = Input.is_action_pressed("action_b")
    if a and b:
        print("both")
    elif a:
        print("a")
    elif b:
        print("b")

```

Except, we don't know for how long one was pressed before the other.

---

If the the player has one action pressed, and pressed the other… With the above code, the combined action would trigger. What if you wanted to distinguish if the player released and then pressed both concurrently?

In that case, we need to keep track if the action ongoing with a variable. So either do this:

```
var action_ongoing = false

func _input(event):
    if event.is_action_pressed("action"):
        action_ongoing = true

    if event.is_action_released("action"):
        action_ongoing = false

```

Or this:

```
var action_ongoing = false

func _physics_process(delta):
    action_ongoing = Input.is_action_pressed("action")

```

---

And for the combined action, you can do this:

```
var a_ongoing = false
var b_ongoing = false

func _physics_process(delta):
    var a = Input.is_action_pressed("action_A")
    var b = Input.is_action_pressed("action_B")
    if a and b:
        if !a_ongoing and !b_ongoing:
            print("both together")
        elif !a_ongoing:
            print("b then a")
        elif !b_ongoing:
            print("a then b")

    elif a and !a_ongoing:
        print("a!")
    elif b and !b_ongoing:
        print("b!")

    a_ongoing = a
    b_ongoing = b

```

---

Please notice that they weren't really pressed at the same time. They just were pressed close enough in time that they register at the same time. That is the time from one input to the other was short enough.

What if we wanted control over that time interval?

Well, let us keep track of the instant the action was pressed!

We can use `OS.get_ticks_msec()` to get milliseconds from engine start. If store the time for one input, when we get another input we can compare the time and decide if they are close enough in time.

I'll add a `max_milliseconds` variable, and if the time between one action is pressed and the other is less than that, we say they happened together.

It is time for `_input` to shine:

```
var a_time = null
var b_time = null
var max_milliseconds = 100

func _input(event):
    var now = OS.get_ticks_msec()
    if event.is_action_pressed("action_A"):
        if b_time != null:
            if now - b_time < max_milliseconds:
                print("both together")
            else:
                print("b then a")
        else:
            print("a!")

        a_time = now

    if event.is_action_released("action_A"):
        a_time = null

    if event.is_action_pressed("action_B"):
        if a_time != null:
            if now - a_time < max_milliseconds:
                print("both together")
            else:
                print("a then b")
        else:
            print("b!")

        b_time = now

    if event.is_action_released("action_B"):
        b_time = null

```

---
Tags: godot, gdscript
---


# Question
Title: Path solving for a game with a similiar pathing mechanic to Anno
I cant quite wrap my head around how to solve pathing in my game. The basic premise is you will place buildings and roads on a 2d field and then you will be able to create routes from one building to another where the pathing alghorithm should figure out the shortest path between them (if there is one).

Something to keep in mind is that the game is going to be quazi infinite scale (think factorio) and i cant think of a performant enough solution.

Currently what i am working with is that i have every straight Path segment saved as two (startPoint, endPoint) Vector2Int points in a list. And everytime a new road gets added or some road segment deleted i update this list depending on what happened, example situation:

I have this road

```
-----|
     |
     |
     |-----
This would be represented in my Roads list as:
0 = startPoint(0, 0) -> endPoint(5, 0)
1 = startPoint(5, 0) -> endPoint(5, 3)
2 = startPoint(5, 3) -> endPoint(10, 3)

I now add another road so we have something like this
-----|
     |
 ----|
     |-----
Which would change the road list to something like:
0 = startPoint(0, 0) -> endPoint(5, 0)
1 = startPoint(5, 0) -> endPoint(5, 2)
2 = startPoint(5, 2) -> endPoint(5, 3)
3 = startPoint(1, 2) -> endPoint(5, 2)
4 = startPoint(5, 3) -> endPoint(10, 3)

```

What i am doing currently when a new route is to be calculated is that i create a 2d bool array which i am feeding into a A\* solver to get the shortest path so the above road gets transformed into:

```
1 1 1 1 1 1 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0
0 1 1 1 1 1 0 0 0 0 0
0 0 0 0 0 1 1 1 1 1 1

```

With some starting and endpoint.

This works fine for now but when the player will build on a huge size 10kx10k, i cant imagine generating 10kx10k bool array everytime will be a good solution.

Anybody knows how to optimize this?

# Answer
> 0 votes
The answer is pretty simple, depending on the structure of your game i can think of two possible solutions:

1. Chunking. Since in a theoretical-infinite map you have to load and free parts of the world in order to consume a reasonable amount of memory, you could just chunk the paths too and determine for path-finding the chunks the two points lay in, and (if needed) calculate a line from the two points and identify the chunks this line crosses (so you have the chunks "in between"). After that apply the A\* algorithm to the path-points in the identified chunks. This should be fairly easy and the general approach to such games. Of course depending on the complexity of your game you could also just use any path points that are present in the chunks of the currently loaded part of the world.
2. You would need some kind of structure to select path-points by their positions (chunking again would be a solution, but theoretically 2d hashing would work too). After that, imagine a vector connecting start and end point, calculate the center and select any path point in a given radius (depending on how big your "search" radius should be) from that center and apply the A\* algorithm. For a big radius you could speed up the calculation by precalculating subgraphs/subsets i.e. grouping connected paths, or identifying bridges which connect other subsets etc.

So basically it boils down to selecting a subset of all path-points for the A\* algorithm. Theoretically you could also modify the A\* algorithm to work with a infinite set of path points (because of the implemented heuristic assumptions it *should* find a way, except when there is no way in which case you would stop the algorithm at a given count of iterations)

---
Tags: unity, algorithm, path-finding
---


# Question
Title: How to get normals from volume density grid?
I am meshing my volume density data with marching cubes. The density data is a flat array and it's elements contain a) distance from surface, b) a normal (xyz). However this normal is for the density grid point, no the calculated vertexes. So having this data can i calculate normal for each vertex?

# Answer
> 0 votes
I ended up taking the volume outside point normal and inside point normal and doing a lerp between them, where the lerp value is density float. This is how I get normals from SDF while creating volume gird:

```
float H = 0.001;
float dx = sdfFunc(Vector3(xPos + H, yPos, zPos)) - sdfFunc(Vector3(xPos - H, yPos, zPos));
float dy = sdfFunc(Vector3(xPos, yPos + H, zPos)) - sdfFunc(Vector3(xPos, yPos - H, zPos));
float dz = sdfFunc(Vector3(xPos, yPos, zPos + H)) - sdfFunc(Vector3(xPos, yPos, zPos - H));

float dlen = sqrt(dx * dx + dy * dy + dz * dz);

if (dlen > 0.0) {
  float mul = 1.0 / dlen;
  dx *= mul;
  dy *= mul;
  dz *= mul;
}

```

And when calculating vertices with marching cubes I do something like that:

```
Vector3 nn = Vector3();

nn.X = (1 - t) * an.X + t * bn.X;
nn.Y = (1 - t) * an.Y + t * bn.Y;
nn.Z = (1 - t) * an.Z + t * bn.Z;

```

where `an` is inside point and `bn` is outside point normal and `t` is calculated density float (vertex place along he edge).

# Answer
> 1 votes
To find the surface normal for any given marched cube, just average the face normals for all of the 1-5 triangles that are generated. A face normal is calculated here:

```
for (vector<triangle>::const_iterator i = triangles.begin(); i != triangles.end(); i++)
{
    // Get face normal.
    vertex_3 v0 = i->vertex[1] - i->vertex[0];
    vertex_3 v1 = i->vertex[2] - i->vertex[0];
    normal = v0.cross(v1);
    normal.normalize();

    ...

```

Don't forget to sort the vertices before you perform the linear interpolation. If you use floats, which appears so, then you will experience cracks in the mesh. Taubin smoothing of the mesh turns those cracks into holes. If you sort the two vertices beforehand, then no cracks appear. If you use doubles, then no cracks appear. Just my 2 cents.

```
vertex_3 marching_cubes::vertex_interp(const float isovalue, vertex_3 p1, vertex_3 p2, float valp1, float valp2)
{
    // Sort the vertices so that cracks don't mess up the water-tightness of the mesh.
    // Note: the cracks don't appear if you use doubles instead of floats.
    if (p2 < p1)
    {
        vertex_3 tempv = p2;
        p2 = p1;
        p1 = tempv;

        float tempf = valp2;
        valp2 = valp1;
        valp1 = tempf;
    }

    const float epsilon = 1e-10f;

    if(fabs(isovalue - valp1) < epsilon)
        return(p1);

    if(fabs(isovalue - valp2) < epsilon)
        return(p2);

    if(fabs(valp1 - valp2) < epsilon)
        return(p1);

    float mu = (isovalue - valp1) / (valp2 - valp1);

    return p1 + (p2 - p1)*mu;
}

```

where:

```
inline bool operator<(const vertex_3 &right) const
{
    if(right.x > x)
        return true;
    else if(right.x < x)
        return false;

    if(right.y > y)
        return true;
    else if(right.y < y)
        return false;

    if(right.z > z)
        return true;
    else if(right.z < z)
        return false;

    return false;
}

```

---
Tags: voxels, normals, marching-cubes
---


# Question
Title: Measure a distance between the start and end of a drag
I tried to measure a distance from one point to another point on my phone screen by using following code:

```
Vector3 startPoint;
Vector3 endPoint;
public Camera cam;
float distanceX;

void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        Vector3 startPoint = cam.ScreenToWorldPoint(Input.mousePosition);
    }

    if (Input.GetMouseButtonUp(0))
    {
        Vector3 endPoint = cam.ScreenToWorldPoint(Input.mousePosition);

        distanceX = Mathf.Abs(startPoint.x - endPoint.x);
        Debug.Log(distanceX);
    }
}

```

But this code does not give me the correct result and I don't know why...

> Editor's note: this is where you should write what result the code *does* return and how that result differs from the result you *expect* for a specific test case, or several.

# Answer
> 2 votes
There are some obvious mistakes here. Firstly:

```
Vector3 startPoint = cam.ScreenToWorldPoint(Input.mousePosition);

```

This does not store your start position in your member variable `startPoint` so you can read it back on a later frame. This creates a *new* temporary variable called `startPoint` that you throw away at the end of the function - we say that this temporary variable "shadows" the member variable, so any references their shared name will refer to the temporary instead of the member variable as you intended. Remove the `Vector3` in front to use the member variable instead.

Secondly, you don't provide a depth value to `ScreenToWorldPoint`. This can still work if your camera is orthographic, but if you're using a perspective camera then you're asking "What's the position on this ray at a distance of 0 units from the camera?" - no matter what screen position you use for that ray, the answer is always the camera's own position.

You may want to assign `Input.mousePosition` to a `Vector3` variable, and set its z coordinate to your chosen depth. Or fire a ray using `ScreenPointToRay` and check where that ray intersects your scene, using the hit position as your `start`/`endPoint`.

Thirdly, this only measures distances along the world x axis. You can use `Vector3.Distance()` if you want to measure the distance on all axes. Or, if you want to measure a pixel distance on your screen, you can skip the `ScreenToWorldPoint` conversion entirely, and work with your `Input.mousePosition` `Vector2`s directly.

---
Tags: unity, vector, mouse, linear-algebra
---


# Question
Title: Find closest point on NavMesh if current target unreachable
I have a mock environment set up with a cube that has a specified "Not Walkable" layer. I'm using NavMeshAgent and NavMeshPath to set destinations of the player. The way I'm setting paths is by ray-casting points on the terrain by mouse clicking.

I'm having trouble figuring out a way to fix if I click on the cube that has a "Not Walkable" layer, the player just runs into the cube and tries to reach that point.

I've read about the FindClosestEdge function in unity but I don't think that's exactly what I'm looking for.

So basically I need the target location to change to the nearest point **next** to the cube when I click **on** the cube.

Any ideas?

# Answer
I'm wondering about this too! Sad to see there aren't any replies.

I did something *similar* -- parts not included for walking in the navmesh, like static objects in the scene, would be a problem when my agent would get to them and just continue to walk and walk.. and walk. Maybe this can be of use to you.

For now, I worked something up so that my agent walks as close as it can to an area that's not on the navmesh then stops and I clear the path.

I put these in an if statement in my update and check to see if the destination has been reached. Checking if the type of path is partial (I think: part of it is unreachable) and then if we have a path to the desired position (it seems to be true if we can do any more movement, then false when we reach the block).

```
agent.pathStatus == NavMeshPathStatus.PathPartial && !agent.hasPath

```

This way, even when I click on something that's not walkable, like inside a block, it walks as close as it can and stops. Then I have it abandon the path.

Here's what I'm using, until I can find something better. It checks if the agent has reached the destination. There's also my code in that block to see if the agent has reached the destination when the path isn't partial so that I can control my walking and idle animations. isMoving is set when a destination is set for the agent. It's kind of a mouthful. The stuff relevant to the partial path is above, you can check it out in use below if you're interested.

```
   if (isMoving && !agent.pathPending)
    {
        if ((agent.pathStatus == NavMeshPathStatus.PathPartial && !agent.hasPath) ||
            ((Vector3.Distance(agent.destination, agent.transform.position) <= agent.stoppingDistance) &&
             (!agent.hasPath || agent.velocity.sqrMagnitude == 0f)))
        {
            Debug.Log("reached destination");
            isMoving = false;
            anim.SetBool("IsRunning", isMoving);

            agent.ResetPath();
        }

    }

```

I'm still new to unity, so I'm not sure if this is the optimal way that this could be done. If anyone has input, I'd be happy to hear it!

**EDIT:** I was messing around a bit (something smelled off...) and I *think* some of that code was redundant. I tested it under the same conditions as the other code and I get the same results with just:

```
   if (isMoving && !agent.pathPending && !agent.hasPath)
    {
        Debug.Log("reached destination");
        isMoving = false;

        anim.SetBool("IsRunning", isMoving);
        agent.ResetPath();
    }

```
> 1 votes

# Answer
I'm working on a similar problem and although I haven't tested it yet, I think you can use NavMesh.Raycast starting from the user's position and place the cube wherever the ray hit's position is. Hope this helps.
> 0 votes

# Answer
You just precalculate the path like for example :

`if (Input.GetMouseButtonDown(0)) { navAgent.CalculatePath(point,navAgent.path); /*bool*/ pathComplete = false; }` Then out of the box you ask

```
if(pathComplete == false) {
if(navAgent.path.status == NavMeshPathStatus.PathComplete ||
navAgent.hasPath && navAgent.path.status == NavMeshPathStatus.PathPartial) {

navAgent.SetDestination(point);
pathComplete = true;
   }
}

```

The **navAgent.destination** will be the closest point to the destination on a walkable Area!

The problem is, when you dont precalculate the path and set the Destination of your navAgent multiple times a second, the destination will always be the exact point, you set your destination to! So after precalculating the path and `navAgent.SetDestination(point);` the closest reachable point for your NavAgent will be simply the `navAgent.destination`! Thats it.
> 0 votes

---
Tags: unity, collision-detection, collision-avoidance, navmesh
---


# Question
Title: How do I draw 2D textures with Direct3D 11.1?
I'm running into trouble trying to figure out the best way to draw textures to the screen using Directx 11.1 (for Metro apps).

In XNA, I used SpriteBatch. Is there something partially comperable?

In the Win8 SDK examples, they used WIC and Bitmap, although it suggests that that is not the best way to draw 2D graphics with the best performance.

# Answer
> In XNA, I used SpriteBatch. Is there something partially comperable?

No. Direct3D is a *low-level* rendering system. It's job is not to make your life easier (like XNA); it's job is to provide a bare-bones interface to graphics hardware.

You do not "draw textures" in D3D. You draw *triangles*, which have textures mapped onto them with shaders. Two triangles form a rectangle or "quad" (short for quadrilateral), which is how you draw textures.

To do this in D3D, you need to fill a vertex buffer with the vertex positions and texture coordinates for the triangles you want to render. You will also need a (very simple) pair of shaders, vertex and pixel, which pass your positions and texture coordinates. Your pixel shader needs to use the texture coordinate it gets from the vertex shader to fetch from the texture. And that texture's color becomes the pixel shader output.

You use all of these, the two shaders, the texture, and the vertex buffer, to render.

Low-level isn't easy, and it's not meant to be.
> 4 votes

# Answer
> In XNA, I used SpriteBatch. Is there something partially comperable?

Now there is, yes. :) It's called the DirectX Tool Kit. Not as full-featured and mature as XNA, but it seems to get the job done and has been created by members of the orignal XNA team. Worth checking out.
> 2 votes

# Answer
Just make a bitmap and draw it:

```
D2D1_SIZE_U             size;
D2D1_BITMAP_PROPERTIES1 bitmapProperties;

size.width = m_width;
size.height = m_height;

bitmapProperties.bitmapOptions = D2D1_BITMAP_OPTIONS::D2D1_BITMAP_OPTIONS_NONE;
bitmapProperties.colorContext = nullptr;
bitmapProperties.dpiX = 96;
bitmapProperties.dpiY = 96;
bitmapProperties.pixelFormat.format = DXGI_FORMAT_R8G8B8A8_UNORM;
bitmapProperties.pixelFormat.alphaMode = D2D1_ALPHA_MODE::D2D1_ALPHA_MODE_PREMULTIPLIED;

ThrowIfFailed(
m_videoDevice->GetD2DDeviceContext()->CreateBitmap(size, m_data, m_pitch, &bitmapProperties, &m_bitmap)
);

m_videoDevice->GetD2DDeviceContext()->BeginDraw();

D2D1_RECT_F r;

r.left = 10;
r.bottom = 400;
r.right = 200;
r.top = 10;

m_videoDevice->GetD2DDeviceContext()->DrawBitmap(m_imageManager->GetImage("./Assets/starryAlpha.tga")->m_bitmap.Get(), &r);

// Ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
// is lost. It will be handled during the next call to Present.
m_videoDevice->GetD2DDeviceContext()->EndDraw();

```
> 0 votes

---
Tags: 2d, directx, rendering
---


# Question
Title: Combining a pure ECS with a FSM scheduling system
Currently I am evaluating how to refactor my core game logic since I tried to design most of it in pure ECS but isn't really completely feasible the way I intended it.

My game at its core is a turn-based roguelike with multiple (implicit) phases during a turn:

* Player Action Phase: Movement, Attack or Item Usage
    + If the chosen action was Attack or Item Usage, handle it right away
    + Otherwise, queue a Movement intent
* Movement Phase: All units that decided to move will move simultaneously
* Attack Phase: All enemy units that haven't moved will attack one-by-one
* End Phase: Resolve status effects

These phases have been difficult to design with ECS. Certain systems have checks whether the should run right now with a bunch of tag components. Examples include:

* The BehaviorSystem updates enemy entities, that are currently thinking (applied after any player actions have been resolved), but have neither finished their turn yet and are not suppressed by anything (usually used to await animations).
* The AttackerSelectionSystem that only runs when no movement or attack animation is currently playing and then only picks enemies that still have to attack, sorts them by initiative and tags the next enemy to start his attack during the next frame.

Eventually my current architecture won't scale well with more and more systems to come, especially with different kinds of game states such as game elements that are UI only, in-town/hub maps where I don't need any of these combat/turn-based elements and finally the instance/dungeon areas where I will need them.

---

My idea is now to include a FSM in my Game class decoupled from the ECS itself to handle my current approach to invoke systems:

```
auto Game::Implementation::updateSystems(const sf::Time DeltaTime) -> void {
  updatePlayerControllers(Registry, InputManager, Tilemap);
  updateBehaviors(Registry, Tilemap);
  updateMovementAnimations(Registry, DeltaTime);
  updateAttackerSelection(Registry);
  updateAttackAnimations(Registry, DeltaTime);
  updateDamageEvents(Registry, ContentManager);
  updateFloatingCombatTextAnimations(Registry, DeltaTime);
  updateEndOfTurn(Registry);
  updateLocalToWorldTransforms(Registry);
  updateSpriteRendererTransforms(Registry);
  updateEntityRemovals(Registry);
}

```

Now I am evaluating how to implement this in a clean way. I fear with too many states I might end up with spaghetti scheduling using weird if/switch constructs. Alternatively I could add a check at the beginning of each system whether the current state of the FSM/game allows them to even run.

Finally a most sophisticated approach would most likely be a dependency graph with conditions that will schedule the systems to run each frame.

Are there any common patterns and approaches to handle this scheduling based on game/turn state?

# Answer
> 1 votes
### Flat update loop

The multi-phase design may be the root of the problem, because it creates a dependency graph of its own, misaligned to ECS's dependency graph. The most direct solution would be to express the phases as a single ECS update.

If certain update function needs to be called multiple times (i.e. in different phases) during the update loop, you can pass the phase argument to that function. Even better, you could tell it what exactly you want in terms more specific than a phase. Like this:

```
updateMovement(playerOnly = true);
//...
updateMovement(playerOnly = false);

```

To alternate between player's turn and everyone else's, it may be okay to keep phases, but just 2 of them as a simple if-else branch. Alternatively, you may think of an animation queue, that may be played once calculations are complete.

### Entity tracking lists

The issue of update sparsity (i.e. updates are skipping lots or most of the entities) in ECS is solved with entity lists. Ideally, you are supposed to use the entity lists from very beginning, to track which entities are relevant to which update function. The lists must be updated every time entity is created, modified or destroyed.

This approach may be applied to other aspects, such an AI or animation state (those may be FSMs). Allocate a list for each possible state (non-enums must be compressed to enums with clever mapping) and move entities between lists according to their current state. You also want to encapsulate the state to automate the list transfers.

---

These were the core issues, everything below is tangential.

---

One of they key features of rogue-likes is non-modality: one control scheme is used for all gameplay interaction. Picking item from the shelves and interacting with the cash register to deposit the money is the canonical way of trading, while displaying separate UI is antithetical to that.

Not saying that it's a silver bullet, but so far as a player I find that more enjoyable — partly because an "immersive" design promotes well-thought shopping list of really valuable items, while most shopping UIs welcomed me to the bottomless repositories of garbage.

Non-modality should also play well with the ECS design.

---
Tags: architecture, state, entity-component-system, fsm
---


# Question
Title: Starting a Coroutine after another Coroutine ends
I have a method that fades the screen to black, then fades away back again using coroutines but I couldn't get the 2nd part to work.

`FadeToBlack()` works if I put `yield return null` instead of `yield return StartCoroutine(LightUp());` so I know that isn't the problem

```
 private IEnumerator FadeToBlack()
{

    for (float t = 0.01f; t < fadeOutTime; t += Time.deltaTime)
    {

        color = new Color(0, 0, 0, 1);
        night.color = Color.Lerp(night.color, color, Mathf.Min(1, t / fadeOutTime));
        yield return StartCoroutine(LightUp());

    }}

```

If I put yield return `StartCoroutine(LightUp());` in FadeToBlack instead of null it immediately turns black without the fading part. Here's what `LightUp();` looks like

```
private IEnumerator LightUp() {
    for (float t = 0.01f; t < fadeOutTime; t += Time.deltaTime)
    {
        color = new Color(0, 0, 0, 0);
      Color colorD = new Color(0, 0, 0, 1);
        night.color = Color.Lerp(colorD, color, Mathf.Min(1, t / fadeOutTime));

        yield return null;

    }
}

```

# Answer
You want to start your fade back to light coroutine *after* your fade to black loop has finished *all* of its work, not once in every iteration of the loop (ie. every frame the black fade is supposed to be updating).

Move it outside the loop like so:

```
private IEnumerator FadeToBlack()
{
    Color originalColor = night.color;

    for (float t = 0.01f; t < fadeOutTime; t += Time.deltaTime)
    {
        night.color = Color.Lerp(originalColor, Color.black, t / fadeOutTime);
        yield return null;
    }

    yield return StartCoroutine(LightUp());
}

```

I also corrected your lerp, which included a common error that makes the time adjustment incorrect.

We can even combine FadeToBlack and LightUp into one to remove the redundant code, then just call the coroutine twice:

```
public class FadeTest : MonoBehaviour
{
    public Image night;
    public float fadeOutTime = 1f;

    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine(FadeThroughBlack());
    }

    private IEnumerator FadeThroughBlack() {
        yield return FadeTo(Color.black);
        yield return FadeTo(Color.clear);
    }

    private IEnumerator FadeTo(Color destination) {
        Color originalColor = night.color;

        for (float t = 0.01f; t < fadeOutTime; t += Time.deltaTime) {
            night.color = Color.Lerp(originalColor, destination, t / fadeOutTime);
            yield return null;
        }

        night.color = destination;
    }
}

```

I've tested this and verified that it correctly fades the image to black, then fades it to transparent. If you don't observe this then you should edit your question to include a minimal complete verifiable example of the problem you're seeing.
> 2 votes

---
Tags: unity, c#, color, unity-ui
---


# Question
Title: How to construct a octree density from SDF for MC
It very clear how it works with a regular grid. 3 inner loops - x, y, z over some size. The smaller the cells, so will be the mesh more detailed.

But how about octree. I know i can stich different levels with transvoxel (not sure with what max difference), but no idea how to construct the tree from SDF. It kind of needs to know if a cell is occupied and then split and so on? But how?

Or maybe octrees are bad idea for marching cubes and isn't practiced (then what about ray cast)?

# Answer
> 1 votes
You use the octree to skip swaths of work.

Anytime you find an octree node that's fully outside or fully inside the volume, you can skip iterating any cells inside it because you know the surface won't cross any of them, so marching cubes will no need to create any vertices or triangles in that entire cubic region.

Your algorithm can be a depth-first traversal of the octree. Starting from the node that covers your entire space, then descending into one of its 8 children each half the width of your space, then into one of its 8 children (grandchildren of your original) that each span a quarter of the width of your space, etc.

Each time you evaluate a node, sample your SDF at its center. If the absolute value of this sample is greater than `nodeWidth * sqrt(3)/2` then the level set of your SDF is further away than any corner of the node, and so doesn't cross this node at all.

In that case, you can skip descending into any of that node's children (and grandchildren, etc), because none of them will generate any geometry. You skip ahead in your traversal to the node's next sibling instead. Or, if you've run out of siblings, the parent's next sibling, etc.

If the absolute SDF value is not that high, then it's possible the surface crosses this node, and you recurse into its smaller children as normal.

When you get down to a threshold node size, you can iterate over all the individual voxels contained inside it in the normal triple-for-loop way you're used to.

The advantage is that you only have to do this for leaf nodes that are very close to your surface, and can skip iterating the majority of lattice points in your space.

---
Tags: octree, marching-cubes, signed-distance-field
---


# Question
Title: InvalidOperationException: Collection was modified; enumeration operation may not execute
I think it's just my eyes get blured after seen this so many hours. Maybe new ones will see the problem. I'm making a puzzle game and I need to glue parts with each others. And here's how I make it:

```
using System.Collections.Generic;
using UnityEngine;
using Puzzle.Helpers;  //enum RaySides are here

namespace Puzzle
{
    public class PartRayCube : MonoBehaviour
    {
        #region ========== Variables ========

        Part2D _part2DParent;
        /// <summary>
        /// List of sides and where it have glued object - true
        /// </summary>
        Dictionary<RaySide, bool> _relatives = new Dictionary<RaySide, bool>();

        #endregion ========== Variables ========

        #region ========== Unity-time ========

        private void Awake()
        {
            _part2DParent = GetComponentInParent<Part2D>();
        }

        #endregion ========== Unity-time ========

        #region ========== Methods ========

        /// <summary>
        /// Adding empty sides
        /// </summary>
        /// <param name="sides"></param>
        public void AddSides(RaySide[] sides)
        {
            foreach (var side in sides)
                _relatives.Add(side, false);
        }

        /// <summary>
        /// Adding glued part
        /// </summary>
        /// <param name="side">Adding side</param>
        /// <param name="relative">Adding Part</param>
        public void AddRelative(RaySide side, Part2D part)
        {
            _relatives[side] = true;

            // Add each other to the parents list
            _part2DParent.Relatives.Add(part);
            part.Relatives.Add(_part2DParent);

            // If THIS object have any relatives(glued parts) adding them to the part's relatives
            if(_part2DParent.Relatives.Count > 1)
            {
                foreach (var item in _part2DParent.Relatives)
                {
                    if (item == part)
                        continue;

                    part.Relatives.Add(item);
                }
            }

            // If part have relatives, add them to THIS's relatives list
            if (part.Relatives.Count > 1)
            {
                foreach (var item in part.Relatives)
                {
                    if (item == _part2DParent)
                        continue;

                    _part2DParent.Relatives.Add(item);  // Adding rel to this relList

                    item.Relatives.Add(_part2DParent);  // Adding this to item's relList
                }
            }
        }

        /// <summary>
        /// Gluing parts with each other if they fit
        /// </summary>
        public void CheckRelatives()
        {
            Dictionary<RaySide, bool> newRel = new Dictionary<RaySide, bool>();
            newRel = _relatives;

            foreach (var side in newRel.Keys)
            {
                // Skip is side is glued
                if (newRel[side])
                    continue;

                RaycastHit hit;

                switch (side)
                {
                    case RaySide.left:
                        {
                            // Ray to the left with size partSize/2
                            if (Physics.Raycast(transform.position, -transform.right, out hit, _part2DParent.RectTrans.sizeDelta.x / 2))
                            {
                                if (hit.transform.GetComponentInParent<Part2D>().id + 1 == _part2DParent.id)
                                {
                                    AddRelative(RaySide.left, hit.transform.GetComponentInParent<Part2D>());
                                }
                                else
                                    break;
                            }

                            break;
                        }
                    case RaySide.right:
                        {
                            // Ray to the right with size partSize/2
                            if (Physics.Raycast(transform.position, transform.right, out hit, _part2DParent.RectTrans.sizeDelta.x / 2))
                            {
                                if (hit.transform.GetComponentInParent<Part2D>().id - 1 == _part2DParent.id)
                                {
                                    AddRelative(RaySide.right, hit.transform.GetComponentInParent<Part2D>());
                                }
                                else
                                    break;
                            }

                            break;
                        }
                    case RaySide.up:
                        {
                            // Depending on difference take the right number
                            int i = Main.Instance.Diff.GetHashCode() / 4;

                            if (Physics.Raycast(transform.position, transform.up, out hit, _part2DParent.RectTrans.sizeDelta.y / 2))
                            {
                                if (hit.transform.GetComponentInParent<Part2D>().id + i == _part2DParent.id)
                                    AddRelative(RaySide.up, hit.transform.GetComponentInParent<Part2D>());
                                else
                                    break;
                            }

                            break;
                        }
                    case RaySide.down:
                        {
                            // Depending on difference take the right number
                            int i = Main.Instance.Diff.GetHashCode() / 4;

                            if (Physics.Raycast(transform.position, -transform.up, out hit, _part2DParent.RectTrans.sizeDelta.y / 2))
                            {
                                if (hit.transform.GetComponentInParent<Part2D>().id - i == _part2DParent.id)
                                    AddRelative(RaySide.up, hit.transform.GetComponentInParent<Part2D>());
                                else
                                    break;
                            }

                            break;
                        }
                }
            }
        }

        #endregion ========== Methods ========
    }
}

```

And after all I see:

```
InvalidOperationException: Collection was modified; enumeration operation may not execute.
System.Collections.Generic.Dictionary`2+KeyCollection+Enumerator[TKey,TValue].MoveNext () (at <eae584ce26bc40229c1b1aa476bfa589>:0)
Puzzle.PartRayCube.CheckRelatives () (at Assets/Scripts/PartRayCube.cs:88)

```

But sometimes it works perfect. After 2-3 repeating

# Answer
```
            Dictionary<RaySide, bool> newRel = new Dictionary<RaySide, bool>();
            newRel = _relatives;

```

This creates new dictionary and immediately replaces it with a reference to existing dictionary. You probably wanted to **copy** it, like this:

```
            Dictionary<RaySide, bool> newRel = new Dictionary<RaySide, bool>(_relatives);

```
> 2 votes

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


# Question
Title: If player is not holding the ladder then it should not jump twice
I am using Unity2d and I am stuck with a problem. I made the new layer for ground and ladder and added `OverlapCircle` and make double jump script for the player, so if the player touches the ground or ladder it jump twice (on pressing the `jump` key). If the player presses the `W` key in front of ladder then it should hold the ladder and the player can move up and down. Then if the player presses jump then the players jump from the ladder, we can jump single or twice from the ladder according to our intention.

I want it so that if the player presses the `W` key and holds the ladder then only he can jump and if he only touches touches the ladder and `W` key is not pressed the `jump` key should not work.

Below is the player script:

```
[SerializeField]
[SerializeField] float _xSpeed = 1f;
[SerializeField] float _ySpeed = 1f;
[SerializeField] float _jumpForce = 1f;
[SerializeField] float _distance;
[SerializeField] LayerMask _ladderLayer;
private float _horizontalMovement;
private float _verticalMovement;
private Rigidbody2D _rb;
private bool _isClimbing;
private bool _isMovingHorizontal = true;

[SerializeField] Transform _groundPos;
[SerializeField] float _checkRadius;
[SerializeField] LayerMask _groundLayer;
private bool _isGrounded;

// ExtraJump
private int _extraJumps;
[SerializeField] int _extraJumpValue = 1;

void Start()
{
    _rb = GetComponent<Rigidbody2D>();
    _extraJumps = _extraJumpValue;
}

void Update()
{
    _horizontalMovement = Input.GetAxis("Horizontal");
    _verticalMovement = Input.GetAxis("Vertical");
}

void FixedUpdate()
{
    if(_isMovingHorizontal)
    {
        _rb.velocity = new Vector2( _horizontalMovement * _xSpeed,_rb.velocity.y);
    }

    _isGrounded = Physics2D.OverlapCircle(_groundPos.position,_checkRadius,_groundLayer);

    if(_isGrounded == true)
    {
        _extraJumps = _extraJumpValue;
    }
    if(Input.GetKeyDown(KeyCode.Space) && _extraJumps > 0)
    {
        _rb.velocity = new Vector2(_rb.velocity.x,_jumpForce);
        _extraJumps --;
    }
    else if(Input.GetKeyDown(KeyCode.Space) && _extraJumps == 0 && _isGrounded == true)
    {
        _rb.velocity = new Vector2(_rb.velocity.x,_jumpForce);
    }

    RaycastHit2D hitLadder = Physics2D.Raycast(transform.position,Vector2.up,_distance,_ladderLayer);

    if(hitLadder.collider == true)
    {
        if(Input.GetKey(KeyCode.W))
        {
            _isClimbing = true;
            _rb.gravityScale = 0;
        }
        else if(Input.GetKey(KeyCode.Space))
        {
            _isClimbing = false;
        }
    }

    if(_isClimbing == true && hitLadder.collider == true)
    {
        _rb.velocity = new Vector2(_rb.velocity.x,_verticalMovement *
        _ySpeed);
    }
    else
    {
        _rb.gravityScale = 1;
    }
}

```

# Answer
> 0 votes
Not sure if I totally understand your `ladder` and `jump` interaction. If the behaviour you want is different from this, I will adjust it. The basic idea behind this is, you can't climb the ladder if you do not have any jumps. Since jumps refill when we are on the ground, you can always start climbing up and down from the platform. But when jumping, there is no interaction with the ladder (at least not now if your maxjumpamount is only 1)

```
if(Input.GetKeyDown(KeyCode.Space) && _extraJumps > 0) {
  _rb.velocity = new Vector2(_rb.velocity.x,_jumpForce);
  _extraJumps --;
}

RaycastHit2D hitLadder = Physics2D.Raycast(transform.position,Vector2.up,_distance,_ladderLayer);

if(hitLadder.collider && Input.GetKey(KeyCode.W) && _extraJumps > 0) {
  _rb.gravityScale = 0;
  _rb.velocity = new Vector2(_rb.velocity.x,_verticalMovement * _ySpeed);
} else {
  _rb.gravityScale = 1;
}

```

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


# Question
Title: Saving settings when exiting the application
I created a static class CustomPlayerPrefs, it has a WriteToDisk() method that writes the saves to disk.

For saving I am using Application.quiting event:

```
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSplashScreen)]
static void Init()
{
    Application.quitting += WriteToDisk;
}

```

But on android it never works. I know that applications are not closed but paused, but it doesn't even work when I restart the device or force the application to stop.

How to fix this or how to make it better?

Need IOS and Android support.

# Answer
To be safe, you actually need to save in three different places, when the game is paused (OnApplicationPause), when the game loses focus (OnApplicationFocus) and finally just in case when the game quits (OnApplicationQuit). The last one should be unnecessary accordingly to some, but better safe than sorry.

```
public class MyGameManager : MonoBehaviour
{
    // ...

    /// <summary>
    /// Called when the application pauses.
    /// </summary>
    /// <param name="pause"><c>true</c> if the application is paused, else <c>false</c>.</param>
    private static void OnApplicationPause(bool pause)
    {
        if (pause)
            Save();
    }

    /// <summary>
    /// Called when the gamme loses or gains focus.
    /// </summary>
    /// <param name="hasFocus"><c>true</c> if the gameobject has focus, else <c>false</c>.</param>
    /// <remarks>
    /// On Windows Store Apps and Windows Phone 8.1 there's no application quit event,
    /// consider using OnApplicationFocus event when hasFocus equals false.
    /// </remarks>
    void OnApplicationFocus(bool hasFocus)
    {
        if(!hasFocus)
            Save();
    }

    /// <summary>
    /// Called before the application quits.
    /// </summary>
    /// <remarks>
    /// iOS applications are usually suspended and do not quit.
    /// On Windows Store Apps and Windows Phone 8.1 there's no application quit event,
    /// consider using OnApplicationFocus event when focusStatus equals false.
    /// On WebGL is not possible to implement OnApplicationQuit due to nature of the
    /// browser tabs closing.
    /// </remarks>
    private void OnApplicationQuit()
    {
        // Note that we do not get an OnApplicationQuit event on iOS devices. We
        // therefore saves the data in the OnApplicationPause and OnApplicationFocus
        // events, and have this code just in case:
        Save();
    }

```
> 1 votes

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


# Question
Title: How do I enable/disable a gameobject from a different Script?
I wanted a shield around my player when my player picks it up. Now shield component is a child of object of player which is disable at start. I wanna enable it from the shield prefab. This is all in unity

How can i do that?

# Answer
```
shieldGameObject.SetActive(true);

```

You can read about it here: https://docs.unity3d.com/ScriptReference/GameObject.SetActive.html
> 1 votes

---
Tags: unity
---


# Question
Title: How to make object move in exact gametime in Monogame, XNA?
I have recently started learning monogame. The big question i faced is how to make object move, when gametime variable has an exact value.

```
//Update method in Game.cs
     float delta = (float)gameTime.ElapsedGameTime.Milliseconds / 1000f;
        if (CurrentState != null)
            CurrentState.update(delta);

     if (Keyboard.GetState().IsKeyDown(Keys.Enter))
            SetState(new GameState());

    //GameState.cs, there is a box that's need to be moved in 5 seconds
    Vector2 boxpos = new Vector2(800, Game1.graphics.PreferredBackBufferHeight / 2 - 100);
    float olddelta = 0;
    public void update(float delta)
    {
        float newdelta = delta;
        if (newdelta - olddelta >= 5)
        {
            boxpos += new Vector2(0, -200);
            olddelta = newdelta;
        }
    }

```

I've drawn a box in my gamestate's draw method using `spritebatch.Draw(Box, boxpos, null, Color.White, 0f, Vector2.Zero, 1f, SpriteEffects.None, 1f);`, but it's position remains constant. I really have no idea how to do it in a right way. Hope can receive some help.

# Answer
Have you tried to step through your program, I suspect that your clause of \>= 5 is never being met here. As you are taking in a frame in milliseconds, and taking away the previous frame, this value will remain very low. What you should be using here is an accumulation of time, so to reach that five second mark.

For a good reference on the subject, have a read of the following http://gafferongames.com/game-physics/fix-your-timestep/ It goes through the steps on implementing a time step correctly, and the reasoning behind it in a clear manner
> 1 votes

# Answer
In your gamestate code, `olddelta` value is only assigned in two places.

First it is assigned to `0` in the beginning.

Then, it is assigned to the value of `newdelta` (which is effectively a copy of `delta` \- the extra variable is not really necessary), but only on the condition of `delta` being more than or equal to 5 (seconds?), at which point it will get assigned to that value. Next time around the check would be for a value that's more than 5+ whatever value passed the check last time, so something over 10.

All in all highly unlikely to happen and definitely not the intention of the code.

What you likely intended to do is to add the value of `delta` to `olddelta` or some better named variable and then check the value of that second variable. When it exceeds 5, you perform your action.

Side note, if you want to perform your action *every* 5 seconds, once the action is performed, you subtract 5 from your accumulating variable.

The way the title is worded, there seems to be a second question that asks if it is possible to do this exactly, the answer for this is - not with this method, you will probably be a frame (so around 17ms) late most of the time.
> 0 votes

---
Tags: 2d, graphics
---


# Question
Title: Press button event instead of onClick() in Unity
I want to add a nitro in my arcade game and i want to detect press UI button instead of click. unfortunately only onClick() event is available for UI button

what kind of options do I have ?

Thank you

# Answer
You can use OnPointerDown. Here is the example: http://forum.unity3d.com/threads/touch-and-hold-a-button-on-new-ui.266065/#post-1758312

```
public static bool mouseDown;
public float timeMouseDown;

void Update(){
    if(mouseDown)
       timeMouseDown += time.deltaTime;
}

void OnPointerDown(){
      mouseDown = true;
}
void OnPointerUp(){
      mouseDown = false;
      timeMouseDown = 0;
}

```
> 8 votes

# Answer
Check out the AddListener stuff. You don't have to use the inspector click if you do not want to. But when you do it fires when it is pressed

```
.onClick.AddListener()//to add a listener

```

Also you can put a script on any gameobject as a nitro button and use

```
OnMouseDown(){} //fire on mouse down or tap

```

to answer your comment. you would drag the game object that has the script with the method to fire to the button click slot and as long as it is a public method you can scroll in and find the method to fire on click it will execute the code in that method. It looks like your button is set up properly was it not firing? if it does not fire right click and create a UI EventSystem to solve.
> 2 votes

# Answer
You can implement your own click handler to load a scene like this:

```
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.SceneManagement;

//Be sure to change YOUR_SCRIPT_NAME_NAME to the name of your script.
public class YOUR_SCRIPT_NAME_HERE : MonoBehaviour, IPointerClickHandler
{
    public void OnPointerClick(PointerEventData eventData)
    {
        //I named my button the name of the scene i want to load
        SceneManager.LoadScene(eventData.pointerPress.name);
        Debug.Log("Switching level: " + eventData.pointerPress.name);
    }
}

```
> 1 votes

# Answer
OnPointerDown didn't work for me - For some reason, it only triggered when the button was released.

This worked great though:

```
public void CustomOnPressed()
{
    Debug.LogError("I got pressed!");
}

```

Then add an `Event Trigger (Script)` to your object in the editor (instead of Button), and select `Pointer Down`:
> 1 votes

# Answer
I just removed the Button component and added the PressButton component. Now I can call the public IsPressed() method to check the state.

```
using UnityEngine.UI;

public class PressButton : Button
{
    public bool PublicIsPressed()
    {
        return base.IsPressed();
    }
}

```
> 0 votes

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


# Question
Title: Dynamic Sort order For walking in front and behind stuff
I'm using tile maps, and I'm having a difficult time with the concept of walking both in front of things, and behind things and having the layers sort order show properly. Take the image below, I need it to behave like #1 **AND** #2, so that if you walk behind it, you get that nice layering. However, I also need it to act like #2 when infront of it without looking like #3. Is there some sort of way to make the top of the barrels sort order change depending on if the player is in front of it, or behind it?

I was looking at rule tiles, but that's something else, unless there is some feature about it I do not know of.

# Answer
> 1 votes
The image doesn't need to fit into the space where the tile goes. The barrel can be a single tile which extends above it's bounding box. As long as the tile display order draws lower tiles over higher ones, everything should work out. It also means you don't need separate images in your tileset for every different tile your barrel can be in front of.

This works even for very large objects, like archways which span multiple tiles.

---
Tags: 2d
---