title: Tracking playing position into an array

text:
# Question
Title: Tracking playing position into an array
I'm trying to track playing position every 500ms which i can do but i need it to populate an array which i save to a txt file as a comma delimted list or something.

I have this code so far (which incorporates the player movement code too), which displays the positions in the console:

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

public class CharacterControllerT : MonoBehaviour {

    public float speed = 10.0f;
    public Read_moveT ReadMove;
    [SerializeField] private float _duration = 0.5f;
    private float _timer = 0f;
    public Vector3 PlayerPosT;
    GameObject Mover;
    public Vector3[] PlayerTxyz;

    // Use this for initialization
    void Start () {
        Cursor.lockState = CursorLockMode.Locked;
        Mover = GameObject.Find ("PlayerT");
        ReadMove = Mover.GetComponent<Read_moveT> ();
    }

    // Update is called once per frame
    void Update () {

        if (!Input.GetButton ("DoorTrigger")) {
            ReadMove.mUP = Input.GetAxis ("Vertical");
            ReadMove.mLEFT = Input.GetAxis ("Horizontal");
            float translation = ReadMove.mUP * speed;
            float straffe = ReadMove.mLEFT * speed;

            translation *= Time.deltaTime;
            straffe *= Time.deltaTime;

            transform.Translate (straffe, 0, translation);
        }

        if (Input.GetKeyDown ("escape")) {
            Cursor.lockState = CursorLockMode.None;
        }

        _timer += Time.deltaTime;
        if (_timer >= _duration) {
            _timer = 0f;
            PlayerPosT = Mover.transform.position;
            print ("Player:: X: " + PlayerPosT.x + ", Z: " + PlayerPosT.z);
        }
    }
}

```

I just need these coords to be saved into an array that i can process when the game is over. The problem being that the array will always be (until game over) of undetermined length.

Any ideas?

Thanks,

Paul..

# Answer
> 1 votes
You can initialize a `List<Vector3>` and then when you need to save the position just call it with the List.Add(Vector3) like the following. Note that saving process better be done outside of your `CharacterControllerT` script in order not to lose the saved positions if you destroy the character or something.

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

public class PositionRecorder : MonoBehaviour {

    private static List<Vector3> savedPositions;

    // Use this for initialization
    void Start () {
        savedPositions = new List<Vector3>();
    }

    public static void SavePosition(Vector3 position){
        savedPositions.Add(position);
    }
}

```

Then call it from outside like `positionRecorder.SavePosition(PlayerPosT)`

---
Tags: transformation, coordinates, timer
---


title: Unity input manager use multiple keys

text:
# Question
Title: Unity input manager use multiple keys
Is it possible to use multiple keys so that they combined will do the action?

Say for instance you want a jump attack that would require two buttons to be pressed at the same time. in this case: `space + mouse 1` ?

I tried creating that however it didnt seem to take my input.

Does anyone know how this can be achieved?

# Answer
> 2 votes
You'd have to coordinate the two buttons in your script, something like this:

(adding some leeway in case they're pressed a frame or so apart)

```
public float inputWindow = 2f/30f;
float _attack1Time;
float _attack2Time;

void Update() {
    if(Input.GetButtonDown("AttackButton1")) {
       _attack1Time = Time.unscaledTime;
       if(Time.unscaledTime - _attack2Time < inputWindow)
        DoTwoButtonAttack();
    }
    if(Input.GetButtonDown("AttackButton2")) {
       _attack2Time = Time.unscaledTime;
       if(Time.unscaledTime - _attack1Time < inputWindow)
        DoTwoButtonAttack();
    }
}

```

---
Tags: unity, input
---


# Question
Title: How do I delete instantiated game objects when they move off the left side of the camera?
The game objects move from the right to the left, via a separate, working script. I want them to be destroyed when they cross the left side of the camera. How do I delete instantiated game objects when they move off the left side of the camera?

---

I am using this script to spawn game objects:

```
// Use this for initialization
void Start ()
{
    InvokeRepeating ("spawnObject", this.spawnInterval, this.spawnInterval);
}

void spawnObject()
{
        float y = Random.Range(objectMinX, objectMaxX);

        GameObject newObject = Instantiate (this.prefabToSpawn,
            this.transform.position + new Vector3(30,y,-30), Quaternion.identity);

        if (newObject.transform.position.x < Camera.main.transform.position.x)
        {
            // neither the print nor Destroy gets called
            print("destroy");
            Destroy(newObject);
        }
    }

```

# Answer
> 1 votes
You actually have *two* problems, in your code. The first is that the objects are not destroying. The second is that, when they *do* destroy, they *won't* destroy in the intended place.

I feel it will be more helpful to solve each problem, separately. First we will get the objects to start destroying, then we will adjust the code to provide the correct position.

---

### Getting your objects to correctly check the `Destroy()` condition

In the above code, you instantiate the object as `newObject`, and than check if it is past a certain position. As soon as this check completes, you lose your reference to that object. The `spawnObject` method only ever checks the position *straight after* instantiation. It appears that you intend to perform this check *regularly*, as you continue to move the object.

You say that you have a script attached to the object in charge of scrolling. We will use this script to perform the checks, instead. For the sake of example, we will say this script is called `AutoScroll`.

```
public class AutoScroll : MonoBehaviour
{
    void Update()
    {
        // Perform logic to move the object, first. That way, it trigers
        // Destroy() as soon as it oversteps its boundary.

        if(transform.position.x < Camera.main.transform.position.x)
        {
            Destroy(gameObject);
        }
    }
}

```

---

### Getting your objects to meet the *right* `Destroy()` condition

Now we have your objects destroying, you might notice that they destroy in the middle of the screen. That is because your checking against `Camera.main.transform.position.x`. The camera projects forward, but the object itself is positioned right in the middle of the view port.

We could find the true position for directly off the screen in a couple of ways. The programmatic way would involve trigonometry, notably incorporating the angle of the view and the distance from the object to identify the exact position where the object disappears out of camera view. For a simple project, especially in Unity, this might be over-complicated for your requirements. There is a much simpler one; we measure it, in the editor.

Create a cube, and place it in the scene at the co-ordinates where an object would be created by your object spawner. With the game view visible, move it to the left until it is just off the screen. Assuming the cube is not parented to anything, this should give us an approximate x position for off-screen. Note that "off-screen" changes, slightly, with different resolutions. You *may* want to change resolutions, in order to ensure you are *always* off-screen.

In my example, I find the cube is just off the left of the screen at a reliable x position of -8.35. I have checked across a couple of resolutions, but I like to cover myself in these sort of situations, and it will not hurt if it moves *a little bit more* off the screen. I would use a value of -9 or -10. We than check against this direct value, instead of `Camera.main.transform.position.x`.

```
public class AutoScroll : MonoBehaviour
{
    public float dropoffPosition = -9f;

    void Update()
    {
        // Perform logic to move the object, first. That way, it trigers
        // Destroy() as soon as it oversteps its boundary.

        if(transform.position.x < dropoffPosition )
        {
            Destroy(gameObject);
        }
    }
}

```

Note that you would have to readjust your boundary value if you make edits to the position of the camera; notably, the size or field of view, the position, or the size or position of your actual game objects being destroyed.

---
Tags: unity, camera
---


# Question
Title: How do I switch between different Update behaviour states in Unity?
I have a bird entity that needs different update rules when it's moving or dying (among potentially other states).

I want to avoid making my `Update` method a clutter of if-else branches like this:

```
void Update() {
   if(state == movingState) {
       // Do moving logic.
   else if(state == dyingState) {
       // Do dying logic.
   else if...

```

Instead, I thought I could make a base class for all my bird behaviours, then derive classes for each state with their own update functions, and use the appropriate derived version based on the current state.

```
public class BirdBaseModel : MonoBehaviour
{
    void Update()
    {
        // ...
    }
}

public class BirdMoving : BirdBaseModel
{
    void Update()
    {
        // ...
    }
}

public class BirdDying : BirdBaseModel
{
    void Update()
    {
        // ...
    }
}

```

My `BirdBaseModel` is attached to the bird game object. Based on game states, I want to dynamically reference it in the `GameController` class.

```
BirdBaseModel b;

if(State == 1)
{
    b = new BirdMoving();
}
else if(State == 2)
{
    b = new BirdDying();
}

```

Based on the above logic, I want to call the Update function of that particular class. How do I invoke the Update of the subclass?

# Answer
If you just want different behaviours for different states, but without complicated switching logic in your Update loop, I'd recommend using Coroutines. That way you keep the related behaviour in one class/instance, rather than juggling a collection of them every time you want a different state.

A coroutine with a `yield return null` loop executes once each frame very similar to the Update message, and by switching between multiple coroutines you get your state change behaviour.

```
public class MultiStateBehaviour : MonoBehaviour {

    // Set up externally-visible state labels we can edit in the Inspector.
    [System.Serializable]
    public enum State { A, B }

    Coroutine _activeState;

    public void ChangeState(State destinationState) {

       // Optionally, you can check if you're already in destinationState
       // and early-out rather than restarting the state.

       IEnumerator state;
       switch(destinationState) {
           case A : state = StateA(); break;
           case B : state = StateB(); break;
       }

       // Abort the currently-running state.
       if(_activeState != null)
           StopCoroutine(_activeState);

       _activeState = StartCoroutine(state);
   }

   IEnumerator StateA() {
       // Do State A setup stuff here.

       while(true) {
           // Do State A per-frame stuff here.

           // Resume again next frame.
           yield return null;
       }
   }

   IEnumerator StateB() {
       // Do State B setup stuff here.

       while(true) {
           // Do State B per-frame stuff here.

           // Resume again next frame.
           yield return null;
       }
   }
}

```

This gives you a lot of power to have local data tracked in the current state, or complicated control flow within a state that changes from frame to frame.

If you only need another method to run though, you can do this even more simply with delegates:

```
public class MultiStateBehaviour : MonoBehaviour {

    // Define the method signature all of our update functions should have.
    delegate void UpdateBehaviour();

    // Store a delegate representing our current desired behaviour.
    UpdateBehaviour _currentUpdateBehaviour;

    // Here I just initialize to a particular state.
    // You can adapt the same kind of state switch logic as the example above.
    void Start () {
        _currentUpdateBehaviour = StateA;
    }

    // In Update, run whatever our current update behaviour is.
    void Update () {
        _currentUpdateBehaviour();
    }

    // Define a couple of update behaviours we might want to use:
    void StateA()
    {
        // Do State A per-frame stuff here.
    }

    void StateB()
    {
        // Do State B per-frame stuff here.
    }
}

```

That said, if you really need subclasses for each state, you can do this using virtual methods like so:

```
public class BaseClass : MonoBehaviour {
    protected virtual void Update() {
        // Do base class stuff here.

        // Or, if you don't ever construct the base class at all,
        // use the "abstract" keyword instead of "virtual"
        // and mark the class itself as "abstract" too.
    }
}

public class DerivedClass : BaseClass {

    protected override void Update() {
        // Do derived class stuff here.
    }
}

```

Now any code calling `DerivedClass.Update()` will get the derived class's version, even if they know only that it's some flavour of `BaseClass`. That includes the Unity game loop.

You can't just force an instance of `BaseClass` to use the `DerivedClass`'s method though. You'd have to remove/disable the `BaseClass` component on the object and replace it with `AddComponent<DerivedClass>`, or enable a `DerivedClass` instance that was already on the object. As you can see, switching states this way is a much more heavyweight operation than the previous two options, so I wouldn't really recommend it unless the states need to be radically different from each other.
> 4 votes

# Answer
Simply put, you simply *override* the base methods. The problem I see is *not* that you can not call the specific `Update`; it is that you can not call `Update`, at all:

```
class ParentClass : MonoBehaviour
{
    void Update()
    {
        // ...
    }
}

```

In this fashion, `Update` will naturally be called during the game logic, as it is a `MonoBehaviour`. However, it is *also* a `private` method. You *can not* access it from outside the class.

Let's assume we are using a non-broadcasted method; that is, a method that does not get called unless we call it.

```
class ParentClass : MonoBehaviour
{
    public ParentClass[] variations;

    void Start()
    {
        for(int i = 0; i < variations.Length; i++)
        {
            variations[i].Call();
        }
    }

    protected virtual void Call()
    {
        Debug.Log("I am a Parent");
    }
}

```

Note the two distinct differences:

* I use a `protected` method. This is the same as a `private` method, except you can access it from other children of the parent. If you wish to access this method from *outside* the class (for example, from a controlling class that is not a child), you need to make the method `public`.
* I use a `virtual` method. This tells the class that I might override it in a child class.

You will also notice that I have a public array of `ParentClass` types, and a `Start` method. This is to demonstrate the way in which I store all of my variations, and output the `Call` method.

When I create children, I simply override the original method. You can still use `base` to reference the parent and its internal methods, including the one we are overriding.

```
class ChildOne : ParentClass
{
    protected override void Call()
    {
        Debug.Log("I am the first Child");
    }
}

class ChildTwo : ParentClass
{
    protected override void Call()
    {
        Debug.Log("I am the second Child");
        base.Call();
    }
}

```

This gives you the following debug output:

> I am a Parent
> I am the first Child
> I am the second Child
> I am a Parent

For situations like `Update`, where you have a broadcasted method, behaviour will stay the same. As long as it is an `override` of a `virtual` method (and it will throw errors, if this is not the case), the `Update` method of the specific child will be called, automatically.
> 2 votes

# Answer
Another option might be something like this:

```
public class BirdBehaviour : MonoBehaviour
{
    private BirdMovingState movingState;
    private BirdDyingState dyingState;

    private BirdState currentState;

    private void Awake()
    {
        // Initialize states.
        this.movingState = new BirdMovingState();
        this.dyingState = new BirdDyingState();

        // Set the current state.
        this.currentState = this.movingState;
    }

    private void Update()
    {
        // Invoke update method of the current state.
        this.currentState.Update();
    }
}

public abstract class BirdState
{
    public virtual void Update()
    {
    }
}

public class BirdMovingState : BirdState
{
    public override void Update()
    {
        Debug.Log("Moving...");
    }
}

public class BirdDyingState : BirdState
{
    public override void Update()
    {
        Debug.Log("Dying... :'(");
    }
}

```
> 1 votes

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


title: Rotating hitboxes in PyGame?

text:
# Question
Title: Rotating hitboxes in PyGame?
I'm using `pygame.rect.colliderect()` to check hitbox collision between sprites in my game, but now that I'm rotating the sprites, I'm realizing I can't do this because there's no way to rotate a PyGame `rect`, so the hitboxes are way off now.

How should I handle collision in a game with rotating sprites if I don't want to use masks or pixel perfect collision? Is there a way to make a hitbox that rotates with the sprite?

# Answer
As mentioned, pygame doesn't directly offer support for rotating hitboxes. However, you could either look into coding your own non-axis aligned box classes, or use a little cheat. The cheat basically calculates the axis-aligned hitbox that completely contains your sprite. It's pretty easy to calculate, and might be good enough for your game, depending on your needs of course. I myself use the trick in my current game project.

So here's the basic outline for the calculation. You'll need to rotate each corner of your sprite image by the rotation amount, and then find the largest and smallest coordinates, and build your box around those. The code might look something like this in pseudo-code (semi Python):

```
rotatedCorners = [rotate(topleft), rotate(topright), rotate(bottomleft), rotate(bottomright)]
# Assumes that "rotate" returns a tuple point.
xCoordinates = list(c[0] for c in rotatedCorners)
yCoordinates = list(c[1] for c in rotatedCorners)
# Then we just calculate the box data.
position = (min(xCoordinates), min(yCoordinates))
size = (max(xCoordinates) - position[0], max(yCoordinates) - position[1])

```

The `rotate`-function should look something like this:

```
def rotate(point):
    # First translates the point to have the origin at your sprite's center.
    origin = yourSpriteCenterPosition;
    originPoint = (point[0] - origin[0], point[1] - origin[1])
    # Then we rotate the point using basic trigonometry.
    rotatedX = originPoint[0] * cos(angle) - originPoint[1] * sin(angle)
    rotatedY = originPoint[0] * sin(angle) + originPoint[1] * cos(angle)

    # Finally we need to translate the point back to world space.
    return (rotatedX + origin[0], rotatedY + origin[1])

```

This is what my quick and dirty implementation yields:
> 3 votes

# Answer
Building on Tyyppi\_77's answer above, there are a few approaches you can take:

1) Resizing the hit box (as he suggests) - although you can do it much much easier just by using image.get\_rect(), which will have the same result.

