# Question
Title: Move circle inside semi-circle based on external object
I have a circle that I'd like to move around in semicircle with it's location following an external object.

I can get the direction the circle should be facing with something like this:

```
Vector3 targetDir = X.transform.position - circle.transform.position;

```

How can I stick the movement of the circle inside a semicircle?

# Answer
> 1 votes
A useful trick for collision detection and finding closest points is Minkowski addition. This says that if we want to know how close a disc can get to an edge, we can inflate that edge by the radius of the disc, and correspondingly deflate the disc to a single point at its center. The situation of collisions between the point and the inflated edge is equivalent to the original situation we wanted to solve, but usually easier to reason about.

For the case of the small disc inside the semi-circle, we could attack it like this:

Here the pale purple semi-circle is our container. It's defined by a center point \\$C\\$ in purple, an outer radius \\$R\\$ in the solid blue line, and a diameter line in red that cuts it to just a semi-circle instead of a full one. I've also labelled the vector \\$\vec n \\$ in red, which is the unit normal perpendicular to this diameter.

From those, we can define a shrunken circle and a shifted diameter, inset by the radius of the small disc \\$r\\$, and represented here with the dashed lines. These form the boundary of the region the center of our disc can occupy - the darker purple not-quite-semi-circle.

If the target point we want to approach is inside that darker part-circle, we're done. That's a position our disc can reach without leaving the outer semi-circle.

If not, then closest our disc can get to it is to have its center along either the red or blue dashed lines.

What's great is we can use the projection of the target point onto our normal vector \\$\vec n\\$ to very quickly determine which one. If it's less than one disc radius "below" the circle center, or anywhere higher, then the closest we can reach to it has to be along the red dashed line. We can just project it down onto that line, and then clamp its position, so it doesn't go further left or right than our "half-width" value \\$h\\$, which we can compute with Pythagorean theorem:

$$\begin{align} h^2 + r^2 &= (R - r)^2\\ h^2 + r^2 - r^2 &= R^2 - 2Rr + r^2 - r^2\\ h^2 &= R^2 - 2Rr\\ h &= \sqrt {R^2 - 2Rr} \end{align}$$

(Here I'm taking just the positive root because we've defined \\$h\\$ to be a positive length)

If the target point is on the other side of that dashed red line, then it's either within the radius \\$(R - r)\\$ and thus we can go there directly, or it's on the blue dashed line - in which case we can just scale the vector from the center to the target to the length \\$(R - r)\\$ and we're done.

Here's some C# code implementing these ideas. I called it "Googley Eye" and the disc "pupil" since that seemed more intuitive.

```
public struct GoogleyEye {

    public Vector2 center;

    public readonly float outerRadius;
    public readonly float pupilRadius;
    readonly float _innerHalfWidth;

    Vector2 _unitNormal;
    public Vector2 normal {
        get { return _unitNormal; }
        set { _unitNormal = value.normalized; }
    }

    public GoogleyEye(Vector2 center, float outerRadius, float pupilRadius, Vector2 normal) {
        this.center = center;
        this.outerRadius = outerRadius;
        this.pupilRadius = pupilRadius;
        _unitNormal = normal.normalized;

        _innerHalfWidth = Mathf.Sqrt(outerRadius * (outerRadius - 2f * pupilRadius));
    }

    public Vector2 ClosestPupilCenter(Vector2 target) {
        // Vector from the center of the circle to the target.
        var fromCenter = target - center;

        // Perpendicular distance of the target "above" the semi-circle.
        var offDiameter = Vector2.Dot(_unitNormal, fromCenter);

        // If this is less than a pupil radius inside the semi-circle,
        // then it's above the red dashed line, and the closest we can
        // get is on the red dashed line from -h to h.
        if (offDiameter > -pupilRadius) {
            // Quick perpendicular pointing along the diameter.
            var diameterDirection = new Vector2(-_unitNormal.y, _unitNormal.x);
            // Horizontal distance from center to target along this line.
            var alongDiameter = Vector2.Dot(diameterDirection, fromCenter);

            // Clamp it so it doesn't go outside our range of motion.
            alongDiameter = Mathf.Clamp(alongDiameter, -_innerHalfWidth, _innerHalfWidth);

            // Add the horizontal and vertical offsets to our center
            // to get the final point.
            return center - pupilRadius * _unitNormal + alongDiameter * diameterDirection;
        }

        // Radius of the inner dashed blue circle.
        float innerRadius = outerRadius - pupilRadius;
        // If we're inside this circle, then we're inside both dashed
        // regions, and our pupil can go to the target point directly.
        if (fromCenter.sqrMagnitude < innerRadius * innerRadius) {
            return target;
        }

        // Otherwise, we just project it to the closest point on the circle.
        return center + fromCenter.normalized * innerRadius;
    }
}

```

---
Tags: unity
---


title: why doesn't spritecollide method work?

text:
# Question
Title: why doesn't spritecollide method work?
In my code, I wanted to use the spritecollides method but I got the following error message:

> Traceback (most recent call last):
>
> File "/Users/lanik2009/Documents/pygame testing.py", line 76, in \<module\>
> hits = pygame.sprite.spritecollide(player, obstacles, False)
>
> File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pygame/sprite.py", line 1645, in spritecollide
> default\_sprite\_collide\_func = sprite.rect.colliderect
>
> AttributeError: 'pygame.Rect' object has no attribute 'rect'

My code:

```
import pygame

pygame.init()

white = (255, 255, 255)
green = (0, 255, 0)
blue = (0, 0, 128)
black = (0, 0, 0)
red = (255, 0, 0)

w = 500
h = 500

x = 15
y = 480

vel = 5
screen = pygame.display.set_mode((500, 500))

square = pygame.image.load(r'/Users/lanik2009/Downloads/square.PNG')
square = pygame.transform.scale(square, (46, 40))
triangle = pygame.image.load(r'/Users/lanik2009/Downloads/triangle.PNG')
triangle = pygame.transform.scale(triangle, (46, 40))

squareSprite = pygame.sprite.Sprite()
squareSprite.image = square
squareSprite.rect = square.get_rect()

triangleSprite = pygame.sprite.Sprite()
triangleSprite.image = triangle
triangleSprite.rect = triangle.get_rect()

def drawer():
    screen.fill(black)
    screen.blit(triangle, (100, 460))
    screen.blit(square, (300, 460))

jump = False

obstacles = pygame.sprite.Group()

obstacles.add(squareSprite)
obstacles.add(triangleSprite)

running = True

while running:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    keys = pygame.key.get_pressed()

    if keys[pygame.K_LEFT]:
        x -= vel

    if keys[pygame.K_RIGHT]:
        x += vel

    if jump == False:
        y = 480

    if keys[pygame.K_UP]:
        y -= 40
        jump = False

    if event.type == pygame.KEYUP:
        jump = False

    drawer()

    player = pygame.draw.circle(screen, white, (x, y), 10, 500)
    pygame.display.update()

    hits = pygame.sprite.spritecollide(player, obstacles, False)
    if hits:
        running = False

pygame.quit()

```

# Answer
> 0 votes
As in your previous question, your error message tells you exactly what is wrong.

> AttributeError: 'pygame.Rect' object has no attribute 'rect'

This means that pygame expected you to give it an object that has an attribute called "rect". Instead, you gave it a `pygame.Rect`. `pygame.Rect`, naturally, does not have an attribute called "rect". It *is* a `Rect`, it doesn't *have* a `Rect`.

Where did this `Rect` come from? If you read the documentation for `pygame.draw.circle`, you'll see it says:

> Returns:
> a rect bounding the changed pixels, if nothing is drawn the bounding rect's position will be the center parameter value (float values will be truncated) and its width and height will be 0

So this line:

```
player = pygame.draw.circle(screen, white, (x, y), 10, 500)

```

...sets `player` to be a `Rect` object.

The `spritecollide` function expects you to pass it a `Sprite` and a `SpriteGroup`. You passed it a `Rect` and a `SpriteGroup`.

You can draw your player as a sprite instead of a circle if you want to use the `spritecollide` function, or you can use a different collision checking function to test a `Rect` against members of a `SpriteGroup`.

---
Tags: python, pygame
---


# Question
Title: Time.fixedDeltaTime & Time.deltaTime in Unity
The old Unity 5.3 documentation said:

