title: How to allow infinite custom inputs?

text:
# Question
Title: How to allow infinite custom inputs?
***Summary: What approach should I take to allow custom inputs saved in a file be interpreted in the engine?***

So I am making a game engine similar to Mugen where I want characters to have their own special combo inputs. Similar to how Kage has the Shun Goku Satsu. Where its just a combination of multiple keys pressed in quick succession. The thing is I want to give the ability to create these combinations to the character creators and let the engine handle the rest.

I already parsed the list of moves from the character file, so now I got an in-memory list of valid input sequences for each character and what moves they trigger. But I don't really know how to interpret a valid sequence.

# Answer
What you basically need to do is have a list of the input sequences of the character and a counter for each sequence which states at what step of that input sequence they are currently on. For example, let's assume that the list of input sequences of the player-character is the following:

```
punch, punch, kick
punch, kick, punch, forward
kick, punch, backward

```

At the start of the game, the player did not make any inputs yet, so the counter for all three sequences would be at 0.

When the player presses "punch", then you would check all three sequences and notice that it matches the currently expected input for sequences 0 and 1. So you increment the counters for those two sequences by one. Now the list of sequences with their counters look like this:

```
1    punch, punch, kick
1    punch, kick, punch, forward
0    kick, punch, backward

```

Now the player presses "kick". The first sequence expects a punch, so this was a wrong input for it. Its counter gets reset to 0. But kick matches the next expected entry for sequence 1, so its counter gets incremented to 2. It also matches the first input of sequence 2, so it gets incremented to 1:

```
0    punch, punch, kick
2    punch, kick, punch, forward
1    kick, punch, backward

```

Next input is "punch", which actually matches the next expected input of all three sequences:

```
1    punch, punch, kick
3    punch, kick, punch, forward
2    kick, punch, backward

```

Now there are four possible options which could happen next:

1. The player might press "punch" again, advancing the sequence 0 but resetting all others
2. The player might press "forward" completing sequence 1 and resetting all others
3. The player might press "backward", completing sequence 2 and resetting all others
4. The player might press something entirely different, resetting them all.

When the player actually completed a sequence, then they just entered a valid move sequence. Their character performs that move and all the sequence gets reset to 0.

When you implemented this successfully, then there are a couple other things you might want to take care of next:

* When the player doesn't make any inputs for a while, then you might also want to reset all the sequence counters back to 0. This can be easily accomplished by sending a "null input" to the system which does not match any input the content creators can define.
* What happens when the character gets hit while the player is performing an input sequence? Does it interrupt those sequences? And what happens when a sequence finished, but the character is currently in a state where they can not perform this move? This is more of a game design question, so you will have to find your own answer for these questions (or open a new one).
* The content creators might create sequences which are prefixes for others. For example, they might create one sequence "punch, punch, kick" and another "punch, punch, kick, punch". When a player entered the first sequence, then there is no way to tell if they are finished inputting the first sequence or want to continue with the second. You have to decide how to handle that situation. You might disallow that, you might wait for a 4th input before executing the move, or you might start the first action but then abort it and continue with the other on the 4th input.
* The content creators might create sequences which are suffixes of others. This might lead to ambiguous situations where the player completed two sequences at the same time. Like "punch, punch, kick" and "kick, punch, punch, kick". When the player completes the second sequence, they also completed the first. In that case you should give precedent to the longest sequence. When two sequences have the same length... well, then the content creator created a duplicate entry, and you should ~~smack them for that~~ reject the character file with an error message.
> 2 votes

---
Tags: c++, input, sfml
---


# Question
Title: fastest way to check for surrounding tiles
I'm working on a tile map where each type of tiles has 12 states with 12 different sprites associated with it, what I'm trying to say is that whenever I place a tile let's say a road tile, that tile should adjust itself automatically according to the 4 tiles surrounding it, so for example if the tile above it is a road tile and the tile below it is also a road tile, it should automatically adjust itself into a vertical road tile... there is 12 states a tile can have:

1-closed(not surrounded by any similar tile)

2-horizontal(similar tiles up and down)

3-vertical(similar tiles right and left)

4-open from up and left(similar tiles to the left and above)

5-open from left and down(...)

6-open from down and right(...)

7-open from right and up(...)

8-open from up & left & down(3 similar tiles up, left and down)

9-open from left & down & right(...)

10-open from down & right & up(...)

11-open from right & up & left(...)

12-open from all 4 directions(all surrounding tiles are similar)

the problem is that I don't know how to check for surrounding tiles and choose the right tile state without having a huge mess of if statements and performance waste, and I don't have enough experience with algorithms and data structures to figure it out myself.

how can check all 12 states the fastest way possible ?

thanks!

# Answer
> 2 votes
Use a binary mapping:

* Assign the directions N/E/S/W to the numbers 1/2/4/8
* If the adjacent tile is a road, add that number.
* Use the resulting number as the tile image.

The map tiles will need to be in the corresponding order. No adjacent roads is tile 0, and 4 adjacent roads is tile 15. If your sprite sheet is laid out correctly this can be coded in a concise and elegant way.

Your 12 states are missing the case where there is a single adjacent road. You need to decide what happens with that, if it's a possible game state (duplicate the closed tile?).

Here's an example from one of my old projects:

```
var tileMap = new Array(9, 10, 13, 16, 12, 11, 17, 21, 15, 18, 14, 23, 19, 24, 22, 20);
var mapDressing = 0;

function getTileImage(x, y) {
    //in: x,y location of tile
    //out: number of tile for that location
    //known: global tile map
    if (!isWall(getTile(x,y))) {
        return (mapDressing * 54) + 4;
    }

    var tileAbove = getTile(x, y-1);
    var tileBelow = getTile(x, y+1);
    var tileLeft = getTile(x-1, y);
    var tileRight = getTile(x+1, y);

    var tileAboveContent = 0;
    var tileBelowContent = 0;
    var tileLeftContent = 0;
    var tileRightContent = 0;

    if (isWall(tileAbove)) {
        tileAboveContent = 1;
    }
    if (isWall(tileBelow)) {
        tileBelowContent = 1;
    }
    if (isWall(tileLeft)) {
        tileLeftContent = 1;
    }
    if (isWall(tileRight)) {
        tileRightContent = 1;
    }

    var tileIndex = tileRightContent + tileBelowContent*2 + tileLeftContent*4 + tileAboveContent * 8;

    return (mapDressing * 54) + tileMap[tileIndex];
}

```

# Answer
> 1 votes
If you want to change the state of a tile based on its neighbors, you pretty much have to do this. You can calculate the cost up-front during construction if the map doesn't change during the game but it's almost unavoidable to have to iterate through all the neighbors and keep a count.

There are small improvements that can be made using bit manipulation techniques for instant checking, but again, the value representing the neighbors' state still needs to be calculated somehow.

---
Tags: algorithm, tilemap
---


title: Sliding movement on a grid

text:
# Question
Title: Sliding movement on a grid
I'm trying to implement "sliding" movement on a simple grid, where the movement vector is continuous (floating point direction) but the grid is discrete (boolean blocked or open on integer axes).

The "destination" tile is found by adding the rounded movement vector to the current tile. That part is naive and works well enough.

For example, here:

* blue is the current (source) tile
* the yellow arrow is the movement vector
* green is the destination tile

But this movement ends up being restrictive and I'd like to enable "sliding" to approximate player intent. **My goal is that if the destination tile is blocked, the "next best" tile is used instead, provided it is available. I don't know how to calculate that.**

As you can see, the naive destination tile (where the yellow arrow lands) is blocked. As a result, I'd like to pick the green tile above as the destination tile.

However, crossing a diagonal should be allowed either, so the following case should result in the movement being blocked:

Finally, I'd like this algorithm to be as permissive as possible, so even the smallest component of the movement vector could win if no better alternative is found. For example, the movement should carry upwards in that case:

This sounds like a fairly simple problem and there may be existing algorithms for it, but I don't know what it's called, so I'm having trouble finding resources on it.

# Answer
1. Check if the cell in the direction of the largest component (in absolute value) is free.

* If so, move there. Done.
2. Check if the cell in the direction of the smallest component (in absolute value) is free.

* If so, check if the diagonal cell that's the sum of the two previous offsets checked is also free.

    + If so, move there. Done.
    * If not, move to the tile in step 2. Done.
3. If we get here, we're blocked on both sides and cannot honour movement in this direction.

You'll likely want to set a minimum threshold on the check in step 2. If the smallest component is very close to zero, you might want to stop rather than slide, to avoid it feeling too slippery.
> 1 votes

# Answer
I realized I needed to cover more cases than my question initially asked for, so this is the approach I used instead of the accepted answer (which did cover the initial cases).

1. Create a check function to tell whether a cell can move to a neighbouring cell

a) If the cell is a direct neighbour in a cross on either the X or Y axis, return whether that cell is open

b) If the cell is in a diagonal, also check that the neighbouring cell of *either* of its components is open
2. Test the following cases, in order of priority. As soon as one move is allowed, take it and abort.

1. Move in the exact direction
    2. Move in direction of the largest component
    3. Move in direction of the smallest component
    4. Move in direction of the largest component with the reverse of the smallest component
    5. Move in direction of the smallest component with the reverse the largest component
    6. Move in direction of the reverse of the smallest component
    7. Move in direction of the reverse of the largest component
    8. Move in the reverse direction
3. If no case allowed a movement, fail to move

Steps 2.4 to 2.8 are optional -- it depends how permissive you want the algorithm to be. I personally only kept 2.4 and 2.5, in the end.

