# Question
Title: Creating Dynamic Weapons in Unreal Engine?
Back Story: Learning Unreal Engine 4 from scratch, I am making a fantasy Darksouls-ish Game.

I am Having trouble understanding Creating a weapon and allowing the character to hold it with added Functions. For example, I want to have a working torch, lights, flame, stick, to appear in his hand at the press of a button.

I do not know if I am going about this in the correct way, but this is what I did:

1. Created a Static Mesh (Torch Stick)
2. Added The Flame and Light Source to it (Emitter & Point Light)
3. Put the Emitter and Point Light into the Torch Tree
4. Created a Socket in "Persona" in the left hand

At this point I got stuck, because the third person Blueprint. Doesn't Register my amateur Torch as an "Asset".

I watched some "Equipping Weapon tutorials" But the problem is they don't explain where their weapons came from Ex (Rifle), or if they are dynamic (Lights or laser sights)

How am I supposed to go about this? Thanks

# Answer
These 3 functions are what you want: The third one applies to what you are trying to do, just add the socket name and then the target is your weapon and InParent is the StaticMeshComponent. Attach Location Type should be SnapTo.

For this to work, you should make a StaticMeshComponent in your PlayerClass
> 1 votes

# Answer
Create a Class Blue Print for Actor, Then apply Static meshes and or Emitters into it like your regularly building something, Then save it and it will be one object under class.
> 0 votes

---
Tags: unreal-4
---


# Question
Title: How check if an arbitrary given mesh is a single closed mesh?
I'm building a space game where it is allowed for the player to insert his own mesh to be his spaceship. The problem I'm facing is that a ship must be a Polygon Mesh. The player will then be able to place thing inside the ship to make it behave. My question is, given an arbitrary mesh (a set of vertices and triangles), how check if it is a polygon mesh (no holes, with a clear inner side)?

# Answer
> 8 votes
Alternatively - to provide an easier-to-implement and more efficient solution - one can check the mesh's Euler-Poincaré characteristic. Given the number of vertices **V**, number of faces **F** and number of edges **E**.

> A triangle mesh is a closed 2-manifold, if and only if
>
> **V** \+ **F** \- **E** = 2.

If you store your mesh as a list of vertices and indices, **V** and **F** can simply be read out. To compute the number of edges **E**, one can iterate over all faces and insert the three triangle edges in a set, effectively counting unique vertex-vertex-pairs in your mesh.

Additionally, you might want to clean your mesh before-hand, removing duplicate vertices.

Note that above approach only works for fully connected meshes, as pointed out by Adrian Maire. Using sets of connected vertices, you can split the input and assess each part individually instead.

# Answer
> 3 votes
For triangle meshes, you should check:

**(1)** If it is manifold and;

**(2)** If all vertices are inside of a closed fan.

To check **(1)**, just:

**(1.a)** iterate over edges and check if each one is incident to just 1 or 2 faces and;

**(1.b)** iterate over vertices and check if all incident faces form a closed or open fan.

To check **(2)**, just:

**(2.a)** iterate vertices and check all incident edges to it. If all of them are incident to exact 2 faces, then this vertex pass the test. It fails otherwise.

Note that you can do **(1.b)** and **(2.a)** at the same time to optimize things.

http://www.cs.mtu.edu/~shene/COURSES/cs3621/SLIDES/Mesh.pdf

---
Tags: 3d, 3d-meshes
---


title: Intersecting rectangles in space

text:
# Question
Title: Intersecting rectangles in space
I need to intersect 1 million spatial polygons (specified using their Minimum Bounding Rectangles) with 4 completely disjoint MBR's (MBR1,MBR2,MBR3,MBR4) in space. MBR1, MBR2, MBR3 and MBR4 divide the entire space into 4 disjoint parts. For doing so, I wrote the following code. However, it turns out that for 1 million points the code is running very slowly. Is there some way by which I may improve the code so that it may run a bit faster. If yes, then can someone please help with the same

```
//---------------------------------------------------------------------------
struct MBR
{
    double xRight, xLeft, yBottom, yTop;
};
bool intersects(MBR spatialId,MBR mbr)
{
    if (mbr.yBottom > spatialId.yTop || mbr.yTop < spatialId.yBottom) return false;
    if (mbr.xLeft > spatialId.xRight || mbr.xRight < spatialId.xLeft) return false;
    return true;
}
//---------------------------------------------------------------------------
bool contains(MBR spatialId,MBR mbr)
{
    if (mbr.yBottom > spatialId.yBottom || mbr.yTop < spatialId.yTop) return false;
    if (mbr.xLeft > spatialId.xLeft || mbr.xRight < spatialId.xRight) return false;
    return true;
}
//---------------------------------------------------------------------------
bool touches(MBR spatialId,MBR mbr)
{
    if (    (mbr.yBottom >= spatialId.yBottom + std::numeric_limits<double>::epsilon() &&
            mbr.yBottom <= spatialId.yBottom - std::numeric_limits<double>::epsilon()) ||
            (mbr.yTop >= spatialId.yTop + std::numeric_limits<double>::epsilon() &&
            mbr.yTop <= spatialId.yTop - std::numeric_limits<double>::epsilon()))
            return true;
    if (    (mbr.xLeft >= spatialId.xLeft + std::numeric_limits<double>::epsilon() &&
            mbr.xLeft <= spatialId.xLeft - std::numeric_limits<double>::epsilon()) ||
            (mbr.xRight >= spatialId.xRight + std::numeric_limits<double>::epsilon() &&
            mbr.xRight <= spatialId.xRight - std::numeric_limits<double>::epsilon()))
            return true;
    return false;
}
//---------------------------------------------------------------------------
MBR MBR1,MBR2,MBR3,MBR4;
vector<unsigned> spatialIds; //contain 1 million spatial identifiers which are intersected with MBR1, MBR2, MBR3, MBR4
//MBR1, MBR2, MBR3, MBR4 are again specified using their Minimum Bounding Rectangles
vector<unsigned> resultMBR1, resultMBR2, resultMBR3, resultMBR4; //contains the resulting intersecting spatial ids
for(vector<MBR>::iterator itSpatialId=spatialIds.begin(),lSpatialId=spatialIds.end();itSpatialId!=lSpatialId;++itSpatialId)
{
    if(intersects((*itSpatialId),MBR1)||contains((*itSpatialId),MBR1)||touches((*itSpatialId),MBR1))
    {
        resultMBR1.push_back((*itSpatialId));
    }

    if(intersects((*itSpatialId),MBR2)||contains((*itSpatialId),MBR2)||touches((*itSpatialId),MBR2))
    {
        resultMBR2.push_back((*itSpatialId));
    }

    if(intersects((*itSpatialId),MBR3)||contains((*itSpatialId),MBR3)||touches((*itSpatialId),MBR3))
    {
        resultMBR3.push_back((*itSpatialId));
    }

    if(intersects((*itSpatialId),MBR4)||contains((*itSpatialId),MBR4)||touches((*itSpatialId),MBR4))
    {
        resultMBR4.push_back((*itSpatialId));
    }
}

```

# Answer
> 1 votes
I suggest using a space-partitioning data structure, i.e. Quadtrees. They reduce running time from linear to logarithmic in the number of rectangles, which will give you the desired performance boost.

Here is a nice tutorial on how to implement and use them.

http://gamedevelopment.tutsplus.com/tutorials/quick-tip-use-quadtrees-to-detect-likely-collisions-in-2d-space--gamedev-374

---
Tags: c++, space-partitioning
---


# Question
Title: Solution for Shipping Optimized and Minified GLSL?
I've tried to find a reputable optimizing compiler for GLSL that takes source shaders, performs what optimizations it can statically assume, and outputs a minified GLSL file with optimizations, stripped local variable names, and unnecessary content like comments/extra whitespace.

The goal is to transpile GLSL into a portable, obfuscated source file that has been optimized enough so that local device compilers can optimize the shaders at game startup while still maintaining simple and readable GLSL for development.

I'm searching for a solution in my development pipeline in lieu of HLSL's precompiled intermediate representation or Vulkan's SPIR-V intermediate representation. Am I wrong in my assumptions about shipping shaders for OpenGL, is there a best practice for optimizing and shipping shaders with a release build?

# Answer
Unity's ArasP has written an optimizer that could possibly do what you need: https://github.com/aras-p/glsl-optimizer

You could also save the driver's compiled shader binary using OpenGL extension `GL_ARB_get_program_binary` on the first run and use it on subsequent runs to reduce loading hitches. The binary is hardware and driver dependent so you can't ship those.
> 1 votes

---
Tags: opengl, shaders, glsl
---


# Question
Title: Unity3D - How to get highest value for acceleration from Input.gyro
I'm trying to develop an app that can detect car acceleration, braking and cornering speed. I need to detect device acceleration. Is that acceleration high or low?. Like flo app on Google Play.

I'm using gyroscope and I need to get highest value for user acceleration (x, y, z axises) from gyroscope. Values of x, y and z are changing every frame. I need to achieve highest value of this 3 axis for later use.

Now my current code looks like this

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

public class NewBehaviourScript : MonoBehaviour
{
 public Text x, y, z;

 void Start()
 {
     Input.gyro.enabled = true;
 }

 void Update()
 {
     x.text = Mathf.Abs(Input.gyro.userAcceleration.x).ToString();
     y.text = Mathf.Abs(Input.gyro.userAcceleration.y).ToString();
     z.text = Mathf.Abs(Input.gyro.userAcceleration.z).ToString();
 }
}

```

Thanks for any help

# Answer
You can store your `Input.gyro.userAcceleration` into a `Vector3` variable to make your life easier in your `Update()`.

Then you will need to store the maximum value into some class scoped variables, so I would start writing this in your class:

```
public float maxX = 0f, maxY = 0f, maxZ = 0f, maxMagnitude = 0f;

```

And update those values if you get an higher value:

```
void Update()
{
    Vector3 acceleration = Input.gyro.userAcceleration;

    x.text = Mathf.Abs(acceleration.x).ToString();
    y.text = Mathf.Abs(acceleration.y).ToString();
    z.text = Mathf.Abs(acceleration.z).ToString();

    if (maxX < Mathf.Abs(acceleration.x)) {
        maxX = Mathf.Abs(acceleration.x);
    }

    if (maxY < Mathf.Abs(acceleration.y)) {
        maxY = Mathf.Abs(acceleration.y);
    }

    if (maxZ < Mathf.Abs(acceleration.z)) {
        maxZ = Mathf.Abs(acceleration.z);
    }

    if (maxMagnitude < acceleration.magnitude) {
        maxMagnitude = acceleration.magnitude;
    }
}

```

**EDITED** after update to fit the question edits.
> 1 votes

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


title: Send OpenGL video flux via UDP

text:
# Question
Title: Send OpenGL video flux via UDP
It is possible to send the video flux of an OpenGL desktop app via UDP **on Linux** ? I looked up FBO and off-screen rendering but I still can't figure out how to extract the video flux and send it.

I'm working with C++ but if you have explanations in others langages go ahead.

Thanks.

My original post on stack overflow.

# Answer
> 1 votes
I understood by myself how to retrieve the frame rendered and now I have this method :

```
void Renderer::getVideoStream(){
    glReadBuffer(GL_BACK);

    int width = m_window->width();
    int height = m_window->height();

    vector< unsigned char > buf( width * height * 3 );

    glPixelStorei( GL_PACK_ALIGNMENT, 1 );
    glReadPixels( 0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, &buf[0] );

    // compress the image

    // send it via UDP
}