> **Time.fixedDeltaTime**
>
> The interval in seconds at which physics and other fixed frame rate updates (like MonoBehaviour's *FixedUpdate*) are performed.
>
> For reading the delta time it is recommended to use *Time.deltaTime* instead because it automatically returns the right delta time if you are inside a *FixedUpdate* function or *Update* function.
>
> Note that the *fixedDeltaTime* interval is with respect to the in-game time affected by *timeScale*.

So, it was said (paraphrased as I get it) that *Time.fixedDeltaTime* returns the interval at which the *FixedUpdate* method should be called with respect to the *timeScale*. But the real interval could differ (for technical reasons) and that's why *Time.deltaTime* should be used instead to return a real time elapsed since the previous *FixedUpdate* call.

The latest docs don't say that anymore: https://docs.unity3d.com/ScriptReference/Time-fixedDeltaTime.html

Does it mean that now *FixedUpdate* is called exactly at *Time.fixedDeltaTime* rate?

Now it also says:

> Unity does not adjust *fixedDeltaTime* based on *Time.timeScale*. The *fixedDeltaTime* interval is always relative to the in-game time which *Time.timeScale* affects.

Don't these two sentences contradict each other?

# Answer
> So, it was said (paraphrased as I get it) that Time.fixedDeltaTime returns the interval at which the FixedUpdate method should be called with respect to the timeScale.

Yes, it's the interval of *game time* between successive `FixedUpdate` calls.

> But the real interval could differ (for technical reasons) and that's why Time.deltaTime should be used instead to return a real time elapsed since the previous FixedUpdate call.

No.

You can imagine `deltaTime` being implemented something like this:

```
public float deltaTime { get {
    if (_isCurrentlyRunningFixedUpdates) {
        return fixedDeltaTime;
    } else {
        return Mathf.Min(timeScale * _realtimeSecondsSinceLastFrame, maximumDeltaTime);
    }
} }

```

Basically `deltaTime` is a getter that returns "how much game simulation time should I treat as having passed, based on where in the update flow I am currently running?".

* If you're in a fixed step (physics updates, `FixedUpdate`, collision handling messages), it gives you exactly the same value as writing `fixedDeltaTime` instead.

That's the point of a fixed time step: it's *fixed* \- it does not change no matter what weirdness might be happening with regard to wall-clock-time.
* If you're in a variable step (`Update`, `LateUpdate`), it gives you the amount of game simulation time that's run since the last rendered frame, which could be more or less depending on your framerate, transient load spikes, etc.

The convenience of this behaviour is that if you have a function that's called in multiple places, sometimes from `FixedUpdate` or a collision handler and sometimes from `Update`, it automatically adapts itself to give the right value for that context. Or if you refactor some code and move it from one update to another, you don't need to remember to update the time step you're using, as long as you've been consistent about always reading `Time.deltaTime`.

---

It's important to remember that `fixedDeltaTime` is a measure of *game simulation time*. It is not a measure of real time.

When running a fixed update loop, the game measures the total realtime / wall clock time elapsed since the last frame, scales it by your time scale, and then divides that by your `fixedDeltaTime` to get an integer representing how many times it should tick the physics simulation this frame. Any fractional part is carried over as loose change to add to the calculation for *next* frame.

So on a short frame, you might not run the physics step or `FixedUpdate` at all. On a longer frame, you might run the physics step and `FixedUpdate` functions multiple times.

When we do tick multiple times in one frame, all those ticks are run in rapid succession back-to-back. We don't put delays in between them so that each is called one `fixedDeltaTime` apart from the last with regard to the wall clock. Because again, `fixedDeltaTime` measures game sim time, not wall clock time.

What matters is that "by the time we get to a frame \\$x\\$ seconds into the game, I expect \\$\lfloor 50 \cdot x\rfloor\\$ `FixedUpdate` steps have run" (if using the default `0.02` value for `fixedDeltaTime` and a `timeScale` of `1.0`). So we don't get ahead the rendered frame, or fall behind it by a `fixedDeltaTime` or more.

When exactly in wall clock time that code ran on the CPU doesn't matter - it's not directly observable by the player, all they can see is the resulting rendered frame that gets presented *after* we've done all the catching-up we need to do for this frame.

There is an exception in the case where your computer just can't keep up with running the number of physics steps / `FixedUpdate` calls needed to keep pace: Unity provides a maximum allowable game time step. If your frame time runs so long that the game simulation it accounts for exceeds this limit, then Unity will stop running fixed steps and cap the simulation as far as it got this frame, resuming next frame. In this situation, game time slows down relative to real time until the computer is able to catch up. But each `FixedUpdate` call still represents exactly the same amount of game time as before.

---

> > Unity does not adjust fixedDeltaTime based on Time.timeScale. The fixedDeltaTime interval is always relative to the in-game time which Time.timeScale affects.
>
> Don't these two sentences contradict each other?

No. What this is saying is that changing the value you put into `Time.timeScale` does not change the value you read from `fixedDeltaTime`.

By setting `fixedDeltaTime` to `0.02`, I am saying "I want physics to tick and `FixedUpdate` to run exactly 50 times per second of game time". And Unity honours that.

* If I speed up game time so it's running 2 seconds of simulation for every 1 second of real time, then Unity will run 100 physics steps for every wall clock second (still 50 per game second)
* If I slow down my game time so it's running at half a second of simulation for every 1 second of real time, then Unity will run 25 physics steps for every wall clock second (still 50 per game second)

`Time.timeScale` changes the relationship between game time and real time. `fixedDeltaTime` is measured in game time, so this scaling does not affect it.
> 4 votes

# Answer
`Time.fixedDeltaTime` is the interval for `FixedUpdate()` calls relative to scaled in-game time.

For example, if `fixedDeltaTime` is `.02`, `FixedUpdate()` is called 50 times a second (both real-time and in-game time) when `timeScale` = 1. If `timescale` = 2, `FixedUpdate()` would still be called 50 times a second in in-game time, but 100 times a second in real-time. `fixedDeltaTime` would still be `.02` regardless of what the `timeScale` is.

`Time.deltaTime` does different things depending on when you use it:

* If you use it during the `Update()` cycle, it returns the amount of time elapsed since the previous frame
* If you use it during the `FixedUpdate()` cycle, it returns the same value as `fixedDeltaTime`.

Unity recommends always using `Time.deltaTime` because it returns the relevant value regardless of whether you're currently in `Update()` or `FixedUpdate()`, but if you find this confusing then you can use `fixedDeltaTime` for clarity.
> 1 votes

---
Tags: unity, timestep, fixed-timestep, time
---


# Question
Title: How to make player jump to mouse position
Currently I have the player moving towards the mouse position , using this example :

https://kidscancode.org/godot\_recipes/3d/click\_to\_move/

now how would I achieve jumping to the mouse position, currently my script is like this:

```
  void Player::move(const float &delta) {
            velocity.y += gravity * delta;

            if (target != godot::Vector3::ZERO) {

                look_at(target, godot::Vector3::UP);
                rotate_x(0.0);
                velocity = -get_transform().basis.z * speed;

                auto distance_to_target = get_transform().origin.distance_to(target);
                if (distance_to_target < 0.5) {
                    velocity = target = godot::Vector3::ZERO;
                }

// weird behavior not what I'm looking for

                if (godot::Input::get_singleton()->is_action_pressed("Jump") && is_on_floor()) {
                    godot::Godot::print(std::to_string(distance_to_target).c_str());
                    velocity.y = 100;
                }
            }

            velocity = move_and_slide(velocity, godot::Vector3::UP);
        }

```

I tried messing around with velocity.y , but it always result in weird behaviors and the player when landing point/look at the floor.

how would I do it correctly ?

# Answer
> 1 votes
This is the version in the article, I'll work from it:

```
extends KinematicBody

export var speed = 5
export var gravity = -5

var target = null
var velocity = Vector3.ZERO

func _physics_process(delta):
    velocity.y += gravity * delta
    if target:
        look_at(target, Vector3.UP)
        rotation.x = 0
        velocity = -transform.basis.z * speed
        if transform.origin.distance_to(target) < .5:
            target = null
            velocity = Vector3.ZERO
    velocity = move_and_slide(velocity, Vector3.UP)

```

---

I suggest (against what the linked article says) to check the distance to the target instead of checking with `ZERO` (`ZERO` could be a valid target). And, I'll set `target` to `transform.origin` for initialization. Since we are already checking for the distance, refactor the conditional that does that:

```
extends KinematicBody

export var speed = 5
export var gravity = -5

var target = transform.origin
var velocity = Vector3.ZERO

func _physics_process(delta):
    velocity.y += gravity * delta
    if transform.origin.distance_to(target) < 0.5:
        # perhaps you want to flip this line
        target = transform.origin
        velocity = Vector3.ZERO
    else:
        look_at(target, Vector3.UP)
        rotation.x = 0
        velocity = -transform.basis.z * speed

    velocity = move_and_slide(velocity, Vector3.UP)

```

---

There is another problem with the article code: when we write `velocity` we are erasing the vertical velocity we set with gravity (which, of course, you would not notice until the physics object is not on the floor). So let us fix that:

```
extends KinematicBody

export var speed = 5
export var gravity = -5

var target = transform.origin
var velocity = Vector3.ZERO

func _physics_process(delta):
    velocity.y += gravity * delta
    if transform.origin.distance_to(target) < 0.5:
        # perhaps you want to flip this line
        target = transform.origin
        velocity = Vector3(0, velocity.y, 0)
    else:
        look_at(target, Vector3.UP)
        rotation.x = 0
        var vel = -transform.basis.z * speed
        velocity = Vector3(vel.x, velocity.y, vel.z)

    velocity = move_and_slide(velocity, Vector3.UP)

```

---

Now, let us work on the jump. First of all, do not use `is_on_floor` before using `move_and_slide`. Let us try at the end:

```
extends KinematicBody

export var speed = 5
export var gravity = -5

var target = transform.origin
var velocity = Vector3.ZERO

func _physics_process(delta):
    velocity.y += gravity * delta
    if transform.origin.distance_to(target) < 0.5:
        # perhaps you want to flip this line, maybe just set x and z
        target = transform.origin
        velocity = Vector3(0, velocity.y, 0)
    else:
        look_at(target, Vector3.UP)
        rotation.x = 0
        var vel = -transform.basis.z * speed
        velocity = Vector3(vel.x, velocity.y, vel.z)

    velocity = move_and_slide(velocity, Vector3.UP)
    if is_on_floor() and Input.is_action_pressed("Jump"):
        velocity.y = 10

```

Did you see that? We have a fixed jump velocity, it might undershoot. Or it might overshoot which is worse because the code snaps to the target horizontal position mid-air.

So that snapping must only happen when `is_on_floor()` is true. Which means we need to put `move_and_slide` before all that:

```
extends KinematicBody

export var speed = 5
export var gravity = -5

var target = transform.origin
var velocity = Vector3.ZERO

func _physics_process(delta):
    velocity.y += gravity * delta
    velocity = move_and_slide(velocity, Vector3.UP)
    if is_on_floor():
        if Input.is_action_pressed("Jump"):
            velocity.y = 10
        if transform.origin.distance_to(target) < 0.5:
            # perhaps you want to flip this line, maybe just set x and z
            target = transform.origin
            velocity = Vector3(0, velocity.y, 0)
        else:
            look_at(target, Vector3.UP)
            rotation.x = 0
            var vel = -transform.basis.z * speed
            velocity = Vector3(vel.x, velocity.y, vel.z)

```

Now it jumps, falls to the ground, then it adjusts directions.

Perhaps you want it to compute how much to jump to get there. With the help of good old motion equations we can do that. We will need the horizontal distance. It is also a good idea to check against horizontal distance, just in case the target is on a different elevation.

And there you go, this code jumps to the target:

```
extends KinematicBody

export var speed = 5
export var gravity = -5

var target = transform.origin
var velocity = Vector3.ZERO

func _physics_process(delta):
    velocity.y += gravity * delta
    velocity = move_and_slide(velocity, Vector3.UP)
    if is_on_floor():
        var h_distance = Vector2(transform.origin.x, transform.origin.z).distance_to(Vector2(target.x, target.z))
        if Input.is_action_pressed("Jump"):
            var expected_time = h_distance / speed
            var v_velocity = -0.5 * expected_time * gravity
            velocity.y = v_velocity
        if h_distance < 0.5:
            # perhaps you want to flip this line, maybe just set x and z
            target = transform.origin
            velocity = Vector3(0, velocity.y, 0)
        else:
            look_at(target, Vector3.UP)
            rotation.x = 0
            var vel = -transform.basis.z * speed
            velocity = Vector3(vel.x, velocity.y, vel.z)

```

*By the way, if you change the target mid-air, it will complete the jump, then change direction and go. Similarly, if it fails to land on the target because of an obstacle, it will change direction after landing then go. There is no path-finding or obstacle avoidance (other than sliding on walls because `move_and_slide`) of course.*

If this is not the behavior that you want, hopefully you can modify it from there. Remember:

* When setting `velocity` you are overriding `velocity.y`
* Use `is_on_floor` after `move_and_slide` (and `move_and_slide` after applying gravity). *The `KinematicBody` might be on the floor, but if it didn't slide on it, it will not register.*
* Consider if you want it to be able to change direction mid-air or not. *If the target is directly below it will suddenly stop the jump arc and fall vertically.*
* Do not assume that `ZERO` is not a valid target.

I'm letting translating that to C++ to you, because, honestly, it is too much setup to test it (I'm being lazy), and I'm not confident to get it right without testing it. Yet you should be able to do it with little effort.

