title: Showing range on hexagonal grid

text:
# Question
Title: Showing range on hexagonal grid
Here is the situation.

I have hexagonal board,and a unit on it,with speed or move value 4.Diffrent terrain has a diffrent cost.When i click on the unit,game should show me a move range.

My solution was to check each hex in range of 4,with A\* pathfinding,and if path cost was less than 4 then this hex was in range.Finally game nicely show me range of that unit.

My question is: Is there other solution to search for range on hex grids or square grid,because even if i am really proud of what i did in my solution,i think,it is a little to exaggerated?:))

What make me ask this question?I noticed that when unit speed is 4 or 6 or even 8,time to computing range for my computer was really good,but when speed was 10 and more i noticed that i needed to wait few second to compute.Well in real games i rather dont see something like this and my A\* pathfinding is rather well optimized,so im thinking that my solution is wrong.

Thanks for any replies.

# Answer
You're right that A\* is a little overkill, but not by much. You shouldn't be seeing delays like you are. A\* is really just a modified Dijikstra's algorithm. Since you're not using an end position (as your end position is just "as far as you can go"), using A\* with it's added heuristic isn't necessary. Simply using Dijikstra or a simple breadth first search will be sufficient.

For example, Dikikstra will spread out evenly in all directions:

(A simple breadth first search will look similar to this)

Keep track of the cost to travel to each node. Once a node is at the maximum travel cost, don't process its connected nodes any further. (Similar to where the nodes run into the wall below).

If you're running into performance issues at only 10 nodes out, you'll want to look at how you're accessing the nodes. A breadth first search should be able to navigate hundreds of nodes without a noticeable delay (certainly not a few seconds). Consider storing a simple version of your world in a graph format, for quick traversal.
> 11 votes

# Answer
Amit Patel has provided an excellent resource for getting ranges on his site. In the article, he uses the following algorithm for collecting hex tiles within a range:

```
for each -N ≤ Δx ≤ N:
    for each max(-N, -Δx-N) ≤ Δy ≤ min(N, -Δx+N):
        Δz = -Δx-Δy
        results.append(H.add(Cube(Δx, Δy, Δz)))

```

This creates bounds aligned with the hex grid:

This will find all the hexes within a certain distance of the center hex, if you want to consider obstacles, use the breadth first search from my other answer.
> 4 votes

# Answer
In case anyone needs it, here's the C# implementation of Patel's algorithm:

```
IEnumerable<Hex> GetRange(Hex center, int range)
    {
        var inRange = new List<Hex>();
        for (int q = -range; q <= range; q++)
        {
            int r1 = Math.Max(-range, -q - range);
            int r2 = Math.Min(range, -q + range);
            for (int r = r1; r <= r2; r++)
            {
                inRange.Add(center.Add(new Hex(q, r, -q - r)));
            }
        }

        return inRange;
    }

```
> 2 votes

---
Tags: algorithm, ai, game-mechanics, software-engineering, hexagonal-grid
---


# Question
Title: how to move object in a circle around point?
There are two controllable objects orbiting around a centre block. Unfortunately, I don't really know how to stick them so they can only move around the block (left/a sends them clockwise, right/a sends them anti-clockwise) and can only get them to move like normal sprites not on a set path.

I haven't got any code to show yet, but I could really appreciate either some advice, or preferably some examples.

# Answer
consider constant velocity for a simplier explaination.

in a linear movement you would calculate each frame's delta position depending on your velocity and adjust your object location adding the result.

ds = v * dt

in a circular movement things are quite the same but you have to calculate delta angle based on your angular velocity.

dϕ = ω * dt

compute your new position with

p = (x = cosϕ * r, y= sinϕ * r)

given r the distance of your object from the center of the circle
> 0 votes

---
Tags: physics, python, pygame
---


title: Phantom objects in ray tracing

text:
# Question
Title: Phantom objects in ray tracing
I am attempting to add volumetric shadowing to an application I am working on to test some things. For this effect I wrote the following fragment

```
shader:#version 450

in float visible;
in vec3 normal;//Normal to the vertex
in vec3 vertexPos;//True position of the vertex (i.e it's location in space)

in vec2 texture_coord;

out vec4 outColor;//Final color of the pixel

uniform sampler2D text;

uniform vec4 color = vec4(1);//Default color
uniform vec3 lum = vec3(80,70,0.1);//A unique light position
uniform vec3 cameraPos = vec3(0);//The position of the camera in the world
uniform vec3 cameraDir = vec3(0);

float sphereIntersection(vec3 ray, vec3 origin, vec3 center, float radius)
{

    float a = dot(ray,ray);
    float b = -2*dot(center, ray)+2*dot(ray,origin);
    float c = -2*dot(origin,center)+dot(center,center)
              -radius*radius+dot(origin,origin);

    float discriminant =b*b - 4*a*c;

    float t, t1, t2;
    if(discriminant < 0)
    {
        return -1;
    }

    else
    {
        t1=(-b-sqrt(discriminant))/(2*a);
        t2=(-b+sqrt(discriminant))/(2*a);
    }

    if(t1<0 && t2>=0)
        t1=t2;
    else if (t1>=0 && t2<0)
        t2=t1;

    return min(t1,t2);
}

void main()
{
  vec3 l = vec3(lum-vertexPos);
  if(length(l)>0)
    l = normalize(l);
  vec3 c = vec3(texture(text,abs(texture_coord)));
  vec3 n = normalize(normal);
  vec3 e = cameraPos-vertexPos;
  e = normalize(e);
  vec3 h = normalize(e+l);

  outColor = vec4(c*(vec3(0.5)+0.5*max(0,dot(n,l))) + vec3(0.1)*max(0,pow(dot(h,n), 100)), 1);

  float t = sphereIntersection(vec3(90,70,1)-vertexPos, vertexPos, vec3(80,80,3), 6);

  if(t>0.01)
  {
    outColor = vec4(t/100,0,0,0);
  }
}

```

The issue is as follows, in the next image there's 2 shadows:

However as you can see, there's only one sphere and only one source of light and they are both hard coded, so I do not understand where the second shadow comes from (the one that does not have the circle).

# Answer
> 2 votes
The issue was not testing that the intersection needs to happen between the object and the light position. i.e I was raytracing past the light.

i.e the check: `if(t>0.01)` should instead be `if(t>0.01 && t < length(object_pos - light_pos))`

Or in other words, the intersection must happen between the position we are currently testing for shadowing an the light position. You also need to make sure your direction vector is normalized.

---
Tags: shaders, glsl, fragment-shader, shadows, debugging
---


title: slow/fast/slow experience system

text:
# Question
Title: slow/fast/slow experience system
I am looking for an experience ladder that 'starts' off relatively quickly like a bit of geometric series, then quickly grows like an exponential curve, and then a slow exponetial curve for later levels, in the range of levels 1-5000.

How would I do this mathematically? I am assuming I might just have three sets of equations, but then what is the correct math for getting the level (based on XP), and vice-versa, XP based on level?

I.e., I am thinking something like:

lvl 1 - 10 exp lvl 2 - 12 exp lvl 3 - 15 exp lvl 4 - 18 exp lvl 5 - 22 exp (not quite fibacconi) lvl 6 - 26 exp lvl 7 - 32 exp ... then maybe around level 150 or so it starts growing quickly, like lvl 150 -1000 exp lvl 151 - 1200 exp ... lvl 3000 - 30000 exp lvl 3100 - 40000 exp lvl 4000 - 75000 exp lvl 5000 - 100000 exp

If it's been done, a link would be great (since I am not exactly sure what I am looking for, not quite sure how to find it). Or if it is easy for you to just write the math, please do that too, thanks for your help!

# Answer
If you use an exponential function in the form:

```
XPTotal = 2 ^ (Level * some_function(Level))

```

Then you can play around with `some_function` to get different kinds of growth.

Like this makes it so you double every five levels:

```
some_function() = 1/5

```

I think what you could use here is something like this, where X, Y, and Z are constants you mess with:

```
some_function(Level) = X * cos(Y+Level/Z)

```

Then probably pass the `XPTotal` through some creative rounding function that gives you XP values like "225" instead of "223.1567017350735012".
> 1 votes

# Answer
Build a spline and give it as many control points as you think it'll need, my guess is only three unless you want multiple speed-up and slow-down phases. The Y axis is how much XP you're gaining, so the steeper the slope the longer it takes to move across the X axis. And the X axis will represent your 1..5000 "levels." In this you can quickly change the leveling experience just by tweaking the control points of the spline.
> 0 votes

---
Tags: mathematics, progression
---


title: Kryonet - Open a server locally only

text:
# Question
Title: Kryonet - Open a server locally only
On the game I'm working on I wanted the singleplayer mode to use an integrated server to make adding more players via networking easier. The way I have it right now is I open a server and connects the client to my local address which works fine. But the problem is that if I play the game Singleplayer I don't want to leave anything exposed to the internet while only playing locally. Is there any way to limit the "range" of the server to only let communication happen via LAN?

Thanks in advance!

EDIT: I am using kryonet for networking. The game is written with LibGDX.

# Answer
> if I play the game Singleplayer I don't want to leave anything exposed to the internet while only playing locally

That is *usually* not a problem, because *usually* the LAN is behind a NAT installed by the ISP. Such that you actually do not have an public IP to which other can connect... instead everybody outside your LAN sees the router/gateway IP.

> Is there any way to limit the "range" of the server to only let communication happen via LAN?

What you want is a subnet mask. All the IPs in the same network will match within the mask... to put it another way, the subnet mask defines up to what point IPs in the same network are equal.

The server can be programmed to use the subnet mask to compare its IP with the origin IP and allow or deny connections based on that. See Test with Java if two IPs are in the same network.

In the odd case where you cannot※ get mask programmatically, you can always let the user specify as part of server configuration.

*You may, of course, use a whitelist of IPs, or a simple ACL.*

---

※: I'm not familiar with Kryonet or whatever or not it will filter by subnet out of the box, so I looked it up, and found this:

> // Java 1.5 doesn't support getting the subnet mask

-- Source.
> 2 votes

---
Tags: networking, multiplayer
---


# Question
Title: Can I remake a game I don't own any copyright to?
Can I remake a game I don't own any copyright to?

There's a online browser game which I played 5 years ago. Some time ago, this game was shutdown because its developer went bankrupt. I want to re-make this game and provide it to Web again. Can I do this? Or there's some copyright problem or something like this?

# Answer
Somebody still owns the copyright, trademarks, et cetera for that game and related assets, even if the game is "shut down."