2) Use circle collisions. In Pygame this is pretty easy if you're using the Sprite class. Just assign each sprite a self.radius, and then use pygame.sprite.collide\_circle() - http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.collide\_circle NOTE: depending on the shape of your sprite, this may or may not result in better looking collisions.

3) Define a smaller hitbox. Give each sprite a custom hitbox that is a little bit smaller than the image. This can result in a much better game feel, and you don't get those near-miss collisions that can frustrate players. I recently did a tutorial on this, if you're interested: https://www.youtube.com/watch?v=5M\_-cJP5rk8

4) Use a collision mask. This is how you do "pixel perfect" collisions in Pygame. You define a mask for each sprite - using pygame.mask.from\_image() is the simplest way - and then use the pygame.sprite.collide\_mask() callback for your collisions. http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.collide\_mask

Which solution you choose will depend on what you are trying to accomplish. Collisions can be done in lots of different ways, and programmers often over-engineer them when a simpler solution will give the same game feel. For example, circle collisions are much faster than masks, but in a fast-moving game the player usually won't be able to see the difference.
> 3 votes

# Answer
Usually hit boxes are implemented to always be axis aligned. Pygame is really old and it hasn't been updated in a couple of years so it is missing a lot of the features we'd expect from a game development API such as proper collision detection. I would suggest you either use circles for collision which are very easy to implement and are the fastest method of collision detection or you could write a proper collision box class that can be rotated with the object.
> 1 votes

# Answer
There's another alternative: Pymunk the 2d physics library. You can give your game objects pretty arbitrary shapes by adding several pymunk.Shapes to a pymunk.Body (as you see in the `GameObject` class) and then use them for collision detection in your py-game. In the example below a point query is used to delete sprites with the right mouse button (just for demonstration purposes). To implement bullets or other colliding objects you can use collision handlers. Of course you can turn the gravity and interactions between the bodies off as well if you don't need them.

The green lines show the outlines of the Pymunk shapes. The rect of the pygame sprite is set to the body.position in the `update` method, so that the image gets blitted at the correct point. That means in order to move the sprite, you would have to manipulate its body.

```
import math

import pygame as pg
import pymunk as pm
from pymunk import Vec2d

def flipy(p):
    """Convert chipmunk coordinates to pygame coordinates."""
    return Vec2d(p[0], -p[1]+600)

class GameObject(pg.sprite.Sprite):
    """A sprite with an attached physics body."""

    def __init__(self, pos, space):
        super().__init__()
        self.image = pg.Surface((80, 70), pg.SRCALPHA)
        offset = Vec2d(80/2, 70/2)  # Offset for poly drawing below.
        self.orig_image = self.image
        self.rect = self.image.get_rect(topleft=pos)

        self.space = space

        self.body = pm.Body(0, 0)
        # Attach the sprite to the body, so that we can access it later.
        self.body.sprite = self
        self.body.position = pos
        self.space.add(self.body)
        # Add 2 shapes to the body.
        # Vertices of the shapes.
        vertices = (
            [(-25, 14), (0, 24), (0, 0), (30, 0), (30, -20), (0, -20)],
            [(20, 34), (40, 24), (10, 0), (-10, 0)],
            )
        for verts in vertices:
            shape = pm.Poly(self.body, verts, radius=.1)
            shape.density = 1
            shape.friction = .9
            self.space.add(shape)
            # Need to transform the verts before they can
            # be used to draw a poly on self.image.
            verts2 = [vert.rotated(self.body.angle) + offset
                      for vert in shape.get_vertices()]
            verts2 = [(x, -y+70) for x, y in verts2]
            pg.draw.polygon(self.image, (60, 80, 140), verts2)

    def update(self, dt):
        # Synchronize the position of the sprite rect and Pymunk body.
        self.rect.center = flipy(self.body.position)
        # Rotate the image.
        self.image = pg.transform.rotate(
            self.orig_image, math.degrees(self.body.angle))
        self.rect = self.image.get_rect(center=self.rect.center)

        if self.rect.bottom > 560:  # Off-screen.
            self.space.remove(self.body, self.body.shapes)
            self.kill()

class Game:

    def __init__(self):
        self.fps = 30
        self.done = False
        self.green = pg.Color('springgreen')
        self.clock = pg.time.Clock()
        self.screen = pg.display.set_mode((800, 600))
        self.all_sprites = pg.sprite.Group()

        self.space = pm.Space()
        self.space.gravity = Vec2d(0.0, -900.0)
        # A static body platform.
        body = pm.Body(0, 0, pm.Body.STATIC)
        verts = [[150, 100], [650, 100], [650, 200], [150, 200]]
        poly = pm.Poly(body, verts, radius=.1)
        poly.friction = 0.5
        self.space.add(body, poly)

        self.shape_filter = pm.ShapeFilter()

    def run(self):
        while not self.done:
            self.dt = self.clock.tick(self.fps) / 1000
            self.handle_events()
            self.run_logic()
            self.draw()
            self.current_fps = self.clock.get_fps()

    def handle_events(self):
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.done = True
            elif event.type == pg.MOUSEBUTTONDOWN:
                if event.button == 1:  # Left button adds GameObjects.
                    self.all_sprites.add(
                        GameObject(flipy(event.pos), self.space))
                elif event.button == 3:  # Right button.
                    # Remove the body and shapes under
                    # the mouse cursor.
                    query = self.space.point_query(
                        flipy(pg.mouse.get_pos()), 0.0, self.shape_filter)
                    for info in query:
                        body = info.shape.body
                        # Don't remove the platform.
                        if hasattr(body, 'sprite'):
                            try:
                                self.space.remove(body, body.shapes)
                                body.sprite.kill()
                            except KeyError:
                                pass

    def run_logic(self):
        self.space.step(1/60)
        self.all_sprites.update(self.dt)

    def draw(self):
        self.screen.fill((166, 166, 150))
        # Platform rect.
        pg.draw.rect(self.screen, (120, 130, 110), (150, 400, 500, 100))
        self.all_sprites.draw(self.screen)

        # Draw the outlines of the shapes.
        for shape in self.space.shapes:
            pts = [flipy(pos.rotated(shape.body.angle) + shape.body.position)
                   for pos in shape.get_vertices()]
            pg.draw.lines(self.screen, self.green, True, pts, 1)

        pg.display.flip()

if __name__ == '__main__':
    pg.init()
    Game().run()
    pg.quit()

```
> 1 votes