```

It works good with screenshots and I should be able to send it via UDP but I don't understand how to use it with **FBO** so I'll do some search and eventually post another question about it in an other thread.

---
Tags: opengl, c++, 3d, udp
---


# Question
Title: OpenGL: Generating a single square with a Quad Strip
I am currently trying to create a terrain generation system (for my 3D game) with OpenGL 2.1.

The way I am doing it requires the creation of a massive 2D square that consists of multiple smaller squares. After the flat square is generated, the points are randomly offset in the y axis, making it into a 3D structure.

But I can't seem to figure out how to generate this using GL\_QUAD\_STRIP. Can someone please help me figure this out?

Thanks!

P.s. I know my method may not be the best, but I would like to get it to work anyway as it suits my game

# Answer
How about drawing a quad strip for each row in your grid of quads?

I guess it depends on how you're representing your data. One way could be to have a 2D array of 3D coordinates for the grid's vertices. To start, the Y component can be zero and then you can assign random Y values while maintaining the X and Z values intact. Then you would draw a GL\_QUAD\_STRIP using two rows of coordinates at a time from the 2D array: the first strip uses rows 0 and 1, the second strip uses rows 1 and 2 (row 1 is common to the first two strips) and so on... Does that fit your need?
> -1 votes

---
Tags: opengl, 3d, terrain-rendering
---


# Question
Title: Choosing between multiple shaders based on uniform variable
I want to choose from 2 fragment shaders based on the value of an uniform variable. I want to know how to do that.

I have onSurfaceCreated function which does compile and link to create program1 and glGetAttribLocation of that program1

In my onDrawFrame I do glUseProgram(program1). This function runs for every frame.

My problem is that, in the function onDrawFrame(), I get value of my uniform variable. There I have to choose between program1 or program2. But program1 is already compiled linked and all. How to do this? How will I change my program accordingly and use that since it is already done in onSurfaceCreated.?

# Answer
> 1 votes
You can think of glUseProgram as a temporary function. You call it and it "binds" the program to the current context. What you need to do is call glUseProgram(program2) if the uniform variable is a certain value, though I'd highly recommend you avoid this if at all possible. You usually would compile program1 and program2 separately and then just bind whichever one whenever you need it. Example:

```
//compile shader 1
//compile shader 2
glUseProgram(prog1);
//Draw stuff that you want to draw with prog1
glUseProgram(prog2);
//Draw more stuff using prog2
glUseProgram(0);

```

Or if you insist on changing it based off of a uniform value:

```
//compile shaders
glUseProgram(prog1);
//get the uniform value here (but this will be slow)
if(uniformVal == whatever)
    glUseProgram(prog1);
else
    glUseProgram(prog2);
//Draw stuff
glUseProgram(0);

```

Again, I highly recommend you do NOT use the uniform value, because communicating from the GPU towards the CPU is harder. Instead solve which shader you require before ever binding the shader at all.

---
Tags: fragment-shader
---


# Question
Title: Why is xcode not letting me use my static variable?
I'm pretty sure I'm making some stupid mistake. Can't seem to find it, and no good results when googling it either.

When I run my SDL project I get these errors :

> Undefined symbols for architecture x86\_64: "Input::evnt", referenced from: Input::ProcessInput() in Input.o ld: symbol(s) not found for architecture x86\_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)

I know these are the lines that are causing the error :

```
switch (evnt->type)
{
    case SDL_KEYDOWN:
        std::cout << "Key pressed" << std::endl;
        break;

}

```

I know it's not the "contains" of the while loop, but the while loop itself.

This is what my evnt variable looks like :

```
static SDL_Event* evnt;

```

---

Not sure what I'm doing wrong....

# Answer
> 1 votes
You need to both define and declare static variables. I'm assuming that you declared your `SDL_Event*` variable in a header file, inside a class declaration or something similar. That's only half the work of adding a static variable. You need to also define it, such as `static SDL_Event* MyClass::event`. Anyways, you probably don't need to make the event `static`. It should work fine just either as a normal class member or even a local variable.

---
Tags: c++
---


title: Collision isn't working in pong

text:
# Question
Title: Collision isn't working in pong
I've posted about another pong problem a while ago, but now I'm having another problem with the ball collision with the paddle , when the ball collides, it doesn't bounce back, why is that? Here is a snippet of the code:-

```
if (ev.type == ALLEGRO_EVENT_TIMER){

        ballx = ballx + 10;
        bally = bally + 10;
        if (ballx ==x+(P1W/1.0)){
            if (bally == y + (P1H / 1.0)){
                ballx = ballx - 10;
                bally = bally - 10;
            }
        }
    }

```

Here is the whole code:-

```
ALLEGRO_EVENT ev;
int main(){
int d = 200;
int f = 200;
int x = 700;
int y = 100;
int a = 100;
int b = 100;
int ballx = 10;
int bally = 10;
bool ballmoving = true;
al_init_image_addon();
ALLEGRO_BITMAP *Player1;
ALLEGRO_BITMAP *Player2;
ALLEGRO_BITMAP *ball;
ALLEGRO_DISPLAY *display = NULL;

ALLEGRO_EVENT_QUEUE *eventqueue = NULL;
ALLEGRO_TIMER *timer = NULL;

bool playing = true;
al_init();
al_init_primitives_addon();
display = al_create_display(800, 600);
al_install_keyboard();
eventqueue = al_create_event_queue();
timer = al_create_timer(1.0 / 60.0);
al_register_event_source(eventqueue, al_get_keyboard_event_source());
al_register_event_source(eventqueue, al_get_display_event_source(display));
al_register_event_source(eventqueue, al_get_timer_event_source(timer));
Player1 = al_load_bitmap("rectt.png");
Player2 = al_load_bitmap("rectt.png");
int P1W = al_get_bitmap_width(Player1);
int P1H = al_get_bitmap_height(Player1);
ball = al_load_bitmap("ball.png");

while (playing){

    al_clear_to_color(al_map_rgb(255, 255, 0));
    al_wait_for_event(eventqueue, &ev);
    al_start_timer(timer);
    if (ev.type == ALLEGRO_EVENT_TIMER){

        ballx = ballx + 10;
        bally = bally + 10;
        if (ballx ==x+(P1W/1.0)){
            if (bally == y + (P1H / 1.0)){
                ballx = ballx - 10;
                bally = bally - 10;
            }
        }
    }
        if (ev.type = ALLEGRO_EVENT_KEY_DOWN){
            switch (ev.keyboard.keycode){
            case ALLEGRO_KEY_UP:
                y -= 5;
                break;
            case ALLEGRO_KEY_DOWN:
                y += 5;
                break;
            case ALLEGRO_KEY_W:
                b -= 5;
                break;
            case ALLEGRO_KEY_S:
                b += 5;
                break;

            }
        }

        al_draw_bitmap(Player1, x, y, 0);
        al_draw_bitmap(Player2, a, b, 0);
        al_draw_bitmap(ball, ballx, bally, 0);
        al_flip_display();
    }

al_flip_display();
al_rest(5);
}

```

Could you please help? Thank you!

UPDATE:-

```
  ALLEGRO_EVENT ev;
  int main(){
     int d = 200;
     int f = 200;
    int x = 700;
    int y = 100;
    int a = 100;
    int b = 100;
    int ballx = 10;
    int bally = 10;
    int ballXSpeed = 5;
    int ballYSpeed = 3;
    bool ballmoving = true;
    al_init_image_addon();
    ALLEGRO_BITMAP *Player1;
    ALLEGRO_BITMAP *Player2;
    ALLEGRO_BITMAP *ball;
    ALLEGRO_DISPLAY *display = NULL;

    ALLEGRO_EVENT_QUEUE *eventqueue = NULL;
    ALLEGRO_TIMER *timer = NULL;

bool playing = true;
al_init();
al_init_primitives_addon();
display = al_create_display(800, 600);
al_install_keyboard();
eventqueue = al_create_event_queue();
timer = al_create_timer(1.0 / 60.0);
al_register_event_source(eventqueue, al_get_keyboard_event_source());
al_register_event_source(eventqueue, al_get_display_event_source(display));
al_register_event_source(eventqueue, al_get_timer_event_source(timer));
Player1 = al_load_bitmap("rectt.png");
Player2 = al_load_bitmap("rectt.png");
int P1W = al_get_bitmap_width(Player1);
int P1H = al_get_bitmap_height(Player1);
ball = al_load_bitmap("ball.png");

while (playing){

    al_clear_to_color(al_map_rgb(255, 255, 0));
    al_wait_for_event(eventqueue, &ev);
    al_start_timer(timer);
    if (ev.type == ALLEGRO_EVENT_TIMER){

        ballx = ballx + ballXSpeed;
        bally = bally + ballYSpeed;
        if (ballx == x + (P1W / 1.0)){
            ballXSpeed = ballXSpeed * -1;
        }
            if (bally == y + (P1H / 1.0)){

                ballYSpeed = ballYSpeed*-1;
            }

    }
        if (ev.type = ALLEGRO_EVENT_KEY_DOWN){
            switch (ev.keyboard.keycode){
            case ALLEGRO_KEY_UP:
                y -= 5;
                break;
            case ALLEGRO_KEY_DOWN:
                y += 5;
                break;
            case ALLEGRO_KEY_W:
                b -= 5;
                break;
            case ALLEGRO_KEY_S:
                b += 5;
                break;

            }
        }

        al_draw_bitmap(Player1, x, y, 0);
        al_draw_bitmap(Player2, a, b, 0);
        al_draw_bitmap(ball, ballx, bally, 0);
        al_flip_display();
    }

al_flip_display();
al_rest(5);
}

```

still not working

# Answer
> 2 votes
**Edit**

The observed behavior of the ball going through the paddle prompts me to check your collision detection statements, and I believe they are the problem. The condition `if (ballx == x + (P1W / 1.0))` will only return true if `ballx`is exactly equal to a specific point of your paddle. What you want to check is if any part of your ball overlaps any part of your paddle. Let's try an example.

Let's say we have a `ball` and a `wall` and let's assume that both are normal rectangles. \*note this is sudo code to get the logic across. I'm not familiar enough with c++ or your framework to know what the actual code required would be.

```
if (// if the ball is not to the left of the wall
    (!(ball.position.x + ball.width < wall.position.x))
    // and the ball is not to the right of the wall
    &&  (!(ball.position.x > wall.position.x + wall.width))
    // and the ball is not above the wall
    && (!(ball.position.y + ball.height < wall.position.y))
    // and the ball is not below the wall
    && (!(ball.position.y > wall.position.y + wall.height))){
    // then the ball collides with the wall!
}