In order to use any of those, you would need permission from the holder of those rights.

You can make a game that is mechanically similar, as game mechanics themselves are not subject to copyright. But you cannot make use of anything that is subject to copyright, trademark, et cetera.
> 32 votes

# Answer
It depends on the game and the nature of the remake.

Game mechanics cannot be protected by copyright, trademark, or patent. You can freely copy the mechanics of any game you want, as the basis of a new game. (This is why there are so many clones of things like Scrabble and Tetris out there, Snake clones are a common programming exercise, and many computer RPGs have mechanics that are strongly reminiscent of those from Dungeons & Dragons.)

However, the creative aspects of the game are protected by copyright. You'll need entirely new artwork, created in a way that doesn't make it a derivative work of the original (eg. by giving the artist bare-bones descriptions of what you need). Any re-use of the original storyline is entirely out: I can't picture a way of using it as the basis for your new game that doesn't create a derivative work.

Additionally, the game's name is almost certainly protected by trademark, either registered or common-law.
> 17 votes

---
Tags: copyright, intellectual-property
---


# Question
Title: Blueprint formula doesn't match material formula
I'm currently working on a physical water system for Unreal. To represent the water surface, I have a simple flat grid mesh that I then apply a material to which has a formula for world position offset.

The formula currently is pretty simple, I just have a simple sine wave powered by world X position and elapsed time, however despite both formulas being, as far as I can tell, the same, they give different outputs.

As you can see below, both formulas perform the same operations, and both are powered by the same input, world position and Game Time in Seconds. In theory, the material (second-last image) should be dividing X position by 2000 and multiplying time by 0.1, just as those values are in the material, however instead the closest I could get to having both values line up is 314\* and 0.625.

It's important that these values line up, as the blueprint version is meant to be used for buoyant objects to make sure they stay on the surface of the water, and probably other calculations as I progress.

Does anyone know why these formulas don't line up like they should? Does math work differently in the material editor? Does Absolute World Position give values in a different scale compared to Actor Position?

\*I thought this might be 100 * PI, but that doesn't seem to line up exactly either so may be a coincidence.

The final result here is piped directly into World Position Offset.

Time parameter is updated every frame to match the blueprint version.

Blueprint function that I need to match the material formula for accurate buoyancy and such.

Included for completeness, an example of how the water height function is used.

# Answer
> 2 votes
Other than the obviously different constants in both screenshots you posted, what might not be so obvious is that the input of the blueprint `sin` function is expected to be in radians, while the input of the material graph `sin` function is expected to be from `0` to `1`.

To match between them, you should divide your material graph input to `sin` by `2*PI`

---
Tags: unreal-4
---


# Question
Title: How do I order sprites by depth in Java, when their objects are of different classes?
I'm developing a game to learn more about Java, and I've run into a problem: My character (the guy) moves, but I can not figure out how to automatically change the order of how the sprites are drawn. Each sprite has a depth, which is just the `y` value of the bottom of the sprite. If a sprite has a higher depth, then it is displayed in front of a sprite with a lower depth. Here are a few pictures of the problem:

As you can see the first picture, the guy should be in front of the girl.

I was thinking about putting them into an array list, and ordering them based upon their depth, but they are different object types. The guy is an object of class character, and the girl is an object of class NPC. Is there a way to put both of these object types into one array list, or is there a better solution?

# Answer
> I was thinking about putting them into an array list, and ordering them based upon their depth

YES.

> but they are different object types. The guy is an object of class character, and the girl is an object of class NPC. Is there a way to put both of these object types into one array list, or should is their another solution.

Define an interface that has the position - let us say, `IHasPosition`, and implement this interface in the different types. You will also need to write a `Comparator<IHasPosition>` (an anonymous class will do).

Then, the simplest solution is to a generic List `ArrayList<IHasPosition>` where you can put all the objects that are in view, as long as they have the right interface, regardless of their actual class... and call `Collections.sort` passing the comparator.

*Thinking about it, you probably should use an `IDrawable` that has the position and whatever else is needed to draw the objects.*

---

Other solutions include:

* using a tree structure, where the nodes point to your objects and can be kept sorted.
* using a drawable component type, instead of an interface, and use composition (Composition over Inheritance). *The game objects would have a drawable component.*
* A more *orthodox* way of doing things is to have one single base class for every game object (that is, no Composition, only Inheritance).

Software enginering (there is an stackexchange site for that) has been moving to "composition over inheritance". the topic is beyond the scope of this question, so I suggest searching for that, also considering your language of choice (the language matters because some have multiple inheritance, some have traits, some have interfaces, some have default interface method implementations).
> 1 votes

---
Tags: java, draw-order
---


# Question
Title: how to use unity3d webgl content in a asp.net mvc view?
I asked this question in stackoverflow but no answers so I think it would fit here better.

I have a unity webgl project and an asp.net mvc project.

I need to show the webgl content in a view.

The first thing that came to my mind was to simply copy the content of the index.html that unity gave me and paste it in a .cshtml file and change the addresses. But when I do this the incorrect header error pops up.

Am I doing some thing wrong or everything wrong. should I change my method entirely?

I also added these file extensions to the web.config

```
<staticContent>
  <!-- Unity 5.x -->
  <remove fileExtension=".mem" />
  <mimeMap fileExtension=".mem" mimeType="application/octet-stream" />
  <remove fileExtension=".data" />
  <mimeMap fileExtension=".data" mimeType="application/octet-stream" />
  <remove fileExtension=".memgz" />
  <mimeMap fileExtension=".memgz" mimeType="application/octet-stream" />
  <remove fileExtension=".datagz" />
  <mimeMap fileExtension=".datagz" mimeType="application/octet-stream" />
  <remove fileExtension=".unity3dgz" />
  <mimeMap fileExtension=".unity3dgz" mimeType="application/octet-stream" />
  <remove fileExtension=".jsgz" />
  <mimeMap fileExtension=".jsgz" mimeType="application/x-javascript; charset=UTF-8" />
</staticContent>

```

# Answer
> 1 votes
This question has already an answer in StackOverflow given by the user kenoni. I'm quoting the answer:

Basically, you copy all the file references to your view and of course your canvas container with the code that initializes it.

Add everything that is a css style file with

```
@Styles.Render("~/webgl/TemplateData/style.css")

```

And everything that is a js file with

```
@Scripts.Render("~/webgl/TemplateData/UnityProgress.js");

```

So you\`ll have something similar to this

```
@{
    ViewBag.Title = "Stage";
    @Styles.Render("~/webgl/TemplateData/style.css")
    @Scripts.Render("~/webgl/TemplateData/UnityProgress.js");
    @Scripts.Render("~/webgl/Build/UnityLoader.js");
}

<h2>Stage</h2>

<script>
    var gameInstance = UnityLoader.instantiate("gameContainer", "../webgl/Build/Builds.json", {onProgress: UnityProgress});
</script>

<div class="webgl-content">
    <div id="gameContainer" style="width: 960px; height: 600px"></div>
    <div class="footer">
        <div class="webgl-logo"></div>
        <div class="fullscreen" onclick="gameInstance.SetFullscreen(1)"></div>
        <div class="title">Figurines</div>
    </div>
</div>

```

Don\`t forget to add unityweb mime type to web.config

```
<system.webServer>
    <staticContent>
      <remove fileExtension=".unityweb" />
      <mimeMap fileExtension=".unityweb" mimeType="application/octet-stream" />
    </staticContent>
</system.webServer>

```

# Answer
> 0 votes
The generated index.html file from unity webgl build have a html5 canvas in it. You have to use that canvas to your intended platform or vice versa.

---
Tags: unity, server, client-server, webgl
---


# Question
Title: How do I permanently set the interpolation for every image, sprite, and texture in pyglet to GL_NEAREST in pyglet?
There are plenty of examples of posts that describe how to set the default interpolation of specific images to GL\_NEAREST, for example here, but they all have to be run after the image texture is defined.

My question is simply this: is there any way to set the default interpolation of every image, including ones that have not been created yet, to GL\_NEAREST in a single statement? I will never use any other scaling method as I am making a pixel-based game, and I do not want to have to set the interpolation every time on\_draw() is run. If there is no answer, then please say so.

# Answer
Default OpenGL states are given in the OpenGL specification and other related documentation, and there is typically no global override for these; if you want to use a different state you must set it yourself.

Firstly, you don't need to set interpolation (via glTexParameter) every time you draw; instead you only set it once per texture and after you initially create the texture, following which the setting "sticks".

If you're pushing all of your texture creation through a single function (and if not, you should be) then this is the appropriate place to set it.

Alternatively, if your GL implementation has sampler objects available, you may create and bind one sampler object per texture unit (GL\_TEXTURE0, GL\_TEXTURE1, etc) you use, and this overrides settings from glTexParameter. Again, this would only need to be done once, at program startup, rather than every time you draw.
> 0 votes

---
Tags: python, image, pyglet
---


# Question
Title: Puting all vertex attributes of a scene into a single VBO
I'm rendering various elements in OpenGL ES 2 on Android, and I'd like to pack the vertex attributes of the whole scene into a single vertex buffer object (VBO).

My question is, if these objects have different sets of attributes, strides and offsets, can I still pack this data into a single VBO and draw everything using it?

Most of these elements have 2 floats for position and 2 floats for texture coords (X, Y, S, T) as vertex attributes, and they do get drawn correctly using this:

```
@Override
public void onDrawFrame(GL10 glUnused) {
    glClear(GL_COLOR_BUFFER_BIT);
    glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer.getBufferId());
    drawObject1();
    drawObject2();
    drawObject3();
    glBindBuffer(GL_ARRAY_BUFFER, 0);
}

public void drawObject1() {
    glUseProgram(object1Program);
    object1Program.setUniforms(finalMatrixObject1, object1Texture);

    glVertexAttribPointer(object1Program.getPositionAttributeLocation(), 2, GL_FLOAT, false, 16, 0);
    glEnableVertexAttribArray(object1Program.getPositionAttributeLocation());
    glVertexAttribPointer(object1Program.getTextureCoordinatesAttributeLocation(), 2, GL_FLOAT, false, 16, 8);
    glEnableVertexAttribArray(object1Program.getTextureCoordinatesAttributeLocation());

    glDrawArrays(GL_TRIANGLES, 0, 6);
}

