title: Jump Point Search with Weights

text:
# Question
Title: Jump Point Search with Weights
Everywhere I've searched on the internet, people seem to assume that jump point search would not work with weighted grids. So why wouldn't it work with this simple modification to the algorithm:

This diagram here illustrates the circumstances that the traditional jump point search algorithm would add the node x to the open set.

Please note that the black squares are numbered 2 and 4 respectively.

In these two images, the reason x is added to the open set is because the optimal paths to the circled squares from the parent of x must go through x. I propose, that if any path going through x from the parent of x to a node around x is lighter than the corresponding path going around x, x should be expanded.

### Example psuedocode:

Please note that `weightOfPath` should return infinity if any of the nodes are impassable.

**Horizontal case:**

```
if weightOfPath(4,x,3) < weightOfPath(4,2,3) or weightOfPath(4,x,8) < weightOfPath(4,7,8):
    addToOpenNodes(x);

```

**Diagonal case:**

```
if weightOfPath(6,x,1) < weightOfPath(6,4,1) or weightOfPath(6,x,8) < weightOfPath(6,7,8):
    addToOpenNodes(x);

```

Why wouldn't this work?

# Answer
My thought is that JPS makes the assumption of things being symmetrical. Meaning two possible paths can give you the same path.

The problem when you add weights, some behavior becomes really undefined.

When an expansion hits a wall, it just stops. Period. It doesn't even create a new point.

But when it passes by a wall, and detects a space is open after the wall that a previous expansion couldn't get to it stops and creates a jump point.

My best guess is that you'd need to treat any areas with additional weights as just that. An area with an additional weight, and not create a new jump point when you enter, leave, or pass by.

This would mean that logically we'd be saying that we're just slowing down. But the route can get to the same place.

This is best seen as, "What can get me there faster" than "what is the shortest path". The shortest path could obviously lead you through quick sand that's only two feet deep. But the fastest is likely around it.
> 1 votes

---
Tags: path-finding
---


# Question
Title: Zero vector test in projection intersection test in SAT
I stumbled across this implementation for a projection intersection test to use in a SAT test:

```
// aCorn and bCorn are arrays containing all corners (vertices) of the two OBBs
private static bool IntersectsWhenProjected( Vector3[] aCorn, Vector3[] bCorn, Vector3 axis ) {

    // Handles the cross product = {0,0,0} case
    if( axis == Vector3.zero )
        return true;

    float aMin = float.MaxValue;
    float aMax = float.MinValue;
    float bMin = float.MaxValue;
    float bMax = float.MinValue;

    // Define two intervals, a and b. Calculate their min and max values
    for( int i = 0; i < 8; i++ ) {
        float aDist = Vector3.Dot( aCorn[i], axis );
        aMin = ( aDist < aMin ) ? aDist : aMin;
        aMax = ( aDist > aMax ) ? aDist : aMax;
        float bDist = Vector3.Dot( bCorn[i], axis );
        bMin = ( bDist < bMin ) ? bDist : bMin;
        bMax = ( bDist > bMax ) ? bDist : bMax;
    }

    // One-dimensional intersection test between a and b
    float longSpan = Mathf.Max( aMax, bMax ) - Mathf.Min( aMin, bMin );
    float sumSpan = aMax - aMin + bMax - bMin;
    return longSpan < sumSpan; // Change this to <= if you want the case were they are touching but not overlapping, to count as an intersection
}

```

I now don't really get why there is a check for the zero vector, i.e. these lines right here:

```
if( axis == Vector3.zero )
    return true;

```

Why can we immediately say that the projections intersect, when there is a zero vector as projection axis?

The code is from Acegikmo answer on this question right here: How many and which axes to use for 3D OBB collision with SAT

He just states, that:

> The cross product will give you a zero vector {0,0,0} when any two axes between the objects point in the same direction.

Can anyone clarify this?

# Answer
I did some reading on this, and in the book Game Physics Pearls, the following is stated:

***Edge-Edge (EE) is a degenerate case if the edges are parallel. Degenerate EE is the special case of either Edge-Vertex (EV) or Vertex-Edge (VE), which in turn may be a case of Vertex-Vertex(VV).***

***We can just skip and ignore all special cases for the purposes of obtaining (smin, dmin)***

In plain English, this means that if you produce a zero vector from the cross product, there is no point testing that vector, and should skip it. This makes sense, as attempting to obtain penetration depth would produce a spurious minimum penetration axis.

However, I still feel the code is incorrect, as there is no guarantee that the cross products will produce a "zero" vector, in the truest sense. the glm maths library, for example, will produce undefined results if two parallel vectors are crossed.

A better solution would be to zero test the vector outside that function, and also test it for being undefined. if either test is true, don't even call the function, and skip to the next axis to be tested.
> 1 votes

# Answer
> Why can we immediately say that the projections intersect, when there is a zero vector as projection axis?

Intuitively, the zero vector has no direction, and so can't be used to determine a line on which to project your vertices. The zero vector in this case could be thought of as a single point, and obviously the projection of anything on to that single point will only ever be that point, so all vertices projected on to that point can be said to yield segments that intersect.

As far as how the zero vector would get passed to this function in the first place; the cross product of parallel vectors is zero. So, assuming you understand how to obtain the list of possible separating axes by finding every possible cross product between the object's edges, if any particular axis was obtained from the cross product of two edges that happen to be parallel (one edge from object A and one edge from object B,) it will be the zero vector.
> 1 votes

---
Tags: separating-axis-theorem
---


# Question
Title: onClickListeners not working correctly (conflicting)
In my pause dialog, the exit is working correctly, but the resume isn't, if I press resume 3 times, the third time it's going to exit.

```
ImageButton btnPlayOn = UIFactory.createButton(txtrPlayOn);
btnPlayOn.setSize(40, 40);
btnPlayOn.setPosition(75, 75, Align.center);
dialogP.addActor(btnPlayOn);

ImageButton btnEndGame = UIFactory.createButton(txtrEndGame);
btnEndGame.setSize(40, 40);
btnEndGame.setPosition(75, 55, Align.center);
dialogP.addActor(btnEndGame);

btnPlayOn.addListener(new ClickListener() {
            @Override
            public void clicked(InputEvent event, float x, float y) {
                System.out.println("resuumeeeeeeee");

            }
        });

        btnEndGame.addListener(new ClickListener() {
            @Override
            public void clicked(InputEvent event, float x, float y) {
                System.out.println("exiiiiiiiiit");

            }
        });

```

I think I know why, it's because both buttons have the same x so the listener is getting confused. Anyhow I don't know how to fix it.

# Answer
Looks like the buttons are overlapping so both listeners get triggered. Moving the buttons so they are not on top of each other will fix it but you should be calling event.handle() inside onclick(), that will stop the event from propagating.

Charanor's comment is only valid if you are using Tablelayout.
> 1 votes

---
Tags: java, android, libgdx
---


title: Developing a Bot for Fanorona game

text:
# Question
Title: Developing a Bot for Fanorona game
I am currently developing a bot for a game board called Fanorona. The game is not as popular as other board games such as chess or backgammon, but still it brings a lot of fun. Some of you may know it from Assassins Creed 3, specifically the game Connor and Achilles play together.

http://gasy-fanorona.sourceforge.net/docs/fanorona\_rules.html

In this link I provided the basic rules.

I have studied what people usually use for bots for chess, algorithms like Alpha-Beta Minimax. These algorithms require a score system in order to make specific decisions, take into account the branching factor, which in this game is hard to estimate. Additionally, the bot could be trained to recognize patterns.

I have never worked with AI algorithms before, therefore I would like find out your opinion concerning this subject. What course of action would you employ in order to build a bot for this kind of game?

# Answer
> 2 votes
I am not proficient in this game, but the number of possible moves per turn seems to be quite limited, making it quite applicable for MiniMax.

As usual with MiniMax, the biggest challenge is to write a good rating function. Finding out how to tell a good position apart from a bad one requires some in-depth experience with the game.

A trivial solution to start out with to get the game running could be to simply consider **material** advantage only. Simply count the number of pieces each player has left. Whoever has more pieces on the board appears to be winning. This simple AI could already be strong enough to at least entertain a novice player. Even without alpha-beta pruning and a simple breadth-first search with a hard limit on the number of evaluated positions.

We have a completely deterministic game without information hiding here. That means this alone would in fact be enough to create a perfectly playing AI, **if** you have enough computing resources available to calculate the whole game from start to end. But that would 1. be very boring to play against and 2. you likely don't have enough computing resources available. That means you need to limit your search-tree depth. That means a more advanced rating function could make the AI much stronger.

When this AI turns out to be too weak, you could add some **tactical** analysis. One tactical rating criteria could be to account for the number of move-options each piece has left (more being better) and from how many positions each piece could be captured (less being better).

Another rating criteria could be a **strategic** analysis. You could, for example, reduce the rating of any stones which are in a formation which potentially allows the opponent to make multiple captures at once. Because even if the opponent might not be able to do that in the moves which appear in the current search tree depth, they might get an opportunity to exploit this formation in the future.

---
Tags: ai, board-game
---


title: Unstable sampled color in GLSL shader

text:
# Question
Title: Unstable sampled color in GLSL shader
It looks like that sampling the same exact color data from different areas of a texture atlas results in different `vec4` in the GLSL fragment shader.

In other words, `texture2D` is directly dependent of the specified texture coordinates, and not only transitively because of the color of the texel at those coordinates.

To say that with an example, I am getting the impression that sampling a red pixel surrounded by blue pixels from, say, `(0.1, 0.2)` may give a different result than sampling the same shade of red surrounded by the same shade of blue at, say, `(0.7, 0.3)`.

**Is this non-deterministic behavior that I am observing likely to be real?**

# Additional details

I have a atlas that we use to texture multiple screen-aligned quads. Each vertex has a `xy` position and `uv` texture coordinates. The allotted rectangles in the atlas do not overlap; furthermore, a 2 pixel margin exists between adjacent rectangles. We are using linear filtering and no mipmapping.

The atlas is populated dynamically using sprites downloaded from the web. Two different runs of the program may have the atlas populated in different orders, even if user input is exactly the same, due to the fact that some HTTP requests may complete before others.

So now imagine that on a run we have a Princess Peach sprite in the middle of the screen; the texture is coming from the upper left corner of the atlas, because Princess Peach was the first sprite added to the scene.

