# Question
Title: How can I rotate a camera on the X and lookat target and once looking at the target to stop slowly the rotation?
This is a screenshot showing the camera position. I want it to rotate slowly smooth to the left and once looking at the soldier to stop rotating.

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

public class SoldierNaviFight : MonoBehaviour
{
    public Camera fightCam;
    public Transform target;
    public float speed = 2f;

    // Use this for initialization
    void Start ()
    {

    }

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

    }
}

```

The script is attached to a empty gameobject. What I want to do is once the camera stopped rotating and looking at the soldier to make the soldier start moving to the right and camera should follow the soldier rotating and keep follow the soldier moving.

The main idea is to create a cut scene. The camera is position at this point just to display the cut scene.

To make the first rotation to the target I tried this:

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

public class SoldierNaviFight : MonoBehaviour
{
    public Camera fightCam;
    public Transform target;
    public float speed = 2f;
    Quaternion targetRotation;

    // Use this for initialization
    void Start ()
    {
        targetRotation = target.rotation;
    }

    // Update is called once per frame
    void Update ()
    {
        Quaternion.RotateTowards(transform.rotation, targetRotation, Time.deltaTime * speed);
    }
}

```

But the camera is not rotating at all.

This is screenshot of the Hierarchy and Inspector:

The script is attached to GameObject: SoldierNaviFight The camera that I want to move is the child of SoldierNaviFight: SoldierNaviFightCamera

UPDATE:

This will rotate the camera but it's rotating it to the right instead to the left to the soldier. Not sure why:

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

public class SoldierNaviFight : MonoBehaviour
{
    public Camera fightCam;
    public Transform target;
    public float speed = 2f;
    Quaternion targetRotation;

    // Use this for initialization
    void Start ()
    {
        targetRotation = target.rotation;
    }

    // Update is called once per frame
    void Update ()
    {
        fightCam.transform.rotation = Quaternion.RotateTowards(fightCam.transform.rotation, targetRotation, Time.deltaTime * speed);
    }
}

```

# Answer
So first off, you need to seperate this kind of logic, otherwise you'll face problems along the way. I would suggest to you, to create a small script, that handles the cut scene stuff, deactivates and than activates unity ready-to-use third person camera setup. Otherwise, if you want to use your own camera script, activate this one instead.

First, create a boolean that checks what kind of status our cutscene has:

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

public class SoldierNaviFight : MonoBehaviour
{
    bool CutSceneStatus = false;

    // Use this for initialization
    void Start ()
    {

    }

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

    }
}

```

To manipulate the camera rotation and position, use transform and Rotate and multiply those by a float and time (almost like you already tried to do)

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

public class SoldierNaviFight : MonoBehaviour
{
    bool CutSceneStatus = false;

// Use this for initialization
void Start ()
{

}

// Update is called once per frame
void Update ()
{
 CheckIfPlayerVisible();
 TransformCamera();
 RotateCamera();
}

void TransformCamera(){

 if(!CutSceneStatus){
 transform.position += new Vector3(30, 0, 0) * speed * Time.deltaTime;
 }
}

void RotateCamera(){
 if(!CutSceneStatus){
 transform.Rotate(0, 30, 0) * Time.deltaTime;
 }
}

void CheckIfPlayerVisible(){

 RaycastHit hit;
    // Does the ray intersect any objects excluding the player layer
    if (Physics.Raycast(transform.position,
    transform.TransformDirection(Vector3.forward), out hit,
    Mathf.Infinity))
    {
        if(hit.gameObject.tag == "Player"){
        Debug.DrawRay(transform.position,
        transform.TransformDirection(Vector3.forward) * hit.distance,
        Color.yellow);
        Debug.Log("Did Hit Player!");

        CutSceneStatus = true;
        }
    }
    else
    {
        Debug.DrawRay(transform.position,
        transform.TransformDirection(Vector3.forward) * 1000, Color.white);
        Debug.Log("Did not Hit");
        }

   void DeactivateScript(){

    if(CutSceneStatus = true){

      Destroy(gameObject, 1f);
      }

   }
}

```

Note that this can only work if your Character has a Tag "Player" and if the camera has a Raycast component attached to it. Of course, the given values for the rotation, transformations are just examples and need to be adjusted for your scene. Also, the camera needs to be at a height where it can "hit" the player. This is not the most elegant way, but just to give you an idea how to approach this. When you 'destroy' the camera itself, you could also activate the third person camera from unity or your very own camera.

Also, check out Unitys CutScene Guide, im pretty sure they added lately a new function to handle cut scenes without any coding. See this link here

Greetings!
> 1 votes

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


# Question
Title: Display dynamic texture image on inside of sphere
I'm displaying a ring wherever the camera 'looks'. When the camera faces the ground (green) the ring image always looks correct, see image:

However, my scene is within a sphere (purple)... and when the ring reaches the sphere it does not display correctly. See image:

This second image, the ring should be facing the camera since it's on a surface that is in front of the camera (not on the ground like the image appears).

Sorry if my images are poor representations. I basically have a flat plane which is within a sphere. The sphere has flipped normals to be able to display from within the sphere. I need the ring to "attach" or bend to the shaped of the object it is being drawn against. Any help is greatly appreciated.

EDIT: (more details). You can't raycast to a collider from within the same collider, so I'm using a raycast in the opposite direction. Code:

```
Ray ray = new Ray(m_Camera.position, m_Camera.forward); // get ray
Vector3 forwardVector = ray.GetPoint(100); // get a point 100 away
ray = new Ray(forwardVector, m_Camera.forward); // create new ray from this point
ray.direction = -ray.direction; // reverse ray direction
if (Physics.Raycast(ray, out hit, m_RayLength, ~m_ExclusionLayers)) {
     imageTransform.rotation = Quaternion.FromToRotation (Vector3.forward, hit.normal);
}

```

# Answer
So, it ended up being a combination of rotations... one for the ground and one for the sphere. It's a little hacky, but here's my solution. Hopefully it helps someone else out:

```
Target.transform.position = hit.point;
if (hit.collider.gameObject.tag == "GroundTeleportationZone")
     Target.transform.rotation = Quaternion.FromToRotation(Vector3.down, hit.normal);
else
     Target.transform.rotation = Quaternion.FromToRotation(Vector3.up, hit.point);

```
> 0 votes

---
Tags: textures, graphics, geometry
---


# Question
Title: The value of VSync on vSync Count in Unity
In Unity, we can set the vSync value as "No sync" = 0, "Every V Blank" (60 fps) = 1 and "Every Second V Blank" (30 fps) = 2. But in the Unity Quality Setting documentation , it's written the vSync count value must be either 0, 1, 2, 3, or 4. What is 3 and 4 ?

You can set this vSync value on your code, the value must be either 0, 1, 2, 3, 4. But in Quality Setting in Unity, the option is only for : No Sync, Every V Blank, and Every Second V Blank. So basically only for 0, 1, and 2.

There's no option for 3,4. If we set the value on the code as 3 or 4, how should we set the value in Quality Setting Properties ? Because we need to choose a value other than No Sync for the vSync to work. How the vSync count in Properties and Code related if they accept different value ?

# Answer
It's written in the link you provided:

> The number of VSyncs that should pass between each frame.

So, 3 means one frame every 3 VSyncs (with VSync at 60Hz, this means 20FPS), and 4 means 15FPS.

EDIT: to answer to your edit - the value you set via the Quality Settings is your "default" setting, if you change that value by using `QualitySettings.vSyncCount` anywhere in the code, the latter will always takes precedence.
> 2 votes

---
Tags: unity, unityscript, frame-rate, vsync
---


# Question
Title: Is it feasible to create a blockchain to use as a market place game mechanic without extreme inflation?
After watching a fascinating video about block chains, the narrator brought up the idea of using block chains in video games. The example he used was in an MMO type of situation where the player used a sword to defeat a dragon and then the sword became known as Dragon Slayer and its stats would go up and the value of it would increase as well. The player would then sell it to another player who used it to defeat some other powerful monster and it gained more stats and its name changed again. Obviously, it needs to be fine tuned a lot more before it is a feasible idea considering if a sword is owned by say 1000 players then, its description couldn't hold that much information and would need to be limited.

I am thinking of using the block chains similar to the above example except bring it to more of a market place type of mechanic. The player maybe goes through dungeons to defeat monsters. The deeper you go the higher the value of your weapon goes up (stats and gold value) and the higher dungeon you get to the more powerful weapon you will need.

As I think about this concept more I find myself wondering how I could avoid extreme inflation of the in game currency. I'd like to get away from micro-transactions but, I know that is a big tool in helping keep inflation down. (i.e. a second currency). What are some other key ways to keep inflation down in a fast growing in-game economy?

I guess the main thing I see happening is that the balance between the skills earned vs. value earned on a weapon need to be extremely similar so that combat farming doesn't occur in the lower levels but also so that players don't just hold onto the same weapon the whole time they play the game either.

I guess that could be part of the solution but, maybe there are more concrete answers out there that may prevent extreme inflation of in game currencies.

# Answer
> 4 votes
Let me first clear up some misconceptions you seem to have.

The thing a block chain (by itself) provides is a way of cryptographically proving that no-one tampered with previous records. That is, if you know block N is correct for whatever reason (you trust whomever signed it) then you know all blocks prior to that one were at some point also trusted (also fault tolerance and help writing a distributed system).

But, you're asking, how can you prevent inflation with a blockchain? To which the answer is... well... you can't. They're completely unrelated. The blockchain is a datastructure you should probably replace with a database with proper backups and only letting your servers write to it.

A datastructure isn't going to help run an economy, trading doesn't care if you write the history of everything that happens on a piece of paper or if you're permanently storing it across millions of PCs in a blockchain datastructure. *It's irrelevant*

**tl;dr;** Yes you can create a market place without extreme inflation with a blockchain. You can create the same market place without extreme inflation with pen and paper and a lot of interns to keep track of it. The blockchain does nothing except add complexity.

(well, it'd be easier then the interns probably, just stick to a database)

---
Tags: game-mechanics, economy
---


# Question
Title: How do i rotate my view on its own center
**PROBLEM**

I am trying to translate and rotate my view, the translation works fine but when rotating the rotation is happening on the center of the world(0,0,0) instead of the view position.

**EXAMPLE**

What is happening:

What i need to happen:

**CODE**

This is the code i use

```
    Matrix Rotation = Matrix.RotationX(gameObject.transform.Rotation.X) *
                          Matrix.RotationY(gameObject.transform.Rotation.Y) *
                          Matrix.RotationZ(gameObject.transform.Rotation.Z);

    Vector3 Target = Vector3.UnitZ;

    Target += gameObject.transform.Position;

    Matrix Translation = LookAtLH(gameObject.transform.Position, Target, Vector3.UnitY);