public void drawObject2() {
    glUseProgram(object2Program);
    object2Program.setUniforms(finalMatrixObject2, object2Texture);

    glVertexAttribPointer(object2Program.getPositionAttributeLocation(), 2, GL_FLOAT, false, 16, 0);
    glEnableVertexAttribArray(object2Program.getPositionAttributeLocation());
    glVertexAttribPointer(object2Program.getTextureCoordinatesAttributeLocation(), 2, GL_FLOAT, false, 16, 8);
    glEnableVertexAttribArray(object2Program.getTextureCoordinatesAttributeLocation());

    glDrawArrays(GL_TRIANGLES, 6, 6);
}

```

But I have weird artifacts and coords showing (if at all) when I try to render an element with a different pattern of vertex attributes, for example just 2 floats for position (X Y), or 3 floats for position and 2 floats for texture coord (X Y Z S T).

```
public void drawObject3() {
    glUseProgram(object3Program);
    object3Program.setUniforms(finalMatrixObject3);

    glVertexAttribPointer(object3Program.getPositionAttributeLocation(), 2, GL_FLOAT, false, 8, 0);
    glEnableVertexAttribArray(object3Program.getPositionAttributeLocation());

    glDrawArrays(GL_TRIANGLES, 12, 6);
}

```

To resume the situation, I have a VBO packed this way (it differs a bit from my previous example):

```
6 * (X, Y, S, T)
6 * (X, Y, S, T)
6 * (X, Y, S, T)
6 * (X, Y)
36 * (X, Y, Z, S, T)

```

Is it possible to do what I'm trying to do? Or do I have to use different VBOs for every element with a unique set of vertex attributes?

If it's possible, what am I doing wrong? Before moving to VBO everything was working fine.

# Answer
You were calculating the starting offsets into the buffer to render from incorrectly. The byte offset used is `pointer` \+ `first` * `stride`. When you call `glVertexAttribPointer` in `drawObject3` you set the `stride` to 8 and `pointer` to 0, so the offset is 8 * 12 which puts you at the start of your second row of data, not the row you expected. The easy way to do it correctly is to set `pointer` to where the data you want to render starts (18 * 16) and `first` to 0.

For the last row it would be 18 * 16 + 6 * 8.
> 3 votes

---
Tags: opengl-es2, vbo, vertex-attribute
---


# Question
Title: BoxCollider2D fails verification, where CircleCollider2D does not
I have a 2D game object with no parent and a 2D box collider set with trigger enables. The dimensions are quite large.

When I place the game object in the scene, manually, it works just fine. However, when I instantiate the prefab, it doesn't work; in the inspector view, under the collider component a notification appears:

> The collider did not create any collision shapes as they all failed verification. This could be because they were deemed too small or the vertices were too close. Vertices can also become close under rotations or very small scaling.

When I switch to scene view, while the game is in play mode, I can not see the collider boundaries. Surprisingly, everything works fine, if I use the circle collider. Does anyone know what the problem could be?

# Answer
> 1 votes
Read the error carefully - it took me a day to find out that the answer is in that error.

See if somehow the scale of your game object becomes 0 or any of that side is overlapping with other side. If that happens, the box collider won't work and will give that error message.

# Answer
> 0 votes
You can try this

```
GameObject canon = Instantiate(prefab);
canon.GetComponent<BoxCollider2d>().size=new Vector2(10f,10f);

```

Increase your canon box collider size based on box collider visible on your scene window.

# Answer
> 0 votes
You might try adding the collider after the object is instantiated so the calculations are correct. So first remove the collider from the prefab and then :

```
//After prefab is created

prefabCloneName.AddComponent<BoxCollider2D>();

```

# Answer
> 0 votes
In the above diagram, we can see that size *should* be relatively appropriate, and there should not be any rotation. *This could be a false assumption*. What we *do not* see is the game object hierarchy, in which our problem object could still be parented1 under *another* game object.

*Should* the game object be parented to another game object, you still want to observe the scale and rotation of any parents. Both of these will be multiplied by local values, in order to give world values. *World* values are what really matter, in context of the error being displayed.

---

In this case, I believe this could point to additional *rotation*. You say that the circle collider works fine - this would not be the case, if world scale really did make the game object too small.

However, as discussed on the Unity Answers site, the box collider can still throw this error as it approaches 90 degree rotations. This is because the rotation converts to a skew in the *interpreted* size, and at 90 degrees, one of the axis is going to be approaching rather minimal values. As the error reports, we can't have that.

---

Ultimately, if this is the case, you need to figure out if you need the parent. If you do, in turn, you should decide if you need rotation. If you need rotation, you should use a circle collider, instead.

Failing all that, due to the precise nature of your problem, I would honestly put this down to a Unity bug.

1 It occurs to me that I have missed the additional note that there *is* no parent, but it is still worth addressing the code where you instantiate objects. ***You can set a parent during instantiation without it visually displaying so in the hierarchy***. I'm unsure why such a method would be useful, as it took me some time to figure it out, too.

---
Tags: unity, 2d, collision-detection, physics
---


# Question
Title: Both Trigger and Collision BoxCollider2D
My `Player` sprite needs to collide with some objects and be unable to pass through them and in other cases detect when it passes through some object (e.g. some non-fatal enemies and some one-way barriers).

How do I test what an object is and make enforce one collision type or the other?

# Answer
> 1 votes
**Effectors!** You could create two different kinds of gameObjects:

* One is a normal barrier, so you can just attach a collider2D and make sure that in the layers interaction matrix you allow interactions between the layer the player is in and the barriers' one;
* The other gameObject is similar but you additionally attach the PlatformEffector2D component to it (be sure to tick the option "used by effector" in the collider2D component). You can then tweak how the one-way barrier will work through the inspector (direction, area of effectiveness etc.).

Here you have a good video that explains how the effectors work.

# Answer
> 1 votes
you have you have all events and callbacks for Both trigger and collider. for example **OnTriggerEnter()** and **OnCollisionEnter()** but if you want to use trigger event on a collider behavior, you can have duplicate collider component with one one them checked as trigger. you can make scale of trigger a little bigger for detection

# Answer
> 1 votes
You can also do this with just vanilla collider setup and physics layers.

Make two layers in your Tags and Layers settings:

* PlayerCollision — represents a solid player character
* PlayerTrigger — represents trigger-only interactions with player characters

In your physics settings, tick the boxes so that the PlayerCollision layer does not collide with PlayerTrigger. Both layers can still collide with themselves, with default, etc.

Give your player character prefab two child objects with colliders attached: one on the PlayerCollision layer, and one on the PlayerTrigger layer. Set `isTrigger` to true on the second one.

Now, anything that should stop the player can go on the default layer — it will interact with the non-trigger PlayerCollision collider on the player character and halt it.

Anything that should not stop the player should go on the PlayerTrigger layer. It will interact with the player's trigger collider and send trigger messages, without triggering a physical collision resolution.

These entities can still physically interact with other entities on the default layer (if you don't want them colliding with anything, then just set the entity's own collider's `isTrigger` to true instead)

This gives you the flexibility to make the player's trigger volume different than their collision volume, if that's useful for your needs. And it correctly filters all the physics behaviours without adding extra component types into the mix.

---
Tags: unity, 2d, collision-detection
---


# Question
Title: How can I get a bouncy ball conserve its energy?
In my project I have a ball with a `PhysicsMaterial` where:

* Dynamic Friction and Static Friction both are 0
* Bounciness = 1
* Friction Combine is set to Multiply
* Bounce Combine is set to Maximum

This ball has a `Rigidbody` attached in which:

* mass = 1
* drag and angular drag both are 0
* useGravity = true

In my scene there are some cubes which create a boundary for the ball to bounce inside. The ball bounces in a closed boundary. The problem is that over time the ball's maximum velocity keeps on increasing, and after some time it escapes the boundaries.

How can I prevent the velocity of this ball from exceeding a provided `maxVelocity`?

# Answer
> 0 votes
If the ball's high velocity is causing it to escape its boundaries you can improve high speed collision detection by changing the ball's rigidbody collision detection mode to "Continuous Dynamic". You can read about the details of collision modes here in the unity docs.

I'm not sure what the cause of the continuous acceleration is, I would guess either gravity, or bounciness unintentionally being calculated as \>1.

Since there is no drag and collisions are perfectly elastic, there is no reduction in energy to offset the acceleration of gravity (other than gravity offsetting itself ie: as the ball bounces upwards, gravity pulls it downwards).

Alternatively one of the physics materials involved in the collision may be set to a bounce mode that is resulting in the bounciness of a collision exceeding one, thereby adding energy to the system with every bounce.

If investigating gravity and bounce don't lead to anything you may need to set an upper limit on the ball's speed, you can see some discussion about how to implement a max speed/terminal velocity here on the unity boards.

---
Tags: unity, physics
---


# Question
Title: Implementation of a quaternion based hinge constraint
I'm trying to implement a hinge joint between two rigid bodies based on Lagnange multipliers, s.t. constraint functions to be constraints on quaternions, which describe bodies orientation, itself. It's more natural than describe constraints in terms of some vectors rigidly connected with bodies as it is just implicit quaternions. Plus quaternions should handle the problem of bistability of "vectorial constraints". It is essential to write the correct constraint functions.

It seems that I found the correct constraints but something goes wrong (later). Tell me, please, if I do something wrong or miss something. Let us concentrate just on unlimited hinge rotation of two rigid bodies about some common axis. So we need to get rid of two degrees of freedom. Let

```
q = rAconj qAconj qB rB,

```

where qA and qB are usual orientation quaternions (s.t. if a vector V has a coordinates column V' in a frame of a body B (lets name this frame B') then (qB\*(0, V')\*qBconj).im is its coordinates column in a world frame (lets call this frame W)), rB is a quaternion which carry out rotation from frame where the axis, bodies rotate about, direction vector has coordinates (0, 0, 1) (lets call this frame B'') to frame B', rA defined by analogy.

The hinge constraint would not be violated iff vectorial part of q is collinear with Z axis. I.e. the (coordinate) constraints are just

```
q.x = 0,
q.y = 0.

```

Then differentiating this equations, minding Leibniz rule, unitarity of quaternions and dq/dt = 0.5 q (0, w) identity we get

```
qdot = 0.5 rAconj (qAconj qB (0, wB) - (0, wA) qAconj qB) rB

```

and the velocity constraints:

```
qdot.x = 0,
qdot.y = 0.