---
Tags: rotation, python, pygame
---


# Question
Title: Why is Unity 5.6 displaying launch image wrong on iOS?
I updated from Unity 5.5.0p3 to 5.6.0f3, and I have no idea what's causing this. The iOS launch image which looked like this:

Now looks like this:

# Answer
> 3 votes
There is a bug in 5.6 which causes transparency to not be imported. Install the newest patch release. Then reimport the affected file(s). Then try the build.

---
Tags: unity, ios
---


# Question
Title: Translating yaw degrees into 2D movement
I've been hitting my head on the wall for a while with this, and I'm almost sure I'm overcomplicating it.

I have a variable for yaw in degrees (and also pitch and roll, but those should be irrelevant). I want to turn that variable into normalized 2D movement, so the distance traveled per frame should always be a constant.

I was easily able to to workout movement when I had a fixed view direction, but translating it with yaw is what's confusing me. I've been trying a combination of converting to radians, then using cos(x) and sin(x) but it only works if I'm looking in a certain direction.

# Answer
> 1 votes
Yep, was definitely overthinking it. Here's the quick version, probably some ways to optimize it:

```
        double x = Math.sin(Math.toRadians(yaw));
        double z = Math.cos(Math.toRadians(yaw));
        double xo = Math.sin(Math.toRadians(yaw + 90)); // 90 offset of current direction
        double zo = Math.cos(Math.toRadians(yaw + 90));

        if(Keyboard.isKeyDown(Keyboard.KEY_W)) {
            position.z -= MOVESPEED * z;
            position.x += MOVESPEED * x;
        }
        if(Keyboard.isKeyDown(Keyboard.KEY_D)) {
            position.z -= MOVESPEED * zo;
            position.x += MOVESPEED * xo;
        }
        if(Keyboard.isKeyDown(Keyboard.KEY_A)) {
            position.z += MOVESPEED * zo;
            position.x -= MOVESPEED * xo;
        }
        if(Keyboard.isKeyDown(Keyboard.KEY_S)) {
            position.z += MOVESPEED * z;
            position.x -= MOVESPEED * x;
        }

```

---
Tags: movement, trigonometry
---


# Question
Title: Unity Assets folder is empty after opening package from the asset store
I downloaded the following Survival Shooter Tutorial from the Asset Store :

https://www.assetstore.unity3d.com/en/#!/content/40756

I was prompted to open it in Unity so I did and began following this tutorial :

https://www.youtube.com/watch?v=\_lP6epjupJs

I am only 2 minutes into the first video and am stuck. In the tutorial there are lots of folders in the assets folder. I took a screenshot of what my screen looks like to show that it is empty.

# Answer
> 1 votes
It looks like I needed to have Unity open FIRST then download the package from the Asset store INSIDE Unity

---
Tags: unity
---


# Question
Title: How do I reference a particular UI Image or Sprite in my assets folder?
I have an `Item` class, and I want to associate an `Image` class with it. How do I get a reference to the intended `Image`, from my assets folder, in order to provide it as a reference to a constructor for `Item`?

---

Here is my code:

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

public class ItemData : MonoBehaviour
{
    private List<Item> items;

    void Start()
    {
        items = new List<Item>();

        Item sword = new Item(0, "Sword", /*What goes here?*/);
        items.Add(sword);

        Item hammer = new Item(0, "Hammer", /*What goes here?*/);
        items.Add(hammer);
    }
}

public class Item
{
    public int itemID;
    public string itemName;
    public Image itemImage;

    public Item(int newItemID, string newItemName, Image newItemImage)
    {
        itemID = newItemID;
        itemName = newItemName;
        itemImage = newItemImage;
    }
}

```

# Answer
The easiest way is to provide a reference, via the Inspector. That said, you can use `Resources.Load()` to programmatically locate an asset in your Assets folder.

### Direct Reference

You can provide a direct reference via the Inspector using a `public` reference or the `[SerializeField]` attribute. This allows you to drag and drop your reference in, in the actual Unity Editor. This may not be the best option, especially if you do not want to keep reference to your `Image` set in the `ItemData` class; however, given its simplicity, I feel it is important to make note of the option for completion sake.

```
public class ItemData : MonoBehaviour
{
    private List<Item> items;
    [SerializeField] private Image swordImage, hammerImage;

    void Start()
    {
        items = new List<Item>();

        Item sword = new Item(0, "Sword", swordImage);
        items.Add(sword);

        Item hammer = new Item(0, "Hammer", hammerImage);
        items.Add(hammer);
    }
}

```

### Using `Resources.Load()`

The `Resources` class provides functionality for locating assets from any available *Resources* directory, in your Project. We can use `Resources.Load` to locate assets by name. Let's take a look at the official documentation:

> ## Resources.Load
>
> `public static Object Load(string path);`
> `public static Object Load(string path, Type systemTypeInstance);`
>
> ### Parameters
>
> `path` Pathname of the target folder. When using the empty string (i.e., ""),
> the function will load the entire contents of the Resources folder.
> `systemTypeInstance` Type filter for objects returned.
>
> ### Description
>
> Loads an asset stored at `path` in a Resources folder.
> Returns the asset at `path` if it can be found otherwise returns null. Only objects of `type` will be returned if this parameter is supplied. The `path` is relative to any Resources folder inside the Assets folder of your project, extensions must be omitted.
> **Note:** All asset names and paths in Unity use forward slashes, paths using backslashes will **not** work.
>
>  \- `Resources.Load()` @ official Unity documentation

---

Now we know how it works, there are further matters to consider.

The first matter is our target type. You want to load an `Image`; but `Image` is a `MonoBehaviour`. You can not have a prefabed `Image` in your assets folder; but you *can* have a `GameObject` that *contains* an attached `Image`. Thus, we locate the `GameObject`, and use it to get the attached `Image`:

```
public class ItemData : MonoBehaviour
{
    private List<Item> items;

    /// <summary>The directory path inside the main "Resources" folder. We declare this as a
    /// const string, as it should not change. This allows us to write the directory path
    /// once, and limit logical errors.</summary>
    private const string path = "ItemImages/"

    void Start()
    {
        items = new List<Item>();

        GameObject swordImage = Resources.Load(path + "SwordImage") as GameObject;

        Item sword = new Item(0, "Sword", swordImage.GetComponent<Image>());
        items.Add(sword);
    }
}

```

---

Perhaps you mean to find an actual image; that is, a `Sprite` to use when generating an `Image`. This might be a more efficient means to complete your desired functionality; but keep in mind that you will need to generate the `Image`, later, assuming you still intend to1. You would probably complete this functionality in a constructor for `Item`; specifically, `Item(int newItemID, string newItemName, Sprite newItemImage)`.

```
public class ItemData : MonoBehaviour
{
    private List<Item> items;

    /// <summary>The directory path inside the main "Resources" folder. We declare this as a
    /// const string, as it should not change. This allows us to write the directory path
    /// once, and limit logical errors.</summary>
    private const string path = "ItemImages/"

    void Start()
    {
        items = new List<Item>();

        Sprite swordImage = Resources.Load(path + "SwordImage") as Sprite;

        Item sword = new Item(0, "Sword", swordImage);
        items.Add(sword);
    }
}

```

---

1 You may be using `Image` incorrectly. Think of `Image` as your UI container, and `Sprite` as your *actual* image. Typically, you would have a reference to the `Image` container in your scene view; and than replace its `sprite` reference with the desired `Sprite`, when you wish to change the display.
> 0 votes

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


# Question
Title: How can I look up an object given only the name of its type?
This question came from a fellow developer on Twitter, and I figured StackExchange would be a better format for explaining & sharing the answer. To paraphrase the question:

---

I'm setting up an in-game dev console in my Unity game, where a user should be able to call any method on any MonoBehaviour in the scene.

I want to use something like `FindObjectsOfType<>`, but because it's coming from a string input by the user, the class name is unknown at compile time.

I also want this to work universally, on any MonoBehaviour, not just ones I've specially instrumented or registered with the console system.

Is there a way to find instances of a type with a particular name, and call methods on them, using something like reflection?

# Answer
Yes, this is possible.

Because it's making heavy use of reflection and uncontrolled strings, it can be both slow and unsafe, so I would not recommend it for regular game behaviour. For a console use case though, it's probably OK. If you intend to ship the console with a released game, I'd recommend adding some extra error-checking and sanitization of allowed commands that I've elided here.

```
// References to the Unity Engine types need an assembly qualified name,
// so we cache that here. Repeat for any 3rd-party assemblies you use.
static readonly string engineAssemblyName =
     System.Reflection.Assembly.GetAssembly(typeof(GameObject)).FullName;

void InvokeAll(string componentName, string methodName, System.Object[] arguments)
{
    // We'll search for a type matching the given component name.
    System.Type type;

    // First, check our own CSharp assembly (no extra qualification needed).
    type = System.Type.GetType(componentName);

    // If not found there, then check the UnityEngine assembly.
    if (type == null) {
        string qualifiedName = string.Format("UnityEngine.{0}",
            System.Reflection.Assembly.CreateQualifiedName
            (engineAssemblyName, componentName));
        type = System.Type.GetType(qualifiedName);
    }

    if(type == null) {
        Debug.LogErrorFormat(
              "Could not find type {0} in Assembly-CSharp or UnityEngine.",
              componentName);
        return;
    }

    // We've found a valid type.
    // Use the Unity method to retrieve all active instances in the scene.
    var components = FindObjectsOfType(type);

    // Note: this currently works only for methods with a single definition.
    // More information is needed to disambiguate which method you want when
    // it has multiple overloads (same name with different signatures).
    var method = type.GetMethod(methodName);

    // If you need to access private/protected methods too,
    // use this version that peeks into non-public areas...
    //var method = type.GetMethod(methodName,
    //      System.Reflection.BindingFlags.Public
    //    | System.Reflection.BindingFlags.NonPublic
    //    | System.Reflection.BindingFlags.Instance);

    // You could also search through the array to select only
    // certain instances to invoke...
    foreach(var component in components)
    {
        method.Invoke(component, arguments);
    }
}