    View = Matrix.Multiply(Rotation, Translation);

```

i followed directxtutorial.com to create this code What should i do to rotate on the center of my view

# Answer
> 0 votes
I tend to use Polar Coordinates. This means I tend to only mess with the Theta (in your case) or the Phi for any controls regarding looking (and is very intuitive for me) and means that any controls for panning just take the angles into account.

Here's part of my camera's implementation below:

```
 public void HandleKeyboardInput()
    {
        // TODO: Mark that the camera pos or target changed when it does

        bool w = Keyboard.GetState().IsKeyDown(Keys.W);
        bool a = Keyboard.GetState().IsKeyDown(Keys.A);
        bool s = Keyboard.GetState().IsKeyDown(Keys.S);
        bool d = Keyboard.GetState().IsKeyDown(Keys.D);

        if (!(w || a || s || d))
        {
            return;
        }

        updateCamera = true;
        bool shift = Keyboard.GetState().IsKeyDown(Keys.LeftShift);

        // camera panning
        if (!shift)
        {
            if (w)
            {
                pos.X += (float)Math.Sin(theta);
                pos.Z += (float)Math.Cos(theta);
            }
            if (s)
            {
                pos.X -= (float)Math.Sin(theta);
                pos.Z -= (float)Math.Cos(theta);
            }

            if (a)
            {
                pos.X += (float)Math.Cos(theta);
                pos.Z -= (float)Math.Sin(theta);
            }
            if (d)
            {
                pos.X -= (float)Math.Cos(theta);
                pos.Z += (float)Math.Sin(theta);
            }
        }
        // camera twisting
        else
        {
            if (w && phi < -Utilities.thirdPi)
            {
                phi += (float)Math.PI / 180;
            }
            if (s && phi > Utilities.halfPi * -0.97)
            {
                phi -= (float)Math.PI / 180;
            }

            if (a)
            {
                theta += (float)Math.PI / 180;
                if (theta > Math.PI * 2)
                {
                    theta = 0;
                }
            }
            if (d)
            {
                theta -= (float)Math.PI / 180;
                if (theta < 0)
                {
                    theta = (float)Math.PI * 2;
                }
            }
        }

        //Target is based on Position, that way they are always synchronus
        tar.X = pos.X + radius * (float)Math.Sin(theta) * (float)Math.Cos(phi);
        tar.Z = pos.Z + radius * (float)Math.Cos(theta) * (float)Math.Cos(phi);
        tar.Y = pos.Y + radius * (float)Math.Sin(phi);
    }

    const float FIELD_OF_VIEW = Utilities.halfPi;
    public Matrix BuildProjection()
    {
            return Matrix.CreatePerspectiveFieldOfView(
                               FIELD_OF_VIEW,
                               gd.DisplayMode.AspectRatio,
                               1f, 500f);
    }

    public Matrix BuildView()
    {
        return Matrix.CreateLookAt(pos, tar, new Vector3(0f, 1f, 0f));
    }

    public Matrix BuildWorld()
    {
        return Matrix.Identity;// CreateWorld(tar, Vector3.Forward, Vector3.Up);
    }

```

I use similar code for twisting models, pointing models at things, etc. Let me know if I can make this answer more helpful to you.

---
Tags: c#, rotation, matrix, sharpdx
---


title: Switching lanes in an endless runner

text:
# Question
Title: Switching lanes in an endless runner
Some of you probably know the (once) popular mobile games Temple Run, Minion Rush or Subway Surfers. They all have the similarity of a lane system, which allows you to switch your position with a simple swipe to the left/right.

I am creating a game that also consists of three lanes. The only difference is your general movement going from left to right, thus making the lanes on top of each other.

As LibGDX is my preferred 2D games framework, I want to accomplish this task with mostly built-in functionality. Currently, I have two approaches, which both have flaws and resolving any of them would be a major help to me.

1) Using Actions. I could add an moveTo(upperLane.x, upperLane.y, 0.5f) if the player is in the middle, same goes for the lowerLane. But what, if he double swipes down, while being at the top? I would need so build a sequence, after the first actions started, or cancel the current action and start a new, but how to calculate the appropriate time for that large movement, while still "hanging between" two lines?

2) Implement impulses, that are able to add up in positive (up) and negative (down) directions. This would make it possible to move two steps at once, while having an appropriate time and also to move back up, while being in between two lanes, on your way down. Everything about impulses is plain speculation, as I have no further knowledge and don't want to use Box2D only for this purpose.

3) Feel free to give better suggestions! Special thanks to whom can point out the mechanic of one of the above mentioned games, which implement this feature flawlessly!

# Answer
> 1 votes
Number 1 should have a pretty simple fix (pseudocode):

```
// destination and position are Vector2s
float TRANSITION_SPEED = 0.5f; // How long it takes to move between lanes
float DISTANCE_BETWEEN_LANES = ...; // The distance between two lanes

float distanceToDestination = (destination - position).length();
float percentDistance = distanceToDestination / DISTANCE_BETWEEN_LANES;
float time = percentDistance * TRANSITION_SPEED;
removeAllActions();
moveTo(destination.x, destination.y, time);

```

This will first remove all actions of the Actor so the different actions don't disturb with each other, then calculate the percent distance of the current position `position` to the destination lane `destination`. So if you have traveled 40% of the distance `percentDistance` would be 0.6 which means it would take `0.6 * 0.5 = 0.3` seconds to travel the remaining distance.

---
Tags: libgdx, physics, movement
---


# Question
Title: How to access Unity Game Engine menu bar by keyboard shortcut?
How to access Unity Game Engine top Menu bar by keyboard is there is any keyboard shortcut I could not find it on the internet

# Answer
> 0 votes
The bar in your image can be accessed by holding down the Alt Key (on Windows), then pressing whatever letter is underlined (e.g. the F will be underlined in File).

So, to access the file dropdown, you press Alt + F. Edit is Alt + E. This won't show up in Unity docs as it's an OS thing, not a Unity thing - most programs have this menu bar.

For Macs (and other OSs), you can find the equivalent shortcuts here: https://en.wikipedia.org/wiki/Table\_of\_keyboard\_shortcuts#General\_shortcuts

# Answer
> 0 votes
Unity Documentation shows all shortcuts here

---
Tags: unity
---


# Question
Title: Setting object position in screen space - camera
I'm trying to set an Image gameobject's `transform.position`. My canvas is "screen space - camera" because I needed to use a line renderer.

However, when I set the position, say to `new Vector3(-320, -240);` the object (in play mode) gets positioned at `-16266.44, y: -15360`, way off-screen.

I've tried to reset the localPosition and such based on some other answers but it doesn't help. What else could be translating my pixel coords?

```
var go = Instantiate(HexTilePrefab, this.transform);
go.transform.localPosition = Vector3.zero;
go.transform.localRotation = Quaternion.identity;
go.transform.localScale = Vector3.one;
go.transform.position = new Vector3(screenX, screenY);

```

# Answer
The trick you're missing is converting between screen coordinates, which are generally measured in device pixels from the bottom left corner, and your UI's layout units, which you can configure in the editor to your liking.

Because the latter are configurable, the exact details will depend on how you've set up your UI object hierarchy and anchoring settings. The example below works with one setup, where the parent spans the whole canvas and the child is anchored to the bottom-left. If that doesn't match your setup, edit your question to include details of your arrangement and we can recommend how to compensate.

```
// For UI positioning, we want to work with the RectTransforms of our object
// and its containing canvas, rather than Transforms which don't know about UI.
var canvas = (RectTransform)GetComponentInParent<Canvas>().transform;
var rectTransform = (RectTransform)go.transform;

// Compute a scale conversion between the screen's pixel size
// and the canvas's internal dimensions.
Vector2 scale = new Vector2(
     canvas.rect.width / Screen.width,
     canvas.rect.height / Screen.height
);

// If your anchors are set to the bottom-left, you can use this directly.
// Otherwise, offset by a suitable multiple of the canvas width or height.
rectTransform.anchoredPosition = Vector2.Scale(
    Input.mousePosition,
    scale
);

```
> 1 votes

# Answer
In a 2D game you can match the plane of the objects and the canvas:

* Set Camera \> Transform.z = -10
* Set Canvas \> Plane Distance = 10
* Set UI element transform.position = object.transform.position;
> 0 votes

---
Tags: unity
---


# Question
Title: Difference and interaction between Viewport and Camera
I'm very very confused about some very basic concepts in game/grafical developing. The interaction between the individual components (camera, viewport, window-sizes, gameworld-sizes, ...) when rendering graphical things are still confusing me.

As far as I understand:

* A camera "filming"/viewing something as long it is between the near- and the far-clipping plane
* Camera has a Width and Height which defines the area of what will get "viewed"... ?
    + The viewport can connect to an camera
    + the viewport is the area which will get shown withing the window
    + the cameras view will get projected onto the viewport
    + so if the camera has a size of 1024x768 and the viewport ist only 300x400, the 1024 pixels will get upset on 300 "real" pixels

As you may have have recognized Im very unsure about this. Maybe you can help me with that.

I want to run the test-app down bellow in a way, that the picture will not get stretched. Also Im wondering what "game coordinates" are in that context. For Demo-Cases and learning I've just created a piece of src:

```
package com.mygdx.game;

import ...

public class MyGdxGame extends ApplicationAdapter {
    public PerspectiveCamera cam;
    public Model model;
    public ModelBatch modelBatch;
    public ModelInstance instance;
    private FitViewport viewport;

    @Override
    public void create() {
        modelBatch = new ModelBatch();

        // creating a camera; gets width and height from the window
        // so it will "fit" best in the current window
        cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        cam.position.set(10f, 10f, 10f);
        cam.lookAt(0, 0, 0);
        cam.near = 1f;
        cam.far = 300f;
        cam.update();

        // creating viewport; width n height r not really necessary since it gets new
        // values within
        // the rezise() method; correct?
        viewport = new FitViewport(1920, 1080, cam);

        ModelBuilder modelBuilder = new ModelBuilder();
        model = modelBuilder.createBox(5f, 5f, 5f, new Material(ColorAttribute.createDiffuse(Color.GREEN)),
                Usage.Position | Usage.Normal);
        instance = new ModelInstance(model);
    }

    @Override
    public void render() {
        Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);

        // what is happening here?
        cam.update();

        modelBatch.begin(cam);
        modelBatch.render(instance);
        modelBatch.end();
    }

    @Override
    public void dispose() {
        model.dispose();
    }

    @Override
    public void resize(int w, int h) {

        // putting new values into the viewport
        // and updating it will "resize" the camera ... ?
        float aspectRatio = (float) w / (float) h;
        // viewport.update((int) (h * aspectRatio), h);
        viewport.update(1920, 1080);
        viewport.update(w, h);
    }
}