```

Velocities are "decoupled" so to get Jacobian is a matter of simple quaternion multiplication. For convenience while experimenting I just write short functions getC, getCdot by which Jacobian is calculated. I'm quite sure in that part of code 'cause I've tested with "not quaternion version" of getCdot and it works fine.

Everything works fine if one of the bodies has an infinite inertia (kinematic body) or (if both bodies are dynamic) if angular velocities are orthogonal or collinear to rotation axis. If angular velocities are in general case simulation blows up. Can you get a tip why is this happening? This is not because of quadratic term (Coriolis', gyroscopic, ...) in the Euler equations -- I ignore this term for now for the sake of stability.

# Answer
> 1 votes
A possible answer: Angular velocity for the example listed above is `w=2 {q_conjg} {q_dot}` which turns out to only have a non-zero value in the last term (i.e., only `w.z` is non-zero). This makes sense since rotation and is about z-axis. If so, imposing an angular velocity that is not aligned with the z-axis would be inconsistent leading to blow up.

---
Tags: physics, joints
---


# Question
Title: Flat shaded triangles using the ModelBuilder?
I decided to give the `ModelBuilder` a try but I cannot get rid of the smoothing of my terrain. So what I tried:

* Create each triangle individually with there own vertex position.
* Put each triangle in it's own `part`.
* Put each triangle in its own `node`.
* Set indices individually after vertex positions been set.
* Used `ensureTriangleIndices` and `ensureCapacity` to set the vertex and index count.

*Executable test*

```
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.model.Node;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.MeshPartBuilder;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.math.Vector3;

/**
 * libgdxtestenvironment [2019]
 * By Menno Gouw
 */
public class TerrainBuilderTest extends ApplicationAdapter {

    PerspectiveCamera cam;
    CameraInputController camController;
    ModelBatch modelBatch;
    Model model;
    ModelInstance instance;
    Environment environment;

    //CreateTerrain createTerrain;
    // Hardcoded heightmap for testing
    private final int[][] heightMap = {
            {0, 1, 3, 1, 0},
            {1, 2, 1, 3, 1},
            {2, 3, 2, 2, 1},
            {2, 4, 2, 1, 2},
            {1, 3, 2, 1, 2},
    };

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

        setCamera();

        //createTerrain = new CreateTerrain(16, 16);
        instance = new ModelInstance(myModelBuilder(heightMap));

        Gdx.input.setInputProcessor(camController = new CameraInputController(cam));
    }

    private void setCamera() {
        cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        cam.position.set(0f, 7f, 10f);
        cam.lookAt(0, 0, 0);
        cam.near = 1f;
        cam.far = 50f;
        cam.update();
    }

    private void setEnvironment() {
        environment = new Environment();
        environment.set(new ColorAttribute(ColorAttribute.AmbientLight, .4f, .4f, .4f, 1f));
        environment.add(new DirectionalLight().set(1, 1, 1, -.2f, -.7f, -.1f));
    }

    @Override
    public void render () {
        camController.update();

        Gdx.gl.glViewport(0, 0, Gdx.graphics.getBackBufferWidth(), Gdx.graphics.getBackBufferHeight());
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);

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

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

    private Model myModelBuilder(int[][] heightMap){
        ModelBuilder modelBuilder = new ModelBuilder();

        modelBuilder.begin();
        MeshPartBuilder mpb = null;

        // Build the terrain, I tried with one part/node and with one for each triangle.
        modelBuilder.node();
        for (int y = 0; y < heightMap[0].length - 1; y++){
            for (int x = 0; x < heightMap.length - 1; x++) {
                mpb = modelBuilder.part("quad[" + x + "," + y + "]" + "tri-1", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal | Usage.ColorUnpacked,
                        new Material(ColorAttribute.createDiffuse(Color.WHITE)));
                mpb.triangle(
                        new Vector3(x, heightMap[x][y] / 2f, y),
                        new Vector3(x, heightMap[x][y + 1] / 2f, y + 1),
                        new Vector3(x + 1, heightMap[x + 1][y] / 2f, y)
                );

                modelBuilder.node();
                mpb = modelBuilder.part("quad[" + x + "," + y + "]" + "tri-2", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal | Usage.ColorUnpacked,
                        new Material(ColorAttribute.createDiffuse(Color.WHITE)));
                mpb.triangle(
                        new Vector3(x + 1, heightMap[x + 1][y] / 2f, y),
                        new Vector3(x, heightMap[x][y + 1] / 2f, y + 1),
                        new Vector3(x + 1, heightMap[x + 1][y + 1] / 2f, y + 1)
                );
                modelBuilder.node();
            }
        }

        // Try setting indices manually
        for (int i = 0; i < (heightMap[0].length - 1) * (heightMap.length - 1); i += 3){
            mpb.triangle((short)i, (short)(i + 1),(short)(i + 2));
        }

        // Try setting indice numbers
        mpb.ensureTriangleIndices((heightMap[0].length - 1) * (heightMap.length - 1) * 2);

        mpb.ensureCapacity(
                (heightMap[0].length - 1) * (heightMap.length - 1) * 6,
                (heightMap[0].length - 1) * (heightMap.length - 1) * 6
        );

        return modelBuilder.end();
    }
}

```

# Answer
I solved the issue by using `VertexInfo` but would still like a answer where I can provide raw floats straight into the `MeshPartBuilder`. I Also find it strange that in the example code in my question I provide 6 verts per quad and the mesh still gets smoothed, it probably merges the verts under the hood otherwise it could not smooth the mesh afaik.

Anyway, with `VerteInfo` I can specify all parameters.

```
            v1.setPos(x + 1, heightMap[x + 1][y] / 2f, y);
            v2.setPos(x, heightMap[x][y + 1] / 2f, y + 1);
            v3.setPos(x + 1, heightMap[x + 1][y + 1] / 2f, y + 1);
            v1.setUV(1, 0);
            v2.setUV(0, 1);
            v3.setUV(1, 1);
            v1.setNor(normal);
            v2.setNor(normal);
            v3.setNor(normal);

```

And then just provide the `MeshPartBuilder` with the `VertexInfo` objects.

```
mpb.triangle(v1, v2, v3);

```

For completeness, one does need to specify the part consist of these attributes.

```
mpb = modelBuilder.part("part",
                    GL20.GL_TRIANGLES, Usage.Position | Usage.Normal | Usage.TextureCoordinates,
                    new Material(TextureAttribute.createDiffuse(texture)));