---

**Note**: The value `0.5` on `h_distance < 0.5` might be too large depending on the size of the scene. Which results in the motion stopping too short. If that happens, try an smaller value.

---

## Addendum: Making jump time constant

Look again at this code:

```
var expected_time = h_distance / speed
var v_velocity = -0.5 * expected_time * gravity
velocity.y = v_velocity

```

It only sets the vertical velocity, and uses the `speed` it has. If you want the jump to take a constant time, you would have to change the speed. Solve the equation for speed:

```
var expected_time = h_distance / speed
=>
speed * expected_time = h_distance
=>
speed = h_distance / expected_time

```

It also means you would have to do the following again:

```
look_at(target, Vector3.UP)
rotation.x = 0
var vel = -transform.basis.z * speed
velocity = Vector3(vel.x, velocity.y, vel.z)

```

Thus:

```
var jump_speed = h_distance / jump_time
var v_velocity = -0.5 * jump_time * gravity
look_at(target, Vector3.UP)
rotation.x = 0
var vel = -transform.basis.z * jump_speed
velocity = Vector3(vel.x, v_velocity, vel.z)

```

And put `jump_time` (it is in seconds, by the way) as an exported variable alongside `speed`. That should do it… Well, almost. The last block will undo it by setting the velocity again. We can simply put the second if statement in the else of the first one. However, as you have seen we have some code repetition. Instead, I suggest the following refactor:

```
if is_on_floor():
    var h_distance = Vector2(transform.origin.x, transform.origin.z).distance_to(Vector2(target.x, target.z))
    var h_velocity = speed
    var v_velocity = 0
    if Input.is_action_pressed("Jump"):
        h_velocity = h_distance / jump_time
        v_velocity = -0.5 * jump_time * gravity
    if h_distance < 0.05:
        # perhaps you want to flip this line, maybe just set x and z
        target = transform.origin
        velocity = Vector3(0, v_velocity, 0)
    else:
        look_at(target, Vector3.UP)
        rotation.x = 0
        var vel = -transform.basis.z * h_velocity
        velocity = Vector3(vel.x, v_velocity, vel.z)

```

---

## Addendum: Fixing both time and jump height

A way to make the object reach higher is by increasing the initial vertical velocity. However, the object will also take longer to fall down. Thus, we need to change the rate at which the object falls down, which means tweaking the gravitational acceleration.

As soon as the object begins it upwards motion, its vertical velocity begins to decrease according to the gravitational acceleration. Eventually it reaches a point where the vertical velocity is zero. At which point it cannot continue to move up. Thus, that is the highest point of the jump.

The rate at which the object lost its upwards velocity, is the same rate at which it gains downwards velocity: the gravitational acceleration. Since it is the same rate, it takes the same time for the object to get to highest than it gets to fall down from it.

Thus, we can consider the motion in two halves. For the second half, the initial velocity is zero and the object accelerates down for half the jump time. The final velocity has the same magnitud as the initial velocity of the jump, but in the opposite direction. Thus: `v_velocity = -0.5 * jump_time * gravity`, which is what we were using before.

*Remember that gravity is a negative value.*

Now, how high the object gets depends on its initial velocity and the gravitational acceleration. Which are related by the jump time as shown above.

And I'm not going to bother finding the specific equation. Instead, I'll pick a general one:

```
y = v_velocity * time + 0.5 * gravity * time * time

```

We can figure out how high the object is at half way into the jump by replacing `time` with `0.5 * jump_time`:

```
jump_height = v_velocity * (0.5 * jump_time) + 0.5 * gravity * (0.5 * jump_time) * (0.5 * jump_time)

=>

jump_height = v_velocity * 0.5 * jump_time + 0.5 * gravity * 0.25 * jump_time * jump_time

=>

jump_height = v_velocity * 0.5 * jump_time + 0.125 * gravity * jump_time * jump_time

```

We can replace `v_velocity` by the formula we had before:

```
jump_height = (-0.5 * jump_time * gravity) * 0.5 * jump_time + 0.125 * gravity * jump_time * jump_time

```

And we got to solve for `gravity`:

```
jump_height = -0.25 * gravity * jump_time * jump_time + 0.125 * gravity * jump_time * jump_time

=>

jump_height = (-0.25 + 0.125) * gravity * jump_time * jump_time

=>

jump_height = -0.125 * gravity * jump_time * jump_time

=>

-0.125 * gravity * jump_time * jump_time = jump_height

=>

gravity * jump_time * jump_time = (1/-0.125) * jump_height

=>

gravity * jump_time * jump_time = -8 * jump_height

=>

gravity = -8 * jump_height / (jump_time * jump_time)

```

And thus we can update the code:

```
func _physics_process(delta):
    velocity.y += gravity * delta
    velocity = move_and_slide(velocity, Vector3.UP)
    if is_on_floor():
        var h_distance = Vector2(transform.origin.x, transform.origin.z).distance_to(Vector2(target.x, target.z))
        var h_velocity = speed
        var v_velocity = 0
        if Input.is_action_pressed("Jump"):
            h_velocity = h_distance / jump_time
            gravity = -8 * jump_height / (jump_time * jump_time)
            v_velocity = -0.5 * jump_time * gravity
        if h_distance < 0.05:
            # perhaps you want to flip this line, maybe just set x and z
            target = transform.origin
            velocity = Vector3(0, v_velocity, 0)
        else:
            look_at(target, Vector3.UP)
            rotation.x = 0
            var vel = -transform.basis.z * h_velocity
            velocity = Vector3(vel.x, v_velocity, vel.z)

```

And yes, that means that each jump will have a different gravity.

---

## Addendum: Thank you Mario, but the floor is in another elevation

So far we have been ignoring the vertical component of the `target` (when we compute the horizontal distance - `h_distance` \- we only use `target.x` and `target.z`).

As a consequence, if the target is above, the jump will not be able to complete the parabola, and thus will end up short of the target (we found floor before we expected it). Similarly, if the target is below, the jump parabola will overextend, and thus will overshoot the target (the floor wasn't were we expected it, so the jump arc kept going).

Alright, so what do we know? We know that after `jump_time`, we should have reached target coordinates:

```
position(time = jump_time) = (target.x, target.y, target.z)

```

To make it easier, I'll call the initial coordinate zero, and we will be working on jump arc as if it were 2D. Our dimensions are `h` and `v`:

```
position(time = 0) = (0, 0)
position(time = jump_time) = (h_distance, v_distance)

```

Where:

```
h_distance = Vector2(transform.origin.x, transform.origin.z).distance_to(Vector2(target.x, target.z))
v_distance = target.y - transform.origin.y

```

*The sign of `v_distance` is important.*

We also know that the motion will follow the motion equations. This is the one we had previously:

```
y = v_velocity * time + 0.5 * gravity * time * time

```

Which I will rename to `v` for vertical:

```
v(time) = v_velocity * time + 0.5 * gravity * time * time

```

Let me restate the points we had before:

```
v(time) = v_velocity * time + 0.5 * gravity * time * time

v(0) = 0
v(jump_time) = v_distance

```

Actually `v(0) = 0` is trivial, we can see that evaluating `v(time)` when `time = 0` will gives us `0`. Let us not worry about that one:

```
v(time) = v_velocity * time + 0.5 * gravity * time * time
v(jump_time) = v_distance

```

And this gives us - *drum roll* \- infinite solutions. There are infinite possible jump arcs that satisfy those equations. The jump arc could go higher, and have higher gravity, or go lower but with less gravity.

We dealt with that before. We will be modifying `gravity` based on the `jump_height`. However, we want to make sure the jump always goes above both start and end points. If it were below, we would end with negative gravity, and we don't want that.

So, I'll say that `height = max(v_distance, 0) + jump_height` where `jump_height > 0`.

Thus, let us have it like this:

```
v(time) = v_velocity * time + 0.5 * gravity * time * time
v(jump_time/2) = height
v(jump_time) = v_distance

```

By the way, to keep these equations short, I will be using:

```
tt = jump_time * jump_time
gtt = gravity * jump_time * jump_time

```

Now let us solve the equation system. Starting with:

```
v(jump_time) = v_distance

```

We have:

```
v_distance = v(jump_time) = v_velocity * jump_time + 0.5 * gtt

=>

v_distance = v_velocity * jump_time + 0.5 * gtt

=>

v_distance - 0.5 * gtt = v_velocity * jump_time

=>

(v_distance - 0.5 * gtt)/jump_time = v_velocity

```

And starting with:

```
v(jump_time/2) = height

```

We have:

```
height = v(jump_time/2) = v_velocity * jump_time/2 + 0.5 * gtt/4

=>

height = v_velocity * 0.5 * jump_time + 0.125 * gtt

=>

height - 0.125 * gtt = v_velocity * 0.5 * jump_time

=>

(height - 0.125 * gtt) / (0.5 * jump_time) = v_velocity

```

Thus:

```
v_velocity
= (height - 0.125 * gtt) / (0.5 * jump_time)
= (v_distance - 0.5 * gtt)/jump_time

=>

height * 2.0 - 0.125 * gtt * 2.0 = v_distance - 0.5 * gtt

=>

height * 2.0 - 0.25 * gtt = v_distance - 0.5 * gtt

=>

height * 2.0 = v_distance - 0.5 * gtt + 0.25 * gtt

=>

height * 2.0 = v_distance - 0.25 * gtt

=>

height * 2.0 + 0.25 * gtt = v_distance

=>

0.25 * gtt = v_distance - height * 2.0

=>

gtt = (v_distance - height * 2.0) / 0.25

=>

gtt = v_distance/0.25 - height * 2.0/0.25

=>

gtt = 4 * v_distance - 8 * height

=>

gravity * tt = 4 * v_distance - 8 * height

=>

gravity = (4 * v_distance - 8 * height)/tt

```

And we replace that here:

```
(v_distance - 0.5 * gtt)/jump_time = v_velocity

```

Getting:

```
v_velocity = (v_distance - 0.5 * ((4 * v_distance - 8 * height)/tt) * tt)/jump_time

=>

v_velocity = (v_distance - 0.5 * (4 * v_distance - 8 * height))/jump_time

=>

v_velocity = (v_distance - (2 * v_distance - 4 * height))/jump_time

=>

v_velocity = (v_distance - 2 * v_distance + 4 * height)/jump_time

=>

v_velocity =  (4 * height - v_distance)/jump_time

```

Alright, update the code:

```
func _physics_process(delta):
    velocity.y += gravity * delta
    velocity = move_and_slide(velocity, Vector3.UP)
    if is_on_floor():
        var h_distance = Vector2(transform.origin.x, transform.origin.z).distance_to(Vector2(target.x, target.z))
        var v_distance = target.y - transform.origin.y
        var h_velocity = speed
        var v_velocity = 0
        if Input.is_action_pressed("Jump"):
            var height = max(v_distance, 0) + jump_height
            gravity = (4 * v_distance - 8 * height) / (jump_time * jump_time)
            h_velocity = h_distance / jump_time
            v_velocity = (4 * height - v_distance) / jump_time
        if h_distance < 0.05:
            # perhaps you want to flip this line, maybe just set x and z
            target = transform.origin
            velocity = Vector3(0, v_velocity, 0)
        else:
            look_at(target, Vector3.UP)
            rotation.x = 0
            var vel = -transform.basis.z * h_velocity
            velocity = Vector3(vel.x, v_velocity, vel.z)

```

*Tested.*

---
Tags: 3d, mmo, godot
---


# Question
Title: Why does a 3D scene need to be voxelized before it can be transformed into a navmesh?
Why do solutions such as Recast voxelize a 3D scene before transforming it back into polygons?

Would it not be possible to just determine intersections of meshes, check for slope angles and adjust triangulations in that way? I think agent height problems could also be solved by testing sweeps upwards against the other meshes.

# Answer
> 2 votes
DMGregory's point about voxelization's simplicity seems about right. Another reason though, is performance. With these navmesh algorithims, you *need* a way to reduce the complexity of a scene.

Voxelization is a way of reducing the complexity of high poly meshes. Additionally it has the same effect as spatial partitioning whereby the number of potential neighbors of any feature (triangle/voxel) is reduced to a small, finite amount. You can imagine, depending on the mesh, that a long triangle could require intersection checks with a large portion of the scene, while that will never be the case with a voxel.

If you're interested in different approaches then Recast, here's a video by Casey Muratori in which he explains the (real-time) walking system he developed for the Witness. From what I remember, instead of voxels, he uses sort of poles to quantize the world (thereby simplifying it)

---
Tags: path-finding, navmesh
---


# Question
Title: How do I change the turn from a user to the next?
I was asked by a friend to develop a small web game which should support 10 players. Very basic game-play: There is a piñata which has x-"healthpoints". Each player can hit the piñata when it's their turn.

However, I'm having a hard time figuring out how to handle this. As of now, I have three databases:

**Table: game**

* hasStarted
* usersTurn

**Table: users**

* id
* username

**TABLE: usersPlaying**

* id
* username

So far my game works like this:

'users' holds all of the users.

When the game starts all of the online users username are copied into 'usersPlaying'. Then a random row from 'usersPlaying' is selected and that username is copied into 'game' in the 'usersTurn' field.

From the webpage there's a AJAX-script checking for 'usersTurn' variable every second. If the username matches $\_SESSION\["username"\] the users will know if it's their turn.

However from here, I've totally lost it. I cannot figure out how to move on to the next player, and I'm even wondering if this is the right way to go at all. It's not ment to be too fancy, it's only going to be used once or twice.

So with my hands folded - is there anyone who can point me in the right direction?

# Answer
> 0 votes
Whenever you're dealing with a game where multiple players on their own machine are playing the same game (i.e. the same game "session", if you will), the easiest approach is always to **play the game on the server** (i.e. the backend), and have the players' machine (i.e. the webpage they are on, the frontend) merely represent the state of the game on the server and decide the UI based on the server game's state.

Your situation is perfect for this approach.

Now I can't (and won't) write the whole thing for you, but I'll help you get started on the basics.