```

Now that is a big ugly check, and it only check for collision with one wall. There are at least 2 walls and 2 bumpers in PONG so we probably want to make that a method so we can just say

```
if(ballHitsRect(bumper1) || ballHitsRect(bumper2)){
    //handle collision
    ballXStep = ballXStep * -1;
}
if(ballHitsRect(topWall) || ballHitsRect(bottomWall)){
    //handle collision
    ballYStep = ballYStep * -1;
}

```

\*note: the above reflection logic is simplified and will always revers a ball's X direction when it hits a bumper in any way. This causes some odd behavi,or but it is a good starting point. It's up to you how realistic you want your physics to be. You can certainly improve upon this by playing around with your game and seeing how it behaves and what you want to change.

**Original Answer**

It doesn't look like your properly reversing the direction the ball travels.

```
if (ev.type == ALLEGRO_EVENT_TIMER){

    ballx = ballx + 10;
    bally = bally + 10;
    if (ballx ==x+(P1W/1.0)){
        if (bally == y + (P1H / 1.0)){
            ballx = ballx - 10;
            bally = bally - 10;
        }
    }
}

```

This code will only move the ball -10 for the pass through the loop where the ball hits the bumper.

My suggestion, try storing the ball movement in a variable. Then you can just change the value of the variable to control the direction and speed of the ball.

Also you should probably check for collisions with the walls and the bumper separately.

Here's an example of this

```
if (ev.type == ALLEGRO_EVENT_TIMER){

    ballx = ballx + ballXStep;
    bally = bally + ballYStep;
    if (ballx ==x+(P1W/1.0)){ // if x movement causes collision
        ballXStep = ballXStep * -1; // reverse x movement direction
    }
    if (bally == y + (P1H / 1.0)){ // if y movement causes collision
        ballYStep = ballYStep * -1; // reverse y movement direction
    }

}

```

\*note: I'm not that familiar with C++ so there might be a silly error in the conditions.

Just initialize these variables with your other variables.

```
int ballXStep = 10;
int ballYStep = 10;

```

Also, one note on your variables. You may want to consider renaming them so they have meaningful names. `ballx` is a good name. It tells me that is the x coordinate of the ball. `d`, `f`, `a`, and `b` aren't great names because I don't easily know what `b -= 5;` means without looking through other code. This isn't a big problem in code as short as yours is, but if you write something more in-depth, then this will become a bigger setback. Good variable names will help you add features and debug much more easily.

---
Tags: c++, collision-detection, allegro
---


# Question
Title: Most efficient way to calculate angle between two line-segments that do not necessarily touch each other
Although I found answers on calculating angles from vectors, I didn't find a specific way to calculate angles between line-segments that do not necessarily touch each other (I say "not necessarily because I will apply to different cases).

See the figure below:

Consider that I know the 2D position of all 4 red points. I am using C# here. What would be the cheapest way of calculating the angles formed by line-segments that do not touch each other, such like the ones above?

# Answer
> 5 votes
Let `s1` and `s2` the segments, so you can calculate the angle of each using `atan2(s.p1.y-s.p2.y,s.p1.x-s.p2.x)` where `p1` and `p2` are the two points defining s;

```
double theta1 = Math.atan2(s1.p1.y-s1.p2.y,s1.p1.x-s1.p2.x);
double theta2 = Math.atan2(s2.p1.y-s2.p2.y,s2.p1.x-s2.p2.x);

```

Taking the absolute value of the difference, you get the angle between the segments:

```
double diff = Math.abs(theta1-theta2);

```

And finally, you can use the minor angle:

```
double angle=min(diff,Math.abs(180-diff));

```

---
Tags: c#, 2d, geometry, angles
---


# Question
Title: Whose name should I put next to my copyright notice?
I've seen other developers put their own names next to their copyright notice while others choose to put their studio name instead.

I read that having a studio name could potentially protect me legally in the future. if that's the case, why do some indie developers opt to instead put in their real names?

But I also read that if you're just starting out, it's better to just use your name instead.

Also if I put in a studio name instead, is the game still copyrighted to me or the random studio name I give it?

Edit: Upon doing some more reading online, it seems like it'll be more beneficial to use a studio name because it'll easier to perform SEO with it. Am I right about this? This is really confusing me.

# Answer
It depends on what your long-term career strategy is. Is your game the first step to establish your own game development company? Or is it a part of your personal portfolio to land a job with an existing company?

When it is the first, you would of course attribute it to the company to build up the brand.

When it is the latter, you would attribute it to yourself to emphasize that you made it all by yourself.

Regarding legal protection: In many countries you can form a limited liability company and then hire yourself as an employee. The company is then a separate legal entity from you. Should the company go bankrupt, you will only lose what you invested into the company. Even when your companies bank accounts are deep in the red, your personal assets won't be touched (unless you were *criminally* negligent). This is a very valuable safety net for yourself.

But for your company to accumulate debt, it either needs contractual obligations which involve fixcosts or a money loan from an external investor. For the one-person-in-their-bedroom development project which finances all expenses from their personal savings anyway, often neither is the case. So some people feel that there is no reason for them to bother with the paperwork which would be required to form a company.
> 2 votes

# Answer
You put who owns the copyright. That is not determined by the copyright notice, it merely describes the state.

If you are being paid by a studio to develop it, they almost certainly own it. If you additionally own it to a degree, or possibly but unlikely wholly own it and license it to them, is going to depend on your contract/working agreement.

If you own the studio and develop the software, then you are likely free to do as you please. This still could vary, though. If you are not the sole owner, and rarely do companies have sole owners, you still do not own it unless explicitly stated.

If the studio is not a legal entity, it cannot own the copyright, and therefore should not be used in the notice; your name should be. Adding a fictitious studio might limit your ability to enforce the copyright in the future.

If you're worried about liability (which seems unlikely with a game, unless you are doing something illegal intentionally), I suggest a warranty disclaimer like Open Source licenses almost all have.

Basically, this depends on a lot of details of the situation you have not provided. You are best being as honest as possible - making up a legal entity is not a good start on that front. There is also a potential for locale-based legal differences. I am speaking as a US non-lawyer.
> 2 votes

---
Tags: legal, copyright
---


# Question
Title: Setting oblique projection to data visualization
I'm developing a small application using Directx intended to plot frequency spectra data in a waterfall plot. It should look like this:

So far, I managed to created most of the chart components(axes, title and the data can be plotted as lines or slices as the picture above). The problem now is that I could not managed to create a projection similar to that in the image. I know the projection shown in the image is an "Oblique projection" and I've tried several ways to get it:

1. https://www.cs.unm.edu/~angel/CS433/LECTURES/CS433\_17.pdf

Here, the author proposes the projection matrix as

```
P = M_orth * H(θ,φ)

```

where `M_orth` is an orthogonal projection matrix and `H(θ,φ)` is a shear matrix defined as

```
H(θ,φ) =
    | 1  0  -cot(θ)  0 |
    | 0  1  -cot(φ)  0 |
    | 0  0    1      0 |
    | 0  0    0      1 |

```
2. Practical C# - Chart and Graphics, Chapter 5, Pg 247

Here, the projection matrix is defined as

```
P(α,θ) =
    | 1  0  cos(θ) / tan(α)  0 |
    | 0  1  sin(θ) / tan(α)  0 |
    | 0  0         0         0 |
    | 0  0         0         1 |

```

and the author gives two special cases:

* Cavalier projection: alpha = 45°, 30 \<= theta \<= 45
* Cabinet projection: alpha = 63.4°, 30 \<= theta \<= 45

But none of them have gave me good results:

And I don't understand why I'm getting this strange results? Any of you guys knows how to set the oblique projection properly?

Thanks in advance

# Answer
> 2 votes
Turns out that setting the oblique projection was pretty straight forward. To make it work on D3D11, the oblique projection should be composed by two matrices:

```
P(α,θ) = S(α,θ) * M_orth

```

where

*M\_orth* is an orthographic projection matrix and *S(α,θ)* the shear matrix given by:

```
S(α,θ) = | 1  0  0  0 |
         | 0  1  0  0 |
         | a  b  1  0 |
         | 0  0  0  1 |

```

with

```
a = cos(θ) / tan(α)

```

and

```
b = sin(θ) / tan(α)

```

These are the results I've got:

---
Tags: directx, projection
---


title: LibGDX : Scene2D ScrollPane

text:
# Question
Title: LibGDX : Scene2D ScrollPane
I want to create a list of buttons with ScrollPane , but I cant create a ScrollPane . In the constructor method in the examples Skins are used (.atlas , .json files) but how to create these files?

```
Skin skin = new Skin(Gdx.files.internal("data/uiskin.json"));

```

Is there a program to generate this json ? As I noticed a lot of Scene2D elements need skins.

# Answer
Unfortunately, you usually have to write these json files by hand. The syntax isn't too awful. To style an object its usually

```
<fullyQualifiedUIWidgetName>$<StyleClassName>:{
   <styleName>: {
       <styleParameter>: <value>,
       <styleParameter>: <value>,
   },
   <styleName>: {
       <styleParameter>: <value>,
       <styleParameter>: <value>,
   },
   ...
}

```

The libgdx test project has an example ui skin that I usually use to start from (just make sure that you copy the uiskin.atlas and uiskin.png files from the same directory to make it work)

Here is a pretty good article on using libgdx skins

Libgdx does, however, come with an atlas file generator called TexturePacker to help create your `.atlas` files from your image assets. You have to have inlcuded the tools library when you created your project.

It will take several different images and combine them into one or more pngs, then give you an atlas file. As long as this png and atlas file are in the same directory as the json file with the same name, then the skin will automatically load them

TexturePacker is a command line tool so I usually create another project to manage it. Here is a blog post I wrote on how to do that.
> 1 votes

# Answer
you can create scrollPane without that. Create it with no input and then call setWidget(Table or Actor) on it to attach the widget you want
> 0 votes

---
Tags: libgdx, scene2d
---


# Question
Title: Unity new UI - Dynamically change the functions called by GUI elements
Looking to dynamically change the value in the button OnClick and slider On Value Changed .

If I had to guess on how this was done, get a reference to the button/gui element. Next get the Button script component and access that list of function calls. However I'm not sure how to modify that list. Anyone have any ideas?

More Details that might help:

* The function being called is apart of a custom script component
* Using the 'dynamic' variable option for the sliders
* Could be used to create dynamic buttons

# Answer
There's a super simple way to change events:

**EDIT**

See my other answer for the quick and easy way to add an event for the `OnClick` event only. For other events, like `OnDrag` see below.

---

Additionally, if you need more than just the events provided by default, I'd suggest instead attaching a `EventTrigger` to your game object. This gives us access to the `BaseEventData` object returned from the event, telling us stuff like the object that created the event. Then you can do something like:

```
//Create an event delegate that will be used for creating methods that respond to events
public delegate void EventDelegate(UnityEngine.EventSystems.BaseEventData baseEvent);

```

Then we can create a method for handling events, the signature must match that of our delegate. So, it needs to return `void` and accept `BaseEventData` as its first and only parameter:

```
public void DropEventMethod(UnityEngine.EventSystems.BaseEventData baseEvent) {
    Debug.Log(baseEvent.selectedObject.name + " triggered an event!");
    //baseEvent.selectedObject is the GameObject that triggered the event,
    // so we can access its components, destroy it, or do whatever.
}