```

And it is also worth noting that you should not create a new `VertexInfo` object for each vertex. I just initialized 3 and reused them for each triangle.
> 0 votes

---
Tags: opengl, java, libgdx, 3d-meshes, terrain-rendering
---


title: Editor throwing NullReferenceException

text:
# Question
Title: Editor throwing NullReferenceException
I have the following exception being thrown at compile time:

```
NullReferenceException: Object reference not set to an instance of an object
UnityEditor.Graphs.Edge.WakeUp () (at C:/buildslave/unity/build/Editor/Graphs/UnityEditor.Graphs/Edge.cs:114)
UnityEditor.Graphs.Graph.DoWakeUpEdges (System.Collections.Generic.List`1[T] inEdges, System.Collections.Generic.List`1[T] ok, System.Collections.Generic.List`1[T] error, System.Boolean inEdgesUsedToBeValid) (at C:/buildslave/unity/build/Editor/Graphs/UnityEditor.Graphs/Graph.cs:387)
UnityEditor.Graphs.Graph.WakeUpEdges (System.Boolean clearSlotEdges) (at C:/buildslave/unity/build/Editor/Graphs/UnityEditor.Graphs/Graph.cs:286)
UnityEditor.Graphs.Graph.WakeUp (System.Boolean force) (at C:/buildslave/unity/build/Editor/Graphs/UnityEditor.Graphs/Graph.cs:272)
UnityEditor.Graphs.Graph.WakeUp () (at C:/buildslave/unity/build/Editor/Graphs/UnityEditor.Graphs/Graph.cs:250)
UnityEditor.Graphs.Graph.OnEnable () (at C:/buildslave/unity/build/Editor/Graphs/UnityEditor.Graphs/Graph.cs:245)

```

I know well enough what a `NullReferenceException` is and what causes one, but the stack trace above implies that it's being thrown by the editor or some other internal thing.

Does anyone have any advice on how to debug this?

# Answer
> 0 votes
No idea what the original cause was, however the exception vanished after upgrading Unity so I can only assume it was something corrupted in the install/packages/other.

---
Tags: unity
---


# Question
Title: Libgdx fbx converter doesn't write meshes to g3dj file
LibGDX FBX converter doesn't write meshes nor materials to g3dj file.

This happens with blender 2.8 when exporting model to `FBX` then converting it to `g3dj`. meshes will result in an empty block.

2.8 blender settings

and when converting...

`g3dj` file..

```
{
   "version": [  0,   1],
   "id": "",
   "meshes": [],
   "materials": [],
   "nodes": [
       {
           "id": "Cube",
           "rotation": [-0.707107, -0.000000,  0.000000,  0.707107],
           "scale": [ 10.000000,  10.000000,  10.000000]
       }
   ],
   "animations": []
}

```

I tried to convert a `fbx` written with blender `2.76` with these settings...

and meshes and materials are written in `g3dj` file successfully. I'm thinking this has to do with `FBX` version, but it seems you can't change `FBX` version in blender `2.8`

# Answer
Silly me, IT says the error right on the terminal

`skipping geometry without materials`

Just add a material to the model.

Seems blender previous versións of blender models comes with a default material
> 1 votes

---
Tags: libgdx, blender, fbx
---


# Question
Title: Why is my player movement code not working?
I'm trying to make my 2D character able to float around the screen, but my code isn't working:

```
using UnityEngine;

public class playermovement : MonoBehaviour
{

    public float moveSpeed = 5f;

    public Rigidbody2D rb;

    Vector2 Movement;

    public Vector2 Movementspeed { get; private set; }

    // Update is called once per frame
    void Update()
    {
        Movement.x = Input.GetAxisRaw("Horizontal");
        Movement.y = Input.GetAxisRaw("Vertical");
    }

    void FixedUpdate()
    {
        rb.MovePosition(rb.position + (Movement * Movementspeed * Time.fixedDeltaTime));
    }
}

```

# Answer
> 1 votes
Let's go over what your code is doing, and perhaps we can point some things out.

You use the variable `Movement` to capture the input for each axis at each update frame:

```
void Update()
{
    Movement.x = Input.GetAxisRaw("Horizontal");
    Movement.y = Input.GetAxisRaw("Vertical");
}

```

Capturing this in a `Vector2` makes sense since you're moving in 2d, and doing it in the `Update` callback makes sense since you want to read the input every frame. So far so good.

Then in fixed update, you're moving the position of the `Rigidbody2d` by doing so:

```
rb.MovePosition(rb.position + (Movement * Movementspeed * Time.fixedDeltaTime));

```

What is the value of the variable `Movementspeed` at this point? Unless you have used the property setter to give it a value from somewhere else, it would default to (0,0). So the value of the statement `(Movement * Movementspeed * Time.fixedDeltaTime)` will return 0. So essentially you're setting the position of the rigidbody to its current position.

But really think about what you're trying to do in that statement. `Movement` is a 2d vector that represents your direction of movement, `Time.fixedDeltaTime` ensures that we move by a consistent amount no matter the variance in time between fixed update calls, but what is the purpose of `Movementspeed`? You're doing a cross product here when I don't think you intend to. You don't really need to use another `Vector2` to represent your speed, just use a float. Remember that any vector multiplied by a float just changes the magnitude of that vector. The direction stays the same.

So what you probably want to do here is:

```
rb.MovePosition(rb.position + (Movement * moveSpeed* Time.fixedDeltaTime));

```

where `moveSpeed` is the float variable you've defined at the top of the script.

# Answer
> 0 votes
I fixed it thanks for the help? it works now! this is how it ended up:

using UnityEngine;

public class playermovement : MonoBehaviour {

```
public float moveSpeed = 5f;

public Rigidbody2D rb;

Vector2 movement;

// Update is called once per frame
void Update()
{
    movement.x = Input.GetAxisRaw("Horizontal");
    movement.y = Input.GetAxisRaw("Vertical");
}

void FixedUpdate()
{
    rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
}

```

}

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


# Question
Title: threejs lerp and camera the animation is not smooth
what is the problem with linear interpolation?
in update() in case this is animate() and when I call zoomCamera() in update() there is lerp with smooth but when I call here

```
function onObjectsClick(event) {
            event.preventDefault();
            setPickPosition(event);
            raycasting(pickPosition, scene, camera);
            pickedObject = intersectedObjects[0].object;
            const notebook = pickedObject.getObjectByName('notebook');
            const laptop = pickedObject.getObjectByName('laptop');

            if (notebook || laptop) {

                zoomCamera();
            }

        }
canvas.addEventListener('click', onObjectsClick, false);

```

in **if** there is no smooth lerp but sharp transition what I miss?

```
function zoomCamera() {
            const vec = new THREE.Vector3(-1, 2, 2);
            const alpha = .1;
            camera.position.lerp(vec, alpha);
            console.log('zoom');
        }

```

and the onObjectsClick is in animate()
why it is happened?

# Answer
Unfortunately there are many ways to do what your asking and from the info you have here it's very hard to tell what's going on. We're missing a lot of information.

It appears to me that `zoomCamera();` in `onObjectsClick(event)` is not an "Updated" but a single frame function.

It appears to me that you are using lerp in a way that it's not really designed for. Don't get me wrong, if it works then awesome. But lerp is typically a value between 0% and 100%. So, you need to get the percentage of where you want it to be along its trip. Here, take a look at what I have here written in C#. Plug it into a fresh script and drag the script onto the camera. press the "M" and you'll see it lerps. You can adapt this to "slerp" or Spherical Lerp very easily. slerp is a lerp on a sign wave function. Looks smoother but fundamentally the same thing. I hope this helps you learn about Lerp and how it's supposed to work.

LERP REQUIRES: A static start point. A static end point. A static start time. A static length (of time or anything really).

If you update any of these values while it's lerping you'll likely end up with an infinite lerp (which can look smooth sometimes) or just a quick pop from one place to another. Like I said, use it how you like. What ever gets the effect you're looking for but this is likely one of the more optimal (performance wise) ways to use lerp.

```
public class CameraLerp : MonoBehaviour
{

public Vector3 camPosStart;
public Vector3 camPosTarget;
public float lerpStartTime;
public float lerpTimeLength = 5f;
public bool lerping;

private void Update()
{
    MoveCamera();
}

private void MoveCamera()
{

    //every time you press m the camera will move 10 on the z axis (world space).
    //This will work for any vector3's.  Just input the start time as Time.time and the
    //startPos as the currect Vector3's value.  The target as the target value
    if (Input.GetKeyDown(KeyCode.M))
    {
        lerpStartTime = Time.time;
        camPosStart = Camera.main.transform.position;
        camPosTarget += new Vector3(0, 0, 10f);  //this should be set to what ever you want the camera position to lerp to.
        lerping = true;
    }

    if (Camera.main.transform.position == camPosTarget)
    {
        lerping = false;
    }

    if (lerping)
    {
        Camera.main.transform.position = Vec3Lerp(camPosStart, camPosTarget, lerpStartTime, lerpTimeLength);
    }
}

private Vector3 Vec3Lerp(Vector3 start, Vector3 target, float startTime, float timeLength)
{
    float timeLerping = Time.time - startTime;

    float percentageComplete = timeLerping / timeLength;

    Vector3 result = Vector3.Lerp(start, target, percentageComplete);

    return result;
}
}

```
> 2 votes

---
Tags: javascript, webgl, three.js
---


# Question
Title: How to make a homing projectile make a more objective path to the target?
I'm having trouble trying to get a projectile thrown by a tower to hit the player quickly.

**See the image below:**

The projectile hits the ground very close to where the player was.

If the player did not move so much, the projectile would certainly hit him, but even by slowing the player down and increasing the speed of the shot, the projectile often does not hit the player.

What happens almost always is the projectile orbiting the player.

If the player stands still when the tower starts firing, the projectile hits him, the problem happens when the player moves, the projectile does not follow the player correctly.

**Expected result:**

I have already tried to modify the speed of the player and the projectile, but I have not obtained efficient improvements in the result. I tried to modify the gravity (of the projectile and its mesh), friction. All to no avail.

**Projectile BP:**

---

EDIT 1

**With this code I was able to stop the projectile from crossing the floor:**

**But the projectile still orbits the player:**

If the player does not stop moving, the projectile orbits it indefinitely.

Below is how the components went after I turned off the physics at all.

**Sphere Collision:**

**Static Mesh:**

**ProjectileMovement:**

# Answer
> 1 votes
### Intercept the target

I'm not too familiar with UE, but the behaviour you describe is consistent with the projectile "naively" accelerating towards the target's current position (from your blueprint, it looks like a constant acceleration is indeed being applied).

To actually hit a moving target, you should predict its location at the time the projectile actually reaches it, and move towards that point\*.

If the projectile is significantly faster than the target, an easy approximation for that point would be:

```
travel time = distance to target / projectile speed
point to move towards = target position + (target velocity * travel time)

```

---

(\* Recalculate periodically, e.g. once per physics tick)

# Answer
> 1 votes
This is probably what you need. It's for unity in C# but the maths all there.

http://wiki.unity3d.com/index.php/Trajectory\_Simulation

I use this all the time and it is VERY accurate even at high speeds. It can't predict changes in direction like weaving but it will hit where the target is going to be on the dot every single time. If you want it to predict direction changes you need homing code added but you don't sound like you want homing missiles. You want projectiles.

Hope this helps.

---
Tags: unreal-4, path, projectile
---


title: Select a button without calling click

text:
# Question
Title: Select a button without calling click
i have a grid layout group containing buttons. My game must be playable with a joystick and so I have to navigate the buttons using horizontal/vertical input.

My problem right now is when the layout group first becomes visible. Once I click on a button (with my mouse), it becomes "selected" and I can navigate through the layout group with my keyboard and 'click' with spacebar. This functionality is all fine, *except* for the need to click the button with a mouse to set the first selection.

I've tried both of the following:

```
void buttonClicked() {
    Debug.Log("clicked");
}

void Start () {
  // this button is actually instantiated from a prefab,
  // not shown here
  Button btn = inventorySlot.button;

  btn.onClick.AddListener(buttonClicked);

  # attempt 1
  btn.Select();

  # attempt 2
  eventSystem.SetSelectedGameObject(
    btn.gameObject,
    new BaseEventData(eventSystem)
  );
}

```

both these commands *do* select the button, but they also inadvertently call the `onClick`, and the button is clearly being clicked because it changes color (I have configured this through button opts in the inspector).

My question is - how can I "select" the button without clicking it?

I perhaps should also note, I am populating the layout group with buttons at runtime. Each button is intantiated from a prefab in `Start()` (not showing that here). I only add the event listeners and try to select the button after it's already added to actual game objects in my scene.

# Answer
Figured it out, the issue was that I call `btn.Select()` before the menu is actually open, and space is *also* the command to show the menu. So basically I need to put the `btn.Select()` *after* the menu is visible.
> 1 votes

---
Tags: unity
---


# Question
Title: Preventing the final segment in a linerenderer from being stiff?
I am creating a fishing pole, and have the script that draws the line -mostly- worked out using verlet physics. However, the final segment is stiff. The code follows an old Unity3D Subreddit post.

Best way to do fishing line

I was able to read through the advice, and came up with a similar set of classes. They seem to work pretty well, though I have to prewarm the line on startup. My main issue is that my version attaches to two targets.

The first is the pole end, which seems fine, but the final segment is the hook. The last segment for it remains 'stiff', while the rest of the line curves properly. I'm not one hundred percent sure how to fix this, and advice would be much appreciated. The issue appears to be the way I'm setting the final target, but I'm not sure how to normalize it all. The code follows a picture of the stiff segment:

```
using UnityEngine;

public class LineParticle  {
    public Vector3 pos;
    public Vector3 oldPos;
    public Vector3 Accel = new Vector3(0, -1.95f, 0);
}

using UnityEngine;

public class Line : MonoBehaviour {

    public LineRenderer lineRenderer;

    LineParticle[] lineLength;
    public Transform targetObject;
    public float lineRest = 0.8f;
    public int lineSegmentCount = 30;
    private Transform tc;

    private bool isReady = false;

    private void Awake()
    {
        lineRenderer = GetComponent<LineRenderer>();
        tc = transform;
    }

    public void Start()
    {
        lineRenderer.positionCount = lineSegmentCount;
        lineLength = new LineParticle[lineSegmentCount];

        for(int i = 0; i < lineSegmentCount; i++)
        {
            lineLength[i] = new LineParticle();

        }

        for (int i = 0; i < 450; i++)
        {
            loopRun();
        }

        isReady = true;
    }

    private void Verlet(LineParticle p, float dt)
    {
        Vector3 temp = p.pos;
        p.pos += p.pos - p.oldPos + (p.Accel * dt * dt);
        p.oldPos = temp;
    }

    private void PoleConstraint(LineParticle p1, LineParticle p2, float restLength)
    {
        Vector3 delta = p2.pos - p1.pos;
        float deltaLength = delta.magnitude;

        float diff = (deltaLength - restLength) / deltaLength;

        p1.pos += delta * diff * .5f;
        p2.pos -= delta * diff * .5f;
    }

    private void FixedUpdate()
    {
        if (isReady)
        {
            loopRun();
        }
    }

    private void loopRun()
    {
        lineLength[0].pos = tc.position;

        for (int i = 0; i < lineLength.Length; i++)
        {
            LineParticle lp = lineLength[i];

            Verlet(lp, 0.8f * Time.deltaTime);

            int testLP = i + 1;

            for (int y = 0; y < 6; y++)
            {
                if (testLP < lineLength.Length - 1)
                {
                    LineParticle lp2 = lineLength[testLP];
                    PoleConstraint(lp, lp2, lineRest);
                }

                if (i == lineSegmentCount - 1)
                {
                    lineLength[i].pos = targetObject.position;
                }

                lineRenderer.SetPosition(i, lp.pos);
            }

        }
    }
}

```

# Answer
you have width curve in **LineRenderer Component**. you can simply add nodes to it ad change width along it.

if you look for a whole curve, something like bezier curve is suitable for you.
> 1 votes

# Answer
Found the problem. Wrong operator - testLP \< lineLength should be \<=.
> 0 votes

---
Tags: c#, physics, line-renderer
---


# Question
Title: Best way to do multiple choice in Unity 2D?
So I'm about to start development on a game in unity that is going to require multiple choice each choice having a some what unique function. I've thought of 2 ways of doing this but I'm unsure if there is an easier way as I've never really worked with unity.

So the first way I was thinking about doing this and I think better then the second would be to make a class for each choice with all the functions that belong to that choice in there and then just calling it when its needed. However, I don't know if this will scale very well as I will have over 100 different events with their own choices...

The second way I was thinking was to do it via JSON and then just code each function to parse that. So for example: `addmoney`, `dothis`, `dothat` etc... However this seems like a lot more work then it would be worth so I'm not 100% sure...

So I'm wondering what option would be better and if anyone else has any suggestions I'd love to hear!

# Answer
> 0 votes
Have a base abstract class of Choice. It has options such as "Choose". Then the functionality of choose is implemented in the subclasses.

```
public abstract class Choice
{
    void Choose();
}

public class RightChoice : Choice
{
    public void Choose()
    {
        Debug.Log("You made the right choice!");
    }
}

public class LeftChoice : Choice
{
    public void Choose()
    {
        Debug.Log("You made the left choice!");
    }
}

```

Then you can proceed to sub-class LeftChoice and RightChoice as needed.

*Disclaimer: For the sample code above, an interface would be better. But I suspect that an abstract class will be better for your situation.*

# Answer
> 0 votes
you have lots of choices. i list a few and you can choose which works best for you.

1) simple **if.. else** statement. its hard-coded and you dont have much freedom