```
> 8 votes

---
Tags: unity, c#, code-reflection
---


# Question
Title: How do I trigger a collider on a child game object from the parent game object?
I have an enemy, which has a rag doll component. It has a few child object,s and each child has its own collider. I don't want to add a script for every child, as the `OnCollisionEnter` method will be the same.

How can I do I trigger `OnCollisionEnter` with just one script, from the parent game object?

# Answer
> -1 votes
If you want to set the object up just by placing one script, and have all the logic contained in that one script, you can create a class that forwards the collision event to the parent object with gameObject.sendMessage(), or even just a reference to a public method of your parent object's script.

Instead of manually adding this class to the limbs of your ragdoll, you can use gameObject.AddComponent() to add the class dynamically.

Using gameObject.GetComponentsInChildren() will get you an array of all child objects that can get collisions, that you can then iterate over to add the forwarding script.

# Answer
> 0 votes
If you want colliders attached to child game objects to trigger your game objects `OnCollisionEnter` method, there is no reason to add *any* additional code; that is, they will *already* trigger the parent `OnCollisionEnter` method.

I have demonstrated this, below, using a basic script that prints to the debug log through a single `OnCollisionEnter` method.

---

As you can see, the parent contains the script, while the child contains the collider. Regardless, the `OnCollisionEnter` method still enters, and prints to the debug.

---
Tags: unity
---


# Question
Title: Moving a Polygon based on Camera position
I am in the process of implementing TMX Maps (made in Tiled) for my game. In Tiled, I can create polygons, which leaves a tag, containing the points.

Loading in these points to a Polygon (java.awt.Polygon) isn't a problem. When all points are loaded into a Polygon (which also had an x and y position, which is the origin of the Polygon), and I draw it, it looks perfect.

However, when I was to move it the troubles started. Every tick, I want to set the position of this Polygon according to the x, y position (the origin), and the Camera position, so that when I draw it, it will draw on position.x - Camera.x and position.y - Camera.y. So every tick, I want to set the (x, y) position of the Polygon equal to position - Camera.position.

I thought that this would be as simple as calling the translate(position.x - Camera.x, position.y - Camera.y) function in the polygon every tick, but the problem here is that this function adds a delta, instead of setting the position. Because of this, the Polygon won't stay still when the Camera is still, because it adds this delta, so the Polygon just moves off the screen.

So, the question is really how to set the position of a polygon every tick, instead of adding a delta to it every tick?

# Answer
> 1 votes
You have to keep separated your `world` and `screen` coordinates.

Store only `world` coordinates of your object (position inside the whole map).

Then, when you need to test collisions (object with another object) you can check both object in `world`coordinates. If you apply rotation or scaling to object you will have to go from object coordinates in `world` to `screen` coordinates and then to another object `world` coordinates to account for object or another object changes.

When you want to draw it on the screen use the transform matrix to go from `world` coordinates to `screen` coordinates.

A graphical explanation about transformations can be found here and an explanation to understand how to use matrix here.

# Answer
> 0 votes
Store the x points, y points and any other polygon related data elsewhere. Then in the render function you can save the data to a local scope set of variables (or an array or List if you want) and apply the transformations using good old mathematical operators. Then you can draw the polygon using this new data.

# Answer
> 0 votes
I'm not sure I completely understand, but if you say you want to update your polygons coordinates to `polygon.x - Camera.x, polygon.y - Camera.y` and `translate` expects a *delta*, wouldn't then

```
translate(-Camera.x, -Camera.y)

```

be what you're after?

However, if what you want is to compensate for the camera movement, i.e., have the polygons always be drawn at the same screen coordinates independent of where the camera is, you could try recording the Camera's delta and use that as the parameter for `translate`:

```
// compute camera delta
int deltax = Camera.x - prevCameraX;
int deltay = Camera.y - prevCameraY;

// translate all polygons
for (Polygon polygon : polygons) {
    polygon.translate(deltax, deltay);
}

...

// store current camera position for next tick
prevCameraX = Camera.x
prevCameraY = Camera.y

```

---
Tags: java, collision-detection
---


# Question
Title: Capturing video with sound, from cameras in Unity?
I want to capture video from cameras and save them in Unity. There is a function `Application.CaptureScreenShot()` but it only captures images. There is another function that only captures images, too.

It's said to be possible to capture images and attach them together to make a video file but I think it uses a lot of resources and makes the process heavy and in the end there is still no sound.

I mean ingame cameras not reall cameras. I want to capture videos from game

Is there any other way for me to record sound?

# Answer
I think the best answer for least spend of time is "video capture" plugin that is in asset store for free. but to use it and removing al bugs you have to get "SteamVR" plugin in asset store because "video capture" uses some "SteamVR" feature.
> 1 votes

# Answer
Use what's built into Unity - the video capture API. Note that it says,

> You must enable the WebCam and Microphone capabilities to use the VideoCapture API.

Otherwise google "unity video capture library" - there are some results on the Unity Store.
> 2 votes

# Answer
You could simply create a proper build and do a normal screen recording of the game. Why does it have to be recorded inside Unity?
> -4 votes

---
Tags: unity, camera, video
---


# Question
Title: Unity 5.6.0f3 Inspector Tooltips are off in macOS, is me or everyone the same?
Running latest version (5.6.0f3) in macOS, my tooltips are always misalign to the left of my screen, is me or anyone else also experience the same? And, it is still misalign even after I reset the layout setting to factory default.

Here are the screenshots https://i.stack.imgur.com/vRldI.jpg

---

Update: Filed a bug report.

# Answer
> 1 votes
Update: Fixed in patch release 5.6.0p3 https://unity3d.com/unity/qa/patch-releases?version=5.6

(884238) - Editor: Fixed screen offsets updates for tooltips.

---
Tags: unity, macos
---


# Question
Title: C++ A* Pathfinding help find issue ? (Infinite Loop)
I am trying to debug my pathfinding algorithm I made adjustments to it to try and make it quicker and I broke it again for the 5th time, could someone help me debug it?

It appears to get stuck in an infinite loop, I was using the tutorials here.

Psuedocode I got from here.

I'm sorry I cannot show much to process as it goes, I was just hoping people could decipher the logic.

My heuristic gets CWaypoints using a general square root 1 , 1.4 for adjacent and diagonals and also has a terrain cost, 999 for impassible and 0 for normal, 4 for water, the specific reasons I want to not make a bool to hold whether a waypoint is passible is due to the fact that certain objects in the game can travel anywhere and they will not take the 999 cost.

The grid is also connected top to bottom.

```
void fRetracesteps(vector<CWaypoint*> &Current)
{
    ofstream ostMoveFile;
    ostMoveFile.open("move.txt");
    CWaypoint* path = Current[0];
    int MAX_MOVES = 0;

    while (path != 0 && MAX_MOVES <= 200)
    {
        cout << path->ret_posX() << ":" << path->ret_posY() << endl;
        ostMoveFile << path->ret_posX() << " " << path->ret_posY() << "\n";
        path = path->m_parent;
        MAX_MOVES++;
    }
    ostMoveFile.close();
}

void pf_foreach(int current_x, int current_y, int top_x, int top_y, int dest_x, int dest_y, vector<vector<CWaypoint*>> &myvec, deque<CWaypoint*>&OPEN, deque<CWaypoint*>&CLOSED, vector<CWaypoint*> &Current, CWaypoint &pState )
{

    current_x = Current[0]->ret_posX();
    current_y = Current[0]->ret_posY();
    // for each
    const int dx[8] = { 1, 1, 0, -1, -1, -1, 0, 1 };
    const int dy[8] = { 0, 1, 1, 1, 0, -1, -1, -1 };
    const float manhattan[8] = { 1.0f, 1.41f, 1.0f, 1.41f, 1.0f, 1.41f, 1.0f, 1.41f };
    //cout << pos_x << " : " << pos_y << endl;

    for (int i = 0; i < 8; i++)
    {
        int nx = current_x + dx[i];
        int ny = current_y + dy[i];

        if (nx == dest_x && ny == dest_y)
        {
            cout << "goal found" << endl;
            continue;
        }

        if (nx > top_x - 1)
        {
            nx = 0;
        }
        if (nx < 0)
        {
            nx = top_x - 1;
        }
        if (ny > top_y - 1)
        {
            ny = 0;
        }
        if (ny < 0)
        {
            ny = top_y - 1;
        }

        // if its already on closed list dont do

        pState.m_parent = myvec[current_x][current_y];
        cout << "X:" << nx << ":Y:" << ny << " ";
        cout << "Parent: " << current_x << ":" << current_y << endl;;

        pState = CWaypoint(0, 0, 0, 0, 0);
        pState.set_posX(nx);
        pState.set_posY(ny);
        pState.set_waypoint_coords(myvec[nx][ny]->GetX(), myvec[nx][ny]->GetY(), myvec[nx][ny]->GetZ());
        pState.mAccumulatedCost = myvec[nx][ny]->mAccumulatedCost;
        pState.mHeuristic_Manhattan = manhattan[i];
        pState.mvalue_f = pState.mHeuristic_Manhattan + pState.mAccumulatedCost + pState.ret_terraincost();

        bool check = false;
        // If its not on open list, add to open list
        for (auto ceg = OPEN.begin(); ceg != OPEN.end(); ++ceg)
        {
            if ((*ceg)->ret_posX() != nx && (*ceg)->ret_posY() != ny)
            {
                if ((*ceg)->ret_f_cost() < pState.ret_f_cost())
                {
                 check = true;
                }
            }
        }
        bool check2 = false;
        for (auto ceg = CLOSED.begin(); ceg != CLOSED.end(); ++ceg)
        {
            if ((*ceg)->ret_posX() != nx && (*ceg)->ret_posY() != ny)
            {
                if ((*ceg)->ret_f_cost() < pState.ret_f_cost())
                {
                 check2 = true;
                }
            }
        }

        if (check)
        {
            continue;
            check = false;
        }
        if (check2)
        {
            continue;
            check2 = false;
        }

        cout<<":"<< pState.m_parent << endl;
        //cout << "Accumu: " << pState->mAccumulatedCost << endl;
        //cout << "Accumu: " << pState->mHeuristic_Manhattan << endl;
        OPEN.push_front(new CWaypoint(pState));
        pState.resetall();

        //cout << "Pushing " << &myvec[nx][ny] << endl;

    }
}

bool cmp(CWaypoint *lhs, CWaypoint *rhs)
{
    return lhs->ret_f_cost() < rhs->ret_f_cost();
}