---

I strongly suggest adding an `turnOrder` field to `usersPlaying`, to keep track of whose turn it is next. If you're using a database, you're not always guaranteed to get the data with the same order, unless you specifically tell the database to order the data.

I would suggest rename `userPlaying` in `game` to `currentTurnOrder`.

Assuming a player set like this:

| UserId | GameId | TurnOrder |
| --- | --- | --- |
| Andy | 1 | 1 |
| Bob | 1 | 2 |
| Chris | 1 | 3 |

You can calculate the next turn, and whose turn it is, using the following formula:

```
$game.CurrentTurnOrder = (($game.CurrentTurnOrder + 1) % $number_of_players) + 1;

```

To walk you through the formula:

* `($game.CurrentTurnOrder + 1)` increases the turn counter
* `% $number_of_players` ensures that when the turn counter goes beyond the amount of players, it loops back to the beginning
* The final `+ 1` is added because `%` returns a 0-indexed value, but we've made `turnOrder` a 1-indexed value, so + 1 to fix it. If you store your `turnOrder` as a 0-indexed value, you don't need to do this step.

If you run this method several times, you will see that `$nextTurnOrder` changes value to 1,2,3,1,2,3,1,2,3,... and therefore creating a perfect match with each player's `turnOrder` column.
For the sake of example, if you had a list of 5 players, , you will see that `$nextTurnOrder` changes value to 1,2,3,4,5,1,2,3,4,5,1,2,..., so you can see that the same formula neatly cycles over all players for any arbitrary amount of players.

So, in order for a given webpage to check if it's their turn, you check the game's current turn order, and see if it matches the local player's `TurnOrder` value.

The basic approach on the webpage is as follows:

* Load the initial game data, including this player's `TurnOrder`
* Keep checking the game's `CurrentTurnOrder` value
* When the game's `CurrentTurnOrder` matches this player's `TurnOrder`, it is this player's turn.

---
Tags: browser-based-games, turn-based, php
---


# Question
Title: Ponderate dijkstra relative to previous position
I use dijkstra in my rust game to find path to a destination. My game is in a square grid like this:

There is, for illustration, the Rust code which use dijkstra:

```
use crate::map::Map;
use crate::physics::GridPoint;
use pathfinding::prelude::dijkstra;

pub fn find_path(map: &Map, from: &GridPoint, to: &GridPoint) -> Option<Vec<GridPoint>> {
    match dijkstra(from, |p| map.successors(p), |p| *p == *to) {
        None => None,
        Some(path) => Some(path.0),
    }
}

// ...

pub fn successors(&self, from: &GridPoint) -> Vec<(GridPoint, i32)> {
        let mut successors = vec![];

        for (mod_x, mod_y) in [
            (-1, -1),
            (0, -1),
            (1, -1),
            (-1, 0),
            (0, 0),
            (1, 0),
            (-1, 1),
            (0, 1),
            (1, 1),
        ]
        .iter()
        {
            let new_x = from.x + mod_x;
            let new_y = from.y + mod_y;

            if new_x < 0 || new_y < 0 {
                continue;
            }

            if let Some(next_tile) = self.terrain.tiles.get(&(new_x as u32, new_y as u32)) {
                successors.push((GridPoint::new(new_x, new_y), next_tile.pedestrian_cost))
            }
        }

        successors
    }
// ...

```

And visualization of found path (white is found path, pink is goal):

The found path is not a direct line. I'm not surprised, because the weight of diagonal is the same as lateral. With what I understand with dijkstra is I can return successor with weight for a coordinate. But I can't increase weight of diagonal/lateral according to previous position (ex: comming from West -\> moving to Est will be less weight; maybe it is not the solution ...).

How can I achieve that ? With another algorithm than dijkstra ?

# Answer
> 1 votes
Once I created this algorithm. You need to increase weight in diagonal paths: you will use the value 10 for non diagonal, and value 14 for diagonal. This value is the distance between squares; 10 is the width and height of square, 14 is the distance between center points of diagonal squares.

This is the code that I calculated the distance between two `pathCell`:

```
int distanceBetween(PathCell A, PathCell B) //find path a to b
{
    int sum;

    //Diagonal cost and not diagonal cost
    int diagonalCost = 14;
    int notDiagonalCost = 10;

    //visitedPaths
    int ndiagonal=0;
    int nNotDiagonal=0;

    //position now
    int nowX, nowY;

    //object pos
    float posBX = B.pos.x;
    float posBY = B.pos.y;

    //setting new pos
    nowX = A.pos.x;
    nowY = A.pos.y;

    //calculating the path distance
    while(nowX != posBX && nowY != posBY)
    {
        int difX = posBX - nowX;
        int difY = posBY - nowY;

        //std::cout << nowX << ", " << nowY << " | " << posBX << ", " << posBY << std::endl;

        if (difX != 0 || difY != 0)
        {
            if(difX != 0 && difY != 0)
            {
               ndiagonal++;
            }
            else
            {
                nNotDiagonal++;
            }

            int aX = abs(difX);
            int aY = abs(difY);
            nowX += (difX/aX);
            nowY += (difY/aY);
        }
    }

    int difX = abs(posBX - nowX);
    int difY = abs(posBY - nowY);
    nNotDiagonal += difX + difY;

    sum = (ndiagonal * diagonalCost) + (nNotDiagonal * notDiagonalCost);

    return fabs(sum);
}

```

You can see the full project code here.

---
Tags: path-finding, rust
---


# Question
Title: Networking a fast-paced game (2D) - Forced Movement - Server / Client
I started a new project, a fast-paced online game (some sort of 2D MOBA). I encountered a problem with the part of netcode about client prediction & server reconciliation.

**Game Mechanics:** 2D - Platformer (MOBA)
**Movement:** WASD (jump / left / down / right)
**Abilites & Autoattack:** J/K/L
**Architecture:** Client/server (authoritative)

My netcode is using these techniques:

* Client-side prediction & server reconciliation
    + Server is sending position & data to the player, the player is replaying the last unprocessed inputs
    + Client is sending input each frame at a fixed timestep (60 times/sec) which are processed on the server-side

* Other entities are interpolated
* Bullets/abilities are extrapolated (Dead reckoning)

So far, this is working good on clients. My question is, how to handle some sort of forced movement?

For example, another player stuns or slows down you, on the server, you will be slowed down or stunned, but you will not know it before the packet arrives, since you are predicting the next state, it will teleport you back because your speed was changed to 0 or lower (in case of slow), it will immediately turn you back (teleport).

What is a good way to handle this technique? I was thinking about interpolating between the current position and the position on the server, but it is not working well for me.

# Answer
> For example, another player stuns or slows down you, on the server, you will be slowed down or stunned