```

Finally, to dynamically add the event:

```
//Get the event trigger attached to the UI object
EventTrigger eventTrigger = buttonObject.GetComponent<EventTrigger>();

//Create a new entry. This entry will describe the kind of event we're looking for
// and how to respond to it
EventTrigger.Entry entry = new EventTrigger.Entry();

//This event will respond to a drop event
entry.eventID = EventTriggerType.Drop;

//Create a new trigger to hold our callback methods
entry.callback = new EventTrigger.TriggerEvent();

//Create a new UnityAction, it contains our DropEventMethod delegate to respond to events
UnityEngine.Events.UnityAction<BaseEventData> callback =
    new UnityEngine.Events.UnityAction<BaseEventData>(DropEventMethod);

//Add our callback to the listeners
entry.callback.AddListener(callback);

//Add the EventTrigger entry to the event trigger component
eventTrigger.delegates.Add(entry);

```

If you're using version 5.3.3 or above, use this line instead instead of the last line above, delegates is depreciated:

```
eventTrigger.triggers.Add(entry);

```
> 23 votes

# Answer
The word is that the `delegate{}` syntax found in my previous answer is obsolete, there is another way of doing this using lambda notation:

```
void buttonSetup(Button button) {
    //Remove the existing events
    button.onClick.RemoveAllListeners();
    //Add your new event using lambda notation
    button.onClick.AddListener (handleButton);
}

void handleButton() {
    Debug.Log("Button pressed!");
}

```

Or you can pass the button along to make things a little more dynamic:

```
void buttonSetup(Button button) {
    button.onClick.RemoveAllListeners();
    //Add your new event
    button.onClick.AddListener(() => handleButton(button));
}

void handleButton(Button b) {
    Debug.Log("Button '" + b.name + "' pressed!");
}

```
> 11 votes

# Answer
How unity implements the UI is just like any other unity components. You add GameObject and attach UI components to it. Once you have the game object you can get the UI components from it and change the properties.

API reference for UI can be found under UnityEngine.UI namespace, API reference for BUtton is http://docs.unity3d.com/ScriptReference/UI.Button.html

See the post http://blog.trsquarelab.com/2015/03/new-ui-implementation-using-c-scripts.html for more information on accessing UI from C# scripts
> 0 votes

# Answer
Create a new script, along the lines of:

```
public class EventHandler : MonoBehaviour, IPointerClickHandler
{
    public void OnPointerClick(PointerEventData eventData)
    {
        Debug.Log("Element: " +
                   eventData.selectedObject.name +
                   " was clicked at " +
                   eventData.position.ToString());
    }
}

```

This script implements in the interface IPointerClickHandler (among many other available interfaces). Simply attaching this script to a UI element will allow this script to intercept click events (or whatever event your implement the interface for).

The next step is to simply dynamically add this script as a component to the UI element you want:

```
myButton.AddComponent<EventHandler>();

```

This will add the script as a component to `myButton` and the next time I click the button, I'll get information about which button was clicked, and where the click took place.

This provides the most information about the event compared to my other answers.
> 0 votes

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


title: Resolution scaling

text:
# Question
Title: Resolution scaling
I'm currently working on a project and I'm happy with the UI design:

Being the fool that I am, I decided to only design my UI for one resolution, and now that I want to have the user be able to change that resolution I've hit a wall.

So my question is, how can I scale this to fit any resolution? I'm programming it in SDL 2.

# Answer
> 5 votes
SDL2 actually supports this natively. While it caused me some artifacts while rendering tile-based maps, it works pretty nicely with everything else. I'm not 100% sure on this, but I think SDL also automatically transforms for an example mouse coordinates to work with the scaling nicely.

So, to enable scaling, you only need to call `SDL_RenderSetLogicalSize(renderer, width, height);` with the width and height values that you used to design the interface. SDL uses letterboxing for the scaling, however, so it will always keep everything in view.

While this might not be the optimal scaling method specifically for user interfaces, it is a quick and fast way to get your game resolution independent. You can continue developing the game while assuming the resolution is static, and SDL does everything else for you automatically. This is definitely something you should try out and see if it is good enough for your requirements.

Otherwise, as already pointed out, you could try out an actual UI framework.

# Answer
> 1 votes
This requirement is not easy to fulfill. Of course you can upscale the design to a higher resolution, but this will make fonts, images just bigger, which normally does not too so nice. To avoid this you can try to define anchors for things like your text-box or your avatar-picture. When resizing the screen / window they should stay at the right ( for the avatar for instance ) or at the bottom ( for the text box ). And you need to define which areas can be resized automatically ( like the chat-box ).

If you don't want to implement these features on your own you can try to use a ui-framework like ImGui to do this.

---
Tags: sdl, resolution
---


title: Reducing mobile build size

text:
# Question
Title: Reducing mobile build size
This is my second time making and game and I want to make sure that I fit under 50 mbs. So far my plan is to fit all the games artwork into two 2048x2048 sprite sheets. I tested a empty unity3d project and when the apk was made it was 19 035 KB of size. Where does this overhead come from and how can I reduce it?

This is not a duplicate question of this one. I'm asking why building a completely empty project results in a apk with a size of 19 MB. Does this mean that I have limit my assets to 30 MB so that the complete app will be less than 50 or is there a way to strip some of those initial 19 MB.

# Answer
> 1 votes
Yes, that's the minimum size for an empty project when deployed.

**Mono Runtime**

The Mono Runtime which allows your C#, JS, Boo code to execute - basically like the .NET Framework - not a trivial piece of machinery!

**Unity Platform**

You know wherever you are `using UnityEngine`? That doesn't come from nowhere. All the logic and functionality of the engine (a lot) works in conjunction with whatever code you write and assets you insert, to create the game in question. You can't reduce it - the engine / platform comes as-is. Imagine you had to write everything that Unity does, in native code. It would not be small.

**Other details**

The same was true of SWF files back when Flash was a big thing. A large portion of the runtime is contained in the build artifact.

You can try `Edit->Project Settings->Player Settings->Stripping Level`.

Beyond a Unity build's base size, i.e. for trimming your own resources, you can try this.

And IME you won't get a build / deploy time less than 2 mins on Android.

P.S. This is one reason I prefer writing native apps using C. Incredibly small, fast build and deploy.

---
Tags: unity, android
---


# Question
Title: How can you effectively filter your community feedback?
I am not asking for myself, I am asking for someone else who will likely not read this question because he is too busy reading his email, but I am sure that this question will be of a lot of value to others.

The poor guy has the problem that his development project got quite a bit more attention during development than he liked. Now he gets bombarded with emails full of bad suggestions and useless bug reports. Reading through all these emails takes him several hours of development time each day. However, not reading it is not an option either as it would mean that he could miss some emails which are actually important, like mails from potential project members, *useful* bug reports or press and business contacts.

He recently called it the biggest problem for the development of his project in a 20 minute video <sub>(you don't need to watch this rant entirely. The blog post linked in the first sentence of this question summarizes it very well)</sub>

How can a game developer canalize and filter their feedback stream to improve the signal-to-noise ratio?

# Answer
There are many possibilities that could work for some projects and individuals and do not work for others - choose for your self. For shortness, I'm using term "input" for every kind of feedback. Items are in not any particular order (except the last one).

* Build a **community** and encourage input solving in it. Once shown examples of how to handle questions, community can continue to apply them without your constant supervision. Just check in and correct results if needed.
* Use **pre-defined responses** to input. This can reduce response times greatly, freeing up time
* Expand your team, find someone to fit the role of a **secretary** (even hire a professional) to handle the input and let him/her filter it and present to you only the most important input
* Add **obstacles**. No ways to contact - no input - nothing to filter. Reduce means of contacting you as much as possible. Only the most insistent will reach to you.
* **Ignore** the junk input for as much as you can. Respond only to the helpful input.
* **Reduce the need** for people to send in input. Maintain FAQs and roadmaps, post status updates, feature lists, etc.
* Build your (project) **reputation**. Teach people what they can/cannot do when sending their input.
* And finally - **calm down** and try to not over-react about the topic. Maybe it is not such a big deal to skip some inputs or to not resolve everyone's input under 24h.

\** *I might not agree with all the items on the list, still they could be viable for some*

In any way, every kind of filtering has a setup cost, running cost and chance of filtering out valuable input.
> 2 votes

# Answer
If you try to do this by e-mails, you already lost.

Try Trello *(or any other kanban that allows people to comment on cards)*. So everybody will be aware of what is **already being developed**, what will **not be developed**, what is **planning to be developed**... etc.

So you will not receive dozens of e-mails talking about the same thing.

If you don't like idea of keeping a kanban, then a **community forum** will be great for the same purpose. If managed properly, community will filter theirselves by keeping popular threads at the top of the thread list.
> 2 votes

---
Tags: project-management, community-management
---


title: Unity simple solid color alpha shader

text:
# Question
Title: Unity simple solid color alpha shader
I searched for a shader, where I can set a solid color, which I can fade in or out like I want. There is not such a thing build in as far as I could see. Now I got this code, which works fine in case of the alpha value, but it turns everything behind upside down. Since I'm absolutely not into shaders, I need help to fix that to a simple alpha shader.

```
Shader "Unity Answers/Solid Transparency Color"
{
    Properties
    {
        _Color ("Color", Color) = (0.5, 0.5, 0.5, 0.5)
    }

    SubShader
        {
            Tags {"Queue" = "Transparent"}
            ZWrite Off GrabPass { }
            Pass { Fog { Mode Off } Blend SrcAlpha OneMinusSrcAlpha

         CGPROGRAM
         #pragma vertex vert
         #pragma fragment frag

         fixed4 _Color;
         sampler2D _GrabTexture;
         struct appdata
         {
             float4 vertex : POSITION;
         };
         struct v2f
         {
             float4 pos : SV_POSITION;
             float4 uv : TEXCOORD0;
         };
         v2f vert (appdata v)
         {
             v2f o;
             o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
             o.uv = o.pos;
             return o;
         }
         half4 frag(v2f i) : COLOR
         {
             float2 coord = 0.5 + 0.5 * i.uv.xy / i.uv.w;
             fixed4 tex = tex2D(_GrabTexture, float2(coord.x, 1 - coord.y));
             return fixed4(lerp(tex.rgb, _Color.rgb, _Color.a), 1);
         }
         ENDCG
     }
 }
}

```

# Answer
Okay, I found the answer, with debugging it by myself. The fix is kinda simple, just remove the `1 -` in this line `fixed4 tex = tex2D(_GrabTexture, float2(coord.x, 1 - coord.y));`

```
Shader "Unity Answers/Solid Transparency Color"
{
    Properties
    {
        _Color ("Color", Color) = (0.5, 0.5, 0.5, 0.5)
    }

    SubShader
        {
            Tags {"Queue" = "Transparent"}
            ZWrite Off GrabPass { }
            Pass { Fog { Mode Off } Blend SrcAlpha OneMinusSrcAlpha

         CGPROGRAM
         #pragma vertex vert
         #pragma fragment frag

         fixed4 _Color;
         sampler2D _GrabTexture;
         struct appdata
         {
             float4 vertex : POSITION;
         };
         struct v2f
         {
             float4 pos : SV_POSITION;
             float4 uv : TEXCOORD0;
         };
         v2f vert (appdata v)
         {
             v2f o;
             o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
             o.uv = o.pos;
             return o;
         }
         half4 frag(v2f i) : COLOR
         {
             float2 coord = 0.5 + 0.5 * i.uv.xy / i.uv.w;
             fixed4 tex = tex2D(_GrabTexture, float2(coord.x, coord.y)); //Here is the fix
             return fixed4(lerp(tex.rgb, _Color.rgb, _Color.a), 1);
         }
         ENDCG
     }
 }
}