void pathfinder(vector<vector<CWaypoint*>> &myvec, int start_x, int start_y , int dest_x, int dest_y, EntityUnit Unit, int top_x , int top_y)
{
    // Pseudocode
    // initialize the open list
    // initialize the closed list
    deque<CWaypoint*>OPEN;
    deque<CWaypoint*>CLOSED;
    vector<CWaypoint*> Current;
    CWaypoint pState(myvec[start_x][start_y]->GetX(), myvec[start_x][start_y]->GetY(), myvec[start_x][start_y]->GetZ(), start_x, start_y);
    pState.set_cost(0);
    // push the initial state on the open list
    // current node in open list with lowest F Cost
    OPEN.push_back(new CWaypoint(pState));
    cout << "pushing first node onto open list" << endl;

    // Values Value_G = Manhattan Distance = mHeuristic_Manhattan
    // Value: Value_MC = Movement Cost Heuristic  = mNodeCost
    // Value: Value_F = H + MC = m_valuef
    string unittype = to_string(Unit.UDReturnUnitType()); // get unit type so we can know what kind of terrain it likes

    int current_x = start_x;
    int current_y = start_y;
    bool reached_target = false;

    // look for lowest cost on open list

    float last_f_cost = 999;
    float current_f_cost = 0;

    current_f_cost = 1;

    // While open list is not empty
    int max_range = 0;
    bool dest_found = false;
    while (OPEN.empty()!= true && dest_found == false)
    {
        // find the node with the least f on the open list and call it p
        pState = *OPEN[0];
        Current.push_back(new CWaypoint(pState));
        std::sort(OPEN.begin(), OPEN.end(), cmp);
        // pop p off the open list
        OPEN.pop_front();

        if (Current[0]->ret_posX() == dest_x && Current[0]->ret_posY() == dest_y)
        {
            cout << "dest found" << endl;
            dest_found = true;
            fRetracesteps(Current);
            continue;

        }
        pf_foreach(pState.ret_posX(), pState.ret_posY(), top_x, top_y, dest_x, dest_y, myvec, OPEN, CLOSED, Current, pState);
        Current.clear();
        CLOSED.push_back(new CWaypoint(pState));
        max_range++;
    }

}

```

Waypoint Class

```
class CWaypoint
{

    int pos_x = 0; // position in grid
    int pos_y = 0;
    float x = 0;
    float y = 0;
    float z = 0;

    float terrainCost = 0; // this cost is determined by terrain type, which is used in the A* pathfinding
    float f_cost = 0;

    float influence = 0;
    string current_owner = "NULL";
    string waypointname = "WP";
    string wp_terraintype = "NULL";
    vector <CWaypoint *> connected_nodes;

    // LAND
    // WATER
    // MOUNTAIN
    // NULL - not passible
    // AIR
    // NUKE

public:
    // Values for pathfinder
    int cubesnumber;
    float mAccumulatedCost = 0;
    float mHeuristic_Manhattan = 0;
    float mvalue_f = 0;
    CWaypoint* m_parent;
    // ---------------------------------
    CWaypoint(float _x, float _y, float _z, int _pos_x, int _pos_y)
    {
        x = _x;
        y = _y;
        z = _z;
        pos_x = _pos_x;
        pos_y = _pos_y;
        stringstream ss;
        ss << "WP " << x << ":" << y << ":" << z;
        waypointname = ss.str();
    }

    ~CWaypoint()
    {

    };

    void set_waypoint_coords(float _x, float _y, float _z)
    {
        x = _x;
        y = _y;
        z = _z;
    }

    float ret_terraincost() const
    {
        return terrainCost;
    }

    void set_cost(float cost)
    {
        this->terrainCost = cost;
    }

    float ret_f_cost() const
    {
        return f_cost;
    }

    void set_f_cost(float cost)
    {
        f_cost = cost;
    }

    void find_adjacent_nodes(vector<vector< CWaypoint*>> TheWaypoints, int top_x, int top_y)
    {
        // function adds the adjacent nodes to it and top_x and top_y is the maximum boundary of the grid so if it goes over, the node will connect to the bottom
        // node beneath it goes over the top, or if over the right, goes back to the left, effectively wrapping the nodes around the sphere for the pathfinding
        const int dx[8] = { 1, 1, 0, -1, -1, -1, 0, 1 };
        const int dy[8] = { 0, 1, 1, 1, 0, -1, -1, -1 };
        //const float cost[8] = { 1.0f, 1.41f, 1.0f, 1.41f, 1.0f, 1.41f, 1.0f, 1.41f }; - important but we dont do the calculation here
        //cout << pos_x << " : " << pos_y << endl;
        for (int i = 0; i < 8; i++)
        {

            int nx = pos_x + dx[i];
            int ny = pos_y + dy[i];

            // wrapper
            if (nx > top_x -1)
            {
                nx = 0;
            }
            if (nx < 0)
            {
                nx = top_x -1;
            }
            if (ny > top_y -1)
            {
                ny = 0;
            }
            if (ny < 0)
            {
                ny = top_y -1;
            }

            //cout << nx << " : " << ny << endl;
            connected_nodes.push_back(TheWaypoints[nx][ny]);
        }
        //cout << "_________" << endl;
    }

    int ret_posX() const
    {
        return pos_x;
    }

    void set_posX(int pos_x)
    {
        this->pos_x = pos_x;
    }

    int ret_posY() const
    {
        return pos_y;
    }

    void set_posY(int pos_y)
    {
        this->pos_y = pos_y;
    }

    float GetX() const
    {
        return x;
    }

    float GetY() const
    {
        return y;
    }

    float GetZ() const
    {
        return z;
    }

    string returnterraintype()
    {
        return wp_terraintype;
    }

    void setterraintype(string wt)
    {
        wp_terraintype = wt;
    }

    int return_terrain_cost()
    {
        if (wp_terraintype == "LAND")
        {
            terrainCost = 1;
            return 1;
        }
        if (wp_terraintype == "WATER")
        {
            terrainCost = 4;
            return 4;
        }
        if (wp_terraintype == "MOUNTAIN")
        {
            terrainCost = 6;
            return 6;
        }
        if (wp_terraintype == "NULL")
        {
            terrainCost = 999;
            return 999;
        }
        if (wp_terraintype == "NUKE")
        {
            terrainCost = 0;
            return 0;
        }
        if (wp_terraintype == "AIR")
        {
            terrainCost = 0;
            return 0;
        }
    }

    void resetall()
    {
         pos_x = 0; // position in grid
         pos_y = 0;
         x = 0;
         y = 0;
         z = 0;

         terrainCost = 0; // this cost is determined by terrain type, which is used in the A* pathfinding
         f_cost = 0;

         influence = 0;
         current_owner = "NULL";
         waypointname = "WP";
         wp_terraintype = "NULL";
    }

    void CWaypointSetup(float _x, float _y, float _z)
    {
        x = _x; y = _y; z = _z;
    }
};

```

# Answer
> 2 votes
Several issues with your code.

1. The code is executed top to bottom in several places there are bits of code that that just don't make sense.

In the for\_each function there are a few ifs that test on a `check` variable and immediately continue, When that happens they variable isn't reset.

At the start of the pathfinder while loop you first copy the front of the open set and then sort and pop\_front it. Instead you will want to sort then copy the front and after that pop\_front.
2. You never add the destination to the open set at all **so it can never be selected from it**.
3. You used `using namespace std;` at some point, that's a bad habit to get into as it paves the way to name conflicts down the line.
4. Your code leaks like a sieve, you don't `delete` anything you have `new`ed.

In fact you don't need to allocate any new CWaypoints during pathfinding at all.

---
Tags: c++
---


# Question
Title: UE4 How to Avoid Boundary Seams with Multiple Refractive Meshes
We use multiple box meshes to create our game world in Unreal Engine 4, but we also use those boxes with translucent/sss materials with refraction. The problem is there are seams between those boxes but want to combine those meshes to make them behave like one big mesh while rendering. We don't want to leave our boxed layout.

Those boxes use all exactly the same material by the way.

Thank you for your help.

# Answer
You don't say if your boxmodel uses separate materials per face - if not, I suggest that you do this. Then pre-pass each face before drawing the block, checking for a water block against each face; if a water block exists, use a nodraw material on that face.

This is essentially what Minecraft does every time it needs to redraw a block, it constructs the block from separated faces then determines face visibility based on various criteria.

Edit: to do this, some prep work is needed. Your box model should be unwrapped with a Multi-Sub Material (assuming 3DSMax here, search for the term in your 3D modeling app of choice) and with a different material id on each face - giving six material ids. Now you have the ability to put a different material on each face. Next, import into Unreal and create the six materials (or basically two materials - one water, one nodraw). Apply these materials to the box faces in the StaticMesh Editor. Then, at runtime and when you do your box visibility calculations, you can examine each face and determine what material it should display: I imagine something like "if face is \>orthogonal to camera direction, or if next block in this face's normal direction is the same as this block, then use nodraw; otherwise use water".

This should give you what you need, at least at a basic level - enough for you to begin modifying, anyway. I cannot give node setups because I don't know your current implementation so I've tried to be as descriptive as possible.
> 2 votes

---
Tags: shaders, unreal-4, transparency, materials
---


title: Unity, choosing a mobile shader

text:
# Question
Title: Unity, choosing a mobile shader
I have multiple 3d objects in my scenes. These are without any graphics and have different colors and some lights.

I was building all of the scenes with a standard shader and now, when running on an Android device, FPS drops to 30-50. I've already fixed the particles with `Mobile` shaders, these work well now but I have some problems with normal cubes, spheres etc.

As I read, `Standard shader == death` on mobiles and here comes my question. I read that I should use one of these from `Mobiles` tab or `Legacy` ones.

Which one is better in my case? Which one should I use when I only want to adjust the color of the object ( + support a lightmap ) ?

# Answer
> 3 votes
There is no `Mobile` shader which will only adjust the color of the object, you must write your own custom shader or modify Unity's build-in shaders. If you only want that "color shader" here is the code for that shader.

```
Shader "Custom/ColorShader" {
Properties {
    _Color("Color", Color) = (1.000000,1.000000,1.000000,1.000000)
}
SubShader {
    Tags
{
    "RenderType"="Opaque"
}
    LOD 150

    CGPROGRAM
    // Physically based Standard lighting model, and enable shadows on all light types
    #pragma surface surf Lambert noforwardadd

    float4 _Color;

    struct Input {
        half color : COLOR;
    };
    void surf (Input IN, inout SurfaceOutput o) {
        o.Albedo = _Color;
    }
    ENDCG
}
FallBack "Diffuse"  }