My specific implementation looks like this:

        private bool CanMove(Vector2 p, Vector2 q)
        {
            //var distance = Vector2.Distance(p, q);
            //
            //if (distance > 1.01)
            //{
            //  throw new ArgumentException($"Points must be up to 1 unit apart ({distance})");
            //}

            var pi = GetPixel(p);
            var qi = GetPixel(q);

            // If the destination isn't open, then we can't move to it.
            if (!IsOpen(qi))
            {
                return false;
            }

            var delta = qi - pi;

            // If we're moving in a cross (no diagonal),
            // then we only need to check if the destination
            // is open, no need for further checks.
            if (delta.x == 0 || delta.y == 0)
            {
                return true;
            }

            // If we're moving in diagonal, we also need to check if
            // either side path leading to it is open.
            var dx = pi + new Vector2Int(delta.x, 0);
            var dy = pi + new Vector2Int(0, delta.y);

            return IsOpen(dx) || IsOpen(dy);
        }

        private bool TryMove2(Vector2 source, Vector2 target, ref float remainingDistance, out Vector2 destination, out bool succeeded)
        {
            var difference = target - source;
            var distance = difference.magnitude;

            if (distance == 0)
            {
                //Debug.Log("No movement");
                destination = source;
                succeeded = true;
                return false;
            }

            var direction = difference.normalized;

            var continueOnSuccess = remainingDistance > 1;

            if (distance > 1)
            {
                distance = 1;
            }
            else if (distance > remainingDistance)
            {
                distance = remainingDistance;
            }

            // Try possibilities in this order:
            // 1. Move in exact direction
            // 2. Move in direction of largest component
            // 3. Move in direction of smallest component
            // 4. Move in direction of largest component with reverse smallest component
            // 5. Move in direction of smallest component with reverse largest component
            // 6. Move in direction of reverse smallest component
            // 7. Move in direction of reverse largest component
            // 8. Move in reverse direction

            var xComponent = new Vector2(Mathf.Sign(direction.x), 0);
            var yComponent = new Vector2(0, Mathf.Sign(direction.y));

            Vector2 largestComponentDirection;
            Vector2 smallestComponentDirection;
            Vector2 largestReverseSmallestDirection;
            Vector2 smallestReverseLargestDirection;
            Vector2 reverseSmallestDirection;
            Vector2 reverseLargestDirection;

            if (Mathf.Abs(direction.x) > Mathf.Abs(direction.y))
            {
                largestComponentDirection = xComponent;
                smallestComponentDirection = yComponent;
                largestReverseSmallestDirection = xComponent - yComponent;
                smallestReverseLargestDirection = yComponent - xComponent;
                reverseSmallestDirection = -yComponent;
                reverseLargestDirection = -xComponent;
            }
            else
            {
                largestComponentDirection = yComponent;
                smallestComponentDirection = xComponent;
                largestReverseSmallestDirection = yComponent - xComponent;
                smallestReverseLargestDirection = xComponent - yComponent;
                reverseSmallestDirection = -xComponent;
                reverseLargestDirection = -yComponent;
            }

            var exactAttempt = source + direction * distance;
            var largestComponentAttempt = source + largestComponentDirection * distance;
            var smallestComponentAttempt = source + smallestComponentDirection * distance;
            var largestReverseSmallestAttempt = source + largestReverseSmallestDirection * distance;
            var smallestReverseLargestAttempt = source + smallestReverseLargestDirection * distance;
            var reverseSmallestAttempt = source + reverseSmallestDirection * distance;
            var reverseLargestAttempt = source + reverseLargestDirection * distance;
            var reverseAttempt = source - direction * distance;

            if (CanMove(source, exactAttempt))
            {
                destination = exactAttempt;
            }
            else if (CanMove(source, largestComponentAttempt))
            {
                destination = largestComponentAttempt;
            }
            else if (CanMove(source, smallestComponentAttempt))
            {
                destination = smallestComponentAttempt;
            }
            else if (CanMove(source, largestReverseSmallestAttempt))
            {
                destination = largestReverseSmallestAttempt;
            }
            else if (CanMove(source, smallestReverseLargestAttempt))
            {
                destination = smallestReverseLargestAttempt;
            }
            //else if (CanMove(source, reverseSmallestAttempt))
            //{
            //  destination = reverseSmallestAttempt;
            //}
            //else if (CanMove(source, reverseLargestAttempt))
            //{
            //  destination = reverseLargestAttempt;
            //}
            //else if (CanMove(source, reverseAttempt))
            //{
            //  destination = reverseAttempt;
            //}
            else
            {
                succeeded = false;
                remainingDistance = 0;
                destination = source;
                return false;
            }

            succeeded = true;
            remainingDistance -= distance;
            return continueOnSuccess;
        }
```

> 0 votes

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


# Question
Title: Class Not Found Exception on Class.forName()
I am having this exception on title. I have been following a LibGDX programming PDF, everything was working perfectly and then this code have been implemented, and it isnt working anymore. I should add that Rock and Starfish are classes on my project, and there is no typo on class names

Edit: Here is the photo of my project, and I was indeed wrong for not putting the whole path to the class I wanted. Now "book.ep3.Rock" seems to work, but strangely Starfish is now having an exception.

Caught message:

```
    java.lang.ClassNotFoundException: Starfish
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)
    at book.ep3.BaseActor.getList(BaseActor.java:161)
    at book.ep3.BaseActor.count(BaseActor.java:174)
    at book.ep3.StarfishCollector.update(StarfishCollector.java:43)
    at book.ep3.GameBeta.render(GameBeta.java:22)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:233)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:128)
Exception in thread "LWJGL Application" java.lang.NullPointerException
    at book.ep3.BaseActor.getList(BaseActor.java:167)
    at book.ep3.BaseActor.count(BaseActor.java:174)
    at book.ep3.StarfishCollector.update(StarfishCollector.java:43)
    at book.ep3.GameBeta.render(GameBeta.java:22)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:233)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:128)

```

Starfish Class:

```
package book.ep3;

import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.Action;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;

public class Starfish extends BaseActor
{

    boolean collected;

    public Starfish(float x, float y, Stage s)
    {
        super(x,y,s);
       loadTexture("starfish.png");
       Action spin = Actions.rotateBy(30, 1);
       this.addAction( Actions.forever(spin) );
       setBoundaryPolygon(8);

       collected = false;

    }

    public boolean isCollected() {
        return collected;
    }

    public void collect() {
        collected = true;
        clearActions();
        addAction(Actions.fadeOut(1));
        addAction(Actions.after(Actions.removeActor()));
    }
}

```

Main class code:

```
public class StarfishCollector extends GameBeta {
private Turtle turtle;
private boolean win;

public void initialize() {
    BaseActor ocean = new BaseActor(0, 0, mainStage);
    ocean.loadTexture("water.jpg");
    ocean.setSize(800, 600);
    new Starfish(400, 400, mainStage);
    new Starfish(500, 100, mainStage);
    new Starfish(100, 450, mainStage);
    new Starfish(200, 250, mainStage);
    new Rock(200, 150, mainStage);
    new Rock(100, 300, mainStage);
    new Rock(300, 350, mainStage);
    new Rock(450, 200, mainStage);

    turtle = new Turtle(20, 20, mainStage);

    win = false;
}

public void update(float dt) {
    for (BaseActor rockActor : BaseActor.getList(mainStage, "book.ep3.Rock"))
        turtle.preventOverlap(rockActor);

    for (BaseActor starfishActor : BaseActor.getList(mainStage, "book.ep3.Starfish")) {
        Starfish starfish = (Starfish) starfishActor;
        if (turtle.overlaps(starfish) && !starfish.collected) {
            starfish.collected = true;
            starfish.clearActions();
            starfish.addAction(Actions.fadeOut(1));
            starfish.addAction(Actions.after(Actions.removeActor()));
            Whirlpool whirl = new Whirlpool(0, 0, mainStage);
            whirl.centerAtActor(starfish);
            whirl.setOpacity(0.25f);
        }
    }
    if (BaseActor.count(mainStage, "Starfish") == 0 && !win) {
        win = true;
        BaseActor youWinMessage = new BaseActor(0, 0, mainStage);
        youWinMessage.loadTexture("you-win.png");
        youWinMessage.centerAtPosition(400, 300);
        youWinMessage.setOpacity(0);
        youWinMessage.addAction(Actions.delay(1));
        youWinMessage.addAction(Actions.after(Actions.fadeIn(1)));
    }
}
}

```

Get List function code (this is inside the BaseActor class):

```
public static ArrayList<BaseActor> getList(Stage stage, String className) {
    ArrayList<BaseActor> list = new ArrayList<BaseActor>();
    Class theClass = null;
    try {
        theClass = Class.forName(className);
    } catch (Exception error) {     //THIS IS WHERE THE EXCEPTION IS HAPPENING
        error.printStackTrace();
    }

    for (Actor a : stage.getActors()) {
        if (theClass.isInstance(a))
            list.add((BaseActor) a);
    }
    return list;
}

public static int count(Stage stage, String className) {
    return getList(stage, className).size();
}

```

So the mainStage and Class names are indeed correct, and the rest of the code is copied from the book. Also, if I comment my For loop where its trying to find the Rock class, It will have the same Exception on the next For loop, while searching for the Starfish class. Any help? Thank you so much!

# Answer
Why use the class name for this? Just pass the class itself:

```
public static <T> ArrayList<T> getList(Stage stage, Class<T> type) {
    List<T> list = new ArrayList<T>();
    for (Actor a : stage.getActors()) {
        if (type.isInstance(a))
            list.add((T) a);
    }
    return list;
}

```

Usage: `BaseActor.getList(mainStage, Starfish.class);`
> 1 votes

# Answer
Solved, for some reason my For each loop was getting out of bounds for the Starfish class, so I did a little null check and it worked out fine! The problem in the 5th loop of the Starfish searching, where It resulted in null
> 0 votes

# Answer
Note the parameter String `Rock` and the parameter String `Starfish`

on Android Studio you can just list the package then the class on other IDE you will have to provide full PATH, that is `C:/Games/StarfishCollector/Rock`

```
public void update(float dt){

    for(BaseActor rockActor : BaseActor.getList(mainStage, "com.starfishcollector3.Rock")){
        turtle.preventOverlap(rockActor);
    }

    for(BaseActor starfishActor : BaseActor.getList(mainStage, "com.starfishcollector3.Starfish")){
        Starfish starfish = (Starfish) starfishActor;

        if(turtle.overlaps(starfish) &&  !starfish.collected){
            starfish.collected = true;

            starfish.clearActions();
            starfish.addAction(Actions.fadeOut(1));
            starfish.addAction(Actions.after(Actions.removeActor()));

            Whirlpool whirl = new Whirlpool(0 , 0, mainStage);
            whirl.centerAtActor(starfish);
            whirl.setOpacity(0.25f);
        }
    }

    if(BaseActor.count(mainStage, "com.starfishcollector3.Starfish") == 0 && !win){
        win = true;
        BaseActor youWinMessage = new BaseActor(0, 0, mainStage);
        youWinMessage.loadTexture("you-win.png");
        youWinMessage.centerAtPosition(400, 300);
        youWinMessage.setOpacity(0);
        youWinMessage.addAction(Actions.delay(1));
        youWinMessage.addAction(Actions.after(Actions.fadeIn(1)));
    }
}

```
> 0 votes

---
Tags: java, libgdx
---


# Question
Title: OpenGL/C++ Rotate relative to shooting gun
I'm trying to make a 2D game where I have a gun that i use to shot things in the direction of the mouse resulting in an angle that I can get. I have some problems with the trajectory of the bullet because I don't know what to put in the Transpose and Rotate function. For example Point 1 has x = 20 and y = 30. I want to shot in the direction of Point 2 at x = 50 and y = 50. To do that i get an angle 't' which I use in the rotate function. But the reality is that I get the animation that I presented in the photo. I increase the x coord of the bullet because I can only shot in right side so only positive x. The bullet is moving on the 0x axis rotated at an angle t but at the same y as the gun.

What I want is something like

I'm sorry if this is a duplicate I couldn't find a solution to my problem. I think the resulting Matrix should have the form : Translate * Rotate * Translate but I can't find the right x and y.

Sorry if this seemed dumb and thank you for your time!

# Answer
> 0 votes
Let us say you are shooting from `p1` with coordinates `p1.x` and `p1.y`. And you want to shoot in direction to `p2` with coordinates `p2.x` and `p2.y`.

When the bullet is created, you will place it in `p1`. That would be something like this:

```
bullet.position = p1;