```

# Answer
You've got a lot of really good questions here! I'll be honest, after years of doing this stuff, I still find there are things I misunderstand everyday and I have to adjust my way of thinking about it.

Let's look at your questions:

* A camera "filming"/viewing something as long it is between the near- and the far-clipping plane

No, not exactly. Your scene exists in a (virtual) world. By setting up some matrices (more on this in a minute), we can tell the computer to project a portion of that world onto a portion of our window (or offscreen drawing surface if you're not drawing to a window).

This does something similar to what a real-world camera does. In the real world, photons are being emitted from light sources (light bulbs, the sun, etc.) and bouncing off objects in the world. They then pass through the lens of the camera and hit the film or sensor. This ends up projecting the objects from the scene onto the film or sensor. So it's a similar process to real-world camera in many ways, but is not exactly the same. (Generally, you'll only project the endpoints of the line segments that make up the polygons of your scene onto your window, and interpolate the values in between.)

* Camera has a Width and Height which defines the area of what will get "viewed"... ?

Again, not exactly. You have a window or other area of memory that you wish to draw into. It's usually a 2D array of pixels. You need to tell the computer which part of the world you want to project into some part of that 2D array of pixels. To do this, you need to give it a few different pieces of information:

1. Where in the world you want to project the scene to. You can think of this as the location of your virtual camera in your scene. It would generally be the translation component of a view matrix. (Or as Sidar pointed out in the comments: "the view matrix is the inverse of the camera objects transformation matrix in world space. This transforms the world ( vertices are transformed in the vertex shader ) as if the camera is always at its origin. This simplifies calculating to normalized device coordinates.")
2. The orientation of your virtual camera. That is, what direction is it facing. This is generally the rotation component of your view matrix.

With those 2 things you have a plane floating in your virtual world that you can project onto. Now you need to cut out a portion of that plane, squeeze it into your window and show it to the user. That's where the projection matrix comes in.

3. The projection matrix defines that space in front of the plane defined by the view matrix that you want to show to the user. Note that it doesn't have to be the same size or shape as the window you're drawing to. You can squeeze or stretch in x or y. You can also set the near and far planes as you mention to include objects farther or closer to the plane.

One way to think about this is that the view matrix defines the location and direction of your virtual camera. The projection matrix is sort of like the lens of that camera, either viewing a wider or narrower area and projecting it onto the same space in your window or offscreen drawing surface. It can simulate a wide angle lens that captures sweeping vistas, or a telephoto that zooms in close to the action.

* The viewport can connect to an camera

Generally in OpenGL (and I'd assume D3D, though I've not used that) the viewport is the 2D area of your window (or offscreen space) that you're going to draw into. It is unrelated to the camera in that sense. (It's also not to be confused with your view matrix.)

* the viewport is the area which will get shown withing the window

More precisely, it's the area of the window which will display something.

* the cameras view will get projected onto the viewport

Yes. (Well, the view of the scene through your virtual camera will get projected, not the camera itself.)

* so if the camera has a size of 1024x768 and the viewport ist only 300x400, the 1024 pixels will get upset on 300 "real" pixels

Don't think of the camera as having a size. That's not generally helpful. The projection matrix will cut out a portion of the 3D world and display it into the area of the window. The viewport is a mask on the window which only shows you a portion of the window.
> 1 votes

---
Tags: opengl, libgdx
---


# Question
Title: CompileFromFile syntax error upon compilation
I am using visual studio c++ 2003 edition and I am trying to use the function CompileFromFIle function from DirectX SDK February 2010 SDK to add bloom to my source code for a mod I am working on and I get this error upon building the release build what is the issue. How do I fix this error?

Output build errors:

c:\Users\john\Desktop\fear public tools 108\Source\Game\ClientFxDLL\D3D10.h(839) : error C2061: syntax error : identifier '\__out' c:\Users\john\Desktop\fear public tools 108\Source\Game\ClientFxDLL\D3D10.h(843) : error C2061: syntax error : identifier '\__in' c:\Users\john\Desktop\fear public tools 108\Source\Game\ClientFxDLL\D3D10.h(847) : error C2059: syntax error : ')' c:\Users\john\Desktop\fear public tools 108\Source\Game\ClientFxDLL\D3D10.h(847) : fatal error C1903: unable to recover from previous error(s); stopping compilation

Here is my code cpp file to look at also:

```
#define _WIN32_WINNT 0x600
#include "stdafx.h"
#include <stdio.h>

#include "C:\Users\john\Desktop\fear public tools 108\Source \Game\ClientFxDLL\D3Dcompiler.h"

#pragma comment(lib,"d3dcompiler.lib")

HRESULT CompileShader( _In_ LPCWSTR srcFile, _In_ LPCSTR entryPoint, _In_   LPCSTR profile, _Outptr_ ID3DBlob** blob )
{
if ( !srcFile || !entryPoint || !profile || !blob )
   return E_INVALIDARG;

*blob = nullptr;

UINT flags = D3DCOMPILE_ENABLE_STRICTNESS;
#if defined( DEBUG ) || defined( _DEBUG )
flags |= D3DCOMPILE_DEBUG;
#endif

const D3D_SHADER_MACRO defines[] =
{
    "EXAMPLE_DEFINE", "1",
    NULL, NULL
};

ID3DBlob* shaderBlob = nullptr;
ID3DBlob* errorBlob = nullptr;
HRESULT hr = D3DCompileFromFile( srcFile, defines,    D3D_COMPILE_STANDARD_FILE_INCLUDE,
                                 entryPoint, profile,
                                 flags, 0, &shaderBlob, &errorBlob );
if ( FAILED(hr) )
{
    if ( errorBlob )
    {
        OutputDebugStringA( (char*)errorBlob->GetBufferPointer() );
        errorBlob->Release();
    }

    if ( shaderBlob )
       shaderBlob->Release();

    return hr;
}

*blob = shaderBlob;

return hr;
}

int main()
{
// Compile vertex shader shader
ID3DBlob *vsBlob = nullptr;
 HRESULT hr = CompileShader( L"BloomCombine.hlsl", "VSMain",   "vs_4_0_level_9_1", &vsBlob );
if ( FAILED(hr) )
{
    printf("Failed compiling vertex shader %08X\n", hr );
    return -1;
}

// Compile pixel shader shader
ID3DBlob *psBlob = nullptr;
hr = CompileShader( L"BloomExtract.hlsl", "PSMain", "ps_4_0_level_9_1",    &psBlob );
if ( FAILED(hr) )
{
    vsBlob->Release();
    printf("Failed compiling pixel shader %08X\n", hr );
    return -1;
}

printf("Success\n");

// Clean up
vsBlob->Release();
psBlob->Release();

return 0;
}

```

# Answer
> 1 votes
The basic problem here is that VS .NET 2003 support was dropped a long, long time ago. The DirectX SDK (November 2007) was the last release to support VS 2003. The legacy DirectX SDK assumed a specific Windows SDK / Platform SDK and your headers are just too out of date for the February 2010 release (which supported VS 2005 and VS 2008).

> The legacy DirectX SDK itself is deprecated. See MSDN.

---
Tags: c++, shaders, directx
---


# Question
Title: How to check if NPCs are on ground or not?
I'm using Unity Engine. I see the common way to check if player is on ground is shooting a Raycast:

How to solve the ground check problem?

How to check if grounded with rigidbody

I have a simple scene with Unity's terrain for ground (Game Object \> 3D Object \> Terrain). Imagine you have a lot of NPCs (like GTA), is it possible to check a character on ground without Raycast? Do you have to run loop to ray cast check each NPC?

# Answer
> 3 votes
My advice for pedestrian-type NPCs would be: don't.

For player characters, we often want to give them full freedom of motion to run and climb and leap or launch themselves around all over the place. That usually involves some form of physics simulation, and checking to see whether they've landed/caught a ledge/gobs of other complex motion states and contact events.

For crowds of pedestrians who mostly stand around and stick to the pathways, this would be excessive. Rather than simulate them physically and check if they're on the ground, we can instead drive them along the ground by construction.

This is commonly accomplished by a navmesh - a polygon mesh representing the walkable/navigable surface of your world. We can use it for more than just AI pathfinding: since the navmesh is constructed to closely follow the terrain, picking a point on the navmesh automatically gets us a grounded position. We don't need to check if the NPC is in the air, because we never build navmesh floating out in the air.

In practical terms this means removing or disabling rigidbody physics from your NPCs, and letting the navmesh navigation component drive their motion.

Now, there might still be edge cases where you need more player-like physics & motion: your NPC gets pushed off of the navmesh, or gets thrown into the air by an explosion, or is standing on a dynamic object like a drawbridge when it starts to open. For these situations you'll want to switch to a dynamic/physics-navigating state for the small collection of NPCs who need this special attention, while still letting the bulk of your NPCs use the cheaper, pure-navmesh route.

---
Tags: unity, collision-detection, physics, rigidbody
---


title: Agent hesitate when choose direction?

text:
# Question
Title: Agent hesitate when choose direction?
I have script for my agent enemy where he should choose one random point and goes to it. But what he did is hesitating !

```
private NavMeshAgent mAgent;
public GameObject[] dead_point;
public float dist;
public int direction_point;

void Start()    {
    mAgent = GetComponent<NavMeshAgent>();
    player = GameObject.FindWithTag("Player");
    dead_point = GameObject.FindGameObjectsWithTag("dead_point"); // 3 points
} // end start

void enemy_dirction()    {
    farPoint = Random.Range(0, dead_point.Length);
    mAgent.destination = dead_point[farPoint].transform.position;
}

// Update is called once per frame
void Update()    {
    dist = Vector3.Distance(transform.position, player.transform.position);
    if (dist <= 20)
    {
        mAgent.destination = player.transform.position;
    }
    else
    {
        enemy_dirction();
    }

}// end update

```

update 1, I used this new script and solved my problem.

```
    private NavMeshAgent mAgent;
public GameObject[] dead_point;
public float dist;
public int direction_point;

void Start()    {
    mAgent = GetComponent<NavMeshAgent>();
    player = GameObject.FindWithTag("Player");
    dead_point = GameObject.FindGameObjectsWithTag("dead_point"); // 3 points
    enemy_dirction()
} // end start

void enemy_dirction()    {
    farPoint = Random.Range(0, dead_point.Length);
    mAgent.destination = dead_point[farPoint].transform.position;
}

// Update is called once per frame
void Update()    {
    dist = Vector3.Distance(transform.position, player.transform.position);
    if (dist <= 20)
    {
        mAgent.destination = player.transform.position;
    }
    else
    {
        if (mAgent.remainingDistance <= 0.5f) {
            mAgent.destination = dead_point[farPoint].transform.position;
            print(farPoint);
        }
    }

}// end update