2) switch case statement. its not OO and is not adviced.

3) using **command** pattern. this is like @Evorlor done in his answer. you can change command or choices by simply changing the class.

4) using **delegate** and events. you can simply Make a Delegate like **Action** and change choices just by set different function to it.

---
Tags: unity, c#, game-mechanics
---


title: Have two steamworks accounts?

text:
# Question
Title: Have two steamworks accounts?
I am finishing my game project and I already have my steamworks registration, I am just fine-tuning details and preparing marketing for the start.

But I look a little short of cash, I would like to invest more in marketing, when I heard this, a friend recommended that I sell some educational games that I had done a while ago (type "dora the explorer") but I don't want to publish them in my account , since my current project is a game of gore, blood, violence etc. I don't think it's right that they are "together", can I generate a new steamworks account to publish my other games?

I have not found anything in the document confirming that yes or no

# Answer
I have never worked on steam but after few searches i found this on Quora:

**Quote from "Adam Henley"**

" The advice on Steam’s FAQ:

**Should I create a new Steam account to post with?**

This will depend on your situation. If your Steam account is already associated with a Steamworks partner and your submission is for that partner, then you should continue to use that Steam account. If you are a member of an existing Steamworks partner but wish to post a submission that will not be part of that Steamworks partner, then please create a new Steam account before you post.

If you represent a team of individuals or a company, you may find it beneficial to create a new Steam account to represent your team or company rather than using your personal account to post.

> Src: Steam Workshop :: Greenlight FAQs

I can see benefits of creating a separate account, including but not limited to (other benefits available):

* You may want to publish as a brand to look more professional
* You may want to maintain the privacy of your existing Steam account
* A VAC ban or bad feedback from a trade on your personal profile might look bad (even if they have innocent explanations).

> Link To Quroa Post

**Note:** I don't have any experience with steam And I am not sure how legit is the above answer. I am just trying to help if i am able.
> 2 votes

---
Tags: steam
---


# Question
Title: Sanitise a high score table to remove offensive terms / usernames
I'm building an app for a client, which they've requested to have a publicly-visible high score table. It'll be displaying their username, which is a free-text field that the players can input. Player count is likely to be extremely low - I’d expect 10s or 100s/day at most.

The username field will be longer than 3 characters. The names will be tied to Firebase Auth accounts, but these are created through the app, not tied to anything like Google Play or a Facebook account or anything like that. I think they’re going to be fine with deleting obviously offensive names, but they’re not going to have massive resources devoted to manual moderation.

When I was a young lad, 100% of my local arcade cabinet high score tables consisted of a bunch of swear words and offensive terms (or variations of such words).

I can't imagine the internet has improved matters at all.

How can I sanitise usernames to make them safe for display?

# Answer
> 73 votes
**I recommend you just let the client do it manually.**

From a cost perspective, you have luck on your side this time:

* You expect no more than 100 users/day, possibly as low as 10/day
* You have an authentication system, meaning bans can be permanent
* You have a client that is happy to delete names (infrequently)

The reality is, the 10 minutes it will take for somebody to look over the top leaderboards and ban any extreme names - will simply be cheaper and more reliable, than you spending time on an engineering solution (which will have problems).

With such a low playercount, it's unlikely this would need done often - even once per week during peak is likely to be enough.

---

**But I've got plenty of time, I can do something right?**

Wrong.

You can very easily do something wrong, that is more damaging to the client's brand than doing nothing at all.

Want to use Regex to catch all the bad names? Better hope you get it perfectly right, and also filter all false-positives from multiple databases of international real-people names:

https://en.wikipedia.org/wiki/Scunthorpe\_problem

And even if you do manage the above successfully, players are not dumb - they will very easily find a way around your system to create an equally offensive name that you aren't catching.

At a minimum, you have just added even more work in keeping these rules updated, compared with the small manual work of just looking at the highest scores and banning.

---

**No but seriously, this is a kids game - the client has made it clear there can be NO TOLERANCE for offensive names. There has to be something!**

If this is honestly the case, and you cannot tolerate offensive names at all. The only realistic solution is just not to let your players create their own names.

This is the solution you'll find on almost all children's gaming websites, such as Cartoon Network.

Instead of giving a blank input, you give a selection of premade "name parts". For example:

* An adjective, such as "Awesome", "Fantastic", "Cunning"
* A middle, such as "Bearded", "Laser-eye", "Pirate"
* A noun, such as "Master", "Winner", "Detector"

Which restricts display names to things like "Awesome Pirate Master".

*Do also give a quick consideration of what wordlists you are using. There is no point implementing this system if the user is able to fiddle names to get things that still sound offensive or dirty.*

Of course, there is the possibility for duplicates as well - but you can either write this off (3 lists of 100 words, already gives 1 million possible names) due to how few players you have, or if needed - you can still check that nobody else has the name on registration.

Realistically, this may be the most effective solution if you are seriously worried about bad names. But you do need to do a cost analysis, and find whether even making this system is really worth it compared to simple manual checks.

# Answer
> 7 votes
A small user-base is probably not enough to detract from the ease of implementing a blacklist. There are many libraries and/or word-lists such as the ones referenced here that can allow you to simply check usernames against whatever you deem inappropriate.

If you decided to attempt your own list, you probably want to use `regex` to filter out names.

As Bilkokuya points out, there may be issues with legitimate names getting blacklisted. *That is a business decision for your client to make*, but one that you can/should make them aware of. I am not aware of any ways to get around the cultural aspect, except that if you are expecting a large number of users from cultures where that may be an issue, you may want to implement region-specific filtering.

Reasons to implement some form of filtering (in addition to manual checks):

* Ease of implementation. Probably won't take more than an hour to get *something* going.
* A deterrent to the less-dedicated pranksters.
* Allows for checking at registration-time, lowering the chance that they will even reach the high score table.
* Works **with** manual checks.
* Seeing as it's an old problem, there should be many resources available.

---
Tags: leaderboards
---


# Question
Title: Is it possible to run simulation of two scenes simultaneously in Unity3D?
I have got 2 scenes in a unity project and want to play simulation of both the scenes in parallel. Has anyone tried this? Thanks!

# Answer
You can load multiple scenes additively with

`SceneManager.LoadScene(scene, LoadSceneMode.Additive);`

The result will be that the objects of both scenes exist in the same 3d space. That means the objects from the two scenes can potentially collide and interact with each other. If you don't want that, then there are two strategies you can use to avoid this:

1. Use layers to isolate the physics and rendering of the two scenes.
2. Have the content of the two scenes far away from each other in 3d space.
> 1 votes

---
Tags: unity, simulations, scene
---


# Question
Title: What is an ArchVisCharacter? What is it used for?
As the question states.

I can't really find any useful documentation surrounding this.

What is an ArchVisCharacter and what do you use them for?

# Answer
> 1 votes
`AArchVisCharacter` is a character actor subclass. The term "ArchVis" is short for "architectural visualization," which is a feature area Unreal has been branching out into recently.

If you’re building any sort of architectural visualization or product design demo or VR scene using Unreal Studio, you may want to use an `AArchVisCharacter`. If you're just building a "regular game," you don't need to use it, although you probably could if you wanted to.

It's a reasonably small class contained in its own plugin. It provides some basic movement APIs suited for first-person style movement, and uses a related `UArchVisCharacterMovementComponent` to implement custom `PhysWalking` behavior.

---
Tags: unreal-4, unreal
---


title: Collision Detection For A Maze/Cave

text:
# Question
Title: Collision Detection For A Maze/Cave
I have a simple code written in Processing 3.x that I am using to test out the collision detection for a cave/maze.