```
> 1 votes

---
Tags: shaders, unity
---


# Question
Title: Reskinning assets on-the-fly with LibGDX TextureAtlas
I'm building a game for Android using LibGDX and I'm attempting to add in a skin feature so players can change the look of the game on-the-fly. I've packed the skinnable assets into their own .pack files, separate from those of the rest of the assets, and I want to swap out the packs being used when the player selects a new skin.

In my `Game` Class I've got a function like this one:

```
public void loadSkinnedAssets(String skin){
    if(skinnableAtlas != null){
        //Tried both with and without disposing.
        skinnableAtlas.dispose();
    }
    skinnableAtlas = new TextureAtlas(Gdx.files.internal("skins/" + skin + "/Assets.pack"), true);

    if(gameScreen != null){
        gameScreen.refreshSkinnedSprites();
    }
}

```

Then in the `GameScreen` it does something like this:

```
public void refreshSkinnedSprites(){
    mySprite = new Sprite(game.getSkinAtlas().findRegion("myRegion");
    //Rest of the sprite setup not important.
    //Also attempted to just use mySprite.setRegion().
}

```

When the player chooses a skin from a list, it calls `game.loadSkinAssets("skinName")`. This is only possible from an options screen separate from the `GameScreen`.

These two functions work properly when called on launch, but the result of running them to replace existing assets is all of the replaced assets being drawn as solid black rectangles. If the game is left and then returned to (dispose and resume being called organically) everything loads properly, which again calls the same functions.

Is there something I'm missing in the posted code, or is there some entirely different way of accomplishing this?

# Answer
> 0 votes
After researching LibGDX and OpenGL further I've found the root of the problem, which was loss of OpenGL Context. All of the texture loading needs to be done when the thread has access to the context, which is true when the app first loads but becomes false later on. In order to fix the problem, the textures need to be loaded in a thread that has access to the OpenGl Context, which can be done very simply by posting the body of the function as a runnable to the app. This gave me a final implementation similar to this:

```
public void loadSkinnedAssets(final String skin){
    Gdx.app.postRunnable(new Runnable() {
        @Override
        public void run() {
        if(skinnableAtlas != null){
            //Tried both with and without disposing.
            skinnableAtlas.dispose();
        }
        skinnableAtlas = new TextureAtlas(Gdx.files.internal("skins/" + skin + "/Assets.pack"), true);

        if(gameScreen != null){
             gameScreen.refreshSkinnedSprites();
        }
    });
}

```

I still need to do a lot of testing to ensure that this is a good means by which to do this, but at the very least it accomplishes the end I'm looking for.

---
Tags: android, libgdx, texture-atlas
---


# Question
Title: Limit Quaternion/vector3 axe in a certain interval
I have some trouble to understand, and handle Quaternion and Vector3. I'm improving the tutorial Tank of Unity:

**EDIT:** Because a video explain so much better, there is a link to the 30 secondes video I made: https://www.youtube.com/watch?v=nNrmlfbHNTI&feature=youtu.be

In the first part, the turret turn with restriction made with the both line `newRotation.z = 0.0f; and newRotation.x = 0.0f;` (see code bellow).

In the second part, I just comment this two line.

My probleme is: i want to be able to look up and down (like in the second part of the video, but with a **DEPRESSION LIMIT** (don't look too much high and too much down)

I try soo manny case and can't manage the thing i want to do... there is the code of the script in ref to the Tank turret:

```
public float m_TurnSpeed = 8f;
private Transform m_Transform;
private int floorMask;
private float camRayLength = 100f;

void Awake()
{
    floorMask = LayerMask.GetMask ("Ground");
    m_Transform = GetComponent <Transform> ();
}

void FixedUpdate()
{
    Turning ();
}

void Turning()
{
    Ray camRay = Camera.main.ScreenPointToRay (Input.mousePosition);
    RaycastHit floorHit;

    if (Physics.Raycast (camRay, out floorHit, camRayLength, floorMask))
    {
        Vector3 playerToMouse = floorHit.point - transform.position;
        Quaternion newRotation = Quaternion.Slerp(m_Transform.rotation, Quaternion.LookRotation(playerToMouse), Time.deltaTime * m_TurnSpeed);

/////////////////////////////////////////////////////////////////////
////////// EDIT 2: probleme solved with the following line //////////
/////////////////////////////////////////////////////////////////////

        //block totaly Z and X quanta
        //newRotation.z = 0.0f;
        //newRotation.x = 0.0f;

        m_Transform.rotation = newRotation;

        float tmpX = m_Transform.localEulerAngles.x;
        if (tmpX > 20.0f && tmpX < 90.0f)
            tmpX = 20.0f;
        else if (tmpX < 315.0f && tmpX > 280.0f)
            tmpX = 315.0f;
        m_Transform.localEulerAngles = new Vector3(tmpX , m_Transform.localEulerAngles.y, 0.0f);
    }
}

```

Thanks !

# Answer
> 1 votes
Looks like you need to restrict the euler angles of the turret, after the quaternion rotation has been effected. basically you'd just do something like:

```
transform.localEulerAngles = new Vector3(transform.localEulerAngles.x < 0 ? 0 : transform.localEulerAngles.x, transform.localEulerAngles.y, transform.localEulerAngles.z);

```

...I think X is the right axis and not sure if it should be `<` or `>` and I think 0 rather than 90, 180 or 270. Try variations and you should get results.

---
Tags: unity, vector, raycasting, quaternion, raytracing
---


# Question
Title: Rotating A model in 3D so it matches its direction of movement
So I have a model of a spear and when it gets thrown I want to set the orientation of the spear to its direction. ( I also want to use this for other things like bullets pointing in the direction they are moving in)

my Models local forward Vector is +Z and I have the direction that it is moving in (in world space) from the velocity but I can't work out how to rotate it locally so that it is always pointing the right direction.

I tried to work out the difference in the angles and then create a Rotation matrix to apply to its rotation, but that didn't give me the desired results.

I am working in DirectX. Any help would be appreciated

# Answer
> 1 votes
You could rebuild the spears orientation matrix from a direction vector.

Good example with dx code is here..

https://stackoverflow.com/questions/4237873/rotate-a-sphere-so-that-its-pole-heads-towards-the-camera/4237921#4237921

---
Tags: c++, mathematics, directx, rotation, transformation
---


# Question
Title: Backend for data-driven multiplayer game
I am working on a match-based (5v5) multiplayer steam game that is similar to TF2, LoL, Dota 2, etc.

I am planning a data-driven approach where character/abilities/items/etc are defined in data (JSON). This will allow for easy patching to constantly balance the game.

So I have something like the following. (obviously simplified)

```
{
    "Troll": {
        "name" : "Troll",
        "health" : "100",
        "abilities" : [
            {
                "name" : "ClubSwing",
                "damage" : "50"
            },
            {
                "name" : "FootSmash"
                "damage" : "100"
            }
        ]
    },
    "Orc": {
        "name" : "Orc",
        "health" : "50",
        "abilities" : [
            {
                "name" : "SwordSwing",
                "damage" : "10"
            },
            {
                "name" : "ArrowShoot",
                "damage" : "25"
            }
        ]
    }
}

```

I am wondering what the best practice way is for storing this data. I obviously can't store it client-side or the player will be able to cheat. Is it normally stored in the database? I haven't setup any backend for my game yet. Should I setup a nodejs server with a nosql database like mongodb to be the master of this data? And then build a REST API on top of that for reading this data?

I also need to write some things to a database. Such as the users rank, items, game stats, etc.

Would it be better to have two separate databases? One for reading gameplay data like I have above and another reading/writing user information (stats, rank, items, etc.)

Or would it be wiser to use a single database? Would you recommend nosql or sql based?

Note: The game engine I'm using is unreal engine 4. Currently I am using a listen server (peer-to-peer), but think it may be necessary to eventually use the dedicated server instead.

# Answer
> 3 votes
You probably do want to communicate to this information to the client so that they are able to view it. You can treat the client as a dummy terminal though with sparkly representation and have a "neutral" server as the authority.

Lets consider League of Legends in this context.

At the beginning of the game, each client connects to Riots servers. Every time a player moves or attacks, the client plays the animation and sends the action to the server. The server calculates the outcome and sends it to the relevant clients. If you broadcast all information to all clients then you are leaking in the sense that a client can know what is occurring in the fog of war and they should not be able to. The information transmitted affects the game state.

It is worth doing some calculations client-side though such as collision detection to prevent walking through walls or minions. This offloads some non-critical calculations and decreases latency. This does mean a client could allow itself to walk through walls, however because movement affects game state the server would still be aware of it so you could detect this kind of "attack".

In summary, the server is the final authority of the game state so it would be best to store data on the server. NoSQL vs a relational database is up to you, but odds are you can use a relational database will preform satisfactorily.

Tou most likely want to implement a binary network protocol as opposed to a textual one. This allows you to decrease the amount of data sent to convey the same information. Consider the following example, player A attacks player B. Please note this is contrived and does not include any method of ensuring message integrity.

Text Protocol Message \[size=10B\]: A attack B

Binary Protocol Message \[size=3B\]: 0x1 0x1 0x2 -

This link discusses the LoL protocol a bit, https://nelsonslog.wordpress.com/2014/08/07/league-of-legends-game-protocol/ .

# Answer
> 2 votes
I wouldn't store them on clients, or even ship that information with game. If security is your main concern, fetch all informations required at the beginning of the game (from a database), store them temporarily, and delete them after the game session ends.

You can also cross-check local data with database during gameplay if you want an extra layer of security.

---
Tags: architecture, multiplayer, server, databases, data
---


# Question
Title: How do I get data from a WWW object without freezing my game?
I am using Unity 3d to create a real time multiplayer game. I have a database set up that keeps track of player statistics and what in app purchases they have purchased. I have written a Database class that is used to access my database via php scripts. It all works pretty well, but I run into problems when I try to get values from the database and it doesn't return quick enough. My assumption is that I need to use a coroutine in order keep letting it run so that I can eventually get the value. How exactly would I do that though?

This is the code I currently have:

```
public string GetValue(string id, string valid)
{
    string hash = Md5Sum(string.Format("{0}{1}{2}", id, valid, secretKey));
    string url = string.Format("{0}id={1}&vid={2}&hash={3}", getValue, id, valid, hash);
    WWW www = new WWW(url);
    while (!www.isDone) { }
    return www.text;
}

```

I figured that by adding the while loop in the middle it would always return a value but it doesn't seem to work that way. Should this be in a coroutine? And if so how would I get my value back from it compared to how I currently do it where it just returns the string value I wanted.

# Answer
Yes, you can use a coroutine for this. It's essentially making it asynchronous.

The documentation for the `WWW` class actually has an example for this:

```
public class ExampleClass : MonoBehaviour {
    public string url = "http://images.earthcam.com/ec_metros/ourcams/fridays.jpg";
    IEnumerator Start() {
        WWW www = new WWW(url);
        yield return www;
        Renderer renderer = GetComponent<Renderer>();
        renderer.material.mainTexture = www.texture;
    }
}

```

In this example the call is made via the `Start()` method of the script. Likely a good place to be loading data from your database. However, you could also convert this to a method call, similar to your existing code, by passing in a callback:

```
 public string GetValue(string id, string valid)
 {
     string hash = Md5Sum(string.Format("{0}{1}{2}", id, valid, secretKey));
     string url = string.Format("{0}id={1}&vid={2}&hash={3}", getValue, id, valid, hash);
     StartCoroutine(QueryDB(url, (myReturnValue) => {
         if(myReturnValue) { ... }
     });

 }

 IEnumerator QueryDB(string url, System.Action<string> callback)
 {
     WWW www = new WWW(url);
     yield return www;
     callback(www.text);
 }

```

This creates a method on the fly to take the action you're interested in when the coroutine finishes (that's the `if(myReturnValue) { ... }` part).
> 2 votes

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


# Question
Title: Storing and using UV and Normal Data with OpenGL
I'm having trouble mapping UV coordinates to vertices in OpenGL. I'm binding my buffers and enabling all of my attrib arrays perfectly well and things are rendering - but what I'm stuck on is how to map UV and Normal data.

You can't just store UV and Normal data with the Vertex data, because obviously you'll be re-using vertices, but not necessarily with the same Normal or UV.

For clarity this is the general flow of what I'm doing at the moment:

1. I bind my shader program.
2. I bind my vertex array buffer with GL.BindBuffer
3. I Bind my element buffer with GL.BindBuffer
4. I use GL.Uniform (1, 2, 3 or 4) to bind values to my uniform variables
5. I enable all of my vertex buffer attributes with GL.EnableVertexAttribArrau and then encode their layout using GL.VertexAttribPointer
6. I draw using GL.DrawElements
7. I disable all of my vertex attrib arrays again

I'm totally stuck on how to encode UV and Normal data to my vertex attributes. Do I need to use a second buffer? If so; how does OpenGL know to use a different set of indices to find them? I'm totally lost and any help would be greatly appreciated.

# Answer
> 0 votes
OpenGL does not allow for indexing position, uv and normals separately. There can be only one index buffer. Your best bet is to allow redundant position data. Some reuse by using indexing may be possible (and yield better quality) where faces share an averaged normal and uv.

---
Tags: opengl
---


# Question
Title: Black Screen when using High-Performance NVIDIA Processor
I have an issue where my program renders a black screen on other computers. I narrowed it down to when a different graphics card is being used. When I run the program using Integrated Graphics (default) it works just fine. However, when I run the program using High-Performance NVIDIA Processor it just shows a black screen.

I am using non-static Glew32 that I made using CMAKE specifically for Visual Studio 11 2012 Win32. Glew experiment is set to true.

Shader errors output to log file. (There are none right now)

---

**Main Question:** Is there a specific way of setting up and rendering OpenGL for NVIDIA Graphics so that it renders properly, and not a black screen? Alternatively, is there a way to setup and use OpenGL so it works on every graphics card?

---

**Edit**: nvcompatlog.txt: *Trying to draw without a program bound.*

(Is this a big clue as to what is wrong? I can not find anything about how to solve this in any specific google search.)

I'm assuming this means my shader program is not being bound before I am rendering. So there must be something there that NVIDIA does not like.

I have another shader that just renders with Ortho view fonts/UIelements, and those render just fine ontop of the black screen.

I stripped my shader down to pretty much nothing. Got rid of all glGetUniform calls to uniforms that do not exist, all variables that aren't used are gone. Still black screen.

---

**OS**: Windows 8.1, 64-bit

**GPU**: GeForce GTX 970M

---

**Source Code:**

**Generating VBO, VAO, etc.**

```
    glGenVertexArrays( 1, &mesh->GL_VBO_ID );
    glBindVertexArray( mesh->GL_VBO_ID );
    CheckGLError();

    glEnableVertexAttribArray ( 0 );
    glEnableVertexAttribArray ( 1 );
    glEnableVertexAttribArray ( 2 );
    CheckGLError();

    glGenBuffers ( 1, &mesh->GL_VertexBuffer_ID );
    glGenBuffers ( 1, &mesh->GL_IndexBuffer_ID );
    CheckGLError();

    glBindBuffer ( GL_ARRAY_BUFFER, mesh->GL_VertexBuffer_ID );
    CheckGLError();

    unsigned int totalVertBufferSizeBYTES = numIndicesInIndexArray * sizeof ( sVertex_p4t4n4 ); ;
    glBufferData ( GL_ARRAY_BUFFER, totalVertBufferSizeBYTES, pTempVertArray, GL_DYNAMIC_DRAW );
    CheckGLError();

    unsigned int bytesInOneVertex = sizeof( sVertex_p4t4n4 );
    unsigned int byteOffsetToPosition = offsetof( sVertex_p4t4n4, Pos );
    unsigned int byteOffsetToNormal = offsetof( sVertex_p4t4n4, Normal );
    unsigned int byteOffsetToUVCoords = offsetof( sVertex_p4t4n4, TexUVx2 );

    glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, bytesInOneVertex, (GLvoid*)byteOffsetToPosition );
    glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, bytesInOneVertex, (GLvoid*)byteOffsetToUVCoords );
    glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, bytesInOneVertex, (GLvoid*)byteOffsetToNormal );
    CheckGLError();

    glBindBuffer ( GL_ELEMENT_ARRAY_BUFFER, mesh->GL_IndexBuffer_ID );
    CheckGLError();

    unsigned int sizeOfIndexArrayInBytes = numIndicesInIndexArray * sizeof( GLuint );

    glBufferData ( GL_ELEMENT_ARRAY_BUFFER, sizeOfIndexArrayInBytes, pIndexArrayLocal, GL_DYNAMIC_DRAW);
    CheckGLError();

    glBindVertexArray( 0 );
    CheckGLError();