```

---

We need to figure out how it should move.

Let us call `d` the vector that goes from `p1` to `p2`:

```
d = p2 - p1
d = (p2.x - p1.x, p2.y - p1.y)

```

*If you want the angle `t`, it will be `t = atan2(d.y, d.x)` or `t = atan2(p2.y - p1.y, p2.x - p1.x)` if you prefer. You don't need the angle.*

Let us say that the bullet should advance `speed` distance per unit for time. Then your velocity is:

```
velocity = d * speed/length(d)

```

That `velocity` describes the motion of the bullet. *I'm assuming no gravity, as it was not mentioned in the question. I'm guessing this is a top down game.*

I suggest to store it in the bullet:

```
bullet.position = p1;

var d = p2 - p1;
bullet.velocity = d * speed/length(d);

```

Each game cycle you will move the bullet by `velocity` according to the number of units of times elapsed. That would be something like this:

```
bullet.position = bullet.position + (bullet.velocity * delta);

```

where `delta` is the elapsed time in the same units used for `l`. For example `l` is pixels per millisecond and `delta` is milliseconds. If you are working with different units you need a unit conversion. For example if `l` is pixels per second, and `delta` is milliseconds, you need to divide delta by 1000 so it is in seconds.

---

The vector operations used:

* Vector addition: `v1 + v2 = (v1.x + v2.x, v1.y + v2.y)`
* Vector subtraction: `v1 - v2 = (v1.x - v2.x, v1.y - v2.y)`
* Scalar product: `v * s = (v.x * s, v.y * s)`
* Length: `length(v) = sqrt(v.x * v.x + v.y * v.y)`

---

Alright, let us suppose you are placing a model to represent the bullet, and you want to be able to apply a transformation to the model.

We want to have the orientation stored so we have use it to orient the model.

```
bullet.position = p1;

var d = p2 - p1;
bullet.direction = d * 1/length(d);
bullet.velocity = bullet.direction * speed;

```

Let us see how the rotation matrix transformation looks like:

```
+-                  -+
|  cos(θ)    -sin(θ) |
|                    |
|  sin(θ)    cos(θ)  |
+-                  -+

```

We already have those values:

```
+-                                          -+
|  bullet.direction.x    -bullet.direction.y |
|                                            |
|  bullet.direction.y    bullet.direction.x  |
+-                                          -+

```

And, of course, you would make your translation matrix from `bullet.position`.

*There is no need to call any trigonometric function. No need to waste CPU cycles on them or introduce floating point errors due their computation.*

---
Tags: opengl, c++, rotate
---


# Question
Title: How do I save my Highest Time for each level on playerprefs?
So I want to make hill climb wanna be game but have an issue with saving `bestTime` each level, the point is I want to save the best time for each level to playerprefs also save it on text value in main menu like the image.

here my timer script :

```
 public void TimerSystemOn()
{
    if (timerIsRunning)
    {
        if (timeRemaining > 0)
        {
            timeRemaining -= Time.deltaTime;
            DisplayTime(timeRemaining);
        }
        else
        {
            if (timeRemaining <= 0)
            {
                Debug.Log("Time has run out!");
                timeRemaining = 0;
                timerIsRunning = false;

                if (!timerIsRunning)
                {
                    TimeOut();
                }
            }
        }
    }

    if (!timerIsRunning)
    {
        ReachFinishLine();
        DisplayTime(timeRemaining);

    }
}

void DisplayTime(float timeToDisplay)
{
    timeToDisplay += 1;

    float minutes = Mathf.FloorToInt(timeToDisplay / 60);
    float seconds = Mathf.FloorToInt(timeToDisplay % 60);

    PlayerPrefs.SetFloat("Minutes", minutes);
    PlayerPrefs.SetFloat("Seconds", seconds);
    timeText.text = string.Format("{0:00}:{1:00}", minutes, seconds);

    float highscoreMins = PlayerPrefs.GetFloat("Minutes");
    float highscoreSec = PlayerPrefs.GetFloat("Seconds");

    if (minutes > highscoreMins || seconds > highscoreSec)
    {
        PlayerPrefs.SetFloat("Minutes", minutes);
        PlayerPrefs.SetFloat("Seconds", seconds);
    }
    Debug.Log("HighscoreSec : " + highscoreSec);
}

```

that's my current script to save the bestTime. and this script call on the game, when died the timer value or `time remaining = 0` and when the car reached the destiny `timer will be stopped but the value saved to best time` I confused here about saving that value and save it on each level

I want to save it in the bottom text.

# Answer
You are basically always saving the time as highscore. The comments are explaining why your current code is not doing what it should.

```
//Here you save already to your playerPref
PlayerPrefs.SetFloat("Minutes", minutes);
PlayerPrefs.SetFloat("Seconds", seconds);
timeText.text = string.Format("{0:00}:{1:00}", minutes, seconds);
//Here you load the same time that you just saved
float highscoreMins = PlayerPrefs.GetFloat("Minutes");
float highscoreSec = PlayerPrefs.GetFloat("Seconds");
//This condition does nothing since the time is the same value and we saved it already
if (minutes > highscoreMins || seconds > highscoreSec)
{
    PlayerPrefs.SetFloat("Minutes", minutes);
    PlayerPrefs.SetFloat("Seconds", seconds);
}

```

If you need a highscore per level, you might add a level prefix. And you can always save the time in total seconds since you even have the time already in seconds. For display purpose you convert it, for saving it is not needed. Keep it simple with one value.

You should as well not mix saving and displaying. Make an extra saving function that can determinate handles saving your highscore.

**(Your display method should as well not handle the increase of time, this is another part you should rework)**

```
void DisplayTime(float timeToDisplay){
     timeToDisplay += 1;
     float minutes = Mathf.FloorToInt(timeToDisplay / 60);
     float seconds = Mathf.FloorToInt(timeToDisplay % 60);
     timeText.text = string.Format("{0:00}:{1:00}", minutes, seconds);
}

void SaveIfHighScore(float time, string level){
     float currentHighscore = PlayerPrefs.GetFloat("Time_" + level);
     if (time > currentHighscore) {
         PlayerPrefs.SetFloat("Time_" + level, time)
     }
}

```

This assumes that highscore means the longer time, the better it is. If you need it to be fastest time, you need to switch the \>.
> 0 votes

---
Tags: unity, timer, savegame
---


# Question
Title: How to calculate trajectory on a planet with drag factor
I'm curious what is the valid calculation of a projectile trajectory in case when:

* surface is not flat but spherical like a planet
* drag is enabled (for example 0.1)
* and we are in 3D

I've found calculations where either the drag or the spherical surface factor was missing. I assume in each simulation step I have to recalculate the direction of the gravity which is the direction between the current position of the projectile and center of the planet.

I've tried to reuse the SimulateArc method in one of these answers: https://stackoverflow.com/questions/61125224/2d-projectile-trajectory-predictionunity-2d

I changed Vector2 to Vector3 and added a gravity direction recalculation on the loop after the new position is calculated. But Drag factor is missing yet. Is it a good approach to solve this issue? If not how should I calculate the trajectory also with the Drag factor?

```
private void CalculateTrajectory()
{
    float simulateForDuration = 5f;//simulate for 5 secs in the furture
    float simulationStep = 0.1f;//Will add a point every 0.1 secs.

    int steps = (int)(simulateForDuration/simulationStep);//50 in this example
    Vector3 calculatedPosition;
    Vector3 directionVector = unit.CannonDirection;
    Vector3 launchPosition = unit.StartPosition;
    float launchSpeed = unit.ShootPower;

    for(int i = 0; i < steps; ++i)
    {
        calculatedPosition = launchPosition + ( directionVector * (launchSpeed * i * simulationStep));
        //Calculate gravity
        Vector3 gravity = (planet.transform.position - transform.position).normalized * gravityConst;
        calculatedPosition += gravity * ( i * simulationStep) *  ( i * simulationStep);

        Gizmos.DrawSphere(calculatedPosition, 0.5f);
    }

}

```

**EDIT 1:** I tried to code the formula provided by Sacha but it seems it is not perfect yet (only on flat surface and without drag for now, if it works then I will add the drag factor and a sphere surface):

```
private void CalculateTrajectory()
{
    float simulateForDuration = 5f;
    float simulationStep = 0.1f;

    int steps = (int)(simulateForDuration / simulationStep);
    float mass = 0.5f;
    Vector3 previousPosition = transform.position;
    Vector3 previousVelocity = transform.forward.normalized * 5;
    Vector3 gravity = Physics.gravity;

    for (int i = 0; i < steps; ++i)
    {
        Vector3 acceleration = (previousVelocity + gravity) / mass;
        Vector3 newVelocity = previousVelocity + acceleration * simulationStep;
        Vector3 newPosition = previousPosition + newVelocity * simulationStep;

        Gizmos.DrawSphere(newPosition, 0.2f);

        previousPosition = newPosition;
        previousVelocity = newVelocity;
    }

}

```

Here is my projectile creation code:

```
GameObject clone = GameObject.Instantiate(sphere);
clone.transform.position = transform.position;
clone.transform.forward = transform.forward;

Rigidbody rb = clone.GetComponent<Rigidbody>();
rb.velocity = clone.transform.forward.normalized * 5f;

```

What did I miss?

**EDIT 2:** I tried another approach:

```
float simulateForDuration = 5f;
float simulationStep = 0.02f;

int steps = (int)(simulateForDuration / simulationStep);
Vector3 initialVelocity = transform.forward.normalized * 5f;

for (int i = 0; i < steps; ++i)
{
    Vector3 pos = new Vector3(
        transform.position.x + initialVelocity.x * (i * simulationStep),
        transform.position.y + initialVelocity.y * (i * simulationStep) - 0.5f * -Physics.gravity.y * Mathf.Pow(i * simulationStep, 2),
        transform.position.z + initialVelocity.z * (i * simulationStep));

    Gizmos.DrawSphere(pos, 0.05f);
}