```

# Answer
If your agent is not close to the player, then you're asking it to choose a new random destination every frame.

If you want to pick one destination and stick to it for a while, you'll need to add some conditional logic to pick a new destination only sometimes, and otherwise carry on with the old one, eg:

* when you've gotten "close enough" to the last destination you picked
* when enough time has passed since the last frame when you chose a new destination
* when an event changes your character's state
* randomly, with a low probability

etc.
> 1 votes

---
Tags: unity, navmesh
---


# Question
Title: OpenGL is not drawing model with more than one material
I have model created in Blender that have 3 UV Maps, 3 materials and each material has texture. Below you can see it.

Also I have OpenGL application that draw this model. Application is working perfectly with one material, but with two or more materials it draw only first. Model was imported with Assimp. I saw that Assimp splits the mesh in three meshes for each material, maybe I handle wrong way these 3 meshes. Below is illustrated results(left in Blender and right in OpenGL):

Code. Initializing model

```
void AnimatedModel::initModel(string filePath) {
    path = filePath;
    loaded = true;
    Importer importer;
    unsigned int flags = aiProcess_Triangulate |
        aiProcess_FlipUVs |
        aiProcess_CalcTangentSpace | aiProcess_GenNormals | aiProcess_LimitBoneWeights;
    const aiScene* scene = importer.ReadFile(filePath, flags);
    if (!scene || scene->mFlags&& AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) {
        cout << "Model::'" << filePath << "': " << importer.GetErrorString() << endl;
        loaded = false;
        return;
    }

    processNode(scene->mRootNode, scene);
}
void AnimatedModel::processNode(aiNode* node, const aiScene* scene) {
    //process all meshes
    unsigned int nrMeshes = node->mNumMeshes;
    for (int a = 0; a < nrMeshes; ++a) {
        aiMesh* mesh = scene->mMeshes[a];
        BoneMesh processedMesh = processBoneMesh(mesh, scene);
        meshes.push_back(processedMesh);
    }

    //do the same with children
    for (int a = 0; a < node->mNumChildren; ++a) {
        processNode(node->mChildren[a], scene);
    }
}
map<string, int> tmp;
BoneMesh AnimatedModel::processBoneMesh(aiMesh* mesh, const aiScene* scene) {
    vector<BoneVertex> vertices;
    vector<unsigned int> indices;
    vector<Texture> textures;

    //calculate texture index
    string meshName(mesh->mName.C_Str());
    int textureIndex = 0;
    if (tmp.find(meshName) == tmp.end()) {
        tmp.insert(make_pair(meshName, 1));
    }
    else {
        textureIndex = tmp.at(meshName);
        tmp.at(meshName) += 1;
    }

    //read vertices
    unsigned int nrVertices = mesh->mNumVertices;
    for (int a = 0; a < nrVertices; ++a) {
        BoneVertex vertex;
        vec3 tmpVector;

        //position
        tmpVector.x = mesh->mVertices[a].x;
        tmpVector.y = mesh->mVertices[a].y;
        tmpVector.z = mesh->mVertices[a].z;
        vertex.position = tmpVector;

        //textures
        if (mesh->mTextureCoords[textureIndex]) {
            vec2 texCoord;
            texCoord.x = mesh->mTextureCoords[textureIndex][a].x;
            texCoord.y = mesh->mTextureCoords[textureIndex][a].y;
            vertex.texCoords = texCoord;
        }

        vertices.push_back(vertex);
    }

    //read faces
    unsigned int nrFaces = mesh->mNumFaces;
    for (int a = 0; a < nrFaces; ++a) {
        aiFace face = mesh->mFaces[a];
        for (int b = 0; b < face.mNumIndices; ++b) {
            indices.push_back(face.mIndices[b]);
        }
    }

    //read material
    aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex];
    if (material) {
        vector<Texture> diffuseMaps = loadMaterialTextures(material, aiTextureType_DIFFUSE, "texture_diffuse");
        textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end());
        vector<Texture> specularMaps = loadMaterialTextures(material, aiTextureType_SPECULAR, "texture_specular");
        textures.insert(textures.end(), specularMaps.begin(), specularMaps.end());
    }

    BoneMesh boneMesh(vertices, indices, textures);
    return boneMesh;
}
vector<Texture> AnimatedModel::loadMaterialTextures(aiMaterial* material, aiTextureType texType, string texName) {
    vector<Texture> textures;
    unsigned int nrTextures = material->GetTextureCount(texType);

    for (int a = 0; a < nrTextures; ++a) {
        aiString texPath;
        aiReturn ret = material->GetTexture(texType, a, &texPath);
        if (ret != aiReturn_SUCCESS) {
            cout << "Error: Can't get '" << texPath.C_Str() << "' texture" << endl;
            continue;
        }

        unsigned int nrLoadedTextures = this->textures.size();
        bool alreadyLoaded = false;
        for (int b = 0; b < nrLoadedTextures; ++b) {
            if (strcmp(texPath.C_Str(), this->textures[b].path.C_Str()) == 0) {
                alreadyLoaded = true;
                textures.push_back(this->textures[b]);
                break;
            }
        }

        if (!alreadyLoaded) {
            Texture texture;
            string directory = path.substr(0, path.find('/', 0));
            texture.id = loadTextureFromFile(texPath.C_Str(), directory);
            texture.path = texPath;
            texture.type = texName;
            textures.push_back(texture);
            this->textures.push_back(texture);
        }
    }

    return textures;
}
unsigned int AnimatedModel::loadTextureFromFile(const string& path, const string& directory, bool gamma) {
    unsigned int id;
    glGenTextures(1, &id);

    int width, height, nrComponents;
    string matPath = string(directory + "/" + path);

    unsigned char* data = stbi_load(matPath.c_str(), &width, &height, &nrComponents, 0);
    if (data) {
        GLenum format;
        if (nrComponents == 1)
            format = GL_RED;
        else if (nrComponents == 3)
            format = GL_RGB;
        else if (nrComponents == 4)
            format = GL_RGBA;

        glBindTexture(GL_TEXTURE_2D, id);
        glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    }
    else
    {
        cout << "Error: Can't load texture '" << matPath.c_str() << "'" << endl;
    }
    stbi_image_free(data);

    return id;
}

```

Drawing model

```
void AnimatedModel::draw(Shader shader) {
    for (BoneMesh m : meshes) {
        m.draw(shader);
    }
}

```

Initializing Mesh

```
void BoneMesh::initMesh(){
    // create buffers/arrays
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);
    glGenBuffers(1, &EBO);
    glBindVertexArray(VAO);
    // load data into vertex buffers
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(BoneVertex), &vertices[0], GL_STATIC_DRAW);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW);

    // set the vertex attribute pointers
    // vertex Positions
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(BoneVertex), (void*)0);
    // vertex texture coords
    glEnableVertexAttribArray(2);
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(BoneVertex), (void*)offsetof(BoneVertex, texCoords));

    //reset
    glBindVertexArray(0);
}

```

Draw Mesh

```
void BoneMesh::draw(Shader shader)
{
    //bind textures
    unsigned int diffuseNr = 1;
    unsigned int specularNr = 1;
    for (unsigned int nrTexture = 0; nrTexture < textures.size(); ++nrTexture)
    {
        glActiveTexture(GL_TEXTURE0 + nrTexture);
        stringstream ss;
        string number;
        string name = textures[nrTexture].type;
        if (name == "texture_diffuse")
            ss << diffuseNr++;
        else if (name == "texture_specular")
            ss << specularNr++;
        number = ss.str();

        glUniform1i(glGetUniformLocation(shader.getId(), (name + number).c_str()), nrTexture);
        glBindTexture(GL_TEXTURE_2D, textures[nrTexture].id);
    }

    // draw mesh
    glBindVertexArray(VAO);
    glDrawElements(GL_TRIANGLES, (GLsizei)indices.size(), GL_UNSIGNED_INT, (void*)0);

    //set to default
    glBindVertexArray(0);
    glActiveTexture(GL_TEXTURE0);
}

```

# Answer
I found solution. Problem was in bone weights. I have skeletal animation so in vertex shader I multiply each bone matrixes with bone weights and finally with vertex position. Bone weights had 0.0 value so all vertex positions after multiply becomes 0.0 .
> 1 votes

---
Tags: opengl, c++, blender, assimp
---


# Question
Title: Unity download image from Firebase database
I am currently trying to download an image using Google Firebase.

The database stores a URL to an image on Firebase storage, Unity pulls the URL from the DB and uses Unity WWW to download it. However the texture shows up as a red question mark texture.

If I use a http URL from another website however it works, is Unity able to download from https addresses?

This downloads the URL from Firebase and stores it in the data\_url variable:

```
void DownloadViaURL()
{
    Debug.Log("Called DownloadViaURL");
    FirebaseDatabase.DefaultInstance
   .GetReference("test_image")
   .GetValueAsync().ContinueWith(task => {
       Debug.Log("Default Instance entered");
       if (task.IsFaulted)
       {
           Debug.Log("Error retrieving data from server");
       }
       else if (task.IsCompleted)
       {
           DataSnapshot snapshot = task.Result;

           string data_URL = snapshot.GetValue(true).ToString();

           //Start coroutine to download image
           StartCoroutine(AccessURL(data_URL));
       }
   });
}

```

This uses Unity WWW to download from the URL:

```
IEnumerator AccessURL(string url)
{

    //Debug.Log("Accessing texture URL in database");
    using (WWW www = new WWW(url))
    {
        yield return www;
        Renderer r = GetComponent<Renderer>();
        r.material.mainTexture = www.texture;
        Debug.Log("Texture URL: " + www.url);
    }
}