```

**Rendering**

```
glBindVertexArray ( pGameObject->GL_VBO_ID );
unsigned int numberOfIndices = pGameObject->numTriangles * 3;
glDrawElements( GL_TRIANGLES, numberOfIndices, GL_UNSIGNED_INT, (GLvoid*)0);
CheckGLError();

```

**Create Window**

```
case WM_CREATE:
    {
        this->m_hdc = GetDC(hWnd);
        setupPixelFormat();

        int attribs[] = {
            WGL_CONTEXT_MAJOR_VERSION_ARB, 4,
            WGL_CONTEXT_MINOR_VERSION_ARB, 0,
        0};

        // Create temporary context to get a pointer to the function
        HGLRC tmpContext = wglCreateContext(m_hdc);
        // Make it current
        wglMakeCurrent(this->m_hdc, tmpContext);

        //Get the function pointer
        wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC) wglGetProcAddress("wglCreateContextAttribsARB");

        // If this is NULL then OpenGL 4.0 is not supported
        if ( !wglCreateContextAttribsARB )
        {
            MessageBox(NULL, "OpenGL 4.0 is not supported, falling back to GL #.#", "An error occurred", MB_ICONERROR | MB_OK);
            this->m_hglrc = tmpContext;
        }
        else
        {
            //Create an OpenGL 4.0 context using the new function
            this->m_hglrc = wglCreateContextAttribsARB(this->m_hdc, 0, attribs);
            // Delete the temporary context
            wglDeleteContext(tmpContext);
        }

        // Make the GL context current
        wglMakeCurrent(this->m_hdc, this->m_hglrc);

        // We are running!
        this->m_bIsRunning = true;
    }
    break;

```

**Vertex Shader**

```
#version 400

layout(location=0) in vec4 in_Position;
layout(location=1) in vec4 in_UV_x2;
layout(location=2) in vec4 in_Normal;

out vec4 ex_PositionWorld;
out vec4 ex_Normal;
out vec4 ex_UV_x2;

uniform mat4 ModelMatrix;
uniform mat4 RotationMatrix;
uniform mat4 ViewMatrix;
uniform mat4 ProjectionMatrix;

void main(void)
{
    mat4 MVP = ProjectionMatrix * ViewMatrix * ModelMatrix;
    gl_Position = MVP * in_Position;

    ex_PositionWorld = ModelMatrix * in_Position;
    ex_Normal = RotationMatrix * normalize(in_Normal);
    ex_UV_x2 = in_UV_x2;

    return;
}

```

**Fragment Shader**

```
#version 400

// in from vertex shader
in vec4 ex_PositionWorld;
in vec4 ex_Normal;
in vec4 ex_UV_x2;

// Default colour output
out vec4 out_Colour;

// Lights
struct LightDesc
{
    vec3 position;
    vec3 direction;
    vec3 ambient;
    vec3 diffuse;
    vec3 specular;
    float attenConst;
    float attenLinear;
    float attenQuad;
    float angle;
};
const int NUMLIGHTS = 10;
uniform LightDesc lights[NUMLIGHTS];

// Material
struct MaterialDesc
{
    vec3 ambient;
    vec3 diffuse;
    vec3 specular;
    float shininess;
};
const int NUMMATERIALS = 1;
uniform MaterialDesc materials[NUMMATERIALS];
int curMat = 0;

// 1 Texture
uniform sampler2D Texture00;

// 1 CubeMap
uniform samplerCube SamplerCube00;  // Used mostly for skybox. (Like to reserve for skybox reflections if illum set

// Shader ID
uniform int ShaderId;

// Camera
uniform vec3 eye;

vec3 ADSLightModel( in vec3 Normal,
                    in vec3 Position,
                    in int LightIndex );

void main(void)
{
// The SkyBox
    if ( ShaderId == 1 )
    {
        vec4 colour = texture( SamplerCube00, ex_Normal.xyz );

        out_Colour = vec4(colour.xyz, 1.0f);

        return;
    }

    vec4 colour = texture( Texture00, ex_UV_x2.xy);

    vec3 lightContrib = vec3(0.0f, 0.0f, 0.0f);
    for (int lightIdx = 0; lightIdx < 10; lightIdx++)
    {
        lightContrib += ADSLightModel(ex_Normal.xyz, ex_PositionWorld.xyz, lightIdx);
    }

    colour *= lightContrib;
    colour = clamp(colour, 0.0f, 1.0f);

    out_Colour = vec4(colour.xyz, 1.0f);

    return;
}