In another run, there have been a few sprites loaded but now their quads are not on the screen and again we have Princess Peach in the middle, in the same exact position as the first run. But this time the texture is coming from a different region of the atlas.

*Problem: rendered images are not the same. The differences are imperceptible and usually consist of only a few pixels near the edges of the rendered sprites. The differences are detected by a screenshot testing framework.* **Where is the source of randomness?**

# Even more details

* It's a WebGL project.
* It happens on both GeForce and Quadro cards.
* Using nearest neighbor sampling leads to more stable (and ugly) renderings but it does not fully eliminate the problem.
* Enforcing a strict order when copying the sprites to the atlas **fully solves** the problem, but it is not an acceptable solution.
* I inspected the GL state using an inspector and I found two frames that should have been the same in two different runs of the program; the state is the same in both cases, the only difference being a different arrangement of sprites in the atlas, and consequently different texture coordinates in the array buffer.
* I know that I could test using some sort of fuzzy/thresholded comparison but first I would like to rule out bugs on my side.

# Answer
> 1 votes
Two possibilities I can think of so far:

1. Contamination in transparent regions. You mention the artifacts show up mainly near the edges of the sprites. Depending on how you perform your atlas updates, it could be that when the sprites are placed in the atlas, only the texels with non-zero alpha are being replaced. Texels with zero alpha could, under some update methods, retain the RGB value of whatever was in that part of the atlas previously (eg. a previous sprite, or uninitialized video memory...). This can cause odd fringing at the edges of objects under bilinear texture filtering, as the RGB is tugged away from your sprite's value while the alpha is still ramping down.
2. Rounding/phase differences. Especially if your atlas packing uses a non-power-of-two grid of entries, or you're scaling your sprites as you copy them into the atlas. Factors like these introduce a multiplier into the texture coordinates used to read or write into the atlas, which could lead to a sub-pixel-sized offset that varies from entry to entry in your atlas with a period different than your entry spacing. So moving the same sprite over one slot causes the offset to hit it in a different phase, slightly nudging texel lookups away from where they landed in the original position.

I think we can rule out floating point differences. Most GPUs perform texture filtering using fixed-point arithmetic with 8 binary digits of sub-pixel precision, and 32-bit floating point texture coordinates have even more. Unless you're using a reduced-precision format for the UV coordinates, this shouldn't come into play.

To narrow this down further, it would help to see the methods you use to initialize & populate the atlas, and to produce your textured quads. Image examples of the effect would help too - particularly if you can construct clear-cut cases using eg. grid textures or other regular patterns that will help us isolate which pixels/cases contribute to the issue.

# Answer
> 1 votes
Texture coords (like pixel coords) go from the edges of pixels. So, imagine you have a 3x1 texture.

```
0.0                           1.0
 |                             |
 V                             V
 +---------+---------+---------+
 |         |         |         |
 |         |         |         |
 |         |         |         |
 +---------+---------+---------+

```

So if you're trying to select a specific pixel the correct texture coordinate for that pixel is

```
 uv = (pixelCoord + 0.5) / size;

```

Plugging that into the example above the correct texcoords for each of the pixels are

```
 pixel 0 =  (0 + .5) / 3 = 0.16666
 pixel 1 =  (1 + .5) / 3 = 0.5
 pixel 2 =  (2 + .5) / 3 = 0.83333

```

That may or may not have anything to do with the issue you're seeing. I just know sometimes people think it's

```
 uv = pixelCoord / size

```

That ends up putting you exactly on the boundary between 2 pixels and so if your filtering is set to `NEAREST` you'll often get randomly one pixel or the other depending on various rounding issues and if you are using `LINEAR` you'll get the exact mix between 2 pixels.

For mapping textures to pixels it works because if your source is 3x1 and your dest is 3x1 then the grids overlap perfectly and GL will do what you expect. But as soon as you start trying to pick specific pixels out of the texture then it starts to get more complicated.

Being that it's WebGL it seems like it would be easy to post a simple example. Make a texture using canvas2d. Put a red block and and a blue block in the texture. Make another, put the red and blue blocks in different places that repo your issue. Render with those as your atlas. That would help narrow the issue down.

# Answer
> 0 votes
Our current understanding of the situation is:

**The sampler will do whatever the heck he wants**

The smallest code that can reproduce a similar looking issue is a quad rendering app that does texture mapping this way:

```
varying highp vec2 v_texcoord;

uniform highp sampler2D u_texture;
uniform highp float u_time;

void main(void) {
    highp vec2 err = 10.0 * vec2(cos(u_time), sin(u_time));
    highp vec2 iErr = floor(err);
    mediump vec4 color = texture2D(u_texture, v_texcoord + iErr);
    gl_FragColor = color;
}

```

The brick texture used in this test is taken from TextureX.com website.

If you use `GL_REPEAT` texture wrapping, this fragment shader should produce the same output every frame. There are no possible rounding errors issues/excuses. Every frame surely looks the same to the naked eye. But if you take a screenshot and enhance the difference in the RGB channels, you will see that there are a lot of mismatches. Probably imgur.com is doing a recopression of the image and they end up showing as vertical streaks of white blobs, but nevertheless, they are not part of the original texture.

There is also a https://www.shadertoy.com/view/XdfBzM that shows the problem in motion.

## Note for people that need to do screenshot testing

If your app dynamically populates a texture atlas, and the order to which sprites/glyphs/textures/whatever are added to the atlas is somewhat pseudo-random, you may want to provide also a deterministic path to use during testing, or simply accept the fact that results are going to be different every time and find a threshold value that works for you.

---
Tags: textures, glsl, webgl
---


# Question
Title: My GML object doesn't want to inherit variables
here's the error that I can't seem to get rid of.

> FATAL ERROR in action number 1 of Step Event0 for object side2\_obj3:
>
> Variable side2\_obj3.sidePick2(100004, -2147483648) not set before reading it. at gml\_Object\_side2\_obj3\_StepNormalEvent\_1 (line 1) - if (sidePick2 == 1)

this object is inheriting from an object that holds the variables sidePick1 and sidePick2. I stripped the level down to just the object to see if this was being caused by a code collision and the issue seems to be persisting.

EDIT

I gave tried calling the following function

```
Event_inherited ()

```

And it didn't work

# Answer
Make sure you called

```
event_inherited();

```

In the create event of child object (side2), because if you put something else in the event (create event in this case), the inheritance won't work without manual call of the function.
> 1 votes

# Answer
I figured it out. in GML, event\_inherited only works on step 0 and forward, relative to the object. if the creation code for an object executes on the same step as the creation code for a child, the child will not have time to inherit. Normally this wouldn't matter, but if the creation code for the child alters the local version of a variable provided by the parent, the object might not have the time to acquire and set the inherited variable before attempting to access it.

Kirk Summation : imagine 2 cars, identical except one doesnt have an ignition. its okay because you have left instructions on which ignition to use and how to install it. but the instructions say to drop the part in at the second the race starts. obviously, the car wont go because the ignition isnt installed until the second the race starts. same basic concept.
> 0 votes

---
Tags: game-maker
---


# Question
Title: How to model classes to be serialisation friendly in c#?
It is going to be just a fraction of the code but for the sake of the example let's say I have a class `Stat`

```
class Stat
{
    private string _name
    public Name { get { return _name; } }

    public Stat(string name)
    {
        _name = name;
    }
}

```

When I serialise object of type Stat with for example TinyJSON, it produces:

```
{ "Name": "some random name" }

```

So I figured I will create `StatData` with public property and not a getter so then I can use it for serialisation.

```
class StatData
{
    public string name
}

```

As far as I can tell I have now 2 choices:

1. Write converter method and, upon serialisation request, convert `Stat` to `StatData` and serialise `StatData`.
**Pros:** single responsibility principle preserved
**Cons:** more code and nested dependencies
2. Go with `private StatData _data` in `Stat` class and using getters as previously and adding, eg.: `ToJSON()` method on `Stat`
**Pros:** public interface
**Cons:** generics to handle inheritance eg.: `StatComposite` and serialiser dependency

Is/are there any other method(s) or potentially design pattern to deal with the problem?

# Answer
> 1 votes
Specific language and technology platform notwithstanding, I generally find the ideal approach is to separate the concepts of *static* versions of some data (resources you will load from or save to the disk, and thus serialize) versus the potentially *dynamic* versions of that data you'll use at runtime.

For example, I'd have one type (class, in C#) for a `WeaponResource` which contains all the fixed information about a weapon type. But at runtime I'd create a `Weapon` class which is actually used by the player. That `Weapon` class is initialized with a `WeaponResource` reference, but also has methods to do things to the weapon at runtime (such as apply temporary buffs) that don't make sense for the resource to have. This goes towards your "separation of responsibilities" point.

It's the `WeaponResource` that is serialized, and thus built in such a way as to be amenable to serialization. How to do this varies depending on language and serialization tools, but generally the approach is to make the type as close to plain-old-data as possible.

I don't think this approach actually results in "more code," as you note as a con. At least not appreciably; you were already going to have all the fields in the resource type *somewhere*, now they're just nicely packaged away. The dependencies between the resource and the runtime consumer of the resource are nice and clear as well.

---
Tags: unity, c#, design-patterns
---


# Question
Title: Is allowing the server to remotely execute code on a client a security risk?
My game uses scripts that can be edited by the player and I'm trying to figure out how to handle multi-player, while still allowing custom scripts. What I am thinking about doing is having the server send it's scripts' source code over to the clients and have the clients execute that. So if a client joins a modded server, the client can use those mods, and this prevents the client from easily cheating by editing scripts.

What can I do to prevent the scripts from being abused? Or is this just an all-around bad idea?

# Answer
You might want to ask yourself if you really need client-sided scripting at all. You might be able to make many interesting mods possible by simply making your network protocol powerful enough. Most client-sided functions which you could consider exposing to the scripting engine could just as well be exposed to the server by adding another type of network message.

But if you really want client-sided scripts downloaded from untrusted servers, then the risk depends on what your scripting engine can and can't do. What's always dangerous is:

* **Any form of file I/O**: It might exfoliate sensitive information, delete/overwrite important files or infect executable files with malware code.
* **Any form of network I/O with anything but the currently connected gameserver**: It might be abused to turn your game clients into botnet zombies which send spam, perform DDOS attacks, distribute illegal content or other evil stuff. Even peer-to-peer connections between players currently playing on the same server would make me feel uneasy. There might be a lot of potential for abuse here when players use some hacking.
* **Running other programs**: You don't want your game client to run any 3rd party programs on the user's PC.
* **Sharing data between servers**: You want to properly sandbox servers against each other. For example, if your scripts have some way to create persistent information on the user's computer, it should not be allowed to read or overwrite information which was written by a different server. You also don't want a script to run code from scripts which originate from other servers.
* **Any access to personal information**: Your scripts should not be able to find out anything about the user or their setup. Personal information can be used by games in ways which seems like a cool feature at first glance but can end up being very creepy and potentially dangerous even if meant well. Extra Credits recently made a video about this. This is really something I would not trust some mod-building teens to use in a responsible manner.
* **Any social interaction which might be mistaken for player action**: For example, when your game has a chat, a malicious script might generate insulting chat messages which appear as if they came from a player. This might end up ruining real-life relationships between your players.

When you develop your own scripting language from scratch, you can easily avoid these things by simply not implementing them. But when you are using an existing scripting engine, you need to inform yourself well what it can or can't do and how it can be limited and/or sandboxed. Some are quite a lot more powerful than they seem at first glance. Lua, for example, which this question was tagged with, has quite a lot of potentially evil stuff in its standard library.

And then you need to be aware of security problems with your script execution environment itself. This question was tagged with `C++`, which is a language potentially vulnerable to buffer overflow bugs which allow arbitrary code execution. If scripts are able to send arbitrary data to the C++ layer, they can potentially be used to exploit any such bugs remotely and drop some shellcode. For example, it might not be safe to assume that every `char*` you get from your scripting engine points to a properly nul-terminated string.

Another possible problem is abuse of player computing resources. A script could be used to make player PCs perform expensive tasks for the server host, like mining cryptocurrency or cracking passwords etc.. This isn't evil per-se. Having players mine cryptocurrency might be a good way to finance a free server, if players are made aware of this. But it would not be in the best interest of your players to let others exploit them in this way without their knowledge. A good way to limit this is by limiting the amount of CPU time scripts can use. Usually there are few legitimate reasons why game scripts would perform lots of expensive calculations.
> 4 votes

---
Tags: c++, scripting, lua, security
---


# Question
Title: Determine the direction of force when ball is moved through pipes
I have set of pipes(edge colliders) in my scene, through which I pass the ball.

```
     ____|  |  <---Edge colliders
   o _______|

```

How do I move the ball in upward direction. For above this pipe I have to move along the positive x direction first, then positive y direction. How can I detect that.?

```
mRigidBody.AddForce (new Vector2 (moveSpeed,moveSpeed));

```

I tried this, but this can be used to move one direction at a time

# Answer
> 1 votes
What you can do is have your ball fire out whisker rays around it to detect nearby colliders, using 2D raycast methods:

```
RaycastHit2D hit = Physics2D.Raycast(ballPosition, rayDirection, maxDistance);

```