```

Result:

This seems fine when I have only gravity on axis Y. We can say that the first version is almost fine, but I cannot figure out what is missing.

**EDIT Final:** Based on Sacha updated answer regarding P = m * g the calculation is fine. I also had to update the AddForce method on the projectile itself because I added 9.81 * normalizedDirectionToTheCenter for the projectile as gravity. Now it is 9.81 * projectileMass * normalizedDirectionToTheCenter .

Here is the full code:

```
private void CalculateTrajectory()
{
    float simulateForDuration = 10f;
    float simulationStep = 0.02f;

    int steps = (int)(simulateForDuration / simulationStep);
    float mass = r.mass; // Mass of the projectile.

    Vector3 previousPosition = transform.position;
    Vector3 previousVelocity = transform.forward.normalized * power;

    for (int i = 1; i < steps; ++i)
    {
        Vector3 directionToCenter = (planet.position - previousPosition).normalized;
        Vector3 gravity = directionToCenter * 9.81f;

        // Separated vectors to understand better.
        Vector3 force = gravity * mass;
        Vector3 acceleration = force / mass;
        Vector3 newVelocity = previousVelocity + acceleration * simulationStep;
        Vector3 newPosition = previousPosition + newVelocity * simulationStep;

        Gizmos.DrawSphere(newPosition, 0.05f);

        previousPosition = newPosition;
        previousVelocity = newVelocity;
    }
}

```

Thanks Sacha!

# Answer
Your approach has good grounds, but there are mistakes in your code.

A little theory first: Your simulation needs to use the second law of Newton which gives you the acceleration of the projectile:
\\$\vec{F} = m.\vec{a}\\$ where \\$\vec{F}\\$ is the sum of the forces applied to your projectile.
For that you need to add all the forces that act on your projectile: its weight (due to gravity) and air drag.

**Drag**
The drag can be computed as \\$A.V^2\\$ where V is the projectile's speed and A is a constant (your drag factor). Remember that it applies in the opposite direction of the speed vector.
(For reference, I've covered computation of air drag in a simplified model in the following answer: Simplified aerodynamics for 3D airplane )

**Weight**
The weight is given by \\$\vec{P} = m.\vec{g}\\$.
\\$\vec{g}\\$ is the gravity vector and for a good enough approximation, points from your projectile to the center on Earth. As you consider the curvature of Earth, you have to update this vector at each step.

**Position**
Acceleration being the derivative of speed, and speed being the derivative of position, you can update now update both:

* \\$\vec{V\_{n+1}} = \vec{V\_n} + \vec{a\_{n+1}}.\Delta t\\$
* \\$\vec{r\_{n+1}} = \vec{r\_n} + \vec{V\_{n+1}}.\Delta t\\$ (\\$\vec{r}\\$ is the position vector of your projectile)

In your code, you need variables to memorize the projectile speed and position (Vector3). Those variables will be incrementaly updated, once per loop. The initial conditions (launchPosition and launchSpeed) should not appear within the loop body.
> 2 votes

---
Tags: projectile-physics, sphere, trajectory, movement-prediction
---


# Question
Title: Efficient collision detection - tile based HTML5/Javascript game
I'm building a basic RPG game and I'm looking at collisions/pickups etc now.

It's tile based and I'm using HTML5 and Javascript.

I use a 2D array to create my tilemap.

I'm currently using a switch statement for whatever key has been pressed to move the player.

I have if statements to stop the player going off the edge of the map and viewport. If the player is about to land on a tile with tileID 3 then the player stops.

Here is the statement:

```
canvas.addEventListener('keydown', function(e) {
    console.log(e);
    var key = null;
    switch (e.which) {
        case 37:
            // Left
            if (playerX > 0) {
                playerX--;
            }
            if(board[playerX][playerY] == 3){
                playerX++;
            }
            break;
        case 38:
            // Up
            if (playerY > 0) playerY--;
            if(board[playerX][playerY] == 3){
                playerY++;
            }
            break;
        case 39:
            // Right
            if (playerX < worldWidth) {
                playerX++;
            }
            if(board[playerX][playerY] == 3){
                playerX--;
            }
            break;
        case 40:
            // Down
            if (playerY < worldHeight) playerY++;
            if(board[playerX][playerY] == 3){
                playerY--;
            }
            break;
    }

    viewX = playerX - Math.floor(0.5 * viewWidth);
    if (viewX < 0) viewX = 0;
    if (viewX+viewWidth > worldWidth) viewX = worldWidth - viewWidth;

    viewY = playerY - Math.floor(0.5 * viewHeight);
    if (viewY < 0) viewY = 0;
    if (viewY+viewHeight > worldHeight) viewY = worldHeight - viewHeight;

}, false);

```

**Is there a more efficient way of handling collisions, than loads of if statements for each key?**

The reason I ask is because I plan on having many items that the player will need to be able to pickup or not walk through like walls cliffs etc.

# Answer
> 5 votes
Collisions need to be detected and resolved *after* you retrieve the user input and apply all the transformations to the object.

So, for instance, your board would have a bounding box equal to the board width and height. To check for a collision with the outer bounds you would ask if your player object is outside the board's bounding box.

If so, then you need to apply transformations to the object's x and y coordinates so that it is inside the box.

The main conceptual point, I suppose, is that you shouldn't be checking for collisions as a precondition for user input. Instead, you should be checking for collisions as a result of user input, and then applying transformations to resolve it.

# Answer
> 0 votes
I usually have an array of solid tiles and a function to check collisions against them.

```
function inArray(needle, haystack) {
    for (var key in haystack) {
        if (haystack[key] == needle) {
            return true;
        }
    }
    return false;
}

var solidTiles = [3, 6, 14];