```

# Answer
I just found the solution, read permission was disabled in the Firebase storage settings.
> 1 votes

---
Tags: unity
---


# Question
Title: How can I emulate Diablo 3's Isometric view using Perspective?
Using DX11, SimpleMath I am building a isometric game like Diablo 3 in 3D and I want to use a perspective camera that emulates their top down view.

Projection Matrix: `CreatePerspectiveFieldOfView(1, width/height, 0.1f, 100.0f);`

But after this I am a bit unsure how I am suppose to rotate the camera. I assume I could just do p - `Vector3(10, 10, 10)` to get a 45 degree angle at any given p.

How do I properly position, and rotate the camera and point it at position p, to mimic Diablo 3 view?

# Answer
As mentioned, D3 is not in true Isometric view, it's merely at an angle. Isometric (orthographic) ignores the Z axis and thus and no true depth in the shot. It's hard to describe without just playing with it.

I find it much easier to work in 3d because the math for everything being displayed makes more sense to me.

Regardless, I posted a similar answer to another post of my camera code:

```
public class UlmerCam3D
    {
        public Vector3 CameraTarget { get { return tar; } set { tar = value; } }
        public Vector3 CameraPosition { get { return pos; } set { pos = value; } }
        private Vector3 Up { get; } = new Vector3(0.0f, 1.0f, 0.0f);

    // a variable is modified easier in this case than a property
    private Vector3 pos;
    private Vector3 tar;

    // phi is the angle from the vertical axis (Y-axis) expressed as radians
    // NOTE: Because of the way it is oriented and the fact we don't want an upside-down camera,
    // phi is *always* negative, between 0 and Pi. It does not "roll over" when changed beyond this, but instead "sticks"
    public float phi;

    // theta is the angle from the horizontal axis (X-axis) expressed as radians
    // because of it's orientation, theta is always positive, between 0 and 2-Pi
    // This min and max value roll into eachother when changed
    public float theta;

    // the distance between the Camera Position and Camera Target, used to calculate where the target is
    public float radius;

    // The graphics device and the member variables that are related to it
    private static GraphicsDevice gd;

    public UlmerCam3D(GraphicsDevice ingd)
    {
        gd = ingd;
        pos = new Vector3(0f, 100f, 0f);
        tar = new Vector3(0f, 0f, 0f);

        theta = Utilities.halfPi;
        phi = -Utilities.halfPi * .97f;

        radius = 100;

        //TODO : eventually move this copy-code somewhere
        //Target is based on Position, that way they are always synchronus
        tar.X = pos.X + radius * (float)Math.Sin(theta) * (float)Math.Cos(phi);
        tar.Z = pos.Z + radius * (float)Math.Cos(theta) * (float)Math.Cos(phi);
        tar.Y = pos.Y + radius * (float)Math.Sin(phi);
    }

    const float FIELD_OF_VIEW = Utilities.halfPi;
    public Matrix BuildProjection()
    {
        // TODO: Only Calculate if it needs updating
        return Matrix.CreatePerspectiveFieldOfView(
                           FIELD_OF_VIEW,
                           gd.DisplayMode.AspectRatio,
                           1f, 500f);
    }

    public Matrix BuildView()
    {
        // TODO: Only Calculate if it needs updating
        return Matrix.CreateLookAt(pos, tar, new Vector3(0f, 1f, 0f));
    }

    public Matrix BuildWorld()
    {
        return Matrix.Identity;// CreateWorld(tar, Vector3.Forward, Vector3.Up);
    }

    private bool updateCamera = true;
    public void HandleKeyboardInput()
    {
        // TODO: Mark that the camera pos or target changed when it does

        bool w = Keyboard.GetState().IsKeyDown(Keys.W);
        bool a = Keyboard.GetState().IsKeyDown(Keys.A);
        bool s = Keyboard.GetState().IsKeyDown(Keys.S);
        bool d = Keyboard.GetState().IsKeyDown(Keys.D);

        if (!(w || a || s || d))
        {
            return;
        }

        updateCamera = true;
        bool shift = Keyboard.GetState().IsKeyDown(Keys.LeftShift);

        if (!shift)
        {
            if (w)
            {
                pos.X += (float)Math.Sin(theta);
                pos.Z += (float)Math.Cos(theta);
            }
            if (s)
            {
                pos.X -= (float)Math.Sin(theta);
                pos.Z -= (float)Math.Cos(theta);
            }

            if (a)
            {
                pos.X += (float)Math.Cos(theta);
                pos.Z -= (float)Math.Sin(theta);
            }
            if (d)
            {
                pos.X -= (float)Math.Cos(theta);
                pos.Z += (float)Math.Sin(theta);
            }
        }
        else
        {
            if (w && phi < -Utilities.thirdPi)
            {
                phi += (float)Math.PI / 180;
            }
            if (s && phi > Utilities.halfPi * -0.97)
            {
                phi -= (float)Math.PI / 180;
            }

            if (a)
            {
                theta += (float)Math.PI / 180;
                if (theta > Math.PI * 2)
                {
                    theta = 0;
                }
            }
            if (d)
            {
                theta -= (float)Math.PI / 180;
                if (theta < 0)
                {
                    theta = (float)Math.PI * 2;
                }
            }
        }

        //Target is based on Position, that way they are always synchronus
        tar.X = pos.X + radius * (float)Math.Sin(theta) * (float)Math.Cos(phi);
        tar.Z = pos.Z + radius * (float)Math.Cos(theta) * (float)Math.Cos(phi);
        tar.Y = pos.Y + radius * (float)Math.Sin(phi);
    }

```

This is technically in my monogame C# project, but is based on old DirectX 9 code I wrote way back when. Unfortunately this is *way* more readable than my C++ code from them and it doesn't require any hacks.

For the most part you just want the math for the Target based on the Position; then simply set Phi to -Pi/4 and Theta to Pi/4 (any multiple of it) and you'll be looking at a 45 degree plane down at 45 degrees.

Side note: You should stop thinking in degrees. I highly recommend memorizing the Unit Circle (https://www.mathsisfun.com/geometry/unit-circle.html) and getting used to thinking of Angles in terms of P (http://math.rice.edu/~pcmi/sphere/drg\_txt.html.)

In your case, Pi/4 is 45 degrees, which means you want to adjust the camera "down" Pi/4, and then adjust it "over" or "around" Pi/4.
> 1 votes

---
Tags: camera, directx11, isometric, perspective
---


# Question
Title: How do I make a transition between two states to be slowly?
Now it's doing the first New State then it's jumping to New State 0 Instead I want it to slowly move between the two states. I want to see the animation transition slowly changing from state to state.

For example when you see a character sitting and then standing so to see the transition from sitting to standing slow.

# Answer
> 1 votes
# You need an intermediate state

And play an animation that when completed, sets the character to the resulting state.

---
Tags: unity
---


# Question
Title: Creating a master server for Unity game (Unity 2017)
I have a basic FPS game made in Unity. I am using the Unity NetworkManager, NetworkManagerUI and NetworkIdentity components that came with Unity.

The game is working fine on my local network when I make one pc a client-host and other a client. It is also working great using the 'Mulitplayer' service that is free with Unity (for up to 20 max over all games/projects etc, and is supposed to be only for testing I believe)

I'm 99% sure it is possible to run a 'server version' of my app on a pc in my home, and make this into a dedicated master server, but I cannot find much at all from Unity officially regarding this (It seems to always point me to just extending my deal with them to get more players into the server they provide, for which the costs are 1000x more than the budget I have for the game)

Before Unity were offering these pricey services, there was info such as this: https://unity3d.com/master-server

But it says that is only compatible with Unity 3.x

I've asked this question 2-3 times already on the Unity Answers site, and there are no answers at all. I've also browsed it for similar questions and all those seem to be unanswered or way out-of-date.

As I stated last time I ask this, I know thatt Rust game is made with Unity. In past, I downloaded (officially from Facepunch, the devs of Rust) the 'Rust Dedicated Server' application, which I ran on my desktop PC (with fibre network connection) and then I was hosting a server in game. The server ran smooth as silk, so for my game I dont think i would need an actual modern server machine or direct internet connection (otherwise, how did Rust manage it??)

So as I say, I have the network functionality all up-n-running. But the last piece of the puzzle is that I'm using Unity's Mulitplayer Service, and this only allows 20 max concurrent players. This isn't quite enough, as I'd like to have at least 50 if possible. Also I would end up running 10-20 of these so that there is a choice of 'rooms'. Ideally I would be able to let people download and run their own just like Rust.

Before I got to this stage, I was trying to make one user become the Client-Host, but I couldn't figure out how the other clients would be able to tell what is the IP address for the host.

Please can anybody help me, I feel like I've gotten the majority of the way there but now I can't get any further by myself.

Many thanks!

# Answer
> 1 votes
You can have as many users as you would like and scale as you grow using unity multi player services as seen here UnityMultiplayer

Unity offers a free amount of Concurrent users (CCU) for each license.

* Personal: 20 Concurrent Users
* Plus: 50 Concurrent Users
* Professional: 200 Concurrent Users

If you need to increase the number of CCUs that your game supports then you can set this when you submit a live request via the multiplayer dashboard. If you do this, you will be charged $0.49/ GB of traffic that travels through the Unity infrastructure (Matchmaker, Relay Server). This means that you pay for the extra bandwidth that you use. We also have a way to estimate your monthly bill. This can be found by scrolling to the bottom of the multiplayer page.

# Answer
> 1 votes
Reality check.The Unity CCU deal is fine for novice developers. Assuming your game will be the next blockbuster game is going to be disappointing. Spending 100's/1000s of hours setting up a cutting edge personal 'free' server only to have 1 or 2 players visiting daily would be soul destroying. Instead, concentrate on time-to-market and build up your player base. Use the free CCU limits. WHILE the free plan is in place AND you are actually getting people playing THEN build your personal server. Sure, you may need to spend money on CCUs above free limit for a while. However, by then you are not wasting your time on an unrealistic dream.

---
Tags: unity, networking, multiplayer, unity-networking, unet
---


title: Overlay an Image on Screen in Unreal

text:
# Question
Title: Overlay an Image on Screen in Unreal
I need to overlay an image on the screen, the whole screen. The process would be like: A screenshot is captured by the camera. It's blended with another image and the resultant image is displayed on the screen. However, this overlaid image should not be seen by the camera. How would I go about doing this in the Unreal Engine?

# Answer
It seems like you want the image to display on a UI/HUD of some sort?

You can either use a widget blueprint, or extend the HUD blueprint, and add a draw material function that draws a dynamic material with a vector parameter on it.

You can then set the image by setting the vector parameter of your material to the Texture2D file your image is.
> 2 votes

---
Tags: unreal
---


# Question
Title: Lava flow shader with Shader Forge in Unity
I am just starting with shader programming and after reading a bit, I tried creating a shader that is simulating the flow of lava on rocks. Got a placeholder rock texture from internet and everything, however the end result is obviously bad. How can I simulate a flow that moves in the cracks between the rocks? My first idea was to somehow get the color of the cracks and change it to red. Then to animate it by just moving the texture with the Panner node.

Right now it just drags the bubbles texture and returns it.

Here is my shader code (generated by Shader Forge) :

```
 // Shader created with Shader Forge v1.38
// Shader Forge (c) Neat Corporation / Joachim Holmer - http://www.acegikmo.com/shaderforge/
// Note: Manually altering this data may prevent you from opening it in Shader Forge
/*SF_DATA;ver:1.38;sub:START;pass:START;ps:flbk:,iptp:0,cusa:False,bamd:0,cgin:,lico:1,lgpr:1,limd:0,spmd:1,trmd:0,grmd:0,uamb:True,mssp:True,bkdf:False,hqlp:False,rprd:False,enco:False,rmgx:True,imps:True,rpth:0,vtps:0,hqsc:True,nrmq:1,nrsp:0,vomd:0,spxs:False,tesm:0,olmd:1,culm:0,bsrc:0,bdst:1,dpts:2,wrdp:True,dith:0,atcv:False,rfrpo:True,rfrpn:Refraction,coma:15,ufog:False,aust:True,igpj:False,qofs:0,qpre:1,rntp:1,fgom:False,fgoc:False,fgod:False,fgor:False,fgmd:0,fgcr:0.2426471,fgcg:0.2337262,fgcb:0.2337262,fgca:1,fgde:0.01,fgrn:0,fgrf:300,stcl:False,atwp:False,stva:128,stmr:255,stmw:255,stcp:6,stps:0,stfa:0,stfz:0,ofsf:0,ofsu:0,f2p0:False,fnsp:False,fnfb:False,fsmp:False;n:type:ShaderForge.SFN_Final,id:3138,x:33559,y:32494,varname:node_3138,prsc:2|emission-2871-OUT;n:type:ShaderForge.SFN_Tex2d,id:7055,x:32587,y:32402,ptovrint:False,ptlb:Bubbles,ptin:_Bubbles,varname:_Bubbles,prsc:2,glob:False,taghide:False,taghdr:False,tagprd:False,tagnsco:False,tagnrm:False,tex:5735196e5b92b7f4491fd8c4988c9271,ntxv:0,isnm:False|UVIN-2523-UVOUT;n:type:ShaderForge.SFN_Color,id:4099,x:32361,y:33099,ptovrint:False,ptlb:node_4099,ptin:_node_4099,varname:_node_4099,prsc:0,glob:False,taghide:False,taghdr:False,tagprd:False,tagnsco:False,tagnrm:False,c1:1,c2:0.2279412,c3:0.2279412,c4:0.5;n:type:ShaderForge.SFN_Time,id:156,x:32825,y:33195,varname:node_156,prsc:0;n:type:ShaderForge.SFN_Sin,id:7354,x:32982,y:33195,varname:node_7354,prsc:2|IN-156-T;n:type:ShaderForge.SFN_RemapRange,id:1566,x:33042,y:32932,varname:node_1566,prsc:2,frmn:-1,frmx:1,tomn:0.2,tomx:0.6|IN-7354-OUT;n:type:ShaderForge.SFN_Multiply,id:5363,x:33083,y:32739,varname:node_5363,prsc:2|A-1380-OUT,B-1566-OUT;n:type:ShaderForge.SFN_Panner,id:2523,x:32373,y:32402,varname:vvvvvvvvvvvvvvvvvvvvvv,prsc:2,spu:0,spv:1|UVIN-2113-UVOUT,DIST-3406-OUT;n:type:ShaderForge.SFN_TexCoord,id:2113,x:32111,y:32402,varname:node_2113,prsc:2,uv:0,uaff:False;n:type:ShaderForge.SFN_Time,id:9149,x:31788,y:32700,varname:node_9149,prsc:0;n:type:ShaderForge.SFN_Sin,id:8507,x:31886,y:32962,varname:node_8507,prsc:2|IN-9149-T;n:type:ShaderForge.SFN_RemapRange,id:3406,x:32223,y:32638,varname:node_3406,prsc:2,frmn:-1,frmx:1,tomn:0.1,tomx:0.3|IN-8507-OUT;n:type:ShaderForge.SFN_Tex2d,id:86,x:32361,y:32859,ptovrint:False,ptlb:MainTex,ptin:_MainTex,varname:_MainTex,prsc:0,glob:False,taghide:False,taghdr:False,tagprd:False,tagnsco:False,tagnrm:False,tex:5032107f8d981f2409d4adf0dd38b065,ntxv:0,isnm:False;n:type:ShaderForge.SFN_OneMinus,id:6833,x:32536,y:32876,varname:node_6833,prsc:0|IN-86-RGB;n:type:ShaderForge.SFN_Multiply,id:1380,x:32680,y:33027,varname:node_1380,prsc:2|A-6833-OUT,B-4099-RGB,C-4099-A;n:type:ShaderForge.SFN_Add,id:2871,x:33086,y:32458,varname:node_2871,prsc:2|A-5363-OUT,B-1603-OUT;n:type:ShaderForge.SFN_Multiply,id:1603,x:32821,y:32391,varname:node_1603,prsc:2|A-7055-RGB,B-1630-OUT;n:type:ShaderForge.SFN_ValueProperty,id:1630,x:32619,y:32692,ptovrint:False,ptlb:Alpha,ptin:_Alpha,varname:_Alpha,prsc:2,glob:False,taghide:False,taghdr:False,tagprd:False,tagnsco:False,tagnrm:False,v1:0;proporder:7055-4099-86-1630;pass:END;sub:END;*/

Shader "Shader Forge/lavaFlow" {
    Properties {
        _Bubbles ("Bubbles", 2D) = "white" {}
        _node_4099 ("node_4099", Color) = (1,0.2279412,0.2279412,0.5)
        _MainTex ("MainTex", 2D) = "white" {}
        _Alpha ("Alpha", Float ) = 0
    }
    SubShader {
        Tags {
            "RenderType"="Opaque"
        }
        Pass {
            Name "FORWARD"
            Tags {
                "LightMode"="ForwardBase"
            }

            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #define UNITY_PASS_FORWARDBASE
            #include "UnityCG.cginc"
            #pragma multi_compile_fwdbase_fullshadows
            #pragma only_renderers d3d9 d3d11 glcore gles
            #pragma target 3.0
            uniform sampler2D _Bubbles; uniform float4 _Bubbles_ST;
            uniform fixed4 _node_4099;
            uniform sampler2D _MainTex; uniform float4 _MainTex_ST;
            uniform float _Alpha;
            struct VertexInput {
                float4 vertex : POSITION;
                float2 texcoord0 : TEXCOORD0;
            };
            struct VertexOutput {
                float4 pos : SV_POSITION;
                float2 uv0 : TEXCOORD0;
            };
            VertexOutput vert (VertexInput v) {
                VertexOutput o = (VertexOutput)0;
                o.uv0 = v.texcoord0;
                o.pos = UnityObjectToClipPos( v.vertex );
                return o;
            }
            float4 frag(VertexOutput i) : COLOR {
////// Lighting:
////// Emissive:
                fixed4 _MainTex_var = tex2D(_MainTex,TRANSFORM_TEX(i.uv0, _MainTex));
                fixed4 node_156 = _Time;
                fixed4 node_9149 = _Time;
                float2 vvvvvvvvvvvvvvvvvvvvvv = (i.uv0+(sin(node_9149.g)*0.1+0.2)*float2(0,1));
                float4 _Bubbles_var = tex2D(_Bubbles,TRANSFORM_TEX(vvvvvvvvvvvvvvvvvvvvvv, _Bubbles));
                float3 emissive = ((((1.0 - _MainTex_var.rgb)*_node_4099.rgb*_node_4099.a)*(sin(node_156.g)*0.2+0.4))+(_Bubbles_var.rgb*_Alpha));
                float3 finalColor = emissive;
                return fixed4(finalColor,1);
            }
            ENDCG
        }
    }
    FallBack "Diffuse"
    CustomEditor "ShaderForgeMaterialInspector"
}

```

P.S. I decided to add the Bubbles texture, so I can at least try to animate the move of the flow.

Edit:

GIF Link to imgur

The colors are broken after the upload, however the gif shows the movement. The circle things are the "bubbles" texture that I animated with the shader. The red rocks behind is the rock texture.

# Answer
I don't use Shaderforge, so i cannot help in telling you how to set it up. However, i can show you in code and explain what you could do.

You should be able to use another texture exactly the same as the rock texture except its black and white (so obviously not *exactly* the same...), where you want the bubbles to be is white and black wont show any bubbles. This texture can then be used as a mask in the shader above by doing the following:

```
return fixed4(finalColor,1) * MaskTexture.r;

```

If *MaskTexture* contains the black and white texture it works because in a texture black = 0,0,0, white is 1,1,1 and obivously multiplying the bubbles by 0 = no bubbles, and multiplying it by 1 = bubbles!. You could even use the rocks texture itself by using its alpha channel. This means the area where the bubbles are supposed to show is transparent in the texture itself, and then you do this:

```
return fixed4(finalColor,1) * RockTexture.a;

```

This does mean you cannot use the alpha channel for anything else but, this is better optimized because it doesnt require a third texture.

**Alternatively** you could create 2 meshes, 1 for the rock, and 1 for the lava flow. The upside of this is that you could make the lava seemingly change direction and follow the cracks direction when moving trough the cracks (like real lava would) if the uv of the mesh for the lava is setup correctly. The texture moves along the uv axis, so any change in the direction of the line in the mesh will determine the direction of the flow as long as the uv's don't follow the same line, as displayed below. The left side of the image below shows the uv layout, the right the actual line. As you can see the bubble image could simply move up on the UV layout, and on the mesh it would appear to change direction.

A single line for a Lava flow mesh (example):
> 2 votes

---
Tags: unity, shaders
---


# Question
Title: Is it legal to publish a Noughts and crosses (tic-tac-toe) game?
Is it be legal to publish a Noughts and crosses game?

# Answer
> 0 votes
A quick search online indicates that Noughts and crosses is a several thousands years old, so it doesn't have any copyright.

I'd just like to point out if you plan to make such a game for practise, and not to publish it, you don't have to worry about copyrights or patents. If you want to publish it and earn money, I guess you know that there's plenty of noughts and crosses in the market already.

# Answer
> 0 votes
This is not legal advice.

**You can copy:**

* Mechanics

**You cannot copy:**

* Art, sounds
* Lore/transcripts
* Other in-game content

---
Tags: legal
---


# Question
Title: How to make ghosts AI chase Pac-Man in Java
I'm beginner at Java and I want to make ghosts chase Pac-Man in game. I read some algorithm like A\* or Dijkstra but I don't know how to implement them in my game. Please help me.

# Answer
### AI is not intelligent, it just acts like it

I don't think the effort of implementing such algorithms is worth, given the simplicity of a game such as Pac-Man.

I. Millington & J. Funge talk right about Pac-Man *AI* in their book "Artificial Intelligence for Games", paragraph 1.1.2:

> \[...\] Pac-Man had definite enemy characters that seemed to conspire against you, moved around the level just as you did, and made life tough.
>
> Pac-Man relied on a very simple AI technique: a state machine \[...\]. Each of the four monsters \[...\] was either chasing you or running away. For each state they took a semi-random route at each junction. In chase mode, each had a different chance of chasing the player or choosing a random direction. In run-away mode, they either ran away or chose a random direction. All very simple and very 1979.

Pac-Man developers didn't use neither A\* or Dijkstra's algorithm for making enemies chase the player. Monsters who got at intersections chose a new, random direction (not turning back), one of which was the right one to chase the player.

The reason it worked smoothly was because "ghosts" were sort of cooperating and able to patrol most of the level, eventually trapping the player and killing them.

### A simple solution

This said, you can try this approach instead of trying to implement A\* in the first place. My suggested algorithm assumes that:

* Every level can be treated as a grid whose tiles' size is known, and level walls must be placed accordingly to such grid. A square grid is ideal for this purpose;
* *Ghosts* can move either horizontally or vertically, not diagonally;
* *Ghosts* reverse their horizontal and vertical speeds when collision with level walls occur.

Then, a generic ghost AI behavior to change path could be described as follows:

```
function ChangeDirection():
    SPD = desired constant speed
    if horizontal speed == 0:
        if chance 1 out of 3 and no collisions leftwards:
            horizontal speed = -SPD
            vertical speed = 0
        if chance 1 out of 3 and no collisions rightwards:
            horizontal speed = SPD
            vertical speed = 0
    else
        if chance 1 out of 3 and no collisions downwards:
            horizontal speed = 0
            vertical speed = -SPD
        if chance 1 out of 3 and no collisions upwards:
            horizontal speed = 0
            vertical speed = SPD
end

```

When implemented, this function must be executed when *at least* one of these two events occur:

* **Grid snap:** every time a *ghost* snaps with the grid (which means, every time its position is such that it fits perfectly inside a single grid tile), the function can be called to test the opportunity to change direction. This results in actual turning left or right when the monster reaches a corner or any crossing point; in any case, the `ChangeDirection` algorithm doesn't allow a *ghost* to U-turn back;
* **Wall collision:** every time a *ghost* collides with a wall object, it means it can't move further, and a new direction to move towards is required. This time, we must consider the direction the *ghost* came from a valid path to be chosen; for this reason, before executing the `ChangeDirection` algorithm we must tell the ghost to reverse its horizontal and vertical speeds, *then* the algorithm is applied: note that when colliding with a wall, the ghost is definitely snapping with our virtual level grid because we contrain its movements along the grid.

At this point a *ghost*'s update function would look something like this:

```
function Update():
    if colliding with wall at next step:
        reverse horizontal speed
        reverse vertical speed
    if ghost snaps to grid:
        ChangeDirection()
    update ghost position
end

```

Note that we reverse both horizontal and vertical speed although we know only one of them is non-zero from time to time, just for the sake of a compact code.
> 4 votes

---
Tags: java, algorithm, ai, path-finding
---


# Question
Title: Rotation doesn't turn towards characters on right
So I'm working on a tower defense type of game and I have a rotation set up that is supposed to follow a chosen enemy. What I'm seeing is when the enemy comes from the left the turret turns quickly to face the enemy quickly. But when the enemy is on the right it goes much slower and doesn't actually "face" the character until much longer.

In this image I have the game set to show the capsule when the enemy is "targeted" so I know which one the turret is supposed to be facing.Right now its set for closest to base so the enemy at the bottom of the circle is the one the turret should be aimed at. It had from the time the enemy entered the blue area from the right till now when its almost out to point at the enemy. But it still hasn't completely turned to point at the enemy yet. However when the closest enemy is on the left it has no problem turning to face the enemy quickly.

Here is the code I am using to turn towards the enemy. Any ideas on what could possibly causing this behavior?

# Answer
It's a bit difficult to accurately diagnose the problem here without knowing the initial transform (position and rotation, world and local) of each of these objects, but here are a few suggestions to maybe help narrow it down for you:

**Suggestion #1**

Have you tried to feed the rotation returned from FindLookAtRotation directly into the **Target** rotation of RInterpTo and in turn use that result as your target rotation in SetActorRotation?

I'm just going off memory but if I recall correctly, the FindLookAtRotation does the main work of finding your destination rotation. RInterpTo then just interpolates smoothly to that destination over time. Not sure if/why the Make/Break rotator nodes are needed at all.

**Suggestion #2: Overriding actual yaw/roll values**

It's possible that your turret's rotation does not actually equal zero for Yaw and Roll (X/Z). Have you tried setting the X/Z values of that final MakeRotator node to the actual X/Z values from your base turret? You would need to use a BreakRotator node on the turret's rotation and then take the X/Z values from there, instead of overriding them as zero.

**Suggestion #3: Initial Orientation**

Does the turret and these target\_enemies have the same initial orientation? As a quick test, try replacing those target enemy "ship" actors with turret actors. Does the main turret have any trouble rotating towards other turrets (instead of ships)?
> 1 votes

---
Tags: rotation, unreal-4, blueprints
---


# Question
Title: Is it possible to program a game to resume where it left off when you quit in Unity?
I have a game I'm making in Unity and now I'm stuck on saving. Is it possible to program a game to resume where it left off when you quit? Every time I search for this on Google I get nothing. Can anyone tell me if this is possible or not? And if it is how would I do it?

# Answer
First, write a standard save function for the game.

Second, when you detect a "close" or "quit" event, call that function.

Alternatively, if the data you're saving is fast/small enough, you simply save constantly. See Darkest Dungeon for an example of a game that saves constantly.
> 0 votes

---
Tags: unity, savegame
---


# Question
Title: Are there recursive variants for trigonometric functions to potentially improve performance?
This is perhaps a better question for mathematics SE, however, this deals more with the performance side of gaming, and software in general. When I say recursive function, I mean recurrence relation.

I figure, in theory, a recursive function for sine, cosine, and tangent, would provide a function that takes less time to execute, rather than calculating the individual sine, cosine, and tangent every single time, considering that most functions in a game are continuous that require sine and cosine or tangent, e.g. the camera in a 2D or 3D scene. Whenever the mouse is moved, we could use a previous metric of sine, cosine, or tangent to calculate the next value.

Do such recursive functions exist? I have done a quick Google search, but I couldn't really find anything, and I would not know how to formulate a recursive function with my current knowledge of mathematics. (There must be a recursive formula for every function of x that is, at least, continuous.)

Were there older approaches taken in older or even recent video games to achieve good-enough results, like quaternion rotation, to achieve a real-time result?

Some examples where this might potentially be an optimization:

* Any terrain generation algorithm. For example, Minecraft *currently generates* xyz 16-256-16 chunks. Instead of generating 16x16 or 16x256x16 chunks, you could generate individual blocks at a time as time passes or per tick. This would reduce the time per tick spent on generating terrain, and is relatively cheap as you could make it camera direction-dependent, e.g. generate blocks in the direction of the camera, and visible blocks can be generated first allowing lazy terrain generation. This would work with chunks of any size. The same could apply to vector terrain generation. However, relating to recurrence relation, said function would require (for Minecraft) one of 6 cardinal directions to calculate what the next block should be.
* Camera matrices. Despite the fact that you can move your mouse around to make the camera jump on-screen, the Camera function is effectively contiguous per frame. When there is entropy, the transitions are very smooth with about the same interval for each camera rotation, and even then, all movement is a paraboloid shape. This could allow for some optimization like **iterative approximation** as mentioned in the comments.
* Any algorithm that is inherently contiguous in software; interpolations; etc.

# Answer
Even if you could make something that's better **on paper**, than the already available sine and cosine functions, you'd have to essentially go down to the metal to make it useful.

Some systems use the fsin assembly instruction, some create their own approximation. What you need to understand is that these have been in use for almost half a century and were optimized to a point where they're incredibly fast. They don't use traditional algorithms, they use bit trickery.

Using a lookup table today doesn't cut it. It may have been fine in the era of the DS, where small differences in the camera rotation didn't matter, since you had relatively few pixels to work with, but in today's world, where people obsess over low mouse sensitivity values to make sure they have as little pixel skipping as possible, making the camera or something else imprecise isn't worth it. Also, lookup tables will probably be slower.

If you still want to try it, then here are some suggestions:

The taylor series is a good way to approximate the sine of a number. It's an infinite series and can be cut anywhere depending on the precision you need. It's not very fast, but it's a good start.

The other algorithm is called CORDIC. This is what's in your calculator probably. It was designed to be easily implementable in hardware and can give you a pretty decent result very fast. It relies on complec number arithmetics. However, there's a reason it was made for hardware and not software. Adding a layer of abstraction to it can make it suffer pretty badly. And that's only if you're working with a compiled language. Python has 2 layers of abstraction, Java 3, and let's not even talk about JavaScript.
> 2 votes

# Answer
The closest things I'm aware of that might relate to your definition of 'recursive' are:

* Lazy evaluation aka call-by-need - an evaluation strategy which delays the evaluation of an expression until its value is needed and which also avoids repeated evaluations through sharing. This is tied to your choice of programming language & is often used used by functional programming launagues.
* Recurrence relation \- an equation that recursively defines a sequence of values (function) as a function of the preceding terms.
* Differencing \- a specific form of recurrence relationships. Starting with a mathematical expression of the form f(x + b) − f(x + a), one can divide by b - a to get a difference quotient. In some situations, you can recycle much of the work used to find the previous value by noting the change in value & calculating that instead of the entire value. For instance, linear interpolation can be rewritten as forward differencing so that at each step, you only need to calculate the change that occured from the previous step.

With respect to performance, the problem is that not all functions can be differenced in a way that reduces computation. Differencing is best to linear functions. But typically, it's non-linear functions that are expensive. While you could redefine a transcendental function to be 'recursive', unless you're dealing with an approximation, the resulting variant function will also be transcendental & that the property that makes them expensive to compute.
> 1 votes

# Answer
You could use a look-up table. This uses a bit more memory, but memory is quite cheap. This is a common technique used in many Fractal renderers for computing the `log`-function. The log function is used to compute a kind of brightness, and since there are only 256 color values (well, levels of brightness), a lookup table with say 1000 entries is more than enough.
> 0 votes

---
Tags: performance, trigonometry
---


# Question
Title: Find appropriate camera-projector coordinates to project contours of real objects
I am developping a game (unity3d + opencv for image processing) where i detect real-life objects from the webcam on every frame, find their edges and then draw them on the real objects. I need to find the real-world coordinates in order to place my camera and projector in a way to get edges that align with their respective objects. I looked into camera calibration which returns the camera's intrinsics, extrinsics, and lens distortion parameters but i don't know how to use them in my case. Is there a possible way to calculate these positions and angles?

Basically my real-world view looks something like this:

And the image that I should project is this:

I think i should also mention that it's a top-down projection and i'm not using any depth sensing camera.

EDIT: When i put the camera on the same axis as the projector it keeps displaying the projected image infinitely (still didn't figure out the right distance for display)... So where should i place the camera (is there an angle to be mesured?) to be able to detect the objects but not the projection? I appreciate your help.

# Answer
This is going to be tough.

When you have a camera and a projector with an offset between them, there will be parallax between them, shifting the positions and projections of objects in the image plane.

You can compensate for shallow parallax to some degree by re-projecting your scene from a different point of view, but to do this you need to know the depth of each part of the surface away from the camera - something you don't normally get from a webcam.

If your objects are fairly flat and stay close to a fixed plane, you might be able to get away with pretending they're all in a flat plane, and re-project based on that.

For aligning the two, you can use the fact that one shines light and one sees light. Run a calibration step at the start of your session, where you use the projector to shine a calibration pattern onto the object plane.

(If you're using an IR camera to avoid feedback effects, take out the filter that blocks visible light for this step, or use the projected grid as a guide to make marks/place tokens that the camera can see)

For instance, you could project an image that's a dense, uniform grid of dots. By varying their intensity or flashing them one at a time, you can register which dot in the projected image corresponds to which dot in the captured image.

Now you have a series of point-to-point correspondences between coordinates in the camera's image plane and coordinates in the projection image plane.

You can run some fancy pose inference algorithms and lens distortion compensation algorithms on this to find an exact mapping between the two, but I'd suggest a more quick & dirty approach:

Construct a mesh, where each vertex's position corresponds to the position of one of your calibration points in projection space, and its texture coordinate corresponds to the position of that point in camera space. By displaying your edge-processed image feed on this mesh, using normal texture mapping, and capturing that appearance to shoot through the projector, you precisely match the distortion at every calibration point that was visible to the camera. The denser the mesh, the less interpolation error in-between.
> 0 votes

# Answer
Phones are generally terrible at knowing exactly where they are. GPSes have a couple of meters of error and the only other way you have is using the accelerometer, which gives you the second derivative of position, which makes it very vulnerable against small precision issues (of which there is a lot). You could technically do it the hard way by following points on the video feed and trying to guess the position based on the relative position to each other, but even video editing software has to stop for a second to calculate that.
> 0 votes

---
Tags: unity, image-processing
---


# Question
Title: How do I build interesting mechanics-driven puzzles for my stealth game?
I'm currently working on a turn-by-turn puzzle stealth game (as a student group project), inspired by Tiny Heist. The basic mechanic is that every time the player moves a square / does a thing, every NPC moves as well.

---

**My objective is to make an experience similar to Portal**: the player goes from room to room, each room has an entrance and an exit, with obstacles between them. The player can see where the exit is, as well as the obstacles, and must leverage the game mechanics to bypass the obstacles and reach the exit.

An example room would be:

* There is a corridor, with a guard going back and forth. The exit is at the end of the corridor.
* There is a closet in the middle of the corridor.
* The player must exploit the guard's patrol to hide in the closet, let the guard pass him by, get out of the closet and reach the exit.

**I want the player to feel perplexed** when they're trying to solve the puzzle; ideally, I want them to feel there is a solution just within their grasp, but they can't find it; and **I want them to feel smart** once they do solve the puzzle.

The problem is, **I don't know how to design puzzles to give that experience**. I have a few ideas, some of which feel like they'd make fun "early game" levels, but after a while all the levels I'm sketching feel same-y and boring, or too complicated with too many moving parts (I had the same problem back when I tried to design Portal 2 levels).

I want to create dependencies, levels where the mechanics overlap with one another to make the player think "I need to do X, but I can't do X before I've got Y, but how do I do Y without having done X?". I could add additional mechanics like dogs, or security cameras, but I don't know how to exploit them.

When I try to design a level, the kind of ideas I come up with follow a pattern of "you need to turn off the cameras to progress, but you need to give a bone to the dog to reach the camera, but you need to distract the guard to acquire the dog". These ideas are convoluted, but shallow; they don't feel like they'd make for intellectually stimulating (or even difficult) levels.

**What methodology or design pattern** can I apply to create richer problem-solving opportunities for the player in this stealth game context, or in any kind of puzzle game?

# Answer
The Game Maker's Toolkit episode on puzzle-making, which was released a few months after I posted this question, describes game design principles for puzzle games with many examples from existing games.

While the video covers a lot of ground, there are two highlights pertinent to this question:

# 1. Provide clear information

The focus of a puzzle should be finding the solution, and everything else should be immediately clear:

* **The final objective**: for instance, the exit door in Portal rooms. The player should never be wondering what's their goal.
* **What are the player's tools**. The situation you want to avoid is the one where the player finds the solution in a walkthrough and thinks "I didn't even know I could do that". Having simple, broad mechanics helps.
* **The consequences of an action**. The player should always know what triggering any level in a room does.
* **What is possible and what isn't**. If you want a gap to be too wide for the player's 10m jump, don't make the gap 12m wide, make it 20m wide.

These principles are helpful, but I already knew them when I asked the question; giving clear information isn't enough if the puzzles aren't challenging. They need to provide an intellectual challenge that the player can feel good about overcoming, which means the game designer needs to create that challenge somehow.

# 2. Build puzzles around mastering the mechanics

The key insight: **the player should solve puzzles by achieving a deeper understanding of the game's mechanics**.

Puzzles shouldn't be a matter of brute-forcing every combination of moves until you find the one where making move A doesn't stop you from making move B. Solving a mechanic-driven puzzle should be an act of realization, of understanding an emergent property of the game's mechanics, like a combination of two properties, or some way a rule previously introduced can have new implications.

* Dark Matter is immune to gravity, the Planetary Crown reverses gravity.
* Your robots stop moving when they're broken, so in this puzzle you have to break a robot to keep it from moving away from a pressure plate.

Notice that the second example **doesn't introduce a new mechanic**; it introduces the fact that a previous mechanic (robots breaking) which usually had negative consequences, can now be necessary to progress.

Achieving this without breaking rule n°1 (provide clear information) can be hard. You want the player to discover emergent property of the rules, not discover the rules themselves.

* If a puzzle is based on breaking a robot with a laser, you need to introduce lasers and their robot-breaking properties in a previous level.

The way you present your level is also important. You need to build puzzles with **a catch**. Something where, if the player follows their first intuition, they're faced with an insurmountable obstacle.

To achieve that, you may want to put the player in a situation where they make a **wrong assumption**. What you want to avoid is a level design where the player's first intuition leads them directly to the exit. You want the player to see the locked door before they find the key.

# To summarize

* Provide clear information.
* The player should solve puzzles by understanding the game better and deeper.
* Lead the player to false assumptions.
* Do lots and lots of playtesting.
> 3 votes

# Answer
What it sounds like you're currently missing is a way for the player to *influence* the state of the level and its patrols.

If all the player can do is identify a sequence of hiding places and wait for their opportunity to cross between them, then I think you're right, the level design space becomes somewhat limited (though you could embrace this dodging detection as a core play experience, like the Frogger or Bullet Hell of stealth)

Check out other stealth games and you'll find they often contain ways to *make* new opportunities. A few examples....

* throwing a rock or noise-making device to divert a guard from their course, or a piece of meat to distract a dog
* donning a disguise to slip through a checkpoint undisturbed
* stealing a key or information needed to open a secure door
* deactivating a security system or moving its detection area

Once the player can influence the state of the level, it becomes a problem of how to defuse the threat at each juncture, and there might be more than one solution depending on how the player changes the situation.

To get the kind of staged logical reasoning you're talking about, you should consider the dependency graph of the steps the player needs to take. Zelda dungeons do this all the time in their level design, forcing the player to do one series of actions to get a key for a locked door, or to access a switch that changes the dungeon's state in such a way that a new area is reachable.

The last thing to consider is that stealth games are often playgrounds of consequences. I open the gas line which makes a hiss which lures the guard who falls unconscious from the gas who's then seen by another guard on the next patrol who diverts from his path which lets me slip through but gives me only a short window before he sounds the alarm - the level can be a Rube Goldberg machine of chains of events. :)

To maximize the possibilities you get from this, think of each object and verb you add to the game, and how it could possibly interact with every other.

Guards can detect the player. What else can guards detect? How do they react when they detect that thing? If the player can throw a rock on the ground to make noise, what else can the player throw? What else can a thrown rock trigger? (eg. activating a switch from a distance, or disabling a camera... if a camera can be disabled, how does a guard react to detecting a disabled camera?)

Thinking about all the potential intersections of your features is what helps you build a rich world for problem solving, and identify game verbs or elements that might be very one-note and don't offer the kind of gameplay variety bang-for-your-buck that you're seeking.

One of my favourite descriptions of this style of game design was from Jonathan Blow, who described the role of the designer as "curating the mechanics to achieve the maximum combinatorial goodness" - and I think this style benefits stealth games especially.

To close, I'd also recommend watching this talk on the design of Mark of the Ninja for some more inspirations - it's one of my favourites. :)
> 12 votes

# Answer
If you have ever played LittleBigPlanet 3, there are some bonus side levels which are side-scrolling puzzles where the controller controls 2 characters with the same analog stick. I can't find a clip at the moment.

Anyways, you hold the stick right and both characters go right; EXCEPT, if there is a wall to the right of character B, only character A will move to the right, while B walks in place.

You could add this to complexity to your game in later levels (or as bonus levels). Two characters start in different areas of the level, and the player controls both with the same buttons.

Here's how this could work with the scenario you described: character A is hiding in the closet, with the closet door to the left and the rest are walls. The player can input patterns of up, right, or down to move character B (while keeping A in the closet) to advance the guard's patrol, and navigate character B to his or her destination. Once the guard moves past the closet, the player can move character A out of the closet.

Obviously having the player control 2 characters simultaneously would require really thought out level design, but it could add that extra layer you are looking for. Hope that helps.
> 3 votes

# Answer
You could also design the primary challenge of your game around observing and understanding enemy behaviors.

Create more different enemy behavior patterns, and represent them with clearly visually distinct sprites. Make the puzzles about figuring out these behavior patterns and ways to navigate around them.
> 0 votes

---
Tags: game-design, game-mechanics, level-design, puzzle
---


# Question
Title: How to play a sound by C# that is linked to the object with AudioSource?
I trying to play a sound while the player is ontriggerenter. The sound is linked to the object with a AudioSource component. But notting happened.

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

public class FloatBehavior : MonoBehaviour {

    Vector2 floatY;
    float originalY;

    public float floatStrength = 1;

    AudioSource triggerAudio;                                    // Reference to the AudioSource component.

    void Start () {
        this.originalY = this.transform.position.y;
        triggerAudio = GetComponent <AudioSource> ();
        Debug.Log (triggerAudio);
    }

    void Update () {
        transform.position = new Vector3(transform.position.x,
                                         originalY + ((float)Math.Sin(Time.time) * floatStrength),
                                         transform.position.z);
    }

    // OnTriggerEnter 2D
    void OnTriggerEnter2D(Collider2D other) {

        // If gameObject comes in contact with player
        if (other.gameObject.tag == "Player") {
            // Play the hurt sound effect.
            triggerAudio.Play ();
        }

    }

}

```

Trying to debug, but the `triggerAudio` object will retrieve: `woodstump 3 (UnityEngine.AudioSource) UnityEngine.Debug:Log(Object) FloatBehavior:Start() (at Assets/C#/Objects/FloatBehavior.cs:17)`.

What am I missing in my script? Should I use `AudioClip` also?

# Answer
Well the first step is to verify that your OnTriggerEnter2D function is getting called. It's easy enough to put a debug log in there with who it collided to.

An audio source is just that -- it's a "source" audio. It contains important things like positioning and so forth. On the audio source is a field for audio clip. Assuming you have a clip in there already (e.g. this is on a prefab and you can edit it in the inspector), then calling `Play` should play it.

Check the audio source to see that it's not firing on startup, that might be another issue.
> 1 votes

# Answer
check that audio listener is atached at the camera, and the camera is close enough to the audio source position.
> 0 votes

# Answer
You can put the Audio file into the Resources folder and load it from there.

```
...

public class FloatBehavior : MonoBehaviour {
    ...

    AudioSource triggerAudio;                 // Reference to the AudioSource component.

    void Start ()
    {
        ...
        triggerAudio= this.gameObject.AddComponent<AudioSource>();
    }

    void Update ()
    {
        ...
    }

    void OnTriggerEnter2D(Collider2D other)
    {
            ...
            AudioClip ac = Resources.Load("myFile") as AudioClip;

            triggerAudio.PlayOneShot(ac, 1f);
    }

}

```

Hope it helps!
> 0 votes

# Answer
gameObject.GetComponent‹AudioSource›().Play();
> -1 votes

---
Tags: unity, sound
---