vec3 ADSLightModel( in vec3 Normal,
                    in vec3 Position,
                    in int LightIndex )
{
    if ( length(lights[LightIndex].direction) != 0.0f )
    {
        vec3 diff = normalize(Position - lights[LightIndex].position);
        if ( dot(diff, lights[LightIndex].direction) < lights[LightIndex].angle )
            return vec3(0.0f, 0.0f, 0.0f);
    }

    // normal, light, view, and light reflection vectors
    vec3 norm =     normalize( Normal );
    vec3 lightv =   normalize( lights[LightIndex].position - Position);
    vec3 viewv =    normalize( eye - Position );
    vec3 refl =     -( reflect( lightv, norm ) );

    // ambient light computation
    vec3 ambient = materials[curMat].ambient * lights[LightIndex].ambient;

    // diffuse light computation
    vec3 diffuse = max(0.0f, dot(lightv, norm))
                   * materials[curMat].diffuse
                   * lights[LightIndex].diffuse;// myLightDiffuse;

    // Calculate Attenuation
    float dist = distance( Position, lights[LightIndex].position );
    float atten = 1.0f /( lights[LightIndex].attenConst +
                          lights[LightIndex].attenLinear * dist +
                          lights[LightIndex].attenQuad * dist * dist );

    diffuse *= atten;

    // specular light computation
    vec3 specular = vec3( 0.0f, 0.0f, 0.0f );
    if( dot(lightv, norm) > 0.0f )
    {
        specular = pow( max(0.0f, dot(viewv,refl)), materials[curMat].shininess)
                    * materials[curMat].specular
                    * lights[LightIndex].specular;// // myLightSpecular;
        specular *= atten;
    }

    return clamp( ambient + diffuse + specular, 0.0f, 1.0f );
}

```

---

**ErrorLog**: (*There were no errors in log at one point, and black screen was still a result*) **The only error previously was when glDrawElements was called.** *Don't focus directly on these errors to answer my question. This is just here for extra information.*

```
[cGameWindow.cpp:191] INVALID_ENUM   // (Right after GlewInit() *not false*)
4.00 NVIDIA via Cg compiler
[cShaderManager.cpp:112] INVALID_OPERATION  (glUseProgram)
[cRenderManager.cpp:312] INVALID_OPERATION  (glGetUniformLocation)
[cRenderManager.cpp:232] INVALID_OPERATION  (glClearColor)
[cRenderManager.cpp:357] INVALID_OPERATION  (glUniform...)
[cRenderManager.cpp:662] INVALID_OPERATION  (glUniform...)
[cRenderManager.cpp:685] INVALID_OPERATION
[cRenderManager.cpp:401] INVALID_OPERATION
[cRenderManager.cpp:410] INVALID_OPERATION
[cRenderManager.cpp:662] INVALID_OPERATION
[cRenderManager.cpp:591] INVALID_OPERATION
[cRenderManager.cpp:509] INVALID_OPERATION
[cRenderManager.cpp:662] INVALID_OPERATION
[cRenderManager.cpp:509] INVALID_OPERATION
[cRenderManager.cpp:662] INVALID_OPERATION
...
...

```

**ErrorLog** With stripped fragment shader (Minimal stuff)

```
[cGameWindow.cpp:191] INVALID_ENUM
4.00 NVIDIA via Cg compiler

```

# Answer
> 1 votes
> Main Question: Is there a specific way of setting up and rendering OpenGL for NVIDIA Graphics so that it renders properly, and not a black screen?

NVIDIA graphics cards are no different from any other cards seen from an OpenGL perspective. Different behavior on different platforms may exist as a result of: \- Different capabilities. Some cards may tolerate bigger uniform storage than others. OpenGL standard often require a ridiculous minimum leaving how much is needed to please custumers to the vendors to decide. \- Bug in the driver. \- Your code is reliant on undefined behavior. This may work perfectly well for you on many platforms, in some cases without warnings.

> Alternatively, is there a way to setup and use OpenGL so it works on every graphics card?

Sure. Stay within the limitations of your platform. Review your code against the OpenGL standard and look for definitions not matching your required behavior. If reliant on extension, check for them at context creation and shutdown if not found. If any OpenGL error is generated your code should be considered utterly broken. One error is enough.

---
Tags: opengl, c++, glsl, windows, nvidia
---


title: Invalid GLSL on some machines

text:
# Question
Title: Invalid GLSL on some machines
I'm writing a game engine using OpenGL 4.3 using gcc 5, mainly to teach myself graphics programming.

Initial development was on my Surface Pro 3 using mingw-w64 and worked like a charm.

I've decided to move to my desktop, which is running two GTX 670s, and both Windows and Arch Linux. I've made sure that I have the latest NVIDIA drivers installed on both operating systems, but am having issues with my vertex and fragment shaders. All I know is that neither system compiles the shaders, but the OpenGL Reference Compiler simply issues a warning saying that OpenGL 4.3 might not be fully implemented. I've also tried downgrading all the way to OpenGL 4.0, but this doesn't seem to fix the issue.

Below are the shaders that I'm currently trying out. Hoping someone more experienced than I can lend a hand?

shader.vert:

```
#version 430

layout (location = 0) in vec3 vertex_position;
layout (location = 1) in vec2 vt;

uniform mat4 cam_view, cam_proj, sprite_matrix;

out vec2 texture_coordinates;

void main()
{
   texture_coordinates = vt;
   gl_Position = cam_proj * cam_view * sprite_matrix * vec4(vertex_position, 1.0);
}

```

shader.frag:

```
#version 430

in vec2 texture_coordinates;
layout (binding = 0) uniform sampler2D tex;

out vec4 frag_colour;

void main()
{
   vec4 texel = texture(tex, texture_coordinates);
   frag_colour = texel;
}

```

Thanks in advance :)

# Answer
> -1 votes
http://www.geforce.com/hardware/desktop-gpus/geforce-gtx-670/specifications

Nvidia homepage says only 4.2 is supported.

Check the error logs and for any other opengl error and fix them if any.

---
Tags: opengl, c++, glsl, glfw
---


# Question
Title: Rotate smoothly object to angle (Y axis) of the collided object
Well, let's say I have two planes, one which I am moving, and another one that I collide with, that has a different y rotation. I want to make that, once both planes collide, the plane the user controls changes it´s rotation to the collided plane rotation.I´ve achieved it simply equaling both planes transform.rotations, but that was just a testing, i would like to rotate the plane smoothly. I have tried with eulerAngles, and Quaternion.Lerps, but it doesn´t work, or I am not following well the sintaxis. I know that a rotation and the eulerAngles are different values. There seems to be a solution with the dotween scripts, but I would like to learn the right approach to do it, rather than make it directly with dotween. Here I paste the trigger enter code, with the methods I tried (are commented). I guess that the rotation origin would be another issue.

```
void OnTriggerEnter(Collider col)
{
    if (col.gameObject.tag == "Plane")
    {
        Debug.Log ("Yup...Angle: " + col.gameObject.transform.rotation.y);
        //this.transform.rotation = col.gameObject.transform.rotation;

        /*newAngle 0 (this.transform.eulerAngles.x, col.gameObject.transform.eulerAngles.y, this.transform.eulerAngles.z);
        this.transform.eulerAngles(newAngle, 2 * Time.deltaTime);*/
        this.transform.rotation = Quaternion.Lerp (this.transform.rotation, col.gameObject.transform.rotation, Time.deltaTime * 0.1f);
    }
}

```

# Answer
> 0 votes
You are most of the way there already.

The problem is, OnTriggerEnter only happens once. Quaternion.Lerp changes the value over time, at the speed specified by the timestep. Since it is only being called once, it will only move the rotation one step. In this case, .1f * Time.deltaTime is your step. This is a very small number. It needs to move that small of a step many many times until the two values are equal.

If you made the step equal to the difference between the two values, that single call would be the same as setting one equal to the other.

So we need to move Quaternion.Lerp to something like Update() where it will happen dozens/hundreds of times.

Basically this:

```
private Quaternion targetRotation;
private float rotationSpeed = 2;

void Update()
{
    transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, rotateSpeed * Time.deltaTime);
}

void OnTriggerEnter(Collider col)
{
    if (col.gameObject.tag == "Plane")
    {
        targetRotation = col.gameObject.transform.rotation;
    }
}

```

---
Tags: unity, 3d, quaternion, angles
---


# Question
Title: how to bring movement and rotation vectors of object in the current scene in unity editor
sometimes in unity i need to zoom to fix the exact position and rotation of an object. but movement and rotation sign of the object always stays on object and i think its pivot of the object.

How can i really bring those movement and rotation signs to simply perform those translations of my object?

thank you for helping.

# Answer
> 1 votes
A crude solution is to create a new, empty game object. By default, it will be created at the center of your scene view.

Next, parent the object you want to edit to this new object.

Now, use the new object's transform controls to manipulate the whole thing. (If its controls are off-screen, make sure you switch to pivot instead of object center mode)

When you're done, unparent the object back to its original place in the hierarchy and delete the empty object.

---
Tags: unity
---


# Question
Title: What can be a game-play element in a game with Shakespeare's plays as the main theme?
I was thinking of learning about making games, so I thought of an idea about making a game on a play, since the content is already there. I actually found well parsed XMLs of Shakespeare's plays. I thought of a few rather simple game-play elements, but none seem fun. I thought of a 'word shooter' but it wouldn't be much fun since there are so many speech lines. Then I thought of a game where you have to match which of the characters currently on the screen said a particular dialog.

I know that this game probably will not be much fun, but I could try to make it fun. What I may be able to do right now is make an application which 'enacts' the whole play. You can skip right to any act or a scene in an act etc. It will be a 2d game and i will use pygame.

# Answer
How about these as options (both implemented as some kind of point-click adventure)...

a) Break down the story and have the player have to say the right things at the right parts. If he doesn't, something funny (and usually painful) happens down the line. It may not be immediately afterward, so for example (if the player knows the play) and MacBeth asked the wrong questions of the witches for example, he might not be warned, "Beware the ides of March!" and so he gets axed at some inopportune moment because he's out playing croquet on the ides of March... or something like that. You get the idea.

b) Have the story play through linearly. But insert extra bits in between parts of the actual story, things that might have happened to the main character(s), and play those bits out. interactively. So for example after some speech in Othello, he's ravenously hungry and you have to help him find the kitchens or he comes to an ignoble end.

Traditional stories are linear, that's why they tend not to translate too well to an interactive experience. It's the interactiveness that makes things fun. However, the best value you're going to get from Shakespeare's plays comes from his excellent stories and characters. Basically if you view a story as a linear sequence of events i.e. a linear graph, then in case (a) you are allowing branchings in that graph, but those branchings immediately lead to a cut scene detailing the consequences of failure (i.e. of choosing the wrong action). Whereas with (b), you are lengthening the graph by inserting extra "pieces" of interactive story in between the main (and mandatory) parts of the graph. In this latter case, wrong choices need not be fatal, they can just be for fun, because it doesn't affect the outcomes of each part of the main storyline.
> 2 votes

# Answer
How about a 'Find the Item' game where you hide an item somewhere in the play / act / scene. You have a time scroller so you can go back and forward through the play enactment looking for that item hidden somewhere in one scene. And/or you could have multiple items flashed to the player before the game begins and he has to find as many as he can in a time limit. Have multiple decoy items, or have all items selectable so you can click any item for an answer.

There there's an obvious 'tomato throw' game. Try to hit the actors by launching tomatoes at them, or target non-actors too, depending on the objective.

'Shakespeare Hero' - Have the words come at you while they are being spoken/presented, and either type them as a typing test, or click them to a certain rhythm (ha, can't really see how this would work, but it would be funny!)

'Mystery' - Have the player watch a scene, and ask her a question afterwords. The question could be about the written content (ie: Who said "...."), or have the actors 'randomly' doing quirky things not related to the play, such as scratching, sitting, sneezing, etc, then quiz them on who did what.
> 2 votes

# Answer
How about a theater manager game, where you can hire actors, upgrade the scene. You get money based on the audience. The actors could also have experience levels and/or stats. You could also expand this game to other plays, or make some mini-games in it, like some button-mashing, some kind of "improvise" mini-game etc.
> 1 votes

# Answer
There was some very nice take on similar topic in Psychonauts.

There you had set with decors and few plays and a sad/happy lighting. So by switching between modes you transformed the plays to achieve your goal.

So you sandbox the plays, and give options to influence and mutate some key scenes to advance.

So your protagonist is trapped in the world of Shakespeare plays and lets say he needs to solve puzzle that requires poison, so he must save Romeo and Juliet etc etc. So we have gameplay where he must think what he may use from each play and some QTE and other ways to influence the plays plot to obtain the items he needs.
> 1 votes

# Answer
Not sure if it would be something you want to consider, but something I've seen work well with classic works (the specific ones I had in mind used fairy tales instead of Shakespeare) is to have the player be a third party participant that is effected by the play.For instance, in World of Warcraft they played out a raid boss as Little Red Riding Hood and the story played out during the fight with certain lines predicting certain moves. This wouldn't need to be translated directly, but maybe you can do some form of puzzle where the lines of the play give a clue about how to solve it. Like maybe in a mystery style game, to be or not to be clues the player in to needing to find something related to Hamlet or the skull that is classically portrayed with Hamlet. It actually also ties into following e-MEE's thinking of a manager of a theater. They would be the third party interacting with the play from outside of it.

There is also the idea of possibly making something like the scene it games that used to be really popular. While you may not be able to have professional video like those games did due to budgets, copyrights, and rights. You still may be able to pull of something fun like that with virtual trivia that is more than just text.
> 0 votes

---
Tags: game-design, pygame
---


# Question
Title: Enemy AI with Rigidbody - Floating in the air
I'm working on my enemy AI scripts and I'm using a rigidbody to have the enemies chase the player when the player gets into its aggro distance.

Two of the main problems I'm having:

1. When the game starts, all the enemies are floating in the air
2. Even when the player is outside the enemie's aggro distance, the enemy still chases the player

**Code:**

```
using UnityEngine;
using System.Collections;