There is a delay there, from when the player initiates the stun until it reaches the server. For the player initiating the stun, it does not happen right away. If we do not deal with that lag, it will bite us later.

Let us follow the general approach: Send message to the server, and initiate animation (not a telegraphing animation, this is at the stage where there is not cancellation), and wait for server response.

Thus, when the player initiates the stun, it will play an animation, which has some duration. We, hopefully get the response from the server just when the animation ends. How much time must pass in the server so that the client receives the response form the server when the animation ends? That is animation duration minus round trip time for that player.

Thus, `ClientA`:

* Send message to `Server`
* Initiate animation (duration = `D`)
* Wait for server response ("stun happens")

Server:

* Receives message from the `CliantA`
* Wait `D - ClientA.RTT`
* Apply stun
* Send message to `ClientA` ("stun happens")

Notes:

* Do not take Wait here as sleeping. It is more like "continue this process after this much time has elapsed", or "remember to do the rest of the steps after this much time has passed".
* By apply stun means that from that moment on, the server will take the stun into consideration in the simulation

---

> but you will not know it before the packet arrives, since you are predicting the next state

Right, we must deal with the other player. The issue is that it can't predict being stun. If only the server could tell the player before the stun should happen… Wait, we can, because we dealt with the entry lag!

Server:

* Receives message from the `ClientA`
* Send message to `ClientB` ("you will be stun in `X`")
* Wait `D - ClientA.RTT`
* Apply stun
* Send message to `ClientA` ("stun happens")

Hmm… So we need this feature where the server tells the client something will happen ahead of time (so that the client can take into account on its prediction).

If we can tell the client something will happen in the future, we can get rid of the wait on the server. Also how much time is `X`? We can try to compute something like `D - ClientA.RTT/2 - ClientB.RTT/2`, However, better talk in frames:

Server:

* Receives message from the `ClientA`
* `Target_Frame = Current_Frame + (D - ClientA.RTT) / Frame_Duration`
* Send message to `ClientB` ("stunt will happen at `Target_Frame`")
* Send message to `ClientA` ("stunt will happen at `Target_Frame`")
* Wait until Target\_Frame
* Apply stun

And there you go. If all clients know on what frame they are, this works, they can predict the stun.

---

> but you will not know it before the packet arrives, since you are predicting the next state, it will teleport you back because your speed was changed to 0 or lower (in case of slow), it will immediately turn you back (teleport).

This should not happen anymore. Because the client was able to predict the stun, because the server told it about it before hand. However…

You are still going to need interpolation. In some situations `D - ClientA.RTT` will be negative. And that just does not work. In others `ClientB` is too far behind.

You can, of course, tweak the animation so that D of reasonable length (keeping in mind that making it longer can be in detriment of user experience). But you can't control the round trip time. If it is long enough then interpolation is the way.
> 4 votes

# Answer
I found a workaround after lot of testing & calculating.

I tried to slowly adjust client position to match server position by adjusting client predicted moves

If server and client does not agree with position, player will continue his client prediction (movement) but it is slowly adjusted to the server position. I do not think this is actually best way to do it, but it hides lags (jittering/teleporting) pretty well.

I will set this answer as solution, however feel free to share your ideas
> 0 votes

---
Tags: 2d, movement, networking, client-server, movement-prediction
---


# Question
Title: Why the MoveTowards make the transform moving nonstop?
In the Update in the else part, I'm trying to move the transform up from its current position on the exit more up by offset.

When the flag bool exit is true I want the transform to move up more by the offset for example if the offset is 7 then move up on the Y more 7. but it's moving up non-stop.

I tried to like this with exitPosition variable for storing at exit: but still, it's moving up non-stop.

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

public class Testing : MonoBehaviour
{
    public float speed;
    public float offset;

    private bool exited = false;
    private Vector3 exitPosition;

    private void Start()
    {
        Debug.Log("Position : " + transform.position);
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.name == "Cube")
        {
            Debug.Log("Exited !");
        }

        exitPosition = new Vector3(transform.position.x,
                transform.position.y + offset, transform.position.z);

        exited = true;
    }

    private void Update()
    {
        if (!exited)
        {
            transform.position += Vector3.up * speed * Time.deltaTime;
        }
        else
        {
            transform.position = Vector3.MoveTowards(transform.position, exitPosition, speed * Time.deltaTime);
        }
    }
}

```

# Answer
Just make sure your *exitPosition* is set only once:

```
private void OnTriggerExit(Collider other)
{
    if (other.name == "Cube" && exited == false)
    {
        Debug.Log("Exited !");
        exitPosition = new Vector3(transform.position.x,transform.position.y + offset,transform.position.z);
        exited = true;
   }
}

```
> 0 votes

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


# Question
Title: Help Me Make Sense of the Canvas and Text-Based Non-UI Objects in Unity
I am trying to wrap my head around the concept of the **Canvas in Unity** and its many uses especially **outside of user interfaces**. However, I cannot really find a good tutorial that digs deep enough into it; so, I was hoping that I can find some help here.

The concept of a user interface needing to have a separate wrapper layer to position elements overlaying the game window does, kinda-sorta, make sense, and I have created one that works fine at the moment. What does not make sense is how everything that contains text also needs to be inside a canvas object to even be visible. I don't understand how a canvas makes sense when I want to display non-UI game elements that contain text, such as damage counters or, as in the case of the game I started working on, playing cards.

Furthering the concept of playing cards, it gets even more complicated. If I understand it correctly, I would not only need a canvas to place my cards on (preferably separate from the one that contains my UI elements) but if I want to put text on my cards and make them come from a reusable Prefab, the Prefab itself needs to be a canvas (or somehow contain one), otherwise text elements would not show up on it (at least based on my trials).

Now, I have read about and actually tried the Text Mesh Pro framework, but honestly I don't need that bloated functionality; a simple text would be perfectly fine for my needs, if only I could make it work.

My question is, can someone **briefly illustrate how to work with canvases and text-based game objects** (preferably in the context of a card game). My cards need to contain an image and several text fields to display various information. What would be the best way to create a Prefab to initialize these cards? Then, what would be the most optimal way to display these cards on the scene (they should not be part of the UI but the game itself).

My game is 2D and uses a pixel art aesthetic if it is relevant.

Many thanks for your answers!

# Answer
> 1. I don't understand how a canvas makes sense when I want to display non-UI game elements that contain text, such as damage counters or, as in the case of the game I started working on, playing cards.

A: All these things are graphical user interface design elements, so by definition they belong on the presentation layer, in this case a Canvas! Even if your cards exists physically in the scene, the best way to display icons, text etc everything you need for a card based game will be mostly done on canvases.

> 2: If I understand it correctly, I would not only need a canvas to place my cards on (preferably separate from the one that contains my UI elements) but if I want to put text on my cards and make them come from a reusable Prefab, the Prefab itself needs to be a canvas (or somehow contain one), otherwise text elements would not show up on it (at least based on my trials).

You can also use TextMeshPro Unity Package which has a Component TextMeshPro (not TextMeshProUGUI) which can be used to display text in world space without a canvas.

A: Incorrect, if the object you are spawning is going to be placed onto a canvas, then the object itself doesn't need its own canvas, in fact due to how Unity Canvases update I would think it would be even worse than giving every single item its own canvas, **since a canvas only updates when something changes, but if something changes the ENTIRE canvas is refreshed and if you have a canvas within a canvas, it will be checking two canvases each time one of them changes.**

I would have thought having all cards on their own canvas, then the dynamic UI on one canvas and static on another would be a good starting point, but really I wouldn't prematurely optimize this.

As to a tutorial there are actually plenty around, though I usually don't like linking Youtube tutorials on GameDevSE https://www.youtube.com/watch?v=aPXvoWVabPY by Brackeys would help you best, this covers using ScriptableObjects as Data containers for cards, it shows you how to set up a prefab, which along with the ScriptableObject data container can display any card you have, it generally explains the concept of using ScriptableObject as data containers for cards well without eating up too much time.

Hope some of this helps!
> 1 votes

# Answer
> everything that contains text also needs to be inside a canvas object to even be visible.

You actually can have text outside of the canvas by adding the TextMesh component or the (IMO superior) TextMeshPro Text Mesh component to a gameObject. These components allow you to create a regular game object represented by a piece of text floating in 3d space.

One possible use-case for that are damage numbers flying around when something gets hit.

But for text on cards in a card game, this is probably not the best approach. I would really recommend to use canvas instead. This makes it far easier to get the layouting of the cards correct and consistent.

> if I want to put text on my cards and make them come from a reusable Prefab, the Prefab itself needs to be a canvas (or somehow contain one), otherwise text elements would not show up on it (at least based on my trials).

No, you misunderstood that. It is perfectly possible to turn a gameObject which is a child of a canvas into a prefab. That prefab will then "remember" that it belongs onto a canvas. When you edit such a prefab, it will even be presented to you within a dummy canvas. I am using that a lot. In fact one of the first things I do in most projects is to create prefabs based on each of the UI elements like Button or Text and then only use instances of those prefabs when building my UI. The reason is that I can then easily change the look of my game UI by editing those prefabs, and the changes then get applied automatically to all the UIs in the game.

So having the playing field as one canvas with each card being a separate gameObject on that canvas instantiated from prefabs is perfectly possible. I would recommend the approach of prefab variants here. Create one template card to define the basic layout all cards are going to have in common. Then create each individual card as a prefab variant inheriting from the basic template card. This has the advantage that any changes to the template card will also be respected in the variants. For example, when you decide to move the points cost from the upper right to the upper left corner, or change the font of the card name from Arial to Helvetica, you don't need to edit 100 cards, you only need to edit one, and all others will inherit those changes automatically.

However, the approach to keep each card as a separate canvas can also have benefits. For example, when you want to do some eye-candy effects like in Hearthstone with cards flying around in 3d space. In that case you can use a World Space Canvas for each card. A world space canvas is a canvas which is not glued to the screen, but instead acts as a game object in 3d space which you can move, scale and rotate as you want. But the drawback is of course that you are now responsible for managing the layout of the playing field yourself and can no longer rely on the auto layouting components for the canvas to do that for you.
> 1 votes

---
Tags: unity, text, unity-ui, card-game
---


# Question
Title: ItemManager / Creating Managing Item Instances
I am looking for advice on how to proceed, currently in my project all items extend from a base ScriptableObject called BaseItem, this class has a property that holds the ItemPrefab for when the item is spawned in-scene.

```
[CreateAssetMenu(fileName = "BaseItem", menuName = "Item/New BaseItem")]
public class BaseItem : ScriptableObject
{
    public string name;
    public string id;
    [TextArea]
    public string description;
    public Sprite icon;
    public GameObject ItemPrefab;