(You can add other parameters to limit the ray to only the pipes' physics layer, or specific z-values)

Then for each ray that hits a pipe wall, you can get its normal - a unit vector sticking perpendicularly outward from the edge.

We can do a bit of math on our current velocity to divide it into two parts: one that runs parallel to the wall and one that runs perpendicular to the wall.

```
float awayDistance = Vector2.dot(hit.normal, rayDirection * hit.distance);
float awaySpeed = Vector2.Dot(hit.normal, body.velocity);

Vector2 perpendicularVelocity = hit.normal * awaySpeed;
Vector2 parallelVelocity = body.velocity - perpendicularVelocity;

```

To keep the ball in roughly the middle of the pipe, you can apply a repulsive spring force based on the distance the ball is from each wall (`awayDistance`), and add some damping to the perpendicular velocity. This will help nudge the ball around 90-degree corners like the one in the diagram: it gets repulsed from the floor and the ceiling drops away, so there's no counter-force holding it down. (Just be careful not to double-count walls that get hit by more than one whisker ray)

Then you can apply another force/impulse to keep the length of the parallel component of the velocity close to your target speed, so the ball moves along at a roughly steady rate.

# Answer
> 1 votes
An alternative solution would be to use the physics engine to detect collisions and use effectors to force your ball to move along your pipe. I would typically add an area effector to every section of your pipes to recreate a feeling of flow. This means that your balls will most likely hit and bounce off the walls of your pipes. Here is an example of GameObject with effector to align with one section of your pipe:

A few things to watch:

1. select collider mask in the Area Effector component to match the layer of your balls
2. decide if you want gravity to apply or not, this will affect the result that you get
3. You will most likely need/want to tweak the force magnitude and force variation parameters to get something realistic (or not)

I think that an advantage to rely on the physics engine will be that you can create scenes that are closer from reality. The main disadvantage might be that you have less control during gameplay as things might not always react as anticipated/as they would with scripting.

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


# Question
Title: Why I get different size for equal attributes types?
I trying to implement flexible shader attributes, but when I try to get them I got strange info. This is my vertex shader:

```
    GLchar* vertexShader =
    "in vec4 position; \n"
    "in vec4 loc;\n"
    "\n"
    "void main()\n"
    "{\n"
    "gl_Position = position + loc;\n"
    "}";

```

This is my code with the help of which I get attributes info:

```
GLint i;
GLint count;

GLint size; // size of the variable
GLenum type; // type of the variable (float, vec3 or mat4, etc)

const GLsizei bufSize = 16; // maximum name length
GLchar name[bufSize]; // variable name in GLSL
GLsizei length; // name length

glGetProgramiv(shader->GetProgram(), GL_ACTIVE_ATTRIBUTES, &count);
printf("Active Attributes: %d\n", count);

for (i = 0; i < count; i++)
{
    glGetActiveAttrib(shader->GetProgram(), (GLuint)i, bufSize, &length, &size, &type, name);

    printf("Attribute #%d Type: %u Lenght: %d\n", i, type, length);
}

```

And what I get:

Why I got such strange info and how I can get size of each attribute?

# Answer
> 1 votes
Apart from relying that indices of attributes start from zero and increments by one, but could be anything in valid index range (indices are not set in provided code).
The length parameter:

> Returns the number of characters actually written by OpenGL in the string indicated by name (excluding the null terminator) if a value other than NULL is passed.

The length of `loc` is 3 and the length of `position` is 8, which appears to be correct (note different order, again do not rely on driver indexing, query it!).
*tl;dr:* You probably wanted to print `size` instead of `length`(of attribute's name).

---

Edit: further reading of linked documentation page shows that

> The size argument will return the size of the attribute, in units of the type returned in type.

The `size` is in **units of the type**, not bytes!
Many may find this counter-intuitive, however this is how the API was designed. For sizes of types please refer to the Type documentation.

# Answer
> 0 votes
Ok, because of nobody answered this question I think I should answer it by myself. I found "brute-force" solution.
First of all, I need to get attribute info with that commands:

```
GLint numActiveAttribs = 0;
glGetProgramiv(shaderprogram, GL_ACTIVE_ATTRIBUTES, &numActiveAttribs);

std::vector<GLchar> nameData(256);
std::vector<GLenum> properties;
properties.push_back(GL_NAME_LENGTH);
properties.push_back(GL_TYPE);
properties.push_back(GL_ARRAY_SIZE);
std::vector<GLint> values(properties.size());
for (int attrib = 0; attrib < numActiveAttribs; ++attrib)
{
    glGetProgramResourceiv(shaderprogram, GL_PROGRAM_INPUT, attrib, properties.size(),
        &properties[0], values.size(), nullptr, &values[0]);

    nameData.resize(values[0]);
    glGetProgramResourceName(shaderprogram, GL_PROGRAM_INPUT, attrib, nameData.size(), NULL, &nameData[0]);
    std::string name((char*)&nameData[0], nameData.size() - 1);
}

```

With this commands, you can find name of the attribute, it's type and size (**IN UNITS LIKE SIZE OF AN ARRAY**) After that, I used simple switch to find what type is it and multiply it with attribute size. You can find types of attributes and its sizes there: Basic GLSL data types or there OpenGL Type

---
Tags: opengl
---


title: Issues with Toggle

text:
# Question
Title: Issues with Toggle
hope you're all good..

I'm struggling with a simple toggle for inverting Y axis..

What i have works for my first scene but i'm trying to keep this setting through all scenes, hence why the script below isn't destroyed on load..

Although its fine for the first scene and works, to help me debug it i'm trying to get its value to show up on the console - the InvertYCheck() function - but it displays the console text once but then doesn't update (display the new value) again even if i add an if statment in the Update() function.

So from this, is seems that it despite being able to check and uncheck the toggle in-game, the value of it will only update the first time you click it.

Basically, all i want is the user to be able to select the Y axis orientation during training (scene 1), then retain this value (but not the UI toggle) so that becomes the setting throughout the game..

From looking at the code it should work but it doesn't. Any ideas why not?

Thanks,

Paul..

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

public class InvertYscr : MonoBehaviour {

    public Toggle InvertYtog;
    public bool InvertY = false;

    // Use this for initialization
    void Start () {
        InvertYtog = InvertYtog.GetComponent<Toggle> ();
    }

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

    void Awake () {
        DontDestroyOnLoad (this);
    }

    public void InvertYCheck(bool newVal)
    {
        InvertY = newVal;
        print ("Y Axis is: " + InvertY.ToString());
    }

    public float MouseYval (float MY) {
        if (InvertY) {
            MY = MY * 1;
        } else if (!InvertY) {
            MY = MY * -1;
        }
        return MY;
    }
}

```

# Answer
> -1 votes
Whether the player prefers the Y-axis inverted or not is a personal preference of the player, hence it's something which fits quite well into the `PlayerPrefs` class. This is a persistent key/value store which doesn't just survive a scene reload but even a game restart.

To set a player preference:

```
PlayerPrefs.SetInt("InvertY", 1);

```

To read the player's preference when your player-controller is started:

```
void Start () {
    InvertY = PlayerPrefs.GetInt("InvertY") == 1;
}

```

Note that using player preferences is not appropriate when you simply want to pass data between scenes (use either `static` variables or store the data in a game-object with `DontDestroyOnLoad` enabled) or for saving more than a few values, or for implementing savegames which are more than a handful of values (serialize your game-state to a file and write that).

---
Tags: ui-design, axis, boolean
---


# Question
Title: Are all conditions in an if statement checked?
If I have an `if` statement like this:

```
bool conditionOne = true;
bool conditionTwo = false;
bool conditionThree = false;

if(conditionOne || conditionTwo || conditionThree)
{
    //do something
}

```

Will `conditionTwo` and `conditionThree` actually be checked even though conditionOne is already true, and thus has met the requirements of the if statement to run the code inside it? It would be pointless to check if `conditionTwo` and `conditionThree` are true because either way the code inside the if statement would be run.

I'm thinking this would be useful to know if I have some really long and quite expensive checks to do.

# Answer
> 12 votes
You are using the logical `&&` and `||` operators which short-circuit, which means that the logical AND terminates as soon as one false value is found, and the logical OR branches as soon as one true statement has been found. If you want to evaluate the whole condition you can use bitwise operators, like this:

`if(conditionOne | conditionTwo | conditionThree){}`

This is useful if you call functions in your if-statement which operate on global variables and they should all execute before the evaluation of the if statement. However, this is not a good coding practice...

(edit, as suggested by DMGregory:)

An advantage of short circuit operators is that you *don't have to worry about* null references, because the condition is simply false if the object has a null reference and therefore skips the rest of the evaluation : `if ( myObject != null && myObject.foo > bar )`.

https://stackoverflow.com/questions/4820610/is-relying-on-short-circuiting-safe-in-net

# Answer
> 5 votes
`conditionTwo` and `conditionThree` won't be checked. C# evaluates it just like you'd read it:

```
if(firstIsTrue or secondIsTrue) -> go

```

It would be so inefficient to check both, or even three of them. Think about all these complex apps, which perform hundred thousand operations per second. It would multiply the evaluation time by 3.

If you don't need to know the second and the third variable state to make a decision, a PC doesn't need too. It depends on the programming language, but most of the modern objective and functional ones doesn't need to know if there's something after the first `true` evaluation in this kind of condition.

Read this on `StackOverflow` and remember to ask these kind of questions there, not on `GameDev`. https://stackoverflow.com/questions/20680943/and-or-logic-for-multiple-condition-statements

Or don't, you'll get destroyed in 30 seconds for this kind of question! :) These are basics, you should learn them by googling.

# Answer
> -3 votes
Short answer, No they won't be checked

---
Tags: c#
---


title: How to draw 3ds max gizmos?

text:
# Question
Title: How to draw 3ds max gizmos?
I'm trying to achieve the same effect than 3ds max gizmo drawn on the bottom-left and up-right side of the viewports, these ones:

So, let's say i got already the 3d models of those 2 gizmos. What's the transformation i should apply to them?

I think my current attempt is not correct actually, for instance:

Let's say i can apply a model/view/projection matrix on a subviewport to the 3d model... right now i'd be using

```
model      = mat4.extract_rotation(self.camera.view)
view       = identity()
projection = identity()

```

where extract\_rotation is getting the upper-left 3x3 submatrix of a 4x4 matrix.

Anyway, what's the theory behind these 3ds max gizmos and how i can mimick them on my opengl test?

# Answer
In your 3D rendering process, you do multiple transformations from one space to another. Recall, that we use a 4\*4 matrix to represent the three basic transformations: Scaling, Translating and Rotating.

What your 3 axis gizmo is showing you is the rotation of your camera. You don't care about the scale or translation. So, every time you move the camera, you only apply the rotation part of it to the gizmo, instead of the whole matrix. Here is a small post if you don't remember how to extract the rotation matrix out of a 4\*4 transformation matrix.

Going a step further, you can also do it the opposite way, and apply the rotation you do on the gizmo (such as the cube on the upper right in your screenshot) to your main camera, and thus easily align your main view on the axis you want.

Please note that you still have to apply the projection matrix to your gizmos, as you're still projecting the 3D objects to a 2D screen!
> 0 votes

---
Tags: opengl, transformation, 3dsmax
---


# Question
Title: How to detect collisions between a point and a tube in space?
Alright, so I am wondering in general if given a tube that follows a curve in space whether or not there is a way to detect if a point is within the tube? I am assuming that a curve is a continuous function taking a single value and returning a point. I would assume this is done via a comparison with the shortest distance to the curve. Is there a formula that works for all curves? I looked around and found that most things rely upon calculus and derivatives of the curves. Preferably, it would work in the general case without having to rely upon calculus.

# Answer
Get a parametric definition for the curve, using that you can have x, y, and z in function of the parameter. Then you define the distance from the point a, b, b to a point x, y, z on the curve by using Euclidean distance.

Now, you have a function that gives you the distance to your point from the parameters. (x, y, z) should have been gone, because you replace them by their parametric functions.

Use second derivate method to find at what value of the parameter you have the minimum value for the distance.

Evaluate the parametric functions for x, y and z with the found parameter value, and there you have point on the curve that is closest to the point you have.

You can build you collision detection with that and the radius of the tube.

---

Without knowing the curve, and without using calculus, you would have to go for numeric methods. I'm unsure what would be appropiate for 3D... yet, I can tell you that the implementation with calculus is more efficient, because using numeric mehtods means iterations.

---

Addendum: Perhaps the problem is doing the derivation itself. In that case you can do Numerical differentiation and then Root Approximation to find an inflection points of the distance equation.

It should be noted that without the second derivate method you can't tell if what you found is a minimun or a maximun. Also, note that numeric methods are prone to result in local optimizations... so you may end up with a local minimun or maximun instead of the global minimun you want.

So, you could try finding the root using AI. Something like Stochastic hill climbing or Simulated annealing would work. Yet, on this point we are no longer talking about finding the distance, but about finding something close enough, where "enough" depends on how much time you have to search for it.

Are you sure calculus is the harder option here?
> 0 votes

# Answer
The simple way to do this is approximate your curve with straight, tubular segments. How many points along the curve you sample to do this, and thus how many segments you end up with, is your choice.

Then for each straight, tubular segment approximating your curve:

* Get tube's backbone axis in its own local space, defined as a `yz` position and a set of extents in `x` (`min, max`), and its 3x3 world space orientation matrix.
* Transform the point from world space into the cylinder's/tube's space (using inverse 3x3 orientation matrix)
* Check the point falls within the `x` extents AND
* Check the point falls within some radius `r` of the `yz` axis position, using Pythagoras.

The only thing you would still need to attend to here, is the "ball-joint" corners between each tubular segment representing the curve. There you would need to add an extra step:

* Check the point falls within a spherical radius of the end point (`x max`) of every segment except the last segment (as this gives you every interstitial).

If it falls into either the the tube/cylinder OR the sphere, it is considered "inside" this segment. If it falls into any of the segments, then it is of course considered "inside" the tubular curve as a whole.

The good news is that unless you are raytracing, you will have a mesh constructed using essentially the same parameters. So this will give you accurate collision detection against the edges of the tube.
> 0 votes

---
Tags: collision-detection, 3d
---


# Question
Title: limits of tiles on tilemap, for mobile devices?
how many tiles are we allowed to add on a Tile map, using softwares like Tiled , to target mobile devices? Some devices cannot load a texture that exceeds 2048x2048, would you know how a tilemap works and if a limit of size exists?

Thanks

# Answer
> 1 votes
The limits are more likely to come from the details of how you render & process the tiles, rather than some universal cutoff number.

* If you're "baking" your tilemap to a pre-assembled image, then you'll be limited by the size of that image. For example, if your tiles are 32x32 pixels across, and your device supports textures up to 4096x4096 (eg iPhone 5 or newer), then you're limited to 128x128 tiles in any one image. You can make larger maps by breaking them into 128x128 chunks to render separately, so here your limit is most likely to come from available memory and (if the baking is not done at runtime) download size.
* If you're rendering each tile as a separate sprite/image/quad, then you might start to hit draw call limits or bandwidth bottlenecks as you try to draw thousands of them. Batching can help with this dramatically, and should let you draw tens to hundreds of thousands of tiles with good performance.
* One of my favourite ways to render large tilemaps is to store a tileset texture and a tile index texture. Each pixel of the index texture points to a particular tile in the tileset, letting a custom shader look up the right tile using texture indirection. This lets us render a very large tilemap (4096 x 4096 tiles on modern phones, over 16 million) as a single quad, and we could again render multiple of these chunks to make a world even larger.

(Though given limited display resolution, you probably won't need to display more tiles than this at a time - once you're zoomed out so far that each tile is just a few pixels on the screen, you'd want to transition to a reduced level of detail version anyway to avoid aliasing)

As always with performance questions, the only way to know for sure on a given device is to actually test it and profile the performance on real hardware. Overall though, I'd suspect that performance won't be the limiting factor in the size of your tiled maps, as long as you're willing to put in the work on a solid chunking and/or batching system of some kind. You'll hit the limit of how many tiles legibly fit on screen first.

---
Tags: tilemap, mobile, texture-atlas
---


# Question
Title: Move GameObject with defined lists of position and rotation
I'm working on playing a replay on every strike. For that I'm recording the positions and rotation of the sphere in the list individually. I now have the values reside in the list. How do i move my sphere with the defined pos and rot. Below is what I've tried so far.

**Replay.cs**

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

public class Replay : MonoBehaviour
{

    BallRecorder script;

    public List<Vector3> position;

    public List<Quaternion> rotation;

    // Use this for initialization
    void Start()
    {
        script = GetComponent<BallRecorder>();

        position = new List<Vector3>();
        rotation = new List<Quaternion>();

        position = script.position;   // Now contains all the values of the sphere(positions)
        rotation = script.rotation;   // Now contains all the values of the sphere(rotation)

        foreach (Vector3 av in position)
        {
            transform.position = av;  //transferring position to the sphere
        }

     }

```

**BallRecorder.cs**

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

public class BallRecorder : MonoBehaviour {

    // Use this for initialization

  public  List<Vector3> position;
  public  List<Quaternion> rotation;
    static int count = 50;

    void Start () {

        position = new List<Vector3>();

        rotation = new List<Quaternion>();

    }

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

        count = count - 1;

        if (count < 1)
        {
            position.Add(transform.position);
            rotation.Add(transform.rotation);

        }
    }
}

```

# Answer
> 2 votes
I'd be inclined to do this as a Coroutine like so, letting us start the playback by calling `StartCoroutine(PlayFrom(0f));`

```
IEenumerator PlayFrom(float time = 0f) {
    // As long as there's still more recording to play,
    // update our transform to match the replay data at this moment.
    while(Playback(time)) {
        // Wait until next frame.
        yield return null;

        // Advance the playhead by deltaTime and loop again.
        // You can set Time.timeScale to get slow-motion replays this way.
        time += Time.deltaTime;
    }
}

bool Playback(float time) {
    // Convert the playback time to a position in our sample array.
    // (Here I'm assuming the current fixedDeltaTime is the same one used to record)
    float sample = time / Time.fixedDeltaTime;

    // Round down to the position & rotation sample just before this moment.
    // (Here I'm assuming time is non-negative)
    int previousIndex = (int)(sample);

    int last = positions.Count - 1;
    if(previousIndex < last) {
        // We have another snapshot ahead, so we'll interpolate smoothly between them.
        int nextIndex = previousIndex + 1;
        float interpolation = sample - previousIndex;

        transform.position = Vector3.Lerp(
                                position[previousIndex],
                                position[nextIndex],
                                interpolation);

        // Slerp is technically a more consistent option here, since it keeps
        // the rate of change even over the course of the interpolation.
        // But each step is usually too small for this difference to be visible.
        transform.rotation = Quaternion.Lerp(
                                rotation[previousIndex],
                                rotation[nextIndex].
                                interpolation);

        // Signal that there's still more replay past here.
        return true;
    }

    // Here we're off the end of the timeline, so we'll hold on the last snapshot.
    transform.position = position[last];
    transform.rotation = rotation[last];

    // Signal that we're at the end of the replay.
    return false;
}

```

Pulling out `Playback` as its own method also lets you call it separately if you want to seek to a particular freezeframe in the replay, or reverse time and rewind the recording, or use a shared playhead controller to scrub through the timeline, things like that.

# Answer
> 0 votes
Your `Start` method doesn't make much sense.

```
    foreach (Vector3 av in position)
    {
        transform.position = av;  //transferring position to the sphere
    }

```

This replaces the position of the object with those from the list one after another. But the problem with this is that it does all that during the start-method. So when Start is over, the object ends up with the last position and the player has no chance to see those between. What you need to do is have a counter-variable which says at which point in the recording you are currently and then transfer the positions during the `Update` method, one after another.

```
int current = 0;

void Update() {
     if (current < position.Count) {
         transform.position = position[current];
         transform.rotation = rotation[current];
         current++;
     }
}

```

By the way, there are also some more improvements you could do to your Replay class:

1. You don't need to keep a reference to the BallRecorder around when you've already copied its positions.
2. There is no point in initializing `position` and `rotation` to empty List's and then throw those empty lists away and assign an existing list to them. You can declare and assign a variable in one line.
3. According to your comments, you seem to misunderstand what `position = script.position;` *actually* does. It does not copy all the positions. It makes `position` point to the list in `script.position`. In this case this doesn't make that much of a difference, but you should be aware that this means that when the `BallRecorder` changes its list of positions, those changes will immediately be visible in `Replay`. If you want to create a new List which is a copy of everything in an existing List, use `List<Vector3> copiedList = new List<Vector3>(existingList);`

To sumarize, here is how I would write that class (note: Untested!)

```
public class Replay : MonoBehaviour
{

    private List<Vector3> positions;
    private List<Quaternion> rotations;

    private int current = 0;

    void Start()
    {
        BallRecorder recorder = GetComponent<BallRecorder>();
        positions = recorder.positions;
        rotations = recorder.rotations;
    }

    void Update() {
         if (current < positions.Count) {
             transform.positions = positions[current];
             transform.rotations = rotations[current];
             current++;
         }
    }
}

```

---
Tags: unity, movement
---


title: HLSL Shader help

text:
# Question
Title: HLSL Shader help
I'm trying to go over some Shader code at my university, I have forgotten it, and well, Its really confusing, The documentation we have been given is really difficult to read.

Also is there any good beginner tutorials In HLSL that can walk me through the whole thing ?

```
void RenderScene( float updateTime )
{
    // Setup the viewport - defines which part of the back-buffer we will render to (usually all of it)
    D3D10_VIEWPORT vp;
    vp.Width  = BackBufferWidth;
    vp.Height = BackBufferHeight;
    vp.MinDepth = 0.0f;
    vp.MaxDepth = 1.0f;
    vp.TopLeftX = 0;
    vp.TopLeftY = 0;
    g_pd3dDevice->RSSetViewports( 1, &vp );

    //************************************************
    // FIRST RENDER PASS - Render scene to texture

    // Specify that the scene texture will be the render target in this first pass (rather than the backbuffer), will share the depth/stencil buffer with the backbuffer though
    g_pd3dDevice->OMSetRenderTargets( 1, /* MISSING */ , DepthStencilView );
    /*MISSING - specify scene texture as render target (variables near top of file)*/
    // Clear the texture and the depth buffer
    g_pd3dDevice->ClearRenderTargetView( SceneRenderTarget, &AmbientColour.r );
    g_pd3dDevice->ClearDepthStencilView( DepthStencilView, D3D10_CLEAR_DEPTH, 1.0f, 0 );

    // Prepare camera
    MainCamera->SetAspect( static_cast<TFloat32>(BackBufferWidth) / BackBufferHeight );
    MainCamera->CalculateMatrices();
    MainCamera->CalculateFrustrumPlanes();

    // Set camera and light data in shaders
    SetCamera( MainCamera );
    SetAmbientLight( AmbientColour );
    SetLights( &Lights[0] );

    // Render entities and draw on-screen text
    EntityManager.RenderAllEntities( MainCamera );

    //************************************************

```

I'm really not sure whats to go in OMSSetRenderTarget, it has aweird parameter that has Variable * const \*variable which I try replicating with the values I have been given and it returns an error.

# Answer
> 1 votes
If you check the online documentation of `OMSetRenderTargets`, then you'll see that the second argument should be of type `ID3D11RenderTargetView * const *` and is named `ppRenderTargetViews`, which is a pointer to a pointer of render target views (most likely an array of pointers to render target views).

It's clear that the intended variable is `SceneRenderTarget`, but without knowing the type of `SceneRenderTarget` (whether it's a struct or a pointer) I couldn't tell you what `/*Missing*/` should be. Thankfully I can check the online documentation of `ClearRenderTargetView` to discover that its type is `ID3D11RenderTargetView *`, so I can deduce that as `OMSetRenderTargets` needs a `ID3D11RenderTargetView * const *` (a pointer to a pointer) and `SceneRenderTarget` is a pointer, you just need to take the address of `SceneRenderTarget` to have a valid argument, leaving the answer as:

```
g_pd3dDevice->OMSetRenderTargets( 1, &SceneRenderTarget, DepthStencilView );

```

(Next time you get a problem of type 'fill in the missing argument', always check the documentation to discover the expected type of the argument and what the expected argument represents.)

---
Tags: hlsl
---


# Question
Title: GLSL Fragment Shader compiles fine on certain computers
I got this piece of code in a fragment shader:

```
if (color.a < 0.01f)
    discard;

```

It runs fine on an older graphic card but can't even compile on my newer (maybe not new, but..) GTX 770. I got the most recent drivers and everything. The versions is correct. OpenGL 4.4. The shader compiles like normal if I remove the *discard* statement.

I've been searching around and I'm finding nothing about this. Does the *discard* just not work on certain graphic cards or what?

# Answer
> 3 votes
Remove the 'f' on your float constants. It's not part of the GLSL language.

Source: GLSL Specification

If you do not put a `#version NNN` pragma at the top of your shader it will compile according to GLSL 1.10 which does not supports the f suffix.

Source: khronos wiki

---
Tags: opengl, glsl, fragment-shader
---


# Question
Title: What is the difference between Pygames, Pyglet and Kivy and how each helps python game development?
I trying to figure out which options would be best to give a graphics to a UNIX based 2D game whose logical part was written in python. Which engine to use.

What is the difference between Pygames, Pyglet and Kivy and how each works in relating the logical part of the game with it's actual graphical display?

# Answer
> 3 votes
The difference between the three frameworks/engines is the abstraction level.

Pyglet is low level compared to the other two and is based on SDL, a popular C++ multimedia library. You'll have to use pure OpenGL functions and constants to achieve the desired result, but it also has many built-in features, such as batches. This has pros and cons too, it's much harder to do anything with it, but it gives you a higher creative freedom.

Kivy is in the middle, it has Processing-esque built-in drawing functions, such as Ellipse, Rectangle, Text, Button, etc., but it has an OpenGL wrapper class.

Pygame is a bit higher level, it has many built-in constructs, such as the rectangle, circle, etc. If you want to achieve a higher level of creativity, then you can integrate it with PyOpenGL, though at which point you may just use Pyglet.

---
Tags: python, pygame, pyglet
---


title: Unity Behavior Designer get gameobject

text:
# Question
Title: Unity Behavior Designer get gameobject
I am trying to create my own action in Behavior Designer. However i cannot seem to get the game object that designer is attached to. if i attempt to do:

```
protected Combatant enemyCombatantObject;

public override void OnAwake()
{
    enemyCombatantObject = GameObject.GetComponent<Combatant>();
    base.OnAwake();
}

```

It gives me an error:

> the property or indexer 'Task.GameObject' cannot be used in this context because it lacks the get accessor

Can anyone tell me how to get the `GameObject` that the script is attached to?

# Answer
> 1 votes
Use `gameObject.GetComponent<Combatant>();`. Note the small `g`. `gameObject` is the object the script is attached to.

`GameObject` is the class of all game objects. You can use `GameObject` to call methods which aren't specific to any particular game object ("static methods"), like `GameObject.CreatePrimitive` or `GameObject.Find`. You also need to use `GameObject` when you want to declare a variable which holds a reference to a game object.

---
Tags: unity
---


# Question
Title: How do I add tiles to a ds grid using script?
I am new to Game Maker Studio 2; how do I add tiles to a ds grid using script?

# Answer
> 0 votes
I Did It After a long Research

```
for (var yy = 0; yy < height; yy++) {
    for (var xx = 0; xx < width; xx++) {
        if (grid[# xx, yy] == FLOOR) {
            // Draw the floor
                var tilemapID = layer_tilemap_get_id("Floor");
                var tileData = tilemap_get(tilemapID , xx, yy);
                tileData = tile_set_index(tileData, 1);
                tilemap_set(tilemapID, tileData, xx, yy);
        }
    }
}

```

`tile_set_index` is used to define which cell i want to place the cell the first topleft cell is 1, 2 is the one next to it and so on

`grid` is my ds grid

---
Tags: game-maker
---


# Question
Title: Find the 4 Corners of a Bounding Box of a Rotated, Offsetted Square
How does one find the coordinates of the 4 corners of a bounding box of a square of width `w` and height `h` that is rotated `theta` degrees and is offset from the origin `x` in the x direction and `y` in the y direction?

Here is a visual example of what I mean:

Here is some python3 code that I came up with, but it only works in the right quadrants except when theta = 0 or 360 or etc.:

```
import math

def bounds(x,y,w,h,theta):
   theta = theta * math.pi / 180

   A = ( x, y+round((math.sin(theta)*w), 2) )
   B = ( x+round((w/math.sin(theta)), 2), y+round((math.sin(theta)*w), 2) )
   C = ( x+round((w/math.sin(theta)), 2), y+round((math.cos(theta)*h), 2) )
   D = ( x, y+round((math.cos(theta)*h), 2) )
   print(A)
   print(B)
   print(C)
   print(D)

```

I was reading this but I could not figure it out for my specific problem.

Any help is much appreciated. Next time I will use matrices to store all the transformation data because this would be so much easier that way.

# Answer
> 0 votes
Figured it out. The main part is finding out how to get the corners of the square. I suggest brute forcing through the trigonometry on paper to figure out how to get the 4 corners of the square. After that, it's just a matter of finding the width between the furthest corners in the x direction and finding the height between the furthest corners in the y direction, and finally adding them up with the top-left x,y coordinates of the bounding box, appropriately for each corner of the bounding box.

Here is a pseudo code:

```
// corner functions (tricky part)
get_top_left_corner = function() {
    return [my_x, my_y]
}

get_top_right_corner = function() {
    angle = to_radians(my_angle)
    return [my_x + cos(angle) * my_w,
            my_y - sin(angle) * my_w]
}

get_bottom_left_corner = function() {
    angle = to_radians(my_angle)
    return [my_x + sin(angle) * my_h,
            my_y + cos(angle) * my_h]
}

get_bottom_right_corner = function() {
    angle = to_radians(my_angle)
    return [(my_x + cos(angle) * my_w)  +  (sin(angle) * my_h),
            (my_y - sin(angle) * my_w)  +  (cos(angle) * my_h)]
}

// [x,y] coordinates of corners of rotated square
tl = get_top_left_corner()
tr = get_top_right_corner()
bl = get_bottom_left_corner()
br = get_bottom_right_corner()

// coordinates of bounding box's top left corner
ax = min( tl.x, tr.x, bl.x, br.x )
ay = min( tl.y, tr.y, bl.y, br.y )

// width & height of bounding box
w = max( tl.x, tr.x, bl.x, br.x ) - ax
h = max( tl.y, tr.y, bl.y, br.y ) - ay

// [x,y] coordinates of bounding box's corners
A = [ax, ay]
B = [ax + w, ay]
C = [ax + w, ay + h]
D = [ax, ay + h]

```

---
Tags: 2d, sprites, rotation, transformation, bounding-boxes
---


title: How to make a delayed mouse input?

text:
# Question
Title: How to make a delayed mouse input?
I have a car game and the idea is that the player is drunk. I want to have a delayed input from the mouse, where you move the mouse side to side to turn.

How can I setup a constant delay between the input the user gives and the turn amount of the car?

Right now I have this:

```
h = Mathf.Lerp(h, (((Input.mousePosition.x / Screen.width) * 2) - 1), Time.deltaTime * 2);

```

What happens is the turn is delayed, but is very slow, in other words, if I move the mouse very fast, the car turns very slowly, but if I crank up the multiplier for `Time.deltaTime`, the car turns faster, but delay effect is minimized.

How else could I do this?

# Answer
I ended up using a coroutine, because (from what I understand) the delay will be constant regardless of the performance of the device running the game.

This is my code:

```
private IEnumerator DelayedInput()
{
    Vector3 a = Input.acceleration;
    Vector2 m = Input.mousePosition;

    yield return new WaitForSeconds(delay);

    accelerometer = Vector3.Lerp(accelerometer, a, Time.deltaTime * turnSpeed);
    mouse = Vector2.Lerp(mouse, m, Time.deltaTime * turnSpeed);
}

```
> 4 votes

# Answer
To simulate a time lag, use a circular buffer to store the last *N* frames' mouse positions. Store the current mouse position each frame. In your control calculations, use the oldest mouse position from the buffer instead of the current mouse position.
> 31 votes

---
Tags: unity, c#, input, mouse
---


# Question
Title: Can I run my own loading script during the Unity splash screen?
Can I load data in the background while the Unity splash screen is up? If so, how?

I am trying to run code during the splash screen, not just load assets.

I have not been able to find any information on this in Google or the Unity Documentation.

# Answer
I just did some tests, and I found that the constructor for objects in the first scene actually gets called while the splash screen is still displayed.

Here are some timings I measured with a static Stopwatch:

```
Constructed  0     s
Awake        2.118 s
OnEnable     2.12  s
Start        2.744 s
First Update 2.919 s

```

So, it looks like we can trigger a script to run nearly 3 seconds before the end of the splash screen (with default settings) by firing it off from the constructor. You can try triggering your loading code (possibly on its own thread) from there.

Just beware that this is probably being called from the loading thread, so since we're not on the main thread we'll be a bit more limited with what we're allowed to do here. If there's a specific thing you're trying to do that's not supported on the loading thread, consider posting a new question with details of your application and we can try to find a workaround for that case.
> 10 votes

# Answer
Your best bet is to make your own loading screen and set that as the initial scene. Then, from that simple scene, use the Scene Manager to load the next scene in the background, asynchronously.

I cannot find information to confirm this, but from my observation, it seems Unity is loading your initial scene while the splash screen is being shown.

On some platforms, the game starts to run before the splash screen goes away, if loading is fast enough.

All this can change at any time, on any platform, on any version update. There is no guarantee that this will be consistent, so you're better off using your own loading screen.
> 3 votes

# Answer
Short answer is **no**, you can not do that.

Both above answers are correct in terms of scene management. You can use Scene Manager to load the scene and since it is async you can run other code in parallel.

Look at SceneManager.LoadScene documentation for more details.

The closest you can get to running your code as fast as possible after game starts is running it from the first scene with tiny footprint. Let's call it ***Splash Scene***. The only thing it would contain is your splash image and controller running needed code and loading another scene.

Since it has small footprint, it will load very fast and thus make your code running almost instantly. You can then do what you have to do, and load ***Other Scene*** afterwards.

Another thing you can try is removing "splash screen" remove any images you would want to display there. It will be just a bit faster since it won't be loaded initially.

So the flow would be something like this:

1. Splash screen (no image here, just make it black)
2. Splash scene (small footprint with your initial code and next scene loader)
3. Intro scene (regular intro scene)
4. .... (other scenes as usual)

Smaller the scene is faster it will load. You can use something like splash controller attached to any object in loaded **Splash screen**.

```
using UnityEngine;
using UnityEngine.SceneManagement;

public class SplashController: MonoBehaviour
{
    void Start()
    {

        // RunSomeSyncMethod();

        SceneManager.LoadScene("OtherSceneName", LoadSceneMode.Additive);
    }
}

```
> -1 votes

---
Tags: unity, loading
---


# Question
Title: Porting to Android...what is the equivalent of Properties.Settings.Default?
I'm porting my MonoGame/OpenGL app to Android. My game uses Properties.Settings.Default to store user preferences.

What is the equivalent of this in Android?

# Answer
You can use IsolatedStorage to achieve this in a rather cross-platform way. Xamarin provides it's own implementation for mobile platforms.
> 1 votes

---
Tags: android, monogame
---


title: Translate Object position into Time

text:
# Question
Title: Translate Object position into Time
I have a cube which i am moving in circle shape (with horizontal key input) is below code suggested.

```
public class Oscillator : MonoBehaviour {
    float timeCounter = 0;

    float speed,width, height;

    public float yPosition = 30;
    // Use this for initialization
    void Start () {
        speed = 2; width = 10; height = 10;
    }

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

        timeCounter += Time.deltaTime * speed * Input.GetAxis("Horizontal");
        float x = Mathf.Sin (timeCounter)* height;
        float y = yPosition;
        float z = Mathf.Cos (timeCounter) * width;
        transform.position = new Vector3 (x, y, z);

    }
}

```

Now my object is moving in circular shape which is fine. Now i want to translate my objects movement into time. Let suppose

if my object x position is 1 then it should give me time 1.0

if it is 1.5 then it should give me 1.5

it increase or decrease according to x postion of my object (or possibly throught z).

**I logged my object's x position which is starting from 0 to 9.999 and then become decrease 0, then -1 to -9 then it become decrease 0 and reached to its initial position**. This circular movement x values are strange for me, i am unable to form any formula that can convert my x position into time. Please can any one help me in this purely mathematics and 3d math problem?

# Answer
> 0 votes
I am able to convert my range

> 0 to 9.999 and then become decrease 0, then -1 to -9 then it become decrease 0 and reached to its initial position

Into time using this code snippet. Thanks to this **stackoverflow answer**.

```
public float ConvertRange(float originalStart, float orignialEnd, float newStart, float newEnd, float value){
        double scale = (newEnd - newStart) / (orignialEnd - originalStart);
        return (float) (newStart + ((value - originalStart) * scale));
    }

```

I am calling CovertRange Method using these parameters.

```
hour = ConvertRange(-9.99f,9.99f, 0f, 23.99f, controlledCube.transform.position.x);

```

while variables means

```
     int originalStart, int originalEnd, // original range, my object position of any axis
    int newStart, int newEnd, // desired range
    int value) // value to convert

```

***Note : This is not a complete answer. It somehow changing one range to another range but partially not completely.***

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


title: The largest vector in an array

text:
# Question
Title: The largest vector in an array
I'm working on a game engine in C# at the moment and I've come across a matter I find confusing. I need to know how to get the maximum three component vector in an array.

There is a method in OpenTK that can compare two `Vector3`s to find out the max, I need this on a larger scale.

I've tried using `Array.Max()`, but I get the error :

> At least one object must implement IComparable

# Answer
> 1 votes
Linq method of solving this would be using MaxBy coupled with a method mapping vector to a scalar type, e.g. `LengthSquared` or `ComponentMax` which gives `float`,

```
var resVec = array.MaxBy(vec => vec.LengthSquared);

```

# Answer
> 0 votes
Having a look at the Vector3 class of monotk gives us a hint why this doesn't work. Classes such as Sort() and Max() require your datastructure to implement the IComparable interface, which requires the CompareTo() method.

With this method you define a new binary relation. You can implement a lexicographical relation (aa \> ab (this only works because the characters are ordinal) ) for strings, use distances if your class is a topological graph,...

Comparing two vectors ( dimension \> 1) isn't so straight-forward. Which vector is greater: (100,10) or (10,100) or (67,43)? To compare vectors in a metric space, you have to rely on a norm. You might however want to create a different ordering, such as: First compare the Y coordinate, then the X coordinate. This gives us (for points) all the points sorted row by row.

As you can see, it is not trivial to compare vectors, and different use cases need a different definition of "the greatest of two vectors". The trivial case, where you want to know if two vectors are equal, is implemented (overloading the == and != operator).

Now what? You can extend the Vector3 class and implement the IComparable interface to be able to use Array.Max(). Or you can simply create a loop and compare your vectors on your own, and define what you want as "max". You can compare their norms, or use the implemented ComponentMax() functions, which compares the vector by, you guessed it, components.

All in all, once you defined "your maximum vector", the implementation is straight-forward.

# Answer
> -1 votes
You can do this in linear time:

```
Vector3 best = yourArray[0];

for (int i = 1; i < yourArray.Length; i++)
{
    if (yourArray[i] > best)
        best = yourArray[i];
}

```

---
Tags: c#, opengl, opentk
---


title: Emission on part of the mesh

text:
# Question
Title: Emission on part of the mesh
I would like to port this mesh in Unity but in a way that smaller face, which is selected, has emission material and rest of the mesh has albedo material.

I know how to apply material in Blender on different faces but I don't know how to port it in Unity this way.

Updated post: emission texture

# Answer
When you set the UVs for your model, make sure the faces which are supposed to have a different material get assigned to different images. When you then import the model into Unity, you will have a different material-slot for each image in your model. You can then drag-and-drop different materials into those.

Another option is to use one material for everything and add an emission texture to it. Make that texture black except for those parts of the texture which are supposed to glow. In that case you don't need any specific geometry in your mesh just to define the emissive parts. You can do that with the texture. Here is an example for such an emission texture from the Unity documentation:
> 3 votes

---
Tags: unity, blender, materials
---


# Question
Title: Data structure for logical representatios of maps for a 2D top-down RPG
I wish to logically represent a map for a 2D top-down RPG using a a bidimensional list (in python) structure. The map is like a variable size chess board. The first dimension represents the north-south direction of the map and the second represents the west-east direction.

For a square map of i.j cells ,in other words, a list of i lists, of j elements each, each element containing another list of variable representing what is contained in that square cell of the map, like type of terrain, any object, character occupying it, etc, which can be dinamically modified during gameplay.

Is this a good practice that can be easily interpreted by a graphical engine to draw a map?

I have the logical part of the game in python clear in my head, but I know nothing of graphical engines and don't wish to create something that cannot be tranformed easily by a graphical engine in future. Does any one knows a graphical engine that could use this data structure and draw based on it? It does not need to be in python itself, as long as it can be worked with without MUCH programing in other languages.

# Answer
> 2 votes
Using (your programming language's equivalent of) a two-dimensional array is pretty much the default solution for representing a 2d tile-based world.

Other options are:

* Some form of 2d tree or spatial hashtable, if you want to allow for extremely large (potentially even infinite) levels
* Having all objects store their x- and y-position themselves, if you have a very sparse map (like a space exploration game where you rarely have more than two planets and three ships on the screen at once).

You can also have a hybrid approach: Divide your maps into chunks of n\*n tiles, which you represent as 2d arrays. Then manage these chunks with one of the methods listed above.

You can also use different solutions for different kinds of objects. For example, it's not uncommon to put all the map tiles in a 2d array with indices corresponding to their positions, but put any moving objects into a regular array sorted by drawing order and have them store their own coordinates.

---
Tags: 2d, tilemap, maps, rpg
---


# Question
Title: Method for Modifying Numbers based on Attributes in a Game
A game that I'm working on in Unity has a diverse set of spells. The player character and NPCs all use an attributes which modify these spells in different ways. Our design is very fluid and the functions that modify these spells are continuously changing. As of now I've been hard coding the modifying function into the spell class itself while leaving different variables open for designers to modify it. Example for amount of missiles fired:

```
BaseQty + Strength * MissilesPerStrength

```

Leaving the BaseQty and MissilesPerStrength attribute open in the inspector for designers.

As our game balancing is changing so much I feel as if only leaving certain variables open isn't enough, as I'll have to go back and change the formula itself if required. I've thought about allowing designers to script the function itself, and for the spell class to get the number for (Example) missiles fired by interpreting the script, but I'm not sure how to go about doing this and in my mind it feels a little bit needlessly complicated for the small team that we are. It's not too much of a hassle to go into the class and change the formula, it just feels wrong not to have it separate.

I'm looking for critique and suggestions on my ideas if possible. Thanks for reading.

# Answer
> 0 votes
It all depends on how complicated you want to get with your formulas. The formula you listed in the example is a type of Linear function (Linear as in linear algebra where terms are simply added together, not in linear as a line). If you restrict to linear functions, then you can generalize your equation to be like...

y = C0 + C1\*term1 + C2\*term2 + C3\*term3 + ... + CN\*termN

In code, you could make an abstract "term" class that contains the coefficient C and requires you to override the logic needed to compute the specific term. You could then add these to a generic array which just computes the sum.

Generalizing to a non-linear function would be exceedingly more difficult and normally revolves around creating a transform that will take you from a non-linear into a linear. I think you could just avoid this class in general and stick to linear functions.

As an aside, if you stick to these linear function you could later apply some fun machine learning optimization algorithms to have the computer decide how to balance your game, but maybe you need to go over to Cross Validated to learn more about that.

---
Tags: unity, c#, scripting, balance
---


# Question
Title: How can I give a MonoBehaviour field a default value that depends on the object?
In Unity3D, I have a `MonoBehaviour` which gets added to game objects. I'm adding a `string` "name" field to it. I'd like the default value for the name to be the name of the game object the component is added to. Is there an easy way to do this? Some more details:

* The component is an existing one to which I'm adding the name field. In old versions, the name was always the name of the game object, and this is a new feature to allow them to be different.
* The common case is (still) for the name to be the name of the game object, so having that as the default would simplify the process of adding the component to a new object.
* **Ideally**, deserializing an old scene will fill in the default, so updating scenes takes zero effort. I'm **less** concerned about this than about newly created scenes/objects.
* The component already uses a `CustomEditor`.
* I don't care about updating the name in the component if the game object's name is changed, or if the component values are pasted into a different game object.

One way I can think of is to add a `bool` "override name" to the object. If the `bool` is unchecked, it uses the default name (the game object); if it's checked, it uses the new field. But I'd like to avoid adding complexity to the GUI to support it. The whole point of my request is to add the new functionality (overriding the name) without adding steps to the creation workflow.

# Answer
> 6 votes
Here's an alternative solution that will copy the current name when the component is added in the editor or at runtime:

```
public class NamedComponent : MonoBehaviour {

    new public string name = "";

    // For editor support: newly added scripts and deserialized scripts, respectively.
    void Reset() { InheritName(); }
    void OnValidate() { InheritName(); }

    // For components added at runtime.
    void Awake() { InheritName(); }

    void InheritName()
    {
        if (name == "")
            name = gameObject.name;
    }
}

```

This way the inspector field always shows the inherited name, rather than needing to explain a special behaviour when the field is empty.

# Answer
> 4 votes
So I had a bit of a "rubber duck debugging" moment with this question. Obviously the easiest way to do it is not to default the field at all, but to add a runtime wrapper for the field like this:

```
public string theField
{
    get
    {
        return !string.IsNullOrEmpty(_theField) ? _theField : gameObject.name;
    }
    set { _theField = value; }
}

```

That is, if the field isn't set, return the default value instead. That even handles the cases of pasting the component or renaming the object. It just needs a bit of extra UI or documentation so your users understand the effect of leaving the field empty. (In my case, there's only a handful of users, so it's easy enough to just tell them, but you could instead add a note using the custom editor.)

---
Tags: unity, monobehaviour
---


# Question
Title: Insert 3d text to the front face of a cube GameObject
I want to add a text to a cube in Unity.

I have a cube which has a 3d text as a child.

I am using the below UnityScript to write on the 3d text:

```
var countdown : int = 200;

function Update()
{
    GetComponent(TextMesh).text = countdown.ToString();
}

```

I am trying to write/show the text to the front face(or very close) of the cube but I am failing.

EDIT: My difficulty is to make the text appear in the front side/face of the cube, like it is written on it. Attaching the text or the script to any object is not an issue

My last failed try was to use the below lines:

```
var tm = gameObject.AddComponent(TextMesh);
tm.text = countdown.ToString();

```

Any ideas?

# Answer
> 4 votes
I *think* understand this question well enough to answer it and a year old (old questions deserve some love too).

Simply adding the TextMesh component to the cube is insufficient, as the text mesh has its own way of positioning itself relative to the GameObject's transform position. So adding it as a child GameObject is the correct approach. However, there's two caveats.

1. We will need to position this child GameObject such that the text aligns with the face of the parent cube.
2. We need to adjust the TextMesh's align property so that it aligns the way we want it to on the face of our cube.

Both of these tasks are fairly easy, but require a little understanding of Unity and how Unity works.

Transforms components essentially act as the object's *center* so that they have a position around which they rotate and scale. For a default cube, this is in fact the geometric center of the cube. We can use this, and some other Transform properties to position the text along one face. For other imported models, this may not be the case.

This script is written as if it was attached to the TextMesh's GameObject which is a child of the Cube

```
Start() {
    transform.position = transform.parent.forward * 0.5f;
    transform.rotation.localEulerAngles.y = 180;
}

```

Of course, this could be achieved in the editor by simply moving the child transform to the desired position or acting on it from a script attached to the cube itself. Note that until we accomplish step 2, the text may still not be rendering in the desired manner.

Because we want the text on the front of the cube, we offset the text *towards the front* by half a unit: the exact distance from the center of the cube to one of its faces. It does not matter how large the cube itself is scaled, it will always be half a unit. If you get Z-Fighting add a tiny amount (e.g. `* 0.501f`) to offset the text from the surface of the cube by enough that the user won't be able to tell, but enough for the GPU to know that they aren't occupying the same space.

The rotation value is 180 around Y because...TextMesh points the wrong way compared to the "front" face on the cube. If the "back" face works too, then by all means use a negative offset and no rotation. It's weird, don't worry about it.

Step 2: modify the text's Align property. If the text already exists in the scene, hit up the inspector and change the "anchor" property from "upper left" to "middle center."

We can accomplish this with code, as well. Again, this script assumes that it is attached to the TextMesh's GameObject:

```
Start() {
    //using strongly typed syntax!
    var tm:TextMesh = GetComponent(TextMesh);
    tm.anchor = TextAnchor.MiddleCenter;
}

```

An example doing this very thing is on Unity's documentation page.

Bonus step 3!

TextMesh text by default is super large and blurry. Fixing this is easy: reduce the transform scale. Just set the TextMesh transform's local scale to about `0.1` on X and Y (Z doesn't actually have any meaning, but it's good practice to scale it uniformly, particularly if you're going to be adding any children to *this* GameObject). 0.1 and the default font size (12 point, even though it shows 0) fits "Hello World" on the side of the cube quite nicely. If you want larger text at this point, then increase the "Font Size" property of the text mesh.

---
Tags: unity, 3d, graphics-programming, unityscript, text
---


# Question
Title: Changing the RotateAround center point dynamically
* Black circles are static
* Red - player
* Blue line - path

I'm trying to achieve a constant movement of the red dot like on the image below. For now, I have something like:

```
void Update(){

    target = firstCircle; // here I need to perform some calculations
    this.transform.RotateAround(target.transform.position, Vector3.forward, speed * Time.deltaTime);

}

```

As you can see in the code, it rotates around the upper circle now. I need to switch the `target` variable to the `secondCircle` when the player comes back to it's initial position (or is near it).

I came up with something like:

```
if(Mathf.Abs(Mathf.DeltaAngle(360f,this.transform.rotation.eulerAngles.z)) < 5f)
    //change target

```

and it works but has two issues. First - the `epsilon value`. If I set it to `5f` the above `if` is true like 7 times (depending on the player's speed). Of course I could make a `lock` to run it only once per cycle, but there's a second problem. If the object is moving too fast, the `if` will be false each time, cause the speed-step is always higher than the `epsilon`.

How is this done in 'gravity' games like `AngryBirds` when the bullet changes it's attraction point?

# Answer
There are two options, both involve using a velocity vector.

Option A: Place a "trigger" at the center point. When triggered, set the center of orbit based on the direction of the velocity. IE: the dot product of the vel and the vector towards circle A \> 0 then set circle A as orbit center, and vice versa. For this method, velocity can be determined by comparing current point and previous point.

The big problem with this method is that it won't work for a more complicated selection of objects. If you only need to move around 2 circles it's fine, but beyond that it's not really going to work.

Option B: Actually do the gravity calculations / steering forces. Start with some initial V and add the acceleration from gravity or target seek. Naturally this will give you the most realistic results as the object will be moving in ellipses rather than perfect spheres. For this to work, you will need to start with an initial velocity.

This scales very well. Everything works as expected regardless of the number of objects.
> 1 votes

---
Tags: unity, rotation
---


# Question
Title: How do I get the networkId of an object?
My clients have a way of spawning "defense" barriers and I would like to limit the number of defense barriers per client to 1; A way of doing this is to destroy the old defense (if any) and then spawn the new one. Since this defenses are spawned by the server, how can I tell the server to destroy only the defense that was created by that client?

I guess that by storing the networkID of the spawned defense I can later tell the server to destroy it and repeat. Am I attacking this right?

Having this:

```
[Command]
void CmdDefenseSpawned(string _playerID, string PlaceToDefenseName, Vector3 toDefense, Quaternion defenseRotation)
{
    Debug.Log("Player " + _playerID + " placed a defense on " + PlaceToDefenseName + " Position= " + toDefense);
    GameObject defenseInstance = Instantiate(defense, toDefense, defenseRotation);
    NetworkServer.Spawn(defenseInstance);
}

```

I would like something like this:

```
NetworkInstanceId defenseInstanceNetId = defenseInstance.NetworkIdentity.netID

```

So I can later delete the object whenever the client wants to spawn it again.

# Answer
Here is the answer:

```
   using UnityEngine;
 using UnityEngine.Networking;

 public class Example : NetworkBehaviour
 {
     void NetworkDestroy(GameObject Object)
     {
         //Get the NetworkIdentity assigned to the object
         NetworkIdentity id = Object.GetComponent<NetworkIdentity>();
         // Check if we successfully got the NetworkIdentity Component from our object, if not we return(essentially do nothing).
         if (id == null) return;
         // First check if the objects NetworkIdentity can be transferred, or if it is server only.
         if (id.localPlayerAuthority == true) {
             // Do we already own this NetworkIdentity? If so, don't do anything.
             if (id.hasAuthority == false)  {
                 // If we do not already have authority over the NetworkIdentity, assign authority.
                 // Keep in mind, using connectionToClient to get this NetworkIdentity is only valid for Network Player Objects.
                 if (id.AssignClientAuthority(connectionToClient) == true)
                 {
                     // If takeover was successful, we can now destroy our GameObject.
                     Network.Destroy(Object);
                 }
             }  else {
                 // Do nothing because we already have ownership of this NetworkIdentity.
             }
         } else {
             //Server only, so we can't do anything.
         }
     }
 }

```
> 2 votes

---
Tags: unity
---


title: Unresolved external symbols

text:
# Question
Title: Unresolved external symbols
I have installed direct SDK and I have visual studio 2010 , I started to write code and compile and when I run I get error of unresolved external symbols or some sort of this , I searched and I found that I need a library called legacy\_stdio\_definition.lib which I don't have in my files , note my code worked on other computer that have vs 2010

# Answer
Based on the comments, you likely have misconfigured your x86 vs. x64 library paths for using the legacy DirectX SDK with VS 2010.

In the Project Settings under VC++ Directories.

For all configurations for the Win32 (x86) platform, you need:

```
Include: ``$(DXSDK_DIR)Include;$(IncludePath)``
Lib: ``$(DXSDK_DIR)Lib\x86;$(LibraryPath)``
Executable: ``$(DXSDK_DIR)Utilities\bin\x86;$(ExecutablePath)``

```

For all configurations for the x64 platform, you need:

```
Include: ``$(DXSDK_DIR)Include;$(IncludePath)``
Lib: ``$(DXSDK_DIR)Lib\x64;$(LibraryPath)``
Executable: ``$(DXSDK_DIR)Utilities\bin\x64;$(DXSDK_DIR)Utilities\bin\x86;$(ExecutablePath)``

```

> Keep in mind that that legacy DirectX SDK is end-of-life. See MSDN and this blog post.

Note that the instructions above only work correctly for VS 2010 which uses the Windows 7.1 SDK. When using any newer version of Visual Studio that comes with the Windows 8.x SDK or Windows 10 SDK, you need to *reverse* the path order to use the legacy DirectX SDX.
> 1 votes

---
Tags: c++, directx9
---


# Question
Title: LibGdx: set TextButton font to a TrueTypeFont
I am making my first LibGdx game, and having an hard time understanding font scaling on TextButtons.

Here is a comparison between the rendering on my Kindle Fire 7 and an high resolution tablet:

I tried using the scale() method, but the result is a pixelated mess.

I've read about TrueType fonts, and I'd like to set the font size by calculating the screen density.

I've tried to create a TextButtonStyle containing a font with the following:

```
//Generate the font
FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("fonts/Merriweather-Regular.ttf"));
TextButtonStyle style = new TextButtonStyle();
FreeTypeFontParameter param = new FreeTypeFontParameter();

//Set the font size (12 as an example)
param.size = 12;
style.font = generator.generateFont(param);

//Set the new style to the button
button = new TextButton("START GAME", style);

```

The TextButton correctly gets the new font, BUT loses the actual button as only the text gets rendered; I guess that's because the new TextButtonStyle only contains information about the font and is otherwise empty.

I tried setting the new font to a Skin also, but only ended with further confusion; most resources I found online don't mention font rendering on TextButtons, or end up being confusing with convulted methods.

Is there a simple way to achieve what I want? Thanks.

# Answer
> 1 votes
In my answer to this question on SO I describe how you can add a TTF font to your `skin` file which will allow you to use the font on your labels.

Basically when you create your skin file you have to add an `ObjectMap` with the fonts inside and supply it to your skin's parameters.

---
Tags: android, libgdx, fonts, scale
---


# Question
Title: Raycast drawing and hitting limited to inside cylinder
I'm trying to get a very basic "radar" system to work. Right now, I'm not even scanning, just looking at a known target location.

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

public class RadarScript : MonoBehaviour {

    public GameObject radar;
    public GameObject target;

    private bool found = false;

    void Update () {

        Vector3 lookLocation = target.transform.position - radar.transform.position;

        RaycastHit hitInfo;

        if (found == false) {

            Ray ray = new Ray (radar.transform.position, lookLocation);

            Debug.DrawRay (ray.origin, ray.direction, Color.red);

            if (Physics.Raycast (ray, out hitInfo, 10000.0f, 0)) {
                if (hitInfo.collider.tag == "Target") {

                    printHitInfo (hitInfo);

                    found = true;
                }
            }
        }
    }

    private void printHitInfo(RaycastHit hit) {
        Debug.Log ("TARGET FOUND!");
        Debug.Log ("Distance: " + hit.distance);
    }
}

```

So, here's the result can be seen here: https://gfycat.com/FloweryBraveCockroach

There's 2 problems here.

1. The Debug.DrawRay call is only drawing the ray **inside** the cylinder (radar).
2. The target is never being hit.

What's going wrong here ?

# Answer
> **Direction** is always a **normalized vector**. If you assign a vector of non unit length, it will be normalized. https://docs.unity3d.com/ScriptReference/Ray-direction.html

So `Debug.DrawRay` call is only drawing normalized vector.

```
Debug.DrawRay (ray.origin, ray.direction, Color.red);

```

this Is mean you used normalized vector Instead of self vector:

```
Debug.DrawRay (ray.origin,lookLocation.normalized, Color.red);

```

try this it should work:

```
Debug.DrawRay (ray.origin,lookLocation, Color.red);

```

**Next problem**:The target is never being hit.

because you used LayerMask in the last parameter

```
if (Physics.Raycast (ray, out hitInfo, 10000.0f, ⚠0 (LayerMask)⚠)

```

you can replace **0** by **1** it will work.but you don't need **LayerMask** here remove it like this:

```
if (Physics.Raycast (ray, out hitInfo, 10000.0f)

```
> 1 votes

---
Tags: unity, physics, raycasting, meshcollider
---