The code is here: https://github.com/NoahJon3s/New-Journey-The-Game/blob/master/sketch\_190820a.pde

If you where to run said code, you'd see that I have the code so that it detects collisions on the x-axis (top of the rectangle) and y-axis (left side of the rectangle), and correctly prevents the movement of the "player" from moving out of the rectangle, but I cannot seem to find a solution for preventing the movement out of the bottom or the right side of the rectangle, even though I am able to detect the collision. Every solution I try seems to lock the "player" to those respective sides. Any suggestions?

Thanks in advance.

# Answer
> 1 votes
You have a logic problem in your code here

```
if(x>oldx)
{
 x=oldx;
 x-=2;
}

if(x<oldx)
{
  x=oldx;
  x+=2;
}

```

The reason why it only works for left and top is because you are overriding the x value in the second if statement. When going right x will be greater than oldx. You then set x to oldx - 2, the second if checks if x is lower than oldx which in this case it is. The way to solve this is to put else if in front of the second if statement. This also counts for the Y axis.

---
Tags: collision-detection, processing
---


# Question
Title: Quaternion.slerps resets camera rotation to (0,0,0) when i go to play mode help!
i am building a camera rotation script like in fps. Everything is setup and working except that camera rotation resets to zero at the start of game which i dont want. This is the camera rotation i have set:

This is rotation of character my script is attached to:

And after hitting play it resets camera rotation to (0,0,0). i want it to remain how i have set it in inspector. i am using quaternion.slerp to rotate camera around to rotations on the basis of touch inputs. After reset to (0,0,0) everything works fine.please help, i have always had a hard time understanding quaternions.

this is the script:

```
    public class ScreenCharacterController : MonoBehaviour {

     private Camera mainCamera;
     private CharacterController character;
     private int leftFingerID = -1;
     private int rightFingerID = -1;
     private Vector2 leftFingerInput;
     private Vector2 rightFingerInput;
     private float xAxisRotation;
     private float yAxisRotation;
     [SerializeField] private float minXRotation;
     [SerializeField] private float maxXRotation;
     [SerializeField] private float minYRotation = -25f;
     [SerializeField] private float maxYRotation = 25f;
     [SerializeField] private float cameraRotationSpeed = 20f;

     void Start()
     {
         mainCamera = Camera.main;
     }

     void Update()
     {
        //for touch
         TouchInput();

        //for calculating rotation vaues
         CalculateAndClampRotation();

         RotateCamera();
     }

     void TouchInput()
     {
         foreach (Touch touch in Input.touches)
         {
             if (touch.phase == TouchPhase.Began)
             {
                 //Left Touch
                 if (touch.position.x < Screen.width / 2)
                 {
                     leftFingerID = touch.fingerId;

                 }
                 //Right touch
                 else
                 {
                     rightFingerID = touch.fingerId;

                 }
             }
             else if (touch.phase == TouchPhase.Moved)
             {
                 //Left Touch
                 if (touch.position.x < Screen.width / 2)
                 {
                     if (leftFingerID == touch.fingerId)
                     {

                     }

                 }
                 //Right touch
                 else
                 {
                     if (rightFingerID == touch.fingerId)
                     {
                         rightFingerInput = touch.deltaPosition * Time.smoothDeltaTime;

                     }

                 }
             }
             else if (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled)
             {
                 if (touch.fingerId == leftFingerID)
                 {
                     leftFingerID = -1;

                 }
                 else if (touch.fingerId == rightFingerID)
                 {
                     rightFingerID = -1;
                     rightFingerInput = new Vector2(0, 0);
                 }

             }
         }
     }

 void RotateCamera()
     {
         Quaternion currentRotation = mainCamera.transform.localRotation;
         Quaternion targetRotation = Quaternion.identity;

         targetRotation = Quaternion.Euler((mainCamera.transform.localRotation.x - yAxisRotation),
         -(mainCamera.transform.localRotation.y - xAxisRotation), 0f);

         mainCamera.transform.localRotation = Quaternion.Slerp(currentRotation, targetRotation, 0.5f);

     }

     void CalculateAndClampRotation()
     {
         xAxisRotation += rightFingerInput.x * cameraRotationSpeed;
         yAxisRotation += rightFingerInput.y * cameraRotationSpeed;
         xAxisRotation = Mathf.Clamp(xAxisRotation, minXRotation, maxXRotation);
         yAxisRotation = Mathf.Clamp(yAxisRotation, minYRotation, maxYRotation);
     }

 }

```

# Answer
Thanks @DMGregory for pointing this out. Fixed it by initializing xAxisRotation and yAxisRotation variables to camera's start rotations and by changing the target rotation.

Initialized those at start method and i have also carefully set clamping values according to default camera x and y rotations. My start method now looks like this:

```
void Start()
    {
        mainCamera = Camera.main;

        xAxisRotation = mainCamera.transform.eulerAngles.y;
        yAxisRotation = mainCamera.transform.eulerAngles.x;

        minYRotation = xAxisRotation - minYRotation;
        maxYRotation = xAxisRotation + maxYRotation;

        minXRotation = yAxisRotation - minXRotation;
        maxXRotation = yAxisRotation + maxXRotation;

    }

```

Also changed this code:

```
Quaternion targetRotation = Quaternion.identity;

targetRotation = Quaternion.Euler((mainCamera.transform.localRotation.x - yAxisRotation),
         -(mainCamera.transform.localRotation.y - xAxisRotation), 0f);

```

to this:

```
Quaternion targetRotation = Quaternion.Euler(yAxisRotation, xAxisRotation, 0f);

```
> 1 votes

---
Tags: unity, c#, camera, quaternion, touch
---


# Question
Title: What's an acceptable delay between a player's action and the effects of the action being visible?
So, I'm creating a game where all the systems push events onto the event queue. Those events are then dispatched at the start of the next frame. This works fine, but there are some situations where the delay between a player's action and the effects of the actions can be upto 3 frames.

3 frames for a 60fps is around 50ms. Is this kind of "lag" noticeable to a player?

# Answer
200ms of delay (between input and response) can be considered to be the point at which things get annoying. Sensitivity to the issue varies from person-to-person, of course, so it's not really possible to give a concrete number.

A delay of 50ms is well under that, and is probably not going to be that noticeable. It may be a problem if your event dispatch is tied to frame rate and you have sustained dips below 60, or if anything else occurs to change the delay from your theoretical worst-case noted in your question.

In general, user testing can give you a more complete picture of whether or not the effect of the latency matters. I suspect you'll be fine, however, unless you're making a game for which reaction time is very important (fighting games, rhythm games).
> 2 votes

---
Tags: game-design, architecture, events
---


# Question
Title: Unity) What should i do if i want to change sprite animation in same action?
My character has Idle-Walk-Jump-Attack state in animator. and it can change its appearance when it gets an item. for example, it can equip sword or armor. and i need to change whole sprite. the sword and armor are not separate with body.

which is best way to handle it?

before get item) Idle-Walk-Jump-Attack with sprite set 1.

after get item) Idle-Walk-Jump-Attack with sprite set 2.

how can i change animation state after get item? do i make every animation state in Base Layer?

# Answer
> 1 votes
When equipping items, it really is best to have them be separate from the rest of the sprite. Unless there are only a handful of items in the entire game that can appear to be equipped, it takes a lot of effort to remake every animation for every item. Additionally, if the player can have multiple items simultaneously, you will need to animate every combination of items too. And on top of that, all that work will have very little payoff unless each unique item needs to *drastically* change the animation of the character.

Equipping an item that is separate from the sprite isn't too difficult. If the item is static on the player, it can just be parented to the player's sprite and positioned fittingly. If it's animated, you can have a separate animator control the equipment's animations (or you can make the main animator do it which can get tedious).

If the item needs to move with the player's animations (IE a sword needs to swing with the hands of the player), you could either move the hands and sword in code, or you could make an empty game object that is animated to move with the hands in all the animations and then parent the weapon to that empty game object when it is equipped.

But if you really want to animate the player again for every single combination of items, and you don't have many items (or you have way too much spare time), then a similar approach to DMGregory's comment on Millard's answer may be appropriate. You would have a separate Boolean for each item (for a sword it would be "hasSword" and for armor it would be "has Armor") that is set to true when each item is equipped. Then, the animator would have transitions between each item's animation set (IdleDefault -\> IdleSword, WalkingDefault -\> WalkingSword, etc) based on those variables. And yes, every animation would be in the base layer.

# Answer
> 0 votes
What I would do is I would have a different animation for such states, like "walk" "walk\_sword" etc. than, I would make different animation bools, like "isWalking" "isWalkingSword" etc. and then, I would have a boolean on the script that handles the animations, called hasSword, set to false. and then, at the point where you want to start the walk animation, you could type

```
if(hasSword)
{
   animator.SetBool("isWalkingSword", true);
}
else
{
   animator.SetBool("isWalking", true);
}

```

then, when you pick up the sword, you could set the boolean hasSword true.

This is tedious, but I can't think of another way of doing it.

I hope this is helpful.

---
Tags: unity, animation, sprites
---


# Question
Title: How to make a changeable color constant for editor materials?
Due to the nature of a project I'm working on, the models I got have a bunch of redundant materials on them. I have to fiddle around with some of the colors, but every time I want to change the colors, I have to change each material to the exact same color.

Is there any way to declare some kind of swatch that I can *change* and have those changes just apply to the materials or anywhere else? For instance, in code, you'd just make a `readonly Color mainColor`, that you'd use wherever you need and could change at will. I'm looking for this kind of behavior in the **editor** itself.

# Answer
> 1 votes
If the materials are entirely redundant, it might be best to apply a single material to all of the models, and then delete all of the other redundant materials.

If they are different enough to make it worth changing each one individually, you could write an editor extension that takes a single color and a list of materials as inputs, and then applies that color to all the materials in the list. If you need help writing an editor extension, check out Brackey's YouTube video on the topic.

---
Tags: unity
---


title: CharacterController rotation with mouse

text:
# Question
Title: CharacterController rotation with mouse
I'm trying to rotate my characterController around with the mouse movement. I've tried to do so with this:

`rotLeftRight = Input.GetAxis("Mouse X") * MOUSESENSIVITY * Time.deltaTime;
 rotUpDown = -Input.GetAxis("Mouse Y") * MOUSESENSIVITY * Time.deltaTime;`

It works fine when I just move the mouse, but Input.getAxis returns 0 if you don't move the mouse, even if it's already on a corner of the screen. Is this normal?

What I need is something that returns 0 only when the mouse is in the center of the screen. I don't know if that is posible using Input.GetAxis or I should use another function.