public class EnemyAI : MonoBehaviour {
    public Transform target;
    public int moveSpeed;
    public int rotationSpeed;
    public int attackSpeed;
    public int maxDistance;
    public int aggroDistance;

    private Transform myTransform;
    public Rigidbody rb;
    private Vector3 dir;

    void Awake() {
        myTransform = transform;
        rb = GetComponent<Rigidbody>();
    }

    void Start () {
        character = GetComponent<CharacterController>();
        //Find playerS
        GameObject go = GameObject.FindGameObjectWithTag("Player");
        //Set player as target
        target = go.transform;

        maxDistance = 2;
        aggroDistance = 10;
    }

    void Update() {
        dir = target.position - rb.position;
        dir.Normalize();
        transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(dir), rotationSpeed * Time.deltaTime);

        if (Vector3.Distance(target.position, myTransform.position) < aggroDistance) {
            if (Vector3.Distance(target.position, myTransform.position) > maxDistance) {
                rb.MovePosition(transform.position + transform.forward * moveSpeed * Time.deltaTime);
            }
        }
    }

    void FixedUpdate () {
        rb.AddForce (dir * rotationSpeed);
    }
}

```

**Enemy Properties:**

# Answer
You are manipulating your GameObject's `RigidBody` as well as its `Transform`. This is a no-no.

From the Official Unity Documentation: http://docs.unity3d.com/Manual/class-Rigidbody.html

> Rigidbodies allow your GameObjects to act under control of the physics engine. This opens the gateway to realistic collisions, varied types of joints, and other very cool behaviors. Manipulating your GameObjects by adding forces to a Rigidbody creates a very different feel and look than adjusting the Transform Component directly. **Generally, you shouldn’t manipulate the Rigidbody and the Transform of the same GameObject - only one or the other.**

However, sometimes you will want to have objects within your game world that *can* react to physics at certain times, just not all the time. For example you may want your enemies to be controlled manually by your script when they are alive, but when they die they could become ragdolls and fall to the floor convincingly.

The way you do this is by using the **isKinematic** property on the `RigidBody`. When set to true, your GameObject will not react to physics events, however it can still cause physics events on other objects that have a `RigidBody`. So you can directly manipulate the `Transform` of an object marked **isKinematic**. This property can be manually turned on/off in your scripts.

More info on **isKinematic** here: http://docs.unity3d.com/ScriptReference/Rigidbody-isKinematic.html

---

## What you need to do:

* On your Enemy's `RigidBody`, set **isKinematic** to true.
* Manipulate the `transform` but **not** the `rigidbody`.

When you need to, you can make your Enemy react to physics again by doing:

```
rb.isKinematic = false;

```

Now you can manipulate the `rigidbody` but **not** the `transform`.

In your code you should change

```
rb.MovePosition(transform.position + transform.forward * moveSpeed * Time.deltaTime);

```

to

```
transform.position = Vector3.MoveTowards(transform.position, target.position, moveSpeed * Time.deltaTime);

```

and you should remove the code from `FixedUpdate()`.

I hope this helps you solve your problem :)
> 1 votes

# Answer
Remove the FixedUpdate. Each frame you set "dir" to point towards the player and then apply a force in that direction regardless of the distance, so your rigidbody is always going to move towards the player. And you are already rotating and changing the position of the enemy in Update, so the FixedUpdate isn't needed.
> 0 votes

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


# Question
Title: how can i take the value of a vector 3 from a liste of vector 3
```
foreach (Vector3 posit in position){
    if (ang){

        float a = Random.Range (0.0f, 60.0f);
        //Vector3 p1= new Vector3((position[i-1].x)+(ra*cos(a)),0.0f,(position[i-1].z)+(ra*Sin(a)));

    //  position.Add(p1);

    }
    else
    {
        //Quaternion.Angle=60.0f;
        float a = Random.Range (120.0f, 290.0f);

    }
    Vector3 p1 = new Vector3((posit[i-1].x)+(ra*(Mathf cos(a))), posit[i].y,(posit[i-1].z)+(ra*(Mathf Sin(a))));

    position.Add(p1);

    ang=!ang;
    //return(pos);
    i++;
}

return(position[i]);

```

}

# Answer
Instead of `foreach`, you'll want to use `for`.

```
for (int i = 0; i < position.Count; i++) {
    Vector3 posit = position[i];
    ...
}

```

This way, you'll be able to access the previous position using `position[i-1]`.

Keep in mind, however, that this won't work if `i == 0` because you can't go less than zero, so you'll want to add some checks to ensure `i > 0` before using `position[i-1]`.
> 3 votes

---
Tags: vector
---


title: Draw rectangles on Cube and remove

text:
# Question
Title: Draw rectangles on Cube and remove
I have 3d object as Wall ( Cube with texture and width and height large ) with some texture and attached c# ( Unity 5.3.2 ) script to that wall. I want to programmatically draw rectangles on that Wall with green semitransparent color and after 5 seconds remove them. I am new to Unity and found OnGui but it is not drawing in 3d space but in front of screen. How to achieve this to draw and remove rectangles on Wall ?

# Answer
> 1 votes
It sounds like you're after what are usually called "Decals" (not to be confused with this legacy decal shader!). They're typically used for things like bullet holes, posters, or anything you wouldn't want to paint into a texture.

To do that, you can instantiate things called billboards on your wall parallel to its surface, slightly away from it so it doesn't Z-fight. Whatever is instantiating them should keep track of the instances, then either deactivate (`billboard.SetActive(false)`) or destroy them after a certain amount of time (`destructTime = Time.time + lifespan; ... if(Time.time > destructTime) ...`).

Alternatively, there is at least one ready made asset in the Unity Store that will do the same thing. Just search for "Decal"

# Answer
> 0 votes
The Unity standard shader has a second "secondary map" texture. That texture is drawn over the primary one. You can draw your rectangles to a procedurally generated texture and then assign it to the secondary map of your wall-material.

---
Tags: unity
---


# Question
Title: Unity C#: Change speed when all Targets are destroyed
I have a game where a Gunner moves on a pre-set path towards a final destination. You play as a Magic Bullet that auto-fires from the Gunner's current position and can be controlled with WASD. When the bullet collides with a Target, it's destroyed.

My question: How do I change the speed of the Gunner after all of the Targets are destroyed? The idea if for the Gunner to hurry to the end, instead of skilled players waiting around.

Any help would be greatly appreciated. Here's what I have so far:

```
using UnityEngine;
using System.Collections;

public class MovementPathScript : MonoBehaviour {

    public GunnerPathScript PathToFollow;
    public int CurrentWayPointID = 0;

    private float speedVariable;
    public float gunnerSpeed;
    public float hurrySpeed;

    private float reachDistance = 1.0f;
    public float rotatationSpeed = 5.0f;

    public string pathName;

    public static Quaternion gunnerRotation;

    private Vector3 last_position;
    private Vector3 current_position;

    void Start () {
        last_position = transform.position;
    }

    void Update () {

        float distance = Vector3.Distance (PathToFollow.path_objs [CurrentWayPointID].position, transform.position);
        GunnerMove ();

        PointTowards ();

        if (distance <= reachDistance) {
            CurrentWayPointID++;
        }

        if (CurrentWayPointID >= PathToFollow.path_objs.Count) {
            CurrentWayPointID = 13;
        }
    }

        void GunnerMove(){
            transform.position = Vector3.MoveTowards (transform.position, PathToFollow.path_objs [CurrentWayPointID].position, Time.deltaTime * speedVariable);
            speedVariable = gunnerSpeed;

        if (GameObject.FindGameObjectsWithTag ("Target") == null) {
            speedVariable = hurrySpeed;
            //Unity doesn't recognize this, and maintains gunnerSpeed

        }
    }

    void OnTriggerEnter(Collider other){
        if (other.gameObject.CompareTag ("Target"))
            Destroy (this.gameObject);
    }

    public void PointTowards(){
        var gunnerRotation = Quaternion.LookRotation (PathToFollow.path_objs [CurrentWayPointID].position - transform.position);
        transform.rotation = Quaternion.Lerp(transform.rotation, gunnerRotation, Time.deltaTime * rotatationSpeed);
    }
}

```

# Answer
> 1 votes
Change this line:

```
if (GameObject.FindGameObjectsWithTag ("Target") == null) {

```

To:

```
if (GameObject.FindGameObjectsWithTag ("Target").Length == 0) {

```

**Reason:** FindGameObjectsWithTag returns an array, it can never be null, but it can be "empty". So you need to check it's length.

---

Also note that this is an inefficient way of target tracking. It would be better if you keep a list of targets somewhere and check the count of that list.

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