```

To create that shader you need to go to `Create->Shader->Standard Surface Shader`.Open it in some code editor ,delete all existing code and paste this code. Now you can use this shader for your materials choosing it from `Custom` menu.

---
Tags: unity, shaders, performance, mobile
---


title: cron jobs for MMO browser game

text:
# Question
Title: cron jobs for MMO browser game
I have to implement cron jobs in to my MMO browser game. Its like in Travian game - you build something, and wait few minutes or hours.. But the problem is, that cron job shedulers made to be sheduled every second/minute/day etc.. But in my game i need to shedule thousands of the same jobs, which must run separately and after some unique time to be released. So far i am unlucky with that idea. I am using Node.js and I just tried so many node shedulers, they seem are not supposed to have thousands of jobs.. I can run few unique only. I trough maybe then i can make like - cron job, which runs every 1 second and checks the Redis DB for any finished proccess. But that sounds crazy.. if i have few jobs only and they are in 24 hous only, my server checks that every 1 second.. Any ideas what should i do?

---

So far, the best option would be to remove cron jobs. I was doing some my processes without cron jobs. But other processes were really hard to calculate, and it was much easier with cron jobs. But i trough deeper and i think it is possible to calculate eveyrthing and simulate everything without cron jobs.

For example, the user has ressources inside Stats model. And i have hourly ressource income there. If the user wants to build anything, for example, traps, i have to recalculate the user ressources and save new value, set the new updatedAt. This is how i am updating my user ressources (inside Stats model), when some user wants to build a trap.

```
Stats.findOne({user_id: user_id}).exec(function (err, newstats){
  var time_in_ms = (new Date()).getTime() - new Date(newstats.updatedAt).getTime();
  var ressources_per_second = (newstats.base_income + newstats.field_income) / 60 / 60;
  var current_ressources = newstats.resources + parseInt(time_in_ms / 1000 * ressources_per_second) - traps_price;
  if(current_ressources < traps_price) return res.ok();
  Stats.update(newstats.id, {resources: current_ressources});
});

```

# Answer
> 4 votes
Do lazy evaluation of player build progression.

Whenever you need to retrieve the state of a player from your database for any reason, check how old that state is, progress the time which elapsed since the last save, and then put it back into the database.

For example: The current timestamp is `2017-06-15 15:49:23`. You want to know how many windmills player 16433531 has. You retrieve the state from the database and it looks something like this:

```
{
    last_update: "2017-06-15 12:48:03",
    windmills: 12,
    active_tasks: [
         { task: "build_windmill", time_left: "0:23:12" },
         { task: "recruit_swordman", time_left: "14:48:33" }
    ]
}

```

You check the `last_update` timestamp and notice that this state is 3 hours, 1 minute and 20 seconds old. So you advance it by 3 hours, 1 minute and 20 seconds by simulating their progress during his timespan. During that time, the windmill they are currently building is finished. So afterwards your state looks like this:

```
{
    last_update: "2017-06-15 15:49:23",
    windmills: 13,
    active_tasks: [
         { task: "recruit_swordman", time_left: "11:47:13" }
    ]
}

```

Use this for whatever you are doing right now and also put it back into the database.

The advantage of this method over regular cronjobs is that you no longer waste time with updating the states of any players which are of no interest for anyone right now. So your total server load only depends on your current active users, not your total registered users. Considering that most online games accumulate a huge amount of dead accounts over their running history, this will really save you a lot of server capacity.

Also, updating longer timespans in bulk is likely faster than doing many frequent updates because they allow you to make a lot of optimizations. When a player has an income of 2 gold per second and you need to process 3000 seconds of game time, then incrementing their gold once by 6000 requires far less CPU time than incrementing it 3000 times by 2. And that doesn't account for the huge overhead the cron job scheduling system will cause for running a job every second.

---
Tags: javascript, mmo, node.js, mmorts
---


# Question
Title: Bouncing off edge in libGDX doesn't work after resizing window
I have a game in which the enemy has to bounce of the edge, when it hits it. It is working fine, normally, but when I resize the window, the bouncing breaks. It doesn't bounce properly.

In the image, the red enemy is not in the screen. How would I make it bounce off properly even after resizing the window?

---

Here is my `BasicEnemy` code:

```
public class BasicEnemy extends Enemy {

    public BasicEnemy(Player player, float x, float y) {

        super(player, new TextureRegion(), x, y, 5, 5);
        width = 16;
        height = 16;
    }

    @Override
    public void tick(float dt) {

        wrapPos();
        if (touchesPlayer())
            player.setHealth(player.getHealth() - 1);

        x += velX;
        y += velY;
    }

    @Override
    public void render(SpriteBatch batch, ShapeRenderer renderer) {

        renderer.setColor(Color.RED);
        renderer.rect(x - width/2, y-height/2, width, height);
    }
}

```

Here is my `Enemy` code:

```
public abstract class Enemy extends Entity {

    protected Player player;

    public Enemy(Player player, TextureRegion region, float x, float y,
        float velX, float velY) {

        super(region, x, y, velX, velY);
        this.player = player;
    }

    @Override
    protected void wrapPos() {

        if (x > Gdx.graphics.getWidth() - width /2 || x < width/2) {

            //Here we flip the speed, so it bounces the other way.
            velX = -velX;
        }

        //Same as above, but with on the y-axis.
        if (y > Gdx.graphics.getHeight() -height/2 || y < height/2) {

            velY = -velY;
        }
    }

    protected boolean touchesPlayer() {

        return getBoundingBox().overlaps(player.getBoundingBox());
    }
}

```

# Answer
> 1 votes
To explain @ShivGames answer, the reason why some viewports work and some don't is because they change the aspect ratio and limit the viewport size. In fact, all viewports "work" except that they cut off the screen, hence why the "walls" are not at the edges of the screen but actually closer / farther apart from the actual edge.

Take a look at the wiki entry for viewports and look at the images there. The gray part is the actual world that was being collided with while the black part is outside, and therefor not part of, the actual game.

# Answer
> 0 votes
All I had to do was make the viewport a `StretchViewport` or a `FitViewport`. `ExtendViewport` didn't work for some reason.

---
Tags: java, libgdx
---


title: How to update Unity?

text:
# Question
Title: How to update Unity?
I have clicked on *check for updates* but it says I have latest Unity.

But latest is 5.6.

How to update it to 5.6?

# Answer
> 3 votes
I have the same problem here. As **Almo** said, you need to download Unity again.

Unity 5.5 can't update to Unity 5.6

If you download the new version and put to install in the same folder it will replace the older version.

---
Tags: unity
---


# Question
Title: Offset on camera following object that accelerates
I have camera a that is actively following an object (a plane) from behind. This object can accelerate or decelerate.

I would like to have a camera offset when I move the plane, so it doesn't look so static.

I have done this with the following code:

```
float cameraOffset = 0.05 * elapsed_time * 100;

Vector3 previousEye = camera->eye;
Vector3 newEye = ship->model * Vector3(0, 10, -5);
Vector3 eye = previousEye * (1 - cameraOffset) + newEye * cameraOffset;

Vector3 previousCenter = camera->center;
Vector3 newCenter = ship->model * Vector3(0, 0, 10);
Vector3 center = previousCenter * (1 - cameraOffset) + newCenter * cameraOffset;

Vector3 up = ship->model.rotateVector(Vector3(0, 1, 0));

camera->lookAt(eye, center, up);
previousModel = ship->model;

```

It works fine, except that when I increase the object's speed, the camera barely follows it. This is of course logical; my code is supposed to make it difficult for the camera to follow the plane.

However, I would like to have a lateral camera offset and also to keep following the plane from a relatively short distance.

Any hint on how to achieve this is appreciated.

# Answer
> 0 votes
I have something similar in a 2D game I'm making in Unity, but instead I am changing the transform using the Mathf.Lerp function. This interpolates between two numbers. I record my current position, and interpolate to the position I want the camera to be. Mathf.SmoothStep does the same thing but has some more smoothing added in.

I hope this helps. I am very new to this ;D

---
Tags: opengl, c++, mathematics, camera, game-mechanics
---


# Question
Title: Choosing frame rate in PyGame with keyboard input
Using PyGame, I want to create a moving square which moves in a grid, controlled by keyboard presses of the arrows. So, pressing the "up" key moves the square to the cell directly upwards, pressing the "right" key moves the square to the cell directly to the right, etc.

In my loop, I use `pygame.time.wait(x)`, to pause for `x` ms. However, choosing the correct value for `x` is proving difficult. If `x` is too large (e.g. 1000), then the square does not respond immediately, and I actually have to hold down the key to get it to move. But if `x` is too small (e.g. 10), then the square will move several times in a row whenever I press a key. But I just want the square to move once for every key press. How can I do this? Thanks!

Below is the important part of my code:

```
    x = 100
    current_pos = [0, 0]

    while True:

        pygame.event.pump()  # process event queue
        is_key_pressed = pygame.key.get_pressed()

        if is_key_pressed[pygame.K_UP]:
            current_pos[1] -= 1

        elif is_key_pressed[pygame.K_RIGHT]:
            current_pos[0] += 1

        elif is_key_pressed[pygame.K_DOWN]:
            current_pos[1] += 1

        elif is_key_pressed[pygame.K_LEFT]:
            current_pos[0] -= 1

        show_map(current_pos)

        pygame.time.wait(x)

```

# Answer
Use an event loop to move the object a given distance per key press. Also, to limit the frame rate you should instantiate a `pygame.time.Clock` and call its `tick` method. `pygame.time.wait` makes your program unresponsive for the passed time interval.

```
import sys
import pygame as pg

def main():
    screen = pg.display.set_mode((640, 480))
    # Instantiate a Clock to control the frame rate.
    clock = pg.time.Clock()
    player_rect = pg.Rect(0, 380, 90, 90)

    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            if event.type == pg.KEYDOWN:
                if event.key == pg.K_RIGHT:
                    player_rect.x += 100
                if event.key == pg.K_UP:
                    player_rect.y -= 100

        screen.fill((60, 60, 60))
        pg.draw.rect(screen, (120, 190, 90), player_rect)
        pg.display.flip()
        clock.tick(30)  # Limit the frame rate to 30 fps.

if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()
    sys.exit()

```
> 1 votes

---
Tags: python, pygame
---


# Question
Title: Games developed in Python with Pygame lags too much; how can I improve the framerate?
I'm currently working on a very simple RPG game but when I try to load all the tile images for the background, the game lags to the point it freezes (framerate drops to 0 or will just crash). The tiles are 40x40 .png images and are contained in the tiles folders.

The game is divided in 3 files:

Structure of the project:

main.py:

```
import pygame
import sys
import time
from textures import *
from globalsvar import *

pygame.init()

cSecs = 0
cFrame = 0
fps = 0
black = (0, 0, 0)

map_data = []

for x in range(0, 32):
    for y in range(0, 24):
        map_data.append([x, y, "2"])

clock = pygame.time.Clock()

tile_size = 25

info_font = pygame.font.SysFont("Verdana", 20)

class Mage:
    def __init__(self, location):
        self.x, self.y = location
        self.name = "Character"
        self.image = pygame.image.load("graphics\\sprites\\ninja_left.png")
        self.x_update = 0
        self.y_update = 0
        self.mage_width_dif = win_width - self.image.get_width()
        self.mage_height_dif = win_height - self.image.get_height()

    def draw_self(self):
        window.blit(self.image, (self.x, self.y))

    def update(self):
        self.x += self.x_update
        self.y += self.y_update