Anybody can help me with this?

# Answer
`Input.GetAxis()` returns the velocity of the axis in that frame. For example, getting the x-axis from a controller with a joystick will return the same thing as if you had moved your mouse to the right a certain amount. `Input.GetAxis()` will not tell you the overall movement of the mouse over multiple frames, or the position of the mouse on the screen.

To get the mouse position, use `Input.mousePosition`. If you want that value to be 0 when the mouse is at the center of the screen rather than the corner, subtract half of the screen size (this vector: `new Vector2 (Screen.width/2, Screen.height/2)`). For more information, check out the Unity docs: Input.mousePosition
> 2 votes

---
Tags: unity, rotation, mouse
---


title: Unity RTS Single Selection Problem

text:
# Question
Title: Unity RTS Single Selection Problem
I am trying to build an RTS game and I have managed to form a way to select a unit using Raycast and the tag system. I made it so that if the object the ray falls onto is of tag "TankUnit" Make so and so variable true and allow it to move to another place. However, Units of the same tag even when not selected also move. How do I fix this problem? The script is bound to each unit.

using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI;

public class UnitController: MonoBehaviour { bool clicked = false; //public float speed = 10f; //public float rotationSpeed = 10f;

```
 public LayerMask groundLayer;
 public NavMeshAgent playerAgent;
 // Update is called once per frame
 void Update()
 {
     if (Input.GetMouseButton(0))
     {
         Debug.Log("Clicked");
         FindClickPos();
     }
     if (Input.GetMouseButton(1) && clicked == true)
     {
         Debug.Log("I clicked right mouse");
         Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
         RaycastHit hit;
         if (Physics.Raycast(ray, out hit))
         {
             MoveTo(hit);
         }
     }
 }
 private void FindClickPos()
 {
     RaycastHit hitInfo = new RaycastHit();
     bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo);
     if (hit == true)
     {
         Debug.Log("I hit " + hitInfo.collider.name);
         if (hitInfo.collider.tag == "TankUnit")
         {
             Debug.Log("I hit" + hitInfo.collider.tag + "!");
             clicked = true;
         }
         else
         {
             Debug.Log("I didnt hit a unit :/");
             clicked = false;
         }
     }
     else
     {
         Debug.Log("I didnt hit anything...");
         clicked = false;
     }
 }
 void MoveTo(RaycastHit hit)
 {
     Debug.Log("Position: " + hit.point);
     playerAgent.SetDestination(hit.point);
 }

```

}

# Answer
> 0 votes
The problem lies in the fact that you run the FindClickPos function for every unit. This means that if you hit 1 tank all the tanks will set their clicked variable to true. When you then right click to move all the tanks will move to that position.

To easily fix this you can check if the ray hit itself, if not you don't set clicked to true. The code below is not tested but should give you the idea.

```
if (hitInfo.collider.gameObject == this.gameObject)
{
    Debug.Log("I hit" + hitInfo.collider.tag + "!");
    clicked = true;
}

```

However as general advice I would recommend you don't add the player controller logic in the units themselves. Create a new script for the player controller and handle the input there. Since you have the information of the object in RaycastHit you can call the move functions from the playercontroller. This will also make your life easier when you expand the player controller logic like selecting multiple units.

---
Tags: unity, rts, selection
---


title: How to create a 3D grid in Unity3D?

text:
# Question
Title: How to create a 3D grid in Unity3D?
What is a easy way to generate a 3D "hollow" and square grid around a central point, more like a cube (that can vary in size), with each cell being evenly spaced (based on a value)?

Note: I know how to make a 2D grid but not a 3D one.

Edit: I'll try to explain it more: I'm looking for a way to create a grid at every face of a cube (6 faces) at runtime, that lets suppose is 3x3x3m, and each cell being every 1 meter apart from each other. Something like that:

# Answer
> 2 votes
You should be able to achieve this by looping over each axis and creating a gameobject at those points like so.

```
public GameObject block;
public uint Width = 3;
public uint Height = 3;
public uint Depth = 3;

void Start ()
{
    for (uint x = 0; x < Width; ++x)
    {
        for (uint y = 0; y < Height; ++y)
        {
            for (uint z = 0; z < Depth; ++z)
            {
                if (x > 0 && x < Width - 1 &&
                    y > 0 && y < Height - 1 &&
                    z > 0 && z < Depth - 1)
                    continue;

                Instantiate(block, new Vector3(x,y,z), Quaternion.identity);
            }
        }
    }
}

```

Where block is the empty gameobject or "socket". This will spawn objects only at the edge of the rectangle.

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


title: Follow 3D Path Around Sphere

text:
# Question
Title: Follow 3D Path Around Sphere
I have currently have a path that wraps around a Sphere from one side to another - this is basically a 3D highway in the sky type object that is a textured road. I have an Aircraft model that I can get to follow this path, however I'm having trouble getting it to rotate correctly so that it is parallel to the surface of the globe

Using the following code:

```
this.transform.forward = Vector3.RotateTowards(this.transform.forward, this.transform.position - TargetWaypointPos, Airspeed * Time.deltaTime, 0.0f);

this.transform.position = Vector3.MoveTowards(this.transform.position, TargetWaypointPos, Airspeed * Time.deltaTime);

```

This gets the plane to correctly face the next waypoint and follow the path, however I cannot get it to rotate correctly in the Z-space to be parallel to the path/globe. I can compute the correct angle by:

```
Vector3 yAxis = this.transform.position;
yAxis.Normalize();
Vector3 zAxis = nextPoint - this.transform.position;
zAxis.Normalize();
xAxis = Vector3.Cross(yAxis, zAxis);
xAxis.Normalize();
float angleZ = Vector3.Angle(Vector3.right, xAxis);

```

However attempting to apply this to my model in any way appears to ruin the Vector3.RotateTowards logic. I must be missing something simple to combine these two.

Any ideas? I'm new to Unity, still figuring out all the available options.

# Answer
> 1 votes
This is easier than you think!

```
// Get the vector toward the next waypoint from here.
Vector3 forward =  TargetWaypointPos - transform.position;

// Get the local "up" vector pointing out of the planet to here.
Vector3 up = transform.position - SphereCenterPos;

// Form an orientation that points the z+ axis along "forward",
// and the y+ axis as close as possible to "up".
Quaternion targetRotation = Quaternion.LookRotation(forward, up);

// Rotate toward this target at a controlled rate.
transform.rotation = Quaternion.RotateTowards(
    transform.rotation,
    targetRotation,
    Time.deltaTime * DegreesPerSecond
);

```

---
Tags: unity, c#, rotation, transformation
---


# Question
Title: How to draw the path with a thicker stroke?
I have a game where objects follow a path that resembles a circuit (f1, nascar, stock car).

**Using the draw\_path function, I can draw the circuit on the game screen:**

It turns out that dash got too thin.

**To thicken the drawing line and actually look like a circuit (so I don't have to sprite and put in the background) I tried the following (Draw Event):**

```
draw_path(circuito_ovo,500,50,false);
draw_path(circuito_ovo,501,51,false);
draw_path(circuito_ovo,502,52,false);
draw_path(circuito_ovo,503,53,false);
draw_path(circuito_ovo,504,54,false);
draw_path(circuito_ovo,505,55,false);
draw_path(circuito_ovo,506,56,false);

```

**The result was not as expected (detail I added a unit in two dimensions, I thought the secret would be this):**

# Answer
Adding 1 to each dimension just isn't enough.

**It would have to be something like:**

```
draw_path(circuito_ovo,500,50,false);
draw_path(circuito_ovo,500,51,false);
draw_path(circuito_ovo,500,52,false);

draw_path(circuito_ovo,501,50,false);
draw_path(circuito_ovo,501,51,false);
draw_path(circuito_ovo,501,52,false);

draw_path(circuito_ovo,502,50,false);
draw_path(circuito_ovo,502,51,false);
draw_path(circuito_ovo,502,52,false);

```

**For ease just use the repeat function (Draw Event):**

```
repeat(5){
    repeat(5){
        draw_path(circuito_ovo,500+i,50+j,false);
        j+=1;
    }
    i+=1;
    j=0;
}

i=0;
j=0;

```

Initializing the variables with the value 0 (i and j), or negative (if I want the object to be walked exactly in the center of the drawing).

The number of times the repeat function will execute will be equal to the line thickness.

**Result:**
> 0 votes

# Answer
> This will draw a red diagonal line, 6 pixels wide, from point (100,100) to point (200,200).

```
draw_set_colour(c_red);
draw_line_width(100, 100, 200, 200, 6);

```

Taken from: https://docs2.yoyogames.com/source/\_build/3\_scripting/4\_gml\_reference/drawing/forms/draw\_line\_width.html

I can foresee you will have corner issues as the adjoining lines corner won't meet up. It will become more obvious as you thicken the lines and the two angles are extreme.

That is more tricky to solve given you need to work out the corners for each line taking thickness into account and join those with the previous line corners. Quite a bit of maths and code involving atan2, cos and sin is required to make this work correctly.
> 1 votes

---
Tags: game-maker, path
---


# Question
Title: How to make wheelcollider not stutter when moving on high speed?
I have a wheelcollider attached on a rigidbody and i move the object using : "transform.position += transform.forward * speed * input.getkey(keycode.uparrow)" And when the speed increasing the wheelcollider start stuttering How to solve it? Do i wrong using the script above? Or something? Can anyone solve it? thanks

# Answer
wheel collider is for making movements for wehicle and everything that works with wheels. you should use `WheelCollider.motorTorque`otherwise you get some physics problems like stuttering as you said.

check that your wheels not to make collision with other colliders.
> 1 votes

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


# Question
Title: How come changing the speed of an animation isnt making the animation speed up?
I made an animation of a bow string being pulled and another animation of the string being released but my issue is that I need the string to snap back quickly. I changed the speed of the release animation which is what makes the string go back to being straight (as if you had just released it). However, changing the speed isn't making the animation happen any faster... Any ideas why this might be happening?

# Answer
Turns out unity's transitions were the issue. I had the transition set too slow so no matter how fast I made my animation, it would still take the whole length of the transition for the string to snap back. The way to solve this; decrease the transition time!
> 1 votes

# Answer
that doesnt work in **Animator**.

for working with animator you have to use like this:

```
 float CurrentSpeed = m_Animator.GetCurrentAnimatorStateInfo(0).speed;

```

if you are in first layer, use zero index else use other indexes.
> 0 votes

---
Tags: unity, animation
---