    public virtual void Use()
    {

    }

    public virtual string GetDescription()
    {
        return description;
    }

    public string GetName()
    {
        return name;
    }
}

```

I also have "EquippableItems" that as you might have guessed are equippable by the player, these weapons/armour etc have "Rune slots" on them, where a player can slot in runes to alter the behaviour/stats of the equipment via the inventory.

The problem I have is, I am altering the Prefab of the weapon, when I only want this to effect the current item I'm modifying.

I know why this is occurring because I'm editing the prefab and not an instance of it, I know *sort-of* what I need to do to fix it, but I can't find many examples to learn from.

I belive I need some kind of Manager that handles creating specific instances of a prefab and assigning them an ID, but I do not understand how this would work for inventory items which is where you alter the runes.

Because;

**A:** all items are essentially "stateful" scriptable objects while in my inventory and

**B:** instantiating all the items in my inventory hiding them and referencing that instead seems like a silly way to go about it.

**Example Scenario:**

I have two metal katana's in my inventory, I right click one of the metal katana's and click "Manage Runes" and add a +5 Fire Damage rune, I "drop" both katana's so they are now spawned into the scene on the floor, both weapons have the +5 Fire Damage rune slotted.

How do I handle this scenario so only Katana #1 is slotted with the rune? I know it needs its own instance of that Prefab, but when do I create this while it's in-game but not in scene?

thanks for reading! Apologies I feel this question is rather poorly worded but If I had the correct vocabulary for wording this then I could've done a better job of googling/github..ing.

# Answer
> 1 votes
I'd make the prefab member protected and serialized. This prevents your other code from accidentally modifying the source prefab.

To ensure you can still spawn an instance of it when you want, you expose a public method to do this. You make the method virtual so its behaviour can change in your derived types. The base version can simply call `Instantiate` the way you probably would have anyway:

```
public class BaseItem : ScriptableObject
{
    // ...
    [SerializeField]
    protected GameObject ItemPrefab;

    public virtual GameObject InstantiatePrefab(
                      Vector3 position = default,
                      Quaternion orientation = default) {

        return Instantiate(ItemPrefab, position, orientation);
    }

```

So instead of calling `Instantiate(item.ItemPrefab)`, your code would ask the item to spawn itself: `item.InstantiatePrefab()`.

Now your `EquippableItem` `ScriptableObject` can store its customizations:

```
public class EquippableItem : BaseItem
{
    public Rune[] runeSlots;

```

...and override the instantiation method to not just spawn the prefab, but also customize the instance "just in time" before returning it to its caller.

```
    public override GameObject InstantiatePrefab(
                      Vector3 position = default,
                      Quaternion orientation = default) {

        var instance = base.InstantiatePrefab(position, orientation);

        var equippable = instance.GetComponent<Equippable>();

        equippable.ApplyRunes(runeSlots);

        return instance;
    }

```

Because we're modifying the *instance* we've spawned, not the source prefab, this won't have side effects on other items sharing the same prefab. And we pay nothing for equippables we haven't spawned, since we do this work at the last possible moment when spawning them into the world.

# Answer
> 1 votes
I would recommend you to avoid stateful ScriptableObject's in this case. Instead, consider your ScriptableObjects as immutable item *types*, not as concrete items with mutable state.

Create a separate class (or multiple) to represent item instances which then reference the original ScriptableObject to access various pieces of information they are supposed to have in common with all other items of the same type. But any information which is specific to that item instance is held within the instance. The rune configuration would be an example of such an information which would be part of the concrete item.

This is called the "Flyweight Pattern".

---

However, if you really want to avoid creating separate classes for item *types* and item *instances* (with the latter delegating 90% of their functionality to the type anyway), then there is another option: ScriptableObjects can be cloned at runtime by using `var clone = Instantiate(scriptableObject);`. This gives you an independent copy of the scriptable object.

So when you give each item in the players inventory a reference to a separate clone instead of a reference to the original ScriptableObject asset, then each one has its private copy to store state in, and making changes to that copy will not affect the others.

---
Tags: unity
---


title: Rigidbody not working properly

text:
# Question
Title: Rigidbody not working properly
I have two objects: a player and a wall. The player is passing through the long side of the wall but it collided with the short side of the wall.
I want the player to collide with whole wall.

Here is the code:

# Answer
As I explained here there are 2 ways of moving objects:

1. To change transform position by little bit every frame;
2. To use inbuilt physics, and give rigidbody velocity,(or force).

You chose method 1, which is good method (I use it to move units in my RTS game). However you ran into the problem.

**Your problem is this:**

Choosing to change transform position directly, you are basically telling unity - *no matter what happens move this object a little every frame*. Computer does exactly that - no matter what walls , colliders are in the way computer tries to move your transform. At the same time you set up collider system thus asking physics engine to take care of collisions. So now two systems are **fighting** each other - physics system with colliders tries to stop objects overlapping, and your *Update()* function heroically tries to change transform position no matter what. Result - buggy unpredictable behavior.

**The 2 solutions:**

First one.

Since you move object directly without physics, also stop it directly without using physics. To do that in your player object check the box *isTrigger* (might need to do it on the wall object also). What it does, is tells physics system that this player object is not to be affected by collisions, but it will inform you if such collision occurred. Then set the tag of wall object to something like "wall". Then, in your player script use *OnTriggerEnter()* to find out if you hit the wall.

This would be simplified example of code:

```
bool amMoving;
public void OnTriggerEnter(Collider other)
{
    if (other.transform.tag == "wall" && amMoving == true)
    {
        amMoving == false;
    }
}

void FixedUpdate()
{
    if (amMoving == true)
    {
        // here write your code to move transform little by little
    }
}

```

Second solution - do not move player object every frame, instead give rigidbody of player object velocity or force. And physics system will stop it when collision occurs.
> 1 votes

# Answer
I would try changing the type of collision detection of the rigidBodies. They might be moving to fast and be "tunneling" through objects. unity docs

You can read more about different types of collision detection here
> 0 votes

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


title: Scrolling the map in a 2D a tiled game

text:
# Question
Title: Scrolling the map in a 2D a tiled game
I am making a small game where I store information about the world around the player (like tiles) using a small 2d array of integers. In the game you can scroll the screen to the left or right. I also want to be able to read portions of the world from a file instead of loading the entire world at once for performance reasons. My concept of doing this is when the camera has scrolled a certain amount, shift the array by a certain amount and replace the old array data with new information from the file. I'm not sure if this makes sense performance wise or if there is a more performance friendly way of doing this so I was wondering if anybody could provide some insight. I drew an image to show what I am talking about.

# Answer
That looks like how I'd do it. If possible, use an array or array-like data structure that lets you add and remove elements.

Pseudo-code:

```
//O(1) or O(n) depending on data structure
public void ScrollRight(var newColumn) {
    //remove leftmost column. this will shift other columns left one
    columns.RemoveAt(0);
    //insert new column in the rightmost position
    columns.Add(newColumn);
}
//O(1) or O(n) depending on data structure
public void ScrollLeft(var newColumn) {
    //remove rightmost column.
    columns.RemoveAt(columns.Count - 1);
    //insert new column in the leftmost position, shifting other columns right one
    columns.Insert(newColumn, 0);
}

```

The above is much more efficient than this approach:

```
//DON'T do it this way if you can avoid it
//O(n x m), where n = # of columns and m = # of rows
public void ScrollRight(var newColumn) {
    //shift each column left by copying its data to the previous column
    for (int c = 0; c < columns.Count - 1; c++) {
        var column = columns[c];
        var nextColumn = columns[c + 1]
        for (int r = 0; r < column.Count; r++) {
            column[r] = nextColumn[r];
        }
    }
    //copy new data into the last column, replacing old data
    var lastColumn = columns[columns.Count - 1];
    for (int r = 0; r < column.Count; r++) {
        lastColumn[r] = newColumn[r];
    }
}

```
> 0 votes

---
Tags: 2d, tiles, data
---


# Question
Title: How to change FPS when using a sprite sheet and AnimationPlayer?
With AnimatedSprite it is easy to change FPS. Is there a convenient way to do that with AnimationPlayer?

# Answer
> 1 votes
`AnimationPlayer` has a `playback_speed` that you can use the way as the `speed_scale` property of the `AnimatedSprite`.

However, there is no way to manipulate the speed of the individual animation themselves. That is, you cannot change the speed of the animations, only the speed of the player.

Suffice to say that the animations are not encoded in frames, but time in seconds instead.

By the way, I remind you that with Property Tracks and Call Method Tracks, the `AnimationPlayer` can manipulate other nodes, including `AnimatedSprite`.

---
Tags: godot
---


# Question
Title: How to use a normal map for light effects with an AnimatedSrpite?
I am trying to add light effects with normal map on an AnimatedSprite. I was following that tutorial but with no success.

I am using a `Ligth2D`, this sprite sheet:

and have created a shader on Material to apply the normal map with this code:

```
shader_type canvas_item;

uniform sampler2D normal_map;

void fragment(){
    NORMAL = 2.0 * texture(normal_map, UV).rgb - 1.0;
}

```

Here is the result:

One can observe a light reflection on the left upper of the hourglass, but the light is neither smooth nor consistant.

NB: I have made the spirte sheet myself, feel free to use it.

# Answer
The issue was from the fact that I was using a single sprite normal map with a sprite sheet:

When using this, everything works just fine:
> 1 votes

---
Tags: animation, lighting, godot
---


# Question
Title: Stop 2D platformer character from sliding down slope
I'm making a 2D platformer game with the default Unity 2D physics. I am implementing slopes, but my player slips down the slope because of the physics.

Here is the code I use for the player movement:

```
MoveInput = Input.GetAxisRaw("Horizontal");
rbd2.velocity = new Vector2(MoveInput * speed, rbd2.velocity.y);
//rotacion de personaje
if (MoveInput > 0)
{
    transform.localScale = new Vector3(1f, transform.localScale.y, transform.localScale.z);

}
if (MoveInput < 0)
{
    transform.localScale = new Vector3(-1f, transform.localScale.y, transform.localScale.z);

}

```

# Answer
Unity here is constantly running physics simulation (trying to mimic the actual world a bit) and thus applies various forces to your rigidbody2d depending on situation. If rigidbody is on the slope there is the *downwards force* of gravity applied to it. It results in downwards and backwards velocity so that object starts to slide back.

**So your problem is** \- that this backwards/downwards velocity is greater than your forward/upward velocity which you applied.

We can not change physics algorithm, however we can adjust the **parameters**.

to fix it (and make it behave the way you want) adjust these parameters:

* adjust Mass in Rigidbody2d. Try to *increase* it. This alone ***should*** solve the problem.
* you can lower the slope angle
* apply higher velocity

It should work.. Also take a look at Rigidbody2D and play around with its parameters until it behaves as you want.
> 0 votes

---
Tags: unity, 2d, physics, platformer, character-controller
---


# Question
Title: Placing a circle as close as possible to a specific coordinate without overlapping another circle
I am working on a 2D game in Java. My goal is to place a ball as close as possible to the center without overlapping the balls that are already there. How can this be done?

# Answer
> 2 votes
If you take each circle that's already been placed, and expand it by the radius of the one you want to place. Together, these circles form an "exclusion zone" - places where the center of your new circle cannot go without overlapping one of the circles already there. I've visualized the exclusion zone in pink created by the grey circles below. The big black dot is the center of the map we want to try to place our new circle close to.

If the target point we want to approach is inside this pink exclusion zone, then the closest our new circle's center can get is somewhere along the perimeter of the blob these exclusion circles form together. I've highlighted that perimeter in red. We'll check each arc on that perimeter to find our closest point.

To speed up out checks of what is or isn't in the exclusion zone, we can divide our map into a grid of buckets. Above, I've chosen the bucket size to be \\$\sqrt 2 \cdot r\_\text{min}\\$ where \\$r\_\text{min}\\$ is the smallest radius of any grey circle. This means that there can be at most one grey circle center in any bucket, and we only ever need to scan a fixed set of buckets around our test point to find all the exclusion circles that could exclude it - no matter how many circles there are in total.

If all your circles have the same radius, then that's a 5x5 box centered on the point to test. If you have 25 or fewer circles, then just brute forcing through the full list would be just as good.

Alright, with that out of the way, let's get into the meat of the algorithm:

1. We check to see if the target point we want to approach is in our exclusion zone. If not, we're done - place your new circle at that point.

If it is, then we'll add *all* circles overlapping it to what we'll call "the open set". These are the circles we've found, but haven't investigated in detail yet.
2. While the open set is non-empty, take an exclusion circle out of it and add it to the "closed set". These are the circles we've checked thoroughly.

We'll call this our "parent circle".
3. Next we'll find the point along the parent circle's circumference that's closest to our target point, by projecting the line from the parent's center through the target out to the exclusion radius. (Note that this point might not be on the outer perimeter of the whole blob - we'll check that next)

```
toTarget = target - parentCircleCenter;
closest = parentCircleCenter + toTarget.Scale(parentExclusionRadius / toTarget.Magnitude());

```
4. If this blue point is not the closest candidate we've found so far, we give up on this circle. No other point on its perimeter will be any closer. So we grab the next circle off the open set and repeat from 2. (Note that this can't happen for the first circle we check, since we have no better candidate so far)
5. If the blue point *is* the closest we've found so far, we check whether it's inside any other circle on the exclusion zone.

If not (like the example on the left), then we record it as our best candidate and continue to the next circle in the open set.
6. If the blue point is inside another exclusion circle (like the example on the right), then we walk through each other exclusion circle it's a part of. We'll call these "child circles" to distinguish them from the parent we started with.

We'll skip over any child circles that are already in the closed set, to ensure we don't end up going in a loop checking the same circles over and over.
7. As we check each child circle overlapping this blue point, we add it to the open set if it wasn't in it already.
8. We find the two points of intersection between the child circle and the parent circle - you can use the formulas here for that.
9. We check if either of these two intersection points is closer than our best candidate so far.

If so, we check whether this intersection point is excluded by any circles other than the parent-child pair we just looked at. If so, we add that neighbouring circle as another child to check. If not, then we log the point as our best candidate.

Once we've looked at both intersection points and either logged them as our best candidate or rejected them as worse / excluded, we continue to the next child circle in 6.
10. Once we run out of child circles to check, we examine the next circle in the open set in 2 - giving us a new parent circle.
11. Once we've emptied the open set, we're done. The best candidate point that we've found is the best possible.

Note that unlike a randomized approach, this route is guaranteed to find the closest point there is, and that it will do so in a bounded number of steps, linear in the number of circles we need to avoid (we do a bounded amount of work per circle added to the closed set, and we add each circle to the closed set only once).

Also, in the pathological case where there is *no* available place to put a new circle, this approach will determine that in its normal runtime instead of running forever.

# Answer
> 0 votes
While making games I face similar problems quite often. What I found is that often best (quickest,easiest) way is.. not to look for that perfect answer, instead use computer to work it out for me.

This dead simple solution will work:

So there is infinite number of points. Lets find that one.

a) write function which checks if given point is valid. It should check distance to each balls center and if there is enough space for your ball, return true.

b) write a while loop where different points are checked until valid is found. In this loop first supply the center point, then *Random* point close to it, then another.. until fitting point is found.

That's it. Lazy dumb solution but it will work, and yes it might take few hundred cycles to find it, but in user time it will be just a moment. Also add some protection from forever-loop.

---
Tags: java, 2d, algorithm, geometry
---


# Question
Title: Why the distance from the missionTarget is never less then 0.15?
```
using UnityEngine;
using UnityEditor;
using System.Collections;

public class SmoothFollow : MonoBehaviour
{
    public Transform missionTarget;
    public Transform targetToFollow;
    public float lookAtRotationSpeed;
    public float moveSpeed;
    public float followRadius = 1.5f;
    public float fastRadius = 5f;
    public float speedBoost = 0.5f;
    public bool follow = false;
    public bool reachTarget = false;
    public bool moveToMissionTarget = false;
    public float waitAtMission;