def create_window():
    global window, win_height, win_width, win_title
    win_width, win_height = 800, 600
    win_title = "A Little RPG Game"
    pygame.display.set_caption(win_title)
    window = pygame.display.set_mode((win_width, win_height), pygame.HWSURFACE|pygame.DOUBLEBUF)

def draw_grid_terrain():
for x in range(-900, 1800, tile_size):
    for y in range(-900, 1800, tile_size):
        for i in map_data:
            tile = (i[0]*Tiles.File_size, i[1]*Tiles.File_size)
            if (x, y) == tile:
                window.blit(Tiles.Texture_Tags[i[2]], (x + Globals.camera_X, y + Globals.camera_Y))

def show_fps():
    fps_overlay = info_font.render(str(fps), True, black)
    window.blit(fps_overlay, (10, 10))

def fps_manager():
    global cFrame, fps, cSecs, deltaTime

    if cSecs == time.strftime("%S"):
        cFrame += 1
    else:
        fps = cFrame
        cFrame = 0
        cSecs = time.strftime("%S")

gameRunning = True

create_window()

character = Mage((win_width/2, win_height/2))

while(gameRunning):

    if character.x + character.x_update >= character.mage_width_dif or character.x + character.x_update <= 0:
        character.x -= character.x_update

    if character.y + character.y_update >= character.mage_height_dif or character.y + character.y_update <= 0:
            character.y -= character.y_update

    if character.y > ((75 * win_height)/100):
        Globals.camera_MOVE = 1
    elif character.y < ((5 * win_height)/100):
        Globals.camera_MOVE = 2
    elif character.x > ((75 * win_width)/100):
        Globals.camera_MOVE = 3
    elif character.x < ((5 * win_width)/100):
        Globals.camera_MOVE = 4
    else:
        Globals.camera_MOVE = 0

    if Globals.camera_MOVE == 1:
        Globals.camera_Y -= 3.5

    elif Globals.camera_MOVE == 2:
        Globals.camera_Y += 3.5

    elif Globals.camera_MOVE == 3:
        Globals.camera_X -= 3.5

    elif Globals.camera_MOVE == 4:
        Globals.camera_X += 3.5

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

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT or event.key == pygame.K_a:
                character.x_update = -1
            elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:
                character.x_update = 1
            elif event.key == pygame.K_UP or event.key == pygame.K_w:
                character.y_update = -1
            elif event.key == pygame.K_DOWN or event.key == pygame.K_s:
                character.y_update = 1

        if event.type == pygame.KEYUP:
            if (event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT
                    or event.key == pygame.K_a or event.key == pygame.K_d):
                character.x_update = 0
            elif (event.key == pygame.K_DOWN or event.key == pygame.K_UP
                  or event.key == pygame.K_w or event.key == pygame.K_s):
                character.y_update = 0

    clock.tick(60)
    draw_grid_terrain()
    character.update()
    character.draw_self()
    fps_manager()
    show_fps()
    pygame.display.update()

pygame.quit()
sys.exit()

```

textures.py:

```
import pygame

pygame.init()

class Tiles:
    File_size = 25

    def load_textures(file, size):
        bitmap = pygame.image.load(file)
        bitmap = pygame.transform.scale(bitmap, (size, size))
        surface = pygame.Surface((size, size), pygame.HWSURFACE|pygame.SRCALPHA)
        surface.blit(bitmap, (0, 0))
        return surface

    Grass = load_textures("graphics\\tiles\\grass.png", File_size)
    Ground = load_textures("graphics\\tiles\\ground.png", File_size)
    Water = load_textures("graphics\\tiles\\water.png", File_size)
    Floor = load_textures("graphics\\tiles\\floor.png", File_size)

    Texture_Tags = {"1": Grass, "2": Ground, "3": Water, "4": Floor}

```

globalsvar.py:

```
class Globals:
        camera_X = 0
        camera_Y = 0
        camera_MOVE = 0
        camera_pos_X = 0
        camera_pos_Y = 0

```

Game screenshot:

I read somewhere that I should try loading all the tiles on a surface once and then display said surface, but I don't know how.

Why is my game lagging so much, and how could I improve the framerate?

# Answer
> 1 votes
You should (almost) always call `convert()` or `convert_alpha()` after loading an image to improve the performance.

So instead of `pygame.image.load(file)` do `pygame.image.load(file).convert()` or if the image has transparent parts `pygame.image.load(file).convert_alpha()`.

And as mentioned in one of the comments, only load the images once at the program start and then reuse them, because it's slow to load them from the hard drive each frame. **Edit:** Actually, you're not loading the images again and again, because you load them as class attributes which are evaluated at the program start. But this is still important, so I don't remove this recommendation.

---

The suggestions above are just a drop in the ocean, since the main problem is pretty clearly (without profiling) the `draw_grid_terrain` function. It has to iterate 8957952 times per frame.

It's a lot faster to use big surfaces instead of blitting small tiles the whole time. Here's an example in which I first create a big surface and blit the tiles on it (of course you can also create your map in Tiled and then load it in pygame).

I also tried to simplify the rest of the code, especially for the camera. I gave the `Mage` a rect and some vectors which serve to store the position, velocity and camera pos. To check if the player is in the camera area, I also gave him an `area` rect, and if he's outside I use `Rect.clamp_ip` to keep him in this area and move the camera vector.

```
import sys
import pygame as pg

class Mage:

    def __init__(self, location):
        self.image = pg.Surface((TILE_SIZE, TILE_SIZE*2))
        self.image.fill((40, 110, 180))
        self.rect = self.image.get_rect(topleft=location)
        self.pos = pg.math.Vector2(location)
        self.vel = pg.math.Vector2(0, 0)
        self.camera = pg.math.Vector2(0, 0)
        # The area where the player can move without affecting the camera.
        self.area = pg.Rect(100, 100, 600, 400)

    def draw_self(self, window):
        window.blit(self.image, self.rect)

    def update(self):
        """Move the player and the camera."""
        self.pos += self.vel  # Add the vel vector to pos to move.
        # Update the rect, since it's the blit position and is needed to
        # check if the camera should be moved.
        self.rect.topleft = self.pos
        rect = self.rect
        area = self.area
        # If the player has moved outside of the area rect ...
        if rect.left < self.area.left or rect.right > self.area.right:
            self.camera.x -= self.vel.x  # ... move camera.x.
        # The same for the y direction.
        if rect.top < self.area.top or rect.bottom > self.area.bottom:
            self.camera.y -= self.vel.y

        self.rect.clamp_ip(self.area)  # Keep the player in the area.
        self.pos = self.rect.topleft  # Adjust pos after the clamp.

def draw_grid_terrain(surface, map_data):
    """Blit the map tiles on the surface."""
    for row in map_data:
        for rect, tile_type in row:
            surface.blit(TEXTURES[tile_type], rect.topleft)

TILE_SIZE = 32
# The small surfaces that will be blitted on the big surface below.
GRASS = pg.Surface((TILE_SIZE, TILE_SIZE))
GRASS.fill((40, 140, 20))
pg.draw.rect(GRASS, (10, 100, 50), (0, 0, TILE_SIZE, TILE_SIZE), 2)
GROUND = pg.Surface((TILE_SIZE, TILE_SIZE))
GROUND.fill((90, 40, 20))
pg.draw.rect(GROUND, (110, 100, 50), (0, 0, TILE_SIZE, TILE_SIZE), 2)
WATER = pg.Surface((TILE_SIZE, TILE_SIZE))
WATER.fill((40, 70, 170))
pg.draw.rect(WATER, (80, 80, 190), (0, 0, TILE_SIZE, TILE_SIZE), 2)
FLOOR = pg.Surface((TILE_SIZE, TILE_SIZE))
FLOOR.fill((120, 120, 100))
pg.draw.rect(FLOOR, (20, 20, 20), (0, 0, TILE_SIZE, TILE_SIZE), 2)

TEXTURES = {'1': GRASS, '2': GROUND, '3': WATER, '4': FLOOR}

# The map is a list of lists which contain pg.Rects and the tile_type.
MAP_DATA = [[(pg.Rect(TILE_SIZE*x, TILE_SIZE*y, TILE_SIZE, TILE_SIZE), '2')
             for x in range(128)]
            for y in range(128)]
MAP_DATA[4] = [(rect, '1') for rect, _ in MAP_DATA[4]]  # A grass row.
MAP_DATA[20] = [(rect, '3') for rect, _ in MAP_DATA[20]]  # Water.
MAP_DATA[27] = [(rect, '4') for rect, _ in MAP_DATA[27]]  # Floor.
# Create a big surface with the size of the map.
BACKGROUND = pg.Surface((TILE_SIZE*128, TILE_SIZE*128))
draw_grid_terrain(BACKGROUND, MAP_DATA)  # Blit the tiles on the image.

def main():
    clock = pg.time.Clock()
    width, height = 800, 600
    window = pg.display.set_mode((width, height))
    character = Mage((width/2, height/2))
    game_running = True

    while game_running:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                game_running = False
            if event.type == pg.KEYDOWN:
                if event.key in (pg.K_LEFT, pg.K_a):
                    character.vel.x = -3
                elif event.key in (pg.K_RIGHT, pg.K_d):
                    character.vel.x = 3
                elif event.key in (pg.K_UP, pg.K_w):
                    character.vel.y = -3
                elif event.key in (pg.K_DOWN, pg.K_s):
                    character.vel.y = 3
            if event.type == pg.KEYUP:
                if event.key in (pg.K_LEFT, pg.K_RIGHT, pg.K_a, pg.K_d):
                    character.vel.x = 0
                elif event.key in (pg.K_DOWN, pg.K_UP, pg.K_w, pg.K_s):
                    character.vel.y = 0

        character.update()
        # Just blit the background image instead of the single tiles.
        # Adjust its position by the character's camera vector.
        window.blit(BACKGROUND, (0, 0)+character.camera)
        character.draw_self(window)
        pg.display.set_caption('FPS: {}'.format(clock.get_fps()))
        pg.display.update()
        clock.tick(60)

if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()
    sys.exit()