function (isSolidTile(x, y) { //x and y are pixel coordinates, not tile coordinates
    var tileX = Math.floor(x / tileWidth);
    var tileY = Math.floor(y / tileHeight);
    if (inArray(board[tileX][tileY], solidTiles)) {
        return true;
    }
    return false
}

```

With this function you could get the coordinates of the player's new location before moving him, check if those coordinates are a solid tile, and then handle it however you want (ie. move the player to the edge of the tile). You could get the coordinates of the tile the player is moving to with something like `var newX = player.x + player.xVelocity` and `var newY = player.y + player.yVelocity`.

For colliding with items or other sprites (which I assume are not tiles, but other entities with their own pixel coordinates) you can use a function like:

```
function collides(sprite1, sprite2) {
    return a.x < b.x + b.width &&
    a.x + a.width > b.x &&
    a.y < b.y + b.height &&
    a.y + a.height > b.y;
}

//example
if (collides(player, cocoaPuff)) {
    player.cuckoo = true;
}

```

# Answer
> 0 votes
Given the x/y of the player and the width/height you can get the position of all four corners, and then to translate to a point on the array do `Math.floor((x or y)/tileSize)` then you can do

```
for (let i = topCorner; i < bottomCorner; i++) { //topCorner is the array offset of the top edge, bottomCorner is the offset for the bottom edge.
  for (let j = leftCorner; j < rightCorner; j++) { //leftCorner is the offset for the left corner, rightCorner is the offset for the right corner
    if (tileMap[i] !== undefined && tileMap[i][j] == 0) { //tileMap is the array, check for undefined first to avoid errors.
      //add to x and y
    }
  }
}

```

---
Tags: collision-detection, javascript, html5, tiles
---


# Question
Title: How much of a game can be protected by law?
I want to remake an old multiplayer game in commercial way and I wonder how different my game has to be not to violate some IP rights. I know so far that name and logo are registered trademarks of the company that still exists so I cannot use it. But ...

How about other things such as maps or mechanics of the game? Can this be somehow protected?

If I make a new map that will NOT use a single asset from that old map (like textures, sounds or models) but will mimic the old map as much as possible, can this be problem from legal point of view? By mimic I mean for example putting tree in excactly same position as on the old map, but the tree would be completely different model; buildings would have same plans but all the models and walls textures would be different.

Also this game has some certain amount of features (players classes, mission scenarios, types of weapons) that are being used in other games commonly so this cannot be patented. But how about given set of these features? For example having given types of classes connected with given missions scnarios and types of weapons can be protected even though seperately they cannot be??? Is that possible?

# Answer
Scrabble is a good case study for what is allowed, because there are(were) many clones of it, and Hasbro defends it litigiously.

* The name of the game or logo, or anything close enough that someone might confuse them, is protected by the trademark
* The rulebook wording is copyrighted. So is the artwork on the board/box
* Some of the game design can be covered by copyright. Notably the board layout, letter scoring and letter distributions in clones have been changed after being challenged.
* The game mechanics are not protected

Reference: https://en.wikipedia.org/wiki/Lexulous

Tldr; don't copy the level design layout exactly, it *is* covered by copyright, same as the Scrabble board layout.
> 0 votes

# Answer
I'm not a legal expert so obviously don't just take my word on it. If you really are worried, it's best to consult a lawyer.

However, from my knowledge, you can not claim any big idea, method, system, etc. For example, I can create a battle royal game and not have PUBG, Fortnite, etc copyright me as that is a game genre. I can also create a power up system, and not have pac man sue me. I can also have sniper rifles, handguns, swords, etc, as those are general types of weapons and can not be copyrighted. However, I have heard that games change the name and model of specific guns to avoid lawsuits from gun manufactures.

Copyright only protects specific artistic, literary, and musical aspects, such as specific sound effects and music, specific names and in game descriptions, dialogues, etc.

I'd be careful and just move the stuff around a little, as map layout *may* count as artistic expression, but again, I'm not a lawyer, and I may not even be under the same legal system and laws as you.

Here are some sources that may help.
> 1 votes

---
Tags: legal, copyright
---


# Question
Title: How to tell which face of a cube is most visible to the camera?
Imagine a camera that shows a randomly rotated cube at an arbitrary position: The cube's pivot is in the center of the cube. This way its six faces could be referred as positive/negative X, Y or Z.

How can you tell which of the faces is most visible to the camera? What's the math to calculate this? Your help is very much appreciated.

Thank you!

# Answer
> 3 votes
```
public enum CubeFace {
    Left,
    Bottom,
    Back,
    Right,
    Top,
    Front
}

public static GetFaceToward(Transform cube, Vector3 observerPosition) {
    var toObserver = cube.InverseTransformPoint(observerPosition);

    var absolute = new Vector3(
                      Mathf.Abs(toObserver.x),
                      Mathf.Abs(toObserver.y),
                      Mathf.Abs(toObserver.z),
                   );

    if (absolute.x >= absolute.y) {
        if (absolute.x >= absolute.z) {
            return toObserver.x > 0 ? CubeFace.Right : CubeFace.Left;
        } else {
            return toObserver.z > 0 ? CubeFace.Front : CubeFace.Back;
        }
    } else if (absolute.y >= absolute.z) {
        return toObserver.y > 0 ? CubeFace.Top : CubeFace.Bottom;
    } else {
        return toObserver.z > 0 ? CubeFace.Front : CubeFace.Back;
    }
}

```

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


# Question
Title: Online Multiplayer - cheating w/ delta time movement
I'm making a multiplayer game with basic linear movement and interpolation. I've read gabriel's article about client-side prediction and server reconciliation and have tried applying it to my own. My server is supposed to be authoritative, but I am worried clients can still exploit the system.

The system works like this:

1. the client sends timestamped input to the server at 60hz
2. the server runs at 30hz. Each tick it applies all the input since last tick and uses a time delta calculated from the client side input packets to determine movement (e.g. entity.x += message.delta * speed). The server then sends a timestamped state back to all clients.
3. the client receives a timed state from the server and applies the "authoritative" positions.

My concern is with step #2. Because player movement relies on the client's delta time, I'm afraid they can cheat by sending a "fake delta time" to the server and additionaly spam input messages quicker to make them move faster in-game. If I remove the delta time altogether, the game will appear "jumpy". How can I resolve this issue?

# Answer
If you are relying on client information to calculate position, YES this can be cheated. =(

Since you didn't sent information about what kind of game is this and you didn't mention fixed timestep, I'm assuming you are doing some kind of FPS that doesn't require that every client, runs the same frame, at the same time.

I think a good solution is to use PING to sincronize position between server and client. I'll explain:

* Server needs to run without waiting for clients, he is authoritative.
* If needed, server can implement a controlled delay of 1, 2 or 3 frames (at 60fps, 1 frame = 16ms).
* Client should PING server to check latency between him and server.
* Client calculate his current position + N frames ahead using last control input. So he will predict his position and update locally.
* Client also needs to calculate other players position using same method (according to his own ping, no to them).

If latency is low (\<100ms) and your players are not moving too fast, this method works great. With latency \> 250ms or player is really fast, your prediction starts to jump from place to place.

Another solution would be to calculate at server the maximum distance this client can move from frame to frame, if it's higher than this, apply some anti-cheat measure.

Anyway, need more information!
> 2 votes

# Answer
If you treat each move message as a move unit, you don't need delta in this message at all. Whenever server receives a move message, apply it with a hardcoded delta (say 15ms in your case).

However this is still vulnerable to message "spam" hack. Such that a client can send double or triple the amount of move messages. If the server unconditionally handles them all, the player will get 2x/3x speed.

Server side check like maximum location delta involves RTT measurement. Eg, `max_input_message = (RTT/2 + 1000.0) / SERVER_FRAME` When RTT is high this check is very loose, and a cheater can try to manipulate the RTT ping to yield higher RTT.

Maybe you can try to model your message as full state snapshot, while you are still able to adapt the prediction/reconciliation/interpolation demonstrated in Gabriel's tutorial.
> 0 votes

---
Tags: javascript, networking, multiplayer
---


# Question
Title: Crusader Kings 2: How to extract character religion from saved game?
I am trying to parse and interpret the Crusader Kings 2 save file. I run into problem when trying to extract character religion.

```
3185293=
{
    bn="Umar"
    b_d="1543.12.21"
    fat=3160797
    mot=3160268
    att={7 3 4 3 3}
    tr={195 }
    rel="norse_pagan_reformed"
    cul="andalusian_arabic"
    dnt=1000128972
    dna="xvfudvhjgxg"
    prp="ojcf0k00000000000000000000000000000000"
    fer=0.400
    health=5.100
    # ... shortened ...
}

```

In many cases, trait **rel** is missing. In the documentation, I found reference that the trait *does not appear if government make it unnecessary*. Can you please advise how exactly to extract character religion if the trait is missing?

# Answer
The doc you linked seems to have the answer: look it up from the government.

> rel # religion – does not appear if government make it unnecessary,
> e.g. if muslim\_government and religion is sunni

So, you can make a table of key-value pairs, matching each government type to its default religion. If the `rel` trait is missing, take the `gov` trait and use it to look up the corresponding default religion from your table to substitute for the elided trait.
> 0 votes

---
Tags: crusader-kings-2-modding
---


# Question
Title: What is the best way to approach a multi pass rendering system?
I am trying to code a new feature in my engine but I can't find a way to implement my idea, which is the next one. I am trying to get multi pass rendering with more than two passes.

I know how to do a two pass rendering pipeline for effects like blurring and shadow mapping, but my problem is that now I want to make an undefined number of passes without having to have that number of different functions (a different one for every pass).

Do you have any ideas about what could I do here? I have thought about doing some kind of function pointer that is called x amount of times, each time calling to a different function, but again, I don't know what is the best (or the easiest) approach. Would love to hear your ideas and comments. Thanks!

PS, I am using openGL if that is useful information.

# Answer
It is really hard to give a meaningful decision without in-depth knowledge of your game engine. I'll try to answer from what I know making my own game engine.

You could have many *renderer* (I call them painter in my engine) that are each associated with a *rendering step*. When you run your pipeline, you could simply call each steps manually, with things like binding framebuffers and texture between each fixed steps.

That would require you to setup the renderers so that the pipeline you choose for a particular scene will call the right one in each steps.

This keep you freedom to play with framebuffers but keep the rendering of object unaware of how they actually fit together.
> 0 votes

---
Tags: opengl, c++, graphics, graphics-programming
---


# Question
Title: Help with moving object to mouse position
I'm trying to make an object follow my cursor using raycasting. I'm creating the raycast each frame and checking the player's distance from the hit and whether or not the hit landed on an object tagged 'surface'. The code works fine with only one of those conditions, e.g. if I just check for the surface tag or just check the range, but when checking for both the object will only move to a few certain (apparently random) positions on the surface.

```
        if (Physics.Raycast(ray, out hit))
        {
                if (hit.transform.tag == "Surface" && Vector3.Distance(player.transform.position, hit.point) < range)
                {
                    obj.transform.Find("holo").gameObject.SetActive(true);
                    obj.transform.position = new Vector3(hit.point.x, hit.point.y + 0.5f, hit.point.z);
                }
            }

```

At first, I thought maybe the double condition was causing lag, but I have a powerful pc and I struggle to believe that two conditions in a frame are enough to create a noticeable loss in performance.

Video of the bug: https://youtu.be/mLug2ThX2hg , Full script just in case: https://pastebin.com/ruUXivsc

Any pointers would be greatly appreciated :)

# Answer
> 1 votes
I managed to fix this by placing the surfaces inside their own layer, then only casting to that layer. This removed the need for the tag condition.

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


# Question
Title: Refactoring a Unity script into two, and reading variables in one from the other
We got this `SelectionManager` Script from an Asset which allows us to select a building.

We wanted to track if the building is selected and then show a small menu above it. We managed to get it to work, but it was all in the `SC_SelectionManager` script and we wanted to separate it into two scripts.

So we wrote the `micromenuScript` which basicly just copied the working code. But we were not able to get the `isSelected` variable into the `micromenuScript`.

Can anyone please explain how to access a variable from one script in another?

We tried to get a reference to the selection manager script by calling `microMenuScript.Find("_SelectionManager")` as shown below, but got the following error:

> 'GameObject.Find(string)' cannot be accessed with an instance reference; qualify it with a type name instead.

I added both scripts.

`SC_SelectionManager`:

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

public class SC_SelectionManager : MonoBehaviour
{
    public Texture topLeftBorder;
    public Texture bottomLeftBorder;
    public Texture topRightBorder;
    public Texture bottomRightBorder;
    //public GameObject micromenu;
    public bool isSelected;

Texture2D _borderTexture;
Texture2D borderTexture
{
    get
    {
        if (_borderTexture == null)
        {
            _borderTexture = new Texture2D(1, 1);
            _borderTexture.SetPixel(0, 0, Color.white);
            _borderTexture.Apply();
        }

        return _borderTexture;
    }
}

bool selectionStarted = false;
Vector3 mousePosition1;

public static List<SC_Selectable> selectables = new List<SC_Selectable>();
List<int> selectedObjects = new List<int>();

void Start(){
  //micromenu.SetActive(false);
  isSelected = false;
}
// Update is called once per frame
void Update()
{
    // Begin selection
    if (Input.GetMouseButtonDown(0))
    {
        selectionStarted = true;
        mousePosition1 = Input.mousePosition;
    }
    // End selection
    if (Input.GetMouseButtonUp(0))
    {
        selectionStarted = false;
    }
    //Script für die Selection von Objecten
    if (selectionStarted)
    {
        // Detect which Objects are inside selection rectangle
        Camera camera = Camera.main;
        selectedObjects.Clear();
        //activeMenu(false);
        isSelected = false;
        Debug.Log("isSelected auf false gesetzt? =" + isSelected);
        for (int i = 0; i < selectables.Count; i++)
        {
            Bounds viewportBounds = GetViewportBounds(camera, mousePosition1, Input.mousePosition);
            if (viewportBounds.Contains(camera.WorldToViewportPoint(selectables[i].transform.position)))
            {
              selectedObjects.Add(i);
              //activeMenu(true);
              isSelected = true;
              Debug.Log("isSelected auf true gesetzt? =" + isSelected);
            }
        }
    }
}

/*private void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        selectedObjects.Add(0);
    }
}*/

void OnGUI()
{
    if (selectionStarted)
    {
        Rect rect = GetScreenRect(mousePosition1, Input.mousePosition);
        DrawScreenRectBorder(rect, 2, Color.cyan);
    }

    // Draw selection edges
    if(selectedObjects.Count > 0)
    {
        Camera camera = Camera.main;
        for (int i = 0; i < selectedObjects.Count; i++)
        {
            DrawSelectionIndicator(camera, selectables[selectedObjects[i]].GetObjectBounds());
        }
    }
}

void DrawScreenRectBorder(Rect rect, float thickness, Color color)
{
    // Top
    DrawBorderRect(new Rect(rect.xMin, rect.yMin, rect.width, thickness), color);
    // Left
    DrawBorderRect(new Rect(rect.xMin, rect.yMin, thickness, rect.height), color);
    // Right
    DrawBorderRect(new Rect(rect.xMax - thickness, rect.yMin, thickness, rect.height), color);
    // Bottom
    DrawBorderRect(new Rect(rect.xMin, rect.yMax - thickness, rect.width, thickness), color);
}

void DrawBorderRect(Rect rect, Color color)
{
    GUI.color = color;
    GUI.DrawTexture(rect, borderTexture);
    GUI.color = Color.white;
}

Rect GetScreenRect(Vector3 screenPosition1, Vector3 screenPosition2)
{
    // Move origin from bottom left to top left
    screenPosition1.y = Screen.height - screenPosition1.y;
    screenPosition2.y = Screen.height - screenPosition2.y;
    // Calculate corners
    var topLeft = Vector3.Min(screenPosition1, screenPosition2);
    var bottomRight = Vector3.Max(screenPosition1, screenPosition2);
    // Create Rect
    return Rect.MinMaxRect(topLeft.x, topLeft.y, bottomRight.x, bottomRight.y);
}

Bounds GetViewportBounds(Camera camera, Vector3 screenPosition1, Vector3 screenPosition2)
{
    Vector3 v1 = camera.ScreenToViewportPoint(screenPosition1);
    Vector3 v2 = camera.ScreenToViewportPoint(screenPosition2);
    Vector3 min = Vector3.Min(v1, v2);
    Vector3 max = Vector3.Max(v1, v2);
    min.z = camera.nearClipPlane;
    max.z = camera.farClipPlane;

    Bounds bounds = new Bounds();
    bounds.SetMinMax(min, max);
    return bounds;
}

void DrawSelectionIndicator(Camera camera, Bounds bounds)
{
    Vector3 boundPoint1 = bounds.min;
    Vector3 boundPoint2 = bounds.max;
    Vector3 boundPoint3 = new Vector3(boundPoint1.x, boundPoint1.y, boundPoint2.z);
    Vector3 boundPoint4 = new Vector3(boundPoint1.x, boundPoint2.y, boundPoint1.z);
    Vector3 boundPoint5 = new Vector3(boundPoint2.x, boundPoint1.y, boundPoint1.z);
    Vector3 boundPoint6 = new Vector3(boundPoint1.x, boundPoint2.y, boundPoint2.z);
    Vector3 boundPoint7 = new Vector3(boundPoint2.x, boundPoint1.y, boundPoint2.z);
    Vector3 boundPoint8 = new Vector3(boundPoint2.x, boundPoint2.y, boundPoint1.z);

    Vector2[] screenPoints = new Vector2[8];
    screenPoints[0] = camera.WorldToScreenPoint(boundPoint1);
    screenPoints[1] = camera.WorldToScreenPoint(boundPoint2);
    screenPoints[2] = camera.WorldToScreenPoint(boundPoint3);
    screenPoints[3] = camera.WorldToScreenPoint(boundPoint4);
    screenPoints[4] = camera.WorldToScreenPoint(boundPoint5);
    screenPoints[5] = camera.WorldToScreenPoint(boundPoint6);
    screenPoints[6] = camera.WorldToScreenPoint(boundPoint7);
    screenPoints[7] = camera.WorldToScreenPoint(boundPoint8);

    Vector2 topLeftPosition = Vector2.zero;
    Vector2 topRightPosition = Vector2.zero;
    Vector2 bottomLeftPosition = Vector2.zero;
    Vector2 bottomRightPosition = Vector2.zero;

    for (int a = 0; a < screenPoints.Length; a++)
    {
        //Top Left
        if (topLeftPosition.x == 0 || topLeftPosition.x > screenPoints[a].x)
        {
            topLeftPosition.x = screenPoints[a].x;
        }
        if (topLeftPosition.y == 0 || topLeftPosition.y > Screen.height - screenPoints[a].y)
        {
            topLeftPosition.y = Screen.height - screenPoints[a].y;
        }
        //Top Right
        if (topRightPosition.x == 0 || topRightPosition.x < screenPoints[a].x)
        {
            topRightPosition.x = screenPoints[a].x;
        }
        if (topRightPosition.y == 0 || topRightPosition.y > Screen.height - screenPoints[a].y)
        {
            topRightPosition.y = Screen.height - screenPoints[a].y;
        }
        //Bottom Left
        if (bottomLeftPosition.x == 0 || bottomLeftPosition.x > screenPoints[a].x)
        {
            bottomLeftPosition.x = screenPoints[a].x;
        }
        if (bottomLeftPosition.y == 0 || bottomLeftPosition.y < Screen.height - screenPoints[a].y)
        {
            bottomLeftPosition.y = Screen.height - screenPoints[a].y;
        }
        //Bottom Right
        if (bottomRightPosition.x == 0 || bottomRightPosition.x < screenPoints[a].x)
        {
            bottomRightPosition.x = screenPoints[a].x;
        }
        if (bottomRightPosition.y == 0 || bottomRightPosition.y < Screen.height - screenPoints[a].y)
        {
            bottomRightPosition.y = Screen.height - screenPoints[a].y;
        }
    }

    GUI.DrawTexture(new Rect(topLeftPosition.x - 16, topLeftPosition.y - 16, 16, 16), topLeftBorder);
    GUI.DrawTexture(new Rect(topRightPosition.x, topRightPosition.y - 16, 16, 16), topRightBorder);
    GUI.DrawTexture(new Rect(bottomLeftPosition.x - 16, bottomLeftPosition.y, 16, 16), bottomLeftBorder);
    GUI.DrawTexture(new Rect(bottomRightPosition.x, bottomRightPosition.y, 16, 16), bottomRightBorder);
}

//Methode zum aktivieren des MicroMenues
  /* void activeMenu(bool state)
    {
      if(state == true)
        micromenu.SetActive(state);
      else
        micromenu.SetActive(state);

    }*/

}

```

`microMenuScript`:

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

public class micromenuScript : MonoBehaviour
    {

      //public SC_SelectionManager selectionManager;
      public GameObject micromenu;

      void Start()
      {
        //
      }

      void Update()
      {
        menuVisibility();
      }

      public void menuVisibility()
      {
        if(micromenu.Find("_SelectionManager").GetComponent<SC_SelectionManager>().isSelected == true)
        {
          micromenu.SetActive(true);
        }
        else
        {
          micromenu.SetActive(false);
        }
      }
}

```

Thanks for your time.

Have great day.

# Answer
### Background

Normally when a class has variables, every time you make a new instance of the class, it gets its own copies of each variable.

(You can create two `Animal` classes and give each one a different `Name`)

A `static` variable is different. Instead of each instance having its own copy of the variable, they all share the same one.

So if you set `animal1.StaticName`, you'd change `animal2.StaticName` as well. More to the point, you don't even need to make an animal, you can just set `Animal.StaticName` directly.

So... A static variable can be read/set (and static methods can be executed) even if you haven't created an instance of the class.

### Your case

`.Find()` is a *static* method of `GameObject`. that means that `microMenu.Find()` is *actually* calling `GameObject.Find()`. (`MonoBehaviour` is a type of `GameObject`)

.Net is complaining you're using an "instance reference" (`microMenu`) when you should use the type name (`GameObject`) instead.

So change your code to `GameObject.Find()` and you should be fine.

### Finding children

Digging a step deeper... If the reason you're trying to `Find` on a specific instance is that you want to find a child of that instance, you want to look at `microMenu.transform.Find()`.

`GameObject.Find()` will search the whole scene, `microMenu.transform.Find()` will search immediate children of `microMenu` (and is considerably faster).

### Cross-script access

Ideally, you want to use something like this to store a reference to each script

\[In this example, Script1 is unaware of Script2 and Script2 can control/drive Script1, but you can apply the same technique in both directions should you wish.\]

Script1:
```
public class Script1 : MonoBehaviour {
    public string status = String.Empty;
    public void Test() {
        Debug.LogFormat("Status: {0}", status);
    }
}

```
Script2:
```
public class Script2 : MonoBehaviour {
    Script1 otherScript;
    void Awake() {
        //If on same object:
        otherScript = this.GetComponent<Script1>();

        //If on object "_OtherObj"...
        //Will complaing if _OtherObj doesn't exist
        otherScript = GameObject.Find("_OtherObj").GetComponent<Script1>();

        //In either case, check it worked...

        if(otherScript == null) {Debug.LogWarning("Couldn't find otherScript");}
    }

    void Start() {
        otherScript.status = "First test";
        otherScript.Test();
        otherScript.status = "Second test";
        otherScript.Test();
    }
}

```

You *could* get away without looking for a specific reference and instead make `Sript1` status `public static string status`.

In that case, script2 (or anything else) can just refer to `Script1.status` at any time.

The problem with this approach is that it's outside Unity's purview. Eg If the scene changes, the old value will be kept hanging around, possibly pointing at invalid/stale data.

In addition, certain actions taken by unity (like reloading the scene after a compile) will reload the runtime which will reset the value.

So it's not *really* recommended unless you're using it very defensively (always checking the value is present/credible before use).

### Things to note

Any script variables you make public (like status above) will be surfaced in the Unity editor's Inspector when you select the object.

Any value you set through the editor will be saved with the scene, and applied to your scripts after they're created, before Awake() is called.

### Some final thoughts...

Searching for objects is expensive. Do it as infrequently as possible (eg here it's done once on object load).

Also, you want to do as little as possible in each update loop. Instead of having every object poll to see if it's selected and hide/show a menu, you'd be better to handle the select/unselect events to toggle the menu directly.

That way, your code runs once when needed, rather than dozens/hundreds of times every frame.
> 1 votes

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


# Question
Title: How to decompose a 4x4 TRS transformation matrix with negative scale?
As the title says I need to decompose 4x4 TRS transformation matrices and extract the proper scale vectors and the proper rotation vectors (or rotation quaternions).

I know how to extract those information when the upper 3x3 matrix determinant is not negative. The problem is that those matrices can have that negative determinant and as far as I could understand, this negative determinant indicates a flip or mirrored transformation.

What do I have to do to extract the proper values for scale and rotation in those cases?

# Answer
Reopened this to give you a Unity implementation of the method described in the Q&A I linked above:

```
public static class MatrixHelpers
{
    public static Vector3 GetTranslation(this Matrix4x4 matrix) {
        return matrix.GetColumn(3);
    }

    public static bool TryGetRotation(this Matrix4x4 matrix, out Quaternion rotation) {
        Vector3 forward = matrix.GetColumn(2);
        if (forward.sqrMagnitude == 0f) {
            rotation = Quaternion.identity;
            return false;
        }

        Vector3 up = matrix.GetColumn(1);
        if (up.sqrMagnitude == 0f) {
            rotation = Quaternion.LookRotation(forward);
            return false;
        }

        rotation = Quaternion.LookRotation(forward, up);
        return true;
    }

    public static bool TryDecomposeTRS(this Matrix4x4 matrix,
           out Vector3 translation, out Quaternion rotation, out Vector3 scale) {
        translation = matrix.GetTranslation();
        scale = matrix.lossyScale;

        return (matrix.TryGetRotation(out rotation) && matrix.ValidTRS());
    }
}

```

With this you can write:

```
if (!someMatrix.TryDecomposeTRS(out Vector3 t, out Quaternion r, out Vector3 s)) {
    Debug.LogWarning("Input matrix was not in TRS form."
                     + " It may include shear or projection."
                     + " Results will be approximate.");
}
// TODO: Do something useful with the decomposed translation, rotation, and scale.

```

You can probably see why there's not much in the way of external libraries for this - you can do everything you need in just a few lines with the built-in Unity types.
> 2 votes

---
Tags: unity, mathematics, matrix, transformation
---


# Question
Title: Unity IUnityLifecycleManager already exists
I followed this tutorial https://www.youtube.com/watch?v=OElh7wda4Qc in Unity version 2019.3.1f.1 Personal Edition, but I got 6 errors like this in the console, also I updated to version 3.4.4 via the package manager, because it said that the asset store version was not compatible anymore.

> Library\PackageCache\com.unity.ads@3.4.4\Runtime\Monetization\AndroidPlacementContentOperations.cs(55,40): error CS0433: The type 'IUnityLifecycleManager' exists in both 'UnityEngine.Advertisements.Editor, Version=3.4.2.0, Culture=neutral, PublicKeyToken=null' and 'UnityEngine.Advertisements, Version=3.4.2.0, Culture=neutral, PublicKeyToken=null'

This is the code I am using, its the same as the code in the official website, but personalized to my project.

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

public class adsController : MonoBehaviour, IUnityAdsListener
{
    public bool testMode = true;
    public Button rewardedAd;

    private string storeID = "3509232";

    private string rewardedVideo = "rewardedVideo";

    private void Start()
    {
        rewardedAd.interactable = Advertisement.IsReady(rewardedVideo);
        rewardedAd.onClick.AddListener(ShowRewardedVideo);

        Advertisement.Initialize(storeID, testMode);
    }

    private void Update()
    {

    }

    private void ShowRewardedVideo()
    {
        Advertisement.Show(rewardedVideo);
    }

    // Implement IUnityAdsListener interface methods:
    public void OnUnityAdsReady(string placementId)
    {
        // If the ready Placement is rewarded, activate the button:
        if (placementId == rewardedVideo)
        {
            rewardedAd.interactable = true;
        }
    }

    public void OnUnityAdsDidFinish(string placementId, ShowResult showResult)
    {
        // Define conditional logic for each ad completion status:
        if (showResult == ShowResult.Finished)
        {
            // Reward the user for watching the ad to completion.
            Debug.Log("Reward");
        }
        else if (showResult == ShowResult.Skipped)
        {
            // Do not reward the user for skipping the ad.
            Debug.Log("Not Reward");
        }
        else if (showResult == ShowResult.Failed)
        {
            Debug.LogWarning("The ad did not finish due to an error.");
        }
    }

    public void OnUnityAdsDidError(string message)
    {
        // Log the error.
    }

    public void OnUnityAdsDidStart(string placementId)
    {
        // Optional actions to take when the end-users triggers an ad.
    }
}

```

**EDIT:**
Looks like I forgot a line in the code and reinstalling the unity ads package now it runs but still gives this warning.

> Please consider upgrading to the Packman Distribution of the Unity Ads SDK. The Asset Store distribution will not longer be supported after Unity 2018.3

# Answer
That warning is because you have to use the advertisement package, from the package manager instead of the unity monetization of the asset store, cause it's no longer supported after Unity 2018.3 as the warning says.
> 2 votes

# Answer
What worked for me was deleting a "Unity Ads" folder under Assets in the hierarchy. This was not needed since we already had the Advertisements package and since there were conflicts with said package deleting the unneeded folder resolved issue.
> 0 votes

---
Tags: unity, monetization, advertisements
---


# Question
Title: Difference between methods - onClick.AddListener and On Click under UI button inspector?
Within my Unity Project in my code, (see below), I have a button called Check which executes when CheckPress() function is called. I read two approaches by which this can be done.

Appraoch 1: Using `Check.onClick.AddListener(CheckPress);` and then attaching script to Canvas. When I press run and click the Check button, this works.

Approach 2: The other approach I read is that, I can attach my script to Canvas. From there I select the button Check from hierarchy, then under inspector I see On Click(), I click + sign and then drag the Canvas and place it in Object (see the attached image), then under No Function I select the CheckButtonBehaviour Script and select the CheckPress(). When I press run and click the Check button, this also works as intended.

I wanted to know if these two approaches are same or different. If they are different, then in which context either approach should be implemented.

```
using System.Collections.Generic;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
using System.Threading;
using UnityEditor;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System;
using System.Linq;

public class CheckButtonBehaviour : MonoBehaviour
{

public Button Check;
public Button Play;
public Button NextSignal;

public List<string> signals = new List<string> {"Speech1", "Speech2", "Speech3", "Speech4"};
public List<string> shuffledSignals = new List<string>();
public int index = 1;
public int counter = 3;

private static int localPort;
private string IP;
public int port = 8050;
IPEndPoint remoteEndPoint;
UdpClient client;

void Start()
{

    var rndr = new System.Random();
    shuffledSignals = signals.OrderBy(i => rndr.Next()).ToList();

    IP = "127.0.0.1";
    port = 8050;
    remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), port);
    client = new UdpClient();
    Play.gameObject.SetActive(false);
    NextSignal.gameObject.SetActive(false);

    Check.onClick.AddListener(CheckPress);

}

public void CheckPress()
{

    byte[] data0 = Encoding.ASCII.GetBytes("starting"); ///OLD CODE part
    client.Send(data0, data0.Length, remoteEndPoint);
    Debug.Log("<color=blue>Something is sent to MAX</color> : starting");

    Check.gameObject.SetActive(true);
    Check.interactable = false;
    Check.enabled = false;

    Play.gameObject.SetActive(true);
    NextSignal.gameObject.SetActive(true);

}

```

# Answer
> 2 votes
In this particular context there is no good reason to use one over the other.

But in general, there are a couple things you might want to consider:

* Assigning buttons in the inspector requires no programming knowledge. So when you are working with a UI designer who can't program C#, then you just need to provide them with the methods the UI is supposed to call and they can do most of the work themselves.
* When you do it via the inspector, then you can assign a click listener on a gameObject which does not even know the button exists. When you do it in code, then the script which sets up the click handler needs to know both the button and the object which implements the click handler. Usually it's not a problem to create that connection, but it might be additional boilerplate-code you need to write, and in the end you still end up drag&dropping one object into an inspector field of another, just like you would do if you set up the button handler in the UI.
* When you do it in code, then you can do more than just assign a method. You can, for example, assign a lambda expression. Which then has access to all the variables in the scope where it was defined. That allows you to do some elegant things. `AddListener(()=>{ currentlySelectedUnit.attackTarget(enemies[i]); })`
* When you do it in code, then you can assign and reassign button listeners at runtime. This is useful when you have a situation where the object which is controlled by a given button isn't known until the game is running. Or where it changes over the course of the game. You could of course solve this with another layer of indirection: The button always calls the same method of the same object (some kind of "UI Manager" perhaps), and that object knows the current context in which that action should be performed. But when you do it in code, then you can skip that additional indirection layer.

---
Tags: c#, scripting, ui-design, unity-ui, hierarchy
---


# Question
Title: Iterate over a loop to calculate a sum, or update a sum variable as items are added and deleted from a list?
I thought I ran into this concept at one point but can't figure out how to find an answer for it.

Is it better to iterate over a list of ints to calculate a running sum each frame, or is it better to create a variable to hold the sum and to increase or decrease it as numbers are added to the list?

The only downside I see for keeping a sum variable around is that you have to make sure you really update it correctly in all niche cases that might appear. Or ensure that items are removed from the list correctly, say, on death.

# Answer
> 1 votes
First rule of optimization: **profile first**!

Computing a sum each frame instead of updating it could be seen as a waste of CPU time, but it might be negligeable compared to all computation done each frame, so optimizing it would result in no visible result. Plus, determining if it is to be updated can require the same amount of CPU time.

If that's the case, adopt the method that you're more comfortable with, is easier to write (without bugs, of course), to read (readability is very important, I'd take readability over premature optimization every day) and to maintain.
If your case, you're mentionning niche cases. That alone is a big threat for write code without bugs and for maintainability.

In conclusion, I would iterate and compute the sum from zero in each frame. Only if I found that it is a potential performance bottleneck, I'd try to find a less CPU-consuming method. Once again: **profile first!**. This reasoning must be performed again in each case, and not applied everytime without thinking about it.

# Answer
> 1 votes
Regardless of the approach, you will need code with the responsibility to do it correctly. And you want that code to be in a single place.

Why a single place? On one hand, if it has any bug, you only have to fix it there. On the other, if you want to optimize your code, you only have to do it there. Having the code responsible of this in a single place is what enables you to start with a subpart implementation and optimize it later.

Thus, make a class. The only way to access and modify the list should be through the class, making it imposible to do it wrong or forget doing it somewhere. How you compute the sum, is an implementation detail.

*Oh, by the way, if you find yourself needing this code somewhere else, a class is easy to reuse. By properly encapsulating you will need to solve this problem less often. In fact, for problems that come very often, it is faster to find a third party library.*

---

I like the idea of making more performant software by default (with the fall of Moore's law and all)… YAGNI. *Probably*. Implement the one you find simpler and easier to read. If your performance is poor (profile), then optimize it.

---

With that said, let us pretend you have decided that this part of the code has bad performance, what can we do?

I give you these guidelines:

* Not doing something is faster than doing it.
* If you need it done, do it later.
* If you need it done right away, do it less often. *Can you reuse results?*
* *If you need it done often, have a third party solution deal with it.*
* *If you have to do it, then do it faster.*

So, what happens less often? Adding and removing elements or querying the sum?

If you query the sum more often than you add or remove items, you don't want to compute the sum each time. The guideline suggest to update the sum when items are added or removed. That way you can have the value already computed and return it.

On the other hand, when you add and remove items more often than you query the sum, the guideline suggests to compute the sum when you query it.

---

There is a third way: you can do it lazily (doing it later). Have cached sum value. Store a bool that tells you if that cached sum is valid or not. If it is, then just return it. If it isn't, then compute it again, mark it valid, and return it. When you add or remove an item, you mark it invalid.

We can actually make it more complicated: keep track of what items has been added or removed since the last computation. There is a word for that: overengineering.

By the way, you could have a not thread-safe solution. Let me rephrase that: you almost certainly have a not thread-safe solution unless you intentionally made it so and know what you are doing.

> There are 2 hard problems in computer science: cache invalidation, naming things, and off-by-1 errors.

-- Leon Bambrick

---

Or, you know, you could not do it. Chances are that whatever solution you come up with is fine, and never shows up as a problem in profiling. We don't only want to optimize the code, but also the development process. Remember the guidelines.

*Also remember that premature optimization something something*.

# Answer
> 1 votes
As with most things, and similar to the other answers: it depends.

The important thing here (appart from the well put points about not premeturely optimizing) is to consider how often this calculation needs to be performed - and how many times, and in how many places the total is needed:

As a baseline, to calcualte the total, at a minimum we will need:

* An accumulator variable
* To add each element to this once.

So the total number of operations to calculate the total **once** is independant of the implementation (more or less).

Whether we do soemting like this psuedocode:

```
// On our collection
public void AddItem(int item){ this.Items.Add(item);}

// Calculate total later
var total = 0;
foreach(var item in collection){ total += item; }
Console.WriteLine(total);

```

or something like this:

```
// On our collection - pre-calculate tpta;
public void AddItem(int item){ this.Total += item; this.Items.Add(item);}

//Use total later
Console.WriteLine(collection.Total);

```

We still have to perform the same number of steps regardless:

1. Declare a total variable
2. Add to the total N times - once for each item in the list
3. Use the total.

Therefore, the implementations are more or less equivalent, and the important thing to think about is the **use case** that this will serve.

All other considerations being equal:

* How often / in how many places is the total used?
* If it's used in multiple places, the important thing is not to re-calcualte the total multiple times.
* Can we calcualte the total once (in any way you like) but then share that total with whatever code needs it.
* How often is the list changed or ammended? Does the list change every frame?
    + If infrequently changed, then re-calculating the total when it changes may help.
    + If frequently changed, then re-calculating each time it changes might add extra overhead!

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


# Question
Title: Clicking pause button makes character jump before pausing
I have an issue with my Unity 5 game. When I click on the Pause button, my character jumps before the game is paused.

My script detects the click to trigger the jump jump before the pause button. I tried adding a tag check but that didn't work:

```
void Update () {
    if (Input.GetKeyDown (KeyCode.Space) && Time.timeScale == 1 || Input.GetMouseButtonDown (0) && Time.timeScale == 1 && gameObject.tag != "Pause") {
        GetComponent<Rigidbody2D> ().AddForce (Vector2.up * force);
    }

```

http://makeagif.com/i/bmCKQ3:

You can see in this gif, when I click on the pause button it jumps and pauses directly.

How can I click on the Pause button without making my player jump?

# Answer
I had trouble with Daniel's answer in my Phone, but I have found the answer for the problem it

```
if (Input.GetMouseButtonDown (0)) {
if (UnityEngine.EventSystems.EventSystem.current.currentSelectedGameObject) return;
    GetComponent<Rigidbody2D> ().AddForce (Vector2.up * force);
}

```

Thanks to Georgedarocha, source: http://forum.unity3d.com/threads/ispointerovergameobject-ignoring-some-objects.277825/
> 0 votes

# Answer
I had the same issue when I was doing a game. What basically happens is that your script detects if there is a mouse click, including when you click on UI components.

There is a solution to that fortunately:

```
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;

public class PlayerControl : MonoBehaviour {

    void Update () {
        if (Input.GetMouseButtonDown(0) && !EventSystem.current.IsPointerOverGameObject(0))
        {
        MovePlayer();
        }
    }
}

```

So now every-time you tap on a screen unity checks if there is no UI element (buttons, panels etc.) where you tapped before moving your player.

Hope this helps! :)
> 2 votes

# Answer
Ok, the .gif makes it make more sense. I think this is what you're looking for:

```
void Update () {
    Vector2 buttonDimensions = new Vector2(50, 50);
    Rect pauseButtonPosition = new Rect(Screen.width - buttonDimensions.x, 0, buttonDimensions.x, buttonDimensions.y);

    bool mouseOnPauseButton = pauseButtonPosition.Contains(Input.mousePosition);

    if (!mouseOnPauseButton && Input.GetKeyDown(KeyCode.Space) && Time.timeScale == 1 || Input.GetMouseButtonDown(0) && Time.timeScale == 1 && gameObject.tag != "Pause") {
        GetComponent<Rigidbody2D>().AddForce(Vector2.up * force);
    }
}

```

So basically if the mouse is on the pause button when you try to jump, it wont.
> 0 votes

# Answer
For me at least, the below solution worked just fine.. Elmar had it almost right. Hope it helps the next person to find this!

```
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;

public class PlayerControl : MonoBehaviour {

    void Update () {
        if (Input.GetMouseButtonDown(0) && EventSystem.current.IsPointerOverGameObject() == false)
        {
        MovePlayer();
        }
    }
}

```

Slight difference for smartphone games: https://docs.unity3d.com/2018.2/Documentation/ScriptReference/EventSystems.EventSystem.IsPointerOverGameObject.html
> 0 votes

# Answer
While the other answers “Hack” a solution for that individual button, it doesn’t fix the overall problem of a click propagating after it’s been detected by a script that uses it.

The input system can “consume” events. So that they are used up when required.and don’t get passed on to other objects.

For example Event.Use method.

There is a good discussion of this on the following thread:

https://forum.unity.com/threads/consuming-inputs-have-a-few-game-objects-handle-inputs-and-make-others-ignore-inputs-during-1-frame.348189/

You could also roll your own system where you can prioritize clicks to certain layers/ objects and if it gets “used” then it doesn’t get passed on to the next level of priority.
> 0 votes

---
Tags: unity, c#, input, unity-ui, pausing
---


# Question
Title: How to keep same aspect ratio in different devices with cocos2dx?
I have been making a board game and I am using cocos2dx. There are two scenes for now, One is main menu and the other is gameplay scene. When I run the apk on tablet with EXACT\_FIT resolution policy in AppDelegate.cpp sprites in the scene seems stretched out a little bit. How can I maintain the same aspect ration in all devices and also the positions of game entities? Thanks.

# Answer
> 0 votes
In my games, I choose what is the priority dimension: width or height. If I choose to prioritize WIDTH, I set it in AppDelegate.cpp

```
glview->setDesignResolutionSize(resolutionSize.width, resolutionSize.height, ResolutionPolicy::FIXED_WIDTH);

```

and all my background images have enough height to cover all aspect ratios, based on my design resolution. For example, if my design resolution is 460 x 800, to cover a 19:9 screen we need a 460 x 971 background image.

Then, I set UI components position relative to the safeArea borders

```
auto safeArea = Director::getInstance()->getSafeAreaRect();

someSprite->setPosition(Vec2(safeArea.getMinX() + margin, safeArea.getMaxY() - margin));

```

Hope this answer helps you

# Answer
> -1 votes
`SHOW_ALL` resolution policy. Show all policy will scale up the container to the maximum size in the frame which shows all your content on screen with the original width/height ratio you have set. Read more here

C++ code:

```
glview->setDesignResolutionSize(designResolutionSize.width, designResolutionSize.height, kResolutionShowAll);

```

---
Tags: opengl, c++, cocos2d-x
---


# Question
Title: Trying to understand 3D transforms by making an aircraft control script. How would you implement 3D transforms correctly in this example?
I'm struggling to understand 3D transforms in Godot. (I know, I know...)

I'm trying my best to implement an aircraft control script, and I've gotten myself into gimbal lock hell. My controls work pretty well until the Y direction decides to flip, and now my controls to pull up make the plane go down, etc...

I've read the godot 3D transform documentation, but I still find myself looking for an "Aha!" moment.

I figured a good way for me to learn would be to post what code I have and see how others would implement the movement code using transforms correctly.

Thanks for any help in advance.

extends Spatial

# Declare member variables here. Examples:
# var a = 2
# var b = "text"
onready var camera = $Camera
const SPEED = 7
const ROTATE_SPEED = 1.25
const MIN = 0.9
var rx = 0
var ry = 0
var rz = 0
# Called when the node enters the scene tree for the first time.
func _ready():
    pass

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
    self.transform.basis = Basis()
    if Input.is_action_pressed("movement_forward"):
        ry -= 1
    if Input.is_action_pressed("movement_backward"):
        ry += 1
    if Input.is_action_pressed("movement_left"):
        rx += 1
    if Input.is_action_pressed("movement_right"):
        rx -= 1
    if Input.is_action_pressed("rotate_left"):
        rz += 1
    if Input.is_action_pressed("rotate_right"):
        rz -= 1
    self.transform.orthonormalized()

    self.rotate_z(deg2rad(rz))
    self.rotate_x(deg2rad(ry))
    self.rotate_y(deg2rad(rx))
    self.transform.origin += -self.transform.basis.z * SPEED * delta
```
</code></pre>

# Answer
> 1 votes
I'm not fluent in Godot, but it looks like you want to do something like this:

```
var rotationDegreesPerSecond = 90

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
    # don't reset to default orientation every frame. Rotate from where we are.
    # self.transform.basis = Basis()

    var rotationStep = deg2rad(delta * rotationDegreesPerSecond)

    if Input.is_action_pressed("movement_forward"):
        self.rotate_object_local(Vector3.RIGHT, -rotationStep)
    if Input.is_action_pressed("movement_backward"):
        self.rotate_object_local(Vector3.RIGHT, rotationStep)
    if Input.is_action_pressed("movement_left"):
        self.rotate_object_local(Vector3.UP, rotationStep)
    if Input.is_action_pressed("movement_right"):
        self.rotate_object_local(Vector3.DOWN, -rotationStep)
    if Input.is_action_pressed("rotate_left"):
        self.rotate_object_local(Vector3.FORWARD, rotationStep)
    if Input.is_action_pressed("rotate_right"):
        self.rotate_object_local(Vector3.FORWARD, -rotationStep)

    self.transform.origin += -self.transform.basis.z * SPEED * delta

```

Here, instead of building a new rotation from scratch using 3 angle totals each frame, we apply a small rotational increment relative to wherever our local coordinate axes are currently pointing. That means your "pitch up" control is always lifting the plane's nose in the direction the top of the plane is pointing - even if the plane is vertical or upside-down at the time.

There is a risk with this style of control that you start to accumulate unwanted roll, as shown in the animated examples I linked in the comments. Since here you've given the player direct control over their roll, they can simply counter-roll to level themselves back out. But you might also want to implement a little bit of an auto-pilot or self-leveling feature that gently nudges the craft back to upright when the player isn't actively trying to roll it over.

---
Tags: vector, transformation, godot
---


# Question
Title: Raycast returns miss even though it clearly hits its target collider, how to debug?
I'm trying to debug the following situation:

The raycast returns miss even though it clearly hits its target collider.

The target is a stock 3D Object Unity Cube. The script firing the rays has a `Public GameObject` called 'target', the cube is correctly set as the target.

Here is the bulk of the raycasting I am doing. The rays are aimed at an array of positions within the bounds of the box called 'vertices'.

This was working yesterday and I didn't change the code and now it no longer works and I am completely stumped with no idea how to even begin to debug why.

```
    for (int i = 0; i < vertices.Length; i++)
    {
        Vector3 direction = vertices[i] - self.position;

        Ray ray = new Ray(self.position, direction);

        if (Physics.Raycast(ray, out raycastHit))
        {
            if (raycastHit.collider.transform == target)
            {
                Debug.DrawRay(self.position, direction, Color.green, 5.0f, true);
                hitCount += 1f;
            }
            else
            {
                Debug.DrawRay(self.position, direction, Color.red, 5.0f, true);
            }
        }
    }

```

# Answer
> 1 votes
> I am completely stumped with no idea how to even begin to debug why.

Always start with some basic debug logging:

```
if (Physics.Raycast(ray, out raycastHit))
{
    Debug.Log("Hit collider: " + hit.collider +", target: " + target);
    Debug.Log("hit.collider == target" + hit.collider == target);

```

> The script firing the rays has a Public GameObject called 'target'

Your code says `if (raycastHit.collider.transform == target)`. If `target` is a GameObject, the result will always be false, because the Transform component is a Component, not a GameObject.

> Target is a collider but it was comparing transform to collider for some reason.

Wait, is `target` a collider or a GameObject? If it's a collider, why are you comparing it to the Transform of the object that the Raycast hit? Collider and Transform are different components and will never be equal.

This will probably do what you want:

`if (raycastHit.collider.transform == target.transform)`

---
Tags: unity, raycasting
---