    private bool isChild = false;
    private bool changeToOrigin = false;
    private Vector3 lTargetDir;
    private float originSpeed;
    private float originFollowRadius;

    void Start()
    {
        originSpeed = moveSpeed;
        originFollowRadius = followRadius;

        if (reachTarget)
        {
            followRadius = 0.1f;
        }

        waitAtMission = Random.Range(3, 10);
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        if (follow)
        {
            Move(targetToFollow);

            var dist = Vector3.Distance(transform.position, targetToFollow.position);
            if (dist < 0.1f && isChild == false)
            {
                transform.parent = targetToFollow;
                transform.localPosition = new Vector3(0, 0, 0);
                transform.localRotation = Quaternion.identity;
                transform.localScale = new Vector3(0.001f, 0.001f, 0.001f);

                isChild = true;
                follow = false;
            }

            originSpeed = moveSpeed;
            originFollowRadius = followRadius;
        }

        if (moveToMissionTarget && missionTarget != null)
        {
            follow = false;
            Move(missionTarget);

            var distFromMissionTarget = Vector3.Distance(transform.position, missionTarget.position);
            if (distFromMissionTarget < 0.15f)
            {
                moveToMissionTarget = false;

                StartCoroutine(WaitAtMissionSide(waitAtMission));
            }
        }
    }

    private void Turn()
    {
        transform.rotation = Quaternion.RotateTowards(transform.rotation,
                Quaternion.LookRotation(lTargetDir), Time.time * lookAtRotationSpeed);
    }

    private void Move(Transform Target)
    {
        if (reachTarget)
        {
            changeToOrigin = true;
            followRadius = 0.1f;
        }
        else if (changeToOrigin && reachTarget == false)
        {
            moveSpeed = originSpeed;
            followRadius = originFollowRadius;

            changeToOrigin = false;
        }

        lTargetDir = Target.position - transform.position;
        lTargetDir.y = 0.0f;

        Turn();

        float ms = moveSpeed;
        var distance = Vector3.Distance(transform.position, Target.position);
        // Compute a position no further than followRadius away from our target.
        Vector3 fromTarget = Vector3.ClampMagnitude(
            -lTargetDir.normalized, followRadius);
        Vector3 stopPoint = Target.position + fromTarget;

        // Compute a speed that's faster when far away and slower when close.
        float speedBlend = Mathf.Clamp01((distance - followRadius) / (fastRadius - followRadius));

        ms = moveSpeed + speedBlend * speedBoost;

        // Move as far as we can at our speed ms to reach the stopPoint, without overshooting.
        transform.position = Vector3.MoveTowards(transform.position,
            stopPoint, Time.deltaTime * ms);
    }