```

---
Tags: python, pygame
---


title: Are there 3x3 matrices in DirectX 11?

text:
# Question
Title: Are there 3x3 matrices in DirectX 11?
I have a parameter in HLSL shader in a constant buffer which is a `float3x3`. Is there is 3x3 matrix struct in Directx 11 or should I use 4x4 matrix instead, and if so, how?

# Answer
> 4 votes
D3D11 itself doesn't have any matrix structures at all; you might be thinking of the DirectXMath library's matrix classes. It *does* have a 3x3 matrix type you can use.

In general, you can store a 3x3 matrix in the upper-left of a 4x4 matrix (setting the bottom-right-most element to 1) *if* that 3x3 is only storing scale and/or rotation in 3D. If you were storing a 2D translation in there or anything else, you'd have to rebuild the 4x4 matrix appropriately based on whatever data you were putting into the 3x3 matrix.

---
Tags: c++, directx11, hlsl
---


# Question
Title: Transform inertia tensor using quaternion
I have inertia tensor T in body coordinates and quaternion q for the body. I know I can transform T to world coordinate by converting quaternion to rotation matrix R and then use the relation (R * T * R^T). However this seems unnecessarily expensive and unwieldy (especially if you are doing this often).

So my question is:

How do I transform inertia tensor from body to world coordinate directly using quaternion and without having to generate rotation matrix from quaternion?

# Answer
> 2 votes
I finally found the answer in this document. The idea is that you can indeed define multiplication of quaternion and matrix as follows: Take 4x4 matrix M and view each of its column as quaternion m\_j. Now you can define q.M by multiplipliting two quaternions q and m\_j and putting the result quaternion as jth column in to 4x4 result matrix. Now to tranform inertia matrix J from body frame to world frame using quaternion q, one can use following relationship:

`(q.(q.J.q*)^T).q*)^T`

One step I'm hazzy about is how do you convert inertia matrix from 3x3 to 4x4. My assumption is that you do this simply by inserting 1 in extra diagonal element and everything else 0. This extra 1 would correspond to same location as w component of q. I haven't tested this yet.

# Answer
> 1 votes
3D Physics computations are messy and unwieldy. There is no avoiding that.

However, you still have a couple of choices, once you are comfortable bouncing between coordinate systems.

1. Compute your impulses locally, which means inertia tensor never needs to be changed. To do this means transforming contact points to local space for each body.

`M = inv(M), cpLocal = M * cp, J = compute impulse, W += I * J`

2. Compute your impulses in world space, then transform then to local space for each body. This means taking the inverse of your model transform and multiplying the impulse by it.

`Mi = mat3( inv( M ) ), Jlocal = Mi * J, W += I * Jlocal`

3. Compute in world space, and transform the inertia tensor to world space then use that to adjust the angular effects. This is :

`M3I = M3( rot_toM4 ) * I, W += M3I * J`

I will point out, by the way, that many engines do not try to model the inertia of a shape perfectly, and will fudge the numbers, so no rotation of the inertia tensor is necessary.

---
Tags: rotation, matrix, transformation, quaternion
---


# Question
Title: How do I create random game objects on a terrain, but only inside the terrain area?
I have the following code that generates game objects, in my game. The problem with it is that some game objects are out of the terrain area. I want to place them at random, but also make sure they will be inside the terrain area.

I know that I get the terrain size with `terrain.terrainData.size`, but I'm not sure how to use it. How do I create random game objects on a terrain, but only inside the terrain area?

---

Here is my current script:

```
using UnityEngine;

public class Teleport : MonoBehaviour
{
    public Vector3 terrainArea;
    public float spinSpeed = 2.0f;
    public int cloneTeleportations;
    public GameObject prefab;

    private bool rotate = false;
    private bool exited = false;
    private Transform[] teleportations;
    private Random rnd = new Random();

    private void Start()
    {
        GameObject go = GameObject.Find("Terrain");
        Terrain terrain = go.GetComponent(Terrain);
        terrainArea = terrain.terrainData.size;

        for (int i = 0; i < cloneTeleportations; i++)
        {
            GameObject Teleportaion = Instantiate(prefab,
                new Vector3(Random.Range(i * 10.0F, i * 50.0F), 0,
                Random.Range(i * 10.0F, i * 50.0F)), Quaternion.identity);
            Teleportaion.transform.parent = this.transform;
            Teleportaion.transform.tag = "Teleportation";
        }
    }
}

```

# Answer
> 1 votes
In order to restrict your instantiated objects to the confines of the terrain; you need to use the measurements of the terrain during the randomise method used to determine the position of each instantiated object. Your pretty much already there - we just need to implement a bit more little maths. Specifically, the boundary of the terrain.

### Determining the boundary of the Terrain

We already find the size of the terrain with `Terrain.terrainSize.size`; this gives us the measurements of the terrain, in world space. You will also notice that the terrain appears, in your scene view, to expand outwards from the core game object. That is, your "origin" is at the bottom left corner. We can thus use `transform.position` to find our complete boundary.

The boundary of the terrain can thus be described as `transform.position.x` to `transform.position.x + terrain.terrainSize.size.x`, along the x axis, and `transform.position.z` to `transform.position.z + terrain.terrainSize.size.z`, along the z axis.

### Using the Terrain boundary to limit object placement

Now that we have the boundary, all we need to do is provide this boundary when we randomly place instantiated objects. At this point, we do not really have much use for the `i` indexor, so I have moved instantiate into its own method. All `i` does, in the functionality you provide, is extrapolate the range of our instantiated position. As such, it works against us for setting the game objects to the confines of the terrain.

```
private float xMinimum, xMaximum, zMinimum, yMinimum;

private void Start()
{
    // ... Get Terrain reference and terrainArea

    xMinimum = transform.position.x;
    zMinimum = transform.position.z;
    xMaximum = xMinimum + terrainArea.x;
    zMaximum = zMinimum + terrainArea.z;

    for (int i = 0; i < cloneTeleportations; i++)
    {
        InstantiateGameObject();
    }
}

private void InstantiateGameObject()
{
    GameObject newGameObject = Instantiate(prefab,
        new Vector3(Random.Range(xMinimum, xMaximum), 0,
        Random.Range(zMinimum, zMaximum)), Quaternion.identity);

    newGameObject.transform.parent = this.transform;
    newGameObject.transform.tag = "Teleportation";
}

```

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


title: Find points inside a closed area

text:
# Question
Title: Find points inside a closed area
I have a 2D rectangular grid (100x100) with 3 types of cell (Empty, Base and Outline). I need to find cells inside the territory formed by Base and Outline cells.

For example, in this scheme:

I need to find the yellow cells.

The same algorithm, but with hexagonal grid, was implemented in the game in this YouTube video: https://youtu.be/6zyMHnBM5x8.

Any help on how to achieve that would be very helpful. Thanks.

# Answer
You should call this function only when needed, to save on CPU cycle.

Based on the video you linked, there must be a mechanism that determines the first outline cell, the last one, and the cell path in the grid. You need to keep track of the cursor status, in particular we need to know whether the outline cells have became a closed shape along with the base line.

**Phase 1 - Reducing the working area**
Every time a cell path is completed, we compute the AABB vertex coordinates enclosing the outline cells along with the base cell blobs our outline is tangent with. This way we can reduce the grid sector affected by an outline adjunction in the set.

For example, in your image (assuming `(0,0)` as top leftmost corner), we find the rectangle from `(5,2)` to `(14,10)` to contain the outline cells; and the rectangle with vertices `(4,5)` and `(11,12)` to be the one containing the base cells. Then, the area of interest will be from `(4,2)` to `(14,12)` since the floodfill will certainly happen within this area of the grid (this reduces complexity slightly).

**Phase 2 - Find the enclosed blob**
Now you have a subgrid with a border-like shape and two possible surface: the inner and the outer ones. It's easy to determine the one we are interested in: every single cell belongs either to the first or the second one; also, cells lying on the subgrid borders will belong to the outer surface, unless there were not even one of those, which means there is one only, inner surface (and we were looking right for this one).
> 2 votes

# Answer
You should use a hunt and eliminate type algorithm.

Basically, you search through the whole grod until you find an empty space (or something that you search for), then use floodfill and mark every positiom the fill reaches. Continue searching until you find an unmarked empty cell. You have to repeat this until the search reaches the end of the map.
> -2 votes

---
Tags: unity, algorithm, geometry, grid
---


# Question
Title: Why does the debug say my assigned field "is never assigned to, and will always have its default value 'null'"?
I have an `itemData` class that stores the data for a couple of items. It looks something like this:

```
public class ItemData : MonoBehaviour
{
    public List<Item> items;

    [SerializeField] private Sprite itemOneSprite, itemTwoSprite, itemThreeSprite;

    void Awake()
    {
        items = new List<Item>();

        Item itemOne = new Item(0, "Item 1", itemOneSprite);
        items.Add(itemOne);

        Item itemTwo = new Item(1, "Item 2", itemTwoSprite);
        items.Add(itemTwo);

        Item itemThree = new Item(2, "Item 3", itemThreeSprite);
        items.Add(itemThree);
    }
}

```

I get an error message for `itemTwoSprite` and `itemThreeSprite`, stating that they are null and will always be null:

> Field *name of field* is never assigned to, and will always have its default value 'null'

Oddly, when I check the inspector, those fields are not null. I have manually attached sprites to them. When I debug, I see that they are not null. I get something like "itemTwoSprite(UnityEngine.Sprite)". I can run the game, and things seem to work normally.

The order of the declared Sprite variables seems to be important, as well. For instance, if my line of code looked like `Sprite itemTwoSprite, itemOneSprite, itemThreeSprite`, then `itemOneSprite` and `itemThreeSprite` would bring up error messages. The first one declared seems to be unproblematic.

What could be causing the issue, and how do I fix it? I have isolated the problem into an empty project, and it still persists. The only other script is the item class. To reiterate, the error message does not prevent the game from running, but it pops up in the console from time to time, with the yellow exclamation mark.

# Answer
> 1 votes
I feel it is important to note that I can not replicate this problem. However, this really *isn't* a problem. Your being told that there *might* be a problem - and that you should address it now, instead of later; if we *know* that it is not a problem, this is a non-event.

### What are the yellow exclamation marks?

In Unity, logs marked by a yellow exclamation mark are not errors; they are simply warnings. It is the editors way of letting you know that there *may* be a problem - they pose any issues, by themselves. In this case, it can see that the code does not allow for such references being set; but your providing the references via inspector, so it is not a problem.

As far as I am aware, there is a `#pragma` line you can include in your script to prevent warnings associate with this script; however, this line prevents *all* warnings, and is a general bad idea. These warnings can often be *very* useful. I will not go into it, simply for how dangerous it might be, if you are not completely familiar with your code and all possible outcomes. You can omit them from your debug log, in general, by deselecting the matching exclamation mark symbol to the top right.

---

In this case, it also highlights a generally useful practice; especially in regards to anything that is set via the Inspector: it *might* be useful to *make sure* that your reference has been set, prior to accessing it. That way, at times where the reference *has not* been set, it is much easier to diagnose. Having used Unity for several years, I can personally vouch for a couple of excruciating painful errors that came down to a reference I was *sure* I had set, or otherwise became *unset* due to a change in the script or object.

```
if(itemOneSprite != null)
{
    Item itemOne = new Item(0, "Item 1", itemOneSprite);
    items.Add(itemOne);
}
else
{
    Debug.Log("Warning: itemOneSprite has not been set");
}

```

---

As for why it picks up that particular order in that way, I might speculate that it is simply picking up additional *in-line* members as possible sources of concern. The warning *might* go away if each declaration is on a new line; but that, in itself, is no particular1 reason to do so. Again, I can not confirm this solution, as I do not have the initial warnings when I load your script into my scene. *Unity is sometimes funny, that way*. Nothing to be concerned about.

1 Unless you want to, which in itself, is often a good reason.

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