    private IEnumerator WaitAtMissionSide(float WaitAtMissionTime)
    {
        yield return new WaitForSeconds(WaitAtMissionTime);

        follow = true;
    }
}

```

At this part :

```
var distFromMissionTarget = Vector3.Distance(transform.position, missionTarget.position);
            if (distFromMissionTarget < 0.15f)
            {
                moveToMissionTarget = false;

                StartCoroutine(WaitAtMissionSide(waitAtMission));
            }

```

The distance value on distFromMissionTarget is 1.000001 but if I want it to be less than 0.15f ?

# Answer
> 1 votes
your code needs cleaning a bit.

here is your problem:

Within function *Move* you are telling object to move to position *stopPoint* not to *missionTarget.position*. That's what object does, - it arrives to *stopPoint*.

and where is *stopPoint*? It is about 1 meters backwards from your *missionTarget.position*.

```
   Vector3 fromTarget = Vector3.ClampMagnitude(-lTargetDir.normalized,followRadius); // here you just created vector pointing 1 m backward
    Vector3 stopPoint = Target.position + fromTarget;  // and added target position with backwards pointing 1 m long vector...which gives you position 1 m backwards .. which results in stopping much earlier (about 1 m earlier..)

```

P.S. note that any vector if normalized - its size becomes 1. So there is no benefit of normalizing vector if you are going to clamp it..

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


# Question
Title: How can I move an object the fastest way?
How can I move an object the fastest way?

What I'm trying to do is to make an object pass by at speed that you almost cannot see - like an airplane that moves from side to side in very high speed.

Here is my code:

```
transform.position = Vector3.MoveTowards(transform.position,
            stopPoint, Time.deltaTime * ms);

```

# Answer
> 0 votes
Yes, Vector3.MoveTowards can be used. All it does - it moves object a bit. The bigger this 'bit' the further it moves.

if you put it in Update() function it will move your object every frame by 'a bit'. The bigger amount it moves the faster *it seems* to move.

so to adjust the speed in your case just play with values of *ms*, and *stopPoint* untill you get effect you are looking for.

Alternative way of moving things is to add rigidbody and give rigidbody a velocity (but not in Update() function).

So these are 2 ways of moving things in Unity - either move bit by bit, or use physics to move it for you (which is also moving bit by bit, but Unity takes care of all details).

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


title: Icons and imagery rights

text:
# Question
Title: Icons and imagery rights
Can someone tell me if the icons and images of TravianZ in this GitHub project are public domain?

I need to create a similar game and need only the town / buildings images. Seems the project was abandoned so I don't know who to ask.

# Answer
> 1 votes
The image folders of that repository contain this notice:

```
#################################################################################
##              -= YOU MAY NOT REMOVE OR CHANGE THIS NOTICE =-                 ##
## --------------------------------------------------------------------------- ##
##  Filename       404.tpl                                                     ##
##  Developed by:  aggenkeech                                                  ##
##  License:       TravianX Project                                            ##
##  Copyright:     TravianX (c) 2010-2012. All rights reserved.                ##
##                                                                             ##
#################################################################################

```

So it looks as though these assets were copied from a previous adaptation of the game, and the prior copyright would still apply to them.

If you cannot find a statement from the authors releasing these assets into the public domain, then they are not in the public domain. Not enough time has passed from the date shown above for the original creators' copyright to pass into public domain.

---
Tags: image, copyright, licensing
---


# Question
Title: How to check if gun may shoot again (because animation has stopped playing)?
When the user presses the fire button, I set a trigger:

```
_animator.SetTrigger("HG_Shoot");

```

This trigger causes a "pistol shoot" animation to be played.

The gun should only be able to shoot again as soon as the shoot animation has finished.

I could check at each Update() if that certain animation is still being played like this:

```
 bool isAnimationStatePlaying(Animator anim, int animLayer, string stateName)
 {
     if (anim.GetCurrentAnimatorStateInfo(animLayer).IsName(stateName) &&
             anim.GetCurrentAnimatorStateInfo(animLayer).normalizedTime < 1.0f)
         return true;
     else
         return false;
 }

```

But I don't like the frequent checks. I would rather like to have a variable to would be set by the animator. Or I would set it at the beginning of the shoot animation.

Because there are other animations that I have to check that would disallow shooting of the gun, too, like reloading the gun.

This would make everything even more complicated.

How can I solve this problem?

# Answer
You could use Unity's `StateMachineBehavior` component. I'll tell about it later.
However, it's actually might be an overkill feature that might bring up more complexity to the project than needed.
There's nothing wrong with your current approach as far as you keep things more or less readable and properly structured. The only other alternative (in addition to your current approach and `StateMachineBehaviour` approach) would be a timer that would count down in every frame to check if the shoot cooldown is over, or reload time is over, and it's also a commonly used approach.
As for the `isJumping`, `isClimbing`, etc states when the gun shouldn't be able to shoot as well, these states should be managed in the character scripts while the gun's `isShooting`, `isReloading`, `isJammed` states should be in the gun's scripts. That's how you keep things manageable. Player clicks `Fire` button, you call `Shoot()` method in the character script that checks the character's states such as `isJumping`, etc, and then if everything is fine and the character is not busy you call the gun's `Shoot()` method that checks if the gun is not already shooting or reloading currently.
Okay. The `StateMachineBehaviour`. This is a thing that allows you to get certain predefined events from the animator states (nodes in the animator controller window) so you can do your stuff when the animator has entered an animation state, is currently performing some animation or the animation is over and the control is going to transition to some other state.
Here is the official manual: https://docs.unity3d.com/Manual/StateMachineBehaviours.html
The basic workflow is: You open up the animator controller window of the gun's animator, select your 'Shoot' node, than in the inspector window you add a `StateMachineBehavior` component to the node.
It should generate a script that has several methods like this:

```
//OnStateExit is called when a transition ends and the state machine finishes evaluating this state
override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) {

}

```

(Not sure if this is exactly how it's done though, I didn't use the `StateMachineBehaviour` for a long time).

That's what you're looking for - an event that fires when the 'Shoot' animation is over. There is also the `OnStateEnter(...)` method available as well.
So, you could manage the gun's 'canShoot\` boolean flag like this:

```
override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) {
    GunScript gun = animator.GetComponent<GunScript>();
    gun.canShoot = false;
}

override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) {
    GunScript gun = animator.GetComponent<GunScript>();
    gun.canShoot = true;
}

```

You would need to add similar components to other animator nodes like the gun's 'Reload' node, the player's 'Jump' node, etc, so whenever these animations are played the gun's `canShoot` flag will be set to `false` and get back to `true` when the animation is over.
> 2 votes

# Answer
You could add an animation event to your shooting animation action which calls back your controller script and signals it that the player can shoot again.

However, I generally prefer to not design my gameplay using the animation system. I instead design the gameplay first and then have the animation match the gameplay. A game is far easier to balance when all the relevant numbers are in one place. So I would usually define the fire rate of each weapon in the same place where I define the damage, range, accuracy and so on. Then I would experiment with those values until the game is properly balanced, and then take care of matching the animations to the gameplay. Matching animations to gameplay can also be automated by calculating the playback speed of animations based on gameplay variables.
> 2 votes

---
Tags: unity, performance, animator
---


# Question
Title: Where do I have to put actions when the game state changes
I’ve just started to learn Unreal Engine implementing a clone version of Atari’s Pong game.

I’m thinking about where to put the code to change the state of the game. I have an enum in the GameState class to manage when the game hasn’t started, or when we are playing the game. In case when someone scores I decided that I have to stop the ball and move it to its initial position.

My problem comes here because I don’t know where to put the code to do that: on GameMode class or on GameState class.

Where do I have to put that code?

# Answer
The GameMode is for storing the rules of the game.

GameState is for keeping track of the game statistics like score etc. In a pong type game, it would also keep track of whose turn it is to serve next.

GameState is the better place for what you're trying to do.
> 1 votes

---
Tags: unreal-4
---


# Question
Title: Errors displayed even when the project runs in Unity
I work with Unity and Visual Studio.

Almost every single keyword is underlined with the red curvy lines (representing error) in all scripts but the game works fine when I play it.

I tried unloading and reloading the solution and rebuilding and building the solution. But that solves my problem only to some extent. I tried restarting Visual Studio and my computer but that doesn't help.

The problem stated in this question is kind of similar to mine, but the answers do not seem to work with the `UnityEngine` namespace.

Earlier, while working on the same project I didn't get those errors for any reason. I am now getting these errors. I already have checked and installed everything needed.

# Answer
You probably didn't install the additional Unity tools for Visual Studio. Here's what you need to do to setup Visual Studio to work with Unity: https://docs.microsoft.com/en-us/visualstudio/gamedev/unity/get-started/getting-started-with-visual-studio-tools-for-unity?pivots=windows
> 1 votes

# Answer
I solved the errors later by mistake, by doing this:

This is what I did -

1. Made new scripts
2. Copied the code of old scripts to the new ones
3. Deleted the old scripts
> 0 votes

---
Tags: unity, c#, visual-studio
---


# Question
Title: How to pass parameters to a Blueprint function called from C++?
I have found this piece of code showing how to call a blueprint function from C++:

```
 UFUnction* Func = Obj->GetClass()->FindFunction(FName("FuncName"));
 if(Func == nullptr){return;}

 FStructOnScope FuncParam(Func);
 UProperty* ReturnProp = nullptr;

 for (TFieldIterator<UProperty> It(Func); It; ++It)
    {
     UProperty* Prop = *It;
     if (Prop->HasAnyPropertyFlags(CPF_ReturnParm))
     {
         ReturnProp = Prop;
     }
     else
     {
         //FillParam here
     }
 }

 Obj->ProcessEvent(Func, FuncParam.GetStructMemory());

```

But… I don’t know how to `//Fillparam here`.

How can I fill the `FuncParam` with the parameters that I need to pass?

# Answer
> 1 votes
From what you've said in your comments, you're going about this backwards.

By default, C++ can't read Blueprint and, getting it do so seems like a very complicated way of doing it when there are much easier ways to go about this.

As the Widget is being derived from a C++ class, the easiest way for what you're trying to do would be to make a function in C++ but make it a UFUNCTION.

```
UFUNCTION(BlueprintCallable, Category = "Gameplay")
int32 GetPlayerScore();

```

Then in your CPP file, return an int32 showing the score. In your BP, you can now call this function directly and plug the output node into the necessary variable on your widget BP.

---
Tags: c++, unreal-4, unreal, blueprints
---


# Question
Title: Mixamo Rig Hierarchy Reference (In Text List/Tree format)? (modelling in Maya for use in Unity and Mixamo)
I'm trying to find a quick reference to match Mixamos rigging hierarchy. I'm confused over which bones are 'root' and how many bones in the spine/pelvis/chest etc. I want my characters I make in Maya to be fully supported by Mixamo library of animations as well as my own keyframe style animations I intend to make in Maya.

I'm really struggling to make a fully human IK rig for my characters. I found this on Unity Documentation: https://docs.unity3d.com/2017.3/Documentation/Manual/Preparingacharacterfromscratch.html

It states: Possible structures for the hierarchy might be:-

* HIPS - spine - chest - shoulders - arm - forearm - hand
* HIPS - spine - chest - neck - head
* HIPS - UpLeg - Leg - foot - toe - toe\_end

But in other examples and guides I read and watched (including the official Maya documentation) the HIPS are not the root.

This is how I understood the hierarchy to be:

* BACK\_ROOT - pelvis - hip - knee - ankle - foot - toes
* BACK\_ROOT - lower\_back - upper\_back - lower\_neck - upper\_neck - head upper\_back - arm\_root - shoulder - elbow - wrist

I am quite sure I have it wrong but have tried many variations of parenting the bones together, and indeed have tried different amounts of bones as some tutorials differ.

I've had multiple problems with my rig mainly from the fact I can't get the Human IK to work fully in Maya (adding IKHandle to leg or arm can work, but the root just moves the character and there is no way for me to make him crouch automatically as I move the body downwards).

Now I'm lost and not sure even how many bones I need and where.

I already posted a question here and Maya Forums about the similar issue. I got this response on Maya Forums (https://forums.autodesk.com/t5/maya-animation-and-rigging/ik-handle-for-back-bones-allowing-me-to-move-body-downwards-and/m-p/10321981) but I didnt understand what he meant and when i tried adding what he suggested it failed with orange in the HIK view and said it was not alighed to X-axis (It was aligned but the elbows where bent out just slightly as per the maya docs tutorial and others I had seen)

I done another attempt and the arms look aligned to me:

If someone knows of a text guide showing in exactly what a good hierarchy of joints looks like, please be kind enough to post it. I try searching the web but all i can see is tutorial videos and text I have already seen.

# Answer
OK well no sooner than posting the question I had a brainwave. I loaded Unity and found a project where I'd imported an auto-rigged character from Mixamo. Here is the screen of the hierarchy. Not quite in text format, but might serve as a good reference seeing as I was unable to find this online.

Hopefully this is a correct hierarchy, although I still haven't fixed my problem on making my own human IK rig in Maya.
> 0 votes

---
Tags: unity, animation, skeletal-animation, maya, rigging
---